wuhp commited on
Commit
d000f0a
·
verified ·
1 Parent(s): 40c17a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -22
app.py CHANGED
@@ -30,7 +30,7 @@ get_container_logs_decl = {
30
  }
31
  tools = [types.Tool(function_declarations=[get_build_logs_decl, get_container_logs_decl])]
32
 
33
- # --- Core Hugging Face functions (unchanged) ---
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())
@@ -45,10 +45,11 @@ def _fetch_space_logs_level(repo_id: str, level: str):
45
  try:
46
  event = json.loads(raw[len(b"data: "):].decode())
47
  records.append({"timestamp": event.get("timestamp"), "message": event.get("data")})
48
- except: pass
 
49
  return records
50
 
51
- # --- Backends for creating space & uploading files ---
52
  def create_space_backend(username: str, hf_token: str, repo_name: str, sdk: str) -> str:
53
  repo_id = f"{username}/{repo_name}"
54
  create_repo(
@@ -60,7 +61,7 @@ def create_space_backend(username: str, hf_token: str, repo_name: str, sdk: str)
60
  )
61
  return repo_id
62
 
63
- # --- Chat initialization & handlers ---
64
  def init_chat(repo_name: str, sdk: str, api_key: str, hf_profile: gr.OAuthProfile, hf_token: gr.OAuthToken):
65
  global client, chat
66
  # Validate inputs
@@ -68,11 +69,10 @@ def init_chat(repo_name: str, sdk: str, api_key: str, hf_profile: gr.OAuthProfil
68
  return {"success": False, "data": None, "message": "Missing Gemini API key."}, ""
69
  if hf_profile is None or hf_token is None:
70
  return {"success": False, "data": None, "message": "Please sign in with Hugging Face."}, ""
71
- # Create HF space sandbox
72
  repo_id = create_space_backend(hf_profile.username, hf_token.token, repo_name, sdk)
73
- # Set HF token for log streaming
74
  os.environ["HF_TOKEN"] = hf_token.token
75
- # Init Gemini client and chat
76
  client = genai.Client(api_key=api_key)
77
  chat = client.chats.create(
78
  model="gemini-2.5-flash-preview-04-17",
@@ -86,21 +86,16 @@ def init_chat(repo_name: str, sdk: str, api_key: str, hf_profile: gr.OAuthProfil
86
 
87
 
88
  def chatbot_respond(message: str, history: list, repo_id: str, api_key: str):
89
- global chat, client
90
- if not chat:
91
- # Should not happen if initialized properly
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
- # Handle function calls
97
  if part.function_call:
98
  fn = part.function_call
99
  args = json.loads(fn.args)
100
- if fn.name == "get_build_logs":
101
- result = _fetch_space_logs_level(repo_id, "build")
102
- else:
103
- result = _fetch_space_logs_level(repo_id, "run")
104
  response2 = chat.send_message("", function_response={fn.name: result})
105
  reply = response2.candidates[0].content.parts[0].text
106
  else:
@@ -108,7 +103,7 @@ def chatbot_respond(message: str, history: list, repo_id: str, api_key: str):
108
  history.append((message, reply))
109
  return history
110
 
111
- # --- UI: Chatbot with Sidebar for Space Creation ---
112
  with gr.Blocks(title="HF Code Sandbox Chat") as demo:
113
  # Top bar: HF login
114
  with gr.Row():
@@ -116,11 +111,11 @@ with gr.Blocks(title="HF Code Sandbox Chat") as demo:
116
  login_status = gr.Markdown("*Not signed in.*")
117
  login_btn.click(
118
  lambda profile: f"✅ Logged in as {profile.username}" if profile else "*Not signed in.*",
119
- inputs=None, outputs=login_status
120
  )
121
 
122
  with gr.Row():
123
- # Sidebar for sandbox setup
124
  with gr.Column(scale=2):
125
  gr.Markdown("### 🏗️ Create New Space Sandbox")
126
  api_key = gr.Textbox(label="Gemini API Key", placeholder="sk-...", type="password")
@@ -128,11 +123,10 @@ with gr.Blocks(title="HF Code Sandbox Chat") as demo:
128
  sdk_selector = gr.Radio(label="SDK", choices=["gradio","streamlit"], value="gradio")
129
  create_btn = gr.Button("Initialize Sandbox")
130
  create_status = gr.JSON(label="Initialization Status")
131
- # Hidden store for repo_id
132
- repo_store = gr.Variable("")
133
  create_btn.click(
134
  init_chat,
135
- inputs=[repo_name, sdk_selector, api_key, login_btn.profile, login_btn.token],
136
  outputs=[create_status, repo_store]
137
  )
138
 
@@ -143,7 +137,7 @@ with gr.Blocks(title="HF Code Sandbox Chat") as demo:
143
  user_input.submit(
144
  chatbot_respond,
145
  inputs=[user_input, chatbot, repo_store, api_key],
146
- outputs=chatbot
147
  )
148
 
149
  if __name__ == "__main__":
 
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())
 
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(
 
61
  )
62
  return repo_id
63
 
64
+ # --- Chat init & respond handlers ---
65
  def init_chat(repo_name: str, sdk: str, api_key: str, hf_profile: gr.OAuthProfile, hf_token: gr.OAuthToken):
66
  global client, chat
67
  # Validate inputs
 
69
  return {"success": False, "data": None, "message": "Missing Gemini API key."}, ""
70
  if hf_profile is None or hf_token is None:
71
  return {"success": False, "data": None, "message": "Please sign in with Hugging Face."}, ""
72
+ # Create HF sandbox space
73
  repo_id = create_space_backend(hf_profile.username, hf_token.token, repo_name, sdk)
 
74
  os.environ["HF_TOKEN"] = hf_token.token
75
+ # Init Gemini client & chat
76
  client = genai.Client(api_key=api_key)
77
  chat = client.chats.create(
78
  model="gemini-2.5-flash-preview-04-17",
 
86
 
87
 
88
  def chatbot_respond(message: str, history: list, repo_id: str, api_key: str):
89
+ global chat
90
+ if chat is None:
 
91
  history.append((None, "Error: chat not initialized."))
92
  return history
93
  response = chat.send_message(message)
94
  part = response.candidates[0].content.parts[0]
 
95
  if part.function_call:
96
  fn = part.function_call
97
  args = json.loads(fn.args)
98
+ result = _fetch_space_logs_level(repo_id, "build" if fn.name=="get_build_logs" else "run")
 
 
 
99
  response2 = chat.send_message("", function_response={fn.name: result})
100
  reply = response2.candidates[0].content.parts[0].text
101
  else:
 
103
  history.append((message, reply))
104
  return history
105
 
106
+ # --- UI: Chatbot + Sidebar ---
107
  with gr.Blocks(title="HF Code Sandbox Chat") as demo:
108
  # Top bar: HF login
109
  with gr.Row():
 
111
  login_status = gr.Markdown("*Not signed in.*")
112
  login_btn.click(
113
  lambda profile: f"✅ Logged in as {profile.username}" if profile else "*Not signed in.*",
114
+ inputs=[login_btn], outputs=[login_status]
115
  )
116
 
117
  with gr.Row():
118
+ # Sidebar
119
  with gr.Column(scale=2):
120
  gr.Markdown("### 🏗️ Create New Space Sandbox")
121
  api_key = gr.Textbox(label="Gemini API Key", placeholder="sk-...", type="password")
 
123
  sdk_selector = gr.Radio(label="SDK", choices=["gradio","streamlit"], value="gradio")
124
  create_btn = gr.Button("Initialize Sandbox")
125
  create_status = gr.JSON(label="Initialization Status")
126
+ repo_store = gr.State("")
 
127
  create_btn.click(
128
  init_chat,
129
+ inputs=[repo_name, sdk_selector, api_key, login_btn, login_btn],
130
  outputs=[create_status, repo_store]
131
  )
132
 
 
137
  user_input.submit(
138
  chatbot_respond,
139
  inputs=[user_input, chatbot, repo_store, api_key],
140
+ outputs=[chatbot]
141
  )
142
 
143
  if __name__ == "__main__":