MahtaFetrat commited on
Commit
1a27370
·
1 Parent(s): d79993e

add scripts

Browse files
testing-scripts/test.ipynb ADDED
@@ -0,0 +1,1948 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "ABgLYF9R8viP"
7
+ },
8
+ "source": [
9
+ "# Setup"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {
16
+ "colab": {
17
+ "base_uri": "https://localhost:8080/"
18
+ },
19
+ "id": "Qs-J5B3ykaYz",
20
+ "outputId": "66f79f0c-f2e3-47b0-fc05-f56416962f0c"
21
+ },
22
+ "outputs": [
23
+ {
24
+ "name": "stderr",
25
+ "output_type": "stream",
26
+ "text": [
27
+ "/media/external_10TB/mahta_fetrat/venv/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
28
+ " from .autonotebook import tqdm as notebook_tqdm\n"
29
+ ]
30
+ }
31
+ ],
32
+ "source": [
33
+ "from GE2PE import GE2PE\n",
34
+ "\n",
35
+ "g2p = GE2PE(model_path='GE2PE/phase3-t5/checkpoint-487100', GPU=True)\n"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": 2,
41
+ "metadata": {
42
+ "id": "ymcwy5hG9H5l"
43
+ },
44
+ "outputs": [],
45
+ "source": [
46
+ "import pandas as pd\n",
47
+ "import re\n",
48
+ "from jiwer import cer\n",
49
+ "from difflib import SequenceMatcher"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "markdown",
54
+ "metadata": {
55
+ "id": "EOZGZa2lMfPe"
56
+ },
57
+ "source": [
58
+ "# Setup POSTagger"
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": 3,
64
+ "metadata": {
65
+ "colab": {
66
+ "base_uri": "https://localhost:8080/"
67
+ },
68
+ "id": "8TJZ2DrKMg7F",
69
+ "outputId": "c2597cbc-6d60-40c7-e246-983b9eaf8437"
70
+ },
71
+ "outputs": [],
72
+ "source": [
73
+ "# ! git clone https://huggingface.co/roshan-research/spacy_pos_tagger_parsbertpostagger"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "execution_count": 4,
79
+ "metadata": {
80
+ "id": "pCiJ-VnfMiwj"
81
+ },
82
+ "outputs": [],
83
+ "source": [
84
+ "import spacy\n",
85
+ "# spacy.require_gpu()\n",
86
+ "\"\"\"این ماژول شامل کلاس‌ها و توابعی برای برچسب‌گذاری توکن‌هاست.\"\"\"\n",
87
+ "\n",
88
+ "from nltk.tag import stanford # noqa: I001\n",
89
+ "from hazm import SequenceTagger\n",
90
+ "\n",
91
+ "import os\n",
92
+ "import subprocess\n",
93
+ "\n",
94
+ "from spacy.tokens import Doc\n",
95
+ "from spacy.tokens import DocBin\n",
96
+ "from spacy.vocab import Vocab\n",
97
+ "\n",
98
+ "from sklearn.metrics import classification_report,f1_score,accuracy_score,precision_score,recall_score\n",
99
+ "\n",
100
+ "from tqdm import tqdm\n",
101
+ "\n",
102
+ "\n",
103
+ "punctuation_list = [\n",
104
+ " '\"',\n",
105
+ " \"#\",\n",
106
+ " \"(\",\n",
107
+ " \")\",\n",
108
+ " \"*\",\n",
109
+ " \",\",\n",
110
+ " \"-\",\n",
111
+ " \".\",\n",
112
+ " \"/\",\n",
113
+ " \":\",\n",
114
+ " \"[\",\n",
115
+ " \"]\",\n",
116
+ " \"«\",\n",
117
+ " \"»\",\n",
118
+ " \"،\",\n",
119
+ " \";\",\n",
120
+ " \"?\",\n",
121
+ " \"!\",\n",
122
+ "]\n",
123
+ "\n",
124
+ "\n",
125
+ "class POSTagger(SequenceTagger):\n",
126
+ " \"\"\"این کلاس‌ها شامل توابعی برای برچسب‌گذاری توکن‌هاست.\"\"\"\n",
127
+ "\n",
128
+ " def __init__(\n",
129
+ " self: \"POSTagger\", model=None, data_maker=None, universal_tag=False,\n",
130
+ " ) -> None:\n",
131
+ " data_maker = self.data_maker if data_maker is None else data_maker\n",
132
+ " self.__is_universal = universal_tag\n",
133
+ " super().__init__(model, data_maker)\n",
134
+ "\n",
135
+ " def __universal_converter(self: \"POSTagger\", tagged_list):\n",
136
+ " return [(word, tag.split(\",\")[0]) for word, tag in tagged_list]\n",
137
+ "\n",
138
+ " def __is_punc(self: \"POSTagger\", word):\n",
139
+ " return word in punctuation_list\n",
140
+ "\n",
141
+ " def data_maker(self: \"POSTagger\", tokens):\n",
142
+ " \"\"\"تابعی که لیستی از لیستی از کلمات توکنایز شده را گرفته و لیست دو بعدی از از دیکشنری‌هایی که تعیین‌کننده ویژگی‌ها هر کلمه هستند را برمی‌گرداند.\n",
143
+ "\n",
144
+ " Examples:\n",
145
+ " >>> posTagger = POSTagger(model = 'pos_tagger.model')\n",
146
+ " >>> posTagger.data_maker(tokens = [['دلم', 'اینجا', 'مانده‌است', '.']])\n",
147
+ " [[{'word': 'دلم', 'is_first': True, 'is_last': False, 'prefix-1': 'د', 'prefix-2': 'دل', 'prefix-3': 'دلم', 'suffix-1': 'م', 'suffix-2': 'لم', 'suffix-3': 'دلم', 'prev_word': '', 'two_prev_word': '', 'next_word': 'اینجا', 'two_next_word': 'مانده\\u200cاست', 'is_numeric': False, 'prev_is_numeric': '', 'next_is_numeric': False, 'is_punc': False, 'prev_is_punc': '', 'next_is_punc': False}, {'word': 'اینجا', 'is_first': False, 'is_last': False, 'prefix-1': 'ا', 'prefix-2': 'ای', 'prefix-3': 'این', 'suffix-1': 'ا', 'suffix-2': 'جا', 'suffix-3': 'نجا', 'prev_word': 'دلم', 'two_prev_word': '.', 'next_word': 'مانده\\u200cاست', 'two_next_word': '.', 'is_numeric': False, 'prev_is_numeric': False, 'next_is_numeric': False, 'is_punc': False, 'prev_is_punc': False, 'next_is_punc': False}, {'word': 'مانده\\u200cاست', 'is_first': False, 'is_last': False, 'prefix-1': 'م', 'prefix-2': 'ما', 'prefix-3': 'مان', 'suffix-1': 'ت', 'suffix-2': 'ست', 'suffix-3': 'است', 'prev_word': 'اینجا', 'two_prev_word': 'دلم', 'next_word': '.', 'two_next_word': '', 'is_numeric': False, 'prev_is_numeric': False, 'next_is_numeric': False, 'is_punc': False, 'prev_is_punc': False, 'next_is_punc': True}, {'word': '.', 'is_first': False, 'is_last': True, 'prefix-1': '.', 'prefix-2': '.', 'prefix-3': '.', 'suffix-1': '.', 'suffix-2': '.', 'suffix-3': '.', 'prev_word': 'مانده\\u200cاست', 'two_prev_word': 'اینجا', 'next_word': '', 'two_next_word': '', 'is_numeric': False, 'prev_is_numeric': False, 'next_is_numeric': '', 'is_punc': True, 'prev_is_punc': False, 'next_is_punc': ''}]]\n",
148
+ "\n",
149
+ " Args:\n",
150
+ " tokens (List[List[str]]): جملاتی که نیاز به تبدیل آن به برداری از ویژگی‌ها است.\n",
151
+ "\n",
152
+ " Returns:\n",
153
+ " List(List(Dict())): لیستی از لیستی از دیکشنری‌های بیان‌کننده ویژگی‌های یک کلمه.\n",
154
+ " \"\"\"\n",
155
+ " return [\n",
156
+ " [self.features(token, index) for index in range(len(token))]\n",
157
+ " for token in tokens\n",
158
+ " ]\n",
159
+ "\n",
160
+ " def features(self: \"POSTagger\", sentence, index):\n",
161
+ " \"\"\"features.\"\"\"\n",
162
+ " return {\n",
163
+ " \"word\": sentence[index],\n",
164
+ " \"is_first\": index == 0,\n",
165
+ " \"is_last\": index == len(sentence) - 1,\n",
166
+ " # *ix\n",
167
+ " \"prefix-1\": sentence[index][0],\n",
168
+ " \"prefix-2\": sentence[index][:2],\n",
169
+ " \"prefix-3\": sentence[index][:3],\n",
170
+ " \"suffix-1\": sentence[index][-1],\n",
171
+ " \"suffix-2\": sentence[index][-2:],\n",
172
+ " \"suffix-3\": sentence[index][-3:],\n",
173
+ " # word\n",
174
+ " \"prev_word\": \"\" if index == 0 else sentence[index - 1],\n",
175
+ " \"two_prev_word\": \"\" if index == 0 else sentence[index - 2],\n",
176
+ " \"next_word\": \"\" if index == len(sentence) - 1 else sentence[index + 1],\n",
177
+ " \"two_next_word\": (\n",
178
+ " \"\"\n",
179
+ " if index in {len(sentence) - 1, len(sentence) - 2}\n",
180
+ " else sentence[index + 2]\n",
181
+ " ),\n",
182
+ " # digit\n",
183
+ " \"is_numeric\": sentence[index].isdigit(),\n",
184
+ " \"prev_is_numeric\": \"\" if index == 0 else sentence[index - 1].isdigit(),\n",
185
+ " \"next_is_numeric\": (\n",
186
+ " \"\" if index == len(sentence) - 1 else sentence[index + 1].isdigit()\n",
187
+ " ),\n",
188
+ " # punc\n",
189
+ " \"is_punc\": self.__is_punc(sentence[index]),\n",
190
+ " \"prev_is_punc\": \"\" if index == 0 else self.__is_punc(sentence[index - 1]),\n",
191
+ " \"next_is_punc\": (\n",
192
+ " \"\"\n",
193
+ " if index == len(sentence) - 1\n",
194
+ " else self.__is_punc(sentence[index + 1])\n",
195
+ " ),\n",
196
+ " }\n",
197
+ "\n",
198
+ " def tag(self: \"POSTagger\", tokens):\n",
199
+ " \"\"\"یک جمله را در قالب لیستی از توکن‌ها دریافت می‌کند و در خروجی لیستی از\n",
200
+ " `(توکن، برچسب)`ها برمی‌گرداند.\n",
201
+ "\n",
202
+ " Examples:\n",
203
+ " >>> posTagger = POSTagger(model = 'pos_tagger.model')\n",
204
+ " >>> posTagger.tag(tokens = ['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.'])\n",
205
+ " [('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN,EZ'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]\n",
206
+ "\n",
207
+ " >>> posTagger = POSTagger(model = 'pos_tagger.model', universal_tag = True)\n",
208
+ " >>> posTagger.tag(tokens = ['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.'])\n",
209
+ " [('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]\n",
210
+ "\n",
211
+ " Args:\n",
212
+ " tokens (List[str]): لیستی از توکن‌های یک جمله که باید برچسب‌گذاری شود.\n",
213
+ "\n",
214
+ " Returns:\n",
215
+ " (List[Tuple[str,str]]): ‌لیستی از `(توکن، برچسب)`ها.\n",
216
+ "\n",
217
+ " \"\"\"\n",
218
+ " tagged_token = super().tag(tokens)\n",
219
+ " return (\n",
220
+ " self.__universal_converter(tagged_token)\n",
221
+ " if self.__is_universal\n",
222
+ " else tagged_token\n",
223
+ " )\n",
224
+ "\n",
225
+ " def tag_sents(self: \"POSTagger\", sentences):\n",
226
+ " \"\"\"جملات را در قالب لیستی از توکن‌ها دریافت می‌کند\n",
227
+ " و در خروجی، لیستی از لیستی از `(توکن، برچسب)`ها برمی‌گرداند.\n",
228
+ "\n",
229
+ " هر لیست از `(توکن، برچسب)`ها مربوط به یک جمله است.\n",
230
+ "\n",
231
+ " Examples:\n",
232
+ " >>> posTagger = POSTagger(model = 'pos_tagger.model')\n",
233
+ " >>> posTagger.tag_sents(sentences = [['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.']])\n",
234
+ " [[('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN,EZ'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]]\n",
235
+ "\n",
236
+ " >>> posTagger = POSTagger(model = 'pos_tagger.model', universal_tag = True)\n",
237
+ " >>> posTagger.tag_sents(sentences = [['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.']])\n",
238
+ " [[('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]]\n",
239
+ "\n",
240
+ " Args:\n",
241
+ " sentences (List[List[str]]): لیستی از جملات که باید برچسب‌گذاری شود.\n",
242
+ "\n",
243
+ " Returns:\n",
244
+ " (List[List[Tuple[str,str]]]): لیستی از لیستی از `(توکن، برچسب)`ها.\n",
245
+ " هر لیست از `(توکن،برچسب)`ها مربوط به یک جمله است.\n",
246
+ "\n",
247
+ " \"\"\"\n",
248
+ " tagged_sents = super().tag_sents(sentences)\n",
249
+ " return (\n",
250
+ " [self.__universal_converter(tagged_sent) for tagged_sent in tagged_sents]\n",
251
+ " if self.__is_universal\n",
252
+ " else tagged_sents\n",
253
+ " )\n",
254
+ "\n",
255
+ "\n",
256
+ "class StanfordPOSTagger(stanford.StanfordPOSTagger):\n",
257
+ " \"\"\"StanfordPOSTagger.\"\"\"\n",
258
+ "\n",
259
+ " def __init__(\n",
260
+ " self: \"StanfordPOSTagger\",\n",
261
+ " model_filename: \"str\",\n",
262
+ " path_to_jar: str,\n",
263
+ " *args, # noqa: ANN002\n",
264
+ " **kwargs, # noqa: ANN003\n",
265
+ " ) -> None:\n",
266
+ " self._SEPARATOR = \"/\"\n",
267
+ " super(stanford.StanfordPOSTagger, self).__init__(\n",
268
+ " model_filename=model_filename,\n",
269
+ " path_to_jar=path_to_jar,\n",
270
+ " *args, # noqa: B026\n",
271
+ " **kwargs,\n",
272
+ " )\n",
273
+ "\n",
274
+ " def tag(self: \"StanfordPOSTagger\", tokens):\n",
275
+ " \"\"\"tag.\n",
276
+ "\n",
277
+ " Examples:\n",
278
+ " >>> tagger = StanfordPOSTagger(model_filename='persian.tagger', path_to_jar='stanford_postagger.jar')\n",
279
+ " >>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])\n",
280
+ " [('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]\n",
281
+ "\n",
282
+ " \"\"\"\n",
283
+ " return self.tag_sents([tokens])[0]\n",
284
+ "\n",
285
+ " def tag_sents(self: \"StanfordPOSTagger\", sentences):\n",
286
+ " \"\"\"tag_sents.\"\"\"\n",
287
+ " refined = ([w.replace(\" \", \"_\") for w in s] for s in sentences)\n",
288
+ " return super(stanford.StanfordPOSTagger, self).tag_sents(refined)\n",
289
+ "\n",
290
+ "\n",
291
+ "class SpacyPOSTagger(POSTagger):\n",
292
+ " def __init__(\n",
293
+ " self: \"SpacyPOSTagger\",\n",
294
+ " model_path=None,\n",
295
+ " using_gpu=False,\n",
296
+ " gpu_id=0\n",
297
+ " ):\n",
298
+ " \"\"\"\n",
299
+ " Initialize the SpacyPOSTagger with a model and data paths.\n",
300
+ "\n",
301
+ " Args:\n",
302
+ " - model_path: Path to a pre-trained spaCy model.\n",
303
+ " - test_dataset: Test dataset for evaluation. It has a similar structure to the training dataset.\n",
304
+ " - test_directory: Directory to save the test data in spaCy format.\n",
305
+ " - using_gpu: Set to True if you want use gpu (if you dont have one and set this to True the function use cpu automatically)\n",
306
+ " This constructor calls the constructor of the parent class POSTagger.\n",
307
+ " \"\"\"\n",
308
+ " super().__init__(universal_tag=True)\n",
309
+ " self.model_path = model_path #### Usually an output directory for spacy model contain two other directory name model-last , model-best,You should give model_path like this : output/model-last\n",
310
+ " self.using_gpu = using_gpu\n",
311
+ " self.gpu_id = gpu_id\n",
312
+ " self.tagger = None\n",
313
+ " self._setup()\n",
314
+ "\n",
315
+ " def _setup(self: \"SpacyPOSTagger\"):\n",
316
+ " \"\"\"\n",
317
+ " Set up the configuration for the spaCy model, including GPU settings and data preparation.\n",
318
+ "\n",
319
+ " This function initializes and configures the spaCy model, checks for GPU availability, and prepares the training and testing datasets in spaCy format.\n",
320
+ "\n",
321
+ " If using GPU, GPU settings are configured to enhance processing speed. Then, the pre-trained spaCy model is loaded based on the provided model path.\n",
322
+ "\n",
323
+ " Training and testing datasets are prepared and saved in the respective directories for use during model training and evaluation.\n",
324
+ " \"\"\" # noqa: D212\n",
325
+ " if self.using_gpu:\n",
326
+ " self._setup_gpu()\n",
327
+ " else:\n",
328
+ " print(\"------------- You Prefer to use CPU --------------\")\n",
329
+ "\n",
330
+ "\n",
331
+ " def _setup_model(self: \"SpacyPOSTagger\",sents):\n",
332
+ " \"\"\"\n",
333
+ " Initialize and configure the spaCy model for tagging without GPU settings.\n",
334
+ "\n",
335
+ " This method loads and configures the spaCy model based on the provided model path. It also sets up a custom tokenizer for text processing and constructs a dictionary for reference.\n",
336
+ "\n",
337
+ " Args:\n",
338
+ " - model_path: Path to the pre-trained spaCy model.\n",
339
+ "\n",
340
+ " This method is typically called during setup to prepare the model for tagging tasks.\n",
341
+ " \"\"\"\n",
342
+ " self.peykare_dict = {} # Initialize a dictionary for reference\n",
343
+ " self.tagger = spacy.load(self.model_path) # Load the spaCy model\n",
344
+ " self._set_peykare_dictionary(sents) # Construct a reference dictionary\n",
345
+ " self.tagger.tokenizer = self._custom_tokenizer # Set a custom tokenizer for the model.\n",
346
+ "\n",
347
+ " def _setup_gpu(self: \"SpacyPOSTagger\"):\n",
348
+ " \"\"\"\n",
349
+ " Check GPU availability and configure spaCy to use it if possible.\n",
350
+ "\n",
351
+ " This method checks whether a GPU is available and, if so, configures spaCy to utilize it for improved processing speed. It sets the 'gpu_availability' attribute to 'True' or 'False' accordingly.\n",
352
+ "\n",
353
+ " This check is performed during setup to make use of available GPU resources for enhanced performance.\n",
354
+ " \"\"\"\n",
355
+ " print(\"------------------ GPU Setup Process Started ---------------------\")\n",
356
+ " gpu_available = spacy.prefer_gpu(gpu_id=self.gpu_id) # Check if a GPU is available\n",
357
+ " if gpu_available:\n",
358
+ " print(\"------------ GPU is available and ready for use -------------\")\n",
359
+ " spacy.require_gpu(gpu_id=self.gpu_id) # Configure spaCy to use the GPU\n",
360
+ " self.gpu_availability = True\n",
361
+ " else:\n",
362
+ " print(\"------------ GPU is not available; spaCy will use CPU -------------\")\n",
363
+ " self.gpu_availability = False\n",
364
+ "\n",
365
+ "\n",
366
+ " def _setup_dataset(self: \"SpacyPOSTagger\", dataset,saved_directory,data_type='train'):\n",
367
+ " \"\"\"\n",
368
+ " Setup the training dataset in spaCy's binary format.\n",
369
+ "\n",
370
+ " This function prepares the training dataset and saves it in spaCy's binary format.\n",
371
+ " \"\"\"\n",
372
+ " assert data_type in ['train','test']\n",
373
+ " db = DocBin()\n",
374
+ " for sent in tqdm(dataset):\n",
375
+ " words = [word[0] for word in sent]\n",
376
+ " tags = [word[1] for word in sent]\n",
377
+ " doc = Doc(Vocab(strings=words), words=words)\n",
378
+ " for d, tag in zip(doc, tags):\n",
379
+ " d.tag_ = tag\n",
380
+ " db.add(doc)\n",
381
+ "\n",
382
+ " self._handle_data_path(saved_directory)\n",
383
+ " db.to_disk(f'{saved_directory}/{data_type}.spacy')\n",
384
+ "\n",
385
+ " def _handle_data_path(self,path='POSTaggerDataset'):\n",
386
+ " \"\"\"\n",
387
+ " Create the directory if it doesn't exist.\n",
388
+ "\n",
389
+ " This method checks if the specified directory exists, and if not, it creates the directory to store the data.\n",
390
+ "\n",
391
+ " Args:\n",
392
+ " - path: The path to the directory (default is 'POSTaggerDataset').\n",
393
+ "\n",
394
+ " This method is called to ensure the directory is available for saving processed data.\n",
395
+ " \"\"\"\n",
396
+ " if not os.path.exists(path):\n",
397
+ " os.makedirs(path)\n",
398
+ "\n",
399
+ "\n",
400
+ " def _custom_tokenizer(self: \"SpacyPOSTagger\", text):\n",
401
+ " \"\"\"\n",
402
+ " Implement a custom tokenization method for spaCy.\n",
403
+ "\n",
404
+ " This method defines a custom tokenization method for spaCy. It is used to tokenize input text based on a custom dictionary, or it raises an error if tokenization is not available.\n",
405
+ "\n",
406
+ " Args:\n",
407
+ " - text: The input text to be tokenized.\n",
408
+ "\n",
409
+ " This custom tokenization method is used by the spaCy model during processing.\n",
410
+ "\n",
411
+ " \"\"\"\n",
412
+ "\n",
413
+ " if text in self.peykare_dict:\n",
414
+ " return Doc(self.tagger.vocab, self.peykare_dict[text])\n",
415
+ " else:\n",
416
+ " raise ValueError('No tokenization available for input.')\n",
417
+ "\n",
418
+ " def _set_peykare_dictionary(self: \"SpacyPOSTagger\", sents):\n",
419
+ " \"\"\"\n",
420
+ " Create a dictionary for custom tokenization.\n",
421
+ "\n",
422
+ " This method constructs a dictionary to store custom tokenization mappings based on input sentences. It is used for custom tokenization in spaCy.\n",
423
+ "\n",
424
+ " Args:\n",
425
+ " - sents: Input sentences to build the custom tokenization dictionary.\n",
426
+ "\n",
427
+ " This method is called during setup to establish a dictionary for tokenization.\n",
428
+ " \"\"\"\n",
429
+ " self.peykare_dict = {' '.join([w for w in item]): [w for w in item] for item in sents}\n",
430
+ "\n",
431
+ "\n",
432
+ " def _add_to_dict(self: \"SpacyPOSTagger\", sents):\n",
433
+ " \"\"\"\n",
434
+ " Add the sentences to dictianory if it doesnt exist already\n",
435
+ " \"\"\"\n",
436
+ " for sent in sents:\n",
437
+ " key = ' '.join(sent)\n",
438
+ " if key not in self.peykare_dict:\n",
439
+ " self.peykare_dict[key] = sent\n",
440
+ "\n",
441
+ "\n",
442
+ " def tag(self: \"SpacyPOSTagger\", tokens,universal_tag=True):\n",
443
+ " \"\"\"یک جمله را در قالب لیستی از توکن‌ها دریافت می‌کند و در خروجی لیستی از\n",
444
+ " `(توکن، برچسب)`ها برمی‌گرداند.\n",
445
+ "\n",
446
+ " Examples:\n",
447
+ " >>> posTagger = POSTagger(model = 'pos_tagger.model')\n",
448
+ " >>> posTagger.tag(tokens = ['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.'])\n",
449
+ " [('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN,EZ'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]\n",
450
+ "\n",
451
+ " >>> posTagger = POSTagger(model = 'pos_tagger.model', universal_tag = True)\n",
452
+ " >>> posTagger.tag(tokens = ['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.'])\n",
453
+ " [('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]\n",
454
+ "\n",
455
+ " Args:\n",
456
+ " tokens (List[str]): لیستی از توکن‌های یک جمله که باید برچسب‌گذاری شود.\n",
457
+ "\n",
458
+ " Returns:\n",
459
+ " (List[Tuple[str,str]]): ‌لیستی از `(توکن، برچسب)`ها.\n",
460
+ "\n",
461
+ " \"\"\"\n",
462
+ " if self.tagger == None:\n",
463
+ " self._setup_model([tokens])\n",
464
+ " self._add_to_dict([tokens])\n",
465
+ "\n",
466
+ " text = ' '.join(tokens)\n",
467
+ " doc = self.tagger(text)\n",
468
+ " if not universal_tag:\n",
469
+ " tags = [tok.tag_ for tok in doc]\n",
470
+ " else:\n",
471
+ " tags = [tok.tag_.replace(',EZ','') for tok in doc]\n",
472
+ "\n",
473
+ " return list(zip(tokens,tags))\n",
474
+ " # noqa: W293\n",
475
+ "\n",
476
+ " def tag_sents(self:\"SpacyPOSTagger\",sents,universal_tag=True,batch_size=128):\n",
477
+ " \"\"\"\n",
478
+ " Args:\n",
479
+ " sents : List[List[Tokens]]\n",
480
+ " batch_size : number of batches give to model for processing sentences each time\n",
481
+ " \"\"\"\n",
482
+ " \"\"\"\n",
483
+ " Returns : List[List[Tuple(str,str)]]\n",
484
+ " \"\"\"\n",
485
+ " if self.tagger == None:\n",
486
+ " self._setup_model(sents)\n",
487
+ "\n",
488
+ " self._add_to_dict(sents)\n",
489
+ "\n",
490
+ " docs = list(self.tagger.pipe((' '.join([w for w in sent]) for sent in sents), batch_size=batch_size))\n",
491
+ " if not universal_tag:\n",
492
+ " tags = [[w.tag_ for w in doc] for doc in docs]\n",
493
+ " else:\n",
494
+ " tags = [[w.tag_.replace(',EZ','') for w in doc] for doc in docs]\n",
495
+ "\n",
496
+ " combined_out = [list(zip(tok,tag)) for tok,tag in zip(sents,tags)]\n",
497
+ " return combined_out\n",
498
+ "\n",
499
+ " def train(\n",
500
+ " self: \"SpacyPOSTagger\",\n",
501
+ " train_dataset,\n",
502
+ " test_dataset,\n",
503
+ " data_directory,\n",
504
+ " base_config_file,\n",
505
+ " train_config_path,\n",
506
+ " output_dir,\n",
507
+ " use_direct_config=False\n",
508
+ " ):\n",
509
+ " \"\"\"\n",
510
+ " Train the spaCy model using a subprocess and a configuration file.\n",
511
+ "\n",
512
+ " This method executes the training process for the spaCy model by invoking spaCy's training module using subprocess. It takes input configuration files, training and testing data, and GPU settings (if available).\n",
513
+ "\n",
514
+ " Args:\n",
515
+ " - train_dataset: Training dataset for the tagger. It is a list of sentences, where each sentence is a list of token-tag pairs.\n",
516
+ " - test_dataset: Testing dataset for the tagger. It is a list of sentences, where each sentence is a list of token-tag pairs.\n",
517
+ " - data_directory: Directory to save the training and testing data in spaCy format.\n",
518
+ " - base_config_file: Path to the base configuration file for spaCy.\n",
519
+ " - train_config_path: if use_direct_config set to True this is the path of config file for training that you will use\n",
520
+ " if use_direct_config set to False this is the path that you want train config file will create with base_config\n",
521
+ " - output_dir: Directory for storing the trained model and training logs.\n",
522
+ "\n",
523
+ " Upon successful training, this method updates the model path to the trained model.\n",
524
+ "\n",
525
+ " This method is typically called to initiate the training process of the spaCy model.\n",
526
+ " \"\"\"\n",
527
+ "\n",
528
+ " self.spacy_train_directory = data_directory\n",
529
+ " self.train_dataset = train_dataset ### List[List[Tuple]]\n",
530
+ " self.test_dataset = test_dataset\n",
531
+ " if self.train_dataset:\n",
532
+ " # Set up the training dataset configuration\n",
533
+ " self._setup_dataset(dataset=self.train_dataset, saved_directory=self.spacy_train_directory, data_type='train')\n",
534
+ "\n",
535
+ " if self.test_dataset:\n",
536
+ " self._setup_dataset(test_dataset,saved_directory=data_directory,data_type='test')\n",
537
+ "\n",
538
+ " train_data = f'{data_directory}/train.spacy'\n",
539
+ " test_data = f'{data_directory}/test.spacy'\n",
540
+ "\n",
541
+ " if use_direct_config == False:\n",
542
+ " self._setup_train_config(base_config_file, train_config_path=train_config_path)\n",
543
+ " else:\n",
544
+ " self.train_config_file = train_config_path\n",
545
+ "\n",
546
+ " command = f\"python -m spacy train {self.train_config_file} --output ./{output_dir} --paths.train ./{train_data} --paths.dev ./{test_data}\"\n",
547
+ " if self.gpu_availability:\n",
548
+ " command += f\" --gpu-id {self.gpu_id}\"\n",
549
+ "\n",
550
+ " subprocess.run(command, shell=True)\n",
551
+ " self.model_path = f\"{output_dir}/model-last\"\n",
552
+ " self._setup_model([[w for w,_ in sent] for sent in test_dataset])\n",
553
+ "\n",
554
+ " def _setup_train_config(self: \"SpacyPOSTagger\", base_config, train_config_path):\n",
555
+ " \"\"\"\n",
556
+ " Create and configure the training configuration file for spaCy.\n",
557
+ "\n",
558
+ " This method sets up the training configuration file by copying a base configuration file and customizing it according to the specified parameters.\n",
559
+ "\n",
560
+ " Args:\n",
561
+ " - base_config: Path to the base configuration file.\n",
562
+ " - train_config_file_name: Name of the training configuration file for saving it.\n",
563
+ "\n",
564
+ " This method is called to generate the training configuration file used in the training process.\n",
565
+ " \"\"\"\n",
566
+ " self.train_config_file = train_config_path\n",
567
+ " print(\"----------------- Setting up the training configuration file ----------------------\")\n",
568
+ " command = f\"python -m spacy init fill-config {base_config} {train_config_path}\" # Generate the training configuration file\n",
569
+ " subprocess.run(command, shell=True)\n",
570
+ " print(\"----------------- Training configuration file created successfully ----------------------\")\n",
571
+ " print(f\"----------------- Training Config file address is {train_config_path} --------------------\")\n",
572
+ "\n",
573
+ " def evaluate(self: \"SpacyPOSTagger\", test_sents,batch_size):\n",
574
+ " \"\"\"\n",
575
+ " Evaluate the spaCy model on input sentences using different tag options.\n",
576
+ "\n",
577
+ " This method evaluates the spaCy model on input sentences with and without 'EZ' tags and reports classification metrics.\n",
578
+ "\n",
579
+ " Args:\n",
580
+ " - sents: List of sentences for evaluation.\n",
581
+ " - batch_size : number of batches that model should process each time\n",
582
+ " This method calls the internal evaluation method for both tag options.\n",
583
+ "\n",
584
+ " This method is typically used for model evaluation and reporting metrics.\n",
585
+ " \"\"\"\n",
586
+ " self._setup_model([[w for w,_ in sent] for sent in test_sents])\n",
587
+ " if self.tagger:\n",
588
+ " golds, predictions = self._get_labels_and_predictions(test_sents,batch_size)\n",
589
+ " print(\"-----------------------------------------\")\n",
590
+ " self._evaluate_tags(test_sents, golds, predictions, use_ez_tags=True,batch_size=batch_size)\n",
591
+ " print(\"-----------------------------------------\")\n",
592
+ " self._evaluate_tags(test_sents, golds, predictions, use_ez_tags=False,batch_size=batch_size)\n",
593
+ " else:\n",
594
+ " raise ValueError(\"Model does not exist.Please train a new one with train method of this instance or give a model_path , setup the model with self._setup_model() and then call evaluate\")\n",
595
+ "\n",
596
+ " def _evaluate_tags(self, sents, golds=None, predictions=None, use_ez_tags=True,batch_size=128):\n",
597
+ " \"\"\"\n",
598
+ " Evaluate model predictions and report classification metrics.\n",
599
+ "\n",
600
+ " This method evaluates model predictions and reports classification metrics for the specified tag option.\n",
601
+ "\n",
602
+ " Args:\n",
603
+ " - sents: List of sentences for evaluation.\n",
604
+ " - golds: List of gold labels (optional).\n",
605
+ " - predictions: List of model predictions (optional).\n",
606
+ " - use_ez_tags: A flag indicating whether to consider 'EZ' tags.\n",
607
+ " - batch_size : number of batches model should process\n",
608
+ "\n",
609
+ " If `golds` and `predictions` are not provided, they are automatically extracted from the input sentences.\n",
610
+ "\n",
611
+ " This method calculates and displays precision, recall, and F1-score for the specified tag option.\n",
612
+ "\n",
613
+ " This method is called by the `evaluate` method to perform model evaluation.\n",
614
+ " \"\"\"\n",
615
+ " if golds is None or predictions is None:\n",
616
+ " golds, predictions = self._get_labels_and_predictions(sents,batch_size)\n",
617
+ "\n",
618
+ " predictions_cleaned = []\n",
619
+ " golds_cleaned = []\n",
620
+ " if use_ez_tags:\n",
621
+ " get_tag_func = self._get_ez_tags\n",
622
+ " else:\n",
623
+ " get_tag_func = self._remove_ez_tags\n",
624
+ "\n",
625
+ " for preds, golds in zip(predictions, golds):\n",
626
+ " for pred in preds:\n",
627
+ " pred_cleaned = get_tag_func(pred)\n",
628
+ " predictions_cleaned.append(pred_cleaned)\n",
629
+ " for gold in golds:\n",
630
+ " gold_cleaned = get_tag_func(gold)\n",
631
+ " golds_cleaned.append(gold_cleaned)\n",
632
+ "\n",
633
+ " print(classification_report(golds_cleaned, predictions_cleaned))\n",
634
+ " print('Precision: %.5f' % precision_score(golds_cleaned, predictions_cleaned, average='weighted'))\n",
635
+ " print('Recall: %.5f' % recall_score(golds_cleaned, predictions_cleaned, average='weighted'))\n",
636
+ " print('F1-Score: %.5f' % f1_score(golds_cleaned, predictions_cleaned, average='macro'))\n",
637
+ "\n",
638
+ " def _get_ez_tags(self, label):\n",
639
+ " \"\"\"\n",
640
+ " Extract 'EZ' tags from labels.\n",
641
+ "\n",
642
+ " This method extracts 'EZ' tags from labels if they are present and returns them.\n",
643
+ "\n",
644
+ " Args:\n",
645
+ " - label: The label containing 'EZ' tags.\n",
646
+ "\n",
647
+ " Returns:\n",
648
+ " The 'EZ' tags or '-' if 'EZ' tags are not present.\n",
649
+ " \"\"\"\n",
650
+ " if 'EZ' in label:\n",
651
+ " label = 'EZ'\n",
652
+ " else:\n",
653
+ " label = '-'\n",
654
+ "\n",
655
+ " return label\n",
656
+ "\n",
657
+ " def _remove_ez_tags(self, label):\n",
658
+ " \"\"\"\n",
659
+ " Remove 'EZ' tags from labels.\n",
660
+ "\n",
661
+ " This method removes 'EZ' tags from labels if they are present and returns the cleaned label.\n",
662
+ "\n",
663
+ " Args:\n",
664
+ " - label: The label containing 'EZ' tags.\n",
665
+ "\n",
666
+ " Returns:\n",
667
+ " The label with 'EZ' tags removed.\n",
668
+ " \"\"\"\n",
669
+ " return label.replace(',EZ', '') if 'EZ' in label else label\n",
670
+ "\n",
671
+ " def _evaluate_ez_tags(self, sents):\n",
672
+ " \"\"\"\n",
673
+ " Evaluate model predictions with 'EZ' tags included.\n",
674
+ "\n",
675
+ " This method evaluates model predictions with 'EZ' tags included.\n",
676
+ " \"\"\"\n",
677
+ " self._evaluate_tags(sents, use_ez_tags=True)\n",
678
+ "\n",
679
+ " def _evaluate_normal_tags(self, sents):\n",
680
+ " \"\"\"\n",
681
+ " Evaluate model predictions without 'EZ' tags.\n",
682
+ "\n",
683
+ " This method evaluates model predictions without 'EZ' tags.\n",
684
+ " \"\"\"\n",
685
+ " self._evaluate_tags(sents, use_ez_tags=False)\n",
686
+ "\n",
687
+ " def _get_labels_and_predictions(self: \"SpacyPOSTagger\", sents,batch_size):\n",
688
+ " \"\"\"\n",
689
+ " Extract gold labels and model predictions for evaluation.\n",
690
+ "\n",
691
+ " This method extracts gold labels and model predictions from input sentences.\n",
692
+ "\n",
693
+ " Args:\n",
694
+ " - sents: List of sentences for evaluation.\n",
695
+ "\n",
696
+ " Returns:\n",
697
+ " Lists of gold labels and model predictions.\n",
698
+ "\n",
699
+ " This method is typically used for gathering data to perform model evaluation.\n",
700
+ " \"\"\"\n",
701
+ " gold_labels = [[tag for _, tag in sent] for sent in sents]\n",
702
+ " tokens = [[w for w,_ in sent] for sent in sents]\n",
703
+ " prediction_labels = self.tag_sents(tokens,batch_size)\n",
704
+ " return gold_labels, prediction_labels\n"
705
+ ]
706
+ },
707
+ {
708
+ "cell_type": "code",
709
+ "execution_count": 5,
710
+ "metadata": {
711
+ "colab": {
712
+ "base_uri": "https://localhost:8080/"
713
+ },
714
+ "id": "5_IBJXq1Mnfo",
715
+ "outputId": "c07d6be2-70cb-45b1-ed9f-a4eb49fafb90"
716
+ },
717
+ "outputs": [
718
+ {
719
+ "name": "stdout",
720
+ "output_type": "stream",
721
+ "text": [
722
+ "------------------ GPU Setup Process Started ---------------------\n",
723
+ "------------ GPU is not available; spaCy will use CPU -------------\n"
724
+ ]
725
+ }
726
+ ],
727
+ "source": [
728
+ "spacy_posTagger = SpacyPOSTagger(model_path = '/content/spacy_pos_tagger_parsbertpostagger', using_gpu=True)"
729
+ ]
730
+ },
731
+ {
732
+ "cell_type": "code",
733
+ "execution_count": 6,
734
+ "metadata": {},
735
+ "outputs": [],
736
+ "source": [
737
+ "from hazm import WordTokenizer, Normalizer\n",
738
+ "\n",
739
+ "tokenizer = WordTokenizer()\n",
740
+ "normalizer = Normalizer()"
741
+ ]
742
+ },
743
+ {
744
+ "cell_type": "code",
745
+ "execution_count": 7,
746
+ "metadata": {},
747
+ "outputs": [],
748
+ "source": [
749
+ "# Ezafe Correction\n",
750
+ "def get_last_subword(word):\n",
751
+ " # Split the word by word boundaries\n",
752
+ " subwords = re.findall(r'\\b\\w+\\b', word)\n",
753
+ "\n",
754
+ " if len(subwords) > 1 and subwords[-1] in ['های', 'ی']:\n",
755
+ " return (subwords[-2], subwords[-1])\n",
756
+ "\n",
757
+ " return (subwords[-1], '')"
758
+ ]
759
+ },
760
+ {
761
+ "cell_type": "code",
762
+ "execution_count": 8,
763
+ "metadata": {},
764
+ "outputs": [],
765
+ "source": [
766
+ "def get_EZ_tags(grapheme, compound=False):\n",
767
+ " grapheme = re.sub('ۀ', 'ه‌ی', grapheme)\n",
768
+ " tokens = tokenizer.tokenize(normalizer.normalize(grapheme))\n",
769
+ " tags = spacy_posTagger.tag(tokens=tokens, universal_tag=False)\n",
770
+ " tags = [(t[0], t[1], '') for t in tags if 'EZ' in t[1]]\n",
771
+ "\n",
772
+ " if compound:\n",
773
+ " return tags\n",
774
+ "\n",
775
+ " splitted_tags = []\n",
776
+ " for t in tags:\n",
777
+ " subword1, subword2 = get_last_subword(t[0])\n",
778
+ " splitted_tags.append((subword1, t[1], subword2))\n",
779
+ " return splitted_tags"
780
+ ]
781
+ },
782
+ {
783
+ "cell_type": "code",
784
+ "execution_count": 9,
785
+ "metadata": {},
786
+ "outputs": [],
787
+ "source": [
788
+ "def get_naive_phonetic(word):\n",
789
+ " char_map = {\n",
790
+ " 'ا': 'A', 'ب': 'b', 'پ': 'p', 'ت': 't', 'ث': 's', 'ج': 'j', 'چ': 'C',\n",
791
+ " 'ح': 'h', 'خ': 'x', 'د': 'd', 'ذ': 'z', 'ر': 'r', 'ز': 'z', 'ژ': 'Z',\n",
792
+ " 'س': 's', 'ش': 'S', 'ص': 's', 'ض': 'z', 'ط': 't', 'ظ': 'z', 'ع': '?',\n",
793
+ " 'غ': 'q', 'ف': 'f', 'ق': 'q', 'ک': 'k', 'گ': 'g', 'ل': 'l', 'م': 'm',\n",
794
+ " 'ن': 'n', 'و': 'v', 'ه': 'h', 'ی': 'y', 'ء': '?','ئ': '?', 'ؤ': '?',\n",
795
+ " 'آ': 'A', 'أ': '?', 'إ': '?', 'ۀ': 'eye'\n",
796
+ " }\n",
797
+ " mapped_string = ''.join(char_map.get(char, char) for char in word)\n",
798
+ " return mapped_string"
799
+ ]
800
+ },
801
+ {
802
+ "cell_type": "code",
803
+ "execution_count": null,
804
+ "metadata": {},
805
+ "outputs": [],
806
+ "source": [
807
+ "import pandas as pd\n",
808
+ "merged_dict_path = 'final_merged_dict_pruned_POS_prob.csv'\n",
809
+ "merged_dict_df = pd.read_csv(merged_dict_path)\n",
810
+ "\n",
811
+ "merged_dict = {}\n",
812
+ "\n",
813
+ "for idx, row in merged_dict_df.iterrows():\n",
814
+ " g, ps, nodiff, pos, prob = row['grapheme'], eval(row['phoneme']), row['nodiff'], eval(row['POS']), eval(row['prob'])\n",
815
+ " if g not in merged_dict:\n",
816
+ " merged_dict[g] = {'phoneme': [], 'nodiff': nodiff, 'POS': pos, 'prob': prob}\n",
817
+ "\n",
818
+ " for p in ps:\n",
819
+ " merged_dict[g]['phoneme'].append(''.join(p))\n",
820
+ "\n",
821
+ "\n",
822
+ "inverted_merged_dict = {}\n",
823
+ "\n",
824
+ "for key, value_list in merged_dict.items():\n",
825
+ " for value in value_list['phoneme']:\n",
826
+ " inverted_merged_dict[value] = key\n",
827
+ "\n",
828
+ "\n",
829
+ "def word_in_dict(word, inverted_dictionary=inverted_merged_dict):\n",
830
+ " return word in inverted_dictionary"
831
+ ]
832
+ },
833
+ {
834
+ "cell_type": "code",
835
+ "execution_count": 11,
836
+ "metadata": {},
837
+ "outputs": [],
838
+ "source": [
839
+ "import itertools\n",
840
+ "def get_word_phonetic_candidates(word):\n",
841
+ " subwords = []\n",
842
+ " for match in re.finditer(r'\\b(\\w+)\\b', word):\n",
843
+ " match_text = match.group()\n",
844
+ " match_span = match.span()\n",
845
+ " subwords.append((match_text, match_span))\n",
846
+ "\n",
847
+ " subword_candidates = []\n",
848
+ " for subword, _ in subwords:\n",
849
+ " if subword in merged_dict:\n",
850
+ " subword_candidates.append(merged_dict[subword]['phoneme'])\n",
851
+ " else:\n",
852
+ " subword_candidates.append([get_naive_phonetic(subword)])\n",
853
+ "\n",
854
+ " # Generate all possible combinations and concatenate\n",
855
+ " word_candidates = [''.join(comb) for comb in itertools.product(*subword_candidates)]\n",
856
+ " return word_candidates"
857
+ ]
858
+ },
859
+ {
860
+ "cell_type": "code",
861
+ "execution_count": 12,
862
+ "metadata": {},
863
+ "outputs": [],
864
+ "source": [
865
+ "def get_updated_span(match_span, displacements):\n",
866
+ " new_start, new_end = match_span[0], match_span[1]\n",
867
+ " for start, displacement in displacements:\n",
868
+ " if start <= new_start:\n",
869
+ " new_start += displacement\n",
870
+ " new_end += displacement\n",
871
+ "\n",
872
+ " return (new_start, new_end)"
873
+ ]
874
+ },
875
+ {
876
+ "cell_type": "code",
877
+ "execution_count": 13,
878
+ "metadata": {},
879
+ "outputs": [],
880
+ "source": [
881
+ "def add_1_for_EZ(phonemes):\n",
882
+ " # Convert 'a' to 'A' in '-ha' and '-haye'\n",
883
+ " phonemes = phonemes.replace('-ha', '-hA').replace('-haye', '-hAye')\n",
884
+ " \n",
885
+ " # Add '1' after '-e', '-ye', and '-hAye'\n",
886
+ " phonemes = phonemes.replace('-e', '-e1').replace('-ye', '-ye1').replace('-hAye', '-hAye1')\n",
887
+ " \n",
888
+ " return phonemes"
889
+ ]
890
+ },
891
+ {
892
+ "cell_type": "code",
893
+ "execution_count": 14,
894
+ "metadata": {},
895
+ "outputs": [],
896
+ "source": [
897
+ "def correct_phonetic_model_EZ_by_tags(grapheme, model_output):\n",
898
+ " EZ_tags = get_EZ_tags(grapheme, compound=False)\n",
899
+ "\n",
900
+ " matches = []\n",
901
+ " matched_spans = set()\n",
902
+ "\n",
903
+ " for word, tag, ending in EZ_tags:\n",
904
+ " phonetic_candidates = get_word_phonetic_candidates(word)\n",
905
+ "\n",
906
+ " for phonetic in phonetic_candidates:\n",
907
+ " if phonetic.endswith('Aye') and not word.endswith('ه'): continue\n",
908
+ " for match in re.finditer(r'\\b(\\w+)\\b', model_output):\n",
909
+ " match_text = match.group()\n",
910
+ " match_span = match.span()\n",
911
+ " \n",
912
+ " if match_text not in ['e', 'ye', 'i', 'ha', 'hA', 'hAye', 'haye'] and match_span not in matched_spans and SequenceMatcher(None, match_text, phonetic).ratio() > 0.75:\n",
913
+ " matches.append((match_span, match_text, phonetic, ending))\n",
914
+ " matched_spans.add(match_span)\n",
915
+ "\n",
916
+ " non_matches = []\n",
917
+ " for match in re.finditer(r'\\b(\\w+)\\b', model_output):\n",
918
+ " match_text = match.group()\n",
919
+ " match_span = match.span()\n",
920
+ " if not match_text.endswith('e') and not match_text.endswith('ye') and not match_text.endswith('i') and not match_text.endswith('ha')and not match_text.endswith('hAye') and not match_text.endswith('haye') and match_span not in matched_spans:\n",
921
+ " non_matches.append((match_text, match_span))\n",
922
+ "\n",
923
+ " displacements = []\n",
924
+ " for match_span, _, phonetic, ending in matches:\n",
925
+ " match_span = get_updated_span(match_span, displacements)\n",
926
+ " if model_output[match_span[1]:].startswith('-e') or model_output[match_span[1]:].startswith('-ye') or model_output[match_span[1]:].startswith('-hAye') or model_output[match_span[1]:].startswith('-haye') or model_output[match_span[1]:].startswith('-hA-ye') or model_output[match_span[1]:].startswith('-ha-ye'):\n",
927
+ " continue\n",
928
+ "\n",
929
+ " output_word = model_output[match_span[0]:match_span[1]]\n",
930
+ " if len(output_word) >= 4 and output_word[-3] in 'еeiuoaāäâāɒáA' and output_word.endswith('ye') and \\\n",
931
+ " ((word_in_dict(output_word[:-2], inverted_merged_dict) and not word_in_dict(output_word, inverted_merged_dict)) or \\\n",
932
+ " SequenceMatcher(None, output_word[:-2], phonetic).ratio() > SequenceMatcher(None, output_word, phonetic).ratio()):\n",
933
+ " model_output = model_output[:match_span[1] - 2] + '-' + model_output[match_span[1] - 2:]\n",
934
+ " displacements.append((match_span[1] - 2, 1))\n",
935
+ " continue\n",
936
+ "\n",
937
+ " if len(output_word) >= 3 and output_word.endswith('e') and \\\n",
938
+ " ((word_in_dict(output_word[:-1], inverted_merged_dict) and not word_in_dict(output_word, inverted_merged_dict)) or \\\n",
939
+ " SequenceMatcher(None, output_word[:-1], phonetic).ratio() > SequenceMatcher(None, output_word, phonetic).ratio()):\n",
940
+ " model_output = model_output[:match_span[1] - 1] + '-' + model_output[match_span[1] - 1:]\n",
941
+ " displacements.append((match_span[1] - 1, 1))\n",
942
+ " continue\n",
943
+ "\n",
944
+ " if ending == 'ی' and len(output_word) >= 4 and output_word[-2:] == 'ye' and output_word[-3] == phonetic[-1]:\n",
945
+ " model_output = model_output[:match_span[1] - 2] + '-' + model_output[match_span[1] - 2:]\n",
946
+ " displacements.append((match_span[1] - 2, 1))\n",
947
+ " continue\n",
948
+ "\n",
949
+ " if ending == 'های' and len(output_word) >= 7 and output_word[-5:] == 'hAye':\n",
950
+ " model_output = model_output[:match_span[1] - 4] + '-' + model_output[match_span[1] - 4:]\n",
951
+ " displacements.append((match_span[1] - 5, 1))\n",
952
+ " continue\n",
953
+ "\n",
954
+ " if ending == 'های' and len(output_word) >= 6 and output_word[-4:] == 'haye':\n",
955
+ " model_output = model_output[:match_span[1] - 4] + '-hAye' + model_output[match_span[1]:]\n",
956
+ " displacements.append((match_span[1] - 4, 1))\n",
957
+ " continue\n",
958
+ "\n",
959
+ " if ending not in ['ی', 'های'] and len(output_word) >= 3 and output_word[-2] == phonetic[-1] and output_word[-1] == 'e':\n",
960
+ " model_output = model_output[:match_span[1] - 1] + '-' + model_output[match_span[1] - 1:]\n",
961
+ " displacements.append((match_span[1] - 1, 1))\n",
962
+ " continue\n",
963
+ "\n",
964
+ " if output_word[-1] in 'еeiuoaāäâāɒáA' and not output_word.endswith('haye') and not output_word.endswith('hAye'):\n",
965
+ " model_output = model_output[:match_span[1]] + '-ye' + model_output[match_span[1]:]\n",
966
+ " displacements.append((match_span[1], 3))\n",
967
+ " continue\n",
968
+ "\n",
969
+ " if not output_word.endswith('e'):\n",
970
+ " model_output = model_output[:match_span[1]] + '-e' + model_output[match_span[1]:]\n",
971
+ " displacements.append((match_span[1], 2))\n",
972
+ "\n",
973
+ " for non_match, match_span in non_matches:\n",
974
+ " match_span = get_updated_span(match_span, displacements)\n",
975
+ " output_word = model_output[match_span[0]:match_span[1]]\n",
976
+ " if re.match(r'^-e\\b', model_output[match_span[1]:]):\n",
977
+ " model_output = model_output[:match_span[1]] + model_output[match_span[1] + 2:]\n",
978
+ " displacements.append((match_span[1] + 2, -2))\n",
979
+ " continue\n",
980
+ "\n",
981
+ " if re.match(r'^-ye\\b', model_output[match_span[1]:]):\n",
982
+ " model_output = model_output[:match_span[1]] + model_output[match_span[1] + 3:]\n",
983
+ " displacements.append((match_span[1] + 3, -3))\n",
984
+ " continue\n",
985
+ "\n",
986
+ " if len(output_word) >= 4 and output_word[-3] in 'еeiuoaāäâāɒáA' and output_word.endswith('ye') and (word_in_dict(output_word[:-2], inverted_merged_dict) and not word_in_dict(output_word, inverted_merged_dict)):\n",
987
+ " model_output = model_output[:match_span[1] - 2] + model_output[match_span[1]:]\n",
988
+ " displacements.append((match_span[1], -2))\n",
989
+ " continue\n",
990
+ "\n",
991
+ " if len(output_word) >= 3 and output_word.endswith('e') and (word_in_dict(output_word[:-1], inverted_merged_dict) and not word_in_dict(output_word, inverted_merged_dict)):\n",
992
+ " model_output = model_output[:match_span[1] - 1] + model_output[match_span[1]:]\n",
993
+ " displacements.append((match_span[1], -1))\n",
994
+ "\n",
995
+ "\n",
996
+ " model_output = add_1_for_EZ(model_output)\n",
997
+ "\n",
998
+ " return model_output"
999
+ ]
1000
+ },
1001
+ {
1002
+ "cell_type": "markdown",
1003
+ "metadata": {
1004
+ "id": "AdU8VMTIOWLZ"
1005
+ },
1006
+ "source": [
1007
+ "# Get Data"
1008
+ ]
1009
+ },
1010
+ {
1011
+ "cell_type": "markdown",
1012
+ "metadata": {
1013
+ "id": "XhbCA2tkR45b"
1014
+ },
1015
+ "source": [
1016
+ "## Get Merged Dict"
1017
+ ]
1018
+ },
1019
+ {
1020
+ "cell_type": "code",
1021
+ "execution_count": null,
1022
+ "metadata": {
1023
+ "id": "dGYh5bDyRfTg"
1024
+ },
1025
+ "outputs": [],
1026
+ "source": [
1027
+ "merged_dict_path = \"final_merged_dict_pruned_POS_prob.csv\""
1028
+ ]
1029
+ },
1030
+ {
1031
+ "cell_type": "code",
1032
+ "execution_count": 16,
1033
+ "metadata": {
1034
+ "id": "WV2x_iLQRhHI"
1035
+ },
1036
+ "outputs": [],
1037
+ "source": [
1038
+ "import pandas as pd\n",
1039
+ "merged_dict_df = pd.read_csv(merged_dict_path)"
1040
+ ]
1041
+ },
1042
+ {
1043
+ "cell_type": "code",
1044
+ "execution_count": 17,
1045
+ "metadata": {
1046
+ "colab": {
1047
+ "base_uri": "https://localhost:8080/"
1048
+ },
1049
+ "id": "NTDIcLdNUbNX",
1050
+ "outputId": "736b59cd-67cf-4d4f-d4da-4466bff487a1"
1051
+ },
1052
+ "outputs": [
1053
+ {
1054
+ "data": {
1055
+ "text/plain": [
1056
+ "(116630, 5)"
1057
+ ]
1058
+ },
1059
+ "execution_count": 17,
1060
+ "metadata": {},
1061
+ "output_type": "execute_result"
1062
+ }
1063
+ ],
1064
+ "source": [
1065
+ "merged_dict_df.shape"
1066
+ ]
1067
+ },
1068
+ {
1069
+ "cell_type": "code",
1070
+ "execution_count": 18,
1071
+ "metadata": {
1072
+ "id": "JoW9aygRdcP6"
1073
+ },
1074
+ "outputs": [],
1075
+ "source": [
1076
+ "consonants_regex = '(?=' + '|'.join(['q', 'r', 't', 'y', 'p', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'R', 'T', 'Y', 'P', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M' ]) + ')'\n",
1077
+ "vowels_regex = '(?=' + '|'.join(['a', 'A', 'e', 'i', 'u', 'o']) + ')'"
1078
+ ]
1079
+ },
1080
+ {
1081
+ "cell_type": "code",
1082
+ "execution_count": 19,
1083
+ "metadata": {
1084
+ "id": "OJTyOEoMR-cV"
1085
+ },
1086
+ "outputs": [],
1087
+ "source": [
1088
+ "merged_dict = {}\n",
1089
+ "\n",
1090
+ "for idx, row in merged_dict_df.iterrows():\n",
1091
+ " g, ps, nodiff, pos, prob = row['grapheme'], eval(row['phoneme']), row['nodiff'], eval(row['POS']), eval(row['prob'])\n",
1092
+ " if g not in merged_dict:\n",
1093
+ " merged_dict[g] = {'phoneme': [], 'nodiff': nodiff, 'POS': pos, 'prob': prob}\n",
1094
+ "\n",
1095
+ " for p in ps:\n",
1096
+ " merged_dict[g]['phoneme'].append(''.join(p))"
1097
+ ]
1098
+ },
1099
+ {
1100
+ "cell_type": "code",
1101
+ "execution_count": 23,
1102
+ "metadata": {
1103
+ "id": "ujrYr29iy9TJ"
1104
+ },
1105
+ "outputs": [],
1106
+ "source": [
1107
+ "inverted_merged_dict = {}\n",
1108
+ "\n",
1109
+ "for key, value_list in merged_dict.items():\n",
1110
+ " for value in value_list:\n",
1111
+ " inverted_merged_dict[value] = key"
1112
+ ]
1113
+ },
1114
+ {
1115
+ "cell_type": "code",
1116
+ "execution_count": 24,
1117
+ "metadata": {
1118
+ "id": "OoaIwa8nOegN"
1119
+ },
1120
+ "outputs": [],
1121
+ "source": [
1122
+ "def word_in_dict(word, inverted_dictionary=inverted_merged_dict):\n",
1123
+ " return word in inverted_dictionary"
1124
+ ]
1125
+ },
1126
+ {
1127
+ "cell_type": "markdown",
1128
+ "metadata": {
1129
+ "id": "XjAPkfq7SF87"
1130
+ },
1131
+ "source": [
1132
+ "## Get Evaluation Data"
1133
+ ]
1134
+ },
1135
+ {
1136
+ "cell_type": "code",
1137
+ "execution_count": null,
1138
+ "metadata": {
1139
+ "id": "hJO-UAPDQvcb"
1140
+ },
1141
+ "outputs": [],
1142
+ "source": [
1143
+ "sentence_bench = pd.read_csv('SentenceBench.csv')"
1144
+ ]
1145
+ },
1146
+ {
1147
+ "cell_type": "code",
1148
+ "execution_count": 26,
1149
+ "metadata": {
1150
+ "colab": {
1151
+ "base_uri": "https://localhost:8080/",
1152
+ "height": 143
1153
+ },
1154
+ "id": "qlYbrnUa9LAN",
1155
+ "outputId": "ce68f665-681a-454a-9a02-d5d14047fc68"
1156
+ },
1157
+ "outputs": [
1158
+ {
1159
+ "data": {
1160
+ "text/html": [
1161
+ "<div>\n",
1162
+ "<style scoped>\n",
1163
+ " .dataframe tbody tr th:only-of-type {\n",
1164
+ " vertical-align: middle;\n",
1165
+ " }\n",
1166
+ "\n",
1167
+ " .dataframe tbody tr th {\n",
1168
+ " vertical-align: top;\n",
1169
+ " }\n",
1170
+ "\n",
1171
+ " .dataframe thead th {\n",
1172
+ " text-align: right;\n",
1173
+ " }\n",
1174
+ "</style>\n",
1175
+ "<table border=\"1\" class=\"dataframe\">\n",
1176
+ " <thead>\n",
1177
+ " <tr style=\"text-align: right;\">\n",
1178
+ " <th></th>\n",
1179
+ " <th>dataset</th>\n",
1180
+ " <th>grapheme</th>\n",
1181
+ " <th>phoneme</th>\n",
1182
+ " <th>homograph word</th>\n",
1183
+ " <th>pronunciation</th>\n",
1184
+ " </tr>\n",
1185
+ " </thead>\n",
1186
+ " <tbody>\n",
1187
+ " <tr>\n",
1188
+ " <th>0</th>\n",
1189
+ " <td>polyphone</td>\n",
1190
+ " <td>من قدر تو را می‌دانم</td>\n",
1191
+ " <td>man qadr-e to rA mi-dAnam</td>\n",
1192
+ " <td>قدر</td>\n",
1193
+ " <td>qadr</td>\n",
1194
+ " </tr>\n",
1195
+ " <tr>\n",
1196
+ " <th>1</th>\n",
1197
+ " <td>polyphone</td>\n",
1198
+ " <td>از قضای الهی به قدر الهی پناه می‌برم</td>\n",
1199
+ " <td>?az qazAy ?elAhi be qadar-e ?elAhi panAh mi-baram</td>\n",
1200
+ " <td>قدر</td>\n",
1201
+ " <td>qadar</td>\n",
1202
+ " </tr>\n",
1203
+ " <tr>\n",
1204
+ " <th>2</th>\n",
1205
+ " <td>polyphone</td>\n",
1206
+ " <td>به دست و صورتم کرم زدم</td>\n",
1207
+ " <td>be dast-o suratam kerem zadam</td>\n",
1208
+ " <td>کرم</td>\n",
1209
+ " <td>kerem</td>\n",
1210
+ " </tr>\n",
1211
+ " </tbody>\n",
1212
+ "</table>\n",
1213
+ "</div>"
1214
+ ],
1215
+ "text/plain": [
1216
+ " dataset grapheme \\\n",
1217
+ "0 polyphone من قدر تو را می‌دانم \n",
1218
+ "1 polyphone از قضای الهی به قدر الهی پناه می‌برم \n",
1219
+ "2 polyphone به دست و صورتم کرم زدم \n",
1220
+ "\n",
1221
+ " phoneme homograph word \\\n",
1222
+ "0 man qadr-e to rA mi-dAnam قدر \n",
1223
+ "1 ?az qazAy ?elAhi be qadar-e ?elAhi panAh mi-baram قدر \n",
1224
+ "2 be dast-o suratam kerem zadam کرم \n",
1225
+ "\n",
1226
+ " pronunciation \n",
1227
+ "0 qadr \n",
1228
+ "1 qadar \n",
1229
+ "2 kerem "
1230
+ ]
1231
+ },
1232
+ "execution_count": 26,
1233
+ "metadata": {},
1234
+ "output_type": "execute_result"
1235
+ }
1236
+ ],
1237
+ "source": [
1238
+ "sentence_bench.head(3)"
1239
+ ]
1240
+ },
1241
+ {
1242
+ "cell_type": "markdown",
1243
+ "metadata": {
1244
+ "id": "wDV7ysXf2b_H"
1245
+ },
1246
+ "source": [
1247
+ "### Get ManaTTS"
1248
+ ]
1249
+ },
1250
+ {
1251
+ "cell_type": "code",
1252
+ "execution_count": 27,
1253
+ "metadata": {
1254
+ "colab": {
1255
+ "base_uri": "https://localhost:8080/"
1256
+ },
1257
+ "id": "TcL5ZLvSSnVB",
1258
+ "outputId": "3945e139-1b12-44c9-d6c1-dd0b1a790593"
1259
+ },
1260
+ "outputs": [
1261
+ {
1262
+ "data": {
1263
+ "text/plain": [
1264
+ "[('در این نوشته بنا داریم با یک ابزار ساده و مکانیکی افزایش بینایی برای افراد کم\\u200cبینا ',\n",
1265
+ " 'dar ?in neveSte banA dArim bA yek ?abzAr-e sAde va mekAniki-ye ?afzAyeS-e binAyi barAye ?afrAd-e kam\\u200cbinA '),\n",
1266
+ " ('به نام بی\\u200cوپتیک یا عدسی دورنما آشنا شویم. ',\n",
1267
+ " 'be nAm-e biyoptik yA ?adasi-ye durnamA ?ASnA Savim'),\n",
1268
+ " ('دراین\\u200cصورت، انجام خودارزیابی و ارائه بازخورد بر عهده خودتان است. ',\n",
1269
+ " 'dar ?in surat ?anjAm-e xod?arzyAbi va ?erA?e-ye bAzxord bar ?ohde-ye xodetAn ?ast ')]"
1270
+ ]
1271
+ },
1272
+ "execution_count": 27,
1273
+ "metadata": {},
1274
+ "output_type": "execute_result"
1275
+ }
1276
+ ],
1277
+ "source": [
1278
+ "filtered_rows = sentence_bench[sentence_bench['dataset'] == 'mana-tts'][['grapheme', 'phoneme']]\n",
1279
+ "\n",
1280
+ "# Convert to a list of tuples\n",
1281
+ "mana_evaluation_data = list(filtered_rows.itertuples(index=False, name=None))\n",
1282
+ "\n",
1283
+ "mana_evaluation_data[:3]"
1284
+ ]
1285
+ },
1286
+ {
1287
+ "cell_type": "markdown",
1288
+ "metadata": {
1289
+ "id": "Jjacw9Mp2eoX"
1290
+ },
1291
+ "source": [
1292
+ "### Get CommonVoice"
1293
+ ]
1294
+ },
1295
+ {
1296
+ "cell_type": "code",
1297
+ "execution_count": 28,
1298
+ "metadata": {
1299
+ "colab": {
1300
+ "base_uri": "https://localhost:8080/"
1301
+ },
1302
+ "id": "-yQnqCGw26sk",
1303
+ "outputId": "952fad9e-837f-4f0c-e3a4-249365abaa5c"
1304
+ },
1305
+ "outputs": [
1306
+ {
1307
+ "data": {
1308
+ "text/plain": [
1309
+ "[('در اکثر شهرها، مرکزی برای خرید دوچرخه وجود دارد.',\n",
1310
+ " 'dar ?aksar-e Sahr-hA, markazi barAye xarid-e doCarxe vojud dArad.'),\n",
1311
+ " ('پس از مدرسه کودکان به سوی خانه جست و خیز کردند.',\n",
1312
+ " 'pas ?az madrese kudakAn be suye xAne jast-o-xiz kardand.'),\n",
1313
+ " ('شما نگران زن و بچه این نباش.', 'SomA negarAn-e zan-o-baCCe-ye ?in nabAS.')]"
1314
+ ]
1315
+ },
1316
+ "execution_count": 28,
1317
+ "metadata": {},
1318
+ "output_type": "execute_result"
1319
+ }
1320
+ ],
1321
+ "source": [
1322
+ "filtered_rows = sentence_bench[sentence_bench['dataset'] == 'commonvoice'][['grapheme', 'phoneme']]\n",
1323
+ "\n",
1324
+ "# Convert to a list of tuples\n",
1325
+ "commonvoice_evaluation_data = list(filtered_rows.itertuples(index=False, name=None))\n",
1326
+ "\n",
1327
+ "commonvoice_evaluation_data[:3]"
1328
+ ]
1329
+ },
1330
+ {
1331
+ "cell_type": "markdown",
1332
+ "metadata": {
1333
+ "id": "ciSPyhRc3Rvo"
1334
+ },
1335
+ "source": [
1336
+ "### Get Ambiguious"
1337
+ ]
1338
+ },
1339
+ {
1340
+ "cell_type": "code",
1341
+ "execution_count": 29,
1342
+ "metadata": {
1343
+ "colab": {
1344
+ "base_uri": "https://localhost:8080/"
1345
+ },
1346
+ "id": "XlFc5JbN3Rvz",
1347
+ "outputId": "56dd8eb2-0f5e-4e91-ff91-25317ff0581d"
1348
+ },
1349
+ "outputs": [
1350
+ {
1351
+ "data": {
1352
+ "text/plain": [
1353
+ "[('من قدر تو را می\\u200cدانم', 'man qadr-e to rA mi-dAnam', 'قدر', 'qadr'),\n",
1354
+ " ('از قضای الهی به قدر الهی پناه می\\u200cبرم',\n",
1355
+ " '?az qazAy ?elAhi be qadar-e ?elAhi panAh mi-baram',\n",
1356
+ " 'قدر',\n",
1357
+ " 'qadar'),\n",
1358
+ " ('به دست و صورتم کرم زدم', 'be dast-o suratam kerem zadam', 'کرم', 'kerem')]"
1359
+ ]
1360
+ },
1361
+ "execution_count": 29,
1362
+ "metadata": {},
1363
+ "output_type": "execute_result"
1364
+ }
1365
+ ],
1366
+ "source": [
1367
+ "filtered_rows = sentence_bench[sentence_bench['dataset'] == 'polyphone'][['grapheme', 'phoneme', 'homograph word',\t'pronunciation']]\n",
1368
+ "\n",
1369
+ "# Convert to a list of tuples\n",
1370
+ "ambiguous_evaluation_data = list(filtered_rows.itertuples(index=False, name=None))\n",
1371
+ "\n",
1372
+ "ambiguous_evaluation_data[:3]"
1373
+ ]
1374
+ },
1375
+ {
1376
+ "cell_type": "markdown",
1377
+ "metadata": {
1378
+ "id": "R6PE5ds45TPr"
1379
+ },
1380
+ "source": [
1381
+ "# Evaluate Method Outputs"
1382
+ ]
1383
+ },
1384
+ {
1385
+ "cell_type": "markdown",
1386
+ "metadata": {
1387
+ "id": "y73zFlRGIbt9"
1388
+ },
1389
+ "source": [
1390
+ "## PER Evaluation"
1391
+ ]
1392
+ },
1393
+ {
1394
+ "cell_type": "code",
1395
+ "execution_count": 30,
1396
+ "metadata": {
1397
+ "id": "ItuviO3w5Vzv"
1398
+ },
1399
+ "outputs": [],
1400
+ "source": [
1401
+ "def remove_non_word_chars(text):\n",
1402
+ " pattern = r'[^\\w\\s\\?]'\n",
1403
+ " cleaned_text = re.sub(pattern, ' ', text)\n",
1404
+ " return cleaned_text"
1405
+ ]
1406
+ },
1407
+ {
1408
+ "cell_type": "code",
1409
+ "execution_count": 31,
1410
+ "metadata": {
1411
+ "id": "syQCurXu51TO"
1412
+ },
1413
+ "outputs": [],
1414
+ "source": [
1415
+ "def remove_white_spaces(text):\n",
1416
+ " cleaned_text = re.sub(r'\\s+', ' ', text)\n",
1417
+ " return cleaned_text.strip()"
1418
+ ]
1419
+ },
1420
+ {
1421
+ "cell_type": "code",
1422
+ "execution_count": 32,
1423
+ "metadata": {
1424
+ "id": "V7APkVM053RP"
1425
+ },
1426
+ "outputs": [],
1427
+ "source": [
1428
+ "def get_word_only_text(text):\n",
1429
+ " word_only_text = remove_non_word_chars(text)\n",
1430
+ " extra_space_removed_text = remove_white_spaces(word_only_text)\n",
1431
+ "\n",
1432
+ " return extra_space_removed_text"
1433
+ ]
1434
+ },
1435
+ {
1436
+ "cell_type": "code",
1437
+ "execution_count": 33,
1438
+ "metadata": {
1439
+ "id": "ROomKSao57vy"
1440
+ },
1441
+ "outputs": [],
1442
+ "source": [
1443
+ "def get_texts_cer(reference, model_output):\n",
1444
+ " # Preprocess input texts to only contain word characters\n",
1445
+ " word_only_reference = get_word_only_text(reference)\n",
1446
+ " word_only_output = get_word_only_text(model_output)\n",
1447
+ "\n",
1448
+ " # Return +infinity for CER if any of the texts is empty\n",
1449
+ " if not word_only_reference.strip() or not word_only_output.strip():\n",
1450
+ " return float('inf')\n",
1451
+ "\n",
1452
+ " return cer(word_only_reference, word_only_output)"
1453
+ ]
1454
+ },
1455
+ {
1456
+ "cell_type": "code",
1457
+ "execution_count": 34,
1458
+ "metadata": {
1459
+ "id": "4vHLUjp48hc3"
1460
+ },
1461
+ "outputs": [],
1462
+ "source": [
1463
+ "def get_avg_cer_of_method(method_outputs, references):\n",
1464
+ " cers = []\n",
1465
+ " for idx, o in enumerate(method_outputs):\n",
1466
+ " cer = get_texts_cer(o, references[idx][1].replace('-', ''))\n",
1467
+ " if cer != float('inf'):\n",
1468
+ " cers.append(cer)\n",
1469
+ "\n",
1470
+ " return sum(cers) / len(cers)"
1471
+ ]
1472
+ },
1473
+ {
1474
+ "cell_type": "markdown",
1475
+ "metadata": {
1476
+ "id": "f4NqCjr1FxVg"
1477
+ },
1478
+ "source": [
1479
+ "## Ezafe Evaluation"
1480
+ ]
1481
+ },
1482
+ {
1483
+ "cell_type": "code",
1484
+ "execution_count": 35,
1485
+ "metadata": {
1486
+ "id": "Fn1IjihOEDEF"
1487
+ },
1488
+ "outputs": [],
1489
+ "source": [
1490
+ "def get_EZ_words_from_ground_truth(text):\n",
1491
+ " pattern = r'\\b(\\w+)(-e|-ye)\\b'\n",
1492
+ " matches = re.findall(pattern, text,)\n",
1493
+ "\n",
1494
+ " # Extract the words along with the suffix\n",
1495
+ " words_with_suffix = [match[0] + match[1] for match in matches]\n",
1496
+ " EZ_words = [tuple(re.split(r'(?=-)', w)) for w in words_with_suffix]\n",
1497
+ "\n",
1498
+ " return EZ_words"
1499
+ ]
1500
+ },
1501
+ {
1502
+ "cell_type": "code",
1503
+ "execution_count": 36,
1504
+ "metadata": {
1505
+ "id": "xiEKlZjV2OMC"
1506
+ },
1507
+ "outputs": [],
1508
+ "source": [
1509
+ "def get_EZ_words_from_phonetic_model_output(text):\n",
1510
+ " EZ_words = re.findall(r'\\b(\\w+)(-e|-ye)', text)\n",
1511
+ " EZ_word_candidates = []\n",
1512
+ "\n",
1513
+ " other_words = re.findall(r'\\b(\\w+)(?=(?:[^-\\w]|$))', text)\n",
1514
+ " for word in other_words:\n",
1515
+ " if len(word) >= 4 and word[-3] in 'еeiuoaāäâāɒáA' and word.endswith('ye') and word_in_dict(word[:-2], inverted_merged_dict) and not word_in_dict(word, inverted_merged_dict) and not word_in_dict(word[:-1], inverted_merged_dict):\n",
1516
+ " EZ_words.append((word[:-2], '-ye'))\n",
1517
+ " continue\n",
1518
+ "\n",
1519
+ " if len(word) >= 3 and word.endswith('e') and word_in_dict(word[:-1], inverted_merged_dict) and not word_in_dict(word, inverted_merged_dict):\n",
1520
+ " EZ_words.append((word[:-1], '-e'))\n",
1521
+ " continue\n",
1522
+ "\n",
1523
+ " if len(word) >= 4 and word[-3] in 'еeiuoaāäâāɒáA' and word.endswith('ye'):\n",
1524
+ " EZ_word_candidates.append((word[:-2], '-ye'))\n",
1525
+ " continue\n",
1526
+ "\n",
1527
+ " if len(word) >= 3 and word.endswith('e'):\n",
1528
+ " EZ_word_candidates.append((word[:-1], '-e'))\n",
1529
+ "\n",
1530
+ " return EZ_words, EZ_word_candidates"
1531
+ ]
1532
+ },
1533
+ {
1534
+ "cell_type": "code",
1535
+ "execution_count": 37,
1536
+ "metadata": {
1537
+ "id": "PFkBeD262OMD"
1538
+ },
1539
+ "outputs": [],
1540
+ "source": [
1541
+ "def get_phonetic_model_TP_FP_TN_FN(gt_finglish, model_finglish):\n",
1542
+ " gt_word_count = len(re.findall(r'\\b\\w+(?:-\\w+)*\\b', gt_finglish))\n",
1543
+ " gt_EZ_words = get_EZ_words_from_ground_truth(gt_finglish)\n",
1544
+ "\n",
1545
+ " model_EZ_words, model_candidate_EZ_words = get_EZ_words_from_phonetic_model_output(model_finglish)\n",
1546
+ "\n",
1547
+ " TP = 0\n",
1548
+ " FP = 0\n",
1549
+ " TN = 0\n",
1550
+ " FN = 0\n",
1551
+ "\n",
1552
+ " gt_matched_indices = set()\n",
1553
+ " model_matched_indices = set()\n",
1554
+ " model_candidate_matched_indices = set()\n",
1555
+ "\n",
1556
+ " for gt_idx, (word, EZ) in enumerate(gt_EZ_words):\n",
1557
+ " for model_idx, (w, E) in enumerate(model_EZ_words):\n",
1558
+ " if model_idx not in model_matched_indices and SequenceMatcher(None, word, w).ratio() > 0.65:\n",
1559
+ " TP += 1\n",
1560
+ " gt_matched_indices.add(gt_idx)\n",
1561
+ " model_matched_indices.add(model_idx)\n",
1562
+ " break\n",
1563
+ " else:\n",
1564
+ " for model_c_idx, (w, E) in enumerate(model_candidate_EZ_words):\n",
1565
+ " if model_c_idx not in model_candidate_matched_indices and SequenceMatcher(None, word, w).ratio() > 0.65:\n",
1566
+ " TP += 1\n",
1567
+ " gt_matched_indices.add(gt_idx)\n",
1568
+ " model_candidate_matched_indices.add(model_c_idx)\n",
1569
+ " break\n",
1570
+ "\n",
1571
+ " # Calculate FP: model_EZ_words that are not TP\n",
1572
+ " FP = len(model_EZ_words) - (TP - len(list(model_candidate_matched_indices)))\n",
1573
+ "\n",
1574
+ " # Calculate FN: gt_EZ_words that were not detected\n",
1575
+ " FN = len(gt_EZ_words) - TP\n",
1576
+ "\n",
1577
+ " # Calculate TN: non-Ezafe words that are correctly not detected as Ezafe\n",
1578
+ " TN = (gt_word_count - len(gt_EZ_words)) - FP\n",
1579
+ "\n",
1580
+ " return TP, FP, TN, FN\n"
1581
+ ]
1582
+ },
1583
+ {
1584
+ "cell_type": "code",
1585
+ "execution_count": 38,
1586
+ "metadata": {
1587
+ "id": "cbW4otNyIQLh"
1588
+ },
1589
+ "outputs": [],
1590
+ "source": [
1591
+ "def get_phonetic_model_performance(outputs, references):\n",
1592
+ " total_TP, total_FP, total_TN, total_FN = 0, 0, 0, 0\n",
1593
+ "\n",
1594
+ " for idx, o in enumerate(outputs):\n",
1595
+ " TP, FP, TN, FN = get_phonetic_model_TP_FP_TN_FN(references[idx][1], o)\n",
1596
+ " total_TP += TP\n",
1597
+ " total_FP += FP\n",
1598
+ " total_TN += TN\n",
1599
+ " total_FN += FN\n",
1600
+ "\n",
1601
+ "\n",
1602
+ " total_model_EZ = total_TP + total_FP\n",
1603
+ " total_gt_EZ = total_TP + total_FN\n",
1604
+ "\n",
1605
+ " total_model_T = total_TP + total_TN\n",
1606
+ "\n",
1607
+ " total_gt_words = total_TP + total_TN + total_FP + total_FN\n",
1608
+ "\n",
1609
+ " accuracy = (total_model_T) / (total_gt_words) * 100\n",
1610
+ " precision = (total_TP) / (total_model_EZ) * 100\n",
1611
+ " recall = (total_TP) / (total_gt_EZ) * 100\n",
1612
+ "\n",
1613
+ " return accuracy, precision, recall"
1614
+ ]
1615
+ },
1616
+ {
1617
+ "cell_type": "markdown",
1618
+ "metadata": {
1619
+ "id": "oBgNtpFQDwku"
1620
+ },
1621
+ "source": [
1622
+ "## Polyphone Evaluation"
1623
+ ]
1624
+ },
1625
+ {
1626
+ "cell_type": "code",
1627
+ "execution_count": 39,
1628
+ "metadata": {
1629
+ "id": "J445ULEvEEDn"
1630
+ },
1631
+ "outputs": [],
1632
+ "source": [
1633
+ "def get_polyphone_performance(outputs, references):\n",
1634
+ " corrects = 0\n",
1635
+ " total = 0\n",
1636
+ "\n",
1637
+ " for idx, (g, p, polyphone, right) in enumerate(references):\n",
1638
+ " if polyphone != '':\n",
1639
+ " total += 1\n",
1640
+ " if right in outputs[idx]:\n",
1641
+ " corrects += 1\n",
1642
+ " else:\n",
1643
+ " print(f\"Out: {outputs[idx]}\\nRef: {p}\")\n",
1644
+ "\n",
1645
+ " return corrects / total"
1646
+ ]
1647
+ },
1648
+ {
1649
+ "cell_type": "markdown",
1650
+ "metadata": {
1651
+ "id": "JGEUIrbi9kNH"
1652
+ },
1653
+ "source": [
1654
+ "# Full bench"
1655
+ ]
1656
+ },
1657
+ {
1658
+ "cell_type": "code",
1659
+ "execution_count": 40,
1660
+ "metadata": {
1661
+ "id": "fGzQvL8V9mln"
1662
+ },
1663
+ "outputs": [],
1664
+ "source": [
1665
+ "benchmark = []\n",
1666
+ "\n",
1667
+ "for g, p in mana_evaluation_data:\n",
1668
+ " benchmark.append((g, p, '', ''))\n",
1669
+ "\n",
1670
+ "for g, p in commonvoice_evaluation_data:\n",
1671
+ " benchmark.append((g, p, '', ''))\n",
1672
+ "\n",
1673
+ "for g, p, w, r in ambiguous_evaluation_data:\n",
1674
+ " benchmark.append((g, p, w, r))\n",
1675
+ "\n",
1676
+ "benchmark = benchmark[:400]"
1677
+ ]
1678
+ },
1679
+ {
1680
+ "cell_type": "code",
1681
+ "execution_count": 41,
1682
+ "metadata": {
1683
+ "id": "4jlXFt8tCPWB"
1684
+ },
1685
+ "outputs": [],
1686
+ "source": [
1687
+ "def print_all_metrics(predictions):\n",
1688
+ " per = get_avg_cer_of_method(predictions, benchmark) * 100\n",
1689
+ " acc, prec, recall = get_phonetic_model_performance(predictions, benchmark)\n",
1690
+ " polyphone = get_polyphone_performance(predictions, benchmark) * 100\n",
1691
+ "\n",
1692
+ " print(f\"PER: \\t\\t\\t{per:.2f}\")\n",
1693
+ " print(f\"ACC, PREC, RECALL, F1: \\t{acc:.2f}, {prec:.2f}, {recall:.2f}, {((2 * prec * recall) / (prec + recall)):.2f}\")\n",
1694
+ " print(f\"POLYPHONE: \\t\\t{polyphone:.2f}\")"
1695
+ ]
1696
+ },
1697
+ {
1698
+ "cell_type": "markdown",
1699
+ "metadata": {
1700
+ "id": "fTRgGM_8_Fwg"
1701
+ },
1702
+ "source": [
1703
+ "# Inference"
1704
+ ]
1705
+ },
1706
+ {
1707
+ "cell_type": "code",
1708
+ "execution_count": 42,
1709
+ "metadata": {
1710
+ "id": "17lrgWh__Mzr"
1711
+ },
1712
+ "outputs": [],
1713
+ "source": [
1714
+ "graphemes = [item[0] for item in benchmark]"
1715
+ ]
1716
+ },
1717
+ {
1718
+ "cell_type": "code",
1719
+ "execution_count": 43,
1720
+ "metadata": {
1721
+ "id": "ajqTWtNb_HBd"
1722
+ },
1723
+ "outputs": [],
1724
+ "source": [
1725
+ "outputs = g2p.generate(graphemes, use_rules=True)"
1726
+ ]
1727
+ },
1728
+ {
1729
+ "cell_type": "markdown",
1730
+ "metadata": {
1731
+ "id": "jPXWBZ4R_bGs"
1732
+ },
1733
+ "source": [
1734
+ "# Mapping"
1735
+ ]
1736
+ },
1737
+ {
1738
+ "cell_type": "code",
1739
+ "execution_count": 44,
1740
+ "metadata": {
1741
+ "colab": {
1742
+ "base_uri": "https://localhost:8080/"
1743
+ },
1744
+ "id": "g3Etdbv2_dMF",
1745
+ "outputId": "0e8c3f99-4342-4adb-c5d0-0b4e2e803c03"
1746
+ },
1747
+ "outputs": [
1748
+ {
1749
+ "name": "stdout",
1750
+ "output_type": "stream",
1751
+ "text": [
1752
+ "{'k', '$', '/', 'l', 'f', '1', 'g', ';', 'e', 'x', ' ', 'z', 'o', '@', 'a', 'b', 's', 'p', 'h', 'd', 'j', 'c', 'v', 'r', 'm', 'n', 'y', 't', 'u', 'i', 'q'}\n"
1753
+ ]
1754
+ }
1755
+ ],
1756
+ "source": [
1757
+ "print(set(''.join(outputs)))"
1758
+ ]
1759
+ },
1760
+ {
1761
+ "cell_type": "code",
1762
+ "execution_count": 45,
1763
+ "metadata": {
1764
+ "id": "c8C2sJjJA4na"
1765
+ },
1766
+ "outputs": [],
1767
+ "source": [
1768
+ "# Define the replacements\n",
1769
+ "replacements = {\n",
1770
+ " 'a': 'A',\n",
1771
+ " '$': 'S',\n",
1772
+ " '/': 'a',\n",
1773
+ " '1': '',\n",
1774
+ " ';': 'Z',\n",
1775
+ " '@': '?',\n",
1776
+ " 'c': 'C'\n",
1777
+ "}\n",
1778
+ "\n",
1779
+ "# Apply replacements\n",
1780
+ "mapped_outputs = [\n",
1781
+ " ''.join(replacements.get(char, char) for char in output)\n",
1782
+ " for output in outputs\n",
1783
+ "]"
1784
+ ]
1785
+ },
1786
+ {
1787
+ "cell_type": "markdown",
1788
+ "metadata": {
1789
+ "id": "JAIAobLFCKCr"
1790
+ },
1791
+ "source": [
1792
+ "# Results"
1793
+ ]
1794
+ },
1795
+ {
1796
+ "cell_type": "code",
1797
+ "execution_count": 46,
1798
+ "metadata": {
1799
+ "colab": {
1800
+ "base_uri": "https://localhost:8080/"
1801
+ },
1802
+ "id": "CEs_TODaAFHO",
1803
+ "outputId": "658b687f-e842-43e7-b8e1-2089d6581872"
1804
+ },
1805
+ "outputs": [
1806
+ {
1807
+ "name": "stdout",
1808
+ "output_type": "stream",
1809
+ "text": [
1810
+ "Out: ?az qazAye ?elAhi beqadr ?elAhi panAh mibaram\n",
1811
+ "Ref: ?az qazAy ?elAhi be qadar-e ?elAhi panAh mi-baram\n",
1812
+ "Out: ?agar be Sahre maro safar koni\n",
1813
+ "Ref: ?agar be Sahr-e marv safar koni\n",
1814
+ "Out: ?az piSe man mero nemitavAnam bA to biyAyam\n",
1815
+ "Ref: ?az piS-e man maro nemi-tavAnam bA to biyAyam\n",
1816
+ "Out: zendegi tabaqe xAsteye digarAn saxt ?ast\n",
1817
+ "Ref: zendegi tebq-e xAste-ye digarAn saxt ?ast\n",
1818
+ "Out: jazr ?o madde daryA padideye ?ajibi ?ast\n",
1819
+ "Ref: jazr va madd-e daryA padide-ye ?ajibi ?ast\n",
1820
+ "Out: mas?olin dar har samt va pasti ke bASand bAyad xedmat konand\n",
1821
+ "Ref: mas?ulin dar har semat va posti ke bASand bAyad xedmat konand\n",
1822
+ "Out: ?engadr zar nazan xaste Sodim\n",
1823
+ "Ref: ?enqadr zer nazan xaste Sodim\n",
1824
+ "Out: qadri darham ?o dinAr nasibaS Sod\n",
1825
+ "Ref: qadri derham va dinAr nasibaS Sod\n",
1826
+ "Out: ?ey meh zibAye man ?AftAb rA xajal kardei\n",
1827
+ "Ref: ?ey mah-e zibAy-e man ?AftAb rA xejel karde-?i\n",
1828
+ "Out: Savi ?u ruze ba?d ?az ?ezdevAj rahlat namud\n",
1829
+ "Ref: Suye ?u ruz-e ba?d ?az ?ezdevAj rehlat nemud\n",
1830
+ "Out: ?agar xoSAl Savi bAyad Sokr begozAri\n",
1831
+ "Ref: ?agar xoShAl Savi bAyad Sokr begozAri\n",
1832
+ "Out: melk va darbAriyAn ?az dar kAxe dAxel Sodand\n",
1833
+ "Ref: malek va darbAriyAn ?az dar-e kAx dAxel Sodand\n",
1834
+ "Out: melke soleymAn ?az bASokuhtarin farvAnravAyihA budeast\n",
1835
+ "Ref: molk-e soleymAn ?az bASokuh-tarin farmAnravAyi-ha hA bude ?ast\n",
1836
+ "Out: hezArAn hur ?o malek dar beheSt dar ?entezAre ?ust\n",
1837
+ "Ref: hezArAn hur va malak dar beheSt dar ?entezAr-e ?ust\n",
1838
+ "Out: ?in bannA qedmate besyAri dArad\n",
1839
+ "Ref: ?in bana qedmat-e besyAri dArad\n",
1840
+ "Out: man mallAkhAye ?ezdevAj rA barAyetAn tozih midaham\n",
1841
+ "Ref: man melAk-hAye ?ezdevAj rA barAye Soma tozih mi-deham\n",
1842
+ "Out: pedarbozorgam xeyli nAgahAni fut kard va ?az piSe mA raft\n",
1843
+ "Ref: pedar-bozorgam xeyli nAgahAni fot kard va ?az piS-e ma raft\n",
1844
+ "Out: yek SalvAr kardi va kafSAye mahalli xarid\n",
1845
+ "Ref: yek SalvAr-e kordi va kafS-hAye mahalli xarid\n",
1846
+ "Out: ?az sennet xejAlat bekeS dige bozorg Sodi\n",
1847
+ "Ref: ?az sennet xejAlat bekeS dige bozorg Sodi\n",
1848
+ "Out: ?ensAnhAye xeyr be bimAran komak kardand\n",
1849
+ "Ref: ?ensAn-hAye xayyer be bimarAn komak kardand\n",
1850
+ "Out: dar ?elme Simi har mAde bAyad bA ?ehtiyAt barresi Savad\n",
1851
+ "Ref: dar ?elme Simi har mAdde bAyad bA ?ehtiyat barresi\n",
1852
+ "Out: hasan xalq yeki ?az fazilathAye moheme ?AdamizAd ?ast\n",
1853
+ "Ref: hosn-e xolq yeki ?az fazilathAye mohemm-e ?AdamizAd ?ast\n",
1854
+ "Out: CeSme ?alAn dasturtAn rA ?etA?at mikonam\n",
1855
+ "Ref: xaSm ?alAn dasturetAn rA ?etA?at mi-konam\n",
1856
+ "Out: meSk ?Ab ?az dastAne ?abbAs bar zamin ?oftAd\n",
1857
+ "Ref: maSk-e ?Ab ?az dAstAn-e ?abbAs bar zamin ?oftAd\n",
1858
+ "Out: meSk ?An ?ast ke xod bebuyad na ?Anke ?attAr beguyad\n",
1859
+ "Ref: moSk ?An ?ast ke xod bebuyad na ?Anke ?attAr beguyad\n",
1860
+ "Out: muhAyaS rA bA bores SAne zad\n",
1861
+ "Ref: mu-hAyaS rA bA bores SAne zad\n",
1862
+ "Out: boro be kArt beres\n",
1863
+ "Ref: boro be kAret beres\n",
1864
+ "Out: heyvAne xAnegiye man diruz dar ?asare garmA bihuS Sod va mard\n",
1865
+ "Ref: heyvAn-e xAnegi-ye man diruz dar ?asar-e garmA bihuS Sod va mord\n",
1866
+ "Out: ?An zan yek mazne lebAs dArad\n",
1867
+ "Ref: ?An zan yek mezon-e lebAs dArad\n",
1868
+ "Out: donbAlehA va serrihA ?az mohemtarin mabAhese riyAzi yek hastand\n",
1869
+ "Ref: donbAle-hA va seri hA ?az moh-em-tarin mabAhes-e riyAzi-ye yek hastand\n",
1870
+ "Out: har saboki ke barAye naqqASi ?entexAb konad\n",
1871
+ "Ref: har sabki ke barAye naqqASi ?entexAb konad\n",
1872
+ "Out: meydAn rA se dure piCid\n",
1873
+ "Ref: meydAn-ra se dor piCid\n",
1874
+ "Out: ?agar ?orze dASt kAri peydA mikard\n",
1875
+ "Ref: ?agar ?orze dASt kAri peydA mi-kard\n",
1876
+ "Out: ?arze va taqAzA hamiSe dar tavAzon hastand\n",
1877
+ "Ref: ?arze va taqAzA hamiSe dar tavAzon hastand\n",
1878
+ "Out: dorAne hole yek mehvare markazi\n",
1879
+ "Ref: davarAn hol-e yek mehvar-e markazi\n",
1880
+ "Out: ?in CAqu hiC Cizi rA nemibarad\n",
1881
+ "Ref: ?in CAqu hiC Cizi rA nemi borad\n",
1882
+ "Out: ?u barAye xAstehAyaS besyAr moserr bud\n",
1883
+ "Ref: ?u barAye xAste-hAyaS besyAr moser bud\n",
1884
+ "Out: tule ?ommol va ?Arezu ?az CizhAyi ?ast ke nahy Sode\n",
1885
+ "Ref: tul-e ?amal va ?Arezu ?az Ciz-hAyi ?ast ke nahy Sode\n",
1886
+ "Out: ?ArAm dar bastareS xeffat\n",
1887
+ "Ref: ?ArAm dar bastaraS xoft\n",
1888
+ "Out: xodro pas ?az barxord Sodid bA divAre ?AtaS gereft\n",
1889
+ "Ref: xodro pas ?az barxord-e Sadid bA divAr ?AtaS gereft\n",
1890
+ "Out: bAzigare qabl ?az vorud be sahneye gerim Sod\n",
1891
+ "Ref: bAzigAr qabl ?az vorud be sahne Gerim Sod\n",
1892
+ "Out: kole ?in xAne rA begardi peydAyeS nemikani\n",
1893
+ "Ref: koll-e ?in xAne rA begardi peydAyaS nemikoni\n",
1894
+ "Out: nAxodA dastur dAd kaStiye lenger begirad\n",
1895
+ "Ref: nAxodA dastur dAd keSti langar beGirad\n",
1896
+ "Out: rume bAstAn tArixe mohemmi dArad\n",
1897
+ "Ref: rum-e bAstAn tArix-e mohemmi dArad\n",
1898
+ "Out: kard va lor va baluC hame ?az ?aqvAme ?irAni hastand\n",
1899
+ "Ref: kord va lor va baluC hame ?az ?aqvAm-e ?irAni hastand\n",
1900
+ "Out: nabAyad ?in kAr rA mikard\n",
1901
+ "Ref: nabAyad ?in kAr rA mi kard\n",
1902
+ "Out: to mesleye nafs dar riyeye mani\n",
1903
+ "Ref: to mesl-e nafas dar riyeye mani\n",
1904
+ "Out: nabarad ?irAn va ?erAqe haSt sAl be tul ?anjAmid\n",
1905
+ "Ref: nabard-e ?irAn va ?arAq haSt sAl be tul ?anjAmid\n",
1906
+ "Out: ?agar bardAreS rA bA xod be dAneSgAh nabord bad miSavad\n",
1907
+ "Ref: ?agar barAdaraS rA bA xod be dAneSgAh nabarad bad mi-Savad\n",
1908
+ "Out: ?az har berand nabAyad lebAs va kafS xarid\n",
1909
+ "Ref: ?az har berand nabAyad lebAs va kafS xarid\n",
1910
+ "Out: kam guy va gazide guye Con dar\n",
1911
+ "Ref: kam guy ?o gozide guy Con dorr\n",
1912
+ "PER: \t\t\t4.28\n",
1913
+ "ACC, PREC, RECALL, F1: \t98.17, 100.00, 86.68, 92.87\n",
1914
+ "POLYPHONE: \t\t75.94\n"
1915
+ ]
1916
+ }
1917
+ ],
1918
+ "source": [
1919
+ "print_all_metrics(mapped_outputs)"
1920
+ ]
1921
+ }
1922
+ ],
1923
+ "metadata": {
1924
+ "colab": {
1925
+ "provenance": []
1926
+ },
1927
+ "gpuClass": "standard",
1928
+ "kernelspec": {
1929
+ "display_name": "venv",
1930
+ "language": "python",
1931
+ "name": "python3"
1932
+ },
1933
+ "language_info": {
1934
+ "codemirror_mode": {
1935
+ "name": "ipython",
1936
+ "version": 3
1937
+ },
1938
+ "file_extension": ".py",
1939
+ "mimetype": "text/x-python",
1940
+ "name": "python",
1941
+ "nbconvert_exporter": "python",
1942
+ "pygments_lexer": "ipython3",
1943
+ "version": "3.10.12"
1944
+ }
1945
+ },
1946
+ "nbformat": 4,
1947
+ "nbformat_minor": 0
1948
+ }
training-scripts/finetune-ge2pe.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import os
3
+ import pandas as pd
4
+ import numpy as np
5
+ import evaluate
6
+ from transformers import AutoTokenizer, T5ForConditionalGeneration, Seq2SeqTrainer, Seq2SeqTrainingArguments
7
+ from dataclasses import dataclass
8
+ from typing import Union, Dict, List
9
+
10
+ import pandas as pd
11
+ import numpy as np
12
+ from datasets import Dataset
13
+ import argparse
14
+ import torch
15
+ import evaluate
16
+
17
+ import os
18
+ from dataclasses import dataclass
19
+ from typing import Union, Dict, List, Optional
20
+ from transformers import AdamW, AutoTokenizer, T5ForConditionalGeneration, T5Config
21
+ from transformers import (
22
+ DataCollator,
23
+ Seq2SeqTrainer,
24
+ Seq2SeqTrainingArguments,
25
+ set_seed,
26
+ )
27
+
28
+
29
+ os.environ["WANDB_DISABLED"] = "true"
30
+
31
+ # %%
32
+ set_seed(41)
33
+
34
+ # %%
35
+ def prepare_dataset(batch):
36
+
37
+ batch['input_ids'] = batch['Grapheme']
38
+ batch['labels'] = batch['Mapped Phoneme']
39
+
40
+ return batch
41
+
42
+ # %%
43
+ # Data collator for padding
44
+ @dataclass
45
+ class DataCollatorWithPadding:
46
+ tokenizer: AutoTokenizer
47
+ padding: Union[bool, str] = True
48
+
49
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
50
+ words = [feature["input_ids"] for feature in features]
51
+ prons = [feature["labels"] for feature in features]
52
+ batch = self.tokenizer(words, padding=self.padding, add_special_tokens=False, return_attention_mask=True, return_tensors='pt')
53
+ pron_batch = self.tokenizer(prons, padding=self.padding, add_special_tokens=True, return_attention_mask=True, return_tensors='pt')
54
+ batch['labels'] = pron_batch['input_ids'].masked_fill(pron_batch.attention_mask.ne(1), -100)
55
+ return batch
56
+
57
+ # %%
58
+ # Compute metrics (CER and WER)
59
+ def compute_metrics(pred):
60
+ labels_ids = pred.label_ids
61
+ pred_ids = pred.predictions
62
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
63
+ labels_ids[labels_ids == -100] = tokenizer.pad_token_id
64
+ label_str = tokenizer.batch_decode(labels_ids, skip_special_tokens=True)
65
+ cer = cer_metric.compute(predictions=pred_str, references=label_str)
66
+ wer = wer_metric.compute(predictions=pred_str, references=label_str)
67
+ return {"cer": cer, 'wer': wer}
68
+
69
+ # setting the evaluation metrics
70
+ cer_metric = evaluate.load("cer")
71
+ wer_metric = evaluate.load('wer')
72
+
73
+ # %% [markdown]
74
+ # # Phase 1
75
+
76
+ # %%
77
+ def load_pronuncation_dictionary(path, train=True, homograph_only=False, human=False) -> Dataset:
78
+ # path = '/media/external_10TB/mahta_fetrat/PersianG2P_final.csv'
79
+
80
+ # Read the CSV file
81
+ df = pd.read_csv(path, index_col=[0])
82
+
83
+ if homograph_only:
84
+ if human:
85
+ df = df[df['Source'] == 'human']
86
+ if not human:
87
+ df = df[df['Source'] != 'human']
88
+
89
+ # Drop unnecessary columns
90
+ df = df.drop(['Source', 'Source ID'], axis=1)
91
+
92
+ # Drop rows where 'Phoneme' is NaN
93
+ df = df.dropna(subset=['Mapped Phoneme'])
94
+
95
+ # Filter rows based on phoneme length
96
+ Plen = np.array([len(i) for i in df['Mapped Phoneme']])
97
+ df = df.iloc[Plen < 512, :]
98
+
99
+ # Filter rows based on 'Homograph Grapheme' column
100
+ if homograph_only:
101
+ df = df[df['Homograph Grapheme'].notna() & (df['Homograph Grapheme'] != '')]
102
+ else:
103
+ df = df[df['Homograph Grapheme'].isna() | (df['Homograph Grapheme'] == '')]
104
+
105
+ # Shuffle the DataFrame
106
+ df = df.sample(frac=1)
107
+
108
+ # Split into train and test sets
109
+ if train:
110
+ return Dataset.from_pandas(df.iloc[:len(df)-90, :])
111
+ else:
112
+ return Dataset.from_pandas(df.iloc[len(df)-90:, :])
113
+
114
+ # %%
115
+ # Load datasets (only rows with 'Homograph Grapheme')
116
+ train_data = load_pronuncation_dictionary('PersianG2P_final.csv', train=True)
117
+ train_data = train_data.map(prepare_dataset)
118
+ train_dataset = train_data
119
+
120
+ dev_data = load_pronuncation_dictionary('PersianG2P_final.csv', train=False)
121
+ dev_data = dev_data.map(prepare_dataset)
122
+ dev_dataset = dev_data
123
+
124
+ # Load tokenizer and model from checkpoint
125
+ checkpoint_path = "checkpoint-320" # Path to your checkpoint
126
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
127
+ model = T5ForConditionalGeneration.from_pretrained(checkpoint_path)
128
+
129
+ # Data collator
130
+ data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
131
+
132
+ # Training arguments (default values)
133
+ training_args = Seq2SeqTrainingArguments(
134
+ output_dir="./phase1-30-ep", # Directory to save the fine-tuned model
135
+ predict_with_generate=True,
136
+ generation_num_beams=5,
137
+ generation_max_length=512,
138
+ evaluation_strategy="steps",
139
+ per_device_train_batch_size=32, # Default batch size
140
+ per_device_eval_batch_size=100, # Default batch size
141
+ num_train_epochs=5, # Fewer epochs for this step
142
+ learning_rate=5e-4, # Default learning rate
143
+ warmup_steps=1000, # Default warmup steps
144
+ logging_steps=1000, # Default logging steps
145
+ save_steps=4000, # Default save steps
146
+ eval_steps=1000, # Default evaluation steps
147
+ save_total_limit=2, # Keep only the last 2 checkpoints
148
+ load_best_model_at_end=True, # Load the best model at the end of training
149
+ fp16=False, # Disable FP16 by default
150
+ )
151
+
152
+ # Trainer
153
+ trainer = Seq2SeqTrainer(
154
+ model=model,
155
+ tokenizer=tokenizer,
156
+ args=training_args,
157
+ compute_metrics=compute_metrics,
158
+ train_dataset=train_dataset,
159
+ eval_dataset=dev_dataset,
160
+ data_collator=data_collator,
161
+ )
162
+
163
+ # Fine-tune the model
164
+ trainer.train()
165
+
166
+ # Save the fine-tuned model
167
+ trainer.save_model("./phase1-30-ep")
168
+
169
+ # %%
170
+ import matplotlib.pyplot as plt
171
+
172
+ # Extract training and validation loss from the log history
173
+ train_loss = []
174
+ val_loss = []
175
+ for log in trainer.state.log_history:
176
+ if "loss" in log:
177
+ train_loss.append(log["loss"])
178
+ if "eval_loss" in log:
179
+ val_loss.append(log["eval_loss"])
180
+
181
+ # Plot the training and validation loss
182
+ plt.figure(figsize=(10, 6))
183
+ plt.plot(train_loss, label="Training Loss", marker="o")
184
+ plt.plot(val_loss, label="Validation Loss", marker="o")
185
+ plt.xlabel("Steps")
186
+ plt.ylabel("Loss")
187
+ plt.title("Training and Validation Loss")
188
+ plt.legend()
189
+ plt.grid()
190
+
191
+ # Save the plot to disk
192
+ plt.savefig("phase1-30-ep.png")
193
+
194
+ # Optionally, close the plot to free up memory
195
+ plt.close()
196
+
197
+ # %% [markdown]
198
+ # Phase 2
199
+
200
+ # %%
201
+ # Load datasets (only rows with 'Homograph Grapheme')
202
+ train_data = load_pronuncation_dictionary('PersianG2P_final.csv',
203
+ train=True,
204
+ homograph_only=True)
205
+ train_data = train_data.map(prepare_dataset)
206
+ train_dataset = train_data
207
+
208
+ dev_data = load_pronuncation_dictionary('PersianG2P_final.csv',
209
+ train=False,
210
+ homograph_only=True)
211
+ dev_data = dev_data.map(prepare_dataset)
212
+ dev_dataset = dev_data
213
+
214
+ # Load tokenizer and model from the previous fine-tuning step
215
+ checkpoint_path = "./phase1-30-ep" # Path to the model from Step 1
216
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
217
+ model = T5ForConditionalGeneration.from_pretrained(checkpoint_path)
218
+
219
+ # Data collator
220
+ data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
221
+
222
+ # Training arguments (default values)
223
+ training_args = Seq2SeqTrainingArguments(
224
+ output_dir="./phase2-30-ep", # Directory to save the final fine-tuned model
225
+ predict_with_generate=True,
226
+ generation_num_beams=5,
227
+ generation_max_length=512,
228
+ evaluation_strategy="steps",
229
+ per_device_train_batch_size=32, # Default batch size
230
+ per_device_eval_batch_size=100, # Default batch size
231
+ num_train_epochs=30, # More epochs for this step
232
+ learning_rate=5e-4, # Lower learning rate for fine-tuning
233
+ warmup_steps=1000, # Default warmup steps
234
+ logging_steps=1000, # Default logging steps
235
+ save_steps=4000, # Default save steps
236
+ eval_steps=1000, # Default evaluation steps
237
+ save_total_limit=2, # Keep only the last 2 checkpoints
238
+ load_best_model_at_end=True, # Load the best model at the end of training
239
+ fp16=False, # Disable FP16 by default
240
+ )
241
+
242
+ # Trainer
243
+ trainer = Seq2SeqTrainer(
244
+ model=model,
245
+ tokenizer=tokenizer,
246
+ args=training_args,
247
+ compute_metrics=compute_metrics,
248
+ train_dataset=train_dataset,
249
+ eval_dataset=dev_dataset,
250
+ data_collator=data_collator,
251
+ )
252
+
253
+ # Fine-tune the model
254
+ trainer.train()
255
+
256
+ # Save the fine-tuned model
257
+ trainer.save_model("./phase2-30-ep")
258
+
259
+
260
+ # %%
261
+ import matplotlib.pyplot as plt
262
+
263
+ # Extract training and validation loss from the log history
264
+ train_loss = []
265
+ val_loss = []
266
+ for log in trainer.state.log_history:
267
+ if "loss" in log:
268
+ train_loss.append(log["loss"])
269
+ if "eval_loss" in log:
270
+ val_loss.append(log["eval_loss"])
271
+
272
+ # Plot the training and validation loss
273
+ plt.figure(figsize=(10, 6))
274
+ plt.plot(train_loss, label="Training Loss", marker="o")
275
+ plt.plot(val_loss, label="Validation Loss", marker="o")
276
+ plt.xlabel("Steps")
277
+ plt.ylabel("Loss")
278
+ plt.title("Training and Validation Loss")
279
+ plt.legend()
280
+ plt.grid()
281
+
282
+ # Save the plot to disk
283
+ plt.savefig("phase2-30-ep.png")
284
+
285
+ # Optionally, close the plot to free up memory
286
+ plt.close()
287
+
288
+ # %% [markdown]
289
+ # # Phase 3
290
+
291
+ # %%
292
+ # Load datasets (only rows with 'Homograph Grapheme')
293
+ train_data = load_pronuncation_dictionary('PersianG2P_final_augmented_final.csv',
294
+ train=True,
295
+ homograph_only=True,
296
+ human=True)
297
+ train_data = train_data.map(prepare_dataset)
298
+ train_dataset = train_data
299
+
300
+ dev_data = load_pronuncation_dictionary('PersianG2P_final_augmented_final.csv',
301
+ train=False,
302
+ homograph_only=True,
303
+ human=True)
304
+ dev_data = dev_data.map(prepare_dataset)
305
+ dev_dataset = dev_data
306
+
307
+ # Load tokenizer and model from the previous fine-tuning step
308
+ checkpoint_path = "./phase2-30-ep" # Path to the model from Step 1
309
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
310
+ model = T5ForConditionalGeneration.from_pretrained(checkpoint_path)
311
+
312
+ # Data collator
313
+ data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
314
+
315
+ # Training arguments (default values)
316
+ training_args = Seq2SeqTrainingArguments(
317
+ output_dir="./phase3-30-ep", # Directory to save the final fine-tuned model
318
+ predict_with_generate=True,
319
+ generation_num_beams=5,
320
+ generation_max_length=512,
321
+ evaluation_strategy="steps",
322
+ per_device_train_batch_size=32, # Default batch size
323
+ per_device_eval_batch_size=100, # Default batch size
324
+ num_train_epochs=50, # More epochs for this step
325
+ learning_rate=5e-4, # Lower learning rate for fine-tuning
326
+ warmup_steps=1000, # Default warmup steps
327
+ logging_steps=1000, # Default logging steps
328
+ save_steps=4000, # Default save steps
329
+ eval_steps=1000, # Default evaluation steps
330
+ save_total_limit=2, # Keep only the last 2 checkpoints
331
+ load_best_model_at_end=True, # Load the best model at the end of training
332
+ fp16=False, # Disable FP16 by default
333
+ )
334
+
335
+ # Trainer
336
+ trainer = Seq2SeqTrainer(
337
+ model=model,
338
+ tokenizer=tokenizer,
339
+ args=training_args,
340
+ compute_metrics=compute_metrics,
341
+ train_dataset=train_dataset,
342
+ eval_dataset=dev_dataset,
343
+ data_collator=data_collator,
344
+ )
345
+
346
+ # Fine-tune the model
347
+ trainer.train()
348
+
349
+ # Save the fine-tuned model
350
+ trainer.save_model("./phase3-30-ep")
351
+
352
+
353
+ # %%
354
+ import matplotlib.pyplot as plt
355
+
356
+ # Extract training and validation loss from the log history
357
+ train_loss = []
358
+ val_loss = []
359
+ for log in trainer.state.log_history:
360
+ if "loss" in log:
361
+ train_loss.append(log["loss"])
362
+ if "eval_loss" in log:
363
+ val_loss.append(log["eval_loss"])
364
+
365
+ # Plot the training and validation loss
366
+ plt.figure(figsize=(10, 6))
367
+ plt.plot(train_loss, label="Training Loss", marker="o")
368
+ plt.plot(val_loss, label="Validation Loss", marker="o")
369
+ plt.xlabel("Steps")
370
+ plt.ylabel("Loss")
371
+ plt.title("Training and Validation Loss")
372
+ plt.legend()
373
+ plt.grid()
374
+
375
+ # Save the plot to disk
376
+ plt.savefig("phase3-30-ep.png")
377
+
378
+ # Optionally, close the plot to free up memory
379
+ plt.close()
380
+
381
+
training-scripts/finetune-t5.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import os
3
+ import pandas as pd
4
+ import numpy as np
5
+ import evaluate
6
+ from transformers import AutoTokenizer, T5ForConditionalGeneration, Seq2SeqTrainer, Seq2SeqTrainingArguments
7
+ from dataclasses import dataclass
8
+ from typing import Union, Dict, List
9
+
10
+ import pandas as pd
11
+ import numpy as np
12
+ from datasets import Dataset
13
+ import argparse
14
+ import torch
15
+ import evaluate
16
+
17
+ import os
18
+ from dataclasses import dataclass
19
+ from typing import Union, Dict, List, Optional
20
+ from transformers import AdamW, AutoTokenizer, T5ForConditionalGeneration, T5Config
21
+ from transformers import (
22
+ DataCollator,
23
+ Seq2SeqTrainer,
24
+ Seq2SeqTrainingArguments,
25
+ set_seed,
26
+ )
27
+
28
+ os.environ["WANDB_DISABLED"] = "true"
29
+
30
+ # %%
31
+ set_seed(41)
32
+
33
+ # %%
34
+ def prepare_dataset(batch):
35
+
36
+ batch['input_ids'] = batch['Grapheme']
37
+ batch['labels'] = batch['Mapped Phoneme']
38
+
39
+ return batch
40
+
41
+ # %%
42
+ # Data collator for padding
43
+ @dataclass
44
+ class DataCollatorWithPadding:
45
+ tokenizer: AutoTokenizer
46
+ padding: Union[bool, str] = True
47
+
48
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
49
+ words = [feature["input_ids"] for feature in features]
50
+ prons = [feature["labels"] for feature in features]
51
+ batch = self.tokenizer(words, padding=self.padding, add_special_tokens=False, return_attention_mask=True, return_tensors='pt')
52
+ pron_batch = self.tokenizer(prons, padding=self.padding, add_special_tokens=True, return_attention_mask=True, return_tensors='pt')
53
+ batch['labels'] = pron_batch['input_ids'].masked_fill(pron_batch.attention_mask.ne(1), -100)
54
+ return batch
55
+
56
+ # %%
57
+ # Compute metrics (CER and WER)
58
+ def compute_metrics(pred):
59
+ labels_ids = pred.label_ids
60
+ pred_ids = pred.predictions
61
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
62
+ labels_ids[labels_ids == -100] = tokenizer.pad_token_id
63
+ label_str = tokenizer.batch_decode(labels_ids, skip_special_tokens=True)
64
+ cer = cer_metric.compute(predictions=pred_str, references=label_str)
65
+ wer = wer_metric.compute(predictions=pred_str, references=label_str)
66
+ return {"cer": cer, 'wer': wer}
67
+
68
+ # setting the evaluation metrics
69
+ cer_metric = evaluate.load("cer")
70
+ wer_metric = evaluate.load('wer')
71
+
72
+ # %% [markdown]
73
+ # # Phase 1
74
+
75
+ # %%
76
+ def load_pronuncation_dictionary(path, train=True, homograph_only=False, human=False) -> Dataset:
77
+ # path = 'PersianG2P_final.csv'
78
+
79
+ # Read the CSV file
80
+ df = pd.read_csv(path, index_col=[0])
81
+
82
+ if homograph_only:
83
+ if human:
84
+ df = df[df['Source'] == 'human']
85
+ if not human:
86
+ df = df[df['Source'] != 'human']
87
+
88
+ # Drop unnecessary columns
89
+ df = df.drop(['Source', 'Source ID'], axis=1)
90
+
91
+ # Drop rows where 'Phoneme' is NaN
92
+ df = df.dropna(subset=['Mapped Phoneme'])
93
+
94
+ # Filter rows based on phoneme length
95
+ Plen = np.array([len(i) for i in df['Mapped Phoneme']])
96
+ df = df.iloc[Plen < 512, :]
97
+
98
+ # Filter rows based on 'Homograph Grapheme' column
99
+ if homograph_only:
100
+ df = df[df['Homograph Grapheme'].notna() & (df['Homograph Grapheme'] != '')]
101
+ else:
102
+ df = df[df['Homograph Grapheme'].isna() | (df['Homograph Grapheme'] == '')]
103
+
104
+ # Shuffle the DataFrame
105
+ df = df.sample(frac=1)
106
+
107
+ # Split into train and test sets
108
+ if train:
109
+ return Dataset.from_pandas(df.iloc[:len(df)-90, :])
110
+ else:
111
+ return Dataset.from_pandas(df.iloc[len(df)-90:, :])
112
+
113
+ # %%
114
+ # Load datasets (only rows with 'Homograph Grapheme')
115
+ train_data = load_pronuncation_dictionary('PersianG2P_final.csv', train=True)
116
+ train_data = train_data.map(prepare_dataset)
117
+ train_dataset = train_data
118
+
119
+ dev_data = load_pronuncation_dictionary('PersianG2P_final.csv', train=False)
120
+ dev_data = dev_data.map(prepare_dataset)
121
+ dev_dataset = dev_data
122
+
123
+ # # Load tokenizer and model from checkpoint
124
+ # checkpoint_path = "checkpoint-320" # Path to your checkpoint
125
+ # tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
126
+ # model = T5ForConditionalGeneration.from_pretrained(checkpoint_path)
127
+ # # Load tokenizer and model from checkpoint
128
+ # checkpoint_path = "checkpoint-320" # Path to your checkpoint
129
+ tokenizer = AutoTokenizer.from_pretrained('google/byt5-small')
130
+ # model = T5ForConditionalGeneration.from_pretrained(checkpoint_path)
131
+
132
+ config = T5Config.from_pretrained('google/byt5-small')
133
+
134
+ config.num_decoder_layers = 2
135
+ config.num_layers = 2
136
+ config.d_kv = 64
137
+ config.d_model = 512
138
+ config.d_ff = 512
139
+
140
+ print('Initializing a ByT5 model...')
141
+ model = T5ForConditionalGeneration(config)
142
+
143
+
144
+ # Data collator
145
+ data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
146
+
147
+ # Training arguments (default values)
148
+ training_args = Seq2SeqTrainingArguments(
149
+ output_dir="./phase1-t5", # Directory to save the fine-tuned model
150
+ predict_with_generate=True,
151
+ generation_num_beams=5,
152
+ generation_max_length=512,
153
+ evaluation_strategy="steps",
154
+ per_device_train_batch_size=32, # Default batch size
155
+ per_device_eval_batch_size=100, # Default batch size
156
+ num_train_epochs=5, # Fewer epochs for this step
157
+ learning_rate=5e-4, # Default learning rate
158
+ warmup_steps=1000, # Default warmup steps
159
+ logging_steps=1000, # Default logging steps
160
+ save_steps=4000, # Default save steps
161
+ eval_steps=1000, # Default evaluation steps
162
+ save_total_limit=2, # Keep only the last 2 checkpoints
163
+ load_best_model_at_end=True, # Load the best model at the end of training
164
+ fp16=False, # Disable FP16 by default
165
+ remove_unused_columns=False,
166
+ )
167
+
168
+ # Trainer
169
+ trainer = Seq2SeqTrainer(
170
+ model=model,
171
+ tokenizer=tokenizer,
172
+ args=training_args,
173
+ compute_metrics=compute_metrics,
174
+ train_dataset=train_dataset,
175
+ eval_dataset=dev_dataset,
176
+ data_collator=data_collator,
177
+ )
178
+
179
+ # Fine-tune the model
180
+ trainer.train()
181
+
182
+ # Save the fine-tuned model
183
+ trainer.save_model("./phase1-t5")
184
+
185
+ # %%
186
+ import matplotlib.pyplot as plt
187
+
188
+ # Extract training and validation loss from the log history
189
+ train_loss = []
190
+ val_loss = []
191
+ for log in trainer.state.log_history:
192
+ if "loss" in log:
193
+ train_loss.append(log["loss"])
194
+ if "eval_loss" in log:
195
+ val_loss.append(log["eval_loss"])
196
+
197
+ # Plot the training and validation loss
198
+ plt.figure(figsize=(10, 6))
199
+ plt.plot(train_loss, label="Training Loss", marker="o")
200
+ plt.plot(val_loss, label="Validation Loss", marker="o")
201
+ plt.xlabel("Steps")
202
+ plt.ylabel("Loss")
203
+ plt.title("Training and Validation Loss")
204
+ plt.legend()
205
+ plt.grid()
206
+
207
+ # Save the plot to disk
208
+ plt.savefig("phase1-t5.png")
209
+
210
+ # Optionally, close the plot to free up memory
211
+ plt.close()
212
+
213
+ # %% [markdown]
214
+ # # Phase 2
215
+
216
+ # %%
217
+ # Load datasets (only rows with 'Homograph Grapheme')
218
+ train_data = load_pronuncation_dictionary('PersianG2P_final.csv',
219
+ train=True,
220
+ homograph_only=True)
221
+ train_data = train_data.map(prepare_dataset)
222
+ train_dataset = train_data
223
+
224
+ dev_data = load_pronuncation_dictionary('PersianG2P_final.csv',
225
+ train=False,
226
+ homograph_only=True)
227
+ dev_data = dev_data.map(prepare_dataset)
228
+ dev_dataset = dev_data
229
+
230
+ # Load tokenizer and model from the previous fine-tuning step
231
+ checkpoint_path = "./phase1-t5" # Path to the model from Step 1
232
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
233
+ model = T5ForConditionalGeneration.from_pretrained(checkpoint_path)
234
+
235
+ # Data collator
236
+ data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
237
+
238
+ # Training arguments (default values)
239
+ training_args = Seq2SeqTrainingArguments(
240
+ output_dir="./phase2-t5", # Directory to save the final fine-tuned model
241
+ predict_with_generate=True,
242
+ generation_num_beams=5,
243
+ generation_max_length=512,
244
+ evaluation_strategy="steps",
245
+ per_device_train_batch_size=32, # Default batch size
246
+ per_device_eval_batch_size=100, # Default batch size
247
+ num_train_epochs=30, # More epochs for this step
248
+ learning_rate=5e-4, # Lower learning rate for fine-tuning
249
+ warmup_steps=1000, # Default warmup steps
250
+ logging_steps=1000, # Default logging steps
251
+ save_steps=4000, # Default save steps
252
+ eval_steps=1000, # Default evaluation steps
253
+ save_total_limit=2, # Keep only the last 2 checkpoints
254
+ load_best_model_at_end=True, # Load the best model at the end of training
255
+ fp16=False, # Disable FP16 by default
256
+ )
257
+
258
+ # Trainer
259
+ trainer = Seq2SeqTrainer(
260
+ model=model,
261
+ tokenizer=tokenizer,
262
+ args=training_args,
263
+ compute_metrics=compute_metrics,
264
+ train_dataset=train_dataset,
265
+ eval_dataset=dev_dataset,
266
+ data_collator=data_collator,
267
+ )
268
+
269
+ # Fine-tune the model
270
+ trainer.train()
271
+
272
+ # Save the fine-tuned model
273
+ trainer.save_model("./phase2-t5")
274
+
275
+
276
+ # %%
277
+ import matplotlib.pyplot as plt
278
+
279
+ # Extract training and validation loss from the log history
280
+ train_loss = []
281
+ val_loss = []
282
+ for log in trainer.state.log_history:
283
+ if "loss" in log:
284
+ train_loss.append(log["loss"])
285
+ if "eval_loss" in log:
286
+ val_loss.append(log["eval_loss"])
287
+
288
+ # Plot the training and validation loss
289
+ plt.figure(figsize=(10, 6))
290
+ plt.plot(train_loss, label="Training Loss", marker="o")
291
+ plt.plot(val_loss, label="Validation Loss", marker="o")
292
+ plt.xlabel("Steps")
293
+ plt.ylabel("Loss")
294
+ plt.title("Training and Validation Loss")
295
+ plt.legend()
296
+ plt.grid()
297
+
298
+ # Save the plot to disk
299
+ plt.savefig("phase2-t5.png")
300
+
301
+ # Optionally, close the plot to free up memory
302
+ plt.close()
303
+
304
+ # %% [markdown]
305
+ # # Phase 3
306
+
307
+ # %%
308
+ # Load datasets (only rows with 'Homograph Grapheme')
309
+ train_data = load_pronuncation_dictionary('PersianG2P_final_augmented_final.csv',
310
+ train=True,
311
+ homograph_only=True,
312
+ human=True)
313
+ train_data = train_data.map(prepare_dataset)
314
+ train_dataset = train_data
315
+
316
+ dev_data = load_pronuncation_dictionary('PersianG2P_final_augmented_final.csv',
317
+ train=False,
318
+ homograph_only=True,
319
+ human=True)
320
+ dev_data = dev_data.map(prepare_dataset)
321
+ dev_dataset = dev_data
322
+
323
+ # Load tokenizer and model from the previous fine-tuning step
324
+ checkpoint_path = "./phase2-t5" # Path to the model from Step 1
325
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
326
+ model = T5ForConditionalGeneration.from_pretrained(checkpoint_path)
327
+
328
+ # Data collator
329
+ data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
330
+
331
+ # Training arguments (default values)
332
+ training_args = Seq2SeqTrainingArguments(
333
+ output_dir="./phase3-t5", # Directory to save the final fine-tuned model
334
+ predict_with_generate=True,
335
+ generation_num_beams=5,
336
+ generation_max_length=512,
337
+ evaluation_strategy="steps",
338
+ per_device_train_batch_size=32, # Default batch size
339
+ per_device_eval_batch_size=100, # Default batch size
340
+ num_train_epochs=50, # More epochs for this step
341
+ learning_rate=5e-4, # Lower learning rate for fine-tuning
342
+ warmup_steps=1000, # Default warmup steps
343
+ logging_steps=1000, # Default logging steps
344
+ save_steps=4000, # Default save steps
345
+ eval_steps=1000, # Default evaluation steps
346
+ save_total_limit=2, # Keep only the last 2 checkpoints
347
+ load_best_model_at_end=True, # Load the best model at the end of training
348
+ fp16=False, # Disable FP16 by default
349
+ )
350
+
351
+ # Trainer
352
+ trainer = Seq2SeqTrainer(
353
+ model=model,
354
+ tokenizer=tokenizer,
355
+ args=training_args,
356
+ compute_metrics=compute_metrics,
357
+ train_dataset=train_dataset,
358
+ eval_dataset=dev_dataset,
359
+ data_collator=data_collator,
360
+ )
361
+
362
+ # Fine-tune the model
363
+ trainer.train()
364
+
365
+ # Save the fine-tuned model
366
+ trainer.save_model("./phase3-t5")
367
+
368
+
369
+ # %%
370
+ import matplotlib.pyplot as plt
371
+
372
+ # Extract training and validation loss from the log history
373
+ train_loss = []
374
+ val_loss = []
375
+ for log in trainer.state.log_history:
376
+ if "loss" in log:
377
+ train_loss.append(log["loss"])
378
+ if "eval_loss" in log:
379
+ val_loss.append(log["eval_loss"])
380
+
381
+ # Plot the training and validation loss
382
+ plt.figure(figsize=(10, 6))
383
+ plt.plot(train_loss, label="Training Loss", marker="o")
384
+ plt.plot(val_loss, label="Validation Loss", marker="o")
385
+ plt.xlabel("Steps")
386
+ plt.ylabel("Loss")
387
+ plt.title("Training and Validation Loss")
388
+ plt.legend()
389
+ plt.grid()
390
+
391
+ # Save the plot to disk
392
+ plt.savefig("phase3-t5.png")
393
+
394
+ # Optionally, close the plot to free up memory
395
+ plt.close()
396
+
397
+