Subahdip627 commited on
Commit
2ba0f94
Β·
verified Β·
1 Parent(s): 8d47636

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -44
app.py CHANGED
@@ -1,6 +1,6 @@
1
  """
2
  PaperSearchPro - STRICT Hierarchical Keyword Search
3
- BOTH first AND second keywords are REQUIRED
4
  """
5
 
6
  import requests
@@ -46,6 +46,7 @@ class PaperSearchMobile:
46
  max_attempts = 30
47
 
48
  print(f"\nπŸ” Searching: {query}")
 
49
 
50
  # Fetch papers
51
  while len(all_papers) < max_papers and page <= max_attempts:
@@ -80,62 +81,132 @@ class PaperSearchMobile:
80
  break
81
 
82
  # ========== STRICT HIERARCHICAL FILTERING ==========
83
- # BOTH first AND second keywords are REQUIRED
84
  keyword_list = []
85
  if keywords and keywords.strip():
86
  keyword_list = [k.strip().lower() for k in keywords.split(',') if k.strip()]
87
 
88
  if len(keyword_list) >= 2: # Need at least 2 keywords
89
  print(f"\nπŸ”‘ STRICT Filtering: MUST contain BOTH '{keyword_list[0]}' AND '{keyword_list[1]}'")
 
90
  if len(keyword_list) > 2:
91
  print(f" Additional keywords: {', '.join(keyword_list[2:])} (optional, add relevance)")
92
 
93
  scored_papers = []
 
 
 
94
  for paper in all_papers:
95
- text = f"{paper['Title']} {paper.get('Abstract', '')} {paper['Authors']}".lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- # BOTH first AND second keywords MUST be present
98
- if keyword_list[0] not in text or keyword_list[1] not in text:
99
  continue
100
 
 
 
 
 
 
101
  # Calculate score
102
  score = 2 # Base score for having both required keywords
103
  matched = [keyword_list[0], keyword_list[1]]
104
 
105
  # Check additional keywords (optional)
106
  for idx, kw in enumerate(keyword_list[2:], start=3):
107
- if kw in text:
108
  score += (len(keyword_list) - idx + 1)
109
  matched.append(kw)
110
 
 
 
 
 
111
  paper['score'] = score
112
  paper['matched'] = ', '.join(matched)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  paper['required_matched'] = f"βœ“ {keyword_list[0]}, βœ“ {keyword_list[1]}"
 
 
114
  scored_papers.append(paper)
115
 
116
  scored_papers.sort(key=lambda x: x['score'], reverse=True)
117
  all_papers = scored_papers
118
- print(f" Found {len(all_papers)} papers with BOTH required keywords")
 
 
119
 
120
  elif len(keyword_list) == 1:
121
  # Only one keyword provided - just require that one
122
  print(f"\nπŸ”‘ Filtering: MUST contain '{keyword_list[0]}'")
 
123
 
124
  scored_papers = []
 
 
 
125
  for paper in all_papers:
126
- text = f"{paper['Title']} {paper.get('Abstract', '')} {paper['Authors']}".lower()
 
 
 
 
127
 
128
- if keyword_list[0] not in text:
 
129
  continue
130
 
 
 
 
 
131
  paper['score'] = 1
132
  paper['matched'] = keyword_list[0]
133
  paper['required_matched'] = f"βœ“ {keyword_list[0]}"
 
134
  scored_papers.append(paper)
135
 
136
  scored_papers.sort(key=lambda x: x['score'], reverse=True)
137
  all_papers = scored_papers
138
- print(f" Found {len(all_papers)} papers with required keyword")
 
 
139
 
140
  # Prepare display
141
  if all_papers:
@@ -145,7 +216,9 @@ class PaperSearchMobile:
145
  df = pd.DataFrame(all_papers)
146
  display_cols = ["Rank", "score", "Title", "Authors", "Year", "Citations", "Journal"]
147
 
148
- # Add appropriate columns based on what's available
 
 
149
  if 'required_matched' in df.columns:
150
  display_cols.append("required_matched")
151
  if 'matched' in df.columns and len(keyword_list) > 2:
@@ -154,25 +227,40 @@ class PaperSearchMobile:
154
  display_df = df[display_cols]
155
 
156
  # Rename columns for better display
157
- rename_dict = {"score": "Relevance"}
 
 
 
158
  if 'required_matched' in display_df.columns:
159
  rename_dict["required_matched"] = "Required Keywords"
160
  if 'matched' in display_df.columns:
161
- rename_dict["matched"] = "Optional Keywords"
162
 
163
  display_df = display_df.rename(columns=rename_dict)
164
 
165
- # Create summary
166
  if len(keyword_list) >= 2:
167
- summary = f"πŸ“Š **{len(all_papers)} papers** (contain BOTH '{keyword_list[0]}' AND '{keyword_list[1]}')"
 
 
 
 
 
 
168
  elif len(keyword_list) == 1:
169
- summary = f"πŸ“Š **{len(all_papers)} papers** (contain '{keyword_list[0]}')"
 
 
 
 
 
 
170
  else:
171
  summary = f"πŸ“Š **{len(all_papers)} papers**"
172
 
173
  return display_df, summary, all_papers
174
 
175
- return pd.DataFrame(), "No papers found", []
176
 
177
  def _extract_paper_info(self, work):
178
  def get_authors(authorships):
@@ -185,7 +273,7 @@ class PaperSearchMobile:
185
  authors.append(name)
186
  return ", ".join(authors) + ("..." if len(authorships) > 3 else "")
187
 
188
- # Get abstract
189
  abstract = ""
190
  if work.get("abstract_inverted_index"):
191
  words = []
@@ -196,12 +284,12 @@ class PaperSearchMobile:
196
  abstract = " ".join([w[1] for w in words])
197
 
198
  return {
199
- "Title": work.get("title", "No title")[:100],
200
  "Authors": get_authors(work.get("authorships", [])),
201
  "Year": work.get("publication_year", "N/A"),
202
  "Citations": work.get("cited_by_count", 0),
203
- "Journal": (work.get("primary_location", {}).get("source") or {}).get("display_name", "Unknown")[:50],
204
- "Abstract": abstract,
205
  "matched": ""
206
  }
207
 
@@ -237,18 +325,22 @@ def create_interface():
237
  ### Both FIRST and SECOND keywords are REQUIRED
238
 
239
  <div style='background-color: #e8f4fd; padding: 15px; border-radius: 10px; margin: 10px 0;'>
240
- <h3>πŸ”‘ Keyword Hierarchy Rules:</h3>
 
 
 
241
  <ul>
242
- <li><strong style='color: #d32f2f;'>Keyword 1:</strong> <span style='background-color: #ffcdd2; padding: 2px 8px; border-radius: 4px;'>REQUIRED</span></li>
243
- <li><strong style='color: #d32f2f;'>Keyword 2:</strong> <span style='background-color: #ffcdd2; padding: 2px 8px; border-radius: 4px;'>REQUIRED</span></li>
244
- <li><strong style='color: #2e7d32;'>Keyword 3+:</strong> <span style='background-color: #c8e6c9; padding: 2px 8px; border-radius: 4px;'>Optional (adds relevance)</span></li>
245
  </ul>
246
  <p>⚠️ <strong>Note:</strong> Papers missing either Keyword 1 or Keyword 2 are automatically filtered out.</p>
 
247
  </div>
248
  """)
249
 
250
  with gr.Column():
251
- # Inputs with visual hierarchy
252
  query = gr.Textbox(
253
  label="πŸ” Search Topic",
254
  placeholder="e.g., photoacoustic imaging, machine learning",
@@ -264,13 +356,14 @@ def create_interface():
264
  value="blood, cancer, imaging",
265
  )
266
 
267
- # Visual indicator for keyword positions
268
  with gr.Row():
269
  gr.Markdown("""
270
- <div style='display: flex; gap: 10px; margin-top: 5px;'>
271
  <div style='background-color: #ffcdd2; padding: 5px 10px; border-radius: 5px;'>Keyword 1: REQUIRED</div>
272
  <div style='background-color: #ffcdd2; padding: 5px 10px; border-radius: 5px;'>Keyword 2: REQUIRED</div>
273
  <div style='background-color: #c8e6c9; padding: 5px 10px; border-radius: 5px;'>Keyword 3+: Optional</div>
 
274
  </div>
275
  """)
276
 
@@ -289,8 +382,8 @@ def create_interface():
289
  with gr.Row():
290
  max_papers = gr.Slider(
291
  label="Max Papers to Fetch",
292
- minimum=10000,
293
- maximum=50000,
294
  value=1000,
295
  step=100
296
  )
@@ -311,12 +404,12 @@ def create_interface():
311
  )
312
 
313
  # Search button
314
- search_btn = gr.Button("πŸ” SEARCH", variant="primary", size="lg")
315
 
316
  # Outputs
317
  summary = gr.Markdown("Ready")
318
 
319
- # Results with enhanced display
320
  results = gr.Dataframe(
321
  label="Results",
322
  wrap=True,
@@ -369,13 +462,18 @@ def create_interface():
369
  outputs=[download_file, export_status, download_file]
370
  )
371
 
372
- # Add example keywords
373
  gr.Markdown("""
374
  ---
375
  ### πŸ“ Examples:
376
- - **Both required:** `blood, cancer, imaging` (finds papers with BOTH blood AND cancer)
377
  - **Three keywords:** `therapy, treatment, drug` (finds papers with therapy AND treatment, drug adds relevance)
378
- - **Single keyword:** `cancer` (finds papers with cancer only)
 
 
 
 
 
379
  """)
380
 
381
  return demo
@@ -386,17 +484,17 @@ def create_interface():
386
  if __name__ == "__main__":
387
  demo = create_interface()
388
 
389
- print("\n" + "="*80)
390
- print("πŸš€ PaperSearchPro - STRICT Hierarchical Search (AND Condition)")
391
- print("="*80)
392
  print("\nβœ… NEW FEATURES:")
393
- print(" β€’ BOTH first AND second keywords are REQUIRED")
394
- print(" β€’ Smart GUI with visual hierarchy indicators")
395
- print(" β€’ Color-coded keyword requirements")
396
- print(" β€’ Papers missing either required keyword are filtered out")
397
- print(" β€’ Additional keywords add relevance score")
398
  print("\n🌐 Deployed on Hugging Face Spaces - permanent link!")
399
- print("="*80 + "\n")
400
 
401
  # Launch for Hugging Face
402
  demo.launch()
 
1
  """
2
  PaperSearchPro - STRICT Hierarchical Keyword Search
3
+ BOTH first AND second keywords are REQUIRED - Scans Title, Abstract, and Authors
4
  """
5
 
6
  import requests
 
46
  max_attempts = 30
47
 
48
  print(f"\nπŸ” Searching: {query}")
49
+ print(f"πŸ“„ Will scan TITLE, ABSTRACT, and AUTHORS for keywords")
50
 
51
  # Fetch papers
52
  while len(all_papers) < max_papers and page <= max_attempts:
 
81
  break
82
 
83
  # ========== STRICT HIERARCHICAL FILTERING ==========
84
+ # BOTH first AND second keywords are REQUIRED - scanned from ALL FIELDS
85
  keyword_list = []
86
  if keywords and keywords.strip():
87
  keyword_list = [k.strip().lower() for k in keywords.split(',') if k.strip()]
88
 
89
  if len(keyword_list) >= 2: # Need at least 2 keywords
90
  print(f"\nπŸ”‘ STRICT Filtering: MUST contain BOTH '{keyword_list[0]}' AND '{keyword_list[1]}'")
91
+ print(f" Scanning: Title + Abstract + Authors")
92
  if len(keyword_list) > 2:
93
  print(f" Additional keywords: {', '.join(keyword_list[2:])} (optional, add relevance)")
94
 
95
  scored_papers = []
96
+ papers_missing = 0
97
+ papers_with_abstract = 0
98
+
99
  for paper in all_papers:
100
+ # Combine ALL text fields for searching
101
+ title_text = paper['Title'].lower()
102
+ abstract_text = paper.get('Abstract', '').lower()
103
+ authors_text = paper['Authors'].lower()
104
+
105
+ # Search in ALL fields combined
106
+ combined_text = f"{title_text} {abstract_text} {authors_text}"
107
+
108
+ # Track if abstract contributed to match
109
+ abstract_contributed = False
110
+
111
+ # Check if BOTH first AND second keywords are present ANYWHERE
112
+ kw1_present = keyword_list[0] in combined_text
113
+ kw2_present = keyword_list[1] in combined_text
114
 
115
+ if not (kw1_present and kw2_present):
116
+ papers_missing += 1
117
  continue
118
 
119
+ # Check if keywords were found in abstract specifically
120
+ if (keyword_list[0] in abstract_text) or (keyword_list[1] in abstract_text):
121
+ abstract_contributed = True
122
+ papers_with_abstract += 1
123
+
124
  # Calculate score
125
  score = 2 # Base score for having both required keywords
126
  matched = [keyword_list[0], keyword_list[1]]
127
 
128
  # Check additional keywords (optional)
129
  for idx, kw in enumerate(keyword_list[2:], start=3):
130
+ if kw in combined_text:
131
  score += (len(keyword_list) - idx + 1)
132
  matched.append(kw)
133
 
134
+ # Bonus points if keywords found in abstract (more relevant)
135
+ if abstract_contributed:
136
+ score += 1
137
+
138
  paper['score'] = score
139
  paper['matched'] = ', '.join(matched)
140
+
141
+ # Create detailed match info
142
+ match_details = []
143
+ if kw1_present:
144
+ location = []
145
+ if keyword_list[0] in title_text:
146
+ location.append("Title")
147
+ if keyword_list[0] in abstract_text:
148
+ location.append("Abstract")
149
+ if keyword_list[0] in authors_text:
150
+ location.append("Authors")
151
+ match_details.append(f"βœ“ '{keyword_list[0]}' in {', '.join(location)}")
152
+
153
+ if kw2_present:
154
+ location = []
155
+ if keyword_list[1] in title_text:
156
+ location.append("Title")
157
+ if keyword_list[1] in abstract_text:
158
+ location.append("Abstract")
159
+ if keyword_list[1] in authors_text:
160
+ location.append("Authors")
161
+ match_details.append(f"βœ“ '{keyword_list[1]}' in {', '.join(location)}")
162
+
163
+ paper['match_details'] = "\n".join(match_details)
164
  paper['required_matched'] = f"βœ“ {keyword_list[0]}, βœ“ {keyword_list[1]}"
165
+ paper['abstract_match'] = "Yes" if abstract_contributed else "No"
166
+
167
  scored_papers.append(paper)
168
 
169
  scored_papers.sort(key=lambda x: x['score'], reverse=True)
170
  all_papers = scored_papers
171
+ print(f" βœ… Found {len(all_papers)} papers with BOTH required keywords")
172
+ print(f" πŸ“„ Papers where keywords found in abstract: {papers_with_abstract}")
173
+ print(f" ❌ Papers filtered out (missing keywords): {papers_missing}")
174
 
175
  elif len(keyword_list) == 1:
176
  # Only one keyword provided - just require that one
177
  print(f"\nπŸ”‘ Filtering: MUST contain '{keyword_list[0]}'")
178
+ print(f" Scanning: Title + Abstract + Authors")
179
 
180
  scored_papers = []
181
+ papers_missing = 0
182
+ papers_with_abstract = 0
183
+
184
  for paper in all_papers:
185
+ title_text = paper['Title'].lower()
186
+ abstract_text = paper.get('Abstract', '').lower()
187
+ authors_text = paper['Authors'].lower()
188
+
189
+ combined_text = f"{title_text} {abstract_text} {authors_text}"
190
 
191
+ if keyword_list[0] not in combined_text:
192
+ papers_missing += 1
193
  continue
194
 
195
+ # Check if found in abstract
196
+ if keyword_list[0] in abstract_text:
197
+ papers_with_abstract += 1
198
+
199
  paper['score'] = 1
200
  paper['matched'] = keyword_list[0]
201
  paper['required_matched'] = f"βœ“ {keyword_list[0]}"
202
+ paper['abstract_match'] = "Yes" if keyword_list[0] in abstract_text else "No"
203
  scored_papers.append(paper)
204
 
205
  scored_papers.sort(key=lambda x: x['score'], reverse=True)
206
  all_papers = scored_papers
207
+ print(f" βœ… Found {len(all_papers)} papers with required keyword")
208
+ print(f" πŸ“„ Papers with keyword in abstract: {papers_with_abstract}")
209
+ print(f" ❌ Papers filtered out: {papers_missing}")
210
 
211
  # Prepare display
212
  if all_papers:
 
216
  df = pd.DataFrame(all_papers)
217
  display_cols = ["Rank", "score", "Title", "Authors", "Year", "Citations", "Journal"]
218
 
219
+ # Add appropriate columns
220
+ if 'abstract_match' in df.columns:
221
+ display_cols.append("abstract_match")
222
  if 'required_matched' in df.columns:
223
  display_cols.append("required_matched")
224
  if 'matched' in df.columns and len(keyword_list) > 2:
 
227
  display_df = df[display_cols]
228
 
229
  # Rename columns for better display
230
+ rename_dict = {
231
+ "score": "Relevance",
232
+ "abstract_match": "In Abstract"
233
+ }
234
  if 'required_matched' in display_df.columns:
235
  rename_dict["required_matched"] = "Required Keywords"
236
  if 'matched' in display_df.columns:
237
+ rename_dict["matched"] = "All Keywords"
238
 
239
  display_df = display_df.rename(columns=rename_dict)
240
 
241
+ # Create detailed summary
242
  if len(keyword_list) >= 2:
243
+ summary = f"""
244
+ ### πŸ“Š Search Results
245
+ - **{len(all_papers)} papers** found (contain BOTH '{keyword_list[0]}' AND '{keyword_list[1]}')
246
+ - **{df['abstract_match'].value_counts().get('Yes', 0)} papers** have keywords in abstract
247
+ - **Average relevance score:** {df['score'].mean():.1f}
248
+ - **Year range:** {df['Year'].min()} - {df['Year'].max()}
249
+ """
250
  elif len(keyword_list) == 1:
251
+ summary = f"""
252
+ ### πŸ“Š Search Results
253
+ - **{len(all_papers)} papers** found (contain '{keyword_list[0]}')
254
+ - **{df['abstract_match'].value_counts().get('Yes', 0)} papers** have keyword in abstract
255
+ - **Average relevance score:** {df['score'].mean():.1f}
256
+ - **Year range:** {df['Year'].min()} - {df['Year'].max()}
257
+ """
258
  else:
259
  summary = f"πŸ“Š **{len(all_papers)} papers**"
260
 
261
  return display_df, summary, all_papers
262
 
263
+ return pd.DataFrame(), "### πŸ“Š No papers found matching your criteria", []
264
 
265
  def _extract_paper_info(self, work):
266
  def get_authors(authorships):
 
273
  authors.append(name)
274
  return ", ".join(authors) + ("..." if len(authorships) > 3 else "")
275
 
276
+ # Get FULL abstract (not truncated)
277
  abstract = ""
278
  if work.get("abstract_inverted_index"):
279
  words = []
 
284
  abstract = " ".join([w[1] for w in words])
285
 
286
  return {
287
+ "Title": work.get("title", "No title")[:150],
288
  "Authors": get_authors(work.get("authorships", [])),
289
  "Year": work.get("publication_year", "N/A"),
290
  "Citations": work.get("cited_by_count", 0),
291
+ "Journal": (work.get("primary_location", {}).get("source") or {}).get("display_name", "Unknown")[:60],
292
+ "Abstract": abstract, # Full abstract stored
293
  "matched": ""
294
  }
295
 
 
325
  ### Both FIRST and SECOND keywords are REQUIRED
326
 
327
  <div style='background-color: #e8f4fd; padding: 15px; border-radius: 10px; margin: 10px 0;'>
328
+ <h3>πŸ”‘ Keyword Search Scope:</h3>
329
+ <p style='font-size: 16px;'>βœ… <strong>Searching in:</strong> TITLE + ABSTRACT + AUTHORS</p>
330
+
331
+ <h3>πŸ“‹ Keyword Hierarchy Rules:</h3>
332
  <ul>
333
+ <li><strong style='color: #d32f2f;'>Keyword 1:</strong> <span style='background-color: #ffcdd2; padding: 2px 8px; border-radius: 4px;'>REQUIRED</span> (in Title/Abstract/Authors)</li>
334
+ <li><strong style='color: #d32f2f;'>Keyword 2:</strong> <span style='background-color: #ffcdd2; padding: 2px 8px; border-radius: 4px;'>REQUIRED</span> (in Title/Abstract/Authors)</li>
335
+ <li><strong style='color: #2e7d32;'>Keyword 3+:</strong> <span style='background-color: #c8e6c9; padding: 2px 8px; border-radius: 4px;'>Optional</span> (adds relevance if found anywhere)</li>
336
  </ul>
337
  <p>⚠️ <strong>Note:</strong> Papers missing either Keyword 1 or Keyword 2 are automatically filtered out.</p>
338
+ <p>πŸ“Š <strong>Bonus:</strong> Papers with keywords in abstract get +1 relevance score!</p>
339
  </div>
340
  """)
341
 
342
  with gr.Column():
343
+ # Inputs
344
  query = gr.Textbox(
345
  label="πŸ” Search Topic",
346
  placeholder="e.g., photoacoustic imaging, machine learning",
 
356
  value="blood, cancer, imaging",
357
  )
358
 
359
+ # Visual indicator for search scope
360
  with gr.Row():
361
  gr.Markdown("""
362
+ <div style='display: flex; gap: 10px; margin-top: 5px; flex-wrap: wrap;'>
363
  <div style='background-color: #ffcdd2; padding: 5px 10px; border-radius: 5px;'>Keyword 1: REQUIRED</div>
364
  <div style='background-color: #ffcdd2; padding: 5px 10px; border-radius: 5px;'>Keyword 2: REQUIRED</div>
365
  <div style='background-color: #c8e6c9; padding: 5px 10px; border-radius: 5px;'>Keyword 3+: Optional</div>
366
+ <div style='background-color: #fff3cd; padding: 5px 10px; border-radius: 5px;'>πŸ“„ Scanning: Title + Abstract + Authors</div>
367
  </div>
368
  """)
369
 
 
382
  with gr.Row():
383
  max_papers = gr.Slider(
384
  label="Max Papers to Fetch",
385
+ minimum=100,
386
+ maximum=5000,
387
  value=1000,
388
  step=100
389
  )
 
404
  )
405
 
406
  # Search button
407
+ search_btn = gr.Button("πŸ” SEARCH (Scanning Title + Abstract + Authors)", variant="primary", size="lg")
408
 
409
  # Outputs
410
  summary = gr.Markdown("Ready")
411
 
412
+ # Results
413
  results = gr.Dataframe(
414
  label="Results",
415
  wrap=True,
 
462
  outputs=[download_file, export_status, download_file]
463
  )
464
 
465
+ # Add examples
466
  gr.Markdown("""
467
  ---
468
  ### πŸ“ Examples:
469
+ - **Both required:** `blood, cancer, imaging` (finds papers with BOTH blood AND cancer in Title/Abstract/Authors)
470
  - **Three keywords:** `therapy, treatment, drug` (finds papers with therapy AND treatment, drug adds relevance)
471
+ - **Single keyword:** `cancer` (finds papers with cancer in Title/Abstract/Authors)
472
+
473
+ ### πŸ“Š Column Explanations:
474
+ - **Relevance:** Higher score = more keywords matched + keywords in abstract
475
+ - **In Abstract:** "Yes" means keywords found in abstract (not just title)
476
+ - **Required Keywords:** Shows which required keywords were found
477
  """)
478
 
479
  return demo
 
484
  if __name__ == "__main__":
485
  demo = create_interface()
486
 
487
+ print("\n" + "="*90)
488
+ print("πŸš€ PaperSearchPro - STRICT Hierarchical Search (WITH ABSTRACT SCANNING)")
489
+ print("="*90)
490
  print("\nβœ… NEW FEATURES:")
491
+ print(" β€’ Scans TITLE, ABSTRACT, and AUTHORS for keywords")
492
+ print(" β€’ BOTH first AND second keywords REQUIRED anywhere in these fields")
493
+ print(" β€’ Shows if keywords found in abstract")
494
+ print(" β€’ Bonus points for abstract matches")
495
+ print(" β€’ Detailed match information")
496
  print("\n🌐 Deployed on Hugging Face Spaces - permanent link!")
497
+ print("="*90 + "\n")
498
 
499
  # Launch for Hugging Face
500
  demo.launch()