File size: 7,702 Bytes
f01d87d
 
 
 
7287745
aa0b994
f01d87d
aa0b994
 
 
 
f01d87d
 
 
 
 
 
 
 
aa0b994
 
f01d87d
aa0b994
f01d87d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa0b994
 
 
 
 
 
 
 
 
 
 
f01d87d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c67e9f8
 
aa0b994
c67e9f8
 
 
 
 
 
 
aa0b994
c67e9f8
aa0b994
f01d87d
 
7287745
c67e9f8
 
 
7287745
c67e9f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7287745
aa0b994
f01d87d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7287745
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import gradio as gr
from duckduckgo_search import DDGS
from datetime import datetime
import os
import asyncio
import nest_asyncio
from openai import OpenAI  # Using standard OpenAI client
from agents import Agent, Runner, function_tool, OpenAIChatCompletionsModel  # Assuming agents package is installed

# Apply nest_asyncio to allow nested event loops
nest_asyncio.apply()

# 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
client = OpenAI(api_key=OPENAI_API_KEY)

# Define the model
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}"
    
    try:
        # 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}."
    except Exception as e:
        return f"Error searching for news: {str(e)}"

# 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
)

# Fallback to direct OpenAI API if agents don't work
def generate_with_openai(prompt):
    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.7,
            max_tokens=2000
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"Error with OpenAI API: {str(e)}"

# Workflow function for Gradio
def fetch_and_edit_news(topic, language, search_date):
    try:
        # Initialize new event loop
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        
        # Try to use Runner.run_sync with the proper event loop context
        try:
            # Step 1: Run the news agent to get news
            news_prompt = f"Get me the news about {topic} in {language} for date {search_date}"
            news_result = Runner.run_sync(news_agent, news_prompt)
            raw_news = news_result.final_output
            
            # Step 2: Run the editor agent to edit the news
            editor_prompt = f"Please edit the following news in {language} language. Maintain the original language: \n\n{raw_news}"
            editor_result = Runner.run_sync(editor_agent, editor_prompt)
            edited_news = editor_result.final_output
            
            return edited_news
            
        except Exception as agent_error:
            print(f"Agent error: {agent_error}")
            
            # Fallback to direct use of DuckDuckGo and OpenAI if agents fail
            try:
                print("Falling back to direct search and API calls...")
                # Get news directly
                raw_news = get_news_articles(topic, language, search_date)
                
                if raw_news.startswith("Error") or raw_news.startswith("Could not find"):
                    return raw_news
                
                # Format prompt for OpenAI
                editor_prompt = f"""
                Please edit and reformat the following news into a cohesive, publication-ready format. 
                Maintain the original language ({language}). 
                Each news story should be in a separate section with a clear headline:
                
                {raw_news}
                """
                
                # Call OpenAI directly
                edited_news = generate_with_openai(editor_prompt)
                return edited_news
                
            except Exception as fallback_error:
                return f"Both agent-based and fallback approaches failed.\nError details: {str(fallback_error)}"
            
    except Exception as e:
        return f"Error: {str(e)}\n\nPlease check your OpenAI API key and ensure it has been set correctly in the repository secrets."

# 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()