File size: 84,443 Bytes
1a27370 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 |
{
"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
}
|