File size: 6,601 Bytes
2b6e504
3991883
9970500
9194337
bacaaa0
a50a846
c1b5f9e
 
 
 
316e88f
c1b5f9e
 
bacaaa0
c1b5f9e
79ac7b6
c1b5f9e
 
3991883
 
c1b5f9e
bacaaa0
a50a846
bacaaa0
a50a846
 
 
 
bacaaa0
a50a846
 
 
 
 
 
bacaaa0
 
a50a846
 
 
bacaaa0
ee94e30
c1b5f9e
 
79ac7b6
 
bacaaa0
 
79ac7b6
c1b5f9e
79ac7b6
c1b5f9e
 
 
 
79ac7b6
 
c1b5f9e
 
79ac7b6
c1b5f9e
 
 
3991883
a50a846
3991883
 
a50a846
bacaaa0
3991883
a50a846
3991883
 
 
 
 
 
 
 
 
 
 
 
9970500
3991883
 
 
 
bacaaa0
3991883
a50a846
3991883
 
a50a846
 
3991883
 
a50a846
 
 
bacaaa0
3991883
 
c1b5f9e
3991883
9970500
 
 
 
c1b5f9e
 
 
9970500
a50a846
 
 
 
 
 
 
ee94e30
3991883
 
 
bacaaa0
79ac7b6
 
 
3991883
9970500
a50a846
3991883
9194337
a50a846
 
 
8e720f5
 
 
a50a846
 
3991883
 
 
9970500
 
 
 
3991883
a50a846
 
 
 
 
 
 
 
 
 
3991883
 
 
 
 
 
 
 
 
 
 
a50a846
 
 
 
 
 
 
 
 
3991883
 
 
a50a846
3991883
9194337
 
8e77934
45e9fba
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
import gradio as gr
import requests
from huggingface_hub import create_repo, list_models, upload_file

# — USER INFO & MODEL LISTING —

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

# — BUTTON‑ENABLING HELPERS —

def enable_create(
    profile: gr.OAuthProfile | None,
    oauth_token: gr.OAuthToken | None
):
    """Enable Create Space once logged in."""
    return gr.update(interactive=profile is not None)

def enable_repo_actions(
    repo_id: str,
    profile: gr.OAuthProfile | None,
    oauth_token: gr.OAuthToken | None
):
    """Enable Upload & Get Logs once space exists and logged in."""
    return gr.update(interactive=bool(repo_id and profile and oauth_token))

# — CORE ACTIONS —

def create_space(
    repo_name: str,
    sdk: str,
    profile: gr.OAuthProfile | None,
    oauth_token: gr.OAuthToken | None
) -> tuple[str, str, str]:
    if profile is None or oauth_token is None:
        return "", "⚠️ Please log in first.", "<p>No Space created yet.</p>"
    repo_id = f"{profile.username}/{repo_name}"
    create_repo(
        repo_id=repo_id,
        token=oauth_token.token,
        exist_ok=True,
        repo_type="space",
        space_sdk=sdk
    )
    url    = f"https://huggingface.co/spaces/{repo_id}"
    logmsg = f"✅ Space ready: {url} (SDK: {sdk})"
    iframe = f'<iframe src="{url}" width="100%" height="500px"></iframe>'
    return repo_id, logmsg, iframe

def upload_file_to_space(
    file,               # Gradio passes a Python tempfile-like object
    path_in_repo: str,
    repo_id: str,
    profile: gr.OAuthProfile | None,
    oauth_token: gr.OAuthToken | None
) -> str:
    if profile is None or oauth_token is None:
        return "⚠️ Please log in first."
    if not repo_id:
        return "⚠️ Please create a Space first."
    if file is None:
        return "⚠️ No file selected."
    upload_file(
        path_or_fileobj=file.name,
        path_in_repo=path_in_repo,
        repo_id=repo_id,
        token=oauth_token.token,
        repo_type="space"
    )
    return f"✅ Uploaded `{path_in_repo}` to `{repo_id}`"

def get_space_logs(
    repo_id: str,
    profile: gr.OAuthProfile | None,
    oauth_token: gr.OAuthToken | None
) -> str:
    if profile is None or oauth_token is None or not repo_id:
        return "⚠️ Please log in and create a Space first."
    endpoint = f"https://huggingface.co/api/spaces/{repo_id}/logs"
    headers  = {"Authorization": f"Bearer {oauth_token.token}"}
    resp     = requests.get(endpoint, headers=headers)
    if resp.status_code != 200:
        return f"❌ Failed to fetch logs ({resp.status_code})"
    entries  = resp.json()
    return "\n".join(e.get("text","") for e in entries)

# — BUILD THE UI —

with gr.Blocks(title="HF OAuth + Space Manager") as demo:
    gr.Markdown(
        "## Sign in with Hugging Face + Manage Your Space\n\n"
        "1. Sign in\n"
        "2. Create a Space (Gradio/Streamlit)\n"
        "3. Upload files to it\n"
        "4. Fetch its logs\n\n"
        "---"
    )

    # — LOGIN & MODEL LIST —
    login_btn = gr.LoginButton(variant="huggingface", size="lg")
    status_md = gr.Markdown("*Not logged in.*")
    models_md = gr.Markdown()
    demo.load(show_profile,              inputs=None,           outputs=status_md)
    login_btn.click(show_profile,        inputs=None,           outputs=status_md)
    demo.load(list_private_models,       inputs=None,           outputs=models_md)
    login_btn.click(list_private_models, inputs=None,           outputs=models_md)

    # — CREATE SPACE —
    repo_name    = gr.Textbox(label="New Space name", placeholder="my-space")
    sdk_selector = gr.Radio(
        choices=["gradio", "streamlit"],
        value="gradio",
        label="Space template (SDK)"
    )
    create_btn   = gr.Button("Create Space", interactive=False)
    session_id   = gr.Textbox(visible=False)
    create_logs  = gr.Textbox(label="Create Logs", interactive=False, lines=3)
    preview      = gr.HTML("<p>No Space created yet.</p>")

    # enable create_btn after login
    demo.load(enable_create,       inputs=[login_btn], outputs=[create_btn])
    login_btn.click(enable_create, inputs=[login_btn], outputs=[create_btn])

    create_btn.click(
        fn=create_space,
        inputs=[repo_name, sdk_selector, login_btn],
        outputs=[session_id, create_logs, preview]
    )

    # — UPLOAD FILES —
    path_in_repo  = gr.Textbox(label="Path in Space", value="app.py")
    file_uploader = gr.File(label="Select file")
    upload_btn    = gr.Button("Upload File", interactive=False)
    upload_logs   = gr.Textbox(label="Upload Logs", interactive=False, lines=2)

    # enable upload_btn after space exists & login
    demo.load(enable_repo_actions, 
              inputs=[session_id, login_btn], 
              outputs=[upload_btn])
    login_btn.click(enable_repo_actions,
                    inputs=[session_id, login_btn],
                    outputs=[upload_btn])
    session_id.change(enable_repo_actions,
                      inputs=[session_id, login_btn],
                      outputs=[upload_btn])

    upload_btn.click(
        fn=upload_file_to_space,
        inputs=[file_uploader, path_in_repo, session_id, login_btn],
        outputs=[upload_logs]
    )

    # — FETCH SPACE LOGS —
    logs_btn      = gr.Button("Get Space Logs", interactive=False)
    space_logs_md = gr.Textbox(label="Space Logs", interactive=False, lines=10)

    demo.load(enable_repo_actions, 
              inputs=[session_id, login_btn], 
              outputs=[logs_btn])
    login_btn.click(enable_repo_actions,
                    inputs=[session_id, login_btn],
                    outputs=[logs_btn])
    session_id.change(enable_repo_actions,
                      inputs=[session_id, login_btn],
                      outputs=[logs_btn])

    logs_btn.click(
        fn=get_space_logs,
        inputs=[session_id, login_btn],
        outputs=[space_logs_md]
    )

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