Spaces:
Sleeping
Sleeping
File size: 7,754 Bytes
8cfabc7 701ac82 8cfabc7 be2f0b5 8cfabc7 be2f0b5 8cfabc7 701ac82 8cfabc7 | 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | import gradio as gr
from newsdataapi import NewsDataApiClient
from huggingface_hub import InferenceClient
import os
# Initialize APIs
NEWS_API_KEY = os.getenv("NEWS_API_KEY")
HF_TOKEN = os.getenv("HF_TOKEN")
news_client = NewsDataApiClient(apikey=NEWS_API_KEY)
hf_client = InferenceClient(api_key=HF_TOKEN)
def fetch_news(query, country, language, category, max_pages):
"""
Fetch news articles using Newsdata.io API with pagination.
"""
try:
page = None
all_articles = []
for _ in range(max_pages):
response = news_client.latest_api(q=query, country=country, language=language, category=category, page=page)
articles = response.get('results', [])
if not articles:
break
all_articles.extend(articles)
page = response.get('nextPage', None)
if not page:
break
return all_articles
except Exception as e:
return f"Error: {e}"
def summarize_articles(articles, summary_length="brief"):
"""
Summarize articles using Hugging Face models.
"""
try:
article_texts = "\n".join([article['title'] for article in articles])
prompt = "Summarize briefly" if summary_length == "brief" else "Provide a detailed summary"
messages = [{"role": "user", "content": f"{prompt} the following news: {article_texts}"}]
completion = hf_client.chat.completions.create(
model="mistralai/Mistral-7B-Instruct-v0.3",
messages=messages,
max_tokens=500
)
return completion.choices[0].message['content']
except Exception as e:
return f"Error: {e}"
def gradio_interface(query, country, language, category, max_pages, summary_length):
"""
Unified interface for fetching and summarizing news articles.
"""
if country:
country = country.split(" (")[-1][:-1] # Extract the code part from the dropdown choice
articles = fetch_news(query, country, language, category, max_pages)
if isinstance(articles, str): # Error handling
return articles, []
summaries = summarize_articles(articles, summary_length)
article_titles = [article['title'] for article in articles]
# Update the dropdown with new article titles
return summaries, gr.update(choices = article_titles)
countries = [
None, "Afghanistan (af)", "Albania (al)", "Algeria (dz)", "Andorra (ad)", "Angola (ao)", "Argentina (ar)", "Armenia (am)",
"Australia (au)", "Austria (at)", "Azerbaijan (az)", "Bahamas (bs)", "Bahrain (bh)", "Bangladesh (bd)", "Barbados (bb)",
"Belarus (by)", "Belgium (be)", "Belize (bz)", "Benin (bj)", "Bermuda (bm)", "Bhutan (bt)", "Bolivia (bo)",
"Bosnia And Herzegovina (ba)", "Botswana (bw)", "Brazil (br)", "Brunei (bn)", "Bulgaria (bg)", "Burkina Faso (bf)",
"Burundi (bi)", "Cambodia (kh)", "Cameroon (cm)", "Canada (ca)", "Cape Verde (cv)", "Cayman Islands (ky)",
"Central African Republic (cf)", "Chad (td)", "Chile (cl)", "China (cn)", "Colombia (co)", "Comoros (km)", "Congo (cg)",
"Cook Islands (ck)", "Costa Rica (cr)", "Croatia (hr)", "Cuba (cu)", "Curaçao (cw)", "Cyprus (cy)", "Czech Republic (cz)",
"Denmark (dk)", "Djibouti (dj)", "Dominica (dm)", "Dominican Republic (do)", "DR Congo (cd)", "Ecuador (ec)",
"Egypt (eg)", "El Salvador (sv)", "Equatorial Guinea (gq)", "Eritrea (er)", "Estonia (ee)", "Eswatini (sz)",
"Ethiopia (et)", "Fiji (fj)", "Finland (fi)", "France (fr)", "French Polynesia (pf)", "Gabon (ga)", "Gambia (gm)",
"Georgia (ge)", "Germany (de)", "Ghana (gh)", "Gibraltar (gi)", "Greece (gr)", "Grenada (gd)", "Guatemala (gt)",
"Guinea (gn)", "Guyana (gy)", "Haiti (ht)", "Honduras (hn)", "Hong Kong (hk)", "Hungary (hu)", "Iceland (is)",
"India (in)", "Indonesia (id)", "Iran (ir)", "Iraq (iq)", "Ireland (ie)", "Israel (il)", "Italy (it)", "Ivory Coast (ci)",
"Jamaica (jm)", "Japan (jp)", "Jersey (je)", "Jordan (jo)", "Kazakhstan (kz)", "Kenya (ke)", "Kiribati (ki)",
"Kosovo (xk)", "Kuwait (kw)", "Kyrgyzstan (kg)", "Laos (la)", "Latvia (lv)", "Lebanon (lb)", "Lesotho (ls)", "Liberia (lr)",
"Libya (ly)", "Liechtenstein (li)", "Lithuania (lt)", "Luxembourg (lu)", "Macau (mo)", "Macedonia (mk)", "Madagascar (mg)",
"Malawi (mw)", "Malaysia (my)", "Maldives (mv)", "Mali (ml)", "Malta (mt)", "Marshall Islands (mh)", "Mauritania (mr)",
"Mauritius (mu)", "Mexico (mx)", "Micronesia (fm)", "Moldova (md)", "Monaco (mc)", "Mongolia (mn)", "Montenegro (me)",
"Morocco (ma)", "Mozambique (mz)", "Myanmar (mm)", "Namibia (na)", "Nauru (nr)", "Nepal (np)", "Netherlands (nl)",
"New Caledonia (nc)", "New Zealand (nz)", "Nicaragua (ni)", "Niger (ne)", "Nigeria (ng)", "North Korea (kp)", "Norway (no)",
"Oman (om)", "Pakistan (pk)", "Palau (pw)", "Palestine (ps)", "Panama (pa)", "Papua New Guinea (pg)", "Paraguay (py)",
"Peru (pe)", "Philippines (ph)", "Poland (pl)", "Portugal (pt)", "Puerto Rico (pr)", "Qatar (qa)", "Romania (ro)",
"Russia (ru)", "Rwanda (rw)", "Saint Lucia (lc)", "Saint Martin (sx)", "Samoa (ws)", "San Marino (sm)", "São Tomé and Príncipe (st)",
"Saudi Arabia (sa)", "Senegal (sn)", "Serbia (rs)", "Seychelles (sc)", "Sierra Leone (sl)", "Singapore (sg)", "Slovakia (sk)",
"Slovenia (si)", "Solomon Islands (sb)", "Somalia (so)", "South Africa (za)", "South Korea (kr)", "Spain (es)", "Sri Lanka (lk)",
"Sudan (sd)", "Suriname (sr)", "Sweden (se)", "Switzerland (ch)", "Syria (sy)", "Taiwan (tw)", "Tajikistan (tj)", "Tanzania (tz)",
"Thailand (th)", "Timor-Leste (tl)", "Togo (tg)", "Tonga (to)", "Trinidad and Tobago (tt)", "Tunisia (tn)", "Turkey (tr)",
"Turkmenistan (tm)", "Tuvalu (tv)", "Uganda (ug)", "Ukraine (ua)", "United Arab Emirates (ae)", "United Kingdom (gb)",
"United States of America (us)", "Uruguay (uy)", "Uzbekistan (uz)", "Vanuatu (vu)", "Vatican (va)", "Venezuela (ve)",
"Vietnam (vi)", "Virgin Islands (British) (vg)", "World (wo)", "Yemen (ye)", "Zambia (zm)", "Zimbabwe (zw)"
]
categories = [
None, "business", "crime", "domestic", "education", "entertainment",
"environment", "food", "health", "lifestyle", "other",
"politics", "science", "sports", "technology", "top",
"tourism", "world"
]
# Gradio UI
with gr.Blocks() as demo:
# Add Horizontal Bar for App Name and Description using gr.HTML
gr.HTML(
"""
<div style="background-color: #2C3E50; padding: 15px; text-align: center;">
<h1 style="color: white;">Newsify-AI</h1>
<p style="color: #BDC3C7;">Summarize news articles using AI-powered insights</p>
</div>
"""
)
with gr.Row():
query = gr.Textbox(label="Query/Keyword", placeholder="E.g., Ronaldo", value="")
with gr.Row():
country = gr.Dropdown(label="Country",choices=countries)
language = gr.Textbox(label="Language", placeholder="E.g., en", value="en", interactive= False)
category = gr.Dropdown(label="Category", choices=categories)
max_pages = gr.Number(label="Max Pages to Fetch", value=1, precision=0, interactive=False)
summary_length = gr.Radio(["brief", "detailed"], label="Summary Length", value="brief")
fetch_button = gr.Button("Fetch & Summarize")
summary_output = gr.Textbox(label="Summarized News", lines=10)
links_dropdown = gr.Dropdown(label="Article Links", choices=[], interactive=True, allow_custom_value = True)
fetch_button.click(gradio_interface,
inputs=[query, country, language, category, max_pages, summary_length],
outputs=[summary_output, links_dropdown])
if __name__ == "__main__":
demo.launch(debug=True)
|