wuhp commited on
Commit
0df9635
Β·
verified Β·
1 Parent(s): 10a9edd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -117
app.py CHANGED
@@ -1,136 +1,218 @@
1
- import os
2
- import json
3
  import gradio as gr
4
- from huggingface_hub import create_repo, list_models, upload_file, constants
5
  from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status
6
  from google import genai
7
  from google.genai import types
8
 
9
- # β€” USER INFO & MODEL LISTING β€”
10
-
11
- def show_profile(profile: gr.OAuthProfile | None) -> str:
12
- if profile is None:
13
- return "*Not signed in.*"
14
- return f"βœ… Signed in as **{profile.username}**"
15
-
16
- def list_private_models(profile: gr.OAuthProfile | None, oauth_token: gr.OAuthToken | None) -> str:
17
- if profile is None or oauth_token is None:
18
- return "Please sign in to HF."
19
- models = list_models(author=profile.username, token=oauth_token.token)
20
- if not models:
21
- return "No models found."
22
- return "Models:\n" + "\n".join(f"- {m.id} ({'private' if m.private else 'public'})" for m in models)
23
-
24
- # --- GLOBALS ---
25
- client: genai.Client | None = None
26
- chat: genai.chats.Chat | None = None
27
-
28
- # --- System instruction for Gemini ---
29
- system_instruction = (
30
- "You are a helpful assistant that writes, debugs, and pushes code to Hugging Face Spaces. "
31
- "Treat Spaces as a sandbox: create spaces, upload code, and debug via function calling. "
32
- "Always respond in JSON with {'success','data','message'}."
33
- )
34
-
35
- # --- Function declarations for logs ---
36
- get_build_logs_decl = {
37
- "name": "get_build_logs",
38
- "description": "Fetches build logs for a Space",
39
- "parameters": {"type":"object","properties":{"repo_id":{"type":"string"}},"required":["repo_id"]}
40
- }
41
- get_container_logs_decl = {
42
- "name": "get_container_logs",
43
- "description": "Fetches container logs for a Space",
44
- "parameters": {"type":"object","properties":{"repo_id":{"type":"string"}},"required":["repo_id"]}
45
- }
46
- tools = [ types.Tool(function_declarations=[get_build_logs_decl, get_container_logs_decl]) ]
47
-
48
- # --- HF helpers ---
49
- def create_space_backend(username: str, hf_token: str, repo_name: str, sdk: str) -> str:
50
- repo_id = f"{username}/{repo_name}"
51
- create_repo(repo_id=repo_id, token=hf_token, exist_ok=True, repo_type="space", space_sdk=sdk)
52
- return repo_id
53
-
54
- def fetch_logs(repo_id: str, level: str) -> list[dict]:
55
  jwt_url = f"{constants.ENDPOINT}/api/spaces/{repo_id}/jwt"
56
  r = get_session().get(jwt_url, headers=build_hf_headers())
57
  hf_raise_for_status(r)
58
  jwt = r.json()["token"]
59
- logs_url = f"https://api.hf.space/v1/{repo_id}/logs/{level}"
60
- records = []
61
- with get_session().get(logs_url, headers=build_hf_headers(token=jwt), stream=True) as resp:
 
62
  hf_raise_for_status(resp)
63
  for raw in resp.iter_lines():
64
- if raw.startswith(b"data: "):
65
- try:
66
- ev = json.loads(raw[len(b"data: "):].decode())
67
- records.append({"timestamp": ev.get("timestamp"), "message": ev.get("data")})
68
- except:
69
- pass
70
- return records
71
-
72
- # --- Chat init & respond ---
73
- def init_chat(repo_name: str, sdk: str, gemini_key: str, hf_profile: gr.OAuthProfile, hf_token: gr.OAuthToken):
74
- global client, chat
75
- if hf_profile is None or hf_token is None:
76
- return {"success": False, "data": None, "message": "Please sign in with Hugging Face."}, ""
77
- if not gemini_key:
78
- return {"success": False, "data": None, "message": "Missing Gemini API key."}, ""
79
- repo_id = create_space_backend(hf_profile.username, hf_token.token, repo_name, sdk)
80
- os.environ["HF_TOKEN"] = hf_token.token
81
- client = genai.Client(api_key=gemini_key)
82
- chat = client.chats.create(
83
- model="gemini-2.5-flash-preview-04-17",
84
- config=types.GenerateContentConfig(system_instruction=system_instruction, tools=tools, temperature=0)
85
- )
86
- return {"success": True, "data": None, "message": f"Sandbox ready: {repo_id}"}, repo_id
87
-
88
- def chatbot_respond(message: str, history: list, repo_id: str, gemini_key: str):
89
- global chat
90
- if chat is None:
91
- history.append((None, "Error: chat not initialized."))
92
- return history
93
- resp = chat.send_message(message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  part = resp.candidates[0].content.parts[0]
 
 
95
  if part.function_call:
96
- fn = part.function_call
97
- args = json.loads(fn.args)
98
- level = "build" if fn.name == "get_build_logs" else "run"
99
- logs = fetch_logs(repo_id, level)
100
- resp2 = chat.send_message("", function_response={fn.name: logs})
101
- reply = resp2.candidates[0].content.parts[0].text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  else:
103
- reply = part.text
104
- history.append((message, reply))
105
- return history
106
-
107
- # --- UI ---
108
- with gr.Blocks() as demo:
109
- gr.Markdown("# HF Code Sandbox Chat")
110
-
111
- # --- Hugging Face Login ---
112
- login_btn = gr.LoginButton("Sign in with HF", variant="huggingface")
113
- status_md = gr.Markdown("*Not signed in.*")
114
- models_md = gr.Markdown()
115
- login_btn.click(show_profile, inputs=[login_btn], outputs=[status_md])
116
- login_btn.click(list_private_models, inputs=[login_btn, login_btn.token], outputs=[models_md])
117
-
118
- # --- Layout ---
 
 
119
  with gr.Row():
120
- with gr.Column(scale=2):
121
- gr.Markdown("### Setup Sandbox")
122
  gemini_key = gr.Textbox(label="Gemini API Key", type="password")
123
- repo_name = gr.Textbox(label="Space Name")
124
- sdk = gr.Radio(choices=["gradio", "streamlit"], label="SDK", value="gradio")
125
- init_btn = gr.Button("Initialize Sandbox")
126
- init_status = gr.JSON()
127
- repo_store = gr.State("")
128
- init_btn.click(init_chat, inputs=[repo_name, sdk, gemini_key, login_btn, login_btn.token], outputs=[init_status, repo_store])
129
-
130
- with gr.Column(scale=8):
131
- chatbot = gr.Chatbot(type="messages")
132
- user_input = gr.Textbox(show_label=False, placeholder="Ask the sandbox to write/debug code...")
133
- user_input.submit(chatbot_respond, inputs=[user_input, chatbot, repo_store, gemini_key], outputs=[chatbot])
 
 
 
 
 
 
 
134
 
135
  if __name__ == "__main__":
136
  demo.launch()
 
1
+ import os, json
 
2
  import gradio as gr
3
+ from huggingface_hub import create_repo, upload_file, list_repo_files, constants
4
  from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status
5
  from google import genai
6
  from google.genai import types
7
 
8
+ # β€”β€”β€” HELPERS FOR HF SPACES β€”β€”β€”
9
+
10
+ def create_space(repo_name: str, sdk: str, hf_token: str):
11
+ """Create or get a HF Space, return (repo_id, log, iframe)."""
12
+ token = hf_token or os.getenv("HF_TOKEN", "")
13
+ if not token:
14
+ return None, "⚠️ No HF token provided.", ""
15
+ os.environ["HF_TOKEN"] = token
16
+ repo_id = f"{os.getenv('HF_USERNAME', '')}/{repo_name}"
17
+ create_repo(
18
+ repo_id=repo_id,
19
+ token=token,
20
+ exist_ok=True,
21
+ repo_type="space",
22
+ space_sdk=sdk,
23
+ )
24
+ url = f"https://huggingface.co/spaces/{repo_id}"
25
+ return repo_id, f"βœ… Space ready: {url} (SDK={sdk})", f'<iframe src="{url}" width="100%" height="400px"></iframe>'
26
+
27
+ def upload_file_to_space(repo_id: str, local_path: str, hf_token: str):
28
+ """Upload a local file to the Space."""
29
+ token = hf_token or os.getenv("HF_TOKEN", "")
30
+ if not (repo_id and token and os.path.exists(local_path)):
31
+ return "⚠️ Missing repo_id, token, or file not found."
32
+ os.environ["HF_TOKEN"] = token
33
+ upload_file(
34
+ path_or_fileobj=local_path,
35
+ path_in_repo=os.path.basename(local_path),
36
+ repo_id=repo_id,
37
+ token=token,
38
+ repo_type="space",
39
+ )
40
+ return f"βœ… Uploaded `{os.path.basename(local_path)}` to `{repo_id}`"
41
+
42
+ def fetch_logs(repo_id: str, level: str, hf_token: str):
43
+ """Stream build or run logs."""
44
+ token = hf_token or os.getenv("HF_TOKEN", "")
45
+ if not (repo_id and token):
46
+ return "⚠️ Missing repo_id or HF token."
47
+ # 1) get JWT
 
 
 
 
 
 
48
  jwt_url = f"{constants.ENDPOINT}/api/spaces/{repo_id}/jwt"
49
  r = get_session().get(jwt_url, headers=build_hf_headers())
50
  hf_raise_for_status(r)
51
  jwt = r.json()["token"]
52
+ # 2) stream
53
+ url = f"https://api.hf.space/v1/{repo_id}/logs/{level}"
54
+ lines = []
55
+ with get_session().get(url, headers=build_hf_headers(token=jwt), stream=True) as resp:
56
  hf_raise_for_status(resp)
57
  for raw in resp.iter_lines():
58
+ if not raw.startswith(b"data: "): continue
59
+ ev = json.loads(raw[len(b"data: "):])
60
+ ts, txt = ev.get("timestamp",""), ev.get("data","")
61
+ lines.append(f"[{ts}] {txt}")
62
+ return "\n".join(lines)
63
+
64
+ def list_files(repo_id: str, hf_token: str):
65
+ """List files in the Space repo."""
66
+ token = hf_token or os.getenv("HF_TOKEN", "")
67
+ if not (repo_id and token):
68
+ return "⚠️ Missing repo_id or HF token."
69
+ return "\n".join(list_repo_files(repo_id, token=token, repo_type="space"))
70
+
71
+
72
+ # β€”β€”β€” GEMINI FUNCTION DECLARATIONS β€”β€”β€”
73
+
74
+ func_decls = [
75
+ {
76
+ "name": "create_space",
77
+ "description": "Create or get a Hugging Face Space",
78
+ "parameters": {
79
+ "type":"object",
80
+ "properties":{
81
+ "repo_name":{"type":"string"},
82
+ "sdk":{"type":"string","enum":["gradio","streamlit"]}
83
+ },
84
+ "required":["repo_name","sdk"]
85
+ }
86
+ },
87
+ {
88
+ "name":"upload_file",
89
+ "description":"Upload a file to the Space",
90
+ "parameters":{
91
+ "type":"object",
92
+ "properties":{
93
+ "repo_id":{"type":"string"},
94
+ "local_path":{"type":"string"}
95
+ },
96
+ "required":["repo_id","local_path"]
97
+ }
98
+ },
99
+ {
100
+ "name":"list_files",
101
+ "description":"List files in the Space",
102
+ "parameters":{
103
+ "type":"object",
104
+ "properties":{"repo_id":{"type":"string"}},
105
+ "required":["repo_id"]
106
+ }
107
+ },
108
+ {
109
+ "name":"get_build_logs",
110
+ "description":"Fetch the build logs",
111
+ "parameters":{
112
+ "type":"object",
113
+ "properties":{"repo_id":{"type":"string"}},
114
+ "required":["repo_id"]
115
+ }
116
+ },
117
+ {
118
+ "name":"get_run_logs",
119
+ "description":"Fetch the run logs",
120
+ "parameters":{
121
+ "type":"object",
122
+ "properties":{"repo_id":{"type":"string"}},
123
+ "required":["repo_id"]
124
+ }
125
+ },
126
+ ]
127
+
128
+ # β€”β€”β€” CHAT PROCESSING β€”β€”β€”
129
+
130
+ def process_message(user_msg, gemini_key, repo_name, sdk, hf_token, chat_history, session):
131
+ # init Gemini chat
132
+ if session.get("chat") is None:
133
+ client = genai.Client(api_key=gemini_key)
134
+ cfg = types.GenerateContentConfig(
135
+ system_instruction="You are a HF Spaces assistant. Use functions to manage spaces.",
136
+ temperature=0,
137
+ tools=[ types.Tool(function_declarations=func_decls) ]
138
+ )
139
+ session["chat"] = client.chats.create(model="gemini-2.0-flash", config=cfg)
140
+ session["repo_id"] = None
141
+
142
+ chat = session["chat"]
143
+ # record user
144
+ chat_history = chat_history + [(user_msg, None)]
145
+ resp = chat.send_message(user_msg)
146
  part = resp.candidates[0].content.parts[0]
147
+
148
+ # if function call requested
149
  if part.function_call:
150
+ name = part.function_call.name
151
+ args = json.loads(part.function_call.args)
152
+ # dispatch
153
+ if name=="create_space":
154
+ rid, log, iframe = create_space(args["repo_name"], args["sdk"], hf_token)
155
+ session["repo_id"] = rid
156
+ result = {"repo_id":rid,"log":log,"iframe":iframe}
157
+ elif name=="upload_file":
158
+ result = {"log": upload_file_to_space(args["repo_id"], args["local_path"], hf_token)}
159
+ elif name=="list_files":
160
+ result = {"files": list_files(args["repo_id"], hf_token)}
161
+ elif name=="get_build_logs":
162
+ result = {"log": fetch_logs(args["repo_id"], "build", hf_token)}
163
+ elif name=="get_run_logs":
164
+ result = {"log": fetch_logs(args["repo_id"], "run", hf_token)}
165
+ else:
166
+ result = {"log":f"⚠️ Unknown function {name}"}
167
+
168
+ # feed function result back to chat
169
+ chat.send_message(
170
+ types.Content(
171
+ role="function",
172
+ parts=[ types.Part(function_call=part.function_call, function_response=json.dumps(result)) ]
173
+ )
174
+ )
175
+ final = chat.get_history()[-1].parts[0].text
176
  else:
177
+ final = part.text
178
+
179
+ # update panels
180
+ iframe = session.get("iframe", "")
181
+ log = session.get("log", "")
182
+ files = session.get("files", "")
183
+
184
+ if part.function_call:
185
+ session["iframe"] = result.get("iframe", iframe)
186
+ session["log"] = result.get("log", log)
187
+ session["files"] = result.get("files", files)
188
+
189
+ chat_history[-1] = (user_msg, final)
190
+ return chat_history, session["iframe"], session["log"], session["files"], session
191
+
192
+ # β€”β€”β€” GRADIO INTERFACE β€”β€”β€”
193
+
194
+ with gr.Blocks(title="HF Spaces β†’ Gemini Chat") as demo:
195
  with gr.Row():
196
+ with gr.Column(scale=1):
 
197
  gemini_key = gr.Textbox(label="Gemini API Key", type="password")
198
+ repo_name = gr.Textbox(label="Space name", placeholder="my-space")
199
+ sdk_choice = gr.Radio(["gradio","streamlit"], value="gradio", label="SDK")
200
+ hf_token = gr.Textbox(label="HF Token (opt)", type="password")
201
+ with gr.Column(scale=3):
202
+ chatbox = gr.Chatbot()
203
+ user_input = gr.Textbox(show_label=False, placeholder="e.g. Create Space")
204
+ send_btn = gr.Button("Send")
205
+
206
+ iframe_out = gr.HTML(label="Space Preview")
207
+ log_out = gr.Textbox(label="Latest Log", lines=8)
208
+ files_out = gr.Textbox(label="Files in Space", lines=4)
209
+
210
+ state = gr.State({})
211
+ send_btn.click(
212
+ fn=process_message,
213
+ inputs=[user_input, gemini_key, repo_name, sdk_choice, hf_token, chatbox, state],
214
+ outputs=[chatbox, iframe_out, log_out, files_out, state]
215
+ )
216
 
217
  if __name__ == "__main__":
218
  demo.launch()