Spaces:
Sleeping
Sleeping
LJZ commited on
Commit ·
2e901fb
1
Parent(s): 9e69829
添加核心功能以从 arXiv、DOI 和通用 URL 获取 BibTeX 条目,并定义 Gradio 界面
Browse files- app.py +247 -0
- requirements.txt +5 -0
app.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import arxiv
|
| 3 |
+
import re
|
| 4 |
+
import os
|
| 5 |
+
import requests # 用于进行 HTTP 请求,获取 DOI 和通用 URL 元数据
|
| 6 |
+
import datetime # 用于获取当前日期作为访问日期
|
| 7 |
+
import hashlib # 用于为通用 URL 生成唯一的 BibTeX 键
|
| 8 |
+
|
| 9 |
+
# --- 核心逻辑函数 ---
|
| 10 |
+
|
| 11 |
+
def extract_identifiers(input_string):
|
| 12 |
+
"""
|
| 13 |
+
从输入的字符串中提取 arXiv ID、DOI 或通用 URL。
|
| 14 |
+
支持新旧格式的 arXiv 链接/ID、DOI 链接/ID 和常见的 URL 格式。
|
| 15 |
+
返回一个包含 (type, id) 元组的列表,例如 [('arxiv', '2006.01234'), ('doi', '10.1007/s11227-020-03299-8'), ('web', 'https://example.com/blog')]
|
| 16 |
+
"""
|
| 17 |
+
input_string = input_string.strip()
|
| 18 |
+
identifiers = []
|
| 19 |
+
|
| 20 |
+
# 尝试提取 arXiv ID
|
| 21 |
+
arxiv_new_format_match = re.search(r'(?P<id>\d{4}\.\d{5})(v\d+)?', input_string)
|
| 22 |
+
if arxiv_new_format_match:
|
| 23 |
+
identifiers.append(('arxiv', arxiv_new_format_match.group('id')))
|
| 24 |
+
return identifiers
|
| 25 |
+
|
| 26 |
+
arxiv_old_format_match = re.search(r'(?P<id>[a-z\-]+/\d{7})(v\d+)?', input_string)
|
| 27 |
+
if arxiv_old_format_match:
|
| 28 |
+
identifiers.append(('arxiv', arxiv_old_format_match.group('id')))
|
| 29 |
+
return identifiers
|
| 30 |
+
|
| 31 |
+
if re.match(r'^\d{4}\.\d{5}(v\d+)?$', input_string):
|
| 32 |
+
identifiers.append(('arxiv', input_string.split('v')[0]))
|
| 33 |
+
return identifiers
|
| 34 |
+
|
| 35 |
+
if re.match(r'^[a-z\-]+/\d{7}(v\d+)?$', input_string):
|
| 36 |
+
identifiers.append(('arxiv', input_string.split('v')[0]))
|
| 37 |
+
return identifiers
|
| 38 |
+
|
| 39 |
+
# 尝试提取 DOI
|
| 40 |
+
doi_match = re.search(r'(10\.\d{4,9}/[-._;()/:A-Z0-9]+)', input_string, re.IGNORECASE)
|
| 41 |
+
if doi_match:
|
| 42 |
+
identifiers.append(('doi', doi_match.group(1)))
|
| 43 |
+
return identifiers
|
| 44 |
+
|
| 45 |
+
# 如果以上都不是,尝试作为通用 URL
|
| 46 |
+
# 简单的 URL 匹配,确保它看起来像一个 URL (http/https开头或www.开头)
|
| 47 |
+
if re.match(r'^(https?://|www\.)[^\s/$.?#].[^\s]*$', input_string, re.IGNORECASE):
|
| 48 |
+
identifiers.append(('web', input_string))
|
| 49 |
+
return identifiers
|
| 50 |
+
|
| 51 |
+
return identifiers
|
| 52 |
+
|
| 53 |
+
def get_bibtex_from_arxiv(arxiv_id):
|
| 54 |
+
"""
|
| 55 |
+
根据 arXiv ID 获取 BibTeX 条目。
|
| 56 |
+
"""
|
| 57 |
+
try:
|
| 58 |
+
search_results = arxiv.Search(id_list=[arxiv_id]).results()
|
| 59 |
+
paper = next(search_results)
|
| 60 |
+
|
| 61 |
+
authors = " and ".join([author.name for author in paper.authors])
|
| 62 |
+
title = paper.title.replace("\n", " ").strip()
|
| 63 |
+
year = paper.published.year
|
| 64 |
+
arxiv_category = paper.primary_category
|
| 65 |
+
doi_field = f",\n doi = {{{paper.doi}}}" if paper.doi else ""
|
| 66 |
+
|
| 67 |
+
bib_key = arxiv_id.replace('.', '_').replace('/', '_').replace('-', '_')
|
| 68 |
+
|
| 69 |
+
bibtex_entry = f"""
|
| 70 |
+
@article{{{bib_key},
|
| 71 |
+
title={{ {title} }},
|
| 72 |
+
author={{ {authors} }},
|
| 73 |
+
journal={{ arXiv preprint arXiv:{paper.entry_id.split('/')[-1]} [{arxiv_category}] }},
|
| 74 |
+
year={{ {year} }}{doi_field}
|
| 75 |
+
}}
|
| 76 |
+
"""
|
| 77 |
+
return bibtex_entry, None # 返回 BibTeX 和 None (无错误)
|
| 78 |
+
except StopIteration:
|
| 79 |
+
return None, f"错误: 未找到 arXiv ID '{arxiv_id}' 的论文。请检查 ID 是否正确或已发布。"
|
| 80 |
+
except Exception as e:
|
| 81 |
+
return None, f"无法获取 arXiv ID '{arxiv_id}' 的 BibTeX 条目: {e}"
|
| 82 |
+
|
| 83 |
+
def get_bibtex_from_doi(doi):
|
| 84 |
+
"""
|
| 85 |
+
根据 DOI 获取 BibTeX 条目,通过 CrossRef API。
|
| 86 |
+
"""
|
| 87 |
+
try:
|
| 88 |
+
# CrossRef API 直接提供 BibTeX 格式的转换
|
| 89 |
+
url = f"https://api.crossref.org/v1/works/{doi}/transform/application/x-bibtex"
|
| 90 |
+
headers = {'Accept': 'application/x-bibtex'} # 请求 BibTeX 格式
|
| 91 |
+
response = requests.get(url, headers=headers, timeout=10) # 增加超时
|
| 92 |
+
|
| 93 |
+
if response.status_code == 200:
|
| 94 |
+
return response.text, None # 返回 BibTeX 文本和 None (无错误)
|
| 95 |
+
elif response.status_code == 404:
|
| 96 |
+
return None, f"错误: 未找到 DOI '{doi}' 的论文。请检查 DOI 是否正确。"
|
| 97 |
+
else:
|
| 98 |
+
return None, f"错误: 获取 DOI '{doi}' 的 BibTeX 失败,状态码: {response.status_code},响应: {response.text[:100]}..."
|
| 99 |
+
except requests.exceptions.RequestException as e:
|
| 100 |
+
return None, f"网络请求错误,无法获取 DOI '{doi}' 的 BibTeX: {e}"
|
| 101 |
+
except Exception as e:
|
| 102 |
+
return None, f"处理 DOI '{doi}' 时发生未知错误: {e}"
|
| 103 |
+
|
| 104 |
+
def get_bibtex_from_url(url):
|
| 105 |
+
"""
|
| 106 |
+
根据通用 URL 获取 BibTeX 条目。
|
| 107 |
+
尝试从网页标题中提取信息,并生成 @misc 类型的 BibTeX。
|
| 108 |
+
注意:从通用网页提取准确的元数据(作者、日期等)非常困难且不可靠。
|
| 109 |
+
此函数主要提取标题和 URL,并记录访问日期。
|
| 110 |
+
"""
|
| 111 |
+
try:
|
| 112 |
+
# 确保 URL 包含协议,否则 requests 可能无法处理
|
| 113 |
+
if not url.startswith('http://') and not url.startswith('https://'):
|
| 114 |
+
url = 'http://' + url # 默认使用 http,requests 会自动重定向到 https
|
| 115 |
+
|
| 116 |
+
response = requests.get(url, timeout=10)
|
| 117 |
+
response.raise_for_status() # 对 4xx/5xx 响应抛出 HTTPError
|
| 118 |
+
html_content = response.text
|
| 119 |
+
|
| 120 |
+
# 尝试从 <title> 标签中提取标题
|
| 121 |
+
title_match = re.search(r'<title>(.*?)</title>', html_content, re.IGNORECASE | re.DOTALL)
|
| 122 |
+
title = title_match.group(1).strip() if title_match else url # 如果未找到标题,则使用 URL 作为标题
|
| 123 |
+
|
| 124 |
+
# 尝试从 Open Graph 协议中提取标题 (优先级更高)
|
| 125 |
+
og_title_match = re.search(r'<meta\s+property="og:title"\s+content="([^"]*)"', html_content, re.IGNORECASE)
|
| 126 |
+
if og_title_match:
|
| 127 |
+
title = og_title_match.group(1).strip()
|
| 128 |
+
|
| 129 |
+
# 简单的 bib_key 生成,基于 URL 的 MD5 哈希值,取前8位
|
| 130 |
+
bib_key = "web_" + hashlib.md5(url.encode('utf-8')).hexdigest()[:8]
|
| 131 |
+
|
| 132 |
+
access_date = datetime.date.today().strftime("%Y-%m-%d")
|
| 133 |
+
|
| 134 |
+
bibtex_entry = f"""
|
| 135 |
+
@misc{{{bib_key},
|
| 136 |
+
title={{ {title} }},
|
| 137 |
+
howpublished={{ \\url{{{url}}} }},
|
| 138 |
+
note={{ Accessed: {access_date} }}
|
| 139 |
+
}}
|
| 140 |
+
"""
|
| 141 |
+
return bibtex_entry, None
|
| 142 |
+
except requests.exceptions.RequestException as e:
|
| 143 |
+
return None, f"网络请求错误,无法获取 URL '{url}' 的内容: {e}"
|
| 144 |
+
except Exception as e:
|
| 145 |
+
return None, f"处理 URL '{url}' 时发生未知错误: {e}"
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def get_bibtex_entries_and_display(input_string):
|
| 149 |
+
"""
|
| 150 |
+
根据输入的字符串(每行一个 arXiv ID/链接、DOI/链接或通用 URL)获取 BibTeX 条目,
|
| 151 |
+
返回日志信息和所有BibTeX条目的字符串形式。
|
| 152 |
+
"""
|
| 153 |
+
input_lines = input_string.split('\n')
|
| 154 |
+
|
| 155 |
+
processed_identifiers = [] # 存储 (type, id) 元组
|
| 156 |
+
log_messages = []
|
| 157 |
+
all_bibtex_content = [] # 存储所有BibTeX条目
|
| 158 |
+
|
| 159 |
+
log_messages.append("正在从输入中提取 arXiv ID、DOI 或通用 URL...")
|
| 160 |
+
for line in input_lines:
|
| 161 |
+
line = line.strip()
|
| 162 |
+
if not line:
|
| 163 |
+
continue
|
| 164 |
+
extracted = extract_identifiers(line)
|
| 165 |
+
if extracted:
|
| 166 |
+
for id_type, identifier in extracted:
|
| 167 |
+
processed_identifiers.append((id_type, identifier))
|
| 168 |
+
else:
|
| 169 |
+
log_messages.append(f"警告: 无法从 '{line}' 中提取有效的 arXiv ID、DOI 或 URL。将跳过此项。")
|
| 170 |
+
|
| 171 |
+
# 去重处理,确保每个唯一的 (type, id) 对只处理一次
|
| 172 |
+
unique_identifiers = list(set(processed_identifiers))
|
| 173 |
+
|
| 174 |
+
if not unique_identifiers:
|
| 175 |
+
log_messages.append("没有检测到有效的 arXiv ID、DOI 或 URL。请检查输入。")
|
| 176 |
+
return "\n".join(log_messages), "", None
|
| 177 |
+
|
| 178 |
+
log_messages.append(f"\n成功提取到 {len(unique_identifiers)} 个唯一的标识符。正在获取 BibTeX 条目...")
|
| 179 |
+
|
| 180 |
+
for id_type, identifier in unique_identifiers:
|
| 181 |
+
bibtex_entry = None
|
| 182 |
+
error_message = None
|
| 183 |
+
|
| 184 |
+
if id_type == 'arxiv':
|
| 185 |
+
log_messages.append(f"正在获取 arXiv ID '{identifier}' 的 BibTeX 条目...")
|
| 186 |
+
bibtex_entry, error_message = get_bibtex_from_arxiv(identifier)
|
| 187 |
+
elif id_type == 'doi':
|
| 188 |
+
log_messages.append(f"正在获取 DOI '{identifier}' 的 BibTeX 条目...")
|
| 189 |
+
bibtex_entry, error_message = get_bibtex_from_doi(identifier)
|
| 190 |
+
elif id_type == 'web': # 新增的通用 URL 处理
|
| 191 |
+
log_messages.append(f"正在获取通用 URL '{identifier}' 的 BibTeX 条目...")
|
| 192 |
+
bibtex_entry, error_message = get_bibtex_from_url(identifier)
|
| 193 |
+
else:
|
| 194 |
+
error_message = f"未知标识符类型: {id_type} (ID: {identifier})"
|
| 195 |
+
|
| 196 |
+
if bibtex_entry:
|
| 197 |
+
all_bibtex_content.append(bibtex_entry)
|
| 198 |
+
log_messages.append(f"成功获取 {id_type.upper()} '{identifier}' 的 BibTeX 条目。")
|
| 199 |
+
else:
|
| 200 |
+
log_messages.append(error_message)
|
| 201 |
+
|
| 202 |
+
final_bibtex_string = "\n".join(all_bibtex_content)
|
| 203 |
+
|
| 204 |
+
temp_bib_filepath = None
|
| 205 |
+
if final_bibtex_string.strip():
|
| 206 |
+
temp_bib_filepath = "temp_references.bib" # 修改文件名以反映更广泛的来源
|
| 207 |
+
try:
|
| 208 |
+
with open(temp_bib_filepath, 'w', encoding='utf-8') as f:
|
| 209 |
+
f.write(final_bibtex_string)
|
| 210 |
+
log_messages.append(f"\nBibTeX 内容已保存到临时文件 '{temp_bib_filepath}' 以供下载。")
|
| 211 |
+
except Exception as e:
|
| 212 |
+
log_messages.append(f"错误: 无法将BibTeX内容写入临时文件: {e}")
|
| 213 |
+
temp_bib_filepath = None
|
| 214 |
+
|
| 215 |
+
if not final_bibtex_string.strip():
|
| 216 |
+
log_messages.append("\n没有成功获取任何 BibTeX 条目。")
|
| 217 |
+
|
| 218 |
+
return "\n".join(log_messages), final_bibtex_string, temp_bib_filepath
|
| 219 |
+
|
| 220 |
+
# --- Gradio 界面部分 ---
|
| 221 |
+
|
| 222 |
+
# 定义 Gradio 界面
|
| 223 |
+
iface = gr.Interface(
|
| 224 |
+
fn=get_bibtex_entries_and_display,
|
| 225 |
+
inputs=[
|
| 226 |
+
gr.Textbox(
|
| 227 |
+
lines=10,
|
| 228 |
+
label="粘贴 arXiv 链接/ID、DOI 或通用 URL (每行一个)",
|
| 229 |
+
placeholder="例如:\nhttps://arxiv.org/abs/2006.01234\n1904.08133v1\n10.1109/TNNLS.2020.3006789\nhttps://doi.org/10.1038/s41586-023-06670-w\nhttps://www.example.com/blog-post\nwww.anotherblog.org/article"
|
| 230 |
+
)
|
| 231 |
+
],
|
| 232 |
+
outputs=[
|
| 233 |
+
gr.Textbox(label="处理日志", lines=8, interactive=False),
|
| 234 |
+
gr.Textbox(label="在此复制 BibTeX 内容", lines=10, interactive=True),
|
| 235 |
+
gr.File(label="下载 BibTeX 文件")
|
| 236 |
+
],
|
| 237 |
+
title="Anything2Bib: 通用 BibTeX 获取工具",
|
| 238 |
+
description="在此粘贴 arXiv 论文的链接/ID、DOI 或通用网页链接 (每行一个),获取其 BibTeX 条目。",
|
| 239 |
+
allow_flagging="never"
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# 启动 Gradio 应用
|
| 243 |
+
if __name__ == "__main__":
|
| 244 |
+
print("Gradio 应用正在启动...")
|
| 245 |
+
print("你可以在浏览器中访问以下地址:")
|
| 246 |
+
iface.launch(share=False)
|
| 247 |
+
print("Gradio 应用已关闭。")
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# requirements.txt
|
| 2 |
+
gradio
|
| 3 |
+
arxiv
|
| 4 |
+
requests # 用于获取网页标题等信息
|
| 5 |
+
beautifulsoup4 # 用于解析网页HTML,获取标题
|