alakxender commited on
Commit
0def9f2
·
1 Parent(s): 8f97fc5
Files changed (3) hide show
  1. __pycache__/typo_check.cpython-310.pyc +0 -0
  2. app.py +57 -227
  3. typo_check.py +182 -0
__pycache__/typo_check.cpython-310.pyc ADDED
Binary file (5.15 kB). View file
 
app.py CHANGED
@@ -1,243 +1,73 @@
1
- #!/usr/bin/env python
2
- # Gradio app for Dhivehi typo correction
3
-
4
  import gradio as gr
5
- import torch
6
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
7
-
8
- # Load the fine-tuned model and tokenizer
9
- MODEL_PATH = "alakxender/dhivehi-quick-spell-check-t5" # Change this to your model path if different
10
-
11
- # Function to load model and tokenizer
12
- def load_model():
13
- print("Loading model and tokenizer...")
14
- try:
15
- tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
16
- if tokenizer.pad_token is None:
17
- tokenizer.pad_token = tokenizer.eos_token
18
-
19
- model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_PATH)
20
-
21
- # Move model to GPU if available
22
- device = "cuda" if torch.cuda.is_available() else "cpu"
23
- model = model.to(device)
24
-
25
- print(f"Model loaded successfully on {device}")
26
- return model, tokenizer, device
27
- except Exception as e:
28
- print(f"Error loading model: {e}")
29
- return None, None, None
30
-
31
- # Function to correct typos (reverted to single output)
32
- def correct_typo(text, model, tokenizer, device):
33
- if not text.strip():
34
- return "Please enter some text."
35
-
36
- try:
37
- # Prepare input with prefix
38
- input_text = "fix: " + text
39
-
40
- # Tokenize input
41
- inputs = tokenizer(input_text, return_tensors="pt", max_length=128, truncation=True)
42
- inputs = inputs.to(device)
43
-
44
- # Generate output
45
- with torch.no_grad():
46
- outputs = model.generate(
47
- input_ids=inputs["input_ids"],
48
- attention_mask=inputs.get("attention_mask", None),
49
- max_length=128,
50
- num_beams=4,
51
- early_stopping=True
52
- )
53
-
54
- # Decode the output
55
- corrected_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
56
-
57
- return corrected_text
58
- except Exception as e:
59
- return f"Error: {str(e)}"
60
-
61
- # Initialize model and tokenizer
62
- model, tokenizer, device = load_model()
63
-
64
- if model is None:
65
- print("Failed to load model. Please check your model and tokenizer paths.")
66
-
67
- # Function to highlight differences between original and corrected text
68
- def highlight_differences(original, corrected):
69
- import difflib
70
-
71
- d = difflib.Differ()
72
- orig_words = original.split()
73
- corr_words = corrected.split()
74
-
75
- diff = list(d.compare(orig_words, corr_words))
76
-
77
- html_parts = []
78
- i = 0
79
- while i < len(diff):
80
- if diff[i].startswith(' '): # Unchanged
81
- html_parts.append(f'<span>{diff[i][2:]}</span>')
82
- elif diff[i].startswith('- '): # Removed
83
- if i + 1 < len(diff) and diff[i + 1].startswith('+ '):
84
- # Changed word - show correction
85
- old_word = diff[i][2:]
86
- new_word = diff[i + 1][2:]
87
- html_parts.append(f'<span style="background-color: #fff3cd">{old_word}</span>→<span style="background-color: #d4edda">{new_word}</span>')
88
- i += 1
89
- else:
90
- # Removed word
91
- html_parts.append(f'<span style="background-color: #f8d7da">{diff[i][2:]}</span>')
92
- elif diff[i].startswith('+ '): # Added
93
- html_parts.append(f'<span style="background-color: #d4edda">{diff[i][2:]}</span>')
94
- i += 1
95
-
96
- return f'<div class="dhivehi-diff">{" ".join(html_parts)}</div>'
97
-
98
- # Function to process the input for Gradio
99
- def process_input(text):
100
- if model is None:
101
- return "Model not loaded. Please check your model and tokenizer paths.", ""
102
-
103
- corrected = correct_typo(text, model, tokenizer, device)
104
- highlighted = highlight_differences(text, corrected)
105
- return corrected, highlighted
106
 
107
- # Define CSS for Dhivehi font styling
108
- css = """
109
- .textbox1 textarea {
110
- font-size: 18px !important;
111
- font-family: 'MV_Faseyha', 'Faruma', 'A_Faruma' !important;
112
- line-height: 1.8 !important;
113
- direction: rtl !important;
114
- }
115
-
116
- .dhivehi-text {
117
- font-size: 18px !important;
118
- font-family: 'MV_Faseyha', 'Faruma', 'A_Faruma' !important;
119
- line-height: 1.8 !important;
120
- direction: rtl !important;
121
- text-align: right !important;
122
- padding: 10px !important;
123
- background: transparent !important; /* Make background transparent */
124
- border-radius: 4px !important;
125
- color: #ffffff !important; /* White text for dark background */
126
- }
127
-
128
- /* Style for the highlighted differences */
129
- .dhivehi-diff {
130
- font-size: 18px !important;
131
- font-family: 'MV_Faseyha', 'Faruma', 'A_Faruma' !important;
132
- line-height: 1.8 !important;
133
- direction: rtl !important;
134
- text-align: right !important;
135
- padding: 15px !important;
136
- background: transparent !important; /* Make background transparent */
137
- border: 1px solid rgba(255, 255, 255, 0.1) !important; /* Subtle border */
138
- border-radius: 4px !important;
139
- margin-top: 10px !important;
140
- color: #ffffff !important; /* White text for dark background */
141
- }
142
-
143
- /* Ensure the highlighted spans have good contrast */
144
- .dhivehi-diff span {
145
- padding: 2px 5px !important;
146
- border-radius: 3px !important;
147
- margin: 0 2px !important;
148
- }
149
-
150
- /* Original text (yellow background) */
151
- .dhivehi-diff span[style*="background-color: #fff3cd"] {
152
- background-color: rgba(255, 243, 205, 0.2) !important;
153
- color: #ffd700 !important; /* Golden yellow for visibility */
154
- border: 1px solid rgba(255, 243, 205, 0.3) !important;
155
- }
156
-
157
- /* Corrected text (green background) */
158
- .dhivehi-diff span[style*="background-color: #d4edda"] {
159
- background-color: rgba(212, 237, 218, 0.2) !important;
160
- color: #98ff98 !important; /* Light green for visibility */
161
- border: 1px solid rgba(212, 237, 218, 0.3) !important;
162
- }
163
-
164
- /* Removed text (red background) */
165
- .dhivehi-diff span[style*="background-color: #f8d7da"] {
166
- background-color: rgba(248, 215, 218, 0.2) !important;
167
- color: #ff6b6b !important; /* Light red for visibility */
168
- border: 1px solid rgba(248, 215, 218, 0.3) !important;
169
- }
170
-
171
- /* Arrow color */
172
- .dhivehi-diff span:contains('→') {
173
- color: #ffffff !important;
174
- }
175
- """
176
 
177
  # Create Gradio interface using the latest syntax
178
  with gr.Blocks(theme=gr.themes.Default(), css=css) as demo:
179
- gr.Markdown("# <center>Dhivehi Typo Correction</center>")
180
- gr.Markdown("This app uses a fine-tuned T5 model to correct typos in Dhivehi text. Enter text with typos and the model will attempt to fix them.")
181
-
182
- with gr.Row():
183
- input_text = gr.Textbox(
184
- lines=5,
185
- placeholder="ދިވެހި ބަހުން ލިޔުމެއް މިތާ ލިޔެބަލާ",
186
- label="Input Text",
187
- rtl=True,
188
- elem_classes="textbox1"
189
- )
190
-
191
- with gr.Row():
192
- corrected_text = gr.Textbox(
193
- lines=3,
194
- label="Corrected Text",
195
- rtl=True,
196
- elem_classes="textbox1"
197
- )
198
-
199
- with gr.Row():
200
- highlighted_diff = gr.HTML(
201
- label="Changes Highlighted",
202
- elem_classes="dhivehi-text"
203
- )
204
-
205
- submit_btn = gr.Button("ރަނގަޅު ކުރާ") # "Correct" in Dhivehi
206
- submit_btn.click(
207
- fn=process_input,
208
- inputs=input_text,
209
- outputs=[corrected_text, highlighted_diff]
210
- )
211
-
212
- gr.Examples(
213
- examples=[
214
- ["މައި ނޭމް އިސް އަހްމދް"], # My name is Ahmed (with typos)
215
- ["ވަރަށ ރައްގޅޭ ދއުވސް"], # Very good day (with typos)
216
- ["މިއަދ ސްކޫލަށް ދިއުމަށްޓަކައި ހެނދުނ ވަރށް އަވަހށް ތެދުވިން"], # I woke up early today to go to school (with typos)
217
- ["ރާއްޖެއަކީ ވަރށް ރީތި ގުދުރަތީ މަންޒަރުތައް ހުރި ގައުމެކެވެ"], # Maldives is a country with beautiful natural scenery (with typos)
218
- ["ދިވެހި ބަހަކީ އަޅުގަނޑުމެންގެ މާދަރި ބަހެވ އަދި އެބަސް ދިރުވައި އާލާކުރން ޖެހެއވެ"], # Dhivehi is our mother tongue and we need to preserve it (with typos)
219
- ["ކުޅިވަރަކީ ހަށިގަނޑގެ ދުޅަހެޔޮ ކަމަށް ވަރށް މުހިންމު ކަމެކެވެ"], # Sports are very important for physical health (with typos)
220
- ],
221
- inputs=input_text,
222
- )
 
 
223
 
224
- gr.Markdown("""# Dhivehi Typo Correction App
225
 
226
- This application uses a fine-tuned T5 model specifically designed to correct common typos in Dhivehi text. The model focuses on:
227
 
228
- - Fixing common mistakes in diacritics
229
- - Correcting missing Dhivehi letters
230
- - Addressing typical typing errors
231
 
232
- ## What it can fix
233
 
234
- The model works best with common typing mistakes. For example, if you type "ދިވެހ ބަސް" (missing a diacritic), the model will correct it properly.
235
 
236
- ## Limitations
237
 
238
- The model is trained only on common errors and may not fix more complex or unusual mistakes. For instance, if you type "ދިވެހިދަ ބަސް" (with an incorrect vowel mark rather than a missing one), the correction might not work as expected.
239
 
240
- Simply enter your Dhivehi text with typos, and the model will attempt to correct the common errors while preserving the meaning of your text.""")
241
 
242
  # Launch the app
243
  if __name__ == "__main__":
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ from typo_check import css, process_input
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  # Create Gradio interface using the latest syntax
6
  with gr.Blocks(theme=gr.themes.Default(), css=css) as demo:
7
+ with gr.Tabs():
8
+ with gr.Tab("Typo Correction"):
9
+ gr.Markdown("# <center>Dhivehi Typo Correction</center>")
10
+ gr.Markdown("This app uses a fine-tuned T5 model to correct typos in Dhivehi text. Enter text with typos and the model will attempt to fix them.")
11
+
12
+ with gr.Row():
13
+ input_text = gr.Textbox(
14
+ lines=1,
15
+ placeholder="ދިވެހި ބަހުން ލިޔުމެއް މިތާ ލިޔެބަލާ",
16
+ label="Input Text",
17
+ rtl=True,
18
+ elem_classes="textbox1"
19
+ )
20
+
21
+ with gr.Row():
22
+ corrected_text = gr.Textbox(
23
+ lines=1,
24
+ label="Corrected Text",
25
+ rtl=True,
26
+ elem_classes="textbox1"
27
+ )
28
+
29
+ with gr.Row():
30
+ highlighted_diff = gr.HTML(
31
+ label="Changes Highlighted",
32
+ elem_classes="dhivehi-text"
33
+ )
34
+
35
+ submit_btn = gr.Button("ރަނގަޅު ކޮށްލުމަށް",elem_classes="textbox1") # "Correct" in Dhivehi
36
+ submit_btn.click(
37
+ fn=process_input,
38
+ inputs=input_text,
39
+ outputs=[corrected_text, highlighted_diff]
40
+ )
41
+
42
+ gr.Examples(
43
+ examples=[
44
+ ["މައި ނޭމް އިސް އަހްމދް"], # My name is Ahmed (with typos)
45
+ ["ވަރަށ ��ައްގޅޭ ދއުވސް"], # Very good day (with typos)
46
+ ["މިއަދ ސްކޫލަށް ދިއުމަށްޓަކައި ހެނދުނ ވަރށް އަވަހށް ތެދުވިން"], # I woke up early today to go to school (with typos)
47
+ ["ރާއްޖެއަކީ ވަރށް ރީތި ގުދުރަތީ މަންޒަރުތައް ހުރި ގައުމެކެވެ"], # Maldives is a country with beautiful natural scenery (with typos)
48
+ ["ދިވެހި ބަހަކީ އަޅުގަނޑުމެންގެ މާދަރި ބަހެވ އަދި އެބަސް ދިރުވައި އާލާކުރން ޖެހެއވެ"], # Dhivehi is our mother tongue and we need to preserve it (with typos)
49
+ ["ކުޅިވަރަކީ ހަށިގަނޑގެ ދުޅަހެޔޮ ކަމަށް ވަރށް މުހިންމު ކަމެކެވެ"], # Sports are very important for physical health (with typos)
50
+ ],
51
+ inputs=input_text,
52
+ )
53
 
54
+ gr.Markdown("""## Note:
55
 
56
+ This application uses a fine-tuned T5 model specifically designed to correct common typos in Dhivehi text. The model focuses on:
57
 
58
+ - Fixing common mistakes in diacritics
59
+ - Correcting missing Dhivehi letters
60
+ - Addressing typical typing errors
61
 
62
+ ### What it can fix
63
 
64
+ The model works best with common typing mistakes. For example, if you type "ދިވެހ ބަސް" (missing a diacritic), the model will correct it properly.
65
 
66
+ ### Limitations
67
 
68
+ The model is trained only on common errors and may not fix more complex or unusual mistakes. For instance, if you type "ދިވެހިދަ ބަސް" (with an incorrect vowel mark rather than a missing one), the correction might not work as expected.
69
 
70
+ Simply enter your Dhivehi text with typos, and the model will attempt to correct the common errors while preserving the meaning of your text.""")
71
 
72
  # Launch the app
73
  if __name__ == "__main__":
typo_check.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Gradio app for Dhivehi typo correction
3
+
4
+ import difflib
5
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
6
+ import torch
7
+ import gradio as gr
8
+
9
+ # Load the fine-tuned model and tokenizer
10
+ MODEL_PATH = "alakxender/dhivehi-quick-spell-check-t5" # Change this to your model path if different
11
+
12
+ # Function to load model and tokenizer
13
+ def load_model():
14
+ print("Loading model and tokenizer...")
15
+ try:
16
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
17
+ if tokenizer.pad_token is None:
18
+ tokenizer.pad_token = tokenizer.eos_token
19
+
20
+ model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_PATH)
21
+
22
+ # Move model to GPU if available
23
+ device = "cuda" if torch.cuda.is_available() else "cpu"
24
+ model = model.to(device)
25
+
26
+ print(f"Model loaded successfully on {device}")
27
+ return model, tokenizer, device
28
+ except Exception as e:
29
+ print(f"Error loading model: {e}")
30
+ return None, None, None
31
+
32
+ # Function to correct typos (reverted to single output)
33
+ def correct_typo(text, model, tokenizer, device):
34
+ if not text.strip():
35
+ #return "Please enter some text."
36
+ raise gr.Error("Please enter some text💥!", duration=5)
37
+
38
+
39
+ if len(text.strip()) > 200:
40
+ #return "Shorter the better."
41
+ raise gr.Error("Shorter the better💥!", duration=5)
42
+
43
+
44
+ try:
45
+ # Prepare input with prefix
46
+ input_text = "fix: " + text
47
+
48
+ # Tokenize input
49
+ inputs = tokenizer(input_text, return_tensors="pt", max_length=128, truncation=True)
50
+ inputs = inputs.to(device)
51
+
52
+ # Generate output
53
+ with torch.no_grad():
54
+ outputs = model.generate(
55
+ input_ids=inputs["input_ids"],
56
+ attention_mask=inputs.get("attention_mask", None),
57
+ max_length=128,
58
+ num_beams=4,
59
+ early_stopping=True
60
+ )
61
+
62
+ # Decode the output
63
+ corrected_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
64
+
65
+ return corrected_text
66
+ except Exception as e:
67
+ return f"Error: {str(e)}"
68
+
69
+ # Initialize model and tokenizer
70
+ model, tokenizer, device = load_model()
71
+
72
+ if model is None:
73
+ print("Failed to load model. Please check your model and tokenizer paths.")
74
+
75
+ # Function to highlight differences between original and corrected text
76
+ def highlight_differences(original, corrected):
77
+
78
+ d = difflib.Differ()
79
+ orig_words = original.split()
80
+ corr_words = corrected.split()
81
+
82
+ diff = list(d.compare(orig_words, corr_words))
83
+
84
+ html_parts = []
85
+ i = 0
86
+ while i < len(diff):
87
+ if diff[i].startswith(' '): # Unchanged
88
+ html_parts.append(f'<span>{diff[i][2:]}</span>')
89
+ elif diff[i].startswith('- '): # Removed
90
+ if i + 1 < len(diff) and diff[i + 1].startswith('+ '):
91
+ # Changed word - show correction
92
+ old_word = diff[i][2:]
93
+ new_word = diff[i + 1][2:]
94
+ html_parts.append(f'<span style="background-color: #fff3cd">{old_word}</span>→<span style="background-color: #d4edda">{new_word}</span>')
95
+ i += 1
96
+ else:
97
+ # Removed word
98
+ html_parts.append(f'<span style="background-color: #f8d7da">{diff[i][2:]}</span>')
99
+ elif diff[i].startswith('+ '): # Added
100
+ html_parts.append(f'<span style="background-color: #d4edda">{diff[i][2:]}</span>')
101
+ i += 1
102
+
103
+ return f'<div class="dhivehi-diff">{" ".join(html_parts)}</div>'
104
+
105
+ # Function to process the input for Gradio
106
+ def process_input(text):
107
+ if model is None:
108
+ load_model()
109
+
110
+ corrected = correct_typo(text, model, tokenizer, device)
111
+ highlighted = highlight_differences(text, corrected)
112
+ return corrected, highlighted
113
+
114
+ # Define CSS for Dhivehi font styling
115
+ css = """
116
+ .textbox1 textarea {
117
+ font-size: 18px !important;
118
+ font-family: 'MV_Faseyha', 'Faruma', 'A_Faruma' !important;
119
+ line-height: 1.8 !important;
120
+ direction: rtl !important;
121
+ }
122
+
123
+ .dhivehi-text {
124
+ font-size: 18px !important;
125
+ font-family: 'MV_Faseyha', 'Faruma', 'A_Faruma' !important;
126
+ line-height: 1.8 !important;
127
+ direction: rtl !important;
128
+ text-align: right !important;
129
+ padding: 10px !important;
130
+ background: transparent !important; /* Make background transparent */
131
+ border-radius: 4px !important;
132
+ color: #ffffff !important; /* White text for dark background */
133
+ }
134
+
135
+ /* Style for the highlighted differences */
136
+ .dhivehi-diff {
137
+ font-size: 18px !important;
138
+ font-family: 'MV_Faseyha', 'Faruma', 'A_Faruma' !important;
139
+ line-height: 1.8 !important;
140
+ direction: rtl !important;
141
+ text-align: right !important;
142
+ padding: 15px !important;
143
+ background: transparent !important; /* Make background transparent */
144
+ border: 1px solid rgba(255, 255, 255, 0.1) !important; /* Subtle border */
145
+ border-radius: 4px !important;
146
+ margin-top: 10px !important;
147
+ color: #ffffff !important; /* White text for dark background */
148
+ }
149
+
150
+ /* Ensure the highlighted spans have good contrast */
151
+ .dhivehi-diff span {
152
+ padding: 2px 5px !important;
153
+ border-radius: 3px !important;
154
+ margin: 0 2px !important;
155
+ }
156
+
157
+ /* Original text (yellow background) */
158
+ .dhivehi-diff span[style*="background-color: #fff3cd"] {
159
+ background-color: rgba(255, 243, 205, 0.2) !important;
160
+ color: #ffd700 !important; /* Golden yellow for visibility */
161
+ border: 1px solid rgba(255, 243, 205, 0.3) !important;
162
+ }
163
+
164
+ /* Corrected text (green background) */
165
+ .dhivehi-diff span[style*="background-color: #d4edda"] {
166
+ background-color: rgba(212, 237, 218, 0.2) !important;
167
+ color: #98ff98 !important; /* Light green for visibility */
168
+ border: 1px solid rgba(212, 237, 218, 0.3) !important;
169
+ }
170
+
171
+ /* Removed text (red background) */
172
+ .dhivehi-diff span[style*="background-color: #f8d7da"] {
173
+ background-color: rgba(248, 215, 218, 0.2) !important;
174
+ color: #ff6b6b !important; /* Light red for visibility */
175
+ border: 1px solid rgba(248, 215, 218, 0.3) !important;
176
+ }
177
+
178
+ /* Arrow color */
179
+ .dhivehi-diff span:contains('→') {
180
+ color: #ffffff !important;
181
+ }
182
+ """