Subahdip627 commited on
Commit
0971cdc
Β·
verified Β·
1 Parent(s): bcc519d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +248 -65
app.py CHANGED
@@ -1,15 +1,3 @@
1
- """
2
- PaperSearchPro - FULL Professional Version
3
- Hierarchical Keyword Search + Export + Responsive UI + BibTeX Support + Author Filter
4
- """
5
-
6
- import requests
7
- import pandas as pd
8
- import time
9
- from datetime import datetime
10
- import gradio as gr
11
- import os
12
-
13
  # ============================================
14
  # CLEAN RESPONSIVE CSS - UPDATED WITH DARKER GRAY BACKGROUND
15
  # ============================================
@@ -84,6 +72,61 @@ div:has(.metric-value) strong {
84
  border-left: 4px solid var(--primary) !important;
85
  font-weight: 500 !important;
86
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  """
88
 
89
  # ============================================
@@ -233,6 +276,83 @@ class PaperSearchPro:
233
  df = df[column_order]
234
 
235
  return df, all_papers, total, avg_rel, year_range
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
  def extract_info(self, work):
238
  # Rebuild abstract
@@ -270,6 +390,11 @@ class PaperSearchPro:
270
  # Show ALL authors, no truncation
271
  authors_str = ", ".join(all_authors)
272
 
 
 
 
 
 
273
  # Generate BibTeX entry
274
  bibtex = self.generate_bibtex(work, all_authors)
275
 
@@ -280,6 +405,7 @@ class PaperSearchPro:
280
  "Year": work.get("publication_year", "N/A"),
281
  "Citations": work.get("cited_by_count", 0),
282
  "Journal": (work.get("primary_location", {}).get("source") or {}).get("display_name", "Unknown"),
 
283
  "Abstract": abstract,
284
  "BibTeX": bibtex,
285
  "Relevance": 0,
@@ -379,63 +505,94 @@ def create_interface():
379
  </div>
380
  """)
381
 
382
- with gr.Column(elem_classes="white-card"):
 
 
 
 
383
 
384
- query = gr.Textbox(
385
- label="Search Topic",
386
- value="photoacoustic imaging",
387
- placeholder="Enter research topic or keywords..."
388
- )
389
-
390
- with gr.Row():
391
- with gr.Column():
392
- keywords = gr.Textbox(
393
- label="Required Keywords (first 2 REQUIRED for hierarchical search)",
394
- value="blood, photoacoustics, imaging",
395
- placeholder="e.g., blood, photoacoustics, imaging (comma-separated)"
396
- )
397
-
398
- with gr.Column():
399
- authors = gr.Textbox(
400
- label="Filter by Authors (optional)",
401
- value="",
402
- placeholder="e.g., Smith, Zhang, Wang (comma-separated)"
403
  )
404
 
405
- # ==========================
406
- # MAX PAPERS SLIDER WITH BLACK REGION COMMENT
407
- # ==========================
408
- max_papers = gr.Slider(1000, 50000, value=1000, step=100, label="Max Papers")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
409
 
410
- # Add black region comment below slider
411
- gr.HTML("""
412
- <div class="slider-comment">
413
- ⚑ Tip: Set this number as high as possible or more than 5000 for better scanning of all available papers
414
- </div>
415
- """)
416
-
417
- with gr.Row():
418
- year_from = gr.Number(value=2000, label="Year From", precision=0)
419
- year_to = gr.Number(value=2026, label="Year To", precision=0)
420
- open_access = gr.Checkbox(label="Open Access Only")
421
-
422
- # ==========================
423
- # SORTING OPTIONS
424
- # ==========================
425
- with gr.Row():
426
- sort_by = gr.Dropdown(
427
- label="Sort By",
428
- choices=["Relevance", "Year", "Citations"],
429
- value="Relevance"
430
- )
431
- sort_order = gr.Dropdown(
432
- label="Sort Order",
433
- choices=["Descending", "Ascending"],
434
- value="Descending"
435
- )
436
-
437
- search_btn = gr.Button("πŸ” SEARCH PAPERS", variant="primary", size="lg")
438
-
439
  with gr.Row():
440
  total_display = gr.Markdown("**0**", elem_classes="metric-value")
441
  avg_display = gr.Markdown("**0.0**", elem_classes="metric-value")
@@ -447,7 +604,9 @@ def create_interface():
447
  gr.Markdown("**Avg Relevance**", elem_classes="metric-label")
448
  gr.Markdown("**Year Range**", elem_classes="metric-label")
449
 
 
450
  results = gr.Dataframe(
 
451
  row_count=15,
452
  column_widths=["25%", "15%", "5%", "5%", "10%", "20%", "20%", "5%", "5%"],
453
  wrap=True
@@ -490,11 +649,35 @@ def create_interface():
490
  empty_df = pd.DataFrame(columns=['Title', 'Authors', 'Year', 'Citations', 'Journal', 'Abstract', 'BibTeX', 'Relevance', 'Matched Keywords'])
491
  return empty_df, [], "**0**", "**0.0**", "**N/A**"
492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
  search_btn.click(
494
  search_wrapper,
495
  inputs=[query, keywords, authors, max_papers, year_from, year_to, open_access, sort_by, sort_order],
496
  outputs=[results, state, total_display, avg_display, year_display]
497
  )
 
 
 
 
 
 
498
 
499
  def export_results(papers, fname, fmt):
500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # ============================================
2
  # CLEAN RESPONSIVE CSS - UPDATED WITH DARKER GRAY BACKGROUND
3
  # ============================================
 
72
  border-left: 4px solid var(--primary) !important;
73
  font-weight: 500 !important;
74
  }
75
+
76
+ /* Tab styling */
77
+ .tab-nav {
78
+ background-color: #f3f4f6 !important;
79
+ border-radius: 8px !important;
80
+ padding: 4px !important;
81
+ margin-bottom: 20px !important;
82
+ }
83
+
84
+ .tab-nav button {
85
+ border-radius: 6px !important;
86
+ padding: 8px 16px !important;
87
+ font-weight: 500 !important;
88
+ color: #4b5563 !important;
89
+ }
90
+
91
+ .tab-nav button.selected {
92
+ background-color: var(--primary) !important;
93
+ color: white !important;
94
+ }
95
+
96
+ /* Ensure all text in white cards is properly colored */
97
+ .white-card p, .white-card li, .white-card div:not(.slider-comment) {
98
+ color: #111827 !important;
99
+ }
100
+
101
+ .white-card label {
102
+ color: var(--primary) !important;
103
+ font-weight: 500 !important;
104
+ }
105
+
106
+ /* Button text color - PURE WHITE for all buttons */
107
+ button, .gr-button, .lg.primary, .secondary, .gr-button-primary, .gr-button-secondary {
108
+ color: #ffffff !important; /* Pure white text */
109
+ font-weight: 600 !important;
110
+ }
111
+
112
+ /* Ensure button text stays white on hover/focus */
113
+ button:hover, .gr-button:hover, button:focus, .gr-button:focus {
114
+ color: #ffffff !important;
115
+ }
116
+
117
+ /* Specific button styling if needed */
118
+ button.variant-primary, .gr-button-primary {
119
+ background-color: var(--primary) !important;
120
+ }
121
+
122
+ button.variant-secondary, .gr-button-secondary {
123
+ background-color: #4b5563 !important; /* Gray for secondary button */
124
+ }
125
+
126
+ /* Export button specific */
127
+ button[class*="secondary"], .gr-button-secondary {
128
+ background-color: #6b7280 !important;
129
+ }
130
  """
131
 
132
  # ============================================
 
276
  df = df[column_order]
277
 
278
  return df, all_papers, total, avg_rel, year_range
279
+
280
+ def search_specific_paper(self, search_type, search_value):
281
+ """Search for a specific paper by title, author, or DOI"""
282
+
283
+ all_papers = []
284
+
285
+ if search_type == "DOI":
286
+ # Clean DOI (remove URL if present)
287
+ if "doi.org/" in search_value:
288
+ search_value = search_value.split("doi.org/")[-1]
289
+
290
+ # Direct lookup by DOI
291
+ url = f"https://api.openalex.org/works/doi/{search_value}"
292
+ try:
293
+ response = requests.get(url, timeout=15)
294
+ if response.status_code == 200:
295
+ work = response.json()
296
+ paper = self.extract_info(work)
297
+ all_papers.append(paper)
298
+ except Exception as e:
299
+ print(f"Error fetching DOI: {e}")
300
+
301
+ elif search_type == "Exact Title":
302
+ # Search by exact title
303
+ params = {
304
+ "search": f'"{search_value}"', # Quote for exact match
305
+ "per-page": 10,
306
+ "sort": "relevance_score:desc"
307
+ }
308
+ try:
309
+ response = requests.get(self.base_url, params=params, timeout=15)
310
+ data = response.json()
311
+ results = data.get("results", [])
312
+
313
+ for work in results:
314
+ # Check for close title match
315
+ title = work.get("title", "").lower()
316
+ if search_value.lower() in title or title in search_value.lower():
317
+ paper = self.extract_info(work)
318
+ all_papers.append(paper)
319
+ break # Take the first good match
320
+ except Exception as e:
321
+ print(f"Error searching title: {e}")
322
+
323
+ elif search_type == "Specific Author":
324
+ # Search for papers by a specific author
325
+ params = {
326
+ "search": search_value,
327
+ "filter": "authorships.author.display_name.search:" + search_value,
328
+ "per-page": 50,
329
+ "sort": "cited_by_count:desc"
330
+ }
331
+ try:
332
+ response = requests.get(self.base_url, params=params, timeout=15)
333
+ data = response.json()
334
+ results = data.get("results", [])
335
+
336
+ for work in results[:20]: # Limit to 20 papers
337
+ paper = self.extract_info(work)
338
+ all_papers.append(paper)
339
+ except Exception as e:
340
+ print(f"Error searching author: {e}")
341
+
342
+ if all_papers:
343
+ for i, p in enumerate(all_papers):
344
+ p['Rank'] = i + 1
345
+
346
+ df = pd.DataFrame(all_papers)
347
+ column_order = ['Title', 'Authors', 'Year', 'Citations', 'Journal', 'Abstract', 'BibTeX']
348
+ # Only include columns that exist
349
+ available_cols = [col for col in column_order if col in df.columns]
350
+ df = df[available_cols]
351
+
352
+ summary = f"βœ… Found **{len(all_papers)}** paper(s) matching your query"
353
+ return df, all_papers, summary
354
+
355
+ return pd.DataFrame(), [], "❌ No papers found"
356
 
357
  def extract_info(self, work):
358
  # Rebuild abstract
 
390
  # Show ALL authors, no truncation
391
  authors_str = ", ".join(all_authors)
392
 
393
+ # Get DOI for reference
394
+ doi = work.get("doi", "")
395
+ if doi:
396
+ doi = doi.replace("https://doi.org/", "")
397
+
398
  # Generate BibTeX entry
399
  bibtex = self.generate_bibtex(work, all_authors)
400
 
 
405
  "Year": work.get("publication_year", "N/A"),
406
  "Citations": work.get("cited_by_count", 0),
407
  "Journal": (work.get("primary_location", {}).get("source") or {}).get("display_name", "Unknown"),
408
+ "DOI": doi,
409
  "Abstract": abstract,
410
  "BibTeX": bibtex,
411
  "Relevance": 0,
 
505
  </div>
506
  """)
507
 
508
+ # Create tabs for different search modes
509
+ with gr.Tabs(elem_classes="tab-nav"):
510
+ # Tab 1: General Search
511
+ with gr.TabItem("πŸ” General Search", id=0):
512
+ with gr.Column(elem_classes="white-card"):
513
 
514
+ query = gr.Textbox(
515
+ label="Search Topic",
516
+ value="photoacoustic imaging",
517
+ placeholder="Enter research topic or keywords..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  )
519
 
520
+ with gr.Row():
521
+ with gr.Column():
522
+ keywords = gr.Textbox(
523
+ label="Required Keywords (first 2 REQUIRED for hierarchical search)",
524
+ value="blood, photoacoustics, imaging",
525
+ placeholder="e.g., blood, photoacoustics, imaging (comma-separated)"
526
+ )
527
+
528
+ with gr.Column():
529
+ authors = gr.Textbox(
530
+ label="Filter by Authors (optional)",
531
+ value="",
532
+ placeholder="e.g., Smith, Zhang, Wang (comma-separated)"
533
+ )
534
+
535
+ # ==========================
536
+ # MAX PAPERS SLIDER WITH BLACK REGION COMMENT
537
+ # ==========================
538
+ max_papers = gr.Slider(1000, 50000, value=1000, step=100, label="Max Papers")
539
+
540
+ # Add black region comment below slider
541
+ gr.HTML("""
542
+ <div class="slider-comment">
543
+ ⚑ Tip: Set this number as high as possible or more than 5000 for better scanning of all available papers
544
+ </div>
545
+ """)
546
+
547
+ with gr.Row():
548
+ year_from = gr.Number(value=2000, label="Year From", precision=0)
549
+ year_to = gr.Number(value=2026, label="Year To", precision=0)
550
+ open_access = gr.Checkbox(label="Open Access Only")
551
+
552
+ # ==========================
553
+ # SORTING OPTIONS
554
+ # ==========================
555
+ with gr.Row():
556
+ sort_by = gr.Dropdown(
557
+ label="Sort By",
558
+ choices=["Relevance", "Year", "Citations"],
559
+ value="Relevance"
560
+ )
561
+ sort_order = gr.Dropdown(
562
+ label="Sort Order",
563
+ choices=["Descending", "Ascending"],
564
+ value="Descending"
565
+ )
566
+
567
+ search_btn = gr.Button("πŸ” SEARCH PAPERS", variant="primary", size="lg")
568
+
569
+ # Tab 2: Specific Paper Search
570
+ with gr.TabItem("🎯 Find Specific Paper", id=1):
571
+ with gr.Column(elem_classes="white-card"):
572
+ gr.Markdown("""
573
+ ### Find a specific paper by:
574
+ - **DOI** (e.g., 10.1038/nature12373)
575
+ - **Exact Title** (e.g., "Photoacoustic imaging in biomedicine")
576
+ - **Author** (find papers by a specific researcher)
577
+ """)
578
+
579
+ with gr.Row():
580
+ specific_search_type = gr.Dropdown(
581
+ label="Search by",
582
+ choices=["DOI", "Exact Title", "Specific Author"],
583
+ value="DOI"
584
+ )
585
+
586
+ specific_search_value = gr.Textbox(
587
+ label="Enter value",
588
+ placeholder="e.g., 10.1038/nature12373 or exact paper title or author name",
589
+ scale=2
590
+ )
591
+
592
+ specific_search_btn = gr.Button("πŸ” FIND PAPER", variant="primary")
593
+ specific_summary = gr.Markdown("Ready")
594
 
595
+ # Metrics section (common for both tabs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
596
  with gr.Row():
597
  total_display = gr.Markdown("**0**", elem_classes="metric-value")
598
  avg_display = gr.Markdown("**0.0**", elem_classes="metric-value")
 
604
  gr.Markdown("**Avg Relevance**", elem_classes="metric-label")
605
  gr.Markdown("**Year Range**", elem_classes="metric-label")
606
 
607
+ # Results section (common for both tabs)
608
  results = gr.Dataframe(
609
+ label="Results",
610
  row_count=15,
611
  column_widths=["25%", "15%", "5%", "5%", "10%", "20%", "20%", "5%", "5%"],
612
  wrap=True
 
649
  empty_df = pd.DataFrame(columns=['Title', 'Authors', 'Year', 'Citations', 'Journal', 'Abstract', 'BibTeX', 'Relevance', 'Matched Keywords'])
650
  return empty_df, [], "**0**", "**0.0**", "**N/A**"
651
 
652
+ def specific_search_wrapper(search_type, search_value):
653
+ try:
654
+ df, papers, summary = searcher.search_specific_paper(search_type, search_value)
655
+ if not papers:
656
+ return df, papers, summary, "**0**", "**0.0**", "**N/A**"
657
+
658
+ # Calculate metrics for display
659
+ total = len(papers)
660
+ avg_rel = 0
661
+ years = [p["Year"] for p in papers if p["Year"] != "N/A"]
662
+ year_range = f"{min(years)} - {max(years)}" if years else "N/A"
663
+
664
+ return df, papers, summary, f"**{total}**", f"**{avg_rel:.2f}**", f"**{year_range}**"
665
+ except Exception as e:
666
+ empty_df = pd.DataFrame(columns=['Title', 'Authors', 'Year', 'Citations', 'Journal', 'Abstract', 'BibTeX'])
667
+ return empty_df, [], f"❌ Error: {str(e)}", "**0**", "**0.0**", "**N/A**"
668
+
669
+ # Connect search buttons
670
  search_btn.click(
671
  search_wrapper,
672
  inputs=[query, keywords, authors, max_papers, year_from, year_to, open_access, sort_by, sort_order],
673
  outputs=[results, state, total_display, avg_display, year_display]
674
  )
675
+
676
+ specific_search_btn.click(
677
+ specific_search_wrapper,
678
+ inputs=[specific_search_type, specific_search_value],
679
+ outputs=[results, state, specific_summary, total_display, avg_display, year_display]
680
+ )
681
 
682
  def export_results(papers, fname, fmt):
683