Spaces:
Sleeping
Sleeping
File size: 100,147 Bytes
fcc11e3 66f5064 fcc11e3 7dcff31 c1994a6 7dcff31 984bb38 840041c c1994a6 66f5064 fcc11e3 31f189b 217de4e bccb076 31f189b bccb076 29b1a40 217de4e c47ae0a a316dd6 c47ae0a 31ccc3a c9023eb 74cdb5e c47ae0a 217de4e 004f46d 217de4e 004f46d c47ae0a 66f5064 f1e7a64 c47ae0a fcc11e3 f1e7a64 fcc11e3 c47ae0a 7dcff31 004f46d bccb076 217de4e bccb076 7dcff31 c47ae0a 74cdb5e fcc11e3 c1994a6 c47ae0a 66f5064 3ed37b0 7559664 66f5064 7559664 c47ae0a 217de4e 66f5064 217de4e 7559664 217de4e 66f5064 217de4e 29b1a40 c47ae0a 217de4e c1994a6 29b1a40 c1994a6 984bb38 fcc11e3 c47ae0a fcc11e3 217de4e fcc11e3 f1e7a64 31f189b f1e7a64 31f189b f1e7a64 31f189b f1e7a64 c1994a6 31f189b f1e7a64 31f189b f1e7a64 217de4e f1e7a64 217de4e f1e7a64 74cdb5e 31ccc3a 74cdb5e fcc11e3 f1e7a64 fcc11e3 c47ae0a 7dcff31 c0170bb 74cdb5e 66f5064 7559664 29b1a40 66f5064 31f189b 66f5064 29b1a40 66f5064 74cdb5e 217de4e 74cdb5e 29b1a40 66f5064 29b1a40 74cdb5e 29b1a40 74cdb5e c47ae0a 74cdb5e 29b1a40 74cdb5e c47ae0a 29b1a40 74cdb5e c47ae0a 74cdb5e 217de4e 29b1a40 217de4e 29b1a40 217de4e f1e7a64 29b1a40 f1e7a64 29b1a40 f1e7a64 31f189b f1e7a64 29b1a40 f1e7a64 74cdb5e f1e7a64 29b1a40 f1e7a64 66f5064 f1e7a64 29b1a40 f1e7a64 fcc11e3 31f189b bccb076 31f189b bccb076 f1e7a64 fcc11e3 29b1a40 217de4e f1e7a64 29b1a40 31ccc3a bccb076 29b1a40 217de4e fcc11e3 7dcff31 217de4e 840041c 217de4e 840041c 217de4e 840041c bccb076 31f189b 217de4e bccb076 217de4e 840041c 217de4e 29b1a40 840041c 217de4e 29b1a40 217de4e 840041c 217de4e 840041c 217de4e 840041c 217de4e bccb076 29b1a40 840041c 217de4e 840041c 217de4e 840041c fcc11e3 217de4e 7dcff31 217de4e 29b1a40 217de4e 29b1a40 217de4e 31ccc3a 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 7dcff31 217de4e 29b1a40 31ccc3a 29b1a40 217de4e 29b1a40 217de4e 7dcff31 217de4e 29b1a40 217de4e 7dcff31 217de4e 7dcff31 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 7dcff31 217de4e 29b1a40 217de4e 7dcff31 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 7dcff31 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 31ccc3a 217de4e 29b1a40 217de4e 29b1a40 31ccc3a 217de4e 7dcff31 217de4e 29b1a40 217de4e 31ccc3a 217de4e 29b1a40 217de4e 7dcff31 217de4e 29b1a40 31ccc3a 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 7dcff31 217de4e 29b1a40 217de4e 29b1a40 217de4e 29b1a40 7dcff31 217de4e 29b1a40 31ccc3a 217de4e 7dcff31 217de4e 29b1a40 217de4e 29b1a40 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d c0170bb 6c87d2d 29b1a40 c0170bb 29b1a40 6c87d2d c0170bb 6c87d2d 29b1a40 6c87d2d 31ccc3a 6c87d2d 31ccc3a c0170bb 31f189b 6c87d2d 31f189b 6c87d2d 31f189b 6c87d2d 31f189b 6c87d2d 31f189b 6c87d2d 31f189b 6c87d2d 31ccc3a 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d 31ccc3a 6c87d2d c0170bb 6c87d2d 29b1a40 c0170bb 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d 31ccc3a 6c87d2d 29b1a40 6c87d2d c0170bb 6c87d2d 29b1a40 c0170bb 6c87d2d 29b1a40 6c87d2d c0170bb 29b1a40 c0170bb 6c87d2d 29b1a40 6c87d2d 31ccc3a 6c87d2d c0170bb 6c87d2d 29b1a40 c0170bb 6c87d2d 29b1a40 6c87d2d c0170bb 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d c0170bb 6c87d2d 31ccc3a 6c87d2d c0170bb 6c87d2d c0170bb 31ccc3a c0170bb 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d c0170bb 6c87d2d 31ccc3a c0170bb 6c87d2d 31ccc3a 6c87d2d 31ccc3a 6c87d2d 31ccc3a 6c87d2d 37f534c 31f189b 6c87d2d 31f189b 6c87d2d 31f189b 6c87d2d 31ccc3a 6c87d2d 31f189b 6c87d2d 31ccc3a 6c87d2d 31ccc3a 6c87d2d c0170bb 31ccc3a c0170bb 6c87d2d 31ccc3a 6c87d2d 31ccc3a 6c87d2d 31ccc3a 6c87d2d 31ccc3a 6c87d2d 31ccc3a 6c87d2d 31ccc3a 6c87d2d 31ccc3a 6c87d2d 29b1a40 6c87d2d c0170bb 6c87d2d bccb076 6c87d2d 29b1a40 6c87d2d c0170bb 6c87d2d bccb076 6c87d2d c0170bb 6c87d2d c0170bb 6c87d2d 31ccc3a 6c87d2d bccb076 6c87d2d bccb076 6c87d2d bccb076 6c87d2d bccb076 6c87d2d bccb076 6c87d2d 31f189b 6c87d2d 29b1a40 6c87d2d 29b1a40 6c87d2d 31f189b 6c87d2d cd0baad 29b1a40 cd0baad bccb076 cd0baad 29b1a40 bccb076 cd0baad 31ccc3a cd0baad bccb076 29b1a40 cd0baad bccb076 cd0baad 29b1a40 cd0baad bccb076 cd0baad bccb076 cd0baad 31ccc3a cd0baad bccb076 cd0baad 29b1a40 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 31f189b cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad 31f189b cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad 29b1a40 cd0baad bccb076 cd0baad bccb076 cd0baad bccb076 cd0baad c0170bb 31ccc3a c0170bb cd0baad c0170bb cd0baad c0170bb cd0baad 29b1a40 cd0baad c0170bb 31ccc3a c0170bb 29b1a40 cd0baad 31ccc3a cd0baad 29b1a40 cd0baad c0170bb cd0baad c0170bb cd0baad c0170bb cd0baad 31f189b bccb076 cd0baad bccb076 cd0baad 31ccc3a cd0baad bccb076 cd0baad 31ccc3a cd0baad 31ccc3a cd0baad 31ccc3a cd0baad 29b1a40 cd0baad c0170bb 31ccc3a cd0baad c0170bb 31ccc3a cd0baad c0170bb cd0baad bccb076 | 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 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 | # ============================================================
# reBom Regulatory Screening AI - Fast Grounded Fixed Version
# - ๊ตญ๊ฐ/์ฑ๋ ํด๋ ์๋ ์ธ์
# - ๊ท์ ํ์ผ ์๋ ๋ณ๊ฒฝ ๊ฐ์ง
# - ๊ตญ๊ฐ๋ณ FAISS ๋ฒกํฐ DB ๋์คํฌ ์บ์
# - ๊ตญ๊ฐ๋ณ ๋ฌธ์ ๊ฒฉ๋ฆฌ ๊ฒ์์ผ๋ก ํ๊ตญ ๊ท์ ํ์ฐ ๋ฐฉ์ง
# - ๋ก์ปฌ ๊ท์น ์ฐ์ ํ์
# - MFDS ์์ฝํ์์ ๋๋ผ ์์ธ DB ์์
์ฐ๋
# - GPT ํธ์ถ ์ ์๋ฏธ ์๋ ๊ฒ์๊ฒฐ๊ณผ ํํฐ๋ง
# - Formula Ingredients Statement ์๋ณธ ์์ ์ถ๋ ฅ
# - ๋ฌธ์ ์ฑ๋ถ๋ง Regulatory Screening Summary ์ถ๋ ฅ
# - Raw Search Log ๋ณ๋ ์ ์ฅ
# - Gradio ๋ก๊ทธ์ธ ์ธ์ฆ / public share link ์ ์ฉ
# - MergedCell column_letter ์ค๋ฅ ์์ ์๋ฃ
# ============================================================
# ============================================================
# reBom Regulatory Screening AI
# - ๊ตญ๊ฐ๋ณ ๊ท์ ํด๋ ์์์๋ง ๊ฒ์
# - FAISS ๋์คํฌ ์บ์
# - GPT๋ ๊ฒ์๋ ์๋ฌธ ์์์๋ง ํ์
# - ์์ฝ์ฒ ์ฌ์ดํธ ์ค์๊ฐ ์กฐํ ์ต์
# - COOS ์ ๊ฑฐ
# - Water ๋ฑ ์ผ๋ฐ ์ฑ๋ถ์ ์์ฝ์ฒ ์กฐํ ํ์์/์ ์ธ
# - ์์ฝ์ฒ ์ ์ ์คํจ ์ 3ํ ์ฌ์๋
# - ํฅ๋ฃ๋ ๊ตญ๊ฐ ์๊ด์์ด ํ์ธ ํ์
# - ๊ณ ์ํ ์ฑ๋ถ Pass ์๋ ๋ฐฉ์ง
# - Formular Ingredients Statement ์์ ์ถ๋ ฅ
# - ์๋ณธ TOTAL ํ ์ ๊ฑฐ ํ ์ TOTAL ํ 1๊ฐ๋ง ์์ฑ
# ============================================================
import os
import re
import json
import hashlib
import traceback
import sys
import subprocess
from pathlib import Path
from collections import defaultdict
import pandas as pd
import pdfplumber
import gradio as gr
try:
from bs4 import BeautifulSoup
except Exception:
BeautifulSoup = None
try:
from playwright.sync_api import sync_playwright
PLAYWRIGHT_AVAILABLE = True
except Exception:
sync_playwright = None
PLAYWRIGHT_AVAILABLE = False
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
# ============================================================
# 0. ๊ธฐ๋ณธ ์ค์
# ============================================================
api_key = os.getenv("OPENAI_API_KEY")
print("โ
OPENAI_API_KEY ์ ์" if api_key else "โ OPENAI_API_KEY ์์")
BASE_DIR = Path.cwd().resolve()
OUTPUT_DIR = (BASE_DIR / "outputs").resolve()
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
FAISS_CACHE_DIR = ".faiss_cache"
MFDS_LIVE_URL = "https://nedrug.mfds.go.kr/pbp/CCBDF01"
NO_EVIDENCE_TEXT = "ํด๋น ์๋ฃ ๋ด ์ ํ ๊ทผ๊ฑฐ ์์"
NEED_CHECK_TEXT = "ํ์ธ ํ์"
LIMIT_CHECK_TEXT = "๋ฐฐํฉํ๋ ํ์ธ ํ์"
VECTOR_DB_CACHE = {}
EVAL_CACHE = {}
EMBEDDINGS_CACHE = None
RAW_SEARCH_LOGS = []
SUPPORTED_REG_FILE_EXTENSIONS = {".pdf", ".txt", ".csv", ".xlsx", ".xls"}
COUNTRY_ORDER = [
"ASEAN", "CALIFORNIA", "CHINA", "EU (FUTURE)", "EU", "FDA",
"JAPAN", "KOREA", "MEXICO", "SEPHORA", "TARGET", "UK", "ULTA",
]
COUNTRY_DISPLAY = {
"EU": "EU", "์ ๋ฝ": "EU", "EUROPE": "EU",
"FDA": "FDA", "๋ฏธ๊ตญ": "FDA", "USA": "FDA", "US": "FDA",
"KOREA": "Korea", "ํ๊ตญ": "Korea", "KR": "Korea",
"JAPAN": "์ผ๋ณธ", "์ผ๋ณธ": "์ผ๋ณธ", "JP": "์ผ๋ณธ",
"CHINA": "์ค๊ตญ", "์ค๊ตญ": "์ค๊ตญ", "CN": "์ค๊ตญ",
"ASEAN": "ASEAN", "์์ธ์": "ASEAN",
"UK": "UK", "์๊ตญ": "UK",
"EU (FUTURE)": "EU (FUTURE)", "EU_FUTURE": "EU (FUTURE)",
"CALIFORNIA": "CALIFORNIA", "MEXICO": "MEXICO",
"SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA",
}
COUNTRY_FOLDER_ALIASES = {
"EU": "EU", "์ ๋ฝ": "EU", "EUROPE": "EU",
"FDA": "FDA", "๋ฏธ๊ตญ": "FDA", "USA": "FDA", "US": "FDA",
"KOREA": "KOREA", "ํ๊ตญ": "KOREA", "KR": "KOREA",
"JAPAN": "JAPAN", "์ผ๋ณธ": "JAPAN", "JP": "JAPAN",
"CHINA": "CHINA", "์ค๊ตญ": "CHINA", "CN": "CHINA",
"ASEAN": "ASEAN", "์์ธ์": "ASEAN",
"UK": "UK", "์๊ตญ": "UK",
"EU (FUTURE)": "EU (FUTURE)",
"EU_FUTURE": "EU (FUTURE)",
"EU FUTURE": "EU (FUTURE)",
"CALIFORNIA": "CALIFORNIA",
"MEXICO": "MEXICO",
"SEPHORA": "SEPHORA",
"TARGET": "TARGET",
"ULTA": "ULTA",
}
BLOCKED_PATHS = [str(BASE_DIR / c) for c in COUNTRY_ORDER] + [
str(BASE_DIR / FAISS_CACHE_DIR),
str(BASE_DIR / ".env"),
str(BASE_DIR / "__pycache__"),
]
ALLOWED_PATHS = [
str(OUTPUT_DIR),
str(BASE_DIR),
]
BATCH_SIZE = 40
RAG_TOP_K_BATCH = 4
RAG_TOP_K_SINGLE = 2
MEANINGFUL_HIT_K = 2
custom_css = """
#country_checks .wrap,
#country_checks .checkbox-group {
display: flex !important;
flex-direction: row !important;
flex-wrap: wrap !important;
gap: 10px !important;
}
#country_checks label {
display: inline-flex !important;
align-items: center !important;
width: auto !important;
min-width: 110px !important;
padding: 8px 12px !important;
border: 1px solid #555 !important;
border-radius: 10px !important;
margin: 4px !important;
}
"""
# ============================================================
# 1. ๋ก์ปฌ ๊ท์น
# ============================================================
UV_FILTER_RULES = {
"octocrylene": {
"label": "Octocrylene",
"aliases": ["octocrylene", "์ฅํ ํฌ๋ฆด๋ ", "6197-30-4"],
"EU": {"status": "allowed", "limit": 10, "formula_text": "๋ฐฐํฉ ํ๋:\n์คํ๋ ์ด: 9% /\n๊ธฐํ์ ํ: 10%"},
"FDA": {"status": "allowed", "limit": 10, "formula_text": "๋ผ๋ฒจ๋ง ํ์"},
"KOREA": {"status": "allowed", "limit": 10, "formula_text": "๋ฐฐํฉํ๋: 10%"},
"JAPAN": {"status": "allowed", "limit": 10, "formula_text": "๋ฐฐํฉํ๋: 10%"},
"SEPHORA": {"status": "prohibited", "formula_text": "๋ฐฐํฉ๊ธ์ง"},
},
"homosalate": {
"label": "Homosalate",
"aliases": ["homosalate", "ํธ๋ชจ์ด๋ ์ดํธ", "118-56-9"],
"ASEAN": {"status": "allowed", "limit": 10, "formula_text": "๋ฐฐํฉํ๋: 10%"},
"EU": {"status": "allowed", "limit": 7.34, "formula_text": "๋ฐฐํฉํ๋: 7.34%"},
"FDA": {"status": "allowed", "limit": 15, "formula_text": "๋ฐฐํฉํ๋: 15%"},
"KOREA": {"status": "allowed", "limit": 10, "formula_text": "๋ฐฐํฉํ๋: 10%"},
"JAPAN": {"status": "allowed", "limit": 10, "formula_text": "๋ฐฐํฉํ๋: 10%"},
},
"octisalate": {
"label": "Octisalate / Ethylhexyl Salicylate",
"aliases": ["octisalate", "ethylhexyl salicylate", "์ฅํฐ์ด๋ ์ดํธ", "118-60-5"],
"EU": {"status": "allowed", "limit": 5, "formula_text": "๋ฐฐํฉํ๋: 5%"},
"FDA": {"status": "allowed", "limit": 5, "formula_text": "๋ฐฐํฉํ๋: 5%"},
"KOREA": {"status": "allowed", "limit": 5, "formula_text": "๋ฐฐํฉํ๋: 5%"},
"JAPAN": {"status": "allowed", "limit": 5, "formula_text": "๋ฐฐํฉํ๋: 5%"},
},
"avobenzone": {
"label": "Avobenzone",
"aliases": ["avobenzone", "butyl methoxydibenzoylmethane", "์๋ณด๋ฒค์กด", "70356-09-1"],
"EU": {"status": "allowed", "limit": 5, "formula_text": "๋ฐฐํฉํ๋: 5%"},
"FDA": {"status": "allowed", "limit": 3, "formula_text": "๋ฐฐํฉํ๋: 3%"},
"KOREA": {"status": "allowed", "limit": 5, "formula_text": "๋ฐฐํฉํ๋: 5%"},
},
}
PRESERVATIVE_RULES = {
"phenoxyethanol": {
"label": "Phenoxyethanol",
"aliases": ["phenoxyethanol", "ํ๋
น์์ํ์ฌ", "122-99-6"],
"EU": {"status": "allowed", "limit": 1, "formula_text": "๋ฐฐํฉํ๋: 1%"},
"KOREA": {"status": "allowed", "limit": 1, "formula_text": "๋ฐฐํฉํ๋: 1%"},
"JAPAN": {"status": "allowed", "limit": 1, "formula_text": "๋ฐฐํฉํ๋: 1%"},
},
}
FUNCTIONAL_KOREA_RULES = {
"niacinamide": {
"label": "Niacinamide",
"aliases": ["niacinamide", "๋์ด์์ ์๋ง์ด๋", "98-92-0"],
"result": "๊ธฐ๋ฅ์ฑํ์ฅํ ๊ฒํ / Niacinamide ํ์ฌ ํจ๋ {amount}%, ๋ฏธ๋ฐฑ ๊ธฐ๋ฅ์ฑ ํ์ยท๊ด๊ณ ์ ์๊ฑด ํ์ธ ํ์",
"formula_text": "๊ธฐ๋ฅ์ฑ ํ์ธ",
},
"adenosine": {
"label": "Adenosine",
"aliases": ["adenosine", "์๋ฐ๋
ธ์ ", "58-61-7"],
"result": "๊ธฐ๋ฅ์ฑํ์ฅํ ๊ฒํ / Adenosine ํ์ฌ ํจ๋ {amount}%, ์ฃผ๋ฆ๊ฐ์ ๊ธฐ๋ฅ์ฑ ํ์ยท๊ด๊ณ ์ ์๊ฑด ํ์ธ ํ์",
"formula_text": "๊ธฐ๋ฅ์ฑ ํ์ธ",
},
}
FRAGRANCE_ALLERGEN_RULES = {
"limonene": {"label": "Limonene", "aliases": ["limonene", "๋ฆฌ๋ชจ๋จ"], "leave_on": 0.001, "wash_off": 0.01},
"linalool": {"label": "Linalool", "aliases": ["linalool", "๋ฆฌ๋ ๋ฃฐ"], "leave_on": 0.001, "wash_off": 0.01},
"citral": {"label": "Citral", "aliases": ["citral", "์ํธ๋"], "leave_on": 0.001, "wash_off": 0.01},
"geraniol": {"label": "Geraniol", "aliases": ["geraniol", "์ ๋ผ๋์ฌ"], "leave_on": 0.001, "wash_off": 0.01},
"eugenol": {"label": "Eugenol", "aliases": ["eugenol", "์ ์ ๋"], "leave_on": 0.001, "wash_off": 0.01},
"benzyl alcohol": {"label": "Benzyl Alcohol", "aliases": ["benzyl alcohol", "๋ฒค์ง์์ฝ์ฌ"], "leave_on": 0.001, "wash_off": 0.01},
}
# ============================================================
# 2. ๊ณตํต ์ ํธ
# ============================================================
def safe_str(x):
if pd.isna(x):
return ""
return str(x).strip()
def normalize_text(text):
text = safe_str(text).lower()
text = text.replace("ฮฑ", "alpha").replace("ฮฒ", "beta")
text = re.sub(r"[^a-z0-9๊ฐ-ํฃ]+", " ", text)
return re.sub(r"\s+", " ", text).strip()
def normalize_compact(text):
return re.sub(r"\s+", "", normalize_text(text))
def is_total_like_text(text):
compact = normalize_compact(text)
return compact in ["total", "ํฉ๊ณ", "์ดํฉ", "sum"] or compact.startswith("total") or compact.startswith("ํฉ๊ณ")
def row_has_total_like(row_values):
values = [safe_str(v) for v in row_values if safe_str(v)]
for value in values:
if is_total_like_text(value):
return True
row_text = " ".join(values)
row_compact = normalize_compact(row_text)
if (
row_compact in ["total", "ํฉ๊ณ", "์ดํฉ", "sum"]
or row_compact.startswith("total")
or row_compact.startswith("ํฉ๊ณ")
or "total100" in row_compact
or "ํฉ๊ณ100" in row_compact
):
return True
return False
def country_key(country):
text = safe_str(country).upper().replace("_", " ").replace("-", " ")
text = re.sub(r"\s+", " ", text).strip()
mapping = {
"ํ๊ตญ": "KOREA", "KOREA": "KOREA", "KR": "KOREA",
"EU": "EU", "E.U.": "EU", "EUROPE": "EU", "์ ๋ฝ": "EU",
"EU FUTURE": "EU_FUTURE", "EU (FUTURE)": "EU_FUTURE",
"JAPAN": "JAPAN", "JP": "JAPAN", "์ผ๋ณธ": "JAPAN",
"CHINA": "CHINA", "CN": "CHINA", "์ค๊ตญ": "CHINA",
"USA": "FDA", "US": "FDA", "๋ฏธ๊ตญ": "FDA", "FDA": "FDA",
"ASEAN": "ASEAN", "์์ธ์": "ASEAN",
"UK": "UK", "UNITED KINGDOM": "UK", "์๊ตญ": "UK",
"SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA",
}
return mapping.get(text, text)
def display_country(country):
return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), str(country)))
def to_number(value):
if pd.isna(value):
return None
text = str(value).strip().replace(",", ".").replace("%", "")
if not text:
return None
try:
return float(text)
except Exception:
return None
def is_numeric_like(value):
return to_number(value) is not None
def format_amount(value, digits=10):
num = to_number(value)
if num is None:
return ""
if abs(num) >= 1:
text = f"{num:.6f}"
else:
text = f"{num:.{digits}f}"
text = text.rstrip("0").rstrip(".")
return text if text else "0"
def format_percent(value):
return format_amount(value, digits=10)
def format_no(value):
num = to_number(value)
if num is not None and float(num).is_integer():
return str(int(num))
return safe_str(value)
def stable_hash(obj):
text = json.dumps(obj, ensure_ascii=False, sort_keys=True, default=str)
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def safe_filename(text):
text = safe_str(text)
text = re.sub(r"[^a-zA-Z0-9๊ฐ-ํฃ._() -]", "_", text)
text = text.strip().replace(" ", "_")
return text or "unknown"
def chunk_list(items, size):
for i in range(0, len(items), size):
yield items[i:i + size]
def get_embeddings():
global EMBEDDINGS_CACHE
if EMBEDDINGS_CACHE is None:
EMBEDDINGS_CACHE = OpenAIEmbeddings(model="text-embedding-3-small")
return EMBEDDINGS_CACHE
def get_identity_text(material, component):
texts = [
component.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""),
component.get("INCI Name", ""),
component.get("CAS.No", ""),
component.get("FUNCTION", ""),
material.get("Trade name(๊ตญ๋ฌธ)", ""),
material.get("Trade name(์๋ฌธ)", ""),
]
return normalize_text(" ".join([safe_str(x) for x in texts if safe_str(x)]))
def match_rule_key(material, component, rule_dict):
identity = get_identity_text(material, component)
for key, rule in rule_dict.items():
for alias in rule.get("aliases", []):
alias_norm = normalize_text(alias)
if alias_norm and alias_norm in identity:
return key
return None
def is_plain_fragrance_component(material, component):
texts = [
component.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""),
component.get("INCI Name", ""),
component.get("FUNCTION", ""),
material.get("Trade name(๊ตญ๋ฌธ)", ""),
material.get("Trade name(์๋ฌธ)", ""),
]
compact = normalize_compact(" ".join([safe_str(x) for x in texts if safe_str(x)]))
fragrance_words = [
"ํฅ๋ฃ",
"fragrance",
"parfum",
"perfume",
"aroma",
]
return any(normalize_compact(w) in compact for w in fragrance_words)
def evaluate_plain_fragrance_rule(country, material, component):
if not is_plain_fragrance_component(material, component):
return None
return {
"๋ํ INCI": safe_str(component.get("INCI Name", "")) or "Fragrance",
"๊ฒฐ๊ณผ": f"ํฅ๋ฃ / {display_country(country)} ์๋ ๋ฅด๊ฒ ํ์์ฑ๋ถ ๋ฐ ์ธ๋ถ ์กฐ์ฑ ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": NEED_CHECK_TEXT,
"๋น๊ณ ": "ํฅ๋ฃ๋ ์ธ๋ถ ๊ตฌ์ฑ์ฑ๋ถ ๋ฐ ์๋ ๋ฅด๊ฒ ํ์๋์ ์ฌ๋ถ ํ์ธ ํ์. ์๋ Pass ์ฒ๋ฆฌ ๊ธ์ง.",
}
def get_restricted_candidate_reason(material, component):
if is_plain_fragrance_component(material, component):
return "ํฅ๋ฃ"
uv_key = match_rule_key(material, component, UV_FILTER_RULES)
if uv_key:
return "UV ํํฐ"
preservative_key = match_rule_key(material, component, PRESERVATIVE_RULES)
if preservative_key:
return "๋ณด์กด์ /์ ํ์ฑ๋ถ"
functional_key = match_rule_key(material, component, FUNCTIONAL_KOREA_RULES)
if functional_key:
return "๊ธฐ๋ฅ์ฑ ์ฑ๋ถ"
identity = get_identity_text(material, component)
for _, rule in FRAGRANCE_ALLERGEN_RULES.items():
for alias in rule.get("aliases", []):
alias_norm = normalize_text(alias)
if alias_norm and alias_norm in identity:
return "ํฅ๋ฃ ์๋ ๋ฅด๊ฒ"
function_text = normalize_text(component.get("FUNCTION", ""))
inci_text = normalize_text(component.get("INCI Name", ""))
high_risk_words = [
"sunscreen", "uv filter", "preservative", "colorant", "hair dye",
"retinol", "retinal", "retinyl", "salicylic acid",
]
if any(w in function_text for w in high_risk_words) or any(w in inci_text for w in high_risk_words):
return "์ ํ ๊ฐ๋ฅ์ฑ ์ฑ๋ถ"
return ""
def is_country_result_issue(text):
text = safe_str(text)
if not text or text in ["-", NO_EVIDENCE_TEXT, "Pass", "PASS", "pass"]:
return False
keywords = [
"๋ฐฐํฉ๊ธ์ง", "๊ธ์ง", "์ด๊ณผ", "๋ถ์ ํฉ", "์ฌ๊ฒํ ", "ํ์ธ ํ์",
"์๋ฃ ํ์ธ", "ํ์ ํ์", "๋ผ๋ฒจ๋ง", "๋ถ๊ฐ", "์ฃผ์", "๊ฒฝ๊ณ ",
"๋ฐฐํฉํ๋ ํ์ธ ํ์",
]
return any(k in text for k in keywords)
def log_search_context(target_id, country, component, result_text, source, context):
RAW_SEARCH_LOGS.append({
"target_id": target_id,
"๊ตญ๊ฐ/์ฑ๋": display_country(country),
"์ฑ๋ถ๋ช
": safe_str(component.get("ํ๊ธ ์ฑ๋ถ๋ช
", "")),
"INCI Name": safe_str(component.get("INCI Name", "")),
"ํ์ ": safe_str(result_text),
"์ถ์ฒ": safe_str(source),
"๊ฒ์ ์๋ฌธ": safe_str(context)[:3000],
})
def normalize_formula_country_text(text, country_col="", inci_name="", amount_text=""):
text = safe_str(text)
country_col = safe_str(country_col)
inci_norm = normalize_compact(inci_name)
if not text or text == "-" or text == NO_EVIDENCE_TEXT:
return "Pass"
lower = text.lower()
if LIMIT_CHECK_TEXT in text:
return LIMIT_CHECK_TEXT
if NEED_CHECK_TEXT in text:
return NEED_CHECK_TEXT
if "ํฅ๋ฃ" in text or "fragrance" in lower or "parfum" in lower:
return NEED_CHECK_TEXT
if "octocrylene" in inci_norm or "์ฅํ ํฌ๋ฆด๋ " in inci_norm:
if country_col == "EU":
return "๋ฐฐํฉ ํ๋:\n์คํ๋ ์ด: 9% /\n๊ธฐํ์ ํ: 10%"
if country_col == "FDA":
return "๋ผ๋ฒจ๋ง ํ์"
if country_col == "Korea":
return "๋ฐฐํฉํ๋: 10%"
if "homosalate" in inci_norm or "ํธ๋ชจ์ด๋ ์ดํธ" in inci_norm:
if country_col == "ASEAN":
return "๋ฐฐํฉํ๋: 10%"
if country_col == "EU":
return "๋ฐฐํฉํ๋: 7.34%"
if country_col == "FDA":
return "๋ฐฐํฉํ๋: 15%"
if country_col == "Korea":
return "๋ฐฐํฉํ๋: 10%"
if "octisalate" in inci_norm or "ethylhexylsalicylate" in inci_norm or "์ฅํฐ์ด๋ ์ดํธ" in inci_norm:
return "๋ฐฐํฉํ๋: 5%"
if "avobenzone" in inci_norm or "์๋ณด๋ฒค์กด" in inci_norm:
if country_col == "FDA":
return "๋ฐฐํฉํ๋: 3%"
return "๋ฐฐํฉํ๋: 5%"
if "๋ฐฐํฉ๊ธ์ง" in text or "์ฌ์ฉ๊ธ์ง" in text or "๊ธ์ง" in text or "prohibited" in lower:
return "๋ฐฐํฉ๊ธ์ง"
if "์ด๊ณผ" in text or "๋ถ์ ํฉ" in text or "์ฌ์ฉ ๋ถ๊ฐ" in text or "์ฌ์ฉ๋ถ๊ฐ" in text:
return "ํ๋ ์ด๊ณผ"
if "ํ์ ํ์" in text or "๋ผ๋ฒจ" in text or "label" in lower:
return "๋ผ๋ฒจ๋ง ํ์"
limit_match = re.search(r"ํ๋\s*([0-9]+(?:\.[0-9]+)?\s*%)", text)
if limit_match:
return "๋ฐฐํฉํ๋: " + limit_match.group(1).replace(" ", "")
percent_match = re.search(r"([0-9]+(?:\.[0-9]+)?\s*%)", text)
if percent_match and ("ํ๋" in text or "limit" in lower or "max" in lower):
return "๋ฐฐํฉํ๋: " + percent_match.group(1).replace(" ", "")
if "ํ์ธ ํ์" in text or "์๋ฃ ํ์ธ" in text or "์ฌ๊ฒํ " in text or "๊ฒํ ํ์" in text:
return NEED_CHECK_TEXT
if "์ด๋ด" in text or "ํต๊ณผ" in text or "ํ๋ ์ด๋ด" in text:
return "Pass"
return text[:120]
# ============================================================
# 3. ๊ตญ๊ฐ ํด๋ / ๊ท์ DB
# ============================================================
def resolve_country_folder(country):
if not country or country == "ํด๋ ์์":
return None
raw = safe_str(country)
alias = COUNTRY_FOLDER_ALIASES.get(raw, COUNTRY_FOLDER_ALIASES.get(raw.upper(), raw))
candidates = [
raw, alias, raw.upper(), alias.upper(),
raw.replace("_", " "),
raw.replace("-", " "),
raw.replace("EU FUTURE", "EU (FUTURE)"),
raw.replace("EU_FUTURE", "EU (FUTURE)"),
alias.replace("_", " "),
alias.replace("-", " "),
]
seen = []
for item in candidates:
item = safe_str(item)
if item and item not in seen:
seen.append(item)
for item in seen:
if os.path.isdir(item):
return item
folder_map = {
f.lower(): f
for f in os.listdir(".")
if os.path.isdir(f)
}
for item in seen:
matched = folder_map.get(item.lower())
if matched:
return matched
return alias
def get_country_folders():
exclude = [
".git", ".cache", "__pycache__", ".ipynb_checkpoints", ".venv",
"venv", "node_modules", FAISS_CACHE_DIR, "outputs",
]
folders = [
f for f in os.listdir(".")
if os.path.isdir(f) and f not in exclude
]
existing = set(folders)
ordered = [c for c in COUNTRY_ORDER if c in existing]
extras = sorted([f for f in folders if f not in COUNTRY_ORDER])
return ordered + extras if ordered or extras else COUNTRY_ORDER.copy()
def refresh_country_choices_keep_selection(current_values=None):
choices = get_country_folders()
current_values = current_values or []
kept = [v for v in current_values if v in choices]
return gr.update(choices=choices, value=kept)
def refresh_country_choices_and_clear_cache(current_values=None):
VECTOR_DB_CACHE.clear()
EVAL_CACHE.clear()
return refresh_country_choices_keep_selection(current_values)
def get_regulatory_file_list(country_folder):
files = []
if not country_folder or not os.path.isdir(country_folder):
return files
for root, dirs, filenames in os.walk(country_folder):
dirs[:] = [
d for d in dirs
if not d.startswith(".") and d not in ["__pycache__", ".ipynb_checkpoints"]
]
for filename in filenames:
ext = os.path.splitext(filename)[1].lower()
if ext not in SUPPORTED_REG_FILE_EXTENSIONS:
continue
path = os.path.join(root, filename)
try:
stat = os.stat(path)
except FileNotFoundError:
continue
files.append({
"path": path,
"relative_path": os.path.relpath(path, country_folder),
"size": stat.st_size,
"mtime_ns": stat.st_mtime_ns,
"ext": ext,
})
return sorted(files, key=lambda x: x["relative_path"].lower())
def read_text_file_with_fallback(file_path):
for enc in ["utf-8", "utf-8-sig", "cp949", "euc-kr", "latin-1"]:
try:
with open(file_path, "r", encoding=enc) as f:
return f.read()
except Exception:
continue
return ""
def extract_text_from_regulatory_file(file_item):
path = file_item["path"]
rel = file_item["relative_path"]
ext = file_item["ext"]
texts = []
try:
if ext == ".pdf":
with pdfplumber.open(path) as pdf:
for page_no, page in enumerate(pdf.pages, start=1):
text = page.extract_text()
if text:
texts.append(f"[ํ์ผ: {rel}] [ํ์ด์ง: {page_no}]\n{text}")
elif ext == ".txt":
text = read_text_file_with_fallback(path)
if text:
texts.append(f"[ํ์ผ: {rel}]\n{text}")
elif ext == ".csv":
try:
df = pd.read_csv(path, dtype=str)
except UnicodeDecodeError:
df = pd.read_csv(path, dtype=str, encoding="cp949")
texts.append(f"[ํ์ผ: {rel}]\n{df.fillna('').to_string(index=False)}")
elif ext in [".xlsx", ".xls"]:
sheets = pd.read_excel(path, sheet_name=None, dtype=str)
for sheet_name, sheet_df in sheets.items():
texts.append(f"[ํ์ผ: {rel}] [์ํธ: {sheet_name}]\n{sheet_df.fillna('').to_string(index=False)}")
except Exception as e:
print(f"๊ท์ ํ์ผ ์ฝ๊ธฐ ์ค๋ฅ: {path} / {e}")
return "\n\n".join(texts)
def build_database(country):
folder = resolve_country_folder(country)
if not folder or not os.path.isdir(folder):
return None
files = get_regulatory_file_list(folder)
if not files:
return None
signature = tuple((f["relative_path"], f["size"], f["mtime_ns"]) for f in files)
sig_hash = stable_hash(signature)
cached = VECTOR_DB_CACHE.get(folder)
if isinstance(cached, dict) and cached.get("signature_hash") == sig_hash:
return cached.get("db")
embeddings = get_embeddings()
os.makedirs(FAISS_CACHE_DIR, exist_ok=True)
cache_path = os.path.join(FAISS_CACHE_DIR, f"{safe_filename(folder)}_{sig_hash[:16]}")
meta_path = os.path.join(cache_path, "metadata.json")
if os.path.isdir(cache_path) and os.path.exists(meta_path):
try:
with open(meta_path, "r", encoding="utf-8") as f:
meta = json.load(f)
if meta.get("signature_hash") == sig_hash:
print(f"โ
FAISS ๋์คํฌ ์บ์ ๋ก๋: {folder}")
db = FAISS.load_local(cache_path, embeddings, allow_dangerous_deserialization=True)
VECTOR_DB_CACHE[folder] = {"signature_hash": sig_hash, "db": db}
return db
except Exception as e:
print(f"FAISS ์บ์ ๋ก๋ ์คํจ: {folder} / {e}")
print(f"๐ ๊ท์ DB ์ฌ์์ธ: {folder} / ํ์ผ {len(files)}๊ฐ")
EVAL_CACHE.clear()
splitter = RecursiveCharacterTextSplitter(chunk_size=900, chunk_overlap=120)
chunks = []
for item in files:
raw = extract_text_from_regulatory_file(item)
if raw:
chunks.extend(
splitter.split_text(
f"[๊ตญ๊ฐ/์ฑ๋: {folder}] [์ถ์ฒํ์ผ: {item['relative_path']}]\n{raw}"
)
)
if not chunks:
return None
db = FAISS.from_texts(chunks, embeddings)
try:
os.makedirs(cache_path, exist_ok=True)
db.save_local(cache_path)
with open(meta_path, "w", encoding="utf-8") as f:
json.dump(
{
"country_folder": folder,
"signature_hash": sig_hash,
"file_count": len(files),
},
f,
ensure_ascii=False,
indent=2,
)
print(f"โ
FAISS ๋์คํฌ ์บ์ ์ ์ฅ: {cache_path}")
except Exception as e:
print(f"FAISS ์บ์ ์ ์ฅ ์คํจ: {folder} / {e}")
VECTOR_DB_CACHE[folder] = {"signature_hash": sig_hash, "db": db}
return db
def get_current_db_signature(country):
folder = resolve_country_folder(country)
cached = VECTOR_DB_CACHE.get(folder)
if isinstance(cached, dict):
return cached.get("signature_hash")
return None
# ============================================================
# 4. ์
๋ ฅ ์์
๋ฏธ๋ฆฌ๋ณด๊ธฐ / ์ปฌ๋ผ ์ธ์
# ============================================================
def preview_excel(file):
if not file:
return None
try:
return pd.read_excel(file.name)
except Exception as e:
return pd.DataFrame({"์ค๋ฅ": [str(e)]})
def find_best_col(df, keywords, default_index=None, exclude_cols=None):
exclude_cols = exclude_cols or []
scores = []
for idx, col in enumerate(df.columns):
if col in exclude_cols:
continue
header = str(col).lower()
values = df[col].dropna().astype(str).str.strip()
sample = " ".join(values.head(80).tolist()).lower()
score = 0
for kw in keywords:
if kw.lower() in header:
score += 30
markers = [
"aqua", "water", "glycerin", "octocrylene", "homosalate",
"octisalate", "avobenzone", "niacinamide", "phenoxyethanol",
"limonene", "linalool", "citral", "extract", "acid",
"ceramide", "glycol", "retinol",
]
if any(x in sample for x in markers):
if any(k.lower() in ["inci", "ingredient", "์ฑ๋ถ", "์ ์ฑ๋ถ", "๊ตฌ์ฑ", "inci name"] for k in keywords):
score += 10
scores.append((score, idx, col))
scores = sorted(scores, reverse=True, key=lambda x: (x[0], -x[1]))
if scores and scores[0][0] > 0:
return scores[0][2]
if default_index is not None and len(df.columns) > default_index:
return df.columns[default_index]
return df.columns[0]
def find_optional_col(df, keywords, exclude_cols=None):
exclude_cols = exclude_cols or []
best = None
best_score = 0
for idx, col in enumerate(df.columns):
if col in exclude_cols:
continue
header = str(col).lower()
score = 0
for kw in keywords:
if kw.lower() in header:
score += 30
if score > best_score:
best_score = score
best = col
return best
def find_numeric_col(df, keywords, default_index=None, exclude_cols=None, prefer_many_values=True):
exclude_cols = exclude_cols or []
candidates = []
for idx, col in enumerate(df.columns):
if col in exclude_cols:
continue
header = str(col).lower()
values = df[col].dropna()
if values.empty:
continue
count = values.apply(is_numeric_like).sum()
if count <= 0:
continue
score = 0
for kw in keywords:
if kw.lower() in header:
score += 30
candidates.append({
"col": col,
"idx": idx,
"score": score,
"count": count,
"non_null": len(values),
})
if not candidates:
if default_index is not None and len(df.columns) > default_index:
return df.columns[default_index]
return None
if prefer_many_values:
candidates = sorted(candidates, key=lambda x: (x["score"], x["non_null"], x["idx"]), reverse=True)
else:
candidates = sorted(candidates, key=lambda x: (x["score"], -x["non_null"], -x["idx"]), reverse=True)
return candidates[0]["col"]
def find_main_columns(df):
no_col = find_best_col(df, ["no", "๋ฒํธ", "์๋ฒ"], default_index=0)
korean_ing_col = find_best_col(
df,
["ํ๊ธ ํ์คํ ๋ช
์นญ", "ํ๊ธ ์ฑ๋ถ๋ช
", "๊ตญ๋ฌธ ์ฑ๋ถ๋ช
", "ํ๊ธ์ฑ๋ถ๋ช
", "korean", "๊ตญ๋ฌธinci", "์ฑ๋ถ๋ช
"],
default_index=1 if len(df.columns) > 1 else None,
exclude_cols=[no_col],
)
inci_col = find_best_col(
df,
["ingredient name (inci)", "inci name", "inci", "ingredient", "์ ์ฑ๋ถ", "๊ตฌ์ฑ"],
default_index=2 if len(df.columns) > 2 else None,
exclude_cols=[no_col, korean_ing_col],
)
function_col = find_best_col(
df,
["function", "๊ธฐ๋ฅ", "์ฉ๋"],
default_index=3 if len(df.columns) > 3 else None,
exclude_cols=[no_col, korean_ing_col, inci_col],
)
cas_col = find_best_col(
df,
["cas.no", "cas no", "cas", "cas๋ฒํธ", "cas no."],
default_index=4 if len(df.columns) > 4 else None,
exclude_cols=[no_col, korean_ing_col, inci_col, function_col],
)
source_col = find_best_col(
df,
["source", "์ถ์ฒ", "icid"],
default_index=5 if len(df.columns) > 5 else None,
exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col],
)
formula_col = find_numeric_col(
df,
["%(w/w)", "w/w", "in formula", "formula", "์ฒ๋ฐฉ", "์ต์ข
", "์ ํ ๋ด", "์ ํ๋ด", "๋ฐฐํฉ๋", "ํจ๋", "%"],
default_index=6 if len(df.columns) > 6 else None,
exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col],
prefer_many_values=True,
)
trade_ko_col = find_optional_col(
df,
["trade name(๊ตญ๋ฌธ)", "trade name ๊ตญ๋ฌธ", "์๋ฃ๋ช
", "์ํ๋ช
", "๊ตญ๋ฌธ"],
exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col, formula_col],
)
trade_en_col = find_optional_col(
df,
["trade name(์๋ฌธ)", "trade name ์๋ฌธ", "trade", "raw material", "material", "์๋ฌธ"],
exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col, formula_col, trade_ko_col],
)
return {
"no_col": no_col,
"korean_ing_col": korean_ing_col,
"inci_col": inci_col,
"function_col": function_col,
"cas_col": cas_col,
"source_col": source_col,
"formula_col": formula_col,
"trade_ko_col": trade_ko_col,
"trade_en_col": trade_en_col,
}
# ============================================================
# 5. ์
๋ ฅ ์์
์ ๋ฆฌ / ์ ์ฑ๋ถ ํ ์์ฑ
# ============================================================
def clean_input_df(df, cols):
no_col = cols["no_col"]
korean_ing_col = cols["korean_ing_col"]
inci_col = cols["inci_col"]
footer_markers = [
"commitment of the manufacturer",
"the manufacturer here",
"it is illegal",
"rebom co",
"myeonghaksandanseo",
"sejong special",
"tel :",
"fax :",
"lab no.",
"permission",
]
keep_indices = []
footer_started = False
for idx, row in df.iterrows():
row_values = [safe_str(v) for v in row.values]
row_text = " ".join([v for v in row_values if v]).strip()
row_text_lower = row_text.lower()
if not row_text:
continue
no_text = safe_str(row.get(no_col, "")).lower() if no_col in df.columns else ""
korean_text = safe_str(row.get(korean_ing_col, "")).lower() if korean_ing_col in df.columns else ""
inci_text = safe_str(row.get(inci_col, "")).lower() if inci_col in df.columns else ""
if no_text in ["no", "no.", "๋ฒํธ", "์๋ฒ"]:
continue
if korean_text in ["ํ๊ธ ํ์คํ ๋ช
์นญ", "ํ๊ธ ์ฑ๋ถ๋ช
", "ํ๊ธ์ฑ๋ถ๋ช
", "๊ตญ๋ฌธ ์ฑ๋ถ๋ช
"]:
continue
if inci_text in ["ingredient name (inci)", "inci", "inci name"]:
continue
if (
is_total_like_text(no_text)
or is_total_like_text(korean_text)
or is_total_like_text(inci_text)
or row_has_total_like(row_values)
):
footer_started = True
continue
if any(marker in row_text_lower for marker in footer_markers):
footer_started = True
continue
if footer_started:
continue
keep_indices.append(idx)
return df.loc[keep_indices].reset_index(drop=True)
def make_grouped_materials(df):
cols = find_main_columns(df)
cleaned_df = clean_input_df(df, cols)
no_col = cols["no_col"]
korean_ing_col = cols["korean_ing_col"]
inci_col = cols["inci_col"]
function_col = cols["function_col"]
cas_col = cols["cas_col"]
source_col = cols["source_col"]
formula_col = cols["formula_col"]
trade_ko_col = cols.get("trade_ko_col")
trade_en_col = cols.get("trade_en_col")
row_materials = []
for _, row in cleaned_df.iterrows():
no_value = format_no(row.get(no_col, "")) if no_col in row else ""
korean_ing = safe_str(row.get(korean_ing_col, "")) if korean_ing_col in row else ""
inci_name = safe_str(row.get(inci_col, "")) if inci_col in row else ""
if (
is_total_like_text(no_value)
or is_total_like_text(korean_ing)
or is_total_like_text(inci_name)
or row_has_total_like(row.values)
):
continue
if not korean_ing and not inci_name:
continue
function_value = safe_str(row.get(function_col, "")) if function_col and function_col in row else ""
cas_value = safe_str(row.get(cas_col, "")) if cas_col and cas_col in row else ""
source_value = safe_str(row.get(source_col, "")) if source_col and source_col in row else ""
formula_value = format_amount(row.get(formula_col)) if formula_col and formula_col in row else ""
if not source_value:
source_value = "ICID"
trade_ko = safe_str(row.get(trade_ko_col, "")) if trade_ko_col and trade_ko_col in row else korean_ing
trade_en = safe_str(row.get(trade_en_col, "")) if trade_en_col and trade_en_col in row else inci_name
component = {
"ํ๊ธ ์ฑ๋ถ๋ช
": korean_ing,
"INCI Name": inci_name,
"FUNCTION": function_value,
"CAS.No": cas_value,
"SOURCE": source_value,
"In formula(w/w %)": formula_value,
"amount_float": to_number(row.get(formula_col)) if formula_col and formula_col in row else None,
}
material = {
"NO": no_value,
"Trade name(๊ตญ๋ฌธ)": trade_ko,
"Trade name(์๋ฌธ)": trade_en,
"Components": [component],
}
row_materials.append(material)
ingredient_totals = defaultdict(float)
ingredient_amount_parts = defaultdict(list)
for material in row_materials:
comp = material["Components"][0]
identity = get_identity_text(material, comp)
amount = comp.get("amount_float")
if amount is None:
continue
for canonical, rule in FRAGRANCE_ALLERGEN_RULES.items():
for alias in rule.get("aliases", []):
alias_norm = normalize_text(alias)
if alias_norm and alias_norm in identity:
ingredient_totals[canonical] += amount
ingredient_amount_parts[canonical].append(amount)
meta = {
"cols": cols,
"cleaned_df": cleaned_df,
"ingredient_totals": ingredient_totals,
"ingredient_amount_parts": ingredient_amount_parts,
}
return row_materials, meta
# ============================================================
# 6. ์์ฝ์ฒ ์ค์๊ฐ ์กฐํ
# ============================================================
def install_playwright_chromium_once():
try:
print("๐ง Playwright Chromium ์ค์น ์๋ ์ค...")
result = subprocess.run(
[sys.executable, "-m", "playwright", "install", "chromium"],
capture_output=True,
text=True,
timeout=300,
)
if result.returncode == 0:
print("โ
Playwright Chromium ์ค์น ์๋ฃ")
return True, "Chromium ์ค์น ์๋ฃ"
msg = (result.stdout or "") + "\n" + (result.stderr or "")
print("โ Playwright Chromium ์ค์น ์คํจ:", msg[-1000:])
return False, msg[-1000:]
except Exception as e:
print("โ Playwright Chromium ์ค์น ์์ธ:", e)
return False, str(e)
def extract_terms_for_live_lookup(row_items):
"""
์์ฝ์ฒ ์ค์๊ฐ ์กฐํ์ฉ ๊ฒ์์ด ์ถ์ถ.
Water, Glycerin ๊ฐ์ ์ผ๋ฐ ์ฑ๋ถ์ ์ ์ธํ๊ณ ,
UV ํํฐ/๋ณด์กด์ /๊ธฐ๋ฅ์ฑ/์ ํ ๊ฐ๋ฅ์ฑ ์ฑ๋ถ์ ์ฐ์ ์กฐํํ๋ค.
"""
skip_words = {
"water", "aqua", "์ ์ ์",
"glycerin", "๊ธ๋ฆฌ์ธ๋ฆฐ",
"butylene glycol", "๋ถํธ๋ ๊ธ๋ผ์ด์ฝ",
"dipropylene glycol", "๋ค์ดํ๋กํ๋ ๊ธ๋ผ์ด์ฝ",
"1,2-hexanediol", "1,2-ํฅ์ฐ๋ค์ด์ฌ",
"xanthan gum", "์ํ๊ฒ",
"cellulose", "์
๋ฃฐ๋ก์ค์ค",
"silica", "์ค๋ฆฌ์นด",
"arginine", "์์ง๋",
"sodium hyaluronate", "์๋ํ์ด์๋ฃจ๋ก๋ค์ดํธ",
"ethylhexylglycerin", "์ํธํฅ์ค๊ธ๋ฆฌ์ธ๋ฆฐ",
}
priority_terms = []
normal_terms = []
for item in row_items:
material = item["material"]
comp = item["component"]
high_risk_reason = get_restricted_candidate_reason(material, comp)
if is_plain_fragrance_component(material, comp):
continue
candidate_values = [
comp.get("INCI Name", ""),
comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""),
comp.get("CAS.No", ""),
]
for value in candidate_values:
value = safe_str(value)
if not value or value == "-":
continue
key = normalize_compact(value)
if len(key) < 3:
continue
is_skip = any(normalize_compact(w) == key for w in skip_words)
if is_skip and not high_risk_reason:
continue
if high_risk_reason:
priority_terms.append(value)
else:
normal_terms.append(value)
merged = priority_terms + normal_terms
seen = set()
unique = []
for term in merged:
key = normalize_compact(term)
if key and key not in seen:
seen.add(key)
unique.append(term)
return unique
def mfds_visible_text(page):
try:
html = page.content()
if BeautifulSoup is not None:
soup = BeautifulSoup(html, "html.parser")
for tag in soup(["script", "style", "nav", "footer", "header"]):
tag.decompose()
return soup.get_text(separator=" ")
return page.locator("body").inner_text(timeout=5000)
except Exception:
try:
return page.locator("body").inner_text(timeout=5000)
except Exception:
return ""
def mfds_fill_search_input(page, term):
selectors = [
"input[type='search']",
"input[type='text']",
"input[placeholder*='๊ฒ์']",
"input[placeholder*='์ฑ๋ถ']",
"input[placeholder*='์๋ฃ']",
"input[placeholder*='INCI']",
"input:not([type])",
]
for selector in selectors:
try:
loc = page.locator(selector)
for i in range(min(loc.count(), 30)):
item = loc.nth(i)
try:
if item.is_visible(timeout=1000) and item.is_enabled(timeout=1000):
item.fill(term, timeout=3000)
return True
except Exception:
continue
except Exception:
continue
return False
def mfds_click_search(page):
for txt in ["๊ฒ์", "์กฐํ", "Search"]:
try:
loc = page.get_by_text(txt, exact=True)
if loc.count() > 0:
loc.first.click(timeout=3000)
return True
except Exception:
pass
selectors = [
"button[type='submit']",
"input[type='submit']",
"button",
"a",
".search",
".btn-search",
".btn_search",
]
for selector in selectors:
try:
loc = page.locator(selector)
for i in range(min(loc.count(), 30)):
item = loc.nth(i)
try:
if selector == "input[type='submit']":
item.click(timeout=3000)
return True
text = ""
try:
text = item.inner_text(timeout=500)
except Exception:
pass
if "๊ฒ์" in text or "Search" in text or "์กฐํ" in text or selector in [".search", ".btn-search", ".btn_search"]:
item.click(timeout=3000)
return True
except Exception:
continue
except Exception:
continue
return False
def mfds_click_result_row(page, term):
term_norm = normalize_compact(term)
selectors = [
"table tbody tr",
"tbody tr",
"tr",
".list li",
".result li",
".search-result li",
".card",
"a",
]
for selector in selectors:
try:
rows = page.locator(selector)
for i in range(min(rows.count(), 50)):
row = rows.nth(i)
try:
row_text = row.inner_text(timeout=1000)
except Exception:
continue
if term_norm and term_norm in normalize_compact(row_text):
row.click(timeout=3000)
page.wait_for_timeout(2000)
return True
except Exception:
continue
try:
loc = page.get_by_text(term, exact=False)
if loc.count() > 0:
loc.first.click(timeout=3000)
page.wait_for_timeout(2000)
return True
except Exception:
pass
return False
def parse_mfds_text(term, text):
clean = " ".join(safe_str(text).split())
if not clean:
return []
lower_clean = clean.lower()
country_patterns = {
"EU": ["eu", "์ ๋ฝ", "์ ๋ฝ์ฐํฉ", "european union", "europe"],
"FDA": ["๋ฏธ๊ตญ", "usa", "fda", "united states"],
"Korea": ["ํ๊ตญ", "๋ํ๋ฏผ๊ตญ", "korea"],
"์ผ๋ณธ": ["์ผ๋ณธ", "japan"],
"์ค๊ตญ": ["์ค๊ตญ", "china"],
"ASEAN": ["asean", "์์ธ์"],
"UK": ["์๊ตญ", "uk", "united kingdom"],
}
rows = []
for country, aliases in country_patterns.items():
found_index = -1
for alias in aliases:
idx = lower_clean.find(alias)
if idx >= 0:
found_index = idx
break
if found_index < 0:
continue
start = max(0, found_index - 500)
end = min(len(clean), found_index + 1500)
snippet = clean[start:end]
snippet_lower = snippet.lower()
has_reg_keyword = any(
k in snippet_lower
for k in [
"๊ธ์ง", "์ฌ์ฉ๊ธ์ง", "๋ฐฐํฉ๊ธ์ง", "์ ํ", "ํ๋", "๋ฐฐํฉํ๋",
"์ต๋", "max", "maximum", "limit", "restricted",
"prohibited", "banned", "%",
]
)
if not has_reg_keyword:
continue
category = "์ ํ"
if any(k in snippet_lower for k in ["๊ธ์ง", "์ฌ์ฉ๊ธ์ง", "๋ฐฐํฉ๊ธ์ง", "prohibited", "banned", "not allowed"]):
category = "๊ธ์ง"
limit = ""
limit_match = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*%", snippet)
if limit_match:
limit = limit_match.group(0).replace(" ", "")
rows.append({
"์๋ฃ๋ช
": term,
"INCI": term,
"CAS.No": "",
"๊ตฌ๋ถ": category,
"๊ตญ๊ฐ": country,
"๊ท์ ๋ด์ฉ": snippet[:800],
"ํ๋": limit,
"์กฐ๊ฑด": "",
"์ถ์ฒ": "MFDS live: " + MFDS_LIVE_URL,
"์์ธ์๋ฌธ": clean[:6000],
})
return rows
def mfds_live_lookup_terms(terms, max_terms=30, headless=True):
if not PLAYWRIGHT_AVAILABLE or sync_playwright is None:
return pd.DataFrame(), "MFDS ์กฐํ ์คํจ: playwright ๋ฏธ์ค์น ๋๋ ๋ธ๋ผ์ฐ์ ๋ฏธ์ค์น"
terms = [safe_str(t) for t in terms if safe_str(t)]
terms = terms[:int(max_terms)] if max_terms else terms[:30]
def run_browser_lookup():
local_rows = []
local_errors = []
with sync_playwright() as p:
browser = p.chromium.launch(
headless=True,
args=[
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
"--disable-software-rasterizer",
"--disable-extensions",
"--disable-background-networking",
"--disable-default-apps",
"--disable-sync",
"--metrics-recording-only",
"--mute-audio",
],
)
context = browser.new_context(
viewport={"width": 1280, "height": 900},
user_agent=(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36"
),
ignore_https_errors=True,
)
page = context.new_page()
for idx, term in enumerate(terms, start=1):
try:
print(f"MFDS ์ค์๊ฐ ์กฐํ {idx}/{len(terms)}: {term}")
goto_success = False
last_goto_error = ""
for attempt in range(3):
try:
page.goto(
MFDS_LIVE_URL,
wait_until="domcontentloaded",
timeout=45000,
)
page.wait_for_timeout(3000)
goto_success = True
break
except Exception as e:
last_goto_error = str(e)
page.wait_for_timeout(3000)
if not goto_success:
local_errors.append(f"{term}: ์์ฝ์ฒ ์ ์ ์คํจ: {last_goto_error}")
continue
if not mfds_fill_search_input(page, term):
local_errors.append(f"{term}: ๊ฒ์ ์
๋ ฅ์ฐฝ ์ฐพ๊ธฐ ์คํจ")
continue
if not mfds_click_search(page):
try:
page.keyboard.press("Enter")
except Exception:
pass
page.wait_for_timeout(3000)
mfds_click_result_row(page, term)
page.wait_for_timeout(2000)
text = mfds_visible_text(page)
rows = parse_mfds_text(term, text)
if rows:
local_rows.extend(rows)
else:
local_errors.append(f"{term}: ๊ตญ๊ฐ๋ณ ๋ฐฐํฉํ๋/์ ํ ์ ๋ณด ๋ฏธ๊ฒ์ถ")
except Exception as e:
local_errors.append(f"{term}: {e}")
context.close()
browser.close()
return local_rows, local_errors
try:
all_rows, errors = run_browser_lookup()
except Exception as e:
err_text = str(e)
if "Executable doesn't exist" in err_text or "playwright install" in err_text.lower():
ok, install_msg = install_playwright_chromium_once()
if not ok:
return pd.DataFrame(), f"MFDS ๋ธ๋ผ์ฐ์ ์ค์น ์คํจ: {install_msg}"
try:
all_rows, errors = run_browser_lookup()
except Exception as e2:
return pd.DataFrame(), f"MFDS ๋ธ๋ผ์ฐ์ ์คํ ์คํจ: {e2}"
else:
return pd.DataFrame(), f"MFDS ๋ธ๋ผ์ฐ์ ์คํ ์คํจ: {e}"
df = pd.DataFrame(all_rows)
msg = f"MFDS ์ค์๊ฐ ์กฐํ ์๋ฃ: ๊ฒ์์ด {len(terms)}๊ฐ, ๊ฒฐ๊ณผ {len(df)}ํ"
if errors:
msg += " / ์ผ๋ถ ์คํจ: " + " ; ".join(errors[:5])
if len(errors) > 5:
msg += f" ์ธ {len(errors) - 5}๊ฑด"
return df, msg
def ingredient_matches_live_row(material, component, row):
identity_values = [
component.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""),
component.get("INCI Name", ""),
component.get("CAS.No", ""),
material.get("Trade name(๊ตญ๋ฌธ)", ""),
material.get("Trade name(์๋ฌธ)", ""),
]
identity = normalize_compact(" ".join([safe_str(x) for x in identity_values if safe_str(x)]))
row_terms = [row.get("์๋ฃ๋ช
", ""), row.get("INCI", ""), row.get("CAS.No", "")]
for term in row_terms:
term_norm = normalize_compact(term)
if term_norm and len(term_norm) >= 3 and term_norm in identity:
return True
return False
def live_row_country_matches(country, row_country):
row_country_norm = normalize_compact(row_country)
col = display_country(country)
aliases = [country, col, country_key(country)]
if col == "Korea":
aliases += ["ํ๊ตญ", "๋ํ๋ฏผ๊ตญ", "KOREA", "KR"]
elif col == "FDA":
aliases += ["๋ฏธ๊ตญ", "USA", "US", "United States", "FDA"]
elif col == "EU":
aliases += ["EU", "์ ๋ฝ", "์ ๋ฝ์ฐํฉ", "European Union", "Europe"]
elif col == "ASEAN":
aliases += ["ASEAN", "์์ธ์"]
aliases_norm = [normalize_compact(x) for x in aliases if safe_str(x)]
return any(alias and alias in row_country_norm for alias in aliases_norm)
def evaluate_live_detail_rule(country, material, component, live_df):
if live_df is None or live_df.empty:
return None
hits = []
for _, row in live_df.iterrows():
if ingredient_matches_live_row(material, component, row) and live_row_country_matches(country, row.get("๊ตญ๊ฐ", "")):
hits.append(row)
if not hits:
return None
row = hits[0]
category = safe_str(row.get("๊ตฌ๋ถ", "")) or "์ ํ"
regulation = safe_str(row.get("๊ท์ ๋ด์ฉ", ""))
limit = safe_str(row.get("ํ๋", ""))
source = safe_str(row.get("์ถ์ฒ", "MFDS live"))
parts = [category]
if limit:
parts.append(f"ํ๋ {limit}")
if regulation:
parts.append(regulation[:300])
result_text = " / ".join([p for p in parts if p])
return {
"๋ํ INCI": safe_str(component.get("INCI Name", "")) or safe_str(row.get("์๋ฃ๋ช
", "")) or "-",
"๊ฒฐ๊ณผ": result_text,
"ํ์๋ฌธ๊ตฌ": normalize_formula_country_text(result_text, display_country(country), component.get("INCI Name", "")),
"๋น๊ณ ": source,
}
# ============================================================
# 7. ๋ก์ปฌ ๊ท์น ํ์
# ============================================================
def evaluate_limit_rule(country, material, component, rule_group, rule_type_name):
ckey = country_key(country)
key = match_rule_key(material, component, rule_group)
if not key:
return None
rule = rule_group[key]
country_rule = rule.get(ckey)
label = rule.get("label", key)
amount = component.get("amount_float")
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
if not country_rule:
return {
"๋ํ INCI": label,
"๊ฒฐ๊ณผ": f"{rule_type_name} / {label} / {display_country(country)} ๋ฐฐํฉํ๋ ์๋ฃ ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": LIMIT_CHECK_TEXT,
"๋น๊ณ ": "๋ก์ปฌ ์ ํ์ฑ๋ถ ๋ชฉ๋ก์๋ ์์ผ๋ ํด๋น ๊ตญ๊ฐ ํ๋๊ฐ ๋ฏธ๋ฑ๋ก. Pass ์ฒ๋ฆฌ ๊ธ์ง.",
}
status = country_rule.get("status", "allowed")
formula_text = country_rule.get("formula_text", "")
if status == "prohibited":
return {
"๋ํ INCI": label,
"๊ฒฐ๊ณผ": f"{label} ๋ฐฐํฉ๊ธ์ง / ํ์ฌ ํจ๋ {amount_text}% / ์ฌ๊ฒํ ํ์",
"ํ์๋ฌธ๊ตฌ": formula_text or "๋ฐฐํฉ๊ธ์ง",
"๋น๊ณ ": "-",
}
limit = country_rule.get("limit")
if limit is not None:
if amount is not None and amount > limit:
result_text = f"{rule_type_name} / {label} ํ์ฌ ํจ๋ {amount_text}%, ํ๋ {format_percent(limit)}% ์ด๊ณผ(์ฌ๊ฒํ ํ์)"
display_text = "ํ๋ ์ด๊ณผ"
else:
result_text = f"{rule_type_name} / {label} ํ์ฌ ํจ๋ {amount_text}%, ํ๋ {format_percent(limit)}% ์ด๋ด"
display_text = formula_text or f"๋ฐฐํฉํ๋: {format_percent(limit)}%"
return {
"๋ํ INCI": label,
"๊ฒฐ๊ณผ": result_text,
"ํ์๋ฌธ๊ตฌ": display_text,
"๋น๊ณ ": "-",
}
return {
"๋ํ INCI": label,
"๊ฒฐ๊ณผ": f"{rule_type_name} / {label} / ํ๋๊ฐ ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": LIMIT_CHECK_TEXT,
"๋น๊ณ ": "๋ก์ปฌ ๊ท์น์ ์ฑ๋ถ์ ์์ผ๋ ํ๋๊ฐ์ด ๋น์ด ์์. Pass ์ฒ๋ฆฌ ๊ธ์ง.",
}
def evaluate_local_rules(country, material, component, ingredient_totals, ingredient_amount_parts):
ckey = country_key(country)
amount = component.get("amount_float")
plain_fragrance = evaluate_plain_fragrance_rule(country, material, component)
if plain_fragrance is not None:
return plain_fragrance
uv_result = evaluate_limit_rule(country, material, component, UV_FILTER_RULES, "UV ํํฐ")
if uv_result is not None:
return uv_result
preservative_result = evaluate_limit_rule(country, material, component, PRESERVATIVE_RULES, "๋ณด์กด์ /์ ํ์ฑ๋ถ")
if preservative_result is not None:
return preservative_result
functional_key = match_rule_key(material, component, FUNCTIONAL_KOREA_RULES)
if ckey == "KOREA" and functional_key:
rule = FUNCTIONAL_KOREA_RULES[functional_key]
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
return {
"๋ํ INCI": rule["label"],
"๊ฒฐ๊ณผ": rule["result"].format(amount=amount_text),
"ํ์๋ฌธ๊ตฌ": rule.get("formula_text", "๊ธฐ๋ฅ์ฑ ํ์ธ"),
"๋น๊ณ ": "๊ธฐ๋ฅ์ฑ ํ์ยท๊ด๊ณ ์ฌ๋ถ ํ์ธ",
}
identity = get_identity_text(material, component)
for fragrance_key, rule in FRAGRANCE_ALLERGEN_RULES.items():
matched = False
for alias in rule.get("aliases", []):
if normalize_text(alias) in identity:
matched = True
break
if not matched:
continue
return {
"๋ํ INCI": rule["label"],
"๊ฒฐ๊ณผ": f"ํฅ๋ฃ ์๋ ๋ฅด๊ฒ / {rule['label']} / {display_country(country)} ํ์๊ธฐ์ค ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": NEED_CHECK_TEXT,
"๋น๊ณ ": "ํฅ๋ฃ ์๋ ๋ฅด๊ฒ ํ๋ณด. ์ธ๋ถ ํ์๊ธฐ์ค ๋ฐ ์ ํ ์ ํ ํ์ธ ํ์.",
}
if amount is None:
return {
"๋ํ INCI": safe_str(component.get("INCI Name", "")) or "-",
"๊ฒฐ๊ณผ": "ํจ๋ ์ ๋ณด ์์ / In formula(w/w %) ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": "ํจ๋ ํ์ธ",
"๋น๊ณ ": "-",
}
return None
# ============================================================
# 8. GPT ๋ณด์กฐ ํ์
# ============================================================
def parse_country_response(text):
result = {
"๋ํ INCI": "-",
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
for line in safe_str(text).splitlines():
line = line.strip()
if line.startswith("๋ํ INCI:"):
result["๋ํ INCI"] = line.split(":", 1)[1].strip() or "-"
elif line.startswith("๊ฒฐ๊ณผ:"):
result["๊ฒฐ๊ณผ"] = line.split(":", 1)[1].strip() or NO_EVIDENCE_TEXT
elif line.startswith("ํ์๋ฌธ๊ตฌ:"):
result["ํ์๋ฌธ๊ตฌ"] = line.split(":", 1)[1].strip() or "Pass"
elif line.startswith("๋น๊ณ :"):
result["๋น๊ณ "] = line.split(":", 1)[1].strip() or "-"
return result
def clean_json_text(text):
text = safe_str(text)
text = re.sub(r"^```json\s*", "", text.strip(), flags=re.IGNORECASE)
text = re.sub(r"^```\s*", "", text.strip())
text = re.sub(r"\s*```$", "", text.strip())
match = re.search(r"\[.*\]", text, flags=re.DOTALL)
if match:
return match.group(0)
match = re.search(r"\{.*\}", text, flags=re.DOTALL)
if match:
return match.group(0)
return text
def sanitize_country_result(parsed, country_col="", component=None, high_risk_reason=""):
if not isinstance(parsed, dict):
parsed = {}
component = component or {}
representative = safe_str(parsed.get("๋ํ INCI", "")) or safe_str(component.get("INCI Name", "")) or "-"
result_text = safe_str(parsed.get("๊ฒฐ๊ณผ", "")) or NO_EVIDENCE_TEXT
note = safe_str(parsed.get("๋น๊ณ ", "")) or "-"
display_text = safe_str(parsed.get("ํ์๋ฌธ๊ตฌ", ""))
if high_risk_reason and result_text == NO_EVIDENCE_TEXT:
result_text = f"{high_risk_reason} / {representative} / {country_col} ์ ํ ์ฌ๋ถ ํ์ธ ํ์"
display_text = NEED_CHECK_TEXT
note = "๊ณ ์ํ๊ตฐ ํ๋ณด ์ฑ๋ถ์ด๋ฏ๋ก ๊ทผ๊ฑฐ ๋ฏธ๊ฒ์ถ๋ง์ผ๋ก Pass ์ฒ๋ฆฌํ์ง ์์"
if not display_text:
display_text = normalize_formula_country_text(
result_text,
country_col=country_col,
inci_name=safe_str(component.get("INCI Name", "")),
amount_text=safe_str(component.get("In formula(w/w %)", "")),
)
bad_tokens = [
"๊ท์ ๋ช
", "์ด๋ ๊ณ์ฐ", "๊ท์ / ์ด๋", "{๊ท์ ๊ตฐ๋ช
}",
"{์ฑ๋ถ๋ช
", "{ํจ๋}", "{๊ธฐ์ค์น}", "placeholder", "N/A", "n/a",
]
if any(token in result_text for token in bad_tokens):
result_text = "ํ์ธ ํ์ / ๊ท์ ์ธ๋ถ ๊ณ์ฐ ์ฌํ์ธ ํ์"
display_text = NEED_CHECK_TEXT
if note == "-":
note = "๊ตฌ์ฒด ํ๋ ๋๋ ์ด๋ ๊ณ์ฐ๊ฐ ํ์ธ ํ์"
return {
"๋ํ INCI": representative,
"๊ฒฐ๊ณผ": result_text,
"ํ์๋ฌธ๊ตฌ": display_text,
"๋น๊ณ ": note,
}
def make_eval_cache_key(country, component):
amount = component.get("amount_float")
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
db_signature = get_current_db_signature(country)
return (
str(country),
str(db_signature),
safe_str(component.get("INCI Name", "")).lower(),
safe_str(component.get("ํ๊ธ ์ฑ๋ถ๋ช
", "")).lower(),
safe_str(component.get("CAS.No", "")).lower(),
amount_text,
)
def has_meaningful_search_hit(db, search_text, ingredient_names, k=MEANINGFUL_HIT_K):
if not db:
return False, ""
try:
docs = db.similarity_search(search_text, k=k)
context = "\n".join([d.page_content for d in docs])
except Exception:
return False, ""
context_norm = normalize_compact(context)
for name in ingredient_names:
name_norm = normalize_compact(name)
if name_norm and len(name_norm) >= 3 and name_norm in context_norm:
return True, context
return False, context
def evaluate_component_with_llm(country, material, component, llm, target_id=""):
db = build_database(country)
country_col = display_country(country)
inci_name = safe_str(component.get("INCI Name", ""))
korean_name = safe_str(component.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""))
cas_no = safe_str(component.get("CAS.No", ""))
amount = component.get("amount_float")
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
high_risk_reason = get_restricted_candidate_reason(material, component)
if not inci_name and not korean_name:
return {"๋ํ INCI": "-", "๊ฒฐ๊ณผ": "", "ํ์๋ฌธ๊ตฌ": "", "๋น๊ณ ": "-"}
if not db:
if high_risk_reason:
result = {
"๋ํ INCI": inci_name or korean_name or "-",
"๊ฒฐ๊ณผ": f"{high_risk_reason} / {inci_name or korean_name} / {country_col} ์ ํ ์ฌ๋ถ ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": NEED_CHECK_TEXT,
"๋น๊ณ ": "ํด๋น ๊ตญ๊ฐ/์ฑ๋ ๊ท์ DB ์์. ๊ณ ์ํ๊ตฐ ํ๋ณด์ด๋ฏ๋ก Pass ์ฒ๋ฆฌํ์ง ์์.",
}
else:
result = {
"๋ํ INCI": inci_name or "-",
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
log_search_context(target_id, country, component, result["๊ฒฐ๊ณผ"], "NO_DB", "ํด๋น ๊ตญ๊ฐ/์ฑ๋ ๊ท์ DB ์์")
return result
cache_key = make_eval_cache_key(country, component)
if cache_key in EVAL_CACHE:
return EVAL_CACHE[cache_key]
trade_ko = material.get("Trade name(๊ตญ๋ฌธ)", "")
trade_en = material.get("Trade name(์๋ฌธ)", "")
search_text = f"""
๊ตญ๊ฐ/์ฑ๋: {country}
์๋ฃ๋ช
๊ตญ๋ฌธ: {trade_ko}
์๋ฃ๋ช
์๋ฌธ: {trade_en}
๊ฒํ ์ฑ๋ถ ๊ตญ๋ฌธ: {korean_name}
๊ฒํ ์ฑ๋ถ INCI: {inci_name}
CAS.No: {cas_no}
์ต์ข
์ ํ ๋ด ํจ๋: {amount_text}%
์ ํ์ ํ: Leave-on ๋ฐ Wash-off ๊ธฐ์ค ๋ชจ๋ ํ์ธ
"""
has_hit, pre_context = has_meaningful_search_hit(
db=db,
search_text=search_text,
ingredient_names=[inci_name, korean_name, cas_no],
k=MEANINGFUL_HIT_K,
)
if not has_hit:
if high_risk_reason:
result = {
"๋ํ INCI": inci_name or korean_name or "-",
"๊ฒฐ๊ณผ": f"{high_risk_reason} / {inci_name or korean_name} / {country_col} ์ ํ ์ฌ๋ถ ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": NEED_CHECK_TEXT,
"๋น๊ณ ": "๊ณ ์ํ๊ตฐ ํ๋ณด์ด๋ ๊ตญ๊ฐ๋ณ ๊ท์ ํ์ผ์์ ์ง์ ๊ทผ๊ฑฐ ๋ฏธ๊ฒ์ถ. Pass ์ฒ๋ฆฌํ์ง ์์.",
}
else:
result = {
"๋ํ INCI": inci_name or "-",
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
EVAL_CACHE[cache_key] = result
log_search_context(target_id, country, component, result["๊ฒฐ๊ณผ"], "NO_MEANINGFUL_HIT", pre_context)
return result
docs = db.similarity_search(search_text, k=RAG_TOP_K_SINGLE)
context = "\n".join([d.page_content for d in docs])
prompt = f"""
๋๋ ํ์ฅํ ์ ์ฑ๋ถ ๊ท์ ์คํฌ๋ฆฌ๋ ์ ๋ฌธ๊ฐ์ผ.
์๋ ๋จ์ผ ๊ตฌ์ฑ์ฑ๋ถ์ ๋ฐ๋์ "{country}" ๊ธฐ์ค์ผ๋ก๋ง ๊ฒํ ํด.
[์ ๋ ๊ท์น]
- ํ์ฌ ๊ฒํ ๊ตญ๊ฐ๋ "{country}"์ด๋ค.
- ์๋ ๊ฒ์ ์๋ฌธ์ "{country}" ํด๋์์๋ง ๊ฒ์๋ ๊ทผ๊ฑฐ๋ค.
- ์ธ๋ถ ์ง์, ํ์ต ์ง์, ์ผ๋ฐ ๊ท์ ์ง์์ ์ฌ์ฉํ์ง ๋ง.
- ๋ค๋ฅธ ๊ตญ๊ฐ ๊ท์ ์ ํ์ฌ ๊ตญ๊ฐ์ ์์ ์ ์ฉํ์ง ๋ง.
- ๊ฒ์ ์๋ฌธ์ ๋ช
์๋์ง ์์ ์ ํ, ๋ฐฐํฉ๊ธ์ง, ๋ฐฐํฉํ๋๋ ๋ง๋ค์ง ๋ง.
- ๊ฒ์ ์๋ฌธ์ ๋ช
์๋ ์ ํ/๊ธ์ง/ํ๋ ๊ทผ๊ฑฐ๊ฐ ์์ผ๋ฉด ๊ฒฐ๊ณผ๋ ์ ํํ "{NO_EVIDENCE_TEXT}"์ผ๋ก ์์ฑํด.
- ๋จ, ๊ณ ์ํ๊ตฐ ํ๋ณด ์ฑ๋ถ์ด๋ฉด Pass๋ผ๊ณ ๋จ์ ํ์ง ๋ง๊ณ ํ์ธ ํ์๋ก ํ๋จํ ์ ์๋ค.
[๊ฒํ ์ฑ๋ถ]
๊ตญ๋ฌธ๋ช
: {korean_name}
INCI: {inci_name}
CAS.No: {cas_no}
์ต์ข
์ ํ ๋ด ํจ๋: {amount_text}%
๊ณ ์ํ๊ตฐ ํ๋ณด ์ฌ๋ถ: {high_risk_reason or "์๋"}
[๊ฒ์๋ {country} ๊ท์ ์๋ฌธ]
{context}
๋ฐ๋์ ์๋ ํ์์ผ๋ก๋ง ๋ต๋ณํด.
๋ํ INCI:
๊ฒฐ๊ณผ:
ํ์๋ฌธ๊ตฌ:
๋น๊ณ :
"""
try:
response = llm.invoke(prompt).content
parsed = parse_country_response(response)
parsed = sanitize_country_result(
parsed,
country_col=country_col,
component=component,
high_risk_reason=high_risk_reason,
)
EVAL_CACHE[cache_key] = parsed
log_search_context(target_id, country, component, parsed["๊ฒฐ๊ณผ"], "GPT_SINGLE", context)
return parsed
except Exception as e:
result = {
"๋ํ INCI": inci_name or "-",
"๊ฒฐ๊ณผ": "ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": NEED_CHECK_TEXT,
"๋น๊ณ ": str(e),
}
log_search_context(target_id, country, component, result["๊ฒฐ๊ณผ"], "GPT_SINGLE_ERROR", str(e))
return result
def evaluate_components_with_llm_batch(country, targets, llm):
results = {}
if not targets:
return results
db = build_database(country)
country_col = display_country(country)
if not db:
for item in targets:
comp = item["component"]
material = item["material"]
inci_name = safe_str(comp.get("INCI Name", ""))
korean_name = safe_str(comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""))
high_risk_reason = get_restricted_candidate_reason(material, comp)
if high_risk_reason:
result = {
"๋ํ INCI": inci_name or korean_name or "-",
"๊ฒฐ๊ณผ": f"{high_risk_reason} / {inci_name or korean_name} / {country_col} ์ ํ ์ฌ๋ถ ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": NEED_CHECK_TEXT,
"๋น๊ณ ": "ํด๋น ๊ตญ๊ฐ/์ฑ๋ ๊ท์ DB ์์. ๊ณ ์ํ๊ตฐ ํ๋ณด์ด๋ฏ๋ก Pass ์ฒ๋ฆฌํ์ง ์์.",
}
else:
result = {
"๋ํ INCI": inci_name or "-",
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
results[item["target_id"]] = result
log_search_context(item["target_id"], country, comp, result["๊ฒฐ๊ณผ"], "NO_DB", "ํด๋น ๊ตญ๊ฐ/์ฑ๋ ๊ท์ DB ์์")
return results
uncached_targets = []
for item in targets:
comp = item["component"]
cache_key = make_eval_cache_key(country, comp)
if cache_key in EVAL_CACHE:
results[item["target_id"]] = EVAL_CACHE[cache_key]
else:
uncached_targets.append(item)
filtered_targets = []
for item in uncached_targets:
material = item["material"]
comp = item["component"]
inci_name = safe_str(comp.get("INCI Name", ""))
korean_name = safe_str(comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""))
cas_no = safe_str(comp.get("CAS.No", ""))
amount = comp.get("amount_float")
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
high_risk_reason = get_restricted_candidate_reason(material, comp)
search_text = f"""
๊ตญ๊ฐ/์ฑ๋: {country}
์๋ฃ๋ช
๊ตญ๋ฌธ: {material.get("Trade name(๊ตญ๋ฌธ)", "")}
์๋ฃ๋ช
์๋ฌธ: {material.get("Trade name(์๋ฌธ)", "")}
๊ฒํ ์ฑ๋ถ ๊ตญ๋ฌธ: {korean_name}
๊ฒํ ์ฑ๋ถ INCI: {inci_name}
CAS.No: {cas_no}
์ต์ข
์ ํ ๋ด ํจ๋: {amount_text}%
"""
has_hit, context = has_meaningful_search_hit(
db=db,
search_text=search_text,
ingredient_names=[inci_name, korean_name, cas_no],
k=MEANINGFUL_HIT_K,
)
if has_hit:
filtered_targets.append(item)
else:
if high_risk_reason:
result = {
"๋ํ INCI": inci_name or korean_name or "-",
"๊ฒฐ๊ณผ": f"{high_risk_reason} / {inci_name or korean_name} / {country_col} ์ ํ ์ฌ๋ถ ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": NEED_CHECK_TEXT,
"๋น๊ณ ": "๊ณ ์ํ๊ตฐ ํ๋ณด์ด๋ ๊ตญ๊ฐ๋ณ ๊ท์ ํ์ผ์์ ์ง์ ๊ทผ๊ฑฐ ๋ฏธ๊ฒ์ถ. Pass ์ฒ๋ฆฌํ์ง ์์.",
}
else:
result = {
"๋ํ INCI": inci_name or "-",
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
results[item["target_id"]] = result
EVAL_CACHE[make_eval_cache_key(country, comp)] = result
log_search_context(item["target_id"], country, comp, result["๊ฒฐ๊ณผ"], "NO_MEANINGFUL_HIT", context)
uncached_targets = filtered_targets
if not uncached_targets:
return results
for batch in chunk_list(uncached_targets, BATCH_SIZE):
target_payload = []
search_blocks = []
for item in batch:
comp = item["component"]
material = item["material"]
inci_name = safe_str(comp.get("INCI Name", ""))
korean_name = safe_str(comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""))
cas_no = safe_str(comp.get("CAS.No", ""))
amount = comp.get("amount_float")
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
high_risk_reason = get_restricted_candidate_reason(material, comp)
target_payload.append({
"target_id": item["target_id"],
"์ฑ๋ถ ๊ตญ๋ฌธ๋ช
": korean_name,
"INCI": inci_name,
"CAS.No": cas_no,
"์ต์ข
์ ํ ๋ด ํจ๋(%)": amount_text,
"๊ณ ์ํ๊ตฐ ํ๋ณด": high_risk_reason or "์๋",
})
search_blocks.append(f"{inci_name} {korean_name} {cas_no} {amount_text}%")
search_text = f"""
๊ตญ๊ฐ/์ฑ๋: {country}
๊ฒํ ๋์ ์ฑ๋ถ:
{chr(10).join(search_blocks)}
"""
try:
docs = db.similarity_search(search_text, k=RAG_TOP_K_BATCH)
context = "\n".join([d.page_content for d in docs])
prompt = f"""
๋๋ ํ์ฅํ ์ ์ฑ๋ถ ๊ท์ ์คํฌ๋ฆฌ๋ ์ ๋ฌธ๊ฐ์ผ.
์๋ ์ฌ๋ฌ ๊ตฌ์ฑ์ฑ๋ถ์ ๋ฐ๋์ "{country}" ๊ธฐ์ค์ผ๋ก๋ง ๊ฒํ ํด.
[์ ๋ ๊ท์น]
- ํ์ฌ ๊ฒํ ๊ตญ๊ฐ๋ "{country}"์ด๋ค.
- ์๋ ๊ฒ์ ์๋ฌธ์ "{country}" ํด๋์์๋ง ๊ฒ์๋ ๊ทผ๊ฑฐ๋ค.
- ์ธ๋ถ ์ง์, ํ์ต ์ง์, ์ผ๋ฐ ๊ท์ ์ง์์ ์ฌ์ฉํ์ง ๋ง.
- ๊ฒ์ ์๋ฌธ์ ๊ทผ๊ฑฐ๊ฐ ์์ผ๋ฉด ๊ฒฐ๊ณผ๋ ์ ํํ "{NO_EVIDENCE_TEXT}"์ผ๋ก ์์ฑํด.
- ๋จ, ๊ณ ์ํ๊ตฐ ํ๋ณด ์ฑ๋ถ์ด๋ฉด Pass๋ผ๊ณ ๋จ์ ํ์ง ๋ง๊ณ ํ์ธ ํ์๋ก ํ๋จํ ์ ์๋ค.
[๊ฒํ ๋์ JSON]
{json.dumps(target_payload, ensure_ascii=False, indent=2)}
[๊ฒ์๋ {country} ๊ท์ ์๋ฌธ]
{context}
๋ฐ๋์ JSON ๋ฐฐ์ด๋ง ์ถ๋ ฅํด.
๋งํฌ๋ค์ด, ์ค๋ช
๋ฌธ, ์ฝ๋๋ธ๋ก ์์ด ์์ JSON๋ง ์ถ๋ ฅํด.
์ถ๋ ฅ ํ์:
[
{{
"target_id": "์
๋ ฅ target_id ๊ทธ๋๋ก",
"๋ํ INCI": "๋ํ INCI ๋๋ -",
"๊ฒฐ๊ณผ": "{NO_EVIDENCE_TEXT} ๋๋ ๊ท์ ๋ด์ฉ",
"ํ์๋ฌธ๊ตฌ": "Pass ๋๋ ๋ฐฐํฉํ๋/๋ผ๋ฒจ๋ง/ํ์ธ ํ์ ๋ฑ ์งง์ ๋ฌธ๊ตฌ",
"๋น๊ณ ": "-"
}}
]
"""
response = llm.invoke(prompt).content
parsed = json.loads(clean_json_text(response))
if isinstance(parsed, dict):
parsed = [parsed]
parsed_by_id = {}
for obj in parsed:
if not isinstance(obj, dict):
continue
target_id = safe_str(obj.get("target_id", ""))
if not target_id:
continue
item_comp = None
item_material = None
for item in batch:
if item["target_id"] == target_id:
item_comp = item["component"]
item_material = item["material"]
break
high_risk_reason = ""
if item_comp and item_material:
high_risk_reason = get_restricted_candidate_reason(item_material, item_comp)
parsed_by_id[target_id] = sanitize_country_result(
obj,
country_col=country_col,
component=item_comp or {},
high_risk_reason=high_risk_reason,
)
for item in batch:
target_id = item["target_id"]
comp = item["component"]
if target_id in parsed_by_id:
result = parsed_by_id[target_id]
results[target_id] = result
EVAL_CACHE[make_eval_cache_key(country, comp)] = result
log_search_context(target_id, country, comp, result["๊ฒฐ๊ณผ"], "GPT_BATCH", context)
for item in batch:
target_id = item["target_id"]
if target_id in results:
continue
results[target_id] = evaluate_component_with_llm(
country=country,
material=item["material"],
component=item["component"],
llm=llm,
target_id=target_id,
)
except Exception as e:
print(f"batch GPT ํ์ ์คํจ: {country} / {e}")
for item in batch:
target_id = item["target_id"]
if target_id in results:
continue
results[target_id] = evaluate_component_with_llm(
country=country,
material=item["material"],
component=item["component"],
llm=llm,
target_id=target_id,
)
return results
# ============================================================
# 9. ์ถ๋ ฅ ๋ฐ์ดํฐ ๊ตฌ์ฑ
# ============================================================
def make_formula_statement_rows(row_items, country_cols):
rows = []
for item in row_items:
material = item["material"]
comp = item["component"]
row_data = item["row_data"]
no_value = safe_str(material.get("NO", ""))
korean_name = safe_str(comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""))
inci_name = safe_str(comp.get("INCI Name", ""))
if is_total_like_text(no_value) or is_total_like_text(korean_name) or is_total_like_text(inci_name):
continue
row = {
"NO.": no_value,
"ํ๊ธ ํ์คํ ๋ช
์นญ": korean_name,
"INGREDIENT NAME (INCI)": inci_name,
"FUNCTION": comp.get("FUNCTION", ""),
"CAS.No": comp.get("CAS.No", ""),
"SOURCE": comp.get("SOURCE", "ICID") or "ICID",
"%(w/w)": comp.get("In formula(w/w %)", ""),
}
for country_col in country_cols:
raw_text = safe_str(row_data.get(country_col, ""))
display_text = safe_str(row_data.get(country_col + "_display", ""))
if display_text:
row[country_col] = display_text
else:
row[country_col] = normalize_formula_country_text(
raw_text,
country_col=country_col,
inci_name=inci_name,
amount_text=comp.get("In formula(w/w %)", ""),
)
rows.append(row)
total = 0.0
for row in rows:
value = to_number(row.get("%(w/w)", ""))
if value is not None:
total += value
total_row = {
"NO.": "",
"ํ๊ธ ํ์คํ ๋ช
์นญ": "",
"INGREDIENT NAME (INCI)": "TOTAL",
"FUNCTION": "",
"CAS.No": "",
"SOURCE": "",
"%(w/w)": format_amount(total),
}
for country_col in country_cols:
total_row[country_col] = ""
rows.append(total_row)
return pd.DataFrame(rows)
def make_regulatory_summary_rows(row_items, country_cols):
rows = []
for item in row_items:
row_data = item["row_data"]
if not is_country_result_issue(row_data.get("Result", "")):
continue
row = {
"ํ๊ธ ์ฑ๋ถ๋ช
": row_data.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""),
"INCI Name": row_data.get("INCI Name", ""),
"In formula(w/w %)": row_data.get("In formula\n(w/w %)", ""),
"Result": row_data.get("Result", ""),
}
for country_col in country_cols:
value = safe_str(row_data.get(country_col, ""))
row[country_col] = value if is_country_result_issue(value) else "-"
row["๋น๊ณ "] = row_data.get("๋น๊ณ ", "-")
rows.append(row)
columns = ["ํ๊ธ ์ฑ๋ถ๋ช
", "INCI Name", "In formula(w/w %)", "Result"] + country_cols + ["๋น๊ณ "]
if not rows:
return pd.DataFrame(columns=columns)
return pd.DataFrame(rows)[columns]
def sum_formula_percent(formula_df):
total = 0.0
if formula_df is None or formula_df.empty:
return total
for _, row in formula_df.iterrows():
no_value = safe_str(row.get("NO.", ""))
korean_name = safe_str(row.get("ํ๊ธ ํ์คํ ๋ช
์นญ", ""))
inci_name = safe_str(row.get("INGREDIENT NAME (INCI)", ""))
if is_total_like_text(no_value) or is_total_like_text(korean_name) or is_total_like_text(inci_name):
continue
num = to_number(row.get("%(w/w)", ""))
if num is not None:
total += num
return total
# ============================================================
# 10. ์์
์ ์ฅ / ์คํ์ผ
# ============================================================
def write_output_workbook(out_path, product_name, formula_df, regulatory_df, raw_df):
with pd.ExcelWriter(out_path, engine="openpyxl") as writer:
formula_df.to_excel(writer, index=False, sheet_name="Formula Ingredients Statement", startrow=5)
regulatory_df.to_excel(writer, index=False, sheet_name="Regulatory Screening Summary")
raw_df.to_excel(writer, index=False, sheet_name="Evidence Log")
wb = load_workbook(out_path)
ws = wb["Formula Ingredients Statement"]
max_col = max(1, ws.max_column)
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=max_col)
ws["A1"] = "Formular Ingredients Statement"
ws["A1"].font = Font(bold=True, size=24, underline="single")
ws["A1"].alignment = Alignment(horizontal="center", vertical="center")
ws.merge_cells(start_row=4, start_column=1, end_row=4, end_column=max_col)
ws["A4"] = f"PRODUCT NAME : {safe_str(product_name)}"
ws["A4"].font = Font(bold=True, size=13)
ws["A4"].alignment = Alignment(horizontal="left", vertical="center")
wb.save(out_path)
style_output_workbook(out_path)
def style_output_workbook(path):
wb = load_workbook(path)
thin_border = Border(
left=Side(style="thin", color="808080"),
right=Side(style="thin", color="808080"),
top=Side(style="thin", color="808080"),
bottom=Side(style="thin", color="808080"),
)
header_font = Font(color="000000", bold=True, size=10)
body_font = Font(color="000000", size=10)
title_font = Font(color="000000", bold=True, size=24, underline="single")
product_font = Font(color="000000", bold=True, size=13)
warning_fill = PatternFill(start_color="FCE4D6", end_color="FCE4D6", fill_type="solid")
pass_fill = PatternFill(start_color="FFFFFF", end_color="FFFFFF", fill_type="solid")
for ws in wb.worksheets:
if ws.title == "Formula Ingredients Statement":
header_row = 6
ws.sheet_view.showGridLines = False
ws.row_dimensions[1].height = 36
ws.row_dimensions[2].height = 20
ws.row_dimensions[3].height = 20
ws.row_dimensions[4].height = 26
ws.row_dimensions[5].height = 18
ws.row_dimensions[6].height = 28
ws["A1"].font = title_font
ws["A1"].alignment = Alignment(horizontal="center", vertical="center")
ws["A4"].font = product_font
ws["A4"].alignment = Alignment(horizontal="left", vertical="center")
for row in range(header_row, ws.max_row + 1):
for col in range(1, ws.max_column + 1):
cell = ws.cell(row=row, column=col)
cell.border = thin_border
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
cell.font = body_font
if row == header_row:
cell.font = header_font
if row > header_row:
value = safe_str(cell.value)
if value and value != "Pass" and col >= 8:
cell.fill = warning_fill
elif value == "Pass":
cell.fill = pass_fill
total_row = None
for row in range(header_row + 1, ws.max_row + 1):
if safe_str(ws.cell(row=row, column=3).value).upper() == "TOTAL":
total_row = row
break
if total_row:
for col in range(1, ws.max_column + 1):
cell = ws.cell(row=total_row, column=col)
cell.font = Font(bold=True)
cell.border = thin_border
cell.alignment = Alignment(horizontal="center", vertical="center")
try:
ws.merge_cells(start_row=total_row, start_column=2, end_row=total_row, end_column=6)
ws.cell(row=total_row, column=2).value = "TOTAL"
ws.cell(row=total_row, column=2).font = Font(bold=True)
ws.cell(row=total_row, column=2).alignment = Alignment(horizontal="center", vertical="center")
ws.cell(row=total_row, column=3).value = None
except Exception:
pass
widths = {1: 6, 2: 34, 3: 34, 4: 26, 5: 16, 6: 10, 7: 12}
for col_idx in range(1, ws.max_column + 1):
col_letter = get_column_letter(col_idx)
ws.column_dimensions[col_letter].width = widths.get(col_idx, 15)
for row in range(header_row + 1, ws.max_row + 1):
cell = ws.cell(row=row, column=7)
if to_number(cell.value) is not None:
cell.number_format = "0.000######"
ws.freeze_panes = "A7"
else:
header_row = 1
ws.sheet_view.showGridLines = False
for row in range(1, ws.max_row + 1):
for col in range(1, ws.max_column + 1):
cell = ws.cell(row=row, column=col)
cell.border = thin_border
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
if row == header_row:
cell.font = header_font
for col_idx in range(1, ws.max_column + 1):
col_letter = get_column_letter(col_idx)
header = safe_str(ws.cell(row=header_row, column=col_idx).value)
if header in ["๊ฒ์ ์๋ฌธ", "Evidence", "Evidence Text"]:
ws.column_dimensions[col_letter].width = 70
elif header in ["Result", "๋น๊ณ "]:
ws.column_dimensions[col_letter].width = 45
elif header in ["INCI Name"]:
ws.column_dimensions[col_letter].width = 32
else:
ws.column_dimensions[col_letter].width = 18
ws.freeze_panes = "A2"
wb.save(path)
# ============================================================
# 11. ๋ฉ์ธ ์ฒ๋ฆฌ
# ============================================================
def build_integrated_result(row_data, country_cols):
issue_items = []
for country_col in country_cols:
value = safe_str(row_data.get(country_col, ""))
if is_country_result_issue(value):
issue_items.append(country_col)
if not issue_items:
return "PASS"
return "์ฌ๊ฒํ ํ์: " + ", ".join(issue_items)
def process(
countries,
file,
product_name="",
use_mfds_live=False,
live_max_terms=30,
live_headless=True,
):
global RAW_SEARCH_LOGS
RAW_SEARCH_LOGS = []
try:
if not file:
return None, None, "โ ์์
ํ์ผ์ ์
๋ก๋ํด์ฃผ์ธ์."
if not countries:
return None, None, "โ ์คํฌ๋ฆฌ๋ ๊ตญ๊ฐ๋ฅผ ์ ํํด์ฃผ์ธ์."
df = pd.read_excel(file.name)
grouped_materials, meta = make_grouped_materials(df)
if not grouped_materials:
return None, None, "โ ์์
์์ ์ ์ฑ๋ถ ์ ๋ณด๋ฅผ ์ฝ์ง ๋ชปํ์ต๋๋ค. ์ปฌ๋ผ๋ช
์ ํ์ธํด์ฃผ์ธ์."
ingredient_totals = meta["ingredient_totals"]
ingredient_amount_parts = meta["ingredient_amount_parts"]
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
row_items = []
for material in grouped_materials:
comp = material["Components"][0]
target_id = f"row_{len(row_items)}"
row_data = {
"NO": material.get("NO", ""),
"Trade name(๊ตญ๋ฌธ)": material.get("Trade name(๊ตญ๋ฌธ)", ""),
"Trade name(์๋ฌธ)": material.get("Trade name(์๋ฌธ)", ""),
"ํ๊ธ ์ฑ๋ถ๋ช
": comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""),
"INCI Name": comp.get("INCI Name", ""),
"In formula\n(w/w %)": comp.get("In formula(w/w %)", ""),
"Result": "",
}
row_items.append({
"target_id": target_id,
"material": material,
"component": comp,
"row_data": row_data,
"notes": [],
})
mfds_df = pd.DataFrame()
mfds_live_msg = "์ฌ์ฉ ์ ํจ"
terms = extract_terms_for_live_lookup(row_items)
if use_mfds_live:
try:
mfds_df, mfds_live_msg = mfds_live_lookup_terms(
terms=terms,
max_terms=live_max_terms,
headless=live_headless,
)
except Exception as e:
mfds_df = pd.DataFrame()
mfds_live_msg = f"MFDS ์ค์๊ฐ ์กฐํ ์คํจ: {e}"
for country in countries:
col_name = display_country(country)
gpt_targets = []
for item in row_items:
fragrance_result = evaluate_plain_fragrance_rule(
country=country,
material=item["material"],
component=item["component"],
)
if fragrance_result is not None:
item["row_data"][col_name] = fragrance_result.get("๊ฒฐ๊ณผ", "")
item["row_data"][col_name + "_display"] = fragrance_result.get("ํ์๋ฌธ๊ตฌ", NEED_CHECK_TEXT)
note = safe_str(fragrance_result.get("๋น๊ณ ", "-"))
if note and note != "-":
item["notes"].append(f"{col_name}: {note}")
log_search_context(
item["target_id"],
country,
item["component"],
fragrance_result.get("๊ฒฐ๊ณผ", ""),
"FRAGRANCE_RULE",
note,
)
continue
mfds_result = None
if use_mfds_live and mfds_df is not None and not mfds_df.empty:
mfds_result = evaluate_live_detail_rule(
country=country,
material=item["material"],
component=item["component"],
live_df=mfds_df,
)
if mfds_result is not None:
item["row_data"][col_name] = mfds_result.get("๊ฒฐ๊ณผ", "")
item["row_data"][col_name + "_display"] = mfds_result.get("ํ์๋ฌธ๊ตฌ", NEED_CHECK_TEXT)
note = safe_str(mfds_result.get("๋น๊ณ ", "-"))
if note and note != "-":
item["notes"].append(f"{col_name}: {note}")
log_search_context(
item["target_id"],
country,
item["component"],
mfds_result.get("๊ฒฐ๊ณผ", ""),
"MFDS_LIVE",
note,
)
continue
local_result = evaluate_local_rules(
country=country,
material=item["material"],
component=item["component"],
ingredient_totals=ingredient_totals,
ingredient_amount_parts=ingredient_amount_parts,
)
if local_result is not None:
item["row_data"][col_name] = local_result.get("๊ฒฐ๊ณผ", "")
item["row_data"][col_name + "_display"] = local_result.get("ํ์๋ฌธ๊ตฌ", "Pass")
note = safe_str(local_result.get("๋น๊ณ ", "-"))
if note and note != "-":
item["notes"].append(f"{col_name}: {note}")
log_search_context(
item["target_id"],
country,
item["component"],
local_result.get("๊ฒฐ๊ณผ", ""),
"LOCAL_RULE",
note if note and note != "-" else "๋ก์ปฌ ๊ท์น ํ์ ",
)
continue
gpt_targets.append({
"target_id": item["target_id"],
"material": item["material"],
"component": item["component"],
})
batch_results = evaluate_components_with_llm_batch(country=country, targets=gpt_targets, llm=llm)
for item in row_items:
if col_name in item["row_data"]:
continue
result = batch_results.get(item["target_id"])
if result is None:
result = {
"๋ํ INCI": safe_str(item["component"].get("INCI Name", "")) or "-",
"๊ฒฐ๊ณผ": "ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": NEED_CHECK_TEXT,
"๋น๊ณ ": "batch ๊ฒฐ๊ณผ ๋๋ฝ",
}
item["row_data"][col_name] = result.get("๊ฒฐ๊ณผ", "")
item["row_data"][col_name + "_display"] = result.get("ํ์๋ฌธ๊ตฌ", "Pass")
note = safe_str(result.get("๋น๊ณ ", "-"))
if note and note != "-":
item["notes"].append(f"{col_name}: {note}")
country_cols = [display_country(c) for c in countries]
for item in row_items:
item["row_data"]["Result"] = build_integrated_result(item["row_data"], country_cols)
item["row_data"]["๋น๊ณ "] = " / ".join(item["notes"]) if item["notes"] else "-"
formula_df = make_formula_statement_rows(row_items, country_cols)
regulatory_df = make_regulatory_summary_rows(row_items, country_cols)
raw_columns = ["target_id", "๊ตญ๊ฐ/์ฑ๋", "์ฑ๋ถ๋ช
", "INCI Name", "ํ์ ", "์ถ์ฒ", "๊ฒ์ ์๋ฌธ"]
raw_df = pd.DataFrame(RAW_SEARCH_LOGS)
if raw_df.empty:
raw_df = pd.DataFrame(columns=raw_columns)
else:
for col in raw_columns:
if col not in raw_df.columns:
raw_df[col] = ""
raw_df = raw_df[raw_columns]
formula_total = sum_formula_percent(formula_df)
safe_country_name = "_".join([re.sub(r"[^a-zA-Z0-9๊ฐ-ํฃ_-]", "_", str(c)) for c in countries])
product_part = safe_filename(product_name) if safe_str(product_name) else "product"
out_path = str(OUTPUT_DIR / f"screening_result_{product_part}_{safe_country_name}.xlsx")
write_output_workbook(
out_path=out_path,
product_name=product_name,
formula_df=formula_df,
regulatory_df=regulatory_df,
raw_df=raw_df,
)
msg = (
"โ
๋ถ์ ์๋ฃ\n"
f"- Product Name: {safe_str(product_name) or '-'}\n"
f"- ์ ์ฑ๋ถ ํ ์: {len(formula_df)}๊ฐ\n"
f"- In formula ํฉ๊ณ: {format_amount(formula_total)}%\n"
f"- ์ฌ๊ฒํ ํ์ ์ฑ๋ถ: {len(regulatory_df)}๊ฐ\n"
f"- MFDS ์ํ: {mfds_live_msg}\n"
"- ๊ฒฐ๊ณผ ํ์ผ ์ํธ:\n"
" 1) Formula Ingredients Statement\n"
" 2) Regulatory Screening Summary\n"
" 3) Evidence Log\n"
)
return formula_df, out_path, msg
except Exception as e:
tb = traceback.format_exc()
print(tb)
return None, None, f"โ ์ค๋ฅ ๋ฐ์: {str(e)}\n\n{tb[-3000:]}"
# ============================================================
# 12. Gradio UI
# ============================================================
with gr.Blocks(css=custom_css) as demo:
gr.Markdown("# ๐ reBom Regulatory Screening AI")
gr.Markdown("### ๊ตญ๊ฐ๋ณ ๊ท์ ํด๋ ๊ฒ์ + ์์ฝ์ฒ ์ค์๊ฐ ์กฐํ + Formular Ingredients Statement ์ถ๋ ฅ")
with gr.Row():
gr.Button("๐ช ๋ก๊ทธ์์", link="/logout?all_session=false", variant="secondary")
with gr.Tab("๐ ์คํฌ๋ฆฌ๋"):
country = gr.CheckboxGroup(
choices=get_country_folders(),
value=[],
label="๐ ๊ตญ๊ฐ / ์ฑ๋ ์ ํ",
elem_id="country_checks",
)
refresh = gr.Button("๐ ํด๋/๊ท์ ํ์ผ ์๋ก๊ณ ์นจ")
product_name = gr.Textbox(
label="์ ํ๋ช
/ PRODUCT NAME",
placeholder="์: ๋ง๋ฐ์นดํฌ๋ฆผ",
)
file = gr.File(
label="์ ์ฑ๋ถ ์์
์
๋ก๋",
file_types=[".xlsx"],
)
use_mfds_live = gr.Checkbox(
label="์์ฝ์ฒ ์ฌ์ดํธ ์ค์๊ฐ ์กฐํ ์ฌ์ฉ",
value=False,
)
live_max_terms = gr.Number(
label="์์ฝ์ฒ ์ค์๊ฐ ์กฐํ ์ต๋ ๊ฒ์์ด ์",
value=5,
precision=0,
)
live_headless = gr.Checkbox(
label="์์ฝ์ฒ ์กฐํ ๋ธ๋ผ์ฐ์ ์จ๊น ๋ชจ๋",
value=True,
)
btn = gr.Button("๐ ๋ถ์ ์์", variant="primary")
df_out = gr.Dataframe(
label="๋ฏธ๋ฆฌ๋ณด๊ธฐ - Formular Ingredients Statement",
wrap=True,
interactive=False,
)
file_out = gr.File(label="๊ฒฐ๊ณผ ๋ค์ด๋ก๋")
msg_out = gr.Textbox(
label="์ํ / ์ค๋ฅ ๋ฉ์์ง",
interactive=False,
lines=12,
)
refresh.click(
fn=refresh_country_choices_and_clear_cache,
inputs=country,
outputs=country,
)
try:
auto_refresh_timer = gr.Timer(15)
auto_refresh_timer.tick(
fn=refresh_country_choices_keep_selection,
inputs=country,
outputs=country,
)
except Exception as e:
print(f"์๋ ๊ตญ๊ฐ ๋ชฉ๋ก ๊ฐฑ์ ํ์ด๋จธ ๋นํ์ฑํ: {e}")
file.change(
fn=preview_excel,
inputs=file,
outputs=df_out,
)
btn.click(
process,
inputs=[
country,
file,
product_name,
use_mfds_live,
live_max_terms,
live_headless,
],
outputs=[
df_out,
file_out,
msg_out,
],
)
# ============================================================
# 13. ๋ก๊ทธ์ธ ์ธ์ฆ
# ============================================================
USER_DB = {
"jin2li@rebom.kr": "qwer0515!",
"jkh@rebom.kr": "rebom123!",
"member2": "1111",
}
def auth_fn(username, password):
username = str(username).strip()
password = str(password).strip()
return username in USER_DB and USER_DB[username] == password
# ============================================================
# 14. ์ฑ ์คํ
# ============================================================
try:
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
ssr_mode=False,
auth=auth_fn,
allowed_paths=ALLOWED_PATHS,
blocked_paths=BLOCKED_PATHS,
show_api=False,
footer_links=[],
app_kwargs={
"docs_url": None,
"redoc_url": None,
"openapi_url": None,
},
)
except TypeError:
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
auth=auth_fn,
allowed_paths=ALLOWED_PATHS,
blocked_paths=BLOCKED_PATHS,
) |