Download app/infer.py from mintraven/bhs-api: direct link, hf CLI and curl.
- Browser
- Download file 3.65 kB
-
https://huggingface.co/spaces/mintraven/bhs-api/resolve/main/app/infer.py
- Command line
-
hf download hf://spaces/mintraven/bhs-api/app/infer.py
-
curl -L -o infer.py https://huggingface.co/spaces/mintraven/bhs-api/resolve/main/app/infer.py
3.65 kB
| import os | |
| import re | |
| from typing import Any | |
| import ctranslate2 | |
| import torch | |
| from huggingface_hub import snapshot_download | |
| from transformers import AutoModelForSequenceClassification, AutoTokenizer | |
| MODEL_NAME = os.environ.get("MODEL_NAME", "Hate-speech-CNERG/bengali-abusive-MuRIL") | |
| XLIT_REPO = os.environ.get("XLIT_REPO", "Singla0009/all-indic-transliteration") | |
| MAX_LENGTH = int(os.environ.get("MAX_LENGTH", "128")) | |
| ID2LABEL = {0: "normal", 1: "abusive"} | |
| _WORD_RE = re.compile(r"[A-Za-z]+") | |
| _device: str | None = None | |
| _tokenizer = None | |
| _model = None | |
| _xlit = None | |
| _xlit_cache: dict[str, str] = {} | |
| def _pick_device() -> str: | |
| forced = os.environ.get("DEVICE") | |
| if forced: | |
| return forced | |
| return "cuda" if torch.cuda.is_available() else "cpu" | |
| def load() -> None: | |
| global _device, _tokenizer, _model, _xlit | |
| if _model is not None and _xlit is not None and _tokenizer is not None: | |
| return | |
| _device = _pick_device() | |
| dtype = torch.float16 if _device == "cuda" else torch.float32 | |
| if _tokenizer is None: | |
| _tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) | |
| if _model is None: | |
| _model = AutoModelForSequenceClassification.from_pretrained( | |
| MODEL_NAME, | |
| use_safetensors=True, | |
| torch_dtype=dtype, | |
| ).to(_device) | |
| _model.eval() | |
| if _xlit is None: | |
| path = snapshot_download(repo_id=XLIT_REPO, allow_patterns="indicxlit_ct2_fp32/*") | |
| _xlit = ctranslate2.Translator(os.path.join(path, "indicxlit_ct2_fp32"), device="cpu") | |
| def status() -> dict[str, Any]: | |
| return { | |
| "ready": _model is not None and _xlit is not None, | |
| "device": _device, | |
| "model": MODEL_NAME, | |
| } | |
| def _xlit_words(words: list[str]) -> list[str]: | |
| assert _xlit is not None | |
| todo = [w for w in set(words) if w not in _xlit_cache] | |
| if todo: | |
| batch = [["__bn__"] + list(w) for w in todo] | |
| results = _xlit.translate_batch(batch, beam_size=4) | |
| for w, r in zip(todo, results): | |
| _xlit_cache[w] = "".join(r.hypotheses[0]) | |
| return [_xlit_cache[w] for w in words] | |
| def to_bengali(text: str) -> str: | |
| words = [m.group().lower() for m in _WORD_RE.finditer(text)] | |
| if not words: | |
| return text | |
| converted = iter(_xlit_words(words)) | |
| return _WORD_RE.sub(lambda m: next(converted), text) | |
| def prepare_text(text: str) -> tuple[str, str | None]: | |
| if not _WORD_RE.search(text): | |
| return text, None | |
| converted = to_bengali(text) | |
| return converted, converted | |
| def predict(texts: list[str]) -> list[dict[str, Any]]: | |
| assert _tokenizer is not None and _model is not None and _device is not None | |
| if not texts: | |
| return [] | |
| prepared: list[str] = [] | |
| transliterated: list[str | None] = [] | |
| for t in texts: | |
| conv, xl = prepare_text(t) | |
| prepared.append(conv) | |
| transliterated.append(xl) | |
| inputs = _tokenizer( | |
| prepared, | |
| return_tensors="pt", | |
| padding=True, | |
| truncation=True, | |
| max_length=MAX_LENGTH, | |
| ).to(_device) | |
| with torch.no_grad(): | |
| logits = _model(**inputs).logits | |
| probs = torch.softmax(logits, dim=-1).cpu() | |
| results = [] | |
| for original, xl, p in zip(texts, transliterated, probs): | |
| label_id = int(p.argmax()) | |
| item = { | |
| "text": original, | |
| "label": ID2LABEL[label_id], | |
| "confidence": round(float(p[label_id]), 4), | |
| "p_normal": round(float(p[0]), 4), | |
| "p_abusive": round(float(p[1]), 4), | |
| } | |
| if xl is not None: | |
| item["transliterated"] = xl | |
| results.append(item) | |
| return results | |