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
 
 
 
1
+ """
2
+ Web utilities for search, content extraction, and URL handling.
3
+ """
4
+
5
+ import os
6
+ import re
7
+ import requests
8
+ from urllib.parse import urlparse, urljoin
9
+ from bs4 import BeautifulSoup
10
+ import html2text
11
+ from typing import Optional, Dict, Tuple, List
12
+ import time
13
+
14
+ from tavily import TavilyClient
15
+ from config import TAVILY_API_KEY
16
+
17
+ # Initialize Tavily client if API key is available
18
+ tavily_client = None
19
+ if TAVILY_API_KEY:
20
+ try:
21
+ tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
22
+ print("[WebUtils] Tavily client initialized successfully")
23
+ except Exception as e:
24
+ print(f"[WebUtils] Failed to initialize Tavily client: {e}")
25
+ tavily_client = None
26
+ else:
27
+ print("[WebUtils] Tavily API key not found - web search will be unavailable")
28
+
29
+ class WebContentExtractor:
30
+ """Handles web content extraction and processing"""
31
+
32
+ @staticmethod
33
+ def extract_website_content(url: str) -> str:
34
+ """Extract HTML code and content from a website URL"""
35
+ try:
36
+ # Validate and normalize URL
37
+ parsed_url = urlparse(url)
38
+ if not parsed_url.scheme:
39
+ url = "https://" + url
40
+ parsed_url = urlparse(url)
41
+
42
+ if not parsed_url.netloc:
43
+ return "Error: Invalid URL provided"
44
+
45
+ print(f"[WebExtract] Fetching content from: {url}")
46
+
47
+ # Set comprehensive headers
48
+ headers = {
49
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
50
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
51
+ 'Accept-Language': 'en-US,en;q=0.9',
52
+ 'Accept-Encoding': 'gzip, deflate, br',
53
+ 'DNT': '1',
54
+ 'Connection': 'keep-alive',
55
+ 'Upgrade-Insecure-Requests': '1',
56
+ 'Sec-Fetch-Dest': 'document',
57
+ 'Sec-Fetch-Mode': 'navigate',
58
+ 'Sec-Fetch-Site': 'none',
59
+ 'Sec-Fetch-User': '?1',
60
+ 'Cache-Control': 'max-age=0'
61
+ }
62
+
63
+ # Create session for cookie handling
64
+ session = requests.Session()
65
+ session.headers.update(headers)
66
+
67
+ # Retry logic for resilient fetching
68
+ max_retries = 3
69
+ for attempt in range(max_retries):
70
+ try:
71
+ response = session.get(url, timeout=15, allow_redirects=True)
72
+ response.raise_for_status()
73
+ break
74
+ except requests.exceptions.HTTPError as e:
75
+ if e.response.status_code == 403 and attempt < max_retries - 1:
76
+ # Try different User-Agent on 403
77
+ session.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
78
+ continue
79
+ else:
80
+ raise
81
+
82
+ # Handle encoding properly
83
+ try:
84
+ response.encoding = response.apparent_encoding
85
+ raw_html = response.text
86
+ except:
87
+ raw_html = response.content.decode('utf-8', errors='ignore')
88
+
89
+ # Parse with BeautifulSoup
90
+ soup = BeautifulSoup(raw_html, 'html.parser')
91
+
92
+ # Extract metadata
93
+ title = soup.find('title')
94
+ title_text = title.get_text().strip() if title else "No title found"
95
+
96
+ meta_desc = soup.find('meta', attrs={'name': 'description'})
97
+ description = meta_desc.get('content', '') if meta_desc else ""
98
+
99
+ # Fix image URLs to absolute URLs
100
+ WebContentExtractor._fix_image_urls(soup, url)
101
+
102
+ # Extract and analyze content
103
+ content_info = WebContentExtractor._analyze_content(soup)
104
+
105
+ # Get the modified HTML with absolute URLs
106
+ modified_html = str(soup)
107
+
108
+ # Clean and format HTML
109
+ cleaned_html = WebContentExtractor._clean_html(modified_html)
110
+
111
+ # Generate comprehensive website analysis
112
+ website_content = WebContentExtractor._format_website_analysis(
113
+ url, title_text, description, content_info, cleaned_html
114
+ )
115
+
116
+ return website_content.strip()
117
+
118
+ except requests.exceptions.HTTPError as e:
119
+ return WebContentExtractor._handle_http_error(e, url)
120
+ except requests.exceptions.Timeout:
121
+ return "Error: Request timed out. The website may be slow or unavailable."
122
+ except requests.exceptions.ConnectionError:
123
+ return "Error: Could not connect to the website. Please check your internet connection and the URL."
124
+ except requests.exceptions.RequestException as e:
125
+ return f"Error accessing website: {str(e)}"
126
+ except Exception as e:
127
+ return f"Error extracting website content: {str(e)}"
128
+
129
+ @staticmethod
130
+ def _fix_image_urls(soup: BeautifulSoup, base_url: str):
131
+ """Fix relative image URLs to absolute URLs"""
132
+ img_elements = soup.find_all('img')
133
+ for img in img_elements:
134
+ src = img.get('src', '')
135
+ if src:
136
+ img['src'] = WebContentExtractor._make_absolute_url(src, base_url)
137
+
138
+ # Handle lazy loading images
139
+ data_src = img.get('data-src', '')
140
+ if data_src and not src:
141
+ img['src'] = WebContentExtractor._make_absolute_url(data_src, base_url)
142
+
143
+ # Fix background images in style attributes
144
+ elements_with_style = soup.find_all(attrs={'style': True})
145
+ for element in elements_with_style:
146
+ style_attr = element.get('style', '')
147
+ bg_pattern = r'background-image:\s*url\(["\']?([^"\']+)["\']?\)'
148
+ matches = re.findall(bg_pattern, style_attr, re.IGNORECASE)
149
+ for match in matches:
150
+ if match:
151
+ absolute_bg = WebContentExtractor._make_absolute_url(match, base_url)
152
+ style_attr = style_attr.replace(match, absolute_bg)
153
+ element['style'] = style_attr
154
+
155
+ # Fix CSS background images
156
+ style_elements = soup.find_all('style')
157
+ for style in style_elements:
158
+ if style.string:
159
+ style_content = style.string
160
+ bg_pattern = r'background-image:\s*url\(["\']?([^"\']+)["\']?\)'
161
+ matches = re.findall(bg_pattern, style_content, re.IGNORECASE)
162
+ for match in matches:
163
+ if match:
164
+ absolute_bg = WebContentExtractor._make_absolute_url(match, base_url)
165
+ style_content = style_content.replace(match, absolute_bg)
166
+ style.string = style_content
167
+
168
+ @staticmethod
169
+ def _make_absolute_url(url: str, base_url: str) -> str:
170
+ """Convert relative URL to absolute URL"""
171
+ if url.startswith('//'):
172
+ return 'https:' + url
173
+ elif url.startswith('/'):
174
+ return urljoin(base_url, url)
175
+ elif not url.startswith(('http://', 'https://')):
176
+ return urljoin(base_url, url)
177
+ return url
178
+
179
+ @staticmethod
180
+ def _analyze_content(soup: BeautifulSoup) -> Dict:
181
+ """Analyze website content and structure"""
182
+ content_sections = []
183
+ nav_links = []
184
+ images = []
185
+
186
+ # Extract main content areas
187
+ main_selectors = [
188
+ 'main', 'article', '.content', '.main-content', '.post-content',
189
+ '#content', '#main', '.entry-content', '.post-body'
190
+ ]
191
+
192
+ for selector in main_selectors:
193
+ elements = soup.select(selector)
194
+ for element in elements:
195
+ text = element.get_text().strip()
196
+ if len(text) > 100:
197
+ content_sections.append(text)
198
+
199
+ # Extract navigation
200
+ nav_elements = soup.find_all(['nav', 'header'])
201
+ for nav in nav_elements:
202
+ links = nav.find_all('a')
203
+ for link in links:
204
+ link_text = link.get_text().strip()
205
+ link_href = link.get('href', '')
206
+ if link_text and link_href:
207
+ nav_links.append(f"{link_text}: {link_href}")
208
+
209
+ # Extract images
210
+ img_elements = soup.find_all('img')
211
+ for img in img_elements:
212
+ src = img.get('src', '')
213
+ alt = img.get('alt', '')
214
+ if src:
215
+ images.append({'src': src, 'alt': alt})
216
+
217
+ # Test image accessibility
218
+ working_images = []
219
+ for img in images[:10]: # Test first 10 images
220
+ if WebContentExtractor._test_image_url(img['src']):
221
+ working_images.append(img)
222
+
223
+ print(f"[WebExtract] Found {len(images)} images, {len(working_images)} working")
224
+
225
+ return {
226
+ 'content_sections': content_sections,
227
+ 'nav_links': nav_links,
228
+ 'images': images,
229
+ 'working_images': working_images,
230
+ 'script_tags': len(soup.find_all('script'))
231
+ }
232
+
233
+ @staticmethod
234
+ def _test_image_url(img_url: str) -> bool:
235
+ """Test if image URL is accessible"""
236
+ try:
237
+ test_response = requests.head(img_url, timeout=5, allow_redirects=True)
238
+ return test_response.status_code == 200
239
+ except:
240
+ return False
241
+
242
+ @staticmethod
243
+ def _clean_html(html_content: str) -> str:
244
+ """Clean and format HTML for better readability"""
245
+ # Remove comments and normalize whitespace
246
+ cleaned = re.sub(r'<!--.*?-->', '', html_content, flags=re.DOTALL)
247
+ cleaned = re.sub(r'\s+', ' ', cleaned)
248
+ cleaned = re.sub(r'>\s+<', '><', cleaned)
249
+
250
+ # Limit size to avoid token limits
251
+ if len(cleaned) > 15000:
252
+ cleaned = cleaned[:15000] + "\n<!-- ... HTML truncated for length ... -->"
253
+
254
+ return cleaned
255
+
256
+ @staticmethod
257
+ def _format_website_analysis(url: str, title: str, description: str,
258
+ content_info: Dict, html: str) -> str:
259
+ """Format comprehensive website analysis"""
260
+ working_images = content_info['working_images']
261
+ all_images = content_info['images']
262
+
263
+ content = f"""
264
+ WEBSITE REDESIGN - ORIGINAL HTML CODE
265
+ =====================================
266
+
267
+ URL: {url}
268
+ Title: {title}
269
+ Description: {description}
270
+
271
+ PAGE ANALYSIS:
272
+ - Website type: {title.lower()} website
273
+ - Content sections: {len(content_info['content_sections'])}
274
+ - Navigation links: {len(content_info['nav_links'])}
275
+ - Total images: {len(all_images)}
276
+ - Working images: {len(working_images)}
277
+ - JavaScript complexity: {"High" if content_info['script_tags'] > 10 else "Low to Medium"}
278
+
279
+ WORKING IMAGES (use these URLs in your redesign):
280
+ {chr(10).join([f"• {img['alt'] or 'Image'} - {img['src']}" for img in working_images[:20]]) if working_images else "No working images found"}
281
+
282
+ ALL IMAGES (including potentially broken ones):
283
+ {chr(10).join([f"• {img['alt'] or 'Image'} - {img['src']}" for img in all_images[:20]]) if all_images else "No images found"}
284
+
285
+ ORIGINAL HTML CODE (use this as the base for redesign):
286
+ ```html
287
+ {html}
288
+ ```
289
+
290
+ REDESIGN INSTRUCTIONS:
291
+ Please redesign this website with a modern, responsive layout while:
292
+ 1. Preserving all the original content and structure
293
+ 2. Maintaining the same navigation and functionality
294
+ 3. Using the original images and their URLs (listed above)
295
+ 4. Creating a modern, clean design with improved typography and spacing
296
+ 5. Making it fully responsive for mobile devices
297
+ 6. Using modern CSS frameworks and best practices
298
+ 7. Keeping the same semantic structure but with enhanced styling
299
+
300
+ IMPORTANT: All image URLs have been converted to absolute URLs and are ready to use.
301
+ Preserve these exact image URLs in your redesigned version.
302
+
303
+ The HTML code above contains the complete original website structure with all images properly linked.
304
+ Use it as your starting point and create a modernized version.
305
+ """
306
+ return content
307
+
308
+ @staticmethod
309
+ def _handle_http_error(error, url: str) -> str:
310
+ """Handle HTTP errors with user-friendly messages"""
311
+ status_code = error.response.status_code if hasattr(error, 'response') else 0
312
+
313
+ if status_code == 403:
314
+ return f"Error: Website blocked access (403 Forbidden). This website may have anti-bot protection. Try a different website or provide a description instead."
315
+ elif status_code == 404:
316
+ return f"Error: Website not found (404). Please check the URL and try again."
317
+ elif status_code >= 500:
318
+ return f"Error: Website server error ({status_code}). Please try again later."
319
+ else:
320
+ return f"Error accessing website: HTTP {status_code} - {str(error)}"
321
+
322
+ class WebSearchEngine:
323
+ """Handles web search operations using Tavily"""
324
+
325
+ @staticmethod
326
+ def perform_web_search(query: str, max_results: int = 5,
327
+ include_domains: Optional[List[str]] = None,
328
+ exclude_domains: Optional[List[str]] = None) -> str:
329
+ """Perform web search using Tavily with advanced parameters"""
330
+ if not tavily_client:
331
+ return "Web search is not available. Please set the TAVILY_API_KEY environment variable."
332
+
333
+ try:
334
+ print(f"[WebSearch] Searching for: {query}")
335
+
336
+ # Configure search parameters
337
+ search_params = {
338
+ "search_depth": "advanced",
339
+ "max_results": min(max(1, max_results), 20),
340
+ "include_answer": True,
341
+ "include_raw_content": False
342
+ }
343
+
344
+ if include_domains:
345
+ search_params["include_domains"] = include_domains
346
+ if exclude_domains:
347
+ search_params["exclude_domains"] = exclude_domains
348
+
349
+ # Perform search with timeout
350
+ response = tavily_client.search(query, **search_params)
351
+
352
+ # Process results
353
+ search_results = []
354
+ answer = response.get('answer', '')
355
+
356
+ if answer:
357
+ search_results.append(f"Direct Answer: {answer}\n")
358
+
359
+ for result in response.get('results', []):
360
+ title = result.get('title', 'No title')
361
+ url = result.get('url', 'No URL')
362
+ content = result.get('content', 'No content')
363
+ score = result.get('score', 0)
364
+
365
+ result_text = (
366
+ f"Title: {title}\n"
367
+ f"URL: {url}\n"
368
+ f"Relevance Score: {score:.2f}\n"
369
+ f"Content: {content}\n"
370
+ )
371
+ search_results.append(result_text)
372
+
373
+ if search_results:
374
+ final_results = "Web Search Results:\n\n" + "\n---\n".join(search_results)
375
+ print(f"[WebSearch] Found {len(search_results)} results")
376
+ return final_results
377
+ else:
378
+ return "No search results found."
379
+
380
+ except Exception as e:
381
+ error_msg = f"Search error: {str(e)}"
382
+ print(f"[WebSearch] Error: {error_msg}")
383
+ return error_msg
384
+
385
+ @staticmethod
386
+ def enhance_query_with_search(query: str, enable_search: bool) -> str:
387
+ """Enhance the query with web search results if search is enabled"""
388
+ if not enable_search or not tavily_client:
389
+ return query
390
+
391
+ print("[WebSearch] Enhancing query with web search")
392
+
393
+ # Perform search to get relevant information
394
+ search_results = WebSearchEngine.perform_web_search(query, max_results=3)
395
+
396
+ # Combine original query with search results
397
+ enhanced_query = f"""Original Query: {query}
398
+
399
+ {search_results}
400
+
401
+ Please use the search results above to help create the requested application with the most up-to-date information and best practices."""
402
+
403
+ return enhanced_query
404
+
405
+ # URL parsing utilities
406
+ def parse_repo_or_model_url(url: str) -> Tuple[str, Optional[Dict]]:
407
+ """Parse a URL and detect if it's a GitHub repo, HF Space, or HF Model"""
408
+ try:
409
+ parsed = urlparse(url.strip())
410
+ netloc = (parsed.netloc or "").lower()
411
+ path = (parsed.path or "").strip("/")
412
+
413
+ # Hugging Face spaces
414
+ if ("huggingface.co" in netloc or netloc.endswith("hf.co")) and path.startswith("spaces/"):
415
+ parts = path.split("/")
416
+ if len(parts) >= 3:
417
+ return "hf_space", {"username": parts[1], "project": parts[2]}
418
+
419
+ # Hugging Face model repo
420
+ if ("huggingface.co" in netloc or netloc.endswith("hf.co")) and not path.startswith(("spaces/", "datasets/", "organizations/")):
421
+ parts = path.split("/")
422
+ if len(parts) >= 2:
423
+ repo_id = f"{parts[0]}/{parts[1]}"
424
+ return "hf_model", {"repo_id": repo_id}
425
+
426
+ # GitHub repo
427
+ if "github.com" in netloc:
428
+ parts = path.split("/")
429
+ if len(parts) >= 2:
430
+ return "github", {"owner": parts[0], "repo": parts[1]}
431
+
432
+ except Exception:
433
+ pass
434
+
435
+ return "unknown", None
436
+
437
+ def check_hf_space_url(url: str) -> Tuple[bool, Optional[str], Optional[str]]:
438
+ """Check if URL is a valid Hugging Face Spaces URL and extract username/project"""
439
+ url_pattern = re.compile(
440
+ r'^(https?://)?(huggingface\.co|hf\.co)/spaces/([\w-]+)/([\w-]+)$',
441
+ re.IGNORECASE
442
+ )
443
+
444
+ match = url_pattern.match(url.strip())
445
+ if match:
446
+ username = match.group(3)
447
+ project_name = match.group(4)
448
+ return True, username, project_name
449
+ return False, None, None
450
+
451
+ # Export main functions
452
+ web_extractor = WebContentExtractor()
453
+ web_search = WebSearchEngine()
454
+
455
+ def extract_website_content(url: str) -> str:
456
+ return web_extractor.extract_website_content(url)
457
+
458
+ def perform_web_search(query: str, max_results: int = 5) -> str:
459
+ return web_search.perform_web_search(query, max_results)
460
+
461
+ def enhance_query_with_search(query: str, enable_search: bool) -> str:
462
+ return web_search.enhance_query_with_search(query, enable_search)