|
|
|
|
|
import os |
|
import base64 |
|
import webbrowser |
|
import urllib.parse |
|
import tempfile |
|
|
|
import gradio as gr |
|
from huggingface_hub import HfApi, duplicate_space |
|
|
|
|
|
|
|
|
|
|
|
def send_to_sandbox(code: str) -> str: |
|
wrapped = f""" |
|
<!DOCTYPE html> |
|
<html> |
|
<head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head> |
|
<body>{code}</body> |
|
</html> |
|
""" |
|
b64 = base64.b64encode(wrapped.encode("utf-8")).decode("utf-8") |
|
return ( |
|
f'<iframe src="data:text/html;base64,{b64}" ' |
|
'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) -> str: |
|
idx = e.index if hasattr(e, 'index') else 0 |
|
from constants import DEMO_LIST |
|
idx = idx if 0 <= idx < len(DEMO_LIST) else 0 |
|
return DEMO_LIST[idx]["description"] |
|
|
|
|
|
|
|
|
|
|
|
def wrap_html_in_gradio_app(html_code: str) -> str: |
|
safe = html_code.replace('"""', r'\"\"\"') |
|
return ( |
|
"import gradio as gr\n\n" |
|
"def show_html():\n" |
|
f' return """{safe}"""\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: str) -> None: |
|
if not code.strip(): |
|
return |
|
app_py = wrap_html_in_gradio_app(code) |
|
params = urllib.parse.urlencode({"name": "new-space", "sdk": "gradio"}) |
|
files_params = urllib.parse.urlencode({"files[0][path]": "app.py", "files[0][content]": app_py}) |
|
url = f"https://huggingface.co/new-space?{params}&{files_params}" |
|
webbrowser.open_new_tab(url) |
|
|
|
def wrap_html_in_static_app(html_code: str) -> str: |
|
return html_code |
|
|
|
def deploy_to_spaces_static(code: str) -> None: |
|
if not code.strip(): |
|
return |
|
html = wrap_html_in_static_app(code) |
|
params = urllib.parse.urlencode({"name": "new-space", "sdk": "static"}) |
|
files_params = urllib.parse.urlencode({"files[0][path]": "index.html", "files[0][content]": html}) |
|
url = f"https://huggingface.co/new-space?{params}&{files_params}" |
|
webbrowser.open_new_tab(url) |
|
|
|
|
|
|
|
|
|
|
|
def check_hf_space_url(url: str): |
|
import re |
|
pattern = re.compile(r'^(?:https?://)?(?:huggingface\\.co|hf\\.co)/spaces/([\\w-]+)/([\\w-]+)$', re.IGNORECASE) |
|
m = pattern.match(url.strip()) |
|
return (False, None, None) if not m else (True, m.group(1), m.group(2)) |
|
|
|
def fetch_hf_space_content(username: str, project: str) -> str: |
|
api = HfApi() |
|
info = api.space_info(f"{username}/{project}") |
|
sdk = info.sdk |
|
main_file = "index.html" if sdk == "static" else "app.py" |
|
path = api.hf_hub_download(repo_id=f"{username}/{project}", filename=main_file, repo_type="space") |
|
with open(path, "r", encoding="utf-8") as f: |
|
return f.read() |
|
|
|
def load_project_from_url(url: str): |
|
valid, user, proj = check_hf_space_url(url) |
|
if not valid: |
|
return "Error: Invalid Hugging Face Space URL.", "" |
|
try: |
|
content = fetch_hf_space_content(user, proj) |
|
return f"✅ Imported {user}/{proj}", content |
|
except Exception as e: |
|
return f"Error fetching project: {e}", "" |
|
|
|
def deploy_to_user_space(code, space_name, sdk_choice, profile: Optional[gr.OAuthProfile] = None, token: Optional[gr.OAuthToken] = None): |
|
if not profile or not token or not token.token or token.token.startswith("hf_"): |
|
return gr.update(value="Please log in with a valid Hugging Face write token.", visible=True) |
|
|
|
api = HfApi(token=token.token) |
|
repo_id = space_name.strip() if "/" in space_name.strip() else f"{profile.username}/{space_name.strip()}" |
|
sdk = {"Gradio (Python)": "gradio", "Streamlit (Python)": "docker", "Static (HTML)": "static", "Transformers.js": "static"}.get(sdk_choice, "gradio") |
|
|
|
if "/" not in space_name and sdk != "docker": |
|
api.create_repo(repo_id=repo_id, repo_type="space", space_sdk=sdk, exist_ok=True) |
|
|
|
filename = "index.html" if sdk == "static" else "app.py" |
|
with tempfile.NamedTemporaryFile("w", suffix=f".{filename.split('.')[-1]}", delete=False) as f: |
|
f.write(code) |
|
path = f.name |
|
api.upload_file(path_or_fileobj=path, path_in_repo=filename, repo_id=repo_id, repo_type="space") |
|
os.unlink(path) |
|
|
|
return gr.update(value=f"✅ Deployed to https://huggingface.co/spaces/{repo_id}", visible=True) |
|
|