Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -29,30 +29,28 @@ def search_api(query):
|
|
29 |
if not results:
|
30 |
results.append({"Title": "No results found.", "URL": ""})
|
31 |
|
32 |
-
# Add ranking
|
33 |
for i, r in enumerate(results):
|
34 |
r["Rank"] = i + 1
|
35 |
|
36 |
return pd.DataFrame(results)[["Rank", "Title", "URL"]]
|
|
|
37 |
except Exception as e:
|
38 |
return pd.DataFrame([{"Rank": "", "Title": "Error fetching results.", "URL": str(e)}])
|
39 |
|
40 |
-
# Export CSV
|
41 |
def export_csv(results, query):
|
42 |
if results is None or results.empty:
|
43 |
-
return
|
44 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
45 |
-
fname = f"{query.replace(' ', '_')}_results_{timestamp}.csv"
|
46 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", newline='', encoding="utf-8") as tmp:
|
47 |
results.to_csv(tmp.name, index=False)
|
48 |
return tmp.name
|
49 |
|
50 |
-
# Export DOCX
|
51 |
def export_docx(results, query):
|
52 |
if results is None or results.empty:
|
53 |
-
return
|
54 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
55 |
-
fname = f"{query.replace(' ', '_')}_results_{timestamp}.docx"
|
56 |
doc = Document()
|
57 |
doc.add_heading(f"Search Results for: {query}", 0)
|
58 |
for i, row in results.iterrows():
|
@@ -61,17 +59,17 @@ def export_docx(results, query):
|
|
61 |
doc.save(tmp.name)
|
62 |
return tmp.name
|
63 |
|
64 |
-
# UI
|
65 |
with gr.Blocks() as demo:
|
66 |
-
gr.Markdown("## 🔎 Smart Search & Export App")
|
67 |
gr.Markdown("""
|
68 |
-
This app lets you search DuckDuckGo and export the results as a **CSV or Word DOCX
|
69 |
|
70 |
-
|
71 |
-
1.
|
72 |
-
2. Click **Search** to
|
73 |
-
3.
|
74 |
-
4. Export results
|
75 |
""")
|
76 |
|
77 |
query = gr.Textbox(label="Search Query", placeholder="Enter topic...")
|
@@ -95,12 +93,12 @@ with gr.Blocks() as demo:
|
|
95 |
elif "Please enter" in df.iloc[0]["Title"]:
|
96 |
status_msg = "⚠️ Please enter a search term."
|
97 |
else:
|
98 |
-
status_msg = f"✅
|
99 |
return df, status_msg
|
100 |
|
101 |
-
# Actions
|
102 |
search_btn.click(fn=handle_search, inputs=query, outputs=[results_display, status])
|
103 |
export_csv_btn.click(fn=export_csv, inputs=[results_display, query], outputs=csv_file)
|
104 |
export_docx_btn.click(fn=export_docx, inputs=[results_display, query], outputs=docx_file)
|
105 |
|
106 |
-
demo.launch(share=True
|
|
|
|
29 |
if not results:
|
30 |
results.append({"Title": "No results found.", "URL": ""})
|
31 |
|
|
|
32 |
for i, r in enumerate(results):
|
33 |
r["Rank"] = i + 1
|
34 |
|
35 |
return pd.DataFrame(results)[["Rank", "Title", "URL"]]
|
36 |
+
|
37 |
except Exception as e:
|
38 |
return pd.DataFrame([{"Rank": "", "Title": "Error fetching results.", "URL": str(e)}])
|
39 |
|
40 |
+
# Export CSV safely
|
41 |
def export_csv(results, query):
|
42 |
if results is None or results.empty:
|
43 |
+
return ""
|
44 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
|
45 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", newline='', encoding="utf-8") as tmp:
|
46 |
results.to_csv(tmp.name, index=False)
|
47 |
return tmp.name
|
48 |
|
49 |
+
# Export DOCX safely
|
50 |
def export_docx(results, query):
|
51 |
if results is None or results.empty:
|
52 |
+
return ""
|
53 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
|
54 |
doc = Document()
|
55 |
doc.add_heading(f"Search Results for: {query}", 0)
|
56 |
for i, row in results.iterrows():
|
|
|
59 |
doc.save(tmp.name)
|
60 |
return tmp.name
|
61 |
|
62 |
+
# Gradio UI
|
63 |
with gr.Blocks() as demo:
|
64 |
+
gr.Markdown("## 🔎 Smart DuckDuckGo Search & Export App")
|
65 |
gr.Markdown("""
|
66 |
+
This app lets you search DuckDuckGo and export the results as a **CSV or Word DOCX** file.
|
67 |
|
68 |
+
### Instructions:
|
69 |
+
1. Enter a search topic (e.g., "climate change").
|
70 |
+
2. Click **Search** to fetch results from DuckDuckGo.
|
71 |
+
3. View and click links directly.
|
72 |
+
4. Export results using the buttons below.
|
73 |
""")
|
74 |
|
75 |
query = gr.Textbox(label="Search Query", placeholder="Enter topic...")
|
|
|
93 |
elif "Please enter" in df.iloc[0]["Title"]:
|
94 |
status_msg = "⚠️ Please enter a search term."
|
95 |
else:
|
96 |
+
status_msg = f"✅ Found {len(df)} results for: **{q}**"
|
97 |
return df, status_msg
|
98 |
|
|
|
99 |
search_btn.click(fn=handle_search, inputs=query, outputs=[results_display, status])
|
100 |
export_csv_btn.click(fn=export_csv, inputs=[results_display, query], outputs=csv_file)
|
101 |
export_docx_btn.click(fn=export_docx, inputs=[results_display, query], outputs=docx_file)
|
102 |
|
103 |
+
demo.launch() # DO NOT set share=True on Hugging Face Spaces
|
104 |
+
|