mintraven commited on
Commit
ec8f8b3
·
verified ·
1 Parent(s): 7ea5a54

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. README.md +6 -8
  2. app.py +66 -0
  3. app/__init__.py +0 -0
  4. app/infer.py +108 -0
  5. requirements.txt +11 -0
README.md CHANGED
@@ -1,14 +1,12 @@
1
  ---
2
- title: Bhs Api
3
- emoji: 🐠
4
- colorFrom: red
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 6.31.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
- short_description: bengali hate speech API
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: bhs-api
3
+ emoji: 🗣️
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 5.29.0
 
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
+ Bengali abusive / normal classifier (MuRIL + IndicXlit).
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import gradio as gr
3
+
4
+ from app.infer import load, predict
5
+
6
+ TEXT_COLUMNS = ("text", "comment", "message", "content")
7
+ MAX_ROWS = 5000
8
+
9
+ load()
10
+
11
+
12
+ def classify_text(text: str):
13
+ text = (text or "").strip()
14
+ if not text:
15
+ raise gr.Error("text is empty")
16
+ return predict([text])[0]
17
+
18
+
19
+ def _text_column(columns: list[str]) -> str:
20
+ lower = {c.lower(): c for c in columns}
21
+ for name in TEXT_COLUMNS:
22
+ if name in lower:
23
+ return lower[name]
24
+ raise gr.Error(f"CSV needs a text column. Tried: {', '.join(TEXT_COLUMNS)}")
25
+
26
+
27
+ def classify_csv(file):
28
+ if file is None:
29
+ raise gr.Error("no CSV")
30
+ df = pd.read_csv(file)
31
+ if df.empty:
32
+ return pd.DataFrame()
33
+ col = _text_column(list(df.columns))
34
+ series = df[col].fillna("").astype(str).str.strip()
35
+ if len(series) > MAX_ROWS:
36
+ raise gr.Error(f"more than {MAX_ROWS} rows")
37
+ texts = []
38
+ rows = []
39
+ for idx, value in series.items():
40
+ if not value:
41
+ continue
42
+ texts.append(value)
43
+ rows.append(int(idx))
44
+ out = []
45
+ batch = 32
46
+ for i in range(0, len(texts), batch):
47
+ chunk = predict(texts[i : i + batch])
48
+ for row, item in zip(rows[i : i + batch], chunk):
49
+ item["row"] = row
50
+ out.append(item)
51
+ return pd.DataFrame(out)
52
+
53
+
54
+ with gr.Blocks(title="Bengali abusive classifier") as demo:
55
+ gr.Markdown("Bengali / romanized Bangla. Labels: `normal`, `abusive`. Latin text is transliterated first.")
56
+ with gr.Tab("Text"):
57
+ t_in = gr.Textbox(lines=6, label="paragraph")
58
+ t_out = gr.JSON(label="result")
59
+ gr.Button("Classify").click(classify_text, t_in, t_out)
60
+ with gr.Tab("CSV"):
61
+ f_in = gr.File(file_types=[".csv"], label="CSV with a text column")
62
+ f_out = gr.Dataframe(label="results")
63
+ gr.Button("Classify CSV").click(classify_csv, f_in, f_out)
64
+
65
+ if __name__ == "__main__":
66
+ demo.launch()
app/__init__.py ADDED
File without changes
app/infer.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ from typing import Any
4
+
5
+ import ctranslate2
6
+ import torch
7
+ from huggingface_hub import snapshot_download
8
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
9
+
10
+ MODEL_NAME = os.environ.get("MODEL_NAME", "Hate-speech-CNERG/bengali-abusive-MuRIL")
11
+ XLIT_REPO = os.environ.get("XLIT_REPO", "Singla0009/all-indic-transliteration")
12
+ MAX_LENGTH = int(os.environ.get("MAX_LENGTH", "128"))
13
+ ID2LABEL = {0: "normal", 1: "abusive"}
14
+ _WORD_RE = re.compile(r"[A-Za-z]+")
15
+ _device: str | None = None
16
+ _tokenizer = None
17
+ _model = None
18
+ _xlit = None
19
+ _xlit_cache: dict[str, str] = {}
20
+
21
+
22
+ def _pick_device() -> str:
23
+ forced = os.environ.get("DEVICE")
24
+ if forced:
25
+ return forced
26
+ return "cuda" if torch.cuda.is_available() else "cpu"
27
+
28
+
29
+ def load() -> None:
30
+ global _device, _tokenizer, _model, _xlit
31
+ if _model is not None and _xlit is not None:
32
+ return
33
+ _device = _pick_device()
34
+ _tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
35
+ _model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME).to(_device)
36
+ _model.eval()
37
+ path = snapshot_download(repo_id=XLIT_REPO, allow_patterns="indicxlit_ct2_fp32/*")
38
+ _xlit = ctranslate2.Translator(os.path.join(path, "indicxlit_ct2_fp32"), device="cpu")
39
+
40
+
41
+ def status() -> dict[str, Any]:
42
+ return {
43
+ "ready": _model is not None and _xlit is not None,
44
+ "device": _device,
45
+ "model": MODEL_NAME,
46
+ }
47
+
48
+
49
+ def _xlit_words(words: list[str]) -> list[str]:
50
+ assert _xlit is not None
51
+ todo = [w for w in set(words) if w not in _xlit_cache]
52
+ if todo:
53
+ batch = [["__bn__"] + list(w) for w in todo]
54
+ results = _xlit.translate_batch(batch, beam_size=4)
55
+ for w, r in zip(todo, results):
56
+ _xlit_cache[w] = "".join(r.hypotheses[0])
57
+ return [_xlit_cache[w] for w in words]
58
+
59
+
60
+ def to_bengali(text: str) -> str:
61
+ words = [m.group().lower() for m in _WORD_RE.finditer(text)]
62
+ if not words:
63
+ return text
64
+ converted = iter(_xlit_words(words))
65
+ return _WORD_RE.sub(lambda m: next(converted), text)
66
+
67
+
68
+ def prepare_text(text: str) -> tuple[str, str | None]:
69
+ if not _WORD_RE.search(text):
70
+ return text, None
71
+ converted = to_bengali(text)
72
+ return converted, converted
73
+
74
+
75
+ def predict(texts: list[str]) -> list[dict[str, Any]]:
76
+ assert _tokenizer is not None and _model is not None and _device is not None
77
+ if not texts:
78
+ return []
79
+ prepared: list[str] = []
80
+ transliterated: list[str | None] = []
81
+ for t in texts:
82
+ conv, xl = prepare_text(t)
83
+ prepared.append(conv)
84
+ transliterated.append(xl)
85
+ inputs = _tokenizer(
86
+ prepared,
87
+ return_tensors="pt",
88
+ padding=True,
89
+ truncation=True,
90
+ max_length=MAX_LENGTH,
91
+ ).to(_device)
92
+ with torch.no_grad():
93
+ logits = _model(**inputs).logits
94
+ probs = torch.softmax(logits, dim=-1).cpu()
95
+ results = []
96
+ for original, xl, p in zip(texts, transliterated, probs):
97
+ label_id = int(p.argmax())
98
+ item = {
99
+ "text": original,
100
+ "label": ID2LABEL[label_id],
101
+ "confidence": round(float(p[label_id]), 4),
102
+ "p_normal": round(float(p[0]), 4),
103
+ "p_abusive": round(float(p[1]), 4),
104
+ }
105
+ if xl is not None:
106
+ item["transliterated"] = xl
107
+ results.append(item)
108
+ return results
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi>=0.115.0
2
+ uvicorn[standard]>=0.32.0
3
+ python-multipart>=0.0.12
4
+ pandas>=2.2.0
5
+ transformers>=4.46.0
6
+ torch>=2.4.0
7
+ sentencepiece>=0.2.0
8
+ accelerate>=1.0.0
9
+ ctranslate2>=4.5.0
10
+ huggingface_hub>=0.26.0
11
+ gradio>=5.29.0