Spaces:
Running
Running
File size: 12,541 Bytes
81cb6e0 | 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | import { Paper, Reference } from '../types';
// ==================== Rate Limiter ====================
class RateLimiter {
private lastRequestTime = 0;
private queue: Array<{
fn: () => Promise<unknown>;
resolve: (value: unknown) => void;
reject: (reason?: unknown) => void;
}> = [];
private processing = false;
private minDelay: number;
constructor(minDelayMs: number = 3000) {
this.minDelay = minDelayMs;
}
async execute<T>(fn: () => Promise<T>): Promise<T> {
return new Promise<T>((resolve, reject) => {
this.queue.push({
fn: fn as () => Promise<unknown>,
resolve: resolve as (value: unknown) => void,
reject,
});
this.processQueue();
});
}
private async processQueue() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;
while (this.queue.length > 0) {
const item = this.queue.shift()!;
const now = Date.now();
const elapsed = now - this.lastRequestTime;
if (elapsed < this.minDelay) {
await new Promise((r) => setTimeout(r, this.minDelay - elapsed));
}
try {
this.lastRequestTime = Date.now();
const result = await item.fn();
item.resolve(result);
} catch (error) {
item.reject(error);
}
}
this.processing = false;
}
}
const arxivLimiter = new RateLimiter(3500);
const ar5ivLimiter = new RateLimiter(2500);
// ==================== CORS Proxy ====================
async function fetchWithProxy(url: string): Promise<string> {
// Try direct fetch first
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 8000);
const response = await fetch(url, { signal: controller.signal });
clearTimeout(timeout);
if (response.ok) return await response.text();
} catch {
// Direct fetch failed, try proxies
}
// Try allorigins proxy
const proxies = [
`https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`,
`https://corsproxy.io/?${encodeURIComponent(url)}`,
];
for (const proxyUrl of proxies) {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 15000);
const response = await fetch(proxyUrl, { signal: controller.signal });
clearTimeout(timeout);
if (response.ok) return await response.text();
} catch {
continue;
}
}
throw new Error(`Failed to fetch: ${url}`);
}
// ==================== ArXiv Search API ====================
export async function searchArxiv(
query: string,
start: number = 0,
maxResults: number = 10
): Promise<{ papers: Paper[]; total: number }> {
return arxivLimiter.execute(async () => {
const searchQuery = query
.split(/\s+/)
.map((term) => `all:${term}`)
.join('+AND+');
const url = `https://export.arxiv.org/api/query?search_query=${searchQuery}&start=${start}&max_results=${maxResults}&sortBy=relevance&sortOrder=descending`;
const xml = await fetchWithProxy(url);
return parseArxivAtom(xml);
});
}
function parseArxivAtom(xml: string): { papers: Paper[]; total: number } {
const parser = new DOMParser();
const doc = parser.parseFromString(xml, 'application/xml');
const totalEl = doc.querySelector('totalResults') ||
doc.getElementsByTagNameNS('http://a9.com/-/spec/opensearch/1.1/', 'totalResults')[0];
const total = totalEl ? parseInt(totalEl.textContent || '0') : 0;
const entries = doc.getElementsByTagName('entry');
const papers: Paper[] = [];
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
const getTag = (tag: string) => entry.getElementsByTagName(tag)[0]?.textContent?.trim() || '';
const idUrl = getTag('id');
const arxivId = idUrl.replace(/^https?:\/\/arxiv\.org\/abs\//, '').replace(/v\d+$/, '');
const title = getTag('title').replace(/\s+/g, ' ');
const abstract = getTag('summary').replace(/\s+/g, ' ');
const published = getTag('published');
const updated = getTag('updated');
const authorEls = entry.getElementsByTagName('author');
const authors: string[] = [];
for (let j = 0; j < authorEls.length; j++) {
const name = authorEls[j].getElementsByTagName('name')[0]?.textContent;
if (name) authors.push(name);
}
const catEls = entry.getElementsByTagName('category');
const categories: string[] = [];
for (let j = 0; j < catEls.length; j++) {
const term = catEls[j].getAttribute('term');
if (term) categories.push(term);
}
const linkEls = entry.getElementsByTagName('link');
let pdfLink = '';
for (let j = 0; j < linkEls.length; j++) {
if (linkEls[j].getAttribute('title') === 'pdf') {
pdfLink = linkEls[j].getAttribute('href') || '';
}
}
if (title) {
papers.push({
id: arxivId,
title,
authors,
abstract,
published,
updated,
categories,
pdfLink,
htmlLink: `https://ar5iv.labs.arxiv.org/html/${arxivId}`,
sectionsLoaded: false,
sectionsLoading: false,
});
}
}
return { papers, total };
}
// ==================== ar5iv Section Parser ====================
export async function fetchPaperSections(
arxivId: string
): Promise<{
introduction?: string;
relatedWork?: string;
methods?: string;
references?: Reference[];
}> {
return ar5ivLimiter.execute(async () => {
const url = `https://ar5iv.labs.arxiv.org/html/${arxivId}`;
const html = await fetchWithProxy(url);
return parseAr5ivHtml(html);
});
}
function parseAr5ivHtml(html: string): {
introduction?: string;
relatedWork?: string;
methods?: string;
references?: Reference[];
} {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
doc.querySelectorAll('script, style, nav, header, footer').forEach((el) => el.remove());
const result: {
introduction?: string;
relatedWork?: string;
methods?: string;
references?: Reference[];
} = {};
// Try multiple selectors for sections
const sectionSelectors = [
'section.ltx_section',
'section.ltx_chapter',
'div.ltx_section',
'section[id]',
];
let sections: Element[] = [];
for (const sel of sectionSelectors) {
const found = doc.querySelectorAll(sel);
if (found.length > 0) {
sections = Array.from(found);
break;
}
}
// If no structured sections found, try to parse by headings
if (sections.length === 0) {
const headings = doc.querySelectorAll('h2, h3');
headings.forEach((h) => {
const text = h.textContent?.toLowerCase() || '';
const parent = h.parentElement;
if (parent) {
if (text.includes('introduction')) result.introduction = parent.innerHTML;
else if (text.includes('related work') || text.includes('background'))
result.relatedWork = parent.innerHTML;
else if (text.includes('method') || text.includes('approach'))
result.methods = parent.innerHTML;
}
});
} else {
for (const section of sections) {
const heading = section.querySelector('h1, h2, h3, h4, .ltx_title');
if (!heading) continue;
const headingText = heading.textContent?.toLowerCase() || '';
if (
headingText.includes('introduction') &&
!headingText.includes('related')
) {
result.introduction = section.innerHTML;
} else if (
headingText.includes('related work') ||
headingText.includes('related works') ||
headingText.includes('literature review') ||
headingText.includes('background and related') ||
(headingText.includes('background') && headingText.includes('work'))
) {
result.relatedWork = section.innerHTML;
} else if (
!result.methods &&
(headingText.includes('method') ||
headingText.includes('approach') ||
headingText.includes('proposed') ||
headingText.includes('architecture') ||
headingText.includes('framework') ||
headingText.includes('model description'))
) {
result.methods = section.innerHTML;
}
}
}
// Parse references
const bibItems = doc.querySelectorAll(
'.ltx_bibitem, li[id*="bib"], .ltx_biblist > li'
);
const references: Reference[] = [];
bibItems.forEach((item) => {
const tagEl = item.querySelector('.ltx_tag, .ltx_tag_bibitem');
const number = tagEl?.textContent?.replace(/[\[\]]/g, '').trim() || '';
const key = item.id || `ref-${number}`;
let text = '';
const blocks = item.querySelectorAll('.ltx_bibblock');
if (blocks.length > 0) {
blocks.forEach((block) => {
text += block.textContent + ' ';
});
} else {
text = item.textContent?.replace(tagEl?.textContent || '', '').trim() || '';
}
text = text.trim();
let arxivId: string | undefined;
const links = item.querySelectorAll('a[href]');
links.forEach((link) => {
const href = link.getAttribute('href') || '';
const match = href.match(/arxiv\.org\/abs\/(\d{4}\.\d{4,5})/);
if (match) arxivId = match[1];
});
if (!arxivId) {
const textMatch = text.match(/arXiv[:\s]*(\d{4}\.\d{4,5})/i);
if (textMatch) arxivId = textMatch[1];
}
if (number || text) {
references.push({ key, number, text, arxivId });
}
});
result.references = references;
return result;
}
// ==================== Translation ====================
export async function translateText(
text: string,
targetLang: string = 'zh-CN'
): Promise<string> {
if (!text || text.trim().length === 0) return '';
// Strip HTML tags for translation
const plainText = text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
const chunks = splitIntoChunks(plainText, 4500);
const results: string[] = [];
for (const chunk of chunks) {
const translated = await translateChunk(chunk, targetLang);
results.push(translated);
if (chunks.length > 1) {
await new Promise((r) => setTimeout(r, 300));
}
}
return results.join('');
}
function splitIntoChunks(text: string, maxLen: number): string[] {
const chunks: string[] = [];
let remaining = text;
while (remaining.length > 0) {
if (remaining.length <= maxLen) {
chunks.push(remaining);
break;
}
let bp = maxLen;
const sentEnd = remaining.lastIndexOf('. ', maxLen);
if (sentEnd > maxLen * 0.5) bp = sentEnd + 2;
chunks.push(remaining.substring(0, bp));
remaining = remaining.substring(bp);
}
return chunks;
}
async function translateChunk(text: string, targetLang: string): Promise<string> {
// Try Google Translate unofficial API
try {
const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=${targetLang}&dt=t&q=${encodeURIComponent(text)}`;
const response = await fetch(url);
if (response.ok) {
const data = await response.json();
if (Array.isArray(data) && Array.isArray(data[0])) {
return data[0]
.filter((item: unknown) => Array.isArray(item) && item[0])
.map((item: unknown[]) => item[0])
.join('');
}
}
} catch {
// fallthrough
}
// Fallback: MyMemory
try {
const url = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text.substring(0, 500))}&langpair=en|${targetLang}`;
const response = await fetch(url);
if (response.ok) {
const data = await response.json();
if (data.responseStatus === 200) {
return data.responseData.translatedText;
}
}
} catch {
// fallthrough
}
throw new Error('翻译失败,请稍后重试 / Translation failed');
}
// ==================== Fetch Paper By ID ====================
export async function fetchPaperById(arxivId: string): Promise<Paper | null> {
return arxivLimiter.execute(async () => {
const cleanId = arxivId.replace(/^https?:\/\/arxiv\.org\/abs\//, '').replace(/v\d+$/, '');
const url = `https://export.arxiv.org/api/query?id_list=${encodeURIComponent(cleanId)}`;
const xml = await fetchWithProxy(url);
const { papers } = parseArxivAtom(xml);
return papers.length > 0 ? papers[0] : null;
});
}
// ==================== Helpers ====================
export function extractPlainText(html: string): string {
const div = document.createElement('div');
div.innerHTML = html;
return div.textContent || div.innerText || '';
}
|