File size: 4,025 Bytes
a575316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
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

def save_to_local(url, folder):
    """Downloads the resource and saves it locally using urllib"""
    try:
        # Open the URL and read its content
        with urllib.request.urlopen(url) as response:
            file_name = os.path.basename(urlparse(url).path)
            file_path = os.path.join(folder, file_name)
            
            # Write the content to the local file
            with open(file_path, 'wb') as file:
                file.write(response.read())
            
            return file_name
    except Exception as e:
        print(f"Failed to download {url}: {e}")
        return None

def process_html(input_html, folder):
    """Processes the HTML, moves external styles and scripts locally, and updates the HTML"""
    # Parse the HTML content
    with open(input_html, 'r', encoding='utf-8') as f:
        soup = BeautifulSoup(f, 'html.parser')

    # Create a folder to store resources if it doesn't exist
    if not os.path.exists(folder):
        os.makedirs(folder)

    # Process external CSS
    for link in soup.find_all('link', {'rel': 'stylesheet'}):
        href = link.get('href')
        if href:
            url = urljoin(input_html, href)
            local_file = save_to_local(url, folder)
            if local_file:
                link['href'] = os.path.join(folder, local_file)

    # Process external JS
    for script in soup.find_all('script', {'src': True}):
        src = script.get('src')
        if src:
            url = urljoin(input_html, src)
            local_file = save_to_local(url, folder)
            if local_file:
                script['src'] = os.path.join(folder, local_file)

    # Process inline styles
    for style in soup.find_all('style'):
        css_content = style.string
        if css_content:
            file_path = os.path.join(folder, 'style.css')
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(css_content)
            style.decompose()  # Remove inline style tag
            # Link to local CSS file
            new_link = soup.new_tag('link', rel='stylesheet', href=os.path.join(folder, 'style.css'))
            soup.head.append(new_link)

    # Process inline JS
    for script in soup.find_all('script'):
        js_content = script.string
        if js_content:
            file_path = os.path.join(folder, 'script.js')
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(js_content)
            script.decompose()  # Remove inline script tag
            # Link to local JS file
            new_script = soup.new_tag('script', src=os.path.join(folder, 'script.js'))
            soup.body.append(new_script)

    # Get the output file name based on the input file name
    output_html = f"{os.path.splitext(input_html)[0]}2.html"

    # Save the modified HTML
    with open(output_html, 'w', encoding='utf-8') as f:
        f.write(str(soup))

    return output_html


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)