wuhp commited on
Commit
c44aed0
·
verified ·
1 Parent(s): 0542eae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -89
app.py CHANGED
@@ -1,23 +1,23 @@
1
  import os
2
  import json
 
3
  from huggingface_hub import create_repo, list_models, upload_file, constants
4
  from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status
5
- import gradio as gr
6
  from google import genai
7
  from google.genai import types
8
 
9
  # --- Globals ---
10
- client = None # Will hold Gemini client
11
- chat = None # Will hold Gemini chat session
12
 
13
- # --- System prompt for Gemini ---
14
  system_instruction = (
15
  "You are a helpful assistant that writes, debugs, and pushes code to Hugging Face Spaces. "
16
- "Treat Hugging Face as a sandbox: create spaces, upload code, and debug via function calls. "
17
- "Respond in JSON with {success, data, message}."
18
  )
19
 
20
- # --- Function declarations for logs (behind the scenes) ---
21
  get_build_logs_decl = {
22
  "name": "get_build_logs",
23
  "description": "Fetches build logs for a Space",
@@ -28,118 +28,93 @@ get_container_logs_decl = {
28
  "description": "Fetches container logs for a Space",
29
  "parameters": {"type":"object","properties":{"repo_id":{"type":"string"}},"required":["repo_id"]}
30
  }
31
- tools = [types.Tool(function_declarations=[get_build_logs_decl, get_container_logs_decl])]
32
 
33
- # --- Core Hugging Face functions ---
34
- def _fetch_space_logs_level(repo_id: str, level: str):
 
 
 
 
 
35
  jwt_url = f"{constants.ENDPOINT}/api/spaces/{repo_id}/jwt"
36
  r = get_session().get(jwt_url, headers=build_hf_headers())
37
  hf_raise_for_status(r)
38
  jwt = r.json()["token"]
39
- logs_url = f"https://api.hf.space/v1/{repo_id}/logs/{level}"
40
- records = []
41
- with get_session().get(logs_url, headers=build_hf_headers(token=jwt), stream=True) as resp:
42
  hf_raise_for_status(resp)
43
  for raw in resp.iter_lines():
44
- if not raw.startswith(b"data: "): continue
45
- try:
46
- event = json.loads(raw[len(b"data: "):].decode())
47
- records.append({"timestamp": event.get("timestamp"), "message": event.get("data")})
48
- except:
49
- pass
50
- return records
51
 
52
- # --- Backend: create HF Space ---
53
- def create_space_backend(username: str, hf_token: str, repo_name: str, sdk: str) -> str:
54
- repo_id = f"{username}/{repo_name}"
55
- create_repo(
56
- repo_id=repo_id,
57
- token=hf_token,
58
- exist_ok=True,
59
- repo_type="space",
60
- space_sdk=sdk
61
- )
62
- return repo_id
63
-
64
- # --- Chat init & respond handlers ---
65
-
66
- def init_chat(repo_name: str, sdk: str, api_key: str, hf_profile: gr.OAuthProfile, hf_token: gr.OAuthToken):
67
  global client, chat
68
- # Validate inputs
69
- if not api_key:
70
- return {"success": False, "data": None, "message": "Missing Gemini API key."}, ""
71
  if hf_profile is None or hf_token is None:
72
- return {"success": False, "data": None, "message": "Please sign in with Hugging Face."}, ""
73
- # Create HF sandbox space
 
 
74
  repo_id = create_space_backend(hf_profile.username, hf_token.token, repo_name, sdk)
75
  os.environ["HF_TOKEN"] = hf_token.token
76
- # Init Gemini client & chat
77
- client = genai.Client(api_key=api_key)
78
  chat = client.chats.create(
79
  model="gemini-2.5-flash-preview-04-17",
80
- config=types.GenerateContentConfig(
81
- system_instruction=system_instruction,
82
- tools=tools,
83
- temperature=0
84
- )
85
  )
86
- return {"success": True, "data": None, "message": f"Sandbox ready: {repo_id}"}, repo_id
87
 
88
-
89
- def chatbot_respond(message: str, history: list, repo_id: str, api_key: str):
90
  global chat
91
  if chat is None:
92
  history.append((None, "Error: chat not initialized."))
93
  return history
94
- response = chat.send_message(message)
95
- part = response.candidates[0].content.parts[0]
96
  if part.function_call:
97
- fn = part.function_call
98
- args = json.loads(fn.args)
99
- result = _fetch_space_logs_level(repo_id, "build" if fn.name=="get_build_logs" else "run")
100
- response2 = chat.send_message("", function_response={fn.name: result})
101
- reply = response2.candidates[0].content.parts[0].text
 
102
  else:
103
- reply = part.text
104
  history.append((message, reply))
105
  return history
106
 
107
- # --- UI: Chatbot + Sidebar ---
108
- with gr.Blocks(title="HF Code Sandbox Chat") as demo:
109
- # Top bar: HF login
110
- with gr.Row():
111
- login_btn = gr.LoginButton("Sign in with HF", variant="huggingface")
112
- login_status = gr.Markdown("*Not signed in.*")
113
- login_btn.click(
114
- lambda profile: f"✅ Logged in as {profile.username}" if profile else "*Not signed in.*",
115
- inputs=[login_btn], outputs=[login_status]
116
- )
117
 
118
  with gr.Row():
119
- # Sidebar
120
  with gr.Column(scale=2):
121
- gr.Markdown("### 🏗️ Create New Space Sandbox")
122
- api_key = gr.Textbox(label="Gemini API Key", placeholder="sk-...", type="password")
123
- repo_name = gr.Textbox(label="Space Name", placeholder="my-sandbox")
124
- sdk_selector = gr.Radio(label="SDK", choices=["gradio","streamlit"], value="gradio")
125
- create_btn = gr.Button("Initialize Sandbox")
126
- create_status = gr.JSON(label="Initialization Status")
127
  repo_store = gr.State("")
128
- create_btn.click(
129
- init_chat,
130
- inputs=[repo_name, sdk_selector, api_key, login_btn, login_btn],
131
- outputs=[create_status, repo_store]
132
- )
133
-
134
- # Chat area
135
  with gr.Column(scale=8):
136
- chatbot = gr.Chatbot()
137
- user_input = gr.Textbox(show_label=False, placeholder="Ask the sandbox to write or debug code...")
138
- user_input.submit(
139
- chatbot_respond,
140
- inputs=[user_input, chatbot, repo_store, api_key],
141
- outputs=[chatbot]
142
- )
143
 
144
  if __name__ == "__main__":
145
  demo.launch()
 
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
  # --- Globals ---
10
+ client = None
11
+ chat = None
12
 
13
+ # --- System instruction for Gemini ---
14
  system_instruction = (
15
  "You are a helpful assistant that writes, debugs, and pushes code to Hugging Face Spaces. "
16
+ "Treat Spaces as a sandbox: create, upload, debug. "
17
+ "Use function calling for logs and respond in JSON {success, data, message}."
18
  )
19
 
20
+ # --- Function declarations for logs ---
21
  get_build_logs_decl = {
22
  "name": "get_build_logs",
23
  "description": "Fetches build logs for a Space",
 
28
  "description": "Fetches container logs for a Space",
29
  "parameters": {"type":"object","properties":{"repo_id":{"type":"string"}},"required":["repo_id"]}
30
  }
31
+ tools = [ types.Tool(function_declarations=[get_build_logs_decl, get_container_logs_decl]) ]
32
 
33
+ # --- HF helpers ---
34
+ def create_space_backend(username, hf_token, repo_name, sdk):
35
+ repo_id = f"{username}/{repo_name}"
36
+ create_repo(repo_id=repo_id, token=hf_token, exist_ok=True, repo_type="space", space_sdk=sdk)
37
+ return repo_id
38
+
39
+ def fetch_logs(repo_id, level):
40
  jwt_url = f"{constants.ENDPOINT}/api/spaces/{repo_id}/jwt"
41
  r = get_session().get(jwt_url, headers=build_hf_headers())
42
  hf_raise_for_status(r)
43
  jwt = r.json()["token"]
44
+ url = f"https://api.hf.space/v1/{repo_id}/logs/{level}"
45
+ lines=[]
46
+ with get_session().get(url, headers=build_hf_headers(token=jwt), stream=True) as resp:
47
  hf_raise_for_status(resp)
48
  for raw in resp.iter_lines():
49
+ if raw.startswith(b"data: "):
50
+ try:
51
+ ev=json.loads(raw[len(b"data: "):].decode())
52
+ lines.append({"timestamp":ev.get("timestamp"),"message":ev.get("data")})
53
+ except: pass
54
+ return lines
 
55
 
56
+ # --- Chat init & respond ---
57
+ def init_chat(repo_name, sdk, gemini_key, hf_profile, hf_token):
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  global client, chat
59
+ # Validate
 
 
60
  if hf_profile is None or hf_token is None:
61
+ return {"success":False,"data":None,"message":"Please sign in with HF."}, ""
62
+ if not gemini_key:
63
+ return {"success":False,"data":None,"message":"Missing Gemini API key."}, ""
64
+ # create space
65
  repo_id = create_space_backend(hf_profile.username, hf_token.token, repo_name, sdk)
66
  os.environ["HF_TOKEN"] = hf_token.token
67
+ # init Gemini
68
+ client = genai.Client(api_key=gemini_key)
69
  chat = client.chats.create(
70
  model="gemini-2.5-flash-preview-04-17",
71
+ config=types.GenerateContentConfig(system_instruction=system_instruction, tools=tools, temperature=0)
 
 
 
 
72
  )
73
+ return {"success":True,"data":None,"message":f"Sandbox ready: {repo_id}"}, repo_id
74
 
75
+ def chatbot_respond(message, history, repo_id, gemini_key):
 
76
  global chat
77
  if chat is None:
78
  history.append((None, "Error: chat not initialized."))
79
  return history
80
+ resp = chat.send_message(message)
81
+ part = resp.candidates[0].content.parts[0]
82
  if part.function_call:
83
+ fn=part.function_call
84
+ args=json.loads(fn.args)
85
+ level = "build" if fn.name=="get_build_logs" else "run"
86
+ logs=fetch_logs(repo_id, level)
87
+ resp2 = chat.send_message("", function_response={fn.name:logs})
88
+ reply=resp2.candidates[0].content.parts[0].text
89
  else:
90
+ reply=part.text
91
  history.append((message, reply))
92
  return history
93
 
94
+ # --- UI ---
95
+ with gr.Blocks() as demo:
96
+ gr.Markdown("# HF Code Sandbox Chat")
97
+ # login
98
+ login_btn = gr.LoginButton("Sign in with HF", variant="huggingface")
99
+ login_status = gr.Markdown("*Not signed in.*")
100
+ models_md = gr.Markdown()
101
+ login_btn.click(lambda p: show_profile(p), inputs=[login_btn], outputs=[login_status])
102
+ login_btn.click(lambda p, t: list_private_models(p,t), inputs=[login_btn, login_btn.token], outputs=[models_md])
 
103
 
104
  with gr.Row():
 
105
  with gr.Column(scale=2):
106
+ gr.Markdown("## Setup Sandbox")
107
+ gemini_key = gr.Textbox(label="Gemini API Key", type="password")
108
+ repo_name = gr.Textbox(label="Space Name")
109
+ sdk = gr.Radio(choices=["gradio","streamlit"], label="SDK", value="gradio")
110
+ init_btn = gr.Button("Initialize Sandbox")
111
+ init_status = gr.JSON()
112
  repo_store = gr.State("")
113
+ init_btn.click(init_chat, inputs=[repo_name, sdk, gemini_key, login_btn, login_btn.token], outputs=[init_status, repo_store])
 
 
 
 
 
 
114
  with gr.Column(scale=8):
115
+ chatbot = gr.Chatbot(type="messages")
116
+ user_input = gr.Textbox(show_label=False, placeholder="Ask to write/debug code...")
117
+ user_input.submit(chatbot_respond, inputs=[user_input, chatbot, repo_store, gemini_key], outputs=[chatbot])
 
 
 
 
118
 
119
  if __name__ == "__main__":
120
  demo.launch()