kasimali
commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import gradio as gr
|
| 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 required models
|
| 12 |
+
# ----------------------------
|
| 13 |
+
print("Downloading IndicLID models...")
|
| 14 |
+
FTN_PATH = hf_hub_download("ai4bharat/IndicLID-FTN", filename="model_baseline_roman.bin")
|
| 15 |
+
FTR_PATH = hf_hub_download("ai4bharat/IndicLID-FTR", filename="model_baseline_roman.bin")
|
| 16 |
+
BERT_PATH = hf_hub_download("ai4bharat/IndicLID-BERT", filename="basline_nn_simple.pt")
|
| 17 |
+
print("Download complete.")
|
| 18 |
+
|
| 19 |
+
# ----------------------------
|
| 20 |
+
# Data helper for BERT batching
|
| 21 |
+
# ----------------------------
|
| 22 |
+
class IndicBERT_Data(Dataset):
|
| 23 |
+
def __init__(self, indices, X):
|
| 24 |
+
self.x = list(X)
|
| 25 |
+
self.i = list(indices)
|
| 26 |
+
def __len__(self):
|
| 27 |
+
return len(self.x)
|
| 28 |
+
def __getitem__(self, idx):
|
| 29 |
+
return self.i[idx], self.x[idx]
|
| 30 |
+
|
| 31 |
+
# ----------------------------
|
| 32 |
+
# IndicLID Class
|
| 33 |
+
# ----------------------------
|
| 34 |
+
class IndicLID:
|
| 35 |
+
def __init__(self, input_threshold=0.5, roman_lid_threshold=0.6):
|
| 36 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 37 |
+
self.FTN = fasttext.load_model(FTN_PATH)
|
| 38 |
+
self.FTR = fasttext.load_model(FTR_PATH)
|
| 39 |
+
self.BERT = torch.load(BERT_PATH, map_location=self.device)
|
| 40 |
+
self.BERT.eval()
|
| 41 |
+
self.tokenizer = AutoTokenizer.from_pretrained("ai4bharat/IndicBERTv2-MLM-only")
|
| 42 |
+
self.input_threshold = input_threshold
|
| 43 |
+
self.model_threshold = roman_lid_threshold
|
| 44 |
+
|
| 45 |
+
# Official label map
|
| 46 |
+
self.label_map_reverse = {
|
| 47 |
+
0:'asm_Latn',1:'ben_Latn',2:'brx_Latn',3:'guj_Latn',4:'hin_Latn',
|
| 48 |
+
5:'kan_Latn',6:'kas_Latn',7:'kok_Latn',8:'mai_Latn',9:'mal_Latn',
|
| 49 |
+
10:'mni_Latn',11:'mar_Latn',12:'nep_Latn',13:'ori_Latn',14:'pan_Latn',
|
| 50 |
+
15:'san_Latn',16:'snd_Latn',17:'tam_Latn',18:'tel_Latn',19:'urd_Latn',
|
| 51 |
+
20:'eng_Latn',21:'other',22:'asm_Beng',23:'ben_Beng',24:'brx_Deva',
|
| 52 |
+
25:'doi_Deva',26:'guj_Gujr',27:'hin_Deva',28:'kan_Knda',29:'kas_Arab',
|
| 53 |
+
30:'kas_Deva',31:'kok_Deva',32:'mai_Deva',33:'mal_Mlym',34:'mni_Beng',
|
| 54 |
+
35:'mni_Meti',36:'mar_Deva',37:'nep_Deva',38:'ori_Orya',39:'pan_Guru',
|
| 55 |
+
40:'san_Deva',41:'sat_Olch',42:'snd_Arab',43:'tam_Tamil',44:'tel_Telu',
|
| 56 |
+
45:'urd_Arab'
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
def char_percent_check(self, text):
|
| 60 |
+
total_chars = sum(c.isalpha() for c in text)
|
| 61 |
+
roman_chars = sum(bool(re.match(r"[A-Za-z]", c)) for c in text)
|
| 62 |
+
return roman_chars / total_chars if total_chars else 0
|
| 63 |
+
|
| 64 |
+
def native_inference(self, data, out_dict):
|
| 65 |
+
if not data: return out_dict
|
| 66 |
+
texts = [x[1] for x in data]
|
| 67 |
+
preds = self.FTN.predict(texts)
|
| 68 |
+
for (idx, txt), lbls, scrs in zip(data, preds[0], preds[1]):
|
| 69 |
+
out_dict[idx] = {"text": txt, "label": lbls[0][9:], "score": float(scrs[0]), "model": "FTN"}
|
| 70 |
+
return out_dict
|
| 71 |
+
|
| 72 |
+
def ftr_inference(self, data, out_dict, batch_size):
|
| 73 |
+
if not data: return out_dict
|
| 74 |
+
texts = [x[1] for x in data]
|
| 75 |
+
preds = self.FTR.predict(texts)
|
| 76 |
+
bert_inputs = []
|
| 77 |
+
for (idx, txt), lbls, scrs in zip(data, preds[0], preds[1]):
|
| 78 |
+
if float(scrs[0]) > self.model_threshold:
|
| 79 |
+
out_dict[idx] = {"text": txt, "label": lbls[0][9:], "score": float(scrs[0]), "model": "FTR"}
|
| 80 |
+
else:
|
| 81 |
+
bert_inputs.append((idx, txt))
|
| 82 |
+
return self.bert_inference(bert_inputs, out_dict, batch_size)
|
| 83 |
+
|
| 84 |
+
def bert_inference(self, data, out_dict, batch_size):
|
| 85 |
+
if not data: return out_dict
|
| 86 |
+
ds = IndicBERT_Data([x[0] for x in data], [x[1] for x in data])
|
| 87 |
+
dl = DataLoader(ds, batch_size=batch_size)
|
| 88 |
+
with torch.no_grad():
|
| 89 |
+
for idxs, texts in dl:
|
| 90 |
+
enc = self.tokenizer(list(texts), return_tensors="pt", padding=True,
|
| 91 |
+
truncation=True, max_length=512).to(self.device)
|
| 92 |
+
outputs = self.BERT(**enc)
|
| 93 |
+
preds = torch.argmax(outputs.logits, dim=1)
|
| 94 |
+
probs = torch.softmax(outputs.logits, dim=1)
|
| 95 |
+
for batch_i, p in enumerate(preds):
|
| 96 |
+
i = idxs[batch_i].item()
|
| 97 |
+
label_idx = p.item()
|
| 98 |
+
out_dict[i] = {
|
| 99 |
+
"text": texts[batch_i],
|
| 100 |
+
"label": self.label_map_reverse[label_idx],
|
| 101 |
+
"score": probs[batch_i, label_idx].item(),
|
| 102 |
+
"model": "BERT"
|
| 103 |
+
}
|
| 104 |
+
return out_dict
|
| 105 |
+
|
| 106 |
+
def batch_predict(self, texts, batch_size=8):
|
| 107 |
+
native, roman = [], []
|
| 108 |
+
for i, t in enumerate(texts):
|
| 109 |
+
if self.char_percent_check(t) > self.input_threshold:
|
| 110 |
+
roman.append((i, t))
|
| 111 |
+
else:
|
| 112 |
+
native.append((i, t))
|
| 113 |
+
out_dict = {}
|
| 114 |
+
out_dict = self.native_inference(native, out_dict)
|
| 115 |
+
out_dict = self.ftr_inference(roman, out_dict, batch_size)
|
| 116 |
+
return [out_dict[i] for i in sorted(out_dict.keys())]
|
| 117 |
+
|
| 118 |
+
# ----------------------------
|
| 119 |
+
# Gradio UI
|
| 120 |
+
# ----------------------------
|
| 121 |
+
lid_model = IndicLID()
|
| 122 |
+
|
| 123 |
+
def detect(text_block):
|
| 124 |
+
lines = [l.strip() for l in text_block.splitlines() if l.strip()]
|
| 125 |
+
if not lines:
|
| 126 |
+
return []
|
| 127 |
+
return lid_model.batch_predict(lines)
|
| 128 |
+
|
| 129 |
+
with gr.Blocks(title="IndicLID by AI4Bharat") as demo:
|
| 130 |
+
gr.Markdown("## IndicLID (AI4Bharat) — Full Ensemble\nDetects Indian languages in native & roman scripts.")
|
| 131 |
+
inp = gr.Textbox(lines=8, label="Enter one sentence per line")
|
| 132 |
+
out = gr.JSON(label="Predictions")
|
| 133 |
+
btn = gr.Button("Detect Language")
|
| 134 |
+
btn.click(fn=detect, inputs=inp, outputs=out)
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
demo.launch()
|