Spaces:
Sleeping
Sleeping
File size: 76,686 Bytes
2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 a417a57 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e a417a57 170c4b9 ce5f14e 170c4b9 ce5f14e a417a57 32a3c77 d3b9b16 a417a57 ce5f14e a417a57 ce5f14e a417a57 ce5f14e a417a57 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e d3b9b16 2a631c5 ce5f14e 2a631c5 d3b9b16 2a631c5 a417a57 2a631c5 a417a57 2a631c5 a417a57 2a631c5 a417a57 2a631c5 a417a57 2a631c5 d3b9b16 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e a417a57 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e a417a57 ce5f14e 2a631c5 ce5f14e 2a631c5 ce5f14e 2a631c5 d3b9b16 2a631c5 ce5f14e 2a631c5 a417a57 ce5f14e a417a57 ce5f14e 2a631c5 a417a57 ce5f14e a417a57 2a631c5 a417a57 2a631c5 d3b9b16 ce5f14e 170c4b9 ce5f14e 170c4b9 ce5f14e 170c4b9 ce5f14e 170c4b9 ce5f14e 170c4b9 ce5f14e 170c4b9 ce5f14e 170c4b9 ce5f14e 170c4b9 ce5f14e 170c4b9 ce5f14e 170c4b9 ce5f14e 170c4b9 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e d3b9b16 ce5f14e |
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 |
"""
FastAPI Service for Construction Scope Validation - FIXED VERSION
Includes semantic validation to prevent wrong tasks being assigned to stages
"""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any, Tuple
import json
import numpy as np
import os
import torch
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import re
torch.backends.cudnn.benchmark = True
torch.backends.cuda.matmul.allow_tf32 = True
torch.set_float32_matmul_precision('high')
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:512'
app = FastAPI(
title="Construction Scope Validator API - Fixed",
description="Validates with semantic task-stage checking",
version="2.1.0"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ============= MODEL LOADING =============
print("="*60)
print("LOADING MODEL...")
print("="*60)
def setup_model_structure():
if not os.path.exists('1_Pooling') or not os.path.exists('2_Normalize'):
print("Creating temporary model structure...")
os.makedirs('1_Pooling', exist_ok=True)
os.makedirs('2_Normalize', exist_ok=True)
pooling_config = {
"word_embedding_dimension": 384,
"pooling_mode_cls_token": False,
"pooling_mode_mean_tokens": True,
"pooling_mode_max_tokens": False,
"pooling_mode_mean_sqrt_len_tokens": False
}
with open('1_Pooling/config.json', 'w') as f:
json.dump(pooling_config, f, indent=2)
with open('2_Normalize/config.json', 'w') as f:
json.dump({}, f)
print("β Created model structure")
setup_model_structure()
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"GPU device: {torch.cuda.get_device_name(0)}")
try:
model_files = ['config.json', 'sentence_bert_config.json']
has_weights = os.path.exists('pytorch_model.bin') or os.path.exists('model.safetensors')
has_model = all(os.path.exists(f) for f in model_files) and has_weights
if has_model:
print("β Loading trained model...")
embedding_model = SentenceTransformer('./', device='cuda')
print("β
Trained model loaded!")
else:
print("β οΈ Loading base model...")
embedding_model = SentenceTransformer('all-MiniLM-L6-v2', device='cuda')
print("β
Base model loaded!")
except Exception as e:
print(f"β Error: {e}")
embedding_model = SentenceTransformer('all-MiniLM-L6-v2', device='cuda')
BATCH_SIZE = 4096
print(f"β Batch Size: {BATCH_SIZE}")
print("="*60)
# ============= DATA MODELS =============
class ScopeItem(BaseModel):
stage: str
task: str
material: str
quantity: float
unit: str
# Enrichment fields
stageId: Optional[int] = None
taskId: Optional[int] = None
materialId: Optional[int] = None
stage_confidence: Optional[float] = None
task_confidence: Optional[float] = None
material_confidence: Optional[float] = None
validated_stage: Optional[str] = None
validated_task: Optional[str] = None
validated_material: Optional[str] = None
material_price: Optional[float] = None
material_margin: Optional[float] = None
# NEW: Validation flags
task_semantic_valid: Optional[bool] = None
task_database_stageId: Optional[int] = None
class AreaScope(BaseModel):
area: str
items: List[ScopeItem]
roomId: Optional[int] = None
roomType: Optional[str] = None
area_confidence: Optional[float] = None
validated_area: Optional[str] = None
class ScopeRequest(BaseModel):
scope_of_work: List[AreaScope]
class ScopeResponse(BaseModel):
scope_of_work: List[AreaScope]
metadata: Optional[Dict[str, Any]] = None
# ============= HELPER FUNCTIONS =============
def parse_room_area(room_area_value):
if room_area_value is None:
return []
if isinstance(room_area_value, list):
return room_area_value
if isinstance(room_area_value, str):
try:
parsed = json.loads(room_area_value)
if isinstance(parsed, list):
return parsed
return [str(parsed)]
except json.JSONDecodeError:
return [room_area_value]
return [str(room_area_value)]
# ============= DATABASE LOADER =============
class DatabaseLoader:
def __init__(self):
self.stages = []
self.tasks = []
self.materials = []
self.rooms = []
self.stage_embeddings = None
self.task_embeddings = None
self.material_embeddings = None
def load_data(self, stages_file: str, tasks_file: str, materials_file: str, rooms_file: str):
print(f"Loading {stages_file}...")
with open(stages_file, 'r', encoding='utf-8') as f:
self.stages = [json.loads(line) for line in f if line.strip()]
print(f"Loading {tasks_file}...")
with open(tasks_file, 'r', encoding='utf-8') as f:
self.tasks = [json.loads(line) for line in f if line.strip()]
print(f"Loading {materials_file}...")
with open(materials_file, 'r', encoding='utf-8') as f:
self.materials = [json.loads(line) for line in f if line.strip()]
print(f"Loading {rooms_file}...")
with open(rooms_file, 'r', encoding='utf-8') as f:
self.rooms = [json.loads(line) for line in f if line.strip()]
print(f"β
Loaded: {len(self.stages)} stages, {len(self.tasks)} tasks, "
f"{len(self.materials)} materials, {len(self.rooms)} rooms")
def initialize_embeddings(self):
print("\n" + "="*60)
print("INITIALIZING EMBEDDINGS")
print("="*60)
print(f"Computing stage embeddings...")
stage_texts = [s['stage'] for s in self.stages]
self.stage_embeddings = embedding_model.encode(
stage_texts,
batch_size=BATCH_SIZE,
show_progress_bar=True,
convert_to_numpy=True,
normalize_embeddings=True
)
print(f"Computing task embeddings...")
task_texts = [t['task'] for t in self.tasks]
self.task_embeddings = embedding_model.encode(
task_texts,
batch_size=BATCH_SIZE,
show_progress_bar=True,
convert_to_numpy=True,
normalize_embeddings=True
)
print(f"Computing material embeddings...")
material_texts = [m['material'] for m in self.materials]
self.material_embeddings = embedding_model.encode(
material_texts,
batch_size=BATCH_SIZE,
show_progress_bar=True,
convert_to_numpy=True,
normalize_embeddings=True
)
print("="*60)
print("β
Embeddings ready!")
print("="*60)
db = DatabaseLoader()
# ============= SEMANTIC VALIDATOR =============
class SemanticValidator:
"""Validates if tasks semantically belong to stages"""
def __init__(self):
pass
def validate_task_for_stage(self, task: dict, stage: dict,
task_confidence: float) -> Tuple[bool, float]:
"""Check if task semantically belongs to stage"""
# Get embeddings
stage_idx = next((i for i, s in enumerate(db.stages)
if s['stageId'] == stage['stageId']), None)
task_idx = next((i for i, t in enumerate(db.tasks)
if t['taskId'] == task['taskId']), None)
if stage_idx is None or task_idx is None:
return False, 0.0
stage_emb = db.stage_embeddings[stage_idx].reshape(1, -1)
task_emb = db.task_embeddings[task_idx].reshape(1, -1)
semantic_similarity = cosine_similarity(stage_emb, task_emb)[0][0]
# Threshold for semantic belonging
SEMANTIC_THRESHOLD = 0.25 # Lowered for more lenient matching
if semantic_similarity < SEMANTIC_THRESHOLD:
return False, 0.0
# Adjust confidence
adjusted_confidence = task_confidence * min(semantic_similarity / 0.4, 1.0)
return True, adjusted_confidence
validator = SemanticValidator()
# ============= MATCHING FUNCTIONS =============
def find_best_stage(llm_stage: str, threshold: float = 0.5) -> tuple:
query_embedding = embedding_model.encode(
[llm_stage],
batch_size=BATCH_SIZE,
convert_to_numpy=True,
normalize_embeddings=True
)
similarities = cosine_similarity(query_embedding, db.stage_embeddings)[0]
best_idx = np.argmax(similarities)
best_score = similarities[best_idx]
if best_score >= threshold:
return db.stages[best_idx], best_score
return None, 0.0
def find_best_room(llm_area: str, threshold: float = 0.6) -> tuple:
llm_area_lower = llm_area.lower()
for room in db.rooms:
if room['name'].lower() == llm_area_lower:
return room, 1.0
room_texts = [r['name'] for r in db.rooms]
query_embedding = embedding_model.encode(
[llm_area],
batch_size=BATCH_SIZE,
convert_to_numpy=True,
normalize_embeddings=True
)
room_embeddings = embedding_model.encode(
room_texts,
batch_size=BATCH_SIZE,
convert_to_numpy=True,
normalize_embeddings=True
)
similarities = cosine_similarity(query_embedding, room_embeddings)[0]
best_idx = np.argmax(similarities)
best_score = similarities[best_idx]
if best_score >= threshold:
return db.rooms[best_idx], best_score
return None, 0.0
def find_best_task_with_semantic_validation(
stage_id: int,
llm_task: str,
stage: dict,
fallback_to_global: bool = True
) -> Tuple[Optional[dict], float, bool, Optional[int]]:
"""
Enhanced task matching with semantic validation
Returns: (task, confidence, is_semantically_valid, original_db_stageId)
"""
# Try stage-specific tasks first
stage_tasks = [t for t in db.tasks if t['stageId'] == stage_id]
if stage_tasks:
task_indices = [db.tasks.index(t) for t in stage_tasks]
query_embedding = embedding_model.encode(
[llm_task],
batch_size=1,
convert_to_numpy=True,
normalize_embeddings=True
)
stage_task_embeddings = db.task_embeddings[task_indices]
similarities = cosine_similarity(query_embedding, stage_task_embeddings)[0]
# Get top 3 candidates
top_indices = np.argsort(similarities)[-3:][::-1]
for idx in top_indices:
candidate_task = stage_tasks[idx]
candidate_confidence = similarities[idx]
# Validate semantically
is_valid, adjusted_confidence = validator.validate_task_for_stage(
candidate_task, stage, candidate_confidence
)
if is_valid and adjusted_confidence > 0.35:
return (candidate_task, adjusted_confidence, True,
candidate_task['stageId'])
# Fallback: Search ALL tasks
if fallback_to_global:
query_embedding = embedding_model.encode(
[llm_task],
batch_size=1,
convert_to_numpy=True,
normalize_embeddings=True
)
all_similarities = cosine_similarity(query_embedding, db.task_embeddings)[0]
top_global_indices = np.argsort(all_similarities)[-5:][::-1]
for idx in top_global_indices:
candidate_task = db.tasks[idx]
candidate_confidence = all_similarities[idx]
# Validate with our matched stage
is_valid, adjusted_confidence = validator.validate_task_for_stage(
candidate_task, stage, candidate_confidence
)
if is_valid and adjusted_confidence > 0.3:
return (candidate_task, adjusted_confidence, True,
candidate_task['stageId'])
return None, 0.0, False, None
def extract_keywords(text: str) -> List[str]:
stop_words = {'and', 'or', 'the', 'to', 'a', 'of', 'for', 'in', 'on', 'supply', 'install'}
words = re.findall(r'\b\w+\b', text.lower())
return [w for w in words if w not in stop_words and len(w) > 2]
def find_best_material(task: dict, llm_material: str, unit: str) -> tuple:
"""Find single best material for task"""
task_keywords = extract_keywords(task['task'])
llm_keywords = extract_keywords(llm_material)
all_keywords = set(task_keywords + llm_keywords)
compatible_materials = [
m for m in db.materials
if m['unit'] == unit or m['unit'] == 'unit' or m['unit'] is None
]
if not compatible_materials:
compatible_materials = db.materials
query_embedding = embedding_model.encode(
[llm_material],
batch_size=1,
convert_to_numpy=True,
normalize_embeddings=True
)
scored_materials = []
for material in compatible_materials:
score = 0.0
material_text = material['material'].lower()
for keyword in all_keywords:
if keyword in material_text:
score += 2.0
categories_str = ' '.join(material.get('categories', [])).lower()
for keyword in all_keywords:
if keyword in categories_str:
score += 1.0
material_idx = db.materials.index(material)
material_embedding = db.material_embeddings[material_idx].reshape(1, -1)
semantic_score = cosine_similarity(query_embedding, material_embedding)[0][0]
score += semantic_score * 5.0
if score > 0:
scored_materials.append((material, score))
if not scored_materials:
return None, 0.0
scored_materials.sort(key=lambda x: x[1], reverse=True)
return scored_materials[0]
# ============= VALIDATION PIPELINE =============
def validate_scope(request: ScopeRequest) -> ScopeResponse:
"""Validate and enrich scope with semantic validation"""
enriched_areas = []
semantic_mismatches = 0
for area_scope in request.scope_of_work:
matched_room, room_confidence = find_best_room(area_scope.area)
enriched_items = []
for item in area_scope.items:
enriched_item = item.model_copy()
# Match stage
matched_stage, stage_confidence = find_best_stage(item.stage)
if matched_stage:
enriched_item.stageId = matched_stage['stageId']
enriched_item.validated_stage = matched_stage['stage']
enriched_item.stage_confidence = round(stage_confidence, 2)
# Match task with semantic validation
(matched_task, task_confidence,
is_semantic_valid, db_stage_id) = find_best_task_with_semantic_validation(
matched_stage['stageId'],
item.task,
matched_stage,
fallback_to_global=True
)
if matched_task:
enriched_item.taskId = matched_task['taskId']
enriched_item.validated_task = matched_task['task']
enriched_item.task_confidence = round(task_confidence, 2)
enriched_item.task_semantic_valid = is_semantic_valid
enriched_item.task_database_stageId = db_stage_id
if not is_semantic_valid:
semantic_mismatches += 1
# Match material
matched_material, material_score = find_best_material(
matched_task,
item.material,
item.unit
)
if matched_material:
enriched_item.materialId = matched_material['materialId']
enriched_item.validated_material = matched_material['material']
enriched_item.material_confidence = round(material_score / 10.0, 2)
enriched_item.material_price = float(matched_material['price'])
enriched_item.material_margin = float(matched_material['margin'])
enriched_item.material = matched_material['material']
enriched_items.append(enriched_item)
enriched_area = AreaScope(
area=area_scope.area,
items=enriched_items,
roomId=matched_room['id'] if matched_room else None,
roomType=matched_room['roomType'] if matched_room else None,
validated_area=matched_room['name'] if matched_room else area_scope.area,
area_confidence=round(room_confidence, 2) if matched_room else 0.0
)
enriched_areas.append(enriched_area)
# Calculate metadata
total_items = sum(len(area.items) for area in enriched_areas)
validated_stages = sum(1 for area in enriched_areas for item in area.items if item.stageId)
validated_tasks = sum(1 for area in enriched_areas for item in area.items if item.taskId)
validated_materials = sum(1 for area in enriched_areas for item in area.items if item.materialId)
metadata = {
'total_areas': len(enriched_areas),
'total_items': total_items,
'validated_stages': validated_stages,
'validated_tasks': validated_tasks,
'validated_materials': validated_materials,
'semantic_mismatches': semantic_mismatches,
'validation_rate': {
'stages': round(validated_stages / total_items * 100, 1) if total_items > 0 else 0,
'tasks': round(validated_tasks / total_items * 100, 1) if total_items > 0 else 0,
'materials': round(validated_materials / total_items * 100, 1) if total_items > 0 else 0
}
}
return ScopeResponse(scope_of_work=enriched_areas, metadata=metadata)
# ============= API ENDPOINTS =============
@app.get("/")
async def root():
return {
"service": "Construction Scope Validator - FIXED",
"version": "2.1.0",
"status": "running",
"features": ["semantic_task_validation", "fallback_search"],
"data_loaded": len(db.stages) > 0,
"model_type": "trained" if os.path.exists('model.safetensors') else "base",
"gpu_enabled": torch.cuda.is_available(),
"batch_size": BATCH_SIZE
}
@app.get("/health")
async def health():
return {
"status": "healthy",
"stages_loaded": len(db.stages),
"tasks_loaded": len(db.tasks),
"materials_loaded": len(db.materials),
"rooms_loaded": len(db.rooms),
"embeddings_ready": db.stage_embeddings is not None
}
@app.post("/validate", response_model=ScopeResponse)
async def validate_scope_endpoint(request: ScopeRequest):
"""Validate with semantic checking"""
try:
if not db.stages:
raise HTTPException(status_code=500, detail="Database not loaded")
result = validate_scope(request)
return result
except Exception as e:
import traceback
error_detail = f"Validation error: {str(e)}\n{traceback.format_exc()}"
raise HTTPException(status_code=500, detail=error_detail)
@app.post("/validate-simple", response_model=ScopeRequest)
async def validate_scope_simple(request: ScopeRequest):
"""Returns only enriched scope without metadata"""
try:
if not db.stages:
raise HTTPException(status_code=500, detail="Database not loaded")
result = validate_scope(request)
return ScopeRequest(scope_of_work=result.scope_of_work)
except Exception as e:
import traceback
error_detail = f"Validation error: {str(e)}\n{traceback.format_exc()}"
raise HTTPException(status_code=500, detail=error_detail)
# ============= STARTUP =============
@app.on_event("startup")
async def startup_event():
try:
print("\n" + "="*60)
print("STARTING UP - FIXED VERSION")
print("="*60)
if torch.cuda.is_available():
print(f"\nπ GPU ENABLED: {torch.cuda.get_device_name(0)}")
db.load_data(
stages_file='stages.json',
tasks_file='tasks.json',
materials_file='materials.json',
rooms_file='rooms.json'
)
db.initialize_embeddings()
print("\nβ
SERVICE READY WITH SEMANTIC VALIDATION!")
print("="*60)
except Exception as e:
print(f"\nβ STARTUP ERROR: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
# """
# FastAPI Service for Construction Scope Validation
# Deploy on Hugging Face Spaces - Flattened File Structure
# """
# from fastapi import FastAPI, HTTPException
# from fastapi.middleware.cors import CORSMiddleware
# from pydantic import BaseModel, Field
# from typing import List, Optional, Dict, Any
# import json
# import numpy as np
# import os
# import shutil
# from sentence_transformers import SentenceTransformer
# from sklearn.metrics.pairwise import cosine_similarity
# import re
# app = FastAPI(
# title="Construction Scope Validator API",
# description="Validates and enriches LLM-generated construction scope with DB data",
# version="1.0.0"
# )
# #---------------------------
# # CORS middleware
# app.add_middleware(
# CORSMiddleware,
# allow_origins=["*"],
# allow_credentials=True,
# allow_methods=["*"],
# allow_headers=["*"],
# )
# # ============= MODEL LOADING WITH FLAT STRUCTURE =============
# print("="*60)
# print("LOADING MODEL...")
# print("="*60)
# def setup_model_structure():
# """
# Create temporary folder structure for sentence-transformers
# if files are in root (flattened structure)
# """
# # Check if we need to create structure
# if not os.path.exists('1_Pooling') or not os.path.exists('2_Normalize'):
# print("Creating temporary model structure...")
# # Create directories
# os.makedirs('1_Pooling', exist_ok=True)
# os.makedirs('2_Normalize', exist_ok=True)
# # Pooling config
# pooling_config = {
# "word_embedding_dimension": 384,
# "pooling_mode_cls_token": False,
# "pooling_mode_mean_tokens": True,
# "pooling_mode_max_tokens": False,
# "pooling_mode_mean_sqrt_len_tokens": False
# }
# with open('1_Pooling/config.json', 'w') as f:
# json.dump(pooling_config, f, indent=2)
# # Normalize config (empty is fine)
# with open('2_Normalize/config.json', 'w') as f:
# json.dump({}, f)
# print("β Created 1_Pooling/config.json")
# print("β Created 2_Normalize/config.json")
# # Setup structure before loading model
# setup_model_structure()
# try:
# model_files = ['config.json', 'sentence_bert_config.json']
# has_weights = os.path.exists('pytorch_model.bin') or os.path.exists('model.safetensors')
# has_model = all(os.path.exists(f) for f in model_files) and has_weights
# if has_model:
# print("β Model files found in root directory")
# print("Loading trained model...")
# embedding_model = SentenceTransformer('./', device='cpu')
# print("β
Trained model loaded successfully!")
# else:
# print("β οΈ Model not found, using base model...")
# embedding_model = SentenceTransformer('all-MiniLM-L6-v2', device='cpu')
# print("β
Base model loaded successfully!")
# except Exception as e:
# print(f"β Error loading trained model: {e}")
# print("Falling back to base model...")
# embedding_model = SentenceTransformer('all-MiniLM-L6-v2', device='cpu')
# print("β
Base model loaded successfully!")
# print("="*60)
# # ============= DATA MODELS =============
# class LLMScopeItem(BaseModel):
# stage: str
# task: str
# material: str
# quantity: float
# unit: str
# class LLMAreaScope(BaseModel):
# area: str
# items: List[LLMScopeItem]
# class LLMScopeRequest(BaseModel):
# scope_of_work: List[LLMAreaScope]
# class ValidatedMaterial(BaseModel):
# materialId: int
# name: str
# material: str
# unit: str
# price: float
# margin: float
# categories: List[str]
# confidence_score: float
# class ValidatedTask(BaseModel):
# taskId: int
# task: str
# displayName: str
# unit: str
# stageId: int
# roomArea: List[str]
# confidence_score: float
# recommended_materials: List[ValidatedMaterial]
# class ValidatedStage(BaseModel):
# stageId: int
# stage: str
# priority: int
# confidence_score: float
# tasks: List[ValidatedTask]
# class ValidatedArea(BaseModel):
# roomId: Optional[int]
# name: str
# roomType: str
# matched: bool
# confidence_score: float
# stages: List[ValidatedStage]
# class ValidatedResponse(BaseModel):
# areas: List[ValidatedArea]
# summary: Dict[str, Any]
# # ============= HELPER FUNCTION =============
# def parse_room_area(room_area_value):
# """Parse roomArea field which might be a string, list, or None"""
# if room_area_value is None:
# return []
# if isinstance(room_area_value, list):
# return room_area_value
# if isinstance(room_area_value, str):
# try:
# parsed = json.loads(room_area_value)
# if isinstance(parsed, list):
# return parsed
# return [str(parsed)]
# except json.JSONDecodeError:
# return [room_area_value]
# return [str(room_area_value)]
# # ============= DATABASE LOADERS =============
# class DatabaseLoader:
# def __init__(self):
# self.stages = []
# self.tasks = []
# self.materials = []
# self.rooms = []
# self.stage_embeddings = None
# self.task_embeddings = None
# self.material_embeddings = None
# def load_data(self, stages_file: str, tasks_file: str, materials_file: str, rooms_file: str):
# """Load JSON data files"""
# print(f"Loading {stages_file}...")
# with open(stages_file, 'r', encoding='utf-8') as f:
# self.stages = [json.loads(line) for line in f if line.strip()]
# print(f"Loading {tasks_file}...")
# with open(tasks_file, 'r', encoding='utf-8') as f:
# self.tasks = [json.loads(line) for line in f if line.strip()]
# print(f"Loading {materials_file}...")
# with open(materials_file, 'r', encoding='utf-8') as f:
# self.materials = [json.loads(line) for line in f if line.strip()]
# print(f"Loading {rooms_file}...")
# with open(rooms_file, 'r', encoding='utf-8') as f:
# self.rooms = [json.loads(line) for line in f if line.strip()]
# print(f"β
Loaded: {len(self.stages)} stages, {len(self.tasks)} tasks, "
# f"{len(self.materials)} materials, {len(self.rooms)} rooms")
# def initialize_embeddings(self):
# """Pre-compute embeddings for fast lookup"""
# print("Computing stage embeddings...")
# stage_texts = [s['stage'] for s in self.stages]
# self.stage_embeddings = embedding_model.encode(stage_texts, show_progress_bar=True)
# print("Computing task embeddings...")
# task_texts = [t['task'] for t in self.tasks]
# self.task_embeddings = embedding_model.encode(task_texts, show_progress_bar=True)
# print("Computing material embeddings...")
# material_texts = [m['material'] for m in self.materials]
# self.material_embeddings = embedding_model.encode(material_texts, show_progress_bar=True)
# print("β
Embeddings ready!")
# # Global DB instance
# db = DatabaseLoader()
# # ============= MATCHING FUNCTIONS =============
# def find_best_stage(llm_stage: str, threshold: float = 0.5) -> tuple:
# """Find closest matching stage from DB"""
# query_embedding = embedding_model.encode([llm_stage])
# similarities = cosine_similarity(query_embedding, db.stage_embeddings)[0]
# best_idx = np.argmax(similarities)
# best_score = similarities[best_idx]
# if best_score >= threshold:
# return db.stages[best_idx], best_score
# return None, 0.0
# def find_best_room(llm_area: str, threshold: float = 0.6) -> tuple:
# """Find closest matching room from DB"""
# llm_area_lower = llm_area.lower()
# for room in db.rooms:
# if room['name'].lower() == llm_area_lower:
# return room, 1.0
# room_texts = [r['name'] for r in db.rooms]
# query_embedding = embedding_model.encode([llm_area])
# room_embeddings = embedding_model.encode(room_texts)
# similarities = cosine_similarity(query_embedding, room_embeddings)[0]
# best_idx = np.argmax(similarities)
# best_score = similarities[best_idx]
# if best_score >= threshold:
# return db.rooms[best_idx], best_score
# return None, 0.0
# def find_tasks_for_stage(stage_id: int, llm_task: str, top_k: int = 5) -> List[tuple]:
# """Find relevant tasks for a stage matching LLM task description"""
# stage_tasks = [t for t in db.tasks if t['stageId'] == stage_id]
# if not stage_tasks:
# return []
# task_indices = [db.tasks.index(t) for t in stage_tasks]
# query_embedding = embedding_model.encode([llm_task])
# stage_task_embeddings = db.task_embeddings[task_indices]
# similarities = cosine_similarity(query_embedding, stage_task_embeddings)[0]
# top_indices = np.argsort(similarities)[-top_k:][::-1]
# results = [(stage_tasks[idx], similarities[idx]) for idx in top_indices]
# return results
# def extract_keywords(text: str) -> List[str]:
# """Extract meaningful keywords from text"""
# stop_words = {'and', 'or', 'the', 'to', 'a', 'of', 'for', 'in', 'on', 'supply', 'install'}
# words = re.findall(r'\b\w+\b', text.lower())
# return [w for w in words if w not in stop_words and len(w) > 2]
# def find_materials_for_task(task: dict, llm_material: str, unit: str, top_k: int = 10) -> List[tuple]:
# """Find materials matching task requirements"""
# task_keywords = extract_keywords(task['task'])
# llm_keywords = extract_keywords(llm_material)
# all_keywords = set(task_keywords + llm_keywords)
# compatible_materials = [
# m for m in db.materials
# if m['unit'] == unit or m['unit'] == 'unit' or m['unit'] is None
# ]
# if not compatible_materials:
# compatible_materials = db.materials
# scored_materials = []
# for material in compatible_materials:
# score = 0.0
# material_text = material['material'].lower()
# for keyword in all_keywords:
# if keyword in material_text:
# score += 2.0
# categories_str = ' '.join(material.get('categories', [])).lower()
# for keyword in all_keywords:
# if keyword in categories_str:
# score += 1.0
# material_idx = db.materials.index(material)
# query_embedding = embedding_model.encode([llm_material])
# material_embedding = db.material_embeddings[material_idx].reshape(1, -1)
# semantic_score = cosine_similarity(query_embedding, material_embedding)[0][0]
# score += semantic_score * 5.0
# if score > 0:
# scored_materials.append((material, score))
# scored_materials.sort(key=lambda x: x[1], reverse=True)
# return scored_materials[:top_k]
# # ============= VALIDATION PIPELINE =============
# def validate_scope(llm_scope: LLMScopeRequest) -> ValidatedResponse:
# """Main validation pipeline"""
# validated_areas = []
# for area_scope in llm_scope.scope_of_work:
# matched_room, room_confidence = find_best_room(area_scope.area)
# validated_stages_dict = {}
# for item in area_scope.items:
# matched_stage, stage_confidence = find_best_stage(item.stage)
# if not matched_stage:
# continue
# stage_id = matched_stage['stageId']
# if stage_id not in validated_stages_dict:
# validated_stages_dict[stage_id] = {
# 'stage_data': matched_stage,
# 'confidence': stage_confidence,
# 'tasks': []
# }
# task_matches = find_tasks_for_stage(stage_id, item.task, top_k=3)
# if not task_matches:
# continue
# best_task, task_confidence = task_matches[0]
# material_matches = find_materials_for_task(
# best_task, item.material, item.unit, top_k=5
# )
# validated_materials = [
# ValidatedMaterial(
# materialId=m['materialId'],
# name=m['name'],
# material=m['material'],
# unit=m['unit'] or 'unit',
# price=float(m['price']),
# margin=float(m['margin']),
# categories=m['categories'],
# confidence_score=round(score / 10.0, 2)
# )
# for m, score in material_matches
# ]
# validated_task = ValidatedTask(
# taskId=best_task['taskId'],
# task=best_task['task'],
# displayName=best_task['displayName'],
# unit=best_task['unit'],
# stageId=best_task['stageId'],
# roomArea=parse_room_area(best_task['roomArea']),
# confidence_score=round(task_confidence, 2),
# recommended_materials=validated_materials
# )
# validated_stages_dict[stage_id]['tasks'].append(validated_task)
# validated_stages = [
# ValidatedStage(
# stageId=stage_data['stage_data']['stageId'],
# stage=stage_data['stage_data']['stage'],
# priority=stage_data['stage_data']['priority'],
# confidence_score=round(stage_data['confidence'], 2),
# tasks=stage_data['tasks']
# )
# for stage_data in validated_stages_dict.values()
# ]
# validated_stages.sort(key=lambda x: x.priority)
# validated_area = ValidatedArea(
# roomId=matched_room['id'] if matched_room else None,
# name=matched_room['name'] if matched_room else area_scope.area,
# roomType=matched_room['roomType'] if matched_room else 'unknown',
# matched=matched_room is not None,
# confidence_score=round(room_confidence, 2),
# stages=validated_stages
# )
# validated_areas.append(validated_area)
# summary = {
# 'total_areas': len(validated_areas),
# 'total_stages': sum(len(a.stages) for a in validated_areas),
# 'total_tasks': sum(len(s.tasks) for a in validated_areas for s in a.stages),
# 'total_materials': sum(
# len(t.recommended_materials)
# for a in validated_areas
# for s in a.stages
# for t in s.tasks
# ),
# 'matched_areas': sum(1 for a in validated_areas if a.matched),
# 'avg_confidence': round(
# np.mean([a.confidence_score for a in validated_areas]), 2
# ) if validated_areas else 0.0
# }
# return ValidatedResponse(areas=validated_areas, summary=summary)
# # ============= API ENDPOINTS =============
# @app.get("/")
# async def root():
# return {
# "service": "Construction Scope Validator",
# "version": "1.0.0",
# "status": "running",
# "data_loaded": len(db.stages) > 0,
# "model_type": "trained" if os.path.exists('model.safetensors') else "base"
# }
# @app.get("/health")
# async def health():
# return {
# "status": "healthy",
# "stages_loaded": len(db.stages),
# "tasks_loaded": len(db.tasks),
# "materials_loaded": len(db.materials),
# "rooms_loaded": len(db.rooms),
# "embeddings_ready": db.stage_embeddings is not None,
# "model_type": "trained" if os.path.exists('model.safetensors') else "base"
# }
# @app.post("/validate", response_model=ValidatedResponse)
# async def validate_scope_endpoint(request: LLMScopeRequest):
# """Validate LLM-generated scope against database"""
# try:
# if not db.stages:
# raise HTTPException(status_code=500, detail="Database not loaded")
# result = validate_scope(request)
# return result
# except Exception as e:
# import traceback
# error_detail = f"Validation error: {str(e)}\n{traceback.format_exc()}"
# raise HTTPException(status_code=500, detail=error_detail)
# @app.post("/match-stage")
# async def match_stage(stage_name: str):
# """Test endpoint: match a single stage name"""
# matched_stage, confidence = find_best_stage(stage_name)
# if matched_stage:
# return {
# "input": stage_name,
# "matched": matched_stage,
# "confidence": round(confidence, 2)
# }
# return {"input": stage_name, "matched": None, "confidence": 0.0}
# @app.post("/match-room")
# async def match_room(room_name: str):
# """Test endpoint: match a single room name"""
# matched_room, confidence = find_best_room(room_name)
# if matched_room:
# return {
# "input": room_name,
# "matched": matched_room,
# "confidence": round(confidence, 2)
# }
# return {"input": room_name, "matched": None, "confidence": 0.0}
# # ============= STARTUP =============
# @app.on_event("startup")
# async def startup_event():
# """Load data and initialize embeddings on startup"""
# try:
# print("\n" + "="*60)
# print("STARTING UP...")
# print("="*60)
# db.load_data(
# stages_file='stages.json',
# tasks_file='tasks.json',
# materials_file='materials.json',
# rooms_file='rooms.json'
# )
# db.initialize_embeddings()
# print("\n" + "="*60)
# print("β
SERVICE READY!")
# print("="*60)
# except Exception as e:
# print(f"\nβ STARTUP ERROR: {e}")
# import traceback
# traceback.print_exc()
# if __name__ == "__main__":
# import uvicorn
# uvicorn.run(app, host="0.0.0.0", port=7860)
# # """
# # FastAPI Service for Construction Scope Validation
# # Deploy on Hugging Face Spaces
# # """
# # from fastapi import FastAPI, HTTPException
# # from fastapi.middleware.cors import CORSMiddleware
# # from pydantic import BaseModel, Field
# # from typing import List, Optional, Dict, Any
# # import json
# # import numpy as np
# # import os
# # from sentence_transformers import SentenceTransformer
# # from sklearn.metrics.pairwise import cosine_similarity
# # import re
# # app = FastAPI(
# # title="Construction Scope Validator API",
# # description="Validates and enriches LLM-generated construction scope with DB data",
# # version="1.0.0"
# # )
# # # CORS middleware
# # app.add_middleware(
# # CORSMiddleware,
# # allow_origins=["*"],
# # allow_credentials=True,
# # allow_methods=["*"],
# # allow_headers=["*"],
# # )
# # # Load embedding model (cached globally)
# # print("="*60)
# # print("LOADING MODEL...")
# # print("="*60)
# # try:
# # model_files = ['config.json', 'sentence_bert_config.json']
# # has_weights = os.path.exists('pytorch_model.bin') or os.path.exists('model.safetensors')
# # has_model = all(os.path.exists(f) for f in model_files) and has_weights
# # if has_model:
# # print("β Trained model files found in root directory")
# # print("Loading trained model...")
# # embedding_model = SentenceTransformer('./', device='cpu')
# # print("β
Trained model loaded successfully!")
# # else:
# # print("β οΈ Trained model not found, using base model...")
# # embedding_model = SentenceTransformer('all-MiniLM-L6-v2', device='cpu')
# # print("β
Base model loaded successfully!")
# # except Exception as e:
# # print(f"β Error loading trained model: {e}")
# # print("Falling back to base model...")
# # embedding_model = SentenceTransformer('all-MiniLM-L6-v2', device='cpu')
# # print("β
Base model loaded successfully!")
# # print("="*60)
# # # ============= DATA MODELS =============
# # class LLMScopeItem(BaseModel):
# # stage: str
# # task: str
# # material: str
# # quantity: float
# # unit: str
# # class LLMAreaScope(BaseModel):
# # area: str
# # items: List[LLMScopeItem]
# # class LLMScopeRequest(BaseModel):
# # scope_of_work: List[LLMAreaScope]
# # class ValidatedMaterial(BaseModel):
# # materialId: int
# # name: str
# # material: str
# # unit: str
# # price: float
# # margin: float
# # categories: List[str]
# # confidence_score: float
# # class ValidatedTask(BaseModel):
# # taskId: int
# # task: str
# # displayName: str
# # unit: str
# # stageId: int
# # roomArea: List[str]
# # confidence_score: float
# # recommended_materials: List[ValidatedMaterial]
# # class ValidatedStage(BaseModel):
# # stageId: int
# # stage: str
# # priority: int
# # confidence_score: float
# # tasks: List[ValidatedTask]
# # class ValidatedArea(BaseModel):
# # roomId: Optional[int]
# # name: str
# # roomType: str
# # matched: bool
# # confidence_score: float
# # stages: List[ValidatedStage]
# # class ValidatedResponse(BaseModel):
# # areas: List[ValidatedArea]
# # summary: Dict[str, Any]
# # # ============= HELPER FUNCTION =============
# # def parse_room_area(room_area_value):
# # """
# # Parse roomArea field which might be a string, list, or None
# # Returns a proper list of strings
# # """
# # if room_area_value is None:
# # return []
# # # If it's already a list, return it
# # if isinstance(room_area_value, list):
# # return room_area_value
# # # If it's a string, try to parse it as JSON
# # if isinstance(room_area_value, str):
# # try:
# # parsed = json.loads(room_area_value)
# # if isinstance(parsed, list):
# # return parsed
# # return [str(parsed)]
# # except json.JSONDecodeError:
# # # If JSON parsing fails, treat it as a single item
# # return [room_area_value]
# # # Fallback: convert to string and wrap in list
# # return [str(room_area_value)]
# # # ============= DATABASE LOADERS =============
# # class DatabaseLoader:
# # def __init__(self):
# # self.stages = []
# # self.tasks = []
# # self.materials = []
# # self.rooms = []
# # self.stage_embeddings = None
# # self.task_embeddings = None
# # self.material_embeddings = None
# # def load_data(self, stages_file: str, tasks_file: str, materials_file: str, rooms_file: str):
# # """Load JSON data files"""
# # print(f"Loading {stages_file}...")
# # with open(stages_file, 'r', encoding='utf-8') as f:
# # self.stages = [json.loads(line) for line in f if line.strip()]
# # print(f"Loading {tasks_file}...")
# # with open(tasks_file, 'r', encoding='utf-8') as f:
# # self.tasks = [json.loads(line) for line in f if line.strip()]
# # print(f"Loading {materials_file}...")
# # with open(materials_file, 'r', encoding='utf-8') as f:
# # self.materials = [json.loads(line) for line in f if line.strip()]
# # print(f"Loading {rooms_file}...")
# # with open(rooms_file, 'r', encoding='utf-8') as f:
# # self.rooms = [json.loads(line) for line in f if line.strip()]
# # print(f"β
Loaded: {len(self.stages)} stages, {len(self.tasks)} tasks, "
# # f"{len(self.materials)} materials, {len(self.rooms)} rooms")
# # def initialize_embeddings(self):
# # """Pre-compute embeddings for fast lookup"""
# # print("Computing stage embeddings...")
# # stage_texts = [s['stage'] for s in self.stages]
# # self.stage_embeddings = embedding_model.encode(stage_texts, show_progress_bar=True)
# # print("Computing task embeddings...")
# # task_texts = [t['task'] for t in self.tasks]
# # self.task_embeddings = embedding_model.encode(task_texts, show_progress_bar=True)
# # print("Computing material embeddings...")
# # material_texts = [m['material'] for m in self.materials]
# # self.material_embeddings = embedding_model.encode(material_texts, show_progress_bar=True)
# # print("β
Embeddings ready!")
# # # Global DB instance
# # db = DatabaseLoader()
# # # ============= MATCHING FUNCTIONS =============
# # def find_best_stage(llm_stage: str, threshold: float = 0.5) -> tuple:
# # """Find closest matching stage from DB"""
# # query_embedding = embedding_model.encode([llm_stage])
# # similarities = cosine_similarity(query_embedding, db.stage_embeddings)[0]
# # best_idx = np.argmax(similarities)
# # best_score = similarities[best_idx]
# # if best_score >= threshold:
# # return db.stages[best_idx], best_score
# # return None, 0.0
# # def find_best_room(llm_area: str, threshold: float = 0.6) -> tuple:
# # """Find closest matching room from DB"""
# # llm_area_lower = llm_area.lower()
# # # Exact match first
# # for room in db.rooms:
# # if room['name'].lower() == llm_area_lower:
# # return room, 1.0
# # # Fuzzy match
# # room_texts = [r['name'] for r in db.rooms]
# # query_embedding = embedding_model.encode([llm_area])
# # room_embeddings = embedding_model.encode(room_texts)
# # similarities = cosine_similarity(query_embedding, room_embeddings)[0]
# # best_idx = np.argmax(similarities)
# # best_score = similarities[best_idx]
# # if best_score >= threshold:
# # return db.rooms[best_idx], best_score
# # return None, 0.0
# # def find_tasks_for_stage(stage_id: int, llm_task: str, top_k: int = 5) -> List[tuple]:
# # """Find relevant tasks for a stage matching LLM task description"""
# # stage_tasks = [t for t in db.tasks if t['stageId'] == stage_id]
# # if not stage_tasks:
# # return []
# # task_indices = [db.tasks.index(t) for t in stage_tasks]
# # query_embedding = embedding_model.encode([llm_task])
# # stage_task_embeddings = db.task_embeddings[task_indices]
# # similarities = cosine_similarity(query_embedding, stage_task_embeddings)[0]
# # top_indices = np.argsort(similarities)[-top_k:][::-1]
# # results = [(stage_tasks[idx], similarities[idx]) for idx in top_indices]
# # return results
# # def extract_keywords(text: str) -> List[str]:
# # """Extract meaningful keywords from text"""
# # stop_words = {'and', 'or', 'the', 'to', 'a', 'of', 'for', 'in', 'on', 'supply', 'install'}
# # words = re.findall(r'\b\w+\b', text.lower())
# # return [w for w in words if w not in stop_words and len(w) > 2]
# # def find_materials_for_task(task: dict, llm_material: str, unit: str, top_k: int = 10) -> List[tuple]:
# # """Find materials matching task requirements"""
# # task_keywords = extract_keywords(task['task'])
# # llm_keywords = extract_keywords(llm_material)
# # all_keywords = set(task_keywords + llm_keywords)
# # compatible_materials = [
# # m for m in db.materials
# # if m['unit'] == unit or m['unit'] == 'unit' or m['unit'] is None
# # ]
# # if not compatible_materials:
# # compatible_materials = db.materials
# # scored_materials = []
# # for material in compatible_materials:
# # score = 0.0
# # material_text = material['material'].lower()
# # for keyword in all_keywords:
# # if keyword in material_text:
# # score += 2.0
# # categories_str = ' '.join(material.get('categories', [])).lower()
# # for keyword in all_keywords:
# # if keyword in categories_str:
# # score += 1.0
# # material_idx = db.materials.index(material)
# # query_embedding = embedding_model.encode([llm_material])
# # material_embedding = db.material_embeddings[material_idx].reshape(1, -1)
# # semantic_score = cosine_similarity(query_embedding, material_embedding)[0][0]
# # score += semantic_score * 5.0
# # if score > 0:
# # scored_materials.append((material, score))
# # scored_materials.sort(key=lambda x: x[1], reverse=True)
# # return scored_materials[:top_k]
# # # ============= VALIDATION PIPELINE =============
# # def validate_scope(llm_scope: LLMScopeRequest) -> ValidatedResponse:
# # """Main validation pipeline"""
# # validated_areas = []
# # for area_scope in llm_scope.scope_of_work:
# # matched_room, room_confidence = find_best_room(area_scope.area)
# # validated_stages_dict = {}
# # for item in area_scope.items:
# # matched_stage, stage_confidence = find_best_stage(item.stage)
# # if not matched_stage:
# # continue
# # stage_id = matched_stage['stageId']
# # if stage_id not in validated_stages_dict:
# # validated_stages_dict[stage_id] = {
# # 'stage_data': matched_stage,
# # 'confidence': stage_confidence,
# # 'tasks': []
# # }
# # task_matches = find_tasks_for_stage(stage_id, item.task, top_k=3)
# # if not task_matches:
# # continue
# # best_task, task_confidence = task_matches[0]
# # material_matches = find_materials_for_task(
# # best_task, item.material, item.unit, top_k=5
# # )
# # validated_materials = [
# # ValidatedMaterial(
# # materialId=m['materialId'],
# # name=m['name'],
# # material=m['material'],
# # unit=m['unit'] or 'unit',
# # price=float(m['price']),
# # margin=float(m['margin']),
# # categories=m['categories'],
# # confidence_score=round(score / 10.0, 2)
# # )
# # for m, score in material_matches
# # ]
# # # FIX: Parse roomArea properly
# # validated_task = ValidatedTask(
# # taskId=best_task['taskId'],
# # task=best_task['task'],
# # displayName=best_task['displayName'],
# # unit=best_task['unit'],
# # stageId=best_task['stageId'],
# # roomArea=parse_room_area(best_task['roomArea']), # <-- FIXED HERE
# # confidence_score=round(task_confidence, 2),
# # recommended_materials=validated_materials
# # )
# # validated_stages_dict[stage_id]['tasks'].append(validated_task)
# # validated_stages = [
# # ValidatedStage(
# # stageId=stage_data['stage_data']['stageId'],
# # stage=stage_data['stage_data']['stage'],
# # priority=stage_data['stage_data']['priority'],
# # confidence_score=round(stage_data['confidence'], 2),
# # tasks=stage_data['tasks']
# # )
# # for stage_data in validated_stages_dict.values()
# # ]
# # validated_stages.sort(key=lambda x: x.priority)
# # validated_area = ValidatedArea(
# # roomId=matched_room['id'] if matched_room else None,
# # name=matched_room['name'] if matched_room else area_scope.area,
# # roomType=matched_room['roomType'] if matched_room else 'unknown',
# # matched=matched_room is not None,
# # confidence_score=round(room_confidence, 2),
# # stages=validated_stages
# # )
# # validated_areas.append(validated_area)
# # summary = {
# # 'total_areas': len(validated_areas),
# # 'total_stages': sum(len(a.stages) for a in validated_areas),
# # 'total_tasks': sum(len(s.tasks) for a in validated_areas for s in a.stages),
# # 'total_materials': sum(
# # len(t.recommended_materials)
# # for a in validated_areas
# # for s in a.stages
# # for t in s.tasks
# # ),
# # 'matched_areas': sum(1 for a in validated_areas if a.matched),
# # 'avg_confidence': round(
# # np.mean([a.confidence_score for a in validated_areas]), 2
# # ) if validated_areas else 0.0
# # }
# # return ValidatedResponse(areas=validated_areas, summary=summary)
# # # ============= API ENDPOINTS =============
# # @app.get("/")
# # async def root():
# # return {
# # "service": "Construction Scope Validator",
# # "version": "1.0.0",
# # "status": "running",
# # "data_loaded": len(db.stages) > 0,
# # "model_type": "trained" if os.path.exists('model.safetensors') else "base"
# # }
# # @app.get("/health")
# # async def health():
# # return {
# # "status": "healthy",
# # "stages_loaded": len(db.stages),
# # "tasks_loaded": len(db.tasks),
# # "materials_loaded": len(db.materials),
# # "rooms_loaded": len(db.rooms),
# # "embeddings_ready": db.stage_embeddings is not None,
# # "model_type": "trained" if os.path.exists('model.safetensors') else "base"
# # }
# # @app.post("/validate", response_model=ValidatedResponse)
# # async def validate_scope_endpoint(request: LLMScopeRequest):
# # """
# # Validate LLM-generated scope against database
# # Returns enriched data with matched stages, tasks, materials, and confidence scores
# # """
# # try:
# # if not db.stages:
# # raise HTTPException(status_code=500, detail="Database not loaded")
# # result = validate_scope(request)
# # return result
# # except Exception as e:
# # import traceback
# # error_detail = f"Validation error: {str(e)}\n{traceback.format_exc()}"
# # raise HTTPException(status_code=500, detail=error_detail)
# # @app.post("/match-stage")
# # async def match_stage(stage_name: str):
# # """Test endpoint: match a single stage name"""
# # matched_stage, confidence = find_best_stage(stage_name)
# # if matched_stage:
# # return {
# # "input": stage_name,
# # "matched": matched_stage,
# # "confidence": round(confidence, 2)
# # }
# # return {"input": stage_name, "matched": None, "confidence": 0.0}
# # @app.post("/match-room")
# # async def match_room(room_name: str):
# # """Test endpoint: match a single room name"""
# # matched_room, confidence = find_best_room(room_name)
# # if matched_room:
# # return {
# # "input": room_name,
# # "matched": matched_room,
# # "confidence": round(confidence, 2)
# # }
# # return {"input": room_name, "matched": None, "confidence": 0.0}
# # # ============= STARTUP =============
# # @app.on_event("startup")
# # async def startup_event():
# # """Load data and initialize embeddings on startup"""
# # try:
# # print("\n" + "="*60)
# # print("STARTING UP...")
# # print("="*60)
# # db.load_data(
# # stages_file='stages.json',
# # tasks_file='tasks.json',
# # materials_file='materials.json',
# # rooms_file='rooms.json'
# # )
# # db.initialize_embeddings()
# # print("\n" + "="*60)
# # print("β
SERVICE READY!")
# # print("="*60)
# # except Exception as e:
# # print(f"\nβ STARTUP ERROR: {e}")
# # print("Make sure JSON files are in the correct location")
# # import traceback
# # traceback.print_exc()
# # if __name__ == "__main__":
# # import uvicorn
# # uvicorn.run(app, host="0.0.0.0", port=7860)
# # """
# # FastAPI Service for Construction Scope Validation
# # Deploy on Hugging Face Spaces
# # """
# # from fastapi import FastAPI, HTTPException
# # from fastapi.middleware.cors import CORSMiddleware
# # from pydantic import BaseModel, Field
# # from typing import List, Optional, Dict, Any
# # import json
# # import numpy as np
# # import os
# # from sentence_transformers import SentenceTransformer
# # from sklearn.metrics.pairwise import cosine_similarity
# # import re
# # app = FastAPI(
# # title="Construction Scope Validator API",
# # description="Validates and enriches LLM-generated construction scope with DB data",
# # version="1.0.0"
# # )
# # # CORS middleware
# # app.add_middleware(
# # CORSMiddleware,
# # allow_origins=["*"],
# # allow_credentials=True,
# # allow_methods=["*"],
# # allow_headers=["*"],
# # )
# # # Load embedding model (cached globally)
# # # Try to load trained model from root, fallback to base model
# # print("="*60)
# # print("LOADING MODEL...")
# # print("="*60)
# # try:
# # # Check if trained model files exist in root
# # # Check if trained model files exist in root
# # model_files = ['config.json', 'sentence_bert_config.json']
# # # Check for either pytorch_model.bin or model.safetensors
# # has_weights = os.path.exists('pytorch_model.bin') or os.path.exists('model.safetensors')
# # has_model = all(os.path.exists(f) for f in model_files) and has_weights
# # if has_model:
# # print("β Trained model files found in root directory")
# # print("Loading trained model...")
# # embedding_model = SentenceTransformer('./', device='cpu')
# # print("β
Trained model loaded successfully!")
# # else:
# # print("β οΈ Trained model not found, using base model...")
# # embedding_model = SentenceTransformer('all-MiniLM-L6-v2', device='cpu')
# # print("β
Base model loaded successfully!")
# # except Exception as e:
# # print(f"β Error loading trained model: {e}")
# # print("Falling back to base model...")
# # embedding_model = SentenceTransformer('all-MiniLM-L6-v2', device='cpu')
# # print("β
Base model loaded successfully!")
# # print("="*60)
# # # ============= DATA MODELS =============
# # class LLMScopeItem(BaseModel):
# # stage: str
# # task: str
# # material: str
# # quantity: float
# # unit: str
# # class LLMAreaScope(BaseModel):
# # area: str
# # items: List[LLMScopeItem]
# # class LLMScopeRequest(BaseModel):
# # scope_of_work: List[LLMAreaScope]
# # class ValidatedMaterial(BaseModel):
# # materialId: int
# # name: str
# # material: str
# # unit: str
# # price: float
# # margin: float
# # categories: List[str]
# # confidence_score: float
# # class ValidatedTask(BaseModel):
# # taskId: int
# # task: str
# # displayName: str
# # unit: str
# # stageId: int
# # roomArea: List[str]
# # confidence_score: float
# # recommended_materials: List[ValidatedMaterial]
# # class ValidatedStage(BaseModel):
# # stageId: int
# # stage: str
# # priority: int
# # confidence_score: float
# # tasks: List[ValidatedTask]
# # class ValidatedArea(BaseModel):
# # roomId: Optional[int]
# # name: str
# # roomType: str
# # matched: bool
# # confidence_score: float
# # stages: List[ValidatedStage]
# # class ValidatedResponse(BaseModel):
# # areas: List[ValidatedArea]
# # summary: Dict[str, Any]
# # # ============= DATABASE LOADERS =============
# # class DatabaseLoader:
# # def __init__(self):
# # self.stages = []
# # self.tasks = []
# # self.materials = []
# # self.rooms = []
# # self.stage_embeddings = None
# # self.task_embeddings = None
# # self.material_embeddings = None
# # def load_data(self, stages_file: str, tasks_file: str, materials_file: str, rooms_file: str):
# # """Load JSON data files"""
# # print(f"Loading {stages_file}...")
# # with open(stages_file, 'r', encoding='utf-8') as f:
# # self.stages = [json.loads(line) for line in f if line.strip()]
# # print(f"Loading {tasks_file}...")
# # with open(tasks_file, 'r', encoding='utf-8') as f:
# # self.tasks = [json.loads(line) for line in f if line.strip()]
# # print(f"Loading {materials_file}...")
# # with open(materials_file, 'r', encoding='utf-8') as f:
# # self.materials = [json.loads(line) for line in f if line.strip()]
# # print(f"Loading {rooms_file}...")
# # with open(rooms_file, 'r', encoding='utf-8') as f:
# # self.rooms = [json.loads(line) for line in f if line.strip()]
# # print(f"β
Loaded: {len(self.stages)} stages, {len(self.tasks)} tasks, "
# # f"{len(self.materials)} materials, {len(self.rooms)} rooms")
# # def initialize_embeddings(self):
# # """Pre-compute embeddings for fast lookup"""
# # print("Computing stage embeddings...")
# # stage_texts = [s['stage'] for s in self.stages]
# # self.stage_embeddings = embedding_model.encode(stage_texts, show_progress_bar=True)
# # print("Computing task embeddings...")
# # task_texts = [t['task'] for t in self.tasks]
# # self.task_embeddings = embedding_model.encode(task_texts, show_progress_bar=True)
# # print("Computing material embeddings...")
# # material_texts = [m['material'] for m in self.materials]
# # self.material_embeddings = embedding_model.encode(material_texts, show_progress_bar=True)
# # print("β
Embeddings ready!")
# # # Global DB instance
# # db = DatabaseLoader()
# # # ============= MATCHING FUNCTIONS =============
# # def find_best_stage(llm_stage: str, threshold: float = 0.5) -> tuple:
# # """Find closest matching stage from DB"""
# # query_embedding = embedding_model.encode([llm_stage])
# # similarities = cosine_similarity(query_embedding, db.stage_embeddings)[0]
# # best_idx = np.argmax(similarities)
# # best_score = similarities[best_idx]
# # if best_score >= threshold:
# # return db.stages[best_idx], best_score
# # return None, 0.0
# # def find_best_room(llm_area: str, threshold: float = 0.6) -> tuple:
# # """Find closest matching room from DB"""
# # llm_area_lower = llm_area.lower()
# # # Exact match first
# # for room in db.rooms:
# # if room['name'].lower() == llm_area_lower:
# # return room, 1.0
# # # Fuzzy match
# # room_texts = [r['name'] for r in db.rooms]
# # query_embedding = embedding_model.encode([llm_area])
# # room_embeddings = embedding_model.encode(room_texts)
# # similarities = cosine_similarity(query_embedding, room_embeddings)[0]
# # best_idx = np.argmax(similarities)
# # best_score = similarities[best_idx]
# # if best_score >= threshold:
# # return db.rooms[best_idx], best_score
# # return None, 0.0
# # def find_tasks_for_stage(stage_id: int, llm_task: str, top_k: int = 5) -> List[tuple]:
# # """Find relevant tasks for a stage matching LLM task description"""
# # # Filter tasks by stage
# # stage_tasks = [t for t in db.tasks if t['stageId'] == stage_id]
# # if not stage_tasks:
# # return []
# # # Compute similarities
# # task_indices = [db.tasks.index(t) for t in stage_tasks]
# # query_embedding = embedding_model.encode([llm_task])
# # stage_task_embeddings = db.task_embeddings[task_indices]
# # similarities = cosine_similarity(query_embedding, stage_task_embeddings)[0]
# # # Get top K
# # top_indices = np.argsort(similarities)[-top_k:][::-1]
# # results = [(stage_tasks[idx], similarities[idx]) for idx in top_indices]
# # return results
# # def extract_keywords(text: str) -> List[str]:
# # """Extract meaningful keywords from text"""
# # # Remove common words
# # stop_words = {'and', 'or', 'the', 'to', 'a', 'of', 'for', 'in', 'on', 'supply', 'install'}
# # words = re.findall(r'\b\w+\b', text.lower())
# # return [w for w in words if w not in stop_words and len(w) > 2]
# # def find_materials_for_task(task: dict, llm_material: str, unit: str, top_k: int = 10) -> List[tuple]:
# # """Find materials matching task requirements"""
# # task_keywords = extract_keywords(task['task'])
# # llm_keywords = extract_keywords(llm_material)
# # all_keywords = set(task_keywords + llm_keywords)
# # # Filter by unit compatibility
# # compatible_materials = [
# # m for m in db.materials
# # if m['unit'] == unit or m['unit'] == 'unit' or m['unit'] is None
# # ]
# # if not compatible_materials:
# # # Fallback: allow any unit
# # compatible_materials = db.materials
# # # Score materials
# # scored_materials = []
# # for material in compatible_materials:
# # score = 0.0
# # material_text = material['material'].lower()
# # # Keyword matching
# # for keyword in all_keywords:
# # if keyword in material_text:
# # score += 2.0
# # # Category matching
# # categories_str = ' '.join(material.get('categories', [])).lower()
# # for keyword in all_keywords:
# # if keyword in categories_str:
# # score += 1.0
# # # Embedding similarity
# # material_idx = db.materials.index(material)
# # query_embedding = embedding_model.encode([llm_material])
# # material_embedding = db.material_embeddings[material_idx].reshape(1, -1)
# # semantic_score = cosine_similarity(query_embedding, material_embedding)[0][0]
# # score += semantic_score * 5.0
# # if score > 0:
# # scored_materials.append((material, score))
# # # Sort and return top K
# # scored_materials.sort(key=lambda x: x[1], reverse=True)
# # return scored_materials[:top_k]
# # # ============= VALIDATION PIPELINE =============
# # def validate_scope(llm_scope: LLMScopeRequest) -> ValidatedResponse:
# # """Main validation pipeline"""
# # validated_areas = []
# # for area_scope in llm_scope.scope_of_work:
# # # Match room/area
# # matched_room, room_confidence = find_best_room(area_scope.area)
# # validated_stages_dict = {}
# # for item in area_scope.items:
# # # Match stage
# # matched_stage, stage_confidence = find_best_stage(item.stage)
# # if not matched_stage:
# # continue # Skip if stage not found
# # stage_id = matched_stage['stageId']
# # # Initialize stage if new
# # if stage_id not in validated_stages_dict:
# # validated_stages_dict[stage_id] = {
# # 'stage_data': matched_stage,
# # 'confidence': stage_confidence,
# # 'tasks': []
# # }
# # # Match task
# # task_matches = find_tasks_for_stage(stage_id, item.task, top_k=3)
# # if not task_matches:
# # continue
# # best_task, task_confidence = task_matches[0]
# # # Match materials
# # material_matches = find_materials_for_task(
# # best_task,
# # item.material,
# # item.unit,
# # top_k=5
# # )
# # validated_materials = [
# # ValidatedMaterial(
# # materialId=m['materialId'],
# # name=m['name'],
# # material=m['material'],
# # unit=m['unit'] or 'unit',
# # price=float(m['price']),
# # margin=float(m['margin']),
# # categories=m['categories'],
# # confidence_score=round(score / 10.0, 2)
# # )
# # for m, score in material_matches
# # ]
# # validated_task = ValidatedTask(
# # taskId=best_task['taskId'],
# # task=best_task['task'],
# # displayName=best_task['displayName'],
# # unit=best_task['unit'],
# # stageId=best_task['stageId'],
# # roomArea=best_task['roomArea'],
# # confidence_score=round(task_confidence, 2),
# # recommended_materials=validated_materials
# # )
# # validated_stages_dict[stage_id]['tasks'].append(validated_task)
# # # Build validated stages list
# # validated_stages = [
# # ValidatedStage(
# # stageId=stage_data['stage_data']['stageId'],
# # stage=stage_data['stage_data']['stage'],
# # priority=stage_data['stage_data']['priority'],
# # confidence_score=round(stage_data['confidence'], 2),
# # tasks=stage_data['tasks']
# # )
# # for stage_data in validated_stages_dict.values()
# # ]
# # # Sort stages by priority
# # validated_stages.sort(key=lambda x: x.priority)
# # validated_area = ValidatedArea(
# # roomId=matched_room['id'] if matched_room else None,
# # name=matched_room['name'] if matched_room else area_scope.area,
# # roomType=matched_room['roomType'] if matched_room else 'unknown',
# # matched=matched_room is not None,
# # confidence_score=round(room_confidence, 2),
# # stages=validated_stages
# # )
# # validated_areas.append(validated_area)
# # # Build summary
# # summary = {
# # 'total_areas': len(validated_areas),
# # 'total_stages': sum(len(a.stages) for a in validated_areas),
# # 'total_tasks': sum(len(s.tasks) for a in validated_areas for s in a.stages),
# # 'total_materials': sum(
# # len(t.recommended_materials)
# # for a in validated_areas
# # for s in a.stages
# # for t in s.tasks
# # ),
# # 'matched_areas': sum(1 for a in validated_areas if a.matched),
# # 'avg_confidence': round(
# # np.mean([a.confidence_score for a in validated_areas]), 2
# # ) if validated_areas else 0.0
# # }
# # return ValidatedResponse(areas=validated_areas, summary=summary)
# # # ============= API ENDPOINTS =============
# # @app.get("/")
# # async def root():
# # return {
# # "service": "Construction Scope Validator",
# # "version": "1.0.0",
# # "status": "running",
# # "data_loaded": len(db.stages) > 0,
# # "model_type": "trained" if os.path.exists('pytorch_model.bin') else "base"
# # }
# # @app.get("/health")
# # async def health():
# # return {
# # "status": "healthy",
# # "stages_loaded": len(db.stages),
# # "tasks_loaded": len(db.tasks),
# # "materials_loaded": len(db.materials),
# # "rooms_loaded": len(db.rooms),
# # "embeddings_ready": db.stage_embeddings is not None,
# # "model_type": "trained" if os.path.exists('pytorch_model.bin') else "base"
# # }
# # @app.post("/validate", response_model=ValidatedResponse)
# # async def validate_scope_endpoint(request: LLMScopeRequest):
# # """
# # Validate LLM-generated scope against database
# # Returns enriched data with:
# # - Matched stages from DB
# # - Matched tasks from DB
# # - Recommended materials with pricing
# # - Confidence scores for all matches
# # """
# # try:
# # if not db.stages:
# # raise HTTPException(status_code=500, detail="Database not loaded")
# # result = validate_scope(request)
# # return result
# # except Exception as e:
# # raise HTTPException(status_code=500, detail=f"Validation error: {str(e)}")
# # @app.post("/match-stage")
# # async def match_stage(stage_name: str):
# # """Test endpoint: match a single stage name"""
# # matched_stage, confidence = find_best_stage(stage_name)
# # if matched_stage:
# # return {
# # "input": stage_name,
# # "matched": matched_stage,
# # "confidence": round(confidence, 2)
# # }
# # return {"input": stage_name, "matched": None, "confidence": 0.0}
# # @app.post("/match-room")
# # async def match_room(room_name: str):
# # """Test endpoint: match a single room name"""
# # matched_room, confidence = find_best_room(room_name)
# # if matched_room:
# # return {
# # "input": room_name,
# # "matched": matched_room,
# # "confidence": round(confidence, 2)
# # }
# # return {"input": room_name, "matched": None, "confidence": 0.0}
# # # ============= STARTUP =============
# # @app.on_event("startup")
# # async def startup_event():
# # """Load data and initialize embeddings on startup"""
# # try:
# # print("\n" + "="*60)
# # print("STARTING UP...")
# # print("="*60)
# # # Check what files are available
# # print("\nFiles in root directory:")
# # for file in os.listdir('.'):
# # print(f" - {file}")
# # # Load data
# # db.load_data(
# # stages_file='stages.json',
# # tasks_file='tasks.json',
# # materials_file='materials.json',
# # rooms_file='rooms.json'
# # )
# # db.initialize_embeddings()
# # print("\n" + "="*60)
# # print("β
SERVICE READY!")
# # print("="*60)
# # except Exception as e:
# # print(f"\nβ STARTUP ERROR: {e}")
# # print("Make sure JSON files are in the correct location")
# # import traceback
# # traceback.print_exc()
# # if __name__ == "__main__":
# # import uvicorn
# # uvicorn.run(app, host="0.0.0.0", port=7860) |