# Gradio_UI.py import gradio as gr from smolagents import CodeAgent from typing import Optional, List, Tuple import logging from bs4 import BeautifulSoup import requests import json logger = logging.getLogger(__name__) class GradioUI: def __init__(self, agent: CodeAgent): self.agent = agent def fetch_content(self, url: str) -> str: """Fetch content from URL.""" try: response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') return soup.get_text() except Exception as e: logger.error(f"Error fetching URL: {str(e)}") return f"Error fetching content: {str(e)}" def analyze_content(self, content: str, analysis_types: List[str]) -> dict: """Analyze the content based on selected analysis types.""" results = { 'clean_text': content[:1000] + '...' if len(content) > 1000 else content, 'summary': '', 'sentiment': '', 'topics': '' } try: if 'summarize' in analysis_types: results['summary'] = self.agent.run(f"Summarize this text: {content[:2000]}") if 'sentiment' in analysis_types: results['sentiment'] = self.agent.run(f"Analyze the sentiment of this text: {content[:2000]}") if 'topics' in analysis_types: results['topics'] = self.agent.run(f"Identify the main topics in this text: {content[:2000]}") except Exception as e: logger.error(f"Error in analysis: {str(e)}") return { 'error': str(e), 'clean_text': 'Analysis failed', 'summary': '', 'sentiment': '', 'topics': '' } return results def process_url(self, url: str, analysis_types: List[str]) -> Tuple[str, str, str, str]: """Process URL and return analysis results.""" try: # Fetch content content = self.fetch_content(url) # Analyze content results = self.analyze_content(content, analysis_types) # Return results for each tab return ( results.get('clean_text', ''), results.get('summary', ''), results.get('sentiment', ''), results.get('topics', '') ) except Exception as e: error_msg = f"Error: {str(e)}" return error_msg, error_msg, error_msg, error_msg def launch(self, server_name: Optional[str] = None, server_port: Optional[int] = None, share: bool = False): """Launch the Gradio interface.""" with gr.Blocks(title="Smart Web Analyzer Plus") as demo: # Header gr.Markdown("# 🌐 Smart Web Analyzer Plus") gr.Markdown("Analyze web content using AI to extract summaries, determine sentiment, and identify topics.") # Input section with gr.Row(): url_input = gr.Textbox( label="Enter URL", placeholder="https://example.com", scale=3 ) analysis_types = gr.CheckboxGroup( choices=["summarize", "sentiment", "topics"], value=["summarize"], label="Analysis Types", scale=2 ) analyze_btn = gr.Button( "Analyze", variant="primary", scale=1 ) # Progress indicator progress = gr.Markdown(visible=False) # Results section - using a single Tabs component with gr.Tabs() as output_tabs: with gr.Tab("Clean Text", id="clean_text"): clean_text_output = gr.Markdown() with gr.Tab("Summary", id="summary"): summary_output = gr.Markdown() with gr.Tab("Sentiment", id="sentiment"): sentiment_output = gr.Markdown() with gr.Tab("Topics", id="topics"): topics_output = gr.Markdown() # Examples gr.Examples( examples=[ ["https://www.bbc.com/news/technology-67881954", ["summarize", "sentiment"]], ["https://arxiv.org/html/2312.17296v1", ["topics", "summarize"]] ], inputs=[url_input, analysis_types] ) # Event handlers def show_progress(): return gr.update(value="⏳ Analysis in progress...", visible=True) def hide_progress(): return gr.update(value="", visible=False) # Connect the button click event analyze_btn.click( fn=show_progress, outputs=progress ).then( fn=self.process_url, inputs=[url_input, analysis_types], outputs=[clean_text_output, summary_output, sentiment_output, topics_output] ).then( fn=hide_progress, outputs=progress ) # Launch the interface demo.launch( server_name=server_name, server_port=server_port, share=share, debug=True )