Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,7 +5,6 @@ from docx import Document
|
|
5 |
from datetime import datetime
|
6 |
from xml.etree import ElementTree as ET
|
7 |
|
8 |
-
# 1. Function to fetch PubMed articles
|
9 |
def fetch_pubmed_articles(query, max_results, page, sort_by, journal_filter, min_year, max_year):
|
10 |
if not query or query.strip() == "":
|
11 |
return "β Please enter a search query.", "", pd.DataFrame()
|
@@ -56,24 +55,21 @@ def fetch_pubmed_articles(query, max_results, page, sort_by, journal_filter, min
|
|
56 |
df = pd.DataFrame(articles)
|
57 |
if df.empty:
|
58 |
return "β No results could be parsed.", "", pd.DataFrame()
|
59 |
-
# Filter
|
60 |
if journal_filter:
|
61 |
df = df[df["Journal"].str.contains(journal_filter, case=False, na=False)]
|
62 |
-
if min_year
|
63 |
df = df[df["Year"] >= int(min_year)]
|
64 |
-
if max_year
|
65 |
df = df[df["Year"] <= int(max_year)]
|
66 |
if df.empty:
|
67 |
return "β No results matched your filters.", "", pd.DataFrame()
|
68 |
-
# Sort
|
69 |
if sort_by == "Year":
|
70 |
df = df.sort_values(by="Year", ascending=False, na_position='last')
|
71 |
elif sort_by == "Title":
|
72 |
df = df.sort_values(by="Title", ascending=True, na_position='last')
|
73 |
elif sort_by == "Journal":
|
74 |
df = df.sort_values(by="Journal", ascending=True, na_position='last')
|
75 |
-
|
76 |
-
result_text = f"**Showing {len(df)} results:**\n\n"
|
77 |
for _, row in df.iterrows():
|
78 |
pmid_url = f"https://pubmed.ncbi.nlm.nih.gov/{row['PMID']}/"
|
79 |
result_text += f"#### [{row['Title']}]({pmid_url})\n"
|
@@ -84,9 +80,9 @@ def fetch_pubmed_articles(query, max_results, page, sort_by, journal_filter, min
|
|
84 |
except Exception as e:
|
85 |
return f"β Error: {str(e)}", "", pd.DataFrame()
|
86 |
|
87 |
-
|
88 |
-
|
89 |
-
if df
|
90 |
return None
|
91 |
now = datetime.now().strftime("%Y%m%d_%H%M%S")
|
92 |
if file_type == "CSV":
|
@@ -108,16 +104,21 @@ def export_results(df, file_type):
|
|
108 |
return path
|
109 |
return None
|
110 |
|
111 |
-
# 3. Gradio Interface
|
112 |
with gr.Blocks(theme="soft") as app:
|
113 |
gr.Markdown("""
|
114 |
-
# π¬ PubMed Article Search Tool
|
|
|
115 |
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
|
|
|
|
|
|
|
|
|
|
121 |
|
122 |
---
|
123 |
""")
|
@@ -125,18 +126,18 @@ with gr.Blocks(theme="soft") as app:
|
|
125 |
with gr.Row():
|
126 |
with gr.Column():
|
127 |
query_input = gr.Textbox(label="Search Query", placeholder="e.g., brain inflammation", lines=2)
|
128 |
-
max_results_input = gr.Number(label="Max Results
|
129 |
page_input = gr.Number(label="Page Number", value=1, minimum=1)
|
130 |
sort_input = gr.Dropdown(["Year", "Title", "Journal"], value="Year", label="Sort By")
|
131 |
journal_filter_input = gr.Textbox(label="Journal Filter (optional)")
|
132 |
-
min_year_input = gr.Number(label="Min Year
|
133 |
-
max_year_input = gr.Number(label="Max Year
|
134 |
-
search_button = gr.Button("π Search PubMed"
|
135 |
-
status_output = gr.Markdown(
|
136 |
with gr.Column():
|
137 |
-
markdown_output = gr.Markdown(
|
138 |
-
table_output = gr.DataFrame(
|
139 |
-
df_state = gr.State(
|
140 |
|
141 |
with gr.Row():
|
142 |
export_csv_button = gr.Button("β¬οΈ Export CSV")
|
@@ -144,12 +145,9 @@ with gr.Blocks(theme="soft") as app:
|
|
144 |
export_csv_output = gr.File(label="Download CSV")
|
145 |
export_docx_output = gr.File(label="Download DOCX")
|
146 |
|
147 |
-
# 4. Logic to control buttons and flow
|
148 |
def run_search(query, max_results, page, sort_by, journal_filter, min_year, max_year):
|
149 |
-
status, md, df = fetch_pubmed_articles(
|
150 |
-
|
151 |
-
)
|
152 |
-
return status, md, df, df
|
153 |
|
154 |
search_button.click(
|
155 |
fn=run_search,
|
@@ -157,8 +155,9 @@ with gr.Blocks(theme="soft") as app:
|
|
157 |
outputs=[status_output, markdown_output, table_output, df_state]
|
158 |
)
|
159 |
|
160 |
-
export_csv_button.click(lambda
|
161 |
-
export_docx_button.click(lambda
|
162 |
|
163 |
app.launch()
|
164 |
|
|
|
|
5 |
from datetime import datetime
|
6 |
from xml.etree import ElementTree as ET
|
7 |
|
|
|
8 |
def fetch_pubmed_articles(query, max_results, page, sort_by, journal_filter, min_year, max_year):
|
9 |
if not query or query.strip() == "":
|
10 |
return "β Please enter a search query.", "", pd.DataFrame()
|
|
|
55 |
df = pd.DataFrame(articles)
|
56 |
if df.empty:
|
57 |
return "β No results could be parsed.", "", pd.DataFrame()
|
|
|
58 |
if journal_filter:
|
59 |
df = df[df["Journal"].str.contains(journal_filter, case=False, na=False)]
|
60 |
+
if min_year and str(min_year).isdigit():
|
61 |
df = df[df["Year"] >= int(min_year)]
|
62 |
+
if max_year and str(max_year).isdigit():
|
63 |
df = df[df["Year"] <= int(max_year)]
|
64 |
if df.empty:
|
65 |
return "β No results matched your filters.", "", pd.DataFrame()
|
|
|
66 |
if sort_by == "Year":
|
67 |
df = df.sort_values(by="Year", ascending=False, na_position='last')
|
68 |
elif sort_by == "Title":
|
69 |
df = df.sort_values(by="Title", ascending=True, na_position='last')
|
70 |
elif sort_by == "Journal":
|
71 |
df = df.sort_values(by="Journal", ascending=True, na_position='last')
|
72 |
+
result_text = f"### β
Showing {len(df)} result(s):\n\n"
|
|
|
73 |
for _, row in df.iterrows():
|
74 |
pmid_url = f"https://pubmed.ncbi.nlm.nih.gov/{row['PMID']}/"
|
75 |
result_text += f"#### [{row['Title']}]({pmid_url})\n"
|
|
|
80 |
except Exception as e:
|
81 |
return f"β Error: {str(e)}", "", pd.DataFrame()
|
82 |
|
83 |
+
def export_results(df_dict, file_type):
|
84 |
+
df = pd.DataFrame(df_dict)
|
85 |
+
if df.empty:
|
86 |
return None
|
87 |
now = datetime.now().strftime("%Y%m%d_%H%M%S")
|
88 |
if file_type == "CSV":
|
|
|
104 |
return path
|
105 |
return None
|
106 |
|
|
|
107 |
with gr.Blocks(theme="soft") as app:
|
108 |
gr.Markdown("""
|
109 |
+
# π¬ **PubMed Article Search Tool**
|
110 |
+
Search biomedical literature from PubMed using keywords and filters.
|
111 |
|
112 |
+
β
Supports filters by journal, year range, and sorting by year/title/journal.
|
113 |
+
π₯ Export search results to CSV or DOCX.
|
114 |
+
|
115 |
+
---
|
116 |
+
|
117 |
+
### π How to use:
|
118 |
+
1. Enter your search keywords (e.g., `brain inflammation`).
|
119 |
+
2. Adjust filters (journal name, min/max year, etc.).
|
120 |
+
3. Click **π Search PubMed** to view articles.
|
121 |
+
4. Use buttons to **download results**.
|
122 |
|
123 |
---
|
124 |
""")
|
|
|
126 |
with gr.Row():
|
127 |
with gr.Column():
|
128 |
query_input = gr.Textbox(label="Search Query", placeholder="e.g., brain inflammation", lines=2)
|
129 |
+
max_results_input = gr.Number(label="Max Results", value=20, minimum=1, maximum=100)
|
130 |
page_input = gr.Number(label="Page Number", value=1, minimum=1)
|
131 |
sort_input = gr.Dropdown(["Year", "Title", "Journal"], value="Year", label="Sort By")
|
132 |
journal_filter_input = gr.Textbox(label="Journal Filter (optional)")
|
133 |
+
min_year_input = gr.Number(label="Min Year", value=2000, minimum=1800, maximum=2100)
|
134 |
+
max_year_input = gr.Number(label="Max Year", value=2025, minimum=1800, maximum=2100)
|
135 |
+
search_button = gr.Button("π Search PubMed")
|
136 |
+
status_output = gr.Markdown()
|
137 |
with gr.Column():
|
138 |
+
markdown_output = gr.Markdown("βΉοΈ Search results will appear here.")
|
139 |
+
table_output = gr.DataFrame(label="Results Table", interactive=False)
|
140 |
+
df_state = gr.State({}) # Store as dictionary
|
141 |
|
142 |
with gr.Row():
|
143 |
export_csv_button = gr.Button("β¬οΈ Export CSV")
|
|
|
145 |
export_csv_output = gr.File(label="Download CSV")
|
146 |
export_docx_output = gr.File(label="Download DOCX")
|
147 |
|
|
|
148 |
def run_search(query, max_results, page, sort_by, journal_filter, min_year, max_year):
|
149 |
+
status, md, df = fetch_pubmed_articles(query, max_results, page, sort_by, journal_filter, min_year, max_year)
|
150 |
+
return status, md, df, df.to_dict()
|
|
|
|
|
151 |
|
152 |
search_button.click(
|
153 |
fn=run_search,
|
|
|
155 |
outputs=[status_output, markdown_output, table_output, df_state]
|
156 |
)
|
157 |
|
158 |
+
export_csv_button.click(fn=lambda df_dict: export_results(df_dict, "CSV"), inputs=[df_state], outputs=[export_csv_output])
|
159 |
+
export_docx_button.click(fn=lambda df_dict: export_results(df_dict, "DOCX"), inputs=[df_state], outputs=[export_docx_output])
|
160 |
|
161 |
app.launch()
|
162 |
|
163 |
+
|