Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,175 +1,72 @@
|
|
1 |
import gradio as gr
|
2 |
-
import requests
|
3 |
import pandas as pd
|
4 |
-
import
|
|
|
|
|
5 |
from docx import Document
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
elif sort_by == "Title":
|
47 |
-
articles.sort(key=lambda x: x["Title"])
|
48 |
-
elif sort_by == "Journal":
|
49 |
-
articles.sort(key=lambda x: x["Journal"])
|
50 |
-
|
51 |
-
# Format markdown results
|
52 |
-
formatted_results = []
|
53 |
-
for article in articles:
|
54 |
-
formatted_results.append(
|
55 |
-
f"## π° {article['Title']}\n"
|
56 |
-
f"π **<span style='color:blue'>{article['Journal']}</span>** ({article['Year']})\n"
|
57 |
-
f"π¨βπ¬ **<span style='color:gray'>{article['Authors']}</span>**\n"
|
58 |
-
f"π [Read on PubMed]({article['PubMed_URL']})\n\n"
|
59 |
-
f"<details><summary>π **Show Abstract**</summary>\n{article['Abstract']}\n</details>"
|
60 |
-
f"\n---\n"
|
61 |
-
)
|
62 |
-
|
63 |
-
df = pd.DataFrame(articles)
|
64 |
-
return "\n\n".join(formatted_results), df
|
65 |
-
|
66 |
-
except Exception as e:
|
67 |
-
return f"β οΈ Error fetching data: {str(e)}", None
|
68 |
-
|
69 |
-
|
70 |
-
def export_results(df, format_type):
|
71 |
-
"""
|
72 |
-
Safely exports the given DataFrame to a temporary file (CSV or DOCX).
|
73 |
-
"""
|
74 |
-
import traceback
|
75 |
-
|
76 |
-
if df is None or df.empty:
|
77 |
-
print("β οΈ Warning: DataFrame is empty or None. Nothing to export.")
|
78 |
-
return None
|
79 |
-
|
80 |
-
try:
|
81 |
-
suffix = f".{format_type.lower()}"
|
82 |
-
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
|
83 |
-
temp_file_path = temp_file.name
|
84 |
-
|
85 |
-
if format_type == "CSV":
|
86 |
-
df.to_csv(temp_file_path, index=False)
|
87 |
-
|
88 |
-
elif format_type == "DOCX":
|
89 |
-
doc = Document()
|
90 |
-
doc.add_heading("PubMed Search Results", level=1)
|
91 |
-
for _, row in df.iterrows():
|
92 |
-
doc.add_heading(row.get("Title", "Untitled"), level=2)
|
93 |
-
doc.add_paragraph(f"π Journal: {row.get('Journal', 'Unknown')} ({row.get('Year', '')})")
|
94 |
-
doc.add_paragraph(f"π¨βπ¬ Authors: {row.get('Authors', 'N/A')}")
|
95 |
-
doc.add_paragraph(f"π Link: {row.get('PubMed_URL', 'N/A')}")
|
96 |
-
doc.add_paragraph(f"π Abstract: {row.get('Abstract', '')}")
|
97 |
-
doc.add_paragraph("---")
|
98 |
-
doc.save(temp_file_path)
|
99 |
-
|
100 |
-
temp_file.close()
|
101 |
-
return temp_file_path
|
102 |
-
|
103 |
-
except Exception as e:
|
104 |
-
print("β Export failed:", str(e))
|
105 |
-
traceback.print_exc()
|
106 |
-
return None
|
107 |
-
|
108 |
-
|
109 |
-
def export_csv():
|
110 |
-
if global_df is not None:
|
111 |
-
file_path = export_results(global_df, "CSV")
|
112 |
-
if isinstance(file_path, str):
|
113 |
-
return file_path
|
114 |
-
return None
|
115 |
-
|
116 |
-
|
117 |
-
def export_docx():
|
118 |
-
if global_df is not None:
|
119 |
-
file_path = export_results(global_df, "DOCX")
|
120 |
-
if isinstance(file_path, str):
|
121 |
-
return file_path
|
122 |
-
return None
|
123 |
-
|
124 |
-
|
125 |
-
def search_and_display(query, max_results, page, sort_by, journal_filter, min_year, max_year):
|
126 |
-
global global_df
|
127 |
-
result_text, df = fetch_pubmed_articles(query, max_results, page, sort_by, journal_filter, min_year, max_year)
|
128 |
-
global_df = df
|
129 |
-
print("π Search completed. DataFrame loaded with", len(df) if df is not None else 0, "articles.")
|
130 |
-
return result_text
|
131 |
-
|
132 |
-
|
133 |
-
with gr.Blocks() as app:
|
134 |
-
gr.Markdown("""
|
135 |
-
# π **PubMed Search Tool with Export Options**
|
136 |
-
### Search biomedical literature and export results as CSV or Word DOCX.
|
137 |
-
""")
|
138 |
-
|
139 |
-
with gr.Row():
|
140 |
-
query_input = gr.Textbox(label="π Search Query", placeholder="e.g., 'Deep Learning in Psychiatry'")
|
141 |
-
|
142 |
-
with gr.Row():
|
143 |
-
max_results_input = gr.Slider(1, 50, value=10, step=1, label="π Results per Page")
|
144 |
-
page_input = gr.Slider(1, 100, value=1, step=1, label="π Page Number")
|
145 |
-
|
146 |
-
with gr.Row():
|
147 |
-
sort_input = gr.Dropdown(["Year", "Title", "Journal"], value="Year", label="π Sort By")
|
148 |
-
journal_filter_input = gr.Textbox(label="π― Filter by Journal (optional)", placeholder="e.g., Nature")
|
149 |
|
150 |
with gr.Row():
|
151 |
-
|
152 |
-
|
153 |
|
154 |
-
|
155 |
-
|
156 |
-
export_csv_button = gr.Button("π Export as CSV")
|
157 |
-
export_docx_button = gr.Button("π Export as Word DOCX")
|
158 |
|
159 |
-
|
160 |
-
|
161 |
-
|
|
|
162 |
|
163 |
-
|
164 |
-
|
165 |
-
sort_input, journal_filter_input, min_year_input, max_year_input],
|
166 |
-
outputs=results_output)
|
167 |
|
168 |
-
|
169 |
-
|
170 |
|
|
|
|
|
|
|
171 |
|
172 |
-
|
173 |
-
app.launch()
|
174 |
|
175 |
|
|
|
1 |
import gradio as gr
|
|
|
2 |
import pandas as pd
|
3 |
+
import requests
|
4 |
+
import os
|
5 |
+
from datetime import datetime
|
6 |
from docx import Document
|
7 |
|
8 |
+
def search_api(query):
|
9 |
+
url = f"https://api.duckduckgo.com/?q={query}&format=json&no_redirect=1"
|
10 |
+
response = requests.get(url)
|
11 |
+
if response.status_code == 200:
|
12 |
+
data = response.json()
|
13 |
+
related_topics = data.get("RelatedTopics", [])
|
14 |
+
results = []
|
15 |
+
for topic in related_topics:
|
16 |
+
if "Text" in topic and "FirstURL" in topic:
|
17 |
+
results.append({
|
18 |
+
"Title": topic["Text"],
|
19 |
+
"URL": topic["FirstURL"]
|
20 |
+
})
|
21 |
+
return pd.DataFrame(results)
|
22 |
+
else:
|
23 |
+
return pd.DataFrame([{"Title": "Error", "URL": "Failed to fetch results"}])
|
24 |
+
|
25 |
+
# Save results
|
26 |
+
def export_csv(df):
|
27 |
+
file_path = "search_results.csv"
|
28 |
+
df.to_csv(file_path, index=False)
|
29 |
+
return file_path
|
30 |
+
|
31 |
+
def export_docx(df):
|
32 |
+
doc = Document()
|
33 |
+
doc.add_heading("Search Results", 0)
|
34 |
+
for _, row in df.iterrows():
|
35 |
+
doc.add_paragraph(f"{row['Title']}\n{row['URL']}")
|
36 |
+
file_path = "search_results.docx"
|
37 |
+
doc.save(file_path)
|
38 |
+
return file_path
|
39 |
+
|
40 |
+
# Set up Gradio Blocks
|
41 |
+
with gr.Blocks() as demo:
|
42 |
+
gr.Markdown("## π Simple Search with Export Options")
|
43 |
+
|
44 |
+
query_input = gr.Textbox(label="Search Query", placeholder="Enter a topic...")
|
45 |
+
search_button = gr.Button("Search")
|
46 |
+
results_df = gr.Dataframe(label="Search Results", interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
with gr.Row():
|
49 |
+
export_csv_button = gr.Button("Export as CSV")
|
50 |
+
export_docx_button = gr.Button("Export as Word DOCX")
|
51 |
|
52 |
+
csv_output = gr.File(label="Download CSV")
|
53 |
+
docx_output = gr.File(label="Download DOCX")
|
|
|
|
|
54 |
|
55 |
+
# Logic
|
56 |
+
def handle_search(q):
|
57 |
+
df = search_api(q)
|
58 |
+
return df
|
59 |
|
60 |
+
def handle_csv_export(df):
|
61 |
+
return export_csv(df)
|
|
|
|
|
62 |
|
63 |
+
def handle_docx_export(df):
|
64 |
+
return export_docx(df)
|
65 |
|
66 |
+
search_button.click(handle_search, inputs=query_input, outputs=results_df)
|
67 |
+
export_csv_button.click(handle_csv_export, inputs=results_df, outputs=csv_output)
|
68 |
+
export_docx_button.click(handle_docx_export, inputs=results_df, outputs=docx_output)
|
69 |
|
70 |
+
demo.launch()
|
|
|
71 |
|
72 |
|