MHamdan commited on
Commit
4ec04a7
Β·
verified Β·
1 Parent(s): 3efce00

Upload tool

Browse files
Files changed (3) hide show
  1. app.py +6 -0
  2. requirements.txt +4 -0
  3. tool.py +209 -0
app.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from smolagents import launch_gradio_demo
2
+ from tool import SimpleTool
3
+
4
+ tool = SimpleTool()
5
+
6
+ launch_gradio_demo(tool)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ bs4
2
+ requests
3
+ transformers
4
+ smolagents
tool.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import Tool
2
+ from typing import Any, Optional
3
+
4
+ class SimpleTool(Tool):
5
+ name = "advanced_web_analyzer"
6
+ description = "Advanced web content analyzer with ML-powered analysis capabilities."
7
+ inputs = {"url":{"type":"string","description":"The webpage URL to analyze."},"analysis_mode":{"type":"string","nullable":True,"description":"Analysis mode ('analyze', 'search', 'summarize', 'sentiment', 'topics')."},"query":{"type":"string","nullable":True,"description":"Optional search term for 'search' mode."},"language":{"type":"string","nullable":True,"description":"Content language (default: 'en')."}}
8
+ output_type = "string"
9
+
10
+ def forward(self, url: str,
11
+ analysis_mode: str = "analyze",
12
+ query: Optional[str] = None,
13
+ language: str = "en") -> str:
14
+ """Advanced web content analyzer with ML-powered analysis capabilities.
15
+
16
+ Args:
17
+ url: The webpage URL to analyze.
18
+ analysis_mode: Analysis mode ('analyze', 'search', 'summarize', 'sentiment', 'topics').
19
+ query: Optional search term for 'search' mode.
20
+ language: Content language (default: 'en').
21
+
22
+ Returns:
23
+ str: Advanced analysis of web content.
24
+ """
25
+ import requests
26
+ from bs4 import BeautifulSoup
27
+ from urllib.parse import urlparse
28
+ import re
29
+ from collections import Counter
30
+ from transformers import pipeline
31
+
32
+ try:
33
+ # Validate URL
34
+ parsed_url = urlparse(url)
35
+ if not all([parsed_url.scheme, parsed_url.netloc]):
36
+ return "Error: Invalid URL format. Please provide a valid URL."
37
+
38
+ # Fetch webpage
39
+ headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
40
+ response = requests.get(url, headers=headers, timeout=10)
41
+ response.raise_for_status()
42
+
43
+ # Parse content
44
+ soup = BeautifulSoup(response.text, 'html.parser')
45
+ for tag in soup(['script', 'style', 'meta']):
46
+ tag.decompose()
47
+
48
+ # Extract basic elements
49
+ title = soup.title.string if soup.title else "No title found"
50
+ title = re.sub(r'\s+', ' ', title).strip() if title else "No title found"
51
+
52
+ text_content = soup.get_text()
53
+ text_content = re.sub(r'\s+', ' ', text_content).strip()
54
+
55
+ # Process based on mode
56
+ if analysis_mode == "analyze":
57
+ # Initialize ML pipelines
58
+ summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
59
+ classifier = pipeline("text-classification", model="nlptown/bert-base-multilingual-uncased-sentiment")
60
+
61
+ # Get word statistics
62
+ words = text_content.lower().split()
63
+ word_count = len(words)
64
+ word_freq = Counter(words).most_common(5)
65
+ common_words = ""
66
+ for word, count in word_freq:
67
+ common_words += f"- {word}: {count} times\n"
68
+
69
+ # Get summary
70
+ summary = summarizer(text_content[:1024], max_length=100, min_length=30)[0]['summary_text']
71
+
72
+ # Get sentiment
73
+ sentiment = classifier(text_content[:512])[0]
74
+ sentiment_score = int(sentiment['label'][0]) # Convert '5 stars' to number
75
+ sentiment_desc = ["Very Negative", "Negative", "Neutral", "Positive", "Very Positive"][sentiment_score-1]
76
+
77
+ # Format comprehensive analysis
78
+ return f"""πŸ” Comprehensive Content Analysis
79
+
80
+ πŸ“‘ Basic Information:
81
+ Title: {title}
82
+ Word Count: {word_count}
83
+ Reading Time: {word_count // 200} minutes
84
+
85
+ πŸ“ Quick Summary:
86
+ {summary}
87
+
88
+ 😊 Content Sentiment:
89
+ {sentiment_desc} ({sentiment_score}/5 stars)
90
+
91
+ πŸ“Š Most Common Words:
92
+ {common_words}"""
93
+
94
+ elif analysis_mode == "summarize":
95
+ # Use BART for better summarization
96
+ summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
97
+
98
+ # Split into chunks if text is too long
99
+ chunks = [text_content[i:i+1024] for i in range(0, len(text_content), 1024)]
100
+ summaries = []
101
+
102
+ for chunk in chunks[:3]: # Process up to 3 chunks
103
+ if len(chunk.strip()) > 100:
104
+ summary = summarizer(chunk, max_length=100, min_length=30)[0]['summary_text']
105
+ summaries.append(summary)
106
+
107
+ return f"""πŸ“ Content Summary for: {title}
108
+
109
+ {' '.join(summaries)}"""
110
+
111
+ elif analysis_mode == "sentiment":
112
+ # Use multilingual sentiment analyzer
113
+ classifier = pipeline("text-classification", model="nlptown/bert-base-multilingual-uncased-sentiment")
114
+
115
+ # Analyze main content and paragraphs
116
+ main_sentiment = classifier(text_content[:512])[0]
117
+
118
+ # Analyze individual paragraphs
119
+ paragraphs = soup.find_all('p')
120
+ detailed_sentiments = ""
121
+ para_count = 0
122
+
123
+ for p in paragraphs:
124
+ text = p.text.strip()
125
+ if len(text) > 50: # Only analyze meaningful paragraphs
126
+ sentiment = classifier(text[:512])[0]
127
+ score = int(sentiment['label'][0])
128
+ mood = ["Very Negative", "Negative", "Neutral", "Positive", "Very Positive"][score-1]
129
+ detailed_sentiments += f"\nParagraph {para_count + 1}: {mood} ({score}/5)"
130
+ para_count += 1
131
+ if para_count >= 5: # Limit to 5 paragraphs
132
+ break
133
+
134
+ return f"""😊 Sentiment Analysis
135
+
136
+ Overall Sentiment: {["Very Negative", "Negative", "Neutral", "Positive", "Very Positive"][int(main_sentiment['label'][0])-1]}
137
+ Overall Score: {main_sentiment['label'][0]}/5
138
+
139
+ Detailed Analysis:{detailed_sentiments}"""
140
+
141
+ elif analysis_mode == "topics":
142
+ # Use Zero-shot classification for topic detection
143
+ classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
144
+
145
+ # Define potential topics
146
+ topics = [
147
+ "Technology", "Business", "Politics", "Science",
148
+ "Health", "Entertainment", "Sports", "Education",
149
+ "Environment", "Culture"
150
+ ]
151
+
152
+ # Analyze main content
153
+ topic_results = classifier(text_content[:512], topics)
154
+
155
+ # Format results
156
+ topic_analysis = "Main Topics:\n"
157
+ for topic, score in zip(topic_results['labels'], topic_results['scores']):
158
+ if score > 0.1: # Only show relevant topics
159
+ topic_analysis += f"- {topic}: {score*100:.1f}% confidence\n"
160
+
161
+ # Get key phrases
162
+ from keybert import KeyBERT
163
+ kw_model = KeyBERT()
164
+ keywords = kw_model.extract_keywords(text_content[:5000], keyphrase_ngram_range=(1, 2), stop_words='english', top_n=5)
165
+
166
+ key_phrases = "\nKey Phrases:\n"
167
+ for phrase, score in keywords:
168
+ key_phrases += f"- {phrase}: {score:.2f} relevance\n"
169
+
170
+ return f"""🎯 Topic Analysis
171
+
172
+ {topic_analysis}
173
+ {key_phrases}"""
174
+
175
+ elif analysis_mode == "search":
176
+ if not query:
177
+ return "Error: Search query is required for search mode."
178
+
179
+ # Use transformers for better search
180
+ qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
181
+
182
+ # Search in paragraphs
183
+ paragraphs = soup.find_all('p')
184
+ search_results = ""
185
+ result_count = 0
186
+
187
+ for p in paragraphs:
188
+ text = p.text.strip()
189
+ if len(text) > 50 and query.lower() in text.lower():
190
+ # Get AI-enhanced answer
191
+ qa_result = qa_pipeline(question=query, context=text)
192
+ search_results += f"\n{result_count + 1}. Found in context: {qa_result['answer']}\n"
193
+ search_results += f" Confidence: {qa_result['score']:.2%}\n"
194
+ search_results += f" Full context: {text}\n"
195
+ result_count += 1
196
+ if result_count >= 3:
197
+ break
198
+
199
+ if not search_results:
200
+ return f"No matches found for '{query}'"
201
+
202
+ return f"""πŸ” AI-Enhanced Search Results for '{query}':
203
+ {search_results}"""
204
+
205
+ else:
206
+ return f"Error: Unknown mode '{analysis_mode}'"
207
+
208
+ except Exception as e:
209
+ return f"Error processing webpage: {str(e)}"