Download app.py from mintraven/bhs-api: direct link, hf CLI and curl.
- Browser
- Download file 2.29 kB
-
https://huggingface.co/spaces/mintraven/bhs-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/mintraven/bhs-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mintraven/bhs-api/resolve/main/app.py
2.29 kB
| import spaces | |
| import gradio as gr | |
| import pandas as pd | |
| from app.infer import load, predict | |
| TEXT_COLUMNS = ("text", "comment", "message", "content") | |
| MAX_ROWS = 5000 | |
| load() | |
| def classify_text(text: str): | |
| text = (text or "").strip() | |
| if not text: | |
| raise gr.Error("text is empty") | |
| return predict([text])[0] | |
| def _text_column(columns: list[str]) -> str: | |
| lower = {c.lower(): c for c in columns} | |
| for name in TEXT_COLUMNS: | |
| if name in lower: | |
| return lower[name] | |
| raise gr.Error(f"CSV needs a text column. Tried: {', '.join(TEXT_COLUMNS)}") | |
| def classify_csv(file): | |
| if file is None: | |
| raise gr.Error("no CSV") | |
| df = pd.read_csv(file) | |
| if df.empty: | |
| return pd.DataFrame() | |
| col = _text_column(list(df.columns)) | |
| series = df[col].fillna("").astype(str).str.strip() | |
| if len(series) > MAX_ROWS: | |
| raise gr.Error(f"more than {MAX_ROWS} rows") | |
| texts = [] | |
| rows = [] | |
| for idx, value in series.items(): | |
| if not value: | |
| continue | |
| texts.append(value) | |
| rows.append(int(idx)) | |
| out = [] | |
| batch = 32 | |
| for i in range(0, len(texts), batch): | |
| chunk = predict(texts[i : i + batch]) | |
| for row, item in zip(rows[i : i + batch], chunk): | |
| item["row"] = row | |
| out.append(item) | |
| return pd.DataFrame(out) | |
| with gr.Blocks(title="Bengali abusive classifier") as demo: | |
| gr.Markdown("Bengali / romanized Bangla. Labels: `normal`, `abusive`. Latin text is transliterated first.") | |
| with gr.Tab("Text"): | |
| t_in = gr.Textbox(lines=6, label="paragraph") | |
| t_out = gr.JSON(label="result") | |
| gr.Button("Classify").click( | |
| classify_text, | |
| t_in, | |
| t_out, | |
| api_name="classify_text", | |
| concurrency_limit=1, | |
| ) | |
| with gr.Tab("CSV"): | |
| f_in = gr.File(file_types=[".csv"], label="CSV with a text column") | |
| f_out = gr.Dataframe(label="results") | |
| gr.Button("Classify CSV").click( | |
| classify_csv, | |
| f_in, | |
| f_out, | |
| api_name="classify_csv", | |
| concurrency_limit=1, | |
| ) | |
| demo.queue(max_size=8) | |
| if __name__ == "__main__": | |
| demo.launch(ssr_mode=False) | |