Spaces:
Sleeping
Sleeping
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() | |