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eff17c
a0f57d6
 
 
 
 
 
 
 
b4396cd
246858a
a0f57d6
 
 
 
 
 
 
4eff17c
7e0fac0
a0f57d6
 
 
 
 
 
 
 
 
 
4eff17c
a0f57d6
 
 
 
 
 
 
 
 
 
4eff17c
91af2dc
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# 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) -> str:
    if profile is None:
        return "Please log in to see your models."
    try:
        token_obj = profile._token
        models = [
            f"{m.id} ({'private' if m.private else 'public'})"
            for m in list_models(author=profile.username, token=token_obj.token if token_obj else None)
        ]
        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 ---

def configure_gemini(api_key: str | None) -> str:
    if not api_key:
        return "Gemini API key is not set."
    try:
        genai.configure(api_key=api_key)
        genai.GenerativeModel("gemini-pro").generate_content("ping")
        return "Gemini configured successfully."
    except Exception as e:
        return f"Error configuring Gemini: {e}. Please check your API key."

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

# --- AI workflow logic ---

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,
    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
]:
    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

    try:
        # Preliminary checks
        if not hf_profile or not hf_token:
            bot_message = "Please log in to Hugging Face first."
            new_workflow = "awaiting_login"
        elif not gemini_api_key:
            bot_message = "Please enter your Google AI Studio API key."
            new_workflow = "awaiting_api_key"

        # Starting a new Space
        elif (new_workflow == "idle" or "create" in message.lower()) and not new_repo_id:
            bot_message = "What should the Space be called? (e.g., `my-awesome-app`)"
            new_workflow = "awaiting_repo_name"

        # User provides a repo name
        elif new_workflow == "awaiting_repo_name":
            repo_name = message.strip()
            if not repo_name:
                bot_message = "Please provide a valid Space name."
            else:
                bot_message = f"Creating Space `{hf_profile.username}/{repo_name}`..."
                new_repo_id, iframe_html = create_space_action(repo_name, space_sdk, hf_profile, hf_token)
                updated_preview = iframe_html
                bot_message += "\n✅ Space created."
                new_workflow = "awaiting_app_description"

        # User describes the app or debugging
        elif new_workflow in ("awaiting_app_description", "debugging"):
            if new_workflow == "awaiting_app_description":
                app_desc = message
                bot_message = f"Generating code for a `{space_sdk}` app based on: '{app_desc}'..."
                prompt = f"""
You are an AI assistant specializing in Hugging Face Spaces using the {space_sdk} SDK.
Generate a full, single-file Python app based on:
'{app_desc}'
Return **only** the code block (```python ...```).
"""
            else:  # debugging
                debug_instr = message
                logs = get_container_logs_action(new_repo_id, hf_profile, hf_token)
                bot_message = f"Analyzing logs and applying fixes: '{debug_instr}'..."
                prompt = f"""
You are debugging a {space_sdk} Space.
Logs:
{logs}
User instructions:
'{debug_instr}'
Generate a fixed, single-file Python app. Return only the ```python``` code block.
"""
            new_workflow = "generating_code"
            resp = call_gemini(prompt, gemini_api_key)
            # Extract code
            start = resp.find("```python")
            end   = resp.rfind("```")
            if start != -1 and end != -1 and end > start:
                code = resp[start + len("```python"):end].strip()
                bot_message += "\n✅ Code generated. Uploading..."
                new_workflow = "uploading_code"
                upload_log = upload_file_to_space_action(code, "app.py", new_repo_id, hf_profile, hf_token)
                bot_message += "\n" + upload_log
                if "✅ Uploaded" in upload_log:
                    bot_message += "\nThe Space is now rebuilding. Say 'check logs' to fetch them."
                    new_workflow = "awaiting_log_check"
                    updated_preview = f'<iframe src="https://huggingface.co/spaces/{new_repo_id}" width="100%" height="500px"></iframe>'
                else:
                    new_workflow = "idle"
            else:
                bot_message += f"\n⚠️ Could not parse code from Gemini.\nResponse:\n{resp}"
                new_workflow = "awaiting_app_description"

        # Check logs
        elif new_workflow == "awaiting_log_check" and "check logs" in message.lower():
            bot_message = "Fetching container logs..."
            updated_container = get_container_logs_action(new_repo_id, hf_profile, hf_token)
            updated_build     = get_build_logs_action(new_repo_id, hf_profile, hf_token)
            bot_message += "\n✅ Logs updated. Describe any errors or say 'generate fix'."
            new_workflow = "reviewing_logs"

        # Auto-generate fix
        elif new_workflow == "reviewing_logs" and "generate fix" in message.lower():
            latest = get_container_logs_action(new_repo_id, hf_profile, hf_token)
            if "Error" not in latest and "Exception" not in latest:
                bot_message = "No clear error found. What should I fix?"
                new_workflow = "reviewing_logs"
            else:
                bot_message = "Generating a fix based on logs..."
                new_workflow = "debugging"

        # Reset workflow
        elif "reset" in message.lower():
            bot_message = "Workflow reset."
            new_repo_id = None
            updated_preview = "<p>No Space created yet.</p>"
            updated_container = ""
            updated_build = ""
            new_workflow = "idle"

        else:
            bot_message = ("Command not recognized. You can ask to 'create', "
                           "'check logs', 'generate fix', or 'reset'.")
            new_workflow = workflow_state

    except Exception as e:
        bot_message = f"An unexpected error occurred: {e}"
        new_workflow = "idle"

    # Append bot response
    if history and history[-1][1] is None:
        history[-1][1] = bot_message
    else:
        history.append([None, bot_message])

    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)
    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")

            login_btn.logout(
                lambda: (None, None, "*Not logged in.*"),
                outputs=[hf_profile, hf_token, login_status]
            ).then(
                show_profile,
                inputs=[hf_profile],
                outputs=[login_status]
            ).then(
                lambda profile, token: (profile, token),
                inputs=[login_btn],
                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]
            ).then(
                configure_gemini,
                inputs=[gemini_key],
                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")

            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, rid, wf, sdk, prev, run_l, build_l):
                hist = [[u, v] for u, v in history]
                new_hist, new_rid, new_wf, new_prev, new_run, new_build = ai_workflow_chat(
                    msg, hist, prof, tok, key, rid, wf, sdk, prev, run_l, build_l
                )
                out_hist = [(u or "", v or "") for u, v in new_hist]
                return out_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,
                    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_profile = gr.State(None)
    manual_token   = gr.State(None)
    manual_repo    = gr.State(None)

    gr.Markdown("## Manual Sign-In & Space Management")
    manual_login_btn = gr.LoginButton(variant="huggingface", size="lg")
    manual_status    = gr.Markdown("*Not logged in.*")
    manual_models    = gr.Markdown()

    manual_login_btn.logout(
        lambda: (None, None, "*Not logged in.*", ""),
        outputs=[manual_profile, manual_token, manual_status, manual_repo]
    ).then(
        show_profile,
        inputs=[manual_profile],
        outputs=[manual_status]
    ).then(
        lambda profile, token: (profile, token),
        inputs=[manual_login_btn],
        outputs=[manual_profile, manual_token]
    ).then(
        list_private_models,
        inputs=[manual_profile],
        outputs=[manual_models]
    )

    manual_repo_name = gr.Textbox(label="New Space name", placeholder="my-space")
    manual_sdk_sel   = gr.Radio(
        choices=["gradio","streamlit"],
        value="gradio",
        label="Template SDK"
    )
    manual_create_btn = gr.Button("Create Space", interactive=False)
    manual_create_logs= gr.Textbox(label="Create Logs", lines=3, interactive=False)
    manual_preview   = gr.HTML("<p>No Space created yet.</p>")

    manual_login_btn.click(
        lambda prof: gr.update(interactive=prof is not None),
        inputs=[manual_profile],
        outputs=[manual_create_btn]
    )

    manual_create_btn.click(
        create_space_action,
        inputs=[manual_repo_name, manual_sdk_sel, manual_profile, manual_token],
        outputs=[manual_repo, manual_preview]
    ).then(
        lambda x: "",
        outputs=[manual_create_logs]
    )

    # File upload
    manual_path = gr.Textbox(label="Path in Space", value="app.py")
    manual_file = gr.File(label="Select file")
    manual_up_btn  = gr.Button("Upload File", interactive=False)
    manual_up_log  = gr.Textbox(label="Upload Logs", lines=2, interactive=False)

    manual_repo.change(
        lambda rid, prof: gr.update(interactive=bool(rid and prof)),
        inputs=[manual_repo, manual_profile],
        outputs=[manual_up_btn]
    )
    manual_login_btn.click(
        lambda rid, prof: gr.update(interactive=bool(rid and prof)),
        inputs=[manual_repo, manual_profile],
        outputs=[manual_up_btn]
    )

    manual_up_btn.click(
        upload_file_to_space_action,
        inputs=[manual_file, manual_path, manual_repo, manual_profile, manual_token],
        outputs=[manual_up_log]
    )

    # Logs
    manual_build_btn     = gr.Button("Fetch Build Logs", interactive=False)
    manual_container_btn = gr.Button("Fetch Container Logs", interactive=False)
    manual_build_txt     = gr.Textbox(label="Build Logs", lines=10, interactive=False)
    manual_container_txt = gr.Textbox(label="Container Logs", lines=10, interactive=False)

    for btn in (manual_build_btn, manual_container_btn):
        manual_repo.change(
            lambda rid, prof: gr.update(interactive=bool(rid and prof)),
            inputs=[manual_repo, manual_profile],
            outputs=[btn]
        )
        manual_login_btn.click(
            lambda rid, prof: gr.update(interactive=bool(rid and prof)),
            inputs=[manual_repo, manual_profile],
            outputs=[btn]
        )

    manual_build_btn.click(
        get_build_logs_action,
        inputs=[manual_repo, manual_profile, manual_token],
        outputs=[manual_build_txt]
    )
    manual_container_btn.click(
        get_container_logs_action,
        inputs=[manual_repo, manual_profile, manual_token],
        outputs=[manual_container_txt]
    )

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

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