bashyaldhiraj2067 commited on
Commit
ba5f14a
·
verified ·
1 Parent(s): 8579004

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +71 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoModelForSeq2SeqLM
4
+ from huggingface_hub import InferenceClient
5
+
6
+ # Define tokenizer
7
+ special_tokens = ["<pad>", "<s>", "</s>", "<unk>"]
8
+ nepali_chars = list("अआइईउऊऋॠऌॡऎएऐओऔकखगघङचछजझञटठडढणतथदधनपफबभमयरलवशषसह्ािीुूृॄेैोौंंःँ।०१२३४५६७८९,.;?!़ॅंःॊॅऒऽॉड़ॐ॥ऑऱफ़ढ़")
9
+ char_vocab = special_tokens + nepali_chars
10
+
11
+ char2id = {char: idx for idx, char in enumerate(char_vocab)}
12
+ id2char = {idx: char for char, idx in char2id.items()}
13
+
14
+ class CharTokenizer:
15
+ def __init__(self, char2id, id2char):
16
+ self.char2id = char2id
17
+ self.id2char = id2char
18
+
19
+ def encode(self, text):
20
+ return [self.char2id.get(char, self.char2id["<unk>"]) for char in text]
21
+
22
+ def decode(self, tokens):
23
+ return "".join([self.id2char.get(token, "<unk>") for token in tokens])
24
+
25
+ def decodex(self, tokens):
26
+ decoded_string = ""
27
+ for i, token in enumerate(tokens):
28
+ char = self.id2char.get(token, "<unk>")
29
+ if char == "<unk>":
30
+ if i == 0 or i == len(tokens) - 1 or self.id2char.get(tokens[i - 1], "<unk>") == "<unk>":
31
+ decoded_string += ""
32
+ else:
33
+ decoded_string += " "
34
+ elif char == "<pad>":
35
+ pass
36
+ else:
37
+ decoded_string += char
38
+ return decoded_string
39
+
40
+ # Initialize tokenizer
41
+ tokenizer = CharTokenizer(char2id, id2char)
42
+
43
+ # Load T5 model
44
+ model_name = "bashyaldhiraj2067/t5_char_nepali"
45
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
46
+
47
+ def correct_text(input_text, max_length=256):
48
+ input_ids = tokenizer.encode(input_text)
49
+ input_tensor = torch.tensor([input_ids])
50
+
51
+ with torch.no_grad():
52
+ outputs = model.generate(
53
+ input_tensor,
54
+ max_length=max_length,
55
+ return_dict_in_generate=True
56
+ )
57
+
58
+ generated_tokens = outputs.sequences[0].tolist()
59
+ return tokenizer.decodex(generated_tokens)
60
+
61
+ # Gradio interface
62
+ demo = gr.Interface(
63
+ fn=correct_text,
64
+ inputs=[gr.Textbox(label="Enter Nepali Text"), gr.Slider(50, 256, step=10, label="Max Length")],
65
+ outputs=gr.Textbox(label="Corrected Text"),
66
+ title="Nepali Text Correction",
67
+ description="Enter text with errors and get corrected output using a T5 model trained on Nepali text.",
68
+ )
69
+
70
+ if __name__ == "__main__":
71
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ huggingface_hub==0.25.2
2
+ torch
3
+ transformers