Spaces:
Build error

new_widget / app.py
anthony9's picture
Update app.py
9274426 verified
Raw History Blame Contribute Delete
21.8 kB
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 <g> 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 <g> elements and preserve them in the output HTML
for g_tag in soup.find_all('g', class_='style_168'):
if g_tag:
# Extract the <g> tag and wrap it with necessary SVG tags
svg_header = '<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="500" height="500">\n'
svg_footer = '\n</svg>'
# Create the full SVG content with the <g> element inside the <svg>
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 <g> element with the class 'style_168' found.")
# Find all <svg> tags that contain <image> tags with base64 href
svg_tags = soup.find_all('svg')
# Loop through each <svg> tag
for svg_tag in svg_tags:
# Find all <image> tags within the current <svg> 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 <iframe> tags
for iframe_tag in soup.find_all('iframe'):
iframe_tag.decompose() # This will remove the <iframe> tag and its contents
# Find all meta tags with properties related to images (e.g., twitter:image, og:image, etc.)
for image_meta_tags in soup.find_all('meta', attrs={'property': True}):
# List to store all the image URLs
image_urls = []
# Iterate through each meta tag and check if it contains an image URL
for i, meta_tag in image_meta_tags:
# Check if the property is related to images (e.g., twitter:image, og:image)
if 'image' in meta_tag['property'].lower() and 'content' in meta_tag.attrs:
image_urls.append(meta_tag['content'])
# Generate a unique file path for each image (e.g., image_1.png, image_2.png)
output_image_path = os.path.join(output_dir, f"image_meta_{i + 1}.png")
image_urls.append(meta_tag['content'])
# Save the base64 image to a file
save_base64_image(base64_data, output_image_path)
# Find all meta tags with properties related to images (e.g., twitter:image, og:image, etc.)
for image_meta_tags_name in soup.find_all('meta', attrs={'name': True}):
# Iterate through each meta tag and check if it contains an image URL
for i, meta_tag in image_meta_tags_name:
# Check if the property is related to images (e.g., twitter:image, og:image)
if 'image' in meta_tag['name'].lower() and 'content' in meta_tag.attrs:
image_urls.append(meta_tag['content'])
# Generate a unique file path for each image (e.g., image_1.png, image_2.png)
output_image_path = os.path.join(output_dir, f"image_meta2_{i + 1}.png")
image_urls.append(meta_tag['content'])
# Save the base64 image to a file
save_base64_image(base64_data, output_image_path)
# Find all <image> tags with href attributes that contain base64 data
image_tags = soup.find_all('image', href=re.compile(r'^data:image\/[a-zA-Z0-9\-+]+;base64,', re.IGNORECASE))
for i, img_tag in enumerate(image_tags):
# Extract the base64 href value
base64_data = img_tag['href']
# Generate a unique file path for each image (e.g., image_1.png, image_2.png)
output_image_path = os.path.join(output_dir, f"image_{i + 1}.png")
# Save the base64 image to a file
save_base64_image(base64_data, output_image_path)
# Step 2: Process all tags with resource links
for tag in soup.find_all(['link', 'script', 'img', 'style', 'link']):
if tag.name == 'link' and tag.get('rel') == ['stylesheet']:
href = tag.get('href')
if href:
resource_counter += 1
local_path = download_and_save_resource(urljoin(input_file, href), output_dir, f"resource_{resource_counter}")
if local_path:
tag['href'] = local_path
elif tag.name == 'script' and tag.get('src'):
src = tag.get('src')
resource_counter += 1
local_path = download_and_save_resource(urljoin(input_file, src), output_dir, f"resource_{resource_counter}")
if local_path:
tag['src'] = local_path
elif tag.name == 'img' and tag.get('src'):
src = tag.get('src')
src = unquote(src) # Decode any URL-encoded components in the src URL
if re.match(r'data:image', src): # Inline base64 image
if "base64" in src: # Check if it's base64 encoded
resource_counter += 1
ext = src.split(';')[0].split('/')[1] # Extract image extension
data = src.split(',')[1]
decoded_data = decode_base64_with_padding(data) # Ensure proper padding before decoding
if decoded_data:
local_path = save_resource(decoded_data, ext, output_dir, f"resource_{resource_counter}")
if local_path:
tag['src'] = local_path
else:
print(f"Skipping base64 image due to decoding error: {src}")
elif "svg+xml" in src: # Handle inline SVG directly without decoding
resource_counter += 1
data = src.split('base64,')[1] if 'base64,' in src else src.split('svg+xml,')[1] # Handle base64 and plain SVG
decoded_data = unquote(data) # Decode URL-encoded SVG if necessary
local_path = save_resource(decoded_data.encode(), "svg", output_dir, f"resource_{resource_counter}")
if local_path:
tag['src'] = local_path
else: # External image
resource_counter += 1
local_path = download_and_save_resource(urljoin(input_file, src), output_dir, f"resource_{resource_counter}")
if local_path:
tag['src'] = local_path
elif tag.name == 'style':
resource_counter += 1
local_path = save_resource(tag.string.encode(), "css", output_dir, f"resource_{resource_counter}")
if local_path:
new_style_tag = soup.new_tag("link", rel="stylesheet", href=local_path)
tag.replace_with(new_style_tag)
elif tag.name == 'link' and tag.get('rel') == ['preload']:
href = tag.get('href')
if href:
resource_counter += 1
local_path = download_and_save_resource(urljoin(input_file, href), output_dir, f"resource_{resource_counter}")
if local_path:
tag['href'] = local_path
# Step 3: Remove inline styles (CSS)
for tag in soup.find_all(True):
if 'style' in tag.attrs:
resource_counter += 1
style_content = tag['style'].encode()
local_path = save_resource(style_content, "css", output_dir, f"resource_{resource_counter}")
if local_path:
tag['class'] = f"style_{resource_counter}" # Example class for applying styles externally
del tag['style']
# Handle elements with the `data-savepage-src` attribute
for element in soup.find_all(attrs={"data-savepage-src": True}):
data_src = element.get('data-savepage-src')
if data_src:
resource_counter += 1
try:
response = requests.get(data_src)
if response.status_code == 200:
# Extract the file extension
parsed_url = urlparse(data_src)
ext = os.path.splitext(parsed_url.path)[1] or ".jpg" # Default to .jpg if no extension
local_path = save_resource(response.content, ext.lstrip('.'), output_dir, f"resource_{resource_counter}")
if local_path:
element['data-savepage-src'] = local_path
else:
print(f"Failed to download resource {data_src}: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"Error downloading resource: {e}")
# Handle elements with the `data-savepage-src` attribute
for element in soup.find_all(attrs={"data-savepage-href": True}):
data_src = element.get('data-savepage-href')
if data_src:
resource_counter += 1
try:
response = requests.get(data_src)
if response.status_code == 200:
# Extract the file extension
parsed_url = urlparse(data_src)
ext = os.path.splitext(parsed_url.path)[1] or ".jpg" # Default to .jpg if no extension
local_path = save_resource(response.content, ext.lstrip('.'), output_dir, f"resource_{resource_counter}")
if local_path:
element['data-savepage-href'] = local_path
else:
print(f"Failed to download resource {data_src}: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"Error downloading resource: {e}")
# Handle elements with the `data-savepage-srcset` attribute
for element in soup.find_all(attrs={"data-savepage-srcset": True}):
srcset = element.get('data-savepage-srcset')
if srcset:
srcset_values = srcset.split(',')
updated_srcset = []
for src in srcset_values:
src = src.strip()
if src.startswith('data:image'):
# Handle base64-encoded images in the srcset
try:
base64_data = src.split('base64,')[1]
decoded_data = base64.b64decode(base64_data)
resource_counter += 1
local_path = save_resource(decoded_data, "png", output_dir, f"resource_{resource_counter}") # Save as PNG (can adjust based on type)
if local_path:
updated_srcset.append(local_path)
except Exception as e:
print(f"Error decoding base64 image in srcset: {e}")
else:
# Process external image URLs in srcset
try:
response = requests.get(src)
if response.status_code == 200:
# Extract the file extension
parsed_url = urlparse(src)
ext = os.path.splitext(parsed_url.path)[1] or ".jpg" # Default to .jpg if no extension
local_path = save_resource(response.content, ext.lstrip('.'), output_dir, f"resource_{resource_counter}")
if local_path:
updated_srcset.append(local_path)
else:
print(f"Failed to download image in srcset: {src}")
except requests.exceptions.RequestException as e:
print(f"Error downloading image in srcset: {e}")
# Update the srcset attribute with local resource paths
element['data-savepage-srcset'] = ', '.join(updated_srcset)
# Handle `href` with base64-encoded images (e.g., in <a> or <use> tags)
for tag in soup.find_all(['a', 'use']):
href = tag.get('href', '')
if href and href.startswith('data:image'):
try:
base64_data = href.split('base64,')[1]
decoded_data = base64.b64decode(base64_data)
resource_counter += 1
local_path = save_resource(decoded_data, "png", output_dir, f"resource_{resource_counter}") # Save as PNG (can adjust based on type)
if local_path:
tag['href'] = local_path
except Exception as e:
print(f"Error decoding base64 image in href: {e}")
# Handle data-savepage-href attributes by replacing base64 with local resource paths
for link_tag in soup.find_all('link', {'data-savepage-href': True}):
base64_href = link_tag.get('href', '')
data_savepage_href = link_tag.get('data-savepage-href', '')
if base64_href.startswith('data:image') and data_savepage_href:
# If the href is base64 and data-savepage-href exists, replace href with the saved resource path
link_tag['href'] = data_savepage_href
# Step 4: Save the updated HTML to output file
output_html_file = os.path.join(output_dir, 'index.html')
with open(output_html_file, 'w', encoding='utf-8') as file:
file.write(str(soup))
return output_html_file
def create_zip(output_dir):
zip_path = f"{output_dir}.zip"
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, _, files in os.walk(output_dir):
for file in files:
full_path = os.path.join(root, file)
arcname = os.path.relpath(full_path, start=output_dir)
zipf.write(full_path, arcname)
return zip_path
def main(input_file):
output_dir = "output"
updated_html = process_html(input_file, output_dir)
if "Error" in updated_html:
return updated_html
zip_path = create_zip(output_dir)
return zip_path
interface = gr.Interface(
fn=main,
inputs=gr.File(label="Upload HTML File"),
outputs=gr.File(label="Download ZIP Archive")
)
if __name__ == "__main__":
interface.launch(share=True)