paper_analysis.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. // 论文分析 JavaScript
  2. // 将API密钥存储在会话存储中
  3. let apiKey = sessionStorage.getItem('deepseekApiKey');
  4. // DOM元素
  5. const apiKeyInput = document.getElementById('apiKey');
  6. const saveApiKeyBtn = document.getElementById('saveApiKey');
  7. const fileInput = document.getElementById('paperFile');
  8. const fileInfo = document.getElementById('fileInfo');
  9. const analyzeBtn = document.getElementById('analyzePaper');
  10. const resultsSection = document.querySelector('.results-section');
  11. const tabButtons = document.querySelectorAll('.tab-btn');
  12. const tabPanes = document.querySelectorAll('.tab-pane');
  13. const exportBtn = document.getElementById('exportResults');
  14. // 如果存在API密钥则初始化
  15. if (apiKey) {
  16. apiKeyInput.value = apiKey;
  17. }
  18. // 保存API密钥并测试连接
  19. saveApiKeyBtn.addEventListener('click', async () => {
  20. const newApiKey = apiKeyInput.value.trim();
  21. if (!newApiKey) {
  22. showNotification('请输入有效的API密钥', 'error');
  23. return;
  24. }
  25. try {
  26. showLoading('正在测试API连接...');
  27. const response = await fetch('/paper-analysis/api/test-deepseek', {
  28. method: 'POST',
  29. headers: {
  30. 'X-API-Key': newApiKey,
  31. 'Content-Type': 'application/json'
  32. }
  33. });
  34. const data = await response.json();
  35. if (response.ok && data.success) {
  36. sessionStorage.setItem('deepseekApiKey', newApiKey);
  37. apiKey = newApiKey;
  38. showNotification('API连接成功', 'success');
  39. } else {
  40. showNotification(`API错误: ${data.error || '未知错误'}`, 'error');
  41. console.error('API错误详情:', data);
  42. }
  43. } catch (error) {
  44. showNotification('测试API连接时出错: ' + error.message, 'error');
  45. console.error('API测试错误:', error);
  46. } finally {
  47. hideLoading();
  48. }
  49. });
  50. // 文件上传处理
  51. fileInput.addEventListener('change', handleFileSelect);
  52. document.querySelector('.file-upload-container').addEventListener('dragover', handleDragOver);
  53. document.querySelector('.file-upload-container').addEventListener('drop', handleFileDrop);
  54. function handleFileSelect(event) {
  55. const file = event.target.files[0];
  56. if (file) {
  57. updateFileInfo(file);
  58. }
  59. }
  60. function handleDragOver(event) {
  61. event.preventDefault();
  62. event.stopPropagation();
  63. event.currentTarget.classList.add('drag-over');
  64. }
  65. function handleFileDrop(event) {
  66. event.preventDefault();
  67. event.stopPropagation();
  68. event.currentTarget.classList.remove('drag-over');
  69. const file = event.dataTransfer.files[0];
  70. if (file) {
  71. fileInput.files = event.dataTransfer.files;
  72. updateFileInfo(file);
  73. }
  74. }
  75. function updateFileInfo(file) {
  76. const sizeInMB = (file.size / (1024 * 1024)).toFixed(2);
  77. fileInfo.innerHTML = `
  78. <strong>文件:</strong> ${file.name}<br>
  79. <strong>大小:</strong> ${sizeInMB} MB<br>
  80. <strong>类型:</strong> ${file.type || '未知'}
  81. `;
  82. }
  83. // 标签页导航
  84. tabButtons.forEach(button => {
  85. button.addEventListener('click', () => {
  86. const tabName = button.getAttribute('data-tab');
  87. // 更新激活状态
  88. tabButtons.forEach(btn => btn.classList.remove('active'));
  89. tabPanes.forEach(pane => pane.classList.remove('active'));
  90. button.classList.add('active');
  91. document.getElementById(`${tabName}Tab`).classList.add('active');
  92. });
  93. });
  94. // 论文分析
  95. analyzeBtn.addEventListener('click', async () => {
  96. if (!apiKey) {
  97. showNotification('请先配置您的Deepseek API密钥', 'error');
  98. return;
  99. }
  100. if (!fileInput.files[0]) {
  101. showNotification('请选择要分析的文件', 'error');
  102. return;
  103. }
  104. const formData = new FormData();
  105. formData.append('file', fileInput.files[0]);
  106. formData.append('extract_keywords', document.getElementById('extractKeywords').checked);
  107. formData.append('generate_summary', document.getElementById('generateSummary').checked);
  108. formData.append('find_related', document.getElementById('findRelatedWorks').checked);
  109. try {
  110. showLoading('正在分析论文...');
  111. const response = await fetch('/paper-analysis/api/analyze-paper', {
  112. method: 'POST',
  113. headers: {
  114. 'X-API-Key': apiKey
  115. },
  116. body: formData
  117. });
  118. const responseData = await response.json();
  119. if (!response.ok) {
  120. // 显示详细的错误信息
  121. const errorMessage = responseData.error || `HTTP错误! 状态: ${response.status}`;
  122. throw new Error(errorMessage);
  123. }
  124. displayResults(responseData);
  125. hideLoading();
  126. resultsSection.style.display = 'block';
  127. showNotification('分析完成成功', 'success');
  128. } catch (error) {
  129. hideLoading();
  130. console.error('分析错误:', error);
  131. showNotification('分析论文时出错: ' + error.message, 'error');
  132. }
  133. });
  134. // 显示结果
  135. function displayResults(results) {
  136. // 显示关键词
  137. const keywordsContainer = document.querySelector('.keywords-container');
  138. if (results.keywords) {
  139. keywordsContainer.innerHTML = results.keywords.map(keyword =>
  140. `<div class="keyword-item">
  141. <span class="keyword-text">${keyword.text}</span>
  142. <span class="keyword-score">${(keyword.score * 100).toFixed(1)}%</span>
  143. </div>`
  144. ).join('');
  145. }
  146. // 显示摘要
  147. const summaryContainer = document.querySelector('.summary-container');
  148. if (results.summary) {
  149. summaryContainer.innerHTML = `<div class="summary-text">${results.summary}</div>`;
  150. }
  151. // 显示相关工作
  152. const relatedContainer = document.querySelector('.related-works-container');
  153. if (results.related_works) {
  154. // 如果尚未加载MathJax,则添加脚本
  155. if (!window.MathJax) {
  156. const script = document.createElement('script');
  157. script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
  158. script.async = true;
  159. document.head.appendChild(script);
  160. window.MathJax = {
  161. tex: {
  162. inlineMath: [['$', '$'], ['\\(', '\\)']],
  163. displayMath: [['$$', '$$'], ['\\[', '\\]']]
  164. }
  165. };
  166. }
  167. // 显示公式
  168. relatedContainer.innerHTML = results.related_works.map((formula, index) => {
  169. // 根据类型确定公式显示方式
  170. let formulaDisplay = formula.formula;
  171. // 为MathJax包装公式分隔符
  172. if (!formulaDisplay.includes('$') && !formulaDisplay.includes('\\[') && !formulaDisplay.includes('\\(')) {
  173. // 如果没有分隔符,则添加它们
  174. if (formula.type === 'definition' || formula.type === 'theorem' || formula.importance > 0.7) {
  175. formulaDisplay = `\\[${formulaDisplay}\\]`; // 为重要公式显示数学模式
  176. } else {
  177. formulaDisplay = `\\(${formulaDisplay}\\)`; // 为其他公式显示行内数学
  178. }
  179. }
  180. // 确保变量格式正确以便显示
  181. let variablesDisplay = '';
  182. if (formula.variables) {
  183. let englishVariables = '';
  184. let chineseVariables = '';
  185. // 处理英文变量
  186. if (typeof formula.variables === 'string') {
  187. try {
  188. const variablesObj = JSON.parse(formula.variables);
  189. englishVariables = Object.entries(variablesObj)
  190. .map(([symbol, description]) => {
  191. // 将数学符号包装在LaTeX分隔符中
  192. const mathSymbol = `\\(${symbol}\\)`;
  193. return `<div class="variable-item"><span class="variable-symbol">${mathSymbol}</span><span class="variable-separator">:</span><span class="variable-desc">${description}</span></div>`;
  194. })
  195. .join('');
  196. } catch (e) {
  197. englishVariables = `<div class="variable-item">${formula.variables}</div>`;
  198. }
  199. } else if (typeof formula.variables === 'object') {
  200. englishVariables = Object.entries(formula.variables)
  201. .map(([symbol, description]) => {
  202. // 将数学符号包装在LaTeX分隔符中
  203. const mathSymbol = `\\(${symbol}\\)`;
  204. return `<div class="variable-item"><span class="variable-symbol">${mathSymbol}</span><span class="variable-separator">:</span><span class="variable-desc">${description}</span></div>`;
  205. })
  206. .join('');
  207. } else {
  208. englishVariables = `<div class="variable-item">${String(formula.variables)}</div>`;
  209. }
  210. // 如果可用,处理中文变量
  211. if (formula.variables_chinese) {
  212. if (typeof formula.variables_chinese === 'string') {
  213. try {
  214. const variablesChineseObj = JSON.parse(formula.variables_chinese);
  215. chineseVariables = Object.entries(variablesChineseObj)
  216. .map(([symbol, description]) => {
  217. // 将数学符号包装在LaTeX分隔符中
  218. const mathSymbol = `\\(${symbol}\\)`;
  219. return `<div class="variable-item"><span class="variable-symbol">${mathSymbol}</span><span class="variable-separator">:</span><span class="variable-desc">${description}</span></div>`;
  220. })
  221. .join('');
  222. } catch (e) {
  223. chineseVariables = `<div class="variable-item">${formula.variables_chinese}</div>`;
  224. }
  225. } else if (typeof formula.variables_chinese === 'object') {
  226. chineseVariables = Object.entries(formula.variables_chinese)
  227. .map(([symbol, description]) => {
  228. // 将数学符号包装在LaTeX分隔符中
  229. const mathSymbol = `\\(${symbol}\\)`;
  230. return `<div class="variable-item"><span class="variable-symbol">${mathSymbol}</span><span class="variable-separator">:</span><span class="variable-desc">${description}</span></div>`;
  231. })
  232. .join('');
  233. }
  234. }
  235. if (chineseVariables) {
  236. variablesDisplay = `
  237. <div class="variables-tabs">
  238. <button class="var-tab-btn active" onclick="switchVariableTab(this, 'english')">English</button>
  239. <button class="var-tab-btn" onclick="switchVariableTab(this, 'chinese')">中文</button>
  240. </div>
  241. <div class="variables-content">
  242. <div class="variables-list english-vars active">${englishVariables}</div>
  243. <div class="variables-list chinese-vars">${chineseVariables}</div>
  244. </div>`;
  245. } else {
  246. variablesDisplay = `<div class="variables-list">${englishVariables}</div>`;
  247. }
  248. }
  249. return `<div class="formula-item">
  250. <div class="formula-header">
  251. <span class="formula-number">#${index + 1}</span>
  252. <span class="formula-type ${formula.type}">${formula.type.toUpperCase()}</span>
  253. </div>
  254. <div class="formula-expression">${formulaDisplay}</div>
  255. <div class="formula-description">${formula.description}</div>
  256. ${variablesDisplay ? `<div class="formula-variables"><strong>变量:</strong><div class="variables-list">${variablesDisplay}</div></div>` : ''}
  257. <div class="formula-context"><strong>上下文:</strong> ${formula.context}</div>
  258. <div class="formula-chinese"><strong>中文描述:</strong> ${formula.chinese_description || formula.Chinese_description || '无中文描述'}</div>
  259. </div>`;
  260. }).join('');
  261. // 触发MathJax处理公式
  262. if (window.MathJax && window.MathJax.typesetPromise) {
  263. window.MathJax.typesetPromise([relatedContainer]).catch((e) => console.error(e));
  264. }
  265. }
  266. }
  267. // 导出结果
  268. exportBtn.addEventListener('click', () => {
  269. const results = {
  270. keywords: Array.from(document.querySelectorAll('.keyword-item')).map(item => ({
  271. text: item.querySelector('.keyword-text').textContent,
  272. score: parseFloat(item.querySelector('.keyword-score').textContent) / 100
  273. })),
  274. summary: document.querySelector('.summary-text')?.textContent,
  275. related_works: Array.from(document.querySelectorAll('.formula-item')).map(item => {
  276. const variablesElement = item.querySelector('.formula-variables');
  277. const contextElement = item.querySelector('.formula-context');
  278. const chineseElement = item.querySelector('.formula-chinese');
  279. return {
  280. formula: item.querySelector('.formula-expression').textContent,
  281. type: item.querySelector('.formula-type').textContent.toLowerCase(),
  282. description: item.querySelector('.formula-description').textContent,
  283. variables: variablesElement ? variablesElement.textContent.replace('变量: ', '') : '',
  284. context: contextElement ? contextElement.textContent.replace('上下文: ', '') : '',
  285. chinese_description: chineseElement ? chineseElement.textContent.replace('中文描述: ', '') : ''
  286. };
  287. })
  288. };
  289. const blob = new Blob([JSON.stringify(results, null, 2)], { type: 'application/json' });
  290. const url = URL.createObjectURL(blob);
  291. const a = document.createElement('a');
  292. a.href = url;
  293. a.download = 'paper_analysis_results.json';
  294. document.body.appendChild(a);
  295. a.click();
  296. document.body.removeChild(a);
  297. URL.revokeObjectURL(url);
  298. });
  299. // 工具函数
  300. function showNotification(message, type) {
  301. const notification = document.createElement('div');
  302. notification.className = `notification ${type}`;
  303. notification.textContent = message;
  304. document.body.appendChild(notification);
  305. setTimeout(() => {
  306. notification.remove();
  307. }, 3000);
  308. }
  309. let loadingElement = null;
  310. function showLoading(message) {
  311. loadingElement = document.createElement('div');
  312. loadingElement.className = 'loading-overlay';
  313. loadingElement.innerHTML = `
  314. <div class="loading-spinner"></div>
  315. <div class="loading-message">${message}</div>
  316. `;
  317. document.body.appendChild(loadingElement);
  318. }
  319. function hideLoading() {
  320. if (loadingElement) {
  321. loadingElement.remove();
  322. loadingElement = null;
  323. }
  324. }
  325. // 在英文和中文变量描述之间切换的函数
  326. function switchVariableTab(button, language) {
  327. const variablesContainer = button.closest('.formula-variables');
  328. const tabs = variablesContainer.querySelectorAll('.var-tab-btn');
  329. const contents = variablesContainer.querySelectorAll('.variables-list');
  330. // 更新标签按钮
  331. tabs.forEach(tab => tab.classList.remove('active'));
  332. button.classList.add('active');
  333. // 更新内容可见性
  334. contents.forEach(content => content.classList.remove('active'));
  335. const targetContent = variablesContainer.querySelector(`.${language}-vars`);
  336. if (targetContent) {
  337. targetContent.classList.add('active');
  338. }
  339. }
  340. // 使函数全局化,以便可以从onclick调用
  341. window.switchVariableTab = switchVariableTab;