wuhp commited on
Commit
9194337
·
verified ·
1 Parent(s): 16a1a03

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -59
app.py CHANGED
@@ -1,64 +1,164 @@
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
61
 
62
 
63
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  demo.launch()
 
1
+ # main.py
2
+
3
+ import os
4
+ import json
5
  import gradio as gr
6
+
7
+ from google import genai
8
+ from google.genai import types
9
+ from google.genai.types import Tool, GoogleSearch
10
+ from huggingface_hub import create_repo, snapshot_upload
11
+
12
+ # ——— Configuration ———
13
+ MODEL_ID = "gemini-2.5-flash-preview-04-17"
14
+ WORKSPACE_DIR = "workspace"
15
+ SYSTEM_INSTRUCTION = (
16
+ "You are a helpful coding assistant that scaffolds a complete Hugging Face Space app. "
17
+ "Based on the user's request, decide between Gradio or Streamlit (whichever fits best), "
18
+ "and respond with exactly one JSON object with keys:\n"
19
+ " • \"framework\": either \"gradio\" or \"streamlit\"\n"
20
+ " • \"files\": a map of relative file paths to file contents\n"
21
+ " • \"message\": a human-readable summary\n"
22
+ "Do not include extra text or markdown."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  )
24
 
25
 
26
+ def start_app(gemini_key, hf_token, hf_username, repo_name):
27
+ """
28
+ Initialize workspace and Gemini chat state.
29
+ """
30
+ os.makedirs(WORKSPACE_DIR, exist_ok=True)
31
+ client = genai.Client(api_key=gemini_key)
32
+ config = types.GenerateContentConfig(system_instruction=SYSTEM_INSTRUCTION)
33
+ tools = [Tool(google_search=GoogleSearch())]
34
+ chat = client.chats.create(model=MODEL_ID, config=config, tools=tools)
35
+
36
+ local_path = os.path.join(WORKSPACE_DIR, repo_name)
37
+ os.makedirs(local_path, exist_ok=True)
38
+
39
+ state = {
40
+ "chat": chat,
41
+ "hf_token": hf_token,
42
+ "hf_username": hf_username,
43
+ "repo_name": repo_name,
44
+ "created": False,
45
+ "repo_id": None,
46
+ "local_path": local_path,
47
+ "logs": [f"Initialized workspace at {WORKSPACE_DIR}/{repo_name}."],
48
+ }
49
+ return state
50
+
51
+
52
+ def handle_message(user_msg, state):
53
+ """
54
+ Send user message to Gemini, apply updates, commit to HF, and log steps.
55
+ """
56
+ chat = state["chat"]
57
+ logs = state.get("logs", [])
58
+ logs.append(f"> User: {user_msg}")
59
+
60
+ # Generate or debug code via Gemini
61
+ resp = chat.send_message(user_msg)
62
+ logs.append("Received response from Gemini.")
63
+ text = resp.text
64
+
65
+ try:
66
+ data = json.loads(text)
67
+ framework = data["framework"]
68
+ files = data.get("files", {})
69
+ reply_msg = data.get("message", "")
70
+ except Exception:
71
+ logs.append("⚠️ Failed to parse assistant JSON.\n" + text)
72
+ state["logs"] = logs
73
+ return "⚠️ Parsing error. Check logs.", state
74
+
75
+ # On first structured response, create the HF Space
76
+ if not state["created"]:
77
+ full_repo = f"{state['hf_username']}/{state['repo_name']}"
78
+ logs.append(f"Creating HF Space '{full_repo}' with template '{framework}'.")
79
+ create_repo(
80
+ repo_id=full_repo,
81
+ token=state["hf_token"],
82
+ exist_ok=True,
83
+ repo_type="space",
84
+ space_sdk=framework
85
+ )
86
+ state["created"] = True
87
+ state["repo_id"] = full_repo
88
+ state["embed_url"] = f"https://huggingface.co/spaces/{full_repo}"
89
+
90
+ # Write file updates
91
+ if files:
92
+ logs.append(f"Writing {len(files)} file(s): {list(files.keys())}")
93
+ for relpath, content in files.items():
94
+ dest = os.path.join(state["local_path"], relpath)
95
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
96
+ with open(dest, "w", encoding="utf-8") as f:
97
+ f.write(content)
98
+
99
+ # Commit the snapshot
100
+ logs.append("Uploading snapshot to Hugging Face...")
101
+ snapshot_upload(
102
+ repo_id=state["repo_id"],
103
+ repo_type="space",
104
+ token=state["hf_token"],
105
+ folder=state["local_path"],
106
+ commit_message="Update from assistant"
107
+ )
108
+ logs.append("Snapshot upload complete.")
109
+
110
+ state["logs"] = logs
111
+ return reply_msg, state
112
+
113
+
114
+ # ——— Gradio UI ———
115
+ with gr.Blocks() as demo:
116
+ with gr.Sidebar():
117
+ gemini_key = gr.Textbox(label="Gemini API Key", type="password")
118
+ hf_token = gr.Textbox(label="Hugging Face Token", type="password")
119
+ hf_user = gr.Textbox(label="HF Username")
120
+ repo_name = gr.Textbox(label="New App (repo) name")
121
+ start_btn = gr.Button("Start a new app")
122
+
123
+ chatbot = gr.Chatbot()
124
+ state = gr.State(value=None)
125
+ logs_display = gr.Textbox(label="Operation Logs", interactive=False, lines=8)
126
+ preview_iframe = gr.HTML("<p>No deployed app yet.</p>")
127
+
128
+ user_msg = gr.Textbox(label="Your message")
129
+ send_btn = gr.Button("Send")
130
+
131
+ def on_start(g_key, h_token, h_user, r_name):
132
+ s = start_app(g_key, h_token, h_user, r_name)
133
+ logs = "\n".join(s["logs"])
134
+ return s, logs, "<p>Awaiting first instruction...</p>"
135
+
136
+ start_btn.click(
137
+ on_start,
138
+ inputs=[gemini_key, hf_token, hf_user, repo_name],
139
+ outputs=[state, logs_display, preview_iframe]
140
+ )
141
+
142
+ def on_send(msg, chat_history, s):
143
+ if s is None:
144
+ return chat_history, s, "", ""
145
+ reply, new_state = handle_message(msg, s)
146
+ chat_history = chat_history + [(msg, reply)]
147
+ logs = "\n".join(new_state.get("logs", []))
148
+ embed = ""
149
+ if new_state.get("embed_url"):
150
+ embed = f'<iframe src="{new_state["embed_url"]}" width="100%" height="500px"></iframe>'
151
+ return chat_history, new_state, logs, embed
152
+
153
+ send_btn.click(
154
+ on_send,
155
+ inputs=[user_msg, chatbot, state],
156
+ outputs=[chatbot, state, logs_display, preview_iframe]
157
+ )
158
+ user_msg.submit(
159
+ on_send,
160
+ inputs=[user_msg, chatbot, state],
161
+ outputs=[chatbot, state, logs_display, preview_iframe]
162
+ )
163
+
164
  demo.launch()