Download app.py from anthony9/widget: direct link, hf CLI and curl.
- Browser
- Download file 22.2 kB
-
https://huggingface.co/spaces/anthony9/widget/resolve/main/app.py
- Command line
-
hf download hf://spaces/anthony9/widget/app.py
-
curl -L -o app.py https://huggingface.co/spaces/anthony9/widget/resolve/main/app.py
22.2 kB
| import os | |
| import hashlib | |
| import re | |
| import base64 | |
| import zipfile | |
| from urllib.parse import urljoin, urlparse, unquote | |
| from urllib.request import urlopen, Request | |
| from bs4 import BeautifulSoup | |
| import gradio as gr | |
| def remove_comments(text): | |
| # Remove HTML comments | |
| text = re.sub(r'<!--[\s\S]*?-->', '', text) | |
| # Remove CSS comments (both block and inline) | |
| text = re.sub(r'/\*[\s\S]*?\*/|//.*', '', text) | |
| # Remove JavaScript comments (both block and inline) | |
| text = re.sub(r'/\*[\s\S]*?\*/|//.*?\n', '', text) | |
| return text | |
| # Function to fetch HTML from a URL and extract all CSS | |
| def save_css(style_tag): | |
| try: | |
| # Extract all <style> tags (CSS code within them) | |
| css_content = "" | |
| css_content += style_tag.string if style_tag.string else '' | |
| # Save the CSS content to a local file | |
| with open('index.css', 'w',encoding='utf-8') as css_file: | |
| css_file.write(css_content) | |
| print("CSS has been extracted and saved to index.css") | |
| except Exception as e: | |
| print(f"Error fetching the HTML content: {e}") | |
| def download_images_from_html(input_file, output_dir): | |
| os.makedirs(output_dir, exist_ok=True) | |
| try: | |
| with open(input_file, 'r', encoding='utf-8') as file: | |
| html = file.read() | |
| except FileNotFoundError: | |
| print(f"Error: The file {input_file} was not found.") | |
| return | |
| html_content = remove_comments(html) | |
| soup = BeautifulSoup(html_content, 'html.parser') | |
| def get_extension_from_mime(mime_type): | |
| # Handle video MIME types | |
| if mime_type.startswith('video'): | |
| return mime_type.split('/')[1] | |
| # Handle special cases first | |
| if mime_type == 'image/svg+xml': | |
| return 'svg' | |
| if mime_type.startswith('image/avif'): # Handle AVIF images | |
| return 'avif' | |
| if mime_type == 'font': | |
| extension = '.woff2' if extension == 'woff2' else '.ttf' # Assuming WOFF2 or TTF for fonts | |
| if mime_type == 'js': | |
| extension = '.js' # JavaScript file extension | |
| if mime_type.startswith('image/webp'): # Handle WebP images | |
| return 'webp' | |
| # Handle font MIME types | |
| if mime_type.startswith('font-'): | |
| return mime_type.split(';')[0] # Remove charset part | |
| if 'font' in mime_type: | |
| return mime_type.split('/')[-1].split(';')[0] # Get the font type without charset | |
| # Default case: get extension from MIME type | |
| ext = mime_type.split('/')[-1] | |
| # Clean up any parameters | |
| ext = ext.split(';')[0] | |
| return ext | |
| def decode_base64(data): | |
| try: | |
| return base64.b64decode(data.split('base64,')[-1]).decode('utf-8') | |
| except Exception as e: | |
| print(f"Error decoding base64: {e}") | |
| return None | |
| def minimy_path(output_dir,file_type,extension): | |
| # Generate a hash of the base64 data and encode it in base36 to create a minimal file_path | |
| file_hash = hashlib.sha256(base64_data.encode('utf-8')).hexdigest()[:8] # Get first 8 characters of the hash | |
| file_path = os.path.join(output_dir, f"{file_type}_{file_hash}{extension}") | |
| # unquote(f"{file_type}_{file_hash}{extension}") # Decode filename if necessary | |
| # filename = f"base64_image_{}.{ext}" | |
| # len(os.listdir(output_dir)) + 1 | |
| return file_path | |
| def save_base64_file(data_uri, element, attr, file_type): | |
| match = re.match(r'data:(.*?);base64,(.*)', data_uri) | |
| if not match: | |
| return | |
| mime_type, base64_data = match.groups() | |
| ext = get_extension_from_mime(mime_type) | |
| # Check for video type and handle specific cases for video formats | |
| if mime_type.startswith('video'): | |
| if ext not in ['mp4', 'webm']: | |
| print(f"Unsupported video format: {ext}. Skipping video.") | |
| return None | |
| if 'mp4' in ext: # Special handling for MP4 videos | |
| try: | |
| file_path = minimy_path(output_dir,file_type,ext) | |
| with open(file_path, 'wb') as f: | |
| f.write(decode_base64(base64_data)) | |
| if element is not None: | |
| if attr in element.attrs: | |
| element[attr] = filename | |
| # If this is a data-savepage-src attribute, also update the src attribute | |
| if attr == 'data-savepage-src': | |
| element['src'] = filename | |
| # Clean up attributes after processing | |
| if attr in ['data-savepage-href', 'href', '--savepage-url','data-savepage-currentsrc','data-savepage-src']: | |
| del element[attr] | |
| return filename # Return filename for further processing | |
| except Exception as e: | |
| file_type = 'MP4' | |
| print(f"Error saving video {file_type} Base64: {e}") | |
| return None | |
| file_path = minimy_path(output_dir,file_type,ext) | |
| try: | |
| with open(file_path, 'wb') as f: | |
| f.write(decode_base64(base64_data)) | |
| if element is not None: | |
| if attr in element.attrs: | |
| element[attr] = filename | |
| # If this is a data-savepage-src attribute, also update the src attribute | |
| if attr == 'data-savepage-src': | |
| element['src'] = filename | |
| # Handle srcset for images (WebP, AVIF, or any other images) | |
| if 'srcset' in element.attrs: | |
| element['srcset'] = re.sub(r'\b(\S+?)(?=\s|$)', lambda match: match.group(0).replace('.avif', f'.{ext}').replace('.webp', f'.{ext}'), element['srcset']) | |
| if 'data-savepage-srcset' in element.attrs: | |
| element['data-savepage-srcset'] = re.sub(r'\b(\S+?)(?=\s|$)', lambda match: match.group(0).replace('.avif', f'.{ext}').replace('.webp', f'.{ext}'), element['data-savepage-srcset']) | |
| # Remove any attributes that were for processing after use | |
| if attr in ['data-savepage-href', 'href', '--savepage-url', 'data-savepage-src','data-savepage-currentsrc']: | |
| del element[attr] | |
| return filename # Return filename for CSS variable replacement | |
| except Exception as e: | |
| print(f"Error saving Base64 {file_type}: {e}") | |
| return None | |
| def save_font_file(base64_data): | |
| # Save the font file (application/x-font-ttf) | |
| full_data_uri = f"data:application/x-font-ttf;charset=utf-8;base64,{base64_data}" | |
| filename = save_base64_file(full_data_uri, None, None, 'font') | |
| if filename: | |
| return f'src:url({filename})' | |
| return f'src:url(data:application/x-font-ttf;charset=utf-8;base64,{base64_data})' | |
| def save_javascript_file(base64_data): | |
| # Save the JavaScript file | |
| filename = save_base64_file(base64_data, 'js', 'js','script') | |
| if filename: | |
| return f'src:url({filename})' | |
| return '' | |
| def save_base64_link(prefix, base64_data): | |
| # Decode the base64 data and save it as a local file | |
| filename = save_base64_file(base64_data, 'image', 'ico','image') # Assuming it's an icon file | |
| if filename: | |
| return prefix + filename | |
| return '' | |
| def process_css_variables(style): | |
| if not style.string: | |
| return | |
| # Remove all CSS comments including those within @font-face or any other rules | |
| css_content = style.string or '' | |
| css_content = remove_comments(css_content) | |
| # Ensure CSS rules are not malformed after comment removal | |
| css_content = re.sub(r'src:\s*', 'src:', css_content) # Fix src: after comment removal | |
| # Save CSS content | |
| save_css(css_content) | |
| # Remove the <style> tag from the soup | |
| style.decompose() | |
| # Rule 1: Process --savepage-url-\d+ CSS variables | |
| root_rules = re.findall(r':root\s*{([^}]+)}', css_content) | |
| for rule in root_rules: | |
| var_matches = re.findall(r'(--savepage-url-\d+)\s*:\s*url\([\'"]?data:image/svg\+xml;base64,([^\'"]+)[\'"]?\)', rule) | |
| for var_name, base64_data in var_matches: | |
| full_data_uri = f"data:image/svg+xml;base64,{base64_data}" | |
| filename = save_base64_file(full_data_uri, None, None, 'image') | |
| if filename: | |
| old_value = f"{var_name}: url(data:image/svg+xml;base64,{base64_data})" | |
| new_value = f"{var_name}: url({filename})" | |
| css_content = css_content.replace(old_value, new_value) | |
| # Rule 2: Replace data:image application/x-font-ttf base64 URLs | |
| css_content = re.sub( | |
| r'src:url\((data:application/x-font-ttf;charset=utf-8;base64,([^\'"]+))\)', | |
| lambda m: save_font_file(m.group(1)), | |
| css_content or '' | |
| ) | |
| # Rule 3: Replace data:image application/x-font-ttf base64 URLs (Font files) | |
| css_content = re.sub( | |
| r'src:url\((data:(font/woff2|application/x-font-ttf);base64,([^\'"]+))\)', | |
| lambda m: save_font_file(m.group(2), m.group(3)), | |
| css_content or '' | |
| ) | |
| # Rule 4 <style> tags with base64 images or fonts | |
| css_content = re.sub( | |
| r'url\((data:image/[^;]+;base64,([^"]+))\)', | |
| lambda match: handle_base64_css(match.group(1), match.group(2)), | |
| css_content | |
| ) | |
| # Rule 5: Replace data:text/javascript;base64 (JavaScript files) | |
| css_content = re.sub( | |
| r'data:text/javascript;base64,([^\'"]+)', | |
| lambda m: save_javascript_file(m.group(1)), | |
| css_content or '' | |
| ) | |
| # Rule 6 Handle <link> tags with base64 images | |
| css_content = re.sub( | |
| r'(<link[^>]+href="data:image/[^;]+;base64,)([^"]+)', | |
| lambda match: handle_base64_link(match.group(1), match.group(2)), | |
| css_content | |
| ) | |
| return css_content | |
| def save_file(url, element, attr, file_type): | |
| try: | |
| if url.startswith('data:'): | |
| save_base64_file(url, element, attr,'image') | |
| return | |
| parsed_url = urlparse(url) | |
| filename = unquote(os.path.basename(parsed_url.path)) # Decode %20 to space | |
| file_path = os.path.join(output_dir, filename) | |
| if not os.path.exists(file_path): | |
| request = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) | |
| with urlopen(request) as response: | |
| with open(file_path, 'wb') as f: | |
| f.write(response.read()) | |
| if element is not None: | |
| if attr in element.attrs: | |
| element[attr] = filename | |
| # If this is a data-savepage-src attribute, also update the src attribute | |
| if attr == 'data-savepage-src': | |
| element['src'] = filename | |
| # Remove processed attributes | |
| if attr in ['data-savepage-href', 'href', '--savepage-url', 'data-savepage-src', 'data-savepage-currentsrc']: | |
| del element[attr] | |
| except Exception as e: | |
| print(f"Error downloading {url}: {e}") | |
| def process_specific_attributes(tag, attrs, file_type): | |
| for attr in attrs: | |
| if attr in tag.attrs: | |
| save_file(tag[attr], tag, attr, file_type) | |
| # If this is a data-savepage-src attribute, make sure to update the src | |
| if attr == 'data-savepage-src' and 'src' not in tag.attrs: | |
| tag['src'] = tag[attr] | |
| # 1) Handling font in <head> | |
| for element in soup.head.find_all(attrs={'savepage-url': True}): | |
| url = element['savepage-url'] | |
| if url.startswith('https://www.*'): | |
| real_url = url.replace('*', '') | |
| try: | |
| response = requests.get(real_url) | |
| response.raise_for_status() | |
| base64_data = base64.b64encode(response.content).decode('utf-8') | |
| element['href'] = f'data:application/font-woff2;base64,{base64_data}' | |
| del element['savepage-url'] | |
| except Exception as e: | |
| print(f"Failed to fetch {real_url}: {e}") | |
| # Process <video> tags with data-savepage-src or src attributes | |
| for video in soup.find_all('video'): | |
| if video is not None: | |
| # Process data-savepage-src first if it exists | |
| if 'data-savepage-src' in video.attrs: | |
| save_file(video['data-savepage-src'], video, 'data-savepage-src', 'video') | |
| # Then process src if it still exists and wasn't updated by data-savepage-src | |
| elif 'src' in video.attrs: | |
| save_file(video['src'], video, 'src', 'video') | |
| # Process <source> tags inside video elements | |
| for source in soup.find_all('source'): | |
| if source is not None and 'src' in source.attrs: | |
| save_file(source['src'], source, 'src', 'video') | |
| # Process CSS variables in style tags | |
| for style in soup.find_all('style'): | |
| process_css_variables(style) | |
| # Process tags with data-savepage-src first | |
| for tag in soup.find_all(lambda t: t.has_attr('data-savepage-src')): | |
| if tag is not None: | |
| save_file(tag['data-savepage-src'], tag, 'data-savepage-src','image') | |
| # Process any tag with data-img-zoom-url | |
| for tag in soup.find_all(lambda t: t.has_attr('data-img-zoom-url')): | |
| if tag is not None: | |
| process_specific_attributes(tag, ['data-img-zoom-url'],'image') | |
| # Process any tag with data-savepage-href, href with base64 data, or --savepage-url | |
| for tag in soup.find_all(lambda t: any(attr in t.attrs for attr in ['data-savepage-href', 'href', '--savepage-url','data-savepage-currentsrc','data-savepage-src'])): | |
| if tag is not None: | |
| if 'data-savepage-href' in tag.attrs: | |
| save_file(tag['data-savepage-href'], tag, 'data-savepage-href','image') | |
| if 'href' in tag.attrs and tag['href'].startswith('data:'): | |
| save_file(tag['href'], tag, 'href','image') | |
| if 'data-savepage-currentsrc' in tag.attrs and tag['data-savepage-currentsrc'].startswith('data:'): | |
| save_file(tag['data-savepage-currentsrc'], tag, 'data-savepage-currentsrc','image') | |
| if 'data-savepage-src' in tag.attrs and tag['data-savepage-src'].startswith('data:'): | |
| save_file(tag['data-savepage-src'], tag, 'data-savepage-src','image') | |
| if '--savepage-url' in tag.attrs: | |
| css_content = tag['--savepage-url'] | |
| matches = re.findall(r'url\(svg\+xml;base64,(.*?)\)', css_content) | |
| for match in matches: | |
| full_data_uri = f"data:image/svg+xml;base64,{match}" | |
| save_base64_file(full_data_uri, tag, '--savepage-url','image') | |
| tag['--savepage-url'] = '' | |
| # Process any tag with data-original | |
| for tag in soup.find_all(lambda t: t.has_attr('data-original')): | |
| if tag is not None: | |
| process_specific_attributes(tag, ['data-original'],'image') | |
| # Process <img> tags | |
| for img in soup.find_all('img'): | |
| if img is not None: | |
| # Process data-savepage-src first if it exists | |
| if 'data-savepage-src' in img.attrs: | |
| save_file(img['data-savepage-src'], img, 'data-savepage-src','image') | |
| # Then process src if it still exists and wasn't updated by data-savepage-src | |
| elif 'src' in img.attrs: | |
| save_file(img['src'], img, 'src','image') | |
| # Process <meta> tags | |
| for meta in soup.find_all('meta'): | |
| if meta is not None and 'content' in meta.attrs: | |
| save_file(meta['content'], meta, 'content','image') | |
| # Process <a> tags | |
| for link in soup.find_all('a'): | |
| if link is not None: | |
| if 'href' in link.attrs and link['href'].startswith('data:image'): | |
| save_file(link['href'], link, 'href','image') | |
| if 'data-savepage-href' in link.attrs: | |
| save_file(link['data-savepage-href'], link, 'data-savepage-href','image') | |
| if '--savepage-url' in link.attrs: | |
| save_file(link['--savepage-url'], link, '--savepage-url','image') | |
| if 'data-savepage-src' in link.attrs: | |
| save_file(link['data-savepage-src'], link, 'data-savepage-src','image') | |
| if 'data-savepage-currentsrc' in link.attrs: | |
| save_file(link['data-savepage-currentsrc'], link, 'data-savepage-currentsrc','image') | |
| # if '--savepage-url' in tag.attrs: | |
| # css_content = tag['--savepage-url'] | |
| # matches = re.findall(r'url\(svg\+xml;base64,(.*?)\)', css_content) | |
| # for match in matches: | |
| # full_data_uri = f"data:image/svg+xml;base64,{match}" | |
| # save_base64_file(full_data_uri, tag, '--savepage-url') | |
| # tag['--savepage-url'] = '' | |
| # Process <svg> tags | |
| for i, svg in enumerate(soup.find_all('svg'), start=1): | |
| if svg is not None: | |
| filename = f"svg_image_{i}.svg" | |
| file_path = os.path.join(output_dir, filename) | |
| with open(file_path, 'w', encoding='utf-8') as f: | |
| f.write(str(svg)) | |
| svg.replace_with(f'<img src="{filename}" alt="SVG Image">') | |
| def process_css_styles(css_content, base_url=None): | |
| updated_css = css_content | |
| urls = re.findall(r'url\(["\']?(.*?)["\']?\)|background-image:\s*url\(["\']?(.*?)["\']?\)', css_content) | |
| for match in urls: | |
| url = match[0] or match[1] | |
| if not url: | |
| continue | |
| full_url = urljoin(base_url, url) if base_url else url | |
| parsed_url = urlparse(full_url) | |
| filename = os.path.basename(parsed_url.path) | |
| file_path = os.path.join(output_dir, filename) | |
| if full_url.startswith('data:'): | |
| if full_url.startswith('data:image/svg+xml;base64,'): | |
| save_base64_file(full_url, None, None,'image') | |
| updated_css = updated_css.replace(url, filename) | |
| else: | |
| save_base64_file(full_url, None, None,'image') | |
| updated_css = updated_css.replace(url, filename) | |
| else: | |
| try: | |
| if not os.path.exists(file_path): | |
| request = Request(full_url, headers={'User-Agent': 'Mozilla/5.0'}) | |
| with urlopen(request) as response: | |
| with open(file_path, 'wb') as f: | |
| f.write(response.read()) | |
| updated_css = updated_css.replace(url, filename) | |
| except Exception as e: | |
| print(f"Error downloading {url}: {e}") | |
| return updated_css | |
| # Handle inline <style> tags | |
| for style in soup.find_all('style'): | |
| if style is not None and style.string: | |
| updated_content = process_css_styles(style.string) | |
| style.string = updated_content | |
| # Handle linked CSS files | |
| for link in soup.find_all('link', {'rel': 'stylesheet'}): | |
| if link is not None and 'href' in link.attrs: | |
| css_url = link['href'] | |
| try: | |
| request = Request(css_url, headers={'User-Agent': 'Mozilla/5.0'}) | |
| with urlopen(request) as response: | |
| css_content = response.read().decode('utf-8') | |
| updated_content = process_css_styles(css_content, base_url=css_url) | |
| css_filename = os.path.basename(urlparse(css_url).path) | |
| css_file_path = os.path.join(output_dir, css_filename) | |
| with open(css_file_path, 'w', encoding='utf-8') as f: | |
| f.write(updated_content) | |
| link['href'] = css_filename | |
| except Exception as e: | |
| print(f"Error downloading CSS {css_url}: {e}") | |
| # Handling favicon in CSS style | |
| for link in soup.find_all('link', attrs={'data-savepage-href': True}): | |
| if link is not None and 'href' in link.attrs: | |
| css_url = link['href'] | |
| try: | |
| base64_data = decode_base64(response.content) | |
| link['href'] = f'data:image/x-icon;base64,{base64_data}' | |
| save_base64_file(full_url, None, None,'image') | |
| del link['data-savepage-href'] | |
| except Exception as e: | |
| print(f"Error downloading CSS {css_url}: {e}") | |
| # Write the modified HTML 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)) # prettify() | |
| 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 update_and_package_html(input_file): | |
| output_dir = "output" | |
| updated_html = download_images_from_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=update_and_package_html, | |
| inputs=gr.File(label="Upload HTML File"), | |
| outputs=gr.File(label="Download ZIP Archive") | |
| ) | |
| if __name__ == "__main__": | |
| interface.launch(share=True) |