Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,11 +6,15 @@ import gradio as gr
|
|
| 6 |
import os
|
| 7 |
import re
|
| 8 |
import bibtexparser
|
| 9 |
-
from bibtexparser.bparser import BibTexParser
|
| 10 |
from bibtexparser.customization import convert_to_unicode
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# ============================================
|
| 13 |
-
# CLEAN RESPONSIVE CSS -
|
| 14 |
# ============================================
|
| 15 |
custom_css = """
|
| 16 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
|
@@ -313,7 +317,7 @@ select option:checked,
|
|
| 313 |
}
|
| 314 |
"""
|
| 315 |
# ============================================
|
| 316 |
-
# SEARCH ENGINE
|
| 317 |
# ============================================
|
| 318 |
|
| 319 |
class PaperSearchPro:
|
|
@@ -321,6 +325,64 @@ class PaperSearchPro:
|
|
| 321 |
def __init__(self):
|
| 322 |
self.base_url = "https://api.openalex.org/works"
|
| 323 |
self.per_page = 200
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
def search_papers(self, query, keywords, authors, max_papers, year_from, year_to, open_access, sort_by, sort_order):
|
| 326 |
|
|
@@ -387,95 +449,142 @@ class PaperSearchPro:
|
|
| 387 |
break
|
| 388 |
|
| 389 |
# ===============================
|
| 390 |
-
#
|
| 391 |
-
#
|
| 392 |
# ===============================
|
| 393 |
|
| 394 |
keyword_phrases = [k.strip() for k in keywords.split(",") if k.strip()]
|
| 395 |
-
|
| 396 |
-
if len(keyword_phrases) >=
|
| 397 |
filtered = []
|
| 398 |
-
|
| 399 |
-
# Pre-process keyword
|
| 400 |
-
|
| 401 |
-
keyword_words = []
|
| 402 |
for phrase in keyword_phrases:
|
| 403 |
-
#
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
for
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
#
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
matched_phrases = [
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
break
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
all_papers = filtered[:max_papers]
|
| 474 |
|
| 475 |
# ===============================
|
| 476 |
-
# AUTHOR FILTERING (
|
| 477 |
# ===============================
|
| 478 |
-
elif authors and authors.strip():
|
| 479 |
# If we have author filter but no keyword hierarchy
|
| 480 |
author_list = [a.strip().lower() for a in authors.split(",") if a.strip()]
|
| 481 |
filtered = []
|
|
@@ -549,10 +658,10 @@ class PaperSearchPro:
|
|
| 549 |
print(f"Error fetching DOI: {e}")
|
| 550 |
|
| 551 |
elif search_type == "Exact Title":
|
| 552 |
-
# Search by exact title
|
| 553 |
params = {
|
| 554 |
-
"search":
|
| 555 |
-
"per-page":
|
| 556 |
"sort": "relevance_score:desc"
|
| 557 |
}
|
| 558 |
try:
|
|
@@ -560,13 +669,23 @@ class PaperSearchPro:
|
|
| 560 |
data = response.json()
|
| 561 |
results = data.get("results", [])
|
| 562 |
|
|
|
|
|
|
|
|
|
|
| 563 |
for work in results:
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
except Exception as e:
|
| 571 |
print(f"Error searching title: {e}")
|
| 572 |
|
|
@@ -595,6 +714,9 @@ class PaperSearchPro:
|
|
| 595 |
|
| 596 |
df = pd.DataFrame(all_papers)
|
| 597 |
column_order = ['Title', 'Authors', 'Year', 'Citations', 'Journal', 'PDF_URL', 'Abstract', 'BibTeX']
|
|
|
|
|
|
|
|
|
|
| 598 |
# Only include columns that exist
|
| 599 |
available_cols = [col for col in column_order if col in df.columns]
|
| 600 |
df = df[available_cols]
|
|
@@ -750,7 +872,7 @@ class PaperSearchPro:
|
|
| 750 |
return "\n".join(bibtex_lines)
|
| 751 |
|
| 752 |
# ============================================
|
| 753 |
-
#
|
| 754 |
# ============================================
|
| 755 |
|
| 756 |
def parse_bibtex_file(self, bibtex_file):
|
|
@@ -829,11 +951,11 @@ class PaperSearchPro:
|
|
| 829 |
except:
|
| 830 |
pass
|
| 831 |
|
| 832 |
-
# Try title search
|
| 833 |
if entry.get('title'):
|
| 834 |
params = {
|
| 835 |
'search': entry['title'],
|
| 836 |
-
'per-page':
|
| 837 |
'sort': 'relevance_score:desc'
|
| 838 |
}
|
| 839 |
|
|
@@ -843,42 +965,60 @@ class PaperSearchPro:
|
|
| 843 |
results = data.get('results', [])
|
| 844 |
|
| 845 |
if results:
|
| 846 |
-
best_match =
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
# Calculate confidence
|
| 850 |
-
confidence = 0.5
|
| 851 |
-
|
| 852 |
-
# Check year
|
| 853 |
-
if entry.get('year') and str(corrected['Year']) == entry['year']:
|
| 854 |
-
confidence += 0.3
|
| 855 |
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 871 |
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
'
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 882 |
except:
|
| 883 |
pass
|
| 884 |
|
|
@@ -899,7 +1039,7 @@ class PaperSearchPro:
|
|
| 899 |
entries = self.parse_bibtex_file(bibtex_file)
|
| 900 |
|
| 901 |
if not entries:
|
| 902 |
-
return None, "β No valid BibTeX entries found"
|
| 903 |
|
| 904 |
# Check each entry
|
| 905 |
results = []
|
|
@@ -937,6 +1077,7 @@ class PaperSearchPro:
|
|
| 937 |
<th>Original BibTeX Key</th>
|
| 938 |
<th>Original Title</th>
|
| 939 |
<th>Corrected Title</th>
|
|
|
|
| 940 |
<th>Status</th>
|
| 941 |
</tr>
|
| 942 |
"""
|
|
@@ -959,8 +1100,10 @@ class PaperSearchPro:
|
|
| 959 |
|
| 960 |
if result['corrected']:
|
| 961 |
corrected_title = result['corrected']['Title'][:50] + "..." if len(result['corrected']['Title']) > 50 else result['corrected']['Title']
|
|
|
|
| 962 |
else:
|
| 963 |
corrected_title = "No match found"
|
|
|
|
| 964 |
|
| 965 |
html_output += f"""
|
| 966 |
<tr>
|
|
@@ -968,6 +1111,7 @@ class PaperSearchPro:
|
|
| 968 |
<td><code>{original['id']}</code></td>
|
| 969 |
<td><div class="original-ref">{original_title}</div></td>
|
| 970 |
<td><div class="corrected-ref">{corrected_title}</div></td>
|
|
|
|
| 971 |
<td class="{status_class}">{status_text}</td>
|
| 972 |
</tr>
|
| 973 |
"""
|
|
@@ -1063,10 +1207,13 @@ def create_interface():
|
|
| 1063 |
with gr.Row():
|
| 1064 |
with gr.Column():
|
| 1065 |
keywords = gr.Textbox(
|
| 1066 |
-
label="Required Keywords (first 2
|
| 1067 |
-
value="blood, photoacoustics, imaging",
|
| 1068 |
-
placeholder="e.g., blood, photoacoustics, imaging (comma-separated)"
|
| 1069 |
)
|
|
|
|
|
|
|
|
|
|
| 1070 |
|
| 1071 |
with gr.Column():
|
| 1072 |
authors = gr.Textbox(
|
|
@@ -1117,6 +1264,8 @@ def create_interface():
|
|
| 1117 |
- **DOI** (e.g., 10.1038/nature12373)
|
| 1118 |
- **Exact Title** (e.g., "Photoacoustic imaging in biomedicine")
|
| 1119 |
- **Author** (find papers by a specific researcher)
|
|
|
|
|
|
|
| 1120 |
""")
|
| 1121 |
|
| 1122 |
with gr.Row():
|
|
@@ -1135,7 +1284,7 @@ def create_interface():
|
|
| 1135 |
specific_search_btn = gr.Button("π FIND PAPER", variant="primary")
|
| 1136 |
specific_summary = gr.Markdown("Ready")
|
| 1137 |
|
| 1138 |
-
# Tab 3: BibTeX Checker
|
| 1139 |
with gr.TabItem("π Check BibTeX", id=2):
|
| 1140 |
with gr.Column(elem_classes="white-card"):
|
| 1141 |
gr.Markdown("""
|
|
@@ -1147,6 +1296,8 @@ def create_interface():
|
|
| 1147 |
3. Show you which entries are correct and which need fixing
|
| 1148 |
4. Generate a corrected BibTeX file
|
| 1149 |
5. Provide a comparison CSV with all details
|
|
|
|
|
|
|
| 1150 |
""")
|
| 1151 |
|
| 1152 |
bibtex_file = gr.File(
|
|
@@ -1227,7 +1378,7 @@ def create_interface():
|
|
| 1227 |
return df, papers, summary, "**0**", "**0.0**", "**N/A**"
|
| 1228 |
|
| 1229 |
total = len(papers)
|
| 1230 |
-
avg_rel = 0
|
| 1231 |
years = [p["Year"] for p in papers if p["Year"] != "N/A"]
|
| 1232 |
year_range = f"{min(years)} - {max(years)}" if years else "N/A"
|
| 1233 |
|
|
|
|
| 6 |
import os
|
| 7 |
import re
|
| 8 |
import bibtexparser
|
| 9 |
+
from bibtexparser.bparser import BibTexParser
|
| 10 |
from bibtexparser.customization import convert_to_unicode
|
| 11 |
+
from difflib import SequenceMatcher
|
| 12 |
+
import numpy as np
|
| 13 |
+
from collections import Counter
|
| 14 |
+
import math
|
| 15 |
|
| 16 |
# ============================================
|
| 17 |
+
# CLEAN RESPONSIVE CSS - (same as your original)
|
| 18 |
# ============================================
|
| 19 |
custom_css = """
|
| 20 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
|
|
|
| 317 |
}
|
| 318 |
"""
|
| 319 |
# ============================================
|
| 320 |
+
# SEARCH ENGINE - ENHANCED WITH GOOGLE SCHOLAR LIKE SENSITIVITY
|
| 321 |
# ============================================
|
| 322 |
|
| 323 |
class PaperSearchPro:
|
|
|
|
| 325 |
def __init__(self):
|
| 326 |
self.base_url = "https://api.openalex.org/works"
|
| 327 |
self.per_page = 200
|
| 328 |
+
# Common stop words to ignore in matching
|
| 329 |
+
self.stop_words = set(['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
|
| 330 |
+
'of', 'with', 'by', 'from', 'as', 'is', 'was', 'are', 'were', 'be',
|
| 331 |
+
'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will',
|
| 332 |
+
'would', 'should', 'could', 'may', 'might', 'must', 'can'])
|
| 333 |
+
|
| 334 |
+
def calculate_text_similarity(self, text1, text2):
|
| 335 |
+
"""Calculate similarity between two texts using multiple methods"""
|
| 336 |
+
if not text1 or not text2:
|
| 337 |
+
return 0
|
| 338 |
+
|
| 339 |
+
text1 = text1.lower()
|
| 340 |
+
text2 = text2.lower()
|
| 341 |
+
|
| 342 |
+
# Method 1: Sequence matching (good for phrases)
|
| 343 |
+
seq_similarity = SequenceMatcher(None, text1, text2).ratio()
|
| 344 |
+
|
| 345 |
+
# Method 2: Word overlap (good for keywords)
|
| 346 |
+
words1 = set(re.findall(r'\w+', text1))
|
| 347 |
+
words2 = set(re.findall(r'\w+', text2))
|
| 348 |
+
|
| 349 |
+
# Remove stop words for better matching
|
| 350 |
+
words1 = words1 - self.stop_words
|
| 351 |
+
words2 = words2 - self.stop_words
|
| 352 |
+
|
| 353 |
+
if not words1 or not words2:
|
| 354 |
+
return seq_similarity
|
| 355 |
+
|
| 356 |
+
intersection = words1.intersection(words2)
|
| 357 |
+
union = words1.union(words2)
|
| 358 |
+
word_similarity = len(intersection) / len(union) if union else 0
|
| 359 |
+
|
| 360 |
+
# Method 3: Partial word matching (for stem variations)
|
| 361 |
+
partial_matches = 0
|
| 362 |
+
for w1 in words1:
|
| 363 |
+
for w2 in words2:
|
| 364 |
+
if len(w1) > 3 and len(w2) > 3:
|
| 365 |
+
if w1 in w2 or w2 in w1 or SequenceMatcher(None, w1, w2).ratio() > 0.8:
|
| 366 |
+
partial_matches += 1
|
| 367 |
+
break
|
| 368 |
+
|
| 369 |
+
partial_ratio = partial_matches / len(words1) if words1 else 0
|
| 370 |
+
|
| 371 |
+
# Weighted combination
|
| 372 |
+
return (seq_similarity * 0.3 + word_similarity * 0.5 + partial_ratio * 0.2)
|
| 373 |
+
|
| 374 |
+
def extract_keywords_from_phrase(self, phrase):
|
| 375 |
+
"""Extract meaningful keywords from a phrase"""
|
| 376 |
+
words = re.findall(r'\w+', phrase.lower())
|
| 377 |
+
# Remove stop words and short words
|
| 378 |
+
keywords = [w for w in words if w not in self.stop_words and len(w) > 2]
|
| 379 |
+
|
| 380 |
+
# Also include bigrams if phrase has multiple words
|
| 381 |
+
if len(words) > 1:
|
| 382 |
+
bigrams = [' '.join(words[i:i+2]) for i in range(len(words)-1)]
|
| 383 |
+
keywords.extend(bigrams)
|
| 384 |
+
|
| 385 |
+
return list(set(keywords)) # Remove duplicates
|
| 386 |
|
| 387 |
def search_papers(self, query, keywords, authors, max_papers, year_from, year_to, open_access, sort_by, sort_order):
|
| 388 |
|
|
|
|
| 449 |
break
|
| 450 |
|
| 451 |
# ===============================
|
| 452 |
+
# ENHANCED KEYWORD FILTERING - GOOGLE SCHOLAR LIKE SENSITIVITY
|
| 453 |
+
# Supports unlimited keywords with fuzzy matching and relevance scoring
|
| 454 |
# ===============================
|
| 455 |
|
| 456 |
keyword_phrases = [k.strip() for k in keywords.split(",") if k.strip()]
|
| 457 |
+
|
| 458 |
+
if len(keyword_phrases) >= 1: # At least one keyword required
|
| 459 |
filtered = []
|
| 460 |
+
|
| 461 |
+
# Pre-process each keyword phrase into search terms
|
| 462 |
+
keyword_search_terms = []
|
|
|
|
| 463 |
for phrase in keyword_phrases:
|
| 464 |
+
# Extract meaningful keywords from each phrase
|
| 465 |
+
terms = self.extract_keywords_from_phrase(phrase)
|
| 466 |
+
keyword_search_terms.append({
|
| 467 |
+
'original': phrase,
|
| 468 |
+
'terms': terms,
|
| 469 |
+
'weight': 1.0
|
| 470 |
+
})
|
| 471 |
+
|
| 472 |
+
# Calculate IDF-like weights for terms (rarer terms get higher weight)
|
| 473 |
+
all_terms = []
|
| 474 |
+
for kst in keyword_search_terms:
|
| 475 |
+
all_terms.extend(kst['terms'])
|
| 476 |
+
|
| 477 |
+
term_freq = Counter(all_terms)
|
| 478 |
+
total_terms = len(all_terms)
|
| 479 |
+
|
| 480 |
+
for kst in keyword_search_terms:
|
| 481 |
+
# Adjust weight based on term rarity
|
| 482 |
+
avg_freq = sum(term_freq[t] for t in kst['terms']) / len(kst['terms']) if kst['terms'] else 1
|
| 483 |
+
# Rarer terms (lower frequency) get higher weight
|
| 484 |
+
kst['weight'] = 1.0 / (avg_freq / total_terms + 0.1) if avg_freq > 0 else 1.0
|
| 485 |
+
|
| 486 |
+
for paper in all_papers:
|
| 487 |
+
# Combine all text fields for searching
|
| 488 |
+
combined_text = f"{paper['Title']} {paper['Abstract']} {paper['Authors']}".lower()
|
| 489 |
+
|
| 490 |
+
# Calculate relevance score using multiple factors
|
| 491 |
+
score = 0
|
| 492 |
+
matched_terms = []
|
| 493 |
+
matched_phrases = []
|
| 494 |
+
|
| 495 |
+
# Check each keyword phrase
|
| 496 |
+
for i, kst in enumerate(keyword_search_terms):
|
| 497 |
+
phrase_score = 0
|
| 498 |
+
phrase_matched_terms = []
|
| 499 |
+
|
| 500 |
+
# Check each term in the phrase
|
| 501 |
+
for term in kst['terms']:
|
| 502 |
+
# Exact match (highest score)
|
| 503 |
+
if term in combined_text:
|
| 504 |
+
term_score = 1.0 * kst['weight']
|
| 505 |
+
phrase_matched_terms.append(term)
|
| 506 |
+
else:
|
| 507 |
+
# Fuzzy/partial matching
|
| 508 |
+
# Check if term appears as part of a word
|
| 509 |
+
words = re.findall(r'\w+', combined_text)
|
| 510 |
+
best_partial = 0
|
| 511 |
+
|
| 512 |
+
for word in words:
|
| 513 |
+
if len(word) > 3 and len(term) > 3:
|
| 514 |
+
# Check if term is a substring of word
|
| 515 |
+
if term in word:
|
| 516 |
+
best_partial = max(best_partial, 0.8)
|
| 517 |
+
# Check word similarity
|
| 518 |
+
elif SequenceMatcher(None, term, word).ratio() > 0.7:
|
| 519 |
+
sim = SequenceMatcher(None, term, word).ratio()
|
| 520 |
+
best_partial = max(best_partial, sim * 0.7)
|
| 521 |
+
|
| 522 |
+
if best_partial > 0:
|
| 523 |
+
term_score = best_partial * kst['weight']
|
| 524 |
+
phrase_matched_terms.append(f"{term}~")
|
| 525 |
+
else:
|
| 526 |
+
term_score = 0
|
| 527 |
+
|
| 528 |
+
if term_score > 0:
|
| 529 |
+
phrase_score += term_score
|
| 530 |
+
|
| 531 |
+
# Normalize phrase score by number of terms
|
| 532 |
+
if kst['terms']:
|
| 533 |
+
phrase_score = phrase_score / len(kst['terms'])
|
| 534 |
+
|
| 535 |
+
# First two phrases are required (must have at least partial match)
|
| 536 |
+
if i < 2:
|
| 537 |
+
if phrase_score > 0.3: # Partial match threshold for required phrases
|
| 538 |
+
score += phrase_score * 2 # Higher weight for first two
|
| 539 |
+
matched_phrases.append(kst['original'])
|
| 540 |
+
matched_terms.extend(phrase_matched_terms)
|
| 541 |
+
else:
|
| 542 |
+
# Required phrase not matched well enough - skip this paper
|
| 543 |
+
score = 0
|
| 544 |
break
|
| 545 |
+
else:
|
| 546 |
+
# Additional phrases boost score
|
| 547 |
+
if phrase_score > 0:
|
| 548 |
+
score += phrase_score
|
| 549 |
+
matched_phrases.append(kst['original'])
|
| 550 |
+
matched_terms.extend(phrase_matched_terms)
|
| 551 |
+
|
| 552 |
+
if score > 0:
|
| 553 |
+
# Additional boost factors
|
| 554 |
+
|
| 555 |
+
# 1. Title match boost (keywords in title are more important)
|
| 556 |
+
title_text = paper['Title'].lower()
|
| 557 |
+
title_boost = 0
|
| 558 |
+
for term in set(matched_terms):
|
| 559 |
+
term_clean = term.replace('~', '')
|
| 560 |
+
if term_clean in title_text:
|
| 561 |
+
title_boost += 0.2
|
| 562 |
+
score += title_boost
|
| 563 |
+
|
| 564 |
+
# 2. Recent papers boost (slightly)
|
| 565 |
+
if paper['Year'] != 'N/A' and paper['Year'] >= 2020:
|
| 566 |
+
score += 0.1
|
| 567 |
+
|
| 568 |
+
# 3. Citation boost (log scale)
|
| 569 |
+
if paper['Citations'] > 0:
|
| 570 |
+
citation_boost = math.log10(paper['Citations'] + 1) * 0.05
|
| 571 |
+
score += min(citation_boost, 0.3)
|
| 572 |
+
|
| 573 |
+
paper['Relevance'] = round(score, 2)
|
| 574 |
+
paper['Matched Keywords'] = f"Phrases: {', '.join(matched_phrases[:5])}" + \
|
| 575 |
+
(f" (+{len(matched_phrases)-5} more)" if len(matched_phrases) > 5 else "") + \
|
| 576 |
+
f" | Terms: {', '.join(matched_terms[:10])}" + \
|
| 577 |
+
(f" (+{len(matched_terms)-10} more)" if len(matched_terms) > 10 else "")
|
| 578 |
+
filtered.append(paper)
|
| 579 |
+
|
| 580 |
+
# Sort by relevance score (descending)
|
| 581 |
+
filtered.sort(key=lambda x: x['Relevance'], reverse=True)
|
| 582 |
all_papers = filtered[:max_papers]
|
| 583 |
|
| 584 |
# ===============================
|
| 585 |
+
# AUTHOR FILTERING (if no keywords)
|
| 586 |
# ===============================
|
| 587 |
+
elif authors and authors.strip() and not keyword_phrases:
|
| 588 |
# If we have author filter but no keyword hierarchy
|
| 589 |
author_list = [a.strip().lower() for a in authors.split(",") if a.strip()]
|
| 590 |
filtered = []
|
|
|
|
| 658 |
print(f"Error fetching DOI: {e}")
|
| 659 |
|
| 660 |
elif search_type == "Exact Title":
|
| 661 |
+
# Search by exact title with fuzzy matching
|
| 662 |
params = {
|
| 663 |
+
"search": search_value,
|
| 664 |
+
"per-page": 20,
|
| 665 |
"sort": "relevance_score:desc"
|
| 666 |
}
|
| 667 |
try:
|
|
|
|
| 669 |
data = response.json()
|
| 670 |
results = data.get("results", [])
|
| 671 |
|
| 672 |
+
best_match = None
|
| 673 |
+
best_score = 0
|
| 674 |
+
|
| 675 |
for work in results:
|
| 676 |
+
title = work.get("title", "")
|
| 677 |
+
if title:
|
| 678 |
+
# Calculate similarity score
|
| 679 |
+
similarity = self.calculate_text_similarity(search_value, title)
|
| 680 |
+
if similarity > best_score and similarity > 0.4: # Threshold for acceptance
|
| 681 |
+
best_score = similarity
|
| 682 |
+
best_match = work
|
| 683 |
+
|
| 684 |
+
if best_match:
|
| 685 |
+
paper = self.extract_info(best_match)
|
| 686 |
+
paper['Match_Score'] = round(best_score, 2)
|
| 687 |
+
all_papers.append(paper)
|
| 688 |
+
|
| 689 |
except Exception as e:
|
| 690 |
print(f"Error searching title: {e}")
|
| 691 |
|
|
|
|
| 714 |
|
| 715 |
df = pd.DataFrame(all_papers)
|
| 716 |
column_order = ['Title', 'Authors', 'Year', 'Citations', 'Journal', 'PDF_URL', 'Abstract', 'BibTeX']
|
| 717 |
+
if 'Match_Score' in df.columns:
|
| 718 |
+
column_order.insert(1, 'Match_Score')
|
| 719 |
+
|
| 720 |
# Only include columns that exist
|
| 721 |
available_cols = [col for col in column_order if col in df.columns]
|
| 722 |
df = df[available_cols]
|
|
|
|
| 872 |
return "\n".join(bibtex_lines)
|
| 873 |
|
| 874 |
# ============================================
|
| 875 |
+
# BIBTEX CHECKER FEATURE
|
| 876 |
# ============================================
|
| 877 |
|
| 878 |
def parse_bibtex_file(self, bibtex_file):
|
|
|
|
| 951 |
except:
|
| 952 |
pass
|
| 953 |
|
| 954 |
+
# Try title search with enhanced matching
|
| 955 |
if entry.get('title'):
|
| 956 |
params = {
|
| 957 |
'search': entry['title'],
|
| 958 |
+
'per-page': 10,
|
| 959 |
'sort': 'relevance_score:desc'
|
| 960 |
}
|
| 961 |
|
|
|
|
| 965 |
results = data.get('results', [])
|
| 966 |
|
| 967 |
if results:
|
| 968 |
+
best_match = None
|
| 969 |
+
best_confidence = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 970 |
|
| 971 |
+
for work in results:
|
| 972 |
+
if work.get('title'):
|
| 973 |
+
# Calculate similarity
|
| 974 |
+
similarity = self.calculate_text_similarity(entry['title'], work['title'])
|
| 975 |
+
|
| 976 |
+
confidence = similarity * 0.6 # Base confidence from title match
|
| 977 |
+
|
| 978 |
+
# Check year
|
| 979 |
+
if entry.get('year') and work.get('publication_year'):
|
| 980 |
+
if str(work['publication_year']) == entry['year']:
|
| 981 |
+
confidence += 0.25
|
| 982 |
+
|
| 983 |
+
# Check author
|
| 984 |
+
if entry.get('author'):
|
| 985 |
+
work_authors = []
|
| 986 |
+
for auth in work.get('authorships', []):
|
| 987 |
+
name = auth.get('raw_author_name', '') or auth.get('author', {}).get('display_name', '')
|
| 988 |
+
if name:
|
| 989 |
+
work_authors.append(name.lower())
|
| 990 |
+
|
| 991 |
+
work_authors_str = ' '.join(work_authors)
|
| 992 |
+
entry_authors = entry['author'].lower()
|
| 993 |
+
|
| 994 |
+
# Check if any author matches
|
| 995 |
+
for author in entry_authors.split(' and '):
|
| 996 |
+
author_parts = author.strip().split()
|
| 997 |
+
for part in author_parts:
|
| 998 |
+
if len(part) > 2 and part in work_authors_str:
|
| 999 |
+
confidence += 0.15
|
| 1000 |
+
break
|
| 1001 |
+
|
| 1002 |
+
confidence = min(confidence, 1.0)
|
| 1003 |
+
|
| 1004 |
+
if confidence > best_confidence:
|
| 1005 |
+
best_confidence = confidence
|
| 1006 |
+
best_match = work
|
| 1007 |
|
| 1008 |
+
if best_match and best_confidence > 0.4:
|
| 1009 |
+
corrected = self.extract_info(best_match)
|
| 1010 |
+
corrected_bibtex = self.generate_bibtex(best_match, corrected['Authors'].split(', '))
|
| 1011 |
+
|
| 1012 |
+
status = 'valid' if best_confidence > 0.8 else 'partial' if best_confidence > 0.5 else 'not_found'
|
| 1013 |
+
|
| 1014 |
+
return {
|
| 1015 |
+
'original': entry,
|
| 1016 |
+
'corrected': corrected,
|
| 1017 |
+
'corrected_bibtex': corrected_bibtex,
|
| 1018 |
+
'status': status,
|
| 1019 |
+
'confidence': best_confidence,
|
| 1020 |
+
'method': 'title search'
|
| 1021 |
+
}
|
| 1022 |
except:
|
| 1023 |
pass
|
| 1024 |
|
|
|
|
| 1039 |
entries = self.parse_bibtex_file(bibtex_file)
|
| 1040 |
|
| 1041 |
if not entries:
|
| 1042 |
+
return None, None, "β No valid BibTeX entries found"
|
| 1043 |
|
| 1044 |
# Check each entry
|
| 1045 |
results = []
|
|
|
|
| 1077 |
<th>Original BibTeX Key</th>
|
| 1078 |
<th>Original Title</th>
|
| 1079 |
<th>Corrected Title</th>
|
| 1080 |
+
<th>Confidence</th>
|
| 1081 |
<th>Status</th>
|
| 1082 |
</tr>
|
| 1083 |
"""
|
|
|
|
| 1100 |
|
| 1101 |
if result['corrected']:
|
| 1102 |
corrected_title = result['corrected']['Title'][:50] + "..." if len(result['corrected']['Title']) > 50 else result['corrected']['Title']
|
| 1103 |
+
confidence = f"{result['confidence']:.0%}"
|
| 1104 |
else:
|
| 1105 |
corrected_title = "No match found"
|
| 1106 |
+
confidence = "0%"
|
| 1107 |
|
| 1108 |
html_output += f"""
|
| 1109 |
<tr>
|
|
|
|
| 1111 |
<td><code>{original['id']}</code></td>
|
| 1112 |
<td><div class="original-ref">{original_title}</div></td>
|
| 1113 |
<td><div class="corrected-ref">{corrected_title}</div></td>
|
| 1114 |
+
<td>{confidence}</td>
|
| 1115 |
<td class="{status_class}">{status_text}</td>
|
| 1116 |
</tr>
|
| 1117 |
"""
|
|
|
|
| 1207 |
with gr.Row():
|
| 1208 |
with gr.Column():
|
| 1209 |
keywords = gr.Textbox(
|
| 1210 |
+
label="Required Keywords (unlimited, first 2 required for match)",
|
| 1211 |
+
value="blood, photoacoustics, imaging, vascular, hemoglobin",
|
| 1212 |
+
placeholder="e.g., blood, photoacoustics, imaging, vascular (comma-separated)"
|
| 1213 |
)
|
| 1214 |
+
gr.Markdown("""
|
| 1215 |
+
<small style="color: #6b7280;">β¨ **Enhanced matching**: Supports unlimited keywords with fuzzy/partial matching like Google Scholar</small>
|
| 1216 |
+
""")
|
| 1217 |
|
| 1218 |
with gr.Column():
|
| 1219 |
authors = gr.Textbox(
|
|
|
|
| 1264 |
- **DOI** (e.g., 10.1038/nature12373)
|
| 1265 |
- **Exact Title** (e.g., "Photoacoustic imaging in biomedicine")
|
| 1266 |
- **Author** (find papers by a specific researcher)
|
| 1267 |
+
|
| 1268 |
+
β¨ **Enhanced**: Title matching now uses fuzzy similarity scoring
|
| 1269 |
""")
|
| 1270 |
|
| 1271 |
with gr.Row():
|
|
|
|
| 1284 |
specific_search_btn = gr.Button("π FIND PAPER", variant="primary")
|
| 1285 |
specific_summary = gr.Markdown("Ready")
|
| 1286 |
|
| 1287 |
+
# Tab 3: BibTeX Checker
|
| 1288 |
with gr.TabItem("π Check BibTeX", id=2):
|
| 1289 |
with gr.Column(elem_classes="white-card"):
|
| 1290 |
gr.Markdown("""
|
|
|
|
| 1296 |
3. Show you which entries are correct and which need fixing
|
| 1297 |
4. Generate a corrected BibTeX file
|
| 1298 |
5. Provide a comparison CSV with all details
|
| 1299 |
+
|
| 1300 |
+
β¨ **Enhanced**: Better title matching with fuzzy similarity scoring
|
| 1301 |
""")
|
| 1302 |
|
| 1303 |
bibtex_file = gr.File(
|
|
|
|
| 1378 |
return df, papers, summary, "**0**", "**0.0**", "**N/A**"
|
| 1379 |
|
| 1380 |
total = len(papers)
|
| 1381 |
+
avg_rel = sum(p.get('Match_Score', 0) for p in papers) / total if total else 0
|
| 1382 |
years = [p["Year"] for p in papers if p["Year"] != "N/A"]
|
| 1383 |
year_range = f"{min(years)} - {max(years)}" if years else "N/A"
|
| 1384 |
|