Emirhan Gazi commited on
Commit
d83a8df
1 Parent(s): 1efd675

Add application file

Browse files
Files changed (1) hide show
  1. app.py +139 -0
app.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ from transformers import (
4
+ AutoTokenizer,
5
+ AutoModelForSeq2SeqLM,
6
+ AutoModelForTokenClassification,
7
+ pipeline)
8
+ from transformers import Pipeline
9
+ import re
10
+
11
+ model = AutoModelForSeq2SeqLM.from_pretrained("emirhangazi77/Turkish-T5")
12
+ tokenizer = AutoTokenizer.from_pretrained("emirhangazi77/Turkish-T5")
13
+ ner_model = AutoModelForTokenClassification.from_pretrained("akdeniz27/bert-base-turkish-cased-ner") # pretrained ner model
14
+ ner_tokenizer = AutoTokenizer.from_pretrained("akdeniz27/bert-base-turkish-cased-ner") # pretrained ner tokenizer
15
+ ner = pipeline('ner', model=ner_model, tokenizer=ner_tokenizer, aggregation_strategy="first") #
16
+
17
+
18
+
19
+ device = torch.device('cpu')
20
+
21
+ class Diacritic_Pipe(Pipeline):
22
+
23
+ def __init__(self,ner,model,tokenizer):
24
+ super().__init__(model = model, tokenizer = tokenizer)
25
+ self.ner_pipe = ner
26
+
27
+ def generate_result(self,text):
28
+ prefix = "Correct diacritics for : "
29
+ postfix = " </s>"
30
+ text = prefix + text + postfix
31
+
32
+ self.tokenizer.truncation_side = "left"
33
+ batch = self.tokenizer(text, return_tensors='pt', max_length = 64, truncation = False).to(device)
34
+ result = self.model.generate(**batch, max_new_tokens = 128)
35
+ result = self.tokenizer.batch_decode(result)
36
+
37
+ return str(result[0])
38
+ def ner_predict_mapping(self,text, threshold=0.3):
39
+ result = self.ner_pipe(text)
40
+ if len(result) == 0:
41
+ return []
42
+ else:
43
+ special_words = [result["word"] for result in result if result["score"] > threshold]
44
+ special_words_ = []
45
+ for word_ in special_words:
46
+ if word_.lower()[0] == "i":
47
+ word_ = word_.replace("I","İ")
48
+ if len(word_.split()) > 1:
49
+ special_words_.extend(word_.split())
50
+ else:
51
+ special_words_.append(word_)
52
+
53
+ return special_words_
54
+
55
+ def split_text_into_n_worded_chunks(self,text, n):
56
+ words = text.split()
57
+ chunks = []
58
+ for i in range(0, len(words), n):
59
+ chunks.append(' '.join(words[i:i+n]))
60
+ last_chunk_words = len(words) % n
61
+ if last_chunk_words != 0:
62
+ chunks[-1] = ' '.join(words[-last_chunk_words:])
63
+ return chunks
64
+
65
+ def chunk_2(self,text):
66
+ chunks = self.split_text_into_n_worded_chunks(text, 2)
67
+ processed_chunks = [re.sub(r'(["q(°\[\]{}&´])\s+', r'\1',self.generate_result(chunk)) for chunk in chunks]
68
+ result = ' '.join(processed_chunks)
69
+ return result.replace("<pad>","").replace("</s>","").replace(" "," ")
70
+
71
+ def chunk_1(self,text):
72
+ chunks = self.split_text_into_n_worded_chunks(text, 1)
73
+ processed_chunks = [self.generate_result(chunk).replace(" ","") for chunk in chunks]
74
+ result = ''.join(processed_chunks)
75
+ return result.replace("<pad>"," ").replace("</s>","")
76
+
77
+ def process_text(self,text):
78
+ words = self.ner_predict_mapping(text)
79
+ two_chunk = self.chunk_2(text)
80
+ one_chunk = self.chunk_1(text)
81
+ if len(one_chunk.split()) != len(two_chunk.split()):
82
+ for word in words:
83
+ one_chunk = one_chunk.replace(word.lower().replace('i̇',"i"),word)
84
+ return one_chunk
85
+ else:
86
+ for word in words:
87
+ two_chunk = two_chunk.replace(word.lower().replace('i̇',"i"),word)
88
+ return two_chunk
89
+
90
+ def _sanitize_parameters(self, **kwargs):
91
+ preprocess_kwargs = {}
92
+ if "maybe_arg" in kwargs:
93
+ preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"]
94
+ return preprocess_kwargs, {}, {}
95
+
96
+ def preprocess(self, inputs, maybe_arg=2):
97
+ return {"model_input": inputs}
98
+
99
+ def _forward(self, model_inputs):
100
+ #model_inputs == {"model_input": model_input}
101
+ outputs = self.process_text(model_inputs["model_input"])
102
+ # Maybe {"logits": Tensor(...)}
103
+ return outputs
104
+
105
+ def postprocess(self, model_outputs):
106
+ return model_outputs
107
+
108
+ import gradio as gr
109
+
110
+ diacritics = Diacritic_Pipe(ner = ner , model = model , tokenizer = tokenizer)
111
+
112
+ def fn(query):
113
+ response = diacritics(query)
114
+ return str(response)
115
+
116
+ def my_chatbot(input, history):
117
+ history = history or []
118
+ my_history = list(sum(history, ()))
119
+ my_history.append(input)
120
+ my_input = ' '.join(my_history)
121
+ output = fn(input)
122
+ history.append((input, output))
123
+ return history, history
124
+
125
+ import gradio as gr
126
+ import logging
127
+ import sys
128
+
129
+ logging.basicConfig(stream=sys.stdout, level=logging.INFO)
130
+ logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
131
+
132
+ with gr.Blocks() as demo:
133
+ gr.Markdown("""<h1><center>Diacritics on Turkish</center></h1>""")
134
+ chatbot = gr.Chatbot()
135
+ state = gr.State()
136
+ txt = gr.Textbox(show_label=False, placeholder="Ask me a question and press enter.")
137
+ txt.submit(my_chatbot, inputs=[txt, state], outputs=[chatbot, state])
138
+
139
+ demo.launch(share=True)