1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948 |
- {
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "ABgLYF9R8viP"
- },
- "source": [
- "# Setup"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "Qs-J5B3ykaYz",
- "outputId": "66f79f0c-f2e3-47b0-fc05-f56416962f0c"
- },
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "/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",
- " from .autonotebook import tqdm as notebook_tqdm\n"
- ]
- }
- ],
- "source": [
- "from GE2PE import GE2PE\n",
- "\n",
- "g2p = GE2PE(model_path='GE2PE/phase3-t5/checkpoint-487100', GPU=True)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "id": "ymcwy5hG9H5l"
- },
- "outputs": [],
- "source": [
- "import pandas as pd\n",
- "import re\n",
- "from jiwer import cer\n",
- "from difflib import SequenceMatcher"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "EOZGZa2lMfPe"
- },
- "source": [
- "# Setup POSTagger"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "8TJZ2DrKMg7F",
- "outputId": "c2597cbc-6d60-40c7-e246-983b9eaf8437"
- },
- "outputs": [],
- "source": [
- "# ! git clone https://huggingface.co/roshan-research/spacy_pos_tagger_parsbertpostagger"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {
- "id": "pCiJ-VnfMiwj"
- },
- "outputs": [],
- "source": [
- "import spacy\n",
- "# spacy.require_gpu()\n",
- "\"\"\"این ماژول شامل کلاسها و توابعی برای برچسبگذاری توکنهاست.\"\"\"\n",
- "\n",
- "from nltk.tag import stanford # noqa: I001\n",
- "from hazm import SequenceTagger\n",
- "\n",
- "import os\n",
- "import subprocess\n",
- "\n",
- "from spacy.tokens import Doc\n",
- "from spacy.tokens import DocBin\n",
- "from spacy.vocab import Vocab\n",
- "\n",
- "from sklearn.metrics import classification_report,f1_score,accuracy_score,precision_score,recall_score\n",
- "\n",
- "from tqdm import tqdm\n",
- "\n",
- "\n",
- "punctuation_list = [\n",
- " '\"',\n",
- " \"#\",\n",
- " \"(\",\n",
- " \")\",\n",
- " \"*\",\n",
- " \",\",\n",
- " \"-\",\n",
- " \".\",\n",
- " \"/\",\n",
- " \":\",\n",
- " \"[\",\n",
- " \"]\",\n",
- " \"«\",\n",
- " \"»\",\n",
- " \"،\",\n",
- " \";\",\n",
- " \"?\",\n",
- " \"!\",\n",
- "]\n",
- "\n",
- "\n",
- "class POSTagger(SequenceTagger):\n",
- " \"\"\"این کلاسها شامل توابعی برای برچسبگذاری توکنهاست.\"\"\"\n",
- "\n",
- " def __init__(\n",
- " self: \"POSTagger\", model=None, data_maker=None, universal_tag=False,\n",
- " ) -> None:\n",
- " data_maker = self.data_maker if data_maker is None else data_maker\n",
- " self.__is_universal = universal_tag\n",
- " super().__init__(model, data_maker)\n",
- "\n",
- " def __universal_converter(self: \"POSTagger\", tagged_list):\n",
- " return [(word, tag.split(\",\")[0]) for word, tag in tagged_list]\n",
- "\n",
- " def __is_punc(self: \"POSTagger\", word):\n",
- " return word in punctuation_list\n",
- "\n",
- " def data_maker(self: \"POSTagger\", tokens):\n",
- " \"\"\"تابعی که لیستی از لیستی از کلمات توکنایز شده را گرفته و لیست دو بعدی از از دیکشنریهایی که تعیینکننده ویژگیها هر کلمه هستند را برمیگرداند.\n",
- "\n",
- " Examples:\n",
- " >>> posTagger = POSTagger(model = 'pos_tagger.model')\n",
- " >>> posTagger.data_maker(tokens = [['دلم', 'اینجا', 'ماندهاست', '.']])\n",
- " [[{'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",
- "\n",
- " Args:\n",
- " tokens (List[List[str]]): جملاتی که نیاز به تبدیل آن به برداری از ویژگیها است.\n",
- "\n",
- " Returns:\n",
- " List(List(Dict())): لیستی از لیستی از دیکشنریهای بیانکننده ویژگیهای یک کلمه.\n",
- " \"\"\"\n",
- " return [\n",
- " [self.features(token, index) for index in range(len(token))]\n",
- " for token in tokens\n",
- " ]\n",
- "\n",
- " def features(self: \"POSTagger\", sentence, index):\n",
- " \"\"\"features.\"\"\"\n",
- " return {\n",
- " \"word\": sentence[index],\n",
- " \"is_first\": index == 0,\n",
- " \"is_last\": index == len(sentence) - 1,\n",
- " # *ix\n",
- " \"prefix-1\": sentence[index][0],\n",
- " \"prefix-2\": sentence[index][:2],\n",
- " \"prefix-3\": sentence[index][:3],\n",
- " \"suffix-1\": sentence[index][-1],\n",
- " \"suffix-2\": sentence[index][-2:],\n",
- " \"suffix-3\": sentence[index][-3:],\n",
- " # word\n",
- " \"prev_word\": \"\" if index == 0 else sentence[index - 1],\n",
- " \"two_prev_word\": \"\" if index == 0 else sentence[index - 2],\n",
- " \"next_word\": \"\" if index == len(sentence) - 1 else sentence[index + 1],\n",
- " \"two_next_word\": (\n",
- " \"\"\n",
- " if index in {len(sentence) - 1, len(sentence) - 2}\n",
- " else sentence[index + 2]\n",
- " ),\n",
- " # digit\n",
- " \"is_numeric\": sentence[index].isdigit(),\n",
- " \"prev_is_numeric\": \"\" if index == 0 else sentence[index - 1].isdigit(),\n",
- " \"next_is_numeric\": (\n",
- " \"\" if index == len(sentence) - 1 else sentence[index + 1].isdigit()\n",
- " ),\n",
- " # punc\n",
- " \"is_punc\": self.__is_punc(sentence[index]),\n",
- " \"prev_is_punc\": \"\" if index == 0 else self.__is_punc(sentence[index - 1]),\n",
- " \"next_is_punc\": (\n",
- " \"\"\n",
- " if index == len(sentence) - 1\n",
- " else self.__is_punc(sentence[index + 1])\n",
- " ),\n",
- " }\n",
- "\n",
- " def tag(self: \"POSTagger\", tokens):\n",
- " \"\"\"یک جمله را در قالب لیستی از توکنها دریافت میکند و در خروجی لیستی از\n",
- " `(توکن، برچسب)`ها برمیگرداند.\n",
- "\n",
- " Examples:\n",
- " >>> posTagger = POSTagger(model = 'pos_tagger.model')\n",
- " >>> posTagger.tag(tokens = ['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.'])\n",
- " [('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN,EZ'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]\n",
- "\n",
- " >>> posTagger = POSTagger(model = 'pos_tagger.model', universal_tag = True)\n",
- " >>> posTagger.tag(tokens = ['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.'])\n",
- " [('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]\n",
- "\n",
- " Args:\n",
- " tokens (List[str]): لیستی از توکنهای یک جمله که باید برچسبگذاری شود.\n",
- "\n",
- " Returns:\n",
- " (List[Tuple[str,str]]): لیستی از `(توکن، برچسب)`ها.\n",
- "\n",
- " \"\"\"\n",
- " tagged_token = super().tag(tokens)\n",
- " return (\n",
- " self.__universal_converter(tagged_token)\n",
- " if self.__is_universal\n",
- " else tagged_token\n",
- " )\n",
- "\n",
- " def tag_sents(self: \"POSTagger\", sentences):\n",
- " \"\"\"جملات را در قالب لیستی از توکنها دریافت میکند\n",
- " و در خروجی، لیستی از لیستی از `(توکن، برچسب)`ها برمیگرداند.\n",
- "\n",
- " هر لیست از `(توکن، برچسب)`ها مربوط به یک جمله است.\n",
- "\n",
- " Examples:\n",
- " >>> posTagger = POSTagger(model = 'pos_tagger.model')\n",
- " >>> posTagger.tag_sents(sentences = [['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.']])\n",
- " [[('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN,EZ'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]]\n",
- "\n",
- " >>> posTagger = POSTagger(model = 'pos_tagger.model', universal_tag = True)\n",
- " >>> posTagger.tag_sents(sentences = [['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.']])\n",
- " [[('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]]\n",
- "\n",
- " Args:\n",
- " sentences (List[List[str]]): لیستی از جملات که باید برچسبگذاری شود.\n",
- "\n",
- " Returns:\n",
- " (List[List[Tuple[str,str]]]): لیستی از لیستی از `(توکن، برچسب)`ها.\n",
- " هر لیست از `(توکن،برچسب)`ها مربوط به یک جمله است.\n",
- "\n",
- " \"\"\"\n",
- " tagged_sents = super().tag_sents(sentences)\n",
- " return (\n",
- " [self.__universal_converter(tagged_sent) for tagged_sent in tagged_sents]\n",
- " if self.__is_universal\n",
- " else tagged_sents\n",
- " )\n",
- "\n",
- "\n",
- "class StanfordPOSTagger(stanford.StanfordPOSTagger):\n",
- " \"\"\"StanfordPOSTagger.\"\"\"\n",
- "\n",
- " def __init__(\n",
- " self: \"StanfordPOSTagger\",\n",
- " model_filename: \"str\",\n",
- " path_to_jar: str,\n",
- " *args, # noqa: ANN002\n",
- " **kwargs, # noqa: ANN003\n",
- " ) -> None:\n",
- " self._SEPARATOR = \"/\"\n",
- " super(stanford.StanfordPOSTagger, self).__init__(\n",
- " model_filename=model_filename,\n",
- " path_to_jar=path_to_jar,\n",
- " *args, # noqa: B026\n",
- " **kwargs,\n",
- " )\n",
- "\n",
- " def tag(self: \"StanfordPOSTagger\", tokens):\n",
- " \"\"\"tag.\n",
- "\n",
- " Examples:\n",
- " >>> tagger = StanfordPOSTagger(model_filename='persian.tagger', path_to_jar='stanford_postagger.jar')\n",
- " >>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])\n",
- " [('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]\n",
- "\n",
- " \"\"\"\n",
- " return self.tag_sents([tokens])[0]\n",
- "\n",
- " def tag_sents(self: \"StanfordPOSTagger\", sentences):\n",
- " \"\"\"tag_sents.\"\"\"\n",
- " refined = ([w.replace(\" \", \"_\") for w in s] for s in sentences)\n",
- " return super(stanford.StanfordPOSTagger, self).tag_sents(refined)\n",
- "\n",
- "\n",
- "class SpacyPOSTagger(POSTagger):\n",
- " def __init__(\n",
- " self: \"SpacyPOSTagger\",\n",
- " model_path=None,\n",
- " using_gpu=False,\n",
- " gpu_id=0\n",
- " ):\n",
- " \"\"\"\n",
- " Initialize the SpacyPOSTagger with a model and data paths.\n",
- "\n",
- " Args:\n",
- " - model_path: Path to a pre-trained spaCy model.\n",
- " - test_dataset: Test dataset for evaluation. It has a similar structure to the training dataset.\n",
- " - test_directory: Directory to save the test data in spaCy format.\n",
- " - 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",
- " This constructor calls the constructor of the parent class POSTagger.\n",
- " \"\"\"\n",
- " super().__init__(universal_tag=True)\n",
- " 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",
- " self.using_gpu = using_gpu\n",
- " self.gpu_id = gpu_id\n",
- " self.tagger = None\n",
- " self._setup()\n",
- "\n",
- " def _setup(self: \"SpacyPOSTagger\"):\n",
- " \"\"\"\n",
- " Set up the configuration for the spaCy model, including GPU settings and data preparation.\n",
- "\n",
- " This function initializes and configures the spaCy model, checks for GPU availability, and prepares the training and testing datasets in spaCy format.\n",
- "\n",
- " 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",
- "\n",
- " Training and testing datasets are prepared and saved in the respective directories for use during model training and evaluation.\n",
- " \"\"\" # noqa: D212\n",
- " if self.using_gpu:\n",
- " self._setup_gpu()\n",
- " else:\n",
- " print(\"------------- You Prefer to use CPU --------------\")\n",
- "\n",
- "\n",
- " def _setup_model(self: \"SpacyPOSTagger\",sents):\n",
- " \"\"\"\n",
- " Initialize and configure the spaCy model for tagging without GPU settings.\n",
- "\n",
- " 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",
- "\n",
- " Args:\n",
- " - model_path: Path to the pre-trained spaCy model.\n",
- "\n",
- " This method is typically called during setup to prepare the model for tagging tasks.\n",
- " \"\"\"\n",
- " self.peykare_dict = {} # Initialize a dictionary for reference\n",
- " self.tagger = spacy.load(self.model_path) # Load the spaCy model\n",
- " self._set_peykare_dictionary(sents) # Construct a reference dictionary\n",
- " self.tagger.tokenizer = self._custom_tokenizer # Set a custom tokenizer for the model.\n",
- "\n",
- " def _setup_gpu(self: \"SpacyPOSTagger\"):\n",
- " \"\"\"\n",
- " Check GPU availability and configure spaCy to use it if possible.\n",
- "\n",
- " 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",
- "\n",
- " This check is performed during setup to make use of available GPU resources for enhanced performance.\n",
- " \"\"\"\n",
- " print(\"------------------ GPU Setup Process Started ---------------------\")\n",
- " gpu_available = spacy.prefer_gpu(gpu_id=self.gpu_id) # Check if a GPU is available\n",
- " if gpu_available:\n",
- " print(\"------------ GPU is available and ready for use -------------\")\n",
- " spacy.require_gpu(gpu_id=self.gpu_id) # Configure spaCy to use the GPU\n",
- " self.gpu_availability = True\n",
- " else:\n",
- " print(\"------------ GPU is not available; spaCy will use CPU -------------\")\n",
- " self.gpu_availability = False\n",
- "\n",
- "\n",
- " def _setup_dataset(self: \"SpacyPOSTagger\", dataset,saved_directory,data_type='train'):\n",
- " \"\"\"\n",
- " Setup the training dataset in spaCy's binary format.\n",
- "\n",
- " This function prepares the training dataset and saves it in spaCy's binary format.\n",
- " \"\"\"\n",
- " assert data_type in ['train','test']\n",
- " db = DocBin()\n",
- " for sent in tqdm(dataset):\n",
- " words = [word[0] for word in sent]\n",
- " tags = [word[1] for word in sent]\n",
- " doc = Doc(Vocab(strings=words), words=words)\n",
- " for d, tag in zip(doc, tags):\n",
- " d.tag_ = tag\n",
- " db.add(doc)\n",
- "\n",
- " self._handle_data_path(saved_directory)\n",
- " db.to_disk(f'{saved_directory}/{data_type}.spacy')\n",
- "\n",
- " def _handle_data_path(self,path='POSTaggerDataset'):\n",
- " \"\"\"\n",
- " Create the directory if it doesn't exist.\n",
- "\n",
- " This method checks if the specified directory exists, and if not, it creates the directory to store the data.\n",
- "\n",
- " Args:\n",
- " - path: The path to the directory (default is 'POSTaggerDataset').\n",
- "\n",
- " This method is called to ensure the directory is available for saving processed data.\n",
- " \"\"\"\n",
- " if not os.path.exists(path):\n",
- " os.makedirs(path)\n",
- "\n",
- "\n",
- " def _custom_tokenizer(self: \"SpacyPOSTagger\", text):\n",
- " \"\"\"\n",
- " Implement a custom tokenization method for spaCy.\n",
- "\n",
- " 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",
- "\n",
- " Args:\n",
- " - text: The input text to be tokenized.\n",
- "\n",
- " This custom tokenization method is used by the spaCy model during processing.\n",
- "\n",
- " \"\"\"\n",
- "\n",
- " if text in self.peykare_dict:\n",
- " return Doc(self.tagger.vocab, self.peykare_dict[text])\n",
- " else:\n",
- " raise ValueError('No tokenization available for input.')\n",
- "\n",
- " def _set_peykare_dictionary(self: \"SpacyPOSTagger\", sents):\n",
- " \"\"\"\n",
- " Create a dictionary for custom tokenization.\n",
- "\n",
- " This method constructs a dictionary to store custom tokenization mappings based on input sentences. It is used for custom tokenization in spaCy.\n",
- "\n",
- " Args:\n",
- " - sents: Input sentences to build the custom tokenization dictionary.\n",
- "\n",
- " This method is called during setup to establish a dictionary for tokenization.\n",
- " \"\"\"\n",
- " self.peykare_dict = {' '.join([w for w in item]): [w for w in item] for item in sents}\n",
- "\n",
- "\n",
- " def _add_to_dict(self: \"SpacyPOSTagger\", sents):\n",
- " \"\"\"\n",
- " Add the sentences to dictianory if it doesnt exist already\n",
- " \"\"\"\n",
- " for sent in sents:\n",
- " key = ' '.join(sent)\n",
- " if key not in self.peykare_dict:\n",
- " self.peykare_dict[key] = sent\n",
- "\n",
- "\n",
- " def tag(self: \"SpacyPOSTagger\", tokens,universal_tag=True):\n",
- " \"\"\"یک جمله را در قالب لیستی از توکنها دریافت میکند و در خروجی لیستی از\n",
- " `(توکن، برچسب)`ها برمیگرداند.\n",
- "\n",
- " Examples:\n",
- " >>> posTagger = POSTagger(model = 'pos_tagger.model')\n",
- " >>> posTagger.tag(tokens = ['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.'])\n",
- " [('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN,EZ'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]\n",
- "\n",
- " >>> posTagger = POSTagger(model = 'pos_tagger.model', universal_tag = True)\n",
- " >>> posTagger.tag(tokens = ['من', 'به', 'مدرسه', 'ایران', 'رفته_بودم', '.'])\n",
- " [('من', 'PRON'), ('به', 'ADP'), ('مدرسه', 'NOUN'), ('ایران', 'NOUN'), ('رفته_بودم', 'VERB'), ('.', 'PUNCT')]\n",
- "\n",
- " Args:\n",
- " tokens (List[str]): لیستی از توکنهای یک جمله که باید برچسبگذاری شود.\n",
- "\n",
- " Returns:\n",
- " (List[Tuple[str,str]]): لیستی از `(توکن، برچسب)`ها.\n",
- "\n",
- " \"\"\"\n",
- " if self.tagger == None:\n",
- " self._setup_model([tokens])\n",
- " self._add_to_dict([tokens])\n",
- "\n",
- " text = ' '.join(tokens)\n",
- " doc = self.tagger(text)\n",
- " if not universal_tag:\n",
- " tags = [tok.tag_ for tok in doc]\n",
- " else:\n",
- " tags = [tok.tag_.replace(',EZ','') for tok in doc]\n",
- "\n",
- " return list(zip(tokens,tags))\n",
- " # noqa: W293\n",
- "\n",
- " def tag_sents(self:\"SpacyPOSTagger\",sents,universal_tag=True,batch_size=128):\n",
- " \"\"\"\n",
- " Args:\n",
- " sents : List[List[Tokens]]\n",
- " batch_size : number of batches give to model for processing sentences each time\n",
- " \"\"\"\n",
- " \"\"\"\n",
- " Returns : List[List[Tuple(str,str)]]\n",
- " \"\"\"\n",
- " if self.tagger == None:\n",
- " self._setup_model(sents)\n",
- "\n",
- " self._add_to_dict(sents)\n",
- "\n",
- " docs = list(self.tagger.pipe((' '.join([w for w in sent]) for sent in sents), batch_size=batch_size))\n",
- " if not universal_tag:\n",
- " tags = [[w.tag_ for w in doc] for doc in docs]\n",
- " else:\n",
- " tags = [[w.tag_.replace(',EZ','') for w in doc] for doc in docs]\n",
- "\n",
- " combined_out = [list(zip(tok,tag)) for tok,tag in zip(sents,tags)]\n",
- " return combined_out\n",
- "\n",
- " def train(\n",
- " self: \"SpacyPOSTagger\",\n",
- " train_dataset,\n",
- " test_dataset,\n",
- " data_directory,\n",
- " base_config_file,\n",
- " train_config_path,\n",
- " output_dir,\n",
- " use_direct_config=False\n",
- " ):\n",
- " \"\"\"\n",
- " Train the spaCy model using a subprocess and a configuration file.\n",
- "\n",
- " 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",
- "\n",
- " Args:\n",
- " - train_dataset: Training dataset for the tagger. It is a list of sentences, where each sentence is a list of token-tag pairs.\n",
- " - test_dataset: Testing dataset for the tagger. It is a list of sentences, where each sentence is a list of token-tag pairs.\n",
- " - data_directory: Directory to save the training and testing data in spaCy format.\n",
- " - base_config_file: Path to the base configuration file for spaCy.\n",
- " - train_config_path: if use_direct_config set to True this is the path of config file for training that you will use\n",
- " if use_direct_config set to False this is the path that you want train config file will create with base_config\n",
- " - output_dir: Directory for storing the trained model and training logs.\n",
- "\n",
- " Upon successful training, this method updates the model path to the trained model.\n",
- "\n",
- " This method is typically called to initiate the training process of the spaCy model.\n",
- " \"\"\"\n",
- "\n",
- " self.spacy_train_directory = data_directory\n",
- " self.train_dataset = train_dataset ### List[List[Tuple]]\n",
- " self.test_dataset = test_dataset\n",
- " if self.train_dataset:\n",
- " # Set up the training dataset configuration\n",
- " self._setup_dataset(dataset=self.train_dataset, saved_directory=self.spacy_train_directory, data_type='train')\n",
- "\n",
- " if self.test_dataset:\n",
- " self._setup_dataset(test_dataset,saved_directory=data_directory,data_type='test')\n",
- "\n",
- " train_data = f'{data_directory}/train.spacy'\n",
- " test_data = f'{data_directory}/test.spacy'\n",
- "\n",
- " if use_direct_config == False:\n",
- " self._setup_train_config(base_config_file, train_config_path=train_config_path)\n",
- " else:\n",
- " self.train_config_file = train_config_path\n",
- "\n",
- " command = f\"python -m spacy train {self.train_config_file} --output ./{output_dir} --paths.train ./{train_data} --paths.dev ./{test_data}\"\n",
- " if self.gpu_availability:\n",
- " command += f\" --gpu-id {self.gpu_id}\"\n",
- "\n",
- " subprocess.run(command, shell=True)\n",
- " self.model_path = f\"{output_dir}/model-last\"\n",
- " self._setup_model([[w for w,_ in sent] for sent in test_dataset])\n",
- "\n",
- " def _setup_train_config(self: \"SpacyPOSTagger\", base_config, train_config_path):\n",
- " \"\"\"\n",
- " Create and configure the training configuration file for spaCy.\n",
- "\n",
- " This method sets up the training configuration file by copying a base configuration file and customizing it according to the specified parameters.\n",
- "\n",
- " Args:\n",
- " - base_config: Path to the base configuration file.\n",
- " - train_config_file_name: Name of the training configuration file for saving it.\n",
- "\n",
- " This method is called to generate the training configuration file used in the training process.\n",
- " \"\"\"\n",
- " self.train_config_file = train_config_path\n",
- " print(\"----------------- Setting up the training configuration file ----------------------\")\n",
- " command = f\"python -m spacy init fill-config {base_config} {train_config_path}\" # Generate the training configuration file\n",
- " subprocess.run(command, shell=True)\n",
- " print(\"----------------- Training configuration file created successfully ----------------------\")\n",
- " print(f\"----------------- Training Config file address is {train_config_path} --------------------\")\n",
- "\n",
- " def evaluate(self: \"SpacyPOSTagger\", test_sents,batch_size):\n",
- " \"\"\"\n",
- " Evaluate the spaCy model on input sentences using different tag options.\n",
- "\n",
- " This method evaluates the spaCy model on input sentences with and without 'EZ' tags and reports classification metrics.\n",
- "\n",
- " Args:\n",
- " - sents: List of sentences for evaluation.\n",
- " - batch_size : number of batches that model should process each time\n",
- " This method calls the internal evaluation method for both tag options.\n",
- "\n",
- " This method is typically used for model evaluation and reporting metrics.\n",
- " \"\"\"\n",
- " self._setup_model([[w for w,_ in sent] for sent in test_sents])\n",
- " if self.tagger:\n",
- " golds, predictions = self._get_labels_and_predictions(test_sents,batch_size)\n",
- " print(\"-----------------------------------------\")\n",
- " self._evaluate_tags(test_sents, golds, predictions, use_ez_tags=True,batch_size=batch_size)\n",
- " print(\"-----------------------------------------\")\n",
- " self._evaluate_tags(test_sents, golds, predictions, use_ez_tags=False,batch_size=batch_size)\n",
- " else:\n",
- " 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",
- "\n",
- " def _evaluate_tags(self, sents, golds=None, predictions=None, use_ez_tags=True,batch_size=128):\n",
- " \"\"\"\n",
- " Evaluate model predictions and report classification metrics.\n",
- "\n",
- " This method evaluates model predictions and reports classification metrics for the specified tag option.\n",
- "\n",
- " Args:\n",
- " - sents: List of sentences for evaluation.\n",
- " - golds: List of gold labels (optional).\n",
- " - predictions: List of model predictions (optional).\n",
- " - use_ez_tags: A flag indicating whether to consider 'EZ' tags.\n",
- " - batch_size : number of batches model should process\n",
- "\n",
- " If `golds` and `predictions` are not provided, they are automatically extracted from the input sentences.\n",
- "\n",
- " This method calculates and displays precision, recall, and F1-score for the specified tag option.\n",
- "\n",
- " This method is called by the `evaluate` method to perform model evaluation.\n",
- " \"\"\"\n",
- " if golds is None or predictions is None:\n",
- " golds, predictions = self._get_labels_and_predictions(sents,batch_size)\n",
- "\n",
- " predictions_cleaned = []\n",
- " golds_cleaned = []\n",
- " if use_ez_tags:\n",
- " get_tag_func = self._get_ez_tags\n",
- " else:\n",
- " get_tag_func = self._remove_ez_tags\n",
- "\n",
- " for preds, golds in zip(predictions, golds):\n",
- " for pred in preds:\n",
- " pred_cleaned = get_tag_func(pred)\n",
- " predictions_cleaned.append(pred_cleaned)\n",
- " for gold in golds:\n",
- " gold_cleaned = get_tag_func(gold)\n",
- " golds_cleaned.append(gold_cleaned)\n",
- "\n",
- " print(classification_report(golds_cleaned, predictions_cleaned))\n",
- " print('Precision: %.5f' % precision_score(golds_cleaned, predictions_cleaned, average='weighted'))\n",
- " print('Recall: %.5f' % recall_score(golds_cleaned, predictions_cleaned, average='weighted'))\n",
- " print('F1-Score: %.5f' % f1_score(golds_cleaned, predictions_cleaned, average='macro'))\n",
- "\n",
- " def _get_ez_tags(self, label):\n",
- " \"\"\"\n",
- " Extract 'EZ' tags from labels.\n",
- "\n",
- " This method extracts 'EZ' tags from labels if they are present and returns them.\n",
- "\n",
- " Args:\n",
- " - label: The label containing 'EZ' tags.\n",
- "\n",
- " Returns:\n",
- " The 'EZ' tags or '-' if 'EZ' tags are not present.\n",
- " \"\"\"\n",
- " if 'EZ' in label:\n",
- " label = 'EZ'\n",
- " else:\n",
- " label = '-'\n",
- "\n",
- " return label\n",
- "\n",
- " def _remove_ez_tags(self, label):\n",
- " \"\"\"\n",
- " Remove 'EZ' tags from labels.\n",
- "\n",
- " This method removes 'EZ' tags from labels if they are present and returns the cleaned label.\n",
- "\n",
- " Args:\n",
- " - label: The label containing 'EZ' tags.\n",
- "\n",
- " Returns:\n",
- " The label with 'EZ' tags removed.\n",
- " \"\"\"\n",
- " return label.replace(',EZ', '') if 'EZ' in label else label\n",
- "\n",
- " def _evaluate_ez_tags(self, sents):\n",
- " \"\"\"\n",
- " Evaluate model predictions with 'EZ' tags included.\n",
- "\n",
- " This method evaluates model predictions with 'EZ' tags included.\n",
- " \"\"\"\n",
- " self._evaluate_tags(sents, use_ez_tags=True)\n",
- "\n",
- " def _evaluate_normal_tags(self, sents):\n",
- " \"\"\"\n",
- " Evaluate model predictions without 'EZ' tags.\n",
- "\n",
- " This method evaluates model predictions without 'EZ' tags.\n",
- " \"\"\"\n",
- " self._evaluate_tags(sents, use_ez_tags=False)\n",
- "\n",
- " def _get_labels_and_predictions(self: \"SpacyPOSTagger\", sents,batch_size):\n",
- " \"\"\"\n",
- " Extract gold labels and model predictions for evaluation.\n",
- "\n",
- " This method extracts gold labels and model predictions from input sentences.\n",
- "\n",
- " Args:\n",
- " - sents: List of sentences for evaluation.\n",
- "\n",
- " Returns:\n",
- " Lists of gold labels and model predictions.\n",
- "\n",
- " This method is typically used for gathering data to perform model evaluation.\n",
- " \"\"\"\n",
- " gold_labels = [[tag for _, tag in sent] for sent in sents]\n",
- " tokens = [[w for w,_ in sent] for sent in sents]\n",
- " prediction_labels = self.tag_sents(tokens,batch_size)\n",
- " return gold_labels, prediction_labels\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "5_IBJXq1Mnfo",
- "outputId": "c07d6be2-70cb-45b1-ed9f-a4eb49fafb90"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "------------------ GPU Setup Process Started ---------------------\n",
- "------------ GPU is not available; spaCy will use CPU -------------\n"
- ]
- }
- ],
- "source": [
- "spacy_posTagger = SpacyPOSTagger(model_path = '/content/spacy_pos_tagger_parsbertpostagger', using_gpu=True)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [],
- "source": [
- "from hazm import WordTokenizer, Normalizer\n",
- "\n",
- "tokenizer = WordTokenizer()\n",
- "normalizer = Normalizer()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Ezafe Correction\n",
- "def get_last_subword(word):\n",
- " # Split the word by word boundaries\n",
- " subwords = re.findall(r'\\b\\w+\\b', word)\n",
- "\n",
- " if len(subwords) > 1 and subwords[-1] in ['های', 'ی']:\n",
- " return (subwords[-2], subwords[-1])\n",
- "\n",
- " return (subwords[-1], '')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [],
- "source": [
- "def get_EZ_tags(grapheme, compound=False):\n",
- " grapheme = re.sub('ۀ', 'هی', grapheme)\n",
- " tokens = tokenizer.tokenize(normalizer.normalize(grapheme))\n",
- " tags = spacy_posTagger.tag(tokens=tokens, universal_tag=False)\n",
- " tags = [(t[0], t[1], '') for t in tags if 'EZ' in t[1]]\n",
- "\n",
- " if compound:\n",
- " return tags\n",
- "\n",
- " splitted_tags = []\n",
- " for t in tags:\n",
- " subword1, subword2 = get_last_subword(t[0])\n",
- " splitted_tags.append((subword1, t[1], subword2))\n",
- " return splitted_tags"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [],
- "source": [
- "def get_naive_phonetic(word):\n",
- " char_map = {\n",
- " 'ا': 'A', 'ب': 'b', 'پ': 'p', 'ت': 't', 'ث': 's', 'ج': 'j', 'چ': 'C',\n",
- " 'ح': 'h', 'خ': 'x', 'د': 'd', 'ذ': 'z', 'ر': 'r', 'ز': 'z', 'ژ': 'Z',\n",
- " 'س': 's', 'ش': 'S', 'ص': 's', 'ض': 'z', 'ط': 't', 'ظ': 'z', 'ع': '?',\n",
- " 'غ': 'q', 'ف': 'f', 'ق': 'q', 'ک': 'k', 'گ': 'g', 'ل': 'l', 'م': 'm',\n",
- " 'ن': 'n', 'و': 'v', 'ه': 'h', 'ی': 'y', 'ء': '?','ئ': '?', 'ؤ': '?',\n",
- " 'آ': 'A', 'أ': '?', 'إ': '?', 'ۀ': 'eye'\n",
- " }\n",
- " mapped_string = ''.join(char_map.get(char, char) for char in word)\n",
- " return mapped_string"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import pandas as pd\n",
- "merged_dict_path = 'final_merged_dict_pruned_POS_prob.csv'\n",
- "merged_dict_df = pd.read_csv(merged_dict_path)\n",
- "\n",
- "merged_dict = {}\n",
- "\n",
- "for idx, row in merged_dict_df.iterrows():\n",
- " g, ps, nodiff, pos, prob = row['grapheme'], eval(row['phoneme']), row['nodiff'], eval(row['POS']), eval(row['prob'])\n",
- " if g not in merged_dict:\n",
- " merged_dict[g] = {'phoneme': [], 'nodiff': nodiff, 'POS': pos, 'prob': prob}\n",
- "\n",
- " for p in ps:\n",
- " merged_dict[g]['phoneme'].append(''.join(p))\n",
- "\n",
- "\n",
- "inverted_merged_dict = {}\n",
- "\n",
- "for key, value_list in merged_dict.items():\n",
- " for value in value_list['phoneme']:\n",
- " inverted_merged_dict[value] = key\n",
- "\n",
- "\n",
- "def word_in_dict(word, inverted_dictionary=inverted_merged_dict):\n",
- " return word in inverted_dictionary"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {},
- "outputs": [],
- "source": [
- "import itertools\n",
- "def get_word_phonetic_candidates(word):\n",
- " subwords = []\n",
- " for match in re.finditer(r'\\b(\\w+)\\b', word):\n",
- " match_text = match.group()\n",
- " match_span = match.span()\n",
- " subwords.append((match_text, match_span))\n",
- "\n",
- " subword_candidates = []\n",
- " for subword, _ in subwords:\n",
- " if subword in merged_dict:\n",
- " subword_candidates.append(merged_dict[subword]['phoneme'])\n",
- " else:\n",
- " subword_candidates.append([get_naive_phonetic(subword)])\n",
- "\n",
- " # Generate all possible combinations and concatenate\n",
- " word_candidates = [''.join(comb) for comb in itertools.product(*subword_candidates)]\n",
- " return word_candidates"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {},
- "outputs": [],
- "source": [
- "def get_updated_span(match_span, displacements):\n",
- " new_start, new_end = match_span[0], match_span[1]\n",
- " for start, displacement in displacements:\n",
- " if start <= new_start:\n",
- " new_start += displacement\n",
- " new_end += displacement\n",
- "\n",
- " return (new_start, new_end)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {},
- "outputs": [],
- "source": [
- "def add_1_for_EZ(phonemes):\n",
- " # Convert 'a' to 'A' in '-ha' and '-haye'\n",
- " phonemes = phonemes.replace('-ha', '-hA').replace('-haye', '-hAye')\n",
- " \n",
- " # Add '1' after '-e', '-ye', and '-hAye'\n",
- " phonemes = phonemes.replace('-e', '-e1').replace('-ye', '-ye1').replace('-hAye', '-hAye1')\n",
- " \n",
- " return phonemes"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {},
- "outputs": [],
- "source": [
- "def correct_phonetic_model_EZ_by_tags(grapheme, model_output):\n",
- " EZ_tags = get_EZ_tags(grapheme, compound=False)\n",
- "\n",
- " matches = []\n",
- " matched_spans = set()\n",
- "\n",
- " for word, tag, ending in EZ_tags:\n",
- " phonetic_candidates = get_word_phonetic_candidates(word)\n",
- "\n",
- " for phonetic in phonetic_candidates:\n",
- " if phonetic.endswith('Aye') and not word.endswith('ه'): continue\n",
- " for match in re.finditer(r'\\b(\\w+)\\b', model_output):\n",
- " match_text = match.group()\n",
- " match_span = match.span()\n",
- " \n",
- " 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",
- " matches.append((match_span, match_text, phonetic, ending))\n",
- " matched_spans.add(match_span)\n",
- "\n",
- " non_matches = []\n",
- " for match in re.finditer(r'\\b(\\w+)\\b', model_output):\n",
- " match_text = match.group()\n",
- " match_span = match.span()\n",
- " 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",
- " non_matches.append((match_text, match_span))\n",
- "\n",
- " displacements = []\n",
- " for match_span, _, phonetic, ending in matches:\n",
- " match_span = get_updated_span(match_span, displacements)\n",
- " 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",
- " continue\n",
- "\n",
- " output_word = model_output[match_span[0]:match_span[1]]\n",
- " if len(output_word) >= 4 and output_word[-3] in 'еeiuoaāäâāɒáA' and output_word.endswith('ye') and \\\n",
- " ((word_in_dict(output_word[:-2], inverted_merged_dict) and not word_in_dict(output_word, inverted_merged_dict)) or \\\n",
- " SequenceMatcher(None, output_word[:-2], phonetic).ratio() > SequenceMatcher(None, output_word, phonetic).ratio()):\n",
- " model_output = model_output[:match_span[1] - 2] + '-' + model_output[match_span[1] - 2:]\n",
- " displacements.append((match_span[1] - 2, 1))\n",
- " continue\n",
- "\n",
- " if len(output_word) >= 3 and output_word.endswith('e') and \\\n",
- " ((word_in_dict(output_word[:-1], inverted_merged_dict) and not word_in_dict(output_word, inverted_merged_dict)) or \\\n",
- " SequenceMatcher(None, output_word[:-1], phonetic).ratio() > SequenceMatcher(None, output_word, phonetic).ratio()):\n",
- " model_output = model_output[:match_span[1] - 1] + '-' + model_output[match_span[1] - 1:]\n",
- " displacements.append((match_span[1] - 1, 1))\n",
- " continue\n",
- "\n",
- " if ending == 'ی' and len(output_word) >= 4 and output_word[-2:] == 'ye' and output_word[-3] == phonetic[-1]:\n",
- " model_output = model_output[:match_span[1] - 2] + '-' + model_output[match_span[1] - 2:]\n",
- " displacements.append((match_span[1] - 2, 1))\n",
- " continue\n",
- "\n",
- " if ending == 'های' and len(output_word) >= 7 and output_word[-5:] == 'hAye':\n",
- " model_output = model_output[:match_span[1] - 4] + '-' + model_output[match_span[1] - 4:]\n",
- " displacements.append((match_span[1] - 5, 1))\n",
- " continue\n",
- "\n",
- " if ending == 'های' and len(output_word) >= 6 and output_word[-4:] == 'haye':\n",
- " model_output = model_output[:match_span[1] - 4] + '-hAye' + model_output[match_span[1]:]\n",
- " displacements.append((match_span[1] - 4, 1))\n",
- " continue\n",
- "\n",
- " if ending not in ['ی', 'های'] and len(output_word) >= 3 and output_word[-2] == phonetic[-1] and output_word[-1] == 'e':\n",
- " model_output = model_output[:match_span[1] - 1] + '-' + model_output[match_span[1] - 1:]\n",
- " displacements.append((match_span[1] - 1, 1))\n",
- " continue\n",
- "\n",
- " if output_word[-1] in 'еeiuoaāäâāɒáA' and not output_word.endswith('haye') and not output_word.endswith('hAye'):\n",
- " model_output = model_output[:match_span[1]] + '-ye' + model_output[match_span[1]:]\n",
- " displacements.append((match_span[1], 3))\n",
- " continue\n",
- "\n",
- " if not output_word.endswith('e'):\n",
- " model_output = model_output[:match_span[1]] + '-e' + model_output[match_span[1]:]\n",
- " displacements.append((match_span[1], 2))\n",
- "\n",
- " for non_match, match_span in non_matches:\n",
- " match_span = get_updated_span(match_span, displacements)\n",
- " output_word = model_output[match_span[0]:match_span[1]]\n",
- " if re.match(r'^-e\\b', model_output[match_span[1]:]):\n",
- " model_output = model_output[:match_span[1]] + model_output[match_span[1] + 2:]\n",
- " displacements.append((match_span[1] + 2, -2))\n",
- " continue\n",
- "\n",
- " if re.match(r'^-ye\\b', model_output[match_span[1]:]):\n",
- " model_output = model_output[:match_span[1]] + model_output[match_span[1] + 3:]\n",
- " displacements.append((match_span[1] + 3, -3))\n",
- " continue\n",
- "\n",
- " 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",
- " model_output = model_output[:match_span[1] - 2] + model_output[match_span[1]:]\n",
- " displacements.append((match_span[1], -2))\n",
- " continue\n",
- "\n",
- " 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",
- " model_output = model_output[:match_span[1] - 1] + model_output[match_span[1]:]\n",
- " displacements.append((match_span[1], -1))\n",
- "\n",
- "\n",
- " model_output = add_1_for_EZ(model_output)\n",
- "\n",
- " return model_output"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "AdU8VMTIOWLZ"
- },
- "source": [
- "# Get Data"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "XhbCA2tkR45b"
- },
- "source": [
- "## Get Merged Dict"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "dGYh5bDyRfTg"
- },
- "outputs": [],
- "source": [
- "merged_dict_path = \"final_merged_dict_pruned_POS_prob.csv\""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "metadata": {
- "id": "WV2x_iLQRhHI"
- },
- "outputs": [],
- "source": [
- "import pandas as pd\n",
- "merged_dict_df = pd.read_csv(merged_dict_path)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "NTDIcLdNUbNX",
- "outputId": "736b59cd-67cf-4d4f-d4da-4466bff487a1"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "(116630, 5)"
- ]
- },
- "execution_count": 17,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "merged_dict_df.shape"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 18,
- "metadata": {
- "id": "JoW9aygRdcP6"
- },
- "outputs": [],
- "source": [
- "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",
- "vowels_regex = '(?=' + '|'.join(['a', 'A', 'e', 'i', 'u', 'o']) + ')'"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 19,
- "metadata": {
- "id": "OJTyOEoMR-cV"
- },
- "outputs": [],
- "source": [
- "merged_dict = {}\n",
- "\n",
- "for idx, row in merged_dict_df.iterrows():\n",
- " g, ps, nodiff, pos, prob = row['grapheme'], eval(row['phoneme']), row['nodiff'], eval(row['POS']), eval(row['prob'])\n",
- " if g not in merged_dict:\n",
- " merged_dict[g] = {'phoneme': [], 'nodiff': nodiff, 'POS': pos, 'prob': prob}\n",
- "\n",
- " for p in ps:\n",
- " merged_dict[g]['phoneme'].append(''.join(p))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 23,
- "metadata": {
- "id": "ujrYr29iy9TJ"
- },
- "outputs": [],
- "source": [
- "inverted_merged_dict = {}\n",
- "\n",
- "for key, value_list in merged_dict.items():\n",
- " for value in value_list:\n",
- " inverted_merged_dict[value] = key"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 24,
- "metadata": {
- "id": "OoaIwa8nOegN"
- },
- "outputs": [],
- "source": [
- "def word_in_dict(word, inverted_dictionary=inverted_merged_dict):\n",
- " return word in inverted_dictionary"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "XjAPkfq7SF87"
- },
- "source": [
- "## Get Evaluation Data"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "hJO-UAPDQvcb"
- },
- "outputs": [],
- "source": [
- "sentence_bench = pd.read_csv('SentenceBench.csv')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 26,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 143
- },
- "id": "qlYbrnUa9LAN",
- "outputId": "ce68f665-681a-454a-9a02-d5d14047fc68"
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "<div>\n",
- "<style scoped>\n",
- " .dataframe tbody tr th:only-of-type {\n",
- " vertical-align: middle;\n",
- " }\n",
- "\n",
- " .dataframe tbody tr th {\n",
- " vertical-align: top;\n",
- " }\n",
- "\n",
- " .dataframe thead th {\n",
- " text-align: right;\n",
- " }\n",
- "</style>\n",
- "<table border=\"1\" class=\"dataframe\">\n",
- " <thead>\n",
- " <tr style=\"text-align: right;\">\n",
- " <th></th>\n",
- " <th>dataset</th>\n",
- " <th>grapheme</th>\n",
- " <th>phoneme</th>\n",
- " <th>homograph word</th>\n",
- " <th>pronunciation</th>\n",
- " </tr>\n",
- " </thead>\n",
- " <tbody>\n",
- " <tr>\n",
- " <th>0</th>\n",
- " <td>polyphone</td>\n",
- " <td>من قدر تو را میدانم</td>\n",
- " <td>man qadr-e to rA mi-dAnam</td>\n",
- " <td>قدر</td>\n",
- " <td>qadr</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>1</th>\n",
- " <td>polyphone</td>\n",
- " <td>از قضای الهی به قدر الهی پناه میبرم</td>\n",
- " <td>?az qazAy ?elAhi be qadar-e ?elAhi panAh mi-baram</td>\n",
- " <td>قدر</td>\n",
- " <td>qadar</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>2</th>\n",
- " <td>polyphone</td>\n",
- " <td>به دست و صورتم کرم زدم</td>\n",
- " <td>be dast-o suratam kerem zadam</td>\n",
- " <td>کرم</td>\n",
- " <td>kerem</td>\n",
- " </tr>\n",
- " </tbody>\n",
- "</table>\n",
- "</div>"
- ],
- "text/plain": [
- " dataset grapheme \\\n",
- "0 polyphone من قدر تو را میدانم \n",
- "1 polyphone از قضای الهی به قدر الهی پناه میبرم \n",
- "2 polyphone به دست و صورتم کرم زدم \n",
- "\n",
- " phoneme homograph word \\\n",
- "0 man qadr-e to rA mi-dAnam قدر \n",
- "1 ?az qazAy ?elAhi be qadar-e ?elAhi panAh mi-baram قدر \n",
- "2 be dast-o suratam kerem zadam کرم \n",
- "\n",
- " pronunciation \n",
- "0 qadr \n",
- "1 qadar \n",
- "2 kerem "
- ]
- },
- "execution_count": 26,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "sentence_bench.head(3)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "wDV7ysXf2b_H"
- },
- "source": [
- "### Get ManaTTS"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 27,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "TcL5ZLvSSnVB",
- "outputId": "3945e139-1b12-44c9-d6c1-dd0b1a790593"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "[('در این نوشته بنا داریم با یک ابزار ساده و مکانیکی افزایش بینایی برای افراد کم\\u200cبینا ',\n",
- " 'dar ?in neveSte banA dArim bA yek ?abzAr-e sAde va mekAniki-ye ?afzAyeS-e binAyi barAye ?afrAd-e kam\\u200cbinA '),\n",
- " ('به نام بی\\u200cوپتیک یا عدسی دورنما آشنا شویم. ',\n",
- " 'be nAm-e biyoptik yA ?adasi-ye durnamA ?ASnA Savim'),\n",
- " ('دراین\\u200cصورت، انجام خودارزیابی و ارائه بازخورد بر عهده خودتان است. ',\n",
- " 'dar ?in surat ?anjAm-e xod?arzyAbi va ?erA?e-ye bAzxord bar ?ohde-ye xodetAn ?ast ')]"
- ]
- },
- "execution_count": 27,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "filtered_rows = sentence_bench[sentence_bench['dataset'] == 'mana-tts'][['grapheme', 'phoneme']]\n",
- "\n",
- "# Convert to a list of tuples\n",
- "mana_evaluation_data = list(filtered_rows.itertuples(index=False, name=None))\n",
- "\n",
- "mana_evaluation_data[:3]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "Jjacw9Mp2eoX"
- },
- "source": [
- "### Get CommonVoice"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 28,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "-yQnqCGw26sk",
- "outputId": "952fad9e-837f-4f0c-e3a4-249365abaa5c"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "[('در اکثر شهرها، مرکزی برای خرید دوچرخه وجود دارد.',\n",
- " 'dar ?aksar-e Sahr-hA, markazi barAye xarid-e doCarxe vojud dArad.'),\n",
- " ('پس از مدرسه کودکان به سوی خانه جست و خیز کردند.',\n",
- " 'pas ?az madrese kudakAn be suye xAne jast-o-xiz kardand.'),\n",
- " ('شما نگران زن و بچه این نباش.', 'SomA negarAn-e zan-o-baCCe-ye ?in nabAS.')]"
- ]
- },
- "execution_count": 28,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "filtered_rows = sentence_bench[sentence_bench['dataset'] == 'commonvoice'][['grapheme', 'phoneme']]\n",
- "\n",
- "# Convert to a list of tuples\n",
- "commonvoice_evaluation_data = list(filtered_rows.itertuples(index=False, name=None))\n",
- "\n",
- "commonvoice_evaluation_data[:3]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "ciSPyhRc3Rvo"
- },
- "source": [
- "### Get Ambiguious"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 29,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "XlFc5JbN3Rvz",
- "outputId": "56dd8eb2-0f5e-4e91-ff91-25317ff0581d"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "[('من قدر تو را می\\u200cدانم', 'man qadr-e to rA mi-dAnam', 'قدر', 'qadr'),\n",
- " ('از قضای الهی به قدر الهی پناه می\\u200cبرم',\n",
- " '?az qazAy ?elAhi be qadar-e ?elAhi panAh mi-baram',\n",
- " 'قدر',\n",
- " 'qadar'),\n",
- " ('به دست و صورتم کرم زدم', 'be dast-o suratam kerem zadam', 'کرم', 'kerem')]"
- ]
- },
- "execution_count": 29,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "filtered_rows = sentence_bench[sentence_bench['dataset'] == 'polyphone'][['grapheme', 'phoneme', 'homograph word',\t'pronunciation']]\n",
- "\n",
- "# Convert to a list of tuples\n",
- "ambiguous_evaluation_data = list(filtered_rows.itertuples(index=False, name=None))\n",
- "\n",
- "ambiguous_evaluation_data[:3]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "R6PE5ds45TPr"
- },
- "source": [
- "# Evaluate Method Outputs"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "y73zFlRGIbt9"
- },
- "source": [
- "## PER Evaluation"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 30,
- "metadata": {
- "id": "ItuviO3w5Vzv"
- },
- "outputs": [],
- "source": [
- "def remove_non_word_chars(text):\n",
- " pattern = r'[^\\w\\s\\?]'\n",
- " cleaned_text = re.sub(pattern, ' ', text)\n",
- " return cleaned_text"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 31,
- "metadata": {
- "id": "syQCurXu51TO"
- },
- "outputs": [],
- "source": [
- "def remove_white_spaces(text):\n",
- " cleaned_text = re.sub(r'\\s+', ' ', text)\n",
- " return cleaned_text.strip()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 32,
- "metadata": {
- "id": "V7APkVM053RP"
- },
- "outputs": [],
- "source": [
- "def get_word_only_text(text):\n",
- " word_only_text = remove_non_word_chars(text)\n",
- " extra_space_removed_text = remove_white_spaces(word_only_text)\n",
- "\n",
- " return extra_space_removed_text"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 33,
- "metadata": {
- "id": "ROomKSao57vy"
- },
- "outputs": [],
- "source": [
- "def get_texts_cer(reference, model_output):\n",
- " # Preprocess input texts to only contain word characters\n",
- " word_only_reference = get_word_only_text(reference)\n",
- " word_only_output = get_word_only_text(model_output)\n",
- "\n",
- " # Return +infinity for CER if any of the texts is empty\n",
- " if not word_only_reference.strip() or not word_only_output.strip():\n",
- " return float('inf')\n",
- "\n",
- " return cer(word_only_reference, word_only_output)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 34,
- "metadata": {
- "id": "4vHLUjp48hc3"
- },
- "outputs": [],
- "source": [
- "def get_avg_cer_of_method(method_outputs, references):\n",
- " cers = []\n",
- " for idx, o in enumerate(method_outputs):\n",
- " cer = get_texts_cer(o, references[idx][1].replace('-', ''))\n",
- " if cer != float('inf'):\n",
- " cers.append(cer)\n",
- "\n",
- " return sum(cers) / len(cers)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "f4NqCjr1FxVg"
- },
- "source": [
- "## Ezafe Evaluation"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 35,
- "metadata": {
- "id": "Fn1IjihOEDEF"
- },
- "outputs": [],
- "source": [
- "def get_EZ_words_from_ground_truth(text):\n",
- " pattern = r'\\b(\\w+)(-e|-ye)\\b'\n",
- " matches = re.findall(pattern, text,)\n",
- "\n",
- " # Extract the words along with the suffix\n",
- " words_with_suffix = [match[0] + match[1] for match in matches]\n",
- " EZ_words = [tuple(re.split(r'(?=-)', w)) for w in words_with_suffix]\n",
- "\n",
- " return EZ_words"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 36,
- "metadata": {
- "id": "xiEKlZjV2OMC"
- },
- "outputs": [],
- "source": [
- "def get_EZ_words_from_phonetic_model_output(text):\n",
- " EZ_words = re.findall(r'\\b(\\w+)(-e|-ye)', text)\n",
- " EZ_word_candidates = []\n",
- "\n",
- " other_words = re.findall(r'\\b(\\w+)(?=(?:[^-\\w]|$))', text)\n",
- " for word in other_words:\n",
- " 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",
- " EZ_words.append((word[:-2], '-ye'))\n",
- " continue\n",
- "\n",
- " 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",
- " EZ_words.append((word[:-1], '-e'))\n",
- " continue\n",
- "\n",
- " if len(word) >= 4 and word[-3] in 'еeiuoaāäâāɒáA' and word.endswith('ye'):\n",
- " EZ_word_candidates.append((word[:-2], '-ye'))\n",
- " continue\n",
- "\n",
- " if len(word) >= 3 and word.endswith('e'):\n",
- " EZ_word_candidates.append((word[:-1], '-e'))\n",
- "\n",
- " return EZ_words, EZ_word_candidates"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 37,
- "metadata": {
- "id": "PFkBeD262OMD"
- },
- "outputs": [],
- "source": [
- "def get_phonetic_model_TP_FP_TN_FN(gt_finglish, model_finglish):\n",
- " gt_word_count = len(re.findall(r'\\b\\w+(?:-\\w+)*\\b', gt_finglish))\n",
- " gt_EZ_words = get_EZ_words_from_ground_truth(gt_finglish)\n",
- "\n",
- " model_EZ_words, model_candidate_EZ_words = get_EZ_words_from_phonetic_model_output(model_finglish)\n",
- "\n",
- " TP = 0\n",
- " FP = 0\n",
- " TN = 0\n",
- " FN = 0\n",
- "\n",
- " gt_matched_indices = set()\n",
- " model_matched_indices = set()\n",
- " model_candidate_matched_indices = set()\n",
- "\n",
- " for gt_idx, (word, EZ) in enumerate(gt_EZ_words):\n",
- " for model_idx, (w, E) in enumerate(model_EZ_words):\n",
- " if model_idx not in model_matched_indices and SequenceMatcher(None, word, w).ratio() > 0.65:\n",
- " TP += 1\n",
- " gt_matched_indices.add(gt_idx)\n",
- " model_matched_indices.add(model_idx)\n",
- " break\n",
- " else:\n",
- " for model_c_idx, (w, E) in enumerate(model_candidate_EZ_words):\n",
- " if model_c_idx not in model_candidate_matched_indices and SequenceMatcher(None, word, w).ratio() > 0.65:\n",
- " TP += 1\n",
- " gt_matched_indices.add(gt_idx)\n",
- " model_candidate_matched_indices.add(model_c_idx)\n",
- " break\n",
- "\n",
- " # Calculate FP: model_EZ_words that are not TP\n",
- " FP = len(model_EZ_words) - (TP - len(list(model_candidate_matched_indices)))\n",
- "\n",
- " # Calculate FN: gt_EZ_words that were not detected\n",
- " FN = len(gt_EZ_words) - TP\n",
- "\n",
- " # Calculate TN: non-Ezafe words that are correctly not detected as Ezafe\n",
- " TN = (gt_word_count - len(gt_EZ_words)) - FP\n",
- "\n",
- " return TP, FP, TN, FN\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 38,
- "metadata": {
- "id": "cbW4otNyIQLh"
- },
- "outputs": [],
- "source": [
- "def get_phonetic_model_performance(outputs, references):\n",
- " total_TP, total_FP, total_TN, total_FN = 0, 0, 0, 0\n",
- "\n",
- " for idx, o in enumerate(outputs):\n",
- " TP, FP, TN, FN = get_phonetic_model_TP_FP_TN_FN(references[idx][1], o)\n",
- " total_TP += TP\n",
- " total_FP += FP\n",
- " total_TN += TN\n",
- " total_FN += FN\n",
- "\n",
- "\n",
- " total_model_EZ = total_TP + total_FP\n",
- " total_gt_EZ = total_TP + total_FN\n",
- "\n",
- " total_model_T = total_TP + total_TN\n",
- "\n",
- " total_gt_words = total_TP + total_TN + total_FP + total_FN\n",
- "\n",
- " accuracy = (total_model_T) / (total_gt_words) * 100\n",
- " precision = (total_TP) / (total_model_EZ) * 100\n",
- " recall = (total_TP) / (total_gt_EZ) * 100\n",
- "\n",
- " return accuracy, precision, recall"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "oBgNtpFQDwku"
- },
- "source": [
- "## Polyphone Evaluation"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 39,
- "metadata": {
- "id": "J445ULEvEEDn"
- },
- "outputs": [],
- "source": [
- "def get_polyphone_performance(outputs, references):\n",
- " corrects = 0\n",
- " total = 0\n",
- "\n",
- " for idx, (g, p, polyphone, right) in enumerate(references):\n",
- " if polyphone != '':\n",
- " total += 1\n",
- " if right in outputs[idx]:\n",
- " corrects += 1\n",
- " else:\n",
- " print(f\"Out: {outputs[idx]}\\nRef: {p}\")\n",
- "\n",
- " return corrects / total"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "JGEUIrbi9kNH"
- },
- "source": [
- "# Full bench"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 40,
- "metadata": {
- "id": "fGzQvL8V9mln"
- },
- "outputs": [],
- "source": [
- "benchmark = []\n",
- "\n",
- "for g, p in mana_evaluation_data:\n",
- " benchmark.append((g, p, '', ''))\n",
- "\n",
- "for g, p in commonvoice_evaluation_data:\n",
- " benchmark.append((g, p, '', ''))\n",
- "\n",
- "for g, p, w, r in ambiguous_evaluation_data:\n",
- " benchmark.append((g, p, w, r))\n",
- "\n",
- "benchmark = benchmark[:400]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 41,
- "metadata": {
- "id": "4jlXFt8tCPWB"
- },
- "outputs": [],
- "source": [
- "def print_all_metrics(predictions):\n",
- " per = get_avg_cer_of_method(predictions, benchmark) * 100\n",
- " acc, prec, recall = get_phonetic_model_performance(predictions, benchmark)\n",
- " polyphone = get_polyphone_performance(predictions, benchmark) * 100\n",
- "\n",
- " print(f\"PER: \\t\\t\\t{per:.2f}\")\n",
- " print(f\"ACC, PREC, RECALL, F1: \\t{acc:.2f}, {prec:.2f}, {recall:.2f}, {((2 * prec * recall) / (prec + recall)):.2f}\")\n",
- " print(f\"POLYPHONE: \\t\\t{polyphone:.2f}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "fTRgGM_8_Fwg"
- },
- "source": [
- "# Inference"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 42,
- "metadata": {
- "id": "17lrgWh__Mzr"
- },
- "outputs": [],
- "source": [
- "graphemes = [item[0] for item in benchmark]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 43,
- "metadata": {
- "id": "ajqTWtNb_HBd"
- },
- "outputs": [],
- "source": [
- "outputs = g2p.generate(graphemes, use_rules=True)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "jPXWBZ4R_bGs"
- },
- "source": [
- "# Mapping"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 44,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "g3Etdbv2_dMF",
- "outputId": "0e8c3f99-4342-4adb-c5d0-0b4e2e803c03"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "{'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"
- ]
- }
- ],
- "source": [
- "print(set(''.join(outputs)))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 45,
- "metadata": {
- "id": "c8C2sJjJA4na"
- },
- "outputs": [],
- "source": [
- "# Define the replacements\n",
- "replacements = {\n",
- " 'a': 'A',\n",
- " '$': 'S',\n",
- " '/': 'a',\n",
- " '1': '',\n",
- " ';': 'Z',\n",
- " '@': '?',\n",
- " 'c': 'C'\n",
- "}\n",
- "\n",
- "# Apply replacements\n",
- "mapped_outputs = [\n",
- " ''.join(replacements.get(char, char) for char in output)\n",
- " for output in outputs\n",
- "]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "JAIAobLFCKCr"
- },
- "source": [
- "# Results"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 46,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "CEs_TODaAFHO",
- "outputId": "658b687f-e842-43e7-b8e1-2089d6581872"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Out: ?az qazAye ?elAhi beqadr ?elAhi panAh mibaram\n",
- "Ref: ?az qazAy ?elAhi be qadar-e ?elAhi panAh mi-baram\n",
- "Out: ?agar be Sahre maro safar koni\n",
- "Ref: ?agar be Sahr-e marv safar koni\n",
- "Out: ?az piSe man mero nemitavAnam bA to biyAyam\n",
- "Ref: ?az piS-e man maro nemi-tavAnam bA to biyAyam\n",
- "Out: zendegi tabaqe xAsteye digarAn saxt ?ast\n",
- "Ref: zendegi tebq-e xAste-ye digarAn saxt ?ast\n",
- "Out: jazr ?o madde daryA padideye ?ajibi ?ast\n",
- "Ref: jazr va madd-e daryA padide-ye ?ajibi ?ast\n",
- "Out: mas?olin dar har samt va pasti ke bASand bAyad xedmat konand\n",
- "Ref: mas?ulin dar har semat va posti ke bASand bAyad xedmat konand\n",
- "Out: ?engadr zar nazan xaste Sodim\n",
- "Ref: ?enqadr zer nazan xaste Sodim\n",
- "Out: qadri darham ?o dinAr nasibaS Sod\n",
- "Ref: qadri derham va dinAr nasibaS Sod\n",
- "Out: ?ey meh zibAye man ?AftAb rA xajal kardei\n",
- "Ref: ?ey mah-e zibAy-e man ?AftAb rA xejel karde-?i\n",
- "Out: Savi ?u ruze ba?d ?az ?ezdevAj rahlat namud\n",
- "Ref: Suye ?u ruz-e ba?d ?az ?ezdevAj rehlat nemud\n",
- "Out: ?agar xoSAl Savi bAyad Sokr begozAri\n",
- "Ref: ?agar xoShAl Savi bAyad Sokr begozAri\n",
- "Out: melk va darbAriyAn ?az dar kAxe dAxel Sodand\n",
- "Ref: malek va darbAriyAn ?az dar-e kAx dAxel Sodand\n",
- "Out: melke soleymAn ?az bASokuhtarin farvAnravAyihA budeast\n",
- "Ref: molk-e soleymAn ?az bASokuh-tarin farmAnravAyi-ha hA bude ?ast\n",
- "Out: hezArAn hur ?o malek dar beheSt dar ?entezAre ?ust\n",
- "Ref: hezArAn hur va malak dar beheSt dar ?entezAr-e ?ust\n",
- "Out: ?in bannA qedmate besyAri dArad\n",
- "Ref: ?in bana qedmat-e besyAri dArad\n",
- "Out: man mallAkhAye ?ezdevAj rA barAyetAn tozih midaham\n",
- "Ref: man melAk-hAye ?ezdevAj rA barAye Soma tozih mi-deham\n",
- "Out: pedarbozorgam xeyli nAgahAni fut kard va ?az piSe mA raft\n",
- "Ref: pedar-bozorgam xeyli nAgahAni fot kard va ?az piS-e ma raft\n",
- "Out: yek SalvAr kardi va kafSAye mahalli xarid\n",
- "Ref: yek SalvAr-e kordi va kafS-hAye mahalli xarid\n",
- "Out: ?az sennet xejAlat bekeS dige bozorg Sodi\n",
- "Ref: ?az sennet xejAlat bekeS dige bozorg Sodi\n",
- "Out: ?ensAnhAye xeyr be bimAran komak kardand\n",
- "Ref: ?ensAn-hAye xayyer be bimarAn komak kardand\n",
- "Out: dar ?elme Simi har mAde bAyad bA ?ehtiyAt barresi Savad\n",
- "Ref: dar ?elme Simi har mAdde bAyad bA ?ehtiyat barresi\n",
- "Out: hasan xalq yeki ?az fazilathAye moheme ?AdamizAd ?ast\n",
- "Ref: hosn-e xolq yeki ?az fazilathAye mohemm-e ?AdamizAd ?ast\n",
- "Out: CeSme ?alAn dasturtAn rA ?etA?at mikonam\n",
- "Ref: xaSm ?alAn dasturetAn rA ?etA?at mi-konam\n",
- "Out: meSk ?Ab ?az dastAne ?abbAs bar zamin ?oftAd\n",
- "Ref: maSk-e ?Ab ?az dAstAn-e ?abbAs bar zamin ?oftAd\n",
- "Out: meSk ?An ?ast ke xod bebuyad na ?Anke ?attAr beguyad\n",
- "Ref: moSk ?An ?ast ke xod bebuyad na ?Anke ?attAr beguyad\n",
- "Out: muhAyaS rA bA bores SAne zad\n",
- "Ref: mu-hAyaS rA bA bores SAne zad\n",
- "Out: boro be kArt beres\n",
- "Ref: boro be kAret beres\n",
- "Out: heyvAne xAnegiye man diruz dar ?asare garmA bihuS Sod va mard\n",
- "Ref: heyvAn-e xAnegi-ye man diruz dar ?asar-e garmA bihuS Sod va mord\n",
- "Out: ?An zan yek mazne lebAs dArad\n",
- "Ref: ?An zan yek mezon-e lebAs dArad\n",
- "Out: donbAlehA va serrihA ?az mohemtarin mabAhese riyAzi yek hastand\n",
- "Ref: donbAle-hA va seri hA ?az moh-em-tarin mabAhes-e riyAzi-ye yek hastand\n",
- "Out: har saboki ke barAye naqqASi ?entexAb konad\n",
- "Ref: har sabki ke barAye naqqASi ?entexAb konad\n",
- "Out: meydAn rA se dure piCid\n",
- "Ref: meydAn-ra se dor piCid\n",
- "Out: ?agar ?orze dASt kAri peydA mikard\n",
- "Ref: ?agar ?orze dASt kAri peydA mi-kard\n",
- "Out: ?arze va taqAzA hamiSe dar tavAzon hastand\n",
- "Ref: ?arze va taqAzA hamiSe dar tavAzon hastand\n",
- "Out: dorAne hole yek mehvare markazi\n",
- "Ref: davarAn hol-e yek mehvar-e markazi\n",
- "Out: ?in CAqu hiC Cizi rA nemibarad\n",
- "Ref: ?in CAqu hiC Cizi rA nemi borad\n",
- "Out: ?u barAye xAstehAyaS besyAr moserr bud\n",
- "Ref: ?u barAye xAste-hAyaS besyAr moser bud\n",
- "Out: tule ?ommol va ?Arezu ?az CizhAyi ?ast ke nahy Sode\n",
- "Ref: tul-e ?amal va ?Arezu ?az Ciz-hAyi ?ast ke nahy Sode\n",
- "Out: ?ArAm dar bastareS xeffat\n",
- "Ref: ?ArAm dar bastaraS xoft\n",
- "Out: xodro pas ?az barxord Sodid bA divAre ?AtaS gereft\n",
- "Ref: xodro pas ?az barxord-e Sadid bA divAr ?AtaS gereft\n",
- "Out: bAzigare qabl ?az vorud be sahneye gerim Sod\n",
- "Ref: bAzigAr qabl ?az vorud be sahne Gerim Sod\n",
- "Out: kole ?in xAne rA begardi peydAyeS nemikani\n",
- "Ref: koll-e ?in xAne rA begardi peydAyaS nemikoni\n",
- "Out: nAxodA dastur dAd kaStiye lenger begirad\n",
- "Ref: nAxodA dastur dAd keSti langar beGirad\n",
- "Out: rume bAstAn tArixe mohemmi dArad\n",
- "Ref: rum-e bAstAn tArix-e mohemmi dArad\n",
- "Out: kard va lor va baluC hame ?az ?aqvAme ?irAni hastand\n",
- "Ref: kord va lor va baluC hame ?az ?aqvAm-e ?irAni hastand\n",
- "Out: nabAyad ?in kAr rA mikard\n",
- "Ref: nabAyad ?in kAr rA mi kard\n",
- "Out: to mesleye nafs dar riyeye mani\n",
- "Ref: to mesl-e nafas dar riyeye mani\n",
- "Out: nabarad ?irAn va ?erAqe haSt sAl be tul ?anjAmid\n",
- "Ref: nabard-e ?irAn va ?arAq haSt sAl be tul ?anjAmid\n",
- "Out: ?agar bardAreS rA bA xod be dAneSgAh nabord bad miSavad\n",
- "Ref: ?agar barAdaraS rA bA xod be dAneSgAh nabarad bad mi-Savad\n",
- "Out: ?az har berand nabAyad lebAs va kafS xarid\n",
- "Ref: ?az har berand nabAyad lebAs va kafS xarid\n",
- "Out: kam guy va gazide guye Con dar\n",
- "Ref: kam guy ?o gozide guy Con dorr\n",
- "PER: \t\t\t4.28\n",
- "ACC, PREC, RECALL, F1: \t98.17, 100.00, 86.68, 92.87\n",
- "POLYPHONE: \t\t75.94\n"
- ]
- }
- ],
- "source": [
- "print_all_metrics(mapped_outputs)"
- ]
- }
- ],
- "metadata": {
- "colab": {
- "provenance": []
- },
- "gpuClass": "standard",
- "kernelspec": {
- "display_name": "venv",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.10.12"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 0
- }
|