kasimali
commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,190 +1,128 @@
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
-
import
|
| 4 |
import fasttext
|
| 5 |
import torch
|
|
|
|
| 6 |
from transformers import AutoTokenizer
|
| 7 |
from huggingface_hub import hf_hub_download
|
| 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 |
-
if
|
| 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 |
-
for k in enc:
|
| 118 |
-
enc[k] = enc[k].to(DEVICE)
|
| 119 |
-
outputs = bert_model(
|
| 120 |
-
enc["input_ids"],
|
| 121 |
-
token_type_ids=enc.get("token_type_ids"),
|
| 122 |
-
attention_mask=enc.get("attention_mask"),
|
| 123 |
-
)
|
| 124 |
-
logits = outputs.logits if hasattr(outputs, "logits") else outputs[0]
|
| 125 |
-
probs = torch.softmax(logits, dim=1)
|
| 126 |
-
preds = torch.argmax(probs, dim=1)
|
| 127 |
-
scores = probs.gather(1, preds.unsqueeze(1)).squeeze(1)
|
| 128 |
-
results = []
|
| 129 |
-
for i, t, p, s in zip(idxs, texts, preds, scores):
|
| 130 |
-
label_idx = int(p.item())
|
| 131 |
-
label = LABEL_MAP_REVERSE.get(label_idx, str(label_idx))
|
| 132 |
-
results.append({"index": i, "text": t, "label": label, "score": float(s.item()), "model": "IndicLID-BERT"})
|
| 133 |
-
results.sort(key=lambda x: x["index"])
|
| 134 |
-
return results
|
| 135 |
-
|
| 136 |
-
def ensemble_predict(texts):
|
| 137 |
-
roman_inputs, native_inputs = [], []
|
| 138 |
-
for i, t in enumerate(texts):
|
| 139 |
-
if roman_char_ratio(t) > ROMAN_SPLIT_THRESHOLD:
|
| 140 |
-
roman_inputs.append((i, t))
|
| 141 |
-
else:
|
| 142 |
-
native_inputs.append((i, t))
|
| 143 |
-
|
| 144 |
-
outputs = {}
|
| 145 |
-
|
| 146 |
-
if native_inputs:
|
| 147 |
-
nat_texts = [t for _, t in native_inputs]
|
| 148 |
-
nat_out = predict_ftn(nat_texts)
|
| 149 |
-
for (i, _), r in zip(native_inputs, nat_out):
|
| 150 |
-
outputs[i] = r
|
| 151 |
-
|
| 152 |
-
if roman_inputs:
|
| 153 |
-
rom_texts = [t for _, t in roman_inputs]
|
| 154 |
-
ftr_kept, bert_inputs = ftr_predict_or_route(rom_texts)
|
| 155 |
-
for kept in ftr_kept:
|
| 156 |
-
i_orig = roman_inputs[kept["index"]][0]
|
| 157 |
-
outputs[i_orig] = {
|
| 158 |
-
"text": kept["text"], "label": kept["label"], "score": kept["score"], "model": kept["model"]
|
| 159 |
-
}
|
| 160 |
-
if bert_inputs:
|
| 161 |
-
bert_out = bert_predict(bert_inputs)
|
| 162 |
-
for r in bert_out:
|
| 163 |
-
i_orig = roman_inputs[r["index"]][0]
|
| 164 |
-
outputs[i_orig] = {
|
| 165 |
-
"text": r["text"], "label": r["label"], "score": r["score"], "model": r["model"]
|
| 166 |
-
}
|
| 167 |
-
|
| 168 |
-
return [outputs[i] for i in sorted(outputs.keys())]
|
| 169 |
-
|
| 170 |
-
# ---------------------------------------------------------------------------------
|
| 171 |
-
# Gradio UI
|
| 172 |
-
# ---------------------------------------------------------------------------------
|
| 173 |
-
def detect(texts_str: str):
|
| 174 |
-
if not texts_str or not texts_str.strip():
|
| 175 |
-
return []
|
| 176 |
-
lines = [t.strip() for t in texts_str.split("\n") if t.strip()]
|
| 177 |
-
return ensemble_predict(lines)
|
| 178 |
-
|
| 179 |
-
with gr.Blocks(title="IndicLID Ensemble (AI4Bharat) — Gradio Space") as demo:
|
| 180 |
-
gr.Markdown(
|
| 181 |
-
"## IndicLID Ensemble (AI4Bharat)\n"
|
| 182 |
-
"Two-stage LID for 22 Indian languages (47 classes), with native fastText (FTN), roman fastText (FTR), "
|
| 183 |
-
"and IndicBERT fallback for low-confidence romanized inputs."
|
| 184 |
-
)
|
| 185 |
-
inp = gr.Textbox(lines=8, label="Enter text(s) — one per line")
|
| 186 |
-
out = gr.JSON(label="Predictions")
|
| 187 |
-
gr.Button("Detect").click(fn=detect, inputs=inp, outputs=out)
|
| 188 |
-
|
| 189 |
if __name__ == "__main__":
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
+
import pandas as pd
|
| 4 |
import fasttext
|
| 5 |
import torch
|
| 6 |
+
from torch.utils.data import Dataset, DataLoader
|
| 7 |
from transformers import AutoTokenizer
|
| 8 |
from huggingface_hub import hf_hub_download
|
| 9 |
|
| 10 |
+
# ------------------------------
|
| 11 |
+
# Download models automatically
|
| 12 |
+
# ------------------------------
|
| 13 |
+
print("Downloading IndicLID models from Hugging Face...")
|
| 14 |
+
|
| 15 |
+
FTN_PATH = hf_hub_download("ai4bharat/IndicLID-FTN", filename="model_baseline_roman.bin")
|
| 16 |
+
FTR_PATH = hf_hub_download("ai4bharat/IndicLID-FTR", filename="model_baseline_roman.bin")
|
| 17 |
+
BERT_PATH = hf_hub_download("ai4bharat/IndicLID-BERT", filename="basline_nn_simple.pt")
|
| 18 |
+
|
| 19 |
+
print("Download complete.")
|
| 20 |
+
|
| 21 |
+
# ------------------------------
|
| 22 |
+
# Dataset class for BERT batching
|
| 23 |
+
# ------------------------------
|
| 24 |
+
class IndicBERT_Data(Dataset):
|
| 25 |
+
def __init__(self, indices, X):
|
| 26 |
+
self.x = list(X)
|
| 27 |
+
self.i = list(indices)
|
| 28 |
+
def __len__(self):
|
| 29 |
+
return len(self.x)
|
| 30 |
+
def __getitem__(self, idx):
|
| 31 |
+
return self.i[idx], self.x[idx]
|
| 32 |
+
|
| 33 |
+
# ------------------------------
|
| 34 |
+
# Full IndicLID Ensemble
|
| 35 |
+
# ------------------------------
|
| 36 |
+
class IndicLID:
|
| 37 |
+
def __init__(self, input_threshold=0.5, roman_lid_threshold=0.6):
|
| 38 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 39 |
+
self.IndicLID_FTN = fasttext.load_model(FTN_PATH)
|
| 40 |
+
self.IndicLID_FTR = fasttext.load_model(FTR_PATH)
|
| 41 |
+
self.IndicLID_BERT = torch.load(BERT_PATH, map_location=self.device)
|
| 42 |
+
self.IndicLID_BERT.eval()
|
| 43 |
+
self.IndicLID_BERT_tokenizer = AutoTokenizer.from_pretrained("ai4bharat/IndicBERTv2-MLM-only")
|
| 44 |
+
self.input_threshold = input_threshold
|
| 45 |
+
self.model_threshold = roman_lid_threshold
|
| 46 |
+
|
| 47 |
+
# Official label mapping from AI4Bharat
|
| 48 |
+
self.label_map_reverse = {
|
| 49 |
+
0: 'asm_Latn', 1: 'ben_Latn', 2: 'brx_Latn', 3: 'guj_Latn', 4: 'hin_Latn',
|
| 50 |
+
5: 'kan_Latn', 6: 'kas_Latn', 7: 'kok_Latn', 8: 'mai_Latn', 9: 'mal_Latn',
|
| 51 |
+
10: 'mni_Latn', 11: 'mar_Latn', 12: 'nep_Latn', 13: 'ori_Latn', 14: 'pan_Latn',
|
| 52 |
+
15: 'san_Latn', 16: 'snd_Latn', 17: 'tam_Latn', 18: 'tel_Latn', 19: 'urd_Latn',
|
| 53 |
+
20: 'eng_Latn', 21: 'other', 22: 'asm_Beng', 23: 'ben_Beng', 24: 'brx_Deva',
|
| 54 |
+
25: 'doi_Deva', 26: 'guj_Gujr', 27: 'hin_Deva', 28: 'kan_Knda', 29: 'kas_Arab',
|
| 55 |
+
30: 'kas_Deva', 31: 'kok_Deva', 32: 'mai_Deva', 33: 'mal_Mlym', 34: 'mni_Beng',
|
| 56 |
+
35: 'mni_Meti', 36: 'mar_Deva', 37: 'nep_Deva', 38: 'ori_Orya', 39: 'pan_Guru',
|
| 57 |
+
40: 'san_Deva', 41: 'sat_Olch', 42: 'snd_Arab', 43: 'tam_Tamil', 44: 'tel_Telu',
|
| 58 |
+
45: 'urd_Arab'
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
def char_percent_check(self, text):
|
| 62 |
+
total_chars = sum(c.isalpha() for c in text)
|
| 63 |
+
roman_chars = sum(bool(re.match(r"[A-Za-z]", c)) for c in text)
|
| 64 |
+
return roman_chars / total_chars if total_chars else 0
|
| 65 |
+
|
| 66 |
+
def native_inference(self, data, out_dict):
|
| 67 |
+
if not data: return out_dict
|
| 68 |
+
texts = [x[1] for x in data]
|
| 69 |
+
preds = self.IndicLID_FTN.predict(texts)
|
| 70 |
+
for (idx, txt), lbls, scrs in zip(data, preds[0], preds[1]):
|
| 71 |
+
out_dict[idx] = (txt, lbls[0][9:], float(scrs[0]), 'IndicLID-FTN')
|
| 72 |
+
return out_dict
|
| 73 |
+
|
| 74 |
+
def ftr_inference(self, data, out_dict, batch_size):
|
| 75 |
+
if not data: return out_dict
|
| 76 |
+
texts = [x[1] for x in data]
|
| 77 |
+
preds = self.IndicLID_FTR.predict(texts)
|
| 78 |
+
bert_inputs = []
|
| 79 |
+
for (idx, txt), lbls, scrs in zip(data, preds[0], preds[1]):
|
| 80 |
+
if float(scrs[0]) > self.model_threshold:
|
| 81 |
+
out_dict[idx] = (txt, lbls[0][9:], float(scrs[0]), 'IndicLID-FTR')
|
| 82 |
+
else:
|
| 83 |
+
bert_inputs.append((idx, txt))
|
| 84 |
+
return self.bert_inference(bert_inputs, out_dict, batch_size)
|
| 85 |
+
|
| 86 |
+
def bert_inference(self, data, out_dict, batch_size):
|
| 87 |
+
if not data: return out_dict
|
| 88 |
+
ds = IndicBERT_Data([x[0] for x in data], [x[1] for x in data])
|
| 89 |
+
dl = DataLoader(ds, batch_size=batch_size)
|
| 90 |
+
with torch.no_grad():
|
| 91 |
+
for idxs, texts in dl:
|
| 92 |
+
enc = self.IndicLID_BERT_tokenizer(list(texts), return_tensors="pt", padding=True,
|
| 93 |
+
truncation=True, max_length=512).to(self.device)
|
| 94 |
+
outputs = self.IndicLID_BERT(**enc)
|
| 95 |
+
preds = torch.argmax(outputs.logits, dim=1)
|
| 96 |
+
probs = torch.softmax(outputs.logits, dim=1)
|
| 97 |
+
for i, t, p in zip(idxs, texts, preds):
|
| 98 |
+
label = self.label_map_reverse[p.item()]
|
| 99 |
+
score = probs[i, p].item()
|
| 100 |
+
out_dict[i.item()] = (t, label, score, 'IndicLID-BERT')
|
| 101 |
+
return out_dict
|
| 102 |
+
|
| 103 |
+
def batch_predict(self, texts, batch_size=8):
|
| 104 |
+
native, roman = [], []
|
| 105 |
+
for i, t in enumerate(texts):
|
| 106 |
+
if self.char_percent_check(t) > self.input_threshold:
|
| 107 |
+
roman.append((i, t))
|
| 108 |
+
else:
|
| 109 |
+
native.append((i, t))
|
| 110 |
+
out_dict = {}
|
| 111 |
+
out_dict = self.native_inference(native, out_dict)
|
| 112 |
+
out_dict = self.ftr_inference(roman, out_dict, batch_size)
|
| 113 |
+
return [out_dict[i] for i in sorted(out_dict.keys())]
|
| 114 |
+
|
| 115 |
+
# ------------------------------
|
| 116 |
+
# Run a quick test
|
| 117 |
+
# ------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
if __name__ == "__main__":
|
| 119 |
+
detector = IndicLID()
|
| 120 |
+
samples = [
|
| 121 |
+
"यह एक हिंदी वाक्य है।",
|
| 122 |
+
"ennai pudikkuma?",
|
| 123 |
+
"ఇది ఒక తెలుగు వాక్యం",
|
| 124 |
+
"Hello, how are you?"
|
| 125 |
+
]
|
| 126 |
+
results = detector.batch_predict(samples)
|
| 127 |
+
for text, label, score, model in results:
|
| 128 |
+
print(f"Text: {text}\nPredicted: {label} | Score: {score:.4f} | Model: {model}\n")
|