VisionThink.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. <template>
  2. <!-- 右侧AI问答 -->
  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. <!-- 显示AI返回的HTML内容 -->
  49. <div v-if="item.htmlContent" v-html="item.htmlContent" class="ai-html-content"></div>
  50. <div class="image-list" v-if="item.imageList && item.imageList.length > 0">
  51. <video
  52. v-for="(video, index) in item.imageList"
  53. :key="index"
  54. style="width: 60%; max-width: 600px; height: auto; margin: 10px;border-radius: 2%;"
  55. :src="video"
  56. controls
  57. playsinline
  58. >
  59. 您的浏览器不支持视频播放
  60. </video>
  61. </div>
  62. </div>
  63. </div>
  64. </div>
  65. </div>
  66. <!-- 输入框和发送按钮 -->
  67. <div class="input-section">
  68. <input
  69. type="text"
  70. v-model="displayedPrompt"
  71. placeholder="描述任何画面..."
  72. @keyup.enter="sendMessage"
  73. style="flex: 1; margin-right: 8px;"
  74. />
  75. <ImageUpload v-model="uploadedImage" ref="imageUploadRef"/>
  76. <!-- 语音输入按钮 -->
  77. <VoiceInput
  78. inputSelector="input[type='text']"
  79. lang="zh-CN"
  80. maxDuration="10"
  81. @voiceRecognized="handleVoiceRecognized"
  82. @recordingStatusChanged="handleRecordingStatusChanged"
  83. />
  84. <!-- 终止按钮 -->
  85. <div
  86. v-if="conversationInProgress"
  87. @click="stopStream"
  88. class="stop-btn"
  89. title="终止问答"
  90. >
  91. <img :src="stopicon" alt="停止" />
  92. </div>
  93. <button v-if="!conversationInProgress"
  94. @click="sendMessage">发送</button>
  95. </div>
  96. </div>
  97. </div>
  98. </div>
  99. </template>
  100. <script setup>
  101. import {ref, onMounted, defineEmits, computed} from 'vue'
  102. import {VisionThink} from '@/api/questions.js'
  103. import { useRouter } from 'vue-router'
  104. import VoiceInput from '../voice/VoiceInput_Api.vue'
  105. // 导入全局状态
  106. import { globalState } from '@/utils/globalState.js'
  107. // 终止按钮
  108. import stopicon from "@/assets/icon/stopicon.png";
  109. // 消息组件
  110. import {Message} from "@/utils/message/Message.js";
  111. // 上传参考图
  112. import ImageUpload from '@/components/ImageUpload/index.vue';
  113. // 导入getModelIdByType接口
  114. import {getModelIdByType, ModelPlatformEnum} from '@/api/teachers.js'
  115. import { ModelTypeEnum } from '@/api/teachers.js'
  116. // 定义props
  117. const props = defineProps({
  118. //根据需求传输
  119. isCourse: { type: Boolean, default: false},
  120. cacheDataKey: { type: String, default: localStorage.getItem('token') + "_ai_visionThink" },
  121. cacheDataHistoryKey: { type: String, default: localStorage.getItem('token') + "_ai_visionThink_history" },
  122. preDialogueList: { type: Array, default: () => []},
  123. replySupplement: { type: String, default: ''},
  124. })
  125. // 定义emits
  126. const emits = defineEmits(['saveProgress'])
  127. //历史记录缓存集合
  128. const cacheDataHistoryList = ref([]);
  129. // 存储上传的图片
  130. const uploadedImage = ref('');
  131. const imageUploadRef = ref(null);
  132. // 对话状态变量
  133. const conversationInProgress = ref(false); // 对话是否正在进行中
  134. const router = useRouter()
  135. // modelId响应式变量
  136. const modelId = ref(0)
  137. // 保存记录
  138. onMounted(async () => {
  139. try{
  140. // 获取modelId
  141. const modelRes = await getModelIdByType({ type: ModelTypeEnum.VISION_THINK, platform: ModelPlatformEnum.DOUBAO })
  142. modelId.value = modelRes.data
  143. }catch(error){
  144. console.error('保存记录失败:', error);
  145. }
  146. // 取缓存历史记录
  147. let cacheDataHistoryStr = localStorage.getItem(props.cacheDataHistoryKey);
  148. if (cacheDataHistoryStr) {
  149. cacheDataHistoryList.value = JSON.parse(cacheDataHistoryStr) || [];
  150. imageAllList.value.push(...cacheDataHistoryList.value);
  151. }else{
  152. // 加入预置对话
  153. imageAllList.value.push(...props.preDialogueList);
  154. cacheDataHistoryList.value.push(...props.preDialogueList);
  155. if (cacheDataHistoryList.value.length > 0) localStorage.setItem(props.cacheDataHistoryKey, JSON.stringify(cacheDataHistoryList.value));
  156. }
  157. });
  158. // 消息列表和输入内容的响应式变量
  159. const messages = ref([])
  160. const inputMessage = ref('这是什么植物?')
  161. // 语音输入状态跟踪
  162. const isVoiceRecording = ref(false); // 当前是否正在录音
  163. const voiceRecognizedText = ref(""); // 实时语音识别结果
  164. // 用于控制输入框显示的内容
  165. const displayedPrompt = computed({
  166. get() {
  167. // 录音时,只显示inputMessage.value(已经在handleVoiceRecognized中实时更新)
  168. if (isVoiceRecording.value) {
  169. return inputMessage.value;
  170. }
  171. // 不录音时,只显示inputMessage.value
  172. return inputMessage.value;
  173. },
  174. set(newValue) {
  175. // 只在用户手动输入时更新inputMessage.value
  176. if (!isVoiceRecording.value) {
  177. inputMessage.value = newValue;
  178. }
  179. }
  180. });
  181. // 语音输入识别结果处理
  182. const handleVoiceRecognized = (data) => {
  183. if (isVoiceRecording.value) {
  184. // 在同一次录音过程中,实时更新文本框内容
  185. voiceRecognizedText.value = data.originalText;
  186. inputMessage.value = data.processedText;
  187. } else {
  188. // 在录音结束时,将最终的语音内容插入到光标位置
  189. const input = document.querySelector('input[type="text"]');
  190. if (input) {
  191. inputMessage.value = data.processedText;
  192. // 重新设置光标位置到插入文本的末尾
  193. setTimeout(() => {
  194. input.selectionStart = input.selectionEnd = data.cursorPos;
  195. }, 0);
  196. } else {
  197. // 如果没有找到输入框,直接替换整个内容
  198. inputMessage.value = data.originalText;
  199. }
  200. // 清空临时变量
  201. voiceRecognizedText.value = "";
  202. }
  203. };
  204. // 处理录音状态变化
  205. const handleRecordingStatusChanged = (status) => {
  206. const wasRecording = isVoiceRecording.value;
  207. isVoiceRecording.value = status;
  208. // 如果是从录音状态切换到非录音状态,清空临时变量
  209. if (wasRecording && !status) {
  210. // 清空临时变量
  211. voiceRecognizedText.value = "";
  212. }
  213. };
  214. // 停止操作函数
  215. const stopStream = async () => {
  216. // 直接设置为 false
  217. conversationInProgress.value = false;
  218. };
  219. // 发送消息函数
  220. const sendMessage = async() => {
  221. if (uploadedImage.value) {
  222. // 如果正在录音,先停止录音
  223. if (isVoiceRecording.value) {
  224. const voiceInputComponent = document.querySelector('.voice-input-container .speech-btn');
  225. if (voiceInputComponent) {
  226. voiceInputComponent.click();
  227. }
  228. // 等待录音结束后再发送
  229. setTimeout(() => {
  230. sendMessage();
  231. }, 100);
  232. return;
  233. }
  234. // 标记对话进行中
  235. conversationInProgress.value = true;
  236. // 先保存内容 再置空输入框
  237. let content = inputMessage.value;
  238. inputMessage.value = ''
  239. // 创建用户消息对象,包含可能的图片
  240. const userMessage = {
  241. type: 'user',
  242. content: content,
  243. };
  244. // 如果有上传的图片,添加到用户消息中
  245. if (uploadedImage.value) {
  246. userMessage.imageUrl = uploadedImage.value;
  247. }
  248. // 添加用户消息到消息列表
  249. imageAllList.value.push(userMessage);
  250. imageAllList.value.push({
  251. type: 'ai',
  252. content: "正在处理您的请求,请稍等",
  253. loading: true
  254. })
  255. // 调用子组件的方法清除预览图
  256. imageUploadRef.value?.clearPreview();
  257. // 清空上传的图片路径
  258. uploadedImage.value = null;
  259. // 通过emit事件通知父组件保存进度
  260. emits('saveProgress', "aiCount", 1)
  261. if (props.isCourse){
  262. emits('saveProgress', "course", 100)
  263. }
  264. // 同步历史记录缓存
  265. cacheDataHistoryList.value.push(userMessage);
  266. localStorage.setItem(props.cacheDataHistoryKey, JSON.stringify(cacheDataHistoryList.value));
  267. try {
  268. const res = await VisionThink({
  269. "modelId": modelId.value,
  270. "prompt":content,
  271. "promptImage":[userMessage.imageUrl]
  272. });
  273. console.log("视觉理解结果", res);
  274. // 移除加载中的消息
  275. imageAllList.value.pop();
  276. // 添加AI返回的HTML内容
  277. let aiMsg = {
  278. type: 'ai',
  279. content: "",
  280. htmlContent: res.data?.result || "请求失败,请稍后重试!",
  281. };
  282. imageAllList.value.push(aiMsg);
  283. // 添加补充信息
  284. if (props.replySupplement) {
  285. imageAllList.value.push({
  286. type: "system",
  287. content: props.replySupplement,
  288. });
  289. }
  290. // 同步缓存历史记录
  291. cacheDataHistoryList.value.push(aiMsg);
  292. localStorage.setItem(props.cacheDataHistoryKey, JSON.stringify(cacheDataHistoryList.value));
  293. } catch (error) {
  294. console.error('视觉理解失败:', error);
  295. // 移除加载中的消息
  296. imageAllList.value.pop();
  297. // 添加错误消息
  298. imageAllList.value.push({
  299. type: 'ai',
  300. content: "处理失败,请稍后重试"
  301. });
  302. } finally {
  303. // 图片生成请求完成后更新状态
  304. conversationInProgress.value = false;
  305. }
  306. } else {
  307. // 如果没有上传图片,显示提示信息
  308. Message().error('请先上传参考图!', true);
  309. }
  310. };
  311. // 生成图片
  312. import { ElIcon } from 'element-plus'
  313. import {
  314. Back,
  315. DArrowRight,
  316. Download,
  317. Refresh,
  318. RefreshLeft,
  319. RefreshRight,
  320. Right,
  321. ZoomIn,
  322. ZoomOut,
  323. } from '@element-plus/icons-vue'
  324. const imageAllList = ref([]) // 对话的消息列表
  325. const imageList = ref([]) // image 列表
  326. </script>
  327. <style scoped lang="scss">
  328. @use 'sass:math';
  329. // 定义rpx转换函数
  330. @function rpx($px) {
  331. @return math.div($px, 750) * 100vw;
  332. }
  333. // 用户图片列表样式
  334. .user-image-list {
  335. display: flex;
  336. flex-wrap: wrap;
  337. margin-top: rpx(5);
  338. }
  339. //===========================================全局除了删除侧边栏内容唯一改动的地方
  340. .number-people {
  341. flex: 1;
  342. height: 100%;
  343. display: flex;
  344. background-color: #ece9fd;
  345. }
  346. .content-box {
  347. flex: 1;
  348. // margin-top: rpx(10);
  349. // margin-bottom: rpx(10);
  350. margin: rpx(7);
  351. border-radius: rpx(15);
  352. background: rgba($color: #ffffff, $alpha: 0.5);
  353. overflow-y: auto;
  354. }
  355. //左侧展览区图标
  356. .img-box {
  357. margin-top: rpx(50);
  358. color: #a39dce;
  359. }
  360. // 对话框
  361. .chat-dialog {
  362. display: flex;
  363. flex-direction: column;
  364. height: 100%;
  365. }
  366. .message-list {
  367. flex: 1;
  368. overflow-y: auto;
  369. padding: rpx(15);
  370. }
  371. /* 自定义滚动条样式 */
  372. .message-list::-webkit-scrollbar {
  373. width: rpx(2); /* 滚动条宽度 */
  374. }
  375. .message-list::-webkit-scrollbar-track {
  376. background: #f1effd; /* 滚动条轨道背景色 */
  377. border-radius: rpx(4);
  378. }
  379. .message-list::-webkit-scrollbar-thumb {
  380. background: #e2ddfc; /* 滚动条滑块颜色 */
  381. border-radius: rpx(4);
  382. }
  383. .message-list::-webkit-scrollbar-thumb:hover {
  384. background: #e2ddfc; /* 滚动条滑块 hover 状态颜色 */
  385. }
  386. .message-list .user-message {
  387. background-color: #ffffff;
  388. margin-left: auto; // 消息靠右显示
  389. margin-right: 0; // 重置右边距
  390. margin-bottom: rpx(10);
  391. max-width: rpx(400);
  392. font-size: rpx(8);
  393. font-weight: normal;
  394. width: fit-content; // 宽度随文字内容变化
  395. border-radius: rpx(5);
  396. padding: rpx(5);
  397. text-align: left; // 文字左对齐
  398. }
  399. .message-list .ai-message {
  400. background-color: #ffdd55;
  401. margin-left: 0; // 消息靠左显示
  402. margin-right: auto; // 重置右边距
  403. margin-bottom: rpx(10);
  404. width: fit-content;
  405. max-width: rpx(400);
  406. padding: rpx(5);
  407. font-size: rpx(8);
  408. font-weight: normal;
  409. border-radius: rpx(5);
  410. text-align: left; // 文字左对齐
  411. }
  412. // 加载动画效果
  413. .loading-dots {
  414. display: inline-block;
  415. margin-left: rpx(5);
  416. }
  417. .loading-dots .dot {
  418. display: inline-block;
  419. width: rpx(3);
  420. height: rpx(3);
  421. border-radius: 50%;
  422. background-color: #333;
  423. margin: 0 rpx(1);
  424. animation: loading-dot 1.4s infinite ease-in-out both;
  425. }
  426. .loading-dots .dot:nth-child(1) {
  427. animation-delay: -0.32s;
  428. }
  429. .loading-dots .dot:nth-child(2) {
  430. animation-delay: -0.16s;
  431. }
  432. @keyframes loading-dot {
  433. 0%, 80%, 100% {
  434. transform: scale(0);
  435. }
  436. 40% {
  437. transform: scale(1);
  438. }
  439. }
  440. .image-list {
  441. display: flex;
  442. flex-wrap: wrap;
  443. }
  444. /* AI返回的HTML内容样式 */
  445. .ai-html-content {
  446. border-radius: rpx(5);
  447. max-width: 100%;
  448. overflow-x: auto;
  449. }
  450. /* 确保HTML内容中的图片适应容器 */
  451. .ai-html-content img {
  452. max-width: 100%;
  453. height: auto;
  454. border-radius: 3px;
  455. }
  456. /* 确保HTML内容中的文本样式 */
  457. .ai-html-content p {
  458. margin: 5px 0;
  459. line-height: 1.5;
  460. }
  461. .content-demo {
  462. background-color: #f4f2fa;
  463. border-radius: 15px;
  464. padding: 30px 10px;
  465. }
  466. .input-section {
  467. display: flex;
  468. align-items: center;
  469. align-content: center;
  470. padding: rpx(10);
  471. gap: rpx(5);
  472. flex-wrap: nowrap;
  473. min-height: rpx(30);
  474. // 确保所有子组件容器也垂直居中
  475. > * {
  476. display: flex;
  477. align-items: center;
  478. justify-content: center;
  479. height: rpx(20);
  480. box-sizing: border-box;
  481. }
  482. .speech-btn {
  483. padding: rpx(5) rpx(10);
  484. background: #fff;
  485. border: 1px solid #ffce1b;
  486. border-radius: rpx(5);
  487. cursor: pointer;
  488. &.recording {
  489. background: #ffeeba;
  490. border-color: #ffc107;
  491. .el-icon {
  492. color: #dc3545;
  493. }
  494. }
  495. .el-icon {
  496. font-size: rpx(8);
  497. color: #666;
  498. }
  499. }
  500. // 终止按钮样式
  501. .stop-btn {
  502. cursor: pointer;
  503. img {
  504. width: rpx(20);
  505. height: rpx(20);
  506. }
  507. }
  508. }
  509. .input-section input {
  510. flex: 1;
  511. min-width: rpx(50);
  512. padding: rpx(5);
  513. font-size: rpx(7);
  514. border: 1px solid #ccc;
  515. border-radius: rpx(5);
  516. height: rpx(20);
  517. box-sizing: border-box;
  518. }
  519. .input-section button {
  520. padding: rpx(5) rpx(15);
  521. background: linear-gradient(
  522. to bottom,
  523. #fee78a,
  524. #ffce1b
  525. ); /* 设置悬停、聚焦、点击状态下的背景色 */
  526. color: black;
  527. border: none;
  528. font-size: rpx(7);
  529. border-radius: rpx(5);
  530. cursor: pointer;
  531. box-shadow: 0 0px 2px rgba(0, 0, 0, 0.3);
  532. white-space: nowrap;
  533. }
  534. // 图片上传组件的容器样式
  535. .input-section :deep(.el-upload) {
  536. display: flex;
  537. align-items: center;
  538. justify-content: center;
  539. height: rpx(20);
  540. }
  541. // 语音输入组件的容器样式
  542. .input-section :deep(.voice-input-container) {
  543. display: flex;
  544. align-items: center;
  545. justify-content: center;
  546. height: rpx(20);
  547. }
  548. .image-upload-section {
  549. padding: rpx(10);
  550. display: flex;
  551. justify-content: center;
  552. align-items: center;
  553. }
  554. </style>