File size: 5,691 Bytes
265b6a6
 
 
7eed016
5952adf
7eed016
 
5952adf
 
 
265b6a6
 
 
 
5952adf
7eed016
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5952adf
 
265b6a6
7eed016
 
5952adf
7eed016
 
5952adf
7eed016
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5952adf
 
 
 
 
 
265b6a6
7eed016
5952adf
 
265b6a6
 
 
 
5952adf
265b6a6
7eed016
5952adf
265b6a6
 
 
5952adf
265b6a6
7eed016
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265b6a6
7eed016
 
5952adf
7eed016
 
 
265b6a6
7eed016
265b6a6
7eed016
265b6a6
7eed016
265b6a6
 
 
 
 
 
 
 
7eed016
265b6a6
 
5952adf
7eed016
265b6a6
7eed016
 
265b6a6
7eed016
 
265b6a6
7eed016
 
265b6a6
7eed016
265b6a6
5952adf
265b6a6
7eed016
 
265b6a6
 
 
 
 
 
7eed016
 
5952adf
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
# 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
        )