wuhp commited on
Commit
476039c
·
verified ·
1 Parent(s): 3dc01aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -36
app.py CHANGED
@@ -38,7 +38,10 @@ def handle_user_message(
38
  sdk_choice: str,
39
  gemini_api_key, grounding_enabled
40
  ):
41
- # Initialize Gemini client + prime the conversation
 
 
 
42
  genai_client = genai.Client(api_key=gemini_api_key)
43
  chat = [{
44
  "role":"system",
@@ -52,34 +55,27 @@ def handle_user_message(
52
  chat.append({"role": role, "content": msg})
53
 
54
  filename = "app.py" if sdk_choice=="gradio" else "streamlit_app.py"
55
-
56
  build_logs = run_logs = ""
 
57
  for _ in range(5):
58
- # --- build the tool list ---
59
  tools = []
60
  if grounding_enabled:
61
  tools.append(Tool(google_search=GoogleSearch()))
 
62
 
63
- # --- configure Gemini properly ---
64
- config = GenerateContentConfig(
65
- tools=tools,
66
- response_modalities=["TEXT"],
67
- )
68
-
69
- # --- call Gemini ---
70
- response = genai_client.models.generate_content(
71
  model="gemini-2.5-flash-preview-04-17",
72
  contents=[c["content"] for c in chat],
73
  config=config
74
  )
75
- ai_code = response.text
76
  chat.append({"role":"assistant", "content": ai_code})
77
 
78
- # write out the code
79
  with open(filename, "w") as f:
80
  f.write(ai_code)
81
 
82
- # create/update the Space
83
  repo_id = f"{hf_profile.username}/{hf_profile.username}-auto-space"
84
  create_repo(
85
  repo_id=repo_id,
@@ -96,15 +92,12 @@ def handle_user_message(
96
  repo_type="space"
97
  )
98
 
99
- # fetch logs
100
  build_logs = fetch_logs(repo_id, "build")
101
  run_logs = fetch_logs(repo_id, "run")
102
 
103
- # stop if no "ERROR" in either log
104
  if "ERROR" not in build_logs.upper() and "ERROR" not in run_logs.upper():
105
  break
106
 
107
- # else, feed logs back into Gemini to repair
108
  chat.append({
109
  "role":"user",
110
  "content":(
@@ -115,7 +108,6 @@ def handle_user_message(
115
  })
116
  time.sleep(2)
117
 
118
- # prepare the outputs
119
  new_history = [(h["role"], h["content"]) for h in chat if h["role"]!="system"]
120
  iframe = f'<iframe src="https://huggingface.co/spaces/{repo_id}" width="100%" height="500px"></iframe>'
121
  return new_history, build_logs, run_logs, iframe
@@ -126,36 +118,45 @@ with gr.Blocks(title="HF Space Auto‑Builder (Gradio & Streamlit)") as demo:
126
  with gr.Row():
127
  with gr.Column(scale=1):
128
  gr.Markdown("### Sidebar")
 
 
 
 
129
  login_btn = gr.LoginButton("huggingface", size="sm")
130
  login_status = gr.Markdown("*Not logged in.*")
131
- sdk_choice = gr.Radio(
132
- choices=["gradio", "streamlit"],
133
- value="gradio",
134
- label="SDK Template"
135
- )
136
- api_key = gr.Textbox(label="Gemini API Key", type="password")
137
- grounding = gr.Checkbox(label="Enable grounding", value=False)
138
 
139
- demo.load(lambda *args: f"Logged in as **{args[0].username}**" if args and args[0] else "*Not logged in.*",
140
- inputs=None, outputs=login_status)
 
 
 
 
141
  login_btn.click(
142
- lambda *args: f"Logged in as **{args[0].username}**" if args and args[0] else "*Not logged in.*",
143
- inputs=None, outputs=login_status
 
 
 
 
 
144
  )
 
 
145
 
146
  with gr.Column(scale=3):
147
- chatbot = gr.Chatbot()
148
- user_input = gr.Textbox(placeholder="Your prompt here...", label="Prompt")
149
- send_btn = gr.Button("Send")
150
 
151
- build_box = gr.Textbox(label="Build logs", lines=5, interactive=False)
152
- run_box = gr.Textbox(label="Run logs", lines=5, interactive=False)
153
- preview = gr.HTML("<p>No Space yet.</p>")
154
 
155
  send_btn.click(
156
  fn=handle_user_message,
157
  inputs=[
158
- chatbot, login_status, login_btn,
 
159
  sdk_choice, api_key, grounding
160
  ],
161
  outputs=[chatbot, build_box, run_box, preview]
 
38
  sdk_choice: str,
39
  gemini_api_key, grounding_enabled
40
  ):
41
+ # Ensure we actually have a profile & token
42
+ if hf_profile is None or hf_token is None:
43
+ return history + [("assistant", "⚠️ 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",
 
55
  chat.append({"role": role, "content": msg})
56
 
57
  filename = "app.py" if sdk_choice=="gradio" else "streamlit_app.py"
 
58
  build_logs = run_logs = ""
59
+
60
  for _ in range(5):
61
+ # build tool list for grounding
62
  tools = []
63
  if grounding_enabled:
64
  tools.append(Tool(google_search=GoogleSearch()))
65
+ config = GenerateContentConfig(tools=tools, response_modalities=["TEXT"])
66
 
67
+ resp = genai_client.models.generate_content(
 
 
 
 
 
 
 
68
  model="gemini-2.5-flash-preview-04-17",
69
  contents=[c["content"] for c in chat],
70
  config=config
71
  )
72
+ ai_code = resp.text
73
  chat.append({"role":"assistant", "content": ai_code})
74
 
75
+ # write & deploy
76
  with open(filename, "w") as f:
77
  f.write(ai_code)
78
 
 
79
  repo_id = f"{hf_profile.username}/{hf_profile.username}-auto-space"
80
  create_repo(
81
  repo_id=repo_id,
 
92
  repo_type="space"
93
  )
94
 
 
95
  build_logs = fetch_logs(repo_id, "build")
96
  run_logs = fetch_logs(repo_id, "run")
97
 
 
98
  if "ERROR" not in build_logs.upper() and "ERROR" not in run_logs.upper():
99
  break
100
 
 
101
  chat.append({
102
  "role":"user",
103
  "content":(
 
108
  })
109
  time.sleep(2)
110
 
 
111
  new_history = [(h["role"], h["content"]) for h in chat if h["role"]!="system"]
112
  iframe = f'<iframe src="https://huggingface.co/spaces/{repo_id}" width="100%" height="500px"></iframe>'
113
  return new_history, build_logs, run_logs, iframe
 
118
  with gr.Row():
119
  with gr.Column(scale=1):
120
  gr.Markdown("### Sidebar")
121
+ # hidden state holders for OAuthProfile and OAuthToken
122
+ profile_state = gr.State()
123
+ token_state = gr.State()
124
+
125
  login_btn = gr.LoginButton("huggingface", size="sm")
126
  login_status = gr.Markdown("*Not logged in.*")
 
 
 
 
 
 
 
127
 
128
+ # capture profile & token into state
129
+ login_btn.click(
130
+ lambda profile, oauth_token: (profile, oauth_token),
131
+ outputs=[profile_state, token_state]
132
+ )
133
+ # update status text
134
  login_btn.click(
135
+ lambda profile, oauth_token: f"Logged in as **{profile.username}**"
136
+ if profile else "*Not logged in.*",
137
+ outputs=login_status
138
+ )
139
+
140
+ sdk_choice = gr.Radio(
141
+ ["gradio","streamlit"], value="gradio", label="SDK Template"
142
  )
143
+ api_key = gr.Textbox(label="Gemini API Key", type="password")
144
+ grounding = gr.Checkbox(label="Enable grounding", value=False)
145
 
146
  with gr.Column(scale=3):
147
+ chatbot = gr.Chatbot(type="messages")
148
+ user_in = gr.Textbox(placeholder="Your prompt ", label="Prompt")
149
+ send_btn = gr.Button("Send")
150
 
151
+ build_box = gr.Textbox(label="Build logs", lines=5, interactive=False)
152
+ run_box = gr.Textbox(label="Run logs", lines=5, interactive=False)
153
+ preview = gr.HTML("<p>No Space yet.</p>")
154
 
155
  send_btn.click(
156
  fn=handle_user_message,
157
  inputs=[
158
+ chatbot,
159
+ profile_state, token_state,
160
  sdk_choice, api_key, grounding
161
  ],
162
  outputs=[chatbot, build_box, run_box, preview]