chd 5 mēneši atpakaļ
vecāks
revīzija
204343b064

+ 5 - 6
src/entrypoints/background.js

@@ -18,9 +18,6 @@ export default defineBackground(() => {
         
         if (message.type === 'FROM_SIDE_PANEL_TO_ACTION') {
             console.log(565888);
-            chrome.tabs.query({ active: true }, (tabs) => {
-                console.log(tabs);
-            });
             chrome.tabs.query({ active: true }, (tabs) => {
                 console.log(tabs);
                 
@@ -31,7 +28,9 @@ export default defineBackground(() => {
                         console.error("消息发送失败:", chrome.runtime.lastError.message);
                     } else {
                         console.log("收到 content script 响应:", response);
-                        sendResponse(response.data)
+                        console.log(response,998);
+                        
+                        sendResponse(response)
                     }
                     return true
                 });
@@ -47,7 +46,7 @@ export default defineBackground(() => {
                         console.error("消息发送失败:", chrome.runtime.lastError.message);
                     } else {
                         console.log("收到 content script 响应:", response);
-                        sendResponse(response.data)
+                        sendResponse(response)
                     }
 
                 });
@@ -55,7 +54,7 @@ export default defineBackground(() => {
             return true
         } 
         if (message.type === 'FROM_SIDE_PANEL_TO_INPUT_FORM') {
-            chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
+            chrome.tabs.query({ active: true }, (tabs) => {
                 if (tabs.length === 0) return; // 确保有活动标签页
                 const tabId = tabs[0].id; // 获取当前活动的 tabId
                 chrome.tabs.sendMessage(tabId, { type: "INPUT_FORM", data: message.data }, (response) => {

+ 90 - 21
src/entrypoints/content.js

@@ -1,8 +1,5 @@
 // entrypoints/content.ts
-import { Loading } from 'element-plus/es/components/loading/src/service.mjs';
-import src1 from '../assets/images/begin.png'
-import PageAnalyzer from '../utils/page-analyzer'
-import { log } from 'console';
+import PageAnalyzer, { cleanPage } from '../utils/page-analyzer'
 
 export default defineContentScript({
     matches: ["<all_urls>"],
@@ -12,6 +9,8 @@ export default defineContentScript({
         window.pageAnalyzer = new PageAnalyzer();
         window.onload = () => {
             chrome.runtime.sendMessage(getPageInfo())
+            console.log(document.title);
+
         }
         let form = null
         let formChildren = []
@@ -25,21 +24,24 @@ export default defineContentScript({
             let dom = null
             if (message.type === "GET_TAG_ACTION") {
                 const data = message.data
-                if (data.id) {
+                if (0) {
                     dom = document.getElementById(data.id)
-                }
-                if (data.class) {
-                    dom = [...document.getElementsByTagName(data.tag)]
+                } else {
+                    dom = [...document.getElementsByTagName(data.tag.toLowerCase())]
                         // .filter(_ => _.className.includes(data.class))
-                        .filter(_ => _.innerText.includes(data.text))
+                        .filter(_ => _.innerText.includes(data.text))[0]
                 }
                 console.log(dom);
+                if (!dom) {
+                    sendResponse({ data: '未找到元素,请重试', statue: 'error' })
+                    return
+                }
                 // 添加红色边框,500ms后移除边框,然后点击
-                const originalBorder = dom[0].style.border;
-                dom[0].style.border = '2px solid red';
+                const originalBorder = dom.style.border;
+                dom.style.border = '2px solid red';
                 setTimeout(() => {
-                    dom[0].style.border = originalBorder;
-                    dom[0].click();
+                    dom.style.border = originalBorder;
+                    dom.click();
                 }, 1000);
                 sendResponse({ data: '完成' })
                 return true
@@ -48,6 +50,14 @@ export default defineContentScript({
             if (message.type === 'GET_PAGE_FORM') {
 
                 const len = document.querySelectorAll("form").length
+                if (document.title === '智能招采' && len === 1) {
+                    sendResponse({
+                        status: 'error',
+                        message: '没有找到表单'
+                    })
+                    return
+                }
+
                 if (len) {
                     const forms = document.querySelectorAll("form")
                     if (len > 1) {
@@ -82,7 +92,7 @@ export default defineContentScript({
             if (message.type === "INPUT_FORM") {
                 const { formData, excelData } = message.data
                 excelDataA = excelData
-                console.log(formData, excelData);
+                console.log(formData, excelDataA);
                 await handleFillInput(formData, 0)
             }
             return true
@@ -134,13 +144,13 @@ export default defineContentScript({
                                 if (label) {
                                     const input = findLabelForInput(label)
                                     if (input) {
-                                        await simulateUserInput(input, excelDataA[item.excelColumn][index])
+                                        await simulateUserInput(input, excelDataA[item.excelColumn])
                                     }
                                 }
                             }
                         }
                         if (input) {
-                            await simulateUserInput(input, excelDataA[item.excelColumn][index])
+                            await simulateUserInput(input, excelDataA[item.excelColumn])
                         }
                     }
                     if (item.type === 'radio' || item.type === 'checkbox') {
@@ -150,23 +160,71 @@ export default defineContentScript({
                             if (label) {
                                 const span = findLabelForSpan(label)
                                 span.forEach(span => {
-                                    span.innerText === excelDataA[item.excelColumn][index] && span.click()
+                                    span.innerText === excelDataA[item.excelColumn] && span.click()
                                 })
                             }
                         }
                     }
 
                     if (item.type === 'date') {
+                        
                         const input = formChildren.find(child => child.id === item.findByValue)
-                        if (excelDataA[item.excelColumn][index]) {
+                        if (excelDataA[item.excelColumn]) {
 
-                            await simulateCompleteUserAction(input, input, formatDate(excelDataA[item.excelColumn][index]), formatDate(excelDataA[item.excelColumn][index]))
+                            await simulateCompleteUserAction(input, input, formatDate(excelDataA[item.excelColumn]), formatDate(excelDataA[item.excelColumn]))
                         }
                     }
-                } else if (item.findBy === 'placeholder') {
+                }
+                if (item.findBy === 'placeholder') {
                     const input = formChildren.find(child => child.placeholder === item.findByValue)
                     if (input) {
-                        simulateUserInput(input, excelDataA[item.excelColumn][index])
+                        simulateUserInput(input, excelDataA[item.excelColumn])
+                    }
+                }
+                if (item.findBy === 'label') {
+                    if (!excelDataA[item.excelColumn]) continue
+                    const label = [...form.getElementsByTagName('label')].find(label => label.innerText.includes(item.findByValue) || item.findByValue.includes(label.innerText))
+                    console.log(label)
+                    if (!label) continue
+                    if (item.type === 'radio' || item.type === 'checkbox') {
+                        console.log(excelDataA[item.excelColumn]);
+                        
+                        if (label) {
+                            const span = findLabelForSpan(label)
+                            span.forEach(span => {
+                                console.log(span.innerText);
+                                if (span.innerText) {
+                                    if (span.innerText.includes(excelDataA[item.excelColumn]) || excelDataA[item.excelColumn].includes(span.innerText)) {
+                                        console.log(span);
+                                        span.click()
+                                    }     
+                                }
+                            })
+                        }
+                    }
+
+                    if (item.type === 'date') {
+                        const input = findLabelForInput(label)
+                        console.log(input, excelDataA[item.excelColumn]);
+                        
+                        if (input) {
+                            await simulateCompleteUserAction(input, input, formatDate(excelDataA[item.excelColumn]), formatDate(excelDataA[item.excelColumn]))
+                        }
+                    }
+
+                    if (item.type === 'input' || item.type === 'text' || item.type === 'number' || item.type === 'tel' || item.type === 'email') {
+                        const input = findLabelForInput(label)
+                        if (input) {
+                            console.log(excelDataA[item.excelColumn]);
+
+                            await simulateUserInput(input, excelDataA[item.excelColumn])
+                        }
+                    }
+                    if (item.type === 'select') {
+                        const input = findLabelForInput(label)
+                        if (input) {
+                            await simulateUserInput(input, excelDataA[item.excelColumn])
+                        }
                     }
                 }
             }
@@ -204,6 +262,17 @@ export default defineContentScript({
             }
             return null
         }
+        const findLabelForTag = (label, tag) => {
+            let p = label.parentElement
+            for (let i = 0; i < 10; i++) {
+                const input = p.getElementsByTagName('input')
+                if (input.length > 0) {
+                    return input[0]
+                }
+                p = p.parentElement
+            }
+            return null
+        }
         const findLabelForSpan = (label) => {
             let p = label.parentElement
             for (let i = 0; i < 10; i++) {

+ 75 - 76
src/entrypoints/sidepanel/Chat.vue

@@ -24,7 +24,6 @@
         </div>
       </div>
     </el-scrollbar>
-
     <Tools @read-click="readClick" @upload-file="handleUpload" @handle-capture="handleCapture" />
 
     <div>
@@ -73,14 +72,13 @@
 <script setup>
 import { ref, onMounted, nextTick, inject, useTemplateRef } from 'vue'
 import { ElScrollbar, ElAvatar, ElInput, ElButton } from 'element-plus'
-import { buildExcelUnderstandingPrompt } from '@/utils/ai-service.js'
+import { buildExcelUnderstandingPrompt ,getFileContent} from '@/utils/ai-service.js'
 import * as XLSX from "xlsx";
 import { ElMessage } from 'element-plus';
 import { useMsg } from '@/entrypoints/sidepanel/hook/useMsg.ts';
 import Tools from "@/entrypoints/sidepanel/component/tools.vue";
 import { useSummary } from '@/entrypoints/sidepanel/hook/useSummary.ts'
-import { mockData } from "@/entrypoints/sidepanel/mock"
-import {upload} from '@/utils/ai-service'
+import { mockData,mockData2 } from "@/entrypoints/sidepanel/mock"
 import { useAutoResizeTextarea } from '@/entrypoints/sidepanel/hook/useAutoResizeTextarea.ts';
 
 // 滚动条引用
@@ -100,17 +98,14 @@ const {
   sendRequese,
   getPageInfo,
   streamRes,
-  handleInput
+  handleInput,
+  getFileValue
 } = useMsg(scrollbar, xlsxData, fetchDataAndProcess);
 const { handleCardButtonClick } = useSummary(addMessage, sendRequese);
 
 function handelIntelligentFillingClick() {
-  if (type.value !== '2') {
-    inputMessage.value = '/智能填表 '
-    type.value = '2'
-  } else {
-    type.value = ''
-  }
+  inputMessage.value = '/智能填表 '
+  type.value = '2'
 }
 
 async function readClick() {
@@ -142,9 +137,8 @@ let formInfo = []
 const flag = ref(false)  //true调用算法接口
 
 const handleUpload = (file) => {
- console.log(upload);
- 
-  chrome.runtime.sendMessage({
+  if (type.value === '2') {
+      chrome.runtime.sendMessage({
     type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM',
   }, async (response) => {
     if (chrome.runtime.lastError) {
@@ -153,9 +147,9 @@ const handleUpload = (file) => {
       console.log(file);
       addMessage(`已上传文件:${file.name}`, false)
       const fileExtension = file.name.split('.').pop().toLowerCase();
-        formInfo = response.data
+      if (response.status === 'error') return ElMessage({message:response.message,type: 'error', duration: 4 * 1000, grouping: true})
+      formInfo = response.data
       if (fileExtension === 'xlsx') {
-
         const reader = new FileReader();
         reader.readAsArrayBuffer(file);
         reader.onload = async (e) => {
@@ -181,29 +175,33 @@ const handleUpload = (file) => {
           console.log(readData, 58);
 
           readData[0].forEach((header, i) => {
-            if (!xlsxData.value[header]) xlsxData.value[header] = []
-            xlsxData.value[header].push(readData[1][i])
+            // if (!xlsxData.value[header]) xlsxData.value[header] = []
+            xlsxData.value[header] = readData[1][i]
           })
           if (type.value === '2') {
             await streamRes(buildExcelUnderstandingPrompt(readData, file?.name, response), false)
           }
         };
       } else {
-        let formData = new FormData();
-        formData.append("file", file);
-        const res = await upload(formData)
-        const keys = Object.keys(res)
-        const values = Object.values(res)
-        readData[0].forEach((header, i) => {
-          if (!xlsxData.value[header]) xlsxData.value[header] = []
-          xlsxData.value[header].push(readData[1][i])
-        })
-        console.log(res);
+        await getFileValue(file, response.data)
+
+        // const keys = Object.keys(res)
+        // const values = Object.values(res)
+        // readData[0].forEach((header, i) => {
+        //   if (!xlsxData.value[header]) xlsxData.value[header] = []
+        //   xlsxData.value[header].push(readData[1][i])
+        // })
+        // console.log(res);
       }
+
     }
     return true
   });
 
+  }
+  if (type.value === '') {
+    
+  }
 }
 let str = ''
 async function fetchDataAndProcess(input, obj) {
@@ -212,69 +210,70 @@ async function fetchDataAndProcess(input, obj) {
   }
   str = input
   console.log(str);
-
   const pageInfo = await getPageInfo();
   await new Promise(res => setTimeout(() => {
     res()
-  }, 1000))
-  const res = await hepl({
-      input_data: input,
-      body:pageInfo.content.mainContent
-  })
-  // const res = await new Promise((resolve, reject) => {
-  //   setTimeout(() => {
-  //     resolve({ data: mockData[indexTemp.value] })
-  //   }, 1000)
+  }, 2000))
+  // const res = await hepl({
+  //   input_data: input,
+  //   body: pageInfo.content.mainContent
   // })
+  console.log(pageInfo.title);
+  
+  const res = await new Promise((resolve, reject) => {
+    setTimeout(() => {
+      resolve({ data:pageInfo.title === '智能招采' ?  mockData[indexTemp.value] :mockData2[indexTemp.value] })
+    }, 1000)
+  })
+  if (!res.data.tag || res.data.tag === 'undefined') {
+    ElMessage({ message: '未找到标签,请重试', type: 'error', duration: 4 * 1000, grouping: true })
+    obj.content = '未找到标签,请重试'
+    type.value = ''
+    return
+  }
   await handleClick(res.data, obj);
 }
 
 
 async function handleClick(res, msgObj) {
   await new Promise(resolve => setTimeout(resolve, 2000))
-    msgObj.content = `点击${res.tag}元素`
-    chrome.runtime.sendMessage({
-      type: 'FROM_SIDE_PANEL_TO_ACTION',
-      data: res
-    }, async (response) => {
-      if (chrome.runtime.lastError) {
-        console.error("消息发送错误:", chrome.runtime.lastError);
-        rej(chrome.runtime.lastError)
+  msgObj.content = `点击${res.tag}元素`
+  chrome.runtime.sendMessage({
+    type: 'FROM_SIDE_PANEL_TO_ACTION',
+    data: res
+  }, async ({ data, status }) => {
+    if (chrome.runtime.lastError) {
+      console.error("消息发送错误:", chrome.runtime.lastError);
+      rej(chrome.runtime.lastError)
+    } else {
+      if (status === 'error') {
+        msgObj.content = data
+        type.value = ''
+        return
+      }
+      if (res.next === '是') {
+        const arr = str.split(',')
+        arr.shift()
+        str = arr.join(',')
+        indexTemp.value++
+        fetchDataAndProcess(str, msgObj)
       } else {
-        if (res.next === '是') {
-          indexTemp.value++
-          const arr = str.split(',')
-          arr.shift()
-          str = arr.join(',')
-          fetchDataAndProcess(str, msgObj)
-        } else {
+        if (type.value === '2') {
+           await new Promise((resolve, reject) => {
+    setTimeout(() => {
+      resolve()
+    }, 2000)
+  })
           msgObj.content = `请上传数据`
           ElMessage({ message: '请上传数据', type: 'success', duration: 4 * 1000, grouping: true })
+        } else {
+          msgObj.content = `执行完毕`
         }
       }
-      return true
-    });
-  
-  //     chrome.runtime.sendMessage({
-  //          type: 'FROM_SIDE_PANEL_TO_ACTION',
-  //                 data:obj
-  //     }, async (response) => {
-  //         if (chrome.runtime.lastError) {
-  //             console.error("消息发送错误:", chrome.runtime.lastError);
-  //             rej(chrome.runtime.lastError)
-  //         } else {
-  //             if (obj.next === '是') {
-  //                 console.log(strArr[index]);
-
-  //                 index++
-  //                 fetchDataAndProcess(strArr[index])
-  //             } else {
-  //                 ElMessage({ message: '操作执行完成', type: 'success', duration: 2 * 1000, grouping: true })
-  //                 index = 0
-  //             }
-  //         }
-  //         return true
-  // });
+    }
+    return true
+  });
+
 }
 
 const isHoveringTitle = ref(false)

+ 63 - 13
src/entrypoints/sidepanel/hook/useMsg.ts

@@ -2,8 +2,10 @@
 import { ref, reactive } from 'vue';
 import avator from '@/public/icon/32.png';
 import moment from 'moment'
+// import { getFileContent, getFormKey, buildObjPrompt } from '../../../utils/ai-service'
+import { ElMessage } from 'element-plus';
 // import { sendMessage } from '@/utils/ai-service';
-export function useMsg(scrollbar: any, type: any, xlsxData: any, fetchDataAndProcess: Function) {
+export function useMsg(scrollbar: any, xlsxData: any, fetchDataAndProcess: Function) {
   const inputMessage = ref('');
   const indexTemp = ref(0);
   const taklToHtml = ref<any>(false);
@@ -17,10 +19,48 @@ export function useMsg(scrollbar: any, type: any, xlsxData: any, fetchDataAndPro
     rawContent: '你好!有什么我可以帮助你的吗?',
     timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
     isSelf: false,
-    avatar: avator
+    avatar: avator,
+    addToHistory: false
   }]);
+  const getFileValue = async (file: any, form: any) => {
+    const obj = reactive({
+      id: moment(),
+      username: '用户1',
+      rawContent: '',
+      content: '解析文件中',
+      timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
+      isSelf: false,
+      avatar: avator,
+      addToHistory: !taklToHtml.value
+    })
 
-  // 发送消息
+    try {
+      sendLoading.value = true
+      messages.value.push(obj)
+      nextTick(() => scrollbar.value?.setScrollTop(99999))
+      let formData = new FormData();
+      formData.append("file", file);
+      const res = await getFileContent(formData)
+      console.log({
+        body: form,
+        input_data: res.data
+      });
+
+      const response = await getFormKey({
+        body: form,
+        input_data: res.data
+      })
+      xlsxData.value = response.data
+      console.log(xlsxData.value);
+      console.log(type.value);
+      
+      await streamRes(buildObjPrompt(response.data, form), false)
+    } catch (error) {
+      obj.content = '解析出错'
+    } finally {
+
+    }
+  }  // 发送消息
   const addMessage = (msg: any, fetch: any) => {
     if (!msg) return
     const newMessage: any = {
@@ -59,7 +99,18 @@ export function useMsg(scrollbar: any, type: any, xlsxData: any, fetchDataAndPro
 
   const sendRequese = async (msg: any, addHtml = false) => {
     const res: any = await getPageInfo()
-    if (type.value === '2' && msg.startsWith('/')) {
+
+
+    if ((type.value === '2' && msg.startsWith('/')) || msg.startsWith('请')) {
+      if (!taklToHtml.value) return messages.value.push({
+        username: '用户1',
+        content: '请打开与页面对话!',
+        rawContent: '请打开与页面对话!',
+        timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
+        isSelf: false,
+        avatar: avator,
+        addToHistory: false
+      })
       indexTemp.value = 0
       fetchRes(msg)
     }
@@ -81,11 +132,9 @@ export function useMsg(scrollbar: any, type: any, xlsxData: any, fetchDataAndPro
       addToHistory: !taklToHtml.value
     })
     messages.value.push(obj)
-    scrollbar.value?.setScrollTop(99999);
-    if (type.value === '2') {
-      await fetchDataAndProcess(msg, obj)
-      sendLoading.value = false
-    }
+    nextTick(() => scrollbar.value?.setScrollTop(99999))
+    await fetchDataAndProcess(msg, obj)
+    sendLoading.value = false
   }
 
 
@@ -140,18 +189,19 @@ export function useMsg(scrollbar: any, type: any, xlsxData: any, fetchDataAndPro
       scrollbar.value?.setScrollTop(99999)
     }
     scrollbar.value?.setScrollTop(99999)
-
+    console.log(232344);
+    
     // 处理最终内容
     if (type.value === '2') {
       try {
         formMap.value = JSON.parse(obj.rawContent.split('json')[1].split('```')[0])
-
         handleInput()
         type.value = ''
       } catch (e) {
         console.error('解析JSON失败:', e)
       }
     }
+    type.value = ''
     sendLoading.value = false
     nextTick(() => {
       scrollbar.value?.setScrollTop(99999)
@@ -159,17 +209,17 @@ export function useMsg(scrollbar: any, type: any, xlsxData: any, fetchDataAndPro
   }
 
   const handleInput = () => {
-    const arr = xlsxData.value;
     chrome.runtime.sendMessage({
       type: 'FROM_SIDE_PANEL_TO_INPUT_FORM',
       data: {
-        excelData: arr,
+        excelData: xlsxData.value,
         formData: formMap.value
       }
     });
   }
 
   return {
+    getFileValue,
     messages,
     inputMessage,
     indexTemp,

+ 1 - 1
src/entrypoints/sidepanel/hook/useSummary.ts

@@ -7,4 +7,4 @@ export function useSummary(addMessage: Function, sendRequese: Function) {
   return {
     handleCardButtonClick
   }
-}
+}

+ 1 - 0
src/entrypoints/sidepanel/main.ts

@@ -11,4 +11,5 @@ const app = createApp(App).use(ElementPlus, {locale: locale, size: 'small'});
 for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
     app.component(key, component)
 }
+
 app.mount('#app')

+ 9 - 2
src/entrypoints/sidepanel/mock.ts

@@ -23,6 +23,13 @@ export const options = [
 
 export const mockData = [
   { action: 'click', class: "ant-menu-item", tag: "li", innerHTML: "<span class=\"ant-menu-item-icon\"><span role=\"img\" aria-label=\"book\" class=\"anticon anticon-book\"></span></span><span class=\"ant-menu-title-content\"><span>项目建档</span></span>", id: "", text: "项目建档", next: "是" },
-  { action: 'click', class: "ant-menu-item", tag: "button", innerHTML: "<span class=\"ant-menu-item-icon\"><span role=\"img\" aria-label=\"book\" class=\"anticon anticon-book\"></span></span><span class=\"ant-menu-title-content\"><span>项目建档</span></span>", id: "", text: "新增", next: "" },
+  { action: 'click', class: "ant-menu-item", tag: "button", innerHTML: "<span class=\"ant-menu-item-icon\"><span role=\"img\" aria-label=\"book\" class=\"anticon anticon-book\"></span></span><span class=\"ant-menu-title-content\"><span>项目建档</span></span>", id: "", text: "新增", next: "" },
   { action: 'show', class: "ant-menu-item", tag: "button", innerHTML: "<span class=\"ant-menu-item-icon\"><span role=\"img\" aria-label=\"book\" class=\"anticon anticon-book\"></span></span><span class=\"ant-menu-title-content\"><span>项目建档</span></span>", id: "", text: "请上传数据", next: "是" },
-]
+]
+
+export const mockData2 = [
+  { action: 'click', class: "ant-menu-item", tag: "li", innerHTML: "<span class=\"ant-menu-item-icon\"><span role=\"img\" aria-label=\"book\" class=\"anticon anticon-book\"></span></span><span class=\"ant-menu-title-content\"><span>项目建档</span></span>", id: "", text: "我的简历", next: "是" },
+  { action: 'click', class: "ant-menu-item", tag: "button", innerHTML: "<span class=\"ant-menu-item-icon\"><span role=\"img\" aria-label=\"book\" class=\"anticon anticon-book\"></span></span><span class=\"ant-menu-title-content\"><span>项目建档</span></span>", id: "", text: "去录入", next: "否" },
+  { action: 'show', class: "ant-menu-item", tag: "button", innerHTML: "<span class=\"ant-menu-item-icon\"><span role=\"img\" aria-label=\"book\" class=\"anticon anticon-book\"></span></span><span class=\"ant-menu-title-content\"><span>项目建档</span></span>", id: "", text: "请上传数据", next: "是" },
+]
+

+ 35 - 8
src/utils/ai-service.js

@@ -10,15 +10,24 @@ export const openai = new OpenAI(
         dangerouslyAllowBrowser: true,
     }
 )
-export async function upload(data,ext) {
+export async function getFileContent(data) {
     try {
-        const res = await fetch('http://192.168.1.108:8000/upload-pdf', {
+        const res = await fetch('http://180.76.147.97:18899/upload_file', {
             method: 'post',
             body: data,
         }).then(res => res.json())
         return res
     } catch (error) {
-
+    }
+}
+export async function getFormKey(data) {
+    try {
+        const res = await fetch('http://180.76.147.97:18899/uie', {
+            method: 'post',
+            body: JSON.stringify(data),
+        }).then(res => res.json())
+        return res
+    } catch (error) {
     }
 }
 export async function hepl(data) {
@@ -186,13 +195,31 @@ export function buildExcelUnderstandingPrompt(data, fileName, pageInfo) {
 ${pageInfo}
              
 要求:
-1. 请分析表单中实际可操作的表单项,
-2. 并根据实际可操作的表单项的所有信息与上传的列标题进行匹配,生成表单项与列标题对应的数组,并使用findBy告诉我通过表单项的什么字段信息匹配到的,使用findByValue告诉我匹配到的表单项字段值,使用excelColumn字段告诉我excel文件中列标题的值。在一个字段内返回
+1. 请根据表单中的表单项和列标题进行匹配,一定以表单为准!
+2. 生成表单项与列标题对应的数组,并使用findBy告诉我通过表单项的什么字段信息匹配到的,使用findByValue告诉我匹配到的表单项字段值,使用excelColumn字段告诉我excel文件中列标题的值。
+3. 根据label匹配,findBy是label,并通过findByValue给我label元素的值,根据id匹配,findBy是id,并通过findByValue给是id的值,
 3. 并去除没有匹配到的表单项和excel文件中没有匹配到的列,
 4. 通过type字段告诉我输入项的类型
-5. 如果表单项有label标签,同时返回label,通过label字段告诉我label元素的文本
-6. 优先根据id匹配,再根据placeholder匹配,再根据其他内容匹配
-7. 仅返回数组,不要返回任何其他内容。`
+5. 表单项有label,根据label匹配,没有label根据placeholder匹配,没有placeholder,根据id匹配,再根据其他内容匹配
+6. 仅返回数组,不要返回任何其他内容。`
+}
+// 5. 如果表单项有label标签,同时返回label, 通过label字段告诉我label元素的文本
+export function buildObjPrompt(obj,  pageInfo) {
+  
+
+    return `我将向你展示一个对象和一个form表单。请帮我理解这些数据:
+
+对象:${JSON.stringify(obj)}
+表单内容:
+${pageInfo}
+             
+要求:
+1. 请根据表单中的表单项和对象进行匹配,一定以表单为准!
+2. 表单项有label,根据label匹配,没有label根据placeholder匹配,没有placeholder,根据id匹配,再根据其他内容匹配
+3. 并根据实际可操作的表单项的所有信息与上传的对象的key进行匹配,生成表单项与key的数组,并使用findBy告诉我通过表单项的什么字段信息匹配到的,使用findByValue告诉我匹配到的表单项字段值,使用excelColumn字段告诉我对应的key值。在一个字段内返回
+4. 并去除没有匹配到的表单项和对象中没有匹配到的key,
+5. 通过type字段告诉我输入项的类型,如果对象中key对应的是日期,type统一返回date
+6. 仅返回数组,不要返回任何其他内容。`
 }
 function escapeHtml(html) {
     const div = document.createElement("div");

+ 57 - 57
src/utils/page-analyzer.js

@@ -8,14 +8,14 @@ export default class PageAnalyzer {
    * 分析页面内容
    * @returns {Object} 页面分析结果
    */
-  analyzePage(iframe = false) {
+  analyzePage(form = false) {
     try {
       // 检查Readability是否可用
       if (typeof Readability === "undefined") {
         console.warn(
           "Readability not loaded, falling back to basic extraction"
         );
-        return this.fallbackAnalysis(iframe);
+        return this.fallbackAnalysis(form);
       }
 
       // 创建文档副本以避免修改原始DOM
@@ -68,71 +68,20 @@ export default class PageAnalyzer {
       }
     } else {
       const content = document.body.cloneNode(true);
-      cleanPage(content)
+      return cleanPage(content)
       // .trim().replace(/\s+/g, " ")
       // content
       //     .querySelectorAll("script, style, iframe, nav, header, footer,svg")
       //     .forEach((el) => el.remove());
 
-      const regex = /\s+/g;
-
-      // 定义标准 HTML 属性集合 排除id class style href src target
-      const standardAttributes = new Set(['alt', 'title', 'type', 'value', 'name', 'placeholder', 'disabled', 'checked', 'selected', 'readonly', 'required', 'maxlength', 'min', 'max', 'step', 'pattern', 'autocomplete', 'autofocus', 'multiple', 'rows', 'cols', 'rel', 'aria-*']);
-
-      // 创建一个临时容器
-      const temp = document.createElement('div');
-      temp.innerHTML = content.outerHTML;
-      // 递归删除空标签
-      function removeEmpty(element) {
-        const children = Array.from(element.children);
-        children.forEach(child => {
-          removeEmpty(child); // 递归处理子元素
-        });
-
-        // 检查标签是否为空
-        if (!element.innerHTML.trim()) {
-          element.remove(); // 删除空标签
-        }
-      }
-
-      // 从临时容器的子元素开始处理
-      removeEmpty(temp);
-
-      // 删除 <link> 标签
-      const linkTags = temp.querySelectorAll('link');
-      linkTags.forEach(link => {
-        link.remove();
-      });
-
-      // 遍历所有元素
-      const elements = temp.querySelectorAll('*');
-      elements.forEach(element => {
-        // 获取所有属性
-        const attributes = Array.from(element.attributes);
-        attributes.forEach(attr => {
-          // 如果属性不是标准属性,则移除
-          if (!standardAttributes.has(attr.name) && !attr.name.startsWith('aria-')) {
-            element.removeAttribute(attr.name);
-          }
-        });
-      });
-
-      // 获取处理后的 HTML 字符串
-      const cleanedHtml = temp.innerHTML.trim().replace(regex, " ");
-
-      // 销毁临时容器
-      temp.remove();
-
-      console.log(cleanedHtml)
-      // content.outerHTML.trim().replace(/\s+/g, " ");
-      return cleanedHtml;
+      
     }
 
 
   }
 };
 
-function cleanPage(body) {
+export  function cleanPage(body) {
 
   // 移除所有行内样式
   const elementsWithInlineStyle = body.querySelectorAll('[style]');
@@ -167,7 +116,58 @@ function cleanPage(body) {
   const ads = body.querySelectorAll('.ad, .advertisement, .ads');
   ads.forEach(ad => ad.remove());
 
-  console.log('页面清理完成!');
+  const regex = /\s+/g;
+
+  // 定义标准 HTML 属性集合 排除id class style href src target
+  const standardAttributes = new Set(['alt', 'title', 'type', 'value', 'name', 'placeholder', 'disabled', 'checked', 'selected', 'readonly', 'required', 'maxlength', 'min', 'max', 'step', 'pattern', 'autocomplete', 'autofocus', 'multiple', 'rows', 'cols', 'rel', 'aria-*']);
+
+  // 创建一个临时容器
+  const temp = document.createElement('div');
+  temp.innerHTML = body.outerHTML;
+  // 递归删除空标签
+  function removeEmpty(element) {
+    const children = Array.from(element.children);
+    children.forEach(child => {
+      removeEmpty(child); // 递归处理子元素
+    });
+
+    // 检查标签是否为空
+    if (!element.innerHTML.trim()) {
+      element.remove(); // 删除空标签
+    }
+  }
+
+  // 从临时容器的子元素开始处理
+  removeEmpty(temp);
+
+  // 删除 <link> 标签
+  const linkTags = temp.querySelectorAll('link');
+  linkTags.forEach(link => {
+    link.remove();
+  });
+
+  // 遍历所有元素
+  const elements = temp.querySelectorAll('*');
+  elements.forEach(element => {
+    // 获取所有属性
+    const attributes = Array.from(element.attributes);
+    attributes.forEach(attr => {
+      // 如果属性不是标准属性,则移除
+      if (!standardAttributes.has(attr.name) && !attr.name.startsWith('aria-')) {
+        element.removeAttribute(attr.name);
+      }
+    });
+  });
+
+  // 获取处理后的 HTML 字符串
+  const cleanedHtml = temp.innerHTML.trim().replace(regex, " ");
+
+  // 销毁临时容器
+  temp.remove();
+
+  console.log(cleanedHtml)
+  // content.outerHTML.trim().replace(/\s+/g, " ");
+  return cleanedHtml;
 }