Subahdip627 commited on
Commit
aca47bf
Β·
verified Β·
1 Parent(s): cd1f6b5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +623 -85
app.py CHANGED
@@ -1,14 +1,12 @@
1
- """
2
- PaperSearchPro - FULL Professional Version
3
- Hierarchical Keyword Search + Export + Responsive UI + BibTeX Support + Author Filter + Specific Paper Search
4
- """
5
-
6
  import requests
7
  import pandas as pd
8
  import time
9
  from datetime import datetime
10
- import gradio as gr # Make sure this import is present
11
  import os
 
 
 
12
 
13
  # ============================================
14
  # CLEAN RESPONSIVE CSS - UPDATED WITH DARKER GRAY BACKGROUND
@@ -29,7 +27,7 @@ custom_css = """
29
  /* ================================================= */
30
 
31
  body, .gradio-container {
32
- font-family: 'Inter', sans-serif !important;
33
  background-color: #e5e7eb !important;
34
  color: var(--text-main) !important;
35
  }
@@ -141,21 +139,21 @@ button.variant-secondary {
141
  /* ========================================= */
142
 
143
  /* All buttons */
144
- button,
145
  .gr-button {
146
- color: #ffffff !important; /* TEXT WHITE */
147
  }
148
 
149
  /* Primary button */
150
  button.variant-primary {
151
- background-color: #2563eb !important; /* keep blue */
152
- color: #ffffff !important; /* TEXT WHITE */
153
  }
154
 
155
  /* Secondary button */
156
  button.variant-secondary {
157
- background-color: #6b7280 !important; /* keep gray */
158
- color: #ffffff !important; /* TEXT WHITE */
159
  }
160
 
161
  /* Keep text white even on hover */
@@ -168,8 +166,8 @@ button:hover {
168
 
169
  .metric-label {
170
  display: inline-block !important;
171
- background-color: #111827 !important; /* Black */
172
- color: #ffffff !important; /* White text */
173
  padding: 6px 12px !important;
174
  border-radius: 6px !important;
175
  font-weight: 600 !important;
@@ -183,8 +181,8 @@ button:hover {
183
 
184
  .metric-value {
185
  display: inline-block !important;
186
- background-color: #111827 !important; /* Black */
187
- color: #ffffff !important; /* White text */
188
  padding: 6px 12px !important;
189
  border-radius: 6px !important;
190
  font-weight: 700 !important;
@@ -195,6 +193,123 @@ button:hover {
195
  background: transparent !important;
196
  color: #ffffff !important;
197
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  """
199
  # ============================================
200
  # SEARCH ENGINE
@@ -271,31 +386,84 @@ class PaperSearchPro:
271
  break
272
 
273
  # ===============================
274
- # HIERARCHICAL KEYWORD FILTERING
 
275
  # ===============================
276
 
277
- keyword_list = [k.strip().lower() for k in keywords.split(",") if k.strip()]
278
 
279
- if len(keyword_list) >= 2:
280
  filtered = []
281
 
 
 
 
 
 
 
 
 
 
 
282
  for p in all_papers:
283
  combined = f"{p['Title']} {p['Abstract']} {p['Authors']} {p['All Authors']}".lower()
284
 
285
- # first 2 keywords REQUIRED
286
- if keyword_list[0] not in combined or keyword_list[1] not in combined:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  continue
288
 
289
- score = 2
290
- matched = [keyword_list[0], keyword_list[1]]
 
 
 
 
 
 
 
 
 
 
 
 
291
 
292
- for kw in keyword_list[2:]:
293
- if kw in combined:
 
 
 
 
 
 
 
 
294
  score += 1
295
- matched.append(kw)
 
 
 
 
 
 
 
 
296
 
297
  p["Relevance"] = score
298
- p["Matched Keywords"] = ", ".join(matched)
299
 
300
  filtered.append(p)
301
 
@@ -317,11 +485,25 @@ class PaperSearchPro:
317
  matched_authors = []
318
 
319
  for author in author_list:
320
- if author in all_authors_lower:
321
- matched_authors.append(author)
322
- else:
323
- match_all = False
324
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
 
326
  if match_all:
327
  p["Relevance"] = len(matched_authors)
@@ -338,7 +520,7 @@ class PaperSearchPro:
338
  df = pd.DataFrame(all_papers)
339
 
340
  # Reorder columns to include BibTeX and remove All Authors from display
341
- column_order = ['Title', 'Authors', 'Year', 'Citations', 'Journal', 'Abstract',
342
  'BibTeX', 'Relevance', 'Matched Keywords']
343
  df = df[column_order]
344
 
@@ -411,7 +593,7 @@ class PaperSearchPro:
411
  p['Rank'] = i + 1
412
 
413
  df = pd.DataFrame(all_papers)
414
- column_order = ['Title', 'Authors', 'Year', 'Citations', 'Journal', 'Abstract', 'BibTeX']
415
  # Only include columns that exist
416
  available_cols = [col for col in column_order if col in df.columns]
417
  df = df[available_cols]
@@ -462,6 +644,15 @@ class PaperSearchPro:
462
  if doi:
463
  doi = doi.replace("https://doi.org/", "")
464
 
 
 
 
 
 
 
 
 
 
465
  # Generate BibTeX entry
466
  bibtex = self.generate_bibtex(work, all_authors)
467
 
@@ -473,6 +664,7 @@ class PaperSearchPro:
473
  "Citations": work.get("cited_by_count", 0),
474
  "Journal": (work.get("primary_location", {}).get("source") or {}).get("display_name", "Unknown"),
475
  "DOI": doi,
 
476
  "Abstract": abstract,
477
  "BibTeX": bibtex,
478
  "Relevance": 0,
@@ -556,6 +748,268 @@ class PaperSearchPro:
556
 
557
  return "\n".join(bibtex_lines)
558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
559
 
560
  # ============================================
561
  # INTERFACE
@@ -563,23 +1017,23 @@ class PaperSearchPro:
563
 
564
  def create_interface():
565
 
566
- with gr.Blocks(
567
- title="PaperSearchPro",
568
- css=custom_css,
569
- theme=gr.themes.Default(
570
  primary_hue="blue",
571
  neutral_hue="gray"
572
- )) as demo:
 
 
573
 
574
  gr.HTML("""
575
- <div style='text-align:center; padding:2rem 0'>
576
- <h1><span>πŸ“± PaperSearchPro</span></h1>
577
- <p class='subtitle-text'>Professional Academic Paper Search with BibTeX & Author Filter</p>
578
  </div>
579
  """)
580
 
581
  # Create tabs for different search modes
582
- with gr.Tabs(elem_classes="tab-nav"):
583
  # Tab 1: General Search
584
  with gr.TabItem("πŸ” General Search", id=0):
585
  with gr.Column(elem_classes="white-card"):
@@ -605,10 +1059,10 @@ def create_interface():
605
  placeholder="e.g., Smith, Zhang, Wang (comma-separated)"
606
  )
607
 
608
- # ==========================
609
  # MAX PAPERS SLIDER WITH BLACK REGION COMMENT
610
  # ==========================
611
- max_papers = gr.Slider(1000, 50000, value=1000, step=100, label="Max Papers")
612
 
613
  # Add black region comment below slider
614
  gr.HTML("""
@@ -622,7 +1076,7 @@ def create_interface():
622
  year_to = gr.Number(value=2026, label="Year To", precision=0)
623
  open_access = gr.Checkbox(label="Open Access Only")
624
 
625
- # ==========================
626
  # SORTING OPTIONS
627
  # ==========================
628
  with gr.Row():
@@ -658,59 +1112,88 @@ def create_interface():
658
 
659
  specific_search_value = gr.Textbox(
660
  label="Enter value",
661
- placeholder="e.g., 10.1038/nature12373 or exact paper title or author name",
662
  scale=2
663
  )
664
 
665
  specific_search_btn = gr.Button("πŸ” FIND PAPER", variant="primary")
666
  specific_summary = gr.Markdown("Ready")
667
 
668
- # Metrics section (common for both tabs)
669
- with gr.Row():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
670
  total_display = gr.Markdown("**0**", elem_classes="metric-value")
671
  avg_display = gr.Markdown("**0.0**", elem_classes="metric-value")
672
  year_display = gr.Markdown("**N/A**", elem_classes="metric-value")
673
 
674
  # Add labels for metrics
675
- with gr.Row():
676
  gr.Markdown("**Total Papers**", elem_classes="metric-label")
677
  gr.Markdown("**Avg Relevance**", elem_classes="metric-label")
678
  gr.Markdown("**Year Range**", elem_classes="metric-label")
679
 
680
- # Results section (common for both tabs)
681
  results = gr.Dataframe(
682
  label="Results",
683
  row_count=15,
684
- column_widths=["25%", "15%", "5%", "5%", "10%", "20%", "20%", "5%", "5%"],
685
- wrap=True
 
686
  )
687
  state = gr.State([])
688
 
 
 
689
  # ==========================
690
- # EXPORT SECTION
691
- # ==========================
692
-
693
- gr.HTML("""
694
- <h3 style="color: #2563eb !important; font-weight: 600; margin-bottom: 16px; margin-top: 24px;">πŸ“₯ Export Results</h3>
695
- """)
696
-
697
- with gr.Row():
698
- filename = gr.Textbox(
699
- label="Filename",
700
- value="papers_results",
701
- placeholder="Enter base filename without extension"
702
- )
703
- format_type = gr.Dropdown(
704
- label="Format",
705
- choices=["TXT", "CSV", "Excel", "BibTeX"],
706
- value="TXT"
707
- )
708
-
709
- export_btn = gr.Button("πŸ“₯ Download Results", variant="secondary")
710
 
711
- export_status = gr.Markdown("")
712
- download_file = gr.File(visible=False)
 
713
 
 
714
  searcher = PaperSearchPro()
715
 
716
  def search_wrapper(q, k, a, m, yf, yt, oa, sb, so):
@@ -718,8 +1201,7 @@ def create_interface():
718
  df, papers, total, avg, yr = searcher.search_papers(q, k, a, m, yf, yt, oa, sb, so)
719
  return df, papers, f"**{total}**", f"**{avg:.2f}**", f"**{yr}**"
720
  except Exception as e:
721
- # Return empty results with error message in status
722
- empty_df = pd.DataFrame(columns=['Title', 'Authors', 'Year', 'Citations', 'Journal', 'Abstract', 'BibTeX', 'Relevance', 'Matched Keywords'])
723
  return empty_df, [], "**0**", "**0.0**", "**N/A**"
724
 
725
  def specific_search_wrapper(search_type, search_value):
@@ -728,7 +1210,6 @@ def create_interface():
728
  if not papers:
729
  return df, papers, summary, "**0**", "**0.0**", "**N/A**"
730
 
731
- # Calculate metrics for display
732
  total = len(papers)
733
  avg_rel = 0
734
  years = [p["Year"] for p in papers if p["Year"] != "N/A"]
@@ -736,10 +1217,28 @@ def create_interface():
736
 
737
  return df, papers, summary, f"**{total}**", f"**{avg_rel:.2f}**", f"**{year_range}**"
738
  except Exception as e:
739
- empty_df = pd.DataFrame(columns=['Title', 'Authors', 'Year', 'Citations', 'Journal', 'Abstract', 'BibTeX'])
740
  return empty_df, [], f"❌ Error: {str(e)}", "**0**", "**0.0**", "**N/A**"
741
 
742
- # Connect search buttons
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743
  search_btn.click(
744
  search_wrapper,
745
  inputs=[query, keywords, authors, max_papers, year_from, year_to, open_access, sort_by, sort_order],
@@ -752,6 +1251,12 @@ def create_interface():
752
  outputs=[results, state, specific_summary, total_display, avg_display, year_display]
753
  )
754
 
 
 
 
 
 
 
755
  def export_results(papers, fname, fmt):
756
 
757
  if not papers:
@@ -760,7 +1265,6 @@ def create_interface():
760
  df = pd.DataFrame(papers)
761
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
762
 
763
- # Remove All Authors column from export if it exists
764
  if 'All Authors' in df.columns:
765
  df = df.drop(columns=['All Authors'])
766
 
@@ -794,6 +1298,8 @@ def create_interface():
794
  for col in df.columns:
795
  if col == "BibTeX":
796
  f.write(f"\n{col}:\n{row[col]}\n")
 
 
797
  else:
798
  f.write(f"{col}: {row[col]}\n")
799
  f.write("\n" + "="*80 + "\n\n")
@@ -806,6 +1312,30 @@ def create_interface():
806
  outputs=[download_file, export_status, download_file]
807
  )
808
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
809
  return demo
810
 
811
 
@@ -814,11 +1344,19 @@ def create_interface():
814
  # ============================================
815
 
816
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
817
  demo = create_interface()
818
  demo.launch(
819
  inbrowser=True,
820
  height=1000,
821
  server_name="0.0.0.0", # Makes it accessible on network
822
- share=False # Set to True for temporary public link
823
- )
824
-
 
 
 
 
 
 
1
  import requests
2
  import pandas as pd
3
  import time
4
  from datetime import datetime
5
+ import gradio as gr
6
  import os
7
+ import PyPDF2
8
+ import re
9
+ import io
10
 
11
  # ============================================
12
  # CLEAN RESPONSIVE CSS - UPDATED WITH DARKER GRAY BACKGROUND
 
27
  /* ================================================= */
28
 
29
  body, .gradio-container {
30
+ font-family: 'Inter', sans_serif !important;
31
  background-color: #e5e7eb !important;
32
  color: var(--text-main) !important;
33
  }
 
139
  /* ========================================= */
140
 
141
  /* All buttons */
142
+ button,
143
  .gr-button {
144
+ color: #ffffff !important;
145
  }
146
 
147
  /* Primary button */
148
  button.variant-primary {
149
+ background-color: #2563eb !important;
150
+ color: #ffffff !important;
151
  }
152
 
153
  /* Secondary button */
154
  button.variant-secondary {
155
+ background-color: #6b7280 !important;
156
+ color: #ffffff !important;
157
  }
158
 
159
  /* Keep text white even on hover */
 
166
 
167
  .metric-label {
168
  display: inline-block !important;
169
+ background-color: #111827 !important;
170
+ color: #ffffff !important;
171
  padding: 6px 12px !important;
172
  border-radius: 6px !important;
173
  font-weight: 600 !important;
 
181
 
182
  .metric-value {
183
  display: inline-block !important;
184
+ background-color: #111827 !important;
185
+ color: #ffffff !important;
186
  padding: 6px 12px !important;
187
  border-radius: 6px !important;
188
  font-weight: 700 !important;
 
193
  background: transparent !important;
194
  color: #ffffff !important;
195
  }
196
+
197
+ /* ================================================= */
198
+ /* DROPDOWN POPUP PAGE - WHITE BACKGROUND */
199
+ /* ================================================= */
200
+
201
+ /* The popup menu that appears when clicking dropdown */
202
+ .gr-dropdown-list,
203
+ .dropdown-list,
204
+ div[role="listbox"],
205
+ .options-container,
206
+ select option,
207
+ .gr-dropdown option,
208
+ .gradio-dropdown option,
209
+ div.gr-box select option {
210
+ background-color: #ffffff !important; /* Pure white background */
211
+ color: #111827 !important; /* Dark text */
212
+ }
213
+
214
+ /* Individual options */
215
+ select option,
216
+ .gr-dropdown option,
217
+ .gradio-dropdown option {
218
+ background-color: #ffffff !important;
219
+ color: #111827 !important;
220
+ padding: 8px 12px !important;
221
+ }
222
+
223
+ /* Hover effect */
224
+ select option:hover,
225
+ .gr-dropdown option:hover,
226
+ .gradio-dropdown option:hover {
227
+ background-color: #f3f4f6 !important; /* Light gray on hover */
228
+ color: #111827 !important;
229
+ }
230
+
231
+ /* Selected option */
232
+ select option:checked,
233
+ .gr-dropdown option:checked,
234
+ .gradio-dropdown option:checked {
235
+ background-color: #2563eb !important;
236
+ color: white !important;
237
+ }
238
+
239
+ /* ================================================= */
240
+ /* PDF LINK STYLING */
241
+ /* ================================================= */
242
+
243
+ .pdf-link {
244
+ color: #2563eb !important;
245
+ text-decoration: none !important;
246
+ font-weight: 500 !important;
247
+ }
248
+
249
+ .pdf-link:hover {
250
+ text-decoration: underline !important;
251
+ color: #1d4ed8 !important;
252
+ }
253
+
254
+ .no-pdf {
255
+ color: #6b7280 !important;
256
+ font-style: italic !important;
257
+ }
258
+
259
+ /* ================================================= */
260
+ /* REFERENCE CHECKER TABLE STYLING */
261
+ /* ================================================= */
262
+
263
+ .ref-valid {
264
+ color: #10b981 !important;
265
+ font-weight: 600 !important;
266
+ }
267
+
268
+ .ref-invalid {
269
+ color: #ef4444 !important;
270
+ font-weight: 600 !important;
271
+ }
272
+
273
+ .ref-partial {
274
+ color: #f59e0b !important;
275
+ font-weight: 600 !important;
276
+ }
277
+
278
+ .comparison-table {
279
+ border-collapse: collapse !important;
280
+ width: 100% !important;
281
+ }
282
+
283
+ .comparison-table th {
284
+ background-color: #2563eb !important;
285
+ color: white !important;
286
+ padding: 10px !important;
287
+ text-align: left !important;
288
+ }
289
+
290
+ .comparison-table td {
291
+ padding: 8px !important;
292
+ border-bottom: 1px solid #e5e7eb !important;
293
+ vertical-align: top !important;
294
+ }
295
+
296
+ .comparison-table tr:hover {
297
+ background-color: #f9fafb !important;
298
+ }
299
+
300
+ .original-ref {
301
+ background-color: #fee2e2 !important;
302
+ padding: 4px 8px !important;
303
+ border-radius: 4px !important;
304
+ border-left: 3px solid #ef4444 !important;
305
+ }
306
+
307
+ .corrected-ref {
308
+ background-color: #dcfce7 !important;
309
+ padding: 4px 8px !important;
310
+ border-radius: 4px !important;
311
+ border-left: 3px solid #10b981 !important;
312
+ }
313
  """
314
  # ============================================
315
  # SEARCH ENGINE
 
386
  break
387
 
388
  # ===============================
389
+ # IMPROVED HIERARCHICAL KEYWORD FILTERING
390
+ # Now supports partial word matching like Google
391
  # ===============================
392
 
393
+ keyword_phrases = [k.strip() for k in keywords.split(",") if k.strip()]
394
 
395
+ if len(keyword_phrases) >= 2:
396
  filtered = []
397
 
398
+ # Pre-process keyword phrases into words for partial matching
399
+ # For each phrase, get all individual words (split by spaces)
400
+ keyword_words = []
401
+ for phrase in keyword_phrases:
402
+ # Split phrase into individual words, filter out common stop words and short words
403
+ words = [w.lower() for w in phrase.split() if len(w) > 2] # Only words longer than 2 chars
404
+ if not words: # If phrase was a single short word, use the whole phrase
405
+ words = [phrase.lower()]
406
+ keyword_words.append(words)
407
+
408
  for p in all_papers:
409
  combined = f"{p['Title']} {p['Abstract']} {p['Authors']} {p['All Authors']}".lower()
410
 
411
+ # Check first keyword phrase (ANY word from it must match)
412
+ first_phrase_matched = False
413
+ for word in keyword_words[0]:
414
+ if word in combined:
415
+ first_phrase_matched = True
416
+ break
417
+
418
+ # Check second keyword phrase (ANY word from it must match)
419
+ second_phrase_matched = False
420
+ for word in keyword_words[1]:
421
+ if word in combined:
422
+ second_phrase_matched = True
423
+ break
424
+
425
+ # First 2 keyword phrases are REQUIRED (at least one word from each must match)
426
+ if not first_phrase_matched or not second_phrase_matched:
427
  continue
428
 
429
+ # Calculate score and track matched words
430
+ score = 2 # Base score for first two phrases
431
+ matched_phrases = [keyword_phrases[0], keyword_phrases[1]]
432
+ matched_words = []
433
+
434
+ # Add the specific words that matched from first two phrases
435
+ for word in keyword_words[0]:
436
+ if word in combined:
437
+ matched_words.append(word)
438
+ break # Just take one representative word
439
+ for word in keyword_words[1]:
440
+ if word in combined:
441
+ matched_words.append(word)
442
+ break
443
 
444
+ # Check additional keyword phrases
445
+ for i, phrase_words in enumerate(keyword_words[2:], start=2):
446
+ phrase_matched = False
447
+ for word in phrase_words:
448
+ if word in combined:
449
+ phrase_matched = True
450
+ matched_words.append(word)
451
+ break
452
+
453
+ if phrase_matched:
454
  score += 1
455
+ matched_phrases.append(keyword_phrases[i])
456
+
457
+ # Remove duplicates from matched words while preserving order
458
+ seen = set()
459
+ unique_matched_words = []
460
+ for word in matched_words:
461
+ if word not in seen:
462
+ seen.add(word)
463
+ unique_matched_words.append(word)
464
 
465
  p["Relevance"] = score
466
+ p["Matched Keywords"] = f"Phrases: {', '.join(matched_phrases)} | Matched words: {', '.join(unique_matched_words)}"
467
 
468
  filtered.append(p)
469
 
 
485
  matched_authors = []
486
 
487
  for author in author_list:
488
+ # Split author name into parts for partial matching
489
+ author_parts = author.split()
490
+ author_matched = False
491
+
492
+ # Check if any part of the author name appears
493
+ for part in author_parts:
494
+ if len(part) > 2 and part in all_authors_lower: # Only check significant parts
495
+ author_matched = True
496
+ matched_authors.append(part)
497
+ break
498
+
499
+ if not author_matched:
500
+ # Fallback: check if the whole author string appears
501
+ if author in all_authors_lower:
502
+ author_matched = True
503
+ matched_authors.append(author)
504
+ else:
505
+ match_all = False
506
+ break
507
 
508
  if match_all:
509
  p["Relevance"] = len(matched_authors)
 
520
  df = pd.DataFrame(all_papers)
521
 
522
  # Reorder columns to include BibTeX and remove All Authors from display
523
+ column_order = ['Title', 'Authors', 'Year', 'Citations', 'Journal', 'PDF_URL', 'Abstract',
524
  'BibTeX', 'Relevance', 'Matched Keywords']
525
  df = df[column_order]
526
 
 
593
  p['Rank'] = i + 1
594
 
595
  df = pd.DataFrame(all_papers)
596
+ column_order = ['Title', 'Authors', 'Year', 'Citations', 'Journal', 'PDF_URL', 'Abstract', 'BibTeX']
597
  # Only include columns that exist
598
  available_cols = [col for col in column_order if col in df.columns]
599
  df = df[available_cols]
 
644
  if doi:
645
  doi = doi.replace("https://doi.org/", "")
646
 
647
+ # Get PDF URL if available
648
+ pdf_url = ""
649
+ if work.get("open_access", {}).get("oa_url"):
650
+ pdf_url = work["open_access"]["oa_url"]
651
+ elif work.get("primary_location", {}).get("pdf_url"):
652
+ pdf_url = work["primary_location"]["pdf_url"]
653
+ else:
654
+ pdf_url = "No free PDF available"
655
+
656
  # Generate BibTeX entry
657
  bibtex = self.generate_bibtex(work, all_authors)
658
 
 
664
  "Citations": work.get("cited_by_count", 0),
665
  "Journal": (work.get("primary_location", {}).get("source") or {}).get("display_name", "Unknown"),
666
  "DOI": doi,
667
+ "PDF_URL": pdf_url,
668
  "Abstract": abstract,
669
  "BibTeX": bibtex,
670
  "Relevance": 0,
 
748
 
749
  return "\n".join(bibtex_lines)
750
 
751
+ # ============================================
752
+ # NEW: REFERENCE CHECKER FEATURE
753
+ # ============================================
754
+
755
+ def extract_references_from_pdf(self, pdf_file):
756
+ """Extract reference strings from PDF file"""
757
+ references = []
758
+
759
+ try:
760
+ # Read PDF file
761
+ pdf_reader = PyPDF2.PdfReader(pdf_file)
762
+ full_text = ""
763
+
764
+ # Extract text from all pages
765
+ for page in pdf_reader.pages:
766
+ full_text += page.extract_text() + "\n"
767
+
768
+ # Look for references section (common patterns)
769
+ ref_patterns = [
770
+ r'References\s*\n(.*?)(?=\n\s*\n|\Z)',
771
+ r'REFERENCES\s*\n(.*?)(?=\n\s*\n|\Z)',
772
+ r'Bibliography\s*\n(.*?)(?=\n\s*\n|\Z)',
773
+ r'BIBLIOGRAPHY\s*\n(.*?)(?=\n\s*\n|\Z)'
774
+ ]
775
+
776
+ ref_text = ""
777
+ for pattern in ref_patterns:
778
+ match = re.search(pattern, full_text, re.DOTALL | re.IGNORECASE)
779
+ if match:
780
+ ref_text = match.group(1)
781
+ break
782
+
783
+ if not ref_text:
784
+ # If no clear references section, take last part of document
785
+ ref_text = full_text[-5000:] # Last 5000 chars
786
+
787
+ # Split into individual references (numbered or bulleted)
788
+ ref_lines = re.split(r'\n\s*\d+\.|\n\s*\[?\d+\]?\.?|\nβ€’', ref_text)
789
+
790
+ for ref in ref_lines:
791
+ ref = ref.strip()
792
+ if len(ref) > 30 and any(c.isalpha() for c in ref): # Valid reference
793
+ references.append(ref)
794
+
795
+ return references[:50] # Limit to 50 references
796
+
797
+ except Exception as e:
798
+ print(f"Error extracting PDF: {e}")
799
+ return []
800
+
801
+ def search_reference(self, ref_text):
802
+ """Search for a reference in OpenAlex and return corrected version"""
803
+
804
+ # Extract potential DOI from reference
805
+ doi_match = re.search(r'10\.\d{4,9}/[-._;()/:A-Z0-9]+', ref_text, re.IGNORECASE)
806
+
807
+ if doi_match:
808
+ # If DOI found, search by DOI
809
+ doi = doi_match.group()
810
+ url = f"https://api.openalex.org/works/doi/{doi}"
811
+ try:
812
+ response = requests.get(url, timeout=10)
813
+ if response.status_code == 200:
814
+ work = response.json()
815
+ corrected = self.extract_info(work)
816
+ return {
817
+ 'original': ref_text,
818
+ 'corrected': corrected,
819
+ 'status': 'valid',
820
+ 'confidence': 1.0,
821
+ 'method': 'DOI match'
822
+ }
823
+ except: # Do not print or raise exception here; fallback to title search
824
+ pass
825
+
826
+ # Extract potential title (first sentence or up to 100 chars)
827
+ title_guess = ref_text.split('.')[0][:100]
828
+
829
+ # Search by title
830
+ params = {
831
+ 'search': title_guess,
832
+ 'per-page': 5,
833
+ 'sort': 'relevance_score:desc'
834
+ }
835
+
836
+ try:
837
+ response = requests.get(self.base_url, params=params, timeout=10)
838
+ data = response.json()
839
+ results = data.get('results', [])
840
+
841
+ if results:
842
+ best_match = results[0]
843
+ confidence = 0.5 # Base confidence
844
+
845
+ # Check title similarity
846
+ found_title = best_match.get('title', '').lower()
847
+ if title_guess.lower() in found_title or found_title in title_guess.lower():
848
+ confidence = 0.8
849
+
850
+ corrected = self.extract_info(best_match)
851
+
852
+ # Check year if available
853
+ year_match = re.search(r'[12][0-9]{3}', ref_text)
854
+ if year_match:
855
+ ref_year = int(year_match.group())
856
+ if corrected['Year'] == ref_year:
857
+ confidence = min(confidence + 0.2, 1.0) # Increase confidence
858
+
859
+ status = 'valid' if confidence > 0.7 else 'partial'
860
+
861
+ return {
862
+ 'original': ref_text,
863
+ 'corrected': corrected,
864
+ 'status': status,
865
+ 'confidence': confidence,
866
+ 'method': 'title search'
867
+ }
868
+ except: # Do not print or raise exception here
869
+ pass
870
+
871
+ return {
872
+ 'original': ref_text,
873
+ 'corrected': None,
874
+ 'status': 'not_found',
875
+ 'confidence': 0,
876
+ 'method': 'none'
877
+ }
878
+
879
+ def check_references(self, pdf_file):
880
+ """Main function to check references in PDF"""
881
+
882
+ # Extract references
883
+ references = self.extract_references_from_pdf(pdf_file)
884
+
885
+ if not references:
886
+ return None, "❌ No references found in PDF"
887
+
888
+ # Check each reference
889
+ results = []
890
+ valid_count = 0
891
+ partial_count = 0
892
+ invalid_count = 0
893
+
894
+ for i, ref in enumerate(references):
895
+ result = self.search_reference(ref)
896
+ results.append(result)
897
+
898
+ if result['status'] == 'valid':
899
+ valid_count += 1
900
+ elif result['status'] == 'partial':
901
+ partial_count += 1
902
+ else:
903
+ invalid_count += 1
904
+
905
+ # Small delay to avoid rate limiting
906
+ time.sleep(0.2)
907
+
908
+ # Create comparison HTML
909
+ html_output = f"""
910
+ <div style="margin-bottom: 20px; padding: 15px; background-color: #f3f4f6; border-radius: 8px;">
911
+ <h3 style="color: #2563eb; margin-bottom: 10px;">πŸ“Š Reference Check Summary</h3>
912
+ <p><span style="color: #10b981; font-weight: 600;">βœ… Valid: {valid_count}</span> |
913
+ <span style="color: #f59e0b; font-weight: 600;">⚠️ Partial: {partial_count}</span> |
914
+ <span style="color: #ef4444; font-weight: 600;">❌ Not Found: {invalid_count}</span></p>
915
+ <p>Total references checked: {len(references)}</p>
916
+ </div>
917
+
918
+ <table class="comparison-table">
919
+ <tr>
920
+ <th>#</th>
921
+ <th>Original Reference (from PDF)</th>
922
+ <th>Corrected/Found Reference</th>
923
+ <th>Status</th>
924
+ </tr>
925
+ """
926
+
927
+ for i, result in enumerate(results):
928
+ status_class = {
929
+ 'valid': 'ref-valid',
930
+ 'partial': 'ref-partial',
931
+ 'not_found': 'ref-invalid'
932
+ }.get(result['status'], '')
933
+
934
+ status_text = {
935
+ 'valid': 'βœ… VALID',
936
+ 'partial': '⚠️ PARTIAL',
937
+ 'not_found': '❌ NOT FOUND'
938
+ }.get(result['status'], '')
939
+
940
+ # Original reference (truncated for display)
941
+ orig_display = result['original'][:200] + "..." if len(result['original']) > 200 else result['original']
942
+
943
+ # Corrected reference display
944
+ if result['corrected']:
945
+ corr = result['corrected']
946
+ # Create a clickable link for the PDF URL
947
+ pdf_link_html = ""
948
+ if corr.get('PDF_URL') and corr['PDF_URL'] != "No free PDF available":
949
+ pdf_link_html = f"<a href='{corr['PDF_URL']}' target='_blank' class='pdf-link'>[PDF]</a>"
950
+ else:
951
+ pdf_link_html = f"<span class='no-pdf'>[No PDF]</span>"
952
+
953
+ corrected_display = f"""
954
+ <div class="corrected-ref">
955
+ <strong>{corr['Title']}</strong><br>
956
+ <em>{corr['Authors']}</em><br>
957
+ {corr['Journal']}, {corr['Year']}<br>
958
+ DOI: {corr.get('DOI', 'N/A')} {pdf_link_html}<br>
959
+ <small>Found by: {result['method']} (confidence: {result['confidence']:.1%})</small>
960
+ </div>
961
+ """
962
+ else:
963
+ corrected_display = '<em>No match found</em>'
964
+
965
+ html_output += f"""
966
+ <tr>
967
+ <td>{i+1}</td>
968
+ <td><div class="original-ref">{orig_display}</div></td>
969
+ <td>{corrected_display}</td>
970
+ <td class="{status_class}">{status_text}</td>
971
+ </tr>
972
+ """
973
+
974
+ html_output += "</table>"
975
+
976
+ # Create downloadable CSV with comparison
977
+ comparison_data = []
978
+ for result in results:
979
+ if result['corrected']:
980
+ corr = result['corrected']
981
+ comparison_data.append({
982
+ 'Reference_#': len(comparison_data) + 1,
983
+ 'Original_Reference': result['original'],
984
+ 'Status': result['status'],
985
+ 'Confidence': result['confidence'],
986
+ 'Found_By': result['method'],
987
+ 'Corrected_Title': corr['Title'],
988
+ 'Corrected_Authors': corr['Authors'],
989
+ 'Corrected_Year': corr['Year'],
990
+ 'Corrected_Journal': corr['Journal'],
991
+ 'Corrected_DOI': corr.get('DOI', ''),
992
+ 'PDF_URL': corr.get('PDF_URL', '')
993
+ })
994
+ else:
995
+ comparison_data.append({
996
+ 'Reference_#': len(comparison_data) + 1,
997
+ 'Original_Reference': result['original'],
998
+ 'Status': result['status'],
999
+ 'Confidence': result['confidence'],
1000
+ 'Found_By': result['method'],
1001
+ 'Corrected_Title': 'NOT FOUND',
1002
+ 'Corrected_Authors': '',
1003
+ 'Corrected_Year': '',
1004
+ 'Corrected_Journal': '',
1005
+ 'Corrected_DOI': '',
1006
+ 'PDF_URL': ''
1007
+ })
1008
+
1009
+ df = pd.DataFrame(comparison_data)
1010
+
1011
+ return df, html_output
1012
+
1013
 
1014
  # ============================================
1015
  # INTERFACE
 
1017
 
1018
  def create_interface():
1019
 
1020
+ # Define the theme here to pass to launch later
1021
+ default_theme = gr.themes.Default(
 
 
1022
  primary_hue="blue",
1023
  neutral_hue="gray"
1024
+ )
1025
+
1026
+ with gr.Blocks(title="PaperSearchPro", css=custom_css, theme=default_theme) as demo:
1027
 
1028
  gr.HTML("""
1029
+ <div style='text-align:center; padding:3rem 0'>
1030
+ <h1><span>πŸ“±XYZπŸ“±PaperInfo</span></h1>
1031
+ <p class='subtitle-text'>Easy Academic Paper/journal details by Paul</p>
1032
  </div>
1033
  """)
1034
 
1035
  # Create tabs for different search modes
1036
+ with gr.Tabs(elem_classes="tab-nav") as tabs_component: # Assign to a variable
1037
  # Tab 1: General Search
1038
  with gr.TabItem("πŸ” General Search", id=0):
1039
  with gr.Column(elem_classes="white-card"):
 
1059
  placeholder="e.g., Smith, Zhang, Wang (comma-separated)"
1060
  )
1061
 
1062
+ # ==========================
1063
  # MAX PAPERS SLIDER WITH BLACK REGION COMMENT
1064
  # ==========================
1065
+ max_papers = gr.Slider(1000, 5000000, value=10000, step=1000, label="Max Papers")
1066
 
1067
  # Add black region comment below slider
1068
  gr.HTML("""
 
1076
  year_to = gr.Number(value=2026, label="Year To", precision=0)
1077
  open_access = gr.Checkbox(label="Open Access Only")
1078
 
1079
+ # ==========================
1080
  # SORTING OPTIONS
1081
  # ==========================
1082
  with gr.Row():
 
1112
 
1113
  specific_search_value = gr.Textbox(
1114
  label="Enter value",
1115
+ placeholder="e.10.1038/nature12373 or exact paper title or author name",
1116
  scale=2
1117
  )
1118
 
1119
  specific_search_btn = gr.Button("πŸ” FIND PAPER", variant="primary")
1120
  specific_summary = gr.Markdown("Ready")
1121
 
1122
+ # Tab 3: NEW - Reference Checker
1123
+ with gr.TabItem("βœ… Check References", id=2):
1124
+ with gr.Column(elem_classes="white-card"):
1125
+ gr.Markdown("""
1126
+ ### πŸ“‹ Upload a PDF to check its references
1127
+
1128
+ This tool will:
1129
+ 1. Extract all references from your PDF
1130
+ 2. Check each reference against the OpenAlex database
1131
+ 3. Show you which references are correct and which need fixing
1132
+ 4. Provide corrected versions when available
1133
+ 5. Generate a comparison file you can download
1134
+ """)
1135
+
1136
+ pdf_file = gr.File(
1137
+ label="Upload PDF File",
1138
+ file_types=[".pdf"],
1139
+ type="filepath"
1140
+ )
1141
+
1142
+ check_btn = gr.Button("πŸ” CHECK REFERENCES", variant="primary", size="lg")
1143
+
1144
+ ref_summary = gr.Markdown("Ready to check references...")
1145
+
1146
+ ref_results = gr.HTML(label="Reference Comparison")
1147
+
1148
+ ref_download = gr.File(label="Download Comparison CSV")
1149
+
1150
+ # Metrics section (common for first two tabs)
1151
+ with gr.Row(visible=True) as metrics_row:
1152
  total_display = gr.Markdown("**0**", elem_classes="metric-value")
1153
  avg_display = gr.Markdown("**0.0**", elem_classes="metric-value")
1154
  year_display = gr.Markdown("**N/A**", elem_classes="metric-value")
1155
 
1156
  # Add labels for metrics
1157
+ with gr.Row(visible=True) as metrics_labels_row:
1158
  gr.Markdown("**Total Papers**", elem_classes="metric-label")
1159
  gr.Markdown("**Avg Relevance**", elem_classes="metric-label")
1160
  gr.Markdown("**Year Range**", elem_classes="metric-label")
1161
 
1162
+ # Results section (common for first two tabs)
1163
  results = gr.Dataframe(
1164
  label="Results",
1165
  row_count=15,
1166
+ column_widths=["25%", "15%", "5%", "5%", "10%", "15%", "15%", "5%", "5%"],
1167
+ wrap=True,
1168
+ visible=True
1169
  )
1170
  state = gr.State([])
1171
 
1172
+ # ==========================
1173
+ # EXPORT SECTION (for first two tabs)
1174
  # ==========================
1175
+ with gr.Column(visible=True) as export_section:
1176
+ gr.HTML("""
1177
+ <h3 style="color: #2563eb !important; font-weight: 600; margin-bottom: 16px; margin-top: 24px;">πŸ“₯ Export Results</h3>
1178
+ """)
1179
+
1180
+ with gr.Row():
1181
+ filename = gr.Textbox(
1182
+ label="Filename",
1183
+ value="papers_results",
1184
+ placeholder="Enter base filename without extension"
1185
+ )
1186
+ format_type = gr.Dropdown(
1187
+ label="Format",
1188
+ choices=["TXT", "CSV", "Excel", "BibTeX"],
1189
+ value="TXT"
1190
+ )
 
 
 
 
1191
 
1192
+ export_btn = gr.Button("πŸ“₯ Download Results", variant="secondary")
1193
+ export_status = gr.Markdown("")
1194
+ download_file = gr.File(visible=False)
1195
 
1196
+ # Move searcher instantiation and click bindings inside the Blocks context
1197
  searcher = PaperSearchPro()
1198
 
1199
  def search_wrapper(q, k, a, m, yf, yt, oa, sb, so):
 
1201
  df, papers, total, avg, yr = searcher.search_papers(q, k, a, m, yf, yt, oa, sb, so)
1202
  return df, papers, f"**{total}**", f"**{avg:.2f}**", f"**{yr}**"
1203
  except Exception as e:
1204
+ empty_df = pd.DataFrame(columns=['Title', 'Authors', 'Year', 'Citations', 'Journal', 'PDF_URL', 'Abstract', 'BibTeX', 'Relevance', 'Matched Keywords'])
 
1205
  return empty_df, [], "**0**", "**0.0**", "**N/A**"
1206
 
1207
  def specific_search_wrapper(search_type, search_value):
 
1210
  if not papers:
1211
  return df, papers, summary, "**0**", "**0.0**", "**N/A**"
1212
 
 
1213
  total = len(papers)
1214
  avg_rel = 0
1215
  years = [p["Year"] for p in papers if p["Year"] != "N/A"]
 
1217
 
1218
  return df, papers, summary, f"**{total}**", f"**{avg_rel:.2f}**", f"**{year_range}**"
1219
  except Exception as e:
1220
+ empty_df = pd.DataFrame(columns=['Title', 'Authors', 'Year', 'Citations', 'Journal', 'PDF_URL', 'Abstract', 'BibTeX'])
1221
  return empty_df, [], f"❌ Error: {str(e)}", "**0**", "**0.0**", "**N/A**"
1222
 
1223
+ def check_references_wrapper(pdf_file):
1224
+ if pdf_file is None:
1225
+ return "", "❌ Please upload a PDF file", None
1226
+
1227
+ try:
1228
+ # Pass the temporary file path directly to check_references
1229
+ df, html_output = searcher.check_references(pdf_file.name)
1230
+ if df is None:
1231
+ return "", html_output, None
1232
+
1233
+ # Save CSV for download
1234
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1235
+ csv_path = f"reference_check_{timestamp}.csv"
1236
+ df.to_csv(csv_path, index=False)
1237
+
1238
+ return csv_path, html_output, csv_path
1239
+ except Exception as e:
1240
+ return "", f"❌ Error: {str(e)}", None
1241
+
1242
  search_btn.click(
1243
  search_wrapper,
1244
  inputs=[query, keywords, authors, max_papers, year_from, year_to, open_access, sort_by, sort_order],
 
1251
  outputs=[results, state, specific_summary, total_display, avg_display, year_display]
1252
  )
1253
 
1254
+ check_btn.click(
1255
+ check_references_wrapper,
1256
+ inputs=[pdf_file],
1257
+ outputs=[ref_download, ref_results, ref_download]
1258
+ )
1259
+
1260
  def export_results(papers, fname, fmt):
1261
 
1262
  if not papers:
 
1265
  df = pd.DataFrame(papers)
1266
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1267
 
 
1268
  if 'All Authors' in df.columns:
1269
  df = df.drop(columns=['All Authors'])
1270
 
 
1298
  for col in df.columns:
1299
  if col == "BibTeX":
1300
  f.write(f"\n{col}:\n{row[col]}\n")
1301
+ elif col == "PDF_URL":
1302
+ f.write(f"{col}: {row[col]}\n")
1303
  else:
1304
  f.write(f"{col}: {row[col]}\n")
1305
  f.write("\n" + "="*80 + "\n\n")
 
1312
  outputs=[download_file, export_status, download_file]
1313
  )
1314
 
1315
+ # Show/hide elements based on active tab
1316
+ def on_tab_select(evt: gr.SelectData):
1317
+ if evt.value == "βœ… Check References":
1318
+ return {
1319
+ metrics_row: gr.update(visible=False),
1320
+ metrics_labels_row: gr.update(visible=False),
1321
+ results: gr.update(visible=False),
1322
+ export_section: gr.update(visible=False)
1323
+ }
1324
+ else:
1325
+ return {
1326
+ metrics_row: gr.update(visible=True),
1327
+ metrics_labels_row: gr.update(visible=True),
1328
+ results: gr.update(visible=True),
1329
+ export_section: gr.update(visible=True)
1330
+ }
1331
+
1332
+ tabs_component.select(
1333
+ on_tab_select,
1334
+ inputs=None,
1335
+ outputs=[metrics_row, metrics_labels_row, results, export_section],
1336
+ queue=False
1337
+ )
1338
+
1339
  return demo
1340
 
1341
 
 
1344
  # ============================================
1345
 
1346
  if __name__ == "__main__":
1347
+ # Install required package if not present
1348
+ # The PyPDF2 import at the top of the file causes a ModuleNotFoundError if not installed.
1349
+ # Moving the installation check to a separate cell is generally better for Colab,
1350
+ # or placing it before the import statement that causes the error.
1351
+ # For now, I'm assuming the user wants to keep the import at the top and will install PyPDF2 externally.
1352
+ # If the user wishes to install it programmatically within the notebook,
1353
+ # the !pip install command should be in a separate executable cell before this one.
1354
+
1355
+ # Unpack the returned values from create_interface
1356
  demo = create_interface()
1357
  demo.launch(
1358
  inbrowser=True,
1359
  height=1000,
1360
  server_name="0.0.0.0", # Makes it accessible on network
1361
+ share=False
1362
+ )