File size: 8,034 Bytes
6afd365
 
 
 
 
 
 
 
 
 
 
 
afe5eb9
6afd365
 
 
 
 
2da1c43
875e116
2da1c43
afe5eb9
 
2da1c43
 
6afd365
 
 
 
 
82e3483
6afd365
 
 
 
 
 
 
 
3282cf9
 
 
 
10b46cb
 
3282cf9
 
 
 
6afd365
 
3282cf9
6afd365
 
 
 
 
 
 
 
 
 
 
 
 
 
3282cf9
6afd365
 
afe5eb9
 
 
6afd365
 
3282cf9
 
6afd365
 
 
 
 
10b46cb
6afd365
10b46cb
6afd365
 
 
 
 
10b46cb
6afd365
10b46cb
6afd365
 
 
 
 
10b46cb
6afd365
10b46cb
6afd365
 
 
 
 
10b46cb
6afd365
10b46cb
6afd365
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afe5eb9
 
6afd365
 
 
 
 
 
 
 
 
 
afe5eb9
 
6afd365
 
 
 
 
 
 
 
 
 
4004cdc
6afd365
 
 
 
afe5eb9
 
6afd365
 
 
10b46cb
6afd365
 
 
 
 
10b46cb
6afd365
 
 
 
 
10b46cb
6afd365
 
 
 
 
10b46cb
6afd365
 
 
 
 
 
10b46cb
6afd365
 
 
 
 
 
 
 
 
 
 
 
4004cdc
6afd365
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afe5eb9
 
6afd365
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python

from __future__ import annotations

import dataclasses
import datetime
import pathlib

import datasets
import gradio as gr
import pandas as pd
import tqdm.auto
from gradio_calendar import Calendar
from huggingface_hub import HfApi

from constants import HARDWARE_CHOICES, SDK_CHOICES, SLEEP_TIME_CHOICES, STATUS_CHOICES
from demo_list import DemoInfo, DemoList

TITLE = """\
# Spaces of the Week

This Space provides a list of past Spaces of the Week with some filtering options.
You can find the dataset [here](https://huggingface.co/datasets/hysts-bot/spaces-of-the-week).
Also, check out [this Space](https://huggingface.co/spaces/mvaloatto/ASOTW) by [mvaloatto](https://huggingface.co/mvaloatto).
"""

repo_dir = pathlib.Path(__file__).parent.absolute()

api = HfApi()

df_orig = datasets.load_dataset("hysts-bot/spaces-of-the-week", split="train").to_pandas()


def get_space_info(df: pd.DataFrame, sort_by: list[str], ascending: list[bool]) -> pd.DataFrame:
    data = []
    for _, row in tqdm.auto.tqdm(df.iterrows(), total=len(df)):
        space_id = row["space_id"]
        try:
            info = DemoInfo.from_space_id(space_id)
            info_dict = dataclasses.asdict(info)
            info_dict["space_id"] = row["space_id"]
            info_dict["title"] = row["title"]
            data.append({"featured_week": row["date"]} | info_dict)
        except Exception as e:  # noqa: BLE001
            print(f"Failed to load {space_id}: {e}")  # noqa: T201
            if row["created_at"]:
                created = datetime.datetime.fromisoformat(row["created_at"]).strftime("%Y/%m/%d %H:%M:%S")
            else:
                created = ""
            data.append(
                {
                    "featured_week": row["date"],
                    "space_id": space_id,
                    "url": f"https://huggingface.co/spaces/{space_id}",
                    "title": row["title"],
                    "owner": space_id.split("/")[0],
                    "sdk": "",
                    "sdk_version": "",
                    "likes": None,
                    "status": "",
                    "last_modified": "",
                    "sleep_time": 0,
                    "replicas": 0,
                    "private": True,
                    "hardware": "",
                    "suggested_hardware": "",
                    "created": created,
                }
            )
    df = pd.DataFrame(data).sort_values(sort_by, ascending=ascending).reset_index(drop=True)
    df["featured_week"] = pd.to_datetime(df["featured_week"])
    return df


df_all = get_space_info(df_orig, sort_by=["featured_week", "space_id"], ascending=[False, True])
demo_list = DemoList(df_all)


def update_status_checkboxes(choices: list[str]) -> list[str]:
    if "(ALL)" in choices:
        return STATUS_CHOICES
    if "(NONE)" in choices:
        return []
    return choices


def update_hardware_checkboxes(choices: list[str]) -> list[str]:
    if "(ALL)" in choices:
        return HARDWARE_CHOICES
    if "(NONE)" in choices:
        return []
    return choices


def update_sdk_checkboxes(choices: list[str]) -> list[str]:
    if "(ALL)" in choices:
        return SDK_CHOICES
    if "(NONE)" in choices:
        return []
    return choices


def update_sleep_time_checkboxes(choices: list[str]) -> list[str]:
    if "(ALL)" in choices:
        return SLEEP_TIME_CHOICES
    if "(NONE)" in choices:
        return []
    return choices


DEFAULT_COLUMNS = [
    "featured_week",
    "status",
    "hardware",
    "title",
    "owner",
    "likes",
    "created",
    "sdk",
]
FEATURED_WEEKS = demo_list.df_raw.featured_week.unique().tolist()
DEFAULT_FEATURED_WEEKS = FEATURED_WEEKS[:4]


def update_df(
    status: list[str],
    hardware: list[str],
    sdk: list[str],
    sleep_time: list[str],
    multiple_replicas: bool,
    owner: str,
    start_date: datetime.datetime,
    end_date: datetime.datetime,
    column_names: list[str],
) -> pd.DataFrame:
    return gr.DataFrame(
        value=demo_list.filter(
            status,
            hardware,
            sdk,
            sleep_time,
            multiple_replicas,
            owner,
            start_date,
            end_date,
            column_names,
        ),
        datatype=demo_list.get_column_datatypes(column_names),
    )


def update_num_spaces(df: pd.DataFrame) -> str:
    return f"{len(df)} / {len(demo_list.df_raw)}"


with gr.Blocks(css_paths="style.css") as demo:
    gr.Markdown(TITLE)
    with gr.Accordion(label="Filter", open=True):
        with gr.Group():
            with gr.Row():
                start_date = Calendar(label="Start date", type="datetime", value="2021-10-18")
                end_date = Calendar(label="End date", type="datetime")
        with gr.Accordion(label="Advanced", open=False):
            status = gr.CheckboxGroup(
                label="Status",
                choices=["(ALL)", "(NONE)", *STATUS_CHOICES],
                value=STATUS_CHOICES,
                type="value",
            )
            hardware = gr.CheckboxGroup(
                label="Hardware",
                choices=["(ALL)", "(NONE)", *HARDWARE_CHOICES],
                value=HARDWARE_CHOICES,
                type="value",
            )
            sdk = gr.CheckboxGroup(
                label="SDK",
                choices=["(ALL)", "(NONE)", *SDK_CHOICES],
                value=SDK_CHOICES,
                type="value",
            )
            sleep_time = gr.CheckboxGroup(
                label="Sleep time",
                choices=["(ALL)", "(NONE)", *SLEEP_TIME_CHOICES],
                value=SLEEP_TIME_CHOICES,
                type="value",
            )
            multiple_replicas = gr.Checkbox(label="Multiple replicas", value=False)
            owner = gr.Dropdown(
                label="Owner",
                choices=["(ALL)", *sorted(demo_list.df_raw.owner.unique().tolist())],
                value="(ALL)",
            )
        with gr.Group():
            column_names = gr.CheckboxGroup(label="Columns", choices=demo_list.column_names, value=DEFAULT_COLUMNS)
        apply_button = gr.Button("Apply")

    num_spaces = gr.Textbox(label="Number of Spaces", interactive=False)
    df = gr.Dataframe(
        value=demo_list.df_prettified,
        datatype=demo_list.get_column_datatypes(demo_list.column_names),
        type="pandas",
        row_count=(0, "dynamic"),
        max_height=1000,
        elem_id="table",
        interactive=False,
    )

    status.input(
        fn=update_status_checkboxes,
        inputs=status,
        outputs=status,
        queue=False,
        show_progress=False,
        api_name=False,
    )
    hardware.input(
        fn=update_hardware_checkboxes,
        inputs=hardware,
        outputs=hardware,
        queue=False,
        show_progress=False,
        api_name=False,
    )
    sdk.input(
        fn=update_sdk_checkboxes,
        inputs=sdk,
        outputs=sdk,
        queue=False,
        show_progress=False,
        api_name=False,
    )
    sleep_time.input(
        fn=update_sleep_time_checkboxes,
        inputs=sleep_time,
        outputs=sleep_time,
        queue=False,
        show_progress=False,
        api_name=False,
    )
    inputs = [
        status,
        hardware,
        sdk,
        sleep_time,
        multiple_replicas,
        owner,
        start_date,
        end_date,
        column_names,
    ]
    apply_button.click(
        fn=update_df,
        inputs=inputs,
        outputs=df,
        api_name=False,
    ).then(
        fn=update_num_spaces,
        inputs=df,
        outputs=num_spaces,
        queue=False,
        api_name=False,
    )
    demo.load(
        fn=update_df,
        inputs=inputs,
        outputs=df,
        api_name=False,
    ).then(
        fn=update_num_spaces,
        inputs=df,
        outputs=num_spaces,
        queue=False,
        api_name=False,
    )

if __name__ == "__main__":
    demo.queue(api_open=False).launch(show_api=False)