File size: 5,703 Bytes
36c6cb2
d3e9851
36c6cb2
 
 
 
 
 
c1bba49
917f380
36c6cb2
 
277b10b
36c6cb2
277b10b
917f380
a2cb3cf
277b10b
 
 
36c6cb2
917f380
277b10b
 
 
36c6cb2
 
d3e9851
36c6cb2
 
277b10b
 
36c6cb2
 
 
 
 
277b10b
 
36c6cb2
 
917f380
 
36c6cb2
277b10b
 
36c6cb2
d3e9851
 
 
 
 
 
 
917f380
277b10b
36c6cb2
 
 
d3e9851
 
36c6cb2
 
277b10b
 
 
c1bba49
 
 
 
 
 
917f380
 
 
 
 
 
 
 
 
 
c1bba49
 
36c6cb2
 
c1bba49
277b10b
 
36c6cb2
917f380
c1bba49
 
68f3f5a
 
c1bba49
 
 
68f3f5a
 
c1bba49
917f380
 
 
 
 
 
277b10b
 
36c6cb2
c1bba49
 
36c6cb2
c1bba49
 
917f380
 
 
 
 
277b10b
 
36c6cb2
c1bba49
 
 
277b10b
 
917f380
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277b10b
c1bba49
 
 
277b10b
 
 
c1bba49
 
 
277b10b
 
c1bba49
 
 
 
 
 
277b10b
 
36c6cb2
c1bba49
36c6cb2
277b10b
c1bba49
277b10b
36c6cb2
 
 
 
 
 
 
277b10b
 
36c6cb2
917f380
3b8b7e8
917f380
277b10b
36c6cb2
 
 
 
 
277b10b
 
 
c1bba49
 
 
917f380
 
 
 
 
 
 
 
 
 
 
 
277b10b
 
c1bba49
5c52bc9
 
 
917f380
c1bba49
277b10b
 
d3e9851
 
 
 
 
 
917f380
d3e9851
 
 
 
c1bba49
 
 
d3e9851
 
36c6cb2
 
 
d3e9851
 
 
 
 
 
277b10b
 
 
917f380
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
# /// script
# requires-python = "==3.12"
# dependencies = [
#     "marimo",
#     "polars==1.23.0",
#     "scikit-learn==1.6.1",
#     "numpy==2.1.3",
#     "mohtml==0.1.2",
#     "model2vec==0.4.0",
#     "altair==5.5.0",
# ]
# ///

import marimo

__generated_with = "0.11.14"
app = marimo.App()


@app.cell
def _(mo):
    mo.md("""### Fast labelling demo""")
    return


@app.cell
def _(mo, use_default_switch):
    uploaded_file = mo.ui.file(kind="area") if not use_default_switch.value else None
    uploaded_file
    return (uploaded_file,)


@app.cell
def _(mo):
    use_default_switch = mo.ui.switch(False, label="Use default dataset")
    use_default_switch
    return (use_default_switch,)


@app.cell
def _(mo):
    pos_label = mo.ui.text("pos", placeholder="positive label name", label="positive class name")
    neg_label = mo.ui.text("neg", placeholder="negative label name", label="negative class name")
    return neg_label, pos_label


@app.cell
def _(uploaded_file, use_default_switch):
    should_stop = not use_default_switch.value and len(uploaded_file.value) == 0
    return (should_stop,)


@app.cell
def _(mo, pl, should_stop, uploaded_file, use_default_switch):
    mo.stop(should_stop , mo.md("**Submit a dataset or use default one to continue.**"))

    if use_default_switch.value:
        df = pl.read_csv("spam.csv")
    else:
        df = pl.read_csv(uploaded_file.value[0].contents)

    texts = df["text"].to_list()
    return df, texts


@app.cell
def _(StaticModel, mo):
    with mo.status.spinner(subtitle="Loading model ...") as _spinner:
        tfm = StaticModel.from_pretrained("minishlab/potion-retrieval-32M")
    return (tfm,)


@app.cell
def _(mo, should_stop):
    mo.stop(should_stop)

    text_input = mo.ui.text_area("you will win a free ringtone!", label="Reference sentences")
    form = mo.md("""{text_input}""").batch(text_input=text_input).form()
    form
    return form, text_input


@app.cell
def _(mo, texts, tfm):
    with mo.status.spinner(subtitle="Creating embeddings ...") as _spinner:
        X = tfm.encode(texts)
    return (X,)


@app.cell
def _(add_label, get_example, mo, neg_label, pos_label, undo):
    btn_spam = mo.ui.button(
        label=f"Annotate {neg_label.value}", 
        on_click=lambda d: add_label(get_example(), neg_label.value), 
        keyboard_shortcut="Ctrl-L"
    )
    btn_ham = mo.ui.button(
        label=f"Annotate {pos_label.value}", 
        on_click=lambda d: add_label(get_example(), pos_label.value),
        keyboard_shortcut="Ctrl-K"
    )
    btn_undo = mo.ui.button(
        label="Undo", 
        on_click=lambda d: undo(),
        keyboard_shortcut="Ctrl-U"
    )
    return btn_ham, btn_spam, btn_undo


@app.cell
def _(gen, get_label, set_example, set_label):
    def add_label(text, lab):
        current_labels = get_label()
        set_label(current_labels + [{"text": text, "label": lab}])
        set_example(next(gen))

    def undo(): 
        current_labels = get_label()
        set_label(current_labels[:-2])
    return add_label, undo


@app.cell
def _():
    from mohtml import br
    return (br,)


@app.cell
def _(br, btn_ham, btn_spam, btn_undo, example, mo, neg_label, p, pos_label):
    mo.vstack([
        mo.hstack([
           pos_label, neg_label
        ]),
        br(),
        mo.hstack([
            btn_ham, btn_spam, btn_undo
        ]),
        br(),
        p("Current example:", klass="font-bold"),
        example
    ])
    return


@app.cell
def _(mo):
    get_label, set_label = mo.state([])
    return get_label, set_label


@app.cell
def _(gen, mo):
    get_example, set_example = mo.state(next(gen))
    return get_example, set_example


@app.cell
def _():
    from mohtml import tailwind_css, div, p

    tailwind_css()
    return div, p, tailwind_css


@app.cell
def _(get_label, mo):
    import json

    data = get_label()

    json_download = mo.download(
        data=json.dumps(data).encode("utf-8"),
        filename="data.json",
        mimetype="application/json",
        label="Download JSON",
    )
    return data, json, json_download


@app.cell
def _(X, cosine_similarity, form, get_label, mo, pl, texts, tfm):
    mo.stop(not form.value, "Need a text input to fetch example")
    mo.stop(not form.value.get("text_input", None), "Need a text input to fetch example")

    df_emb = (
        pl.DataFrame({
            "index": range(X.shape[0]), 
            "text": texts
        }).with_columns(sim=pl.lit(1))
    )


    query = tfm.encode([form.value["text_input"]])
    similarity = cosine_similarity(query, X)[0]
    df_emb = df_emb.with_columns(sim=similarity).sort(pl.col("sim"), descending=True)
    label_texts = [_["text"] for _ in get_label()]
    gen = (_["text"] for _ in df_emb.head(100).to_dicts() if _["text"] not in label_texts)
    return df_emb, gen, label_texts, query, similarity


@app.cell
def _(div, get_example, p):
    example = div(
        p(get_example()), 
        klass="bg-gray-100 p-4 rounded-lg"
    )
    return (example,)


@app.cell
def _(get_label, mo, pl, should_stop):
    mo.stop(should_stop)

    pl.DataFrame(get_label()).reverse()
    return


@app.cell
def _(mo):
    with mo.status.spinner(subtitle="Loading libraries ...") as _spinner:
        import polars as pl
        import numpy as np
        from sklearn.metrics.pairwise import cosine_similarity
    return cosine_similarity, np, pl


@app.cell
def _(mo):
    with mo.status.spinner(subtitle="Loading model2vec ...") as _spinner:
        from model2vec import StaticModel
    return (StaticModel,)


@app.cell
def _():
    import marimo as mo
    return (mo,)


@app.cell
def _():
    return


if __name__ == "__main__":
    app.run()