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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838dcd9
b16e4a0
838dcd9
 
 
b16e4a0
 
 
838dcd9
 
 
b16e4a0
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
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)