ImageToImage.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. <template>
  2. <!-- 图生图 -->
  3. <div class="number-people">
  4. <div class="content-box">
  5. <!-- AI对话框 -->
  6. <div class="chat-dialog">
  7. <!-- 对话消息列表 -->
  8. <div class="message-list">
  9. <div v-if="imageAllList.length > 0">
  10. <div v-for="(item, index) in imageAllList" :key="index">
  11. <!-- 用户消息 -->
  12. <div class="user-message" v-if="item.type === 'user'">
  13. {{ item.content }}
  14. <div class="user-image-list" v-if="item.imageUrl">
  15. <el-image
  16. style="width: fit-content; height: 180px; margin: 10px;"
  17. :src="item.imageUrl"
  18. :preview-src-list="[item.imageUrl]"
  19. fit="cover"
  20. show-progress
  21. >
  22. <template
  23. #toolbar="{ actions, prev, next, reset, activeIndex, setActiveItem }"
  24. >
  25. <el-icon @click="prev"><Back /></el-icon>
  26. <el-icon @click="next"><Right /></el-icon>
  27. <el-icon @click="setActiveItem(item.imageList.length - 1)">
  28. <DArrowRight />
  29. </el-icon>
  30. <el-icon @click="actions('zoomOut')"><ZoomOut /></el-icon>
  31. <el-icon @click="actions('zoomIn', { enableTransition: false, zoomRate: 2 })"><ZoomIn /></el-icon>
  32. <el-icon @click="actions('clockwise', { rotateDeg: 180, enableTransition: false })"><RefreshRight /></el-icon>
  33. <el-icon @click="actions('anticlockwise')"><RefreshLeft /></el-icon>
  34. <el-icon @click="reset"><Refresh /></el-icon>
  35. <el-icon @click="download(activeIndex)"><Download /></el-icon>
  36. </template>
  37. </el-image>
  38. </div>
  39. </div>
  40. <!-- AI生成图片对话框 -->
  41. <div class="ai-message" v-if="item.type !== 'user'">
  42. {{ item.content }}
  43. <span v-if="item.loading" class="loading-dots">
  44. <span class="dot"></span>
  45. <span class="dot"></span>
  46. <span class="dot"></span>
  47. </span>
  48. <div class="image-list" v-if="item.imageList">
  49. <el-image
  50. v-for="(image, index) in item.imageList"
  51. :key="index"
  52. style=" width: fit-content; height: 220px; margin: 10px;"
  53. :src="image"
  54. :preview-src-list="item.imageList"
  55. fit="cover"
  56. show-progress
  57. >
  58. <template
  59. #toolbar="{ actions, reset, activeIndex}"
  60. >
  61. <el-icon @click="actions('zoomOut')"><ZoomOut /></el-icon>
  62. <el-icon
  63. @click="actions('zoomIn', { enableTransition: false, zoomRate: 2 })">
  64. <ZoomIn />
  65. </el-icon>
  66. <el-icon
  67. @click="actions('clockwise', { rotateDeg: 180, enableTransition: false })">
  68. <RefreshRight />
  69. </el-icon>
  70. <el-icon @click="actions('anticlockwise')"><RefreshLeft /></el-icon>
  71. <el-icon @click="reset"><Refresh /></el-icon>
  72. <el-icon @click="download(activeIndex)"><Download /></el-icon>
  73. </template>
  74. </el-image>
  75. </div>
  76. </div>
  77. </div>
  78. </div>
  79. </div>
  80. <!-- 输入框和发送按钮 -->
  81. <div class="input-section">
  82. <input
  83. type="text"
  84. v-model="inputMessage"
  85. placeholder="描述任何画面..."
  86. @keyup.enter="sendMessage"
  87. style="flex: 1; margin-right: 8px;"
  88. />
  89. <!-- 参考图 -->
  90. <ImageUpload v-model="uploadedImage" ref="imageUploadRef"/>
  91. <!-- 语音输入按钮 -->
  92. <button
  93. @click="toggleSpeechInput"
  94. class="speech-btn"
  95. :class="{ 'recording': isRecording }"
  96. >
  97. <el-icon v-if="!isRecording"><Microphone /></el-icon>
  98. <el-icon v-else><Mute /></el-icon>
  99. <!-- 显示倒计时(仅录音时显示) -->
  100. <span v-if="isRecording" class="countdown-text">{{ countdown }}s</span>
  101. </button>
  102. <!-- 终止按钮 -->
  103. <div
  104. v-if="conversationInProgress"
  105. @click="stopStream"
  106. class="stop-btn"
  107. title="终止问答"
  108. >
  109. <img :src="stopicon" alt="停止" />
  110. </div>
  111. <button v-if="!conversationInProgress"
  112. @click="sendMessage">发送</button>
  113. </div>
  114. </div>
  115. </div>
  116. </div>
  117. </template>
  118. <script setup>
  119. import { ref, onMounted,onUnmounted} from 'vue'
  120. import {AiImageStatusEnum, CreatePainting, PaintingGetMys} from '@/api/questions.js'
  121. import { useRouter, useRoute } from 'vue-router'
  122. import {
  123. Document,
  124. Menu as IconMenu,
  125. Location,
  126. Setting,
  127. ArrowLeftBold,
  128. Fold,
  129. Expand,
  130. ChatLineRound,
  131. Picture,
  132. MagicStick,
  133. Tickets,
  134. User
  135. } from '@element-plus/icons-vue'
  136. import { saveRecord } from '@/api/personalized/index.js'
  137. // 导入全局状态
  138. import { globalState } from '@/utils/globalState.js'
  139. // 语音图标
  140. import { Microphone, Mute } from "@element-plus/icons-vue";
  141. // 终止按钮
  142. import stopicon from "@/assets/icon/stopicon.png";
  143. // 消息组件
  144. import {Message} from "@/utils/message/Message.js";
  145. // 图生图
  146. import ImageUpload from '@/components/ImageUpload/index.vue';
  147. // 导入getModelIdByType接口
  148. import { getModelIdByType } from '@/api/teachers.js'
  149. import { ModelTypeEnum } from '@/api/teachers.js'
  150. // 存储上传的图片
  151. const uploadedImage = ref('');
  152. const imageUploadRef = ref(null);
  153. // 语音输入响应式变量
  154. const isRecording = ref(false); // 录音状态
  155. const recognition = ref(null); // 语音识别实例
  156. const countdown = ref(0); // 倒计时剩余秒数
  157. const countdownTimer = ref(null); // 倒计时定
  158. // 对话状态变量
  159. const conversationInProgress = ref(false); // 对话是否正在进行中
  160. const conversationInAbortController = ref(); // 对话进行中 abort 控制器
  161. // tts 语音
  162. import { useAudioPlayer } from '@/api/tts/useAudioPlayer';
  163. // 添加抽屉显示状态
  164. const drawerVisible = ref(true)
  165. // 年级ID相关
  166. const gradeId = ref('')
  167. // 添加消息计数器变量
  168. const messageCount = ref(0)
  169. // modelId响应式变量
  170. const modelId = ref(0)
  171. // 保存记录
  172. onMounted(async () => {
  173. // 从全局状态初始化年级ID
  174. gradeId.value = globalState.initGradeId()
  175. try{
  176. const res = await saveRecord({
  177. brpNjId: gradeId.value,
  178. brpType: "aiCount",
  179. brpProgress: 1
  180. });
  181. // 获取modelId
  182. const modelRes = await getModelIdByType({ type: ModelTypeEnum.IMAGE_TO_IMAGE, platform: "DouBao" })
  183. modelId.value = modelRes.data
  184. }catch(error){
  185. console.error('保存记录失败:', error);
  186. }
  187. });
  188. // 消息列表和输入内容的响应式变量
  189. const inputMessage = ref('')
  190. // 初始化语音识别
  191. const initSpeechRecognition = () => {
  192. const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  193. if (!SpeechRecognition) {
  194. alert("当前浏览器不支持语音输入功能");
  195. return null;
  196. }
  197. const instance = new SpeechRecognition();
  198. instance.lang = 'zh-CN';
  199. instance.interimResults = false;
  200. instance.onresult = (event) => {
  201. if (event.results?.[0]?.[0]) {
  202. inputMessage.value += event.results[0][0].transcript;
  203. }
  204. };
  205. // 识别器结束时清除定时器
  206. instance.onend = () => {
  207. clearInterval(countdownTimer.value);
  208. isRecording.value = false;
  209. countdown.value = 0;
  210. };
  211. instance.onerror = (event) => {
  212. console.error('语音识别错误:', event.error);
  213. clearInterval(countdownTimer.value); // 出错时清除定时器
  214. isRecording.value = false;
  215. Message().error('语音输入失败,请重试!', true)
  216. countdown.value = 0;
  217. };
  218. return instance;
  219. };
  220. // 切换录音状态
  221. const toggleSpeechInput = () => {
  222. // 清除可能存在的旧定时器
  223. clearInterval(countdownTimer.value);
  224. countdownTimer.value = null;
  225. if (isRecording.value) {
  226. // 手动停止时重置状态
  227. countdown.value = 0;
  228. recognition.value?.stop();
  229. isRecording.value = false;
  230. } else {
  231. // 初始化倒计时前再次清除定时器(防止快速点击)
  232. clearInterval(countdownTimer.value);
  233. countdown.value = 10; // 重置为10秒
  234. recognition.value = initSpeechRecognition();
  235. if (!recognition.value) return;
  236. navigator.mediaDevices.getUserMedia({ audio: true })
  237. .then(() => {
  238. recognition.value.start();
  239. isRecording.value = true;
  240. // 启动新的倒计时定时器
  241. countdownTimer.value = setInterval(() => {
  242. countdown.value--;
  243. if (countdown.value <= 0) {
  244. clearInterval(countdownTimer.value); // 倒计时结束清除
  245. recognition.value.stop();
  246. isRecording.value = false;
  247. countdown.value = 0;
  248. }
  249. }, 1000);
  250. })
  251. .catch((err) => {
  252. console.error("麦克风权限获取失败:", err);
  253. alert("请允许麦克风权限以使用语音输入");
  254. // 出错时重置状态
  255. isRecording.value = false;
  256. countdown.value = 0;
  257. });
  258. }
  259. };
  260. // 停止操作函数
  261. const stopStream = async () => {
  262. // tip:如果 stream 进行中的 message,就需要调用 controller 结束
  263. if (conversationInAbortController.value) {
  264. conversationInAbortController.value.abort();
  265. }
  266. // 设置为 false
  267. conversationInProgress.value = false;
  268. };
  269. // 发送消息函数,图片数据
  270. const sendMessage = async() => {
  271. if (uploadedImage.value) {
  272. // 创建 AbortController 实例,以便中止请求
  273. conversationInAbortController.value = new AbortController();
  274. // 标记对话进行中
  275. conversationInProgress.value = true;
  276. // 先保存内容 再置空输入框
  277. let content = inputMessage.value;
  278. inputMessage.value = '';
  279. // 创建用户消息对象,包含可能的图片
  280. const userMessage = {
  281. type: 'user',
  282. content: content,
  283. };
  284. // 如果有上传的图片,添加到用户消息中
  285. if (uploadedImage.value) {
  286. userMessage.imageUrl = uploadedImage.value;
  287. // 清空上传的图片
  288. // uploadedImage.value = '';
  289. }
  290. imageAllList.value.push(userMessage);
  291. imageAllList.value.push({
  292. type: 'ai',
  293. content: "正在为您生成图片,请稍等",
  294. loading: true
  295. })
  296. // 递增消息计数器
  297. messageCount.value++
  298. // 发送saveRecord请求 保存消息次数
  299. try{
  300. await saveRecord({
  301. brpNjId: gradeId.value,
  302. brpType: "aiCount",
  303. brpProgress: messageCount.value
  304. });
  305. console.log('保存记录成功,消息次数:', messageCount.value);
  306. }catch(error){
  307. console.error('保存记录失败:', error);
  308. conversationInProgress.value = false;
  309. }
  310. try {
  311. CreatePainting({
  312. "modelId": modelId.value,
  313. "prompt":content,
  314. "width":1024,
  315. "height":1024,
  316. "promptImage":uploadedImage.value
  317. }).then(res=>{
  318. console.log("生成图片",res)
  319. //目前写死调用已生成的图片,全部通了后再改
  320. inProgressImageMap.value[res.data] = {id:res.data,status:AiImageStatusEnum.IN_PROGRESS}
  321. // inProgressImageMap.value[260] = {id:260,status:AiImageStatusEnum.IN_PROGRESS}
  322. }).finally(() => {
  323. // 图片生成请求完成后更新状态
  324. conversationInProgress.value = false;
  325. });
  326. } catch (error) {
  327. console.error('生成图片失败:', error);
  328. conversationInProgress.value = false;
  329. }
  330. } else {
  331. // 如果没有上传图片,显示提示信息
  332. Message().error('请先上传参考图!', true);
  333. }
  334. // 调用子组件的方法清除预览图
  335. imageUploadRef.value?.clearPreview();
  336. };
  337. // 生成图片
  338. import { ElIcon } from 'element-plus'
  339. import {
  340. Back,
  341. DArrowRight,
  342. Download,
  343. Refresh,
  344. RefreshLeft,
  345. RefreshRight,
  346. Right,
  347. ZoomIn,
  348. ZoomOut,
  349. } from '@element-plus/icons-vue'
  350. const imageAllList = ref([]) // 对话的消息列表
  351. // 图片轮询相关的参数(正在生成中的)
  352. const inProgressImageMap = ref({}) // 监听的 image 映射,一般是生成中(需要轮询),key 为 image 编号,value 为 image
  353. const inProgressTimer = ref() // 生成中的 image 定时器,轮询生成进展
  354. /** 轮询生成中的 image 列表 */
  355. const refreshWatchImages = async () => {
  356. const imageIds = Object.keys(inProgressImageMap.value).map(Number)
  357. if (imageIds.length === 0) {
  358. return
  359. }
  360. const list = await PaintingGetMys(imageIds)
  361. const newWatchImages = {}
  362. list.data.forEach((image) => {
  363. if (image.status === AiImageStatusEnum.IN_PROGRESS) {
  364. newWatchImages[image.id] = image
  365. } else {
  366. imageAllList.value.pop();
  367. console.log('AI生成的图片地址:', image.picUrl);
  368. imageAllList.value.push({
  369. type: 'ai',
  370. content: "已为您生成图片:",
  371. imageList: [image.picUrl],
  372. })
  373. }
  374. })
  375. inProgressImageMap.value = newWatchImages
  376. if (newWatchImages.size === 0) {
  377. inProgressTimerFun()
  378. }
  379. }
  380. /** 组件挂在的时候 */
  381. onMounted(async () => {
  382. refreshWatchImagesFun()
  383. })
  384. /** 组件取消挂在的时候 */
  385. onUnmounted(async () => {
  386. inProgressTimerFun()
  387. })
  388. // 自动刷新 image 列表
  389. const refreshWatchImagesFun = () => {
  390. inProgressTimer.value = setInterval(async () => {
  391. await refreshWatchImages()
  392. }, 1000 * 3)
  393. }
  394. // 停止刷新image列表
  395. const inProgressTimerFun = () => {
  396. if (inProgressTimer.value) {
  397. clearInterval(inProgressTimer.value)
  398. }
  399. }
  400. </script>
  401. <style scoped lang="scss">
  402. @use 'sass:math';
  403. // 定义rpx转换函数
  404. @function rpx($px) {
  405. @return math.div($px, 750) * 100vw;
  406. }
  407. // 用户图片列表样式
  408. .user-image-list {
  409. display: flex;
  410. flex-wrap: wrap;
  411. margin-top: rpx(5);
  412. }
  413. //===========================================全局除了删除侧边栏内容唯一改动的地方
  414. .number-people {
  415. flex: 1;
  416. height: 100%;
  417. display: flex;
  418. background-color: #ece9fd;
  419. }
  420. .content-box {
  421. flex: 1;
  422. // margin-top: rpx(10);
  423. // margin-bottom: rpx(10);
  424. margin: rpx(7);
  425. border-radius: rpx(15);
  426. background: rgba($color: #ffffff, $alpha: 0.5);
  427. overflow-y: auto;
  428. }
  429. // 对话框
  430. .chat-dialog {
  431. display: flex;
  432. flex-direction: column;
  433. height: 100%;
  434. }
  435. .message-list {
  436. flex: 1;
  437. overflow-y: auto;
  438. padding: rpx(15);
  439. }
  440. /* 自定义滚动条样式 */
  441. .message-list::-webkit-scrollbar {
  442. width: rpx(2); /* 滚动条宽度 */
  443. }
  444. .message-list::-webkit-scrollbar-track {
  445. background: #f1effd; /* 滚动条轨道背景色 */
  446. border-radius: rpx(4);
  447. }
  448. .message-list::-webkit-scrollbar-thumb {
  449. background: #e2ddfc; /* 滚动条滑块颜色 */
  450. border-radius: rpx(4);
  451. }
  452. .message-list::-webkit-scrollbar-thumb:hover {
  453. background: #e2ddfc; /* 滚动条滑块 hover 状态颜色 */
  454. }
  455. .message-list .user-message {
  456. background-color: #ffffff;
  457. margin-left: auto; // 消息靠右显示
  458. margin-right: 0; // 重置右边距
  459. max-width: rpx(400);
  460. font-size: rpx(8);
  461. width: fit-content; // 宽度随文字内容变化
  462. border-radius: rpx(5);
  463. padding: rpx(5);
  464. text-align: left; // 文字左对齐
  465. }
  466. .message-list .ai-message {
  467. background-color: #ffdd55;
  468. margin-left: 0; // 消息靠左显示
  469. margin-right: auto; // 重置右边距
  470. margin-bottom: rpx(10);
  471. width: fit-content;
  472. max-width: rpx(400);
  473. padding: rpx(5);
  474. font-size: rpx(8);
  475. border-radius: rpx(5);
  476. text-align: left; // 文字左对齐
  477. }
  478. // 加载动画效果
  479. .loading-dots {
  480. display: inline-block;
  481. margin-left: rpx(5);
  482. }
  483. .loading-dots .dot {
  484. display: inline-block;
  485. width: rpx(3);
  486. height: rpx(3);
  487. border-radius: 50%;
  488. background-color: #333;
  489. margin: 0 rpx(1);
  490. animation: loading-dot 1.4s infinite ease-in-out both;
  491. }
  492. .loading-dots .dot:nth-child(1) {
  493. animation-delay: -0.32s;
  494. }
  495. .loading-dots .dot:nth-child(2) {
  496. animation-delay: -0.16s;
  497. }
  498. @keyframes loading-dot {
  499. 0%, 80%, 100% {
  500. transform: scale(0);
  501. }
  502. 40% {
  503. transform: scale(1);
  504. }
  505. }
  506. .image-list {
  507. display: flex;
  508. flex-wrap: wrap;
  509. }
  510. .content-demo {
  511. background-color: #f4f2fa;
  512. border-radius: 15px;
  513. padding: 30px 10px;
  514. }
  515. .input-section {
  516. display: flex;
  517. padding: rpx(10);
  518. gap: rpx(5);
  519. .speech-btn {
  520. padding: rpx(5) rpx(10);
  521. background: #fff;
  522. border: 1px solid #ffce1b;
  523. border-radius: rpx(5);
  524. cursor: pointer;
  525. display: flex;
  526. align-items: center;
  527. &.recording {
  528. background: #ffeeba;
  529. border-color: #ffc107;
  530. .el-icon {
  531. color: #dc3545;
  532. }
  533. }
  534. .el-icon {
  535. font-size: rpx(8);
  536. color: #666;
  537. }
  538. }
  539. // 终止按钮样式
  540. .stop-btn {
  541. cursor: pointer;
  542. display: flex;
  543. align-items: center;
  544. img {
  545. width: rpx(20);
  546. height: rpx(20);
  547. }
  548. }
  549. }
  550. .input-section input {
  551. flex: 1;
  552. padding: rpx(5);
  553. font-size: rpx(7);
  554. border: 1px solid #ccc;
  555. border-radius: rpx(5);
  556. }
  557. .input-section button {
  558. padding: rpx(5) rpx(15);
  559. background: linear-gradient(
  560. to bottom,
  561. #fee78a,
  562. #ffce1b
  563. ); /* 设置悬停、聚焦、点击状态下的背景色 */
  564. color: black;
  565. border: none;
  566. font-size: rpx(7);
  567. border-radius: rpx(5);
  568. cursor: pointer;
  569. box-shadow: 0 0px 2px rgba(0, 0, 0, 0.3);
  570. }
  571. .image-upload-section {
  572. padding: rpx(10);
  573. display: flex;
  574. justify-content: center;
  575. align-items: center;
  576. }
  577. </style>