MHamdan commited on
Commit
300162c
·
1 Parent(s): 7eed016

Initial commit with full functionality extend app req tools

Browse files
Files changed (3) hide show
  1. Gradio_UI.py +106 -116
  2. app.py +9 -26
  3. requirements.txt +2 -16
Gradio_UI.py CHANGED
@@ -1,157 +1,147 @@
1
  # Gradio_UI.py
2
  import gradio as gr
3
- from smolagents import CodeAgent
4
- from typing import Optional, List, Tuple
5
- import logging
6
- from bs4 import BeautifulSoup
7
  import requests
8
- import json
 
 
9
 
 
10
  logger = logging.getLogger(__name__)
11
 
12
- class GradioUI:
13
- def __init__(self, agent: CodeAgent):
14
  self.agent = agent
15
 
16
- def fetch_content(self, url: str) -> str:
17
- """Fetch content from URL."""
18
  try:
19
- response = requests.get(url)
20
  response.raise_for_status()
21
  soup = BeautifulSoup(response.text, 'html.parser')
22
- return soup.get_text()
 
 
 
 
 
 
 
23
  except Exception as e:
24
- logger.error(f"Error fetching URL: {str(e)}")
25
- return f"Error fetching content: {str(e)}"
26
-
27
- def analyze_content(self, content: str, analysis_types: List[str]) -> dict:
28
- """Analyze the content based on selected analysis types."""
29
- results = {
30
- 'clean_text': content[:1000] + '...' if len(content) > 1000 else content,
31
- 'summary': '',
32
- 'sentiment': '',
33
- 'topics': ''
34
- }
35
 
36
- try:
37
- if 'summarize' in analysis_types:
38
- results['summary'] = self.agent.run(f"Summarize this text: {content[:2000]}")
39
-
40
- if 'sentiment' in analysis_types:
41
- results['sentiment'] = self.agent.run(f"Analyze the sentiment of this text: {content[:2000]}")
42
-
43
- if 'topics' in analysis_types:
44
- results['topics'] = self.agent.run(f"Identify the main topics in this text: {content[:2000]}")
45
-
46
- except Exception as e:
47
- logger.error(f"Error in analysis: {str(e)}")
48
- return {
49
- 'error': str(e),
50
- 'clean_text': 'Analysis failed',
51
- 'summary': '',
52
- 'sentiment': '',
53
- 'topics': ''
54
- }
55
-
56
- return results
57
-
58
- def process_url(self, url: str, analysis_types: List[str]) -> Tuple[str, str, str, str]:
59
- """Process URL and return analysis results."""
60
  try:
61
  # Fetch content
62
- content = self.fetch_content(url)
63
-
64
- # Analyze content
65
- results = self.analyze_content(content, analysis_types)
66
-
67
- # Return results for each tab
68
- return (
69
- results.get('clean_text', ''),
70
- results.get('summary', ''),
71
- results.get('sentiment', ''),
72
- results.get('topics', '')
73
- )
 
 
 
 
 
 
 
 
 
 
74
  except Exception as e:
75
- error_msg = f"Error: {str(e)}"
76
- return error_msg, error_msg, error_msg, error_msg
 
77
 
78
- def launch(self,
79
- server_name: Optional[str] = None,
80
- server_port: Optional[int] = None,
81
- share: bool = False):
82
- """Launch the Gradio interface."""
 
 
 
 
 
 
83
 
84
- with gr.Blocks(title="Smart Web Analyzer Plus") as demo:
85
- # Header
86
- gr.Markdown("# 🌐 Smart Web Analyzer Plus")
 
 
 
 
 
 
87
  gr.Markdown("Analyze web content using AI to extract summaries, determine sentiment, and identify topics.")
88
-
89
- # Input section
90
  with gr.Row():
91
- url_input = gr.Textbox(
92
- label="Enter URL",
93
- placeholder="https://example.com",
94
- scale=3
95
- )
96
- analysis_types = gr.CheckboxGroup(
97
- choices=["summarize", "sentiment", "topics"],
98
- value=["summarize"],
99
- label="Analysis Types",
100
- scale=2
101
- )
102
- analyze_btn = gr.Button(
103
- "Analyze",
104
- variant="primary",
105
- scale=1
106
- )
107
-
108
- # Progress indicator
109
- progress = gr.Markdown(visible=False)
110
-
111
- # Results section - using a single Tabs component
112
- with gr.Tabs() as output_tabs:
113
- with gr.Tab("Clean Text", id="clean_text"):
114
  clean_text_output = gr.Markdown()
115
- with gr.Tab("Summary", id="summary"):
116
  summary_output = gr.Markdown()
117
- with gr.Tab("Sentiment", id="sentiment"):
118
  sentiment_output = gr.Markdown()
119
- with gr.Tab("Topics", id="topics"):
120
  topics_output = gr.Markdown()
121
-
122
  # Examples
123
  gr.Examples(
124
  examples=[
125
  ["https://www.bbc.com/news/technology-67881954", ["summarize", "sentiment"]],
126
  ["https://arxiv.org/html/2312.17296v1", ["topics", "summarize"]]
127
  ],
128
- inputs=[url_input, analysis_types]
129
  )
130
-
131
  # Event handlers
132
- def show_progress():
133
- return gr.update(value="⏳ Analysis in progress...", visible=True)
134
-
135
- def hide_progress():
136
- return gr.update(value="", visible=False)
137
-
138
- # Connect the button click event
139
- analyze_btn.click(
140
- fn=show_progress,
141
- outputs=progress
142
  ).then(
143
- fn=self.process_url,
144
  inputs=[url_input, analysis_types],
145
  outputs=[clean_text_output, summary_output, sentiment_output, topics_output]
146
  ).then(
147
- fn=hide_progress,
148
- outputs=progress
149
  )
150
-
151
- # Launch the interface
 
 
 
 
152
  demo.launch(
153
  server_name=server_name,
154
  server_port=server_port,
155
- share=share,
156
- debug=True
157
  )
 
1
  # Gradio_UI.py
2
  import gradio as gr
 
 
 
 
3
  import requests
4
+ from bs4 import BeautifulSoup
5
+ import logging
6
+ from typing import List, Tuple
7
 
8
+ logging.basicConfig(level=logging.INFO)
9
  logger = logging.getLogger(__name__)
10
 
11
+ class WebAnalyzer:
12
+ def __init__(self, agent):
13
  self.agent = agent
14
 
15
+ def fetch_webpage(self, url: str) -> str:
16
+ """Fetch and extract text content from a webpage."""
17
  try:
18
+ response = requests.get(url, timeout=10)
19
  response.raise_for_status()
20
  soup = BeautifulSoup(response.text, 'html.parser')
21
+ # Remove script and style elements
22
+ for script in soup(["script", "style"]):
23
+ script.decompose()
24
+ text = soup.get_text(separator='\n')
25
+ # Clean up whitespace
26
+ lines = (line.strip() for line in text.splitlines())
27
+ text = '\n'.join(line for line in lines if line)
28
+ return text
29
  except Exception as e:
30
+ logger.error(f"Error fetching webpage: {e}")
31
+ return f"Error: Failed to fetch webpage - {str(e)}"
 
 
 
 
 
 
 
 
 
32
 
33
+ def analyze_content(self, url: str, analysis_types: List[str]) -> Tuple[str, str, str, str]:
34
+ """Analyze webpage content based on selected analysis types."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  try:
36
  # Fetch content
37
+ content = self.fetch_webpage(url)
38
+ if content.startswith("Error:"):
39
+ return content, "", "", ""
40
+
41
+ # Initialize results
42
+ clean_text = content[:2000] + "..." if len(content) > 2000 else content
43
+ summary = ""
44
+ sentiment = ""
45
+ topics = ""
46
+
47
+ # Perform selected analyses
48
+ if "summarize" in analysis_types:
49
+ summary = self.agent.run(f"Please summarize this text concisely: {clean_text}")
50
+
51
+ if "sentiment" in analysis_types:
52
+ sentiment = self.agent.run(f"Analyze the sentiment of this text: {clean_text}")
53
+
54
+ if "topics" in analysis_types:
55
+ topics = self.agent.run(f"Identify and list the main topics in this text: {clean_text}")
56
+
57
+ return clean_text, summary, sentiment, topics
58
+
59
  except Exception as e:
60
+ error_msg = f"Error during analysis: {str(e)}"
61
+ logger.error(error_msg)
62
+ return error_msg, "", "", ""
63
 
64
+ class GradioUI:
65
+ def __init__(self, agent):
66
+ self.analyzer = WebAnalyzer(agent)
67
+
68
+ def create_interface(self):
69
+ """Create the Gradio interface."""
70
+ # Create interface components
71
+ url_input = gr.Textbox(
72
+ label="Enter URL",
73
+ placeholder="https://example.com"
74
+ )
75
 
76
+ analysis_types = gr.CheckboxGroup(
77
+ choices=["summarize", "sentiment", "topics"],
78
+ value=["summarize"],
79
+ label="Analysis Types"
80
+ )
81
+
82
+ # Create output components
83
+ with gr.Blocks() as demo:
84
+ gr.Markdown("# Smart Web Analyzer Plus")
85
  gr.Markdown("Analyze web content using AI to extract summaries, determine sentiment, and identify topics.")
86
+
 
87
  with gr.Row():
88
+ with gr.Column(scale=4):
89
+ url_input.render()
90
+ with gr.Column(scale=2):
91
+ analysis_types.render()
92
+ with gr.Column(scale=1):
93
+ analyze_button = gr.Button("Analyze", variant="primary")
94
+
95
+ # Status indicator
96
+ status = gr.Markdown(visible=False)
97
+
98
+ # Output tabs
99
+ with gr.Tabs():
100
+ with gr.Tab("Clean Text"):
 
 
 
 
 
 
 
 
 
 
101
  clean_text_output = gr.Markdown()
102
+ with gr.Tab("Summary"):
103
  summary_output = gr.Markdown()
104
+ with gr.Tab("Sentiment"):
105
  sentiment_output = gr.Markdown()
106
+ with gr.Tab("Topics"):
107
  topics_output = gr.Markdown()
108
+
109
  # Examples
110
  gr.Examples(
111
  examples=[
112
  ["https://www.bbc.com/news/technology-67881954", ["summarize", "sentiment"]],
113
  ["https://arxiv.org/html/2312.17296v1", ["topics", "summarize"]]
114
  ],
115
+ inputs=[url_input, analysis_types],
116
  )
117
+
118
  # Event handlers
119
+ def on_analyze_click(url, types):
120
+ if not url:
121
+ return "Please enter a URL", "", "", ""
122
+ if not types:
123
+ return "Please select at least one analysis type", "", "", ""
124
+ return self.analyzer.analyze_content(url, types)
125
+
126
+ analyze_button.click(
127
+ fn=lambda: gr.Markdown("⏳ Analysis in progress...", visible=True),
128
+ outputs=[status]
129
  ).then(
130
+ fn=on_analyze_click,
131
  inputs=[url_input, analysis_types],
132
  outputs=[clean_text_output, summary_output, sentiment_output, topics_output]
133
  ).then(
134
+ fn=lambda: gr.Markdown("", visible=False),
135
+ outputs=[status]
136
  )
137
+
138
+ return demo
139
+
140
+ def launch(self, server_name=None, server_port=None, share=False):
141
+ """Launch the Gradio interface."""
142
+ demo = self.create_interface()
143
  demo.launch(
144
  server_name=server_name,
145
  server_port=server_port,
146
+ share=share
 
147
  )
app.py CHANGED
@@ -1,32 +1,18 @@
1
  # app.py
2
  from smolagents import CodeAgent, HfApiModel
3
- from tools.final_answer import FinalAnswerTool
4
- import yaml
5
- from Gradio_UI import GradioUI
6
  import logging
7
- import sys
8
 
9
  # Configure logging
10
  logging.basicConfig(
11
  level=logging.INFO,
12
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
13
- handlers=[
14
- logging.StreamHandler(sys.stdout),
15
- logging.FileHandler('app.log')
16
- ]
17
  )
18
  logger = logging.getLogger(__name__)
19
 
20
  def create_agent():
21
  """Create and configure the agent."""
22
  try:
23
- # Initialize tools
24
- final_answer = FinalAnswerTool()
25
-
26
- # Load prompts
27
- with open("prompts.yaml", 'r', encoding='utf-8') as stream:
28
- prompt_templates = yaml.safe_load(stream)
29
-
30
  # Initialize model
31
  model = HfApiModel(
32
  model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
@@ -34,16 +20,14 @@ def create_agent():
34
  temperature=0.5
35
  )
36
 
37
- # Create agent
38
  return CodeAgent(
39
  model=model,
40
- tools=[final_answer],
41
- max_steps=6,
42
- verbosity_level=1,
43
- prompt_templates=prompt_templates
44
  )
45
  except Exception as e:
46
- logger.error(f"Failed to create agent: {str(e)}")
47
  raise
48
 
49
  def main():
@@ -59,12 +43,11 @@ def main():
59
  ui = GradioUI(agent)
60
  ui.launch(
61
  server_name="0.0.0.0",
62
- server_port=7860,
63
- share=False
64
  )
65
  except Exception as e:
66
- logger.error(f"Application failed to start: {str(e)}")
67
- sys.exit(1)
68
 
69
  if __name__ == "__main__":
70
  main()
 
1
  # app.py
2
  from smolagents import CodeAgent, HfApiModel
 
 
 
3
  import logging
4
+ from Gradio_UI import GradioUI
5
 
6
  # Configure logging
7
  logging.basicConfig(
8
  level=logging.INFO,
9
+ format='%(asctime)s - %(levelname)s - %(message)s'
 
 
 
 
10
  )
11
  logger = logging.getLogger(__name__)
12
 
13
  def create_agent():
14
  """Create and configure the agent."""
15
  try:
 
 
 
 
 
 
 
16
  # Initialize model
17
  model = HfApiModel(
18
  model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
 
20
  temperature=0.5
21
  )
22
 
23
+ # Create agent with simple configuration
24
  return CodeAgent(
25
  model=model,
26
+ max_steps=3,
27
+ verbosity_level=1
 
 
28
  )
29
  except Exception as e:
30
+ logger.error(f"Failed to create agent: {e}")
31
  raise
32
 
33
  def main():
 
43
  ui = GradioUI(agent)
44
  ui.launch(
45
  server_name="0.0.0.0",
46
+ server_port=7860
 
47
  )
48
  except Exception as e:
49
+ logger.error(f"Application failed to start: {e}")
50
+ raise
51
 
52
  if __name__ == "__main__":
53
  main()
requirements.txt CHANGED
@@ -1,20 +1,6 @@
1
  # requirements.txt
2
- smolagents>=0.2.0
3
  gradio>=4.0.0
4
  requests>=2.31.0
5
- pytz>=2023.3
6
- pyyaml>=6.0.1
7
- python-dotenv>=1.0.0
8
  beautifulsoup4>=4.12.2
9
- numpy>=1.24.3
10
- pandas>=2.0.3
11
- scikit-learn>=1.3.0
12
- nltk>=3.8.1
13
- spacy>=3.7.2
14
- transformers>=4.35.0
15
- torch>=2.0.1
16
- tqdm>=4.65.0
17
- validators>=0.22.0
18
- aiohttp>=3.8.5
19
- cachetools>=5.3.1
20
- python-dateutil>=2.8.2
 
1
  # requirements.txt
 
2
  gradio>=4.0.0
3
  requests>=2.31.0
 
 
 
4
  beautifulsoup4>=4.12.2
5
+ smolagents>=0.2.0
6
+ python-dotenv>=1.0.0