File size: 5,771 Bytes
f4f6aba
 
 
 
 
 
 
 
 
 
 
 
31a1df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94e602d
31a1df6
 
 
00bfdf9
82fe48d
31a1df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2174ccd
31a1df6
 
 
 
 
94e602d
 
 
31a1df6
 
2174ccd
31a1df6
 
 
 
 
 
 
 
 
 
 
2174ccd
31a1df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94e602d
31a1df6
 
 
 
 
 
 
 
94e602d
31a1df6
 
 
132e2aa
31a1df6
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Start page of the app

This page is used to initialize a model card that is either:

1. based on the skops template
2. empty
3. loads an existing model card

Optionally, users can add a model file, data, requirements, and choose a task.

"""

import glob
import io
import os
import pickle
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
from sklearn.dummy import DummyClassifier

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


hf_path = Path(mkdtemp(prefix="skops-"))  # hf repo
tmp_path = Path(mkdtemp(prefix="skops-"))  # temporary files
description = """Create an sklearn model card

This Hugging Face Space that aims to provide a simple interface to use the
[`skops`](https://skops.readthedocs.io/) model card creation utilities.

"""


def load_model() -> None:
    if st.session_state.get("model_file") is None:
        st.session_state.model = DummyClassifier()
        return

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

    st.session_state.model = model


def load_data() -> None:
    if st.session_state.get("data_file"):
        bytes_data = io.BytesIO(st.session_state.data_file.getvalue())
        df = pd.read_csv(bytes_data)
    else:
        df = pd.DataFrame([])

    st.session_state.data = df


def _clear_repo(path: str) -> None:
    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 init_repo(path: str) -> None:
    _clear_repo(path)
    requirements = []
    task = "tabular-classification"
    data = pd.DataFrame([])

    if "requirements" in st.session_state:
        requirements = st.session_state.requirements.splitlines()
    if "task" in st.session_state:
        task = st.session_state.task
    if "data_file" in st.session_state:
        load_data()
        data = st.session_state.data

    if task.startswith("text") and isinstance(data, pd.DataFrame):
        data = data.values.tolist()

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

        hub_utils.init(
            model=file_name,
            dst=path,
            task=task,
            data=data,
            requirements=requirements,
        )
        1
    except Exception as exc:
        print("Uh oh, something went wrong when initializing the repo:", exc)


def create_skops_model_card() -> None:
    init_repo(hf_path)
    metadata = card.metadata_from_config(hf_path)
    model_card = card.Card(model=st.session_state.model, metadata=metadata)
    st.session_state.model_card = model_card
    st.session_state.model_card_type = "skops"


def create_empty_model_card() -> None:
    init_repo(hf_path)
    metadata = card.metadata_from_config(hf_path)
    model_card = card.Card(
        model=st.session_state.model, metadata=metadata, template=None
    )
    model_card.add(**{"Untitled": "[More Information Needed]"})
    st.session_state.model_card = model_card
    st.session_state.model_card_type = "empty"


def create_hf_model_card() -> None:
    repo_id = st.session_state.get("hf_repo_id", "").strip("'").strip('"')
    if not repo_id:
        return

    print("downloading model card")
    path = hf_hub_download(repo_id, "README.md")
    model_card = card.parse_modelcard(path)
    st.session_state.model_card = model_card
    st.session_state.model_card_type = "loaded"


def start_input_form():
    if "model" not in st.session_state:
        st.session_state.model = DummyClassifier()

    if "data" not in st.session_state:
        st.session_state.data = pd.DataFrame([])

    if "model_card" not in st.session_state:
        st.session_state.model_card = None

    st.markdown(description)
    st.markdown("---")

    st.text(
        "Upload an sklearn model (strongly recommended)\n"
        "The model can be used to automatically populate fields in the model card."
    )
    st.file_uploader("Upload a model*", on_change=load_model, key="model_file")
    st.markdown("---")

    st.text(
        "Upload samples from your data (in csv format)\n"
        "This sample data can be attached to the metadata of the model card"
    )
    st.file_uploader(
        "Upload X data (csv)*", type=["csv"], on_change=load_data, key="data_file"
    )
    st.markdown("---")

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

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

    st.markdown("Choose one of the options below to get started:")
    col_0, col_1, col_2 = st.columns([2, 2, 2])
    with col_0:
        st.button("Create a new skops model card", on_click=create_skops_model_card)

    with col_1:
        st.button("Create a new empty model card", on_click=create_empty_model_card)

    with col_2:
        with st.form("Load existing model card from HF Hub", clear_on_submit=False):
            st.text_input("Repo name (e.g. 'gpt2')", key="hf_repo_id")
            st.form_submit_button("Load", on_click=create_hf_model_card)


start_input_form()