update
Browse files1103 unmodified lines110411051106110711081109111011111112111311141115235 unmodified lines1351135213531354135513565 unmodified lines1362136313641365136613671368136913701 unmodified line1372137313741375137613771378137913801381138258 unmodified lines144114421443144414451446144714 unmodified lines14621463146414651466146714681469147014711472147314743 unmodified lines14781479148014811482148314841103 unmodified lines# Deploy to Spaces logicdef wrap_html_in_gradio_app(html_code):# Escape triple quotes for safe embeddingsafe_html = html_code.replace('"""', r'\"\"\"')return ('import gradio as gr\n\n''def show_html():\n'f' return """{safe_html}"""\n\n''demo = gr.Interface(fn=show_html, inputs=None, outputs=gr.HTML())\n\n''if __name__ == "__main__":\n'' demo.launch()\n'235 unmodified lines):if not code or not code.strip():return gr.update(value="No code to deploy.", visible=True)if profile is None or token is None:return gr.update(value="Please log in with your Hugging Face account to deploy to your own Space. Otherwise, use the default deploy (opens in new tab).", visible=True)username = profile.username5 unmodified lines"Static (HTML)": "static"}sdk = sdk_map.get(sdk_name, "gradio")api = HfApi(token=token.token)# Create the Space if it doesn't existtry:api.create_repo(repo_id=repo_id, # e.g. username/space_namerepo_type="space",1 unmodified lineexist_ok=True # Don't error if it already exists)except Exception as e:return gr.update(value=f"Error creating Space: {e}", visible=True)# Save code to a temporary fileif sdk == "static":file_name = "index.html"with tempfile.NamedTemporaryFile("w", suffix=".html", delete=False) as f:f.write(code)temp_path = f.namefiles_to_upload = [(temp_path, file_name)]58 unmodified linesEdit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community\nforums](https://discuss.streamlit.io).'''readme_path = os.path.join(temp_dir, "README.md")with open(readme_path, "w", encoding="utf-8") as f:14 unmodified lineselse:# Code is HTML, wrap it in a Gradio app structureapp_py = wrap_html_in_gradio_app(code)with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:f.write(app_py)temp_path = f.namefiles_to_upload = [(temp_path, file_name)]# Upload all filestry:for local_path, repo_path in files_to_upload:api.upload_file(path_or_fileobj=local_path,path_in_repo=repo_path,3 unmodified linesspace_url = f"https://huggingface.co/spaces/{repo_id}"return gr.update(value=f"✅ Deployed! [Open your Space here]({space_url})", visible=True)except Exception as e:return gr.update(value=f"Error uploading file: {e}", visible=True)# Connect the deploy button to the new functiondeploy_btn.click(1103 unmodified lines1104110511061107110811091110111111121113111411151116111711181119112011211122235 unmodified lines135813591360136113621363136413655 unmodified lines1371137213731374137513761377137813791380138113821 unmodified line1384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140958 unmodified lines146814691470147114721473147414 unmodified lines148914901491149214931494149514961497149814991500150115023 unmodified lines150615071508150915101511151215131514151515161517151815191520152115221103 unmodified lines# Deploy to Spaces logicdef wrap_html_in_gradio_app(html_code):# Use a more robust approach to handle HTML with quotesimport base64# Encode HTML as base64 to avoid quote issueshtml_bytes = html_code.encode('utf-8')html_b64 = base64.b64encode(html_bytes).decode('utf-8')return ('import gradio as gr\n''import base64\n\n''def show_html():\n'f' html_b64 = "{html_b64}"\n'' html_code = base64.b64decode(html_b64).decode("utf-8")\n'' return html_code\n\n''demo = gr.Interface(fn=show_html, inputs=None, outputs=gr.HTML())\n\n''if __name__ == "__main__":\n'' demo.launch()\n'235 unmodified lines):if not code or not code.strip():return gr.update(value="No code to deploy.", visible=True)if not space_name or not space_name.strip():return gr.update(value="Please enter a valid app name.", visible=True)if profile is None or token is None:return gr.update(value="Please log in with your Hugging Face account to deploy to your own Space. Otherwise, use the default deploy (opens in new tab).", visible=True)username = profile.username5 unmodified lines"Static (HTML)": "static"}sdk = sdk_map.get(sdk_name, "gradio")if not sdk:return gr.update(value="Invalid SDK selection. Please choose a valid SDK.", visible=True)api = HfApi(token=token.token)# Create the Space if it doesn't existtry:print(f"Creating Space {repo_id} with SDK {sdk}")api.create_repo(repo_id=repo_id, # e.g. username/space_namerepo_type="space",1 unmodified lineexist_ok=True # Don't error if it already exists)except Exception as e:print(f"Error creating Space: {e}")return gr.update(value=f"Error creating Space: {e}", visible=True)# Save code to a temporary fileif sdk == "static":file_name = "index.html"# Ensure the code is properly formatted for static HTML deploymentif not code.strip().startswith('<!DOCTYPE html>') and not code.strip().startswith('<html'):# Wrap in basic HTML structure if not already presentcode = f"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Generated App</title></head><body>{code}</body></html>"""with tempfile.NamedTemporaryFile("w", suffix=".html", delete=False, encoding='utf-8') as f:f.write(code)temp_path = f.namefiles_to_upload = [(temp_path, file_name)]58 unmodified linesEdit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community forums](https://discuss.streamlit.io).'''readme_path = os.path.join(temp_dir, "README.md")with open(readme_path, "w", encoding="utf-8") as f:14 unmodified lineselse:# Code is HTML, wrap it in a Gradio app structureapp_py = wrap_html_in_gradio_app(code)with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding='utf-8') as f:f.write(app_py)temp_path = f.namefiles_to_upload = [(temp_path, file_name)]# Upload all filestry:for local_path, repo_path in files_to_upload:print(f"Uploading {local_path} to {repo_path} in {repo_id}")api.upload_file(path_or_fileobj=local_path,path_in_repo=repo_path,3 unmodified linesspace_url = f"https://huggingface.co/spaces/{repo_id}"return gr.update(value=f"✅ Deployed! [Open your Space here]({space_url})", visible=True)except Exception as e:print(f"Deployment error: {e}")return gr.update(value=f"Error uploading file: {e}", visible=True)finally:# Clean up temporary filesimport osfor local_path, _ in files_to_upload:try:if os.path.exists(local_path):os.unlink(local_path)except Exception as cleanup_error:print(f"Warning: Could not clean up {local_path}: {cleanup_error}")# Connect the deploy button to the new functiondeploy_btn.click(
app.py+45-7