builder / deploy.py
mgbam's picture
Rename utils.py to deploy.py
2f92e9e verified
raw
history blame
3.47 kB
def send_to_sandbox(code):
wrapped_code=f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
...
</body>
</html>
"""
encoded_html=base64.b64encode(wrapped_code.encode('utf-8')).decode('utf-8')
data_uri=f"data:text/html;charset=utf-8;base64,{encoded_html}"
return f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
def demo_card_click(e: gr.EventData):
...
return DEMO_LIST[index]['description']
def wrap_html_in_gradio_app(html_code):
safe_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'
)
def deploy_to_spaces(code):
if not code.strip(): return
app_py=wrap_html_in_gradio_app(code.strip())
...
webbrowser.open_new_tab(full_url)
def wrap_html_in_static_app(html_code):
return html_code
def deploy_to_spaces_static(code):
if not code.strip(): return
app_html=wrap_html_in_static_app(code.strip())
...
webbrowser.open_new_tab(full_url)
def check_hf_space_url(url: str) -> Tuple[bool, Optional[str], Optional[str]]:
import re
url_pattern=re.compile(
r'^(https?://)?(huggingface\.co|hf\.co)/spaces/([\w-]+)/([\w-]+)$',
re.IGNORECASE
)
match=url_pattern.match(url.strip())
if match:
return True, match.group(3), match.group(4)
return False, None, None
def fetch_hf_space_content(username: str, project_name: str) -> str:
try:
api=HfApi()
space_info=api.space_info(f"{username}/{project_name}")
sdk=space_info.sdk
...
return f"""IMPORTED PROJECT FROM HUGGING FACE SPACE
==============================================
Space: {username}/{project_name}
SDK: {sdk}
Main File: {main_file}
{file_content}"""
except Exception as e:
return f"Error fetching space content: {str(e)}"
def load_project_from_url(url: str) -> Tuple[str, str]:
is_valid,username,project_name=check_hf_space_url(url)
if not is_valid:
return "Error: Please enter a valid Hugging Face Spaces URL.\n\nExpected format: https://huggingface.co/spaces/username/project",""
content=fetch_hf_space_content(username,project_name)
if content.startswith("Error:"):
return content,""
lines=content.split('\n')
code_start=0
for i,line in enumerate(lines):
if line.strip() and not line.startswith(('=','IMPORTED','Space:','SDK:','Main File:')):
code_start=i
break
code_content='\n'.join(lines[code_start:])
return f"βœ… Successfully imported project from {username}/{project_name}",code_content
def deploy_to_user_space(code, space_name, sdk_name, profile=None, token=None):
import shutil
if 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)
...
return gr.update(value=f"βœ… {action_text}! [Open your Space here]({space_url})", visible=True)