mgbam commited on
Commit
2541fb7
·
verified ·
1 Parent(s): 0cd83f6

Update deploy.py

Browse files
Files changed (1) hide show
  1. deploy.py +43 -26
deploy.py CHANGED
@@ -11,7 +11,7 @@ import gradio as gr
11
  from huggingface_hub import HfApi, duplicate_space
12
 
13
  # ------------------------------------------------------------------
14
- # Utilities for livepreview sandbox in the Gradio UI
15
  # ------------------------------------------------------------------
16
 
17
  def send_to_sandbox(code: str) -> str:
@@ -30,9 +30,17 @@ def send_to_sandbox(code: str) -> str:
30
  )
31
 
32
  def demo_card_click(e: gr.EventData) -> str:
33
- idx = e.index if hasattr(e, 'index') else 0
 
 
 
 
 
 
 
34
  from constants import DEMO_LIST
35
- idx = idx if 0 <= idx < len(DEMO_LIST) else 0
 
36
  return DEMO_LIST[idx]["description"]
37
 
38
  # ------------------------------------------------------------------
@@ -54,8 +62,15 @@ def deploy_to_spaces(code: str) -> None:
54
  if not code.strip():
55
  return
56
  app_py = wrap_html_in_gradio_app(code)
57
- params = urllib.parse.urlencode({"name": "new-space", "sdk": "gradio"})
58
- files_params = urllib.parse.urlencode({"files[0][path]": "app.py", "files[0][content]": app_py})
 
 
 
 
 
 
 
59
  url = f"https://huggingface.co/new-space?{params}&{files_params}"
60
  webbrowser.open_new_tab(url)
61
 
@@ -66,8 +81,15 @@ def deploy_to_spaces_static(code: str) -> None:
66
  if not code.strip():
67
  return
68
  html = wrap_html_in_static_app(code)
69
- params = urllib.parse.urlencode({"name": "new-space", "sdk": "static"})
70
- files_params = urllib.parse.urlencode({"files[0][path]": "index.html", "files[0][content]": html})
 
 
 
 
 
 
 
71
  url = f"https://huggingface.co/new-space?{params}&{files_params}"
72
  webbrowser.open_new_tab(url)
73
 
@@ -77,16 +99,15 @@ def deploy_to_spaces_static(code: str) -> None:
77
 
78
  def check_hf_space_url(url: str):
79
  import re
80
- pattern = re.compile(r'^(?:https?://)?(?:huggingface\\.co|hf\\.co)/spaces/([\\w-]+)/([\\w-]+)$', re.IGNORECASE)
81
  m = pattern.match(url.strip())
82
- return (False, None, None) if not m else (True, m.group(1), m.group(2))
 
 
83
 
84
  def fetch_hf_space_content(username: str, project: str) -> str:
85
  api = HfApi()
86
- info = api.space_info(f"{username}/{project}")
87
- sdk = info.sdk
88
- main_file = "index.html" if sdk == "static" else "app.py"
89
- path = api.hf_hub_download(repo_id=f"{username}/{project}", filename=main_file, repo_type="space")
90
  with open(path, "r", encoding="utf-8") as f:
91
  return f.read()
92
 
@@ -100,22 +121,18 @@ def load_project_from_url(url: str):
100
  except Exception as e:
101
  return f"Error fetching project: {e}", ""
102
 
 
 
 
 
103
  def deploy_to_user_space(code, space_name, sdk_choice, profile: Optional[gr.OAuthProfile] = None, token: Optional[gr.OAuthToken] = None):
104
  if not profile or not token or not token.token or token.token.startswith("hf_"):
105
  return gr.update(value="Please log in with a valid Hugging Face write token.", visible=True)
106
-
107
  api = HfApi(token=token.token)
108
- repo_id = space_name.strip() if "/" in space_name.strip() else f"{profile.username}/{space_name.strip()}"
109
- sdk = {"Gradio (Python)": "gradio", "Streamlit (Python)": "docker", "Static (HTML)": "static", "Transformers.js": "static"}.get(sdk_choice, "gradio")
110
-
111
- if "/" not in space_name and sdk != "docker":
112
- api.create_repo(repo_id=repo_id, repo_type="space", space_sdk=sdk, exist_ok=True)
113
-
114
- filename = "index.html" if sdk == "static" else "app.py"
115
- with tempfile.NamedTemporaryFile("w", suffix=f".{filename.split('.')[-1]}", delete=False) as f:
116
  f.write(code)
117
- path = f.name
118
- api.upload_file(path_or_fileobj=path, path_in_repo=filename, repo_id=repo_id, repo_type="space")
119
- os.unlink(path)
120
-
121
  return gr.update(value=f"✅ Deployed to https://huggingface.co/spaces/{repo_id}", visible=True)
 
11
  from huggingface_hub import HfApi, duplicate_space
12
 
13
  # ------------------------------------------------------------------
14
+ # Utilities for live-preview sandbox in the Gradio UI
15
  # ------------------------------------------------------------------
16
 
17
  def send_to_sandbox(code: str) -> str:
 
30
  )
31
 
32
  def demo_card_click(e: gr.EventData) -> str:
33
+ try:
34
+ idx = (
35
+ e._data.get("index")
36
+ or e._data.get("component", {}).get("index")
37
+ or e._data.get("target", {}).get("index")
38
+ )
39
+ except Exception:
40
+ idx = 0
41
  from constants import DEMO_LIST
42
+ if not (0 <= idx < len(DEMO_LIST)):
43
+ idx = 0
44
  return DEMO_LIST[idx]["description"]
45
 
46
  # ------------------------------------------------------------------
 
62
  if not code.strip():
63
  return
64
  app_py = wrap_html_in_gradio_app(code)
65
+ params = urllib.parse.urlencode({
66
+ "name": "new-space",
67
+ "sdk": "gradio"
68
+ })
69
+ files = {
70
+ "files[0][path]": "app.py",
71
+ "files[0][content]": app_py
72
+ }
73
+ files_params = urllib.parse.urlencode(files)
74
  url = f"https://huggingface.co/new-space?{params}&{files_params}"
75
  webbrowser.open_new_tab(url)
76
 
 
81
  if not code.strip():
82
  return
83
  html = wrap_html_in_static_app(code)
84
+ params = urllib.parse.urlencode({
85
+ "name": "new-space",
86
+ "sdk": "static"
87
+ })
88
+ files = {
89
+ "files[0][path]": "index.html",
90
+ "files[0][content]": html
91
+ }
92
+ files_params = urllib.parse.urlencode(files)
93
  url = f"https://huggingface.co/new-space?{params}&{files_params}"
94
  webbrowser.open_new_tab(url)
95
 
 
99
 
100
  def check_hf_space_url(url: str):
101
  import re
102
+ pattern = re.compile(r'^(?:https?://)?(?:huggingface\.co|hf\.co)/spaces/([\w-]+)/([\w-]+)$', re.IGNORECASE)
103
  m = pattern.match(url.strip())
104
+ if not m:
105
+ return False, None, None
106
+ return True, m.group(1), m.group(2)
107
 
108
  def fetch_hf_space_content(username: str, project: str) -> str:
109
  api = HfApi()
110
+ path = api.hf_hub_download(repo_id=f"{username}/{project}", filename="app.py", repo_type="space")
 
 
 
111
  with open(path, "r", encoding="utf-8") as f:
112
  return f.read()
113
 
 
121
  except Exception as e:
122
  return f"Error fetching project: {e}", ""
123
 
124
+ def handle_load_project(url: str):
125
+ status_message, content = load_project_from_url(url)
126
+ return status_message, content, "", url, [], []
127
+
128
  def deploy_to_user_space(code, space_name, sdk_choice, profile: Optional[gr.OAuthProfile] = None, token: Optional[gr.OAuthToken] = None):
129
  if not profile or not token or not token.token or token.token.startswith("hf_"):
130
  return gr.update(value="Please log in with a valid Hugging Face write token.", visible=True)
 
131
  api = HfApi(token=token.token)
132
+ repo_id = f"{profile.username}/{space_name.strip()}"
133
+ api.create_repo(repo_id=repo_id, repo_type="space", space_sdk=sdk_choice, exist_ok=True)
134
+ with tempfile.NamedTemporaryFile("w", delete=False) as f:
 
 
 
 
 
135
  f.write(code)
136
+ api.upload_file(path_or_fileobj=f.name, path_in_repo="app.py", repo_id=repo_id, repo_type="space")
137
+ os.unlink(f.name)
 
 
138
  return gr.update(value=f"✅ Deployed to https://huggingface.co/spaces/{repo_id}", visible=True)