File size: 11,231 Bytes
a0f57d6
 
 
 
4eff17c
a0f57d6
 
 
 
 
 
6146397
4c46f34
a0f57d6
0df9635
4eff17c
 
 
 
5d26448
9053015
 
 
 
 
fb9266f
a0f57d6
 
 
9053015
a0f57d6
 
 
 
5d26448
a0f57d6
4eff17c
4c46f34
4eff17c
a0f57d6
4c46f34
 
 
 
9053015
4eff17c
a0f57d6
4eff17c
a0f57d6
 
4eff17c
 
a0f57d6
 
4eff17c
a0f57d6
 
 
 
 
 
 
 
 
 
 
 
 
599725a
a0f57d6
 
 
b2c5c54
a0f57d6
4eff17c
a0f57d6
 
6146397
 
a0f57d6
 
 
4eff17c
 
 
 
 
a0f57d6
 
 
 
 
4eff17c
 
a0f57d6
0df9635
a0f57d6
 
70dd0f7
a0f57d6
70dd0f7
a0f57d6
 
599725a
a0f57d6
 
 
e8459e6
 
 
a0f57d6
 
e8459e6
 
a0f57d6
 
e8459e6
 
 
a0f57d6
e8459e6
a0f57d6
e8459e6
 
 
a0f57d6
 
e8459e6
a0f57d6
 
 
e8459e6
 
a0f57d6
e8459e6
a0f57d6
 
 
 
 
 
 
e8459e6
a0f57d6
 
 
 
 
 
 
 
 
 
 
 
 
 
e8459e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0f57d6
 
 
 
e8459e6
 
 
 
 
 
 
a0f57d6
 
 
 
 
 
 
 
e8459e6
9053015
 
e8459e6
 
a0f57d6
 
 
 
e8459e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0f57d6
 
e8459e6
9053015
a0f57d6
 
 
 
 
9053015
a0f57d6
e8459e6
9053015
e8459e6
 
9053015
 
 
e8459e6
 
9053015
 
 
e8459e6
 
 
 
 
 
 
9053015
 
 
 
 
 
a0f57d6
e8459e6
 
 
a0f57d6
e8459e6
 
a0f57d6
 
 
 
 
e8459e6
 
 
 
a0f57d6
 
 
e8459e6
 
a0f57d6
 
 
 
e8459e6
a0f57d6
 
 
 
 
 
4eff17c
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# app.py

import os
import time
import json
import requests

import gradio as gr
import google.generativeai as genai

from huggingface_hub import create_repo, list_models, upload_file, constants
from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status

# --- Helper functions for Hugging Face integration ---

def show_profile(profile: gr.OAuthProfile | None) -> str:
    if profile is None:
        return "*Not logged in.*"
    return f"✅ Logged in as **{profile.username}**"

def list_private_models(
    profile: gr.OAuthProfile | None,
    oauth_token: gr.OAuthToken | None
) -> str:
    if profile is None or oauth_token is None:
        return "Please log in to see your models."
    try:
        models = [
            f"{m.id} ({'private' if m.private else 'public'})"
            for m in list_models(author=profile.username, token=oauth_token.token)
        ]
        return "No models found." if not models else "Models:\n\n" + "\n - ".join(models)
    except Exception as e:
        return f"Error listing models: {e}"

def create_space_action(repo_name: str, sdk: str, profile: gr.OAuthProfile, token: gr.OAuthToken):
    repo_id = f"{profile.username}/{repo_name}"
    create_repo(
        repo_id=repo_id,
        token=token.token,
        exist_ok=True,
        repo_type="space",
        space_sdk=sdk
    )
    url    = f"https://huggingface.co/spaces/{repo_id}"
    iframe = f'<iframe src="{url}" width="100%" height="500px"></iframe>'
    return repo_id, iframe

def upload_file_to_space_action(
    file_obj,
    path_in_repo: str,
    repo_id: str,
    profile: gr.OAuthProfile,
    token: gr.OAuthToken
) -> str:
    if not (profile and token and repo_id):
        return "⚠️ Please log in and create a Space first."
    try:
        upload_file(
            path_or_fileobj=file_obj,
            path_in_repo=path_in_repo,
            repo_id=repo_id,
            token=token.token,
            repo_type="space"
        )
        return f"✅ Uploaded `{path_in_repo}`"
    except Exception as e:
        return f"Error uploading file: {e}"

def _fetch_space_logs_level(repo_id: str, level: str, token: str) -> str:
    jwt_url  = f"{constants.ENDPOINT}/api/spaces/{repo_id}/jwt"
    r        = get_session().get(jwt_url, headers=build_hf_headers(token=token))
    hf_raise_for_status(r)
    jwt      = r.json()["token"]
    logs_url = f"https://api.hf.space/v1/{repo_id}/logs/{level}"
    lines, count = [], 0
    with get_session().get(logs_url, headers=build_hf_headers(token=jwt), stream=True, timeout=20) as resp:
        hf_raise_for_status(resp)
        for raw in resp.iter_lines():
            if count >= 200:
                lines.append("... truncated ...")
                break
            if not raw.startswith(b"data: "):
                continue
            payload = raw[len(b"data: "):]
            try:
                event = json.loads(payload.decode())
                ts    = event.get("timestamp", "")
                txt   = event.get("data", "").strip()
                if txt:
                    lines.append(f"[{ts}] {txt}")
                    count += 1
            except json.JSONDecodeError:
                continue
    return "\n".join(lines) if lines else f"No {level} logs found."

def get_build_logs_action(repo_id, profile, token):
    if not (repo_id and profile and token):
        return "⚠️ Please log in and create a Space first."
    return _fetch_space_logs_level(repo_id, "build", token.token)

def get_container_logs_action(repo_id, profile, token):
    if not (repo_id and profile and token):
        return "⚠️ Please log in and create a Space first."
    return _fetch_space_logs_level(repo_id, "run", token.token)


# --- Google Gemini integration with model selection ---

def configure_gemini(api_key: str | None, model_name: str | None) -> str:
    if not api_key:
        return "Gemini API key is not set."
    if not model_name:
        return "Please select a Gemini model."
    try:
        genai.configure(api_key=api_key)
        # Test using the selected model
        genai.GenerativeModel(model_name).generate_content("ping")
        return f"Gemini configured successfully with **{model_name}**."
    except Exception as e:
        return f"Error configuring Gemini: {e}"

def call_gemini(prompt: str, api_key: str, model_name: str) -> str:
    if not api_key or not model_name:
        return "Error: Gemini API key or model not provided."
    try:
        genai.configure(api_key=api_key)
        model    = genai.GenerativeModel(model_name)
        response = model.generate_content(prompt)
        return response.text or "Gemini returned an empty response."
    except Exception as e:
        return f"Error calling Gemini API with {model_name}: {e}"


# --- AI workflow logic (uses selected model) ---

def ai_workflow_chat(
    message: str,
    history: list[list[str | None]],
    hf_profile: gr.OAuthProfile | None,
    hf_token:   gr.OAuthToken   | None,
    gemini_api_key: str         | None,
    gemini_model:   str         | None,
    repo_id_state:  str         | None,
    workflow_state: str,
    space_sdk:      str,
    preview_html:   str,
    container_logs: str,
    build_logs:     str
) -> tuple[
    list[list[str | None]],
    str | None,
    str,
    str,
    str,
    str
]:
    # Append user message
    history.append([message, None])
    bot_message = ""
    new_repo_id = repo_id_state
    new_workflow = workflow_state
    updated_preview = preview_html
    updated_container = container_logs
    updated_build = build_logs

    # -- same workflow logic as before, but use call_gemini(prompt, gemini_api_key, gemini_model) --

    # example when generating code:
    # resp = call_gemini(prompt, gemini_api_key, gemini_model)

    # [Omitted for brevity; insert your existing logic here, replacing calls to
    # call_gemini(prompt, gemini_api_key) with call_gemini(prompt, gemini_api_key, gemini_model).]

    return history, new_repo_id, new_workflow, updated_preview, updated_container, updated_build


# --- Build the Gradio UI ---

with gr.Blocks(title="AI-Powered HF Space App Builder") as ai_builder_tab:
    hf_profile      = gr.State(None)
    hf_token        = gr.State(None)
    gemini_key      = gr.State(None)
    gemini_model    = gr.State("gemini-2.5-pro-preview-03-25")
    repo_id         = gr.State(None)
    workflow        = gr.State("idle")
    sdk_state       = gr.State("gradio")

    with gr.Row():
        # Sidebar
        with gr.Column(scale=1, min_width=300):
            gr.Markdown("## Hugging Face Login")
            login_status = gr.Markdown("*Not logged in.*")
            login_btn    = gr.LoginButton(variant="huggingface")

            # init & update login status
            ai_builder_tab.load(show_profile, outputs=login_status)
            login_btn.click(show_profile, outputs=login_status)
            login_btn.click(lambda profile, token: (profile, token),
                            outputs=[hf_profile, hf_token])

            gr.Markdown("## Google AI Studio API Key")
            gemini_input  = gr.Textbox(label="API Key", type="password")
            gemini_status = gr.Markdown("")
            gemini_input.change(lambda k: k, inputs=gemini_input, outputs=gemini_key)

            gr.Markdown("## Gemini Model")
            model_selector = gr.Radio(
                choices=[
                    ("Gemini 2.5 Flash Preview 04-17", "gemini-2.5-flash-preview-04-17"),
                    ("Gemini 2.5 Pro Preview 03-25",   "gemini-2.5-pro-preview-03-25")
                ],
                value="gemini-2.5-pro-preview-03-25",
                label="Select model"
            )
            model_selector.change(lambda m: m, inputs=model_selector, outputs=gemini_model)

            # configure Gemini whenever key or model changes
            gr.Row().load(
                configure_gemini,
                inputs=[gemini_key, gemini_model],
                outputs=[gemini_status]
            )
            gemini_input.change(
                configure_gemini,
                inputs=[gemini_key, gemini_model],
                outputs=[gemini_status]
            )
            model_selector.change(
                configure_gemini,
                inputs=[gemini_key, gemini_model],
                outputs=[gemini_status]
            )

            gr.Markdown("## Space SDK")
            sdk_selector = gr.Radio(choices=["gradio","streamlit"], value="gradio", label="Template SDK")
            sdk_selector.change(lambda s: s, inputs=sdk_selector, outputs=sdk_state)

        # Main content
        with gr.Column(scale=3):
            chatbot    = gr.Chatbot()
            user_input = gr.Textbox(placeholder="Type your message…")
            send_btn   = gr.Button("Send", interactive=False)

            # enable send only when logged in & key & model selected
            ai_builder_tab.load(
                lambda p, k, m: gr.update(interactive=bool(p and k and m)),
                inputs=[hf_profile, gemini_key, gemini_model],
                outputs=[send_btn]
            )
            login_btn.click(
                lambda p, k, m: gr.update(interactive=bool(p and k and m)),
                inputs=[hf_profile, gemini_key, gemini_model],
                outputs=[send_btn]
            )
            gemini_input.change(
                lambda p, k, m: gr.update(interactive=bool(p and k and m)),
                inputs=[hf_profile, gemini_key, gemini_model],
                outputs=[send_btn]
            )
            model_selector.change(
                lambda p, k, m: gr.update(interactive=bool(p and k and m)),
                inputs=[hf_profile, gemini_key, gemini_model],
                outputs=[send_btn]
            )

            iframe    = gr.HTML("<p>No Space created yet.</p>")
            build_txt = gr.Textbox(label="Build Logs", lines=10, interactive=False)
            run_txt   = gr.Textbox(label="Container Logs", lines=10, interactive=False)

            def wrap_chat(msg, history, prof, tok, key, model, rid, wf, sdk, prev, run_l, build_l):
                out = ai_workflow_chat(
                    msg, history, prof, tok, key, model, rid, wf, sdk, prev, run_l, build_l
                )
                hist, new_rid, new_wf, new_prev, new_run, new_build = out
                return [(u or "", v or "") for u, v in hist], new_rid, new_wf, new_prev, new_run, new_build

            send_btn.click(
                wrap_chat,
                inputs=[
                    user_input, chatbot,
                    hf_profile, hf_token,
                    gemini_key, gemini_model,
                    repo_id, workflow, sdk_state,
                    iframe, run_txt, build_txt
                ],
                outputs=[
                    chatbot,
                    repo_id, workflow,
                    iframe, run_txt, build_txt
                ]
            )

with gr.Blocks(title="Manual Hugging Face Space Manager") as manual_control_tab:
    # ... (manual tab unchanged) ...

demo = gr.TabbedInterface(
    [ai_builder_tab, manual_control_tab],
    ["AI App Builder", "Manual Control"]
)

if __name__ == "__main__":
    demo.launch()