File size: 12,008 Bytes
76ffd6d
 
b052ddd
 
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
 
433130f
76ffd6d
 
 
 
 
 
 
 
 
 
 
f834b58
 
 
 
 
433130f
 
 
 
af69d1f
76ffd6d
 
 
 
 
f834b58
76ffd6d
 
 
f1e583c
 
 
 
 
 
 
 
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433130f
76ffd6d
 
433130f
76ffd6d
af69d1f
 
76ffd6d
 
433130f
76ffd6d
 
af69d1f
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433130f
 
 
 
 
76ffd6d
 
433130f
 
 
 
 
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f834b58
 
76ffd6d
 
 
 
b052ddd
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b052ddd
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b052ddd
 
 
76ffd6d
 
 
 
 
 
6e9ab9b
76ffd6d
 
 
 
 
 
 
 
 
1b701be
 
 
 
76ffd6d
 
6e9ab9b
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
 
 
f834b58
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
 
433130f
76ffd6d
 
 
f834b58
76ffd6d
 
1b701be
76ffd6d
 
 
 
 
 
1b701be
 
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af69d1f
76ffd6d
af69d1f
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
433130f
 
 
 
76ffd6d
 
433130f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f834b58
76ffd6d
 
 
 
 
 
 
 
 
 
 
 
 
f834b58
76ffd6d
 
 
 
 
 
b052ddd
76ffd6d
b052ddd
76ffd6d
f834b58
76ffd6d
 
 
 
 
b052ddd
 
 
76ffd6d
 
 
 
 
 
f834b58
76ffd6d
f834b58
76ffd6d
 
 
 
1b701be
 
 
 
 
 
 
6e9ab9b
1b701be
 
 
 
1bd69d6
1b701be
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
# HF space creator starting from an sklearn model

from __future__ import annotations

import base64
import glob
import io
import os
import pickle
import re
import shutil
from pathlib import Path
from tempfile import mkdtemp

import pandas as pd
import sklearn
import streamlit as st
from huggingface_hub import hf_hub_download
from sklearn.base import BaseEstimator

import skops.io as sio
from skops import card, hub_utils

st.set_page_config(layout="wide")
st.title("Skops space creator for sklearn")


PLACEHOLDER = "[More Information Needed]"
PLOT_PREFIX = "__plot__:"

# store session state
if "custom_sections" not in st.session_state:
    st.session_state.custom_sections = {}

# the tmp_path is used to upload the sklearn model to
tmp_path = Path(mkdtemp(prefix="skops-"))
# the hf_path is the actual repo used for init()
hf_path = Path(mkdtemp(prefix="skops-"))

# a hacky way to "persist" custom sections
CUSTOM_SECTIONS_CACHE_FILE = ".custom-sections.json"


def _clear_custom_section_cache():
    st.session_state.custom_sections.clear()


def _remove_custom_section(key):
    section_names = list(st.session_state.custom_sections.keys())
    for section_name in section_names:
        if (
            (section_name == key)
            or section_name.startswith(key + "/")
            or section_name.startswith(key + " /")
        ):
            del st.session_state.custom_sections[section_name]


def _clear_repo(path):
    for file_path in glob.glob(str(Path(path) / "*")):
        if os.path.isfile(file_path) or os.path.islink(file_path):
            os.unlink(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)


def _write_plot(plot_name, plot_file):
    with open(plot_name, "wb") as f:
        f.write(plot_file)


def init_repo():
    _clear_repo(hf_path)

    try:
        file_name = tmp_path / "model.skops"
        sio.dump(model, file_name)

        reqs = [r.strip().rstrip(",") for r in requirements.splitlines()]
        hub_utils.init(
            model=file_name,
            dst=hf_path,
            task=task,
            data=data,
            requirements=reqs,
        )
    except Exception as exc:
        print("Uh oh, something went wrong when initializing the repo:", exc)


def load_model():
    if model_file is None:
        return

    bytes_data = model_file.getvalue()
    model = pickle.loads(bytes_data)
    assert isinstance(model, BaseEstimator), "model must be an sklearn model"
    return model


def load_data():
    if data_file is None:
        return

    bytes_data = io.BytesIO(data_file.getvalue())
    df = pd.read_csv(bytes_data)
    return df


def _parse_metrics(metrics):
    metrics_table = {}
    for line in metrics.splitlines():
        line = line.strip()
        name, _, val = line.partition("=")
        try:
            # try to coerce to float but don't error if it fails
            val = float(val.strip())
        except ValueError:
            pass
        metrics_table[name.strip()] = val
    return metrics_table


def _load_model_card_from_repo(repo_id: str) -> Card:
    path = hf_hub_download(repo_id, "README.md")
    return card.parse_modelcard(path)


def _create_model_card():
    init_repo()
    if model_card_repo:  # load existing model card
        model_card = _load_model_card_from_repo(model_card_repo)
    else:  # create new model card
        metadata = card.metadata_from_config(hf_path)
        model_card = card.Card(model=model, metadata=metadata)

    if model_description:
        model_card.add(**{"Model description": model_description})

    if intended_uses:
        model_card.add(
            **{"Model description/Intended uses & limitations": intended_uses}
        )

    if metrics:
        metrics_table = _parse_metrics(metrics)
        model_card.add_metrics(**metrics_table)

    if authors:
        model_card.add(**{"Model Card Authors": authors})

    if contact:
        model_card.add(**{"Model Card Contact": contact})

    if citation:
        model_card.add(**{"Citation": citation})

    if st.session_state.custom_sections:
        for key, val in st.session_state.custom_sections.items():
            if not key:
                continue

            if key.startswith(PLOT_PREFIX):
                key = key[len(PLOT_PREFIX) :]  # noqa
                model_card.add_plot(**{key: val})
            else:
                model_card.add(**{key: val})

    return model_card


def _process_card_for_rendering(rendered: str) -> tuple[str, str]:
    idx = rendered[1:].index("\n---") + 1
    metadata = rendered[3:idx]
    rendered = rendered[idx + 4 :]  # noqa: E203

    # below is a hack to display the images in streamlit
    # https://discuss.streamlit.io/t/image-in-markdown/13274/10 The problem is

    # that streamlit does not display images in markdown, so we need to replace
    # them with html. However, we only want that in the rendered markdown, not
    # in the card that is produced for the hub
    def markdown_images(markdown):
        # example image markdown:
        # ![Test image](images/test.png "Alternate text")
        images = re.findall(
            r'(!\[(?P<image_title>[^\]]+)\]\((?P<image_path>[^\)"\s]+)\s*([^\)]*)\))',
            markdown,
        )
        return images

    def img_to_bytes(img_path):
        img_bytes = Path(img_path).read_bytes()
        encoded = base64.b64encode(img_bytes).decode()
        return encoded

    def img_to_html(img_path, img_alt):
        img_format = img_path.split(".")[-1]
        img_html = (
            f'<img src="data:image/{img_format.lower()};'
            f'base64,{img_to_bytes(img_path)}" '
            f'alt="{img_alt}" '
            'style="max-width: 100%;">'
        )
        return img_html

    def markdown_insert_images(markdown):
        images = markdown_images(markdown)

        for image in images:
            image_markdown = image[0]
            image_alt = image[1]
            image_path = image[2]
            markdown = markdown.replace(
                image_markdown, img_to_html(image_path, image_alt)
            )
        return markdown

    rendered_with_img = markdown_insert_images(rendered)
    return metadata, rendered_with_img


def display_model_card(model_card):
    if not model_card:
        return

    rendered = model_card.render()
    metadata, rendered = _process_card_for_rendering(rendered)
    # idx = rendered[1:].index("\n---") + 1
    # metadata = rendered[3:idx]
    # rendered = rendered[idx + 4 :]  # noqa: E203

    # strip metadata
    with st.expander("show metadata"):
        st.text(metadata)
    st.markdown(rendered, unsafe_allow_html=True)


def download_model_card(model_card):
    if model_card is not None:
        return model_card.render()
    return ""


def add_custom_section():
    # this is required to "refresh" these variables...
    global section_name, section_content
    section_name = st.session_state.key_section_name
    section_content = st.session_state.key_section_content

    if not section_name or not section_content:
        return

    st.session_state.custom_sections[section_name] = section_content


def add_custom_plot():
    # this is required to "refresh" these variables...
    global section_name, section_content
    plot_name = st.session_state.key_plot_name
    plot_file = st.session_state.key_plot_file

    if not plot_name or not plot_file:
        return

    # store plot in temp repo
    file_name = plot_file.name.replace(" ", "_")
    file_path = str(tmp_path / file_name)
    with open(file_path, "wb") as f:
        f.write(plot_file.getvalue())

    st.session_state.custom_sections[str(PLOT_PREFIX + plot_name)] = file_path


with st.sidebar:
    # This contains every element required to edit the model card
    model = None
    data = None
    section_name = None
    section_content = None

    st.title("Model Card Editor")

    model_file = st.file_uploader("Upload a model*", on_change=load_model)
    data_file = st.file_uploader(
        "Upload X data (csv)*", type=["csv"], on_change=load_data
    )

    task = st.selectbox(
        label="Choose the task type*",
        options=[
            "tabular-classification",
            "tabular-regression",
            "text-classification",
            "text-regression",
        ],
        on_change=init_repo,
    )

    requirements = st.text_area(
        label="Requirements*",
        value=f"scikit-learn=={sklearn.__version__}\n",
        on_change=init_repo,
    )

    if model_file is not None:
        model = load_model()

    if data_file is not None:
        data = load_data()

    if model is not None and data is not None:
        init_repo()

    model_card_repo = st.text_input(
        "Optional: HF repo to load model card from (e.g. 'gpt2'), "
        "leave empty to use default skops template",
        value="",
    )

    # DEFAULT SKOPS SECTIONS
    if not model_card_repo:
        model_description = st.text_input("Model description", value=PLACEHOLDER)
        intended_uses = st.text_area(
            "Intended uses & limitations", height=2, value=PLACEHOLDER
        )
        metrics = st.text_area("Metrics (e.g. 'accuracy = 0.95'), one metric per line")
        authors = st.text_area(
            "Authors",
            value="This model card is written by following authors:\n\n" + PLACEHOLDER,
        )
        contact = st.text_area(
            "Contact",
            value="You can contact the model card authors through following channels:\n\n"
            + PLACEHOLDER,
        )
        citation = st.text_area(
            "Citation",
            value="Below you can find information related to citation.\n\nBibTex:\n\n```\n"
            + PLACEHOLDER
            + "\n```",
            height=5,
        )
    else:
        model_description = None
        intended_uses = None
        metrics = None
        authors = None
        contact = None
        citation = None

    # ADD A CUSTOM SECTIONS
    with st.form("custom-section", clear_on_submit=True):
        section_name = st.text_input(
            "Section name (use '/' for subsections, e.g. 'Model description/My new"
            " section')",
            key="key_section_name",
        )
        section_content = st.text_area(
            "Content of the new section", key="key_section_content"
        )
        submit_new_section = st.form_submit_button(
            "Create new section", on_click=add_custom_section
        )

    # ADD A PLOT
    with st.form("custom-plots", clear_on_submit=True):
        plot_name = st.text_input(
            "Section name (use '/' for subsections, e.g. 'Model description/My new"
            " plot')",
            key="key_plot_name",
        )
        plot_file = st.file_uploader("Upload a figure*", key="key_plot_file")

        submit_new_plot = st.form_submit_button("Add plot", on_click=add_custom_plot)

    for key in st.session_state.custom_sections:
        if not key:
            continue

        if key.startswith(PLOT_PREFIX):
            st.button(
                f"Remove plot '{key[len(PLOT_PREFIX):]}'",
                on_click=_remove_custom_section,
                args=(key,),
            )
        else:
            st.button(
                f"Remove section '{key}'", on_click=_remove_custom_section, args=(key,)
            )

    if st.session_state.custom_sections:
        st.button(
            f"Remove all ({len(st.session_state.custom_sections)}) custom elements",
            on_click=_clear_custom_section_cache,
        )


model_card = None
if model is None:
    st.text("*add a model to render the model card*")
if data is None:
    st.text("*add data to render the model card")
if (model is not None) and (data is not None):
    model_card = _create_model_card()

# this contains the rendered model card
rendered = download_model_card(model_card)
if rendered:
    st.download_button(label="Download model card (markdown format)", data=rendered)

display_model_card(model_card)