Spaces:
Runtime error
Runtime error
File size: 272,425 Bytes
8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 8561396 015f037 915d121 015f037 915d121 015f037 915d121 015f037 0b64411 015f037 915d121 015f037 915d121 015f037 0b64411 015f037 915d121 015f037 0b64411 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 0b64411 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 0b64411 015f037 915d121 015f037 915d121 8561396 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 015f037 915d121 0b64411 015f037 915d121 0b64411 015f037 8561396 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 | # api_generator.py - VERSIÓN falta sincronizar categorias
import streamlit as st
import pandas as pd
import numpy as np
import json
import io
import zipfile
import os
from datetime import datetime
import tempfile
import requests
from typing import Dict, List, Any
import re
def show():
st.header("⚡ Generador de API Profesional - E-commerce")
# Configuración de API Keys - ACTUALIZADA CON PIXABAY
with st.expander("🔑 Configuración de APIs Externas", expanded=False):
# Valores por defecto para ambas APIs
if 'pixabay_api_key' not in st.session_state:
st.session_state['pixabay_api_key'] = "52812318-583c94721ffbb74a4f0c5684d"
if 'pexels_api_key' not in st.session_state:
st.session_state['pexels_api_key'] = "jPUxO9Zkb1OzitGkAmI9PeTe3oxqipfsYI3vdfCm0pg8QHFpUeSqVsNS"
col1, col2 = st.columns(2)
with col1:
pixabay_api_key = st.text_input(
"API Key de Pixabay 🥇:",
value=st.session_state['pixabay_api_key'],
type="password",
help="Obtén tu API key gratis en https://pixabay.com/api/docs/"
)
st.session_state['pixabay_api_key'] = pixabay_api_key
with col2:
pexels_api_key = st.text_input(
"API Key de Pexels 🥈:",
value=st.session_state['pexels_api_key'],
type="password",
help="Obtén tu API key gratis en https://www.pexels.com/api/"
)
st.session_state['pexels_api_key'] = pexels_api_key
# ✅✅✅ CORREGIDO: Inyectar AMBAS API keys ANTES de generar cualquier dato
from utils.image_generator import configure_image_generator
configure_image_generator(
pexels_api_key=st.session_state['pexels_api_key'],
pixabay_api_key=st.session_state['pixabay_api_key']
)
# ✅ Verificar que las API keys se configuraron correctamente
from utils.image_generator import image_generator
apis_configuradas = []
if image_generator.pixabay_api_key and image_generator.pixabay_api_key != "TU_API_KEY_PIXABAY_AQUI":
apis_configuradas.append("🥈 Pixabay") # Cambiado a 🥈
if image_generator.pexels_api_key and image_generator.pexels_api_key != "TU_API_KEY_PEXELS_AQUI":
apis_configuradas.append("🥉 Pexels") # Cambiado a 🥉
# ✅ AGREGADO: Verificar Lexica (siempre disponible)
apis_configuradas.append("🥇 Lexica")
if apis_configuradas:
st.success(f"✅ APIs configuradas: {', '.join(apis_configuradas)}")
else:
st.warning("⚠️ No hay APIs configuradas - Se usarán placeholders e IA")
# Verificar datos globales
if st.session_state.get('global_df') is None:
st.warning("📤 No hay datos cargados en el sistema")
st.info("💡 Carga un archivo en la barra lateral para generar API desde datos reales, o usa datos mock")
st.subheader("🎯 Configuración de la API")
# CONFIGURACIÓN PRINCIPAL
col1, col2 = st.columns(2)
with col1:
api_type = st.radio(
"Tipo de API:",
["🚀 Desde datos cargados", "🎭 API Mock (datos de prueba)", "🔗 API Híbrida (datos reales + mock)"],
help="Genera API desde tus datos, con datos de prueba, o combinando ambos"
)
technology = st.selectbox(
"Tecnología del backend:",
["FastAPI (Python - Recomendado)", "Flask (Python)", "Django (Python)", "Spring Boot (Java)", "Express.js (Node.js)"],
index=0
)
database = st.selectbox(
"Base de datos:",
["SQLite (Desarrollo)", "PostgreSQL (Producción)", "MySQL (Producción)", "MongoDB (NoSQL)"],
index=0
)
with col2:
project_name = st.text_input(
"Nombre del proyecto:",
value="mi_api_ecommerce",
help="Nombre de la carpeta y proyecto"
)
api_version = st.text_input(
"Versión de la API:",
value="1.0.0",
help="Versión semántica (ej: 1.0.0)"
)
include_auth = st.checkbox("🔐 Incluir autenticación JWT", value=True)
include_docs = st.checkbox("📚 Incluir documentación Swagger", value=True)
include_docker = st.checkbox("🐳 Incluir Docker y Docker Compose", value=True)
# CONFIGURACIÓN DE MÓDULOS/ENTIDADES
st.subheader("🏗️ Módulos de la API E-commerce")
modules = []
# MÓDULOS DESDE DATOS CARGADOS
if api_type in ["🚀 Desde datos cargados", "🔗 API Híbrida (datos reales + mock)"]:
if st.session_state.get('global_df') is not None:
df = st.session_state.global_df
filename = st.session_state.global_filename
st.success(f"📊 Datos cargados: {filename}")
main_entity = infer_entity_name(filename)
with st.expander(f"🔧 Configurar módulo: {main_entity}", expanded=True):
module_name = st.text_input("Nombre del módulo:", value=main_entity, key="main_module")
base_route = st.text_input("Ruta base:", value=f"/{main_entity}", key="main_route")
st.write("**Configuración de campos:**")
field_config = {}
for col in df.columns:
col1, col2, col3 = st.columns([2, 2, 1])
with col1:
field_name = st.text_input("Nombre campo:", value=col, key=f"field_{col}_name")
with col2:
field_type = st.selectbox(
"Tipo:",
["string", "integer", "float", "boolean", "datetime", "email", "url"],
key=f"field_{col}_type"
)
with col3:
required = st.checkbox("Requerido", value=True, key=f"field_{col}_req")
field_config[col] = {
'name': field_name,
'type': field_type,
'required': required
}
modules.append({
'name': module_name,
'route': base_route,
'source': 'file',
'data': df,
'fields': field_config
})
# ✅✅✅ CORRECCIÓN: AGREGAR MÓDULO USUARIOS AUTOMÁTICAMENTE SOLO PARA "DESDE DATOS CARGADOS"
if include_auth and api_type == "🚀 Desde datos cargados":
# Verificar que no exista ya un módulo 'usuarios' en los módulos que se agregarán
existing_module_names = [m['name'] for m in modules]
if 'usuarios' not in existing_module_names:
modules.append({
'name': 'usuarios',
'route': '/api/usuarios',
'source': 'system', # Nuevo tipo para módulos del sistema
'type': 'usuarios',
'record_count': 2, # ← ¡CORREGIDO: SOLO 2 USUARIOS DEL SISTEMA!
'_include_system_users': True, # ✅ CORRECCIÓN: Agregar flag para el generador
'include_images': False,
'image_source': None,
'categorias_seleccionadas': []
})
st.success("✅ Módulo de usuarios creado automáticamente para autenticación JWT")
# Agregar módulos adicionales para API Mock
if api_type in ["🎭 API Mock (datos de prueba)", "🔗 API Híbrida (datos reales + mock)"]:
st.write("---")
st.write("**➕ Agregar módulos mock para E-commerce**")
# MÓDULOS ESENCIALES vs OPCIONALES
essential_modules = ["usuarios", "productos", "categorias", "pedidos", "carrito"]
optional_modules = ["pagos", "reseñas", "direcciones", "cupones"]
col_ess, col_opt = st.columns(2)
with col_ess:
st.write("**🎯 Módulos Esenciales**")
essential_selected = st.multiselect(
"Seleccionar módulos esenciales:",
essential_modules,
default=essential_modules,
label_visibility="collapsed"
)
with col_opt:
st.write("**🔧 Módulos Opcionales**")
optional_selected = st.multiselect(
"Seleccionar módulos opcionales:",
optional_modules,
default=["pagos", "reseñas"],
label_visibility="collapsed"
)
mock_modules = essential_selected + optional_selected
# ✅ NUEVO: Inicializar categorías de productos mock si no existe
if 'categorias_productos_mock' not in st.session_state:
st.session_state['categorias_productos_mock'] = []
# ✅ CORRECCIÓN: Lista UNIFICADA de categorías para productos y categorías
categorias_disponibles_unificadas = [
'Electrónica', 'Tecnología', 'Hogar', 'Ropa', 'Deportes',
'Juguetes', 'Libros', 'Música', 'Belleza', 'Salud',
'Alimentos', 'Bebidas', 'Automotriz', 'Jardín', 'Oficina',
'Comidas Dulces', 'Comidas Saladas'
]
for module in mock_modules:
with st.expander(f"🎭 Configurar módulo: {module}", expanded=False):
module_name = st.text_input("Nombre:", value=module, key=f"mock_{module}_name")
base_route = st.text_input("Ruta:", value=f"/{module}", key=f"mock_{module}_route")
# ✅ MEJORA: Slider específico para usuarios con JWT
if module == 'usuarios' and include_auth:
record_count = st.slider(
"Número de registros:",
3, # ✅ CORRECCIÓN: Mínimo 3 para usuarios
1000,
50,
key=f"mock_{module}_count",
help="Total de usuarios incluyendo los 2 del sistema (admin + usuario normal)"
)
elif module == "categorias":
# ✅✅✅ CORRECCIÓN CRÍTICA: SLIDER AUTOCONFIGURADO Y NO EDITABLE
# Primero procesamos la configuración de categorías para saber el total real
# ✅ CORRECCIÓN: Sincronización automática para módulo categorías MOCK
categorias_base = st.session_state.get('categorias_productos_mock', [])
# ✅ VALIDACIÓN: Asegurar que categorias_base sea una lista válida
if not isinstance(categorias_base, list):
categorias_base = []
if categorias_base:
st.write("**📦 Categorías detectadas desde productos mock:**")
for cat in categorias_base:
st.write(f"✅ {cat}")
# ✅ CORRECCIÓN: Filtrar categorías adicionales para EVITAR DUPLICADOS
categorias_adicionales_filtradas = [
cat for cat in categorias_disponibles_unificadas
if cat not in categorias_base
]
# Permitir agregar categorías adicionales
categorias_extra = st.multiselect(
"Agregar categorías adicionales:",
categorias_adicionales_filtradas,
default=[],
key=f"mock_{module}_extra_cats"
)
# ✅ VALIDACIÓN: Combinar SIN DUPLICADOS usando set()
todas_las_categorias = list(set(categorias_base + categorias_extra))
# ✅ VALIDACIÓN: Ordenar para consistencia
todas_las_categorias.sort()
# ✅✅✅ CORRECCIÓN CRÍTICA: SLIDER AUTOCONFIGURADO - EVITAR ERROR DE STREAMLIT
total_categorias_reales = len(todas_las_categorias)
if not todas_las_categorias:
st.info("💡 Selecciona categorías adicionales o configura primero el módulo de productos")
total_categorias_reales = 0
else:
st.success(f"📊 Total de categorías detectadas: {total_categorias_reales}")
# ✅✅✅ CORRECCIÓN: SLIDER AUTOCONFIGURADO - SOLUCIÓN DEFINITIVA
if total_categorias_reales > 0:
# SOLUCIÓN: Usar número_input en lugar de slider cuando min=max
record_count = st.number_input(
"Número de registros:",
min_value=total_categorias_reales,
max_value=total_categorias_reales,
value=total_categorias_reales,
key=f"mock_{module}_count",
disabled=True, # ✅ BLOQUEADO - no editable por usuario
help=f"🔒 Automático: 1 registro por categoría ({total_categorias_reales} categorías)"
)
st.info(f"🔢 **Registros en categorías**: {total_categorias_reales} (automático - 1 registro por categoría)")
else:
st.warning("⚠️ No hay categorías para generar")
record_count = 0
# Asignar las categorías combinadas al módulo
categorias_seleccionadas = todas_las_categorias
include_images = False
image_source = None
else:
# Para otros módulos (productos, pedidos, etc.) usar slider normal
record_count = st.slider(
"Número de registros:",
3, # ✅ CORRECCIÓN: Mínimo 3 para TODOS los módulos
1000,
50,
key=f"mock_{module}_count"
)
# Configuración específica por módulo (SOLO para productos, ya que categorías se procesó arriba)
if module in ["productos"]:
include_images = st.checkbox("🖼️ Incluir imágenes reales", value=True, key=f"mock_{module}_images")
image_source = st.selectbox(
"Fuente de imágenes:",
[
"🥇 Lexica (Búsquedas específicas con IA)", # PRIMERA
"🥈 Pollinations AI (Generadas por IA)", # SEGUNDA
"🥉 Pixabay (Precisas, libres de derechos)", # TERCERA
"📸 Pexels (Alta calidad)", # CUARTA
"🪄 Placeholder (Último recurso)",
"🎯 Orden de prioridad automático"
],
key=f"mock_{module}_imgsrc"
)
categorias_seleccionadas = st.multiselect(
f"Categorías de {module}:",
categorias_disponibles_unificadas,
default=categorias_disponibles_unificadas[:5],
key=f"mock_{module}_cats"
)
# ✅ CORRECCIÓN: ACTUALIZAR categorías de productos MOCK en tiempo real
categorias_unicas = list(set(categorias_seleccionadas))
if len(categorias_unicas) != len(categorias_seleccionadas):
st.warning("⚠️ Se detectaron categorías duplicadas, se eliminarán automáticamente")
# ✅ CORRECCIÓN: Actualizar inmediatamente para que categorías lo vea
st.session_state['categorias_productos_mock'] = categorias_unicas
if categorias_seleccionadas and any(cat in ['Comidas Dulces', 'Comidas Saladas', 'Bebidas'] for cat in categorias_seleccionadas):
st.success("🍽️ **Modo Restaurante Activado**: Se generarán productos especializados (tortas, hamburguesas, bebidas, etc.)")
elif module not in ["categorias"]: # Para módulos que no son categorías ni productos
include_images = False
image_source = None
categorias_seleccionadas = []
# ✅✅✅ CORRECCIÓN: AGREGAR FLAG PARA INCLUIR USUARIOS DEL SISTEMA
module_data = {
'name': module_name,
'route': base_route,
'source': 'mock',
'type': module,
'record_count': record_count,
'include_images': include_images if 'include_images' in locals() else False,
'image_source': image_source if 'image_source' in locals() else None,
'categorias_seleccionadas': categorias_seleccionadas if 'categorias_seleccionadas' in locals() else []
}
# Si es módulo usuarios y JWT está activado, incluir flag y mostrar breakdown
if module == 'usuarios' and include_auth:
module_data['_include_system_users'] = True
usuarios_mock = max(0, record_count - 2)
# ✅ MEJORA: Mostrar breakdown visual con métricas
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Total", record_count, help="Total de usuarios que se generarán")
with col2:
st.metric("Sistema", 2, help="Admin + Usuario normal (automáticos)")
with col3:
st.metric("Mock", usuarios_mock, help="Usuarios de prueba generados")
# ✅ CORRECCIÓN: Mensaje mejorado
if usuarios_mock > 0:
st.info(f"🔐 {record_count} usuarios totales: 2 del sistema + {usuarios_mock} mock")
else:
st.info(f"🔐 {record_count} usuarios totales (solo del sistema)")
modules.append(module_data)
# ✅✅✅ CORRECCIÓN: FUSIONAR MÓDULOS USUARIOS DUPLICADOS EN MODO HÍBRIDO
user_modules = [m for m in modules if m['name'] == 'usuarios']
if len(user_modules) > 1:
# Encontrar módulo mock (configurable) y módulo sistema (automático)
mock_user_module = next((m for m in user_modules if m['source'] == 'mock'), None)
system_user_module = next((m for m in user_modules if m['source'] == 'system'), None)
if mock_user_module and system_user_module:
# ✅ CORRECCIÓN: Los 2 usuarios del sistema YA ESTÁN INCLUIDOS en el total configurado
# Solo fusionar manteniendo el módulo mock y eliminando el sistema
mock_user_module['_include_system_users'] = True # Flag para generador
# Eliminar el módulo sistema
modules = [m for m in modules if not (m['name'] == 'usuarios' and m['source'] == 'system')]
st.info(f"🔍 Módulos usuarios fusionados: {mock_user_module['record_count']} usuarios totales (incluye 2 del sistema)")
# CONFIGURACIÓN AVANZADA
st.subheader("⚙️ Configuración Avanzada")
adv_col1, adv_col2 = st.columns(2)
with adv_col1:
cors_enabled = st.checkbox("🌐 Habilitar CORS", value=True)
rate_limiting = st.checkbox("⏱️ Rate Limiting", value=True)
file_uploads = st.checkbox("📁 Manejo de archivos", value=True)
include_migrations = st.checkbox("🔄 Migraciones Alembic", value=True)
pagination_size = st.slider("Tamaño de paginación:", 3, 100, 25)
with adv_col2:
logging_level = st.selectbox("Nivel de logging:", ["DEBUG", "INFO", "WARNING", "ERROR"])
include_tests = st.checkbox("🧪 Incluir tests automatizados", value=True)
generate_sdk = st.checkbox("📦 Generar SDK cliente", value=True)
populate_db = st.checkbox("🌱 Poblar BD con datos mock", value=True)
# GENERACIÓN DE LA API
st.subheader("🎉 Generar API")
if not modules:
st.warning("Agrega al menos un módulo para generar la API")
return
# Mostrar resumen
st.write("### 📋 Resumen de la API")
summary_col1, summary_col2, summary_col3 = st.columns(3)
with summary_col1:
st.metric("Módulos", len(modules))
st.metric("Tecnología", technology.split(" ")[0])
with summary_col2:
st.metric("Base de datos", database.split(" ")[0])
st.metric("Autenticación", "Sí" if include_auth else "No")
with summary_col3:
# ✅✅✅ CORRECCIÓN CRÍTICA: CÁLCULO CORRECTO DE REGISTROS TOTALES
total_records = 0
for mod in modules:
if mod['name'] == 'categorias':
# Para categorías, usar el valor automático configurado (que es el real)
total_records += mod['record_count']
else:
# Para otros módulos, usar el valor configurado
total_records += mod.get('record_count', len(mod.get('data', [])))
st.metric("Registros totales", total_records)
st.metric("Docker", "Sí" if include_docker else "No")
# Información del sistema de imágenes - ACTUALIZADA CON LEXICA
with st.expander("📸 Sistema de Imágenes Configurado", expanded=False):
st.write("**🎯 Orden de Prioridad:**")
st.write("1. 🥇 **Lexica** - Búsquedas específicas con AI (Siempre disponible)")
st.write("2. 🥈 **Pollinations** - Imágenes generadas por IA coherentes")
st.write("3. 🥉 **Pixabay** - Fotos reales libres de derechos")
st.write("4. 📸 **Pexels** - Backup con calidad alta")
st.write("5. 🪄 **Placeholder** - Último recurso (Siempre disponible)")
st.info("**💡 Orden automático:** Lexica → Pollinations → Pixabay → Pexels → Placeholder")
if apis_configuradas:
st.success(f"**APIs Configuradas:** {', '.join(apis_configuradas)}")
else:
st.info("**Modo automático:** Se usará Lexica + Pollinations + Placeholders")
if st.button("⚡ Generar API Completa", type="primary", use_container_width=True):
with st.spinner("🚀 Generando API profesional para E-commerce..."):
try:
api_structure = generate_complete_api(
project_name=project_name,
technology=technology,
database=database,
modules=modules,
include_auth=include_auth,
include_docs=include_docs,
include_docker=include_docker,
api_version=api_version,
cors_enabled=cors_enabled,
rate_limiting=rate_limiting,
file_uploads=file_uploads,
include_migrations=include_migrations,
pagination_size=pagination_size,
include_tests=include_tests,
generate_sdk=generate_sdk,
logging_level=logging_level,
populate_db=populate_db
)
zip_buffer = create_api_zip(api_structure, project_name)
st.success("✅ API generada exitosamente!")
with st.expander("🚀 Instrucciones de Despliegue", expanded=True):
show_deployment_instructions(technology, database, project_name)
st.download_button(
label="📥 Descargar API Completa",
data=zip_buffer,
file_name=f"{project_name}.zip",
mime="application/zip",
use_container_width=True
)
with st.expander("🔗 Endpoints Generados", expanded=True):
show_generated_endpoints(modules)
except Exception as e:
st.error(f"❌ Error generando API: {str(e)}")
st.error("💡 Revisa la configuración y vuelve a intentar")
def infer_entity_name(filename):
"""Inferir nombre de entidad desde el nombre del archivo"""
name = filename.split('.')[0].lower()
entity_map = {
# 'clientes': 'usuarios',
'users': 'usuarios',
'products': 'productos',
'items': 'productos',
'orders': 'pedidos',
'sales': 'ventas',
'cart': 'carrito',
'payments': 'pagos',
'reviews': 'reseñas',
'coupons': 'cupones',
'addresses': 'direcciones'
}
return entity_map.get(name, name)
def generate_complete_api(**kwargs):
"""Generar estructura completa de la API - VERSIÓN CORREGIDA"""
technology = kwargs['technology'].split(' ')[0].lower()
print(f"🚀 Generando API completa:")
print(f" Tecnología: {technology}")
print(f" Base de datos: {kwargs['database']}")
print(f" Módulos: {len(kwargs['modules'])}")
if technology == 'fastapi':
return generate_fastapi_structure(**kwargs)
elif technology == 'flask':
return generate_flask_structure(**kwargs)
elif technology == 'django':
return generate_django_structure(**kwargs)
elif technology == 'spring':
return generate_springboot_structure(**kwargs)
elif technology == 'express.js':
return generate_express_structure(**kwargs)
else:
return generate_fastapi_structure(**kwargs)
def create_api_zip(api_structure, project_name):
"""Crear archivo ZIP con la estructura de la API - CON MÉTRICAS FUNCIONALES"""
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
for file_path, content in api_structure.items():
if content is not None:
dir_path = os.path.dirname(f"{project_name}/{file_path}")
if dir_path and dir_path not in zip_file.namelist():
zip_file.writestr(f"{dir_path}/", "")
zip_file.writestr(f"{project_name}/{file_path}", content)
zip_buffer.seek(0)
zip_data = zip_buffer.getvalue()
# ✅ CORREGIDO: Importación simple - NO crear nueva instancia
try:
file_size = len(zip_data)
# Importar directamente la instancia que YA EXISTE
from metrics_dashboard import metrics_dashboard
# Registrar la métrica
success = metrics_dashboard.record_download(
module_type="api", # ✅ Usar "api" en lugar de "api_generator"
file_type="zip",
file_size=file_size
)
if success:
st.toast("✅ Descarga de API registrada en estadísticas", icon="📊")
else:
st.toast("⚠️ API generada - Error registrando métricas", icon="📦")
except ImportError as e:
st.toast(f"⚠️ API generada - Métricas no disponibles: {e}", icon="📦")
except Exception as e:
st.toast(f"⚠️ API generada - Error: {e}", icon="📦")
return zip_data
# ✅ AGREGADO: Función para registrar métrica de descarga de API
# def register_api_download_metric():
# """Función para registrar métrica de descarga de API - VERSIÓN CORREGIDA"""
# try:
# # ✅ CORREGIDO: Obtener el tamaño desde session_state
# file_size = st.session_state.get('api_zip_size', 0)
# # Importar el dashboard de métricas
# from utils.metrics_dashboard import metrics_dashboard
# metrics_dashboard.record_download(
# module_type="api_generator",
# file_type="zip",
# file_size=file_size
# )
# st.toast("✅ Descarga de API registrada en estadísticas", icon="📊")
# except Exception as e:
# st.error(f"Error registrando métrica de API: {e}")
def show_deployment_instructions(technology, database, project_name):
"""Mostrar instrucciones de despliegue mejoradas"""
st.write("### 🚀 Comandos de Despliegue Rápido")
code_instructions = f'''
# 1. Navegar al directorio del proyecto
cd {project_name}
# 2. Crear y activar entorno virtual con Python 3.12
# 🪟 En Windows (PowerShell)
python -m venv .venv
.\\.venv\\Scripts\\activate
# 🐧 En Linux / macOS
python3.12 -m venv .venv
source .venv/bin/activate
# 3. Instalar dependencias
pip install --upgrade pip
pip install -r requirements.txt
# 4. Ejecutar la API
uvicorn main:app --reload
# 5. Abrir en navegador
# http://localhost:8000/docs
# http://localhost:8000/redoc
# 6. Poblar la base de datos (si no se pobló automáticamente)
python scripts/populate_db.py
# 7. (Opcional) Desactivar el entorno virtual
deactivate
'''
st.code(code_instructions, language='bash')
st.write("### 📊 Verificación de Endpoints")
verify_code = '''
# Verificar que la API esté funcionando
curl http://localhost:8000/
# Verificar health check
curl http://localhost:8000/health
# Listar productos (ejemplo)
curl http://localhost:8000/api/v1/productos
'''
st.code(verify_code, language='bash')
if 'docker' in technology.lower():
st.write("### 🐳 Con Docker")
docker_instructions = f'''
# Construir y ejecutar
docker-compose up -d
# Ver logs
docker-compose logs -f
# Detener
docker-compose down
'''
st.code(docker_instructions, language='bash')
def show_generated_endpoints(modules):
"""Mostrar endpoints generados mejorados"""
st.write("### 🔗 Endpoints Generados")
for module in modules:
st.write(f"#### 📦 Módulo: {module['name']}")
endpoints = [
f"`GET {module['route']}` - Listar {module['name']} (paginado)",
f"`POST {module['route']}` - Crear {module['name']}",
f"`GET {module['route']}/{{id}}` - Obtener {module['name']} por ID",
f"`PUT {module['route']}/{{id}}` - Actualizar {module['name']}",
f"`DELETE {module['route']}/{{id}}` - Eliminar {module['name']}",
f"`GET {module['route']}/search?q=term` - Buscar {module['name']}"
]
for endpoint in endpoints:
st.write(endpoint)
def generate_fastapi_structure(**kwargs):
"""Generar estructura para FastAPI - VERSIÓN COMPLETAMENTE FUNCIONAL"""
structure = {}
project_name = kwargs['project_name']
database = kwargs['database']
print(f"🔧 Iniciando generación de API FastAPI:")
print(f" 📊 Base de datos: {database}")
print(f" 📦 Módulos: {len(kwargs['modules'])}")
for i, module in enumerate(kwargs['modules']):
print(f" {i+1}. {module['name']} (tipo: {module.get('type', 'N/A')}, source: {module['source']})")
# ✅ GENERAR SCRIPTS SQL CON VERIFICACIÓN
try:
sql_script_content = generate_sql_scripts(**kwargs)
init_script_content = generate_init_database_script(**kwargs)
print(f" ✅ Scripts SQL generados:")
print(f" 📄 init_database.sql: {len(sql_script_content)} caracteres")
print(f" 🐍 init_database.py: {len(init_script_content)} caracteres")
# ✅ CORREGIDO: Usar 'in' en lugar de lista fija
if ('PostgreSQL' in database or 'MySQL' in database) and len(sql_script_content) > 50:
first_line = sql_script_content.split('\n')[0]
print(f" 👀 SQL: {first_line}...")
except Exception as e:
print(f" ❌ Error generando scripts SQL: {e}")
# Fallback para no romper la generación
sql_script_content = f"# Error generando script SQL: {str(e)}"
init_script_content = f"# Error generando script Python: {str(e)}"
# ESTRUCTURA PRINCIPAL
structure.update({
# Archivos raíz
"main.py": generate_fastapi_main(**kwargs),
"requirements.txt": generate_requirements_txt(**kwargs),
"Dockerfile": generate_dockerfile(**kwargs) if kwargs['include_docker'] else "",
"docker-compose.yml": generate_docker_compose(**kwargs) if kwargs['include_docker'] else "",
"README.md": generate_readme(**kwargs),
".env.example": generate_env_example(**kwargs),
# Configuración
"config.py": generate_config_file(**kwargs),
"database.py": generate_database_config(**kwargs),
# ✅ SCRIPTS SQL (siempre se generan, pero el contenido varía)
"scripts/init_database.sql": sql_script_content,
"scripts/init_database.py": init_script_content,
# Modelos
"models/__init__.py": generate_models_init(**kwargs),
"models/base.py": generate_base_model(**kwargs),
"schemas/__init__.py": "",
# Routers
"routers/__init__.py": generate_routers_init(**kwargs),
# Datos
"data/__init__.py": "# Datos mock para población inicial\n",
# Utils
"utils/__init__.py": "",
"utils/auth.py": generate_auth_utils(**kwargs) if kwargs['include_auth'] else "",
"utils/rate_limit.py": generate_rate_limit_utils(**kwargs) if kwargs['rate_limiting'] else "",
"utils/file_upload.py": generate_file_upload_utils(**kwargs) if kwargs['file_uploads'] else "",
"utils/image_generator.py": generate_image_generator_utils(**kwargs),
"utils/backup_manager.py": generate_backup_manager(**kwargs),
# Scripts
"scripts/__init__.py": "",
"scripts/populate_db.py": generate_populate_script(**kwargs) if kwargs['populate_db'] else "",
})
# Router de autenticación
if kwargs['include_auth']:
structure["routers/auth.py"] = generate_auth_router(**kwargs)
# Migraciones Alembic
if kwargs['include_migrations']:
structure.update({
"alembic.ini": generate_alembic_ini(**kwargs),
"alembic/env.py": generate_alembic_env(**kwargs),
"alembic/script.py.mako": generate_alembic_script_mako(**kwargs),
"alembic/versions/.gitkeep": "",
})
# Generar módulos específicos
print("🔧 Generando módulos específicos...")
for module in kwargs['modules']:
module_name = module['name']
module_type = module.get('type', 'generic')
print(f" 📦 Generando módulo: {module_name}")
# Modelo
structure[f"models/{module_name}.py"] = generate_fastapi_model(module, **kwargs)
# Schema
structure[f"schemas/{module_name}.py"] = generate_fastapi_schema(module, **kwargs)
# Router
structure[f"routers/{module_name}.py"] = generate_fastapi_router(module, **kwargs)
# Datos mock
if module['source'] == 'mock' and kwargs['populate_db']:
print(f" 📊 Generando datos mock para: {module_name}")
try:
mock_data = generate_mock_data(module, **kwargs)
if mock_data:
structure[f"data/{module_name}_data.py"] = mock_data
print(f" ✅ Datos mock generados para: {module_name}")
else:
print(f" ⚠️ No se generaron datos para: {module_name}")
except Exception as e:
print(f" ❌ Error generando datos para {module_name}: {e}")
structure[f"data/{module_name}_data.py"] = f"# Error generando datos para {module_name}\n# {str(e)}\n"
# Tests
if kwargs['include_tests']:
structure.update({
"tests/__init__.py": "",
"tests/test_api.py": generate_tests(**kwargs),
"tests/conftest.py": generate_test_config(**kwargs),
"tests/test_auth.py": generate_auth_tests(**kwargs) if kwargs['include_auth'] else "",
})
# SDK cliente
if kwargs['generate_sdk']:
structure.update({
f"client/{project_name}_client.py": generate_python_client(**kwargs),
"client/package.json": generate_js_client_package(**kwargs),
"client/index.js": generate_js_client(**kwargs),
"client/types.ts": generate_typescript_types(**kwargs),
})
print(f"✅ Estructura de API generada exitosamente!")
print(f"📊 Resumen final: {len(kwargs['modules'])} módulos, {len(structure)} archivos")
# ✅ CORREGIDO: Usar 'in' en lugar de lista fija
if 'PostgreSQL' in database or 'MySQL' in database:
print(f"🗄️ Scripts SQL para {database} generados correctamente")
print(f" 📄 scripts/init_database.sql - Para crear BD y tablas en producción")
print(f" 🐍 scripts/init_database.py - Para inicialización automática")
else:
print(f"🗄️ Base de datos SQLite - Scripts SQL básicos generados")
return structure
def generate_routers_init(**kwargs):
"""Generar __init__.py para routers"""
imports = []
for module in kwargs['modules']:
imports.append(f"from .{module['name']} import router as {module['name']}_router")
if kwargs['include_auth']:
imports.append("from .auth import router as auth_router")
imports_str = "\n".join(imports)
routers_list = [f'"{module["name"]}_router"' for module in kwargs['modules']]
if kwargs['include_auth']:
routers_list.append('"auth_router"')
routers_str = ', '.join(routers_list)
return f'''{imports_str}
__all__ = [{routers_str}]
'''
def generate_requirements_txt(**kwargs):
"""Generar requirements.txt con versiones actualizadas"""
requirements = [
"fastapi==0.104.1",
"uvicorn[standard]==0.24.0",
"sqlalchemy==2.0.23",
"alembic==1.12.1",
"pydantic==2.8.2",
"pydantic[email]==2.8.2",
"pydantic-core==2.20.1",
"python-multipart==0.0.6",
"python-jose[cryptography]==3.3.0",
"passlib[bcrypt]==1.7.4",
"bcrypt<4.1",
"python-dotenv==1.0.0",
"faker==19.6.2",
"requests==2.31.0",
"slowapi==0.1.9",
"aiohttp==3.9.1"
]
if kwargs['database'] == 'PostgreSQL':
requirements.append("psycopg2-binary==2.9.9")
elif kwargs['database'] == 'MySQL':
requirements.append("mysql-connector-python==8.2.0")
return "\n".join(requirements)
#######################AGREGADO LEXICA - VERSIÓN CORREGIDA
def generate_image_generator_utils(**kwargs):
"""Generar sistema con CACHE PERSISTENTE: Lexica → Pollinations → Pixabay → Pexels → Placeholder"""
pexels_api_key = st.session_state.get('pexels_api_key', "TU_API_KEY_PEXELS_AQUI")
pixabay_api_key = st.session_state.get('pixabay_api_key', "TU_API_KEY_PIXABAY_AQUI")
# Evaluar las condiciones ANTES de crear el string - CORREGIDO
pixabay_configured = pixabay_api_key and pixabay_api_key != "TU_API_KEY_PIXABAY_AQUI"
pexels_configured = pexels_api_key and pexels_api_key != "TU_API_KEY_PEXELS_AQUI"
pixabay_status = '✅ Configurada' if pixabay_configured else '❌ No configurada'
pexels_status = '✅ Configurada' if pexels_configured else '❌ No configurada'
return f'''import requests
import random
import time
import hashlib
import json
import os
import sqlite3
from pathlib import Path
from typing import Optional, Dict
from urllib.parse import quote
class ImageGenerator:
"""Sistema con CACHE PERSISTENTE: Lexica → Pollinations → Pixabay → Pexels → Placeholder"""
def __init__(self, pexels_api_key: Optional[str] = None, pixabay_api_key: Optional[str] = None):
self.pexels_api_key = pexels_api_key or "TU_API_KEY_PEXELS_AQUI"
self.pixabay_api_key = pixabay_api_key or "TU_API_KEY_PIXABAY_AQUI"
# ✅ SOLUCIÓN: CACHE PERSISTENTE EN SQLITE
self.cache_db = "image_cache.db"
self._init_cache_db()
self.request_count = 0
self.fallback_count = 0
print("🔧 ImageGenerator MEJORADO inicializado con CACHE PERSISTENTE")
print(" 🥇 Lexica: ✅ Siempre disponible")
print(" 🥈 Pollinations: ✅ Siempre disponible")
print(" 🥉 Pixabay: {pixabay_status}")
print(" 📸 Pexels: {pexels_status}")
print(" 🪄 Placeholder: ✅ Siempre disponible")
print(" 💾 Cache: ✅ Persistente (SQLite)")
# 🎯 ORDEN DE PRIORIDAD
self.priority_order = ["lexica", "pollinations", "pixabay", "pexels", "placeholder"]
# 🎯 SISTEMA DE BÚSQUEDA HIPER-ESPECÍFICO
self.product_specific_queries = {{
# ELECTRÓNICA
'Auriculares Inalámbricos Premium': 'wireless headphones product photography isolated',
'Smartwatch Deportivo Avanzado': 'sports smartwatch fitness tracker wearable',
'Tablet 10 Pulgadas Pro': 'tablet device screen technology',
'Altavoz Bluetooth Potente': 'bluetooth speaker audio sound',
'Cámara Digital 4K Profesional': 'digital camera photography 4k',
'Drone Profesional GPS': 'drone aerial camera flying',
'Consola Videojuegos Next-Gen': 'gaming console video games',
'Smart TV 55" 4K UHD': 'smart tv television screen',
'Laptop Ultradelgada Gaming': 'gaming laptop computer thin',
'Smartphone Flagship': 'smartphone mobile phone',
'Reloj Inteligente Fitness': 'fitness smartwatch health',
'Cámara Deportiva Resistente': 'sports camera action waterproof',
# TECNOLOGÍA
'Monitor Curvo 27" Gaming': 'gaming monitor curved screen',
'Teclado Mecánico RGB Pro': 'mechanical keyboard rgb gaming',
'Ratón Gaming Precision': 'gaming mouse computer precision',
'Disco SSD 1TB NVMe': 'ssd storage computer hardware',
'Router WiFi 6 AX': 'wifi router internet network',
'Impresora Láser Color': 'laser printer office color',
'Webcam 4K Streaming': 'webcam streaming video conference',
'Micrófono Estudio USB': 'microphone studio recording usb',
'Silla Ergonómica Ejecutiva': 'ergonomic chair office executive',
# HOGAR
'Robot Aspirador Inteligente': 'robot vacuum cleaner smart home',
'Batidora Potente Profesional': 'blender kitchen appliance professional',
'Cafetera Automática Premium': 'coffee maker automatic premium',
'Licuadora Profesional': 'blender professional kitchen',
'Tostadora Digital LCD': 'toaster digital kitchen',
'Horno Eléctrico Multifunción': 'electric oven kitchen multi-function',
'Freidora de Aire Digital': 'air fryer digital kitchen',
'Plancha de Vapor Professional': 'steam iron clothing professional',
'Purificador Aire HEPA': 'air purifier hepa filter',
# ROPA
'Camiseta Algodón Orgánico': 'cotton t-shirt organic clothing',
'Jeans Elásticos Premium': 'jeans denim pants stretch',
'Zapatillas Running Tech': 'running shoes athletic sneakers',
'Chaqueta Impermeable Outdoor': 'waterproof jacket outdoor',
'Sudadera con Capucha Algodón': 'hoodie sweatshirt cotton',
'Vestido Elegante Noche': 'elegant dress evening night',
'Falda Plisada Casual': 'pleated skirt casual',
'Chándal Deportivo Performance': 'tracksuit sportswear performance',
'Abrigo Invierno Lana': 'wool coat winter',
# DEPORTES
'Pelota Fútbol Profesional': 'soccer ball football professional',
'Raqueta Tenis Competición': 'tennis racket competition',
'Balón Baloncesto Official': 'basketball official sports',
'Bicicleta Montaña Suspensión': 'mountain bike suspension',
'Pesas Ajustables Hex': 'dumbbells weights hex adjustable',
'Cinta Correr Plegable': 'treadmill running foldable',
'Eliptica Casa Magnetic': 'elliptical machine magnetic home',
'Mancuernas Acero Cromado': 'dumbbells chrome steel',
'Pelota Yoga Anti-Burst': 'yoga ball anti-burst',
# JUGUETES
'Juguetes Educativos Interactivos': 'educational toys interactive children',
'Set de Construcción Creativa': 'construction building toys creative',
'Muñeca Articulada Premium': 'doll articulated premium toy',
'Kit de Ciencia para Niños': 'science kit children educational',
'Puzzle 1000 Piezas Premium': 'puzzle 1000 pieces premium',
'Juego de Mesa Familiar': 'board game family entertainment',
'Peluche Suave Premium': 'stuffed animal plush soft',
'Set de Arte Infantil': 'art set children creative',
'Juguetes de Exterior': 'outdoor toys children play',
# LIBROS
'Libro de Ficción Best Seller': 'book fiction bestseller reading',
'Novela Romántica Bestseller': 'romance novel book bestseller',
'Libro de Autoayuda Motivacional': 'self-help book motivational',
'Enciclopedia Ilustrada': 'encyclopedia illustrated reference',
'Libro de Cocina Gourmet': 'cookbook gourmet recipes',
'Novela de Misterio Thriller': 'mystery thriller novel book',
'Libro Infantil Educativo': 'children book educational',
'Biografía de Personalidad': 'biography book personality',
'Libro de Historia Antigua': 'history book ancient',
# MÚSICA
'Guitarra Acústica Profesional': 'acoustic guitar professional music',
'Teclado Digital 88 Teclas': 'digital keyboard 88 keys',
'Batería Electrónica Completa': 'electronic drum set complete',
'Micrófono de Estudio Condensador': 'condenser microphone studio',
'Altavoz Bluetooth Portátil': 'portable bluetooth speaker',
'Auriculares Studio Monitor': 'studio monitor headphones',
'Amplificador Guitarra 100W': 'guitar amplifier 100w',
'Piano Digital de Cola': 'digital piano grand',
'Consola Mezcladora 8 Canales': 'mixing console 8 channels',
# BELLEZA
'Kit de Maquillaje Profesional': 'makeup kit professional beauty',
'Secador de Pelo Iónico': 'ionic hair dryer professional',
'Plancha Alisadora Cerámica': 'ceramic flat iron hair',
'Crema Facial Anti-Edad': 'anti-aging face cream',
'Paleta de Sombras 12 Colores': 'eyeshadow palette 12 colors',
'Labial Líquido Mate Duradero': 'liquid lipstick matte long-lasting',
'Perfume Fragancia Exclusive': 'perfume fragrance exclusive',
'Serum Facial Vitamina C': 'vitamin c serum face',
'Base Líquida Alta Cobertura': 'liquid foundation full coverage',
# SALUD
'Tensiómetro Digital Brazo': 'blood pressure monitor digital arm',
'Glucómetro Kit Completo': 'glucometer kit complete diabetes',
'Nebulizador Portátil': 'portable nebulizer asthma',
'Termómetro Digital Infrarrojo': 'infrared digital thermometer',
'Monitor de Sueño Smart': 'smart sleep monitor health',
'Masajeador Percusión Profunda': 'percussion massager deep tissue',
'Vitamina C 1000mg': 'vitamin c 1000mg supplements',
'Omega 3 1000mg': 'omega 3 fish oil supplements',
'Colágeno Hidrolizado': 'hydrolyzed collagen supplements',
# ALIMENTOS
'Aceite Oliva Extra Virgen': 'olive oil extra virgin bottle',
'Miel Natural Pura': 'honey natural jar',
'Café Molido Premium': 'coffee ground premium bag',
'Chocolate Negro 70% Cacao': 'dark chocolate 70% cocoa',
'Mermelada Fresa Artesanal': 'strawberry jam artisanal jar',
'Pasta Integral Orgánica': 'pasta organic whole wheat',
'Salsa Tomate Natural': 'tomato sauce natural jar',
'Galletas Integrales Sin Azúcar': 'cookies whole grain sugar-free',
'Cereal Energético Natural': 'cereal energy natural box',
# BEBIDAS
'Vino Tinto Reserva': 'red wine bottle reserve',
'Cerveza Artesanal IPA': 'craft beer IPA bottle',
'Jugo Naranja Natural': 'orange juice natural bottle',
'Agua Mineral Con Gas': 'sparkling water mineral bottle',
'Refresco Cola Zero': 'cola soda zero can',
'Té Verde Matcha': 'matcha green tea powder',
'Café Molido Expresso': 'espresso coffee ground',
'Batido Proteínas Natural': 'protein shake natural bottle',
'Agua Saborizada Limón': 'lemon flavored water bottle',
# AUTOMOTRIZ
'Llantas Aleación 17 Pulgadas': 'alloy wheels 17 inches automotive',
'Batería Auto 12V 60Ah': 'car battery 12v 60ah automotive',
'Aceite Motor Sintético 5W-30': 'synthetic motor oil 5w-30',
'Kit Herramientas Mecánico': 'mechanic tool kit automotive',
'GPS Navegador Dash Cam': 'gps navigator dash cam automotive',
'Limpiaparabrisas Originales': 'windshield wipers original automotive',
'Cargador Batería Automático': 'battery charger automatic automotive',
'Compresor Aire Portátil': 'portable air compressor automotive',
'Cera Autolavado Premium': 'car wax premium automotive',
# JARDÍN
'Cortadora Césped Eléctrica': 'lawn mower electric garden',
'Set Herramientas Jardinería': 'gardening tools set garden',
'Manguera Reforzada 20m': 'reinforced hose 20m garden',
'Cortasetos Eléctrico Profesional': 'electric hedge trimmer professional garden',
'Aspersor Rotatorio Ajustable': 'rotary sprinkler adjustable garden',
'Tijeras Podar Premium': 'pruning shears premium garden',
'Carretilla Jardín 100L': 'garden wheelbarrow 100l',
'Regador Metalico Clásico': 'metal watering can classic garden',
'Guantes Jardinería Cuero': 'leather gardening gloves',
# OFICINA
'Silla Ergonómica Ejecutiva': 'ergonomic chair office executive',
'Escritorio Oficina Ajustable': 'adjustable office desk',
'Organizador Archivos A-Z': 'file organizer a-z office',
'Calculadora Científica Avanzada': 'scientific calculator advanced office',
'Engrapadora Profesional Metálica': 'metal stapler professional office',
'Set Lapiceras Gel': 'gel pens set office',
'Pizarra Blanca Magnética': 'whiteboard magnetic office',
'Resaltadores Fluorescentes': 'fluorescent highlighters office',
'Tijeras Oficina Precision': 'office scissors precision',
# COMIDAS DULCES (RESTAURANTE)
'Torta de Chocolate Negro': 'chocolate cake dessert',
'Tiramisú Clásico': 'tiramisu classic dessert',
'Cheesecake de Frutos Rojos': 'cheesecake red berries',
'Pastel de Tres Leches': 'tres leches cake',
'Mousse de Chocolate': 'chocolate mousse dessert',
'Flan de Coco': 'coconut flan dessert',
'Brownie con Helado': 'brownie with ice cream',
'Crema Brûlée': 'creme brulee dessert',
'Profiteroles con Chocolate': 'profiteroles chocolate dessert',
# COMIDAS SALADAS (RESTAURANTE)
'Hamburguesa Gourmet con Queso': 'gourmet burger cheese',
'Pollo a la Parrilla con Hierbas': 'grilled chicken herbs',
'Empanadas de Carne Criollas': 'beef empanadas traditional',
'Costillas BBQ Ahumadas': 'bbq ribs smoked',
'Pizza Margherita Artesanal': 'margherita pizza artisanal',
'Tacos al Pastor Mexicanos': 'al pastor tacos mexican',
'Sándwich Club Triple': 'club sandwich triple',
'Lasagna de Carne y Queso': 'lasagna meat cheese',
# BEBIDAS (RESTAURANTE)
'Jugo Natural de Naranja Fresca': 'fresh orange juice glass',
'Smoothie de Frutas Tropicales': 'tropical fruit smoothie',
'Café Espresso Premium': 'espresso coffee premium',
'Té Verde Matcha Orgánico': 'matcha green tea organic',
'Limonada Natural con Menta': 'lemonade mint fresh',
'Agua Mineral con Gas': 'sparkling water glass',
'Refresco de Frutas Natural': 'natural fruit soda',
'Batido Proteico Energético': 'protein shake energetic'
}}
def _init_cache_db(self):
"""✅ SOLUCIÓN: Inicializar base de datos para cache persistente"""
try:
conn = sqlite3.connect(self.cache_db)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS image_cache (
product_key TEXT PRIMARY KEY,
image_url TEXT NOT NULL,
source TEXT NOT NULL,
product_name TEXT,
category TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# ✅ Crear índice para búsquedas más rápidas
cursor.execute('CREATE INDEX IF NOT EXISTS idx_product_key ON image_cache(product_key)')
conn.commit()
conn.close()
print("💾 Cache de imágenes persistente inicializado")
except Exception as e:
print(f"❌ Error inicializando cache persistente: {{e}}")
def _get_cached_image(self, product_key: str) -> Optional[str]:
"""✅ SOLUCIÓN: Obtener imagen del cache persistente"""
try:
conn = sqlite3.connect(self.cache_db)
cursor = conn.cursor()
cursor.execute(
'SELECT image_url, source FROM image_cache WHERE product_key = ?',
(product_key,)
)
result = cursor.fetchone()
conn.close()
if result:
image_url, source = result
print(f"💾 Imagen desde CACHE PERSISTENTE: '{{product_key}}' (fuente: {{source}})")
return image_url
return None
except Exception as e:
print(f"❌ Error leyendo cache persistente: {{e}}")
return None
def _save_to_cache(self, product_key: str, image_url: str, source: str, product_name: str, category: str):
"""✅ SOLUCIÓN: Guardar imagen en cache persistente"""
try:
conn = sqlite3.connect(self.cache_db)
cursor = conn.cursor()
cursor.execute("""
INSERT OR REPLACE INTO image_cache
(product_key, image_url, source, product_name, category, created_at)
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
""", (product_key, image_url, source, product_name, category))
conn.commit()
conn.close()
print(f"💾 Guardado en CACHE PERSISTENTE: '{{product_name}}' -> {{source}}")
except Exception as e:
print(f"❌ Error guardando en cache persistente: {{e}}")
def get_cache_stats(self) -> Dict:
"""✅ NUEVO: Obtener estadísticas del cache persistente"""
try:
conn = sqlite3.connect(self.cache_db)
cursor = conn.cursor()
# Total de imágenes en cache
cursor.execute('SELECT COUNT(*) FROM image_cache')
total_cached = cursor.fetchone()[0]
# Imágenes por fuente
cursor.execute('SELECT source, COUNT(*) FROM image_cache GROUP BY source')
sources = cursor.fetchall()
# Categorías en cache
cursor.execute('SELECT category, COUNT(*) FROM image_cache GROUP BY category')
categories = cursor.fetchall()
conn.close()
return {{
"total_cached_images": total_cached,
"sources": dict(sources),
"categories": dict(categories),
"cache_file": self.cache_db,
"cache_size_kb": os.path.getsize(self.cache_db) / 1024 if os.path.exists(self.cache_db) else 0
}}
except Exception as e:
return {{"error": str(e)}}
def clear_cache(self):
"""✅ NUEVO: Limpiar cache persistente"""
try:
if os.path.exists(self.cache_db):
os.remove(self.cache_db)
self._init_cache_db()
print("🗑️ Cache persistente limpiado completamente")
return True
return False
except Exception as e:
print(f"❌ Error limpiando cache: {{e}}")
return False
def _is_pixabay_configured(self):
"""Verificar si Pixabay está configurado correctamente"""
return (self.pixabay_api_key and
self.pixabay_api_key != "TU_API_KEY_PIXABAY_AQUI" and
len(self.pixabay_api_key) > 10)
def _is_pexels_configured(self):
"""Verificar si Pexels está configurado correctamente"""
return (self.pexels_api_key and
self.pexels_api_key != "TU_API_KEY_PEXELS_AQUI" and
len(self.pexels_api_key) > 10)
def get_hyper_specific_query(self, product_name: str, category: str) -> str:
"""Generar query HIPER-ESPECÍFICA basada en el nombre exacto del producto"""
# Primero buscar coincidencia exacta en el mapeo
for product_key, query in self.product_specific_queries.items():
if product_key.lower() in product_name.lower():
print(f"🎯 Query ESPECÍFICA encontrada: '{{query}}' para '{{product_name}}'")
return query
# Si no hay coincidencia, extraer palabras clave del nombre
words = product_name.lower().split()
# Filtrar palabras genéricas y marcas
generic_words = {{'de', 'con', 'para', 'y', 'o', 'la', 'el', 'los', 'las', 'un', 'una',
'premium', 'profesional', 'avanzado', 'digital', 'inteligente', 'natural'}}
brands = {{'zara', 'nike', 'adidas', 'samsung', 'sony', 'lg', 'apple', 'bose', 'jbl',
'philips', 'dell', 'hp', 'lenovo', 'logitech', 'bosch', 'black+decker',
'miele', 'rowenta', 'tefal', 'nestlé', 'coca-cola', 'pepsi'}}
# Tomar las 3-4 palabras más relevantes
relevant_words = [word for word in words if (word not in generic_words and
word not in brands and
len(word) > 2)]
if len(relevant_words) >= 2:
specific_query = ' '.join(relevant_words[:3])
else:
# Fallback: usar categoría + primera palabra relevante
first_relevant = relevant_words[0] if relevant_words else category.lower()
specific_query = f"{{first_relevant}} {{category.lower()}}"
print(f"🔍 Query GENERADA: '{{specific_query}}' para '{{product_name}}'")
return specific_query
def get_lexica_image(self, product_name: str, category: str) -> Optional[str]:
"""🥇 PRIORIDAD 1: Lexica.art - Búsquedas específicas con AI"""
try:
# Query optimizada para Lexica - más específica y directa
search_query = self.get_hyper_specific_query(product_name, category)
cache_key = f"lexica_{{hashlib.md5(product_name.encode()).hexdigest()[:10]}}"
# ✅ SOLUCIÓN: Verificar cache persistente primero
cached_image = self._get_cached_image(cache_key)
if cached_image:
return cached_image
url = "https://lexica.art/api/v1/search"
params = {{
"q": search_query,
"source": "search",
"model": "lexica-aperture-v3"
}}
self.request_count += 1
time.sleep(0.5) # Aumentar delay para evitar rate limiting
print(f"🔍 Lexica 🥇 BUSCANDO: '{{product_name}}' -> '{{search_query}}'")
response = requests.get(url, params=params, timeout=15)
if response.status_code == 200:
data = response.json()
images = data.get("images", [])
if images:
# Filtrar imágenes que parezcan productos reales
product_images = []
for img in images:
prompt = img.get('prompt', '').lower()
if any(keyword in prompt for keyword in ['product', 'photo', 'photography', 'commercial']):
product_images.append(img)
usable_images = product_images if product_images else images
if usable_images:
selected_image = random.choice(usable_images[:5]) # Reducir a 5
image_url = selected_image.get("src")
if image_url:
# ✅ SOLUCIÓN: Guardar en cache persistente
self._save_to_cache(cache_key, image_url, "lexica", product_name, category)
print(f"✅ Lexica 🥇 ENCONTRADO: '{{product_name}}'")
return image_url
print(f"⚠️ Lexica: Sin resultados para '{{search_query}}'")
return None
else:
print(f"❌ Lexica API error {{response.status_code}}")
return None
except Exception as e:
print(f"❌ Error Lexica: {{str(e)}}")
return None
def get_pollinations_image(self, product_name: str, category: str) -> str:
"""🥈 PRIORIDAD 2: Pollinations - Imágenes generadas coherentes"""
try:
cache_key = f"pollinations_{{hashlib.md5(product_name.encode()).hexdigest()[:10]}}"
# ✅ SOLUCIÓN: Verificar cache persistente primero
cached_image = self._get_cached_image(cache_key)
if cached_image:
return cached_image
# Prompts MEJORADOS y más específicos
prompt_variations = [
# Versión específica de producto
f"professional ecommerce product photo of {{product_name}}, studio lighting, high quality, detailed, 8K, commercial product photography, sharp focus, attractive composition",
# Versión con contexto de uso real
f"{{product_name}} in realistic setting, professional product photography, high detail, commercial use, appealing composition, natural lighting",
# Versión estilo catálogo moderno
f"modern ecommerce product shot of {{product_name}}, clean background, professional photography, high quality, detailed texture, commercial use",
# Versión minimalista pero atractiva
f"{{product_name}} product photography, professional studio shot, high detail, commercial quality, attractive lighting, clean composition"
]
prompt = random.choice(prompt_variations)
encoded_prompt = quote(prompt)
seed = int(hashlib.md5(product_name.encode()).hexdigest()[:8], 16) % 10000
image_url = f"https://image.pollinations.ai/prompt/{{encoded_prompt}}?width=800&height=800&seed={{seed}}&nofilter=true"
# ✅ SOLUCIÓN: Guardar en cache persistente
self._save_to_cache(cache_key, image_url, "pollinations", product_name, category)
print(f"🤖 Pollinations 🥈 GENERANDO: '{{product_name}}'")
return image_url
except Exception as e:
print(f"❌ Error Pollinations: {{e}}")
return self.get_placeholder_image(product_name, category)
def get_pixabay_image(self, product_name: str, category: str) -> Optional[str]:
"""🥉 PRIORIDAD 3: Pixabay - Fotos reales libres"""
if not self._is_pixabay_configured():
print(f"❌ Pixabay: API Key no configurada para '{{product_name}}'")
return None
# Generar query HIPER-ESPECÍFICA
search_query = self.get_hyper_specific_query(product_name, category)
cache_key = f"pixabay_{{hashlib.md5(product_name.encode()).hexdigest()[:10]}}"
# ✅ SOLUCIÓN: Verificar cache persistente primero
cached_image = self._get_cached_image(cache_key)
if cached_image:
return cached_image
try:
url = "https://pixabay.com/api/"
params = {{
"key": self.pixabay_api_key,
"q": search_query,
"image_type": "photo",
"orientation": "horizontal",
"per_page": 15,
"safesearch": "true",
"editors_choice": "true",
"category": "objects"
}}
self.request_count += 1
time.sleep(0.3)
print(f"🔍 Pixabay 🥉 BUSCANDO: '{{product_name}}' -> '{{search_query}}'")
response = requests.get(url, params=params, timeout=15)
if response.status_code == 200:
data = response.json()
hits = data.get("hits", [])
if hits:
# Filtrar imágenes que parezcan productos
product_like_hits = []
for hit in hits:
tags = hit.get('tags', '').lower()
if any(keyword in tags for keyword in ['product', 'object', 'item', 'white background', 'isolated']):
product_like_hits.append(hit)
usable_hits = product_like_hits if product_like_hits else hits
if usable_hits:
selected_hit = random.choice(usable_hits[:5])
image_url = selected_hit["largeImageURL"]
# ✅ SOLUCIÓN: Guardar en cache persistente
self._save_to_cache(cache_key, image_url, "pixabay", product_name, category)
print(f"✅ Pixabay 🥉 ENCONTRADO: '{{product_name}}'")
return image_url
print(f"⚠️ Pixabay: Sin resultados para '{{search_query}}'")
return None
else:
print(f"❌ Pixabay API error {{response.status_code}}")
return None
except Exception as e:
print(f"❌ Error Pixabay: {{str(e)}}")
return None
def get_pexels_image(self, product_name: str, category: str) -> Optional[str]:
"""📸 PRIORIDAD 4: Pexels - Backup calidad alta"""
if not self._is_pexels_configured():
print(f"❌ Pexels: API Key no configurada para '{{product_name}}'")
return None
# Generar query HIPER-ESPECÍFICA
search_query = self.get_hyper_specific_query(product_name, category)
cache_key = f"pexels_{{hashlib.md5(product_name.encode()).hexdigest()[:10]}}"
# ✅ SOLUCIÓN: Verificar cache persistente primero
cached_image = self._get_cached_image(cache_key)
if cached_image:
return cached_image
try:
url = "https://api.pexels.com/v1/search"
headers = {{"Authorization": self.pexels_api_key}}
params = {{
"query": search_query,
"per_page": 10,
"orientation": "square"
}}
self.request_count += 1
time.sleep(0.4)
print(f"🔍 Pexels 📸 BUSCANDO: '{{product_name}}' -> '{{search_query}}'")
response = requests.get(url, headers=headers, params=params, timeout=15)
if response.status_code == 200:
data = response.json()
photos = data.get("photos", [])
if photos:
# Filtrar fotos que parezcan productos
product_photos = []
for photo in photos:
alt = photo.get('alt', '').lower()
if any(keyword in alt for keyword in ['product', 'object', 'item']):
product_photos.append(photo)
usable_photos = product_photos if product_photos else photos
if usable_photos:
selected_photo = random.choice(usable_photos[:5])
image_url = selected_photo["src"]["large"]
# ✅ SOLUCIÓN: Guardar en cache persistente
self._save_to_cache(cache_key, image_url, "pexels", product_name, category)
print(f"✅ Pexels 📸 ENCONTRADO: '{{product_name}}'")
return image_url
print(f"⚠️ Pexels: Sin resultados para '{{search_query}}'")
return None
else:
print(f"❌ Pexels API error {{response.status_code}}")
return None
except Exception as e:
print(f"❌ Error Pexels: {{str(e)}}")
return None
def get_placeholder_image(self, product_name: str, category: str) -> str:
"""🪄 PRIORIDAD 5: Placeholder - Último recurso - VERSIÓN CORREGIDA CON TODAS LAS 18 CATEGORÍAS"""
# ✅ CORREGIDO: Colores por categoría - TODAS LAS 18 CATEGORÍAS
category_colors = {{
'Electrónica': '2563EB', 'Tecnología': '059669', 'Hogar': 'DC2626',
'Ropa': '7C3AED', 'Deportes': 'EA580C', 'Juguetes': 'DC2626',
'Libros': '059669', 'Música': '7C3AED', 'Belleza': 'DB2777',
'Salud': '10B981', 'Alimentos': 'D97706', 'Bebidas': '0369A1',
'Automotriz': '475569', 'Jardín': '16A34A', 'Oficina': 'CA8A04',
'Comidas Dulces': 'FF6B6B', 'Comidas Saladas': '4ECDC4'
}}
# ✅ CORREGIDO: Iconos por categoría - TODAS LAS 18 CATEGORÍAS
icon_mapping = {{
'Electrónica': '📱', 'Tecnología': '💻', 'Hogar': '🏠',
'Ropa': '👕', 'Deportes': '⚽', 'Juguetes': '🧸',
'Libros': '📚', 'Música': '🎵', 'Belleza': '💄',
'Salud': '🏥', 'Alimentos': '🍎', 'Bebidas': '🥤',
'Automotriz': '🚗', 'Jardín': '🌻', 'Oficina': '📎',
'Comidas Dulces': '🍰', 'Comidas Saladas': '🍔'
}}
color = category_colors.get(category, '4F46E5')
icon = icon_mapping.get(category, '📦')
display_text = f"{{icon}} {{product_name}}"
if len(display_text) > 30:
display_text = f"{{icon}} {{category}}"
encoded_text = quote(display_text)
return f"https://placehold.co/800x800/{{color}}/FFFFFF?font=montserrat&text={{encoded_text}}"
def generate_product_image(self, product_name: str, category: str,
image_source: str = "priority") -> str:
"""Sistema PRINCIPAL con CACHE PERSISTENTE"""
print(f"🎨 Generando imagen para: '{{product_name}}'")
# ✅ SOLUCIÓN: Cache key única para este producto
cache_key = f"{{image_source}}_{{hashlib.md5(product_name.encode()).hexdigest()[:10]}}"
# ✅ SOLUCIÓN: Verificar cache persistente PRIMERO
cached_image = self._get_cached_image(cache_key)
if cached_image:
return cached_image
try:
# 🎯 NUEVO ORDEN DE PRIORIDAD MEJORADO
if image_source == "priority":
# 🥇 PRIORIDAD 1: Lexica (búsquedas específicas con AI)
print("🚀 Intentando Lexica 🥇...")
lexica_image = self.get_lexica_image(product_name, category)
if lexica_image:
print(f"✅ ÉXITO Lexica 🥇 para '{{product_name}}'")
return lexica_image
else:
print("🔄 Lexica no encontró imagen específica")
# 🥈 PRIORIDAD 2: Pollinations (IA coherente)
print("🚀 Generando con Pollinations 🥈...")
pollinations_image = self.get_pollinations_image(product_name, category)
if pollinations_image and "pollinations.ai" in pollinations_image:
print(f"✅ ÉXITO Pollinations 🥈 para '{{product_name}}'")
return pollinations_image
# 🥉 PRIORIDAD 3: Pixabay (fotos reales libres)
if self._is_pixabay_configured():
print("🔄 Intentando Pixabay 🥉...")
pixabay_image = self.get_pixabay_image(product_name, category)
if pixabay_image:
print(f"✅ ÉXITO Pixabay 🥉 para '{{product_name}}'")
return pixabay_image
# 📸 PRIORIDAD 4: Pexels (backup calidad alta)
if self._is_pexels_configured():
print("🔄 Intentando Pexels 📸...")
pexels_image = self.get_pexels_image(product_name, category)
if pexels_image:
print(f"✅ ÉXITO Pexels 📸 para '{{product_name}}'")
return pexels_image
# 🪄 PRIORIDAD 5: Placeholder (último recurso)
print(f"📦 Usando placeholder 🪄 para '{{product_name}}'")
placeholder_url = self.get_placeholder_image(product_name, category)
# ✅ SOLUCIÓN: No cachear placeholders (son genéricos)
return placeholder_url
else:
# Modo específico para compatibilidad
if image_source.lower() == "lexica":
result = self.get_lexica_image(product_name, category) or self.get_pollinations_image(product_name, category)
elif image_source.lower() == "pollinations":
result = self.get_pollinations_image(product_name, category)
elif image_source.lower() == "pixabay":
result = self.get_pixabay_image(product_name, category) or self.get_pollinations_image(product_name, category)
elif image_source.lower() == "pexels":
result = self.get_pexels_image(product_name, category) or self.get_pollinations_image(product_name, category)
else:
result = self.get_placeholder_image(product_name, category)
# ✅ SOLUCIÓN: Guardar en cache si no es placeholder
if result and "placehold.co" not in result:
self._save_to_cache(cache_key, result, image_source, product_name, category)
return result
except Exception as e:
print(f"💥 Error crítico: {{str(e)}}")
return self.get_placeholder_image(product_name, category)
def get_stats(self) -> Dict:
"""Obtener estadísticas COMPLETAS con cache persistente"""
cache_stats = self.get_cache_stats()
return {{
"total_requests": self.request_count,
"fallbacks": self.fallback_count,
"pixabay_configured": self._is_pixabay_configured(),
"pexels_configured": self._is_pexels_configured(),
"priority_order": self.priority_order,
"cache_persistent": cache_stats
}}
# Instancia global
image_generator = ImageGenerator()
def get_image_generator() -> ImageGenerator:
return image_generator
def configure_image_generator(pexels_api_key: str = None, pixabay_api_key: str = None):
global image_generator
image_generator = ImageGenerator(
pexels_api_key=pexels_api_key,
pixabay_api_key=pixabay_api_key
)
print("🔧 ImageGenerator MEJORADO configurado")
print(" 🥇 Lexica: ✅ Siempre disponible")
print(" 🥈 Pollinations: ✅ Siempre disponible")
print(f" 🥉 Pixabay: {{'✅' if image_generator._is_pixabay_configured() else '❌'}}")
print(f" 📸 Pexels: {{'✅' if image_generator._is_pexels_configured() else '❌'}}")
print(" 🪄 Placeholder: ✅ Siempre disponible")
print(" 💾 Cache: ✅ Persistente (SQLite)")
return image_generator
'''
####agregada
def generate_backup_manager(**kwargs):
"""Generar el archivo backup_manager.py para el sistema de respaldos JSON"""
return '''import json
import os
from datetime import datetime
from typing import List, Dict, Any, Optional
from sqlalchemy.orm import Session
import logging
class BackupManager:
"""
Sistema de respaldo automático en JSON para todas las entidades de la base de datos.
Genera archivos JSON individuales por cada entidad y se actualiza automáticamente.
"""
def __init__(self, backup_dir: str = "backups/json"):
self.backup_dir = backup_dir
self.setup_backup_structure()
self.setup_logging()
print(f"🔧 BackupManager inicializado - Directorio: {backup_dir}")
def setup_backup_structure(self):
"""Crear estructura de directorios para backups"""
os.makedirs(self.backup_dir, exist_ok=True)
os.makedirs(f"{self.backup_dir}/logs", exist_ok=True)
print(f"📁 Estructura de backups creada: {self.backup_dir}")
def setup_logging(self):
"""Configurar logging para backups"""
logging.basicConfig(
filename=f"{self.backup_dir}/logs/backup.log",
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
encoding='utf-8'
)
self.logger = logging.getLogger(__name__)
def export_entity_to_json(self, db: Session, model_class, entity_name: str) -> bool:
"""
Exportar una entidad específica a JSON
Args:
db: Sesión de base de datos
model_class: Clase del modelo SQLAlchemy
entity_name: Nombre de la entidad (para el archivo)
Returns:
bool: True si fue exitoso, False si hubo error
"""
try:
# Obtener todos los registros de la entidad
records = db.query(model_class).all()
# Convertir registros a diccionario
data = []
for record in records:
record_dict = {}
for column in record.__table__.columns:
value = getattr(record, column.name)
# Convertir tipos especiales a formato serializable
if hasattr(value, 'isoformat'): # datetime, date
value = value.isoformat()
elif value is None:
value = None
elif isinstance(value, (int, float, str, bool)):
value = value
else:
value = str(value) # Fallback para otros tipos
record_dict[column.name] = value
data.append(record_dict)
# Estructura del archivo JSON
backup_data = {
"metadata": {
"entity": entity_name,
"export_date": datetime.now().isoformat(),
"record_count": len(data),
"database_timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
},
"data": data
}
# Guardar en archio JSON
backup_file = f"{self.backup_dir}/{entity_name}.json"
with open(backup_file, 'w', encoding='utf-8') as f:
json.dump(backup_data, f, indent=2, ensure_ascii=False, default=str)
self.logger.info(f"✅ Backup completado: {entity_name} - {len(data)} registros")
print(f"💾 Backup actualizado: {entity_name}.json ({len(data)} registros)")
return True
except Exception as e:
error_msg = f"❌ Error en backup de {entity_name}: {str(e)}"
self.logger.error(error_msg)
print(error_msg)
return False
def export_all_entities(self, db: Session, models_dict: Dict[str, Any]) -> Dict[str, bool]:
"""
Exportar todas las entidades a JSON
Args:
db: Sesión de base de datos
models_dict: Diccionario con {nombre_entidad: clase_modelo}
Returns:
Dict: Resultados por entidad {entidad: éxito}
"""
print("🔄 Iniciando exportación completa de backups...")
results = {}
for entity_name, model_class in models_dict.items():
success = self.export_entity_to_json(db, model_class, entity_name)
results[entity_name] = success
# Estadísticas
successful = sum(results.values())
total = len(results)
print(f"📊 Exportación completada: {successful}/{total} entidades respaldadas")
return results
def get_backup_status(self) -> Dict[str, Any]:
"""
Obtener estado actual de todos los backups
Returns:
Dict: Información de todos los archivos de backup
"""
backups = {}
total_size_kb = 0
if os.path.exists(self.backup_dir):
for file in os.listdir(self.backup_dir):
if file.endswith('.json') and not file.startswith('.'):
file_path = os.path.join(self.backup_dir, file)
try:
file_stats = os.stat(file_path)
entity_name = file.replace('.json', '')
# Leer metadata del archivo JSON
metadata = {}
try:
with open(file_path, 'r', encoding='utf-8') as f:
backup_data = json.load(f)
metadata = backup_data.get('metadata', {})
except:
metadata = {"error": "No se pudo leer metadata"}
backups[entity_name] = {
"file": file,
"size_kb": round(file_stats.st_size / 1024, 2),
"modified": datetime.fromtimestamp(file_stats.st_mtime).isoformat(),
"record_count": metadata.get('record_count', 0),
"last_export": metadata.get('export_date', 'N/A')
}
total_size_kb += file_stats.st_size / 1024
except Exception as e:
backups[file] = {"error": str(e)}
return {
"backups": backups,
"summary": {
"total_files": len(backups),
"total_size_kb": round(total_size_kb, 2),
"backup_directory": self.backup_dir,
"timestamp": datetime.now().isoformat()
}
}
def backup_after_operation(self, db: Session, model_class, entity_name: str):
"""
Ejecutar backup después de una operación CRUD
Versión optimizada para no bloquear la respuesta
"""
try:
# Ejecutar en segundo plano (no bloqueante)
self.export_entity_to_json(db, model_class, entity_name)
except Exception as e:
self.logger.error(f"❌ Error en backup automático de {entity_name}: {str(e)}")
def get_entity_backup(self, entity_name: str) -> Optional[Dict]:
"""
Obtener datos de backup de una entidad específica
Args:
entity_name: Nombre de la entidad
Returns:
Dict: Datos del backup o None si no existe
"""
backup_file = f"{self.backup_dir}/{entity_name}.json"
if os.path.exists(backup_file):
try:
with open(backup_file, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
self.logger.error(f"❌ Error leyendo backup {entity_name}: {str(e)}")
return None
return None
# Instancia global para usar en toda la aplicación
backup_manager = BackupManager()
# Funciones de conveniencia para importar fácilmente
def get_backup_manager() -> BackupManager:
return backup_manager
def configure_backup_manager(backup_dir: str = "backups/json") -> BackupManager:
global backup_manager
backup_manager = BackupManager(backup_dir)
return backup_manager
'''
def generate_fastapi_model(module, **kwargs):
"""Generar modelo SQLAlchemy para un módulo - VERSIÓN PROFESIONAL E-COMMERCE COMPLETA"""
module_name = module['name']
class_name = module_name.capitalize()
model_code = f'''from sqlalchemy import Column, Integer, String, Float, Boolean, DateTime, Text, ForeignKey
from sqlalchemy.orm import relationship
from models.base import Base
from datetime import datetime
class {class_name}(Base):
__tablename__ = "{module_name}"
id = Column(Integer, primary_key=True, index=True)
'''
# Campos específicos para cada tipo de módulo - MODELOS PROFESIONALES E-COMMERCE
if module['source'] == 'file':
for col, config in module['fields'].items():
field_name = config['name'].replace('.', '_').replace(' ', '_')
field_type = config['type']
if field_type == 'integer':
model_code += f' {field_name} = Column(Integer)\n'
elif field_type == 'float':
model_code += f' {field_name} = Column(Float)\n'
elif field_type == 'boolean':
model_code += f' {field_name} = Column(Boolean, default=True)\n'
elif field_type == 'datetime':
model_code += f' {field_name} = Column(DateTime, default=datetime.utcnow)\n'
else: # string, email, url
model_code += f' {field_name} = Column(String)\n'
else: # mock data - MODELOS E-COMMERCE PROFESIONALES
if module.get('type') == 'productos':
model_code += ''' nombre = Column(String, index=True)
descripcion = Column(Text)
precio = Column(Float)
categoria = Column(String, index=True)
marca = Column(String)
stock = Column(Integer, default=0)
sku = Column(String, unique=True, index=True)
imagen_url = Column(String, nullable=True)
activo = Column(Boolean, default=True)
fecha_creacion = Column(DateTime, default=datetime.utcnow)
fecha_actualizacion = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
'''
elif module.get('type') == 'usuarios':
model_code += ''' nombre = Column(String)
apellido = Column(String)
email = Column(String, unique=True, index=True)
password_hash = Column(String)
telefono = Column(String, nullable=True)
direccion = Column(Text, nullable=True)
ciudad = Column(String, nullable=True)
pais = Column(String, default="España")
rol = Column(String, default="usuario")
activo = Column(Boolean, default=True)
fecha_registro = Column(DateTime, default=datetime.utcnow)
fecha_actualizacion = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
'''
elif module.get('type') == 'carrito':
model_code += ''' usuario_id = Column(Integer, ForeignKey('usuarios.id'))
producto_id = Column(Integer, ForeignKey('productos.id'))
cantidad = Column(Integer, default=1)
precio_unitario = Column(Float)
subtotal = Column(Float)
iva = Column(Float, default=0.21)
descuento = Column(Float, default=0.0)
total = Column(Float)
activo = Column(Boolean, default=True)
fecha_agregado = Column(DateTime, default=datetime.utcnow)
fecha_creacion = Column(DateTime, default=datetime.utcnow) # ✅ PROFESIONAL: Agregado campo fecha_creacion
fecha_actualizacion = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
'''
elif module.get('type') == 'categorias':
model_code += ''' nombre = Column(String, unique=True, index=True)
descripcion = Column(Text, nullable=True)
imagen_url = Column(String, nullable=True)
activo = Column(Boolean, default=True)
fecha_creacion = Column(DateTime, default=datetime.utcnow)
fecha_actualizacion = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
'''
elif module.get('type') == 'pedidos':
model_code += ''' usuario_id = Column(Integer, ForeignKey('usuarios.id'))
subtotal = Column(Float)
iva = Column(Float, default=0.21)
descuento = Column(Float, default=0.0)
envio = Column(Float, default=0.0)
total = Column(Float)
estado = Column(String, default="pendiente")
direccion_entrega = Column(Text)
telefono_contacto = Column(String)
notas = Column(Text, nullable=True)
metodo_pago = Column(String, default="tarjeta")
activo = Column(Boolean, default=True)
fecha_pedido = Column(DateTime, default=datetime.utcnow)
fecha_entrega = Column(DateTime, nullable=True)
fecha_creacion = Column(DateTime, default=datetime.utcnow)
fecha_actualizacion = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
'''
elif module.get('type') == 'pagos':
model_code += ''' pedido_id = Column(Integer, ForeignKey('pedidos.id'))
monto = Column(Float)
comision = Column(Float, default=0.0)
total = Column(Float)
metodo_pago = Column(String)
estado = Column(String, default="pendiente")
referencia = Column(String, unique=True, index=True)
activo = Column(Boolean, default=True)
fecha_pago = Column(DateTime, default=datetime.utcnow)
fecha_creacion = Column(DateTime, default=datetime.utcnow)
fecha_actualizacion = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
'''
elif module.get('type') == 'reseñas':
model_code += ''' usuario_id = Column(Integer, ForeignKey('usuarios.id'))
producto_id = Column(Integer, ForeignKey('productos.id'))
calificacion = Column(Integer) # 1-5
comentario = Column(Text, nullable=True)
aprobado = Column(Boolean, default=False)
fecha_review = Column(DateTime, default=datetime.utcnow)
fecha_creacion = Column(DateTime, default=datetime.utcnow)
fecha_actualizacion = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
'''
elif module.get('type') == 'direcciones':
model_code += ''' usuario_id = Column(Integer, ForeignKey('usuarios.id'))
tipo_direccion = Column(String) # 'casa', 'trabajo', 'otro'
direccion = Column(Text)
ciudad = Column(String)
codigo_postal = Column(String)
pais = Column(String, default="España")
principal = Column(Boolean, default=False)
fecha_creacion = Column(DateTime, default=datetime.utcnow)
fecha_actualizacion = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
'''
elif module.get('type') == 'cupones':
model_code += ''' codigo = Column(String, unique=True, index=True)
descripcion = Column(Text, nullable=True)
tipo_descuento = Column(String) # 'porcentaje' o 'monto_fijo'
valor_descuento = Column(Float)
fecha_inicio = Column(DateTime)
fecha_fin = Column(DateTime)
usos_maximos = Column(Integer, default=100)
usos_actuales = Column(Integer, default=0)
activo = Column(Boolean, default=True)
fecha_creacion = Column(DateTime, default=datetime.utcnow)
fecha_actualizacion = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
'''
else: # módulo genérico
model_code += ''' nombre = Column(String, index=True)
descripcion = Column(Text, nullable=True)
activo = Column(Boolean, default=True)
fecha_creacion = Column(DateTime, default=datetime.utcnow)
fecha_actualizacion = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
'''
# RELACIONES CORREGIDAS - Solo si los módulos relacionados existen
related_modules = [m['name'] for m in kwargs.get('modules', [])]
if module.get('type') == 'usuarios':
model_code += '\n # Relaciones\n'
if 'pedidos' in related_modules:
model_code += ' pedidos = relationship("Pedidos", back_populates="usuario")\n'
if 'carrito' in related_modules:
model_code += ' carrito_items = relationship("Carrito", back_populates="usuario")\n'
if 'reseñas' in related_modules:
model_code += ' reseñas = relationship("Reseñas", back_populates="usuario")\n'
if 'direcciones' in related_modules:
model_code += ' direcciones = relationship("Direcciones", back_populates="usuario")\n'
elif module.get('type') == 'productos':
model_code += '\n # Relaciones\n'
if 'carrito' in related_modules:
model_code += ' carrito_items = relationship("Carrito", back_populates="producto")\n'
if 'reseñas' in related_modules:
model_code += ' reseñas = relationship("Reseñas", back_populates="producto")\n'
elif module.get('type') == 'pedidos' and 'usuarios' in related_modules:
model_code += '\n # Relaciones\n'
model_code += ' usuario = relationship("Usuarios", back_populates="pedidos")\n'
if 'pagos' in related_modules:
model_code += ' pagos = relationship("Pagos", back_populates="pedido")\n'
elif module.get('type') == 'carrito':
model_code += '\n # Relaciones\n'
if 'usuarios' in related_modules:
model_code += ' usuario = relationship("Usuarios", back_populates="carrito_items")\n'
if 'productos' in related_modules:
model_code += ' producto = relationship("Productos", back_populates="carrito_items")\n'
elif module.get('type') == 'reseñas':
model_code += '\n # Relaciones\n'
if 'usuarios' in related_modules:
model_code += ' usuario = relationship("Usuarios", back_populates="reseñas")\n'
if 'productos' in related_modules:
model_code += ' producto = relationship("Productos", back_populates="reseñas")\n'
elif module.get('type') == 'direcciones' and 'usuarios' in related_modules:
model_code += '\n # Relaciones\n'
model_code += ' usuario = relationship("Usuarios", back_populates="direcciones")\n'
elif module.get('type') == 'pagos' and 'pedidos' in related_modules:
model_code += '\n # Relaciones\n'
model_code += ' pedido = relationship("Pedidos", back_populates="pagos")\n'
return model_code
def generate_fastapi_schema(module, **kwargs):
"""Generar schemas Pydantic para un módulo - VERSIÓN PROFESIONAL E-COMMERCE CORREGIDA"""
module_name = module['name']
# Mapeo de nombres plural a singular para schemas
singular_map = {
'usuarios': 'Usuario',
'productos': 'Producto',
'pedidos': 'Pedido',
'categorias': 'Categoria',
'carrito': 'CarritoItem',
'pagos': 'Pago',
'reseñas': 'Reseña',
'direcciones': 'Direccion',
'cupones': 'Cupon'
}
schema_name = singular_map.get(module_name, module_name.capitalize())
# Caso especial para usuarios (tiene campo password adicional)
if module.get('type') == 'usuarios':
return f'''from pydantic import BaseModel, EmailStr
from typing import Optional
from datetime import datetime
class {schema_name}Base(BaseModel):
"""Schema base para {module_name}"""
nombre: str
apellido: str
email: EmailStr
telefono: Optional[str] = None
direccion: Optional[str] = None
ciudad: Optional[str] = None
pais: str = "España"
class {schema_name}Create({schema_name}Base):
"""Schema para crear {schema_name.lower()}"""
password: str
class {schema_name}Update(BaseModel):
"""Schema para actualizar {schema_name.lower()}"""
nombre: Optional[str] = None
apellido: Optional[str] = None
email: Optional[EmailStr] = None
telefono: Optional[str] = None
direccion: Optional[str] = None
ciudad: Optional[str] = None
pais: Optional[str] = None
class {schema_name}({schema_name}Base):
"""Schema completo para {schema_name.lower()}"""
id: int
rol: str = "usuario"
activo: bool = True
fecha_registro: Optional[datetime] = None
fecha_actualizacion: Optional[datetime] = None
class Config:
from_attributes = True
'''
# Para otros módulos
schema_code = f'''from pydantic import BaseModel
from typing import Optional
from datetime import datetime
class {schema_name}Base(BaseModel):
"""Schema base para {module_name}"""
'''
# Campos según el tipo de módulo - SCHEMAS PROFESIONALES E-COMMERCE
if module['source'] == 'file':
for col, config in module['fields'].items():
field_name = config['name'].replace('.', '_').replace(' ', '_')
field_type = config['type']
type_mapping = {
'string': 'str',
'integer': 'int',
'float': 'float',
'boolean': 'bool',
'datetime': 'datetime',
'email': 'EmailStr',
'url': 'str'
}
python_type = type_mapping.get(field_type, 'str')
if config['required']:
schema_code += f' {field_name}: {python_type}\n'
else:
schema_code += f' {field_name}: Optional[{python_type}] = None\n'
else: # mock data - SCHEMAS E-COMMERCE PROFESIONALES
if module.get('type') == 'productos':
schema_code += ''' nombre: str
descripcion: Optional[str] = None
precio: float
categoria: str
marca: str
stock: int = 0
sku: str
imagen_url: Optional[str] = None
'''
elif module.get('type') == 'carrito':
schema_code += ''' usuario_id: int
producto_id: int
cantidad: int = 1
precio_unitario: float
subtotal: float
iva: float = 0.21
descuento: float = 0.0
total: float
fecha_agregado: datetime # ✅ CORREGIDO: Agregado campo fecha_agregado
activo: bool = True
'''
elif module.get('type') == 'pedidos':
schema_code += ''' usuario_id: int
subtotal: float
iva: float = 0.21
descuento: float = 0.0
envio: float = 0.0
total: float
estado: str = "pendiente"
direccion_entrega: str
telefono_contacto: str
notas: Optional[str] = None
metodo_pago: str = "tarjeta"
activo: bool = True
'''
elif module.get('type') == 'categorias':
schema_code += ''' nombre: str
descripcion: Optional[str] = None
imagen_url: Optional[str] = None
'''
elif module.get('type') == 'pagos':
schema_code += ''' pedido_id: int
monto: float
comision: float = 0.0
total: float
metodo_pago: str
estado: str = "pendiente"
referencia: str
activo: bool = True
'''
elif module.get('type') == 'reseñas':
schema_code += ''' usuario_id: int
producto_id: int
calificacion: int
comentario: Optional[str] = None
'''
elif module.get('type') == 'direcciones':
schema_code += ''' usuario_id: int
tipo_direccion: str
direccion: str
ciudad: str
codigo_postal: str
pais: str = "España"
principal: bool = False
'''
elif module.get('type') == 'cupones':
schema_code += ''' codigo: str
descripcion: Optional[str] = None
tipo_descuento: str
valor_descuento: float
fecha_inicio: datetime
fecha_fin: datetime
usos_maximos: int = 100
'''
else: # módulo genérico
schema_code += ''' nombre: str
descripcion: Optional[str] = None
'''
# Schema para creación
schema_code += f'''
class {schema_name}Create({schema_name}Base):
"""Schema para crear {schema_name.lower()}"""
pass
'''
# Schema para actualización
schema_code += f'''
class {schema_name}Update(BaseModel):
"""Schema para actualizar {schema_name.lower()}"""
'''
if module['source'] == 'file':
for col, config in module['fields'].items():
field_name = config['name'].replace('.', '_').replace(' ', '_')
field_type = config['type']
python_type = type_mapping.get(field_type, 'str')
schema_code += f' {field_name}: Optional[{python_type}] = None\n'
else:
if module.get('type') == 'productos':
schema_code += ''' nombre: Optional[str] = None
descripcion: Optional[str] = None
precio: Optional[float] = None
categoria: Optional[str] = None
marca: Optional[str] = None
stock: Optional[int] = None
sku: Optional[str] = None
imagen_url: Optional[str] = None
'''
elif module.get('type') == 'carrito':
schema_code += ''' usuario_id: Optional[int] = None
producto_id: Optional[int] = None
cantidad: Optional[int] = None
precio_unitario: Optional[float] = None
subtotal: Optional[float] = None
iva: Optional[float] = None
descuento: Optional[float] = None
total: Optional[float] = None
fecha_agregado: Optional[datetime] = None # ✅ CORREGIDO: Agregado campo fecha_agregado en update
activo: Optional[bool] = None
'''
elif module.get('type') == 'pedidos':
schema_code += ''' usuario_id: Optional[int] = None
subtotal: Optional[float] = None
iva: Optional[float] = None
descuento: Optional[float] = None
envio: Optional[float] = None
total: Optional[float] = None
estado: Optional[str] = None
direccion_entrega: Optional[str] = None
telefono_contacto: Optional[str] = None
notas: Optional[str] = None
metodo_pago: Optional[str] = None
activo: Optional[bool] = None
'''
elif module.get('type') == 'categorias':
schema_code += ''' nombre: Optional[str] = None
descripcion: Optional[str] = None
imagen_url: Optional[str] = None
'''
elif module.get('type') == 'pagos':
schema_code += ''' pedido_id: Optional[int] = None
monto: Optional[float] = None
comision: Optional[float] = None
total: Optional[float] = None
metodo_pago: Optional[str] = None
estado: Optional[str] = None
referencia: Optional[str] = None
activo: Optional[bool] = None
'''
elif module.get('type') == 'reseñas':
schema_code += ''' usuario_id: Optional[int] = None
producto_id: Optional[int] = None
calificacion: Optional[int] = None
comentario: Optional[str] = None
'''
elif module.get('type') == 'direcciones':
schema_code += ''' usuario_id: Optional[int] = None
tipo_direccion: Optional[str] = None
direccion: Optional[str] = None
ciudad: Optional[str] = None
codigo_postal: Optional[str] = None
pais: Optional[str] = None
principal: Optional[bool] = None
'''
elif module.get('type') == 'cupones':
schema_code += ''' codigo: Optional[str] = None
descripcion: Optional[str] = None
tipo_descuento: Optional[str] = None
valor_descuento: Optional[float] = None
fecha_inicio: Optional[datetime] = None
fecha_fin: Optional[datetime] = None
usos_maximos: Optional[int] = None
'''
else:
schema_code += ''' nombre: Optional[str] = None
descripcion: Optional[str] = None
'''
# Schema completo - ✅ CORREGIDO: Incluye todos los campos de timestamp
schema_code += f'''
class {schema_name}({schema_name}Base):
"""Schema completo para {schema_name.lower()}"""
id: int
activo: bool = True
fecha_creacion: Optional[datetime] = None
fecha_actualizacion: Optional[datetime] = None
class Config:
from_attributes = True
'''
return schema_code
# CONTINUARÁ EN LA PARTE 4...
# PARTE 4: Routers y Endpoints Corregidos
def generate_fastapi_router(module, **kwargs):
"""Generar router para un módulo en FastAPI - VERSIÓN CON BACKUPS"""
module_name = module['name']
class_name = module_name.capitalize()
# Mapeo de nombres plural a singular para schemas
singular_map = {
'usuarios': 'Usuario',
'productos': 'Producto',
'pedidos': 'Pedido',
'categorias': 'Categoria',
'carrito': 'CarritoItem',
'pagos': 'Pago',
'reseñas': 'Reseña',
'direcciones': 'Direccion',
'cupones': 'Cupon'
}
schema_name = singular_map.get(module_name, class_name)
router_code = f'''from fastapi import APIRouter, Depends, HTTPException, Query, status
from typing import List, Optional
from sqlalchemy.orm import Session
from database import get_db
from models.{module_name} import {class_name}
from schemas.{module_name} import {schema_name}, {schema_name}Create, {schema_name}Update
from utils.backup_manager import backup_manager # ✅ NUEVO: Importar backup manager
router = APIRouter()
@router.get("/", response_model=List[{schema_name}])
async def get_{module_name}(
skip: int = Query(0, ge=0, description="Registros a saltar"),
limit: int = Query({kwargs["pagination_size"]}, ge=1, le=100, description="Límite de registros"),
db: Session = Depends(get_db)
):
"""Obtener lista de {module_name}"""
{module_name} = db.query({class_name}).offset(skip).limit(limit).all()
return {module_name}
@router.get("/{{id}}", response_model={schema_name})
async def get_{module_name.rstrip('s')}_by_id(
id: int,
db: Session = Depends(get_db)
):
"""Obtener {module_name.rstrip('s')} por ID"""
{module_name.rstrip('s')} = db.query({class_name}).filter({class_name}.id == id).first()
if not {module_name.rstrip('s')}:
raise HTTPException(status_code=404, detail="{schema_name} no encontrado")
return {module_name.rstrip('s')}
@router.post("/", response_model={schema_name}, status_code=status.HTTP_201_CREATED)
async def create_{module_name.rstrip('s')}(
{module_name.rstrip('s')}_data: {schema_name}Create,
db: Session = Depends(get_db)
):
"""Crear nuevo {module_name.rstrip('s')}"""
try:
db_{module_name.rstrip('s')} = {class_name}(**{module_name.rstrip('s')}_data.model_dump())
db.add(db_{module_name.rstrip('s')})
db.commit()
db.refresh(db_{module_name.rstrip('s')})
# ✅ NUEVO: Backup automático después de crear
backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
return db_{module_name.rstrip('s')}
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=f"Error creando {module_name.rstrip('s')}: {{str(e)}}")
@router.put("/{{id}}", response_model={schema_name})
async def update_{module_name.rstrip('s')}(
id: int,
{module_name.rstrip('s')}_data: {schema_name}Update,
db: Session = Depends(get_db)
):
"""Actualizar {module_name.rstrip('s')}"""
db_{module_name.rstrip('s')} = db.query({class_name}).filter({class_name}.id == id).first()
if not db_{module_name.rstrip('s')}:
raise HTTPException(status_code=404, detail="{schema_name} no encontrado")
try:
update_data = {module_name.rstrip('s')}_data.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(db_{module_name.rstrip('s')}, field, value)
db.commit()
db.refresh(db_{module_name.rstrip('s')})
# ✅ NUEVO: Backup automático después de actualizar
backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
return db_{module_name.rstrip('s')}
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=f"Error actualizando {module_name.rstrip('s')}: {{str(e)}}")
@router.delete("/{{id}}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_{module_name.rstrip('s')}(
id: int,
db: Session = Depends(get_db)
):
"""Eliminar {module_name.rstrip('s')}"""
db_{module_name.rstrip('s')} = db.query({class_name}).filter({class_name}.id == id).first()
if not db_{module_name.rstrip('s')}:
raise HTTPException(status_code=404, detail="{schema_name} no encontrado")
try:
db.delete(db_{module_name.rstrip('s')})
db.commit()
# ✅ NUEVO: Backup automático después de eliminar
backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
return None
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=f"Error eliminando {module_name.rstrip('s')}: {{str(e)}}")
@router.get("/search/", response_model=List[{schema_name}])
async def search_{module_name}(
q: str = Query(..., min_length=1, description="Término de búsqueda"),
skip: int = Query(0, ge=0, description="Registros a saltar"),
limit: int = Query({kwargs["pagination_size"]}, ge=1, le=100, description="Límite de registros"),
db: Session = Depends(get_db)
):
"""Buscar {module_name} por término"""
try:
# ✅ MEJORADO: Búsqueda más robusta en múltiples campos
from sqlalchemy import or_
# Determinar campos de búsqueda según el tipo de módulo
search_fields = []
if hasattr({class_name}, 'nombre'):
search_fields.append({class_name}.nombre.ilike(f"%{{q}}%"))
if hasattr({class_name}, 'descripcion'):
search_fields.append({class_name}.descripcion.ilike(f"%{{q}}%"))
if hasattr({class_name}, 'email'):
search_fields.append({class_name}.email.ilike(f"%{{q}}%"))
if search_fields:
{module_name} = db.query({class_name}).filter(or_(*search_fields)).offset(skip).limit(limit).all()
else:
# Fallback: buscar en todos los campos string
{module_name} = db.query({class_name}).offset(skip).limit(limit).all()
return {module_name}
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error en búsqueda: {{str(e)}}")
@router.get("/count")
async def count_{module_name}(
db: Session = Depends(get_db)
):
"""Obtener conteo total de {module_name}"""
count = db.query({class_name}).count()
return {{"count": count, "module": "{module_name}"}}
'''
# Endpoints adicionales para módulos específicos
if module.get('type') == 'productos':
router_code += f'''
@router.get("/categoria/{{categoria}}", response_model=List[{schema_name}])
async def get_productos_por_categoria(
categoria: str,
skip: int = Query(0, ge=0),
limit: int = Query({kwargs["pagination_size"]}, ge=1, le=100),
db: Session = Depends(get_db)
):
"""Obtener productos por categoría"""
productos = db.query({class_name}).filter(
{class_name}.categoria.ilike(f"%{{categoria}}%")
).offset(skip).limit(limit).all()
return productos
@router.get("/categorias/")
async def get_categorias_productos(db: Session = Depends(get_db)):
"""Obtener lista de categorías únicas de productos"""
categorias = db.query({class_name}.categoria).distinct().all()
return {{"categorias": [cat[0] for cat in categorias if cat[0]]}}
'''
elif module.get('type') == 'usuarios':
router_code += f'''
@router.get("/email/{{email}}", response_model={schema_name})
async def get_usuario_por_email(email: str, db: Session = Depends(get_db)):
"""Obtener usuario por email"""
usuario = db.query({class_name}).filter({class_name}.email == email).first()
if not usuario:
raise HTTPException(status_code=404, detail="Usuario no encontrado")
return usuario
'''
elif module.get('type') == 'carrito':
router_code += f'''
@router.get("/usuario/{{usuario_id}}", response_model=List[{schema_name}])
async def get_carrito_usuario(usuario_id: int, db: Session = Depends(get_db)):
"""Obtener items del carrito por usuario"""
carrito_items = db.query({class_name}).filter(
{class_name}.usuario_id == usuario_id
).all()
return carrito_items
@router.delete("/usuario/{{usuario_id}}/clear", status_code=status.HTTP_204_NO_CONTENT)
async def limpiar_carrito_usuario(usuario_id: int, db: Session = Depends(get_db)):
"""Limpiar todo el carrito de un usuario"""
try:
db.query({class_name}).filter({class_name}.usuario_id == usuario_id).delete()
db.commit()
# ✅ NUEVO: Backup automático después de limpiar carrito
backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
return None
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=f"Error limpiando carrito: {{str(e)}}")
'''
elif module.get('type') == 'pedidos':
router_code += f'''
@router.get("/usuario/{{usuario_id}}", response_model=List[{schema_name}])
async def get_pedidos_usuario(usuario_id: int, db: Session = Depends(get_db)):
"""Obtener pedidos por usuario"""
pedidos = db.query({class_name}).filter(
{class_name}.usuario_id == usuario_id
).order_by({class_name}.fecha_pedido.desc()).all()
return pedidos
@router.put("/{{id}}/estado")
async def actualizar_estado_pedido(
id: int,
estado: str = Query(..., description="Nuevo estado del pedido"),
db: Session = Depends(get_db)
):
"""Actualizar estado de un pedido"""
pedido = db.query({class_name}).filter({class_name}.id == id).first()
if not pedido:
raise HTTPException(status_code=404, detail="Pedido no encontrado")
estados_validos = ["pendiente", "confirmado", "preparando", "en_camino", "entregado", "cancelado"]
if estado not in estados_validos:
raise HTTPException(status_code=400, detail=f"Estado inválido. Estados válidos: {{estados_validos}}")
pedido.estado = estado
db.commit()
db.refresh(pedido)
# ✅ NUEVO: Backup automático después de cambiar estado
backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
return pedido
'''
return router_code
def generate_auth_router(**kwargs):
"""Generar router de autenticación - VERSIÓN CON FORM DATA"""
return '''from fastapi import APIRouter, Depends, HTTPException, status, Form
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from datetime import timedelta
from typing import Optional
from database import get_db
from models.usuarios import Usuarios
from schemas.usuarios import Usuario as UsuarioSchema
from utils.auth import (
verify_password, get_password_hash, create_access_token,
create_refresh_token, verify_token, get_current_user
)
from config import settings
router = APIRouter()
@router.post("/register", response_model=UsuarioSchema, status_code=status.HTTP_201_CREATED)
async def register(
nombre: str = Form(...),
apellido: str = Form(...),
email: str = Form(...),
password: str = Form(...),
telefono: Optional[str] = Form(None),
direccion: Optional[str] = Form(None),
ciudad: Optional[str] = Form(None),
pais: str = Form("España"),
db: Session = Depends(get_db)
):
"""Registrar nuevo usuario usando FormData (MÁS SEGURO)"""
# Verificar si el email ya existe
existing_user = db.query(Usuarios).filter(Usuarios.email == email).first()
if existing_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="El email ya está registrado"
)
# Crear usuario
hashed_password = get_password_hash(password)
db_usuario = Usuarios(
nombre=nombre,
apellido=apellido,
email=email,
password_hash=hashed_password,
telefono=telefono,
direccion=direccion,
ciudad=ciudad,
pais=pais
)
db.add(db_usuario)
db.commit()
db.refresh(db_usuario)
return db_usuario
@router.post("/login")
async def login(
form_data: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(get_db)
):
"""Iniciar sesión y obtener token"""
# Verificar usuario
usuario = db.query(Usuarios).filter(Usuarios.email == form_data.username).first()
if not usuario or not verify_password(form_data.password, usuario.password_hash):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Credenciales incorrectas",
headers={"WWW-Authenticate": "Bearer"},
)
if not usuario.activo:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Usuario inactivo"
)
# Crear tokens
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": str(usuario.id)}, expires_delta=access_token_expires
)
refresh_token = create_refresh_token(data={"sub": str(usuario.id)})
return {
"access_token": access_token,
"refresh_token": refresh_token,
"token_type": "bearer"
}
@router.post("/refresh")
async def refresh_token(refresh_token: str, db: Session = Depends(get_db)):
"""Obtener nuevo access token usando refresh token"""
payload = verify_token(refresh_token)
if not payload or payload.get("type") != "refresh":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Refresh token inválido"
)
user_id = payload.get("sub")
usuario = db.query(Usuarios).filter(Usuarios.id == int(user_id)).first()
if not usuario:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Usuario no encontrado"
)
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": str(usuario.id)}, expires_delta=access_token_expires
)
return {
"access_token": access_token,
"token_type": "bearer"
}
@router.get("/me", response_model=UsuarioSchema)
async def get_me(current_user: Usuarios = Depends(get_current_user)):
"""Obtener información del usuario actual"""
return current_user
@router.put("/me")
async def update_me(
usuario_data: UsuarioSchema,
current_user: Usuarios = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""Actualizar información del usuario actual"""
try:
update_data = usuario_data.model_dump(exclude_unset=True)
for field, value in update_data.items():
if field != "id" and field != "password_hash": # No permitir cambiar ID ni password directamente
setattr(current_user, field, value)
db.commit()
db.refresh(current_user)
return current_user
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=f"Error actualizando usuario: {str(e)}")
'''
def generate_fastapi_main(**kwargs):
"""Generar archivo main.py - VERSIÓN CORREGIDA CON PERSISTENCIA, BACKUPS Y REDOC FUNCIONAL"""
project_name = kwargs['project_name']
api_version = kwargs['api_version']
database = kwargs['database']
modules = kwargs['modules']
module_count = len(modules)
module_names = [module['name'] for module in modules]
imports = [
"from fastapi import FastAPI, Depends, HTTPException, Request",
"from fastapi.middleware.cors import CORSMiddleware",
"from fastapi.responses import JSONResponse, FileResponse, HTMLResponse",
"from contextlib import asynccontextmanager",
"import uvicorn",
"from database import get_db, create_tables, engine", # ✅ CORREGIDO: agregar engine
"from datetime import datetime",
"import traceback",
"import sys",
"import os"
]
# ✅ AGREGAR IMPORT PARA VERIFICAR TABLAS EXISTENTES
imports.append("from sqlalchemy import inspect")
# ✅ AGREGAR IMPORTS PARA BACKUPS
imports.append("from fastapi.staticfiles import StaticFiles")
if kwargs['include_auth']:
imports.append("from routers.auth import router as auth_router")
for module in modules:
imports.append(f"from routers.{module['name']} import router as {module['name']}_router")
imports_str = "\n".join(imports)
lifespan_code = f'''@asynccontextmanager
async def lifespan(app: FastAPI):
print("🚀 Iniciando {project_name} API")
print("🔧 Configuración del sistema:")
print(f" • Proyecto: {project_name}")
print(f" • Versión: {api_version}")
print(f" • Base de datos: {database}")
print(f" • Módulos: {module_count}")
# ✅ SOLUCIÓN: VERIFICAR SI LAS TABLAS YA EXISTEN ANTES DE CREARLAS
print("🔍 Verificando estado de la base de datos...")
try:
inspector = inspect(engine)
existing_tables = inspector.get_table_names()
if not existing_tables:
print("🗄️ Creando tablas por primera vez...")
create_tables()
print("✅ Tablas creadas correctamente")
# ✅ SOLUCIÓN: SOLO POBLAR DATOS SI ES LA PRIMERA VEZ
if {kwargs['populate_db']}:
print("🌱 Iniciando población de datos iniciales...")
try:
from scripts.populate_db import populate_initial_data
populate_initial_data()
print("✅ Población de datos completada exitosamente")
except ImportError as e:
print(f"❌ Error importando script de población: {{e}}")
traceback.print_exc()
except Exception as e:
print(f"⚠️ Error durante población automática: {{e}}")
print("💡 Ejecuta manualmente: python scripts/populate_db.py")
traceback.print_exc()
else:
print("⏭️ Población automática deshabilitada")
else:
print(f"✅ Tablas ya existen: {{len(existing_tables)}} tablas detectadas")
print("💾 Base de datos persistente - manteniendo datos existentes")
# ✅ VERIFICAR SI HAY DATOS EXISTENTES
try:
from models.usuarios import Usuarios
from sqlalchemy.orm import Session
from database import SessionLocal
db = SessionLocal()
user_count = db.query(Usuarios).count()
db.close()
if user_count > 0:
print(f"📊 Datos existentes: {{user_count}} usuarios")
else:
print("📊 Base de datos vacía - sin datos de usuarios")
except Exception as e:
print(f"ℹ️ No se pudo verificar datos existentes: {{e}}")
except Exception as e:
print(f"❌ Error verificando base de datos: {{e}}")
traceback.print_exc()
# ✅ FALLBACK: Intentar crear tablas si la verificación falla
try:
print("🔄 Intentando crear tablas como fallback...")
create_tables()
print("✅ Tablas creadas en modo fallback")
except Exception as fallback_error:
print(f"💥 Error crítico creando tablas: {{fallback_error}}")
print("🎯 API lista para recibir requests")
yield
print("🛑 Apagando API...")
print("👋 Hasta pronto!")'''
# ✅ CORREGIDO: Evitar rutas duplicadas con doble "api"
router_includes = ""
if kwargs['include_auth']:
router_includes += 'app.include_router(auth_router, prefix="/api/v1/auth", tags=["auth"])\n'
for module in modules:
# ✅ CORRECCIÓN: Normalizar rutas para evitar /api/v1/api/usuarios
route = module["route"]
# Si la ruta ya empieza con /api/, quitar el /api/ inicial
if route.startswith("/api/"):
route = route[4:] # Remover "/api" del inicio
elif route.startswith("api/"):
route = route[3:] # Remover "api" del inicio
# Asegurar que la ruta empiece con /
if not route.startswith("/"):
route = "/" + route
router_includes += f'app.include_router({module["name"]}_router, prefix="/api/v1{route}", tags=["{module["name"]}"])\n'
# ✅ SOLUCIÓN DEFINITIVA: HTML con CDN corregido
redoc_html = f'''<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{project_name} - ReDoc</title>
<style>
body {{
margin: 0;
padding: 0;
}}
</style>
</head>
<body>
<redoc spec-url="/openapi.json"></redoc>
<!-- ✅ CDN CORREGIDO: Versión estable en lugar de @next -->
<script src="https://cdn.jsdelivr.net/npm/redoc@2.0.0/bundles/redoc.standalone.js"></script>
</body>
</html>'''
return f'''{imports_str}
{lifespan_code}
app = FastAPI(
title="{project_name.replace('_', ' ').title()}",
description="API profesional para E-commerce generada automáticamente - CON PERSISTENCIA DE DATOS Y BACKUPS JSON",
version="{api_version}",
docs_url="/docs" if {kwargs['include_docs']} else None,
redoc_url=None, # ✅ DESACTIVAR REDOC AUTOMÁTICO
openapi_url="/openapi.json",
lifespan=lifespan
)
# ✅ SOLUCIÓN DEFINITIVA: Endpoint personalizado para ReDoc
@app.get("/redoc", response_class=HTMLResponse, include_in_schema=False)
async def redoc_fixed():
"""Endpoint personalizado para ReDoc con HTML válido"""
return HTMLResponse(content={repr(redoc_html)})
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
{router_includes}
# ✅ SISTEMA DE BACKUPS JSON - Montar directorio estático
@app.on_event("startup")
async def startup_backup_system():
"""Inicializar sistema de backups al iniciar la aplicación"""
backup_dir = "backups/json"
if not os.path.exists(backup_dir):
os.makedirs(backup_dir, exist_ok=True)
print(f"📁 Directorio de backups creado: {{backup_dir}}")
# Montar directorio de backups como estático (SOLO DESARROLLO)
if os.path.exists(backup_dir):
app.mount("/backups", StaticFiles(directory=backup_dir), name="backups")
print("🔗 Backups disponibles en: http://localhost:8000/backups/")
@app.get("/")
async def root():
return {{
"message": "🚀 Bienvenido a {project_name} API - Sistema E-commerce CON PERSISTENCIA Y BACKUPS",
"version": "{api_version}",
"status": "operational",
"timestamp": datetime.utcnow().isoformat(),
"docs": "/docs" if {kwargs['include_docs']} else None,
"redoc": "/redoc" if {kwargs['include_docs']} else None,
"backups": "/backups" if {kwargs['include_docs']} else None,
"modules": {module_names},
"features": {{
"authentication": {kwargs['include_auth']},
"documentation": {kwargs['include_docs']},
"docker": {kwargs['include_docker']},
"database": "{database}",
"persistence": True,
"json_backups": True # ✅ NUEVO: Backups JSON habilitados
}}
}}
@app.get("/health")
async def health_check():
# ✅ MEJORADO: Verificar estado real de la base de datos
db_status = "connected"
try:
from sqlalchemy import text
from database import SessionLocal
db = SessionLocal()
db.execute(text("SELECT 1"))
db.close()
except Exception as e:
db_status = f"error: {{str(e)}}"
# ✅ VERIFICAR SISTEMA DE BACKUPS
backup_status = "active"
backup_dir = "backups/json"
if not os.path.exists(backup_dir):
backup_status = "directory_not_found"
elif not os.access(backup_dir, os.W_OK):
backup_status = "no_write_permission"
return {{
"status": "healthy",
"timestamp": datetime.utcnow().isoformat(),
"service": "{project_name}",
"version": "{api_version}",
"database": db_status,
"backups": backup_status, # ✅ NUEVO: Estado de backups
"persistence": True
}}
@app.get("/info")
async def api_info():
module_info = []
for module in {modules}:
module_info.append({{
"name": module['name'],
"route": module['route'],
"type": module.get('type', 'custom'),
"source": module.get('source', 'unknown')
}})
# ✅ MEJORADO: Información sobre persistencia y backups
persistence_info = {{
"database_persistent": True,
"data_safe": True,
"auto_populate": {kwargs['populate_db']},
"json_backups": True, # ✅ NUEVO
"backup_directory": "backups/json",
"warning": "Los datos se mantienen entre reinicios y tienen respaldo JSON"
}}
return {{
"name": "{project_name}",
"version": "{api_version}",
"description": "API E-commerce generada automáticamente - DATOS PERSISTENTES CON BACKUPS JSON",
"modules": module_info,
"database": "{database}",
"authentication": {kwargs['include_auth']},
"documentation": {kwargs['include_docs']},
"backups": True, # ✅ NUEVO
"persistence": persistence_info,
"endpoints": {{
"root": "/",
"health": "/health",
"info": "/info",
"docs": "/docs" if {kwargs['include_docs']} else None,
"redoc": "/redoc" if {kwargs['include_docs']} else None,
"backups": "/backups",
"api_base": "/api/v1",
"backup_api": "/api/v1/backups"
}}
}}
# ✅ ENDPOINTS DE BACKUP - Agregados después de los endpoints principales
@app.get("/api/v1/backups/status")
async def get_backup_status():
"""Obtener estado de los backups JSON"""
backup_dir = "backups/json"
backups = {{}}
if os.path.exists(backup_dir):
for file in os.listdir(backup_dir):
if file.endswith('.json'):
file_path = os.path.join(backup_dir, file)
file_stats = os.stat(file_path)
backups[file] = {{
"size_kb": round(file_stats.st_size / 1024, 2),
"modified": datetime.fromtimestamp(file_stats.st_mtime).isoformat(),
"entities": file.replace('.json', '')
}}
return {{
"status": "success",
"backups": backups,
"backup_count": len(backups),
"timestamp": datetime.utcnow().isoformat(),
"backup_directory": backup_dir
}}
@app.get("/api/v1/backups/download/{{entity_name}}")
async def download_backup(entity_name: str):
"""Descargar backup específico de una entidad"""
backup_file = f"backups/json/{{entity_name}}.json"
if os.path.exists(backup_file):
return FileResponse(
backup_file,
media_type='application/json',
filename=f"{{entity_name}}_backup.json"
)
raise HTTPException(status_code=404, detail=f"Backup no encontrado para entidad: {{entity_name}}")
@app.get("/backups")
async def backups_info():
"""Página de información de backups (para navegador)"""
return {{
"message": "Sistema de Backups JSON",
"description": "Backups automáticos de todas las entidades de la base de datos",
"endpoints": {{
"view_backups": "http://localhost:8000/backups/ (en navegador)",
"api_status": "GET /api/v1/backups/status",
"download": "GET /api/v1/backups/download/{{entity_name}}"
}},
"note": "Los backups se generan automáticamente después de cada operación CRUD"
}}
@app.exception_handler(500)
async def internal_server_error_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={{
"error": "Internal Server Error",
"message": "Ha ocurrido un error interno en el servidor",
"timestamp": datetime.utcnow().isoformat(),
"path": str(request.url.path)
}}
)
@app.exception_handler(404)
async def not_found_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=404,
content={{
"error": "Not Found",
"message": "El recurso solicitado no fue encontrado",
"timestamp": datetime.utcnow().isoformat(),
"path": str(request.url.path)
}}
)
@app.exception_handler(422)
async def validation_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=422,
content={{
"error": "Validation Error",
"message": "Error de validación en los datos enviados",
"timestamp": datetime.utcnow().isoformat()
}}
)
if __name__ == "__main__":
print("🎪 Iniciando servidor de desarrollo...")
print("📖 Documentación disponible en: http://localhost:8000/docs")
print("📚 ReDoc disponible en: http://localhost:8000/redoc")
print("💾 Backups JSON disponibles en: http://localhost:8000/backups/")
print("🔧 Modo: Desarrollo (Auto-reload activado)")
print("💾 MODO PERSISTENTE: Los datos se mantienen entre reinicios")
print("📁 BACKUPS ACTIVOS: Respaldos JSON automáticos")
print("✅ REDOC CORREGIDO: Problema del lang attribute solucionado")
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=True,
log_level="info"
)
'''
# PARTE 5: Scripts de Población de Datos Mejorados
def generate_mock_data(module, **kwargs):
"""Generar datos mock para un módulo - VERSIÓN COMPLETAMENTE FUNCIONAL"""
if module.get('source') != 'mock':
return "# No se generan datos mock para módulos desde archivo\n"
module_type = module.get('type', 'generic')
print(f"🔧 GENERANDO DATOS MOCK PARA: {module_type} (count: {module.get('record_count', 50)})")
if module_type == 'productos':
return generate_productos_mock_data(module, **kwargs)
elif module_type == 'usuarios':
return generate_usuarios_mock_data(module, **kwargs)
elif module_type == 'pedidos':
return generate_pedidos_mock_data(module, **kwargs)
elif module_type == 'categorias':
return generate_categorias_mock_data(module, **kwargs)
elif module_type == 'carrito':
return generate_carrito_mock_data(module, **kwargs)
elif module_type == 'pagos':
return generate_pagos_mock_data(module, **kwargs)
elif module_type == 'reseñas':
return generate_resenas_mock_data(module, **kwargs)
elif module_type == 'direcciones':
return generate_direcciones_mock_data(module, **kwargs)
elif module_type == 'cupones':
return generate_cupones_mock_data(module, **kwargs)
else:
return generate_generic_mock_data(module, **kwargs)
#####################################AGREGADO LÉXICA
def generate_productos_mock_data(module, **kwargs):
"""Generar datos mock para productos - SISTEMA MEJORADO CON LEXICA"""
# Obtener ambas API keys desde session_state
pexels_api_key = st.session_state.get('pexels_api_key', "TU_API_KEY_PEXELS_AQUI")
pixabay_api_key = st.session_state.get('pixabay_api_key', "TU_API_KEY_PIXABAY_AQUI")
# Determinar el modo de imagen basado en la selección - MEJORADO CON LEXICA
image_source_option = module.get('image_source', '🎯 Orden de prioridad automático')
# ✅ MANTENGO EXACTAMENTE EL MAPEO ORIGINAL DE LA UI:
image_mode_mapping = {
'🥇 Lexica (Búsquedas específicas con IA)': 'lexica',
'🥈 Pollinations AI (Generadas por IA)': 'pollinations',
'🥉 Pixabay (Precisas, libres de derechos)': 'pixabay',
'📸 Pexels (Alta calidad)': 'pexels',
'🪄 Placeholder (Último recurso)': 'placeholder',
'🎯 Orden de prioridad automático': 'priority'
}
# MEJORA: Buscar en el mapeo primero, luego en texto
image_mode = image_mode_mapping.get(image_source_option)
if image_mode is None:
if 'Lexica' in image_source_option:
image_mode = 'lexica'
elif 'Pixabay' in image_source_option:
image_mode = 'pixabay'
elif 'Pollinations' in image_source_option:
image_mode = 'pollinations'
elif 'Pexels' in image_source_option:
image_mode = 'pexels'
elif 'Placeholder' in image_source_option:
image_mode = 'placeholder'
else:
image_mode = 'priority' # Orden automático (Lexica → Pollinations → Pixabay → Pexels)
categorias_seleccionadas = module.get('categorias_seleccionadas', [])
# MEJORA: Si no hay categorías seleccionadas, usar todas por defecto
if not categorias_seleccionadas:
categorias_seleccionadas = ['Electrónica', 'Tecnología', 'Hogar', 'Ropa', 'Deportes', 'Alimentos', 'Bebidas', 'Música', 'Belleza', 'Salud', 'Automotriz', 'Jardín', 'Oficina', 'Comidas Dulces', 'Comidas Saladas']
# Definir categorías
categorias_restaurante = ['Comidas Dulces', 'Comidas Saladas', 'Bebidas']
categorias_generales = ['Electrónica', 'Tecnología', 'Hogar', 'Ropa', 'Deportes', 'Alimentos', 'Bebidas', 'Música', 'Belleza', 'Salud', 'Automotriz', 'Jardín', 'Oficina']
# -----------------------
# SISTEMA ORIGINAL GENERAL - MEJORADO
# -----------------------
nombres_reales_str = """{
'Electrónica': [
'Auriculares Inalámbricos Premium', 'Smartwatch Deportivo Avanzado', 'Tablet 10 Pulgadas Pro',
'Altavoz Bluetooth Potente', 'Cámara Digital 4K Profesional', 'Drone Profesional GPS',
'Consola Videojuegos Next-Gen', 'Smart TV 55\\" 4K UHD', 'Laptop Ultradelgada Gaming',
'Smartphone Flagship', 'Reloj Inteligente Fitness', 'Cámara Deportiva Resistente',
'Tablet Gráfica Profesional', 'Cargador Rápido 65W', 'Power Bank 20000mAh'
],
'Tecnología': [
'Monitor Curvo 27\\" Gaming', 'Teclado Mecánico RGB Pro', 'Ratón Gaming Precision',
'Disco SSD 1TB NVMe', 'Router WiFi 6 AX', 'Impresora Láser Color',
'Webcam 4K Streaming', 'Micrófono Estudio USB', 'Silla Ergonómica Ejecutiva',
'Monitor 32\\" 4K UHD', 'Base Laptop Refrigeración', 'Switch HDMI 4K'
],
'Hogar': [
'Robot Aspirador Inteligente', 'Batidora Potente Profesional', 'Cafetera Automática Premium',
'Licuadora Profesional', 'Tostadora Digital LCD', 'Horno Eléctrico Multifunción',
'Freidora de Aire Digital', 'Plancha de Vapor Professional', 'Purificador Aire HEPA',
'Ventilador Torre Silencioso', 'Humidificador Ultrasónico', 'Báscula Digital Cocina'
],
'Ropa': [
'Camiseta Algodón Orgánico', 'Jeans Elásticos Premium', 'Zapatillas Running Tech',
'Chaqueta Impermeable Outdoor', 'Sudadera con Capucha Algodón', 'Vestido Elegante Noche',
'Falda Plisada Casual', 'Chándal Deportivo Performance', 'Abrigo Invierno Lana',
'Blusa Seda Natural', 'Pantalón Vestir Clásico', 'Zapatos Cuero Italiano'
],
'Deportes': [
'Pelota Fútbol Profesional', 'Raqueta Tenis Competición', 'Balón Baloncesto Official',
'Bicicleta Montaña Suspensión', 'Pesas Ajustables Hex', 'Cinta Correr Plegable',
'Eliptica Casa Magnetic', 'Mancuernas Acero Cromado', 'Pelota Yoga Anti-Burst',
'Colchoneta Fitness Premium', 'Mancuernas Neopreno', 'Cuerda Saltar Profesional'
],
'Alimentos': [
'Aceite Oliva Extra Virgen', 'Miel Natural Pura', 'Café Molido Premium',
'Chocolate Negro 70% Cacao', 'Mermelada Fresa Artesanal', 'Pasta Integral Orgánica',
'Salsa Tomate Natural', 'Galletas Integrales Sin Azúcar', 'Cereal Energético Natural',
'Aceitunas Manzanilla Premium', 'Vinagre Balsámico Añejo', 'Especias Gourmet Selección'
],
'Bebidas': [
'Vino Tinto Reserva', 'Cerveza Artesanal IPA', 'Jugo Naranja Natural',
'Agua Mineral Con Gas', 'Refresco Cola Zero', 'Té Verde Matcha',
'Café Molido Expresso', 'Batido Proteínas Natural', 'Agua Saborizada Limón',
'Vino Blanco Fermentado', 'Whisky Añejo 12 Años', 'Ron Premium Caribeño'
],
'Música': [
'Guitarra Eléctrica Profesional', 'Teclado Digital 88 Teclas', 'Batería Acústica Completa',
'Micrófono Condensador Estudio', 'Amplificador Guitarra 100W', 'Piano Digital de Cola',
'Bajo Eléctrico 4 Cuerdas', 'Violín Clásico Profesional', 'Saxofón Alto Jazz',
'Consola Mezcladora 8 Canales', 'Audífonos Studio Monitor', 'Metrónomo Digital'
],
'Belleza': [
'Kit Maquillaje Profesional', 'Secador Pelo Tecnología Iónica', 'Plancha Alisadora Cerámica',
'Crema Facial Anti-Edad', 'Paleta Sombras 12 Colores', 'Labial Líquido Mate Duradero',
'Perfume Fragancia Exclusive', 'Serum Facial Vitamina C', 'Base Líquida Alta Cobertura',
'Rimel Pestañas Volumen Extreme', 'Brillo Labial Hidratante', 'Set Brochas Profesional'
],
'Salud': [
'Tensiómetro Digital Brazo', 'Glucómetro Kit Completo', 'Nebulizador Portátil',
'Termómetro Digital Infrarrojo', 'Monitor Sueño Smart', 'Masajeador Percusión Profunda',
'Vitamina C 1000mg 120 Comprimidos', 'Omega 3 1000mg 90 Cápsulas', 'Colágeno Hidrolizado',
'Báscula Digital Corporal', 'Inhalador Vapor Eucalipto', 'Kit Primeros Auxilios Familiar'
],
'Automotriz': [
'Llantas Aleación 17 Pulgadas', 'Batería Auto 12V 60Ah', 'Aceite Motor Sintético 5W-30',
'Kit Herramientas Mecánico 150 Piezas', 'Gps Navegador Dash Cam', 'Limpiaparabrisas Originales',
'Cargador Batería Automático', 'Compresor Aire Portátil', 'Cera Autolavado Premium',
'Alfombras Auto Goma Original', 'Anticongelante Concentrado', 'Aceite Transmisión ATF'
],
'Jardín': [
'Cortadora Césped Eléctrica', 'Set Herramientas Jardinería', 'Manguera Reforzada 20m',
'Cortasetos Eléctrico Profesional', 'Aspersor Rotatorio Ajustable', 'Tijeras Podar Premium',
'Carretilla Jardín 100L', 'Regador Metalico Clásico', 'Guantes Jardinería Cuero',
'Semillas Césped Premium', 'Fertilizante Universal 5kg', 'Maceta Cerámica 30cm'
],
'Oficina': [
'Silla Ergonómica Ejecutiva', 'Escritorio Oficina Ajustable', 'Organizador Archivos A-Z',
'Calculadora Científica Avanzada', 'Engrapadora Profesional Metálica', 'Set Lapiceras Gel',
'Pizarra Blanca Magnética', 'Resaltadores Fluorescentes 8 Colores', 'Tijeras Oficina Precision',
'Hojas A4 Premium 500 Unidades', 'Grapas Standard Caja 5000', 'Clip Folder Colores Suritdo'
]
}"""
categorias_marcas_str = """{
'Electrónica': ['Sony', 'Samsung', 'Apple', 'LG', 'Philips', 'Bose', 'JBL', 'Xiaomi', 'Huawei', 'OnePlus'],
'Tecnología': ['Dell', 'HP', 'Lenovo', 'Asus', 'Acer', 'Microsoft', 'Logitech', 'Razer', 'Corsair', 'HyperX'],
'Hogar': ['Philips', 'Bosch', 'Black+Decker', 'Miele', 'Rowenta', 'Tefal', 'Braun', 'KitchenAid', 'Ninja', 'Instant Pot'],
'Ropa': ['Nike', 'Adidas', 'Zara', 'H&M', 'Levi\\'s', 'Puma', 'Under Armour', 'Calvin Klein', 'Tommy Hilfiger', 'Ralph Lauren'],
'Deportes': ['Nike', 'Adidas', 'Puma', 'Reebok', 'Wilson', 'Spalding', 'Head', 'Yonex', 'Mikasa', 'Molten'],
'Alimentos': ['Nestlé', 'Kelloggs', 'Heinz', 'Danone', 'Campofrío', 'Font Vella', 'Lays', 'Coca-Cola', 'PepsiCo', 'Unilever'],
'Bebidas': ['Coca-Cola', 'Pepsi', 'Heineken', 'Estrella Galicia', 'Nestlé', 'Red Bull', 'Monster', 'Gatorade', 'Aquarius', 'Schweppes'],
'Música': ['Fender', 'Yamaha', 'Roland', 'Shure', 'Gibson', 'Korg', 'Boss', 'Marshall', 'Sennheiser', 'Audio-Technica'],
'Belleza': ['L\\'Oréal', 'Maybelline', 'MAC', 'Nyx', 'Revlon', 'Estée Lauder', 'Clinique', 'Dior', 'Chanel', 'Lancôme'],
'Salud': ['Omron', 'Accu-Chek', 'Braun', 'Philips', 'Beurer', 'Sanity', 'Bayer', 'Pfizer', 'GSK', 'Johnson & Johnson'],
'Automotriz': ['Michelin', 'Bosch', 'Mobil', 'Castrol', 'Goodyear', '3M', 'Stanley', 'Karcher', 'Mann Filter', 'Varta'],
'Jardín': ['Black+Decker', 'Bosch', 'Gardena', 'Husqvarna', 'MTD', 'Wolf-Garten', 'Fiskars', 'Toro', 'Mc Culloch', 'Stihl'],
'Oficina': ['Fellowes', 'Swingline', 'X-ACTO', 'Staples', 'Paper Mate', 'Sharpie', 'Post-it', 'Scotch', 'Bic', 'Pilot']
}"""
# ✅ CORREGIDO: PRECIOS ARGENTINOS REALISTAS TERMINADOS EN ,999 PARA TODAS LAS CATEGORÍAS
rangos_precios_str = """{
'Electrónica': (49999, 1499999), 'Tecnología': (79999, 2499999), 'Hogar': (14999, 499999),
'Ropa': (4999, 79999), 'Deportes': (9999, 299999), 'Alimentos': (999, 14999), 'Bebidas': (799, 7999),
'Música': (29999, 899999), 'Belleza': (1999, 49999), 'Salud': (4999, 99999),
'Automotriz': (8999, 299999), 'Jardín': (7999, 199999), 'Oficina': (1999, 49999)
}"""
# -----------------------
# SISTEMA RESTAURANTE - MEJORADO CON PRECIOS ARGENTINOS REALISTAS
# -----------------------
categorias_restaurante_str = """{
'Comidas Dulces': {
'productos': [
'Torta de Chocolate Negro', 'Tiramisú Clásico', 'Cheesecake de Frutos Rojos',
'Pastel de Tres Leches', 'Mousse de Chocolate', 'Flan de Coco',
'Brownie con Helado', 'Crema Brûlée', 'Profiteroles con Chocolate',
'Tarta de Manzana Casera', 'Coulant de Chocolate', 'Macarons Franceses'
],
'marcas': ['Dulce Tentación', 'Postres Artesanales', 'Sweet Paradise', 'La Pastelería', 'Chef\\'s Delight'],
'precio_range': (2999, 11999) # ✅ CORREGIDO: Precios argentinos terminados en ,999
},
'Comidas Saladas': {
'productos': [
'Hamburguesa Gourmet con Queso', 'Pollo a la Parrilla con Hierbas',
'Empanadas de Carne Criollas', 'Costillas BBQ Ahumadas',
'Pizza Margherita Artesanal', 'Tacos al Pastor Mexicanos',
'Sándwich Club Triple', 'Lasagna de Carne y Queso',
'Pasta Carbonara Cremosa', 'Risotto de Champiñones', 'Ceviche Mixto Premium'
],
'marcas': ['Sabores Caseros', 'Cocina Tradicional', 'Food Masters', 'El Chef', 'Gourmet Experience'],
'precio_range': (3999, 17999) # ✅ CORREGIDO: Precios argentinos terminados en ,999
},
'Bebidas': {
'productos': [
'Jugo Natural de Naranja Fresca', 'Smoothie de Frutas Tropicales',
'Café Espresso Premium', 'Té Verde Matcha Orgánico',
'Limonada Natural con Menta', 'Agua Mineral con Gas',
'Refresco de Frutas Natural', 'Batido Proteico Energético',
'Cóctel Sin Alcohol Premium', 'Agua de Jamaica Natural', 'Chai Latte Especiado'
],
'marcas': ['Bebidas Frescas', 'Natural Drinks', 'Refresh Co', 'Aqua Pure', 'Beverage Masters'],
'precio_range': (1499, 5999) # ✅ CORREGIDO: Precios argentinos terminados en ,999
}
}"""
# ----------------------------------------------------------------
# ENSAMBLE DE CÓDIGO MOCK MEJORADO Y CORREGIDO
# ----------------------------------------------------------------
mock_data_code = f"""from faker import Faker
from datetime import datetime, timedelta
import random
from utils.image_generator import get_image_generator
fake = Faker('es_ES')
# 📱 SISTEMA GENERAL
nombres_reales = {nombres_reales_str}
categorias_marcas = {categorias_marcas_str}
rangos_precios = {rangos_precios_str}
# 🍽️ SISTEMA RESTAURANTE
CATEGORIAS_RESTAURANTE = {categorias_restaurante_str}
def generate_productos_mixtos():
productos = []
categorias_seleccionadas = {categorias_seleccionadas}
record_count = {module['record_count']} # ✅ CORREGIDO: Guardar en variable
print(f"🚀 Generando {{len(categorias_seleccionadas)}} categorías de productos MIXTOS")
print(f"📋 Categorías seleccionadas: {{', '.join(categorias_seleccionadas)}}")
print(f"💰 SISTEMA DE PRECIOS: PESOS ARGENTINOS CON PSICOLOGÍA ,999 🇦🇷")
categorias_generales_sel = [cat for cat in categorias_seleccionadas if cat in nombres_reales]
categorias_restaurante_sel = [cat for cat in categorias_seleccionadas if cat in CATEGORIAS_RESTAURANTE]
print(f" 📱 Categorías generales: {{', '.join(categorias_generales_sel)}}")
print(f" 🍽️ Categorías restaurante: {{', '.join(categorias_restaurante_sel)}}")
image_gen = get_image_generator()
# ✅ MANTENGO EXACTAMENTE EL MAPEO ORIGINAL DE LA UI:
image_modes = {{
'lexica': '🥇 Lexica (Búsquedas específicas con IA)',
'pollinations': '🥈 Pollinations AI (Generadas por IA)',
'pixabay': '🥉 Pixabay (Precisas, libres de derechos)',
'pexels': '📸 Pexels (Alta calidad)',
'placeholder': '🪄 Placeholder (Último recurso)',
'priority': '🎯 Orden de prioridad automático'
}}
selected_mode_description = image_modes.get('{image_mode}', '{image_mode}')
print(f" 📸 Modo de imágenes: {{selected_mode_description}}")
# MEJORA: Configurar delay entre requests para evitar rate limiting
request_delay = 0.3 if '{image_mode}' == 'priority' else 0.5
for i in range(record_count): # ✅ CORREGIDO: Usar variable
usar_restaurante = False
if categorias_generales_sel and categorias_restaurante_sel:
# MEJORA: Distribución más inteligente entre categorías
ratio_restaurante = len(categorias_restaurante_sel) / (len(categorias_generales_sel) + len(categorias_restaurante_sel))
usar_restaurante = random.random() < ratio_restaurante
elif categorias_restaurante_sel:
usar_restaurante = True
if usar_restaurante:
categoria = random.choice(categorias_restaurante_sel)
categoria_info = CATEGORIAS_RESTAURANTE.get(categoria, {{}})
marca = random.choice(categoria_info.get('marcas', ['Marca Restaurante']))
nombre_producto = random.choice(categoria_info.get('productos', ['Producto Premium']))
nombre_completo = f"{{marca}} {{nombre_producto}}"
descripcion = f"{{nombre_completo}} - Especialidad de restaurante de alta calidad. Preparado con ingredientes frescos y receta exclusiva."
precio_min, precio_max = categoria_info.get('precio_range', (2999, 11999))
sku = fake.unique.bothify(text='RES-#####')
else:
categoria = random.choice(categorias_generales_sel)
marca = random.choice(categorias_marcas[categoria])
nombre_producto = random.choice(nombres_reales[categoria])
nombre_completo = f"{{marca}} {{nombre_producto}}"
descripcion = f"{{nombre_completo}} - Producto de alta calidad en {{categoria}}. Garantía y soporte incluido."
precio_min, precio_max = rangos_precios.get(categoria, (999, 49999))
sku = fake.unique.bothify(text='SKU-#####')
# MEJORA: Pequeño delay entre generaciones de imágenes
if i > 0 and request_delay > 0:
import time
time.sleep(request_delay)
# Generar imagen usando el nuevo sistema con Lexica como prioridad
try:
imagen_url = image_gen.generate_product_image(
product_name=nombre_completo,
category=categoria,
image_source='{image_mode}'
)
except Exception as e:
print(f"⚠️ Error generando imagen para '{{nombre_completo}}': {{e}}")
# MEJORA: Fallback a placeholder en caso de error
imagen_url = image_gen.get_placeholder_image(nombre_completo, categoria)
# ✅ CORREGIDO: Generar precios realistas terminados en ,999 para Argentina
precio_base = random.randint(precio_min, precio_max)
# Asegurar que el precio termine en 999 (psicología de precios argentina)
precio = (precio_base // 1000) * 1000 + 999
producto = {{
"id": i + 1,
"nombre": nombre_completo,
"descripcion": descripcion,
"precio": precio, # ✅ CORREGIDO: Precios terminados en ,999
"categoria": categoria,
"marca": marca,
"stock": random.randint(10, 100),
"sku": sku,
"imagen_url": imagen_url,
"activo": True,
"fecha_creacion": fake.date_time_between(start_date='-6m', end_date='now'),
"fecha_actualizacion": fake.date_time_between(start_date='-1m', end_date='now')
}}
productos.append(producto)
# MEJORA: Progress indicator cada 10 productos
if (i + 1) % 10 == 0:
print(f" 📦 Generados {{i + 1}}/{{record_count}} productos...") # ✅ CORREGIDO: Usar variable
print(f"✅ Generación completada: {{len(productos)}} productos creados")
print(f"💰 RANGOS DE PRECIOS APLICADOS (PSICOLOGÍA ,999):")
print(f" • Electrónica: $49,999 - $1,499,999 ARS")
print(f" • Tecnología: $79,999 - $2,499,999 ARS")
print(f" • Hogar: $14,999 - $499,999 ARS")
print(f" • Ropa: $4,999 - $79,999 ARS")
print(f" • Deportes: $9,999 - $299,999 ARS")
print(f" • Alimentos: $999 - $14,999 ARS")
print(f" • Bebidas: $799 - $7,999 ARS")
print(f" • Música: $29,999 - $899,999 ARS")
print(f" • Belleza: $1,999 - $49,999 ARS")
print(f" • Salud: $4,999 - $99,999 ARS")
print(f" • Automotriz: $8,999 - $299,999 ARS")
print(f" • Jardín: $7,999 - $199,999 ARS")
print(f" • Oficina: $1,999 - $49,999 ARS")
print(f" • Restaurante: $1,499 - $17,999 ARS")
# MEJORA: Estadísticas más detalladas
stats = image_gen.get_stats()
print(f"📊 ESTADÍSTICAS DETALLADAS DE IMÁGENES:")
print(f" • Total de requests: {{stats['total_requests']}}")
print(f" • Fallbacks: {{stats['fallbacks']}}")
print(f" • Pixabay configurado: {{'✅' if stats['pixabay_configured'] else '❌'}}")
print(f" • Pexels configurado: {{'✅' if stats['pexels_configured'] else '❌'}}")
print(f" • Imágenes en cache: {{stats.get('cache_persistent', {{}}).get('total_cached_images', 0)}}") # ✅ CORREGIDO: KeyError
print(f" • Orden de prioridad: {{', '.join(stats['priority_order'])}}")
# MEJORA: Resumen por fuente de imágenes
print(f"🎯 RESUMEN POR FUENTE:")
cache_stats = stats.get('cache_persistent', {{}})
sources_data = cache_stats.get('sources', {{}})
for source, count in sources_data.items():
source_icons = {{'lexica': '🥇', 'pollinations': '🥈', 'pixabay': '🥉', 'pexels': '📸', 'placeholder': '🪄'}}
icon = source_icons.get(source, '📦')
print(f" {{icon}} {{source.capitalize()}}: {{count}} imágenes")
return productos
# MEJORA: Manejo de errores más robusto
try:
productos_data = generate_productos_mixtos()
if not productos_data:
print("❌ No se generaron productos. Verifica la configuración.")
productos_data = []
except Exception as e:
print(f"❌ Error crítico generando productos: {{e}}")
import traceback
traceback.print_exc()
productos_data = []
if __name__ == '__main__':
if productos_data:
print('🎯 MUESTRA DE PRODUCTOS GENERADOS (PRECIOS ARGENTINOS ,999 🇦🇷):')
for i, producto in enumerate(productos_data[:5]):
tipo = '🍽️ RESTAURANTE' if producto['sku'].startswith('RES-') else '📱 GENERAL'
print(f"{{i+1}}. [{{tipo}}] {{producto['nombre']}}")
print(f" Categoría: {{producto['categoria']}}")
print(f" 💰 Precio: ${{producto['precio']:,}} ARS") # ✅ CORREGIDO: Formato argentino con ,999
print(f" SKU: {{producto['sku']}}")
print(f" Imagen: {{producto['imagen_url'][:80]}}...")
print(f" Stock: {{producto['stock']}} unidades")
print()
else:
print("❌ No hay productos para mostrar")
"""
return mock_data_code
def generate_usuarios_mock_data(module, **kwargs):
"""Generar datos mock para usuarios - CORREGIDO"""
# ✅ CALCULAR CUÁNTOS USUARIOS MOCK GENERAR
total_usuarios = module['record_count'] # 3 (lo que el usuario configuró)
usuarios_mock_count = max(0, total_usuarios - 2) # 3 - 2 = 1 usuario mock
mock_data_code = f"""from faker import Faker
from datetime import datetime
import random
from passlib.context import CryptContext
fake = Faker('es_ES')
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def generate_usuarios():
usuarios = []
# ✅ CORRECCIÓN: Generar SOLO {usuarios_mock_count} usuarios mock
for i in range({usuarios_mock_count}):
raw_password = "password123"
usuario = {{
"id": i + 1,
"nombre": fake.first_name(),
"apellido": fake.last_name(),
"email": fake.unique.email(),
"password_hash": pwd_context.hash(raw_password),
"telefono": fake.phone_number(),
"direccion": fake.address().replace('\\n', ', '),
"ciudad": fake.city(),
"pais": "Argentina",
"rol": random.choice(["usuario", "usuario", "usuario", "admin"]),
"activo": random.choice([True, True, True, False]),
"fecha_registro": fake.date_time_this_year(),
"fecha_actualizacion": fake.date_time_this_year()
}}
usuarios.append(usuario)
return usuarios
def get_default_users():
'''Usuarios por defecto para testing'''
return [
{{
# "id": 9991,
"nombre": "Admin",
"apellido": "Sistema",
"email": "admin@example.com",
"password_hash": pwd_context.hash("admin123"),
"telefono": "+1234567890",
"direccion": "Dirección del administrador",
"ciudad": "Buenos Aires",
"pais": "Argentina",
"rol": "admin",
"activo": True,
"fecha_registro": datetime.utcnow(),
"fecha_actualizacion": datetime.utcnow()
}},
{{
# "id": 9992,
"nombre": "Usuario",
"apellido": "Normal",
"email": "usuario@example.com",
"password_hash": pwd_context.hash("user123"),
"telefono": "+0987654321",
"direccion": "Dirección del usuario",
"ciudad": "Córdoba",
"pais": "Argentina",
"rol": "usuario",
"activo": True,
"fecha_registro": datetime.utcnow(),
"fecha_actualizacion": datetime.utcnow()
}}
]
# ✅ CORRECCIÓN: Solo {usuarios_mock_count} usuarios mock + 2 del sistema = {total_usuarios} totales
usuarios_data = generate_usuarios()
default_users_data = get_default_users()
"""
return mock_data_code
def generate_populate_script(**kwargs):
"""Generar script para poblar la base de datos - VERSIÓN CON BACKUPS AUTOMÁTICOS"""
mock_modules = [m for m in kwargs['modules'] if m['source'] == 'mock' and kwargs['populate_db']]
if not mock_modules:
return "# No hay módulos mock para poblar\n"
# ✅ OBTENER API KEYS REALES DE LA CONFIGURACIÓN ACTUAL
pexels_api_key = st.session_state.get('pexels_api_key', "TU_API_KEY_PEXELS_AQUI")
pixabay_api_key = st.session_state.get('pixabay_api_key', "TU_API_KEY_PIXABAY_AQUI")
# ✅ AGREGAR CONFIGURACIÓN AL INICIO DEL SCRIPT
config_section = f"""
# ✅ CONFIGURAR IMAGE_GENERATOR CON API KEYS REALES
from utils.image_generator import configure_image_generator
configure_image_generator(
pexels_api_key="{pexels_api_key}",
pixabay_api_key="{pixabay_api_key}"
)
"""
imports = []
for module in mock_modules:
module_name = module['name']
imports.append(f"# Datos para {module_name}")
imports.append(f"try:")
imports.append(f" from data.{module_name}_data import {module_name}_data")
if module.get('type') == 'usuarios':
imports.append(f" from data.{module_name}_data import default_users_data")
imports.append(f" HAS_{module_name.upper()}_DATA = True")
imports.append(f" print(f\"✅ Datos de {module_name} cargados: {{len({module_name}_data)}} registros\")")
imports.append(f"except ImportError as e:")
imports.append(f" {module_name}_data = []")
if module.get('type') == 'usuarios':
imports.append(f" default_users_data = []")
imports.append(f" HAS_{module_name.upper()}_DATA = False")
imports.append(f" print(f\"❌ Error importando datos de {module_name}: {{e}}\")")
imports.append(f"except SyntaxError as e:")
imports.append(f" {module_name}_data = []")
if module.get('type') == 'usuarios':
imports.append(f" default_users_data = []")
imports.append(f" HAS_{module_name.upper()}_DATA = False")
imports.append(f" print(f\"❌ Error de sintaxis en {module_name}_data.py: {{e}}\")")
imports.append(f" print(\"💡 Regenera la API para solucionar este error\")")
imports.append(f"except Exception as e:")
imports.append(f" {module_name}_data = []")
if module.get('type') == 'usuarios':
imports.append(f" default_users_data = []")
imports.append(f" HAS_{module_name.upper()}_DATA = False")
imports.append(f" print(f\"❌ Error cargando {module_name}: {{e}}\")")
imports.append("")
imports_str = "\n".join(imports)
population_blocks = []
for module in mock_modules:
module_name = module['name']
model_name = module_name.capitalize()
campos_especificos = ""
if module.get('type') in ['pedidos', 'carrito', 'pagos', 'reseñas', 'direcciones']:
campos_especificos = f'''
if "{module_name}" in ["pedidos", "carrito", "pagos", "reseñas", "direcciones"]:
if "nombre" in item_copy:
del item_copy["nombre"]'''
block = f''' # Poblar {module_name}
print("📦 Poblando {module_name}...")
if not HAS_{module_name.upper()}_DATA:
print(" ⚠️ Sin datos disponibles")
else:
try:
model_class = getattr(models, "{model_name}")
existing_count = db.query(model_class).count()
if existing_count > 0:
print(f" ✅ Ya existen {{existing_count}} registros en {module_name}")
else:
records_to_add = []
added_count = 0
error_count = 0
# ✅ CORRECCIÓN: Manejo especial para usuarios por defecto (sin IDs hardcodeados)
if "{module_name}" == "usuarios":
if default_users_data:
for user_data in default_users_data:
try:
user_copy = user_data.copy()
# ✅ ELIMINAR SIEMPRE EL ID - La BD lo generará automáticamente
if "id" in user_copy:
del user_copy["id"]
# ✅ CORRECCIÓN: Asegurar que los usuarios del sistema tengan roles correctos
email = user_copy.get("email", "")
if "admin@example.com" in email:
user_copy["rol"] = "admin"
elif "usuario@example.com" in email:
user_copy["rol"] = "usuario"
record_instance = model_class(**user_copy)
records_to_add.append(record_instance)
added_count += 1
print(f" 👤 Usuario por defecto creado: {{user_copy['nombre']}} ({{user_copy['email']}})")
except Exception as e:
print(f" ⚠️ Error procesando usuario por defecto: {{e}}")
error_count += 1
continue
# Procesar datos mock regulares
for item_data in {module_name}_data:
try:
if not isinstance(item_data, dict):
print(f" ⚠️ Estructura de datos inválida, saltando registro")
error_count += 1
continue
item_copy = item_data.copy()
# ✅ CORRECCIÓN: ELIMINAR SIEMPRE EL ID EN TODOS LOS REGISTROS
if "id" in item_copy:
del item_copy["id"]{campos_especificos}
# ✅ CORRECCIÓN CRÍTICA: SOLO ELIMINAR CAMPOS QUE REALMENTE NO EXISTEN EN LOS MODELOS
# Los campos financieros (subtotal, iva, descuento, total) y fechas SÍ existen ahora
campos_invalidos = [] # ← VACÍO - NO ELIMINAR NINGÚN CAMPO VÁLIDO
# Solo eliminar campos que sabemos que no existen en ningún modelo
campos_inexistentes = ["campo_inexistente"] # Ejemplo, vacío por ahora
for campo in campos_inexistentes:
if campo in item_copy:
del item_copy[campo]
print(f" 🗑️ Eliminado campo inexistente: {{campo}}")
record_instance = model_class(**item_copy)
records_to_add.append(record_instance)
added_count += 1
if added_count % 10 == 0:
print(f" 📝 Procesados {{added_count}} registros de {module_name}...")
except Exception as e:
print(f" ⚠️ Error procesando registro: {{e}}")
print(f" 📋 Datos problemáticos: {{item_copy}}")
error_count += 1
continue
if records_to_add:
try:
db.add_all(records_to_add)
db.commit()
print(f" ✅ {module_name} poblados exitosamente: {{added_count}} registros agregados")
if error_count > 0:
print(f" ⚠️ Se omitieron {{error_count}} registros debido a errores")
# ✅ NUEVO: GENERAR BACKUP DESPUÉS DE POBLAR CADA MÓDULO
try:
from utils.backup_manager import backup_manager
backup_success = backup_manager.export_entity_to_json(db, model_class, "{module_name}")
if backup_success:
print(f" 💾 Backup JSON generado: {module_name}.json")
else:
print(f" ⚠️ Error generando backup de {module_name}")
except Exception as backup_error:
print(f" ⚠️ Error en sistema de backup: {{backup_error}}")
except Exception as e:
db.rollback()
print(f" ❌ Error en inserción masiva de {module_name}: {{str(e)}}")
# Mostrar más detalles del error
import traceback
print(f" 🔍 Detalles del error:")
traceback.print_exc()
else:
print(f" ⚠️ No hay registros válidos para agregar en {module_name}")
except AttributeError:
print(f" ❌ Modelo {model_name} no encontrado en models")
except Exception as e:
db.rollback()
print(f" ❌ Error crítico poblando {module_name}: {{str(e)}}")
import traceback
traceback.print_exc()'''
population_blocks.append(block)
population_str = "\n".join(population_blocks)
module_names = [m['name'] for m in mock_modules]
return f'''#!/usr/bin/env python3
\"\"\"Script para poblar la base de datos con datos iniciales - VERSIÓN CON BACKUPS AUTOMÁTICOS\"\"\"
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy.orm import Session
from database import engine, get_db
import models
{config_section}
# Importaciones de datos mock
{imports_str}
def populate_initial_data():
\"\"\"Poblar la base de datos con datos iniciales - CON BACKUPS JSON AUTOMÁTICOS\"\"\"
print("🚀 Iniciando población de base de datos...")
print("💡 NOTA: Todos los IDs serán generados automáticamente por la base de datos")
print("✅ TODOS los campos financieros y fechas se preservarán (subtotal, iva, descuento, total, fechas)")
print("💾 BACKUPS: Se generarán archivos JSON automáticamente para cada entidad")
print("🗄️ Creando tablas...")
try:
models.Base.metadata.create_all(bind=engine)
print("✅ Tablas creadas correctamente")
except Exception as e:
print(f"❌ Error creando tablas: {{e}}")
return
db = next(get_db())
try:
{population_str}
print("\\n🎉 Proceso de población completado!")
# ✅ NUEVO: GENERAR BACKUP COMPLETO DESPUÉS DE POBLAR TODOS LOS MÓDULOS
print("\\n💾 Generando backups JSON completos...")
try:
from utils.backup_manager import backup_manager
# Crear diccionario de modelos para backup
models_dict = {{}}
for module_name in {module_names}:
try:
model_class = getattr(models, module_name.capitalize())
models_dict[module_name] = model_class
except AttributeError:
print(f" ⚠️ No se pudo encontrar modelo para: {{module_name}}")
if models_dict:
backup_results = backup_manager.export_all_entities(db, models_dict)
successful_backups = sum(backup_results.values())
total_backups = len(backup_results)
print(f" 📊 Backups generados: {{successful_backups}}/{{total_backups}} entidades")
# Mostrar resumen de backups
backup_status = backup_manager.get_backup_status()
print(f" 📁 Directorio de backups: {{backup_status['summary']['backup_directory']}}")
print(f" 💽 Tamaño total: {{backup_status['summary']['total_size_kb']}} KB")
else:
print(" ⚠️ No se pudieron generar backups - sin modelos encontrados")
except Exception as backup_error:
print(f" ❌ Error en sistema de backups: {{backup_error}}")
import traceback
traceback.print_exc()
print("\\n📊 RESUMEN FINAL:")
print("=" * 60)
total_records = 0
for module_name in {module_names}:
try:
model_class = getattr(models, module_name.capitalize())
count = db.query(model_class).count()
total_records += count
status = "✅" if count > 0 else "❌"
icon = "👤" if module_name == "usuarios" else "📦" if module_name == "productos" else "🏷️" if module_name == "categorias" else "🛒" if module_name == "carrito" else "📋"
print(f" {{status}} {{icon}} {{module_name.capitalize():.<15}} {{count:>3}} registros")
except Exception as e:
print(f" ❌ {{module_name.capitalize():.<15}} Error: {{e}}")
print("=" * 60)
print(f" 📈 TOTAL REGISTROS: {{total_records:>18}}")
print(f" 💾 BACKUPS JSON: {'✅ ACTIVOS':>24}")
print(f" 📁 DIRECTORIO: {'backups/json/':>24}")
# ✅ VERIFICACIÓN DE CAMPOS FINANCIEROS EN MÓDULOS CLAVE
print("\\n💰 VERIFICACIÓN DE CAMPOS FINANCIEROS:")
try:
# Verificar carrito
if "carrito" in {module_names}:
from models.carrito import Carrito
carrito_item = db.query(Carrito).first()
if carrito_item:
print(f" 🛒 Carrito: subtotal=${{getattr(carrito_item, 'subtotal', 'N/A')}}, iva=${{getattr(carrito_item, 'iva', 'N/A')}}, total=${{getattr(carrito_item, 'total', 'N/A')}}")
# Verificar pedidos
if "pedidos" in {module_names}:
from models.pedidos import Pedidos
pedido = db.query(Pedidos).first()
if pedido:
print(f" 📦 Pedido: subtotal=${{getattr(pedido, 'subtotal', 'N/A')}}, iva=${{getattr(pedido, 'iva', 'N/A')}}, total=${{getattr(pedido, 'total', 'N/A')}}")
# Verificar pagos
if "pagos" in {module_names}:
from models.pagos import Pagos
pago = db.query(Pagos).first()
if pago:
print(f" 💳 Pago: monto=${{getattr(pago, 'monto', 'N/A')}}, comision=${{getattr(pago, 'comision', 'N/A')}}, total=${{getattr(pago, 'total', 'N/A')}}")
except Exception as e:
print(f" ℹ️ No se pudieron verificar campos financieros: {{e}}")
# ✅ CORRECCIÓN: Información adicional sobre usuarios del sistema
if "usuarios" in {module_names}:
try:
from models.usuarios import Usuarios
admin_user = db.query(Usuarios).filter(Usuarios.email == "admin@example.com").first()
normal_user = db.query(Usuarios).filter(Usuarios.email == "usuario@example.com").first()
print("\\n👤 USUARIOS DEL SISTEMA:")
if admin_user:
print(f" ✅ Admin: {{admin_user.email}} (ID: {{admin_user.id}}) - Rol: {{admin_user.rol}}")
if normal_user:
print(f" ✅ Usuario: {{normal_user.email}} (ID: {{normal_user.id}}) - Rol: {{normal_user.rol}}")
except Exception as e:
print(f" ℹ️ No se pudieron verificar usuarios del sistema: {{e}}")
# ✅ NUEVO: INFORMACIÓN SOBRE BACKUPS
print("\\n🔗 ACCESO A BACKUPS:")
print(" 🌐 Ver en navegador: http://localhost:8000/backups/")
print(" 📊 Estado de backups: http://localhost:8000/api/v1/backups/status")
print(" 💾 Descargar backups: http://localhost:8000/api/v1/backups/download/{{entidad}}")
except Exception as e:
print(f"💥 Error general en población: {{str(e)}}")
db.rollback()
import traceback
traceback.print_exc()
finally:
db.close()
if __name__ == "__main__":
populate_initial_data()
'''
# PARTE 6: Configuraciones y Archivos de Soporte
def generate_base_model(**kwargs):
return '''from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
'''
def generate_auth_utils(**kwargs):
return '''from jose import JWTError, jwt
from passlib.context import CryptContext
from datetime import datetime, timedelta
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from typing import Optional
from database import get_db
from models.usuarios import Usuarios
from config import settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
security = HTTPBearer()
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
def create_refresh_token(data: dict) -> str:
expire = datetime.utcnow() + timedelta(days=7)
to_encode = data.copy()
to_encode.update({"exp": expire, "type": "refresh"})
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
def verify_token(token: str) -> Optional[dict]:
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
return payload
except JWTError:
return None
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db)
) -> Usuarios:
token = credentials.credentials
payload = verify_token(token)
if not payload:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token inválido o expirado",
headers={"WWW-Authenticate": "Bearer"},
)
user_id = payload.get("sub")
if not user_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token inválido",
headers={"WWW-Authenticate": "Bearer"},
)
user = db.query(Usuarios).filter(Usuarios.id == int(user_id)).first()
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Usuario no encontrado",
headers={"WWW-Authenticate": "Bearer"},
)
if not user.activo:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Usuario inactivo",
headers={"WWW-Authenticate": "Bearer"},
)
return user
'''
def generate_database_config(**kwargs):
"""Generar configuración de base de datos - VERSIÓN CORREGIDA CON SOPORTE MULTI-BD"""
database = kwargs['database']
project_name = kwargs['project_name']
if database == 'PostgreSQL':
return f'''from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config import settings
# ✅ CONFIGURACIÓN ESPECÍFICA PARA POSTGRESQL
# URL esperada: postgresql://usuario:password@localhost:5432/{project_name}
engine = create_engine(
settings.DATABASE_URL,
pool_size=10,
max_overflow=20,
pool_pre_ping=True # ✅ Verifica conexiones antes de usarlas
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""Obtener sesión de base de datos para PostgreSQL"""
db = SessionLocal()
try:
yield db
finally:
db.close()
def create_tables():
"""Crear todas las tablas en PostgreSQL"""
from models.base import Base
print("🗄️ Creando tablas en PostgreSQL...")
Base.metadata.create_all(bind=engine)
print("✅ Tablas creadas exitosamente en PostgreSQL")
'''
elif database == 'MySQL':
return f'''from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config import settings
# ✅ CONFIGURACIÓN ESPECÍFICA PARA MYSQL
# URL esperada: mysql+mysqlconnector://usuario:password@localhost:3306/{project_name}
engine = create_engine(
settings.DATABASE_URL,
pool_size=10,
max_overflow=20,
pool_pre_ping=True, # ✅ Verifica conexiones antes de usarlas
pool_recycle=3600 # ✅ Recicla conexiones cada hora
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""Obtener sesión de base de datos para MySQL"""
db = SessionLocal()
try:
yield db
finally:
db.close()
def create_tables():
"""Crear todas las tablas en MySQL"""
from models.base import Base
print("🗄️ Creando tablas en MySQL...")
Base.metadata.create_all(bind=engine)
print("✅ Tablas creadas exitosamente en MySQL")
'''
else: # SQLite (por defecto)
return f'''from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config import settings
# ✅ CONFIGURACIÓN ESPECÍFICA PARA SQLITE
# URL esperada: sqlite:///./data/{project_name}.db
engine = create_engine(
settings.DATABASE_URL,
connect_args={{"check_same_thread": False}} # ✅ Solo para SQLite
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""Obtener sesión de base de datos para SQLite"""
db = SessionLocal()
try:
yield db
finally:
db.close()
def create_tables():
"""Crear todas las tablas en SQLite"""
from models.base import Base
print("🗄️ Creando tablas en SQLite...")
Base.metadata.create_all(bind=engine)
print("✅ Tablas creadas exitosamente en SQLite")
# ✅ Crear directorio data si no existe (solo para SQLite)
import os
data_dir = "data"
if not os.path.exists(data_dir):
os.makedirs(data_dir)
print(f"📁 Directorio '{{data_dir}}' creado para base de datos SQLite")
'''
def generate_config_file(**kwargs):
return '''import os
from dotenv import load_dotenv
load_dotenv()
class Settings:
PROJECT_NAME = os.getenv("PROJECT_NAME", "Mi API E-commerce")
VERSION = os.getenv("VERSION", "1.0.0")
ENVIRONMENT = os.getenv("ENVIRONMENT", "development")
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./test.db")
SECRET_KEY = os.getenv("SECRET_KEY", "clave-secreta-cambiar-en-produccion")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "30"))
CORS_ORIGINS = os.getenv("CORS_ORIGINS", "*").split(",")
settings = Settings()
'''
def generate_env_example(**kwargs):
return f'''# Configuración básica
PROJECT_NAME={kwargs['project_name']}
VERSION={kwargs['api_version']}
ENVIRONMENT=development
# Base de datos
DATABASE_URL=sqlite:///./test.db
# Autenticación JWT
SECRET_KEY=clave-secreta-cambiar-en-produccion
ACCESS_TOKEN_EXPIRE_MINUTES=30
# CORS
CORS_ORIGINS=*
'''
def generate_sql_scripts(**kwargs):
"""Generar scripts SQL de inicialización para MySQL y PostgreSQL - VERSIÓN CORREGIDA"""
database = kwargs['database']
project_name = kwargs['project_name']
modules = kwargs['modules']
print(f"🔧 Generando script SQL para: {database}")
print(f" Proyecto: {project_name}")
print(f" Módulos: {len(modules)}")
# ✅ VERIFICAR SI HAY MÓDULOS VÁLIDOS
if not modules:
return f"-- No hay módulos definidos para generar tablas en {database}"
# ✅ CORREGIDO: Usar 'in' en lugar de '=='
if 'PostgreSQL' in database:
# Generar definiciones de tablas para PostgreSQL
tables_sql = generate_tables_sql_dynamic(modules, 'postgresql')
# ✅ VERIFICAR QUE SE GENERARON TABLAS VÁLIDAS
if not tables_sql or "No se generaron tablas" in tables_sql:
return f"-- Error: No se pudieron generar tablas para PostgreSQL. Módulos: {len(modules)}"
return f'''-- Script de inicialización PostgreSQL para {project_name}
-- Ejecutar: psql -U postgres -f scripts/init_database.sql
CREATE DATABASE {project_name};
\\c {project_name};
-- Crear extensión para UUID si es necesario
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-- Configurar permisos básicos
GRANT ALL PRIVILEGES ON DATABASE {project_name} TO postgres;
-- ✅ CREAR TODAS LAS TABLAS DE LAS ENTIDADES
{tables_sql}
SELECT '✅ Base de datos {project_name} creada exitosamente con {len(modules)} tablas en PostgreSQL' as status;
'''
elif 'MySQL' in database:
# Generar definiciones de tablas para MySQL
tables_sql = generate_tables_sql_dynamic(modules, 'mysql')
# ✅ VERIFICAR QUE SE GENERARON TABLAS VÁLIDAS
if not tables_sql or "No se generaron tablas" in tables_sql:
return f"-- Error: No se pudieron generar tablas para MySQL. Módulos: {len(modules)}"
return f'''-- Script de inicialización MySQL para {project_name}
-- Ejecutar: mysql -u root -p < scripts/init_database.sql
CREATE DATABASE IF NOT EXISTS {project_name};
USE {project_name};
-- Configurar charset para soportar emojis y caracteres especiales
ALTER DATABASE {project_name} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Configurar permisos básicos
GRANT ALL PRIVILEGES ON {project_name}.* TO 'root'@'%';
-- ✅ CREAR TODAS LAS TABLAS DE LAS ENTIDADES
{tables_sql}
SELECT '✅ Base de datos {project_name} creada exitosamente con {len(modules)} tablas en MySQL' as status;
'''
else: # SQLite
return "# SQLite no requiere script de inicialización - La base de datos y tablas se crean automáticamente en ./data/test.db"
############# funciones auxiliares
def generate_fallback_table_sql(module_name, db_type):
if db_type == 'postgresql':
id_column = 'id SERIAL PRIMARY KEY'
else:
id_column = 'id INT AUTO_INCREMENT PRIMARY KEY'
return f'''-- Tabla básica para {module_name}
CREATE TABLE {module_name} (
{id_column},
nombre VARCHAR(255) NOT NULL,
descripcion TEXT,
activo BOOLEAN DEFAULT TRUE,
fecha_creacion TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
fecha_actualizacion TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_{module_name}_activo ON {module_name}(activo);
CREATE INDEX idx_{module_name}_nombre ON {module_name}(nombre);'''
def generate_tables_sql_dynamic(modules, db_type):
"""Generar SQL para crear todas las tablas basadas en los módulos - VERSIÓN CORREGIDA"""
tables_sql = []
if not modules:
return "-- No se generaron tablas (no hay módulos)"
print(f" 📊 Generando tablas para {len(modules)} módulos...")
for module in modules:
module_name = module['name']
try:
table_sql = generate_table_sql_dynamic(module, db_type)
if table_sql and table_sql.strip() and len(table_sql.strip()) > 10: # ✅ Verificar que no esté vacío
tables_sql.append(table_sql)
print(f" ✅ Tabla generada: {module_name}")
else:
print(f" ⚠️ Tabla vacía o inválida para: {module_name}")
# Generar una tabla básica como fallback
fallback_sql = generate_fallback_table_sql(module_name, db_type)
tables_sql.append(fallback_sql)
print(f" 🔄 Usando tabla fallback para: {module_name}")
except Exception as e:
print(f" ❌ Error generando tabla {module_name}: {e}")
# Generar tabla básica como fallback
fallback_sql = generate_fallback_table_sql(module_name, db_type)
tables_sql.append(fallback_sql)
print(f" 🔄 Usando tabla fallback por error para: {module_name}")
if not tables_sql:
return "-- No se generaron tablas (todos los módulos fallaron)"
return '\n\n'.join(tables_sql)
def get_module_specific_fields(module_type, db_type):
"""Obtener campos específicos según el tipo de módulo"""
field_definitions = {
'usuarios': [
' apellido VARCHAR(255) NOT NULL,',
' email VARCHAR(255) UNIQUE NOT NULL,',
' password_hash VARCHAR(255) NOT NULL,',
' telefono VARCHAR(50),',
' direccion TEXT,',
' ciudad VARCHAR(100),',
' pais VARCHAR(100) DEFAULT "España",',
' rol VARCHAR(50) DEFAULT "usuario",'
],
'productos': [
' precio DECIMAL(10,2) NOT NULL,',
' categoria VARCHAR(100) NOT NULL,',
' marca VARCHAR(100),',
' stock INTEGER DEFAULT 0,',
' sku VARCHAR(100) UNIQUE NOT NULL,',
' imagen_url VARCHAR(500),'
],
'pedidos': [
' usuario_id INTEGER NOT NULL,',
' subtotal DECIMAL(10,2) NOT NULL,',
' iva DECIMAL(10,2) DEFAULT 0.21,',
' descuento DECIMAL(10,2) DEFAULT 0.0,',
' envio DECIMAL(10,2) DEFAULT 0.0,',
' total DECIMAL(10,2) NOT NULL,',
' estado VARCHAR(50) DEFAULT "pendiente",',
' direccion_entrega TEXT NOT NULL,',
' telefono_contacto VARCHAR(50) NOT NULL,',
' notas TEXT,',
' metodo_pago VARCHAR(50) DEFAULT "tarjeta",',
' fecha_pedido TIMESTAMP DEFAULT CURRENT_TIMESTAMP,',
' fecha_entrega TIMESTAMP,'
],
'carrito': [
' usuario_id INTEGER NOT NULL,',
' producto_id INTEGER NOT NULL,',
' cantidad INTEGER DEFAULT 1,',
' precio_unitario DECIMAL(10,2) NOT NULL,',
' subtotal DECIMAL(10,2) NOT NULL,',
' iva DECIMAL(10,2) DEFAULT 0.21,',
' descuento DECIMAL(10,2) DEFAULT 0.0,',
' total DECIMAL(10,2) NOT NULL,',
' fecha_agregado TIMESTAMP DEFAULT CURRENT_TIMESTAMP,'
],
'pagos': [
' pedido_id INTEGER NOT NULL,',
' monto DECIMAL(10,2) NOT NULL,',
' comision DECIMAL(10,2) DEFAULT 0.0,',
' total DECIMAL(10,2) NOT NULL,',
' metodo_pago VARCHAR(100),',
' estado VARCHAR(50) DEFAULT "pendiente",',
' referencia VARCHAR(255) UNIQUE NOT NULL,',
' fecha_pago TIMESTAMP DEFAULT CURRENT_TIMESTAMP,'
],
'reseñas': [
' usuario_id INTEGER NOT NULL,',
' producto_id INTEGER NOT NULL,',
' calificacion INTEGER NOT NULL,',
' comentario TEXT,',
' aprobado BOOLEAN DEFAULT FALSE,',
' fecha_review TIMESTAMP DEFAULT CURRENT_TIMESTAMP,'
],
'direcciones': [
' usuario_id INTEGER NOT NULL,',
' tipo_direccion VARCHAR(50),',
' direccion TEXT NOT NULL,',
' ciudad VARCHAR(100) NOT NULL,',
' codigo_postal VARCHAR(20) NOT NULL,',
' pais VARCHAR(100) DEFAULT "España",',
' principal BOOLEAN DEFAULT FALSE,'
],
'cupones': [
' codigo VARCHAR(100) UNIQUE NOT NULL,',
' tipo_descuento VARCHAR(50),',
' valor_descuento DECIMAL(10,2) NOT NULL,',
' fecha_inicio TIMESTAMP NOT NULL,',
' fecha_fin TIMESTAMP NOT NULL,',
' usos_maximos INTEGER DEFAULT 100,',
' usos_actuales INTEGER DEFAULT 0,'
],
'categorias': [
' imagen_url VARCHAR(500),'
]
}
return field_definitions.get(module_type, [])
def generate_table_indexes(table_name, module_type, db_type):
"""Generar índices para la tabla según el tipo de módulo"""
indexes = []
# Índices comunes para todos los tipos
indexes.append(f'CREATE INDEX idx_{table_name}_activo ON {table_name}(activo);')
# Índices específicos por tipo
index_rules = {
'usuarios': ['email'],
'productos': ['categoria', 'sku'],
'pedidos': ['usuario_id', 'estado'],
'carrito': ['usuario_id'],
'pagos': ['referencia'],
'reseñas': ['usuario_id', 'producto_id'],
'direcciones': ['usuario_id'],
'cupones': ['codigo']
}
for field in index_rules.get(module_type, []):
indexes.append(f'CREATE INDEX idx_{table_name}_{field} ON {table_name}({field});')
return indexes
###############
def generate_init_database_script(**kwargs):
"""Generar script Python para inicialización automática de BD - VERSIÓN CORREGIDA"""
database = kwargs['database']
project_name = kwargs['project_name']
modules = kwargs['modules']
return f'''#!/usr/bin/env python3
"""
Script de inicialización automática de base de datos para {project_name}
Soporte para: {database}
Módulos: {len(modules)} ({', '.join([m['name'] for m in modules])})
"""
import os
import sys
import time
from pathlib import Path
def init_database():
"""Inicializar base de datos según el tipo configurado"""
database_type = "{database}"
project_name = "{project_name}"
modules_count = {len(modules)}
print("🚀 INICIALIZACIÓN AUTOMÁTICA DE BASE DE DATOS")
print("=" * 50)
print(f"📊 Proyecto: {{project_name}}")
print(f"🗄️ Base de datos: {{database_type}}")
print(f"📦 Módulos: {{modules_count}}")
print("=" * 50)
if database_type == "PostgreSQL":
return init_postgresql(project_name)
elif database_type == "MySQL":
return init_mysql(project_name)
else: # SQLite
return init_sqlite(project_name)
def init_postgresql(project_name):
"""Inicializar PostgreSQL"""
print("📊 Configurando PostgreSQL...")
try:
# Verificar si podemos conectarnos a PostgreSQL
import psycopg2
print("✅ psycopg2 disponible para PostgreSQL")
except ImportError:
print("❌ psycopg2 no instalado. Instala con: pip install psycopg2-binary")
return False
# El script SQL se ejecuta automáticamente via Docker
# En modo desarrollo, podemos verificar la conexión
print("💡 PostgreSQL se inicializará automáticamente via Docker")
print("📋 Script SQL generado en: scripts/init_database.sql")
# Simular espera para inicialización
print("⏳ Esperando inicialización de PostgreSQL...")
for i in range(3):
print(f" ... {{i+1}}/3")
time.sleep(1)
print("✅ PostgreSQL configurado y listo")
return True
def init_mysql(project_name):
"""Inicializar MySQL"""
print("📊 Configurando MySQL...")
try:
# Verificar si podemos conectarnos a MySQL
import mysql.connector
print("✅ mysql-connector disponible para MySQL")
except ImportError:
print("❌ mysql-connector no instalado. Instala con: pip install mysql-connector-python")
return False
# El script SQL se ejecuta automáticamente via Docker
print("💡 MySQL se inicializará automáticamente via Docker")
print("📋 Script SQL generado en: scripts/init_database.sql")
# Simular espera para inicialización
print("⏳ Esperando inicialización de MySQL...")
for i in range(3):
print(f" ... {{i+1}}/3")
time.sleep(1)
print("✅ MySQL configurado y listo")
return True
def init_sqlite(project_name):
"""Inicializar SQLite"""
print("📊 Configurando SQLite...")
# Crear directorio data si no existe
data_dir = Path("data")
if not data_dir.exists():
data_dir.mkdir(exist_ok=True)
print(f"📁 Directorio '{{data_dir}}' creado")
# Ruta de la base de datos SQLite
db_path = data_dir / f"{{project_name}}.db"
print(f"💾 Base de datos SQLite: {{db_path}}")
# Verificar que se puede crear la base de datos
try:
import sqlite3
# Crear conexión de prueba
conn = sqlite3.connect(db_path)
conn.close()
print("✅ SQLite configurado correctamente")
return True
except Exception as e:
print(f"❌ Error configurando SQLite: {{e}}")
return False
def check_dependencies():
"""Verificar dependencias necesarias"""
print("🔍 Verificando dependencias...")
dependencies = []
# Verificar Python - ✅ CORREGIDO: usar sys.version_info directamente
python_version = sys.version_info
version_str = f"{{python_version.major}}.{{python_version.minor}}.{{python_version.micro}}"
if python_version.major == 3 and python_version.minor >= 8:
dependencies.append(("🐍 Python 3.8+", version_str, "✅"))
else:
dependencies.append(("🐍 Python 3.8+", version_str, "❌"))
# Verificar SQLAlchemy
try:
import sqlalchemy
dependencies.append(("🗄️ SQLAlchemy", sqlalchemy.__version__, "✅"))
except ImportError:
dependencies.append(("🗄️ SQLAlchemy", "No encontrado", "❌"))
# Mostrar resultados
for name, version, status in dependencies:
print(f" {{status}} {{name}}: {{version}}")
return all(status == "✅" for _, _, status in dependencies)
if __name__ == "__main__":
print("🎯 SISTEMA DE INICIALIZACIÓN DE BASE DE DATOS")
print()
# Verificar dependencias
if not check_dependencies():
print("❌ Faltan dependencias necesarias")
sys.exit(1)
print()
# Inicializar base de datos
success = init_database()
print()
print("=" * 50)
if success:
print("🎉 INICIALIZACIÓN COMPLETADA EXITOSAMENTE")
print("💡 La base de datos está lista para usar")
sys.exit(0)
else:
print("💥 ERROR EN INICIALIZACIÓN")
print("🔧 Revisa la configuración y vuelve a intentar")
sys.exit(1)
'''
# ✅ FUNCIÓN DINÁMICA PARA GENERAR TABLAS BASADA EN MÓDULOS REALES
def generate_tables_sql_dynamic(modules, db_type):
"""Generar SQL para crear todas las tablas basadas en los módulos DINÁMICAMENTE"""
tables_sql = []
for module in modules:
module_name = module['name']
module_type = module.get('type', 'custom')
source = module.get('source', 'mock')
table_sql = generate_table_sql_dynamic(module, db_type)
if table_sql:
tables_sql.append(table_sql)
return '\n\n'.join(tables_sql)
# ✅ FUNCIÓN DINÁMICA PARA GENERAR CADA TABLA
def generate_table_sql_dynamic(module, db_type):
"""Generar SQL para crear una tabla específica basada en el módulo - VERSIÓN CORREGIDA"""
module_name = module['name']
module_type = module.get('type', 'custom')
source = module.get('source', 'mock')
try:
sql_parts = [f'-- Tabla: {module_name}']
sql_parts.append(f'CREATE TABLE {module_name} (')
# ✅ CORREGIDO: Campos base SIN "nombre" para tablas que no lo necesitan
base_fields_without_nombre = [
' id SERIAL PRIMARY KEY,' if db_type == 'postgresql' else ' id INT AUTO_INCREMENT PRIMARY KEY,',
' descripcion TEXT,',
' activo BOOLEAN DEFAULT TRUE,',
' fecha_creacion TIMESTAMP DEFAULT CURRENT_TIMESTAMP,',
' fecha_actualizacion TIMESTAMP DEFAULT CURRENT_TIMESTAMP'
]
base_fields_with_nombre = [
' id SERIAL PRIMARY KEY,' if db_type == 'postgresql' else ' id INT AUTO_INCREMENT PRIMARY KEY,',
' nombre VARCHAR(255) NOT NULL,',
' descripcion TEXT,',
' activo BOOLEAN DEFAULT TRUE,',
' fecha_creacion TIMESTAMP DEFAULT CURRENT_TIMESTAMP,',
' fecha_actualizacion TIMESTAMP DEFAULT CURRENT_TIMESTAMP'
]
# ✅ CORREGIDO: Determinar qué campos base usar
tables_without_nombre = ['carrito', 'pagos', 'reseñas', 'direcciones']
if module_name in tables_without_nombre:
base_fields = base_fields_without_nombre
else:
base_fields = base_fields_with_nombre
additional_fields = []
if module_type == 'usuarios':
additional_fields = [
' apellido VARCHAR(255) NOT NULL,',
' email VARCHAR(255) UNIQUE NOT NULL,',
' password_hash VARCHAR(255) NOT NULL,',
' telefono VARCHAR(50),',
' direccion TEXT,',
' ciudad VARCHAR(100),',
' pais VARCHAR(100) DEFAULT "España",',
' rol VARCHAR(50) DEFAULT "usuario",' # ✅ CORREGIDO: Agregada coma
]
elif module_type == 'productos':
additional_fields = [
' precio DECIMAL(10,2) NOT NULL,',
' categoria VARCHAR(100) NOT NULL,',
' marca VARCHAR(100),',
' stock INTEGER DEFAULT 0,',
' sku VARCHAR(100) UNIQUE NOT NULL,',
' imagen_url VARCHAR(500),' # ✅ CORREGIDO: Agregada coma
]
elif module_type == 'pedidos':
additional_fields = [
' usuario_id INTEGER NOT NULL,',
' subtotal DECIMAL(10,2) NOT NULL,',
' iva DECIMAL(10,2) DEFAULT 0.21,',
' descuento DECIMAL(10,2) DEFAULT 0.0,',
' envio DECIMAL(10,2) DEFAULT 0.0,',
' total DECIMAL(10,2) NOT NULL,',
' estado VARCHAR(50) DEFAULT "pendiente",',
' direccion_entrega TEXT NOT NULL,',
' telefono_contacto VARCHAR(50) NOT NULL,',
' notas TEXT,',
' metodo_pago VARCHAR(50) DEFAULT "tarjeta",',
' fecha_pedido TIMESTAMP DEFAULT CURRENT_TIMESTAMP,',
' fecha_entrega TIMESTAMP,' # ✅ CORREGIDO: Agregada coma
]
elif module_type == 'carrito':
additional_fields = [
' usuario_id INTEGER NOT NULL,',
' producto_id INTEGER NOT NULL,',
' cantidad INTEGER DEFAULT 1,',
' precio_unitario DECIMAL(10,2) NOT NULL,',
' subtotal DECIMAL(10,2) NOT NULL,',
' iva DECIMAL(10,2) DEFAULT 0.21,',
' descuento DECIMAL(10,2) DEFAULT 0.0,',
' total DECIMAL(10,2) NOT NULL,',
' fecha_agregado TIMESTAMP DEFAULT CURRENT_TIMESTAMP,' # ✅ CORREGIDO: Agregada coma
]
elif module_type == 'pagos':
additional_fields = [
' pedido_id INTEGER NOT NULL,',
' monto DECIMAL(10,2) NOT NULL,',
' comision DECIMAL(10,2) DEFAULT 0.0,',
' total DECIMAL(10,2) NOT NULL,',
' metodo_pago VARCHAR(100),',
' estado VARCHAR(50) DEFAULT "pendiente",',
' referencia VARCHAR(255) UNIQUE NOT NULL,',
' fecha_pago TIMESTAMP DEFAULT CURRENT_TIMESTAMP,' # ✅ CORREGIDO: Agregada coma
]
elif module_type == 'reseñas':
additional_fields = [
' usuario_id INTEGER NOT NULL,',
' producto_id INTEGER NOT NULL,',
' calificacion INTEGER NOT NULL,',
' comentario TEXT,',
' aprobado BOOLEAN DEFAULT FALSE,',
' fecha_review TIMESTAMP DEFAULT CURRENT_TIMESTAMP,' # ✅ CORREGIDO: Agregada coma
]
elif module_type == 'direcciones':
additional_fields = [
' usuario_id INTEGER NOT NULL,',
' tipo_direccion VARCHAR(50),',
' direccion TEXT NOT NULL,',
' ciudad VARCHAR(100) NOT NULL,',
' codigo_postal VARCHAR(20) NOT NULL,',
' pais VARCHAR(100) DEFAULT "España",',
' principal BOOLEAN DEFAULT FALSE,' # ✅ CORREGIDO: Agregada coma
]
elif module_type == 'cupones':
additional_fields = [
' codigo VARCHAR(100) UNIQUE NOT NULL,',
' tipo_descuento VARCHAR(50),',
' valor_descuento DECIMAL(10,2) NOT NULL,',
' fecha_inicio TIMESTAMP NOT NULL,',
' fecha_fin TIMESTAMP NOT NULL,',
' usos_maximos INTEGER DEFAULT 100,',
' usos_actuales INTEGER DEFAULT 0,' # ✅ CORREGIDO: Agregada coma
]
elif module_type == 'categorias':
additional_fields = [
' imagen_url VARCHAR(500),' # ✅ CORREGIDO: Agregada coma
]
elif source == 'file' and 'fields' in module:
for field_name, config in module['fields'].items():
field_type = config['type']
sql_type = map_field_type_to_sql(field_type, db_type)
required = ' NOT NULL' if config.get('required', True) else ''
additional_fields.append(f' {field_name} {sql_type}{required},')
# ✅ CORREGIDO: Construcción de campos con manejo de comas
all_fields = []
# Agregar campos adicionales primero
if additional_fields:
all_fields.extend(additional_fields)
# Agregar campos base (todos menos el último sin coma)
all_fields.extend(base_fields[:-1])
# Agregar el último campo sin coma
all_fields.append(base_fields[-1])
sql_parts.extend(all_fields)
sql_parts.append(');')
indexes = generate_table_indexes(module_name, module_type, db_type)
if indexes:
sql_parts.append('')
sql_parts.extend(indexes)
foreign_keys = generate_foreign_keys(module_name, module_type, db_type)
if foreign_keys:
sql_parts.append('')
sql_parts.extend(foreign_keys)
return '\n'.join(sql_parts)
except Exception as e:
print(f"Error generando tabla {module_name}: {e}")
return generate_fallback_table_sql(module_name, db_type)
# ✅ FUNCIÓN AUXILIAR PARA MAPEAR TIPOS DE CAMPO A SQL
def map_field_type_to_sql(field_type, db_type):
"""Mapear tipos de campo de Python a tipos SQL"""
type_mapping = {
'string': 'VARCHAR(255)',
'integer': 'INTEGER',
'float': 'DECIMAL(10,2)',
'boolean': 'BOOLEAN',
'datetime': 'TIMESTAMP',
'email': 'VARCHAR(255)',
'url': 'VARCHAR(500)'
}
return type_mapping.get(field_type, 'VARCHAR(255)')
# ✅ FUNCIÓN PARA GENERAR ÍNDICES
def generate_table_indexes(table_name, module_type, db_type):
"""Generar índices para la tabla según el tipo de módulo - VERSIÓN CORREGIDA"""
indexes = []
# Índices comunes para todos los tipos
indexes.append(f'CREATE INDEX idx_{table_name}_activo ON {table_name}(activo);')
# Índices específicos por tipo
if module_type == 'usuarios':
indexes.append(f'CREATE INDEX idx_{table_name}_email ON {table_name}(email);')
elif module_type == 'productos':
indexes.append(f'CREATE INDEX idx_{table_name}_categoria ON {table_name}(categoria);')
indexes.append(f'CREATE INDEX idx_{table_name}_sku ON {table_name}(sku);')
elif module_type == 'pedidos':
indexes.append(f'CREATE INDEX idx_{table_name}_usuario_id ON {table_name}(usuario_id);')
indexes.append(f'CREATE INDEX idx_{table_name}_estado ON {table_name}(estado);')
elif module_type == 'carrito':
indexes.append(f'CREATE INDEX idx_{table_name}_usuario_id ON {table_name}(usuario_id);')
elif module_type == 'pagos':
indexes.append(f'CREATE INDEX idx_{table_name}_pedido_id ON {table_name}(pedido_id);')
indexes.append(f'CREATE INDEX idx_{table_name}_referencia ON {table_name}(referencia);')
indexes.append(f'CREATE INDEX idx_{table_name}_estado ON {table_name}(estado);')
elif module_type == 'reseñas':
indexes.append(f'CREATE INDEX idx_{table_name}_usuario_id ON {table_name}(usuario_id);')
indexes.append(f'CREATE INDEX idx_{table_name}_producto_id ON {table_name}(producto_id);')
elif module_type == 'direcciones':
indexes.append(f'CREATE INDEX idx_{table_name}_usuario_id ON {table_name}(usuario_id);')
elif module_type == 'cupones':
indexes.append(f'CREATE INDEX idx_{table_name}_codigo ON {table_name}(codigo);')
return indexes
# ✅ FUNCIÓN PARA GENERAR FOREIGN KEYS
def generate_foreign_keys(table_name, module_type, db_type):
"""Generar foreign keys según relaciones entre tablas"""
foreign_keys = []
if module_type == 'pedidos':
foreign_keys.append(f'ALTER TABLE {table_name} ADD FOREIGN KEY (usuario_id) REFERENCES usuarios(id);')
elif module_type == 'carrito':
foreign_keys.append(f'ALTER TABLE {table_name} ADD FOREIGN KEY (usuario_id) REFERENCES usuarios(id);')
foreign_keys.append(f'ALTER TABLE {table_name} ADD FOREIGN KEY (producto_id) REFERENCES productos(id);')
elif module_type == 'pagos':
foreign_keys.append(f'ALTER TABLE {table_name} ADD FOREIGN KEY (pedido_id) REFERENCES pedidos(id);')
elif module_type == 'reseñas':
foreign_keys.append(f'ALTER TABLE {table_name} ADD FOREIGN KEY (usuario_id) REFERENCES usuarios(id);')
foreign_keys.append(f'ALTER TABLE {table_name} ADD FOREIGN KEY (producto_id) REFERENCES productos(id);')
elif module_type == 'direcciones':
foreign_keys.append(f'ALTER TABLE {table_name} ADD FOREIGN KEY (usuario_id) REFERENCES usuarios(id);')
return foreign_keys
# ✅ FUNCIÓN AUXILIAR PARA OBTENER CAMPOS DE TABLA
def get_table_fields(module_type):
"""Obtener campos de tabla según tipo de módulo (para índices)"""
fields_map = {
'usuarios': ['usuario_id', 'email'],
'productos': ['categoria', 'sku'],
'pedidos': ['usuario_id', 'estado'],
'carrito': ['usuario_id'],
'pagos': ['usuario_id', 'estado', 'referencia'],
'reseñas': ['usuario_id', 'producto_id'],
'direcciones': ['usuario_id'],
'cupones': ['codigo']
}
return fields_map.get(module_type, [])
def generate_readme(**kwargs):
return f'''# {kwargs['project_name'].replace('_', ' ').title()} API - E-commerce
## 🚀 Características
- **Framework**: FastAPI
- **Base de datos**: {kwargs['database']}
- **Autenticación**: {'JWT' if kwargs['include_auth'] else 'No'}
- **Documentación**: {'Swagger/Redoc' if kwargs['include_docs'] else 'No'}
- **Docker**: {'Sí' if kwargs['include_docker'] else 'No'}
- **Módulos**: {len(kwargs['modules'])} módulos implementados
## 📦 Módulos Implementados
{chr(10).join([f'- **{module["name"]}**: {module["route"]}' for module in kwargs['modules']])}
## 🛠️ Instalación
### Desarrollo
```bash
cd {kwargs['project_name']}
pip install -r requirements.txt
uvicorn main:app --reload
```
### Producción
```bash
docker-compose up -d
```
## 🔗 Endpoints Principales
- **API**: http://localhost:8000
- **Documentación**: http://localhost:8000/docs
- **Health Check**: http://localhost:8000/health
## 📊 Datos Mock
La API incluye datos de prueba automáticos para:
{chr(10).join([f'- {module["name"]} ({module.get("record_count", 0)} registros)' for module in kwargs['modules'] if module.get('source') == 'mock'])}
## 🎯 Características Técnicas
- CRUD completo para todos los módulos
- Validación de datos con Pydantic v2
- Autenticación JWT
- Sistema de imágenes con 3 fuentes
- Paginación y búsqueda
- Manejo de errores robusto
- CORS habilitado
## 📝 Notas
Esta API fue generada automáticamente con DataSuite Pro.
Incluye un sistema completo de E-commerce con módulos esenciales.
'''
# PARTE 7: Generadores de Datos Mock Restantes
def generate_pedidos_mock_data(module, **kwargs):
"""Generar datos mock para pedidos - VERSIÓN ARGENTINA CON PRECIOS REALISTAS"""
mock_data_code = f"""from faker import Faker
from datetime import datetime, timedelta
import random
fake = Faker('es_AR') # 🇦🇷 Cambiado a español Argentina
def generate_pedidos():
pedidos = []
estados = ['pendiente', 'confirmado', 'preparando', 'en_camino', 'entregado', 'cancelado']
# Notas realistas adaptadas para Argentina
notas_posibles = [
"Entregar después de las 18:00 hs",
"Llamar antes de entregar al celular",
"Dejar en portería/recepción",
"Productos refrigerados, mantener en frío",
"Regalo, no incluir factura",
"Entregar en puerta principal",
"Timbre no funciona, llamar por WhatsApp",
"Pedido urgente para hoy",
"Embalaje para regalo",
"Confirmar stock antes de enviar",
"Cobrar contraentrega",
"Departamento A, piso 3",
"Entregar en oficina contabilidad",
"Pedido corporativo - solicitar DNI",
"Factura A requerida"
]
# Métodos de pago comunes en Argentina
metodos_pago = ['tarjeta_credito', 'tarjeta_debito', 'mercado_pago', 'transferencia', 'efectivo']
for i in range({module['record_count']}):
fecha_pedido = fake.date_time_this_year()
fecha_creacion = fecha_pedido - timedelta(hours=random.randint(1, 24))
# ✅ CORREGIDO: CÁLCULOS FINANCIEROS CON PRECIOS ARGENTINOS REALISTAS
subtotal = random.randint(15000, 300000) # Subtotal entre $15.000 y $300.000 ARS (más realista)
iva = round(subtotal * 0.21) # 🇦🇷 IVA 21% Argentina - sin decimales
descuento = round(subtotal * random.uniform(0, 0.15)) if random.random() > 0.7 else 0 # 0-15% descuento ocasional
envio = random.randint(2000, 15000) if random.random() > 0.3 else 0 # Costo de envío $2.000-$15.000 (más realista)
total = subtotal + iva + envio - descuento
pedido = {{
"id": i + 1,
"usuario_id": random.randint(1, {module['record_count']}),
"subtotal": subtotal,
"iva": iva,
"descuento": descuento,
"envio": envio,
"total": total,
"estado": random.choice(estados),
"direccion_entrega": fake.address().replace('\\n', ', '),
"telefono_contacto": fake.phone_number(),
"notas": random.choice(notas_posibles) if random.random() > 0.6 else None,
"metodo_pago": random.choice(metodos_pago),
"fecha_pedido": fecha_pedido,
"fecha_entrega": fecha_pedido + timedelta(days=random.randint(1, 7)) if random.random() > 0.3 else None,
"activo": True,
"fecha_creacion": fecha_creacion,
"fecha_actualizacion": fake.date_time_between(start_date=fecha_creacion, end_date='now')
}}
pedidos.append(pedido)
return pedidos
pedidos_data = generate_pedidos()
if __name__ == '__main__':
data = generate_pedidos()
print(f"📦 Generados {{len(data)}} pedidos - VERSIÓN ARGENTINA 🇦🇷 CON PRECIOS REALISTAS")
print(f"💰 RANGOS APLICADOS: Subtotal $15,000 - $300,000 ARS | Envío $2,000 - $15,000 ARS")
if data:
print("📋 Muestra de pedidos:")
for i, pedido in enumerate(data[:3]):
print(f" {{i+1}}. Usuario {{pedido['usuario_id']}} - Estado: {{pedido['estado'].upper()}}")
print(f" 💰 Subtotal: ${{pedido['subtotal']:,}} ARS")
print(f" 📊 IVA (21%): ${{pedido['iva']:,}} ARS")
print(f" 🚚 Envío: ${{pedido['envio']:,}} ARS")
print(f" 🎁 Descuento: ${{pedido['descuento']:,}} ARS")
print(f" 💵 TOTAL: ${{pedido['total']:,}} ARS")
print(f" 💳 Método pago: {{pedido['metodo_pago']}}")
print(f" 📅 Pedido: {{pedido['fecha_pedido'].strftime('%d/%m/%Y %H:%M')}}")
if pedido['fecha_entrega']:
print(f" 🚚 Entrega: {{pedido['fecha_entrega'].strftime('%d/%m/%Y')}}")
if pedido['notas']:
print(f" 📝 Notas: {{pedido['notas']}}")
print()
"""
return mock_data_code
def generate_categorias_mock_data(module, **kwargs):
"""Generar datos mock para categorías - VERSIÓN CORREGIDA CON SINCRONIZACIÓN"""
# Obtener las categorías seleccionadas desde el módulo
categorias_seleccionadas = module.get('categorias_seleccionadas', [])
# Si no hay categorías seleccionadas, usar algunas por defecto
if not categorias_seleccionadas:
categorias_seleccionadas = ['Electrónicos', 'Hogar', 'Ropa', 'Deportes']
# Diccionario de descripciones para categorías comunes
descripciones_categorias = {
'Electrónicos': "Dispositivos electrónicos de última generación para el hogar y oficina",
'Hogar': "Productos para mejorar y decorar tu hogar",
'Ropa': "Moda actual para todas las edades y ocasiones",
'Deportes': "Equipamiento deportivo para mantenerte activo",
'Juguetes': "Juguetes educativos y divertidos para niños",
'Libros': "Literatura y libros educativos para todos los gustos",
'Música': "Instrumentos musicales y equipos de audio",
'Belleza': "Productos de belleza y cuidado personal",
'Salud': "Productos para el cuidado de la salud y bienestar",
'Tecnología': "Tecnología innovadora para el día a día",
'Alimentos': "Productos alimenticios frescos y de calidad",
'Bebidas': "Bebidas refrescantes y saludables",
'Automotriz': "Accesorios y repuestos para vehículos",
'Jardín': "Herramientas y plantas para tu jardín",
'Oficina': "Suministros y muebles para oficina",
'Comidas Dulces': "Postres y dulces artesanales de alta calidad",
'Comidas Saladas': "Platos salados y especialidades culinarias",
'Bebidas': "Bebidas refrescantes, alcohólicas y no alcohólicas"
}
mock_data_code = f"""from faker import Faker
from datetime import datetime
import random
fake = Faker('es_ES')
def generate_categorias():
categorias = []
# Categorías seleccionadas desde la configuración (YA SIN DUPLICADOS)
categorias_seleccionadas = {categorias_seleccionadas}
# ✅ GARANTIZAR que no hay duplicados (doble verificación)
categorias_unicas = list(set(categorias_seleccionadas))
# ✅ PRIORIDAD: Las categorías se mantienen en el orden original para que
# las categorías de productos aparezcan primero en la paginación
categorias_ordenadas = []
for cat in categorias_seleccionadas:
if cat in categorias_unicas and cat not in categorias_ordenadas:
categorias_ordenadas.append(cat)
# Agregar cualquier categoría que pudiera haberse perdido
for cat in categorias_unicas:
if cat not in categorias_ordenadas:
categorias_ordenadas.append(cat)
# Limitar al número de registros solicitados (que ahora es automático = total categorías)
categorias_a_generar = categorias_ordenadas[:{module['record_count']}]
print(f"📊 Generando categorías SINCRONIZADAS y SIN DUPLICADOS: {{len(categorias_a_generar)}} categorías")
print(f" 🎯 PRIORIDAD: Las categorías de productos aparecerán primero en paginación")
print(f" 📋 Categorías en orden: {{', '.join(categorias_a_generar)}}")
descripciones_categorias = {descripciones_categorias}
for i, nombre_categoria in enumerate(categorias_a_generar):
fecha_creacion = fake.date_time_this_year()
# Obtener descripción o crear una genérica
descripcion = descripciones_categorias.get(
nombre_categoria,
f"Productos de la categoría {{nombre_categoria}}"
)
categoria = {{
"id": i + 1,
"nombre": nombre_categoria,
"descripcion": descripcion,
"imagen_url": f"https://image.pollinations.ai/prompt/{{nombre_categoria.replace(' ', '+')}}+category+icon+español",
"activo": True,
"fecha_creacion": fecha_creacion,
"fecha_actualizacion": fake.date_time_between(start_date=fecha_creacion, end_date='now')
}}
categorias.append(categoria)
return categorias
categorias_data = generate_categorias()
if __name__ == '__main__':
data = generate_categorias()
print(f"✅ Generadas {{len(data)}} categorías SIN DUPLICADOS")
print(f" 🎯 ORDEN DE PRIORIDAD:")
for i, cat in enumerate(data):
print(f" {{i+1}}. 🏷️ {{cat['nombre']}}")
"""
return mock_data_code
# def generate_categorias_mock_data(module, **kwargs):
# """Generar datos mock para categorías - VERSIÓN MEJORADA EN ESPAÑOL"""
# mock_data_code = f"""from faker import Faker
# from datetime import datetime
# import random
# fake = Faker('es_ES')
# def generate_categorias():
# categorias = []
# categorias_info = [
# {{"nombre": "Electrónicos", "descripcion": "Dispositivos electrónicos de última generación para el hogar y oficina"}},
# {{"nombre": "Hogar", "descripcion": "Productos para mejorar y decorar tu hogar"}},
# {{"nombre": "Ropa", "descripcion": "Moda actual para todas las edades y ocasiones"}},
# {{"nombre": "Deportes", "descripcion": "Equipamiento deportivo para mantenerte activo"}},
# {{"nombre": "Juguetes", "descripcion": "Juguetes educativos y divertidos para niños"}},
# {{"nombre": "Libros", "descripcion": "Literatura y libros educativos para todos los gustos"}},
# {{"nombre": "Música", "descripcion": "Instrumentos musicales y equipos de audio"}},
# {{"nombre": "Belleza", "descripcion": "Productos de belleza y cuidado personal"}},
# {{"nombre": "Salud", "descripcion": "Productos para el cuidado de la salud y bienestar"}},
# {{"nombre": "Tecnología", "descripcion": "Tecnología innovadora para el día a día"}},
# {{"nombre": "Alimentos", "descripcion": "Productos alimenticios frescos y de calidad"}},
# {{"nombre": "Bebidas", "descripcion": "Bebidas refrescantes y saludables"}},
# {{"nombre": "Automotriz", "descripcion": "Accesorios y repuestos para vehículos"}},
# {{"nombre": "Jardín", "descripcion": "Herramientas y plantas para tu jardín"}},
# {{"nombre": "Oficina", "descripcion": "Suministros y muebles para oficina"}}
# ]
# # Limitar al número de registros solicitados
# categorias_seleccionadas = categorias_info[:{module['record_count']}]
# for i, cat_info in enumerate(categorias_seleccionadas):
# fecha_creacion = fake.date_time_this_year()
# categoria = {{
# "id": i + 1,
# "nombre": cat_info["nombre"],
# "descripcion": cat_info["descripcion"],
# "imagen_url": f"https://image.pollinations.ai/prompt/{{cat_info['nombre'].replace(' ', '+')}}+category+icon+español",
# "activo": True,
# "fecha_creacion": fecha_creacion,
# "fecha_actualizacion": fake.date_time_between(start_date=fecha_creacion, end_date='now')
# }}
# categorias.append(categoria)
# return categorias
# categorias_data = generate_categorias()
# """
# return mock_data_code
def generate_carrito_mock_data(module, **kwargs):
"""Generar datos mock para carrito - VERSIÓN ARGENTINA CON PRECIOS ,999"""
mock_data_code = f"""from faker import Faker
from datetime import datetime
import random
fake = Faker('es_AR') # 🇦🇷 Cambiado a español Argentina
def generate_carrito():
carrito_items = []
# ✅ CORREGIDO: Precios base realistas en pesos argentinos TERMINADOS EN ,999
precios_base = [15999, 25999, 45999, 75999, 119999, 179999, 249999, 349999, 499999, 749999, 949999, 1199999, 1499999, 1999999]
for i in range({module['record_count']}):
precio_unitario = random.choice(precios_base)
cantidad = random.randint(1, 3) # Cantidades realistas (1-3 productos)
subtotal = precio_unitario * cantidad
iva = round(subtotal * 0.21) # 🇦🇷 IVA 21% estándar Argentina
descuento = round(subtotal * random.uniform(0, 0.15)) if random.random() > 0.7 else 0 # 0-15% descuento ocasional
total = subtotal + iva - descuento
fecha_agregado = fake.date_time_this_month()
fecha_creacion = fecha_agregado
fecha_actualizacion = fake.date_time_between(start_date=fecha_agregado, end_date='now')
item = {{
"usuario_id": random.randint(1, {module['record_count']}),
"producto_id": random.randint(1, {module['record_count']}),
"cantidad": cantidad,
"precio_unitario": precio_unitario,
"subtotal": subtotal,
"iva": iva,
"descuento": descuento,
"total": total,
"fecha_agregado": fecha_agregado,
"activo": True,
"fecha_creacion": fecha_creacion,
"fecha_actualizacion": fecha_actualizacion
}}
carrito_items.append(item)
return carrito_items
carrito_data = generate_carrito()
if __name__ == '__main__':
data = generate_carrito()
print(f"🛒 Generados {{len(data)}} items de carrito - VERSIÓN ARGENTINA 🇦🇷 CON PRECIOS ,999")
print(f"💰 RANGOS DE PRECIOS: $15,999 - $1,999,999 ARS (psicología de precios argentina)")
if data:
print("📋 Muestra de items del carrito:")
for i, item in enumerate(data[:3]):
print(f" {{i+1}}. Usuario {{item['usuario_id']}} - Producto {{item['producto_id']}}")
print(f" Cantidad: {{item['cantidad']}}, Precio unitario: ${{item['precio_unitario']:,}} ARS")
print(f" Subtotal: ${{item['subtotal']:,}} ARS")
print(f" IVA (21%): ${{item['iva']:,}} ARS")
print(f" Descuento: ${{item['descuento']:,}} ARS")
print(f" 💰 TOTAL: ${{item['total']:,}} ARS")
print(f" 📅 Fecha agregado: {{item['fecha_agregado'].strftime('%d/%m/%Y %H:%M')}}")
print()
"""
return mock_data_code
def generate_pagos_mock_data(module, **kwargs):
"""Generar datos mock para pagos - VERSIÓN ARGENTINA CON PRECIOS REALISTAS ,999"""
mock_data_code = f"""from faker import Faker
from datetime import datetime, timedelta
import random
fake = Faker('es_AR') # 🇦🇷 Cambiado a español Argentina
def generate_pagos():
pagos = []
estados_pago = ['pendiente', 'completado', 'fallido', 'reembolsado', 'en_proceso']
# Métodos de pago comunes en Argentina
metodos_pago = ['tarjeta_credito', 'tarjeta_debito', 'mercado_pago', 'transferencia_bancaria', 'efectivo', 'rapipago', 'pagofacil']
for i in range({module['record_count']}):
fecha_pago = fake.date_time_this_year()
fecha_creacion = fecha_pago - timedelta(hours=random.randint(1, 12))
# ✅ CORREGIDO: MONTOS EN PESOS ARGENTINOS REALISTAS TERMINADOS EN ,999
monto_base = random.randint(15000, 300000) # Entre $15.000 y $300.000 ARS (alineado con pedidos realistas)
# Asegurar que el monto base termine en 999
monto_base = (monto_base // 1000) * 1000 + 999
comision = round(monto_base * random.uniform(0.02, 0.08)) # Comisión 2-8% sin decimales
total = monto_base + comision # Sin decimales
# Para pagos completados, la actualización es posterior al pago
if random.random() > 0.3: # 70% de pagos completados
fecha_actualizacion = fecha_pago + timedelta(minutes=random.randint(5, 120))
else:
fecha_actualizacion = fecha_pago
# Generar referencia según método de pago
metodo = random.choice(metodos_pago)
if metodo == 'mercado_pago':
referencia = fake.unique.bothify(text='MP-##########')
elif metodo in ['tarjeta_credito', 'tarjeta_debito']:
referencia = fake.unique.bothify(text='TC-############')
elif metodo in ['rapipago', 'pagofacil']:
referencia = fake.unique.bothify(text='RP-##########')
else:
referencia = fake.unique.bothify(text='PAGO-########')
pago = {{
"id": i + 1,
"pedido_id": random.randint(1, {module['record_count']}),
"monto": monto_base,
"comision": comision,
"total": total,
"metodo_pago": metodo,
"estado": random.choice(estados_pago),
"referencia": referencia,
"fecha_pago": fecha_pago,
"activo": True,
"fecha_creacion": fecha_creacion,
"fecha_actualizacion": fecha_actualizacion
}}
pagos.append(pago)
return pagos
pagos_data = generate_pagos()
if __name__ == '__main__':
data = generate_pagos()
print(f"💳 Generados {{len(data)}} pagos - VERSIÓN ARGENTINA 🇦🇷 CON PRECIOS REALISTAS ,999")
print(f"💰 RANGOS APLICADOS: Monto $15,999 - $299,999 ARS | Comisión 2-8%")
if data:
print("📋 Muestra de pagos:")
for i, pago in enumerate(data[:3]):
print(f" {{i+1}}. Pedido {{pago['pedido_id']}} - {{pago['estado'].upper()}}")
print(f" 💰 Monto: ${{pago['monto']:,}} ARS")
print(f" 📊 Comisión: ${{pago['comision']:,}} ARS ({{pago['comision']/pago['monto']*100:.1f}}%)")
print(f" 💵 TOTAL: ${{pago['total']:,}} ARS")
print(f" 🔗 Método: {{pago['metodo_pago'].replace('_', ' ').title()}}")
print(f" 📞 Referencia: {{pago['referencia']}}")
print(f" 📅 Fecha pago: {{pago['fecha_pago'].strftime('%d/%m/%Y %H:%M')}}")
print(f" 🟢 Activo: {{pago['activo']}}")
print()
"""
return mock_data_code
def generate_resenas_mock_data(module, **kwargs):
"""Generar datos mock para reseñas - VERSIÓN MEJORADA EN ESPAÑOL"""
mock_data_code = f"""from faker import Faker
from datetime import datetime
import random
fake = Faker('es_ES')
def generate_resenas():
reseñas = []
# Comentarios realistas en español para reseñas de productos
comentarios_positivos = [
"Excelente producto, superó mis expectativas. La calidad es impresionante y llegó en perfecto estado.",
"Muy contento con la compra, funciona perfectamente y es justo lo que necesitaba. Recomendado 100%.",
"Calidad premium a un precio increíble. El envío fue rápido y el producto mejor de lo esperado.",
"Increíble relación calidad-precio. Lo uso a diario y no he tenido ningún problema. Muy satisfecho.",
"Producto de alta gama, se nota la calidad en los materiales. Empresa seria y confiable.",
"Compré varios y todos funcionan perfectamente. Atención al cliente excelente y envío rápido.",
"Justo lo que buscaba, fácil de usar y muy eficiente. La entrega fue antes de lo esperado.",
"Muy buena calidad, diseño moderno y funcional. Definitivamente volveré a comprar en esta tienda."
]
comentarios_negativos = [
"El producto no cumple con lo anunciado, la calidad es inferior a lo esperado para el precio.",
"Llegó con daños, tuve que contactar servicio al cliente para el reemplazo. Mala experiencia.",
"Funciona pero no es tan eficiente como esperaba. Podría mejorar en algunos aspectos.",
"La entrega se retrasó 3 días sin explicación. El producto está bien pero el servicio regular.",
"No recomiendo, se rompió después de poco uso. Esperaba mayor durabilidad por el precio.",
"El tamaño es más pequeño de lo que aparece en las fotos. Deberían ser más específicos en la descripción."
]
comentarios_neutrales = [
"Producto aceptable, cumple su función básica. Nada extraordinario pero tampoco malo.",
"Buen producto por el precio, aunque hay aspectos que podrían mejorarse. En general está bien.",
"Cumple con lo esperado, calidad estándar. Buena opción si buscas algo funcional sin lujos.",
"El producto es correcto, llegó a tiempo. No tengo quejas pero tampoco destacaría algo especial."
]
for i in range({module['record_count']}):
calificacion = random.randint(1, 5)
# Seleccionar comentario según calificación
if calificacion >= 4:
comentario = random.choice(comentarios_positivos)
elif calificacion <= 2:
comentario = random.choice(comentarios_negativos)
else:
comentario = random.choice(comentarios_neutrales)
fecha_review = fake.date_time_this_year()
reseña = {{
"id": i + 1,
"usuario_id": random.randint(1, {module['record_count']}),
"producto_id": random.randint(1, {module['record_count']}),
"calificacion": calificacion,
"comentario": comentario,
"aprobado": random.choice([True, True, True, False]), # 75% aprobados
"fecha_review": fecha_review,
"fecha_creacion": fecha_review,
"fecha_actualizacion": fake.date_time_between(start_date=fecha_review, end_date='now')
}}
reseñas.append(reseña)
return reseñas
reseñas_data = generate_resenas()
"""
return mock_data_code
def generate_direcciones_mock_data(module, **kwargs):
"""Generar datos mock para direcciones - VERSIÓN ARGENTINA CON DATOS REALISTAS"""
mock_data_code = f"""from faker import Faker
from datetime import datetime
import random
fake = Faker('es_AR') # ✅ CORREGIDO: Cambiado a español Argentina
def generate_direcciones():
direcciones = []
tipos_direccion = ['casa', 'trabajo', 'otro']
# ✅ CORREGIDO: Ciudades argentinas realistas
ciudades_argentinas = [
'Buenos Aires', 'Córdoba', 'Rosario', 'Mendoza', 'Tucumán', 'La Plata', 'Mar del Plata',
'Salta', 'Santa Fe', 'San Juan', 'Resistencia', 'Neuquén', 'Corrientes', 'Formosa',
'San Luis', 'La Rioja', 'Catamarca', 'Río Gallegos', 'Ushuaia', 'Posadas', 'Paraná',
'San Miguel de Tucumán', 'Bahía Blanca', 'San Salvador de Jujuy', 'Villa María',
'Concordia', 'Comodoro Rivadavia', 'San Nicolás', 'San Rafael', 'Tandil'
]
# ✅ CORREGIDO: Barrios/comunas de Buenos Aires y otras ciudades
barrios_buenos_aires = [
'Palermo', 'Recoleta', 'Belgrano', 'Caballito', 'Almagro', 'Flores', 'Boedo', 'San Telmo',
'Puerto Madero', 'Retiro', 'Balvanera', 'Villa Crespo', 'Villa Urquiza', 'Nuñez', 'Colegiales',
'Villa Devoto', 'Villa Pueyrredón', 'Agronomía', 'Parque Chas', 'Versalles', 'Liniers', 'Mataderos'
]
for i in range({module['record_count']}):
fecha_creacion = fake.date_time_this_year()
# ✅ CORREGIDO: Generar direcciones argentinas realistas
ciudad = random.choice(ciudades_argentinas)
if ciudad == 'Buenos Aires':
barrio = random.choice(barrios_buenos_aires)
direccion_texto = f"{{fake.street_name()}} {{random.randint(100, 5000)}}, {{barrio}}"
else:
direccion_texto = f"{{fake.street_name()}} {{random.randint(100, 3000)}}"
# ✅ CORREGIDO: Códigos postales argentinos (formato: 4 dígitos)
codigo_postal = fake.bothify(text='####')
direccion = {{
"id": i + 1,
"usuario_id": random.randint(1, {module['record_count']}),
"tipo_direccion": random.choice(tipos_direccion),
"direccion": direccion_texto,
"ciudad": ciudad,
"codigo_postal": codigo_postal,
"pais": "Argentina", # ✅ CORREGIDO: País Argentina
"principal": random.choice([True, False, False]),
"fecha_creacion": fecha_creacion,
"fecha_actualizacion": fake.date_time_between(start_date=fecha_creacion, end_date='now')
}}
direcciones.append(direccion)
return direcciones
direcciones_data = generate_direcciones()
if __name__ == '__main__':
data = generate_direcciones()
print(f"🏠 Generadas {{len(data)}} direcciones - VERSIÓN ARGENTINA 🇦🇷")
print(f"📍 Ciudades argentinas realistas aplicadas")
if data:
print("📋 Muestra de direcciones:")
for i, direccion in enumerate(data[:3]):
print(f" {{i+1}}. Usuario {{direccion['usuario_id']}} - {{direccion['tipo_direccion'].upper()}}")
print(f" 🏠 Dirección: {{direccion['direccion']}}")
print(f" 🏙️ Ciudad: {{direccion['ciudad']}}")
print(f" 📮 Código Postal: {{direccion['codigo_postal']}}")
print(f" 🇦🇷 País: {{direccion['pais']}}")
print(f" 📅 Fecha creación: {{direccion['fecha_creacion'].strftime('%d/%m/%Y %H:%M')}}")
print(f" 🎯 Principal: {{'✅ Sí' if direccion['principal'] else '❌ No'}}")
print()
"""
return mock_data_code
def generate_cupones_mock_data(module, **kwargs):
"""Generar datos mock para cupones - VERSIÓN ARGENTINA CON VALORES REALISTAS"""
mock_data_code = f"""from faker import Faker
from datetime import datetime, timedelta
import random
fake = Faker('es_AR') # ✅ CORREGIDO: Cambiado a español Argentina
def generate_cupones():
cupones = []
tipos_descuento = ['porcentaje', 'monto_fijo']
# ✅ CORREGIDO: Descripciones realistas en español para cupones ARGENTINOS
descripciones_cupones = [
"Descuento especial para nuevos clientes",
"Promoción de lanzamiento de temporada",
"Cupón de bienvenida a nuestra tienda online",
"Descuento por compra mínima de $10.000",
"Oferta especial de fin de semana",
"Promoción Black Friday - Descuento exclusivo",
"Cupón de fidelidad para clientes recurrentes",
"Descuento por suscripción al newsletter",
"Oferta de temporada de verano",
"Promoción especial para compras mayores a $50.000",
"Descuento por primera compra en la app móvil",
"Cupón de aniversario de la tienda",
"Promoción de liquidación de inventario",
"Descuento para estudiantes verificados",
"Oferta especial de madrugador",
"Descuento por pago con transferencia",
"Cupón Cyber Monday - Oferta exclusiva",
"Promoción 3 cuotas sin interés",
"Descuento por compra mayor a $30.000",
"Cupón envío gratis en CABA"
]
for i in range({module['record_count']}):
fecha_inicio = fake.date_time_this_year()
fecha_fin = fecha_inicio + timedelta(days=random.randint(30, 90)) # 1-3 meses de validez
tipo = random.choice(tipos_descuento)
fecha_creacion = fecha_inicio - timedelta(days=random.randint(1, 7))
# ✅ CORREGIDO: Valores de descuento realistas para Argentina
if tipo == 'monto_fijo':
# Montos fijos en pesos argentinos realistas (terminados en 99 o 999)
montos_posibles = [1999, 2999, 4999, 7999, 9999, 14999, 19999, 24999, 29999, 49999]
valor_descuento = random.choice(montos_posibles)
else:
# Porcentajes de descuento realistas para Argentina
porcentajes_posibles = [5, 10, 15, 20, 25, 30, 40, 50]
valor_descuento = random.choice(porcentajes_posibles)
# ✅ CORREGIDO: Códigos de cupón más variados
formatos_codigo = [
fake.unique.bothify(text='DESC-??##'),
fake.unique.bothify(text='OFERTA-####'),
fake.unique.bothify(text='PROMO-???'),
fake.unique.bothify(text='CUPON##??'),
fake.unique.bothify(text='ARG-####')
]
codigo = random.choice(formatos_codigo)
cupon = {{
"id": i + 1,
"codigo": codigo,
"descripcion": random.choice(descripciones_cupones),
"tipo_descuento": tipo,
"valor_descuento": valor_descuento,
"fecha_inicio": fecha_inicio,
"fecha_fin": fecha_fin,
"usos_maximos": random.randint(100, 1000), # ✅ CORREGIDO: Más usos posibles
"usos_actuales": random.randint(0, min(200, 500)), # ✅ CORREGIDO: Más usos realistas
"activo": random.choice([True, True, True, False]), # 75% activos
"fecha_creacion": fecha_creacion,
"fecha_actualizacion": fake.date_time_between(start_date=fecha_creacion, end_date='now')
}}
cupones.append(cupon)
return cupones
cupones_data = generate_cupones()
if __name__ == '__main__':
data = generate_cupones()
print(f"🎫 Generados {{len(data)}} cupones - VERSIÓN ARGENTINA 🇦🇷")
print(f"💰 DESCUENTOS REALISTAS: Montos fijos $1,999 - $49,999 | Porcentajes 5% - 50%")
if data:
print("📋 Muestra de cupones:")
for i, cupon in enumerate(data[:3]):
tipo = "💰 $" if cupon['tipo_descuento'] == 'monto_fijo' else "📊 "
simbolo = "ARS" if cupon['tipo_descuento'] == 'monto_fijo' else "%"
print(f" {{i+1}}. Código: {{cupon['codigo']}}")
print(f" 📝 Descripción: {{cupon['descripcion']}}")
print(f" {{tipo}}Descuento: {{cupon['valor_descuento']:,}} {{simbolo}}")
print(f" 🎯 Tipo: {{cupon['tipo_descuento'].replace('_', ' ').title()}}")
print(f" 📅 Válido: {{cupon['fecha_inicio'].strftime('%d/%m/%Y')}} al {{cupon['fecha_fin'].strftime('%d/%m/%Y')}}")
print(f" 🔢 Usos: {{cupon['usos_actuales']}}/{{cupon['usos_maximos']}}")
print(f" 🟢 Activo: {{'✅ Sí' if cupon['activo'] else '❌ No'}}")
print()
"""
return mock_data_code
def generate_generic_mock_data(module, **kwargs):
"""Generar datos mock genéricos para cualquier módulo"""
mock_data_code = f"""from faker import Faker
from datetime import datetime
import random
fake = Faker('es_ES')
def generate_{module['name']}():
data = []
for i in range({module['record_count']}):
item = {{
"id": i + 1,
"nombre": fake.word().capitalize(),
"descripcion": fake.sentence(),
"activo": random.choice([True, False]),
"fecha_creacion": fake.date_time_this_year()
}}
data.append(item)
return data
{module['name']}_data = generate_{module['name']}()
"""
return mock_data_code
def generate_models_init(**kwargs):
"""Generar archivo __init__.py para modelos - CORREGIDO"""
models = []
imports_list = []
for module in kwargs['modules']:
model_name = module['name'].capitalize()
models.append(model_name)
imports_list.append(f"from .{module['name']} import {model_name}")
imports_str = "\n".join(imports_list)
models_str = ', '.join([f'"{model}"' for model in models])
return f'''# Importar todos los modelos aquí para que Alembic los detecte
from .base import Base
{imports_str}
__all__ = ["Base", {models_str}]
'''
def generate_rate_limit_utils(**kwargs):
"""Generar utilidades de rate limiting"""
return '''from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
'''
def generate_file_upload_utils(**kwargs):
"""Generar utilidades para manejo de archivos"""
return '''import os
import shutil
from fastapi import UploadFile, HTTPException
from typing import Optional
import uuid
# Directorios para archivos
UPLOAD_DIR = "uploads"
IMAGES_DIR = os.path.join(UPLOAD_DIR, "images")
DOCUMENTS_DIR = os.path.join(UPLOAD_DIR, "documents")
# Crear directorios si no existen
os.makedirs(IMAGES_DIR, exist_ok=True)
os.makedirs(DOCUMENTS_DIR, exist_ok=True)
ALLOWED_IMAGE_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"]
ALLOWED_DOCUMENT_TYPES = ["application/pdf", "text/plain", "application/msword"]
def save_upload_file(upload_file: UploadFile, file_type: str = "image") -> Optional[str]:
"""Guardar archivo subido y retornar la ruta relativa"""
try:
# Validar tipo de archivo
if file_type == "image" and upload_file.content_type not in ALLOWED_IMAGE_TYPES:
raise HTTPException(status_code=400, detail="Tipo de imagen no permitido")
elif file_type == "document" and upload_file.content_type not in ALLOWED_DOCUMENT_TYPES:
raise HTTPException(status_code=400, detail="Tipo de documento no permitido")
# Generar nombre único
file_extension = os.path.splitext(upload_file.filename)[1]
unique_filename = f"{uuid.uuid4()}{file_extension}"
# Determinar directorio de destino
if file_type == "image":
save_path = os.path.join(IMAGES_DIR, unique_filename)
else:
save_path = os.path.join(DOCUMENTS_DIR, unique_filename)
# Guardar archivo
with open(save_path, "wb") as buffer:
shutil.copyfileobj(upload_file.file, buffer)
return save_path
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error guardando archivo: {str(e)}")
finally:
upload_file.file.close()
'''
def generate_dockerfile(**kwargs):
"""Generar Dockerfile para la API"""
return f'''FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
'''
def generate_docker_compose(**kwargs):
"""Generar docker-compose.yml - VERSIÓN CORREGIDA CON SOPORTE MULTI-BD"""
database = kwargs['database']
project_name = kwargs['project_name']
# Configuración según el tipo de base de datos
if database == 'PostgreSQL':
db_config = f''' postgres:
image: postgres:15
environment:
POSTGRES_DB: {project_name}
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
- ./scripts/init_database.sql:/docker-entrypoint-initdb.d/init.sql # ✅ Script SQL
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
'''
app_environment = f' - DATABASE_URL=postgresql://postgres:password@postgres:5432/{project_name}'
depends_on = ' - postgres'
volumes_config = "volumes:\n postgres_data:"
elif database == 'MySQL':
db_config = f''' mysql:
image: mysql:8.0
environment:
MYSQL_DATABASE: {project_name}
MYSQL_ROOT_PASSWORD: password
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
- ./scripts/init_database.sql:/docker-entrypoint-initdb.d/init.sql # ✅ Script SQL
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
timeout: 5s
retries: 5
command: --default-authentication-plugin=mysql_native_password
'''
app_environment = f' - DATABASE_URL=mysql+mysqlconnector://root:password@mysql:3306/{project_name}'
depends_on = ' - mysql'
volumes_config = "volumes:\n mysql_data:"
else: # SQLite
db_config = ""
app_environment = f' - DATABASE_URL=sqlite:///./data/{project_name}.db' # ✅ En carpeta data
depends_on = ""
volumes_config = ""
# ✅ CORREGIDO: Separar el f-string problemático
docker_compose_content = f'''version: '3.8'
services:
app:
build: .
ports:
- "8000:8000"
environment:
{app_environment}
- PROJECT_NAME={project_name}
volumes:
- ./uploads:/app/uploads
- ./data:/app/data # ✅ Datos persistentes (SQLite + archivos)
- ./scripts:/app/scripts # ✅ Scripts disponibles
'''
# ✅ CORREGIDO: Agregar depends_on condicionalmente sin backslash en f-string
if depends_on:
docker_compose_content += f' depends_on:\n{depends_on}\n'
# ✅ CORREGIDO: Continuar con el resto del contenido
docker_compose_content += f''' healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
command: >
sh -c "python scripts/init_database.py &&
uvicorn main:app --host 0.0.0.0 --port 8000"
{db_config}
{volumes_config}
'''
return docker_compose_content
def generate_alembic_ini(**kwargs):
"""Generar configuración de Alembic"""
return '''[alembic]
script_location = alembic
prepend_sys_path = .
version_path_separator = os
sqlalchemy.url = sqlite:///./test.db
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
'''
def generate_alembic_env(**kwargs):
"""Generar archivo env.py para Alembic"""
return '''from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
from models.base import Base
target_metadata = Base.metadata
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode."""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
'''
def generate_alembic_script_mako(**kwargs):
"""Generar template para migraciones de Alembic"""
return '''"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
'''
# Funciones para otras tecnologías (simplificadas)
def generate_flask_structure(**kwargs):
return {"app.py": "# Flask API - En desarrollo..."}
def generate_django_structure(**kwargs):
return {"manage.py": "# Django API - En desarrollo..."}
def generate_springboot_structure(**kwargs):
return {"pom.xml": "# Spring Boot API - En desarrollo..."}
def generate_express_structure(**kwargs):
return {"app.js": "# Express.js API - En desarrollo..."}
# Funciones para tests y SDK (simplificadas)
def generate_tests(**kwargs):
return '''import pytest
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_root_endpoint():
response = client.get("/")
assert response.status_code == 200
data = response.json()
assert "message" in data
'''
def generate_test_config(**kwargs):
return '''import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database import Base
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
@pytest.fixture(scope="function")
def db():
Base.metadata.create_all(bind=engine)
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
Base.metadata.drop_all(bind=engine)
'''
def generate_auth_tests(**kwargs):
return '''import pytest
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_register_user():
user_data = {
"nombre": "Test",
"apellido": "User",
"email": "test@example.com",
"password": "testpassword123"
}
response = client.post("/api/v1/auth/register", json=user_data)
assert response.status_code in [201, 400]
'''
def generate_python_client(**kwargs):
return f'''import requests
import json
from typing import Optional, Dict, Any, List
class {kwargs['project_name'].replace('_', '').capitalize()}Client:
"""Cliente para la API {kwargs['project_name']}"""
def __init__(self, base_url: str = "http://localhost:8000", api_key: Optional[str] = None):
self.base_url = base_url
self.headers = {{"Content-Type": "application/json"}}
if api_key:
self.headers["Authorization"] = f"Bearer {{api_key}}"
def health_check(self) -> Dict:
"""Verificar el estado de la API"""
return self._request("GET", "/health")
def _request(self, method: str, endpoint: str, data: Optional[Dict] = None) -> Any:
url = f"{{self.base_url}}{{endpoint}}"
response = requests.request(method, url, json=data, headers=self.headers)
response.raise_for_status()
return response.json()
# Ejemplo de uso
if __name__ == "__main__":
client = {kwargs['project_name'].replace('_', '').capitalize()}Client()
print(client.health_check())
'''
def generate_js_client_package(**kwargs):
return '''{
"name": "''' + kwargs['project_name'] + '''-client",
"version": "1.0.0",
"description": "Cliente JavaScript para la API",
"main": "index.js",
"dependencies": {
"axios": "^1.6.0"
}
}
'''
def generate_js_client(**kwargs):
return f'''const axios = require('axios');
class {kwargs['project_name'].replace('_', '').capitalize()}Client {{
constructor(baseURL = 'http://localhost:8000', apiKey = null) {{
this.baseURL = baseURL;
this.headers = {{
'Content-Type': 'application/json'
}};
if (apiKey) {{
this.headers['Authorization'] = `Bearer ${{apiKey}}`;
}}
}}
async healthCheck() {{
const response = await axios.get(`${{this.baseURL}}/health`, {{ headers: this.headers }});
return response.data;
}}
}}
module.exports = {kwargs['project_name'].replace('_', '').capitalize()}Client;
'''
def generate_typescript_types(**kwargs):
return '''// Tipos TypeScript para la API
export interface HealthCheck {
status: string;
timestamp: string;
}
export interface ApiResponse<T> {
data: T;
message?: string;
}
'''
if __name__ == "__main__":
show()
# PARTE 8: README Completo y Documentación
def generate_complete_readme(**kwargs):
"""Generar README.md completo para desarrolladores que usarán la API"""
project_name = kwargs['project_name']
modules = kwargs['modules']
# Módulos disponibles sin rutas específicas
modules_simple_list = ""
for module in modules:
modules_simple_list += f"- **{module['name'].capitalize()}**: Gestión completa de {module['name']}\n"
# Generar sección de autenticación si está incluida
auth_section = ""
if kwargs.get('include_auth', True):
auth_section = """- `POST /api/v1/auth/register` - Registrar nuevo usuario
- `POST /api/v1/auth/login` - Iniciar sesión
- `POST /api/v1/auth/refresh` - Refrescar token
- `GET /api/v1/auth/me` - Obtener usuario actual"""
readme_content = f"""# {project_name.replace('_', ' ').title()} - API E-commerce
## 🚀 Descripción
API REST completa para sistema de E-commerce desarrollada con FastAPI por **DeMarco** usando **DataSuite Pro**.
Incluye todos los módulos esenciales para gestionar una tienda online.
## 📊 Características Principales
### 🏗️ Tecnologías
- **Framework**: FastAPI (Python 3.11+)
- **Base de datos**: {kwargs.get('database', 'SQLite (Desarrollo)')}
- **Autenticación**: {'JWT con refresh tokens' if kwargs.get('include_auth', True) else 'No incluida'}
- **Documentación**: {'Swagger UI y ReDoc automáticas' if kwargs.get('include_docs', True) else 'No incluida'}
### 📦 Módulos Disponibles
{modules_simple_list}
### 🛡️ Seguridad
- Autenticación JWT
- CORS configurado
- Validación de datos con Pydantic v2
- Rate limiting {'habilitado' if kwargs.get('rate_limiting', True) else 'deshabilitado'}
- Manejo seguro de contraseñas
## 🚀 Instalación y Configuración
### Requisitos Previos
Antes de comenzar, asegúrate de tener instalado:
- **Python 3.11 o superior** - [Descargar Python](https://www.python.org/downloads/)
- **pip** (incluido con Python)
- **Git** (opcional, para clonar repositorios)
### 📥 Paso 1: Obtener el Proyecto
Extrae el archivo `{project_name}.zip` en tu directorio de trabajo:
```bash
# Navegar al directorio extraído
cd {project_name}
```
### 🐍 Paso 2: Crear Entorno Virtual
Es **altamente recomendado** usar un entorno virtual para aislar las dependencias:
#### 🪟 En Windows:
```bash
# Crear entorno virtual
python -m venv .venv
# Activar entorno virtual
.venv\\Scripts\\activate
# Verificar que está activo (debería aparecer (.venv) en tu terminal)
```
#### 🐧 En Linux / 🍎 macOS:
```bash
# Crear entorno virtual
python3 -m venv .venv
# Activar entorno virtual
source .venv/bin/activate
# Verificar que está activo (debería aparecer (.venv) en tu terminal)
```
### 📦 Paso 3: Instalar Dependencias
Con el entorno virtual activado:
```bash
# Instalar todas las dependencias
pip install -r requirements.txt
# Verificar instalación
pip list
```
### ⚙️ Paso 4: Configurar Variables de Entorno (Opcional)
```bash
# Copiar archivo de ejemplo
cp .env.example .env
# Editar el archivo .env con tu editor preferido
# nano .env # Linux/macOS
# notepad .env # Windows
```
Variables importantes a configurar:
```env
PROJECT_NAME={project_name}
ENVIRONMENT=development
DATABASE_URL=sqlite:///./test.db
SECRET_KEY=cambia-esto-por-una-clave-segura
```
### ▶️ Paso 5: Ejecutar la API
```bash
# Ejecutar en modo desarrollo (con recarga automática)
uvicorn main:app --reload
# O especificar host y puerto
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
```
### ✅ Paso 6: Verificar que Funciona
Abre tu navegador y visita:
- **Documentación Swagger**: http://localhost:8000/docs
- **Documentación ReDoc**: http://localhost:8000/redoc
- **Health Check**: http://localhost:8000/health
## 🐳 Instalación con Docker (Alternativa)
Si prefieres usar Docker y tienes Docker Desktop instalado:
### Requisitos:
- **Docker Desktop** - [Descargar Docker](https://www.docker.com/products/docker-desktop)
- **Docker Compose** (incluido con Docker Desktop)
### Pasos:
```bash
# 1. Construir y ejecutar
docker-compose up -d
# 2. Ver logs en tiempo real
docker-compose logs -f
# 3. Verificar que está corriendo
docker-compose ps
# 4. Detener la API
docker-compose down
```
La API estará disponible en: http://localhost:8000
## 📚 Documentación de la API
Una vez que la API esté corriendo, accede a la documentación interactiva completa donde encontrarás **todos los endpoints disponibles** con ejemplos y opciones para probarlos:
- **Swagger UI**: http://localhost:8000/docs (Documentación interactiva)
- **ReDoc**: http://localhost:8000/redoc (Documentación alternativa)
### Endpoints Principales
#### Sistema
- `GET /` - Información general de la API
- `GET /health` - Estado del sistema
- `GET /info` - Información de configuración
#### Autenticación
{auth_section}
#### Módulos de Negocio
Cada módulo incluye operaciones CRUD completas (Crear, Leer, Actualizar, Eliminar) más búsqueda y filtros.
Consulta `/docs` para ver todos los endpoints detallados.
### 🔍 Funcionalidades Comunes
Todos los endpoints de listado soportan:
- **Paginación**: `?skip=0&limit=10`
- **Búsqueda**: `?search=texto`
- **Filtros personalizados** por módulo
## 🎯 Características Adicionales
- **Sistema de Imágenes**: Generación automática de imágenes para productos desde múltiples fuentes
- **Cache de Imágenes**: Almacenamiento persistente para evitar descargas repetidas
- **Validación de Datos**: Esquemas Pydantic para validación automática
- **Paginación**: En todos los endpoints de listado
- **Búsqueda**: Búsqueda de texto en todos los módulos
## 🧪 Testing
```bash
# Ejecutar todos los tests
pytest tests/
# Tests con cobertura
pytest --cov=app tests/
# Tests específicos con detalle
pytest tests/test_auth.py -v
```
## 🔧 Configuración Avanzada
### Base de Datos
Por defecto usa SQLite (archivo local). Para cambiar a PostgreSQL o MySQL:
```env
# PostgreSQL
DATABASE_URL=postgresql://usuario:password@localhost/nombre_db
# MySQL
DATABASE_URL=mysql://usuario:password@localhost/nombre_db
```
### Variables de Entorno Importantes
| Variable | Descripción | Valor por Defecto |
|----------|-------------|-------------------|
| `PROJECT_NAME` | Nombre del proyecto | `{project_name}` |
| `ENVIRONMENT` | Entorno (development/production) | `development` |
| `DATABASE_URL` | URL de conexión a BD | `sqlite:///./test.db` |
| `SECRET_KEY` | Clave para JWT | ⚠️ Cambiar en producción |
| `ACCESS_TOKEN_EXPIRE_MINUTES` | Expiración del token | `30` |
| `CORS_ORIGINS` | Orígenes permitidos | `*` |
## 🐛 Solución de Problemas Comunes
### Error: "Puerto 8000 ya está en uso"
```bash
# Windows
netstat -ano | findstr :8000
taskkill /PID <número_pid> /F
# Linux/macOS
lsof -i :8000
kill -9 <PID>
```
### Error: "ModuleNotFoundError"
```bash
# Asegúrate de que el entorno virtual está activado
# Reinstalar dependencias
pip install -r requirements.txt --force-reinstall
```
### Error: "No module named 'uvicorn'"
```bash
# Instalar uvicorn explícitamente
pip install uvicorn[standard]
```
### La API no inicia
```bash
# Verificar versión de Python
python --version # Debe ser 3.11+
# Verificar dependencias instaladas
pip list
# Ver logs detallados
uvicorn main:app --reload --log-level debug
```
## 📈 Despliegue en Producción
### Opción 1: Con Docker (Recomendado)
```bash
# Construir imagen
docker build -t {project_name}:latest .
# Ejecutar con variables de entorno
docker run -d -p 8000:8000 --env-file .env {project_name}:latest
```
### Opción 2: Servidor Tradicional
```bash
# Instalar dependencias
pip install -r requirements.txt
# Ejecutar con Gunicorn + Uvicorn
gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
```
## 🔄 Migraciones de Base de Datos (Opcional)
Si necesitas hacer cambios en la estructura de la BD:
```bash
# Generar migración
alembic revision --autogenerate -m "Descripción del cambio"
# Aplicar migraciones
alembic upgrade head
# Revertir última migración
alembic downgrade -1
```
## 📞 Soporte
Si encuentras problemas:
1. ✅ Revisa la documentación interactiva en `/docs`
2. 📋 Verifica los logs de la aplicación
3. 🔍 Consulta la sección de solución de problemas
4. 📧 Contacta al equipo de desarrollo
---
**Desarrollado por**: DeMarco | **Generado con**: DataSuite Pro
**Versión**: {kwargs.get('api_version', '1.0.0')} | **Última actualización**: {kwargs.get('last_update', '2025-10-15')}
⚠️ **Nota**: Asegúrate de cambiar `SECRET_KEY` antes de desplegar en producción.
"""
return readme_content
# Reemplazar la función generate_readme original
def generate_readme(**kwargs):
return generate_complete_readme(**kwargs) |