Spaces:
Sleeping
Sleeping
| # Import necessary libraries | |
| import requests | |
| from bs4 import BeautifulSoup | |
| import openai | |
| import gradio as gr | |
| import os | |
| from dotenv import load_dotenv | |
| # Load environment variables from .env file | |
| load_dotenv() | |
| openai.api_key = os.getenv("OPENAI_API_KEY") | |
| secret_prompt = os.getenv("PROMPT_SECRET") | |
| # Function to scrape content from a URL | |
| def scrape_content(url): | |
| try: | |
| response = requests.get(url) | |
| soup = BeautifulSoup(response.content, 'html.parser') | |
| # Extract title and content | |
| title = soup.find('title').get_text() | |
| paragraphs = soup.find_all('p') | |
| content = '\n'.join([para.get_text() for para in paragraphs]) | |
| return title, content | |
| except Exception as e: | |
| return None, f"Error fetching content: {str(e)}" | |
| # Function to summarize content in the selected language | |
| def summarize_content(content, language): | |
| try: | |
| # Generate summary using the OpenAI Chat API | |
| response = openai.chat.completions.create( | |
| model="gpt-4o", # Use the latest GPT model | |
| messages=[ | |
| {"role": "system", "content": secret_prompt.replace("{language}", language)}, | |
| {"role": "user", "content": content} | |
| ], | |
| max_tokens=500, # Allows responses of up to ~200 words | |
| temperature=0.2 # More deterministic output | |
| ) | |
| # Extract the summary from the response | |
| summary = response.choices[0].message.content.strip() | |
| return summary | |
| except Exception as e: | |
| return f"Error generating summary: {str(e)}" | |
| # Function to process a single URL and generate a summary | |
| def process_url(url, language): | |
| if not url: | |
| return "No URL provided." | |
| title, content = scrape_content(url) | |
| if content.startswith("Error"): | |
| return content | |
| summary = summarize_content(content, language) | |
| return f"Title: {title}\n\nSummary ({language}):\n{summary}" | |
| # Gradio interface | |
| iface = gr.Interface( | |
| fn=process_url, | |
| inputs=[ | |
| gr.Textbox(lines=2, placeholder="Enter URL here...", label="News Article URL"), | |
| gr.Dropdown( | |
| ["Hindi","English", "Telugu", "Kannada", "Marathi", "Bengali", "Gujarati","Tamil","Malayalam"], | |
| label="Select Language", | |
| value="Hindi" | |
| ) | |
| ], | |
| outputs="text", | |
| title="Multilingual News Article Summarizer", | |
| description="Enter a News Site URL and select a language to generate a summary." | |
| ) | |
| # Launch the interface | |
| if __name__ == "__main__": | |
| iface.launch(share=True) | |