update
Browse files1103 unmodified lines1104110511061107110811091110111111121113111411151116111711181119112011211122101 unmodified lines12241225122612271228122912304 unmodified lines12351236123712381239124012411242124382 unmodified lines132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013516 unmodified lines135813591360136113621363136413655 unmodified lines1371137213731374137513761377137813791380138113821 unmodified line1384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141272 unmodified lines14851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271103 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'101 unmodified lineslabel="app name (e.g. my-cool-app)",placeholder="Enter your app name",lines=1,visible=False)sdk_choices = [("Gradio (Python)", "gradio"),4 unmodified lineschoices=[x[0] for x in sdk_choices],value="Static (HTML)",label="App SDK",visible=False)deploy_btn = gr.Button("🚀 Deploy App", variant="primary", visible=False)deploy_status = gr.Markdown(visible=False, label="Deploy status")# --- End move ---search_toggle = gr.Checkbox(82 unmodified lineselse:return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>"def show_deploy_components(*args):return [gr.Textbox(visible=True), gr.Dropdown(visible=True), gr.Button(visible=True), gr.Markdown(visible=True)]def hide_deploy_components(*args):return [gr.Textbox(visible=False), gr.Dropdown(visible=False), gr.Button(visible=False), gr.Markdown(visible=False)]btn.click(generation_code,inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state],outputs=[code_output, history, sandbox, history_output]).then(show_deploy_components,None,[space_name_input, sdk_dropdown, deploy_btn, deploy_status])# Update preview when code or language changescode_output.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)language_dropdown.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])clear_btn.click(hide_deploy_components, None, [space_name_input, sdk_dropdown, deploy_btn, deploy_status])# Deploy to Spaces logic6 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)]elif sdk == "docker": # Streamlit (Python)import shutilimport os72 unmodified lines# Check if the code is already Python/Gradio code or HTMLif code.strip().startswith('import gradio') or code.strip().startswith('import gr') or 'gradio' in code.lower():# Code is already Python/Gradio, use it directlyapp_py = codeelse:# 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,repo_id=repo_id,repo_type="space")space_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(deploy_to_user_space,inputs=[code_output, space_name_input, sdk_dropdown],outputs=deploy_status)# Keep the old deploy method as fallback (if not logged in, user can still use the old method)1103 unmodified lines110411051106110711081109111011111112111311141115101 unmodified lines12171218121912201221122212234 unmodified lines12281229123012311232123312341235123682 unmodified lines131913201321132213231324132513261327132813291330133113321333133413356 unmodified lines1342134313441345134613475 unmodified lines1353135413551356135713581359136013611 unmodified line1363136413651366136713681369137013711372137372 unmodified lines144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011103 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'101 unmodified lineslabel="app name (e.g. my-cool-app)",placeholder="Enter your app name",lines=1,visible=True)sdk_choices = [("Gradio (Python)", "gradio"),4 unmodified lineschoices=[x[0] for x in sdk_choices],value="Static (HTML)",label="App SDK",visible=True)deploy_btn = gr.Button("🚀 Deploy App", variant="primary", visible=True)deploy_status = gr.Markdown(visible=False, label="Deploy status")# --- End move ---search_toggle = gr.Checkbox(82 unmodified lineselse:return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>"btn.click(generation_code,inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state],outputs=[code_output, history, sandbox, history_output])# Update preview when code or language changescode_output.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)language_dropdown.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])# Deploy to Spaces logic6 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"app_code = codeelif sdk == "docker": # Streamlit (Python)import shutilimport os72 unmodified lines# Check if the code is already Python/Gradio code or HTMLif code.strip().startswith('import gradio') or code.strip().startswith('import gr') or 'gradio' in code.lower():# Code is already Python/Gradio, use it directlyapp_code = codeelse:# Code is HTML, wrap it in a Gradio app structureapp_code = wrap_html_in_gradio_app(code)with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding='utf-8') as f:f.write(app_code)temp_path = f.namefiles_to_upload = [(temp_path, file_name)]# Upload the file(s)try:if sdk == "docker": # Streamlit - upload multiple filesfor local_path, repo_path in files_to_upload:api.upload_file(path_or_fileobj=local_path,path_in_repo=repo_path,repo_id=repo_id,repo_type="space")else: # Gradio or Static - upload single fileapi.upload_file(path_or_fileobj=temp_path,path_in_repo=file_name,repo_id=repo_id,repo_type="space")space_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)finally:# Clean up temporary filesimport osif sdk == "docker": # Streamlit - clean up multiple filesfor 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}")else: # Gradio or Static - clean up single filetry:if os.path.exists(temp_path):os.unlink(temp_path)except Exception as cleanup_error:print(f"Warning: Could not clean up {temp_path}: {cleanup_error}")# Connect the deploy button to the new functiondeploy_btn.click(deploy_to_user_space,inputs=[code_output, space_name_input, sdk_dropdown, login_button, login_button],outputs=deploy_status)# Keep the old deploy method as fallback (if not logged in, user can still use the old method)
app.py+35-61