import os import hashlib import re import requests import zipfile from urllib.parse import urljoin, urlparse, unquote from urllib.request import urlopen, Request import base64 import json from bs4 import BeautifulSoup import argparse import gradio as gr # Function to remove empty attributes from the HTML content def remove_empty_attributes(soup): # Find all elements with attributes for tag in soup.find_all(True): # 'True' finds all tags # Get a list of attributes for the current tag for attribute, value in list(tag.attrs.items()): # If the attribute has an empty value, remove it if value == "": del tag[attribute] return soup # Function to extract and save SVG elements def save_svg_elements(soup, output_dir): svg_elements = [] for i, tag in enumerate(soup.find_all(['g', 'path', 'rect', 'circle', 'line'])): svg_elements.append(str(tag)) # Collect the SVG elements as strings # Define output image path, save as .png by default output_svg_path = os.path.join(output_dir, f"svg_{i + 1}.svg") if svg_elements: # Save the collected SVG elements to a local file with open(output_svg_path, 'w', encoding='utf-8') as svg_file: svg_file.write('\n'.join(svg_elements)) # Write SVG elements to file print(f"SVG elements saved to {output_svg_path}") # Remove the SVG tags from the soup to clean up the main content for tag in soup.find_all(['g', 'path', 'rect', 'circle', 'line']): tag.decompose() return soup def save_resource(content, ext, output_dir, file_name_prefix): """Save resource content (CSS, JS, image) locally. Returns the relative path to the saved file.""" try: # Ensure the resource directory exists os.makedirs(output_dir, exist_ok=True) # Fix: For SVG, we explicitly ensure the extension is '.svg' if ext == "svg+xml": ext = "svg" # Ensure the resource has a leading dot for the extension if not ext.startswith('.'): ext = '.' + ext file_name = f"{file_name_prefix}{ext}" local_path = os.path.join(output_dir, file_name) # Save the resource locally if the content is not None if content: with open(local_path, 'wb') as file: file.write(content) return os.path.relpath(local_path, os.path.dirname(output_dir)) # Ensure relative path is to the resources folder else: print(f"Skipping resource saving due to empty content: {file_name}") return None except Exception as e: print(f"Error saving resource: {e}") return None # Function to download and save resources locally with custom headers to simulate browser request def download_and_save_resource(url, resource_type, output_dir): try: # Decode the URL to handle encoded characters like %20 for spaces decoded_url = urllib.parse.unquote(url) # Set up headers to simulate a browser request headers = { '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', 'Referer': 'https://www.google.com', # You can change this to a valid referer } # Check if the URL is a base64 image if decoded_url.startswith('data:image'): file_extension = decoded_url.split(';')[0].split('/')[1] # Extract file type from base64 data base64_data = decoded_url.split(',')[1] # Get the actual base64-encoded string file_data = base64.b64decode(base64_data) resource_filename = f"{resource_type}/{resource_type}_{hash(url)}.{file_extension}" save_path = os.path.join(output_dir, resource_filename) os.makedirs(os.path.dirname(save_path), exist_ok=True) with open(save_path, 'wb') as f: f.write(file_data) return resource_filename # Return relative path # If the URL is a regular resource, download it with headers using session response = session.get(decoded_url, headers=headers) response.raise_for_status() # Raise an exception for bad responses file_extension = os.path.splitext(decoded_url)[1].lstrip('.') resource_filename = f"{resource_type}/{resource_type}_{hash(decoded_url)}.{file_extension}" save_path = os.path.join(output_dir, resource_filename) os.makedirs(os.path.dirname(save_path), exist_ok=True) with open(save_path, 'wb') as f: f.write(response.content) return resource_filename # Return relative path except Exception as e: print(f"Failed to download and save resource: {e}") return None def decode_base64_with_padding(data): """Ensure proper base64 padding.""" padding = len(data) % 4 if padding != 0: data += '=' * (4 - padding) # Add padding to make the length a multiple of 4 try: return base64.b64decode(data) except base64.binascii.Error as e: print(f"Error decoding base64 image: {e}") return None # Function to save a specific tag content as SVG file def save_svg_content(svg_content, output_svg_path): # Save the extracted SVG content to the file with open(output_svg_path, 'w', encoding='utf-8') as f: f.write(svg_content) # Function to save base64 image data to a file def save_base64_image(base64_data, output_image_path): # Remove the data:image/png;base64, part from the string image_data = base64_data.split(',')[1] if ',' in base64_data else base64_data # Decode the base64 string decoded_data = base64.b64decode(image_data) # Write the decoded data to the file with open(output_image_path, 'wb') as f: f.write(decoded_data) print(f"Image saved to {output_image_path}") def process_html(input_file, output_dir): """Process the HTML, download resources, and replace links with local paths.""" # Use a requests session to maintain session state with requests.Session() as session: with open(input_file, 'r', encoding='utf-8') as f: html_content = f.read() soup = BeautifulSoup(html_content, 'html.parser') # Remove empty attributes from the HTML soup = remove_empty_attributes(soup) # Ensure the resources directory exists os.makedirs(output_dir, exist_ok=True) # Save and remove SVG elements (if any) soup = save_svg_elements(soup, output_dir) resource_counter = 0 # Find all elements with a data-src attribute data_src_tags = soup.find_all(attrs={'data-src': True}) # Extract the data-src values and store them in a list data_src_values = [] for i, tag in enumerate(data_src_tags): # Access data-src attribute directly from the tag's attributes data_src_values.append({'tag': str(tag), 'data-src': tag['data-src']}) # Define output image path, save as .png by default output_json_path = os.path.join(output_dir, f"json_{i + 1}.json") # Save the data-src values to a JSON file with open(output_json_path, 'w', encoding='utf-8') as json_file: json.dump(data_src_values, json_file, ensure_ascii=False, indent=4) print(f"Data-src values saved to {output_json_path}") # Handle SVG elements and preserve them in the output HTML for g_tag in soup.find_all('g', class_='style_168'): if g_tag: # Extract the tag and wrap it with necessary SVG tags svg_header = '\n\n' svg_footer = '\n' # Create the full SVG content with the element inside the svg_content = svg_header + str(g_tag) + svg_footer # Save the content to an SVG file save_svg_content(svg_content, output_svg_path) print(f"SVG file saved as {output_svg_path}") else: print("No element with the class 'style_168' found.") # Find all tags that contain tags with base64 href svg_tags = soup.find_all('svg') # Loop through each tag for svg_tag in svg_tags: # Find all tags within the current tag image_tags = svg_tag.find_all('image', href=re.compile(r'^data:image\/[a-zA-Z0-9\-+]+;base64,', re.IGNORECASE)) # Extract base64 data and save the images for i, image_tag in enumerate(image_tags): base64_data = image_tag['href'] # Define output image path, save as .png by default output_image_path = os.path.join(output_dir, f"image_from_svg_{i + 1}.png") # Save the base64 image to file save_base64_image(base64_data, output_image_path) # Remove all