wuhp commited on
Commit
2aae709
·
verified ·
1 Parent(s): 5ee840c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -29
app.py CHANGED
@@ -38,9 +38,6 @@ def get_sdk_version(sdk_choice: str) -> str:
38
  return "UNKNOWN"
39
 
40
  def extract_code(text: str) -> str:
41
- """
42
- Extract the last ```…``` block. If none, return whole text.
43
- """
44
  blocks = re.findall(r"```(?:\w*\n)?([\s\S]*?)```", text)
45
  return blocks[-1].strip() if blocks else text.strip()
46
 
@@ -69,7 +66,7 @@ def fetch_logs(repo_id: str, level: str) -> str:
69
  continue
70
  return "\n".join(lines)
71
 
72
- # — CORE LOOP (now a generator) —
73
 
74
  def handle_user_message(
75
  history,
@@ -80,12 +77,8 @@ def handle_user_message(
80
  profile: gr.OAuthProfile | None,
81
  oauth_token: gr.OAuthToken | None
82
  ):
83
- # 1) Require login
84
  if profile is None or oauth_token is None:
85
- yield (
86
- history + [{"role":"assistant","content":"⚠️ Please log in first."}],
87
- "", "", "<p>No Space yet.</p>"
88
- )
89
  return
90
 
91
  username = profile.username
@@ -93,15 +86,12 @@ def handle_user_message(
93
  repo_id = f"{username}/{repo_name}"
94
  preview_url = f"https://{username}-{space_suffix}.hf.space"
95
  iframe_html = (
96
- f'<iframe src="{preview_url}" '
97
- f'width="100%" height="500px" frameborder="0"></iframe>'
98
  )
99
 
100
- # 2) Initial “in progress” state
101
- msg_init = history + [{"role":"assistant","content":"🚀 Generating and deploying your Space..."}]
102
- yield msg_init, "Fetching logs…", "Fetching logs…", iframe_html
103
 
104
- # 3) LLM + push loop
105
  client = genai.Client(api_key=gemini_api_key)
106
  system_msg = {
107
  "role":"system",
@@ -119,14 +109,13 @@ def handle_user_message(
119
  for _ in range(5):
120
  tools = [Tool(google_search=GoogleSearch())] if grounding_enabled else []
121
  cfg = GenerateContentConfig(tools=tools, response_modalities=["TEXT"])
122
- resp = client.models.generate_content(
123
  model="gemini-2.5-flash-preview-04-17",
124
  contents=[m["content"] for m in chat],
125
  config=cfg
126
  )
127
 
128
- raw_code = resp.text
129
- code = extract_code(raw_code)
130
  chat.append({"role":"assistant","content":code})
131
 
132
  # Write files
@@ -150,7 +139,7 @@ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-
150
  extra = "streamlit\n" if sdk_choice=="streamlit" else "gradio\n"
151
  with open(reqs_fn, "w") as f: f.write(base_reqs + extra)
152
 
153
- # Push to HF
154
  create_repo(
155
  repo_id=repo_id,
156
  token=oauth_token.token,
@@ -167,19 +156,15 @@ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-
167
  repo_type="space"
168
  )
169
 
170
- # Fetch logs
171
  build_logs = fetch_logs(repo_id, "build")
172
  run_logs = fetch_logs(repo_id, "run")
173
-
174
- # Yield incremental update
175
  msgs = [{"role":m["role"], "content":m["content"]} for m in chat if m["role"]!="system"]
176
  yield msgs, build_logs, run_logs, iframe_html
177
 
178
- # If successful, stop retrying
179
  if "ERROR" not in build_logs.upper() and "ERROR" not in run_logs.upper():
180
  break
181
 
182
- # Otherwise feed logs back to LLM
183
  chat.append({
184
  "role":"user",
185
  "content":(
@@ -190,7 +175,7 @@ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-
190
  })
191
  time.sleep(2)
192
 
193
- # — REFRESH LOGS (unchanged)
194
 
195
  def refresh_logs(
196
  space_suffix: str,
@@ -202,7 +187,7 @@ def refresh_logs(
202
  repo_id = f"{profile.username}/{profile.username}-{space_suffix}"
203
  return fetch_logs(repo_id, "build"), fetch_logs(repo_id, "run")
204
 
205
- # — BUILD THE UI —
206
 
207
  with gr.Blocks(title="HF Space Auto‑Builder") as demo:
208
  gr.Markdown("## Sign in + Auto‑Build Spaces\n\n"
@@ -236,11 +221,11 @@ with gr.Blocks(title="HF Space Auto‑Builder") as demo:
236
  fn=handle_user_message,
237
  inputs=[chatbot, sdk_choice, api_key, grounding, space_suffix],
238
  outputs=[chatbot, build_box, run_box, preview],
239
- queue=True,
240
- stream=True
241
  )
242
 
243
- # Manual log refresh (optional)
244
  refresh_btn = gr.Button("Refresh Logs")
245
  refresh_btn.click(
246
  fn=refresh_logs,
 
38
  return "UNKNOWN"
39
 
40
  def extract_code(text: str) -> str:
 
 
 
41
  blocks = re.findall(r"```(?:\w*\n)?([\s\S]*?)```", text)
42
  return blocks[-1].strip() if blocks else text.strip()
43
 
 
66
  continue
67
  return "\n".join(lines)
68
 
69
+ # — CORE LOOP (generator) —
70
 
71
  def handle_user_message(
72
  history,
 
77
  profile: gr.OAuthProfile | None,
78
  oauth_token: gr.OAuthToken | None
79
  ):
 
80
  if profile is None or oauth_token is None:
81
+ yield history + [{"role":"assistant","content":"⚠️ Please log in first."}], "", "", "<p>No Space yet.</p>"
 
 
 
82
  return
83
 
84
  username = profile.username
 
86
  repo_id = f"{username}/{repo_name}"
87
  preview_url = f"https://{username}-{space_suffix}.hf.space"
88
  iframe_html = (
89
+ f'<iframe src="{preview_url}" width="100%" height="500px" frameborder="0"></iframe>'
 
90
  )
91
 
92
+ # Initial “in progress” update
93
+ yield history + [{"role":"assistant","content":"🚀 Generating and deploying your Space..."}], "Fetching logs…", "Fetching logs…", iframe_html
 
94
 
 
95
  client = genai.Client(api_key=gemini_api_key)
96
  system_msg = {
97
  "role":"system",
 
109
  for _ in range(5):
110
  tools = [Tool(google_search=GoogleSearch())] if grounding_enabled else []
111
  cfg = GenerateContentConfig(tools=tools, response_modalities=["TEXT"])
112
+ resp = client.models.generate_content(
113
  model="gemini-2.5-flash-preview-04-17",
114
  contents=[m["content"] for m in chat],
115
  config=cfg
116
  )
117
 
118
+ code = extract_code(resp.text)
 
119
  chat.append({"role":"assistant","content":code})
120
 
121
  # Write files
 
139
  extra = "streamlit\n" if sdk_choice=="streamlit" else "gradio\n"
140
  with open(reqs_fn, "w") as f: f.write(base_reqs + extra)
141
 
142
+ # Push to Hugging Face
143
  create_repo(
144
  repo_id=repo_id,
145
  token=oauth_token.token,
 
156
  repo_type="space"
157
  )
158
 
159
+ # Fetch and stream logs & iframe
160
  build_logs = fetch_logs(repo_id, "build")
161
  run_logs = fetch_logs(repo_id, "run")
 
 
162
  msgs = [{"role":m["role"], "content":m["content"]} for m in chat if m["role"]!="system"]
163
  yield msgs, build_logs, run_logs, iframe_html
164
 
 
165
  if "ERROR" not in build_logs.upper() and "ERROR" not in run_logs.upper():
166
  break
167
 
 
168
  chat.append({
169
  "role":"user",
170
  "content":(
 
175
  })
176
  time.sleep(2)
177
 
178
+ # — REFRESH LOGS —
179
 
180
  def refresh_logs(
181
  space_suffix: str,
 
187
  repo_id = f"{profile.username}/{profile.username}-{space_suffix}"
188
  return fetch_logs(repo_id, "build"), fetch_logs(repo_id, "run")
189
 
190
+ # — BUILD THE UI —
191
 
192
  with gr.Blocks(title="HF Space Auto‑Builder") as demo:
193
  gr.Markdown("## Sign in + Auto‑Build Spaces\n\n"
 
221
  fn=handle_user_message,
222
  inputs=[chatbot, sdk_choice, api_key, grounding, space_suffix],
223
  outputs=[chatbot, build_box, run_box, preview],
224
+ queue=True
225
+ # stream=True ← removed, not supported :contentReference[oaicite:2]{index=2}
226
  )
227
 
228
+ # (Optional) manual refresh
229
  refresh_btn = gr.Button("Refresh Logs")
230
  refresh_btn.click(
231
  fn=refresh_logs,