Spaces:
Build error
Build error
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import osimport zipfileimport shutilimport gradio as grfrom pywebcopy import save_webpagedef update_and_package_html(html_file):if not html_file:return "Error: No HTML file uploaded"# Define the folder for saving assets and final outputbase_folder = os.getcwd()download_folder = os.path.join(base_folder, 'scraped_page')# Ensure the download folder existstry:if not os.path.exists(download_folder):os.makedirs(download_folder)except Exception as e:return f"Error creating folder: {str(e)}"# Save the uploaded HTML content to a local filehtml_file_path = os.path.join(download_folder, 'index.html')try:# Read the uploaded HTML filewith open(html_file.name, 'r', encoding='utf-8') as f:html_content = f.read()# Save the HTML content locallywith open(html_file_path, 'w', encoding='utf-8') as f:f.write(html_content)# Save the webpage and its assetstry:save_webpage(url=html_file_path,project_folder=download_folder,bypass_robots=True)except Exception as e:return f"Error saving webpage assets: {str(e)}"# Package everything into a ZIP filezip_filename = 'scraped_page.zip'zip_path = os.path.join(base_folder, zip_filename)try:with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:for root, dirs, files in os.walk(download_folder):for file in files:file_path = os.path.join(root, file)zipf.write(file_path, os.path.relpath(file_path, download_folder))except Exception as e:return f"Error creating ZIP file: {str(e)}"# Clean up the temporary foldershutil.rmtree(download_folder)# Return the path to the ZIP file for downloadreturn zip_pathexcept Exception as e:return f"An error occurred: {str(e)}"# Gradio interface for uploading HTML and downloading ZIP fileinterface = 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119import osimport hashlibimport reimport requestsimport zipfilefrom urllib.parse import urljoin, urlparse, unquotefrom urllib.request import urlopen, Requestimport base64import jsonfrom bs4 import BeautifulSoupimport argparseimport gradio as grdef save_to_local(url, folder):"""Downloads the resource and saves it locally using urllib"""try:# Open the URL and read its contentwith 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 filewith open(file_path, 'wb') as file:file.write(response.read())return file_nameexcept Exception as e:print(f"Failed to download {url}: {e}")return Nonedef process_html(input_html, folder):"""Processes the HTML, moves external styles and scripts locally, and updates the HTML"""# Parse the HTML contentwith open(input_html, 'r', encoding='utf-8') as f:soup = BeautifulSoup(f, 'html.parser')# Create a folder to store resources if it doesn't existif not os.path.exists(folder):os.makedirs(folder)# Process external CSSfor 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 JSfor 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 stylesfor style in soup.find_all('style'):css_content = style.stringif 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 filenew_link = soup.new_tag('link', rel='stylesheet', href=os.path.join(folder, 'style.css'))soup.head.append(new_link)# Process inline JSfor script in soup.find_all('script'):js_content = script.stringif 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 filenew_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 nameoutput_html = f"{os.path.splitext(input_html)[0]}2.html"# Save the modified HTMLwith open(output_html, 'w', encoding='utf-8') as f:f.write(str(soup))return output_htmldef 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_pathdef main(input_file):output_dir = "output"updated_html = process_html(input_file, output_dir)if "Error" in updated_html:return updated_htmlzip_path = create_zip(output_dir)return zip_pathinterface = 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)
app.py+96-51