Spaces:
Sleeping
Sleeping
File size: 113,556 Bytes
dbf6bf0 6ca3aa0 207f3d2 ec473d8 207f3d2 d2d632d dbf6bf0 85c4555 dbf6bf0 992c406 dbf6bf0 6ca3aa0 dbf6bf0 6ca3aa0 dbf6bf0 6ca3aa0 dbf6bf0 6ca3aa0 dbf6bf0 6ca3aa0 dbf6bf0 6ca3aa0 dbf6bf0 6ca3aa0 dbf6bf0 6ca3aa0 dbf6bf0 6ca3aa0 dbf6bf0 d96162f dbf6bf0 207f3d2 85c4555 207f3d2 dbf6bf0 2c7d54f 992c406 2c7d54f c055343 b5ed94f c055343 dbf6bf0 c055343 ab786cd c055343 ab786cd ffe1ef2 c055343 dbf6bf0 c055343 ab786cd c055343 ab786cd dbf6bf0 c055343 ab786cd c055343 dbf6bf0 c055343 ab786cd c055343 ab786cd c055343 ab786cd c055343 ab786cd c055343 dbf6bf0 c055343 ab786cd c055343 ab786cd c055343 ab786cd c055343 3f473a4 ffe1ef2 3f473a4 ffe1ef2 c055343 ffe1ef2 40aff38 ffe1ef2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 |
import gradio as gr
import tempfile
import shutil
from pathlib import Path
import pandas as pd
from openpyxl import load_workbook
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import FileResponse,JSONResponse
from typing import List
import uvicorn
import os
import base64
"""
Real Estate Financial Model Pipeline
Extracts data from PDFs, solves formulas with Gemini API, generates Excel
"""
from fastapi.middleware.cors import CORSMiddleware
import re
import json
from pathlib import Path
from typing import Dict, Any, List, Optional
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from pdfminer.high_level import extract_text
import google.generativeai as genai
# Add logging configuration
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class RealEstateModelPipeline:
def __init__(self, gemini_api_key: str):
"""Initialize pipeline with Gemini API key"""
genai.configure(api_key=gemini_api_key)
self.model = genai.GenerativeModel('gemini-2.0-flash')
self.extracted_data = {}
self.formula_results = {}
self.structured_data = {}
def safe_divide(self, numerator: float, denominator: float, default: float = 0) -> float:
"""Safe division that returns default instead of error"""
try:
if denominator == 0 or denominator is None:
return default
return numerator / denominator
except:
return default
def extract_pdf_text(self, pdf_path: str) -> str:
"""Extract text from PDF using pdfminer"""
try:
text = extract_text(pdf_path)
return text.strip()
except Exception as e:
print(f"Error extracting {pdf_path}: {e}")
return ""
def extract_xlsx_text(self, xlsx_path: str) -> str:
"""Extract text from XLSX using pandas and openpyxl"""
try:
extracted_content = []
# Try pandas first for data extraction
try:
xlsx = pd.ExcelFile(xlsx_path)
for sheet_name in xlsx.sheet_names:
df = pd.read_excel(xlsx, sheet_name=sheet_name)
extracted_content.append(f"=== Sheet: {sheet_name} ===")
extracted_content.append(df.to_string(index=False))
extracted_content.append("\n")
except:
pass
# Also try openpyxl for cell-level data
try:
wb = load_workbook(xlsx_path, data_only=True)
for sheet in wb.worksheets:
extracted_content.append(f"\n=== Sheet: {sheet.title} (Raw) ===")
for row in sheet.iter_rows(values_only=True):
row_text = " | ".join([str(cell) if cell is not None else "" for cell in row])
if row_text.strip():
extracted_content.append(row_text)
except:
pass
return "\n".join(extracted_content)
except Exception as e:
print(f"Error extracting {xlsx_path}: {e}")
return ""
def extract_all_pdfs(self, pdf_directory: str) -> Dict[str, str]:
"""Extract text from all PDFs and XLSX files in directory"""
pdf_dir = Path(pdf_directory)
extracted_texts = {}
with open('output_file_3.txt', "w", encoding="utf-8") as f:
# Process PDFs
for pdf_file in pdf_dir.glob("*.pdf"):
print(f"Extracting PDF: {pdf_file.name}")
text = self.extract_pdf_text(str(pdf_file))
extracted_texts[pdf_file.stem] = text
f.write(f"=== {pdf_file.name} ===\n")
f.write(text)
f.write("\n\n" + "="*80 + "\n\n")
# Process XLSX files
for xlsx_file in pdf_dir.glob("*.xlsx"):
print(f"Extracting XLSX: {xlsx_file.name}")
text = self.extract_xlsx_text(str(xlsx_file))
extracted_texts[xlsx_file.stem] = text
f.write(f"=== {xlsx_file.name} ===\n")
f.write(text)
f.write("\n\n" + "="*80 + "\n\n")
self.extracted_data = extracted_texts
return extracted_texts
def extract_address_fallback(self, pdf_texts: Dict[str, str]) -> Optional[str]:
"""Extract address using simple pattern matching as fallback"""
for name, text in pdf_texts.items():
if 'Offering_Memorandum' in name or 'offering' in name.lower():
# Pattern: "Address: <address text>"
match = re.search(r'Address:\s*(.+?)(?:\n|Property Type:)', text, re.IGNORECASE)
if match:
address = match.group(1).strip()
print(f" ✓ Extracted address via fallback: {address}")
return address
return None
def create_gemini_prompt(self, pdf_texts: Dict[str, str]) -> str:
"""Create comprehensive prompt for Gemini to extract structured data"""
# Build a clear summary of what's in each PDF
pdf_summary = "\n".join([f"- {name}: {len(text)} characters" for name, text in pdf_texts.items()])
prompt = f"""You are a real estate financial analyst. Extract ALL numerical data from the following PDF texts and return it as a JSON object.
CRITICAL INSTRUCTIONS:
1. ONLY extract data that is EXPLICITLY stated in the PDFs - DO NOT estimate or make up values
2. For missing values, use null (not 0)
3. Pay close attention to the specific document names - each contains different information
4. Extract exact numbers as they appear in the documents
AVAILABLE DOCUMENTS:
{pdf_summary}
PDF CONTENTS:
"""
for name, text in pdf_texts.items():
prompt += f"\n{'='*60}\n=== {name} ===\n{'='*60}\n{text}\n"
prompt += """
EXTRACTION INSTRUCTIONS BY DOCUMENT:
FROM "Offering_Memorandum.pdf":
- Extract: Address (full address after "Address:")
- Extract: Property Type (after "Property Type:")
- Extract: Units (number after "Units:")
FROM "Operating_Expenses_Summary.pdf" (if present):
- Extract EXACT annual amounts for:
* Real Estate Taxes
* Insurance
* Utilities
* Repairs & Maint. (or Repairs & Maintenance)
* Management Fee
* Payroll
* Administrative (if listed)
* Professional Fees (if listed)
FROM "Sales_Comps.pdf":
- Extract all Price/SF values
- Calculate average_price_per_sf = average of all Price/SF values
- Count total number of comps
FROM "Rent_Comps.pdf" (if present):
- Extract all rent values (numbers before @ symbol)
- Calculate average_rent = average of all rent values
- Count total number of rent comps
FROM "Market_Report.pdf":
- Extract: Vacancy Rate (percentage)
- Extract: Rent Growth (YoY) (percentage)
FROM "Demographics_Overview.pdf":
- Extract: Population (3-mi) - the number
- Extract: Median HH Income - the dollar amount
- Extract: Transit Score - the number
REQUIRED JSON OUTPUT STRUCTURE:
{
"property_info": {
"address": "EXTRACT FROM Offering_Memorandum.pdf",
"property_type": "EXTRACT FROM Offering_Memorandum.pdf",
"units": EXTRACT_NUMBER_FROM_Offering_Memorandum.pdf,
"gross_sf": null,
"rentable_sf": null,
"retail_sf": null
},
"acquisition": {
"land_value": null,
"price": null,
"closing_costs": null
},
"construction": {
"construction_cost_per_gsf": null,
"construction_months": null
},
"soft_costs": {
"architecture_and_interior_cost": null,
"structural_engineering_cost": null,
"mep_engineering_cost": null,
"civil_engineering_cost": null,
"controlled_inspections_cost": null,
"surveying_cost": null,
"utilities_connection_cost": null,
"advertising_and_marketing_cost": null,
"accounting_cost": null,
"monitoring_cost": null,
"ff_and_e_cost": null,
"environmental_consultant_fee": null,
"miscellaneous_consultants_fee": null,
"general_legal_cost": null,
"real_estate_taxes_during_construction": null,
"miscellaneous_admin_cost": null,
"ibr_cost": null,
"project_team_cost": null,
"pem_fees": null,
"bank_fees": null
},
"financing": {
"ltc_ratio": null,
"financing_percentage": null,
"interest_rate_basis_points": null,
"financing_cost": null,
"interest_reserve": null
},
"operating_expenses": {
"payroll": EXTRACT_FROM_Operating_Expenses_Summary.pdf,
"repairs_and_maintenance": EXTRACT_FROM_Operating_Expenses_Summary.pdf,
"utilities": EXTRACT_FROM_Operating_Expenses_Summary.pdf,
"administrative": EXTRACT_FROM_Operating_Expenses_Summary.pdf_OR_null,
"professional_fees": EXTRACT_FROM_Operating_Expenses_Summary.pdf_OR_null,
"insurance": EXTRACT_FROM_Operating_Expenses_Summary.pdf,
"property_taxes": EXTRACT_FROM_Operating_Expenses_Summary.pdf,
"management_fee_percentage": null
},
"revenue": {
"free_market_rent_psf": null,
"affordable_rent_psf": null,
"other_income_per_unit": null,
"vacancy_rate": null,
"retail_rent_psf": null,
"parking_income": null
},
"sales_comps": {
"average_price_per_sf": CALCULATE_AVERAGE_FROM_Sales_Comps.pdf,
"comp_count": COUNT_FROM_Sales_Comps.pdf
},
"rent_comps": {
"average_rent": CALCULATE_AVERAGE_FROM_Rent_Comps.pdf_IF_EXISTS,
"comp_count": COUNT_FROM_Rent_Comps.pdf_IF_EXISTS
},
"market_data": {
"vacancy_rate": EXTRACT_FROM_Market_Report.pdf,
"rent_growth_yoy": EXTRACT_FROM_Market_Report.pdf,
"median_hh_income": EXTRACT_FROM_Demographics_Overview.pdf,
"population_3mi": EXTRACT_FROM_Demographics_Overview.pdf,
"transit_score": EXTRACT_FROM_Demographics_Overview.pdf
},
"projections": {
"lease_up_months": null,
"stabilization_months": null,
"revenue_inflation_rate": null,
"expense_inflation_rate": null,
"hold_period_months": null,
"exit_cap_rate_decimal": null,
"sale_cost_percentage": null
},
"equity_structure": {
"gp_pref_rate": null,
"lp_pref_rate": null,
"promote_percentage": null
}
}
EXAMPLES OF CORRECT EXTRACTION:
Example 1 - From your Offering_Memorandum.pdf:
"Address: 455 Atlantic Ave, Brooklyn, NY"
→ "address": "455 Atlantic Ave, Brooklyn, NY"
"Property Type: Retail"
→ "property_type": "Retail"
"Units: 7"
→ "units": 7
Example 2 - From your Operating_Expenses_Summary.pdf:
"Real Estate Taxes $91940.2"
→ "property_taxes": 91940.2
"Insurance $16778.94"
→ "insurance": 16778.94
"Payroll $44948.21"
→ "payroll": 44948.21
Example 3 - From your Sales_Comps.pdf:
"Price/SF" column shows: $880, $919, $673, $894
→ "average_price_per_sf": 841.5 (average of these 4 values)
→ "comp_count": 4
Example 4 - From your Market_Report.pdf:
"Vacancy Rate: 5.71%"
→ "vacancy_rate": 0.0571
"Rent Growth (YoY): 4.18%"
→ "rent_growth_yoy": 0.0418
CRITICAL RULES:
1. Use EXACT numbers from the PDFs - don't round or modify
2. Convert percentages to decimals (5.71% → 0.0571)
3. Remove dollar signs and commas from numbers ($91,940.2 → 91940.2)
4. If a field is not in ANY PDF, use null
5. Double-check the document name before extracting - make sure you're looking at the right PDF
Return ONLY valid JSON with no explanations, comments, or markdown formatting."""
prompt += """
NOTE: Documents may be in PDF or XLSX format. For XLSX files, data is extracted sheet-by-sheet.
Look for numerical data in tables, columns, and labeled cells.
PDF AND XLSX CONTENTS:
"""
return prompt
def extract_structured_data(self) -> Dict[str, Any]:
"""Use Gemini to extract structured data from PDFs"""
print("\nProcessing with Gemini API...")
# NEW: Try simple extraction first
fallback_address = self.extract_address_fallback(self.extracted_data)
prompt = self.create_gemini_prompt(self.extracted_data)
try:
response = self.model.generate_content(prompt)
response_text = response.text.strip()
# Clean JSON if wrapped in markdown
if "```json" in response_text:
response_text = response_text.split("```json")[1].split("```")[0].strip()
elif "```" in response_text:
response_text = response_text.split("```")[1].split("```")[0].strip()
data = json.loads(response_text)
# NEW: Override with fallback if Gemini failed
if fallback_address and (not data.get('property_info', {}).get('address') or
data['property_info']['address'] == 'adress'):
data['property_info']['address'] = fallback_address
print(f" ✓ Used fallback address: {fallback_address}")
print("✓ Successfully extracted structured data")
return data
except Exception as e:
print(f"Error with Gemini API: {e}")
data = self.get_default_data_structure()
# Use fallback even in error case
if fallback_address:
data['property_info']['address'] = fallback_address
return data
def post_process_extracted_data(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""Fill in missing values with intelligent estimates"""
# Get units
units = data.get('property_info', {}).get('units', 32)
# Estimate SF if missing
if not data['property_info'].get('gross_sf'):
data['property_info']['gross_sf'] = units * 1000
if not data['property_info'].get('rentable_sf'):
data['property_info']['rentable_sf'] = int(data['property_info']['gross_sf'] * 0.85)
# Set retail_sf to 0 if None (most residential projects don't have retail)
if data['property_info'].get('retail_sf') is None:
data['property_info']['retail_sf'] = 0
# Get gross_sf for calculations
gross_sf = data['property_info']['gross_sf']
# Set default construction cost if missing
if not data['construction'].get('construction_cost_per_gsf'):
data['construction']['construction_cost_per_gsf'] = 338
if not data['construction'].get('construction_months'):
data['construction']['construction_months'] = 18
# Estimate land value from sales comps if available
if not data['acquisition'].get('land_value'):
sales_comps = data.get('sales_comps', {})
avg_psf = sales_comps.get('average_price_per_sf')
if avg_psf:
data['acquisition']['land_value'] = avg_psf * gross_sf
else:
# Use default based on typical Manhattan pricing
data['acquisition']['land_value'] = 6000000
if not data['acquisition'].get('price'):
data['acquisition']['price'] = data['acquisition']['land_value']
if not data['acquisition'].get('closing_costs'):
data['acquisition']['closing_costs'] = 150000
# Estimate soft costs as percentages if null
total_hard_cost = data['construction']['construction_cost_per_gsf'] * gross_sf
soft_cost_estimate = total_hard_cost * 0.15 # 15% of hard costs
soft_costs = data.get('soft_costs', {})
default_soft_cost_values = {
'architecture_and_interior_cost': soft_cost_estimate * 0.15,
'structural_engineering_cost': soft_cost_estimate * 0.08,
'mep_engineering_cost': soft_cost_estimate * 0.10,
'civil_engineering_cost': soft_cost_estimate * 0.05,
'controlled_inspections_cost': soft_cost_estimate * 0.03,
'surveying_cost': soft_cost_estimate * 0.02,
'utilities_connection_cost': soft_cost_estimate * 0.05,
'advertising_and_marketing_cost': soft_cost_estimate * 0.06,
'accounting_cost': soft_cost_estimate * 0.03,
'monitoring_cost': soft_cost_estimate * 0.02,
'ff_and_e_cost': soft_cost_estimate * 0.10,
'environmental_consultant_fee': soft_cost_estimate * 0.02,
'miscellaneous_consultants_fee': soft_cost_estimate * 0.03,
'general_legal_cost': soft_cost_estimate * 0.06,
'real_estate_taxes_during_construction': soft_cost_estimate * 0.10,
'miscellaneous_admin_cost': soft_cost_estimate * 0.04,
'ibr_cost': soft_cost_estimate * 0.03,
'project_team_cost': soft_cost_estimate * 0.15,
'pem_fees': soft_cost_estimate * 0.08,
'bank_fees': soft_cost_estimate * 0.05
}
for key, default_value in default_soft_cost_values.items():
if soft_costs.get(key) is None:
soft_costs[key] = default_value
# Set financing defaults if missing
financing = data.get('financing', {})
if not financing.get('ltc_ratio'):
financing['ltc_ratio'] = 0.75
if not financing.get('financing_percentage'):
financing['financing_percentage'] = 0.03
if not financing.get('interest_rate_basis_points'):
financing['interest_rate_basis_points'] = 350
if not financing.get('financing_cost'):
financing['financing_cost'] = 200000
if not financing.get('interest_reserve'):
financing['interest_reserve'] = 500000
# Set revenue defaults if missing
revenue = data.get('revenue', {})
if not revenue.get('free_market_rent_psf'):
revenue['free_market_rent_psf'] = 60
if not revenue.get('affordable_rent_psf'):
revenue['affordable_rent_psf'] = 35
if not revenue.get('other_income_per_unit'):
revenue['other_income_per_unit'] = 100
if not revenue.get('vacancy_rate'):
revenue['vacancy_rate'] = 0.05
if not revenue.get('retail_rent_psf'):
revenue['retail_rent_psf'] = 45
if not revenue.get('parking_income'):
revenue['parking_income'] = 50000
# Ensure operating expenses have defaults
op_expenses = data.get('operating_expenses', {})
if not op_expenses.get('payroll'):
op_expenses['payroll'] = 31136.07
if not op_expenses.get('repairs_and_maintenance'):
op_expenses['repairs_and_maintenance'] = 44418.61
if not op_expenses.get('utilities'):
op_expenses['utilities'] = 12535.90
if not op_expenses.get('administrative'):
op_expenses['administrative'] = 0
if not op_expenses.get('professional_fees'):
op_expenses['professional_fees'] = 18789.84
if not op_expenses.get('insurance'):
op_expenses['insurance'] = 9341.33
if not op_expenses.get('property_taxes'):
op_expenses['property_taxes'] = 118832.22
if not op_expenses.get('management_fee_percentage'):
op_expenses['management_fee_percentage'] = 0.03
# Ensure projections have defaults
projections = data.get('projections', {})
if not projections.get('lease_up_months'):
projections['lease_up_months'] = 12
if not projections.get('stabilization_months'):
projections['stabilization_months'] = 6
if not projections.get('revenue_inflation_rate'):
projections['revenue_inflation_rate'] = 0.03
if not projections.get('expense_inflation_rate'):
projections['expense_inflation_rate'] = 0.025
if not projections.get('hold_period_months'):
projections['hold_period_months'] = 60
if not projections.get('exit_cap_rate_decimal'):
projections['exit_cap_rate_decimal'] = 0.045
if not projections.get('sale_cost_percentage'):
projections['sale_cost_percentage'] = 0.02
# Ensure equity structure has defaults
equity = data.get('equity_structure', {})
if not equity.get('gp_pref_rate'):
equity['gp_pref_rate'] = 0.08
if not equity.get('lp_pref_rate'):
equity['lp_pref_rate'] = 0.08
if not equity.get('promote_percentage'):
equity['promote_percentage'] = 0.20
return data
def get_default_data_structure(self) -> Dict[str, Any]:
"""Return default data structure with known values from PDFs"""
# Try to get basic info from extracted text
units = 32 # Default from your PDFs
# Smart estimation
gross_sf = units * 1000 # Typical 1000 SF per unit
rentable_sf = int(gross_sf * 0.85) # 85% efficiency
return {
"property_info": {
"address": "adress",
"units": units,
"gross_sf": gross_sf,
"rentable_sf": rentable_sf,
"retail_sf": 0 # No retail in this project
},
"acquisition": {
"land_value": None, # Will be estimated from comps
"price": None,
"closing_costs": 150000
},
"construction": {
"construction_cost_per_gsf": 338,
"construction_months": 18
},
"soft_costs": {
"architecture_and_interior_cost": None,
"structural_engineering_cost": None,
"mep_engineering_cost": None,
"civil_engineering_cost": None,
"controlled_inspections_cost": None,
"surveying_cost": None,
"utilities_connection_cost": None,
"advertising_and_marketing_cost": None,
"accounting_cost": None,
"monitoring_cost": None,
"ff_and_e_cost": None,
"environmental_consultant_fee": None,
"miscellaneous_consultants_fee": None,
"general_legal_cost": None,
"real_estate_taxes_during_construction": None,
"miscellaneous_admin_cost": None,
"ibr_cost": None,
"project_team_cost": None,
"pem_fees": None,
"bank_fees": None
},
"financing": {
"ltc_ratio": 0.75,
"financing_percentage": 0.03,
"interest_rate_basis_points": 350,
"financing_cost": None,
"interest_reserve": None
},
"operating_expenses": {
"payroll": 31136.07, # From PDF
"repairs_and_maintenance": 44418.61,
"utilities": 12535.90,
"administrative": 0,
"professional_fees": 18789.84,
"insurance": 9341.33,
"property_taxes": 118832.22,
"management_fee_percentage": 0.03
},
"revenue": {
"free_market_rent_psf": 60,
"affordable_rent_psf": 35,
"other_income_per_unit": 100,
"vacancy_rate": 0.05,
"retail_rent_psf": 45,
"parking_income": 50000
},
"projections": {
"lease_up_months": 12,
"stabilization_months": 6,
"revenue_inflation_rate": 0.03,
"expense_inflation_rate": 0.025,
"hold_period_months": 60,
"exit_cap_rate_decimal": 0.045,
"sale_cost_percentage": 0.02
},
"equity_structure": {
"gp_pref_rate": 0.08,
"lp_pref_rate": 0.08,
"promote_percentage": 0.20
}
}
def calculate_all_formulas(self, data: Dict[str, Any]) -> Dict[str, float]:
"""Calculate all formulas in correct dependency order"""
results = {}
self.structured_data = data
# Flatten data for easier access
d = self.flatten_dict(data)
# Helper function to get value
def get(key, default=0):
value = d.get(key, default)
# CRITICAL: Convert None to default
return default if value is None else value
# def safe_multiply(a, b, default=0):
# """Safely multiply two values, handling None"""
# if a is None or b is None:
# return default
# try:
# return a * b
# except:
# return default
# BASIC PROPERTY METRICS
results['UNITS'] = get('property_info.units')
results['GROSS_SF'] = get('property_info.gross_sf')
results['RENTABLE_SF'] = get('property_info.rentable_sf')
results['RETAIL_SF'] = get('property_info.retail_sf')
results['BUILDING_EFFICIENCY'] = self.safe_divide(results['RENTABLE_SF'], results['GROSS_SF'])
# ACQUISITION COSTS
results['LAND_VALUE'] = get('acquisition.land_value')
results['PRICE'] = get('acquisition.price')
results['CLOSING_COSTS'] = get('acquisition.closing_costs')
results['ACQUISITION_FEE'] = results['LAND_VALUE'] * 0.02
results['TOTAL_ACQUISITION_COST'] = results['LAND_VALUE'] + results['CLOSING_COSTS'] + results['ACQUISITION_FEE']
# Per unit/SF metrics for acquisition
results['LAND_VALUE_PER_GSF'] = self.safe_divide(results['LAND_VALUE'], results['GROSS_SF'])
results['LAND_VALUE_PER_RSF'] = self.safe_divide(results['LAND_VALUE'], results['RENTABLE_SF'])
results['LAND_VALUE_PER_UNIT'] = self.safe_divide(results['LAND_VALUE'], results['UNITS'])
results['TOTAL_ACQUISITION_COST_PER_GSF'] = self.safe_divide(results['TOTAL_ACQUISITION_COST'], results['GROSS_SF'])
results['TOTAL_ACQUISITION_COST_PER_RSF'] = self.safe_divide(results['TOTAL_ACQUISITION_COST'], results['RENTABLE_SF'])
results['TOTAL_ACQUISITION_COST_PER_UNIT'] = self.safe_divide(results['TOTAL_ACQUISITION_COST'], results['UNITS'])
# CONSTRUCTION COSTS
results['CONSTRUCTION_COST_PER_GSF'] = get('construction.construction_cost_per_gsf')
results['CONSTRUCTION_MONTHS'] = get('construction.construction_months')
results['TOTAL_CONSTRUCTION_GMP'] = results['CONSTRUCTION_COST_PER_GSF'] * results['GROSS_SF']
results['CONSTRUCTION_GMP_PER_GSF'] = self.safe_divide(results['TOTAL_CONSTRUCTION_GMP'], results['GROSS_SF'])
results['CONSTRUCTION_GMP_PER_RSF'] = self.safe_divide(results['TOTAL_CONSTRUCTION_GMP'], results['RENTABLE_SF'])
results['CONSTRUCTION_GMP_PER_UNIT'] = self.safe_divide(results['TOTAL_CONSTRUCTION_GMP'], results['UNITS'])
# SOFT COSTS (individual items)
soft_cost_items = [
'architecture_and_interior_cost', 'structural_engineering_cost', 'mep_engineering_cost',
'civil_engineering_cost', 'controlled_inspections_cost', 'surveying_cost',
'utilities_connection_cost', 'advertising_and_marketing_cost', 'accounting_cost',
'monitoring_cost', 'ff_and_e_cost', 'environmental_consultant_fee',
'miscellaneous_consultants_fee', 'general_legal_cost', 'real_estate_taxes_during_construction',
'miscellaneous_admin_cost', 'ibr_cost', 'project_team_cost', 'pem_fees', 'bank_fees'
]
for item in soft_cost_items:
key = item.upper()
results[key] = get(f'soft_costs.{item}')
# REVENUE SETUP (needed for some soft costs)
results['FREE_MARKET_RENT_PSF'] = get('revenue.free_market_rent_psf')
results['AFFORDABLE_RENT_PSF'] = get('revenue.affordable_rent_psf')
results['OTHER_INCOME_PER_UNIT'] = get('revenue.other_income_per_unit')
results['VACANCY_RATE'] = get('revenue.vacancy_rate')
results['RETAIL_RENT_PSF'] = get('revenue.retail_rent_psf')
results['PARKING_INCOME'] = get('revenue.parking_income')
# Calculate retail revenue (needed for soft costs)
results['RETAIL_REVENUE'] = results['RETAIL_RENT_PSF'] * results['RETAIL_SF']
# HPD & IH COST
results['HPD_AND_IH_COST'] = (3500 * results['UNITS'] * 0.75) + (5000 * results['UNITS'] * 0.25)
# RETAIL TI & LC COST
results['RETAIL_TI_AND_LC_COST'] = (results['RETAIL_REVENUE'] * 0.3) + (50 * results['RETAIL_SF'])
# TOTAL SOFT COSTS
soft_cost_sum = sum([results[item.upper()] for item in soft_cost_items])
results['TOTAL_SOFT_COST'] = soft_cost_sum + results['HPD_AND_IH_COST'] + results['RETAIL_TI_AND_LC_COST']
results['TOTAL_SOFT_COST_PER_GSF'] = self.safe_divide(results['TOTAL_SOFT_COST'],results['GROSS_SF'])
# OPERATING EXPENSES (for reserves calculation)
results['PAYROLL'] = get('operating_expenses.payroll')
results['REPAIRS_AND_MAINTENANCE'] = get('operating_expenses.repairs_and_maintenance')
results['UTILITIES'] = get('operating_expenses.utilities')
results['ADMINISTRATIVE'] = get('operating_expenses.administrative')
results['PROFESSIONAL_FEES'] = get('operating_expenses.professional_fees')
results['INSURANCE'] = get('operating_expenses.insurance')
results['PROPERTY_TAXES'] = get('operating_expenses.property_taxes')
results['MANAGEMENT_FEE_PERCENTAGE'] = get('operating_expenses.management_fee_percentage')
results['TOTAL_OPERATING_EXPENSES'] = (results['PAYROLL'] + results['REPAIRS_AND_MAINTENANCE'] +
results['UTILITIES'] + results['ADMINISTRATIVE'] +
results['PROFESSIONAL_FEES'] + results['INSURANCE'] +
results['PROPERTY_TAXES'])
# CONTINGENCY & RESERVES
results['CONTINGENCY_COST'] = (results['TOTAL_CONSTRUCTION_GMP'] + results['TOTAL_SOFT_COST']) * 0.05
results['DEVELOPMENT_FEE'] = (results['TOTAL_CONSTRUCTION_GMP'] + results['TOTAL_SOFT_COST']) * 0.04
results['OPERATING_RESERVE'] = results['TOTAL_OPERATING_EXPENSES'] * 0.2
results['FINANCING_COST'] = get('financing.financing_cost')
results['INTEREST_RESERVE'] = get('financing.interest_reserve')
# TOTAL PROJECT COST (before financing)
results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'] = (
results['TOTAL_SOFT_COST'] +
results['TOTAL_CONSTRUCTION_GMP'] +
results['TOTAL_ACQUISITION_COST'] +
results['CONTINGENCY_COST'] +
results['DEVELOPMENT_FEE'] +
results['FINANCING_COST'] +
results['INTEREST_RESERVE'] +
results['OPERATING_RESERVE']
)
results['TOTAL_PROJECT_COST_PER_GSF'] = self.safe_divide(results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'], results['GROSS_SF'])
results['TOTAL_PROJECT_COST_PER_RSF'] = self.safe_divide(results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'], results['RENTABLE_SF'])
results['TOTAL_PROJECT_COST_PER_UNIT'] = self.safe_divide(results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'], results['UNITS'])
# FINANCING CALCULATIONS
results['LTC_RATIO'] = get('financing.ltc_ratio')
results['FINANCING_PERCENTAGE'] = get('financing.financing_percentage')
results['INTEREST_RATE_BASIS_POINTS'] = get('financing.interest_rate_basis_points')
results['PRE_LTC_BUDGET'] = (results['TOTAL_SOFT_COST'] + results['CONTINGENCY_COST'] +
results['DEVELOPMENT_FEE'] + results['OPERATING_RESERVE'] +
results['TOTAL_CONSTRUCTION_GMP'] + results['TOTAL_ACQUISITION_COST'])
results['LOAN_AMOUNT'] = results['LTC_RATIO'] * results['PRE_LTC_BUDGET']
results['FINANCING_AMOUNT'] = results['FINANCING_PERCENTAGE'] * results['LOAN_AMOUNT']
results['INTEREST_RATE_DECIMAL'] = (results['INTEREST_RATE_BASIS_POINTS'] + 430) / 10000
results['CONSTRUCTION_INTEREST'] = results['LOAN_AMOUNT'] * 0.7 * (results['INTEREST_RATE_DECIMAL'] / 12) * results['CONSTRUCTION_MONTHS']
# DEBT & EQUITY
results['TOTAL_DEBT'] = results['CONSTRUCTION_INTEREST'] + results['LOAN_AMOUNT'] + results['FINANCING_AMOUNT']
results['TOTAL_EQUITY'] = results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'] - results['TOTAL_DEBT']
results['DEBT_PERCENTAGE'] = results['TOTAL_DEBT'] / results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'] if results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'] > 0 else 0
results['EQUITY_PERCENTAGE'] = results['TOTAL_EQUITY'] / results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'] if results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'] > 0 else 0
results['TOTAL_CAPITAL_STACK'] = results['TOTAL_DEBT'] + results['TOTAL_EQUITY']
results['DEBT_PER_GSF'] = self.safe_divide(results['TOTAL_DEBT'],results['GROSS_SF'])
results['EQUITY_PER_GSF'] = self.safe_divide(results['TOTAL_EQUITY'],results['GROSS_SF'])
results['DEBT_PER_UNIT'] = self.safe_divide(results['TOTAL_DEBT'], results['UNITS'])
results['EQUITY_PER_UNIT'] = self.safe_divide(results['TOTAL_EQUITY'], results['UNITS'])
# OPERATING EXPENSE METRICS
results['PAYROLL_PER_UNIT'] = self.safe_divide(results['PAYROLL'], results['UNITS'])
results['REPAIRS_AND_MAINTENANCE_PER_UNIT'] = self.safe_divide(results['REPAIRS_AND_MAINTENANCE'], results['UNITS'])
results['UTILITIES_PER_UNIT'] = self.safe_divide(results['UTILITIES'], results['UNITS'])
results['ADMIN_AND_PROFESSIONAL_PER_UNIT'] = self.safe_divide((results['ADMINISTRATIVE'] + results['PROFESSIONAL_FEES']), results['UNITS'])
results['INSURANCE_PER_UNIT'] = self.safe_divide(results['INSURANCE'], results['UNITS'])
results['OPERATING_EXPENSES_PER_UNIT'] = self.safe_divide(results['TOTAL_OPERATING_EXPENSES'], results['UNITS'])
results['OPERATING_EXPENSES_PER_GSF'] = self.safe_divide(results['TOTAL_OPERATING_EXPENSES'],results['GROSS_SF'])
# REVENUE CALCULATIONS
results['LEASE_UP_MONTHS'] = get('projections.lease_up_months')
results['STABILIZATION_MONTHS'] = get('projections.stabilization_months')
results['REVENUE_INFLATION_RATE'] = get('projections.revenue_inflation_rate')
results['EXPENSE_INFLATION_RATE'] = get('projections.expense_inflation_rate')
results['TRENDING_TERM'] = results['LEASE_UP_MONTHS'] + results['STABILIZATION_MONTHS']
results['TERM_REVENUE_INFLATION'] = (1 + results['REVENUE_INFLATION_RATE']) ** (results['TRENDING_TERM'] / 12)
results['TERM_EXPENSE_INFLATION'] = (1 + results['EXPENSE_INFLATION_RATE']) ** (results['TRENDING_TERM'] / 12)
results['GROSS_POTENTIAL_FREE_MARKET_RENT'] = results['FREE_MARKET_RENT_PSF'] * 0.75 * results['RENTABLE_SF']
results['GROSS_POTENTIAL_AFFORDABLE_RENT'] = results['AFFORDABLE_RENT_PSF'] * 0.25 * results['RENTABLE_SF']
results['OTHER_INCOME'] = results['OTHER_INCOME_PER_UNIT'] * results['UNITS'] * 12 * 0.75
results['VACANCY_LOSS'] = results['VACANCY_RATE'] * (results['OTHER_INCOME'] + results['GROSS_POTENTIAL_FREE_MARKET_RENT'] + results['GROSS_POTENTIAL_AFFORDABLE_RENT'])
results['EFFECTIVE_GROSS_INCOME'] = results['GROSS_POTENTIAL_FREE_MARKET_RENT'] - results['VACANCY_LOSS'] + results['OTHER_INCOME'] + results['GROSS_POTENTIAL_AFFORDABLE_RENT']
results['MANAGEMENT_FEE'] = results['MANAGEMENT_FEE_PERCENTAGE'] * results['EFFECTIVE_GROSS_INCOME']
results['REAL_ESTATE_TAXES'] = results['GROSS_SF'] * 30 * 0.1
results['TOTAL_EXPENSES'] = results['PAYROLL'] + results['REPAIRS_AND_MAINTENANCE'] + results['UTILITIES'] + results['REAL_ESTATE_TAXES'] + results['MANAGEMENT_FEE']
# NOI & RETURNS
results['NET_OPERATING_INCOME'] = results['EFFECTIVE_GROSS_INCOME'] - results['TOTAL_EXPENSES'] + results['PARKING_INCOME'] + results['RETAIL_REVENUE']
results['NOI_PER_UNIT'] = self.safe_divide(results['NET_OPERATING_INCOME'], results['UNITS'])
results['NOI_PER_GSF'] = self.safe_divide(results['NET_OPERATING_INCOME'],results['GROSS_SF'])
results['CAP_RATE'] = (results['NET_OPERATING_INCOME'] / results['PRICE']) * 100 if results['PRICE'] > 0 else 0
results['STABILIZED_YIELD_ON_COST'] = (((results['EFFECTIVE_GROSS_INCOME'] + results['RETAIL_REVENUE'] - results['GROSS_POTENTIAL_AFFORDABLE_RENT']) * results['TERM_REVENUE_INFLATION']) - (results['TOTAL_EXPENSES'] * results['TERM_EXPENSE_INFLATION'])) + results['GROSS_POTENTIAL_AFFORDABLE_RENT']
results['YIELD_ON_COST_PERCENTAGE'] = results['NET_OPERATING_INCOME'] / results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'] if results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'] > 0 else 0
results['STABILIZED_YIELD_ON_COST_PERCENTAGE'] = results['STABILIZED_YIELD_ON_COST'] / results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'] if results['TOTAL_FINANCING_CONTINGENCY_AND_RESERVES'] > 0 else 0
results['ANNUAL_DEBT_SERVICE'] = results['LOAN_AMOUNT'] * results['INTEREST_RATE_DECIMAL']
results['CASH_ON_CASH_RETURN'] = ((results['NET_OPERATING_INCOME'] - results['ANNUAL_DEBT_SERVICE']) / results['TOTAL_EQUITY']) * 100 if results['TOTAL_EQUITY'] > 0 else 0
results['DEBT_SERVICE_COVERAGE_RATIO'] = results['NET_OPERATING_INCOME'] / results['ANNUAL_DEBT_SERVICE'] if results['ANNUAL_DEBT_SERVICE'] > 0 else 0
# EXIT & EQUITY WATERFALL
results['EXIT_CAP_RATE_DECIMAL'] = get('projections.exit_cap_rate_decimal')
results['SALE_COST_PERCENTAGE'] = get('projections.sale_cost_percentage')
results['HOLD_PERIOD_MONTHS'] = get('projections.hold_period_months')
results['PROPERTY_VALUE_ON_SALE'] = (results['STABILIZED_YIELD_ON_COST'] / results['EXIT_CAP_RATE_DECIMAL']) + (results['STABILIZED_YIELD_ON_COST'] * 0.25) if results['EXIT_CAP_RATE_DECIMAL'] > 0 else 0
results['SALE_COST'] = results['SALE_COST_PERCENTAGE'] * results['PROPERTY_VALUE_ON_SALE']
results['NET_SALE_PROCEEDS'] = results['PROPERTY_VALUE_ON_SALE'] - results['SALE_COST']
results['CASH_REMAINING_AFTER_LOAN_PAYBACK'] = results['NET_SALE_PROCEEDS'] - results['TOTAL_DEBT']
results['GP_PREF_RATE'] = get('equity_structure.gp_pref_rate')
results['LP_PREF_RATE'] = get('equity_structure.lp_pref_rate')
results['PROMOTE_PERCENTAGE'] = get('equity_structure.promote_percentage')
results['GP_INVESTMENT'] = results['TOTAL_EQUITY'] * 0.2
results['LP_INVESTMENT'] = results['TOTAL_EQUITY'] - results['GP_INVESTMENT']
results['GP_PREFERRED_RETURN_WITH_PRINCIPAL'] = (1 + results['GP_PREF_RATE'] / 12) ** results['HOLD_PERIOD_MONTHS'] * results['GP_INVESTMENT']
results['LP_PREFERRED_RETURN_WITH_PRINCIPAL'] = (1 + results['LP_PREF_RATE'] / 12) ** results['HOLD_PERIOD_MONTHS'] * results['LP_INVESTMENT']
results['CASH_REMAINING_AFTER_PREFERRED'] = results['CASH_REMAINING_AFTER_LOAN_PAYBACK'] - results['LP_PREFERRED_RETURN_WITH_PRINCIPAL'] - results['GP_PREFERRED_RETURN_WITH_PRINCIPAL']
results['PROMOTE_ON_JOINT_VENTURE'] = results['PROMOTE_PERCENTAGE'] * results['CASH_REMAINING_AFTER_PREFERRED']
results['CASH_TO_LP'] = (results['CASH_REMAINING_AFTER_PREFERRED'] - results['PROMOTE_ON_JOINT_VENTURE']) * (results['LP_INVESTMENT'] / (results['LP_INVESTMENT'] + results['GP_INVESTMENT'])) if (results['LP_INVESTMENT'] + results['GP_INVESTMENT']) > 0 else 0
results['NET_TO_LP_INVESTOR'] = results['CASH_TO_LP'] + results['LP_PREFERRED_RETURN_WITH_PRINCIPAL']
results['LP_MULTIPLE'] = results['NET_TO_LP_INVESTOR'] / results['LP_INVESTMENT'] if results['LP_INVESTMENT'] > 0 else 0
# results['IRR_TO_LP'] = ((results['NET_TO_LP_INVESTOR'] / results['LP_INVESTMENT']) ** (12 / results['HOLD_PERIOD_MONTHS']) - 1) * 100 if results['LP_INVESTMENT'] > 0 and results['HOLD_PERIOD_MONTHS'] > 0 else 0
# IRR calculation with complex number handling
if results['LP_INVESTMENT'] > 0 and results['HOLD_PERIOD_MONTHS'] > 0:
irr_base = results['NET_TO_LP_INVESTOR'] / results['LP_INVESTMENT']
if irr_base > 0:
results['IRR_TO_LP'] = ((irr_base) ** (12 / results['HOLD_PERIOD_MONTHS']) - 1) * 100
else:
results['IRR_TO_LP'] = -100 # Total loss
else:
results['IRR_TO_LP'] = 0
# BLENDED RENT CALCULATIONS
results['BLENDED_RENT_PER_RSF'] = (results['FREE_MARKET_RENT_PSF'] * 0.75) + (results['AFFORDABLE_RENT_PSF'] * 0.25)
results['TOTAL_FREE_MARKET_RENT'] = results['FREE_MARKET_RENT_PSF'] * 425 / 12
results['TOTAL_BLENDED_RENT'] = results['BLENDED_RENT_PER_RSF'] * 750 / 12
results['FREE_MARKET_RENT_PER_SF'] = results['TOTAL_FREE_MARKET_RENT'] * 110 / 12
results['AFFORDABLE_RENT_PER_SF'] = results['AFFORDABLE_RENT_PSF'] * 110 / 12
results['BLENDED_RENT_PER_SF'] = results['TOTAL_BLENDED_RENT'] * 110 / 12
results['AVERAGE_RENT_PER_UNIT'] = self.safe_divide((results['GROSS_POTENTIAL_FREE_MARKET_RENT']+results['GROSS_POTENTIAL_AFFORDABLE_RENT']), results['UNITS'])
results['RENT_PER_UNIT_PER_MONTH'] = results['AVERAGE_RENT_PER_UNIT'] / 12
# EGI PERCENTAGES
if results['EFFECTIVE_GROSS_INCOME'] > 0:
results['PAYROLL_PERCENTAGE_OF_EGI'] = results['PAYROLL'] / results['EFFECTIVE_GROSS_INCOME']
results['REPAIRS_AND_MAINTENANCE_PERCENTAGE_OF_EGI'] = results['REPAIRS_AND_MAINTENANCE'] / results['EFFECTIVE_GROSS_INCOME']
results['UTILITIES_PERCENTAGE_OF_EGI'] = results['UTILITIES'] / results['EFFECTIVE_GROSS_INCOME']
results['ADMIN_AND_PROFESSIONAL_PERCENTAGE_OF_EGI'] = (results['ADMINISTRATIVE'] + results['PROFESSIONAL_FEES']) / results['EFFECTIVE_GROSS_INCOME']
results['INSURANCE_PERCENTAGE_OF_EGI'] = results['INSURANCE'] / results['EFFECTIVE_GROSS_INCOME']
results['PROFESSIONAL_FEES_PERCENTAGE_OF_EGI'] = results['PROFESSIONAL_FEES'] / results['EFFECTIVE_GROSS_INCOME']
results['TOTAL_OPERATING_EXPENSES_PERCENTAGE_OF_EGI'] = results['TOTAL_OPERATING_EXPENSES'] / results['EFFECTIVE_GROSS_INCOME']
else:
results['PAYROLL_PERCENTAGE_OF_EGI'] = 0
results['REPAIRS_AND_MAINTENANCE_PERCENTAGE_OF_EGI'] = 0
results['UTILITIES_PERCENTAGE_OF_EGI'] = 0
results['ADMIN_AND_PROFESSIONAL_PERCENTAGE_OF_EGI'] = 0
results['INSURANCE_PERCENTAGE_OF_EGI'] = 0
results['PROFESSIONAL_FEES_PERCENTAGE_OF_EGI'] = 0
results['TOTAL_OPERATING_EXPENSES_PERCENTAGE_OF_EGI'] = 0
self.formula_results = results
return results
def flatten_dict(self, d: Dict[str, Any], parent_key: str = '', sep: str = '.') -> Dict[str, Any]:
"""Flatten nested dictionary"""
items = []
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.extend(self.flatten_dict(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
def generate_excel(self, output_path: str = "Real_Estate_Financial_Model.xlsx"):
"""Generate professional Excel file with all calculations"""
try:
# Validate critical values before Excel generation
r = self.formula_results
print(" Validating calculations...")
critical_values = {
'UNITS': r.get('UNITS', 0),
'GROSS_SF': r.get('GROSS_SF', 0),
'RENTABLE_SF': r.get('RENTABLE_SF', 0),
'EFFECTIVE_GROSS_INCOME': r.get('EFFECTIVE_GROSS_INCOME', 0),
'TOTAL_PROJECT_COST': r.get('TOTAL_FINANCING_CONTINGENCY_AND_RESERVES', 0)
}
warnings = []
for key, value in critical_values.items():
if value == 0:
warnings.append(f" WARNING: {key} is zero or missing")
if warnings:
print("\n".join(warnings))
print(" Continuing with available data...\n")
wb = openpyxl.Workbook()
# Remove default sheet
if 'Sheet' in wb.sheetnames:
wb.remove(wb['Sheet'])
# Create sheets with error handling
print(" Creating Executive Summary...")
self.create_summary_sheet(wb)
print(" Creating Acquisition sheet...")
self.create_acquisition_sheet(wb)
print(" Creating Construction sheet...")
self.create_construction_sheet(wb)
print(" Creating Soft Costs sheet...")
self.create_soft_costs_sheet(wb)
print(" Creating Financing sheet...")
self.create_financing_sheet(wb)
print(" Creating Operations sheet...")
self.create_operations_sheet(wb)
print(" Creating Returns sheet...")
self.create_returns_sheet(wb)
# Save workbook
wb.save(output_path)
print(f"✓ Excel file generated: {output_path}")
return output_path
except Exception as e:
print(f"ERROR generating Excel: {e}")
import traceback
traceback.print_exc()
raise
def create_summary_sheet(self, wb):
"""Create executive summary sheet"""
ws = wb.create_sheet("Executive Summary", 0)
# Styles
header_fill = PatternFill(start_color="1F4E78", end_color="1F4E78", fill_type="solid")
header_font = Font(color="FFFFFF", bold=True, size=12)
subheader_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
subheader_font = Font(color="FFFFFF", bold=True, size=11)
r = self.formula_results
# Title
ws['A1'] = "REAL ESTATE DEVELOPMENT FINANCIAL MODEL"
ws['A1'].font = Font(bold=True, size=16)
ws.merge_cells('A1:D1')
# Property Information
row = 3
ws[f'A{row}'] = "PROPERTY INFORMATION"
ws[f'A{row}'].fill = header_fill
ws[f'A{row}'].font = header_font
ws.merge_cells(f'A{row}:D{row}')
address = self.structured_data.get('property_info', {}).get('address', 'N/A')
row += 1
data = [
("Address:", address),
("Units:", r.get('UNITS', 0)),
("Gross Square Feet:", f"{r.get('GROSS_SF', 0):,.0f}"),
("Rentable Square Feet:", f"{r.get('RENTABLE_SF', 0):,.0f}"),
("Building Efficiency:", f"{r.get('BUILDING_EFFICIENCY', 0):.2%}"),
]
for label, value in data:
ws[f'A{row}'] = label
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = value
row += 1
# Project Costs Summary
row += 1
ws[f'A{row}'] = "PROJECT COSTS SUMMARY"
ws[f'A{row}'].fill = header_fill
ws[f'A{row}'].font = header_font
ws.merge_cells(f'A{row}:D{row}')
row += 1
ws[f'A{row}'] = "Category"
ws[f'B{row}'] = "Total Cost"
ws[f'C{row}'] = "Per GSF"
ws[f'D{row}'] = "Per Unit"
for col in ['A', 'B', 'C', 'D']:
ws[f'{col}{row}'].fill = subheader_fill
ws[f'{col}{row}'].font = subheader_font
row += 1
cost_summary = [
("Acquisition", r.get('TOTAL_ACQUISITION_COST', 0), r.get('TOTAL_ACQUISITION_COST_PER_GSF', 0), r.get('TOTAL_ACQUISITION_COST_PER_UNIT', 0)),
("Construction", r.get('TOTAL_CONSTRUCTION_GMP', 0), r.get('CONSTRUCTION_GMP_PER_GSF', 0), r.get('CONSTRUCTION_GMP_PER_UNIT', 0)),
("Soft Costs", r.get('TOTAL_SOFT_COST', 0), r.get('TOTAL_SOFT_COST_PER_GSF', 0), r.get('TOTAL_SOFT_COST_PER_GSF', 0) * r.get('GROSS_SF', 0) / r.get('UNITS', 1)),
("Contingency", r.get('CONTINGENCY_COST', 0), r.get('CONTINGENCY_COST', 0) / r.get('GROSS_SF', 1), r.get('CONTINGENCY_COST', 0) / r.get('UNITS', 1)),
("Development Fee", r.get('DEVELOPMENT_FEE', 0), r.get('DEVELOPMENT_FEE', 0) / r.get('GROSS_SF', 1), r.get('DEVELOPMENT_FEE', 0) / r.get('UNITS', 1)),
("Financing & Reserves", r.get('FINANCING_COST', 0) + r.get('INTEREST_RESERVE', 0) + r.get('OPERATING_RESERVE', 0), 0, 0),
]
for label, total, per_gsf, per_unit in cost_summary:
ws[f'A{row}'] = label
ws[f'B{row}'] = total
ws[f'B{row}'].number_format = '$#,##0'
ws[f'C{row}'] = per_gsf
ws[f'C{row}'].number_format = '$#,##0.00'
ws[f'D{row}'] = per_unit
ws[f'D{row}'].number_format = '$#,##0'
row += 1
# Total
ws[f'A{row}'] = "TOTAL PROJECT COST"
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = r.get('TOTAL_FINANCING_CONTINGENCY_AND_RESERVES', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'B{row}'].font = Font(bold=True)
ws[f'C{row}'] = r.get('TOTAL_PROJECT_COST_PER_GSF', 0)
ws[f'C{row}'].number_format = '$#,##0.00'
ws[f'C{row}'].font = Font(bold=True)
ws[f'D{row}'] = r.get('TOTAL_PROJECT_COST_PER_UNIT', 0)
ws[f'D{row}'].number_format = '$#,##0'
ws[f'D{row}'].font = Font(bold=True)
# Capital Stack
row += 2
ws[f'A{row}'] = "CAPITAL STACK"
ws[f'A{row}'].fill = header_fill
ws[f'A{row}'].font = header_font
ws.merge_cells(f'A{row}:D{row}')
row += 1
ws[f'A{row}'] = "Source"
ws[f'B{row}'] = "Amount"
ws[f'C{row}'] = "Percentage"
ws[f'D{row}'] = "Per Unit"
for col in ['A', 'B', 'C', 'D']:
ws[f'{col}{row}'].fill = subheader_fill
ws[f'{col}{row}'].font = subheader_font
row += 1
ws[f'A{row}'] = "Total Debt"
ws[f'B{row}'] = r.get('TOTAL_DEBT', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'C{row}'] = r.get('DEBT_PERCENTAGE', 0)
ws[f'C{row}'].number_format = '0.00%'
ws[f'D{row}'] = r.get('DEBT_PER_UNIT', 0)
ws[f'D{row}'].number_format = '$#,##0'
row += 1
ws[f'A{row}'] = "Total Equity"
ws[f'B{row}'] = r.get('TOTAL_EQUITY', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'C{row}'] = r.get('EQUITY_PERCENTAGE', 0)
ws[f'C{row}'].number_format = '0.00%'
ws[f'D{row}'] = r.get('EQUITY_PER_UNIT', 0)
ws[f'D{row}'].number_format = '$#,##0'
# Returns Summary
row += 2
ws[f'A{row}'] = "INVESTMENT RETURNS"
ws[f'A{row}'].fill = header_fill
ws[f'A{row}'].font = header_font
ws.merge_cells(f'A{row}:D{row}')
row += 1
returns_data = [
("Stabilized NOI:", f"${r.get('NET_OPERATING_INCOME', 0):,.0f}"),
("Yield on Cost:", f"{r.get('YIELD_ON_COST_PERCENTAGE', 0):.2%}"),
("Stabilized Yield on Cost:", f"{r.get('STABILIZED_YIELD_ON_COST_PERCENTAGE', 0):.2%}"),
("Cash-on-Cash Return:", f"{r.get('CASH_ON_CASH_RETURN', 0):.2f}%"),
("DSCR:", f"{r.get('DEBT_SERVICE_COVERAGE_RATIO', 0):.2f}x"),
("LP IRR:", f"{float(r.get('IRR_TO_LP', 0).real if isinstance(r.get('IRR_TO_LP', 0), complex) else r.get('IRR_TO_LP', 0)):.2f}%"),
("LP Multiple:", f"{r.get('LP_MULTIPLE', 0):.2f}x"),
]
for label, value in returns_data:
ws[f'A{row}'] = label
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = value
row += 1
# Adjust column widths
ws.column_dimensions['A'].width = 25
ws.column_dimensions['B'].width = 18
ws.column_dimensions['C'].width = 15
ws.column_dimensions['D'].width = 15
def create_acquisition_sheet(self, wb):
"""Create acquisition costs detail sheet"""
ws = wb.create_sheet("Acquisition")
r = self.formula_results
# Header
ws['A1'] = "ACQUISITION COSTS"
ws['A1'].font = Font(bold=True, size=14)
ws.merge_cells('A1:E1')
# Column headers
row = 3
headers = ["Item", "Total Cost", "Per GSF", "Per RSF", "Per Unit"]
for col_idx, header in enumerate(headers, start=1):
cell = ws.cell(row=row, column=col_idx, value=header)
cell.fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
cell.font = Font(color="FFFFFF", bold=True)
# Data
row += 1
data = [
("Land Value", r.get('LAND_VALUE', 0), r.get('LAND_VALUE_PER_GSF', 0), r.get('LAND_VALUE_PER_RSF', 0), r.get('LAND_VALUE_PER_UNIT', 0)),
("Closing Costs", r.get('CLOSING_COSTS', 0), r.get('CLOSING_COSTS', 0) / r.get('GROSS_SF', 1), r.get('CLOSING_COSTS', 0) / r.get('RENTABLE_SF', 1), r.get('CLOSING_COSTS', 0) / r.get('UNITS', 1)),
("Acquisition Fee (2%)", r.get('ACQUISITION_FEE', 0), r.get('ACQUISITION_FEE', 0) / r.get('GROSS_SF', 1), r.get('ACQUISITION_FEE', 0) / r.get('RENTABLE_SF', 1), r.get('ACQUISITION_FEE', 0) / r.get('UNITS', 1)),
]
for item, total, per_gsf, per_rsf, per_unit in data:
ws.cell(row=row, column=1, value=item)
ws.cell(row=row, column=2, value=total).number_format = '$#,##0'
ws.cell(row=row, column=3, value=per_gsf).number_format = '$#,##0.00'
ws.cell(row=row, column=4, value=per_rsf).number_format = '$#,##0.00'
ws.cell(row=row, column=5, value=per_unit).number_format = '$#,##0'
row += 1
# Total
ws.cell(row=row, column=1, value="TOTAL ACQUISITION COST").font = Font(bold=True)
ws.cell(row=row, column=2, value=r.get('TOTAL_ACQUISITION_COST', 0)).number_format = '$#,##0'
ws.cell(row=row, column=2).font = Font(bold=True)
ws.cell(row=row, column=3, value=r.get('TOTAL_ACQUISITION_COST_PER_GSF', 0)).number_format = '$#,##0.00'
ws.cell(row=row, column=3).font = Font(bold=True)
ws.cell(row=row, column=4, value=r.get('TOTAL_ACQUISITION_COST_PER_RSF', 0)).number_format = '$#,##0.00'
ws.cell(row=row, column=4).font = Font(bold=True)
ws.cell(row=row, column=5, value=r.get('TOTAL_ACQUISITION_COST_PER_UNIT', 0)).number_format = '$#,##0'
ws.cell(row=row, column=5).font = Font(bold=True)
# Adjust widths
for col in range(1, 6):
ws.column_dimensions[get_column_letter(col)].width = 20
def create_construction_sheet(self, wb):
"""Create construction costs sheet"""
ws = wb.create_sheet("Construction")
r = self.formula_results
ws['A1'] = "CONSTRUCTION COSTS"
ws['A1'].font = Font(bold=True, size=14)
row = 3
ws[f'A{row}'] = "Construction Cost per GSF:"
ws[f'B{row}'] = r.get('CONSTRUCTION_COST_PER_GSF', 0)
ws[f'B{row}'].number_format = '$#,##0.00'
row += 1
ws[f'A{row}'] = "Gross Square Feet:"
ws[f'B{row}'] = r.get('GROSS_SF', 0)
ws[f'B{row}'].number_format = '#,##0'
row += 2
ws[f'A{row}'] = "Total Construction GMP:"
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = r.get('TOTAL_CONSTRUCTION_GMP', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'B{row}'].font = Font(bold=True)
row += 2
ws[f'A{row}'] = "Construction Duration:"
ws[f'B{row}'] = f"{r.get('CONSTRUCTION_MONTHS', 0)} months"
ws.column_dimensions['A'].width = 30
ws.column_dimensions['B'].width = 20
def create_soft_costs_sheet(self, wb):
"""Create soft costs detail sheet"""
ws = wb.create_sheet("Soft Costs")
r = self.formula_results
ws['A1'] = "SOFT COSTS BUDGET"
ws['A1'].font = Font(bold=True, size=14)
row = 3
headers = ["Category", "Total Cost", "Per GSF"]
for col_idx, header in enumerate(headers, start=1):
cell = ws.cell(row=row, column=col_idx, value=header)
cell.fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
cell.font = Font(color="FFFFFF", bold=True)
row += 1
soft_cost_items = [
("Architecture & Interior Design", 'ARCHITECTURE_AND_INTERIOR_COST'),
("Structural Engineering", 'STRUCTURAL_ENGINEERING_COST'),
("MEP Engineering", 'MEP_ENGINEERING_COST'),
("Civil Engineering", 'CIVIL_ENGINEERING_COST'),
("Controlled Inspections", 'CONTROLLED_INSPECTIONS_COST'),
("Surveying", 'SURVEYING_COST'),
("Utilities Connection", 'UTILITIES_CONNECTION_COST'),
("Advertising & Marketing", 'ADVERTISING_AND_MARKETING_COST'),
("Accounting", 'ACCOUNTING_COST'),
("Monitoring", 'MONITORING_COST'),
("FF&E", 'FF_AND_E_COST'),
("Environmental Consultant", 'ENVIRONMENTAL_CONSULTANT_FEE'),
("Miscellaneous Consultants", 'MISCELLANEOUS_CONSULTANTS_FEE'),
("General Legal", 'GENERAL_LEGAL_COST'),
("RE Taxes During Construction", 'REAL_ESTATE_TAXES_DURING_CONSTRUCTION'),
("Miscellaneous Admin", 'MISCELLANEOUS_ADMIN_COST'),
("IBR Cost", 'IBR_COST'),
("Project Team", 'PROJECT_TEAM_COST'),
("PEM Fees", 'PEM_FEES'),
("Bank Fees", 'BANK_FEES'),
("HPD & IH Costs", 'HPD_AND_IH_COST'),
("Retail TI & LC", 'RETAIL_TI_AND_LC_COST'),
]
for label, key in soft_cost_items:
cost = r.get(key, 0)
per_gsf = cost / r.get('GROSS_SF', 1) if r.get('GROSS_SF', 0) > 0 else 0
ws.cell(row=row, column=1, value=label)
ws.cell(row=row, column=2, value=cost).number_format = '$#,##0'
ws.cell(row=row, column=3, value=per_gsf).number_format = '$#,##0.00'
row += 1
# Total
ws.cell(row=row, column=1, value="TOTAL SOFT COSTS").font = Font(bold=True)
ws.cell(row=row, column=2, value=r.get('TOTAL_SOFT_COST', 0)).number_format = '$#,##0'
ws.cell(row=row, column=2).font = Font(bold=True)
ws.cell(row=row, column=3, value=r.get('TOTAL_SOFT_COST_PER_GSF', 0)).number_format = '$#,##0.00'
ws.cell(row=row, column=3).font = Font(bold=True)
ws.column_dimensions['A'].width = 35
ws.column_dimensions['B'].width = 18
ws.column_dimensions['C'].width = 15
def create_financing_sheet(self, wb):
"""Create financing structure sheet"""
ws = wb.create_sheet("Financing")
r = self.formula_results
ws['A1'] = "FINANCING STRUCTURE"
ws['A1'].font = Font(bold=True, size=14)
row = 3
ws[f'A{row}'] = "Pre-LTC Budget:"
ws[f'B{row}'] = r.get('PRE_LTC_BUDGET', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 1
ws[f'A{row}'] = "LTC Ratio:"
ws[f'B{row}'] = r.get('LTC_RATIO', 0)
ws[f'B{row}'].number_format = '0.00%'
row += 1
ws[f'A{row}'] = "Loan Amount:"
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = r.get('LOAN_AMOUNT', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'B{row}'].font = Font(bold=True)
row += 2
ws[f'A{row}'] = "Financing Percentage:"
ws[f'B{row}'] = r.get('FINANCING_PERCENTAGE', 0)
ws[f'B{row}'].number_format = '0.00%'
row += 1
ws[f'A{row}'] = "Financing Amount:"
ws[f'B{row}'] = r.get('FINANCING_AMOUNT', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 2
ws[f'A{row}'] = "Interest Rate (bps + spread):"
ws[f'B{row}'] = r.get('INTEREST_RATE_DECIMAL', 0)
ws[f'B{row}'].number_format = '0.00%'
row += 1
ws[f'A{row}'] = "Construction Interest:"
ws[f'B{row}'] = r.get('CONSTRUCTION_INTEREST', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 2
ws[f'A{row}'] = "TOTAL DEBT"
ws[f'A{row}'].font = Font(bold=True, size=12)
ws[f'B{row}'] = r.get('TOTAL_DEBT', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'B{row}'].font = Font(bold=True, size=12)
row += 1
ws[f'A{row}'] = "TOTAL EQUITY"
ws[f'A{row}'].font = Font(bold=True, size=12)
ws[f'B{row}'] = r.get('TOTAL_EQUITY', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'B{row}'].font = Font(bold=True, size=12)
row += 2
ws[f'A{row}'] = "Debt Percentage:"
ws[f'B{row}'] = r.get('DEBT_PERCENTAGE', 0)
ws[f'B{row}'].number_format = '0.00%'
row += 1
ws[f'A{row}'] = "Equity Percentage:"
ws[f'B{row}'] = r.get('EQUITY_PERCENTAGE', 0)
ws[f'B{row}'].number_format = '0.00%'
ws.column_dimensions['A'].width = 35
ws.column_dimensions['B'].width = 20
def create_operations_sheet(self, wb):
"""Create operations and revenue sheet"""
ws = wb.create_sheet("Operations")
r = self.formula_results
ws['A1'] = "OPERATIONS & REVENUE"
ws['A1'].font = Font(bold=True, size=14)
# Revenue Section
row = 3
ws[f'A{row}'] = "REVENUE"
ws[f'A{row}'].fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
ws[f'A{row}'].font = Font(color="FFFFFF", bold=True)
ws.merge_cells(f'A{row}:B{row}')
row += 1
revenue_items = [
("Gross Potential Free Market Rent", r.get('GROSS_POTENTIAL_FREE_MARKET_RENT', 0)),
("Gross Potential Affordable Rent", r.get('GROSS_POTENTIAL_AFFORDABLE_RENT', 0)),
("Other Income", r.get('OTHER_INCOME', 0)),
("Less: Vacancy Loss", -r.get('VACANCY_LOSS', 0)),
("Effective Gross Income", r.get('EFFECTIVE_GROSS_INCOME', 0)),
("Parking Income", r.get('PARKING_INCOME', 0)),
("Retail Revenue", r.get('RETAIL_REVENUE', 0)),
]
for label, value in revenue_items:
ws[f'A{row}'] = label
if "Effective Gross" in label:
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = value
ws[f'B{row}'].number_format = '$#,##0'
row += 1
# Expense Section
row += 1
ws[f'A{row}'] = "OPERATING EXPENSES"
ws[f'A{row}'].fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
ws[f'A{row}'].font = Font(color="FFFFFF", bold=True)
ws.merge_cells(f'A{row}:C{row}')
row += 1
ws[f'A{row}'] = "Expense Category"
ws[f'B{row}'] = "Annual Amount"
ws[f'C{row}'] = "% of EGI"
for col in ['A', 'B', 'C']:
ws[f'{col}{row}'].font = Font(bold=True)
row += 1
# Safe division helper
egi = r.get('EFFECTIVE_GROSS_INCOME', 0)
def safe_pct(value):
return value / egi if egi > 0 else 0
expense_items = [
("Payroll", r.get('PAYROLL', 0), r.get('PAYROLL_PERCENTAGE_OF_EGI', 0)),
("Repairs & Maintenance", r.get('REPAIRS_AND_MAINTENANCE', 0), r.get('REPAIRS_AND_MAINTENANCE_PERCENTAGE_OF_EGI', 0)),
("Utilities", r.get('UTILITIES', 0), r.get('UTILITIES_PERCENTAGE_OF_EGI', 0)),
("Insurance", r.get('INSURANCE', 0), r.get('INSURANCE_PERCENTAGE_OF_EGI', 0)),
("Management Fee", r.get('MANAGEMENT_FEE', 0), safe_pct(r.get('MANAGEMENT_FEE', 0))),
("Real Estate Taxes", r.get('REAL_ESTATE_TAXES', 0), safe_pct(r.get('REAL_ESTATE_TAXES', 0))),
]
for label, amount, pct in expense_items:
ws[f'A{row}'] = label
ws[f'B{row}'] = amount
ws[f'B{row}'].number_format = '$#,##0'
ws[f'C{row}'] = pct
ws[f'C{row}'].number_format = '0.00%'
row += 1
ws[f'A{row}'] = "TOTAL EXPENSES"
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = r.get('TOTAL_EXPENSES', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'B{row}'].font = Font(bold=True)
total_exp_pct = safe_pct(r.get('TOTAL_EXPENSES', 0))
ws[f'C{row}'] = total_exp_pct
ws[f'C{row}'].number_format = '0.00%'
ws[f'C{row}'].font = Font(bold=True)
row += 2
ws[f'A{row}'] = "NET OPERATING INCOME"
ws[f'A{row}'].font = Font(bold=True, size=12)
ws[f'B{row}'] = r.get('NET_OPERATING_INCOME', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'B{row}'].font = Font(bold=True, size=12)
row += 2
ws[f'A{row}'] = "NOI per Unit:"
ws[f'B{row}'] = r.get('NOI_PER_UNIT', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 1
ws[f'A{row}'] = "NOI per GSF:"
ws[f'B{row}'] = r.get('NOI_PER_GSF', 0)
ws[f'B{row}'].number_format = '$#,##0.00'
ws.column_dimensions['A'].width = 35
ws.column_dimensions['B'].width = 20
ws.column_dimensions['C'].width = 15
def create_returns_sheet(self, wb):
"""Create investment returns and waterfall sheet"""
ws = wb.create_sheet("Returns")
r = self.formula_results
ws['A1'] = "INVESTMENT RETURNS & EXIT ANALYSIS"
ws['A1'].font = Font(bold=True, size=14)
# Current Returns
row = 3
ws[f'A{row}'] = "STABILIZED RETURNS"
ws[f'A{row}'].fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
ws[f'A{row}'].font = Font(color="FFFFFF", bold=True)
ws.merge_cells(f'A{row}:B{row}')
row += 1
returns_data = [
("Net Operating Income", f"${r.get('NET_OPERATING_INCOME', 0):,.0f}"),
("Stabilized Yield on Cost", f"${r.get('STABILIZED_YIELD_ON_COST', 0):,.0f}"),
("Yield on Cost %", f"{r.get('YIELD_ON_COST_PERCENTAGE', 0):.2%}"),
("Stabilized Yield on Cost %", f"{r.get('STABILIZED_YIELD_ON_COST_PERCENTAGE', 0):.2%}"),
("Annual Debt Service", f"${r.get('ANNUAL_DEBT_SERVICE', 0):,.0f}"),
("Cash-on-Cash Return", f"{r.get('CASH_ON_CASH_RETURN', 0):.2f}%"),
("Debt Service Coverage Ratio", f"{r.get('DEBT_SERVICE_COVERAGE_RATIO', 0):.2f}x"),
]
for label, value in returns_data:
ws[f'A{row}'] = label
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = value
row += 1
# Exit Analysis
row += 2
ws[f'A{row}'] = "EXIT ANALYSIS"
ws[f'A{row}'].fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
ws[f'A{row}'].font = Font(color="FFFFFF", bold=True)
ws.merge_cells(f'A{row}:B{row}')
row += 1
ws[f'A{row}'] = "Hold Period (months):"
ws[f'B{row}'] = r.get('HOLD_PERIOD_MONTHS', 0)
row += 1
ws[f'A{row}'] = "Exit Cap Rate:"
ws[f'B{row}'] = r.get('EXIT_CAP_RATE_DECIMAL', 0)
ws[f'B{row}'].number_format = '0.00%'
row += 1
ws[f'A{row}'] = "Property Value on Sale:"
ws[f'B{row}'] = r.get('PROPERTY_VALUE_ON_SALE', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 1
ws[f'A{row}'] = "Less: Sale Costs (2%):"
ws[f'B{row}'] = -r.get('SALE_COST', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 1
ws[f'A{row}'] = "Net Sale Proceeds:"
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = r.get('NET_SALE_PROCEEDS', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'B{row}'].font = Font(bold=True)
row += 1
ws[f'A{row}'] = "Less: Loan Payoff:"
ws[f'B{row}'] = -r.get('TOTAL_DEBT', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 1
ws[f'A{row}'] = "Cash After Loan Payback:"
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = r.get('CASH_REMAINING_AFTER_LOAN_PAYBACK', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'B{row}'].font = Font(bold=True)
# Equity Waterfall
row += 2
ws[f'A{row}'] = "EQUITY WATERFALL"
ws[f'A{row}'].fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
ws[f'A{row}'].font = Font(color="FFFFFF", bold=True)
ws.merge_cells(f'A{row}:B{row}')
row += 1
ws[f'A{row}'] = "GP Investment (20%):"
ws[f'B{row}'] = r.get('GP_INVESTMENT', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 1
ws[f'A{row}'] = "LP Investment (80%):"
ws[f'B{row}'] = r.get('LP_INVESTMENT', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 2
ws[f'A{row}'] = "GP Preferred Return + Principal:"
ws[f'B{row}'] = r.get('GP_PREFERRED_RETURN_WITH_PRINCIPAL', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 1
ws[f'A{row}'] = "LP Preferred Return + Principal:"
ws[f'B{row}'] = r.get('LP_PREFERRED_RETURN_WITH_PRINCIPAL', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 1
ws[f'A{row}'] = "Cash After Preferred:"
ws[f'B{row}'] = r.get('CASH_REMAINING_AFTER_PREFERRED', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 2
ws[f'A{row}'] = "GP Promote (20%):"
ws[f'B{row}'] = r.get('PROMOTE_ON_JOINT_VENTURE', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 1
ws[f'A{row}'] = "Cash to LP:"
ws[f'B{row}'] = r.get('CASH_TO_LP', 0)
ws[f'B{row}'].number_format = '$#,##0'
row += 2
ws[f'A{row}'] = "NET TO LP INVESTOR"
ws[f'A{row}'].font = Font(bold=True, size=12)
ws[f'B{row}'] = r.get('NET_TO_LP_INVESTOR', 0)
ws[f'B{row}'].number_format = '$#,##0'
ws[f'B{row}'].font = Font(bold=True, size=12)
row += 2
ws[f'A{row}'] = "LP Multiple:"
ws[f'A{row}'].font = Font(bold=True)
ws[f'B{row}'] = r.get('LP_MULTIPLE', 0)
ws[f'B{row}'].number_format = '0.00x'
ws[f'B{row}'].font = Font(bold=True)
row += 1
ws[f'A{row}'] = "LP IRR:"
ws[f'A{row}'].font = Font(bold=True)
irr_value = r.get('IRR_TO_LP', 0)
# Handle complex numbers or invalid values
if isinstance(irr_value, complex):
irr_value = 0 # or use irr_value.real if you want the real component
ws[f'B{row}'] = irr_value / 100
ws[f'B{row}'].number_format = '0.00%'
ws[f'B{row}'].font = Font(bold=True)
ws.column_dimensions['A'].width = 35
ws.column_dimensions['B'].width = 20
def run_full_pipeline(self, pdf_directory: str, output_excel: str = "Real_Estate_Financial_Model.xlsx"):
"""Execute complete pipeline"""
print("=" * 60)
print("REAL ESTATE FINANCIAL MODEL PIPELINE")
print("=" * 60)
# Step 1: Extract PDFs
print("\n[Step 1/4] Extracting text from PDFs...")
self.extract_all_pdfs(pdf_directory)
print(f"✓ Extracted {len(self.extracted_data)} PDF files")
# Step 2: Process with Gemini
print("\n[Step 2/4] Extracting structured data with Gemini API...")
structured_data = self.extract_structured_data()
# NEW: Post-process to fill gaps
print("\n[Step 2.5/4] Post-processing and filling estimates...")
structured_data = self.post_process_extracted_data(structured_data)
# Step 3: Calculate formulas
print("\n[Step 3/4] Calculating all formulas...")
self.calculate_all_formulas(structured_data)
print(f"✓ Calculated {len(self.formula_results)} formula values")
# Step 4: Generate Excel
print("\n[Step 4/4] Generating Excel file...")
self.generate_excel(output_excel)
print("\n" + "=" * 60)
print("PIPELINE COMPLETE!")
print("=" * 60)
print(f"\nKey Metrics:")
print(f" Total Project Cost: ${self.formula_results.get('TOTAL_FINANCING_CONTINGENCY_AND_RESERVES', 0):,.0f}")
print(f" Total Debt: ${self.formula_results.get('TOTAL_DEBT', 0):,.0f}")
print(f" Total Equity: ${self.formula_results.get('TOTAL_EQUITY', 0):,.0f}")
print(f" NOI: ${self.formula_results.get('NET_OPERATING_INCOME', 0):,.0f}")
print(f" Yield on Cost: {self.formula_results.get('YIELD_ON_COST_PERCENTAGE', 0):.2%}")
irr_val = self.formula_results.get('IRR_TO_LP', 0)
if isinstance(irr_val, complex):
irr_val = irr_val.real
print(f" LP IRR: {irr_val:.2f}%")
print(f"\nExcel file: {output_excel}")
return output_excel
# ============= FastAPI Setup =============
app = FastAPI(title="Real Estate Financial Model API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Hardcoded API Key
GEMINI_API_KEY = "AIzaSyCy6GoBR724Hj9VyuW3hKM4N0P6liBOlDo"
@app.post("/api/generate-model")
async def generate_model(files: List[UploadFile] = File(...)):
"""
API endpoint to process uploaded files and return Excel model
Parameters:
- files: List of PDF/XLSX files to process
Returns:
- Excel file with financial model
"""
if not files:
raise HTTPException(status_code=400, detail="No files uploaded")
try:
# Create temporary directory
temp_dir = tempfile.mkdtemp()
# Save uploaded files
saved_files = []
for upload_file in files:
file_path = Path(temp_dir) / upload_file.filename
# Write file content
with open(file_path, "wb") as f:
content = await upload_file.read()
f.write(content)
saved_files.append(str(file_path))
# Initialize pipeline
pipeline = RealEstateModelPipeline(GEMINI_API_KEY)
# Create output file
output_file = Path(temp_dir) / "Real_Estate_Financial_Model.xlsx"
# Run pipeline
pipeline.run_full_pipeline(temp_dir, str(output_file))
# Return Excel file
return FileResponse(
path=str(output_file),
filename="Real_Estate_Financial_Model.xlsx",
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Processing error: {str(e)}")
finally:
# Cleanup will happen when temp directory is garbage collected
pass
@app.get("/api/health")
async def health_check():
"""Health check endpoint"""
return {"status": "healthy", "service": "Real Estate Financial Model API"}
@app.post("/api/generate-model-with-summary")
async def generate_model_with_summary(files: List[UploadFile] = File(...)):
"""
API endpoint that returns JSON summary with key metrics
AND includes base64 encoded Excel file
Returns JSON with:
- Key financial metrics
- Deal summary
- Market analysis
- Excel file as base64
"""
if not files:
raise HTTPException(status_code=400, detail="No files uploaded")
temp_dir = None
try:
# Create temporary directory
temp_dir = tempfile.mkdtemp()
print(f"📁 Created temp directory: {temp_dir}")
# Save uploaded files
for upload_file in files:
file_path = Path(temp_dir) / upload_file.filename
print(f"💾 Saving file: {upload_file.filename}")
with open(file_path, "wb") as f:
content = await upload_file.read()
f.write(content)
print(f"✅ Saved {len(files)} files")
# Initialize pipeline
print("🔧 Initializing pipeline...")
pipeline = RealEstateModelPipeline(GEMINI_API_KEY)
# Create output file
output_file = Path(temp_dir) / "Real_Estate_Financial_Model.xlsx"
# Run pipeline
print("🚀 Running pipeline...")
pipeline.run_full_pipeline(temp_dir, str(output_file))
# Check if file was created
if not output_file.exists():
raise Exception("Excel file was not generated")
print(f"✅ Excel file created: {output_file}")
# Get formula results
r = pipeline.formula_results
d = pipeline.structured_data
# Build comprehensive JSON response
response_data = {
"status": "success",
"message": "Financial model generated successfully",
# KEY METRICS (Dashboard Top Cards)
"key_metrics": {
"purchase_price": {
"value": r.get('PRICE', 0),
"formatted": f"${r.get('PRICE', 0):,.0f}",
"label": "Purchase Price"
},
"noi": {
"value": r.get('NET_OPERATING_INCOME', 0),
"formatted": f"${r.get('NET_OPERATING_INCOME', 0):,.0f}",
"label": "NOI"
},
"cap_rate": {
"value": r.get('CAP_RATE', 0),
"formatted": f"{r.get('CAP_RATE', 0):.1f}%",
"label": "Cap Rate"
},
"irr_10yr": {
"value": float(r.get('IRR_TO_LP', 0).real if isinstance(r.get('IRR_TO_LP', 0), complex) else r.get('IRR_TO_LP', 0)),
"formatted": f"{float(r.get('IRR_TO_LP', 0).real if isinstance(r.get('IRR_TO_LP', 0), complex) else r.get('IRR_TO_LP', 0)):.1f}%",
"label": "IRR (10 yr)"
},
"dscr": {
"value": r.get('DEBT_SERVICE_COVERAGE_RATIO', 0),
"formatted": f"{r.get('DEBT_SERVICE_COVERAGE_RATIO', 0):.2f}x",
"label": "DSCR"
}
},
# T12 SUMMARY (Extracted Summary)
"t12_summary": {
"gross_income": {
"annual": r.get('EFFECTIVE_GROSS_INCOME', 0),
"monthly": r.get('EFFECTIVE_GROSS_INCOME', 0) / 12,
"source": "Calculated from rent roll"
},
"operating_expenses": {
"annual": r.get('TOTAL_OPERATING_EXPENSES', 0),
"monthly": r.get('TOTAL_OPERATING_EXPENSES', 0) / 12,
"expense_ratio": f"{(r.get('TOTAL_OPERATING_EXPENSES', 0) / r.get('EFFECTIVE_GROSS_INCOME', 1) if r.get('EFFECTIVE_GROSS_INCOME', 0) > 0 else 0):.1%}"
},
"noi": {
"annual": r.get('NET_OPERATING_INCOME', 0),
"monthly": r.get('NET_OPERATING_INCOME', 0) / 12,
"verified": True
},
"occupancy": {
"rate": f"{(1 - r.get('VACANCY_RATE', 0)):.0%}",
"value": 1 - r.get('VACANCY_RATE', 0)
}
},
# PROPERTY INFO
"property_info": {
"address": d.get('property_info', {}).get('address', 'N/A'),
"property_type": d.get('property_info', {}).get('property_type', 'N/A'),
"units": r.get('UNITS', 0),
"gross_sf": r.get('GROSS_SF', 0),
"rentable_sf": r.get('RENTABLE_SF', 0),
"building_efficiency": f"{r.get('BUILDING_EFFICIENCY', 0):.1%}"
},
# DEAL VS MARKET AVERAGES
"market_comparison": {
"your_deal": {
"cap_rate": r.get('CAP_RATE', 0) / 100,
"irr": float(r.get('IRR_TO_LP', 0).real if isinstance(r.get('IRR_TO_LP', 0), complex) else r.get('IRR_TO_LP', 0)) / 100,
"dscr": r.get('DEBT_SERVICE_COVERAGE_RATIO', 0)
},
"market_average": {
"cap_rate": 0.055, # Example market average
"irr": 0.12,
"dscr": 1.25
}
},
# AI OBSERVATIONS
"ai_observations": [
{
"observation": f"Cap Rate {'above' if r.get('CAP_RATE', 0) > 5.5 else 'below'} area average",
"recommendation": "undervalued potential" if r.get('CAP_RATE', 0) > 5.5 else "premium pricing"
},
{
"observation": f"Expense ratio at {(r.get('TOTAL_OPERATING_EXPENSES', 0) / r.get('EFFECTIVE_GROSS_INCOME', 1) if r.get('EFFECTIVE_GROSS_INCOME', 0) > 0 else 0):.1%}",
"recommendation": "within normal range" if 0.3 <= (r.get('TOTAL_OPERATING_EXPENSES', 0) / r.get('EFFECTIVE_GROSS_INCOME', 1)) <= 0.45 else "review expenses"
},
{
"observation": "DSCR meets financing standards" if r.get('DEBT_SERVICE_COVERAGE_RATIO', 0) >= 1.2 else "DSCR below standards",
"recommendation": "approved" if r.get('DEBT_SERVICE_COVERAGE_RATIO', 0) >= 1.2 else "increase equity"
},
{
"observation": "NOI verification",
"recommendation": "Full underwriting review recommended"
}
],
# CAPITAL STACK
"capital_stack": {
"total_project_cost": r.get('TOTAL_FINANCING_CONTINGENCY_AND_RESERVES', 0),
"total_debt": r.get('TOTAL_DEBT', 0),
"total_equity": r.get('TOTAL_EQUITY', 0),
"debt_percentage": r.get('DEBT_PERCENTAGE', 0),
"equity_percentage": r.get('EQUITY_PERCENTAGE', 0),
"ltc_ratio": r.get('LTC_RATIO', 0)
},
# RETURNS ANALYSIS
"returns": {
"yield_on_cost": r.get('YIELD_ON_COST_PERCENTAGE', 0),
"stabilized_yield_on_cost": r.get('STABILIZED_YIELD_ON_COST_PERCENTAGE', 0),
"cash_on_cash_return": r.get('CASH_ON_CASH_RETURN', 0),
"lp_multiple": r.get('LP_MULTIPLE', 0),
"lp_irr": float(r.get('IRR_TO_LP', 0).real if isinstance(r.get('IRR_TO_LP', 0), complex) else r.get('IRR_TO_LP', 0)),
"hold_period_years": r.get('HOLD_PERIOD_MONTHS', 0) / 12
},
# OPERATING METRICS
"operating_metrics": {
"gross_potential_rent": r.get('GROSS_POTENTIAL_FREE_MARKET_RENT', 0) + r.get('GROSS_POTENTIAL_AFFORDABLE_RENT', 0),
"vacancy_loss": r.get('VACANCY_LOSS', 0),
"effective_gross_income": r.get('EFFECTIVE_GROSS_INCOME', 0),
"operating_expenses": r.get('TOTAL_OPERATING_EXPENSES', 0),
"noi": r.get('NET_OPERATING_INCOME', 0),
"noi_per_unit": r.get('NOI_PER_UNIT', 0),
"noi_per_sf": r.get('NOI_PER_GSF', 0)
},
# COST BREAKDOWN
"cost_breakdown": {
"acquisition": {
"total": r.get('TOTAL_ACQUISITION_COST', 0),
"per_unit": r.get('TOTAL_ACQUISITION_COST_PER_UNIT', 0),
"per_sf": r.get('TOTAL_ACQUISITION_COST_PER_GSF', 0)
},
"construction": {
"total": r.get('TOTAL_CONSTRUCTION_GMP', 0),
"per_unit": r.get('CONSTRUCTION_GMP_PER_UNIT', 0),
"per_sf": r.get('CONSTRUCTION_GMP_PER_GSF', 0)
},
"soft_costs": {
"total": r.get('TOTAL_SOFT_COST', 0),
"per_sf": r.get('TOTAL_SOFT_COST_PER_GSF', 0)
},
"contingency": r.get('CONTINGENCY_COST', 0),
"reserves": r.get('OPERATING_RESERVE', 0)
},
# SOURCE FILES
"source_files": [
{
"filename": file.filename,
"size": len(await file.read()) if hasattr(file, 'read') else 0,
"type": file.filename.split('.')[-1].upper()
}
for file in files
],
# EXCEL FILE (BASE64 ENCODED)
"excel_file": {
"filename": "Real_Estate_Financial_Model.xlsx",
"size_bytes": output_file.stat().st_size,
"base64_data": base64.b64encode(output_file.read_bytes()).decode('utf-8')
}
}
print("✅ Response JSON created")
return JSONResponse(content=response_data)
except Exception as e:
import traceback
error_details = traceback.format_exc()
print("❌ ERROR OCCURRED:")
print(error_details)
raise HTTPException(
status_code=500,
detail={
"error": str(e),
"type": type(e).__name__,
"traceback": error_details
}
)
# NEW: Endpoint that returns ONLY JSON (no Excel file)
@app.post("/api/analyze-only")
async def analyze_only(files: List[UploadFile] = File(...)):
"""
Returns only JSON summary without Excel file
Faster response, good for dashboards
"""
if not files:
raise HTTPException(status_code=400, detail="No files uploaded")
temp_dir = None
try:
temp_dir = tempfile.mkdtemp()
for upload_file in files:
file_path = Path(temp_dir) / upload_file.filename
with open(file_path, "wb") as f:
content = await upload_file.read()
f.write(content)
pipeline = RealEstateModelPipeline(GEMINI_API_KEY)
# Extract and process data (no Excel generation)
pipeline.extract_all_pdfs(temp_dir)
structured_data = pipeline.extract_structured_data()
structured_data = pipeline.post_process_extracted_data(structured_data)
pipeline.calculate_all_formulas(structured_data)
r = pipeline.formula_results
d = pipeline.structured_data
# Return lightweight JSON
return JSONResponse(content={
"status": "success",
"key_metrics": {
"purchase_price": r.get('PRICE', 0),
"noi": r.get('NET_OPERATING_INCOME', 0),
"cap_rate": r.get('CAP_RATE', 0),
"irr": float(r.get('IRR_TO_LP', 0).real if isinstance(r.get('IRR_TO_LP', 0), complex) else r.get('IRR_TO_LP', 0)),
"dscr": r.get('DEBT_SERVICE_COVERAGE_RATIO', 0)
},
"property_info": {
"address": d.get('property_info', {}).get('address', 'N/A'),
"units": r.get('UNITS', 0),
"gross_sf": r.get('GROSS_SF', 0)
},
"capital_stack": {
"total_project_cost": r.get('TOTAL_FINANCING_CONTINGENCY_AND_RESERVES', 0),
"total_debt": r.get('TOTAL_DEBT', 0),
"total_equity": r.get('TOTAL_EQUITY', 0)
},
"returns": {
"yield_on_cost": r.get('YIELD_ON_COST_PERCENTAGE', 0),
"cash_on_cash": r.get('CASH_ON_CASH_RETURN', 0),
"lp_multiple": r.get('LP_MULTIPLE', 0)
}
})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analyze-documents")
async def analyze_documents(
files: List[UploadFile] = File(...),
max_pages_per_doc: int = 2,
confidence_threshold: float = 0.7
):
"""
Industrial-scale document relevance analysis endpoint
Analyzes uploaded documents to determine if they are relevant to real estate
and metrics calculation. Uses first few pages for efficiency.
Parameters:
- files: List of document files (PDF, XLSX, DOCX, etc.)
- max_pages_per_doc: Maximum number of pages to analyze per document (default: 2)
- confidence_threshold: Minimum confidence score to mark as relevant (default: 0.7)
Returns:
- JSON with relevance analysis for each file
"""
if not files:
raise HTTPException(status_code=400, detail="No files uploaded")
# Validate input parameters
if max_pages_per_doc < 1 or max_pages_per_doc > 10:
raise HTTPException(status_code=400, detail="max_pages_per_doc must be between 1 and 10")
if confidence_threshold < 0.1 or confidence_threshold > 1.0:
raise HTTPException(status_code=400, detail="confidence_threshold must be between 0.1 and 1.0")
temp_dir = None
try:
# Create temporary directory with unique name
temp_dir = tempfile.mkdtemp(prefix="doc_analysis_")
logger.info(f"Created temp directory: {temp_dir}")
# Process files in parallel for better performance
analysis_results = await process_documents_parallel(
files, temp_dir, max_pages_per_doc, confidence_threshold
)
# Generate overall summary
summary = generate_analysis_summary(analysis_results)
response = {
"status": "success",
"summary": summary,
"analysis": analysis_results,
"metadata": {
"total_files": len(files),
"relevant_files": summary["relevant_count"],
"non_relevant_files": summary["non_relevant_count"],
"confidence_threshold": confidence_threshold,
"max_pages_analyzed": max_pages_per_doc,
"processing_time_seconds": summary["processing_time_seconds"]
}
}
logger.info(f"Document analysis completed: {summary['relevant_count']}/{len(files)} relevant files")
return JSONResponse(content=response)
except Exception as e:
logger.error(f"Document analysis error: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail=f"Document analysis failed: {str(e)}"
)
finally:
# Cleanup temporary directory
if temp_dir and os.path.exists(temp_dir):
try:
shutil.rmtree(temp_dir)
logger.info(f"Cleaned up temp directory: {temp_dir}")
except Exception as e:
logger.warning(f"Failed to cleanup temp directory: {str(e)}")
async def process_documents_parallel(
files: List[UploadFile],
temp_dir: str,
max_pages: int,
confidence_threshold: float
) -> List[Dict]:
"""Process documents in parallel for better performance"""
import asyncio
# Save all files first
saved_paths = []
for upload_file in files:
file_path = Path(temp_dir) / secure_filename(upload_file.filename)
with open(file_path, "wb") as f:
content = await upload_file.read()
f.write(content)
saved_paths.append((file_path, upload_file.filename, upload_file.content_type))
# Process files concurrently
tasks = []
for file_path, filename, content_type in saved_paths:
task = analyze_single_document(
file_path, filename, content_type, max_pages, confidence_threshold
)
tasks.append(task)
# Use asyncio.gather for concurrent processing
results = await asyncio.gather(*tasks, return_exceptions=True)
# Handle exceptions in individual file processing
processed_results = []
for i, result in enumerate(results):
filename = saved_paths[i][1]
if isinstance(result, Exception):
logger.error(f"Error processing {filename}: {str(result)}")
processed_results.append({
"filename": filename,
"relevant": False,
"confidence": 0.0,
"error": str(result),
"reason": "Processing failed",
"key_indicators": []
})
else:
processed_results.append(result)
return processed_results
async def analyze_single_document(
file_path: Path,
filename: str,
content_type: str,
max_pages: int,
confidence_threshold: float
) -> Dict:
"""Analyze a single document for real estate relevance"""
start_time = time.time()
try:
# Extract text from document (first N pages)
extracted_text = await extract_document_text(
file_path, content_type, max_pages
)
if not extracted_text or len(extracted_text.strip()) < 50:
return {
"filename": filename,
"relevant": False,
"confidence": 0.0,
"reason": "Insufficient or unreadable text content",
"key_indicators": [],
"text_sample": extracted_text[:200] if extracted_text else ""
}
# Analyze with Gemini
analysis_result = await analyze_with_gemini(extracted_text, confidence_threshold)
processing_time = time.time() - start_time
return {
"filename": filename,
"relevant": analysis_result["relevant"],
"confidence": analysis_result["confidence"],
"reason": analysis_result["reason"],
"key_indicators": analysis_result["key_indicators"],
"document_type": analysis_result.get("document_type", "unknown"),
"text_sample": extracted_text[:500], # First 500 chars for debugging
"processing_time_seconds": round(processing_time, 2),
"pages_analyzed": min(max_pages, estimate_page_count(file_path, content_type))
}
except Exception as e:
logger.error(f"Error analyzing {filename}: {str(e)}")
return {
"filename": filename,
"relevant": False,
"confidence": 0.0,
"error": str(e),
"reason": "Analysis error",
"key_indicators": []
}
async def extract_document_text(file_path: Path, content_type: str, max_pages: int) -> str:
"""Extract text from document with page limit"""
file_extension = file_path.suffix.lower()
try:
if file_extension == '.pdf':
return extract_pdf_text_limited(file_path, max_pages)
elif file_extension in ['.xlsx', '.xls']:
return extract_excel_text_limited(file_path, max_pages)
elif file_extension in ['.docx', '.doc']:
return extract_docx_text_limited(file_path, max_pages)
elif file_extension in ['.txt', '.csv']:
return extract_text_file_limited(file_path, max_pages)
else:
# Fallback: try to read as text
return extract_text_file_limited(file_path, max_pages)
except Exception as e:
logger.warning(f"Text extraction failed for {file_path}: {str(e)}")
return ""
def extract_pdf_text_limited(pdf_path: Path, max_pages: int) -> str:
"""Extract text from first N pages of PDF"""
try:
from pdfminer.high_level import extract_text
from pdfminer.layout import LAParams
# Extract only first N pages
text = extract_text(
str(pdf_path),
laparams=LAParams(),
maxpages=max_pages
)
return text.strip()
except Exception as e:
logger.error(f"PDF extraction error: {str(e)}")
return ""
def extract_excel_text_limited(excel_path: Path, max_sheets: int) -> str:
"""Extract text from first N sheets of Excel file"""
try:
import pandas as pd
extracted_content = []
xlsx = pd.ExcelFile(excel_path)
# Limit number of sheets processed
sheets_to_process = xlsx.sheet_names[:max_sheets]
for sheet_name in sheets_to_process:
try:
df = pd.read_excel(xlsx, sheet_name=sheet_name, nrows=50) # First 50 rows
extracted_content.append(f"=== Sheet: {sheet_name} ===")
extracted_content.append(df.to_string(index=False, max_rows=20))
extracted_content.append("\n")
except Exception as e:
logger.warning(f"Could not read sheet {sheet_name}: {str(e)}")
continue
return "\n".join(extracted_content)
except Exception as e:
logger.error(f"Excel extraction error: {str(e)}")
return ""
def extract_docx_text_limited(docx_path: Path, max_pages: int) -> str:
"""Extract text from first N pages of DOCX (estimated)"""
try:
import docx
doc = docx.Document(str(docx_path))
full_text = []
# Estimate pages by paragraphs (rough approximation)
paragraphs_processed = 0
paragraphs_per_page = 10 # Rough estimate
for paragraph in doc.paragraphs:
if paragraphs_processed >= max_pages * paragraphs_per_page:
break
if paragraph.text.strip():
full_text.append(paragraph.text)
paragraphs_processed += 1
return "\n".join(full_text)
except Exception as e:
logger.error(f"DOCX extraction error: {str(e)}")
return ""
def extract_text_file_limited(file_path: Path, max_pages: int) -> str:
"""Extract limited text from text file"""
try:
lines_per_page = 50
max_lines = max_pages * lines_per_page
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
lines = []
for i, line in enumerate(f):
if i >= max_lines:
break
lines.append(line)
return "".join(lines)
except Exception as e:
logger.error(f"Text file extraction error: {str(e)}")
return ""
def estimate_page_count(file_path: Path, content_type: str) -> int:
"""Estimate number of pages in document"""
# Simple estimation - can be enhanced based on file type
return 1
async def analyze_with_gemini(text: str, confidence_threshold: float) -> Dict:
"""Use Gemini to analyze document relevance"""
prompt = f"""
Analyze this document text and determine if it's relevant to REAL ESTATE and METRICS CALCULATION.
CRITICAL: You must respond with ONLY a JSON object, no other text.
DOCUMENT TEXT (first few pages):
{text[:8000]} # Limit text to avoid token limits
ANALYSIS INSTRUCTIONS:
1. Determine if this document is relevant to real estate business, investments, or metrics
2. Identify key indicators that support your decision
3. Provide a confidence score (0.0 to 1.0)
4. Classify the document type if possible
RELEVANCE CRITERIA:
- Real estate related: property listings, financial models, market analysis, offering memorandums, rent rolls, operating statements
- Metrics calculation: financial projections, ROI analysis, cap rates, NOI calculations, cash flow analysis
- Real estate development: construction costs, pro formas, feasibility studies
NON-RELEVANT EXAMPLES:
- Resumes, personal documents, marketing brochures for non-real estate
- Academic papers unrelated to real estate
- General business documents without real estate focus
REQUIRED JSON RESPONSE FORMAT:
{{
"relevant": true/false,
"confidence": 0.85,
"reason": "Brief explanation of relevance decision",
"key_indicators": ["indicator1", "indicator2", ...],
"document_type": "offering_memorandum|financial_statement|market_report|rent_roll|unknown"
}}
Confidence threshold for relevance: {confidence_threshold}
"""
try:
# Initialize Gemini
genai.configure(api_key=GEMINI_API_KEY)
model = genai.GenerativeModel('gemini-2.0-flash')
response = await asyncio.get_event_loop().run_in_executor(
None,
lambda: model.generate_content(prompt)
)
response_text = response.text.strip()
# Clean JSON response
if "```json" in response_text:
response_text = response_text.split("```json")[1].split("```")[0].strip()
elif "```" in response_text:
response_text = response_text.split("```")[1].split("```")[0].strip()
result = json.loads(response_text)
# Validate response structure
required_fields = ["relevant", "confidence", "reason", "key_indicators"]
for field in required_fields:
if field not in result:
raise ValueError(f"Missing field in Gemini response: {field}")
# Apply confidence threshold
if result["confidence"] < confidence_threshold:
result["relevant"] = False
result["reason"] = f"Confidence ({result['confidence']}) below threshold ({confidence_threshold})"
return result
except Exception as e:
logger.error(f"Gemini analysis failed: {str(e)}")
# Fallback: simple keyword-based analysis
return perform_fallback_analysis(text, confidence_threshold)
def perform_fallback_analysis(text: str, confidence_threshold: float) -> Dict:
"""Fallback analysis using keyword matching when Gemini fails"""
real_estate_keywords = [
'real estate', 'property', 'rent', 'lease', 'mortgage', 'cap rate',
'noi', 'net operating income', 'cash flow', 'pro forma', 'offering memorandum',
'rent roll', 'operating expenses', 'vacancy rate', 'occupancy', 'square feet',
'acquisition', 'disposition', 'broker', 'listing', 'appraisal', 'valuation',
'construction', 'development', 'zoning', 'permit', 'tenant', 'landlord'
]
metrics_keywords = [
'metrics', 'kpi', 'key performance indicator', 'roi', 'return on investment',
'irr', 'internal rate of return', 'dscr', 'debt service coverage ratio',
'ltv', 'loan to value', 'calculation', 'analysis', 'projection', 'forecast',
'financial model', 'spreadsheet', 'excel', 'numbers', 'data', 'statistics'
]
text_lower = text.lower()
# Count keyword matches
re_matches = sum(1 for keyword in real_estate_keywords if keyword in text_lower)
metrics_matches = sum(1 for keyword in metrics_keywords if keyword in text_lower)
total_matches = re_matches + metrics_matches
# Calculate confidence based on matches
confidence = min(1.0, total_matches / 10) # Normalize
relevant = confidence >= confidence_threshold and (re_matches >= 2 or metrics_matches >= 2)
key_indicators = []
if re_matches > 0:
key_indicators.append(f"Real estate terms found: {re_matches}")
if metrics_matches > 0:
key_indicators.append(f"Metrics terms found: {metrics_matches}")
return {
"relevant": relevant,
"confidence": round(confidence, 2),
"reason": f"Keyword analysis: {re_matches} real estate terms, {metrics_matches} metrics terms",
"key_indicators": key_indicators,
"document_type": "unknown"
}
def generate_analysis_summary(analysis_results: List[Dict]) -> Dict:
"""Generate summary of document analysis"""
relevant_files = [r for r in analysis_results if r.get('relevant', False)]
non_relevant_files = [r for r in analysis_results if not r.get('relevant', False)]
# Calculate average confidence
confidences = [r.get('confidence', 0) for r in analysis_results if r.get('confidence') is not None]
avg_confidence = sum(confidences) / len(confidences) if confidences else 0
# Document type distribution
doc_types = {}
for result in analysis_results:
doc_type = result.get('document_type', 'unknown')
doc_types[doc_type] = doc_types.get(doc_type, 0) + 1
return {
"relevant_count": len(relevant_files),
"non_relevant_count": len(non_relevant_files),
"relevance_rate": len(relevant_files) / len(analysis_results) if analysis_results else 0,
"average_confidence": round(avg_confidence, 3),
"document_type_breakdown": doc_types,
"processing_time_seconds": sum(r.get('processing_time_seconds', 0) for r in analysis_results)
}
def secure_filename(filename: str) -> str:
"""Sanitize filename for security"""
import re
filename = re.sub(r'[^a-zA-Z0-9_.-]', '_', filename)
return filename
def process_pdfs(pdf_files):
"""Process uploaded PDFs and return Excel file"""
if not pdf_files:
return None, "⚠️ Please upload at least one PDF/XLSX file"
try:
# Create temporary directory for PDFs
temp_dir = tempfile.mkdtemp()
# Save uploaded PDFs to temp directory
for pdf_file in pdf_files:
if pdf_file is None:
continue
dest_path = Path(temp_dir) / Path(pdf_file.name).name
shutil.copy(pdf_file.name, dest_path)
# Initialize pipeline with hardcoded API key
pipeline = RealEstateModelPipeline(GEMINI_API_KEY)
# Create output file in temp directory
output_file = Path(temp_dir) / "Real_Estate_Financial_Model.xlsx"
# Run pipeline
result = pipeline.run_full_pipeline(temp_dir, str(output_file))
# Generate summary text
r = pipeline.formula_results
irr_val = r.get('IRR_TO_LP', 0)
if isinstance(irr_val, complex):
irr_val = irr_val.real
summary = f"""✅ **Processing Complete!**
📊 **Key Metrics:**
• Total Project Cost: ${r.get('TOTAL_FINANCING_CONTINGENCY_AND_RESERVES', 0):,.0f}
• Total Debt: ${r.get('TOTAL_DEBT', 0):,.0f}
• Total Equity: ${r.get('TOTAL_EQUITY', 0):,.0f}
• NOI: ${r.get('NET_OPERATING_INCOME', 0):,.0f}
• Yield on Cost: {r.get('YIELD_ON_COST_PERCENTAGE', 0):.2%}
• LP IRR: {float(irr_val):.2f}%
✨ Download your Excel file below ⬇️
"""
return str(output_file), summary
except Exception as e:
import traceback
error_msg = f"❌ **Error occurred:**\n\n{str(e)}\n\n**Details:**\n{traceback.format_exc()}"
return None, error_msg
# Create Gradio interface with better styling
with gr.Blocks(
title="Real Estate Financial Model Generator",
theme=gr.themes.Soft(),
css="""
.gradio-container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
"""
) as demo:
gr.Markdown("""
# 🏢 Real Estate Financial Model Generator
Upload your PDF/XLSX documents and generate a comprehensive financial model in Excel format.
""")
with gr.Row():
with gr.Column(scale=2):
pdf_input = gr.File(
label="Upload PDF/XLSX Files",
file_count="multiple",
file_types=[".pdf", ".xlsx", ".xls"],
type="filepath",
elem_classes=["file-upload"]
)
process_btn = gr.Button(
"Generate Financial Model",
variant="primary",
size="lg"
)
with gr.Column(scale=1):
gr.Markdown("""
### Supported Formats
- **PDF**: Offering Memorandum, Reports
- **XLSX/XLS**: Financial statements, data tables
### Required Documents
- Offering Memorandum
- Operating Expenses Summary
- Sales Comps
- Rent Comps
- Market Report
- Demographics Overview
### Features
- Automated data extraction
- Formula calculations
- Professional Excel output
- Multiple analysis sheets
""")
with gr.Row():
output_text = gr.Textbox(
label="Processing Results",
lines=15,
interactive=False,
elem_classes=["output-text"]
)
with gr.Row():
excel_output = gr.File(
label="Download Excel File",
interactive=False
)
# Connect the button
process_btn.click(
fn=process_pdfs,
inputs=[pdf_input],
outputs=[excel_output, output_text],
api_name="process"
)
gr.Markdown("""
---
### Tips
- Ensure PDF files are readable and not scanned images
- Use descriptive filenames (e.g., "Offering_Memorandum.pdf")
- Processing may take 30-60 seconds depending on file sizes
- Check the **Processing Results** section for detailed feedback
### API Endpoints
- `POST /api/generate-model` - Generate Excel only
- `POST /api/generate-model-with-summary` - Generate Excel + JSON summary
- `POST /api/analyze-only` - Generate JSON summary only
- `GET /api/health` - Health check
""")
# For Hugging Face Spaces, we need to expose the app
if __name__ == "__main__":
# For Hugging Face Spaces deployment
import os
# Check if running on Hugging Face Spaces
is_hf_space = os.environ.get('SPACE_ID') is not None
if is_hf_space:
# On HF Spaces: Mount Gradio to FastAPI and launch together
app = gr.mount_gradio_app(app, demo, path="/")
uvicorn.run(
app,
host="0.0.0.0",
port=7860,
log_level="info"
)
else:
# Local development: Launch separately
import threading
# Start FastAPI in background thread
def run_fastapi():
uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")
api_thread = threading.Thread(target=run_fastapi, daemon=True)
api_thread.start()
# Launch Gradio on main thread
demo.launch(
server_name="0.0.0.0",
server_port=7861,
share=False
) |