-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
132 lines (113 loc) · 5.63 KB
/
Copy pathapp.py
File metadata and controls
132 lines (113 loc) · 5.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import streamlit as st
import re
import requests
import xml.etree.ElementTree as ET
import os
import tempfile
from win32com.client import Dispatch
import pythoncom # 新增:用于初始化 COM
import time
# ===== 初始化 COM 库(必须放在所有 Dispatch 调用之前)=====
pythoncom.CoInitialize()
# 设置网页标题和图标
st.set_page_config(page_title="PMID 自动化处理工具", page_icon="📚")
st.title("📚 拖拽 Word 一键处理 PMID")
st.write("上传你的 Word 文档,自动提取 PMID、生成 EndNote 导入文件,并自动添加批注。")
# 创建文件上传区域(支持拖拽)
uploaded_file = st.file_uploader("将 Word 文档拖拽到这里", type=['docx'])
if uploaded_file is not None:
# 1. 保存用户上传的文件到临时目录
with tempfile.NamedTemporaryFile(delete=False, suffix='.docx') as tmp_input:
tmp_input.write(uploaded_file.getvalue())
input_path = tmp_input.name
# 2. 提取 PMID
with st.spinner('正在提取 PMID...'):
word = Dispatch('Word.Application')
word.Visible = False
doc = word.Documents.Open(input_path)
full_text = doc.Range().Text
doc.Close(False)
word.Quit()
pattern = r'[Pp][Mm][Ii][Dd]\s*[::]\s*(\d+)'
pmid_list = list(dict.fromkeys(re.findall(pattern, full_text)))
st.success(f"✅ 提取成功!共找到 {len(pmid_list)} 个 PMID")
if pmid_list:
# 3. 获取 PubMed 数据并生成 RIS
with st.spinner('正在从 PubMed 抓取文献信息...'):
base_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"
params = {"db": "pubmed", "id": ",".join(pmid_list), "retmode": "xml"}
response = requests.get(base_url, params=params, timeout=60)
root = ET.fromstring(response.text)
ris_lines = []
for article in root.findall(".//PubmedArticle"):
pmid = article.find(".//PMID").text
title = article.find(".//ArticleTitle")
title = title.text if title is not None else "No Title"
journal = article.find(".//Title")
journal = journal.text if journal is not None else "No Journal"
year = article.find(".//PubDate/Year")
year = year.text if year is not None else ""
authors = []
for author in article.findall(".//Author")[:3]:
last = author.find("LastName")
fore = author.find("ForeName")
if last is not None and fore is not None:
authors.append(f"{last.text} {fore.text}")
author_str = ", ".join(authors)
ris_lines.append("TY - JOUR")
ris_lines.append(f"TI - {title}")
ris_lines.append(f"T2 - {journal}")
ris_lines.append(f"PY - {year}")
ris_lines.append(f"AU - {author_str}")
ris_lines.append(f"ID - {pmid}")
ris_lines.append(f"UR - https://pubmed.ncbi.nlm.nih.gov/{pmid}/")
ris_lines.append("ER -")
ris_lines.append("")
ris_content = "\n".join(ris_lines)
# 4. 提供 RIS 下载
st.download_button(
label="📥 下载 RIS 文件(导入 EndNote)",
data=ris_content,
file_name="my_references.ris",
mime="text/plain"
)
# 5. 可选:自动添加批注(用复选框控制)
if st.checkbox("同时自动添加批注并删除原文(谨慎操作,建议先备份)"):
with st.spinner('正在处理批注...'):
word = Dispatch('Word.Application')
word.Visible = True # 显示出来让你看到变化
doc = word.Documents.Open(input_path)
find_obj = word.Selection.Find
find_obj.ClearFormatting()
find_obj.Text = "\(PMID:*\)"
find_obj.MatchWildcards = True
find_obj.Forward = True
find_obj.Wrap = 1
count = 0
while find_obj.Execute():
count += 1
matched_text = word.Selection.Text
pmid_number = matched_text[6:-1]
word.Selection.Text = ""
word.ActiveDocument.Comments.Add(word.Selection.Range, pmid_number)
doc.Save()
# 保存修改后的文件到临时目录
output_path = input_path.replace('.docx', '_modified.docx')
doc.SaveAs2(output_path)
doc.Close()
word.Quit()
st.success(f"✅ 已添加 {count} 条批注!")
# 提供修改后的 Word 下载
with open(output_path, 'rb') as f:
st.download_button(
label="📥 下载修改后的 Word 文档(含批注)",
data=f,
file_name="modified_文档.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml"
)
# 清理临时文件
os.unlink(output_path)
# 清理上传的临时文件
os.unlink(input_path)
else:
st.warning("⚠️ 文档中未找到任何 PMID 格式的内容。")