Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,120 +2,101 @@ import gradio as gr
|
|
2 |
import pandas as pd
|
3 |
from pathlib import Path
|
4 |
|
5 |
-
|
|
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
# ββββββββββ helpers βββββββββββββββββββββββββββββββββββββββββββββ
|
10 |
-
def tokenize_df(df: pd.DataFrame) -> pd.DataFrame:
|
11 |
rows = []
|
12 |
if "text" in df.columns:
|
13 |
lines = df["text"].astype(str)
|
14 |
else:
|
15 |
-
# user + assistant fallback
|
16 |
lines = df.apply(lambda r: f"User: {r['user']} Assistant: {r['assistant']}", axis=1)
|
17 |
for sid, line in enumerate(lines):
|
18 |
for tok in line.split():
|
19 |
rows.append({"sentence_id": sid, "token": tok, "label": "O"})
|
20 |
return pd.DataFrame(rows)
|
21 |
|
22 |
-
#
|
23 |
-
def
|
24 |
global token_df
|
25 |
df = pd.read_csv(file.name)
|
26 |
-
|
27 |
if "text" not in df.columns and not {"user", "assistant"}.issubset(df.columns):
|
28 |
-
return
|
29 |
-
|
30 |
-
gr.update(visible=False), gr.update(visible=False))
|
31 |
|
32 |
-
token_df =
|
|
|
|
|
|
|
33 |
|
34 |
-
|
35 |
-
gr.update(value=token_df, visible=True),
|
36 |
-
f"β
Loaded {len(df)} rows β {len(token_df)} tokens.",
|
37 |
-
gr.update(visible=True),
|
38 |
-
gr.update(visible=False)
|
39 |
-
)
|
40 |
-
|
41 |
-
def save_edits(table_data):
|
42 |
global token_df
|
43 |
-
token_df = pd.DataFrame(
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
47 |
path = "raw_tokens.csv"
|
48 |
token_df.to_csv(path, index=False)
|
49 |
return Path(path)
|
50 |
|
51 |
-
def
|
|
|
52 |
iob, prev = [], {}
|
53 |
for _, r in token_df.iterrows():
|
54 |
sid, lbl = r["sentence_id"], r["label"]
|
55 |
if lbl == "O":
|
56 |
-
iob.append("O")
|
57 |
-
prev[sid] = None
|
58 |
else:
|
59 |
-
|
|
|
60 |
prev[sid] = lbl
|
61 |
out = token_df.copy(); out["iob"] = iob
|
62 |
path = "ner_iob.csv"; out.to_csv(path, index=False)
|
63 |
return Path(path)
|
64 |
|
65 |
-
#
|
66 |
with gr.Blocks() as demo:
|
67 |
gr.Markdown("# π·οΈ Label It! Mini-NER")
|
68 |
-
|
69 |
-
gr.Markdown(
|
70 |
-
"**Step 1** β Upload a CSV containing either a `text` column, or `user` & `assistant` columns."
|
71 |
-
)
|
72 |
|
73 |
with gr.Row():
|
74 |
-
csv_file = gr.File(
|
75 |
load_btn = gr.Button("Load")
|
76 |
|
77 |
status = gr.Textbox(label="Status", interactive=False)
|
78 |
|
79 |
-
# Editable token table (hidden until load)
|
80 |
tok_table = gr.Dataframe(
|
81 |
headers=["sentence_id", "token", "label"],
|
82 |
datatype=["number", "str", "str"],
|
83 |
-
column_config={
|
84 |
-
"label": gr.ColumnConfig(
|
85 |
-
label="label",
|
86 |
-
dtype="categorical",
|
87 |
-
choices=LABEL_CHOICES,
|
88 |
-
)
|
89 |
-
},
|
90 |
row_count=0,
|
91 |
-
|
|
|
92 |
)
|
93 |
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
download_iob = gr.Button("β¬οΈ IOB CSV")
|
99 |
-
|
100 |
-
# File components that appear after export
|
101 |
-
file_tok = gr.File(label="Click to download", visible=False)
|
102 |
-
file_iob = gr.File(label="Click to download", visible=False)
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
outputs=[tok_table, status, buttons_row, file_tok])
|
107 |
|
108 |
-
|
|
|
|
|
109 |
|
110 |
-
|
111 |
-
outputs=file_tok) # file appears for click
|
112 |
|
113 |
-
|
114 |
-
|
115 |
|
116 |
gr.Markdown(
|
117 |
-
"**Step 2** β
|
118 |
-
"\nAfter saving, use the download buttons."
|
119 |
)
|
120 |
|
121 |
demo.launch()
|
|
|
2 |
import pandas as pd
|
3 |
from pathlib import Path
|
4 |
|
5 |
+
LABELS = {"PER", "ORG", "LOC", "EV", "O"} # allowed tags
|
6 |
+
token_df = pd.DataFrame() # global
|
7 |
|
8 |
+
# βββββββββββββββββ tokenization ββββββββββββββββββββββββββββββββ
|
9 |
+
def tokenize(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
|
|
10 |
rows = []
|
11 |
if "text" in df.columns:
|
12 |
lines = df["text"].astype(str)
|
13 |
else:
|
|
|
14 |
lines = df.apply(lambda r: f"User: {r['user']} Assistant: {r['assistant']}", axis=1)
|
15 |
for sid, line in enumerate(lines):
|
16 |
for tok in line.split():
|
17 |
rows.append({"sentence_id": sid, "token": tok, "label": "O"})
|
18 |
return pd.DataFrame(rows)
|
19 |
|
20 |
+
# βββββββββββββββββ callbacks βββββββββββββββββββββββββββββββββββ
|
21 |
+
def load_csv(file):
|
22 |
global token_df
|
23 |
df = pd.read_csv(file.name)
|
|
|
24 |
if "text" not in df.columns and not {"user", "assistant"}.issubset(df.columns):
|
25 |
+
return None, "β CSV must have `text` OR `user`+`assistant` columns.", \
|
26 |
+
gr.update(visible=False), gr.update(visible=False)
|
|
|
27 |
|
28 |
+
token_df = tokenize(df)
|
29 |
+
return gr.update(value=token_df, visible=True), \
|
30 |
+
f"β
Loaded {len(df)} rows β {len(token_df)} tokens.", \
|
31 |
+
gr.update(visible=True), gr.update(visible=False)
|
32 |
|
33 |
+
def save_table(tbl):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
global token_df
|
35 |
+
token_df = pd.DataFrame(tbl, columns=["sentence_id", "token", "label"])
|
36 |
+
# simple validation
|
37 |
+
bad = token_df[~token_df["label"].isin(LABELS)]
|
38 |
+
if not bad.empty:
|
39 |
+
return "β οΈ Unknown labels found. Allowed: PER / ORG / LOC / EV / O"
|
40 |
+
return "πΎ Saved."
|
41 |
+
|
42 |
+
def to_tokens_csv():
|
43 |
path = "raw_tokens.csv"
|
44 |
token_df.to_csv(path, index=False)
|
45 |
return Path(path)
|
46 |
|
47 |
+
def to_iob_csv():
|
48 |
+
# build IOB tags
|
49 |
iob, prev = [], {}
|
50 |
for _, r in token_df.iterrows():
|
51 |
sid, lbl = r["sentence_id"], r["label"]
|
52 |
if lbl == "O":
|
53 |
+
iob.append("O"); prev[sid] = None
|
|
|
54 |
else:
|
55 |
+
prefix = "I-" if prev.get(sid) == lbl else "B-"
|
56 |
+
iob.append(prefix + lbl)
|
57 |
prev[sid] = lbl
|
58 |
out = token_df.copy(); out["iob"] = iob
|
59 |
path = "ner_iob.csv"; out.to_csv(path, index=False)
|
60 |
return Path(path)
|
61 |
|
62 |
+
# βββββββββββββββββ UI ββββββββββββββββββββββββββββββββββββββββββ
|
63 |
with gr.Blocks() as demo:
|
64 |
gr.Markdown("# π·οΈ Label It! Mini-NER")
|
65 |
+
gr.Markdown("**Step 1** β upload a CSV containing a `text` column *or* `user`+`assistant` columns.")
|
|
|
|
|
|
|
66 |
|
67 |
with gr.Row():
|
68 |
+
csv_file = gr.File(file_types=[".csv"])
|
69 |
load_btn = gr.Button("Load")
|
70 |
|
71 |
status = gr.Textbox(label="Status", interactive=False)
|
72 |
|
|
|
73 |
tok_table = gr.Dataframe(
|
74 |
headers=["sentence_id", "token", "label"],
|
75 |
datatype=["number", "str", "str"],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
row_count=0,
|
77 |
+
col_count=3,
|
78 |
+
visible=False
|
79 |
)
|
80 |
|
81 |
+
with gr.Row(visible=False) as btn_row:
|
82 |
+
save_btn = gr.Button("πΎ Save")
|
83 |
+
dl_tok = gr.Button("β¬οΈ Tokens CSV")
|
84 |
+
dl_iob = gr.Button("β¬οΈ IOB CSV")
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
+
file_tok = gr.File(visible=False)
|
87 |
+
file_iob = gr.File(visible=False)
|
|
|
88 |
|
89 |
+
# bind
|
90 |
+
load_btn.click(load_csv, inputs=csv_file,
|
91 |
+
outputs=[tok_table, status, btn_row, file_tok])
|
92 |
|
93 |
+
save_btn.click(save_table, inputs=tok_table, outputs=status)
|
|
|
94 |
|
95 |
+
dl_tok.click(lambda: to_tokens_csv(), outputs=file_tok)
|
96 |
+
dl_iob.click(lambda: to_iob_csv(), outputs=file_iob)
|
97 |
|
98 |
gr.Markdown(
|
99 |
+
"**Step 2** β type `PER`, `ORG`, `LOC`, `EV`, or `O` in the **label** column β Save β Download."
|
|
|
100 |
)
|
101 |
|
102 |
demo.launch()
|