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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import json
|
| 4 |
+
from smolagents import load_tool
|
| 5 |
+
import time
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import plotly.graph_objects as go
|
| 8 |
+
from fpdf import FPDF
|
| 9 |
+
import tempfile
|
| 10 |
+
import os
|
| 11 |
|
| 12 |
+
# Load the analyzer with caching
|
| 13 |
+
analyzer = load_tool("MHamdan/smart-web-analyzer-plus", trust_remote_code=True)
|
| 14 |
+
analysis_cache = {}
|
| 15 |
+
|
| 16 |
+
def create_sentiment_chart(sentiment_data):
|
| 17 |
+
"""Creates an interactive bar chart for sentiment analysis."""
|
| 18 |
+
sections = []
|
| 19 |
+
scores = []
|
| 20 |
+
|
| 21 |
+
for item in sentiment_data['sections']:
|
| 22 |
+
sections.append(f"Section {item['section']}")
|
| 23 |
+
scores.append(item['score'])
|
| 24 |
+
|
| 25 |
+
fig = go.Figure(data=[
|
| 26 |
+
go.Bar(
|
| 27 |
+
x=sections,
|
| 28 |
+
y=scores,
|
| 29 |
+
marker_color='rgb(55, 83, 109)',
|
| 30 |
+
text=scores,
|
| 31 |
+
textposition='auto'
|
| 32 |
+
)
|
| 33 |
+
])
|
| 34 |
+
|
| 35 |
+
fig.update_layout(
|
| 36 |
+
title='Sentiment Analysis by Section',
|
| 37 |
+
xaxis_title='Content Sections',
|
| 38 |
+
yaxis_title='Sentiment Score (1-5)',
|
| 39 |
+
yaxis_range=[0, 5]
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
return fig
|
| 43 |
+
|
| 44 |
+
def generate_pdf_report(analysis_result):
|
| 45 |
+
"""Generates a PDF report from analysis results."""
|
| 46 |
+
pdf = FPDF()
|
| 47 |
+
pdf.add_page()
|
| 48 |
+
|
| 49 |
+
# Header
|
| 50 |
+
pdf.set_font('Arial', 'B', 16)
|
| 51 |
+
pdf.cell(0, 10, 'Content Analysis Report', 0, 1, 'C')
|
| 52 |
+
pdf.line(10, 30, 200, 30)
|
| 53 |
+
|
| 54 |
+
# Date
|
| 55 |
+
pdf.set_font('Arial', '', 10)
|
| 56 |
+
pdf.cell(0, 10, f'Generated on: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}', 0, 1)
|
| 57 |
+
|
| 58 |
+
# Content
|
| 59 |
+
pdf.set_font('Arial', 'B', 12)
|
| 60 |
+
pdf.cell(0, 10, 'Basic Statistics:', 0, 1)
|
| 61 |
+
pdf.set_font('Arial', '', 10)
|
| 62 |
+
|
| 63 |
+
stats = analysis_result.get('stats', {})
|
| 64 |
+
for key, value in stats.items():
|
| 65 |
+
pdf.cell(0, 10, f'{key.title()}: {value}', 0, 1)
|
| 66 |
+
|
| 67 |
+
if 'summary' in analysis_result:
|
| 68 |
+
pdf.set_font('Arial', 'B', 12)
|
| 69 |
+
pdf.cell(0, 10, 'Summary:', 0, 1)
|
| 70 |
+
pdf.set_font('Arial', '', 10)
|
| 71 |
+
pdf.multi_cell(0, 10, analysis_result['summary'])
|
| 72 |
+
|
| 73 |
+
# Save to temporary file
|
| 74 |
+
temp_dir = tempfile.gettempdir()
|
| 75 |
+
pdf_path = os.path.join(temp_dir, 'analysis_report.pdf')
|
| 76 |
+
pdf.output(pdf_path)
|
| 77 |
+
|
| 78 |
+
return pdf_path
|
| 79 |
+
|
| 80 |
+
def process_content(input_text, mode, theme, progress=gr.Progress()):
|
| 81 |
+
"""Main processing function with progress updates."""
|
| 82 |
+
try:
|
| 83 |
+
# Check cache
|
| 84 |
+
cache_key = f"{input_text}_{mode}"
|
| 85 |
+
if cache_key in analysis_cache:
|
| 86 |
+
return (
|
| 87 |
+
analysis_cache[cache_key],
|
| 88 |
+
"Content preview unavailable for cached results",
|
| 89 |
+
"Using cached results",
|
| 90 |
+
None
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# Process in steps
|
| 94 |
+
progress(0, desc="Initializing analysis...")
|
| 95 |
+
time.sleep(0.5) # Simulate processing
|
| 96 |
+
|
| 97 |
+
progress(0.3, desc="Fetching content...")
|
| 98 |
+
result = analyzer(input_text, mode)
|
| 99 |
+
analysis_result = json.loads(result)
|
| 100 |
+
|
| 101 |
+
progress(0.6, desc="Analyzing content...")
|
| 102 |
+
|
| 103 |
+
# Create visualization if sentiment mode
|
| 104 |
+
chart = None
|
| 105 |
+
if mode == "sentiment" and analysis_result.get('status') == 'success':
|
| 106 |
+
progress(0.8, desc="Generating visualizations...")
|
| 107 |
+
chart = create_sentiment_chart(analysis_result['sentiment_analysis'])
|
| 108 |
+
|
| 109 |
+
# Cache results
|
| 110 |
+
analysis_cache[cache_key] = analysis_result
|
| 111 |
+
|
| 112 |
+
# Generate preview text
|
| 113 |
+
preview = analysis_result.get('stats', {}).get('title', '')
|
| 114 |
+
if 'summary' in analysis_result:
|
| 115 |
+
preview += f"\n\nSummary:\n{analysis_result['summary']}"
|
| 116 |
+
|
| 117 |
+
progress(1.0, desc="Complete!")
|
| 118 |
+
return analysis_result, preview, "Analysis complete!", chart
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
return (
|
| 122 |
+
{"status": "error", "message": str(e)},
|
| 123 |
+
"Error occurred",
|
| 124 |
+
f"Error: {str(e)}",
|
| 125 |
+
None
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def create_interface():
|
| 129 |
+
with gr.Blocks(title="Smart Web Analyzer Plus", theme=gr.themes.Base()) as iface:
|
| 130 |
+
# Header
|
| 131 |
+
gr.Markdown("# π Smart Web Analyzer Plus")
|
| 132 |
+
gr.Markdown("""
|
| 133 |
+
Advanced content analysis with AI-powered insights:
|
| 134 |
+
* π Comprehensive Analysis
|
| 135 |
+
* π Detailed Sentiment Analysis
|
| 136 |
+
* π Smart Summarization
|
| 137 |
+
* π― Topic Detection
|
| 138 |
+
""")
|
| 139 |
+
|
| 140 |
+
# Theme toggle
|
| 141 |
+
with gr.Row():
|
| 142 |
+
theme = gr.Radio(
|
| 143 |
+
choices=["light", "dark"],
|
| 144 |
+
value="light",
|
| 145 |
+
label="Theme",
|
| 146 |
+
interactive=True
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# Main content
|
| 150 |
+
with gr.Tabs():
|
| 151 |
+
# Analysis Tab
|
| 152 |
+
with gr.Tab("Analysis"):
|
| 153 |
+
with gr.Row():
|
| 154 |
+
with gr.Column():
|
| 155 |
+
input_text = gr.Textbox(
|
| 156 |
+
label="URL or Text to Analyze",
|
| 157 |
+
placeholder="Enter URL or paste text",
|
| 158 |
+
lines=5
|
| 159 |
+
)
|
| 160 |
+
mode = gr.Radio(
|
| 161 |
+
choices=["analyze", "summarize", "sentiment", "topics"],
|
| 162 |
+
value="analyze",
|
| 163 |
+
label="Analysis Mode"
|
| 164 |
+
)
|
| 165 |
+
analyze_btn = gr.Button("π Analyze", variant="primary")
|
| 166 |
+
status = gr.Markdown("Status: Ready")
|
| 167 |
+
|
| 168 |
+
with gr.Column():
|
| 169 |
+
results = gr.JSON(label="Analysis Results")
|
| 170 |
+
chart = gr.Plot(label="Visualization", visible=False)
|
| 171 |
+
|
| 172 |
+
# Show/hide chart based on mode
|
| 173 |
+
mode.change(
|
| 174 |
+
lambda m: gr.update(visible=(m == "sentiment")),
|
| 175 |
+
inputs=[mode],
|
| 176 |
+
outputs=[chart]
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# Preview Tab
|
| 180 |
+
with gr.Tab("Preview"):
|
| 181 |
+
preview = gr.Textbox(
|
| 182 |
+
label="Content Preview",
|
| 183 |
+
lines=10,
|
| 184 |
+
interactive=False
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
# Report Tab
|
| 188 |
+
with gr.Tab("Report"):
|
| 189 |
+
download_btn = gr.Button("π₯ Download PDF Report")
|
| 190 |
+
pdf_output = gr.File(label="Generated Report")
|
| 191 |
+
|
| 192 |
+
# Examples
|
| 193 |
+
gr.Examples(
|
| 194 |
+
examples=[
|
| 195 |
+
["https://www.artificialintelligence-news.com/2024/02/14/openai-anthropic-google-white-house-red-teaming/", "analyze", "light"],
|
| 196 |
+
["https://www.artificialintelligence-news.com/2024/02/13/ai-21-labs-wordtune-chatgpt-plugin/", "sentiment", "light"]
|
| 197 |
+
],
|
| 198 |
+
inputs=[input_text, mode, theme],
|
| 199 |
+
outputs=[results, preview, status, chart],
|
| 200 |
+
fn=process_content,
|
| 201 |
+
cache_examples=True
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# Handle theme changes
|
| 205 |
+
theme.change(
|
| 206 |
+
lambda t: gr.update(theme=gr.themes.Base() if t == "light" else gr.themes.Soft()),
|
| 207 |
+
inputs=[theme],
|
| 208 |
+
outputs=[iface]
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
# Wire up the analysis button
|
| 212 |
+
analyze_btn.click(
|
| 213 |
+
fn=process_content,
|
| 214 |
+
inputs=[input_text, mode, theme],
|
| 215 |
+
outputs=[results, preview, status, chart]
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
# Wire up PDF download
|
| 219 |
+
download_btn.click(
|
| 220 |
+
fn=lambda: generate_pdf_report(json.loads(results.value)),
|
| 221 |
+
inputs=[],
|
| 222 |
+
outputs=[pdf_output]
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
return iface
|
| 226 |
+
|
| 227 |
+
demo = create_interface()
|
| 228 |
+
demo.launch()
|