SumanDhanu's picture
Update app.py
7287745 verified
raw
history blame
6.08 kB
import gradio as gr
from duckduckgo_search import DDGS
from datetime import datetime
import os
import asyncio
from openai import OpenAI # Using standard OpenAI client
from agents import Agent, Runner, function_tool # Assuming agents package is installed
# Set up environment variables
# For Hugging Face Spaces, set these in the Settings > Repository secrets
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") # You'll need to add this to HF Spaces secrets
# Get current date for default value
default_date = datetime.now().strftime("%Y-%m-%d")
# Configure OpenAI client to use HuggingFace or OpenAI API
client = OpenAI(
api_key=OPENAI_API_KEY,
# If using OpenAI directly
# If using a different API endpoint (e.g., HF Inference API), uncomment and adjust:
# base_url="https://api-inference.huggingface.co/models/meta-llama/Llama-3.2-70b-instruct"
)
# Define the model - assuming the agents library supports standard OpenAI client
from agents import OpenAIChatCompletionsModel # Adjust import if needed
model = OpenAIChatCompletionsModel(
model="gpt-4o-mini", # Using GPT-4o-mini for better performance at a lower cost
openai_client=client
)
# News search tool
@function_tool
def get_news_articles(topic, language="English", search_date=None):
# Use provided date or default to current date
if not search_date:
search_date = datetime.now().strftime("%Y-%m")
else:
# Convert from date picker format (YYYY-MM-DD) to YYYY-MM format
search_date = search_date[:7] # Just get YYYY-MM portion
print(f"Running DuckDuckGo news search for {topic} in {language} for date {search_date}...")
# Map common languages to their search keywords
language_keywords = {
"English": "", # Default, no special keyword needed
"Hindi": "हिंदी",
"Spanish": "español",
"French": "français",
"German": "deutsch",
"Japanese": "日本語",
"Chinese": "中文",
"Russian": "русский",
"Arabic": "العربية",
"Portuguese": "português",
"Italian": "italiano",
"Dutch": "nederlands",
"Korean": "한국어",
"Turkish": "türkçe",
"Kannada": "ಕನ್ನಡ",
"Tamil": "தமிழ்",
"Telugu": "తెలుగు",
"Bengali": "বাংলা",
"Marathi": "मराठी"
}
# Get language keyword if available
lang_keyword = language_keywords.get(language, language)
# Add language to search query if it's not English
search_query = f"{topic} {lang_keyword} {search_date}" if language != "English" else f"{topic} {search_date}"
# DuckDuckGo search
ddg_api = DDGS()
results = ddg_api.text(search_query, max_results=5)
if results:
news_results = "\n\n".join([f"Title: {result['title']}\nURL: {result['href']}\nDescription: {result['body']}" for result in results])
return news_results
else:
return f"Could not find news results for {topic} in {language} for {search_date}."
# Create agents
news_agent = Agent(
name="News Agent",
instructions="You provide the latest news articles for a given topic using DuckDuckGo search. You can search for news in different languages when specified.",
tools=[get_news_articles],
model=model
)
editor_agent = Agent(
name="Editor Assistant",
instructions="Rewrite and give me a news article ready for publishing. Each news story should be in a separate section. Maintain the original language of the news stories. If the content is in a language other than English, edit and format in that same language.",
model=model
)
# Workflow function for Gradio
def fetch_and_edit_news(topic, language, search_date):
try:
# Create a new event loop for this thread
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# Step 1: Run the news agent
news_result = Runner.run_sync(
news_agent,
f"Get me the news about {topic} in {language} for date {search_date}")
raw_news = news_result.final_output
# Step 2: Pass news to editor for final review
editor_news_response = Runner.run_sync(
editor_agent,
f"Please edit the following news in {language} language. Maintain the original language: \n\n{raw_news}")
edited_news = editor_news_response.final_output
return edited_news
except Exception as e:
# Return the error message for debugging
return f"Error: {str(e)}\n\nThis could be due to API key issues or problems with the openai-agents package. Please check the logs for more details."
# Create Gradio interface
with gr.Blocks(title="Multilingual AI News Generator") as demo:
gr.Markdown("# Multilingual AI News Generator")
gr.Markdown("Enter a topic, select a language, and choose a date to receive curated and edited news articles")
with gr.Row():
topic_input = gr.Textbox(label="News Topic", placeholder="Enter a topic (e.g., AI, Climate Change, Sports)")
language_dropdown = gr.Dropdown(
choices=[
"English", "Hindi", "Spanish", "French", "German",
"Japanese", "Chinese", "Russian", "Arabic", "Portuguese",
"Italian", "Dutch", "Korean", "Turkish", "Kannada",
"Tamil", "Telugu", "Bengali", "Marathi"
],
label="Language",
value="English"
)
date_picker = gr.Textbox(
label="Search Date",
placeholder="YYYY-MM-DD",
value=default_date
)
submit_btn = gr.Button("Generate News Article")
output_box = gr.Textbox(label="Generated News Article", lines=20)
submit_btn.click(
fn=fetch_and_edit_news,
inputs=[topic_input, language_dropdown, date_picker],
outputs=output_box
)
# Launch the app
if __name__ == "__main__":
demo.launch()