Spaces:
Sleeping
Sleeping
File size: 95,785 Bytes
10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 e8be687 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f 10e27f9 ebc093f | 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 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 | """
ν
νλ¦Ώ κΈ°λ° μνκΈ°λ‘λΆ νμ
ν΅μ¬ λ‘μ§:
1. PDFμμ μ 체 ν
μ€νΈ μΆμΆ (νμ΄μ§λ³)
2. λ¬Έμ λ²μ κ°μ§ (ꡬλ²μ /μ λ²μ /λμ
μ ν)
3. κ³ μ νμ΄ν λ§€μΉμΌλ‘ μΉμ
κ²½κ³ μ°ΎκΈ°
4. μΉμ
λ³ νμλ‘ λ΄μ© μΆμΆ
"""
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Optional
import pdfplumber
from .section_template import (
SECTIONS,
SECTION_BY_ID,
CREATIVE_ACTIVITY_AREAS,
ACADEMIC_CATEGORIES,
ACADEMIC_CATEGORY_BY_ID,
DocVersion,
normalize_text,
detect_doc_version,
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# κ³Όλͺ©λͺ
λͺ©λ‘ (μΈνΉ νμ±μ©)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SUBJECT_NAMES = [
# κ΅μ΄
"κ΅μ΄", "λ¬Έν", "λ
μ", "νλ²κ³Ό μλ¬Έ", "μΈμ΄μ 맀체", "μ¬ν κ΅μ΄",
# μν
"μν", "μνβ
", "μνβ
‘", "λ―Έμ λΆ", "νλ₯ κ³Ό ν΅κ³", "κΈ°ν",
"μ¬ν μνβ
", "μ¬ν μνβ
‘", "μνμ μ¬κ³ μ μ λΆ", "κ³ κΈ μνβ
", "κ³ κΈ μνβ
‘",
# μμ΄
"μμ΄", "μμ΄β
", "μμ΄β
‘", "μμ΄ λ
ν΄μ μλ¬Έ", "μμ΄ νν", "μ€μ© μμ΄",
# νκ΅μ¬/μ¬ν
"νκ΅μ¬", "ν΅ν©μ¬ν", "νκ΅μ§λ¦¬", "μΈκ³μ§λ¦¬", "λμμμμ¬", "μΈκ³μ¬",
"κ²½μ ", "μ μΉμ λ²", "μ¬νΒ·λ¬Έν", "μ€λ¦¬μ μ¬μ", "μνκ³Ό μ€λ¦¬", "μ¬νμ§λ¦¬",
# κ³Όν
"ν΅ν©κ³Όν", "κ³Όννꡬμ€ν", "물리νβ
", "물리νβ
‘", "ννβ
", "ννβ
‘",
"μλͺ
κ³Όνβ
", "μλͺ
κ³Όνβ
‘", "μ§κ΅¬κ³Όνβ
", "μ§κ΅¬κ³Όνβ
‘",
"κ³ κΈ λ¬Όλ¦¬ν", "κ³ κΈ νν", "κ³ κΈ μλͺ
κ³Όν", "κ³ κΈ μ§κ΅¬κ³Όν",
"물리ν μ€ν", "νν μ€ν", "μλͺ
κ³Όν μ€ν", "μ§κ΅¬κ³Όν μ€ν",
# 체μ‘/μμ
"체μ‘", "μ΄λκ³Ό 건κ°", "μ€ν¬μΈ μν", "μ€ν¬μΈ λ¬Έν", "μ€ν¬μΈ κ³Όν",
"μμ
", "λ―Έμ ", "μ°κ·Ή", "μμ
μ°μ£Ό", "μμ
κ°μκ³Ό λΉν", "λ―Έμ μ°½μ", "λ―Έμ κ°μκ³Ό λΉν",
# κΈ°μ /κ°μ /μ 2μΈκ΅μ΄/κ΅μ
"μ 보", "κΈ°μ Β·κ°μ ", "μΌλ³Έμ΄β
", "μΌλ³Έμ΄β
‘", "μ€κ΅μ΄β
", "μ€κ΅μ΄β
‘",
"νλ¬Έβ
", "νλ¬Έβ
‘", "μ¬λ¦¬ν", "보건", "κ΅μ‘ν", "μ² ν", "λ
Όλ¦¬ν",
]
# κ³Όλͺ©λͺ
β κ΅κ³Όμμ λ§€ν
SUBJECT_TO_AREA = {
# κ΅μ΄
"κ΅μ΄": "κ΅μ΄", "λ¬Έν": "κ΅μ΄", "λ
μ": "κ΅μ΄", "νλ²κ³Ό μλ¬Έ": "κ΅μ΄",
"μΈμ΄μ 맀체": "κ΅μ΄", "μ¬ν κ΅μ΄": "κ΅μ΄",
# μν
"μν": "μν", "μνβ
": "μν", "μνβ
‘": "μν", "λ―Έμ λΆ": "μν",
"νλ₯ κ³Ό ν΅κ³": "μν", "κΈ°ν": "μν", "μ¬ν μνβ
": "μν", "μ¬ν μνβ
‘": "μν",
# μμ΄
"μμ΄": "μμ΄", "μμ΄β
": "μμ΄", "μμ΄β
‘": "μμ΄", "μμ΄ λ
ν΄μ μλ¬Έ": "μμ΄",
"μμ΄ νν": "μμ΄", "μ€μ© μμ΄": "μμ΄",
# νκ΅μ¬
"νκ΅μ¬": "νκ΅μ¬",
# μ¬ν
"ν΅ν©μ¬ν": "μ¬ν(μμ¬/λλν¬ν¨)", "νκ΅μ§λ¦¬": "μ¬ν(μμ¬/λλν¬ν¨)",
"μΈκ³μ§λ¦¬": "μ¬ν(μμ¬/λλν¬ν¨)", "λμμμμ¬": "μ¬ν(μμ¬/λλν¬ν¨)",
"μΈκ³μ¬": "μ¬ν(μμ¬/λλν¬ν¨)", "κ²½μ ": "μ¬ν(μμ¬/λλν¬ν¨)",
"μ μΉμ λ²": "μ¬ν(μμ¬/λλν¬ν¨)", "μ¬νΒ·λ¬Έν": "μ¬ν(μμ¬/λλν¬ν¨)",
"μ€λ¦¬μ μ¬μ": "μ¬ν(μμ¬/λλν¬ν¨)", "μνκ³Ό μ€λ¦¬": "μ¬ν(μμ¬/λλν¬ν¨)",
"μ¬νμ§λ¦¬": "μ¬ν(μμ¬/λλν¬ν¨)",
# κ³Όν
"ν΅ν©κ³Όν": "κ³Όν", "κ³Όννꡬμ€ν": "κ³Όν",
"물리νβ
": "κ³Όν", "물리νβ
‘": "κ³Όν",
"ννβ
": "κ³Όν", "ννβ
‘": "κ³Όν",
"μλͺ
κ³Όνβ
": "κ³Όν", "μλͺ
κ³Όνβ
‘": "κ³Όν",
"μ§κ΅¬κ³Όνβ
": "κ³Όν", "μ§κ΅¬κ³Όνβ
‘": "κ³Όν",
"κ³ κΈ λ¬Όλ¦¬ν": "κ³Όν", "κ³ κΈ νν": "κ³Όν",
"κ³ κΈ μλͺ
κ³Όν": "κ³Όν", "κ³ κΈ μ§κ΅¬κ³Όν": "κ³Όν",
# 체μ‘
"체μ‘": "체μ‘", "μ΄λκ³Ό 건κ°": "체μ‘", "μ€ν¬μΈ μν": "체μ‘",
"μ€ν¬μΈ λ¬Έν": "체μ‘", "μ€ν¬μΈ κ³Όν": "체μ‘",
# μμ
"μμ
": "μμ ", "λ―Έμ ": "μμ ", "μ°κ·Ή": "μμ ",
"μμ
μ°μ£Ό": "μμ ", "μμ
κ°μκ³Ό λΉν": "μμ ",
"λ―Έμ μ°½μ": "μμ ", "λ―Έμ κ°μκ³Ό λΉν": "μμ ", "맀체 λ―Έμ ": "μμ ",
# κΈ°μ Β·κ°μ /κ΅μ
"μ 보": "κΈ°μ Β·κ°μ /μ 2μΈκ΅μ΄/νλ¬Έ/κ΅μ", "κΈ°μ Β·κ°μ ": "κΈ°μ Β·κ°μ /μ 2μΈκ΅μ΄/νλ¬Έ/κ΅μ",
"μΌλ³Έμ΄β
": "κΈ°μ Β·κ°μ /μ 2μΈκ΅μ΄/νλ¬Έ/κ΅μ", "μ€κ΅μ΄β
": "κΈ°μ Β·κ°μ /μ 2μΈκ΅μ΄/νλ¬Έ/κ΅μ",
"νλ¬Έβ
": "κΈ°μ Β·κ°μ /μ 2μΈκ΅μ΄/νλ¬Έ/κ΅μ", "μ¬λ¦¬ν": "κΈ°μ Β·κ°μ /μ 2μΈκ΅μ΄/νλ¬Έ/κ΅μ",
}
@dataclass
class SectionBoundary:
"""μΉμ
κ²½κ³ μ 보 (Yμ’ν κΈ°λ°)"""
section_id: str
start_page: int # 0-indexed
start_y: float # μΉμ
μμ Yμ’ν (νμ΄μ§ λ΄)
end_page: int
end_y: float # μΉμ
λ Yμ’ν (νμ΄μ§ λ΄)
title_found: str # μ€μ μ°Ύμ νμ΄ν
@dataclass
class TableInfo:
"""ν
μ΄λΈ μ 보 (bbox ν¬ν¨)"""
page_num: int # 0-indexed
bbox: tuple # (x0, top, x1, bottom)
data: list # μΆμΆλ ν
μ΄λΈ λ°μ΄ν°
@property
def top_y(self) -> float:
"""ν
μ΄λΈ μλ¨ Yμ’ν"""
return self.bbox[1]
@property
def bottom_y(self) -> float:
"""ν
μ΄λΈ νλ¨ Yμ’ν"""
return self.bbox[3]
@dataclass
class PageText:
"""νμ΄μ§λ³ ν
μ€νΈ"""
page_num: int # 0-indexed
text: str
lines: list[str] = field(default_factory=list)
tables: list[TableInfo] = field(default_factory=list) # TableInfo 리μ€νΈ
page_height: float = 0.0 # νμ΄μ§ λμ΄ (Yμ’ν κ³μ°μ©)
class TemplateParser:
"""ν
νλ¦Ώ κΈ°λ° μνκΈ°λ‘λΆ νμ"""
def __init__(self, pdf_path: str):
self.pdf_path = Path(pdf_path)
if not self.pdf_path.exists():
raise FileNotFoundError(f"PDF νμΌμ μ°Ύμ μ μμ΅λλ€: {pdf_path}")
self.pages: list[PageText] = []
self.full_text: str = ""
self.doc_version: DocVersion = DocVersion.V1_8_SECTIONS
self.section_boundaries: dict[str, SectionBoundary] = {}
self._pdf = None # pdfplumber κ°μ²΄ μ°Έμ‘°
def parse(self) -> dict[str, Any]:
"""μ 체 νμ± μν"""
# 1. PDF λ‘λ λ° ν
μ€νΈ μΆμΆ
self._load_pdf()
# 2. λ¬Έμ λ²μ κ°μ§
self.doc_version = detect_doc_version(self.full_text)
# 3. μΉμ
κ²½κ³ μ°ΎκΈ°
self._find_section_boundaries()
# 4. κ° μΉμ
νμ±
result = {
"metadata": self._extract_metadata(),
"doc_version": self.doc_version.value,
"sections_found": {sid: bool(b) for sid, b in self.section_boundaries.items()},
}
# μΉμ
λ³ νμ±
result["student"] = self._parse_student_info()
result["class_history"] = self._parse_class_history()
result["academic_history"] = self._parse_academic_history()
result["attendance"] = self._parse_attendance()
result["awards"] = self._parse_awards()
result["creative_activities"] = self._parse_creative_activities()
result["academics"] = self._parse_academics()
result["reading_activities"] = self._parse_reading()
result["behavior_and_opinion"] = self._parse_behavior()
return result
def _load_pdf(self):
"""PDF λ‘λ λ° νμ΄μ§λ³ ν
μ€νΈ/ν
μ΄λΈ μΆμΆ (bbox ν¬ν¨)"""
with pdfplumber.open(self.pdf_path) as pdf:
self.pdf_metadata = pdf.metadata
for i, page in enumerate(pdf.pages):
text = page.extract_text() or ""
# ν
μ΄λΈμ TableInfoλ‘ λ³ν (bbox ν¬ν¨)
table_infos = []
for table in page.find_tables():
table_infos.append(TableInfo(
page_num=i,
bbox=table.bbox, # (x0, top, x1, bottom)
data=table.extract(),
))
page_text = PageText(
page_num=i,
text=text,
lines=text.split('\n') if text else [],
tables=table_infos,
page_height=page.height,
)
self.pages.append(page_text)
self.full_text += text + "\n"
# μΉμ
νμ΄ν Yμ’ν μΆμΆμ μν΄ words μ 보 μ μ₯
self._extract_title_positions(pdf)
def _extract_title_positions(self, pdf):
"""μΉμ
νμ΄νμ Yμ’ν μΆμΆ (pdfplumber words μ¬μ©)"""
self.title_positions = {} # {section_id: (page_num, y_top)}
for page_num, page in enumerate(pdf.pages):
words = page.extract_words()
# μΉμ
λ²νΈ ν¨ν΄ ("1.", "2.", ...) μ°ΎκΈ°
for i, word in enumerate(words):
text = word['text']
# "λ²νΈ." ν¨ν΄ νμΈ (μ: "1.", "7.")
num_match = re.match(r'^(\d+)\.$', text)
if not num_match:
continue
section_num = int(num_match.group(1))
y_top = word['top']
# λ€μ λ¨μ΄λ€μ ν©μ³μ νμ΄ν νμΈ
title_words = []
for j in range(i + 1, min(i + 5, len(words))): # μ΅λ 4λ¨μ΄ νμΈ
next_word = words[j]
# Yμ’νκ° λΉμ·νλ©΄ κ°μ μ€
if abs(next_word['top'] - y_top) < 5:
title_words.append(next_word['text'])
else:
break
title_text = ''.join(title_words)
norm_title = normalize_text(title_text)
# μΉμ
λ§€μΉ
for section in SECTIONS:
if section.id in self.title_positions:
continue # μ΄λ―Έ μ°Ύμ μΉμ
for title in section.titles:
if normalize_text(title) in norm_title or norm_title.startswith(normalize_text(title)[:4]):
self.title_positions[section.id] = (page_num, y_top)
break
else:
continue
break
def _find_section_boundaries(self):
"""Yμ’ν κΈ°λ° μΉμ
κ²½κ³ μ€μ
title_positionsμμ μΆμΆν Yμ’νλ₯Ό μ¬μ©νμ¬
κ° μΉμ
μ μμ/λ κ²½κ³λ₯Ό μ νν μ€μ
"""
if not hasattr(self, 'title_positions') or not self.title_positions:
return
# νμ΄μ§/Yμ’ν μμΌλ‘ μ λ ¬
sorted_sections = sorted(
self.title_positions.items(),
key=lambda x: (x[1][0], x[1][1]) # (page_num, y_top)
)
# κ²½κ³ μ€μ
for i, (section_id, (page_num, y_top)) in enumerate(sorted_sections):
# λ€μ μΉμ
μμΉ (λ κ²½κ³)
if i + 1 < len(sorted_sections):
next_section_id, (next_page, next_y) = sorted_sections[i + 1]
end_page = next_page
end_y = next_y
else:
# λ§μ§λ§ μΉμ
- λ¬Έμ λκΉμ§
end_page = len(self.pages) - 1
end_y = self.pages[-1].page_height if self.pages else 1000.0
self.section_boundaries[section_id] = SectionBoundary(
section_id=section_id,
start_page=page_num,
start_y=y_top,
end_page=end_page,
end_y=end_y,
title_found=f"{section_id}",
)
def _get_section_text(self, section_id: str) -> str:
"""μΉμ
IDλ‘ ν΄λΉ μΉμ
ν
μ€νΈ μΆμΆ
μ°Έκ³ : Yμ’ν κΈ°λ° μ λ° νν°λ§μ ν
μ΄λΈμλ§ μ μ©.
ν
μ€νΈλ νμ΄μ§ λ²μ λ΄ μ 체 ν
μ€νΈ λ°ν (보쑰 μ©λ)
"""
boundary = self.section_boundaries.get(section_id)
if not boundary:
return ""
lines = []
for page_num in range(boundary.start_page, boundary.end_page + 1):
if page_num >= len(self.pages):
break
page = self.pages[page_num]
lines.extend(page.lines)
return '\n'.join(lines)
def _get_section_tables(self, section_id: str) -> list:
"""μΉμ
IDλ‘ ν΄λΉ μΉμ
ν
μ΄λΈ μΆμΆ (Yμ’ν κΈ°λ° νν°λ§)
ν
μ΄λΈμ top_yκ° μΉμ
μ Y λ²μ λ΄μ μλ κ²½μ°λ§ λ°ν
- 첫 λ²μ§Έ μΉμ
: νμ΄μ§ μμ(Y=0)λΆν° ν¬ν¨ (λ¬Έμ ν€λ ν¬ν¨)
- νμ΄ν λ§μ§: νμ΄νμ΄ ν
μ΄λΈ λ΄λΆμ μλ κ²½μ° μ²λ¦¬
"""
boundary = self.section_boundaries.get(section_id)
if not boundary:
return []
# νμ΄νμ΄ ν
μ΄λΈ λ΄λΆμ μμ μ μμΌλ―λ‘ λ§μ§ μ μ©
MARGIN = 20.0
# 첫 λ²μ§Έ μΉμ
μΈμ§ νμΈ (μΈμ νμ )
is_first_section = section_id == "μΈμ νμ "
tables = []
for page_num in range(boundary.start_page, boundary.end_page + 1):
if page_num >= len(self.pages):
break
for table_info in self.pages[page_num].tables:
table_y = table_info.top_y
# μμ νμ΄μ§ νν°λ§
if page_num == boundary.start_page:
# 첫 λ²μ§Έ μΉμ
: νμ΄μ§ μμλΆν° ν¬ν¨
if is_first_section:
pass # μμ Y μ ν μμ
elif table_y < (boundary.start_y - MARGIN):
continue
# λ νμ΄μ§ νν°λ§: end_y - MARGIN λ―Έλ§λ§
if page_num == boundary.end_page and table_y >= (boundary.end_y - MARGIN):
continue
tables.append(table_info.data)
return tables
def _get_section_tables_with_page(self, section_id: str) -> list[tuple[int, float, list]]:
"""μΉμ
ν
μ΄λΈμ (page_num, table_y, table_data) νν 리μ€νΈλ‘ λ°ν
κ΅κ³Όνμ΅λ°λ¬μν© νμ± μ νμ΄μ§λ³ νλ
λ§€ν λ° Yμ’ν κΈ°λ° λ§μ»€ μ μ©μ μ¬μ©
"""
boundary = self.section_boundaries.get(section_id)
if not boundary:
return []
MARGIN = 20.0
is_first_section = section_id == "μΈμ νμ "
tables = []
for page_num in range(boundary.start_page, boundary.end_page + 1):
if page_num >= len(self.pages):
break
for table_info in self.pages[page_num].tables:
table_y = table_info.top_y
if page_num == boundary.start_page:
if is_first_section:
pass
elif table_y < (boundary.start_y - MARGIN):
continue
if page_num == boundary.end_page and table_y >= (boundary.end_y - MARGIN):
continue
tables.append((page_num, table_y, table_info.data))
return tables
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# λ©νλ°μ΄ν° μΆμΆ
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _extract_metadata(self) -> dict:
"""λ¬Έμ λ©νλ°μ΄ν° μΆμΆ"""
metadata = {
"document_number": None,
"school_name": None,
"issue_date": None,
"total_pages": len(self.pages),
"pdf_metadata": self.pdf_metadata if hasattr(self, 'pdf_metadata') else {},
}
if self.pages:
first_text = self.pages[0].text
# λ¬ΈμνμΈλ²νΈ
doc_match = re.search(r"λ¬ΈμνμΈλ²νΈ\s*[:οΌ]?\s*([A-Za-z0-9\-]+)", first_text)
if doc_match:
metadata["document_number"] = doc_match.group(1)
# νκ΅λͺ
school_match = re.search(r"([κ°-ν£]+κ³ λ±νκ΅)", first_text)
if school_match:
metadata["school_name"] = school_match.group(1)
# λ°κΈμΌ
date_match = re.search(r"(\d{4}λ
\s*\d{1,2}μ\s*\d{1,2}μΌ)", first_text)
if date_match:
metadata["issue_date"] = date_match.group(1)
return metadata
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# μΈμ Β·νμ μ¬ν νμ±
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_student_info(self) -> dict:
"""νμ κΈ°λ³Έ μ 보 νμ±"""
text = self._get_section_text("μΈμ νμ ")
student = {
"name": None,
"gender": None,
"resident_number": None,
"address": None,
}
# μ±λͺ
- μ½λ‘ μ΄ μλ ν¨ν΄λ§ λ§€μΉ (λ΄μμ±λͺ
vs μ±λͺ
: ꡬλΆ)
name_match = re.search(r"μ±λͺ
\s*[:οΌ]\s*([κ°-ν£]+)", text)
if name_match:
student["name"] = name_match.group(1)
# μ±λ³
gender_match = re.search(r"μ±λ³\s*[:οΌ]?\s*([λ¨μ¬])", text)
if gender_match:
student["gender"] = gender_match.group(1)
# μ£Όλ―Όλ±λ‘λ²νΈ
rrn_match = re.search(r"μ£Όλ―Όλ±λ‘λ²νΈ\s*[:οΌ]?\s*(\d{6}[-\s]*[\d*]+)", text)
if rrn_match:
student["resident_number"] = rrn_match.group(1)
# μ£Όμ
addr_match = re.search(r"μ£Όμ\s*[:οΌ]?\s*(.+?)(?=\n\d{4}λ
|\nνμ |$)", text, re.DOTALL)
if addr_match:
student["address"] = addr_match.group(1).strip().replace('\n', ' ')
return student
def _parse_class_history(self) -> list[dict]:
"""νλ° μ 보 νμ± (Yμ’ν κΈ°λ° νν°λ§μΌλ‘ κ°μν)"""
tables = self._get_section_tables("μΈμ νμ ")
class_history = []
for table in tables:
if not table:
continue
# νλ
, λ°, λ²νΈ μ»¬λΌ μ°ΎκΈ°
header_row = None
for row in table:
if row:
row_text = ''.join(str(c) for c in row if c)
# νλ° ν
μ΄λΈ: "νλ
" AND ("λ°" OR "λ²νΈ" λλ "λ΄μ") νμ
has_grade = "νλ
" in row_text
has_class_info = "λ°" in row_text or "λ²νΈ" in row_text or "λ΄μ" in row_text
if has_grade and has_class_info:
header_row = row
break
if not header_row:
continue
# ν€λ μΈλ±μ€ μ°ΎκΈ°
indices = {}
for i, cell in enumerate(header_row):
if not cell:
continue
cell_str = str(cell)
if "νλ
" in cell_str:
indices["grade"] = i
elif "λ°" in cell_str and "λ²" not in cell_str:
indices["class"] = i
elif "λ²νΈ" in cell_str or ("λ²" in cell_str and "λ°" not in cell_str):
indices["number"] = i
elif "λ΄μ" in cell_str:
indices["teacher"] = i
elif "νκ³Ό" in cell_str:
indices["department"] = i
# λ°μ΄ν° ν νμ±
for row in table:
if row == header_row or not row:
continue
try:
grade_val = row[indices.get("grade", 0)]
if not grade_val or not str(grade_val).strip().isdigit():
continue
entry = {
"grade": int(grade_val),
"department": None,
"class_number": None,
"student_number": None,
"homeroom_teacher": None,
}
if "department" in indices and indices["department"] < len(row):
entry["department"] = row[indices["department"]] or None
if "class" in indices and indices["class"] < len(row):
val = row[indices["class"]]
if val and str(val).strip().isdigit():
entry["class_number"] = int(val)
if "number" in indices and indices["number"] < len(row):
val = row[indices["number"]]
if val and str(val).strip().isdigit():
entry["student_number"] = int(val)
if "teacher" in indices and indices["teacher"] < len(row):
entry["homeroom_teacher"] = row[indices["teacher"]] or None
class_history.append(entry)
except (IndexError, ValueError, TypeError):
continue
return class_history
def _parse_academic_history(self) -> dict:
"""νμ μ¬ν νμ±"""
text = self._get_section_text("μΈμ νμ ")
entries = []
# YYYYλ
MMμ DDμΌ ν¨ν΄
matches = re.findall(
r"(\d{4}λ
\s*\d{1,2}μ\s*\d{1,2}μΌ)\s*([κ°-ν£]+(?:νκ΅|κ³ λ±νκ΅))\s*(.+?)(?=\d{4}λ
|$)",
text, re.DOTALL
)
for date, school, content in matches:
entries.append(f"{date} {school} {content.strip()}")
return {
"entries": entries,
"special_notes": None,
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# μΆκ²°μν© νμ±
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_attendance(self) -> list[dict]:
"""μΆκ²°μν© νμ± (Yμ’ν κΈ°λ° νν°λ§μΌλ‘ κ°μν)"""
tables = self._get_section_tables("μΆκ²°")
attendance = []
for table in tables:
if not table or len(table) < 2:
continue
# ν€λ ν μ°ΎκΈ° (κ²°μ, μ§κ° λ± ν¬ν¨)
header_idx = 0
for i, row in enumerate(table):
if row and any("κ²°μ" in str(c) or "μ§κ°" in str(c) for c in row if c):
header_idx = i
break
# λ°μ΄ν° ν νμ± (νλ
1, 2, 3)
for row in table[header_idx + 1:]:
if not row or len(row) < 2:
continue
grade_val = row[0]
if not grade_val or not str(grade_val).strip().isdigit():
continue
grade = int(grade_val)
if grade not in [1, 2, 3]:
continue
entry = {
"grade": grade,
"school_days": self._safe_int(row[1] if len(row) > 1 else None),
"absence": {"illness": 0, "unauthorized": 0, "other": 0},
"late": {"illness": 0, "unauthorized": 0, "other": 0},
"early_leave": {"illness": 0, "unauthorized": 0, "other": 0},
"class_absence": {"illness": 0, "unauthorized": 0, "other": 0},
"special_notes": None,
}
# μ»¬λΌ λ§€ν (κ²°μ 3κ° + μ§κ° 3κ° + μ‘°ν΄ 3κ° + κ²°κ³Ό 3κ° + νΉκΈ°μ¬ν)
idx = 2
for category in ["absence", "late", "early_leave", "class_absence"]:
for sub in ["illness", "unauthorized", "other"]:
if idx < len(row):
entry[category][sub] = self._safe_int(row[idx])
idx += 1
# νΉκΈ°μ¬ν (λ§μ§λ§ 컬λΌ)
if idx < len(row) and row[idx]:
entry["special_notes"] = str(row[idx]).strip() or None
attendance.append(entry)
return attendance
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# μμκ²½λ ₯ νμ±
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_awards(self) -> list[dict]:
"""μμκ²½λ ₯ νμ±"""
tables = self._get_section_tables("μμ")
awards = []
current_grade = None # λ³ν©λ μ
μ²λ¦¬μ©
current_semester = None # λ³ν©λ νκΈ° μ
μ²λ¦¬μ©
for table in tables:
if not table:
continue
# μμλͺ
μ»¬λΌ νμΈ
has_award = any(
row and any("μμ" in str(c) or "μλͺ
" in str(c) for c in row if c)
for row in table
)
if not has_award:
continue
for row in table:
if not row or len(row) < 4:
continue
# ν€λ ν μ€ν΅ (μμλͺ
, νλ
λ± ν¬ν¨)
row_text = ' '.join(str(c) for c in row if c)
if "μμλͺ
" in row_text or "μ μ λͺ
" in row_text or "μμκ²½λ ₯" in row_text:
continue
# 첫 컬λΌμμ νλ
νμΈ (λ³ν©λ μ
μ NoneμΌ μ μμ)
grade_val = row[0]
if grade_val and str(grade_val).strip().isdigit():
new_grade = int(grade_val)
if new_grade in [1, 2, 3]:
current_grade = new_grade
# νλ
μ΄ μμΌλ©΄ μ€ν΅ (첫 νμ΄κ±°λ ν€λ)
if current_grade is None:
continue
grade = current_grade
# νκΈ° νμΈ (λ λ²μ§Έ 컬λΌ, λ³ν© μ None)
semester_val = row[1] if len(row) > 1 else None
if semester_val and str(semester_val).strip() in ["1", "2"]:
current_semester = int(semester_val)
elif semester_val is None or str(semester_val).strip() == "":
# λ³ν©λ μ
- μ΄μ νκΈ° μ μ§ (current_semester κ·Έλλ‘)
pass
entry = {
"grade": grade,
"semester": current_semester,
"name": None,
"rank": None,
"date": None,
"organization": None,
"participants": None,
}
# λλ¨Έμ§ μ»¬λΌ (κ°ν λ¬Έμ μ κ±°)
# ν
μ΄λΈ ꡬ쑰: [νλ
, νκΈ°, μμλͺ
, λ±κΈ, μμμΌ, μμ¬κΈ°κ΄, μ°Έκ°λμ]
def clean_cell(val):
if not val:
return None
return str(val).replace('\n', '').strip() or None
if len(row) > 2:
entry["name"] = clean_cell(row[2])
if len(row) > 3:
entry["rank"] = clean_cell(row[3])
if len(row) > 4:
entry["date"] = clean_cell(row[4])
if len(row) > 5:
entry["organization"] = clean_cell(row[5])
if len(row) > 6:
entry["participants"] = clean_cell(row[6])
if entry["name"]:
awards.append(entry)
return awards
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# μ°½μμ 체ννλ νμ±
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_creative_activities(self) -> dict:
"""μ°½μμ 체ννλ νμ± - Yμ’ν κΈ°λ° μ
bbox λ°©μ
κΈ°μ‘΄ prefix ν
μ€νΈ κ²μ λ°©μμ λ¬Έμ μ (μμ κ²½κ³ νΌλ, ν€λ νΌμ
) ν΄κ²°μ μν΄
μ
bbox κΈ°λ° νλ
/μμ λ§€ν + chars κΈ°λ° λ΄μ© μΆμΆ λ°©μμΌλ‘ μ ν
"""
result = {
"autonomous": [], # μμ¨νλ
"club": [], # λμ리νλ
"career": [], # μ§λ‘νλ
"volunteer": [], # λ΄μ¬νλ
}
# (grade, area) -> entry λ§€ν (νμ΄μ§ λκΉ λ³ν©μ©)
entries = {}
boundary = self.section_boundaries.get("창체")
if not boundary:
return result
with pdfplumber.open(self.pdf_path) as pdf:
for page_num in range(boundary.start_page, min(boundary.end_page + 1, len(pdf.pages))):
page = pdf.pages[page_num]
tables = page.find_tables()
words = page.extract_words()
chars = page.chars
for table in tables:
table_data = table.extract()
table_text = ' '.join(str(c) for row in table_data[:4] for c in row if c)
# λ΄μ¬νλ ν
μ΄λΈ μ²λ¦¬
if "λ΄μ¬νλ" in table_text or "λκ³μκ°" in table_text or "μΌμ λλ κΈ°κ°" in table_text:
result["volunteer"].extend(self._parse_volunteer_table(table_data))
continue
# 창체 ν
μ΄λΈ νμΈ (λμ΄μ°κΈ° λ³ν μ²λ¦¬)
normalized = table_text.replace(' ', '')
is_creative = ('μ°½μμ ' in normalized or 'μμ¨νλ' in normalized or
'λμ리νλ' in normalized or 'μ§λ‘νλ' in normalized)
is_volunteer = 'λ΄μ¬νλ' in normalized or 'λκ³μκ°' in normalized
if not is_creative or is_volunteer:
continue
bbox = table.bbox
cells = table.cells
# 1. νλ
μ
μ°ΎκΈ° (첫 λ²μ§Έ 컬λΌ, 1/2/3 κ°)
grade_cells = [] # [(grade, y0, y1)]
for cell in cells:
x0, y0, x1, y1 = cell
if x0 < bbox[0] + 50: # 첫 λ²μ§Έ 컬λΌ
try:
cropped = page.within_bbox(cell)
text = (cropped.extract_text() or '').strip()
if text in ['1', '2', '3']:
grade_cells.append((int(text), y0, y1))
except Exception:
pass
# 2. μμ μ
κ³Ό λ΄μ© μ
μ°ΎκΈ°
area_markers = []
for cell in cells:
x0, y0, x1, y1 = cell
try:
cropped = page.within_bbox(cell)
text = (cropped.extract_text() or '').strip()
if text in ['μμ¨νλ', 'λμ리νλ', 'μ§λ‘νλ']:
# λ΄μ© μ
X μμ μμΉ μ°ΎκΈ°
content_cell_x0 = None
for cell2 in cells:
cx0, cy0, cx1, cy1 = cell2
if (cy1 > y0 + 5 and cy0 < y1 - 5 and
cx0 > x1 and cx1 > bbox[2] - 50):
if content_cell_x0 is None or cx0 < content_cell_x0:
content_cell_x0 = cx0
if content_cell_x0 is None:
content_cell_x0 = x1 + 30
# νλ
λ§€ν (μμ μ
μ€μ¬μ κΈ°μ€)
area_center_y = (y0 + y1) / 2
matched_grade = None
for grade, gy0, gy1 in grade_cells:
if gy0 <= area_center_y <= gy1:
matched_grade = grade
break
# μκ° μ°ΎκΈ°
hours = 0
for w2 in words:
if (y0 <= w2['top'] <= y1 and
w2['text'].isdigit() and
5 <= int(w2['text']) <= 200):
hours = int(w2['text'])
break
# ν¬λ§λΆμΌ μ°ΎκΈ° (μ§λ‘νλ)
desired_field = None
content_start_y = y0
if 'μ§λ‘' in text:
for cell2 in cells:
cx0, cy0, cx1, cy1 = cell2
if cy0 >= y0 and cy1 <= y1:
try:
cropped2 = page.within_bbox(cell2)
cell_text = (cropped2.extract_text() or '').strip()
if cell_text == 'ν¬λ§λΆμΌ':
for cell3 in cells:
dx0, dy0, dx1, dy1 = cell3
if (abs(dy0 - cy0) < 5 and dx0 >= cx1 and
abs(dy1 - cy1) < 5 and dx0 != cx0):
cropped3 = page.within_bbox(cell3)
desired_field = (cropped3.extract_text() or '').strip()
break
content_start_y = cy1
break
except Exception:
pass
area_markers.append({
'area': text.replace('νλ', ''),
'grade': matched_grade,
'y0': y0,
'y1': y1,
'content_start_y': content_start_y,
'content_x': content_cell_x0,
'hours': hours,
'desired_field': desired_field,
})
except Exception:
pass
area_markers.sort(key=lambda x: x['y0'])
# 3. κ° μμμ λ΄μ© μΆμΆ (chars κΈ°λ°)
for marker in area_markers:
if marker['grade'] is None:
continue
start_y = marker['content_start_y']
end_y = marker['y1']
content_x = marker['content_x']
content_chars = [
c for c in chars
if start_y <= c['top'] < end_y
and c['x0'] >= content_x
and bbox[0] <= c['x0'] <= bbox[2]
]
# Yλ³ κ·Έλ£Ήν β Xμ μ λ ¬ β ν
μ€νΈ μ‘°ν©
lines = {}
for c in content_chars:
y = round(c['top'], 0)
if y not in lines:
lines[y] = []
lines[y].append(c)
content_parts = []
for y in sorted(lines.keys()):
line_text = ''.join(c['text'] for c in sorted(lines[y], key=lambda x: x['x0']))
content_parts.append(line_text)
content = ' '.join(content_parts).strip()
# κΈ°μ‘΄ νλͺ©κ³Ό λ³ν© (νμ΄μ§ λκΉ μ²λ¦¬)
key = (marker['grade'], marker['area'])
if key in entries:
entries[key]['details'] += ' ' + content
else:
entries[key] = {
'grade': marker['grade'],
'area': marker['area'],
'hours': marker['hours'],
'details': content,
'desired_field': marker['desired_field'],
}
# κ²°κ³Ό μ 리
for (grade, area), entry in entries.items():
details = entry['details'].strip()
restricted = '곡곡기κ΄μ μ 보곡κ°μ κ΄ν λ²λ₯ ' in details
if restricted:
details = "λΉκ³΅κ°"
if area == 'μμ¨':
result['autonomous'].append({
'grade': entry['grade'],
'hours': entry['hours'],
'details': details,
'restricted': restricted,
})
elif area == 'λμ리':
club_name, cleaned_details = self._extract_club_name(details)
result['club'].append({
'grade': entry['grade'],
'hours': entry['hours'],
'club_name': club_name if not restricted else None,
'details': cleaned_details if not restricted else "λΉκ³΅κ°",
'restricted': restricted,
})
elif area == 'μ§λ‘':
desired_field = entry['desired_field']
if desired_field and '곡곡기κ΄' in desired_field:
desired_field = None
result['career'].append({
'grade': entry['grade'],
'hours': entry['hours'],
'desired_field': desired_field if not restricted else None,
'details': details,
'restricted': restricted,
})
# νλ
μ μ λ ¬
for key in ['autonomous', 'club', 'career']:
result[key].sort(key=lambda x: x['grade'])
return result
def _extract_club_name(self, content: str) -> tuple:
"""λμ리λͺ
μΆμΆ - (λμ리λͺ
)(μκ°) ν¨ν΄
Returns: (club_name, cleaned_content)
"""
match = re.match(r'^\(([^)]+(?:\([^)]+\))?[^)]*)\)\s*\((\d+)μκ°\)\s*', content)
if match:
club_name = match.group(1)
cleaned = content[match.end():].strip()
return club_name, cleaned
return None, content
def _normalize_for_matching(self, text: str) -> str:
"""ν
μ€νΈ μ κ·ν (νΉμλ¬Έμ μ°¨μ΄ ν΄κ²°)
PDFμ ν
μ΄λΈ μΆμΆκ³Ό ν
μ€νΈ μΆμΆμμ νΉμλ¬Έμκ° λ€λ₯΄κ² λμ¬ μ μμ:
- κ΄νΈ: () vs οΌοΌ vs ο½ο½
- μ : . vs οΌ vs γ»
- 곡백 μ°¨μ΄
νκΈκ³Ό μ«μλ§ μΆμΆνμ¬ λΉκ΅
"""
# νκΈ, μλ¬Έ, μ«μλ§ μΆμΆ
normalized = re.sub(r'[^κ°-ν£a-zA-Z0-9]', '', text)
return normalized
def _find_prefix_in_text(self, prefix: str, full_text: str) -> int:
"""prefixμ μμΉλ₯Ό full_textμμ μ°ΎκΈ° (μ κ·ν λΉκ΅)
Returns: μμ μμΉ (μ°Ύμ§ λͺ»νλ©΄ -1)
"""
if not prefix:
return -1
# μ κ·νλ prefix (νκΈ+μ«μλ§)
norm_prefix = self._normalize_for_matching(prefix[:20])
if len(norm_prefix) < 5:
return -1
# full_textλ₯Ό μ€μΊνλ©΄μ μ κ·ν λΉκ΅
# μ¬λΌμ΄λ© μλμ°λ‘ κ²μ
for i in range(len(full_text) - 10):
# νμ¬ μμΉλΆν° 40μ μ λ μΆμΆνμ¬ μ κ·ν
window = full_text[i:i + 40]
norm_window = self._normalize_for_matching(window)
# prefixκ° windowμ ν¬ν¨λλμ§ νμΈ
if norm_prefix[:10] in norm_window:
return i
return -1
def _get_creative_area_id(self, area_text: str) -> str:
"""μμ ν
μ€νΈμμ μμ ID λ°ν"""
area_text = area_text.strip()
if "μμ¨" in area_text:
return "μμ¨"
elif "λμ리" in area_text:
return "λμ리"
elif "μ§λ‘" in area_text:
return "μ§λ‘"
return ""
def _add_creative_entry(self, result: dict, area_id: str, grade: int,
hours: int, details: str, desired_field: str = None,
restricted: bool = False):
"""창체 νλͺ© μΆκ°"""
if area_id == "μμ¨":
result["autonomous"].append({
"grade": grade,
"hours": hours,
"details": details,
"restricted": restricted,
})
elif area_id == "λμ리":
result["club"].append({
"grade": grade,
"club_name": None, # detailsμμ μΆμΆ κ°λ₯
"hours": hours,
"details": details,
"restricted": restricted,
})
elif area_id == "μ§λ‘":
result["career"].append({
"grade": grade,
"hours": hours,
"desired_field": desired_field,
"details": details,
"restricted": restricted,
})
def _parse_volunteer_table(self, table: list) -> list[dict]:
"""λ΄μ¬νλ ν
μ΄λΈ νμ±"""
volunteers = []
current_grade = None
for row in table:
if not row or len(row) < 2:
continue
# μ
κ° μΆμΆ (None μ²λ¦¬)
def safe_cell(idx):
if len(row) <= idx:
return ""
val = row[idx]
if val is None or val == '':
return ""
return str(val).strip()
grade_val = safe_cell(0)
data_col = safe_cell(1)
# ν€λ ν μ€ν΅ (λ ꡬ체μ μΈ μ‘°κ±΄)
# 1) 첫 λ²μ§Έ μ΄μ΄ "νλ
" λλ "ν λ
" (νλ
μ΄ ν€λ)
# 2) λ λ²μ§Έ μ΄μ΄ "μΌμ" λλ "λ΄ μ¬" μμ (μ΄ ν€λ)
is_header = False
if grade_val and ("νλ
" in grade_val or "ν λ
" in grade_val):
is_header = True
if data_col and (data_col.startswith("μΌμ") or data_col.startswith("λ΄ μ¬")):
is_header = True
if is_header:
continue
# νλ
μΆμΆ (첫 λ²μ§Έ μ΄)
if grade_val and grade_val.isdigit() and 1 <= int(grade_val) <= 3:
current_grade = int(grade_val)
# λ΄μ¬νλ λ°μ΄ν° (λ μ§ ν¨ν΄μΌλ‘ κ°μ§)
# νμ: νλ
| μΌμ λλ κΈ°κ° + μ₯μ + νλλ΄μ© (λ³ν©) | ...
date_match = re.search(r'(\d{4}\.\d{2}\.\d{2})', data_col)
if date_match and current_grade:
entry = {
"grade": current_grade,
"date": date_match.group(1),
"location": None,
"activity": data_col.replace('\n', ' '), # κ°ν μ κ±°
"hours": None,
"cumulative_hours": None,
}
# μκ°/λκ³μκ° μΆμΆ (μλ κ²½μ°)
if len(row) > 4:
entry["hours"] = self._safe_int(row[4])
if len(row) > 5:
entry["cumulative_hours"] = self._safe_int(row[5])
volunteers.append(entry)
return volunteers
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# κ΅κ³Όνμ΅λ°λ¬μν© νμ±
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _get_page_markers_with_y(self, page_num: int) -> list[tuple[float, str, Any]]:
"""νμ΄μ§μμ νλ
/μΉ΄ν
κ³ λ¦¬ λ§μ»€μ Yμ’ν μΆμΆ
Returns:
[(y_coord, marker_type, marker_value), ...]
marker_type: "grade" or "category"
marker_value: 1/2/3 for grade, "μΌλ°"/"μ§λ‘μ ν"/"체μ‘μμ " for category
"""
if page_num >= len(self.pages):
return []
markers = []
# pdfplumberλ‘ νμ΄μ§ λ€μ μ΄μ΄μ chars μ κ·Ό
with pdfplumber.open(self.pdf_path) as pdf:
if page_num >= len(pdf.pages):
return []
page = pdf.pages[page_num]
chars = page.chars
if not chars:
return []
current_y = None
current_text = ""
for char in chars:
# Yμ’νκ° λ°λλ©΄ μ΄μ μ€ μ²λ¦¬
if current_y is None or abs(char['top'] - current_y) > 5:
if current_text.strip():
# νλ
λ§μ»€ νμΈ
if "[1νλ
]" in current_text:
markers.append((current_y, "grade", 1))
elif "[2νλ
]" in current_text:
markers.append((current_y, "grade", 2))
elif "[3νλ
]" in current_text:
markers.append((current_y, "grade", 3))
# μΉ΄ν
κ³ λ¦¬ λ§μ»€ νμΈ
if "<μ§λ‘ μ ν" in current_text or "<μ§λ‘μ ν" in current_text or "μ§λ‘ μ ν κ³Όλͺ©" in current_text:
markers.append((current_y, "category", "μ§λ‘μ ν"))
elif "<체μ‘" in current_text or "체μ‘γμμ " in current_text or "체μ‘Β·μμ " in current_text:
markers.append((current_y, "category", "체μ‘μμ "))
current_y = char['top']
current_text = char['text']
else:
current_text += char['text']
# λ§μ§λ§ μ€ μ²λ¦¬
if current_text.strip():
if "[1νλ
]" in current_text:
markers.append((current_y, "grade", 1))
elif "[2νλ
]" in current_text:
markers.append((current_y, "grade", 2))
elif "[3νλ
]" in current_text:
markers.append((current_y, "grade", 3))
if "<μ§λ‘ μ ν" in current_text or "<μ§λ‘μ ν" in current_text or "μ§λ‘ μ ν κ³Όλͺ©" in current_text:
markers.append((current_y, "category", "μ§λ‘μ ν"))
elif "<체μ‘" in current_text or "체μ‘γμμ " in current_text or "체μ‘Β·μμ " in current_text:
markers.append((current_y, "category", "체μ‘μμ "))
return sorted(markers, key=lambda x: x[0])
def _find_personal_remarks_by_y(self) -> list[dict]:
"""Yμ’ν κΈ°λ° κ°μΈμΈνΉ κ°μ§
2λ°° μ€κ°κ²© ν κ³Όλͺ©λͺ
: ν¨ν΄ μμ΄ μμνλ ν
μ€νΈλ₯Ό κ°μΈμΈνΉμΌλ‘ κ°μ§
Returns:
[{"page": int, "y": float, "text": str, "grade": int}, ...]
"""
results = []
boundary = self.section_boundaries.get("κ΅κ³Ό")
if not boundary:
return results
with pdfplumber.open(self.pdf_path) as pdf:
# νμ¬ νλ
μΆμ (νμ΄μ§ κ° μ μ§)
current_grade = 1
for page_num in range(boundary.start_page, boundary.end_page + 1):
if page_num >= len(pdf.pages):
continue
page = pdf.pages[page_num]
chars = page.chars
if not chars:
continue
# λΌμΈλ³ κ·Έλ£Ήν
lines_by_y = {}
for char in chars:
y = round(char['top'], 1)
if y not in lines_by_y:
lines_by_y[y] = ''
lines_by_y[y] += char['text']
sorted_ys = sorted(lines_by_y.keys())
if len(sorted_ys) < 3:
continue
# νκ· μ€κ°κ²© κ³μ° (μΌλ°μ μΈ λ²μ: 8-20)
gaps = [sorted_ys[i] - sorted_ys[i-1] for i in range(1, len(sorted_ys))]
normal_gaps = [g for g in gaps if 8 < g < 20]
if not normal_gaps:
continue
avg_gap = sum(normal_gaps) / len(normal_gaps)
# νλ
λ§μ»€ νμΈ λ° κ°μΈμΈνΉ κ°μ§
prev_y = sorted_ys[0]
for y in sorted_ys[1:]:
text = lines_by_y[y].strip()
# νλ
λ§μ»€ μ
λ°μ΄νΈ
if "[1νλ
]" in text:
current_grade = 1
elif "[2νλ
]" in text:
current_grade = 2
elif "[3νλ
]" in text:
current_grade = 3
gap = y - prev_y
# 2λ°° κ°κ²© κ°μ§ (1.7λ°° μ΄μ)
if gap > avg_gap * 1.7:
# κ³Όλͺ©λͺ
: ν¨ν΄μΌλ‘ μμνλμ§ νμΈ
if not self._starts_with_subject_pattern(text):
# λ
Έμ΄μ¦ νν°λ§
if self._is_valid_personal_remark(text):
results.append({
"page": page_num,
"y": y,
"text": text,
"grade": current_grade,
})
prev_y = y
return results
def _starts_with_subject_pattern(self, text: str) -> bool:
"""ν
μ€νΈκ° 'κ³Όλͺ©λͺ
:' ν¨ν΄μΌλ‘ μμνλμ§ νμΈ"""
import re
text = text.strip()
# (1νκΈ°), (2νκΈ°) μ λμ¬ μ κ±°
text = re.sub(r'^\(?\dνκΈ°\)?\s*', '', text)
# μ½λ‘ μμ ν
μ€νΈκ° κ³Όλͺ©λͺ
μΈμ§ νμΈ
colon_match = re.match(r'^([^:οΌ]{1,25})[:οΌ]', text)
if colon_match:
potential_subject = colon_match.group(1).strip()
# κ³Όλͺ©λͺ
νΉμ±: νκΈ μμ£Ό, λ‘λ§μ«μ ν¬ν¨ κ°λ₯
if re.match(r'^[κ°-ν£\sΒ·β
β
‘]+$', potential_subject):
return True
return False
def _is_valid_personal_remark(self, text: str) -> bool:
"""κ°μΈμΈνΉμΌλ‘ μ ν¨ν ν
μ€νΈμΈμ§ νμΈ (λ
Έμ΄μ¦ νν°λ§)"""
import re
if len(text) < 30:
return False
# λ
Έμ΄μ¦ ν¨ν΄
noise_patterns = [
r'^κ³Όλͺ©\s+μΈ\s*λΆ', # ν
μ΄λΈ ν€λ
r'κ³ λ±νκ΅.*\d{4}λ
', # νμ΄μ§ νΈν°
r'^\d+\s*/\s*\d+', # νμ΄μ§ λ²νΈ (1 / 21)
r'^νκΈ°\s+κ΅κ³Ό', # μ±μ ν
μ΄λΈ ν€λ
r'^<μ§λ‘\s*μ ν', # μΉ΄ν
κ³ λ¦¬ λ§μ»€
r'^<체μ‘', # μΉ΄ν
κ³ λ¦¬ λ§μ»€
]
for pattern in noise_patterns:
if re.search(pattern, text):
return False
return True
def _get_full_text_from_y(self, page_num: int, start_y: float) -> str:
"""νΉμ Yμ’νλΆν° λ€μ 2λ°° κ°κ²© λλ κ³Όλͺ© μμκΉμ§μ μ 체 ν
μ€νΈ μΆμΆ"""
with pdfplumber.open(self.pdf_path) as pdf:
if page_num >= len(pdf.pages):
return ""
page = pdf.pages[page_num]
chars = page.chars
if not chars:
return ""
# λΌμΈλ³ κ·Έλ£Ήν
lines_by_y = {}
for char in chars:
y = round(char['top'], 1)
if y not in lines_by_y:
lines_by_y[y] = ''
lines_by_y[y] += char['text']
sorted_ys = sorted(lines_by_y.keys())
# νκ· μ€κ°κ²© κ³μ°
gaps = [sorted_ys[i] - sorted_ys[i-1] for i in range(1, len(sorted_ys))]
normal_gaps = [g for g in gaps if 8 < g < 20]
if not normal_gaps:
return lines_by_y.get(start_y, "")
avg_gap = sum(normal_gaps) / len(normal_gaps)
# start_yλΆν° λ€μ ꡬλΆμ κΉμ§ ν
μ€νΈ μμ§
collecting = False
result_lines = []
prev_y = None
for y in sorted_ys:
if abs(y - start_y) < 2: # start_y μ°ΎκΈ°
collecting = True
if collecting:
text = lines_by_y[y].strip()
# μ’
λ£ μ‘°κ±΄: 2λ°° κ°κ²© + κ³Όλͺ© ν¨ν΄ λλ λ
Έμ΄μ¦
if prev_y is not None:
gap = y - prev_y
if gap > avg_gap * 1.7:
# λ€μ λΈλ‘μ΄ κ³Όλͺ©μ΄λ©΄ μ’
λ£
if self._starts_with_subject_pattern(text):
break
# λ
Έμ΄μ¦λ©΄ μ’
λ£
if not self._is_valid_personal_remark(text):
break
# νμ΄μ§ νΈν° μ μΈ
if "κ³ λ±νκ΅" in text and "νμ΄μ§" not in text:
if len(text) < 50:
break
result_lines.append(text)
prev_y = y
return " ".join(result_lines)
def _get_table_y_start(self, page_num: int, table_idx: int) -> float:
"""ν
μ΄λΈμ μμ Yμ’ν λ°ν"""
if page_num >= len(self.pdf.pages):
return 0
page = self.pdf.pages[page_num]
tables = page.find_tables()
if table_idx < len(tables):
return tables[table_idx].bbox[1] # top Y coordinate
return 0
def _parse_academics(self) -> dict:
"""κ΅κ³Όνμ΅λ°λ¬μν© νμ± - Yμ’ν κΈ°λ° λ§μ»€ μΆμ """
text = self._get_section_text("κ΅κ³Ό")
tables_with_page = self._get_section_tables_with_page("κ΅κ³Ό")
result = {
"by_year": [],
"subject_remarks": [],
}
# νμ΄μ§λ³ λ§μ»€ μΊμ (Yμ’ν ν¬ν¨)
page_markers_cache = {}
boundary = self.section_boundaries.get("κ΅κ³Ό")
if boundary:
for page_num in range(boundary.start_page, boundary.end_page + 1):
page_markers_cache[page_num] = self._get_page_markers_with_y(page_num)
# μ μ μν (νμ΄μ§/ν
μ΄λΈ κ° μ μ§)
current_grade = None
current_category = "μΌλ°"
# (grade, semester, category) -> records λ³ν©μ©
by_year_dict = {}
# μΈλΆλ₯λ ₯νΉκΈ°μ¬νμ νλ
λ³λ‘ λμ
remarks_by_grade = {1: [], 2: [], 3: []}
seen_contents = set() # μ€λ³΅ λ°©μ§μ©
for page_num, table_y, table in tables_with_page:
if not table:
continue
# Yμ’ν κΈ°λ° λ§μ»€ μ μ© (ν
μ΄λΈ μμ μλ λ§μ»€λ€μ Yμ’ν μμλ₯Ό κ³ λ €)
page_markers = page_markers_cache.get(page_num, [])
# ν
μ΄λΈ μμ μλ λ§μ»€λ€ μ€ λ§μ§λ§ κ²λ€λ§ μ μ©
last_grade_y = None
last_grade_value = None
last_category_y = None
last_category_value = None
for marker_y, marker_type, marker_value in page_markers:
if marker_y < table_y: # λ§μ»€κ° ν
μ΄λΈ μμ μμ
if marker_type == "grade":
last_grade_y = marker_y
last_grade_value = marker_value
elif marker_type == "category":
last_category_y = marker_y
last_category_value = marker_value
# νλ
λ§μ»€ μ μ©
if last_grade_value is not None and current_grade != last_grade_value:
current_grade = last_grade_value
# νλ
μ΄ λ°λλ©΄ μΉ΄ν
κ³ λ¦¬λ₯Ό μΌλ°μΌλ‘ 리μ
(μΉ΄ν
κ³ λ¦¬ λ§μ»€κ° νλ
λ§μ»€ μ΄νμ μμΌλ©΄)
if last_category_y is None or last_category_y < last_grade_y:
current_category = "μΌλ°"
# μΉ΄ν
κ³ λ¦¬ λ§μ»€κ° νλ
λ§μ»€λ³΄λ€ λ€μ μμΌλ©΄ μ μ©
if last_category_value is not None:
if last_grade_y is None or last_category_y > last_grade_y:
current_category = last_category_value
# ν€λ νλ€μμ μ 보 μΆμΆ (ν
μ΄λΈ μ체μ λ§μ»€κ° μλ κ²½μ°)
header_rows_text = ""
for row in table[:5]:
if row:
header_rows_text += " " + " ".join(str(cell) for cell in row if cell)
header_rows_no_space = header_rows_text.replace(" ", "")
first_row_text = " ".join(str(cell) for cell in table[0] if cell) if table[0] else ""
# ν
μ΄λΈ ν€λμ νλ
λ§μ»€κ° μμΌλ©΄ μ μ©
if "[1νλ
]" in header_rows_text or "[1νλ
]" in header_rows_no_space:
if current_grade != 1:
current_grade = 1
current_category = "μΌλ°"
elif "[2νλ
]" in header_rows_text or "[2νλ
]" in header_rows_no_space:
if current_grade != 2:
current_grade = 2
current_category = "μΌλ°"
elif "[3νλ
]" in header_rows_text or "[3νλ
]" in header_rows_no_space:
if current_grade != 3:
current_grade = 3
current_category = "μΌλ°"
# ν
μ΄λΈ ν€λμ μΉ΄ν
κ³ λ¦¬ λ§μ»€κ° μμΌλ©΄ μ μ©
if "μ§λ‘μ ν" in header_rows_text or "μ§λ‘ μ ν" in header_rows_text:
current_category = "μ§λ‘μ ν"
elif "체μ‘Β·μμ " in header_rows_text or "체μ‘γμμ " in header_rows_text or "체μ‘μμ " in header_rows_no_space:
current_category = "체μ‘μμ "
# μ±μ ν
μ΄λΈ νμ± (μΉ΄ν
κ³ λ¦¬ μΆλ‘ μμ΄ νμ¬ μΉ΄ν
κ³ λ¦¬ μ¬μ©)
if "κ΅κ³Ό" in header_rows_text and ("κ³Όλͺ©" in header_rows_text or "λ¨μ" in header_rows_text):
records_by_sem = self._parse_grade_table(table, current_grade, 1, current_category)
for sem, records in records_by_sem.items():
if records:
# Yμ’ν κΈ°λ°μΌλ‘ κ²°μ λ μΉ΄ν
κ³ λ¦¬ μ¬μ©
key = (current_grade, sem, current_category)
if key not in by_year_dict:
by_year_dict[key] = []
by_year_dict[key].extend(records)
# μΈλΆλ₯λ ₯νΉκΈ°μ¬ν ν
μ΄λΈ νμ±
first_row_no_space = first_row_text.replace(" ", "")
# 창체 ν
μ΄λΈ μ μΈ (μ°½μμ 체ννλμν© ν
μ΄λΈμ κ΅κ³Ό μΈνΉμ΄ μλ)
is_changche_table = "μ°½μμ 체ννλ" in header_rows_no_space or "μ°½μμ 체ννλ" in first_row_no_space
if ("μΈλΆλ₯λ ₯" in first_row_no_space or "νΉκΈ°μ¬ν" in first_row_no_space) and not is_changche_table:
remarks_text = self._extract_remarks_text(table)
if remarks_text:
# μ€λ³΅ κ°μ§: (νλ
, λ΄μ© ν΄μ) μ‘°ν©μΌλ‘ 체ν¬
# λ€λ₯Έ νλ
μ λμΌ λ΄μ©μ νμ©, κ°μ νλ
λ΄ μ€λ³΅μ νμ© (νκΈ°λ³ λΉκ³΅κ° λ±)
grade_key = current_grade if current_grade in [1, 2, 3] else 1
content_hash = hash((grade_key, remarks_text[:100]))
# λΉκ³΅κ° λ΄μ©μ μ€λ³΅ νμ© (νκΈ°λ³λ‘ κ°μ λ΄μ©μ΄ λ°λ³΅λ¨)
is_restricted = "μ 곡νμ§ μμ΅λλ€" in remarks_text
if not is_restricted and content_hash in seen_contents:
continue
seen_contents.add(content_hash)
remarks_by_grade[grade_key].append(remarks_text)
# by_year_dictλ₯Ό μ λ ¬λ 리μ€νΈλ‘ λ³ν
if by_year_dict:
categories = ["μΌλ°", "μ§λ‘μ ν", "체μ‘μμ "]
for grade in [1, 2, 3]:
for category in categories:
for semester in [1, 2]:
key = (grade, semester, category)
records = by_year_dict.get(key, [])
result["by_year"].append({
"grade": grade,
"semester": semester,
"category": category,
"records": records,
"total_credits": sum(r.get("credits", 0) or 0 for r in records),
})
# νλ
λ³ λμ λ ν
μ€νΈλ₯Ό νμ±
for grade, texts in remarks_by_grade.items():
if texts:
# λΉκ³΅κ° ν
μ€νΈμ μΌλ° ν
μ€νΈ λΆλ¦¬
restricted_texts = []
normal_texts = []
for t in texts:
if "μ 곡νμ§ μμ΅λλ€" in t:
restricted_texts.append(t)
else:
normal_texts.append(t)
# μΌλ° ν
μ€νΈλ ν©μ³μ νμ± (κ³Όλͺ©μ΄ μ¬λ¬ ν
μ΄λΈμ κ±Έμ³μμ μ μμ)
if normal_texts:
combined_text = " ".join(normal_texts)
parsed = self._split_by_subjects(combined_text, grade)
result["subject_remarks"].extend(parsed)
# λΉκ³΅κ° ν
μ€νΈλ κ°λ³μ μΌλ‘ μ²λ¦¬ (κ°κ° λ³λ νλͺ©)
for restricted_text in restricted_texts:
result["subject_remarks"].append({
"grade": grade,
"semester": None,
"subject": None,
"content": restricted_text.strip(),
"restricted": True,
})
# νμ΄μ§ λκΉμΌλ‘ λκΈ΄ μΈνΉ λ³ν©
result["subject_remarks"] = self._merge_orphan_remarks(result["subject_remarks"])
# Yμ’ν κΈ°λ° κ°μΈμΈνΉ κ°μ§ λ° μΆκ°
personal_remarks_by_y = self._find_personal_remarks_by_y()
existing_contents = {r.get("content", "")[:50] for r in result["subject_remarks"]}
for pr in personal_remarks_by_y:
# μ€λ³΅ λ°©μ§: μ΄λ―Έ νμ±λ λ΄μ©κ³Ό κ²ΉμΉμ§ μλμ§ νμΈ
pr_content_prefix = pr["text"][:50]
if pr_content_prefix not in existing_contents:
# μ 체 ν
μ€νΈ κ°μ Έμ€κΈ° (Yμ’ν μ΄νμ μ°μ ν
μ€νΈ)
full_text = self._get_full_text_from_y(pr["page"], pr["y"])
if full_text and len(full_text) > 50:
result["subject_remarks"].append({
"grade": pr["grade"],
"semester": None,
"subject": None, # κ°μΈμΈνΉ
"content": full_text.strip(),
"restricted": False,
})
existing_contents.add(full_text[:50])
return result
def _expand_merged_rows(self, table: list, data_start_idx: int) -> list[list]:
"""λ³ν©λ μ
μ κ°λ³ νμΌλ‘ νμ₯
pdfplumberλ λ³ν© μ
λ΄ μ€λ°κΏμ \\nμΌλ‘ νν.
κ³Όλͺ©λͺ
μ΄μ κΈ°μ€μΌλ‘ ν μλ₯Ό κ²°μ νλ, μλ €μ§ κ³Όλͺ©λͺ
λͺ©λ‘μ νμ©.
"""
expanded_rows = []
for row in table[data_start_idx:]:
if not row or all(cell is None or str(cell).strip() == "" for cell in row):
continue
# "μ΄μνμ ν©κ³" νμ μ€ν΅
row_text = " ".join(str(c) for c in row if c)
if "μ΄μνμ " in row_text or "ν©κ³" in row_text:
continue
# κ³Όλͺ©λͺ
μ΄ μ°ΎκΈ° (λ³΄ν΅ μ΄ 2, μμΌλ©΄ μ΄ 1)
subject_col_idx = 2
if len(row) <= 2 or not row[2]:
subject_col_idx = 1
subject_cell = str(row[subject_col_idx]) if len(row) > subject_col_idx and row[subject_col_idx] else ""
# κ³Όλͺ©λͺ
μΆμΆ - μλ €μ§ κ³Όλͺ©λͺ
λͺ©λ‘μΌλ‘ λ§€μΉ
subjects = self._extract_subjects_from_cell(subject_cell)
# λ³ν©λ νμ΄ μλλ©΄ κ·Έλλ‘ μΆκ°
if len(subjects) <= 1:
cleaned_row = []
for c in row:
cell_str = str(c) if c else ""
# κ°ν μ κ±° (λ―Έμ κ°μκ³Ό λΉ\nν β λ―Έμ κ°μκ³Ό λΉν)
cell_str = cell_str.replace("\n", "").strip()
cleaned_row.append(cell_str)
expanded_rows.append(cleaned_row)
continue
# κ° μ
μ \nμΌλ‘ split
split_cells = []
for cell in row:
cell_str = str(cell) if cell else ""
parts = cell_str.split("\n")
split_cells.append(parts)
num_subjects = len(subjects)
# λ³ν©λ ν: κ³Όλͺ© κ°μλ§νΌ ν μμ±
# rank μ΄(μ΄ 6)μ μ€ν κ³Όλͺ©μ μ€ν΅νλ©΄μ λ§€νν΄μΌ ν¨
rank_col_idx = 6
rank_parts = split_cells[rank_col_idx] if len(split_cells) > rank_col_idx else []
rank_offset = 0 # μ€ν κ³Όλͺ©μ μ€ν΅ν νμ
for i in range(num_subjects):
subject = subjects[i] if i < len(subjects) else ""
is_no_rank_subject = "μ€ν" in subject or "νꡬμ€ν" in subject
new_row = []
for col_idx, parts in enumerate(split_cells):
if col_idx == 0:
# νκΈ° μ΄: 첫 λ²μ§Έ κ°λ§ μ¬μ©
new_row.append(parts[0].strip() if parts else "")
elif col_idx == subject_col_idx:
# κ³Όλͺ©λͺ
μ΄: μΆμΆλ κ³Όλͺ©λͺ
μ¬μ©
new_row.append(subject)
elif col_idx == subject_col_idx - 1:
# κ΅κ³Ό μμ μ΄: κ³Όλͺ©μμ μΆλ‘
area = SUBJECT_TO_AREA.get(subject, "")
new_row.append(area)
elif col_idx == rank_col_idx:
# rank μ΄: μ€ν κ³Όλͺ©μ λΉ κ°, μλλ©΄ μ€νμ
μ μ©
if is_no_rank_subject:
new_row.append("")
else:
adjusted_idx = i - rank_offset
if adjusted_idx < len(rank_parts):
new_row.append(rank_parts[adjusted_idx].strip())
else:
new_row.append("")
else:
# λλ¨Έμ§ μ΄: ν΄λΉ μΈλ±μ€ κ°
if i < len(parts):
new_row.append(parts[i].strip())
else:
new_row.append("")
# μ€ν κ³Όλͺ© μΉ΄μ΄νΈ μ¦κ°
if is_no_rank_subject:
rank_offset += 1
if any(c.strip() for c in new_row[1:]):
expanded_rows.append(new_row)
return expanded_rows
def _extract_subjects_from_cell(self, cell_text: str) -> list[str]:
"""μ
ν
μ€νΈμμ μλ €μ§ κ³Όλͺ©λͺ
λͺ©λ‘ μΆμΆ
pdfplumberκ° λ³ν© μ
μ μΆμΆν λ μ€λ°κΏμΌλ‘ λΆλ¦¬νμ§λ§,
κ³Όλͺ©λͺ
μ체μ μ€λ°κΏμ΄ ν¬ν¨λ μ μμ (λ―Έμ κ°μκ³Ό λΉ\nν).
μλ €μ§ κ³Όλͺ©λͺ
λͺ©λ‘μ μ¬μ©νμ¬ μ ννκ² μΆμΆ.
"""
if not cell_text:
return []
# μ€λ°κΏμ λΉ λ¬Έμμ΄λ‘ λ³ν (λ―Έμ κ°μκ³Ό λΉ\nν β λ―Έμ κ°μκ³Ό λΉν)
full_text = cell_text.replace("\n", "")
# μ°μ 곡백 μ κ±°
full_text = re.sub(r'\s+', ' ', full_text).strip()
# μλ €μ§ κ³Όλͺ©λͺ
μ€ κΈ΄ κ²λΆν° λ§€μΉ (λΆλΆ λ§€μΉ λ°©μ§)
sorted_subjects = sorted(SUBJECT_NAMES, key=len, reverse=True)
found_subjects = []
remaining = full_text
while remaining.strip():
matched = False
remaining_stripped = remaining.strip()
for subject in sorted_subjects:
# 곡백 μ κ·ν ν λΉκ΅
norm_subject = subject.replace(" ", "")
norm_remaining = remaining_stripped.replace(" ", "")
if norm_remaining.startswith(norm_subject):
found_subjects.append(subject)
# μλ³Έ ν
μ€νΈμμ ν΄λΉ λΆλΆ μ κ±°
# 곡백 ν¬ν¨λ κΈΈμ΄λ§νΌ μ κ±°
idx = 0
matched_len = 0
while idx < len(remaining_stripped) and matched_len < len(norm_subject):
if remaining_stripped[idx] != " ":
matched_len += 1
idx += 1
remaining = remaining_stripped[idx:].strip()
matched = True
break
if not matched:
# μλ €μ§ κ³Όλͺ©λͺ
μ΄ μμΌλ©΄ 첫 λ¨μ΄ μ€ν΅
parts = remaining.strip().split(None, 1)
if len(parts) > 1:
remaining = parts[1]
else:
break
# λͺ»μ°ΎμΌλ©΄ μλ λ°©μμΌλ‘ μ€λ°κΏ λΆλ¦¬
if not found_subjects:
raw_parts = cell_text.split("\n")
merged_parts = []
for part in raw_parts:
part = part.strip()
if not part:
continue
# μ§§μ λ¨μ΄(3μ λ―Έλ§)κ° μ΄μ κ³Όλͺ©λͺ
μ μΌλΆμΈ κ²½μ° ν©μΉ¨
if merged_parts and len(part) < 3 and not any(part == s for s in SUBJECT_NAMES):
merged_parts[-1] = merged_parts[-1] + part
else:
merged_parts.append(part)
return merged_parts
return found_subjects
def _parse_grade_table(self, table: list, grade: int, semester: int, category: str) -> dict[int, list[dict]]:
"""μ±μ ν
μ΄λΈ νμ± - νκΈ°λ³λ‘ λΆλ¦¬λ κ²°κ³Ό λ°ν"""
result_by_semester = {1: [], 2: []}
# ν€λ μ°ΎκΈ°
data_start_idx = 0
for i, row in enumerate(table):
row_text = " ".join(str(cell) for cell in row if cell)
if "μμ μ" in row_text or "μ±μ·¨λ" in row_text or "μμ°¨λ±κΈ" in row_text:
data_start_idx = i + 1
break
if data_start_idx == 0:
data_start_idx = 2
# λ³ν© μ
νμ₯
expanded_rows = self._expand_merged_rows(table, data_start_idx)
current_subject_area = None
current_semester = semester
cat_info = ACADEMIC_CATEGORY_BY_ID.get(category, ACADEMIC_CATEGORY_BY_ID["μΌλ°"])
for values in expanded_rows:
values = [self._clean_text(v) for v in values]
# 첫 λ²μ§Έ μ΄μμ νκΈ° μ 보 μΆμΆ
if values[0] and values[0].isdigit() and int(values[0]) in [1, 2]:
current_semester = int(values[0])
record = {
"subject_area": None,
"subject": None,
"credits": None,
"score": None,
"average": None,
"std_dev": None,
"achievement": None,
"students": None,
"rank": None,
"distribution": None,
}
# κ³Όλͺ©λͺ
μΆμΆ - μ΄ 2λ₯Ό μ°μ νμΈ (ν
μ΄λΈ ꡬ쑰: νκΈ°, κ΅κ³Ό, κ³Όλͺ©, ...)
subject_found = False
# μ΄ 2κ° μλ €μ§ κ³Όλͺ©λͺ
μΈμ§ νμΈ
if len(values) > 2 and values[2]:
subject_candidate = values[2].replace("\n", "").strip()
if subject_candidate in SUBJECT_NAMES or (
subject_candidate and not subject_candidate.isdigit()
and subject_candidate not in ["A", "B", "C", "D", "E", "P"]
and len(subject_candidate) >= 2
):
record["subject"] = subject_candidate
subject_found = True
# μ΄ 2μμ λͺ»μ°ΎμΌλ©΄ μ΄ 1-3 λ²μμμ μ°ΎκΈ°
if not subject_found:
for val in values[1:4]:
if val and not val.isdigit() and len(val) >= 2:
if val not in ["A", "B", "C", "D", "E", "P"]:
subject_name = val.replace("\n", "").strip()
record["subject"] = subject_name
break
# κ΅κ³Ό μμ μΆλ‘ - μ΄ 1 λλ κ³Όλͺ©λͺ
μμ
if record["subject"]:
inferred_area = SUBJECT_TO_AREA.get(record["subject"])
if inferred_area:
current_subject_area = inferred_area
elif len(values) > 1 and values[1]:
# μ΄ 1μ΄ κ΅κ³Ό μμμΌ μ μμ
area_candidate = values[1].replace("\n", "").strip()
# μλ €μ§ κ΅κ³Ό μμ ν¨ν΄ νμΈ
if any(area in area_candidate for area in ["κ΅μ΄", "μν", "μμ΄", "μ¬ν", "κ³Όν", "체μ‘", "μμ ", "κΈ°μ "]):
current_subject_area = area_candidate
record["subject_area"] = current_subject_area
# μ«μ κ° μΆμΆμ μν λ³μλ€
found_credits = False
found_score_avg = False
for idx, val in enumerate(values):
if idx == 0:
continue
if not val:
continue
# λ¨μ/νμ (1-9 μ¬μ΄ λ¨μΌ μ«μ)
if val.isdigit() and not found_credits:
num = int(val)
if 1 <= num <= 9:
record["credits"] = num
found_credits = True
continue
# μμ μ/νκ· (νμ€νΈμ°¨) νμ: 78/76.2(14.1)
score_match = re.match(r"^(\d+)/(\d+\.?\d*)\((\d+\.?\d*)\)$", val)
if score_match:
record["score"] = float(score_match.group(1))
record["average"] = float(score_match.group(2))
record["std_dev"] = float(score_match.group(3))
found_score_avg = True
continue
# μ§λ‘μ ν κ³Όλͺ©: μμ μ/νκ· νμ (νμ€νΈμ°¨ μμ): 78/82.8
score_avg_match = re.match(r"^(\d+)/(\d+\.?\d*)$", val)
if score_avg_match and category == "μ§λ‘μ ν":
record["score"] = float(score_avg_match.group(1))
record["average"] = float(score_avg_match.group(2))
found_score_avg = True
continue
# μ±μ·¨λ(μκ°μμ) νμ: A(215), P(100)
achievement_match = re.match(r"^([A-EP])\((\d+)\)$", val)
if achievement_match:
record["achievement"] = achievement_match.group(1)
record["students"] = int(achievement_match.group(2))
continue
# λ¨λ
μ±μ·¨λ: A, B, C, D, E, P
if val in ["A", "B", "C", "D", "E", "P"]:
if record["achievement"] is None:
record["achievement"] = val
continue
# μ±μ·¨λλ³ λΆν¬: A(62.9) B(36.0) C(1.0)
if re.search(r"[A-E]\(\d+\.?\d*\)", val) and not re.match(r"^[A-EP]\(\d+\)$", val):
record["distribution"] = val
continue
# μκ°μμ (3μ리 μ΄μ μ«μ)
if val.isdigit() and len(val) >= 3 and record["students"] is None:
record["students"] = int(val)
continue
# μμ°¨λ±κΈ μΆμΆ (μΌλ° κ³Όλͺ©λ§)
# "μ€ν" κ³Όλͺ©μ μμ°¨λ±κΈμ΄ μμ
subject_name = record.get("subject", "")
is_no_rank_subject = "μ€ν" in subject_name or "νꡬμ€ν" in subject_name
if cat_info.has_rank and not is_no_rank_subject:
# ν
μ΄λΈ ꡬ쑰: νκΈ°, κ΅κ³Ό, κ³Όλͺ©, νμ μ, μμ μ/νκ· , μ±μ·¨λ, μμ°¨λ±κΈ, λΉκ³
# μμ°¨λ±κΈμ μ΄ 6 μμΉ (0-indexed)
rank_col_idx = 6
if len(values) > rank_col_idx:
rank_val = values[rank_col_idx].strip() if values[rank_col_idx] else ""
if rank_val.isdigit() and len(rank_val) == 1:
num = int(rank_val)
if 1 <= num <= 9:
record["rank"] = num
elif rank_val == "P":
record["rank"] = "P"
if record["subject"]:
result_by_semester[current_semester].append(record)
return result_by_semester
def _extract_remarks_text(self, table: list) -> str:
"""μΈλΆλ₯λ ₯νΉκΈ°μ¬ν ν
μ΄λΈμμ ν
μ€νΈ μΆμΆ"""
text_parts = []
for row in table[1:]:
if not row or all(cell is None or str(cell).strip() == "" for cell in row):
continue
for cell in row:
if cell:
cell_text = self._clean_text(str(cell))
if cell_text and cell_text not in ["κ³Όλͺ©", "μΈλΆλ₯λ ₯", "νΉκΈ°μ¬ν", "ν΄λΉ μ¬ν μμ"]:
text_parts.append(cell_text)
return " ".join(text_parts).strip()
def _merge_orphan_remarks(self, remarks: list[dict]) -> list[dict]:
"""νμ΄μ§ λκΉμΌλ‘ λκΈ΄ μΈνΉ λ³ν©
subject=NoneμΈ νλͺ© μ€ μ°μ ν¨ν΄(μ: "μμ", "κ³ ", "νλ©°" λ±μΌλ‘ μμ)μ
κ°μ§νμ¬ μ΄μ κ³Όλͺ©μ λ΄μ©μ λ³ν©ν©λλ€.
κ°μ λ λ‘μ§:
- orphan μ΄μ μ λμ¨ κ³Όλͺ© μ€ λΆμμ νκ² λλλ λ§μ§λ§ κ³Όλͺ©μ λ³ν©
- νλ
μ΄ λ€λ₯΄λλΌλ νμ΄μ§ μμμ κ°κΉμ΄ κ²μ λ³ν©
"""
if not remarks:
return remarks
# μ°μ ν¨ν΄: λ΄μ©μ΄ μ‘°μ¬/μ μμ¬λ‘ μμνλ©΄ μ΄μ λ΄μ©μ μ°μ
continuation_patterns = [
"μμ ", "μμλ ", "κ³ ", "λ©° ", "νλ©° ", "μΌλ©° ",
"κ³Ό ", "μ ", "λ₯Ό ", "μ ", "λ ", "μ ",
"μ ", "λ‘ ", "μΌλ‘ ", "λ€λ ", "λΌλ ",
"ν΄ ", "νμ¬ ", "νκ³ ", "κ² ", "λλ‘ ",
]
result = []
last_subject_idx = -1 # λ§μ§λ§ κ³Όλͺ© νλͺ©μ μΈλ±μ€
for remark in remarks:
is_orphan_continuation = False
if remark.get("subject") is None and not remark.get("restricted", False):
content = remark.get("content", "").strip()
# μ°μ ν¨ν΄μΌλ‘ μμνλμ§ νμΈ
is_orphan_continuation = any(content.startswith(p) for p in continuation_patterns)
if is_orphan_continuation and last_subject_idx >= 0:
# λ§μ§λ§ κ³Όλͺ©μ λ΄μ©μ΄ λΆμμ νκ² λλλμ§ νμΈ
last_remark = result[last_subject_idx]
last_content = last_remark.get("content", "").strip()
if last_content and last_content[-1] not in ".!?γ":
# λ³ν©
result[last_subject_idx]["content"] = last_content + " " + content
continue
result.append(remark)
# κ³Όλͺ©λͺ
μ΄ μλ νλͺ©μ΄λ©΄ λ§μ§λ§ μΈλ±μ€ μ
λ°μ΄νΈ
if remark.get("subject") and not remark.get("restricted", False):
last_subject_idx = len(result) - 1
return result
def _split_by_subjects(self, text: str, grade: int) -> list[dict]:
"""ν
μ€νΈλ₯Ό κ³Όλͺ©λ³λ‘ λΆλ¦¬
κ°μ μ¬ν:
- κ³Όλͺ©λͺ
μλ κ°μΈ μΈνΉ (subject=None) μ§μ
- λΉκ³΅κ° λ΄μ© (restricted=True) κ°μ§
"""
result = []
# λΉκ³΅κ° μ¬λΆ νμΈ
is_restricted = "μ 곡νμ§ μμ΅λλ€" in text or "μ 보곡κ°μ κ΄ν λ²λ₯ " in text
# κ³Όλͺ©λͺ
μ κΈΈμ΄μμΌλ‘ μ λ ¬ (κΈ΄ κ² λ¨Όμ λ§€μΉ)
sorted_subjects = sorted(SUBJECT_NAMES, key=len, reverse=True)
subject_pattern = "|".join(re.escape(s) for s in sorted_subjects)
# ν¨ν΄: "(νκΈ°)" + κ³Όλͺ©λͺ
+ ":"
pattern = re.compile(
rf"(?:^|\s)(\(?\d?νκΈ°\)?)?({subject_pattern})\s*[:οΌ]"
)
matches = list(pattern.finditer(text))
if not matches:
# ν¨ν΄ λ§€μΉ μ€ν¨ μ - μ 체λ₯Ό κ°μΈ μΈνΉ λλ λΉκ³΅κ° λ΄μ©μΌλ‘ μ²λ¦¬
content = text.strip()
if content and content != "ν΄λΉ μ¬ν μμ":
# 첫 μ½λ‘ μ΄μ μ κ³Όλͺ©λͺ
μΌλ‘ μΆμ μλ
colon_pos = text.find(":")
if 0 < colon_pos < 30 and not is_restricted:
subject = text[:colon_pos].strip()
content = text[colon_pos + 1:].strip()
if subject and content:
result.append({
"grade": grade,
"semester": None,
"subject": subject,
"content": content,
"restricted": False,
})
else:
# κ³Όλͺ©λͺ
μλ κ°μΈ μΈνΉ λλ λΉκ³΅κ° λ΄μ©
result.append({
"grade": grade,
"semester": None,
"subject": None, # κ°μΈ μΈνΉ
"content": content,
"restricted": is_restricted,
})
return result
# 첫 λ§€μΉ μ΄μ μ ν
μ€νΈ νμΈ (κ°μΈ μΈνΉ)
if matches[0].start() > 0:
pre_text = text[:matches[0].start()].strip()
# 50μ μ΄μμ΄λ©΄ κ°μΈ μΈνΉμΌλ‘ κ°μ£Ό
if len(pre_text) >= 50:
result.append({
"grade": grade,
"semester": None,
"subject": None, # κ°μΈ μΈνΉ
"content": pre_text,
"restricted": False,
})
# κ° λ§€μΉμ λν΄ κ³Όλͺ©κ³Ό λ΄μ© μΆμΆ
for i, match in enumerate(matches):
semester_str = match.group(1) or ""
subject_name = match.group(2)
semester = None
if "1νκΈ°" in semester_str:
semester = 1
elif "2νκΈ°" in semester_str:
semester = 2
content_start = match.end()
content_end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
content = text[content_start:content_end].strip()
if content:
result.append({
"grade": grade,
"semester": semester,
"subject": subject_name,
"content": content,
"restricted": False,
})
# λͺ¨λ κ³Όλͺ© λ΄μ©μμ κ°μΈ μΈνΉ λΆλ¦¬ μλ
# (κ°μΈ μΈνΉμ΄ λ§μ§λ§ κ³Όλͺ©μ΄ μλ μ€κ° κ³Όλͺ©μ λΆμ΄μμ μ μμ)
personal_remarks_to_add = []
for i, item in enumerate(result):
if item["subject"] is None:
continue # μ΄λ―Έ κ°μΈ μΈνΉμΈ κ²½μ° μ€ν΅
content = item["content"]
personal_remark = self._extract_personal_remark_from_content(content)
if personal_remark:
# κ³Όλͺ© λ΄μ©μμ κ°μΈ μΈνΉ λΆλΆ μ κ±°
result[i]["content"] = content[:content.find(personal_remark)].strip()
# κ°μΈ μΈνΉ μΆκ° (λμ€μ resultμ μΆκ°)
personal_remarks_to_add.append({
"grade": grade,
"semester": None,
"subject": None,
"content": personal_remark.strip(),
"restricted": False,
})
# κ°μΈ μΈνΉ μΆκ°
result.extend(personal_remarks_to_add)
return result
def _extract_personal_remark_from_content(self, content: str) -> Optional[str]:
"""λ§μ§λ§ κ³Όλͺ© λ΄μ©μμ κ°μΈ μΈνΉ λΆλ¦¬
κ°μΈ μΈνΉ μμ ν¨ν΄:
- μμ¨μ κ΅μ‘κ³Όμ (λ μ§)
- λ μ§ ν¨ν΄: (2024.07.17.), (2024λ
)
- νλ‘μ νΈ/νλ: ~νλ‘μ νΈ, ~νλμ μ°Έμ¬
- λ
립μ μ£Όμ μμ (λ§μΉ¨ν ν μ λ¬Έμ₯μ΄ κ³Όλͺ©κ³Ό 무κ΄ν κ²½μ°)
"""
if len(content) < 100:
return None
# κ°μΈ μΈνΉ μμ ν€μλ ν¨ν΄
personal_patterns = [
# μμ¨μ κ΅μ‘κ³Όμ (νκ΅ μμ¨ νλ)
r'(?<=\.\s)(μμ¨μ \s*κ΅μ‘κ³Όμ \s*\([^)]+\))',
r'(?:^|\s)(μμ¨μ \s*κ΅μ‘κ³Όμ \s*\([^)]+\))',
# λ μ§λ‘ μμνλ νλ
r'(?<=\.\s)([κ°-ν£]+\s*νλ‘μ νΈ\s*\(\d{4}\.\d{2}\.\d{2})',
r'(?<=\.\s)([κ°-ν£]+\s*νλ‘μ νΈ\s*\(\d{4}λ
)',
# νΉμ μ£Όμ λ‘ μμ (μλ―Όμ§, μμ¬ λ± νκ΅ νλ)
r'(?<=\.\s)(μμ 리\s+μλ―Όμ§μ¬)',
r'(?<=\.\s)(κ°μΉμ±μ₯\s+νλ‘μ νΈ)',
# μΌλ°μ μΈ κ°μΈ μΈνΉ ν¨ν΄ (λ λμ λ²μ)
r'(?<=\.\s)([κ°-ν£]+(?:νλ|νλ‘μ νΈ)\s*\(\d{4})',
]
for pattern in personal_patterns:
match = re.search(pattern, content)
if match:
# λ§€μΉλ μμΉλΆν° λκΉμ§κ° κ°μΈ μΈνΉ
start_idx = match.start(1)
personal_content = content[start_idx:].strip()
# μ΅μ 50μ μ΄μμ΄μ΄μΌ κ°μΈ μΈνΉμΌλ‘ μΈμ
if len(personal_content) >= 50:
return personal_content
return None
def _clean_text(self, text: str) -> str:
"""ν
μ€νΈ μ 리"""
if not text:
return ""
# 곡백 μ κ·ν
text = re.sub(r'\s+', ' ', text.strip())
return text
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# λ
μνλμν© νμ±
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_reading(self) -> list[dict]:
"""λ
μνλμν© νμ± (Yμ’ν κΈ°λ° νν°λ§μΌλ‘ κ°μν)"""
tables = self._get_section_tables("λ
μ")
reading = []
current_grade = None # λ³ν©λ μ
μ²λ¦¬μ©
current_subject = "곡ν΅" # λ³ν©λ μ
μ²λ¦¬μ©
for table in tables:
if not table:
continue
for row in table:
if not row or len(row) < 2:
continue
# ν€λ ν μ€ν΅
row_text = ' '.join(str(c) for c in row if c)
if "λ
μνλ" in row_text or "κ³Όλͺ© λλ μμ" in row_text:
continue
# νλ
νμΈ (λ³ν©λ μ
μ None)
grade_val = row[0]
if grade_val and str(grade_val).strip().isdigit():
new_grade = int(grade_val)
if new_grade in [1, 2, 3]:
current_grade = new_grade
# νλ
μ΄ μμΌλ©΄ μ€ν΅ (첫 νμ΄κ±°λ ν€λ)
if current_grade is None:
continue
# κ³Όλͺ©/μμ νμΈ (λ³ν©λ μ
μ None)
subject_val = row[1] if len(row) > 1 else None
if subject_val and str(subject_val).strip():
current_subject = str(subject_val).strip()
# λμ λͺ©λ‘ (λ§μ§λ§ 컬λΌ, κ°ν μ κ±°)
books_text = ""
if len(row) > 2 and row[2]:
books_text = str(row[2]).replace('\n', ' ').strip()
elif len(row) > 1 and row[1] and not subject_val:
# κ³Όλͺ© μμ΄ λ΄μ©λ§ μλ κ²½μ° (λ³ν©λ ν)
books_text = str(row[1]).replace('\n', ' ').strip()
# λΉ λ΄μ© μ μΈ
if not books_text:
continue
reading.append({
"grade": current_grade,
"subject_or_area": current_subject,
"content": books_text,
})
return reading
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# νλνΉμ± λ° μ’
ν©μ견 νμ±
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_behavior(self) -> list[dict]:
"""νλνΉμ± λ° μ’
ν©μ견 νμ± (νμ΄μ§ λκΉ λ³ν© μ§μ)
νμ΄μ§ λκΉμΌλ‘ κ°μ νλ
λ΄μ©μ΄ μ¬λ¬ ν
μ΄λΈμ λΆλ¦¬λ κ²½μ° λ³ν©
"""
tables = self._get_section_tables("νλ")
# νλ
λ³ λ΄μ© λ³ν©μ© λμ
λ리
behavior_by_grade = {} # {grade: content_list}
for table in tables:
if not table:
continue
for row in table:
if not row or len(row) < 2:
continue
grade_val = row[0]
if not grade_val or not str(grade_val).strip().isdigit():
continue
grade = int(grade_val)
if grade not in [1, 2, 3]:
continue
# μ’
ν©μ견 (λ λ²μ§Έ 컬λΌλΆν°, κ°ν μ κ±°)
content = ' '.join(str(c).replace('\n', ' ') for c in row[1:] if c)
content = ' '.join(content.split()) # μ°μ 곡백 μ 리
# λΉ λ΄μ© μ μΈ
if not content:
continue
# νλ
λ³λ‘ λ΄μ© λμ (νμ΄μ§ λκΉ λ³ν©)
if grade not in behavior_by_grade:
behavior_by_grade[grade] = []
behavior_by_grade[grade].append(content)
# κ²°κ³Ό μ‘°ν©
behavior = []
for grade in sorted(behavior_by_grade.keys()):
# κ°μ νλ
μ μ¬λ¬ λ΄μ©μ 곡백μΌλ‘ μ°κ²°
combined_content = ' '.join(behavior_by_grade[grade])
combined_content = ' '.join(combined_content.split()) # μ°μ 곡백 μ 리
behavior.append({
"grade": grade,
"content": combined_content,
"restricted": "μ 곡νμ§ μμ΅λλ€" in combined_content,
})
return behavior
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# μ νΈλ¦¬ν°
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _safe_int(self, val) -> int:
"""μμ ν μ μ λ³ν"""
if val is None:
return 0
try:
# . μ 0μΌλ‘ μ²λ¦¬
val_str = str(val).strip()
if val_str in ['.', '', '-']:
return 0
return int(val_str)
except (ValueError, TypeError):
return 0
def parse_with_template(pdf_path: str) -> dict[str, Any]:
"""ν
νλ¦Ώ κΈ°λ° νμ± νΈμ ν¨μ"""
parser = TemplateParser(pdf_path)
return parser.parse() |