wuhp commited on
Commit
7f5a4d4
·
verified ·
1 Parent(s): 3838b07

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -53
app.py CHANGED
@@ -2,16 +2,9 @@ import gradio as gr
2
  import json, time
3
  from huggingface_hub import create_repo, upload_file, constants
4
  from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status
5
- from google import genai # Gemini Python SDK
6
  from google.genai.types import Tool, GenerateContentConfig, GoogleSearch
7
 
8
- # — USER INFO & MODEL LISTING (from your reference) —
9
-
10
- def show_profile(profile: gr.OAuthProfile | None) -> str:
11
- if profile is None:
12
- return "*Not logged in.*"
13
- return f"✅ Logged in as **{profile.username}**"
14
-
15
  # — HELPERS FOR HF SPACE LOGS —
16
 
17
  def _get_space_jwt(repo_id: str):
@@ -30,9 +23,7 @@ def fetch_logs(repo_id: str, level: str):
30
  if raw.startswith(b"data: "):
31
  try:
32
  ev = json.loads(raw[len(b"data: "):].decode())
33
- ts = ev.get("timestamp","")
34
- txt = ev.get("data","")
35
- lines.append(f"[{ts}] {txt}")
36
  except:
37
  continue
38
  return "\n".join(lines)
@@ -51,10 +42,7 @@ def handle_user_message(
51
  if profile is None or oauth_token is None:
52
  return history + [{"role":"assistant","content":"⚠️ Please log in first."}], "", "", "<p>No Space yet.</p>"
53
 
54
- # initialize Gemini
55
  genai_client = genai.Client(api_key=gemini_api_key)
56
-
57
- # build the prompt history (including a system instruction)
58
  chat = [{
59
  "role":"system",
60
  "content":(
@@ -64,34 +52,58 @@ def handle_user_message(
64
  )
65
  }] + history
66
 
67
- filename = "app.py" if sdk_choice=="gradio" else "streamlit_app.py"
68
- build_logs = run_logs = ""
 
 
69
 
 
70
  for _ in range(5):
71
- # assemble tools
72
  tools = []
73
  if grounding_enabled:
74
  tools.append(Tool(google_search=GoogleSearch()))
75
-
76
- config = GenerateContentConfig(
77
- tools=tools,
78
- response_modalities=["TEXT"],
79
- )
80
 
81
  # call Gemini
82
- response = genai_client.models.generate_content(
83
  model="gemini-2.5-flash-preview-04-17",
84
  contents=[m["content"] for m in chat],
85
  config=config
86
  )
87
- ai_code = response.text
88
  chat.append({"role":"assistant", "content": ai_code})
89
 
90
- # write & deploy
91
- with open(filename, "w") as f:
92
  f.write(ai_code)
93
 
94
- repo_id = f"{profile.username}/{profile.username}-auto-space"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  create_repo(
96
  repo_id=repo_id,
97
  token=oauth_token.token,
@@ -99,23 +111,24 @@ def handle_user_message(
99
  repo_type="space",
100
  space_sdk=sdk_choice
101
  )
102
- upload_file(
103
- path_or_fileobj=filename,
104
- path_in_repo=filename,
105
- repo_id=repo_id,
106
- token=oauth_token.token,
107
- repo_type="space"
108
- )
 
109
 
110
- # fetch build & run logs
111
  build_logs = fetch_logs(repo_id, "build")
112
  run_logs = fetch_logs(repo_id, "run")
113
 
114
- # if no errors, stop looping
115
  if "ERROR" not in build_logs.upper() and "ERROR" not in run_logs.upper():
116
  break
117
 
118
- # otherwise feed logs back to Gemini
119
  chat.append({
120
  "role":"user",
121
  "content":(
@@ -133,39 +146,36 @@ def handle_user_message(
133
 
134
  # — BUILD THE UI —
135
 
 
 
 
136
  with gr.Blocks(title="HF Space Auto‑Builder (Gradio & Streamlit)") as demo:
137
- gr.Markdown("## Sign in with Hugging Face + Auto‑Build Spaces\n\n"
138
- "1. Sign in\n2. Enter your prompt\n3. Watch the code deploy & debug itself\n\n---")
139
 
140
- # LOGIN
141
  login_btn = gr.LoginButton(variant="huggingface", size="lg")
142
  status_md = gr.Markdown("*Not logged in.*")
143
- # automatically show profile on load & login
144
  demo.load(show_profile, inputs=None, outputs=status_md)
145
  login_btn.click(show_profile, inputs=None, outputs=status_md)
146
 
147
- # — SIDEBAR CONTROLS
148
- sdk_choice = gr.Radio(
149
- choices=["gradio","streamlit"],
150
- value="gradio",
151
- label="SDK template"
152
- )
153
- api_key = gr.Textbox(label="Gemini API Key", type="password")
154
- grounding = gr.Checkbox(label="Enable grounding", value=False)
155
 
156
- # CHAT INTERFACE & OUTPUTS
157
  chatbot = gr.Chatbot(type="messages")
158
- user_in = gr.Textbox(placeholder="e.g. Generate me a blurtest app…", label="Prompt")
159
  send_btn = gr.Button("Send")
160
 
161
  build_box = gr.Textbox(label="Build logs", lines=5, interactive=False)
162
  run_box = gr.Textbox(label="Run logs", lines=5, interactive=False)
163
  preview = gr.HTML("<p>No Space yet.</p>")
164
 
165
- # wire up the Send button
166
  send_btn.click(
167
  fn=handle_user_message,
168
- inputs=[chatbot, sdk_choice, api_key, grounding],
169
  outputs=[chatbot, build_box, run_box, preview]
170
  )
171
 
 
2
  import json, time
3
  from huggingface_hub import create_repo, upload_file, constants
4
  from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status
5
+ from google import genai # Gemini Python SDK
6
  from google.genai.types import Tool, GenerateContentConfig, GoogleSearch
7
 
 
 
 
 
 
 
 
8
  # — HELPERS FOR HF SPACE LOGS —
9
 
10
  def _get_space_jwt(repo_id: str):
 
23
  if raw.startswith(b"data: "):
24
  try:
25
  ev = json.loads(raw[len(b"data: "):].decode())
26
+ lines.append(f"[{ev.get('timestamp','')}] {ev.get('data','')}")
 
 
27
  except:
28
  continue
29
  return "\n".join(lines)
 
42
  if profile is None or oauth_token is None:
43
  return history + [{"role":"assistant","content":"⚠️ Please log in first."}], "", "", "<p>No Space yet.</p>"
44
 
 
45
  genai_client = genai.Client(api_key=gemini_api_key)
 
 
46
  chat = [{
47
  "role":"system",
48
  "content":(
 
52
  )
53
  }] + history
54
 
55
+ code_filename = "app.py" if sdk_choice=="gradio" else "streamlit_app.py"
56
+ config_filename = "README.md"
57
+ reqs_filename = "requirements.txt"
58
+ repo_id = f"{profile.username}/{profile.username}-auto-space"
59
 
60
+ build_logs = run_logs = ""
61
  for _ in range(5):
62
+ # build tools for grounding
63
  tools = []
64
  if grounding_enabled:
65
  tools.append(Tool(google_search=GoogleSearch()))
66
+ config = GenerateContentConfig(tools=tools, response_modalities=["TEXT"])
 
 
 
 
67
 
68
  # call Gemini
69
+ resp = genai_client.models.generate_content(
70
  model="gemini-2.5-flash-preview-04-17",
71
  contents=[m["content"] for m in chat],
72
  config=config
73
  )
74
+ ai_code = resp.text
75
  chat.append({"role":"assistant", "content": ai_code})
76
 
77
+ # write code file
78
+ with open(code_filename, "w") as f:
79
  f.write(ai_code)
80
 
81
+ # write README.md with correct app_file
82
+ readme = f"""---
83
+ title: Wuhp Auto Space
84
+ emoji: 🐢
85
+ colorFrom: red
86
+ colorTo: pink
87
+ sdk: {sdk_choice}
88
+ sdk_version: 1.44.1
89
+ app_file: {code_filename}
90
+ pinned: false
91
+ ---
92
+
93
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
94
+ """
95
+ with open(config_filename, "w") as f:
96
+ f.write(readme)
97
+
98
+ # write requirements.txt
99
+ if sdk_choice == "streamlit":
100
+ reqs = "streamlit\npandas\n"
101
+ else:
102
+ reqs = "gradio\npandas\n"
103
+ with open(reqs_filename, "w") as f:
104
+ f.write(reqs)
105
+
106
+ # create/update Space and upload all three files
107
  create_repo(
108
  repo_id=repo_id,
109
  token=oauth_token.token,
 
111
  repo_type="space",
112
  space_sdk=sdk_choice
113
  )
114
+ for fn in (code_filename, config_filename, reqs_filename):
115
+ upload_file(
116
+ path_or_fileobj=fn,
117
+ path_in_repo=fn,
118
+ repo_id=repo_id,
119
+ token=oauth_token.token,
120
+ repo_type="space"
121
+ )
122
 
123
+ # fetch logs
124
  build_logs = fetch_logs(repo_id, "build")
125
  run_logs = fetch_logs(repo_id, "run")
126
 
127
+ # stop if no errors
128
  if "ERROR" not in build_logs.upper() and "ERROR" not in run_logs.upper():
129
  break
130
 
131
+ # feed errors back
132
  chat.append({
133
  "role":"user",
134
  "content":(
 
146
 
147
  # — BUILD THE UI —
148
 
149
+ def show_profile(profile):
150
+ return f"✅ Logged in as **{profile.username}**" if profile else "*Not logged in.*"
151
+
152
  with gr.Blocks(title="HF Space Auto‑Builder (Gradio & Streamlit)") as demo:
153
+ gr.Markdown("## Sign in + Auto‑Build Spaces\n\n"
154
+ "1. Sign in\n2. Enter your prompt\n3. Watch the code, README, and requirements deploy & debug\n\n---")
155
 
156
+ # LOGIN
157
  login_btn = gr.LoginButton(variant="huggingface", size="lg")
158
  status_md = gr.Markdown("*Not logged in.*")
 
159
  demo.load(show_profile, inputs=None, outputs=status_md)
160
  login_btn.click(show_profile, inputs=None, outputs=status_md)
161
 
162
+ # CONTROLS
163
+ sdk_choice = gr.Radio(["gradio","streamlit"], value="gradio", label="SDK template")
164
+ api_key = gr.Textbox(label="Gemini API Key", type="password")
165
+ grounding = gr.Checkbox(label="Enable grounding", value=False)
 
 
 
 
166
 
167
+ # CHAT + OUTPUTS
168
  chatbot = gr.Chatbot(type="messages")
169
+ user_in = gr.Textbox(placeholder="e.g. Create me a CSV inspector…", label="Prompt")
170
  send_btn = gr.Button("Send")
171
 
172
  build_box = gr.Textbox(label="Build logs", lines=5, interactive=False)
173
  run_box = gr.Textbox(label="Run logs", lines=5, interactive=False)
174
  preview = gr.HTML("<p>No Space yet.</p>")
175
 
 
176
  send_btn.click(
177
  fn=handle_user_message,
178
+ inputs=[chatbot, sdk_choice, api_key, grounding, gr.State(), gr.State()],
179
  outputs=[chatbot, build_box, run_box, preview]
180
  )
181