Spaces:
Sleeping
Sleeping
Create websearch.py
Browse files- websearch.py +35 -0
websearch.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
# Real-time web search using SerpAPI (Optional)
|
4 |
+
try:
|
5 |
+
from serpapi import GoogleSearch
|
6 |
+
SERP_API_KEY = os.environ.get("SERPAPI_API_KEY", "your-serpapi-key") # Add via HF secrets
|
7 |
+
serpapi_available = True
|
8 |
+
except:
|
9 |
+
serpapi_available = False
|
10 |
+
|
11 |
+
# 🔎 Get online info for query
|
12 |
+
def web_search(query):
|
13 |
+
if serpapi_available and SERP_API_KEY != "your-serpapi-key":
|
14 |
+
params = {
|
15 |
+
"q": query,
|
16 |
+
"api_key": SERP_API_KEY,
|
17 |
+
"num": 3,
|
18 |
+
}
|
19 |
+
search = GoogleSearch(params)
|
20 |
+
results = search.get_dict()
|
21 |
+
snippets = []
|
22 |
+
|
23 |
+
for result in results.get("organic_results", []):
|
24 |
+
snippet = result.get("snippet")
|
25 |
+
if snippet:
|
26 |
+
snippets.append(snippet)
|
27 |
+
|
28 |
+
return "\n".join(snippets[:3])
|
29 |
+
else:
|
30 |
+
# Simulated fallback for Hugging Face or offline use
|
31 |
+
return (
|
32 |
+
"Recent market reports show increased volatility in tech sector.\n"
|
33 |
+
"Analysts predict weak Q3 earnings due to supply chain issues.\n"
|
34 |
+
"Risk models suggest lowering exposure to tech-heavy portfolios."
|
35 |
+
)
|