Spaces:
Sleeping
Sleeping
File size: 2,608 Bytes
ceee457 6b28b7f ceee457 6d43b8b ceee457 6d43b8b 2d30509 6b28b7f ceee457 2d30509 6b28b7f 2d30509 ceee457 6d43b8b 2d30509 ceee457 6b28b7f 2d30509 6b28b7f afb7890 6d43b8b 6b28b7f afb7890 6d43b8b 6b28b7f afb7890 ceee457 2d30509 6b28b7f 6d43b8b 6b28b7f ceee457 afb7890 6d43b8b 6b28b7f 6d43b8b afb7890 ceee457 2d30509 afb7890 ceee457 6b28b7f |
1 2 3 4 5 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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
import gradio as gr
import requests
import os
API_KEY = os.getenv("NEWSDATA_API_KEY")
NEWS_URL = "https://newsdata.io/api/1/latest"
def fetch_news(query, category, num_articles, live, sentiment_filter):
"""Fetch latest news from NewsData.io with safe parameter usage."""
if not API_KEY:
return "**β Error:** API Key is missing. Add `NEWSDATA_API_KEY` in your Space Secrets."
# Basic parameters required
params = {
"apikey": API_KEY,
"language": "en",
"country": "us",
}
# Only add params if filled
if query:
params["q"] = query
if category and category != "Any":
params["category"] = category.lower()
if sentiment_filter and sentiment_filter != "Any":
params["sentiment"] = sentiment_filter
# Optional domainurl β only add if user is on paid plan
# params["domainurl"] = "news.google.com" # Uncomment if paid plan
try:
response = requests.get(NEWS_URL, params=params)
response.raise_for_status()
data = response.json()
articles = data.get("results", [])
if not articles:
return "β οΈ **No articles found.** Try a different topic, category, or sentiment."
results = [
f"### π° {article['title']}\n"
f"{article.get('description', 'No description available.')}\n"
f"[Read More]({article['link']})"
for article in articles[:num_articles]
]
return "\n\n---\n\n".join(results)
except requests.exceptions.HTTPError as http_err:
return f"**β HTTP Error {response.status_code}:** {http_err}"
except Exception as e:
return f"**β Error fetching news:** {str(e)}"
# Gradio Interface
iface = gr.Interface(
fn=fetch_news,
inputs=[
gr.Textbox(label="π Enter a Topic", placeholder="e.g. AI, Politics, Mental Health"),
gr.Dropdown(["Any", "Technology", "Business", "Sports", "Health", "Science", "Politics"], label="π Select Category"),
gr.Slider(1, 10, value=5, step=1, label="ποΈ Number of Articles"),
gr.Checkbox(label="π’ Fetch Live News (Latest Only)", value=True),
gr.Dropdown(["Any", "positive", "neutral", "negative"], label="π Sentiment Filter"),
],
outputs=gr.Markdown(),
title="π§ AI News Fetcher",
description="Fetch latest news using NewsData.io. Works with topic search, category, sentiment, and result count. *(Some filters may require a paid plan.)*",
theme="default",
allow_flagging="never",
)
if __name__ == "__main__":
iface.launch()
|