AI-News-Fetcher / app.py
Prak2005's picture
Update app.py
2d30509 verified
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()