File size: 7,479 Bytes
b35bc08
7df49c3
 
 
 
 
 
 
 
 
b35bc08
7df49c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

import gradio as gr
import json
from smolagents import load_tool
import time
from datetime import datetime
import plotly.graph_objects as go
from fpdf import FPDF
import tempfile
import os

# Load the analyzer with caching
analyzer = load_tool("MHamdan/smart-web-analyzer-plus", trust_remote_code=True)
analysis_cache = {}

def create_sentiment_chart(sentiment_data):
    """Creates an interactive bar chart for sentiment analysis."""
    sections = []
    scores = []
    
    for item in sentiment_data['sections']:
        sections.append(f"Section {item['section']}")
        scores.append(item['score'])
    
    fig = go.Figure(data=[
        go.Bar(
            x=sections,
            y=scores,
            marker_color='rgb(55, 83, 109)',
            text=scores,
            textposition='auto'
        )
    ])
    
    fig.update_layout(
        title='Sentiment Analysis by Section',
        xaxis_title='Content Sections',
        yaxis_title='Sentiment Score (1-5)',
        yaxis_range=[0, 5]
    )
    
    return fig

def generate_pdf_report(analysis_result):
    """Generates a PDF report from analysis results."""
    pdf = FPDF()
    pdf.add_page()
    
    # Header
    pdf.set_font('Arial', 'B', 16)
    pdf.cell(0, 10, 'Content Analysis Report', 0, 1, 'C')
    pdf.line(10, 30, 200, 30)
    
    # Date
    pdf.set_font('Arial', '', 10)
    pdf.cell(0, 10, f'Generated on: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}', 0, 1)
    
    # Content
    pdf.set_font('Arial', 'B', 12)
    pdf.cell(0, 10, 'Basic Statistics:', 0, 1)
    pdf.set_font('Arial', '', 10)
    
    stats = analysis_result.get('stats', {})
    for key, value in stats.items():
        pdf.cell(0, 10, f'{key.title()}: {value}', 0, 1)
    
    if 'summary' in analysis_result:
        pdf.set_font('Arial', 'B', 12)
        pdf.cell(0, 10, 'Summary:', 0, 1)
        pdf.set_font('Arial', '', 10)
        pdf.multi_cell(0, 10, analysis_result['summary'])
    
    # Save to temporary file
    temp_dir = tempfile.gettempdir()
    pdf_path = os.path.join(temp_dir, 'analysis_report.pdf')
    pdf.output(pdf_path)
    
    return pdf_path

def process_content(input_text, mode, theme, progress=gr.Progress()):
    """Main processing function with progress updates."""
    try:
        # Check cache
        cache_key = f"{input_text}_{mode}"
        if cache_key in analysis_cache:
            return (
                analysis_cache[cache_key],
                "Content preview unavailable for cached results",
                "Using cached results",
                None
            )
        
        # Process in steps
        progress(0, desc="Initializing analysis...")
        time.sleep(0.5)  # Simulate processing
        
        progress(0.3, desc="Fetching content...")
        result = analyzer(input_text, mode)
        analysis_result = json.loads(result)
        
        progress(0.6, desc="Analyzing content...")
        
        # Create visualization if sentiment mode
        chart = None
        if mode == "sentiment" and analysis_result.get('status') == 'success':
            progress(0.8, desc="Generating visualizations...")
            chart = create_sentiment_chart(analysis_result['sentiment_analysis'])
        
        # Cache results
        analysis_cache[cache_key] = analysis_result
        
        # Generate preview text
        preview = analysis_result.get('stats', {}).get('title', '')
        if 'summary' in analysis_result:
            preview += f"\n\nSummary:\n{analysis_result['summary']}"
        
        progress(1.0, desc="Complete!")
        return analysis_result, preview, "Analysis complete!", chart
        
    except Exception as e:
        return (
            {"status": "error", "message": str(e)},
            "Error occurred",
            f"Error: {str(e)}",
            None
        )

def create_interface():
    with gr.Blocks(title="Smart Web Analyzer Plus", theme=gr.themes.Base()) as iface:
        # Header
        gr.Markdown("# πŸš€ Smart Web Analyzer Plus")
        gr.Markdown("""
        Advanced content analysis with AI-powered insights:
        * πŸ“Š Comprehensive Analysis
        * 😊 Detailed Sentiment Analysis
        * πŸ“ Smart Summarization
        * 🎯 Topic Detection
        """)
        
        # Theme toggle
        with gr.Row():
            theme = gr.Radio(
                choices=["light", "dark"],
                value="light",
                label="Theme",
                interactive=True
            )
        
        # Main content
        with gr.Tabs():
            # Analysis Tab
            with gr.Tab("Analysis"):
                with gr.Row():
                    with gr.Column():
                        input_text = gr.Textbox(
                            label="URL or Text to Analyze",
                            placeholder="Enter URL or paste text",
                            lines=5
                        )
                        mode = gr.Radio(
                            choices=["analyze", "summarize", "sentiment", "topics"],
                            value="analyze",
                            label="Analysis Mode"
                        )
                        analyze_btn = gr.Button("πŸ” Analyze", variant="primary")
                        status = gr.Markdown("Status: Ready")
                    
                    with gr.Column():
                        results = gr.JSON(label="Analysis Results")
                        chart = gr.Plot(label="Visualization", visible=False)
                
                # Show/hide chart based on mode
                mode.change(
                    lambda m: gr.update(visible=(m == "sentiment")),
                    inputs=[mode],
                    outputs=[chart]
                )
            
            # Preview Tab
            with gr.Tab("Preview"):
                preview = gr.Textbox(
                    label="Content Preview",
                    lines=10,
                    interactive=False
                )
            
            # Report Tab
            with gr.Tab("Report"):
                download_btn = gr.Button("πŸ“₯ Download PDF Report")
                pdf_output = gr.File(label="Generated Report")
        
        # Examples
        gr.Examples(
            examples=[
                ["https://www.artificialintelligence-news.com/2024/02/14/openai-anthropic-google-white-house-red-teaming/", "analyze", "light"],
                ["https://www.artificialintelligence-news.com/2024/02/13/ai-21-labs-wordtune-chatgpt-plugin/", "sentiment", "light"]
            ],
            inputs=[input_text, mode, theme],
            outputs=[results, preview, status, chart],
            fn=process_content,
            cache_examples=True
        )
        
        # Handle theme changes
        theme.change(
            lambda t: gr.update(theme=gr.themes.Base() if t == "light" else gr.themes.Soft()),
            inputs=[theme],
            outputs=[iface]
        )
        
        # Wire up the analysis button
        analyze_btn.click(
            fn=process_content,
            inputs=[input_text, mode, theme],
            outputs=[results, preview, status, chart]
        )
        
        # Wire up PDF download
        download_btn.click(
            fn=lambda: generate_pdf_report(json.loads(results.value)),
            inputs=[],
            outputs=[pdf_output]
        )
    
    return iface

demo = create_interface()
demo.launch()