Spaces:
Configuration error
Configuration error
File size: 72,369 Bytes
e4fcc0b |
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 |
# =========================================================
# POSCO DX - MRO Composite AI - PROCESS GUIDE ENHANCED
# μ
무 νλ‘μΈμ€ κ°μ΄λ ν΅ν© λ²μ - Hugging Face Spaces λ°°ν¬μ©
# =========================================================
import os
import json
import time
import random
import traceback
from dataclasses import dataclass
from typing import Dict, Any, List, Optional, Tuple, TypedDict
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import networkx as nx
# β
Plotly imports
import plotly
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
print(f"β
NumPy: {np.__version__}")
print(f"β
Pandas: {pd.__version__}")
print(f"β
Plotly: {plotly.__version__}")
try:
from pulp import LpProblem, LpMinimize, LpVariable, lpSum, LpStatus
PULP_AVAILABLE = True
print("β
PuLP available")
except ImportError:
print("β οΈ PuLP not available")
PULP_AVAILABLE = False
import gradio as gr
print(f"β
Gradio: {gr.__version__}")
try:
from langgraph.graph import StateGraph, END
LANGGRAPH_AVAILABLE = True
print("β
LangGraph available")
except ImportError:
print("β οΈ LangGraph not available")
LANGGRAPH_AVAILABLE = False
try:
from openai import OpenAI
OPENAI_AVAILABLE = True
print("β
OpenAI available")
except ImportError:
print("β οΈ OpenAI not available")
OPENAI_AVAILABLE = False
# =========================================================
# API Key Configuration for Hugging Face Spaces
# =========================================================
# Hugging Face Spacesμμ νκ²½ λ³μλ‘ API ν€ λ‘λ
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY', '').strip()
if OPENAI_API_KEY:
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
print("β
OpenAI API Key loaded from environment")
else:
print("β οΈ DEMO MODE - No API Key found")
print("π‘ To use OpenAI features, add OPENAI_API_KEY to your Hugging Face Space Secrets")
print("\n" + "=" * 60)
print("β
νλ‘μΈμ€ κ°μ΄λ ν΅ν© λ²μ μ΄κΈ°ν μλ£!")
print("=" * 60 + "\n")
# =========================================================
# Process Guide Configuration
# =========================================================
PROCESS_WORKFLOWS = {
"mro": {
"title": "π§ MRO μ΄μ νλ‘μΈμ€",
"steps": [
{
"id": "1",
"name": "κ³ μ₯/μ λΉ μμ² μ μ",
"description": "μ€λΉ κ³ μ₯ λλ μλ°©μ λΉ μμ²μ μ μν©λλ€",
"input": "μ€λΉ ID, κ³ μ₯ μ ν, μ°μ μμ",
"output": "μμ² λ²νΈ, μ€λΉ μμΈμ 보",
"owner": "νμ₯ λ΄λΉμ β MROν",
"duration": "5λΆ"
},
{
"id": "2",
"name": "μ€λΉ μ 보 μ‘°ν",
"description": "Knowledge Graphμμ μ€λΉ μμΈ μ 보λ₯Ό μ‘°νν©λλ€",
"input": "μ€λΉ ID",
"output": "μ€λΉλͺ
, μμΉ, μ€μλ, μ λΉμ΄λ ₯",
"owner": "MROν (AI μλ)",
"duration": "1λΆ"
},
{
"id": "3",
"name": "νΈν λΆν μλ λ§€μΉ",
"description": "μ€λΉμ νΈνλλ λͺ¨λ λΆνμ μλμΌλ‘ μ‘°νν©λλ€",
"input": "μ€λΉ ID, μ€λΉ νμ
",
"output": "νΈν λΆν 리μ€νΈ, νμ/μ ν ꡬλΆ",
"owner": "MROν (AI μλ)",
"duration": "2λΆ"
},
{
"id": "4",
"name": "μ μ¬ μ¬κ³ νν© νμΈ",
"description": "λ³Έμ¬ λ° κ° μ μ² μμ μ¬κ³ νν©μ μ€μκ° νμΈν©λλ€",
"input": "νλͺ© ID",
"output": "μ°½κ³ λ³ μ¬κ³ λ, μμ μ¬κ³ , μμ½μλ",
"owner": "MROν (AI μλ)",
"duration": "1λΆ"
},
{
"id": "5",
"name": "λ°μ£Ό νμμ± νλ¨",
"description": "μ¬κ³ λΆμ‘± μ λ°μ£Ό μμ²μ μμ±ν©λλ€",
"input": "νμ¬κ³ , μμ μ¬κ³ , μμλ",
"output": "λ°μ£Ό νμ μ¬λΆ, λ°μ£Ό μλ",
"owner": "MROν",
"duration": "3λΆ"
},
{
"id": "6",
"name": "ꡬ맀ν λ°μ£Ό μμ²",
"description": "ꡬ맀νμ λ°μ£Ό μμ²μλ₯Ό μ λ¬ν©λλ€",
"input": "νλͺ© μ 보, μλ, λ©κΈ° μꡬμ¬ν",
"output": "λ°μ£Ό μμ² λ²νΈ",
"owner": "MROν β ꡬ맀ν",
"duration": "2λΆ"
}
],
"total_duration": "μ½ 15λΆ",
"success_criteria": [
"β μ€λΉ μ 보 μ νν μλ³",
"β νΈν λΆν 100% λ§€μΉ",
"β μ¬κ³ νν© μ€μκ° λ°μ",
"β λ°μ£Ό μλ μ΅μ ν"
]
},
"procurement": {
"title": "π° ꡬ맀/μ‘°λ¬ νλ‘μΈμ€",
"steps": [
{
"id": "1",
"name": "λ°μ£Ό μμ² μ μ",
"description": "MROνμΌλ‘λΆν° λ°μ£Ό μμ²μ μ μν©λλ€",
"input": "λ°μ£Ό μμ²μ, νλͺ©, μλ, λ©κΈ°",
"output": "ꡬ맀 μμ
λ²νΈ",
"owner": "ꡬ맀ν",
"duration": "3λΆ"
},
{
"id": "2",
"name": "곡κΈμ
체 μ 보 μ‘°ν",
"description": "νλͺ©λ³ λ±λ‘λ λͺ¨λ 곡κΈμ
체λ₯Ό μ‘°νν©λλ€",
"input": "νλͺ© ID",
"output": "곡κΈμ
체 리μ€νΈ, λ¨κ°, λ©κΈ°, ESGλ±κΈ",
"owner": "ꡬ맀ν (AI μλ)",
"duration": "2λΆ"
},
{
"id": "3",
"name": "κ·μ μ€μ κ²μ¦",
"description": "Neuro-Symbolic AIλ‘ κ΅¬λ§€ κ·μ μ μλ κ²μ¦ν©λλ€",
"input": "νλͺ© μμ±, 곡κΈμ
체 μ 보",
"output": "κ·μ μλ° μ¬λΆ, μ°¨λ¨/κ²½κ³ λ¦¬μ€νΈ",
"owner": "ꡬ맀ν (AI μλ)",
"duration": "1λΆ"
},
{
"id": "4",
"name": "μ΅μ λ°°λΆ κ³μ°",
"description": "Linear ProgrammingμΌλ‘ μ΅μ λ°μ£Ό κ³νμ μ립ν©λλ€",
"input": "곡κΈμ
체 μ€νΌ, μμλ, μ μ½μ‘°κ±΄",
"output": "μ
μ²΄λ³ λ°μ£Όλ, μ΄ λΉμ©, μμ λ©κΈ°",
"owner": "ꡬ맀ν (AI μλ)",
"duration": "2λΆ"
},
{
"id": "5",
"name": "λ°μ£Ό μ λ΅ μ립",
"description": "LLMμ΄ μ΅μ ν κ²°κ³Όλ₯Ό λ°νμΌλ‘ ꡬ맀 μ λ΅μ μ μν©λλ€",
"input": "μ΅μ ν κ²°κ³Ό, μμ₯ μν©",
"output": "λ°μ£Ό μ λ΅, 리μ€ν¬ λΆμ, λμ",
"owner": "ꡬ맀ν (AI μ§μ)",
"duration": "5λΆ"
},
{
"id": "6",
"name": "κ²½μμ§ μΉμΈ μμ²",
"description": "λ°μ£Ό κ³νμ κ²½μμ§μκ² μΉμΈ μμ²ν©λλ€",
"input": "λ°μ£Ό κ³νμ, λΉμ© λΆμ",
"output": "μΉμΈ μμ² λ²νΈ",
"owner": "ꡬ맀ν β κ²½μμ§",
"duration": "3λΆ"
},
{
"id": "7",
"name": "PO λ°ν (μΉμΈ ν)",
"description": "μΉμΈ ν 곡κΈμ
체μ μ μ λ°μ£Όμλ₯Ό λ°νν©λλ€",
"input": "μΉμΈλ λ°μ£Ό κ³ν",
"output": "PO λ²νΈ, κ³μ½μ",
"owner": "ꡬ맀ν",
"duration": "10λΆ"
}
],
"total_duration": "μ½ 25λΆ (μΉμΈ λκΈ° μ μΈ)",
"success_criteria": [
"β κ·μ 100% μ€μ",
"β λΉμ© μ΅μ ν λ¬μ±",
"β λ©κΈ° μꡬμ¬ν μΆ©μ‘±",
"β ESG λ±κΈ κΈ°μ€ λ§μ‘±"
]
},
"executive": {
"title": "π κ²½μμ§ μμ¬κ²°μ νλ‘μΈμ€",
"steps": [
{
"id": "1",
"name": "μΉμΈ μμ² μλ¦Ό",
"description": "λ°μ£Ό μΉμΈ μμ² μλ¦Όμ μμ ν©λλ€",
"input": "μΉμΈ μμ² λ²νΈ, μμ½ μ 보",
"output": "μλ¦Ό νμΈ",
"owner": "μμ€ν
β κ²½μμ§",
"duration": "μ¦μ"
},
{
"id": "2",
"name": "KPI λμ보λ νμΈ",
"description": "μ€μκ° KPI λμ보λλ₯Ό ν΅ν΄ μ λ°μ νν©μ νμ
ν©λλ€",
"input": "μμ",
"output": "λΉμ©μ κ°λ₯ , μ»΄νλΌμ΄μΈμ€, ESGμ μ λ±",
"owner": "κ²½μμ§",
"duration": "2λΆ"
},
{
"id": "3",
"name": "Action Items κ²ν ",
"description": "μ°μ μμλ³ μ‘°μΉ νλͺ©μ κ²ν ν©λλ€",
"input": "Action Items 리μ€νΈ",
"output": "κ²ν μ견",
"owner": "κ²½μμ§",
"duration": "5λΆ"
},
{
"id": "4",
"name": "λ°μ£Ό μμΈ λΆμ",
"description": "λ°μ£Ό κ³νμ νλΉμ±μ λ©΄λ°ν κ²ν ν©λλ€",
"input": "λ°μ£Ό κ³νμ, μ΅μ ν κ²°κ³Ό, κ·μ κ²μ¦",
"output": "λΆμ μ견",
"owner": "κ²½μμ§",
"duration": "10λΆ"
},
{
"id": "5",
"name": "μμ¬κ²°μ ",
"description": "μΉμΈ/λ°λ €/쑰건λΆμΉμΈμ κ²°μ ν©λλ€",
"input": "κ²ν κ²°κ³Ό",
"output": "μΉμΈ κ²°μ , νΌλλ°±",
"owner": "κ²½μμ§",
"duration": "3λΆ"
},
{
"id": "6",
"name": "νΌλλ°± μ 곡",
"description": "κ°μ μ μ λλ μ§μμ¬νμ μ λ¬ν©λλ€",
"input": "μμ¬κ²°μ κ·Όκ±°",
"output": "νΌλλ°± λ©μμ§, κ°μ λ°©ν₯",
"owner": "κ²½μμ§ β ꡬ맀ν",
"duration": "5λΆ"
}
],
"total_duration": "μ½ 25λΆ",
"success_criteria": [
"β μ λ΅μ νλΉμ± κ²μ¦",
"β 리μ€ν¬ μμ© κ°λ₯ μμ€",
"β μμ° λ²μ λ΄ μ§ν",
"β μ₯κΈ° λͺ©ν λΆν©"
]
}
}
# =========================================================
# Enhanced Configuration with Real Part Names
# =========================================================
SCENARIO_PRESETS = {
"κΈ΄κΈ κ³ μ₯ λμ": {
"description": "π¨ ν¬νμ μ² μ μ»¨λ² μ΄μ΄ λ² μ΄λ§ κΈ΄κΈ κ³ μ₯",
"equipment_id": "CONV-PH-007",
"item_id": "",
"demand_qty": 10,
"context": "μ»¨λ² μ΄μ΄ λ² μ΄λ§ κ³ μ₯μΌλ‘ μμ°λΌμΈ μ€λ¨. μ¦μ κ΅μ²΄ νμ.",
"priority": "κΈ΄κΈ",
"guide": "리λνμ μ΅μν μ°μ . κ΅λ΄ 곡κΈμ
체 μ°μ κ³ λ €."
},
"μ κΈ° λ°μ£Ό κ³ν": {
"description": "π μκ° μ κΈ° λ°μ£Ό - μ μνν μλ°©μ λΉ",
"equipment_id": "PUMP-GY-003",
"item_id": "SEAL-A45",
"demand_qty": 50,
"context": "μκ° μλ°©μ λΉ κ³ν. μ΅μ κ°κ²© λ° μ¬κ³ κ· ν νμ.",
"priority": "μ μ",
"guide": "λΉμ© μ΅μ ν μ°μ . ESG λ±κΈ κ³ λ €."
},
"κ·μ μ€μ κ²μ¦": {
"description": "βοΈ κ·μ νλͺ©(νΉμννλ¬Όμ§) ꡬ맀 κ²μ¦",
"equipment_id": "VALVE-PH-005",
"item_id": "",
"demand_qty": 20,
"context": "νΉμ μ€λ§μ¬ ꡬ맀. ν΄μΈκ΅¬λ§€ μ°¨λ¨ κ·μ μ€μ νμ.",
"priority": "κ·μ μ€μ",
"guide": "μ»΄νλΌμ΄μΈμ€ 100% μ€μ. κ΅λ΄μ
μ²΄λ§ νμ©."
}
}
# Real part names and categories
REAL_PART_NAMES = {
"λ² μ΄λ§": ["SKF 6205 λ³Όλ² μ΄λ§", "NSK μν΅λ² μ΄λ§", "NTN ν
μ΄νΌλ² μ΄λ§"],
"μ€νμ ": ["μ μ€λ§λΌ 220", "λͺ¨λΉ DTE 25", "μ§μμ€μΉΌν
μ€ ν°λΉμ "],
"νν°": ["νμ΄λλ‘λ½ μ μνν°", "ν컀 μμ΄νν°", "λλλμ¨ μ λ°νν°"],
"벨νΈ": ["κ²μ΄μΈ νμ그립 벨νΈ", "λ°λ V벨νΈ", "μ΅ν°λ²¨νΈ νμ΄λ°λ²¨νΈ"],
"μΌμ": ["μ§λ©μ€ κ·Όμ μΌμ", "μ€λ―λ‘ κ΄μ μΌμ", "νλμ° μλ ₯μΌμ"],
"ν¨νΉ": ["NOK μ€λ§", "ν컀 μ μμ°", "λ°μΉ΄ κ·Έλλν¨νΉ"],
"ν¨μ¦": ["LSμ°μ MCCB", "μλμ΄λ μ°¨λ¨κΈ°", "ABB ν¨μ¦"],
"νΈμ€": ["ν컀 μ μνΈμ€", "λ§λ¦¬ κ³ μνΈμ€", "λΈλ¦¬μ§μ€ν€ μ°μ
νΈμ€"],
"λ³ΌνΈ": ["SUS304 μ‘κ°λ³ΌνΈ", "κ³ μ₯λ ₯λ³ΌνΈ F10T", "μ΅μ»€λ³ΌνΈ M16"],
"μ€λ§μ¬": ["λ‘νμ΄νΈ μ€λνΈ", "μ°λ¦¬λ³Έλ μ‘μν¨νΉ", "ν¨μΌ λ°λ΄μ¬"]
}
# Enhanced supplier info
REAL_SUPPLIERS = [
{"name": "ν¬μ€μ½μΌλ―ΈμΉΌ", "type": "κ΅λ΄", "esg": "A", "specialty": "νν/μ€νμ "},
{"name": "ν¨μ±μ€κ³΅μ
", "type": "κ΅λ΄", "esg": "A", "specialty": "λ² μ΄λ§/κΈ°κ³"},
{"name": "LSμ°μ ", "type": "κ΅λ΄", "esg": "B", "specialty": "μ κΈ°/μΌμ"},
{"name": "μΌνμ½λ΄μ", "type": "κ΅λ΄", "esg": "B", "specialty": "μ κΈ°λΆν"},
{"name": "νκ΄μ°μ
", "type": "κ΅λ΄", "esg": "C", "specialty": "νΈμ€/ν¨νΉ"},
{"name": "νκ΅ν컀", "type": "κ΅λ΄", "esg": "A", "specialty": "μ μλΆν"},
{"name": "κ·ΈλΌμ½(Graco)", "type": "ν΄μΈ", "esg": "B", "specialty": "μ μμ₯λΉ"},
{"name": "μλ¨Έμ¨(Emerson)", "type": "ν΄μΈ", "esg": "C", "specialty": "λ°ΈλΈ/μΌμ"}
]
# =========================================================
# Utility Functions
# =========================================================
def now_ts() -> str:
return time.strftime("%Y-%m-%d %H:%M:%S")
def safe_json(obj: Any) -> str:
try:
return json.dumps(obj, ensure_ascii=False, indent=2)
except Exception:
return str(obj)
def format_status(status_dict: Dict[str, Any]) -> str:
lines = [
"=" * 60,
"π μμ€ν
μ€ν μν",
"=" * 60,
"",
f"π μ°κ²°: {status_dict.get('mode', 'Unknown')}",
f"π― μλ리μ€: {status_dict.get('scenario', 'N/A')}",
f"βοΈ μ€λΉ: {status_dict.get('equipment', 'N/A')}",
f"π¦ νλͺ©: {status_dict.get('item_name', 'N/A')}",
f"π μμ: {status_dict.get('demand', 'N/A')}κ°",
f"π¨ μ°μ μμ: {status_dict.get('priority', 'N/A')}",
f"\nβ
λ°μ΄ν° κ²μ¦: {'ν΅κ³Ό' if status_dict.get('tables_ok') else 'μ€ν¨'}",
f"β±οΈ μ§ν: {status_dict.get('progress', 'N/A')}",
"\n" + "=" * 60
]
return "\n".join(lines)
def create_process_guide_html(process_key: str) -> str:
"""μ
무 νλ‘μΈμ€ κ°μ΄λλ₯Ό HTMLλ‘ μμ±"""
workflow = PROCESS_WORKFLOWS.get(process_key, {})
if not workflow:
return "<p>νλ‘μΈμ€ μ λ³΄κ° μμ΅λλ€.</p>"
html = f"""
<div style="font-family: 'Malgun Gothic', Arial, sans-serif; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; color: white;">
<h2 style="margin-top: 0;">{workflow['title']}</h2>
<p style="font-size: 14px; opacity: 0.9;">μ΄ μμμκ°: <strong>{workflow['total_duration']}</strong></p>
</div>
<div style="margin-top: 20px;">
"""
for step in workflow['steps']:
html += f"""
<div style="margin-bottom: 20px; padding: 15px; border-left: 4px solid #667eea; background: #f8f9fa; border-radius: 5px;">
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<div style="background: #667eea; color: white; width: 30px; height: 30px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; margin-right: 10px;">
{step['id']}
</div>
<h3 style="margin: 0; color: #2c3e50;">{step['name']}</h3>
<span style="margin-left: auto; background: #e3f2fd; padding: 3px 10px; border-radius: 10px; font-size: 12px; color: #1976d2;">
β±οΈ {step['duration']}
</span>
</div>
<p style="margin: 10px 0; color: #555;">{step['description']}</p>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px;">
<div style="background: white; padding: 10px; border-radius: 5px; border: 1px solid #e0e0e0;">
<strong style="color: #1976d2;">π₯ μ
λ ₯:</strong><br>
<span style="font-size: 13px; color: #666;">{step['input']}</span>
</div>
<div style="background: white; padding: 10px; border-radius: 5px; border: 1px solid #e0e0e0;">
<strong style="color: #388e3c;">π€ μΆλ ₯:</strong><br>
<span style="font-size: 13px; color: #666;">{step['output']}</span>
</div>
</div>
<div style="margin-top: 10px; padding: 8px; background: white; border-radius: 5px; border: 1px solid #e0e0e0;">
<strong style="color: #f57c00;">π€ λ΄λΉ:</strong>
<span style="font-size: 13px; color: #666;">{step['owner']}</span>
</div>
</div>
"""
html += """
</div>
<div style="margin-top: 30px; padding: 20px; background: #e8f5e9; border-radius: 10px; border-left: 4px solid #4caf50;">
<h3 style="margin-top: 0; color: #2e7d32;">β
μ±κ³΅ κΈ°μ€</h3>
<ul style="margin: 0; padding-left: 20px;">
"""
for criterion in workflow['success_criteria']:
html += f"<li style='margin: 5px 0; color: #1b5e20;'>{criterion}</li>"
html += """
</ul>
</div>
"""
return html
# =========================================================
# Enhanced Data Generator with Real Names
# =========================================================
def generate_demo_tables(seed: int = 7) -> Dict[str, pd.DataFrame]:
"""Generate realistic demo data"""
random.seed(seed)
np.random.seed(seed)
plants = pd.DataFrame([
{"plant_id": "PH", "plant_name": "ν¬νμ μ² μ", "region": "κ²½λΆ", "capacity": 1000},
{"plant_id": "GY", "plant_name": "κ΄μμ μ² μ", "region": "μ λ¨", "capacity": 1200},
{"plant_id": "HQ", "plant_name": "λ³Έμ¬", "region": "μμΈ", "capacity": 0},
])
# Equipment with real names
equipment = []
eq_configs = [
("PUMP", "μ μνν", ["PH", "GY"], 6),
("CONV", "μ»¨λ² μ΄μ΄", ["PH", "GY"], 4),
("VALVE", "μ μ΄λ°ΈλΈ", ["PH", "GY"], 3),
("MOTOR", "ꡬλλͺ¨ν°", ["PH", "GY"], 5),
]
eq_id = 1
for eq_type, eq_name_kr, plants_list, count in eq_configs:
for plant in plants_list:
for i in range(1, count + 1):
equipment.append({
"equipment_id": f"{eq_type}-{plant}-{eq_id:03d}",
"equipment_name": f"{eq_name_kr}-{plant}-{i}νΈκΈ°",
"plant_id": plant,
"equipment_type": eq_name_kr,
"criticality": random.choice(["κΈ΄κΈ", "κΈ΄κΈ", "μ€μ", "보ν΅"]),
"status": "κ°λμ€",
"last_maintenance": (datetime.now() - timedelta(days=random.randint(30, 180))).strftime("%Y-%m-%d"),
})
eq_id += 1
equipment = pd.DataFrame(equipment)
# Items with real part names
items = []
item_id = 1
for category, part_list in REAL_PART_NAMES.items():
for part_name in part_list:
items.append({
"item_id": f"{category[:3].upper()}-{chr(65 + (item_id % 3))}{item_id:02d}",
"item_name": part_name,
"category": category,
"uom": "EA",
"risk_class": "κ·μ " if "νν" in part_name or "νΉμ" in category else "μΌλ°",
"unit_weight": round(0.5 + random.random() * 5, 1),
"shelf_life_days": random.choice([365, 730, 1095, None]),
})
item_id += 1
items = pd.DataFrame(items)
# Compatibility
compat = []
for eq_idx, eq_row in equipment.iterrows():
eq_id = eq_row["equipment_id"]
eq_type = eq_row["equipment_type"]
# Match parts to equipment type
if "νν" in eq_type:
relevant_cats = ["λ² μ΄λ§", "μ€νμ ", "ν¨νΉ"]
elif "μ»¨λ² μ΄μ΄" in eq_type:
relevant_cats = ["λ² μ΄λ§", "벨νΈ", "μΌμ"]
elif "λ°ΈλΈ" in eq_type:
relevant_cats = ["μ€λ§μ¬", "ν¨νΉ", "μ€νμ "]
else:
relevant_cats = ["λ² μ΄λ§", "μΌμ", "νν°"]
for cat in relevant_cats:
cat_items = items[items["category"] == cat]
if len(cat_items) > 0:
selected = cat_items.sample(min(2, len(cat_items)))
for _, item in selected.iterrows():
compat.append({
"equipment_id": eq_id,
"item_id": item["item_id"],
"is_mandatory": (cat == relevant_cats[0]),
"annual_consumption_est": random.randint(20, 200),
"failure_rate": round(random.random() * 0.05, 3),
})
compat = pd.DataFrame(compat).drop_duplicates(["equipment_id", "item_id"])
# Storages
storages = pd.DataFrame([
{"storage_id": "WH-HQ", "plant_id": "HQ", "storage_name": "λ³Έμ¬ μ€μμ°½κ³ ", "capacity": 10000},
{"storage_id": "WH-PH", "plant_id": "PH", "storage_name": "ν¬ν MROμ°½κ³ ", "capacity": 5000},
{"storage_id": "WH-GY", "plant_id": "GY", "storage_name": "κ΄μ MROμ°½κ³ ", "capacity": 5000},
])
# Inventory with realistic levels
inventory = []
for st_idx, st_row in storages.iterrows():
sampled_items = items.sample(min(25, len(items)))
for _, item in sampled_items.iterrows():
stock_level = random.randint(10, 100)
safety_stock = int(stock_level * 0.2)
inventory.append({
"storage_id": st_row["storage_id"],
"item_id": item["item_id"],
"on_hand": stock_level,
"safety_stock": safety_stock,
"reserved": random.randint(0, min(5, stock_level)),
"last_updated": (datetime.now() - timedelta(days=random.randint(1, 30))).strftime("%Y-%m-%d"),
})
inventory = pd.DataFrame(inventory)
# Suppliers with real names
suppliers = pd.DataFrame([
{
"supplier_id": f"SUP-{i:03d}",
"supplier_name": sup["name"],
"supplier_type": sup["type"],
"rating": round(3.5 + random.random() * 1.5, 1),
"esg_level": sup["esg"],
"specialty": sup["specialty"],
"region": sup["type"],
"payment_terms": random.choice(["NET30", "NET45", "NET60"]),
"established_year": random.randint(1990, 2020),
}
for i, sup in enumerate(REAL_SUPPLIERS, 1)
])
# Supplier offers with realistic pricing
offers = []
for _, item in items.iterrows():
num_suppliers = random.randint(3, 4)
selected_sups = suppliers.sample(min(num_suppliers, len(suppliers)))
base_price = 10000 + random.randint(0, 90000)
for rank, (_, sup) in enumerate(selected_sups.iterrows()):
price_multiplier = 1.0 + (rank * 0.05) + random.uniform(-0.1, 0.1)
offers.append({
"item_id": item["item_id"],
"supplier_id": sup["supplier_id"],
"unit_price": int(base_price * price_multiplier),
"lead_time_days": 3 + rank * 2 + random.randint(0, 5),
"moq": [10, 20, 50, 100][rank % 4],
"contract_type": random.choice(["λ¨κ°κ³μ½", "μ₯κΈ°κ³μ½", "μ€ν"]),
"discount_rate": round(random.random() * 0.1, 2) if rank == 0 else 0,
"quality_grade": random.choice(["A", "A", "B", "C"]),
})
supplier_offers = pd.DataFrame(offers)
# Policies
policies = pd.DataFrame([
{
"policy_id": "R-001",
"rule_name": "κ·μ νλͺ© ν΄μΈκ΅¬λ§€ μ ν",
"rule_logic": "IF item.risk_class == 'κ·μ ' AND supplier.region == 'ν΄μΈ' THEN block",
"severity": "μ°¨λ¨",
"department": "λ²λ¬΄ν"
},
{
"policy_id": "R-002",
"rule_name": "μμ μ¬κ³ λ―Έλ§ κΈ΄κΈλ°μ£Ό",
"rule_logic": "IF (on_hand - reserved) < safety_stock THEN expedite",
"severity": "κ²½κ³ ",
"department": "MROν"
},
{
"policy_id": "R-003",
"rule_name": "κΈ΄κΈμ€λΉ μ°μ λ°°λΆ",
"rule_logic": "IF equipment.criticality == 'κΈ΄κΈ' THEN priority",
"severity": "μ°μ μμ",
"department": "μμ°ν"
},
{
"policy_id": "R-004",
"rule_name": "ESG Cλ±κΈ μ ν",
"rule_logic": "IF supplier.esg_level == 'C' THEN penalize",
"severity": "ν¨λν°",
"department": "ꡬ맀ν"
},
])
# Purchase history
purchase_history = []
for i in range(200):
item = items.sample(1).iloc[0]
supplier = suppliers.sample(1).iloc[0]
qty = random.randint(10, 100)
price = random.randint(10000, 100000)
purchase_history.append({
"po_id": f"PO-2024-{10000 + i}",
"date": (datetime.now() - timedelta(days=random.randint(1, 365))).strftime("%Y-%m-%d"),
"item_id": item["item_id"],
"supplier_id": supplier["supplier_id"],
"qty": qty,
"unit_price": price,
"total_amount": qty * price,
"delivery_status": random.choice(["μλ£", "μλ£", "μλ£", "μ§μ°", "μ§νμ€"]),
})
purchase_history = pd.DataFrame(purchase_history)
return {
"plants": plants,
"equipment": equipment,
"items": items,
"compat": compat,
"storages": storages,
"inventory": inventory,
"suppliers": suppliers,
"supplier_offers": supplier_offers,
"policies": policies,
"purchase_history": purchase_history
}
def validate_tables(tables: Dict[str, pd.DataFrame]) -> Tuple[bool, List[str]]:
"""Validate tables"""
required = ["plants", "equipment", "items", "compat", "storages", "inventory",
"suppliers", "supplier_offers", "policies", "purchase_history"]
issues = []
for k in required:
if k not in tables:
issues.append(f"Missing: {k}")
elif not isinstance(tables[k], pd.DataFrame):
issues.append(f"Invalid type: {k}")
elif len(tables[k]) == 0:
issues.append(f"Empty: {k}")
return len(issues) == 0, issues
# =========================================================
# Plotly Dashboard Functions
# =========================================================
def create_mro_inventory_dashboard(inv_df: pd.DataFrame, item_name: str) -> go.Figure:
"""MRO μ¬κ³ νν© λμ보λ"""
if len(inv_df) == 0:
fig = go.Figure()
fig.add_annotation(text="μ¬κ³ λ°μ΄ν° μμ", showarrow=False, font_size=20)
fig.update_layout(height=700, title_text="μ¬κ³ μ 보 μμ")
return fig
# μλΈνλ‘― μμ±
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('μ°½κ³ λ³ μ¬κ³ νν©', 'μμ μ¬κ³ λλΉ νμ¬κ³ ', 'μ¬κ³ μν', 'μ°½κ³ λ³ μ μ μ¨'),
specs=[[{"type": "bar"}, {"type": "indicator"}],
[{"type": "pie"}, {"type": "table"}]]
)
# 1. μ°½κ³ λ³ μ¬κ³ λ° μ°¨νΈ
fig.add_trace(
go.Bar(
x=inv_df['storage_name'],
y=inv_df['on_hand'],
name='νμ¬κ³ ',
marker_color='lightblue',
text=inv_df['on_hand'],
textposition='auto',
),
row=1, col=1
)
fig.add_trace(
go.Bar(
x=inv_df['storage_name'],
y=inv_df['safety_stock'],
name='μμ μ¬κ³ ',
marker_color='orange',
text=inv_df['safety_stock'],
textposition='auto',
),
row=1, col=1
)
# 2. μ΄ μ¬κ³ κ²μ΄μ§
total_stock = inv_df['on_hand'].sum()
total_safety = inv_df['safety_stock'].sum()
fig.add_trace(
go.Indicator(
mode="gauge+number+delta",
value=total_stock,
delta={'reference': total_safety, 'increasing': {'color': "green"}},
title={'text': f"μ΄ μ¬κ³ λ<br><sub>{item_name}</sub>"},
gauge={
'axis': {'range': [0, total_safety * 2]},
'bar': {'color': "darkblue"},
'steps': [
{'range': [0, total_safety], 'color': "lightgray"},
{'range': [total_safety, total_safety * 1.5], 'color': "lightgreen"}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': total_safety
}
}
),
row=1, col=2
)
# 3. μ¬κ³ μν νμ΄ μ°¨νΈ
inv_df['available'] = inv_df['on_hand'] - inv_df['reserved']
fig.add_trace(
go.Pie(
labels=['κ°μ©μ¬κ³ ', 'μμ½λ¨', 'μμ μ¬κ³ '],
values=[
inv_df['available'].sum(),
inv_df['reserved'].sum(),
max(0, total_safety - inv_df['available'].sum())
],
marker_colors=['green', 'orange', 'red'],
hole=0.3,
),
row=2, col=1
)
# 4. μμΈ ν
μ΄λΈ
fig.add_trace(
go.Table(
header=dict(
values=['μ°½κ³ ', 'νμ¬κ³ ', 'μμ μ¬κ³ ', 'μμ½', 'κ°μ©'],
fill_color='paleturquoise',
align='left'
),
cells=dict(
values=[
inv_df['storage_name'],
inv_df['on_hand'],
inv_df['safety_stock'],
inv_df['reserved'],
inv_df['available']
],
fill_color='lavender',
align='left'
)
),
row=2, col=2
)
fig.update_layout(
height=700,
showlegend=True,
title_text=f"π¦ MRO μ¬κ³ λΆμ λμ보λ - {item_name}",
title_font_size=20
)
return fig
def create_mro_workflow_status(equipment_info: Dict, compat_items: pd.DataFrame) -> go.Figure:
"""MRO μν¬νλ‘μ° μν μκ°ν"""
fig = go.Figure()
# μν¬νλ‘μ° λ¨κ³
steps = [
"μ€λΉ νμΈ",
"νΈνλΆν μ‘°ν",
"μ¬κ³ νμΈ",
"μμ κ²μ¦",
"λ°μ£Ό μμ²"
]
statuses = ["μλ£", "μλ£", "μ§νμ€", "λκΈ°", "λκΈ°"]
colors = ["green", "green", "orange", "gray", "gray"]
# Funnel μ°¨νΈλ‘ μν¬νλ‘μ° νν
fig.add_trace(go.Funnel(
y=steps,
x=[100, 80, 60, 40, 20],
textposition="inside",
textinfo="label+percent initial",
marker={"color": colors},
connector={"line": {"color": "royalblue", "width": 3}}
))
equipment_name = equipment_info.get('equipment_name', 'N/A') if equipment_info else 'N/A'
fig.update_layout(
title_text=f"π MRO μν¬νλ‘μ° μ§ν μν<br><sub>μ€λΉ: {equipment_name}</sub>",
height=400,
showlegend=False
)
return fig
def create_procurement_comparison_dashboard(offers_df: pd.DataFrame, rules_eval: Dict) -> go.Figure:
"""ꡬ맀 λ΄λΉμ - 곡κΈμ
체 λΉκ΅ λμ보λ"""
if len(offers_df) == 0:
fig = go.Figure()
fig.add_annotation(text="곡κΈμ
체 λ°μ΄ν° μμ", showarrow=False, font_size=20)
fig.update_layout(height=700, title_text="곡κΈμ
체 μ 보 μμ")
return fig
# μλΈνλ‘―
fig = make_subplots(
rows=2, cols=2,
subplot_titles=(
'π° κ°κ²© λΉκ΅',
'β±οΈ λ©κΈ° λΉκ΅',
'π ESG λ±κΈ λΆν¬',
'π― μ’
ν© νκ°'
),
specs=[
[{"type": "bar"}, {"type": "scatter"}],
[{"type": "pie"}, {"type": "table"}]
]
)
# κ·μΉ νκ° κ²°κ³Ό μΆκ°
offers_df['blocked'] = offers_df['supplier_id'].apply(
lambda x: rules_eval.get(x, {}).get('block', False)
)
offers_df['color'] = offers_df['blocked'].apply(lambda x: 'red' if x else 'green')
# 1. κ°κ²© λΉκ΅ λ° μ°¨νΈ
fig.add_trace(
go.Bar(
x=offers_df['supplier_name'],
y=offers_df['unit_price'],
marker_color=offers_df['color'],
text=[f"{p:,}μ" for p in offers_df['unit_price']],
textposition='auto',
name='λ¨κ°',
),
row=1, col=1
)
# 2. κ°κ²©-λ©κΈ° μ€μΊν°
fig.add_trace(
go.Scatter(
x=offers_df['lead_time_days'],
y=offers_df['unit_price'],
mode='markers+text',
marker=dict(
size=15,
color=offers_df['color'],
line=dict(width=2, color='white')
),
text=offers_df['supplier_name'],
textposition="top center",
name='곡κΈμ
체',
),
row=1, col=2
)
# 3. ESG λ±κΈ νμ΄
esg_counts = offers_df['esg_level'].value_counts()
fig.add_trace(
go.Pie(
labels=esg_counts.index,
values=esg_counts.values,
marker_colors=['lightgreen', 'lightyellow', 'lightcoral'],
hole=0.3,
),
row=2, col=1
)
# 4. μ’
ν© νκ° ν
μ΄λΈ
evaluation = offers_df.copy()
evaluation['μ’
ν©μ μ'] = (
(100 - (evaluation['unit_price'] / evaluation['unit_price'].max() * 50)) +
(100 - (evaluation['lead_time_days'] / evaluation['lead_time_days'].max() * 30)) +
evaluation['esg_level'].map({'A': 20, 'B': 10, 'C': 0})
).round(1)
evaluation['μμ'] = evaluation['μ’
ν©μ μ'].rank(ascending=False).astype(int)
fig.add_trace(
go.Table(
header=dict(
values=['μμ', '곡κΈμ
체', 'λ¨κ°', 'λ©κΈ°', 'ESG', 'μ μ'],
fill_color='paleturquoise',
align='center'
),
cells=dict(
values=[
evaluation['μμ'],
evaluation['supplier_name'],
[f"{p:,}" for p in evaluation['unit_price']],
[f"{d}μΌ" for d in evaluation['lead_time_days']],
evaluation['esg_level'],
evaluation['μ’
ν©μ μ']
],
fill_color=[['white' if not b else 'lightcoral' for b in evaluation['blocked']]],
align='center'
)
),
row=2, col=2
)
fig.update_layout(
height=700,
showlegend=False,
title_text="π 곡κΈμ
체 μ’
ν© λΉκ΅ λμ보λ",
title_font_size=20
)
fig.update_xaxes(title_text="λ©κΈ° (μΌ)", row=1, col=2)
fig.update_yaxes(title_text="λ¨κ° (μ)", row=1, col=2)
return fig
def create_procurement_workflow(opt_result: Dict) -> go.Figure:
"""ꡬ맀 μν¬νλ‘μ° μ§ν μν"""
fig = go.Figure()
# μν¬νλ‘μ° λ¨κ³μ μν
workflow_steps = [
{"step": "1. μμ μ μ", "status": "μλ£", "time": "10λΆ"},
{"step": "2. 곡κΈμ
체 μ‘°ν", "status": "μλ£", "time": "5λΆ"},
{"step": "3. κ·μ κ²μ¦", "status": "μλ£", "time": "2λΆ"},
{"step": "4. μ΅μ ν λΆμ", "status": "μλ£", "time": "3λΆ"},
{"step": "5. λ°μ£Ό μΉμΈ", "status": "λκΈ°μ€", "time": "-"},
{"step": "6. PO λ°ν", "status": "λκΈ°μ€", "time": "-"},
]
# Progress Bar μ€νμΌ
y_pos = list(range(len(workflow_steps)))
colors = []
for step_info in workflow_steps:
if step_info["status"] == "μλ£":
colors.append("lightgreen")
elif step_info["status"] == "μ§νμ€":
colors.append("lightyellow")
else:
colors.append("lightgray")
fig.add_trace(go.Bar(
y=[s["step"] for s in workflow_steps],
x=[100 if s["status"] == "μλ£" else 50 if s["status"] == "μ§νμ€" else 0
for s in workflow_steps],
orientation='h',
marker=dict(color=colors),
text=[f"{s['status']} ({s['time']})" for s in workflow_steps],
textposition='auto',
))
fig.update_layout(
title_text="π ꡬ맀 μν¬νλ‘μ° μ§ν νν©",
xaxis_title="μ§νλ₯ (%)",
height=400,
showlegend=False
)
return fig
def create_executive_kpi_dashboard(
opt_result: Dict,
offers_df: pd.DataFrame,
purchase_history: pd.DataFrame
) -> go.Figure:
"""κ²½μμ§ KPI λμ보λ"""
fig = make_subplots(
rows=2, cols=3,
subplot_titles=(
'π° λΉμ© μ κ°',
'βοΈ μ»΄νλΌμ΄μΈμ€',
'π ESG μ μ',
'β±οΈ μ²λ¦¬ μκ°',
'π― λͺ©ν λ¬μ±λ₯ ',
'π μκ° νΈλ λ'
),
specs=[
[{"type": "indicator"}, {"type": "indicator"}, {"type": "indicator"}],
[{"type": "indicator"}, {"type": "indicator"}, {"type": "scatter"}]
]
)
# 1. λΉμ© μ κ°
if len(offers_df) > 0:
min_price = offers_df['unit_price'].min()
max_price = offers_df['unit_price'].max()
savings = ((max_price - min_price) / max_price * 100) if max_price > 0 else 0
else:
savings = 0
fig.add_trace(
go.Indicator(
mode="gauge+number+delta",
value=savings,
title={'text': "λΉμ© μ κ°λ₯ (%)"},
delta={'reference': 10},
gauge={
'axis': {'range': [0, 50]},
'bar': {'color': "darkblue"},
'steps': [
{'range': [0, 10], 'color': "lightgray"},
{'range': [10, 25], 'color': "lightgreen"},
{'range': [25, 50], 'color': "green"}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 15
}
}
),
row=1, col=1
)
# 2. μ»΄νλΌμ΄μΈμ€ μ€μμ¨
fig.add_trace(
go.Indicator(
mode="gauge+number",
value=100,
title={'text': "κ·μ μ€μμ¨ (%)"},
gauge={
'axis': {'range': [0, 100]},
'bar': {'color': "green"},
'steps': [
{'range': [0, 80], 'color': "lightcoral"},
{'range': [80, 95], 'color': "lightyellow"},
{'range': [95, 100], 'color': "lightgreen"}
]
}
),
row=1, col=2
)
# 3. ESG νκ· μ μ
if len(offers_df) > 0:
esg_score = offers_df['esg_level'].map({'A': 100, 'B': 70, 'C': 40}).mean()
else:
esg_score = 0
fig.add_trace(
go.Indicator(
mode="gauge+number",
value=esg_score,
title={'text': "ESG νκ· μ μ"},
gauge={
'axis': {'range': [0, 100]},
'bar': {'color': "darkgreen"},
'steps': [
{'range': [0, 50], 'color': "lightcoral"},
{'range': [50, 80], 'color': "lightyellow"},
{'range': [80, 100], 'color': "lightgreen"}
]
}
),
row=1, col=3
)
# 4. νκ· μ²λ¦¬ μκ°
fig.add_trace(
go.Indicator(
mode="number+delta",
value=20,
title={'text': "μ²λ¦¬ μκ° (λΆ)"},
delta={'reference': 30, 'increasing': {'color': "red"}, 'decreasing': {'color': "green"}},
number={'suffix': "λΆ"}
),
row=2, col=1
)
# 5. λͺ©ν λ¬μ±λ₯
fig.add_trace(
go.Indicator(
mode="gauge+number",
value=85,
title={'text': "μκ° λͺ©ν λ¬μ±λ₯ (%)"},
gauge={
'axis': {'range': [0, 100]},
'bar': {'color': "royalblue"},
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 80
}
}
),
row=2, col=2
)
# 6. μκ° νΈλ λ
months = ['1μ', '2μ', '3μ', '4μ', '5μ', '6μ']
values = [75, 78, 82, 85, 88, 90]
fig.add_trace(
go.Scatter(
x=months,
y=values,
mode='lines+markers',
name='λ°μ£Ό ν¨μ¨',
line=dict(color='royalblue', width=3),
marker=dict(size=10)
),
row=2, col=3
)
fig.update_layout(
height=700,
showlegend=False,
title_text="π κ²½μμ§ KPI λμ보λ",
title_font_size=22
)
return fig
def create_action_items_table(opt_result: Dict, offers_df: pd.DataFrame) -> pd.DataFrame:
"""κ²½μμ§ Action Items μμ±"""
action_items = []
# 1. μ¦μ λ°μ£Ό μΉμΈ νλͺ©
alloc = opt_result.get('allocation', {})
if alloc:
for supplier_id, details in alloc.items():
if isinstance(details, dict):
action_items.append({
"μ°μ μμ": "π΄ κΈ΄κΈ",
"Action Item": f"{details.get('supplier_name')} λ°μ£Ό μΉμΈ",
"μλ": f"{details.get('qty')}κ°",
"μμ λΉμ©": f"{details.get('qty', 0) * details.get('unit_price', 0):,}μ",
"λ΄λΉ": "ꡬ맀ν",
"κΈ°ν": "μ¦μ",
"μν": "μΉμΈ λκΈ°"
})
# 2. μ¬κ³ 보좩 κΆκ³
action_items.append({
"μ°μ μμ": "π‘ μ€μ",
"Action Item": "μμ μ¬κ³ λ―Έλ¬ νλͺ© 보좩",
"μλ": "3κ° νλͺ©",
"μμ λΉμ©": "κ²ν νμ",
"λ΄λΉ": "MROν",
"κΈ°ν": "1μ£ΌμΌ λ΄",
"μν": "κ²ν μ€"
})
# 3. ESG κ°μ
if len(offers_df) > 0:
c_grade_count = len(offers_df[offers_df['esg_level'] == 'C'])
if c_grade_count > 0:
action_items.append({
"μ°μ μμ": "π’ 보ν΅",
"Action Item": "ESG Cλ±κΈ 곡κΈμ
체 λ체 κ²ν ",
"μλ": f"{c_grade_count}κ°μ¬",
"μμ λΉμ©": "μν₯λ λΆμ νμ",
"λ΄λΉ": "ꡬ맀ν",
"κΈ°ν": "1κ°μ λ΄",
"μν": "κ³ν λ¨κ³"
})
# 4. μ₯κΈ° κ³μ½ νμ
action_items.append({
"μ°μ μμ": "π’ 보ν΅",
"Action Item": "μ£Όμ 곡κΈμ
체 μ₯κΈ°κ³μ½ νμ",
"μλ": "2-3κ°μ¬",
"μμ λΉμ©": "5-10% μ κ° μμ",
"λ΄λΉ": "ꡬ맀ν",
"κΈ°ν": "λΆκΈ° λ΄",
"μν": "κ³ν λ¨κ³"
})
return pd.DataFrame(action_items)
# =========================================================
# Core Components
# =========================================================
@dataclass
class ToolCallLog:
ts: str
actor: str
tool: str
input: Dict[str, Any]
output_preview: str
class MCPToolRegistry:
def __init__(self, tables: Dict[str, pd.DataFrame]):
self.tables = tables
self.logs: List[ToolCallLog] = []
def _log(self, actor: str, tool: str, inp: Dict[str, Any], out: Any):
self.logs.append(ToolCallLog(
ts=now_ts(),
actor=actor,
tool=tool,
input=inp,
output_preview=str(out)[:500]
))
def query_inventory(self, actor: str, item_id: str) -> pd.DataFrame:
inv = self.tables["inventory"]
stor = self.tables["storages"]
df = inv[inv["item_id"] == item_id].copy()
if len(df) > 0:
df = df.merge(stor, on="storage_id", how="left")
self._log(actor, "query_inventory", {"item_id": item_id}, f"{len(df)} rows")
return df
def query_offers(self, actor: str, item_id: str) -> pd.DataFrame:
offers = self.tables["supplier_offers"]
suppliers = self.tables["suppliers"]
df = offers[offers["item_id"] == item_id].copy()
if len(df) > 0:
df = df.merge(suppliers, on="supplier_id", how="left")
self._log(actor, "query_offers", {"item_id": item_id}, f"{len(df)} rows")
return df
def query_compat_items(self, actor: str, equipment_id: str) -> pd.DataFrame:
compat = self.tables["compat"]
items = self.tables["items"]
df = compat[compat["equipment_id"] == equipment_id].copy()
if len(df) > 0:
df = df.merge(items, on="item_id", how="left")
self._log(actor, "query_compat_items", {"equipment_id": equipment_id}, f"{len(df)} rows")
return df
def get_equipment_info(self, actor: str, equipment_id: str) -> Dict[str, Any]:
eq = self.tables["equipment"]
match = eq[eq["equipment_id"] == equipment_id]
if len(match) == 0:
return {}
info = match.iloc[0].to_dict()
self._log(actor, "get_equipment_info", {"equipment_id": equipment_id}, safe_json(info))
return info
def audit_log_df(self) -> pd.DataFrame:
if not self.logs:
return pd.DataFrame({"λ©μμ§": ["λ‘κ·Έ μμ"]})
return pd.DataFrame([{
"μκ°": l.ts[:19],
"μμ΄μ νΈ": l.actor,
"λꡬ": l.tool,
"μ
λ ₯": str(l.input)[:50],
} for l in self.logs])
def apply_rules(tables: Dict[str, pd.DataFrame], item_id: str,
supplier_row: Dict[str, Any]) -> Dict[str, Any]:
"""Apply rules"""
items = tables["items"]
item_match = items[items["item_id"] == item_id]
if len(item_match) == 0:
return {"block": False, "alerts": [], "explanations": [], "rules_fired": []}
item = item_match.iloc[0].to_dict()
decision = {
"block": False,
"alerts": [],
"explanations": [],
"rules_fired": []
}
if item.get("risk_class") == "κ·μ " and supplier_row.get("region") == "ν΄μΈ":
decision["block"] = True
decision["rules_fired"].append("R-001")
decision["explanations"].append(
f"π« R-001: κ·μ νλͺ©({item.get('item_name')}) ν΄μΈμ
체({supplier_row.get('supplier_name')}) ꡬ맀 μ°¨λ¨"
)
if supplier_row.get("esg_level") == "C":
decision["rules_fired"].append("R-004")
decision["explanations"].append(
f"π R-004: ESG Cλ±κΈ({supplier_row.get('supplier_name')}) ν¨λν°"
)
return decision
def optimize_order_allocation(demand_qty: int, offers_df: pd.DataFrame,
rules_eval: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
"""Optimize allocation"""
if not PULP_AVAILABLE:
return {
"status": "UNAVAILABLE",
"reason": "PuLP not installed",
"allocation": {},
"demand": demand_qty
}
feasible = []
blocked = []
for _, r in offers_df.iterrows():
sid = r["supplier_id"]
if rules_eval.get(sid, {}).get("block"):
blocked.append({
"supplier_id": sid,
"supplier_name": r.get("supplier_name", sid),
"reason": "κ·μΉ μλ°"
})
else:
feasible.append(r)
if len(feasible) == 0:
return {
"status": "INFEASIBLE",
"reason": "λͺ¨λ 곡κΈμ
체 μ°¨λ¨",
"allocation": {},
"blocked_suppliers": blocked,
"demand": demand_qty
}
fdf = pd.DataFrame(feasible)
prob = LpProblem("MRO_Allocation", LpMinimize)
x = {}
for _, r in fdf.iterrows():
sid = r["supplier_id"]
x[sid] = LpVariable(f"x_{sid}", lowBound=0, cat="Integer")
prob += lpSum(list(x.values())) >= demand_qty, "DemandConstraint"
obj_terms = []
for _, r in fdf.iterrows():
sid = r["supplier_id"]
price = float(r["unit_price"])
obj_terms.append(x[sid] * price)
prob += lpSum(obj_terms), "TotalCost"
prob.solve()
alloc = {}
total_cost = 0.0
for _, r in fdf.iterrows():
sid = r["supplier_id"]
val = x[sid].value()
if val is not None and val > 0:
qty = int(val)
alloc[sid] = {
"qty": qty,
"unit_price": float(r["unit_price"]),
"supplier_name": r.get("supplier_name", sid),
"lead_time": int(r.get("lead_time_days", 0))
}
total_cost += qty * float(r["unit_price"])
return {
"status": LpStatus.get(prob.status, "Unknown"),
"allocation": alloc,
"demand": demand_qty,
"blocked_suppliers": blocked,
"total_cost": round(total_cost, 2)
}
class LLMOrchestrator:
def __init__(self):
self.api_key = os.environ.get("OPENAI_API_KEY", "").strip()
self.demo_mode = (not self.api_key or not OPENAI_AVAILABLE)
if not self.demo_mode:
try:
self.client = OpenAI(api_key=self.api_key)
test_resp = self.client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "test"}],
max_tokens=5
)
print("β
OpenAI API μ°κ²° μ±κ³΅!")
except Exception:
self.demo_mode = True
self.client = None
else:
self.client = None
def chat(self, role: str, system: str, user: str) -> str:
if self.demo_mode:
return self._demo_response(role)
try:
resp = self.client.chat.completions.create(
model="gpt-4o-mini",
temperature=0.2,
messages=[
{"role": "system", "content": system},
{"role": "user", "content": user}
]
)
return resp.choices[0].message.content
except Exception as e:
return f"[ERROR: {e}]\n" + self._demo_response(role)
def _demo_response(self, role: str) -> str:
return f"[DEMO MODE - {role}] AI λΆμ μλ£"
# =========================================================
# LangGraph Workflow
# =========================================================
class DemoState(TypedDict, total=False):
tables: Dict[str, pd.DataFrame]
mcp: MCPToolRegistry
llm: LLMOrchestrator
scenario: str
equipment_id: str
item_id: str
demand_qty: int
priority: str
tables_ok: bool
validation_issues: List[str]
progress: str
inventory_view: pd.DataFrame
offers_view: pd.DataFrame
rules_eval: Dict[str, Any]
optimization: Dict[str, Any]
narrative: Dict[str, str]
audit_log: pd.DataFrame
selected_item_name: str
equipment_info: Dict[str, Any]
compat_items: pd.DataFrame
def node_validate(state: DemoState) -> DemoState:
ok, issues = validate_tables(state["tables"])
state["tables_ok"] = ok
state["validation_issues"] = issues
state["progress"] = "1/4 κ²μ¦ μλ£"
return state
def node_mro_agent(state: DemoState) -> DemoState:
mcp: MCPToolRegistry = state["mcp"]
equipment_id = state.get("equipment_id", "")
item_id = state.get("item_id", "")
# Get equipment info
equipment_info = mcp.get_equipment_info("MRO_AGENT", equipment_id)
state["equipment_info"] = equipment_info
# Get compatible items
compat_df = pd.DataFrame()
if equipment_id:
compat_df = mcp.query_compat_items("MRO_AGENT", equipment_id)
state["compat_items"] = compat_df
if not item_id and len(compat_df) > 0:
mandatory = compat_df[compat_df["is_mandatory"] == True]
if len(mandatory) > 0:
selected = mandatory.iloc[0]
else:
selected = compat_df.iloc[0]
item_id = selected["item_id"]
state["item_id"] = item_id
state["selected_item_name"] = selected.get("item_name", item_id)
inv_df = pd.DataFrame()
if item_id:
inv_df = mcp.query_inventory("MRO_AGENT", item_id)
state["inventory_view"] = inv_df
llm: LLMOrchestrator = state["llm"]
if "narrative" not in state:
state["narrative"] = {}
state["narrative"]["mro"] = llm.chat("MRO", "MRO λΆμ", "μ€λΉ/μ¬κ³ ")
state["progress"] = "2/4 MRO μλ£"
return state
def node_procurement_agent(state: DemoState) -> DemoState:
mcp: MCPToolRegistry = state["mcp"]
item_id = state.get("item_id", "")
demand_qty = int(state.get("demand_qty", 10))
offers_df = pd.DataFrame()
if item_id:
offers_df = mcp.query_offers("PROC_AGENT", item_id)
state["offers_view"] = offers_df
rules_eval = {}
if len(offers_df) > 0:
for _, r in offers_df.iterrows():
sid = r["supplier_id"]
supplier_row = {
"supplier_id": sid,
"supplier_name": r.get("supplier_name", sid),
"region": r.get("region", ""),
"esg_level": r.get("esg_level", ""),
}
rules_eval[sid] = apply_rules(state["tables"], item_id, supplier_row)
state["rules_eval"] = rules_eval
opt_result = {}
if len(offers_df) > 0:
opt_result = optimize_order_allocation(demand_qty, offers_df, rules_eval)
else:
opt_result = {
"status": "NO_DATA",
"reason": "곡κΈμ
체 μ 보 μμ",
"allocation": {},
"demand": demand_qty
}
state["optimization"] = opt_result
llm: LLMOrchestrator = state["llm"]
state["narrative"]["proc"] = llm.chat("PROC", "ꡬ맀 μ λ΅", "μ΅μ ν")
state["narrative"]["exec"] = llm.chat("EXEC", "μμ μμ½", "μ’
ν©")
state["progress"] = "3/4 ꡬ맀 μλ£"
return state
def node_collect_audit(state: DemoState) -> DemoState:
mcp: MCPToolRegistry = state["mcp"]
state["audit_log"] = mcp.audit_log_df()
state["progress"] = "4/4 μλ£ β"
return state
def build_workflow():
if not LANGGRAPH_AVAILABLE:
return None
try:
graph = StateGraph(DemoState)
graph.add_node("validate", node_validate)
graph.add_node("mro_agent", node_mro_agent)
graph.add_node("procurement_agent", node_procurement_agent)
graph.add_node("collect_audit", node_collect_audit)
graph.set_entry_point("validate")
graph.add_edge("validate", "mro_agent")
graph.add_edge("mro_agent", "procurement_agent")
graph.add_edge("procurement_agent", "collect_audit")
graph.add_edge("collect_audit", END)
return graph.compile()
except Exception as e:
print(f"β οΈ LangGraph failed: {e}")
return None
APP = build_workflow()
# =========================================================
# Main Execution - Enhanced with Dashboards
# =========================================================
def run_demo(scenario: str, seed: int, equipment_id: str, item_id: str,
demand_qty: int) -> Tuple:
"""Main execution - returns 12 outputs (enhanced)"""
try:
seed_int = int(seed)
demand_int = int(demand_qty)
tables = generate_demo_tables(seed=seed_int)
mcp = MCPToolRegistry(tables)
llm = LLMOrchestrator()
preset = SCENARIO_PRESETS.get(scenario, SCENARIO_PRESETS["κΈ΄κΈ κ³ μ₯ λμ"])
state: DemoState = {
"tables": tables,
"mcp": mcp,
"llm": llm,
"scenario": scenario,
"equipment_id": equipment_id.strip(),
"item_id": item_id.strip(),
"demand_qty": demand_int,
"priority": preset.get("priority", "μ μ"),
}
if APP is not None:
out = APP.invoke(state)
else:
out = node_validate(state)
out = node_mro_agent(out)
out = node_procurement_agent(out)
out = node_collect_audit(out)
status = {
"mode": "β οΈ DEMO" if llm.demo_mode else "β
LLM",
"scenario": scenario,
"tables_ok": out.get("tables_ok", False),
"equipment": out.get("equipment_id", ""),
"item_name": out.get("selected_item_name", ""),
"demand": out.get("demand_qty", 0),
"priority": out.get("priority", "μ μ"),
"progress": out.get("progress", "μλ£"),
}
status_text = format_status(status)
# Data extraction
inv_df = out.get("inventory_view", pd.DataFrame())
offers_df = out.get("offers_view", pd.DataFrame())
audit_df = out.get("audit_log", pd.DataFrame())
equipment_info = out.get("equipment_info", {})
compat_items = out.get("compat_items", pd.DataFrame())
rules_eval = out.get("rules_eval", {})
opt_result = out.get("optimization", {})
purchase_history = tables.get("purchase_history", pd.DataFrame())
item_name = out.get("selected_item_name", "λΆν")
# Create dashboards
mro_dashboard = create_mro_inventory_dashboard(inv_df, item_name)
mro_workflow = create_mro_workflow_status(equipment_info, compat_items)
proc_dashboard = create_procurement_comparison_dashboard(offers_df, rules_eval)
proc_workflow = create_procurement_workflow(opt_result)
exec_dashboard = create_executive_kpi_dashboard(opt_result, offers_df, purchase_history)
action_items = create_action_items_table(opt_result, offers_df)
# Fallback for empty dataframes
if len(audit_df) == 0:
audit_df = pd.DataFrame({"λ©μμ§": ["κ°μ¬λ‘κ·Έ μμ"]})
print("β
λμ보λ μμ± μλ£\n")
# Return 12 outputs
return (
status_text, # 1
mro_dashboard, # 2 - MRO μ¬κ³ λμ보λ
mro_workflow, # 3 - MRO μν¬νλ‘μ°
proc_dashboard, # 4 - ꡬ맀 λΉκ΅ λμ보λ
proc_workflow, # 5 - ꡬ맀 μν¬νλ‘μ°
exec_dashboard, # 6 - κ²½μμ§ KPI
action_items, # 7 - Action Items
offers_df, # 8 - 곡κΈμ
체 μλ³Έ λ°μ΄ν°
inv_df, # 9 - μ¬κ³ μλ³Έ λ°μ΄ν°
opt_result, # 10 - μ΅μ ν κ²°κ³Ό (dictλ₯Ό textλ‘)
audit_df, # 11 - κ°μ¬ λ‘κ·Έ
out.get("selected_item_name", "N/A") # 12 - νλͺ©λͺ
)
except Exception as e:
print(f"β μ€λ₯: {e}\n{traceback.format_exc()}")
error_msg = f"β μ€λ₯\n\n{str(e)}"
empty_fig = go.Figure()
empty_fig.add_annotation(text="μ€λ₯ λ°μ", showarrow=False)
empty_df = pd.DataFrame({"μ€λ₯": [str(e)[:100]]})
return (
error_msg, empty_fig, empty_fig, empty_fig, empty_fig,
empty_fig, empty_df, empty_df, empty_df, {}, empty_df, "N/A"
)
def update_scenario(scenario: str) -> Tuple[str, str, int, str]:
preset = SCENARIO_PRESETS.get(scenario, SCENARIO_PRESETS["κΈ΄κΈ κ³ μ₯ λμ"])
guide_text = f"""**π {preset['description']}**
**λ°°κ²½**: {preset['context']}
**μ°μ μμ**: {preset.get('priority', 'μ μ')}
**κ°μ΄λ**: {preset.get('guide', '')}
"""
return (
preset["equipment_id"],
preset["item_id"],
preset["demand_qty"],
guide_text
)
# =========================================================
# Enhanced Gradio UI with Process Guides
# =========================================================
print("π¨ νλ‘μΈμ€ κ°μ΄λ ν΅ν© UI κ΅¬μ± μ€...\n")
with gr.Blocks(title="POSCO DX MRO Composite AI", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# π POSCO DX - MRO Composite AI νλ‘μΈμ€ κ°μ΄λ ν΅ν© λ²μ
## π― μ
무 νλ‘μΈμ€ μλν + AI μμ¬κ²°μ μ§μ μμ€ν
**3-Agent Collaboration**: MRO μ΄μ β ꡬ맀/μ‘°λ¬ β κ²½μμ§ μΉμΈ
""")
# Process Overview Section
with gr.Accordion("π μ 체 μ
무 νλ‘μΈμ€ κ°μ", open=False):
gr.Markdown("""
### π End-to-End μν¬νλ‘μ°
```
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β 1οΈβ£ MRO μ΄μ β βββ> β 2οΈβ£ ꡬ맀/μ‘°λ¬ β βββ> β 3οΈβ£ κ²½μμ§ μΉμΈ β
β β β β β β
β β’ κ³ μ₯ μ μ β β ⒠곡κΈμ
체 μ‘°ν β β β’ KPI νμΈ β
β β’ λΆν νμΈ β β β’ κ·μ κ²μ¦ β β β’ μμ¬κ²°μ β
β β’ μ¬κ³ νμΈ β β β’ μ΅μ ν λΆμ β β β’ νΌλλ°± β
β β’ λ°μ£Ό μμ² β β β’ μΉμΈ μμ² β β β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β±οΈ 15λΆ β±οΈ 25λΆ β±οΈ 25λΆ
```
### π‘ ν΅μ¬ κ°μΉ
1. **μλν**: μ€λΉ-λΆν λ§€μΉ, μ¬κ³ μ‘°ν, κ·μ κ²μ¦ λ± λ°λ³΅ μ
무 μλν
2. **μ΅μ ν**: AI κΈ°λ° λΉμ© μ΅μ ν λ° κ³΅κΈμ
체 μ μ
3. **κ²μ¦**: Neuro-Symbolic AIλ‘ 100% κ·μ μ€μ 보μ₯
4. **κ°μμ±**: μ€μκ° λμ보λλ‘ μ κ³Όμ λͺ¨λν°λ§
5. **μΆμ μ±**: λͺ¨λ μμ¬κ²°μ κ³Όμ μλ κΈ°λ‘
### π κΈ°λ ν¨κ³Ό
- β±οΈ **μ²λ¦¬ μκ°**: κΈ°μ‘΄ 3-5μΌ β **1μκ° μ΄λ΄**
- π° **λΉμ© μ κ°**: νκ· **15-25%** ꡬ맀 λΉμ© μ κ°
- βοΈ **μ»΄νλΌμ΄μΈμ€**: **100%** κ·μ μ€μ
- π **ν¨μ¨μ±**: λ΄λΉμ μ
무 μκ° **60%** λ¨μΆ
""")
with gr.Row():
with gr.Column():
gr.Markdown("### π― μλ리μ€")
scenario_radio = gr.Radio(
choices=list(SCENARIO_PRESETS.keys()),
value="κΈ΄κΈ κ³ μ₯ λμ",
label="λΆμ μλ리μ€"
)
scenario_info = gr.Markdown(
value=f"""**π {SCENARIO_PRESETS['κΈ΄κΈ κ³ μ₯ λμ']['description']}**
**λ°°κ²½**: {SCENARIO_PRESETS['κΈ΄κΈ κ³ μ₯ λμ']['context']}
**κ°μ΄λ**: {SCENARIO_PRESETS['κΈ΄κΈ κ³ μ₯ λμ']['guide']}
"""
)
with gr.Column():
gr.Markdown("### βοΈ νλΌλ―Έν°")
seed_number = gr.Number(value=7, label="λ°μ΄ν° μλ", precision=0)
equipment_text = gr.Textbox(value="CONV-PH-007", label="μ€λΉ ID")
item_text = gr.Textbox(value="", label="νλͺ© ID (μ ν)")
demand_number = gr.Number(value=10, label="μλ", precision=0)
run_button = gr.Button("π Composite AI λΆμ μ€ν", variant="primary", size="lg")
gr.Markdown("---")
status_output = gr.Textbox(label="π μ€ν μν", lines=10)
selected_item_display = gr.Textbox(label="π¦ μ νλ νλͺ©", interactive=False)
with gr.Tabs():
with gr.Tab("π§ MRO λ΄λΉμ"):
# Process Guide for MRO
with gr.Accordion("π MRO μ΄μ νλ‘μΈμ€ κ°μ΄λ", open=True):
mro_process_html = gr.HTML(create_process_guide_html("mro"))
gr.Markdown("---")
gr.Markdown("### π λμ보λ λ° λΆμ κ²°κ³Ό")
mro_inventory_plot = gr.Plot(label="π¦ μ¬κ³ λΆμ λμ보λ")
mro_workflow_plot = gr.Plot(label="π MRO μν¬νλ‘μ° μ§ν")
mro_inventory_table = gr.Dataframe(label="π μμΈ μ¬κ³ λ°μ΄ν°")
with gr.Tab("π° ꡬ맀 λ΄λΉμ"):
# Process Guide for Procurement
with gr.Accordion("π ꡬ맀/μ‘°λ¬ νλ‘μΈμ€ κ°μ΄λ", open=True):
proc_process_html = gr.HTML(create_process_guide_html("procurement"))
gr.Markdown("---")
gr.Markdown("### π λμ보λ λ° λΆμ κ²°κ³Ό")
proc_comparison_plot = gr.Plot(label="π 곡κΈμ
체 λΉκ΅ λμ보λ")
proc_workflow_plot = gr.Plot(label="π ꡬ맀 μν¬νλ‘μ°")
proc_offers_table = gr.Dataframe(label="π 곡κΈμ
체 μμΈ μ 보")
with gr.Tab("π κ²½μμ§"):
# Process Guide for Executive
with gr.Accordion("π κ²½μμ§ μμ¬κ²°μ νλ‘μΈμ€ κ°μ΄λ", open=True):
exec_process_html = gr.HTML(create_process_guide_html("executive"))
gr.Markdown("---")
gr.Markdown("### π λμ보λ λ° λΆμ κ²°κ³Ό")
exec_kpi_plot = gr.Plot(label="π κ²½μμ§ KPI λμ보λ")
exec_action_table = gr.Dataframe(label="π Action Items")
gr.Markdown("### π¬ κ²½μμ§ νΌλλ°±")
with gr.Row():
feedback_text = gr.Textbox(
label="κ°μ μ μ / νΌλλ°±",
placeholder="μ: ESG Cλ±κΈ μ
체 λΉμ€μ 20% μ΄νλ‘ μ ννμκΈ° λ°λλλ€.",
lines=3
)
with gr.Row():
approve_btn = gr.Button("β
μΉμΈ", variant="primary")
reject_btn = gr.Button("β λ°λ €", variant="stop")
suggest_btn = gr.Button("π‘ κ°μ μ μ", variant="secondary")
feedback_output = gr.Textbox(label="νΌλλ°± μ²λ¦¬ κ²°κ³Ό", lines=2)
with gr.Tab("π κ°μ¬ λ‘κ·Έ"):
gr.Markdown("""
### κ°μ¬ μΆμ (Audit Trail)
**λͺ©μ **: λͺ¨λ μμ¬κ²°μ κ³Όμ μΆμ λ° μ»΄νλΌμ΄μΈμ€ ν보
**κΈ°λ‘ νλͺ©**:
- π μκ°: μμ
μν μκ°
- π€ μμ΄μ νΈ: MRO/ꡬ맀/κ²½μμ§
- π§ λꡬ: μ¬μ©ν κΈ°λ₯
- π₯ μ
λ ₯: νλΌλ―Έν°
- π€ μΆλ ₯: κ²°κ³Ό μμ½
**νμ©**:
- κ·μ μ€μ κ°μ¬
- νλ‘μΈμ€ κ°μ
- μ±
μ μΆμ μ±
""")
audit_table = gr.Dataframe(label="π μ 체 κ°μ¬ λ‘κ·Έ")
# Hidden outputs for optimization result
opt_result_json = gr.JSON(label="μ΅μ ν μμΈ κ²°κ³Ό", visible=False)
gr.Markdown("""
---
## π‘ μμ€ν
μ¬μ© κ°μ΄λ
### π λ¨κ³λ³ μ¬μ©λ²
#### 1οΈβ£ μλλ¦¬μ€ μ ν
- **κΈ΄κΈ κ³ μ₯ λμ**: μ€λΉ κ³ μ₯μΌλ‘ μ¦μ κ΅μ²΄κ° νμν κ²½μ°
- **μ κΈ° λ°μ£Ό κ³ν**: μκ°/λΆκΈ° μ κΈ° λ°μ£Ό μ΅μ ν
- **κ·μ μ€μ κ²μ¦**: νΉμ νλͺ© ꡬ맀 μ μ»΄νλΌμ΄μΈμ€ νμΈ
#### 2οΈβ£ νλΌλ―Έν° μ
λ ₯
- **μ€λΉ ID**: κ³ μ₯/μ λΉ λμ μ€λΉ (μλ μ
λ ₯)
- **νλͺ© ID**: νΉμ νλͺ© μ§μ (μ νμ¬ν, λΉμ°λ©΄ μλ μ ν)
- **μλ**: λ°μ£Ό νμ μλ
#### 3οΈβ£ λΆμ μ€ν
- "π Composite AI λΆμ μ€ν" λ²νΌ ν΄λ¦
- μ½ 5-10μ΄ λ΄ κ²°κ³Ό νμΈ
#### 4οΈβ£ κ²°κ³Ό κ²ν
- **MRO ν**: μ¬κ³ νν© λ° λ°μ£Ό νμμ± νμΈ
- **ꡬ맀 ν**: 곡κΈμ
체 λΉκ΅ λ° μ΅μ μ ν
- **κ²½μμ§ ν**: KPI νμΈ λ° μμ¬κ²°μ
#### 5οΈβ£ μΉμΈ/νΌλλ°±
- Action Items κ²ν ν μΉμΈ/λ°λ € κ²°μ
- κ°μ μ μ μ
λ ₯ μ μλμΌλ‘ λ΄λΉ λΆμμ μ λ¬
### π νλ‘μΈμ€ μ΄ν΄
κ° νμ "π νλ‘μΈμ€ κ°μ΄λ"λ₯Ό νΌμΉλ©΄:
- λ¨κ³λ³ μμΈ μ μ°¨
- μ
λ ₯/μΆλ ₯ λͺ
μΈ
- λ΄λΉμ λ° μμ μκ°
- μ±κ³΅ κΈ°μ€
μ νμΈν μ μμ΅λλ€.
### π μ£Όμ κΈ°λ₯
1. **μλ λΆν λ§€μΉ**: μ€λΉ IDλ§μΌλ‘ νΈν λΆν μλ κ²μ
2. **μ μ¬ μ¬κ³ ν΅ν©**: λ³Έμ¬, ν¬ν, κ΄μ μ 체 μ°½κ³ μ€μκ° μ‘°ν
3. **AI κ·μ κ²μ¦**: κ·μ νλͺ©, ESG λ±κΈ λ± μλ κ²μ¦
4. **μ΅μ ν μμ§**: Linear ProgrammingμΌλ‘ λΉμ© μ΅μν
5. **μΈν°λν°λΈ λμ보λ**: Plotly μ°¨νΈλ‘ λ릴λ€μ΄ λΆμ κ°λ₯
### π API Key μ€μ (Hugging Face Spaces)
OpenAI κΈ°λ₯μ μ¬μ©νλ €λ©΄:
1. Space Settings β SecretsμΌλ‘ μ΄λ
2. μ Secret μΆκ°:
- Name: `OPENAI_API_KEY`
- Value: `your-openai-api-key`
3. Space μ¬μμ
API ν€ μμ΄λ λ°λͺ¨ λͺ¨λλ‘ κΈ°λ³Έ κΈ°λ₯ μ¬μ© κ°λ₯ν©λλ€.
""")
# Event Handlers
scenario_radio.change(
fn=update_scenario,
inputs=[scenario_radio],
outputs=[equipment_text, item_text, demand_number, scenario_info]
)
run_button.click(
fn=run_demo,
inputs=[scenario_radio, seed_number, equipment_text, item_text, demand_number],
outputs=[
status_output, # 1
mro_inventory_plot, # 2
mro_workflow_plot, # 3
proc_comparison_plot, # 4
proc_workflow_plot, # 5
exec_kpi_plot, # 6
exec_action_table, # 7
proc_offers_table, # 8
mro_inventory_table, # 9
opt_result_json, # 10
audit_table, # 11
selected_item_display # 12
]
)
# Feedback handlers
def handle_approve(feedback):
return f"β
μΉμΈ μλ£: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\nνΌλλ°±: {feedback}"
def handle_reject(feedback):
return f"β λ°λ €λ¨: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\nμ¬μ : {feedback}"
def handle_suggest(feedback):
return f"π‘ κ°μ μ μ μ μ: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\nλ΄μ©: {feedback}"
approve_btn.click(fn=handle_approve, inputs=[feedback_text], outputs=[feedback_output])
reject_btn.click(fn=handle_reject, inputs=[feedback_text], outputs=[feedback_output])
suggest_btn.click(fn=handle_suggest, inputs=[feedback_text], outputs=[feedback_output])
print("=" * 60)
print("β
νλ‘μΈμ€ κ°μ΄λ ν΅ν© UI μλ£!")
print("=" * 60)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True
)
print("\nπ νλ‘μΈμ€ κ°μ΄λ ν΅ν© λ²μ μ€ν μ€!\n")
|