update
Browse files28 unmodified lines293031323334353637383912 unmodified lines525354555657585960616263398 unmodified lines46246346446546646746839 unmodified lines5085095105115125135145155165175185193 unmodified lines5235245255265275285295305315326 unmodified lines5395405415425435445455465475485495505515525535544 unmodified lines559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599129 unmodified lines72973073173273373473528 unmodified lines5. Ensure the code is functional and follows best practicesFor website redesign tasks:- Analyze the extracted website content to understand the structure and purpose- Create a modern, responsive design that improves upon the original- Maintain the core functionality and content while enhancing the user experience- Use modern CSS frameworks and design patterns- Ensure accessibility and mobile responsivenessIf an image is provided, analyze it and use the visual information to better understand the user's requirements.12 unmodified lines6. Ensure the code is functional and follows best practicesFor website redesign tasks:- Analyze the extracted website content to understand the structure and purpose- Use web search to find current design trends and best practices for the specific type of website- Create a modern, responsive design that improves upon the original- Maintain the core functionality and content while enhancing the user experience- Use modern CSS frameworks and design patterns- Ensure accessibility and mobile responsivenessIf an image is provided, analyze it and use the visual information to better understand the user's requirements.398 unmodified linesreturn f"Error extracting text: {e}"def extract_website_content(url: str) -> str:"""Extract content from a website URL"""try:# Validate URLparsed_url = urlparse(url)39 unmodified lineselse:raise# Parse HTML contentsoup = BeautifulSoup(response.content, 'html.parser')# Remove script and style elementsfor script in soup(["script", "style"]):script.decompose()# Extract titletitle = soup.find('title')3 unmodified linesmeta_desc = soup.find('meta', attrs={'name': 'description'})description = meta_desc.get('content', '') if meta_desc else ""# Extract main content areascontent_sections = []# Look for common content containersmain_selectors = ['main', 'article', '.content', '.main-content', '.post-content','#content', '#main', '.entry-content', '.post-body'6 unmodified linesif len(text) > 100: # Only include substantial contentcontent_sections.append(text)# If no main content found, extract from bodyif not content_sections:body = soup.find('body')if body:# Remove navigation, footer, and other non-content elementsfor element in body.find_all(['nav', 'footer', 'header', 'aside']):element.decompose()content_sections.append(body.get_text().strip())# Extract navigation linksnav_links = []nav_elements = soup.find_all(['nav', 'header'])for nav in nav_elements:4 unmodified linesif link_text and link_href:nav_links.append(f"{link_text}: {link_href}")# Extract imagesimages = []img_elements = soup.find_all('img')for img in img_elements:src = img.get('src', '')alt = img.get('alt', '')if src:# Convert relative URLs to absoluteif not src.startswith(('http://', 'https://')):src = urljoin(url, src)images.append(f"Image: {alt} ({src})")# Compile the extracted contentwebsite_content = f"""WEBSITE CONTENT EXTRACTION==========================URL: {url}Title: {title_text}Description: {description}NAVIGATION MENU:{chr(10).join(nav_links[:10]) if nav_links else "No navigation found"}MAIN CONTENT:{chr(10).join(content_sections[:3]) if content_sections else "No main content found"}IMAGES:{chr(10).join(images[:10]) if images else "No images found"}PAGE STRUCTURE:- This appears to be a {title_text.lower()} website- Contains {len(content_sections)} main content sections- Has {len(nav_links)} navigation links- Includes {len(images)} images"""return website_content.strip()129 unmodified lines# URL input for website redesignwebsite_url_input = gr.Textbox(label="Website URL (for redesign)",placeholder="https://example.com",lines=1,visible=True28 unmodified lines29303132333435363738394041424312 unmodified lines56575859606162636465666768697071398 unmodified lines47047147247347447547639 unmodified lines5165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565573 unmodified lines5615625635645655665675686 unmodified lines5755765775785795805814 unmodified lines586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786129 unmodified lines91691791891992092192228 unmodified lines5. Ensure the code is functional and follows best practicesFor website redesign tasks:- Use the provided original HTML code as the starting point for redesign- Preserve all original content, structure, and functionality- Keep the same semantic HTML structure but enhance the styling- Reuse all original images and their URLs from the HTML code- Create a modern, responsive design with improved typography and spacing- Use modern CSS frameworks and design patterns- Ensure accessibility and mobile responsiveness- Maintain the same navigation and user flow- Enhance the visual design while keeping the original layout structureIf an image is provided, analyze it and use the visual information to better understand the user's requirements.12 unmodified lines6. Ensure the code is functional and follows best practicesFor website redesign tasks:- Use the provided original HTML code as the starting point for redesign- Preserve all original content, structure, and functionality- Keep the same semantic HTML structure but enhance the styling- Reuse all original images and their URLs from the HTML code- Use web search to find current design trends and best practices for the specific type of website- Create a modern, responsive design with improved typography and spacing- Use modern CSS frameworks and design patterns- Ensure accessibility and mobile responsiveness- Maintain the same navigation and user flow- Enhance the visual design while keeping the original layout structureIf an image is provided, analyze it and use the visual information to better understand the user's requirements.398 unmodified linesreturn f"Error extracting text: {e}"def extract_website_content(url: str) -> str:"""Extract HTML code and content from a website URL"""try:# Validate URLparsed_url = urlparse(url)39 unmodified lineselse:raise# Get the raw HTML content with proper encodingtry:# Try to get the content with automatic encoding detectionresponse.encoding = response.apparent_encodingraw_html = response.textexcept:# Fallback to UTF-8 if encoding detection failsraw_html = response.content.decode('utf-8', errors='ignore')# Debug: Check if we got valid HTMLif not raw_html.strip().startswith('<!DOCTYPE') and not raw_html.strip().startswith('<html'):print(f"Warning: Response doesn't look like HTML. First 200 chars: {raw_html[:200]}")print(f"Response headers: {dict(response.headers)}")print(f"Response encoding: {response.encoding}")print(f"Apparent encoding: {response.apparent_encoding}")# Try alternative approachestry:raw_html = response.content.decode('latin-1', errors='ignore')print("Tried latin-1 decoding")except:try:raw_html = response.content.decode('utf-8', errors='ignore')print("Tried UTF-8 decoding")except:raw_html = response.content.decode('cp1252', errors='ignore')print("Tried cp1252 decoding")# Parse HTML content for analysissoup = BeautifulSoup(raw_html, 'html.parser')# Check if this is a JavaScript-heavy sitescript_tags = soup.find_all('script')if len(script_tags) > 10:print(f"Warning: This site has {len(script_tags)} script tags - it may be a JavaScript-heavy site")print("The content might be loaded dynamically and not available in the initial HTML")# Extract titletitle = soup.find('title')3 unmodified linesmeta_desc = soup.find('meta', attrs={'name': 'description'})description = meta_desc.get('content', '') if meta_desc else ""# Extract main content areas for analysiscontent_sections = []main_selectors = ['main', 'article', '.content', '.main-content', '.post-content','#content', '#main', '.entry-content', '.post-body'6 unmodified linesif len(text) > 100: # Only include substantial contentcontent_sections.append(text)# Extract navigation links for analysisnav_links = []nav_elements = soup.find_all(['nav', 'header'])for nav in nav_elements:4 unmodified linesif link_text and link_href:nav_links.append(f"{link_text}: {link_href}")# Extract and fix image URLs in the HTMLimg_elements = soup.find_all('img')for img in img_elements:src = img.get('src', '')if src:# Handle different URL formatsif src.startswith('//'):# Protocol-relative URLabsolute_src = 'https:' + srcimg['src'] = absolute_srcelif src.startswith('/'):# Root-relative URLabsolute_src = urljoin(url, src)img['src'] = absolute_srcelif not src.startswith(('http://', 'https://')):# Relative URLabsolute_src = urljoin(url, src)img['src'] = absolute_src# If it's already absolute, keep it as is# Also check for data-src (lazy loading) and other common attributesdata_src = img.get('data-src', '')if data_src and not src:# Use data-src if src is emptyif data_src.startswith('//'):absolute_data_src = 'https:' + data_srcimg['src'] = absolute_data_srcelif data_src.startswith('/'):absolute_data_src = urljoin(url, data_src)img['src'] = absolute_data_srcelif not data_src.startswith(('http://', 'https://')):absolute_data_src = urljoin(url, data_src)img['src'] = absolute_data_srcelse:img['src'] = data_src# Also fix background image URLs in style attributeselements_with_style = soup.find_all(attrs={'style': True})for element in elements_with_style:style_attr = element.get('style', '')# Find and replace relative URLs in background-imageimport rebg_pattern = r'background-image:\s*url\(["\']?([^"\']+)["\']?\)'matches = re.findall(bg_pattern, style_attr, re.IGNORECASE)for match in matches:if match:if match.startswith('//'):absolute_bg = 'https:' + matchstyle_attr = style_attr.replace(match, absolute_bg)elif match.startswith('/'):absolute_bg = urljoin(url, match)style_attr = style_attr.replace(match, absolute_bg)elif not match.startswith(('http://', 'https://')):absolute_bg = urljoin(url, match)style_attr = style_attr.replace(match, absolute_bg)element['style'] = style_attr# Fix background images in <style> tagsstyle_elements = soup.find_all('style')for style in style_elements:if style.string:style_content = style.string# Find and replace relative URLs in background-imagebg_pattern = r'background-image:\s*url\(["\']?([^"\']+)["\']?\)'matches = re.findall(bg_pattern, style_content, re.IGNORECASE)for match in matches:if match:if match.startswith('//'):absolute_bg = 'https:' + matchstyle_content = style_content.replace(match, absolute_bg)elif match.startswith('/'):absolute_bg = urljoin(url, match)style_content = style_content.replace(match, absolute_bg)elif not match.startswith(('http://', 'https://')):absolute_bg = urljoin(url, match)style_content = style_content.replace(match, absolute_bg)style.string = style_content# Extract images for analysis (after fixing URLs)images = []img_elements = soup.find_all('img')for img in img_elements:src = img.get('src', '')alt = img.get('alt', '')if src:images.append({'src': src, 'alt': alt})# Debug: Print some image URLs to see what we're gettingprint(f"Found {len(images)} images:")for i, img in enumerate(images[:5]): # Show first 5 imagesprint(f" {i+1}. {img['alt'] or 'No alt'} - {img['src']}")# Test a few image URLs to see if they're accessibledef test_image_url(img_url):try:test_response = requests.head(img_url, timeout=5, allow_redirects=True)return test_response.status_code == 200except:return False# Test first few imagesworking_images = []for img in images[:10]: # Test first 10 imagesif test_image_url(img['src']):working_images.append(img)else:print(f" ❌ Broken image: {img['src']}")print(f"Working images: {len(working_images)} out of {len(images)}")# Get the modified HTML with absolute URLsmodified_html = str(soup)# Clean and format the HTML for better readability# Remove unnecessary whitespace and commentsimport recleaned_html = re.sub(r'<!--.*?-->', '', modified_html, flags=re.DOTALL) # Remove HTML commentscleaned_html = re.sub(r'\s+', ' ', cleaned_html) # Normalize whitespacecleaned_html = re.sub(r'>\s+<', '><', cleaned_html) # Remove whitespace between tags# Limit HTML size to avoid token limits (keep first 15000 chars)if len(cleaned_html) > 15000:cleaned_html = cleaned_html[:15000] + "\n<!-- ... HTML truncated for length ... -->"# Check if we got any meaningful contentif not title_text or title_text == "No title found":title_text = url.split('/')[-1] or url.split('/')[-2] or "Website"# If we couldn't extract any meaningful content, provide a fallbackif len(cleaned_html.strip()) < 100:website_content = f"""WEBSITE REDESIGN - EXTRACTION FAILED====================================URL: {url}Title: {title_text}ERROR: Could not extract meaningful HTML content from this website. This could be due to:1. The website uses heavy JavaScript to load content dynamically2. The website has anti-bot protection3. The website requires authentication4. The website is using advanced compression or encodingFALLBACK APPROACH:Please create a modern, responsive website design for a {title_text.lower()} website. Since I couldn't extract the original content, you can:1. Create a typical layout for this type of website2. Use placeholder content that would be appropriate3. Include modern design elements and responsive features4. Use a clean, professional design with good typography5. Make it mobile-friendly and accessibleThe website appears to be: {title_text}"""return website_content.strip()# Compile the extracted content with the actual HTML codewebsite_content = f"""WEBSITE REDESIGN - ORIGINAL HTML CODE=====================================URL: {url}Title: {title_text}Description: {description}PAGE ANALYSIS:- This appears to be a {title_text.lower()} website- Contains {len(content_sections)} main content sections- Has {len(nav_links)} navigation links- Includes {len(images)} imagesIMAGES FOUND (use these exact URLs in your redesign):{chr(10).join([f"• {img['alt'] or 'Image'} - {img['src']}" for img in working_images[:20]]) if working_images else "No working images found"}ALL IMAGES (including potentially broken ones):{chr(10).join([f"• {img['alt'] or 'Image'} - {img['src']}" for img in images[:20]]) if images else "No images found"}ORIGINAL HTML CODE (use this as the base for redesign):```html{cleaned_html}```REDESIGN INSTRUCTIONS:Please redesign this website with a modern, responsive layout while:1. Preserving all the original content and structure2. Maintaining the same navigation and functionality3. Using the original images and their URLs (listed above)4. Creating a modern, clean design with improved typography and spacing5. Making it fully responsive for mobile devices6. Using modern CSS frameworks and best practices7. Keeping the same semantic structure but with enhanced stylingIMPORTANT: All image URLs in the HTML code above have been converted to absolute URLs and are ready to use. Make sure to preserve these exact image URLs in your redesigned version.The HTML code above contains the complete original website structure with all images properly linked. Use it as your starting point and create a modernized version."""return website_content.strip()129 unmodified lines# URL input for website redesignwebsite_url_input = gr.Textbox(label="Website URL (extracts HTML for redesign)",placeholder="https://example.com",lines=1,visible=True
app.py+230-43