shukdevdatta123 commited on
Commit
93fb7cb
Β·
verified Β·
1 Parent(s): 3318350

Create app,py

Browse files
Files changed (1) hide show
  1. app,py +304 -0
app,py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ from openai import OpenAI
5
+ import json
6
+ import re
7
+ from urllib.parse import urljoin, urlparse
8
+ import time
9
+
10
+ class WebScrapingTool:
11
+ def __init__(self):
12
+ self.client = None
13
+ self.system_prompt = """You are a specialized web data extraction assistant. Your core purpose is to browse and analyze the content of web pages based on user instructions, and return structured or unstructured information from the provided URL. Your capabilities include:
14
+
15
+ 1. Navigating and reading web page content from a given URL.
16
+ 2. Extracting textual content including headings, paragraphs, lists, and metadata.
17
+ 3. Identifying and extracting HTML tables and presenting them in a clean, structured format.
18
+ 4. Creating new, custom tables based on user queries by processing, reorganizing, or filtering the content found on the source page.
19
+
20
+ You must always follow these guidelines:
21
+ - Accurately extract and summarize both structured (tables, lists) and unstructured (paragraphs, articles) content.
22
+ - Clearly separate different types of data (e.g., summaries, tables, bullet points).
23
+ - When extracting textual content:
24
+ - Maintain original meaning, structure, and tone.
25
+ - Capture all relevant sections based on user instructions (e.g., only the "Overview" or "Methodology" sections).
26
+ - When extracting tables:
27
+ - Preserve headers and align row data correctly.
28
+ - Identify and differentiate multiple tables, if present.
29
+ - When creating custom tables:
30
+ - Include only the relevant columns as per the user request.
31
+ - Sort, filter, and reorganize data accordingly.
32
+ - Use clear and consistent headers.
33
+
34
+ You must not hallucinate or infer data not present on the page. If content is missing, unclear, or restricted, say so explicitly.
35
+
36
+ Always respond based on the actual content from the provided link. If the page fails to load or cannot be accessed, inform the user immediately.
37
+
38
+ Your role is to act as an intelligent browser and data interpreter β€” able to read and reshape any web content to meet user needs."""
39
+
40
+ def setup_client(self, api_key):
41
+ """Initialize OpenAI client with OpenRouter"""
42
+ try:
43
+ self.client = OpenAI(
44
+ base_url="https://openrouter.ai/api/v1",
45
+ api_key=api_key,
46
+ )
47
+ return True, "API client initialized successfully!"
48
+ except Exception as e:
49
+ return False, f"Failed to initialize API client: {str(e)}"
50
+
51
+ def scrape_webpage(self, url):
52
+ """Scrape webpage content"""
53
+ try:
54
+ headers = {
55
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
56
+ }
57
+
58
+ response = requests.get(url, headers=headers, timeout=30)
59
+ response.raise_for_status()
60
+
61
+ soup = BeautifulSoup(response.content, 'html.parser')
62
+
63
+ # Remove script and style elements
64
+ for script in soup(["script", "style", "nav", "footer", "header"]):
65
+ script.decompose()
66
+
67
+ # Extract text content
68
+ text_content = soup.get_text()
69
+
70
+ # Clean up text
71
+ lines = (line.strip() for line in text_content.splitlines())
72
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
73
+ text_content = ' '.join(chunk for chunk in chunks if chunk)
74
+
75
+ # Extract tables
76
+ tables = []
77
+ for table in soup.find_all('table'):
78
+ table_data = []
79
+ headers = []
80
+
81
+ # Extract headers
82
+ header_row = table.find('tr')
83
+ if header_row:
84
+ headers = [th.get_text().strip() for th in header_row.find_all(['th', 'td'])]
85
+
86
+ # Extract rows
87
+ for row in table.find_all('tr')[1:]: # Skip header row
88
+ row_data = [td.get_text().strip() for td in row.find_all(['td', 'th'])]
89
+ if row_data:
90
+ table_data.append(row_data)
91
+
92
+ if headers and table_data:
93
+ tables.append({
94
+ 'headers': headers,
95
+ 'data': table_data
96
+ })
97
+
98
+ return {
99
+ 'success': True,
100
+ 'text': text_content[:15000], # Limit text length
101
+ 'tables': tables,
102
+ 'title': soup.title.string if soup.title else "No title found"
103
+ }
104
+
105
+ except requests.RequestException as e:
106
+ return {
107
+ 'success': False,
108
+ 'error': f"Failed to fetch webpage: {str(e)}"
109
+ }
110
+ except Exception as e:
111
+ return {
112
+ 'success': False,
113
+ 'error': f"Error processing webpage: {str(e)}"
114
+ }
115
+
116
+ def analyze_content(self, scraped_data, user_query, api_key):
117
+ """Analyze scraped content using DeepSeek V3"""
118
+ if not self.client:
119
+ success, message = self.setup_client(api_key)
120
+ if not success:
121
+ return f"Error: {message}"
122
+
123
+ if not scraped_data['success']:
124
+ return f"Error scraping webpage: {scraped_data['error']}"
125
+
126
+ # Prepare content for AI analysis
127
+ content_text = f"""
128
+ WEBPAGE CONTENT:
129
+ Title: {scraped_data['title']}
130
+
131
+ Main Text Content:
132
+ {scraped_data['text']}
133
+
134
+ Tables Found: {len(scraped_data['tables'])}
135
+ """
136
+
137
+ if scraped_data['tables']:
138
+ content_text += "\n\nTABLES:\n"
139
+ for i, table in enumerate(scraped_data['tables']):
140
+ content_text += f"\nTable {i+1}:\n"
141
+ content_text += f"Headers: {', '.join(table['headers'])}\n"
142
+ content_text += "Data:\n"
143
+ for row in table['data'][:10]: # Limit rows
144
+ content_text += f" {' | '.join(row)}\n"
145
+
146
+ try:
147
+ completion = self.client.chat.completions.create(
148
+ extra_headers={
149
+ "HTTP-Referer": "https://gradio-web-scraper.com",
150
+ "X-Title": "AI Web Scraping Tool",
151
+ },
152
+ model="deepseek/deepseek-chat-v3-0324:free",
153
+ messages=[
154
+ {"role": "system", "content": self.system_prompt},
155
+ {"role": "user", "content": f"Here is the webpage content:\n\n{content_text}\n\nUser Query: {user_query}"}
156
+ ],
157
+ temperature=0.1,
158
+ max_tokens=4000
159
+ )
160
+
161
+ return completion.choices[0].message.content
162
+
163
+ except Exception as e:
164
+ return f"Error analyzing content: {str(e)}"
165
+
166
+ def create_interface():
167
+ tool = WebScrapingTool()
168
+
169
+ def process_request(api_key, url, user_query):
170
+ if not api_key.strip():
171
+ return "❌ Please enter your OpenRouter API key"
172
+
173
+ if not url.strip():
174
+ return "❌ Please enter a valid URL"
175
+
176
+ if not user_query.strip():
177
+ return "❌ Please enter your analysis query"
178
+
179
+ # Add progress updates
180
+ yield "πŸ”„ Scraping webpage content..."
181
+
182
+ # Scrape webpage
183
+ scraped_data = tool.scrape_webpage(url)
184
+
185
+ if not scraped_data['success']:
186
+ yield f"❌ {scraped_data['error']}"
187
+ return
188
+
189
+ yield f"βœ… Successfully scraped webpage!\nπŸ“„ Title: {scraped_data['title']}\nπŸ“Š Found {len(scraped_data['tables'])} tables\n\nπŸ€– Analyzing content with DeepSeek V3..."
190
+
191
+ # Analyze content
192
+ result = tool.analyze_content(scraped_data, user_query, api_key)
193
+
194
+ yield f"βœ… Analysis Complete!\n\n{result}"
195
+
196
+ # Create Gradio interface
197
+ with gr.Blocks(title="AI Web Scraping Tool", theme=gr.themes.Soft()) as app:
198
+ gr.Markdown("""
199
+ # πŸ€– AI Web Scraping Tool
200
+ ### Powered by DeepSeek V3 & OpenRouter
201
+
202
+ Extract and analyze web content using advanced AI. Simply provide your OpenRouter API key, a URL, and describe what you want to extract.
203
+ """)
204
+
205
+ with gr.Row():
206
+ with gr.Column(scale=2):
207
+ api_key_input = gr.Textbox(
208
+ label="πŸ”‘ OpenRouter API Key",
209
+ placeholder="Enter your OpenRouter API key here...",
210
+ type="password",
211
+ info="Get your free API key from openrouter.ai"
212
+ )
213
+
214
+ url_input = gr.Textbox(
215
+ label="🌐 Website URL",
216
+ placeholder="https://example.com",
217
+ info="Enter the URL you want to scrape and analyze"
218
+ )
219
+
220
+ query_input = gr.Textbox(
221
+ label="πŸ“ Analysis Query",
222
+ placeholder="What do you want to extract? (e.g., 'Extract main points and create a summary table')",
223
+ lines=3,
224
+ info="Describe what information you want to extract from the webpage"
225
+ )
226
+
227
+ with gr.Row():
228
+ analyze_btn = gr.Button("πŸš€ Analyze Website", variant="primary", size="lg")
229
+ clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
230
+
231
+ with gr.Column(scale=3):
232
+ output = gr.Textbox(
233
+ label="πŸ“Š Analysis Results",
234
+ lines=20,
235
+ max_lines=30,
236
+ show_copy_button=True,
237
+ interactive=False
238
+ )
239
+
240
+ # Example queries
241
+ gr.Markdown("""
242
+ ### πŸ’‘ Example Queries:
243
+ - *"Extract the main summary and any data tables"*
244
+ - *"Create a table of key statistics mentioned in the article"*
245
+ - *"Summarize the main points in bullet format"*
246
+ - *"Extract all numerical data and organize it in a table"*
247
+ - *"Find and extract contact information and company details"*
248
+ """)
249
+
250
+ # Example websites
251
+ with gr.Accordion("πŸ“‹ Try These Example URLs", open=False):
252
+ examples = [
253
+ ["https://www.imf.org/en/Publications/WEO", "Extract economic outlook summary and GDP projections"],
254
+ ["https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)", "Create a table of top 10 countries by GDP"],
255
+ ["https://www.who.int/news", "Summarize the latest health news"],
256
+ ["https://www.nasdaq.com/market-activity/stocks", "Extract stock market data and trends"]
257
+ ]
258
+
259
+ for url, query in examples:
260
+ gr.Markdown(f"**URL:** `{url}` \n**Query:** *{query}*")
261
+
262
+ # Event handlers
263
+ analyze_btn.click(
264
+ fn=process_request,
265
+ inputs=[api_key_input, url_input, query_input],
266
+ outputs=output,
267
+ show_progress=True
268
+ )
269
+
270
+ clear_btn.click(
271
+ fn=lambda: ("", "", "", ""),
272
+ outputs=[api_key_input, url_input, query_input, output]
273
+ )
274
+
275
+ # Auto-fill example
276
+ def fill_example():
277
+ return (
278
+ "", # API key remains empty
279
+ "https://www.imf.org/en/Publications/WEO/Issues/2024/04/16/world-economic-outlook-april-2024",
280
+ """1. Extract a summary of the main economic outlook from this page.
281
+ 2. Extract any available tables or figures with global GDP growth projections.
282
+ 3. Create a new table showing:
283
+ - Country/Region
284
+ - Projected GDP Growth (2024)
285
+ - Change from Previous Forecast (if available)
286
+ 4. Highlight the top 3 fastest-growing economies in a separate mini-table."""
287
+ )
288
+
289
+ example_btn = gr.Button("πŸ“‹ Load IMF Example", variant="secondary")
290
+ example_btn.click(
291
+ fn=fill_example,
292
+ outputs=[url_input, query_input]
293
+ )
294
+
295
+ return app
296
+
297
+ if __name__ == "__main__":
298
+ # Create and launch the app
299
+ app = create_interface()
300
+
301
+ # Launch with public sharing enabled
302
+ app.launch(
303
+ share=True,
304
+ )