image_generator.py 146 KB
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
#!/usr/bin/env python3
"""
Gemini Image Generator App - PySide6 Version
Modern GUI application for generating images using Google's Gemini API
"""

from PySide6.QtWidgets import (
    QApplication, QMainWindow, QDialog, QWidget,
    QVBoxLayout, QHBoxLayout, QFormLayout, QGridLayout,
    QLabel, QLineEdit, QPushButton, QCheckBox, QTextEdit,
    QComboBox, QScrollArea, QGroupBox, QFileDialog, QMessageBox,
    QListWidget, QListWidgetItem, QTabWidget, QSplitter,
    QMenu, QProgressBar, QInputDialog
)
from PySide6.QtCore import Qt, QThread, Signal, QSize, QTimer, QMimeData
from PySide6.QtGui import QPixmap, QFont, QIcon, QDesktopServices, QAction, QImage, QDragEnterEvent, QDropEvent
from PySide6.QtCore import QUrl

import base64
import io
import json
import os
import sys
import shutil
import tempfile
import platform
import logging
import random
from pathlib import Path
from google import genai
from google.genai import types
import hashlib
import pymysql
import socket
import requests
from datetime import datetime
from dataclasses import dataclass, asdict
from typing import List, Optional, Dict, Any


def init_logging(log_level=logging.INFO):
    """
    初始化简单的日志系统
    创建logs目录并配置基本的文件日志记录
    """
    try:
        # 智能选择logs目录 - 与images目录使用相同的逻辑
        def get_logs_directory() -> Path:
            """获取可用的logs目录,支持开发环境和打包环境"""
            def get_candidate_logs_paths():
                """获取logs候选路径列表"""
                system = platform.system()
                candidates = []

                # 1. 优先尝试:当前目录的logs文件夹
                if getattr(sys, 'frozen', False):
                    # 打包环境:使用可执行文件所在目录
                    candidates.append(Path(sys.executable).parent / "logs")
                else:
                    # 开发环境:使用脚本所在目录
                    candidates.append(Path(__file__).parent / "logs")

                # 2. 备选方案:用户目录
                if system == "Darwin":  # macOS
                    candidates.append(Path.home() / "Library/Application Support/ZB100ImageGenerator/logs")
                    candidates.append(Path.home() / "Documents/ZB100ImageGenerator/logs")
                elif system == "Windows":
                    candidates.append(Path(os.environ.get("APPDATA", "")) / "ZB100ImageGenerator/logs")
                    candidates.append(Path.home() / "Documents/ZB100ImageGenerator/logs")
                else:  # Linux
                    candidates.append(Path.home() / ".config/zb100imagegenerator/logs")
                    candidates.append(Path.home() / "Documents/ZB100ImageGenerator/logs")

                return candidates

            def test_logs_write_access(path: Path) -> bool:
                """测试logs路径是否有写入权限"""
                try:
                    # 尝试创建目录
                    path.mkdir(parents=True, exist_ok=True)

                    # 测试写入权限
                    test_file = path / ".write_test"
                    test_file.write_text("test")
                    test_file.unlink()  # 删除测试文件
                    return True
                except Exception:
                    return False

            # 测试候选路径
            for candidate_path in get_candidate_logs_paths():
                if test_logs_write_access(candidate_path):
                    print(f"使用logs目录: {candidate_path}")
                    return candidate_path

            # 所有路径都失败,使用临时目录
            fallback_path = Path(tempfile.gettempdir()) / "ZB100ImageGenerator_logs"
            print(f"警告: 所有logs路径都不可用,使用临时目录: {fallback_path}")
            fallback_path.mkdir(exist_ok=True)
            return fallback_path

        logs_dir = get_logs_directory()

        # 尝试加载日志配置
        script_dir = Path(__file__).parent if not getattr(sys, 'frozen', False) else Path(sys.executable).parent
        config_path = script_dir / "config.json"
        logging_config = {
            "enabled": True,
            "level": "INFO",
            "log_to_console": True
        }

        if config_path.exists():
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    logging_config = config.get("logging_config", logging_config)
            except Exception as e:
                print(f"加载日志配置失败: {e}")

        # 如果日志被禁用,直接返回成功
        if not logging_config.get("enabled", True):
            print("日志系统已禁用")
            return True

        # 解析日志级别
        level_str = logging_config.get("level", "INFO").upper()
        log_level = getattr(logging, level_str, logging.INFO)

        # 确保logs目录存在
        logs_dir.mkdir(parents=True, exist_ok=True)

        # 配置日志文件路径
        log_file = logs_dir / "app.log"

        # 配置日志格式
        log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

        # 配置处理器
        handlers = [logging.FileHandler(log_file, encoding='utf-8')]
        if logging_config.get("log_to_console", True):
            handlers.append(logging.StreamHandler())

        # 配置日志系统
        logging.basicConfig(
            level=log_level,
            format=log_format,
            handlers=handlers,
            force=True  # 强制重新配置
        )

        logging.info(f"日志系统初始化完成 - 级别: {level_str}, 文件: {log_file}")
        return True

    except Exception as e:
        print(f"日志系统初始化失败: {e}")
        return False


def hash_password(password: str) -> str:
    """使用 SHA256 哈希密码"""
    return hashlib.sha256(password.encode('utf-8')).hexdigest()


class DatabaseManager:
    """数据库连接管理类"""

    def __init__(self, db_config):
        self.config = db_config
        self.logger = logging.getLogger(__name__)

    def authenticate(self, username, password):
        """
        验证用户凭证
        返回: (success: bool, message: str)
        """
        try:
            self.logger.info(f"开始用户认证: {username}")

            # 计算密码哈希
            password_hash = hash_password(password)

            # 连接数据库
            self.logger.debug(f"连接数据库: {self.config['host']}:{self.config.get('port', 3306)}")
            conn = pymysql.connect(
                host=self.config['host'],
                port=self.config.get('port', 3306),
                user=self.config['user'],
                password=self.config['password'],
                database=self.config['database'],
                connect_timeout=5
            )

            try:
                with conn.cursor() as cursor:
                    # 使用参数化查询防止 SQL 注入
                    sql = f"SELECT * FROM {self.config['table']} WHERE user_name=%s AND passwd=%s AND status='active'"
                    cursor.execute(sql, (username, password_hash))
                    result = cursor.fetchone()

                    if result:
                        self.logger.info(f"用户认证成功: {username}")
                        return True, "认证成功"
                    else:
                        self.logger.warning(f"用户认证失败: {username} - 用户名或密码错误")
                        return False, "用户名或密码错误"
            finally:
                conn.close()

        except pymysql.OperationalError as e:
            error_msg = "无法连接到服务器,请检查网络连接"
            self.logger.error(f"数据库连接失败: {e}")
            return False, error_msg
        except Exception as e:
            error_msg = f"认证失败: {str(e)}"
            self.logger.error(f"认证过程异常: {e}")
            return False, error_msg


@dataclass
class HistoryItem:
    """历史记录项数据结构"""
    timestamp: str
    prompt: str
    generated_image_path: Path
    reference_image_paths: List[Path]
    aspect_ratio: str
    image_size: str
    model: str
    created_at: datetime

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'timestamp': self.timestamp,
            'prompt': self.prompt,
            'generated_image_path': str(self.generated_image_path),
            'reference_image_paths': [str(p) for p in self.reference_image_paths],
            'aspect_ratio': self.aspect_ratio,
            'image_size': self.image_size,
            'model': self.model,
            'created_at': self.created_at.isoformat()
        }

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'HistoryItem':
        """从字典创建实例"""
        return cls(
            timestamp=data['timestamp'],
            prompt=data['prompt'],
            generated_image_path=Path(data['generated_image_path']),
            reference_image_paths=[Path(p) for p in data['reference_image_paths']],
            aspect_ratio=data['aspect_ratio'],
            image_size=data['image_size'],
            model=data['model'],
            created_at=datetime.fromisoformat(data['created_at'])
        )


def get_app_data_path() -> Path:
    """获取应用数据存储路径 - 智能选择,优先使用当前目录"""

    # 定义多个备选路径,按优先级排序
    def get_candidate_paths():
        """获取候选路径列表"""
        system = platform.system()
        candidates = []

        # 1. 优先尝试:当前目录的images文件夹
        if getattr(sys, 'frozen', False):
            # 打包环境:使用可执行文件所在目录
            candidates.append(Path(sys.executable).parent / "images")
        else:
            # 开发环境:使用脚本所在目录
            candidates.append(Path(__file__).parent / "images")

        # 2. 备选方案:用户目录
        if system == "Darwin":  # macOS
            candidates.append(Path.home() / "Library/Application Support/ZB100ImageGenerator/images")
            candidates.append(Path.home() / "Documents/ZB100ImageGenerator/images")
        elif system == "Windows":
            candidates.append(Path(os.environ.get("APPDATA", "")) / "ZB100ImageGenerator/images")
            candidates.append(Path.home() / "Documents/ZB100ImageGenerator/images")
        else:  # Linux
            candidates.append(Path.home() / ".config/zb100imagegenerator/images")
            candidates.append(Path.home() / "Documents/ZB100ImageGenerator/images")

        return candidates

    # 测试路径可用性
    def test_path_write_access(path: Path) -> bool:
        """测试路径是否有写入权限"""
        try:
            # 尝试创建目录
            path.mkdir(parents=True, exist_ok=True)

            # 测试写入权限
            test_file = path / ".write_test"
            test_file.write_text("test")
            test_file.unlink()  # 删除测试文件

            return True
        except (PermissionError, OSError) as e:
            print(f"路径 {path} 无写入权限: {e}")
            return False
        except Exception as e:
            print(f"路径 {path} 测试失败: {e}")
            return False

    # 按优先级测试每个候选路径
    candidates = get_candidate_paths()

    for path in candidates:
        if test_path_write_access(path):
            print(f"使用图片存储路径: {path}")
            return path

    # 如果所有路径都失败,使用最后的备选方案
    fallback_path = get_candidate_paths()[0]  # 使用第一个候选路径
    try:
        fallback_path.mkdir(parents=True, exist_ok=True)
        print(f"使用备选路径: {fallback_path}")
        return fallback_path
    except Exception as e:
        print(f"警告: 无法创建存储路径,将在当前目录操作: {e}")
        return Path.cwd() / "images"


def save_png_with_validation(file_path: str, image_bytes: bytes) -> bool:
    """使用Pillow验证并重写PNG文件,确保格式正确性

    Args:
        file_path: 保存文件路径
        image_bytes: 图像字节数据

    Returns:
        bool: True表示使用Pillow成功处理,False表示回退到原始方法
    """
    try:
        from PIL import Image
        import io

        # 使用Pillow打开图像数据
        with Image.open(io.BytesIO(image_bytes)) as img:
            # 检查是否实际是JPEG但伪装成PNG的情况
            file_format = img.format
            if file_format == 'JPEG':
                logger = logging.getLogger(__name__)
                logger.info(f"检测到伪装PNG的JPEG文件,实际格式: {file_format}")

            # 根据文件路径的扩展名决定保存格式
            save_format = 'PNG' if file_path.lower().endswith('.png') else 'JPEG'

            # 如果检测到的格式与目标格式不符,进行真正的转换
            if file_format and file_format != save_format:
                logger = logging.getLogger(__name__)
                logger.info(f"执行格式转换: {file_format} -> {save_format}")

                # 如果目标格式是PNG,确保使用RGBA模式以支持透明度
                if save_format == 'PNG':
                    if img.mode not in ['RGBA', 'RGB', 'L']:
                        if img.mode == 'P':
                            img = img.convert('RGBA')
                        elif img.mode == 'LA':
                            img = img.convert('RGBA')
                        else:
                            img = img.convert('RGBA')
                elif save_format == 'JPEG':
                    if img.mode in ['RGBA', 'P']:
                        img = img.convert('RGB')
                    elif img.mode == 'L':
                        img = img.convert('RGB')

            # 保存图片为指定格式
            img.save(file_path, save_format, optimize=True)

        logger = logging.getLogger(__name__)
        logger.info(f"图片格式验证成功: {file_path}, 保存格式: {save_format}")
        return True

    except ImportError:
        # Pillow不可用
        logger = logging.getLogger(__name__)
        logger.warning("Pillow库不可用,使用原始保存方法")
        return False

    except Exception as e:
        # Pillow处理失败,回退到原始方法
        logger = logging.getLogger(__name__)
        logger.warning(f"Pillow处理失败,使用原始保存方法: {e}")
        return False


class HistoryManager:
    """历史记录管理器"""

    def __init__(self, base_path: Optional[Path] = None):
        """初始化历史记录管理器

        Args:
            base_path: 历史记录存储基础路径,默认使用get_app_data_path()的结果
        """
        self.logger = logging.getLogger(__name__)
        self.base_path = base_path or get_app_data_path()
        self.base_path.mkdir(parents=True, exist_ok=True)
        self.history_index_file = self.base_path / "history_index.json"
        self.max_history_count = 100  # 默认最大历史记录数量

        self.logger.debug(f"历史记录管理器初始化完成,存储路径: {self.base_path}")

    def save_generation(self, image_bytes: bytes, prompt: str, reference_images: List[bytes],
                        aspect_ratio: str, image_size: str, model: str) -> str:
        """保存生成的图片到历史记录

        Args:
            image_bytes: 生成的图片字节数据
            prompt: 使用的提示词
            reference_images: 参考图片字节数据列表
            aspect_ratio: 宽高比
            image_size: 图片尺寸
            model: 使用的模型

        Returns:
            历史记录的时间戳
        """
        self.logger.info(f"开始保存历史记录 - 模型: {model}, 尺寸: {image_size}")

        # 生成时间戳目录
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        record_dir = self.base_path / timestamp
        record_dir.mkdir(exist_ok=True)

        # 保存生成的图片 - 使用PNG格式验证
        generated_image_path = record_dir / "generated.png"
        if not save_png_with_validation(str(generated_image_path), image_bytes):
            #
            # ¬,回退到原始方法
            with open(generated_image_path, 'wb') as f:
                f.write(image_bytes)
            self.logger.warning(f"使用原始保存方法: {generated_image_path}")

        # 保存参考图片 - 使用PNG格式验证
        reference_image_paths = []
        for i, ref_img_bytes in enumerate(reference_images):
            ref_path = record_dir / f"reference_{i + 1}.png"
            if not save_png_with_validation(str(ref_path), ref_img_bytes):
                # Pillow处理失败,回退到原始方法
                with open(ref_path, 'wb') as f:
                    f.write(ref_img_bytes)
                self.logger.warning(f"使用原始保存方法: {ref_path}")
            reference_image_paths.append(ref_path)

        # 保存元数据
        metadata = {
            'timestamp': timestamp,
            'prompt': prompt,
            'aspect_ratio': aspect_ratio,
            'image_size': image_size,
            'model': model,
            'created_at': datetime.now().isoformat()
        }

        metadata_path = record_dir / "metadata.json"
        with open(metadata_path, 'w', encoding='utf-8') as f:
            json.dump(metadata, f, ensure_ascii=False, indent=2)

        # 更新历史记录索引
        history_item = HistoryItem(
            timestamp=timestamp,
            prompt=prompt,
            generated_image_path=generated_image_path,
            reference_image_paths=reference_image_paths,
            aspect_ratio=aspect_ratio,
            image_size=image_size,
            model=model,
            created_at=datetime.now()
        )

        self._update_history_index(history_item)

        # 清理旧记录
        self._cleanup_old_records()

        return timestamp

    def load_history_index(self) -> List[HistoryItem]:
        """加载历史记录索引

        Returns:
            历史记录项列表,按时间戳倒序排列
        """
        if not self.history_index_file.exists():
            return []

        try:
            with open(self.history_index_file, 'r', encoding='utf-8') as f:
                data = json.load(f)

            history_items = [HistoryItem.from_dict(item) for item in data]
            # 按时间戳倒序排列
            history_items.sort(key=lambda x: x.timestamp, reverse=True)
            return history_items
        except Exception as e:
            print(f"加载历史记录索引失败: {e}")
            return []

    def get_history_item(self, timestamp: str) -> Optional[HistoryItem]:
        """获取指定时间戳的历史记录项

        Args:
            timestamp: 时间戳

        Returns:
            历史记录项,如果不存在则返回None
        """
        history_items = self.load_history_index()
        for item in history_items:
            if item.timestamp == timestamp:
                return item
        return None

    def delete_history_item(self, timestamp: str) -> bool:
        """删除指定的历史记录

        Args:
            timestamp: 要删除的时间戳

        Returns:
            删除是否成功
        """
        try:
            # 删除文件目录
            record_dir = self.base_path / timestamp
            if record_dir.exists():
                shutil.rmtree(record_dir)

            # 更新索引文件
            history_items = self.load_history_index()
            history_items = [item for item in history_items if item.timestamp != timestamp]
            self._save_history_index(history_items)

            return True
        except Exception as e:
            print(f"删除历史记录失败: {e}")
            return False

    def _update_history_index(self, history_item: HistoryItem):
        """更新历史记录索引

        Args:
            history_item: 要添加的历史记录项
        """
        history_items = self.load_history_index()

        # 检查是否已存在相同时间戳的记录,如果存在则替换
        history_items = [item for item in history_items if item.timestamp != history_item.timestamp]
        history_items.insert(0, history_item)  # 插入到开头

        self._save_history_index(history_items)

    def _save_history_index(self, history_items: List[HistoryItem]):
        """保存历史记录索引到文件

        Args:
            history_items: 历史记录项列表
        """
        try:
            data = [item.to_dict() for item in history_items]
            with open(self.history_index_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存历史记录索引失败: {e}")

    def _cleanup_old_records(self):
        """清理旧的历史记录,保持最大数量限制"""
        history_items = self.load_history_index()
        if len(history_items) > self.max_history_count:
            # 保留最新的记录
            items_to_keep = history_items[:self.max_history_count]
            items_to_remove = history_items[self.max_history_count:]

            # 删除多余记录的文件
            for item in items_to_remove:
                record_dir = self.base_path / item.timestamp
                if record_dir.exists():
                    try:
                        shutil.rmtree(record_dir)
                    except Exception as e:
                        print(f"删除旧历史记录失败 {item.timestamp}: {e}")

            # 更新索引文件
            self._save_history_index(items_to_keep)


class LoginDialog(QDialog):
    """Qt-based login dialog"""

    def __init__(self, db_config, last_user="", saved_password_hash=""):
        super().__init__()
        self.db_config = db_config
        self.last_user = last_user
        self.saved_password_hash = saved_password_hash

        self.success = False
        self.authenticated_user = ""
        self.password_changed = False
        self.current_password_hash = ""

        self.set_window_icon()
        self.setup_ui()
        self.apply_styles()

    def set_window_icon(self):
        """Set window icon based on platform"""
        try:
            icon_path = None

            if getattr(sys, 'frozen', False):
                # Running as compiled executable
                if platform.system() == 'Windows':
                    icon_path = os.path.join(sys._MEIPASS, 'zb100_windows.ico')
                elif platform.system() == 'Darwin':
                    icon_path = os.path.join(sys._MEIPASS, 'zb100_mac.icns')
            else:
                # Running as script
                if platform.system() == 'Windows':
                    icon_path = 'zb100_windows.ico'
                elif platform.system() == 'Darwin':
                    icon_path = 'zb100_mac.icns'

            if icon_path and os.path.exists(icon_path):
                app_icon = QIcon(icon_path)
                if not app_icon.isNull():
                    self.setWindowIcon(app_icon)
                else:
                    print(f"警告:图标文件无效: {icon_path}")
        except Exception as e:
            print(f"设置窗口图标失败: {e}")

    def setup_ui(self):
        """Build login dialog UI"""
        self.setWindowTitle("登录 - 珠宝壹佰图像生成器")
        self.setFixedSize(400, 400)

        # Main layout
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(40, 40, 40, 40)
        main_layout.setSpacing(20)

        # Title
        title_label = QLabel("登录")
        title_label.setObjectName("title")
        title_label.setAlignment(Qt.AlignCenter)
        main_layout.addWidget(title_label)

        main_layout.addSpacing(10)

        # Username field
        username_label = QLabel("用户名")
        username_label.setObjectName("field_label")

        main_layout.addWidget(username_label)

        self.username_entry = QLineEdit()
        self.username_entry.setText(self.last_user)
        self.username_entry.setFixedHeight(40)
        main_layout.addWidget(self.username_entry)

        main_layout.addSpacing(10)

        # Password field
        password_label = QLabel("密码")
        password_label.setObjectName("field_label")
        main_layout.addWidget(password_label)

        self.password_entry = QLineEdit()
        self.password_entry.setEchoMode(QLineEdit.Password)
        self.password_entry.setFixedHeight(40)

        # Handle saved password placeholder
        if self.saved_password_hash:
            self.password_entry.setPlaceholderText("••••••••")
            self.password_entry.setStyleSheet("QLineEdit { color: #999999; }")

        self.password_entry.textChanged.connect(self.on_password_change)
        self.password_entry.returnPressed.connect(self.on_login)

        main_layout.addWidget(self.password_entry)

        # Checkboxes
        checkbox_layout = QHBoxLayout()
        self.remember_user_check = QCheckBox("记住用户名")
        self.remember_user_check.setChecked(bool(self.last_user))
        checkbox_layout.addWidget(self.remember_user_check)

        self.remember_password_check = QCheckBox("记住密码")
        self.remember_password_check.setChecked(bool(self.saved_password_hash))
        checkbox_layout.addWidget(self.remember_password_check)

        checkbox_layout.addStretch()
        main_layout.addLayout(checkbox_layout)

        # Login button
        self.login_button = QPushButton("登录")
        self.login_button.setObjectName("login_button")
        self.login_button.setFixedHeight(40)
        self.login_button.clicked.connect(self.on_login)
        main_layout.addWidget(self.login_button)

        # Error label
        self.error_label = QLabel("")
        self.error_label.setObjectName("error_label")
        self.error_label.setAlignment(Qt.AlignCenter)
        self.error_label.setWordWrap(True)
        main_layout.addWidget(self.error_label)

        main_layout.addStretch()

        self.setLayout(main_layout)

        # Set focus
        if self.last_user:
            self.password_entry.setFocus()
        else:
            self.username_entry.setFocus()

    def apply_styles(self):
        """Apply QSS stylesheet"""
        self.setStyleSheet("""
            QDialog {
                background-color: #ffffff;
            }
            QLabel#title {
                font-size: 20pt;
                font-weight: bold;
                color: #1d1d1f;
            }
            QLabel#field_label {
                font-size: 10pt;
                color: #666666;
            }
            QLineEdit {
                padding: 8px;
                border: 1px solid #e5e5e5;
                border-radius: 4px;
                background-color: #fafafa;
                font-size: 11pt;
                color: #000000;
            }
            QLineEdit:focus {
                border: 1px solid #007AFF;
            }
            QPushButton#login_button {
                background-color: #007AFF;
                color: white;
                font-size: 10pt;
                font-weight: bold;
                padding: 10px 20px;
                border: none;
                border-radius: 6px;
            }
            QPushButton#login_button:hover {
                background-color: #0051D5;
            }
            QPushButton#login_button:pressed {
                background-color: #003D99;
            }
            QPushButton#login_button:disabled {
                background-color: #cccccc;
            }
            QCheckBox {
                font-size: 9pt;
                color: #1d1d1f;
            }
            QLabel#error_label {
                color: #ff3b30;
                font-size: 9pt;
            }
        """)

    def on_password_change(self):
        """Handle password field changes"""
        if not self.password_changed and self.saved_password_hash:
            # First change - clear placeholder style
            self.password_entry.setStyleSheet("")
            self.password_changed = True

    def on_login(self):
        """Handle login button click"""
        username = self.username_entry.text().strip()
        password_input = self.password_entry.text()

        # Validate input
        if not username:
            self.show_error("请输入用户名")
            return

        # Check if password is provided or saved password exists
        if not password_input and not self.saved_password_hash:
            self.show_error("请输入密码")
            return

        # Disable button during authentication
        self.login_button.setEnabled(False)
        self.error_label.setText("正在验证...")
        self.error_label.setStyleSheet("QLabel { color: #666666; }")

        # Determine which password to use
        if not self.password_changed and self.saved_password_hash:
            password_hash = self.saved_password_hash
        else:
            password_hash = hash_password(password_input)

        # Authenticate
        try:
            conn = pymysql.connect(
                host=self.db_config['host'],
                port=self.db_config.get('port', 3306),
                user=self.db_config['user'],
                password=self.db_config['password'],
                database=self.db_config['database'],
                connect_timeout=5
            )

            try:
                with conn.cursor() as cursor:
                    sql = f"SELECT * FROM {self.db_config['table']} WHERE user_name=%s AND passwd=%s AND status='active'"
                    cursor.execute(sql, (username, password_hash))
                    result = cursor.fetchone()

                    if result:
                        self.success = True
                        self.authenticated_user = username
                        self.current_password_hash = password_hash

                        # 记录用户登录日志
                        self.log_user_login(username)

                        self.accept()  # Close dialog with success
                    else:
                        self.show_error("用户名或密码错误,联系[柴进]重置密码")
                        self.password_entry.clear()
                        self.password_changed = False
                        self.login_button.setEnabled(True)
            finally:
                conn.close()

        except pymysql.OperationalError:
            self.show_error("无法连接到服务器,请检查网络连接")
            self.login_button.setEnabled(True)
        except Exception as e:
            self.show_error(f"认证失败: {str(e)}")
            self.login_button.setEnabled(True)

    def get_local_ip(self):
        """获取局域网IP地址"""
        try:
            # 尝试获取真实的局域网IP,而不是127.0.0.1
            hostname = socket.gethostname()
            local_ip = socket.gethostbyname(hostname)

            # 如果获取到的是127.0.0.1,尝试连接外部地址获取本地IP
            if local_ip.startswith('127.'):
                # 创建一个UDP socket连接到公共DNS服务器
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                try:
                    s.connect(('8.8.8.8', 80))
                    local_ip = s.getsockname()[0]
                except:
                    pass
                finally:
                    s.close()

            return local_ip
        except:
            return "127.0.0.1"

    def get_public_ip(self):
        """获取公网IP地址,失败返回None"""
        try:
            # 使用多个API作为备选
            apis = [
                'https://api.ipify.org',
                'https://ifconfig.me',
                'https://ipinfo.io/ip'
            ]

            for api in apis:
                try:
                    response = requests.get(api, timeout=3)
                    if response.status_code == 200:
                        public_ip = response.text.strip()
                        # 简单验证IP格式
                        if len(public_ip.split('.')) == 4 or ':' in public_ip:
                            return public_ip
                except:
                    continue
            return None
        except:
            return None

    def get_device_name(self):
        """获取设备名称"""
        try:
            return socket.gethostname()
        except:
            return "Unknown"

    def log_user_login(self, username):
        """静默记录用户登录日志,支持双IP"""
        try:
            local_ip = self.get_local_ip()
            public_ip = self.get_public_ip()
            device_name = self.get_device_name()

            conn = pymysql.connect(
                host=self.db_config['host'],
                port=self.db_config.get('port', 3306),
                user=self.db_config['user'],
                password=self.db_config['password'],
                database=self.db_config['database'],
                connect_timeout=5
            )

            try:
                with conn.cursor() as cursor:
                    sql = """INSERT INTO nano_banana_user_log
                             (user_name, local_ip, public_ip, device_name, login_time)
                             VALUES (%s, %s, %s, %s, %s)"""
                    cursor.execute(sql, (username, local_ip, public_ip, device_name, datetime.now()))
                    conn.commit()
            finally:
                conn.close()

        except Exception:
            # 静默处理,不影响登录流程
            pass

    def show_error(self, message):
        """显示错误弹窗和标签"""
        # 显示弹窗错误提示
        QMessageBox.critical(self, "登录错误", message)

        # 同时保留标签显示
        self.error_label.setText(message)
        self.error_label.setStyleSheet("QLabel { color: #ff3b30; }")

    def get_remember_user(self):
        """Get remember username checkbox state"""
        return self.remember_user_check.isChecked()

    def get_remember_password(self):
        """Get remember password checkbox state"""
        return self.remember_password_check.isChecked()

    def get_password_hash(self):
        """Get current password hash"""
        return getattr(self, 'current_password_hash', '')


class DragDropScrollArea(QScrollArea):
    """自定义支持拖拽的图像滚动区域"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAcceptDrops(True)
        self.parent_window = parent
        self.setStyleSheet("""
            QScrollArea {
                border: 2px dashed #e5e5e5;
                border-radius: 8px;
                background-color: #fafafa;
            }
            QScrollArea:hover {
                border-color: #007AFF;
                background-color: #f0f8ff;
            }
        """)

    def dragEnterEvent(self, event: QDragEnterEvent):
        """拖拽进入事件处理"""
        mime_data = event.mimeData()

        # 检查是否包含文件URL
        if mime_data.hasUrls():
            urls = mime_data.urls()
            for url in urls:
                if url.isLocalFile():
                    file_path = url.toLocalFile()
                    if self.is_valid_image_file(file_path):
                        event.acceptProposedAction()
                        self.setStyleSheet("""
                            QScrollArea {
                                border: 2px dashed #007AFF;
                                border-radius: 8px;
                                background-color: #e6f3ff;
                            }
                        """)
                        return

        # 检查剪贴板图像
        if mime_data.hasImage():
            event.acceptProposedAction()
            self.setStyleSheet("""
                QScrollArea {
                    border: 2px dashed #007AFF;
                    border-radius: 8px;
                    background-color: #e6f3ff;
                }
            """)
            return

        event.ignore()

    def dragLeaveEvent(self, event):
        """拖拽离开事件处理"""
        self.setStyleSheet("""
            QScrollArea {
                border: 2px dashed #e5e5e5;
                border-radius: 8px;
                background-color: #fafafa;
            }
            QScrollArea:hover {
                border-color: #007AFF;
                background-color: #f0f8ff;
            }
        """)

    def dropEvent(self, event: QDropEvent):
        """拖拽放置事件处理"""
        mime_data = event.mimeData()

        # 重置样式
        self.setStyleSheet("""
            QScrollArea {
                border: 2px dashed #e5e5e5;
                border-radius: 8px;
                background-color: #fafafa;
            }
            QScrollArea:hover {
                border-color: #007AFF;
                background-color: #f0f8ff;
            }
        """)

        # 处理文件拖拽
        if mime_data.hasUrls():
            urls = mime_data.urls()
            image_files = []

            for url in urls:
                if url.isLocalFile():
                    file_path = url.toLocalFile()
                    if self.is_valid_image_file(file_path):
                        image_files.append(file_path)

            if image_files:
                self.parent_window.add_image_files(image_files)
                event.acceptProposedAction()
                return

        # 处理剪贴板图像拖拽
        if mime_data.hasImage():
            image = mime_data.imageData()
            if image and not image.isNull():
                self.parent_window.add_clipboard_image(image)
                event.acceptProposedAction()
                return

        event.ignore()

    def is_valid_image_file(self, file_path: str) -> bool:
        """检查文件是否为有效的图像文件"""
        valid_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'}
        return Path(file_path).suffix.lower() in valid_extensions


class ImageGeneratorWindow(QMainWindow):
    """Qt-based main application window"""

    def __init__(self):
        super().__init__()
        self.logger = logging.getLogger(__name__)
        self.logger.info("应用程序启动")

        self.api_key = ""
        self.uploaded_images = []  # List of file paths
        self.generated_image_data = None
        self.generated_image_bytes = None
        self.saved_prompts = []
        self.db_config = None
        self.last_user = ""
        self.saved_password_hash = ""
        self.authenticated_user = ""  # 当前登录用户名

        self.load_config()
        self.set_window_icon()

        # Initialize history manager
        self.history_manager = HistoryManager()

        # Initialize task queue manager
        from task_queue import TaskQueueManager
        self.task_manager = TaskQueueManager()

        self.setup_ui()
        self.apply_styles()

        self.logger.info("应用程序初始化完成")

    def set_window_icon(self):
        """Set window icon based on platform"""
        try:
            icon_path = None

            if getattr(sys, 'frozen', False):
                # Running as compiled executable
                if platform.system() == 'Windows':
                    icon_path = os.path.join(sys._MEIPASS, 'zb100_windows.ico')
                elif platform.system() == 'Darwin':
                    icon_path = os.path.join(sys._MEIPASS, 'zb100_mac.icns')
            else:
                # Running as script
                if platform.system() == 'Windows':
                    icon_path = 'zb100_windows.ico'
                elif platform.system() == 'Darwin':
                    icon_path = 'zb100_mac.icns'

            if icon_path and os.path.exists(icon_path):
                app_icon = QIcon(icon_path)
                if not app_icon.isNull():
                    self.setWindowIcon(app_icon)
                    self.logger.debug(f"主窗口图标设置成功: {icon_path}")
                else:
                    self.logger.warning(f"图标文件无效: {icon_path}")
            else:
                self.logger.debug(f"图标文件不存在,跳过设置: {icon_path}")

        except Exception as e:
            self.logger.error(f"设置窗口图标失败: {e}")

    def get_config_dir(self):
        """Get the appropriate directory for config files based on platform and mode"""
        if getattr(sys, 'frozen', False):
            system = platform.system()
            if system == 'Darwin':
                config_dir = Path.home() / 'Library' / 'Application Support' / 'ZB100ImageGenerator'
            elif system == 'Windows':
                config_dir = Path(os.getenv('APPDATA', Path.home())) / 'ZB100ImageGenerator'
            else:
                config_dir = Path.home() / '.config' / 'zb100imagegenerator'
        else:
            config_dir = Path('.')

        config_dir.mkdir(parents=True, exist_ok=True)
        return config_dir

    def get_config_path(self):
        """Get the full path to config.json"""
        return self.get_config_dir() / 'config.json'

    def load_config(self):
        """Load API key, saved prompts, and db config from config file"""
        config_path = self.get_config_path()
        self.logger.debug(f"加载配置文件: {config_path}")

        # Try to load from user directory first
        config_loaded = False
        if config_path.exists():
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.api_key = config.get("api_key", "")
                    self.saved_prompts = config.get("saved_prompts", [])
                    self.db_config = config.get("db_config")
                    self.last_user = config.get("last_user", "")
                    self.saved_password_hash = config.get("saved_password_hash", "")

                    # Load history configuration
                    history_config = config.get("history_config", {})
                    if hasattr(self, 'history_manager'):
                        self.history_manager.max_history_count = history_config.get("max_history_count", 100)

                    self.logger.info("配置文件加载成功")
                    config_loaded = True
            except Exception as e:
                self.logger.error(f"配置文件加载失败: {e}")
                print(f"Failed to load config from {config_path}: {e}")

        # If user config doesn't exist or failed to load, try bundled config
        if not config_loaded and getattr(sys, 'frozen', False):
            bundled_config_paths = [
                Path(sys.executable).parent / 'config.json',  # Same directory as exe
                Path(sys._MEIPASS) / 'config.json',  # PyInstaller temp directory
            ]

            for bundled_path in bundled_config_paths:
                if bundled_path.exists():
                    try:
                        with open(bundled_path, 'r', encoding='utf-8') as f:
                            config = json.load(f)
                            self.api_key = config.get("api_key", "")
                            self.saved_prompts = config.get("saved_prompts", [])
                            self.db_config = config.get("db_config")
                            self.last_user = config.get("last_user", "")
                            self.saved_password_hash = config.get("saved_password_hash", "")

                            # Load history configuration
                            history_config = config.get("history_config", {})
                            if hasattr(self, 'history_manager'):
                                self.history_manager.max_history_count = history_config.get("max_history_count", 100)

                            self.logger.info(f"从打包配置文件加载成功: {bundled_path}")
                            config_loaded = True
                            break
                    except Exception as e:
                        self.logger.error(f"打包配置文件加载失败 {bundled_path}: {e}")
                        continue

        # If still no config loaded, try current directory
        if not config_loaded:
            current_config = Path('.') / 'config.json'
            if current_config.exists():
                try:
                    with open(current_config, 'r', encoding='utf-8') as f:
                        config = json.load(f)
                        self.api_key = config.get("api_key", "")
                        self.saved_prompts = config.get("saved_prompts", [])
                        self.db_config = config.get("db_config")
                        self.last_user = config.get("last_user", "")
                        self.saved_password_hash = config.get("saved_password_hash", "")

                        # Load history configuration
                        history_config = config.get("history_config", {})
                        if hasattr(self, 'history_manager'):
                            self.history_manager.max_history_count = history_config.get("max_history_count", 100)

                        self.logger.info(f"从当前目录配置文件加载成功: {current_config}")
                        config_loaded = True
                except Exception as e:
                    self.logger.error(f"当前目录配置文件加载失败: {e}")

        if not config_loaded:
            self.logger.warning("未找到任何有效的配置文件")
            print("警告:未找到配置文件,某些功能可能无法正常工作")

        # 即使没有db_config也继续运行,让用户在UI中配置
        if not self.db_config:
            self.logger.info("未找到数据库配置,将使用UI配置模式")
            self.db_config = None

        if not self.api_key and getattr(sys, 'frozen', False):
            try:
                bundle_dir = Path(sys._MEIPASS)
                bundled_config = bundle_dir / 'config.json'
                if bundled_config.exists():
                    with open(bundled_config, 'r', encoding='utf-8') as f:
                        config = json.load(f)
                        self.api_key = config.get("api_key", "")
                        self.db_config = config.get("db_config")
                    self.save_config()
            except Exception as e:
                print(f"Failed to load bundled config: {e}")

        if not self.api_key:
            QMessageBox.warning(self, "警告",
                                f"未找到API密钥\n配置文件位置: {config_path}\n\n请在应用中输入API密钥或手动编辑配置文件")

    def save_config(self, last_user=None):
        """Save configuration to file"""
        config_path = self.get_config_path()

        try:
            config = {
                "api_key": self.api_key,
                "saved_prompts": self.saved_prompts
            }

            if self.db_config:
                config["db_config"] = self.db_config

            if last_user is not None:
                config["last_user"] = last_user
            elif hasattr(self, 'last_user'):
                config["last_user"] = self.last_user
            else:
                config["last_user"] = ""

            if hasattr(self, 'saved_password_hash'):
                config["saved_password_hash"] = self.saved_password_hash
            else:
                config["saved_password_hash"] = ""

            # Save history configuration
            if hasattr(self, 'history_manager'):
                config["history_config"] = {
                    "max_history_count": self.history_manager.max_history_count
                }

            config_path.parent.mkdir(parents=True, exist_ok=True)

            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=2, ensure_ascii=False)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存配置失败: {str(e)}\n路径: {config_path}")

    def setup_ui(self):
        """Setup the user interface"""
        self.setWindowTitle("珠宝壹佰图像生成器")
        self.setGeometry(100, 100, 1200, 850)
        self.setMinimumSize(1000, 700)

        # Central widget
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        main_layout = QHBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)

        # Left side: Main content
        content_layout = QVBoxLayout()
        content_layout.setSpacing(10)

        # Create tab widget
        self.tab_widget = QTabWidget()

        # Create generation tab
        generation_tab = self.setup_generation_tab()
        self.tab_widget.addTab(generation_tab, "图片生成")

        # Create style designer tab
        try:
            jewelry_lib_manager = JewelryLibraryManager(self.get_config_dir())
            style_designer_tab = StyleDesignerTab(jewelry_lib_manager, parent=self)
            self.tab_widget.addTab(style_designer_tab, "款式设计")
            self.logger.info("款式设计 Tab 创建成功")
        except Exception as e:
            self.logger.error(f"款式设计 Tab 创建失败: {e}")
            # 即使失败也继续运行,不阻止应用启动

        # Create history tab
        history_tab = self.setup_history_tab()
        self.tab_widget.addTab(history_tab, "历史记录")

        content_layout.addWidget(self.tab_widget)

        # Create content widget with vertical layout
        content_widget = QWidget()
        content_widget.setLayout(content_layout)

        # Add content to left side
        main_layout.addWidget(content_widget, 7)  # 70% width

        # Right side: Task queue sidebar
        from task_queue import TaskQueueWidget
        self.task_queue_widget = TaskQueueWidget(self.task_manager)
        main_layout.addWidget(self.task_queue_widget, 3)  # 30% width

        central_widget.setLayout(main_layout)

        self.check_favorite_status()

    def setup_generation_tab(self):
        """Setup the image generation tab"""
        tab_widget = QWidget()
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(15)

        # Reference images section
        ref_group = QGroupBox("参考图片")
        ref_layout = QVBoxLayout()
        ref_layout.setContentsMargins(5, 2, 5, 5)  # 减少上边距

        # Upload button and count
        upload_header = QHBoxLayout()
        upload_btn = QPushButton("添加图片")
        upload_btn.clicked.connect(self.upload_images)
        upload_header.addWidget(upload_btn)

        # Paste button
        paste_btn = QPushButton("📋 粘贴图片")
        paste_btn.clicked.connect(self.paste_from_clipboard)
        paste_btn.setStyleSheet("""
            QPushButton {
                background-color: #f0f0f0;
                border: 1px solid #d0d0d0;
                padding: 8px 16px;
                border-radius: 4px;
                font-size: 12px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #e8e8e8;
                border-color: #007AFF;
            }
            QPushButton:pressed {
                background-color: #d0d0d0;
            }
        """)
        upload_header.addWidget(paste_btn)

        self.image_count_label = QLabel("已选择 0 张")
        upload_header.addWidget(self.image_count_label)

        # Drag and drop hint - 紧凑显示在右侧
        hint_label = QLabel("💡 拖拽或粘贴图片到下方区域")
        hint_label.setStyleSheet("QLabel { color: #666666; font-size: 11px; margin-left: 10px; }")
        upload_header.addWidget(hint_label)

        upload_header.addStretch()
        ref_layout.addLayout(upload_header)

        # Image preview scroll area with drag-and-drop support
        self.img_scroll = DragDropScrollArea(self)
        self.img_scroll.setWidgetResizable(True)
        self.img_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.img_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.img_scroll.setFixedHeight(220)

        self.img_container = QWidget()
        self.img_layout = QHBoxLayout()
        self.img_layout.addStretch()
        self.img_container.setLayout(self.img_layout)
        self.img_scroll.setWidget(self.img_container)

        ref_layout.addWidget(self.img_scroll)
        ref_group.setLayout(ref_layout)
        main_layout.addWidget(ref_group)

        # Content row: Prompt (left) + Settings (right)
        content_row = QHBoxLayout()

        # Prompt section
        prompt_group = QGroupBox("提示词")
        prompt_layout = QVBoxLayout()

        # Prompt toolbar
        prompt_toolbar = QHBoxLayout()
        self.save_prompt_btn = QPushButton("⭐ 收藏")
        self.save_prompt_btn.clicked.connect(self.toggle_favorite)
        prompt_toolbar.addWidget(self.save_prompt_btn)

        prompt_toolbar.addWidget(QLabel("快速选择:"))
        self.saved_prompts_combo = QComboBox()
        prompt_toolbar.addWidget(self.saved_prompts_combo)

        delete_prompt_btn = QPushButton("删除")
        delete_prompt_btn.clicked.connect(self.delete_saved_prompt)
        prompt_toolbar.addWidget(delete_prompt_btn)
        prompt_toolbar.addStretch()

        prompt_layout.addLayout(prompt_toolbar)

        # Prompt text area
        self.prompt_text = QTextEdit()
        self.prompt_text.setStyleSheet("font-size: 16px;")
        self.prompt_text.setPlainText("一幅美丽的风景画,有山有湖,日落时分")
        self.prompt_text.textChanged.connect(self.check_favorite_status)
        prompt_layout.addWidget(self.prompt_text)

        # Update list first (before connecting signal to avoid triggering it during init)
        self.update_saved_prompts_list()

        prompt_group.setLayout(prompt_layout)
        content_row.addWidget(prompt_group, 2)

        # Settings section
        settings_group = QGroupBox("生成设置")
        settings_layout = QVBoxLayout()

        settings_layout.addWidget(QLabel("宽高比"))
        self.aspect_ratio = QComboBox()
        self.aspect_ratio.addItems(["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"])
        settings_layout.addWidget(self.aspect_ratio)

        settings_layout.addSpacing(10)

        settings_layout.addWidget(QLabel("图片尺寸"))
        self.image_size = QComboBox()
        self.image_size.addItems(["1K", "2K", "4K"])
        self.image_size.setCurrentIndex(1)  # Default to 2K
        settings_layout.addWidget(self.image_size)

        settings_layout.addSpacing(10)

        settings_layout.addStretch()
        settings_group.setLayout(settings_layout)
        content_row.addWidget(settings_group, 1)

        main_layout.addLayout(content_row)

        # Action buttons
        action_layout = QHBoxLayout()
        self.generate_btn = QPushButton("生成图片")
        self.generate_btn.clicked.connect(self.generate_image_async)
        action_layout.addWidget(self.generate_btn)

        self.download_btn = QPushButton("下载图片")
        self.download_btn.clicked.connect(self.download_image)
        self.download_btn.setEnabled(False)
        action_layout.addWidget(self.download_btn)

        self.status_label = QLabel("● 就绪")
        action_layout.addWidget(self.status_label)
        action_layout.addStretch()

        main_layout.addLayout(action_layout)

        # Preview section
        preview_group = QGroupBox("预览")
        preview_layout = QVBoxLayout()

        self.preview_label = QLabel("生成的图片将在这里显示\n双击用系统查看器打开")
        self.preview_label.setAlignment(Qt.AlignCenter)
        self.preview_label.setMinimumHeight(300)
        self.preview_label.setStyleSheet("QLabel { color: #999999; font-size: 10pt; }")
        self.preview_label.mouseDoubleClickEvent = self.open_fullsize_view

        preview_layout.addWidget(self.preview_label)
        preview_group.setLayout(preview_layout)
        main_layout.addWidget(preview_group, 1)

        tab_widget.setLayout(main_layout)
        return tab_widget

    def setup_history_tab(self):
        """Setup the history tab"""
        tab_widget = QWidget()
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)

        # History toolbar
        toolbar_layout = QHBoxLayout()

        refresh_btn = QPushButton("🔄 刷新")
        refresh_btn.clicked.connect(self.refresh_history)
        toolbar_layout.addWidget(refresh_btn)

        clear_btn = QPushButton("🗑️ 清空历史")
        clear_btn.clicked.connect(self.clear_history)
        toolbar_layout.addWidget(clear_btn)

        toolbar_layout.addStretch()

        self.history_count_label = QLabel("共 0 条历史记录")
        toolbar_layout.addWidget(self.history_count_label)

        main_layout.addLayout(toolbar_layout)

        # Create splitter for list and details
        from PySide6.QtWidgets import QSplitter
        splitter = QSplitter(Qt.Vertical)

        # History list (upper part)
        self.history_list = QListWidget()
        self.history_list.setIconSize(QSize(120, 120))
        self.history_list.setResizeMode(QListWidget.Adjust)
        self.history_list.setViewMode(QListWidget.IconMode)
        self.history_list.setSpacing(10)
        self.history_list.setMinimumHeight(200)  # Give more space for history list
        self.history_list.itemClicked.connect(self.load_history_item)
        self.history_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.history_list.customContextMenuRequested.connect(self.show_history_context_menu)

        splitter.addWidget(self.history_list)

        # Details panel (lower part)
        self.details_panel = self.create_details_panel()
        splitter.addWidget(self.details_panel)

        # Set splitter proportions (40% for list, 60% for details)
        splitter.setSizes([300, 450])
        splitter.setChildrenCollapsible(False)  # Prevent panels from being collapsed completely

        main_layout.addWidget(splitter)
        tab_widget.setLayout(main_layout)

        # Load initial history
        self.refresh_history()

        return tab_widget

    def create_details_panel(self):
        """Create the details panel for displaying selected history item"""
        panel = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(10)

        # Prompt section
        prompt_group = QGroupBox("提示词")
        prompt_layout = QVBoxLayout()

        # Prompt text area with copy button
        prompt_header = QHBoxLayout()
        prompt_header.addWidget(QLabel("完整提示词:"))
        self.copy_prompt_btn = QPushButton("📋 复制")
        self.copy_prompt_btn.clicked.connect(self.copy_prompt_text)
        self.copy_prompt_btn.setEnabled(False)
        prompt_header.addWidget(self.copy_prompt_btn)
        prompt_header.addStretch()

        prompt_layout.addLayout(prompt_header)

        self.prompt_display = QLabel("请选择一个历史记录查看详情")
        self.prompt_display.setWordWrap(True)
        self.prompt_display.setStyleSheet(
            "QLabel { padding: 8px; background-color: #f9f9f9; border: 1px solid #ddd; border-radius: 4px; }")
        prompt_layout.addWidget(self.prompt_display)

        prompt_group.setLayout(prompt_layout)
        layout.addWidget(prompt_group)

        # Parameters section - compressed to one line
        params_group = QGroupBox("生成参数")
        params_layout = QHBoxLayout()

        params_layout.addWidget(QLabel("生成时间:"))
        self.time_label = QLabel("-")
        params_layout.addWidget(self.time_label)

        params_layout.addWidget(QLabel("  |  宽高比:"))
        self.aspect_ratio_label = QLabel("-")
        params_layout.addWidget(self.aspect_ratio_label)

        params_layout.addWidget(QLabel("  |  图片尺寸:"))
        self.image_size_label = QLabel("-")
        params_layout.addWidget(self.image_size_label)

        params_layout.addStretch()
        params_group.setLayout(params_layout)
        layout.addWidget(params_group)

        # Images section - left (reference) and right (generated) layout
        images_group = QGroupBox("图片预览")
        images_layout = QHBoxLayout()

        # Left side - Reference images
        ref_group = QGroupBox("参考图片")
        ref_layout = QVBoxLayout()

        self.ref_images_scroll = QScrollArea()
        self.ref_images_scroll.setWidgetResizable(True)
        self.ref_images_scroll.setMinimumHeight(200)
        self.ref_images_widget = QWidget()
        self.ref_images_layout = QVBoxLayout()  # Changed to vertical for better layout
        self.ref_images_layout.setAlignment(Qt.AlignCenter)
        self.ref_images_widget.setLayout(self.ref_images_layout)
        self.ref_images_scroll.setWidget(self.ref_images_widget)

        ref_layout.addWidget(self.ref_images_scroll)
        ref_group.setLayout(ref_layout)
        images_layout.addWidget(ref_group, 1)  # 1:1 stretch

        # Right side - Generated image (larger)
        gen_group = QGroupBox("生成图片")
        gen_layout = QVBoxLayout()
        gen_layout.setAlignment(Qt.AlignCenter)

        self.generated_image_label = QLabel("请选择一个历史记录查看生成图片")
        self.generated_image_label.setAlignment(Qt.AlignCenter)
        self.generated_image_label.setMinimumSize(200, 200)  # Larger size for generated image
        self.generated_image_label.setMaximumSize(300, 300)
        self.generated_image_label.setStyleSheet(
            "QLabel { background-color: #f5f5f5; border: 1px solid #ddd; color: #999; }")
        self.generated_image_label.mouseDoubleClickEvent = self.open_generated_image_from_history

        gen_layout.addWidget(self.generated_image_label)
        gen_group.setLayout(gen_layout)
        images_layout.addWidget(gen_group, 1)  # 1:1 stretch

        images_group.setLayout(images_layout)
        layout.addWidget(images_group)

        layout.addStretch()
        panel.setLayout(layout)
        return panel

    def apply_styles(self):
        """Apply QSS stylesheet"""
        """Apply QSS stylesheet - 最小化自定义样式"""
        self.setStyleSheet("""
                QMainWindow {
                    background-color: #ffffff;
                }
                QGroupBox {
                    font-weight: bold;
                    font-size: 10pt;
                    border: 1px solid #e5e5e5;
                    border-radius: 6px;
                    margin-top: 2px;
                    padding-top: 2px;
                }
                QGroupBox::title {
                    subcontrol-origin: margin;
                    left: 10px;
                    padding: 0 5px;
                }
                QPushButton {
                    padding: 6px 12px;
                    font-size: 9pt;
                    border: 1px solid #cccccc;
                    border-radius: 4px;
                }
                QPushButton:disabled {
                    color: #999999;
                }
                QComboBox {
                    padding: 5px;
                    min-width: 100px;
                }
                QTextEdit {
                    border: 1px solid #e5e5e5;
                    border-radius: 4px;
                    font-size: 10pt;
                }
                QScrollArea {
                    border: none;
                    background-color: #f6f6f6;
                }
                /* 只保留必要的边框和背景,不设置颜色 */
                QLineEdit, QComboBox, QTextEdit {
                    border: 1px solid #cccccc;
                    border-radius: 4px;
                }
                QLineEdit:focus, QComboBox:focus, QTextEdit:focus {
                    border: 1px solid #007AFF;  /* 保持焦点状态 */
                }
            """)

        # Connect signals after all widgets are created
        self.saved_prompts_combo.currentIndexChanged.connect(self.load_saved_prompt)

    def upload_images(self):
        """Upload reference images"""
        self.logger.info("开始上传参考图片")
        files, _ = QFileDialog.getOpenFileNames(
            self,
            "选择参考图片",
            "",
            "图片文件 (*.png *.jpg *.jpeg *.gif *.bmp);;所有文件 (*.*)"
        )

        if files:
            self.logger.info(f"选择了 {len(files)} 个文件: {files}")
            valid_count = 0
            for file_path in files:
                try:
                    if self.validate_image_file(file_path):
                        self.uploaded_images.append(file_path)
                        valid_count += 1
                        self.logger.info(f"成功添加图片: {file_path}")
                    else:
                        self.logger.warning(f"图片验证失败: {file_path}")
                except Exception as e:
                    self.logger.error(f"加载图片失败: {file_path}, 错误: {str(e)}", exc_info=True)
                    QMessageBox.critical(self, "错误", f"无法加载图片: {file_path}\n{str(e)}")

            self.update_image_preview()
            self.image_count_label.setText(f"已选择 {len(self.uploaded_images)} 张")
            self.status_label.setText(f"● 已添加 {valid_count} 张参考图片")
            self.status_label.setStyleSheet("QLabel { color: #34C759; }")
            self.logger.info(f"图片上传完成,有效图片: {valid_count} 张")
        else:
            self.logger.info("用户取消了图片选择")

    def add_image_files(self, file_paths):
        """添加图像文件到上传列表(用于拖拽功能)"""
        self.logger.info(f"开始处理拖拽文件,共 {len(file_paths) if file_paths else 0} 个")
        if not file_paths:
            self.logger.warning("拖拽文件列表为空")
            return

        added_count = 0
        for file_path in file_paths:
            self.logger.info(f"处理拖拽文件: {file_path}")
            try:
                if self.validate_image_file(file_path):
                    self.uploaded_images.append(file_path)
                    added_count += 1
                    self.logger.info(f"成功添加拖拽图片: {file_path}")
                else:
                    self.logger.warning(f"无效的图像文件: {file_path}")
            except Exception as e:
                self.logger.error(f"添加图片失败: {file_path}, 错误: {str(e)}", exc_info=True)

        if added_count > 0:
            self.logger.info(f"拖拽添加成功,共 {added_count} 张图片")
            self.update_image_preview()
            self.image_count_label.setText(f"已选择 {len(self.uploaded_images)} 张")
            self.status_label.setText(f"● 已通过拖拽添加 {added_count} 张参考图片")
            self.status_label.setStyleSheet("QLabel { color: #34C759; }")
        else:
            self.logger.warning("没有找到有效的拖拽图片文件")
            QMessageBox.warning(self, "警告", "没有找到有效的图片文件")

    def add_clipboard_image(self, image):
        """添加剪贴板图像(用于拖拽和粘贴功能)"""
        try:
            self.logger.info("开始处理剪贴板图像")
            # 生成临时文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            temp_dir = Path(tempfile.gettempdir()) / "nano_banana_app"
            temp_dir.mkdir(exist_ok=True)
            self.logger.info(f"临时目录: {temp_dir}")

            # 统一使用PNG格式保存,确保跨平台兼容
            file_extension = ".png"
            temp_file_path = temp_dir / f"clipboard_{timestamp}{file_extension}"

            # 尝试多种保存方式,确保兼容性
            success = False
            try:
                # 方法1: 指定PNG格式
                success = image.save(str(temp_file_path), "PNG")
                self.logger.info(f"方法1保存结果: {success}")
            except:
                try:
                    # 方法2: 自动格式
                    success = image.save(str(temp_file_path))
                    self.logger.info(f"方法2保存结果: {success}")
                except:
                    # 方法3: 转换格式再保存
                    converted_image = QImage(image)
                    success = converted_image.save(str(temp_file_path), "PNG")
                    self.logger.info(f"方法3保存结果: {success}")

            if success and temp_file_path.exists():
                self.uploaded_images.append(str(temp_file_path))
                self.update_image_preview()
                self.image_count_label.setText(f"已选择 {len(self.uploaded_images)} 张")
                self.status_label.setText("● 已添加剪贴板图片")
                self.status_label.setStyleSheet("QLabel { color: #34C759; }")
                self.logger.info(f"剪贴板图片已成功保存到: {temp_file_path}")
            else:
                self.logger.error("图片保存失败")
                QMessageBox.critical(self, "错误", "无法保存剪贴板图片")

        except Exception as e:
            self.logger.error(f"添加剪贴板图片失败: {str(e)}", exc_info=True)
            QMessageBox.critical(self, "错误", f"添加剪贴板图片失败: {str(e)}")

    def paste_from_clipboard(self):
        """从剪贴板粘贴图像"""
        try:
            self.logger.info("开始粘贴剪贴板图片")
            clipboard = QApplication.clipboard()

            # 获取剪贴板MIME数据
            mime_data = clipboard.mimeData()
            self.logger.info(f"剪贴板MIME类型: {[mime for mime in mime_data.formats()]}")

            # 检查剪贴板中是否有图像
            if mime_data.hasImage():
                self.logger.info("检测到剪贴板中有图像数据")
                image = clipboard.image()

                if not image.isNull():
                    self.logger.info(f"图像尺寸: {image.width()}x{image.height()}, 格式: {image.format()}")
                    self.add_clipboard_image(image)
                else:
                    self.logger.warning("剪贴板图像为空")
                    QMessageBox.information(self, "信息", "剪贴板中没有有效的图片")
            else:
                self.logger.warning(f"剪贴板中没有图像,可用格式: {mime_data.formats()}")
                QMessageBox.information(self, "信息", "剪贴板中没有图片,请先复制一张图片")

        except Exception as e:
            self.logger.error(f"粘贴剪贴板图片时发生错误: {str(e)}", exc_info=True)
            QMessageBox.critical(self, "错误", f"粘贴失败: {str(e)}")

    def validate_image_file(self, file_path: str) -> bool:
        """验证图像文件"""
        self.logger.info(f"开始验证图像文件: {file_path}")
        try:
            # 检查文件是否存在
            if not Path(file_path).exists():
                self.logger.warning(f"文件不存在: {file_path}")
                return False

            # 检查文件扩展名
            valid_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'}
            file_extension = Path(file_path).suffix.lower()
            if file_extension not in valid_extensions:
                self.logger.warning(f"不支持的文件格式: {file_extension}, 文件: {file_path}")
                return False

            # 检查文件大小
            file_size = Path(file_path).stat().st_size
            self.logger.info(f"文件大小: {file_size} bytes, 格式: {file_extension}")

            if file_size > 10 * 1024 * 1024:  # 10MB
                self.logger.warning(f"文件过大: {file_size} bytes, 文件: {file_path}")
                QMessageBox.warning(self, "警告", f"图片文件过大: {file_path}\n请选择小于10MB的图片")
                return False

            if file_size == 0:
                self.logger.warning(f"文件为空: {file_path}")
                return False

            # 尝试加载图像以验证文件完整性
            self.logger.info(f"尝试加载图片验证完整性: {file_path}")
            pixmap = QPixmap(file_path)
            if pixmap.isNull():
                self.logger.error(f"图片加载失败或损坏: {file_path}")
                return False

            self.logger.info(f"图片验证成功,尺寸: {pixmap.width()}x{pixmap.height()}, 文件: {file_path}")
            return True

        except Exception as e:
            self.logger.error(f"图像文件验证异常: {file_path}, 错误: {str(e)}", exc_info=True)
            return False

    def keyPressEvent(self, event):
        """处理键盘事件"""
        # 检测键盘组合键
        key_text = event.text()
        key_int = event.key()
        modifiers = event.modifiers()
        self.logger.info(f"键盘事件: key={key_int}, text='{key_text}', modifiers={modifiers}")

        # Ctrl+V 粘贴
        if event.key() == Qt.Key_V and event.modifiers() == Qt.ControlModifier:
            self.logger.info("检测到 Ctrl+V 粘贴组合键")
            self.paste_from_clipboard()
            event.accept()
            return

        # Cmd+V 粘贴 (macOS)
        elif event.key() == Qt.Key_V and event.modifiers() == Qt.MetaModifier:
            self.logger.info("检测到 Cmd+V 粘贴组合键 (macOS)")
            self.paste_from_clipboard()
            event.accept()
            return

        self.logger.debug(f"未处理的键盘事件: {key_text}")
        super().keyPressEvent(event)

    def update_image_preview(self):
        """Update image preview thumbnails"""
        self.logger.info(f"更新图片预览,共 {len(self.uploaded_images)} 张图片")
        try:
            # Clear existing previews
            while self.img_layout.count() > 1:  # Keep the stretch
                item = self.img_layout.takeAt(0)
                if item.widget():
                    item.widget().deleteLater()

            # Add thumbnails
            for idx, file_path in enumerate(self.uploaded_images):
                self.logger.info(f"创建第 {idx + 1} 张图片缩略图: {file_path}")
                try:
                    # Load and create thumbnail
                    pixmap = QPixmap(file_path)
                    if pixmap.isNull():
                        self.logger.warning(f"无法加载图片进行预览: {file_path}")
                        continue

                    pixmap = pixmap.scaled(100, 100, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    self.logger.info(f"缩略图创建成功: {pixmap.width()}x{pixmap.height()}")

                    # Container
                    container = QWidget()
                    container_layout = QVBoxLayout()
                    container_layout.setContentsMargins(5, 5, 5, 5)

                    # Image label
                    img_label = QLabel()
                    img_label.setPixmap(pixmap)
                    img_label.setFixedSize(100, 100)
                    img_label.setStyleSheet("QLabel { border: 1px solid #e5e5e5; }")
                    container_layout.addWidget(img_label)

                    # Info row
                    info_layout = QHBoxLayout()
                    index_label = QLabel(f"图 {idx + 1}")
                    index_label.setStyleSheet("QLabel { font-size: 12pt; color: #666666; font-weight: bold; }")
                    info_layout.addWidget(index_label)

                    del_btn = QPushButton("✕")
                    del_btn.setFixedSize(20, 20)
                    del_btn.setStyleSheet("""
                        QPushButton {
                            background-color: #ff4444;
                            color: white;
                            font-weight: bold;
                            border: none;
                            border-radius: 3px;
                            padding: 0px;
                        }
                        QPushButton:hover {
                            background-color: #FF3B30;
                        }
                    """)
                    del_btn.clicked.connect(lambda checked, i=idx: self.delete_image(i))
                    info_layout.addWidget(del_btn)

                    container_layout.addLayout(info_layout)
                    container.setLayout(container_layout)

                    self.img_layout.insertWidget(self.img_layout.count() - 1, container)
                    self.logger.info(f"缩略图UI组件创建完成: {file_path}")

                except Exception as e:
                    self.logger.error(f"创建缩略图失败: {file_path}, 错误: {str(e)}", exc_info=True)

        except Exception as e:
            self.logger.error(f"更新图片预览失败: {str(e)}", exc_info=True)

    def delete_image(self, index):
        """Delete an image by index"""
        self.logger.info(f"尝试删除第 {index + 1} 张图片")
        if 0 <= index < len(self.uploaded_images):
            deleted_file = self.uploaded_images[index]
            self.uploaded_images.pop(index)
            self.logger.info(f"已删除图片: {deleted_file}")
            self.update_image_preview()
            self.image_count_label.setText(f"已选择 {len(self.uploaded_images)} 张")
            self.status_label.setText("● 已删除图片")
            self.status_label.setStyleSheet("QLabel { color: #FF9500; }")
        else:
            self.logger.warning(f"无效的图片索引: {index}")

    def update_saved_prompts_list(self):
        """Update the saved prompts dropdown"""
        # Block signals to avoid triggering load_saved_prompt during update
        self.saved_prompts_combo.blockSignals(True)
        self.saved_prompts_combo.clear()
        if self.saved_prompts:
            display_prompts = [p[:50] + "..." if len(p) > 50 else p for p in self.saved_prompts]
            self.saved_prompts_combo.addItems(display_prompts)
        self.saved_prompts_combo.blockSignals(False)

    def check_favorite_status(self):
        """Check if current prompt is favorited"""
        prompt = self.prompt_text.toPlainText().strip()
        if prompt in self.saved_prompts:
            self.save_prompt_btn.setText("✓ 已收藏")
        else:
            self.save_prompt_btn.setText("⭐ 收藏")

    def toggle_favorite(self):
        """Toggle favorite status of current prompt"""
        prompt = self.prompt_text.toPlainText().strip()
        if not prompt:
            self.status_label.setText("● 提示词不能为空")
            self.status_label.setStyleSheet("QLabel { color: #FF3B30; }")
            return

        if prompt in self.saved_prompts:
            self.saved_prompts.remove(prompt)
            self.save_config()
            self.update_saved_prompts_list()
            self.status_label.setText("● 该提示词已取消收藏")
        else:
            self.saved_prompts.append(prompt)
            self.save_config()
            self.update_saved_prompts_list()
            self.status_label.setText("● 该提示词已收藏")

        self.status_label.setStyleSheet("QLabel { color: #34C759; }")
        self.check_favorite_status()

    def load_saved_prompt(self):
        """Load a saved prompt"""
        index = self.saved_prompts_combo.currentIndex()
        if 0 <= index < len(self.saved_prompts):
            self.prompt_text.setPlainText(self.saved_prompts[index])
            self.status_label.setText("● 已加载提示词")
            self.status_label.setStyleSheet("QLabel { color: #007AFF; }")

    def delete_saved_prompt(self):
        """Delete the currently selected saved prompt"""
        index = self.saved_prompts_combo.currentIndex()

        if index < 0 or index >= len(self.saved_prompts):
            self.status_label.setText("● 请先选择要删除的提示词")
            self.status_label.setStyleSheet("QLabel { color: #FF9500; }")
            return

        self.saved_prompts.pop(index)
        self.save_config()
        self.update_saved_prompts_list()
        self.status_label.setText("● 已删除提示词")
        self.status_label.setStyleSheet("QLabel { color: #34C759; }")

    def generate_image_async(self):
        """Submit image generation task to queue"""
        from task_queue import TaskType

        prompt = self.prompt_text.toPlainText().strip()
        if not prompt:
            QMessageBox.warning(self, "提示", "请输入图片描述!")
            return


        try:
            # Submit task to queue
            import socket
            task_id = self.task_manager.submit_task(
                task_type=TaskType.IMAGE_GENERATION,
                prompt=prompt,
                api_key=self.api_key,
                reference_images=self.uploaded_images.copy(),
                aspect_ratio=self.aspect_ratio.currentText(),
                image_size=self.image_size.currentText(),
                model="gemini-3-pro-image-preview",
                user_name=self.authenticated_user,
                device_name=socket.gethostname()
            )

            # Connect to task completion signal
            self.task_manager.task_completed.connect(
                lambda tid, img, p, refs, ar, size, model:
                    self._on_my_task_completed(task_id, tid, img, p, refs, ar, size, model)
            )

            # Update UI
            self.status_label.setText(f"● 任务已提交 (ID: {task_id[:8]})")
            self.status_label.setStyleSheet("QLabel { color: #007AFF; }")

        except RuntimeError as e:
            QMessageBox.warning(self, "队列已满", str(e))

    def _on_my_task_completed(self, my_task_id, task_id, image_bytes, prompt,
                             reference_images, aspect_ratio, image_size, model):
        """Handle completion of my submitted task"""
        if my_task_id != task_id:
            return  # Not my task

        # Update display
        self.generated_image_bytes = image_bytes
        self.display_image()
        self.download_btn.setEnabled(True)
        self.status_label.setText("● 图片生成成功")
        self.status_label.setStyleSheet("QLabel { color: #34C759; }")

        # Save to history
        try:
            self.history_manager.save_generation(
                image_bytes=image_bytes,
                prompt=prompt,
                reference_images=reference_images,
                aspect_ratio=aspect_ratio,
                image_size=image_size,
                model=model
            )
            self.status_label.setText("● 图片生成成功,已保存到历史记录")
            self.refresh_history()
        except Exception as e:
            self.logger.warning(f"保存到历史记录失败: {e}")

    def on_image_generated(self, image_bytes, prompt, reference_images, aspect_ratio, image_size, model):
        """Handle successful image generation"""
        self.generated_image_bytes = image_bytes
        self.display_image()
        self.download_btn.setEnabled(True)
        self.generate_btn.setEnabled(True)
        self.status_label.setText("● 图片生成成功")
        self.status_label.setStyleSheet("QLabel { color: #34C759; }")

        # 自动保存到历史记录
        try:
            self.history_manager.save_generation(
                image_bytes=image_bytes,
                prompt=prompt,
                reference_images=reference_images,
                aspect_ratio=aspect_ratio,
                image_size=image_size,
                model=model
            )
            self.status_label.setText("● 图片生成成功,已保存到历史记录")
            # 刷新历史记录列表
            self.refresh_history()
        except Exception as e:
            print(f"保存到历史记录失败: {e}")
            # 不影响主要功能,静默处理错误

    def on_generation_error(self, error_msg):
        """Handle image generation error"""
        QMessageBox.critical(self, "错误", f"生成失败: {error_msg}")
        self.generate_btn.setEnabled(True)
        self.status_label.setText("● 生成失败")
        self.status_label.setStyleSheet("QLabel { color: #FF3B30; }")

    def update_status(self, message):
        """Update status label"""
        self.status_label.setText(f"● {message}")

    def display_image(self):
        """Display generated image in preview"""
        if not self.generated_image_bytes:
            return

        try:
            # Load image from bytes
            pixmap = QPixmap()
            pixmap.loadFromData(self.generated_image_bytes)

            # Scale to fit preview area
            available_width = self.preview_label.width() - 40
            available_height = self.preview_label.height() - 40

            scaled_pixmap = pixmap.scaled(
                available_width, available_height,
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation
            )

            self.preview_label.setPixmap(scaled_pixmap)
            self.preview_label.setStyleSheet("")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"图片显示失败: {str(e)}")

    def open_fullsize_view(self, event):
        """Open generated image with system default viewer"""
        if not self.generated_image_bytes:
            return

        try:
            # 获取处理后的PNG图片数据
            processed_bytes = self.get_processed_image_bytes('.png')

            # Create temporary file with processed data
            with tempfile.NamedTemporaryFile(delete=False, suffix='.png', mode='wb') as tmp_file:
                tmp_file.write(processed_bytes)
                tmp_path = tmp_file.name

            # Open with system default viewer
            url = QUrl.fromLocalFile(tmp_path)
            QDesktopServices.openUrl(url)

            processing_method = "格式转换后" if processed_bytes != self.generated_image_bytes else "原始数据"
            self.status_label.setText(f"● 已用系统查看器打开 ({processing_method})")
            self.status_label.setStyleSheet("QLabel { color: #007AFF; }")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"无法打开系统图片查看器: {str(e)}")

    def get_processed_image_bytes(self, file_extension='.png') -> bytes:
        """获取处理后的图片字节数据"""
        try:
            from PIL import Image
            import io

            # 使用Pillow处理图像
            with Image.open(io.BytesIO(self.generated_image_bytes)) as img:
                file_format = img.format
                save_format = 'PNG' if file_extension.lower().endswith('.png') else 'JPEG'

                # 检测并执行格式转换
                if file_format and file_format != save_format:
                    self.logger.info(f"下载时格式转换: {file_format} -> {save_format}")

                    # 模式转换
                    if save_format == 'PNG':
                        if img.mode not in ['RGBA', 'RGB', 'L']:
                            if img.mode == 'P':
                                img = img.convert('RGBA')
                            elif img.mode == 'LA':
                                img = img.convert('RGBA')
                            else:
                                img = img.convert('RGBA')
                    elif save_format == 'JPEG':
                        if img.mode in ['RGBA', 'P']:
                            img = img.convert('RGB')
                        elif img.mode == 'L':
                            img = img.convert('RGB')

                # 转换为字节数据
                processed_bytes = io.BytesIO()
                img.save(processed_bytes, save_format, optimize=True)
                return processed_bytes.getvalue()

        except Exception as e:
            self.logger.warning(f"图片处理失败,使用原始数据: {e}")
            return self.generated_image_bytes

    def download_image(self):
        """Download generated image"""
        if not self.generated_image_bytes:
            QMessageBox.critical(self, "错误", "没有可下载的图片!")
            return

        # Generate default filename
        default_filename = datetime.now().strftime("%Y%m%d%H%M%S.png")

        file_path, _ = QFileDialog.getSaveFileName(
            self,
            "保存图片",
            default_filename,
            "PNG 文件 (*.png);;JPEG 文件 (*.jpg);;所有文件 (*.*)"
        )

        if file_path:
            try:
                # 获取处理后的图片数据
                file_extension = Path(file_path).suffix
                processed_bytes = self.get_processed_image_bytes(file_extension)

                # 保存处理后的图片
                with open(file_path, 'wb') as f:
                    f.write(processed_bytes)

                # 获取实际文件大小
                import os
                file_size = os.path.getsize(file_path)

                processing_method = "格式转换" if processed_bytes != self.generated_image_bytes else "原始数据"
                self.logger.info(f"图片下载完成 - 方法: {processing_method}, 文件: {file_path}, 大小: {file_size} 字节")

                # 只使用状态栏提示,不显示弹窗
                self.status_label.setText("● 图片已保存")
                self.status_label.setStyleSheet("QLabel { color: #34C759; }")
            except Exception as e:
                self.logger.error(f"图片保存失败: {str(e)}")
                QMessageBox.critical(self, "错误", f"保存失败: {str(e)}")

    def refresh_history(self):
        """Refresh the history list"""
        self.history_list.clear()
        history_items = self.history_manager.load_history_index()

        for item in history_items:
            # Create list item with icon
            list_item = QListWidgetItem()

            # Set item data
            list_item.setData(Qt.UserRole, item.timestamp)

            # Create enhanced tooltip with details
            tooltip = f"时间: {item.created_at.strftime('%Y-%m-%d %H:%M:%S')}\n"
            tooltip += f"提示词: {item.prompt}\n"
            tooltip += f"宽高比: {item.aspect_ratio}\n"
            tooltip += f"尺寸: {item.image_size}"
            list_item.setToolTip(tooltip)

            # Try to load thumbnail
            if item.generated_image_path.exists():
                try:
                    pixmap = QPixmap(str(item.generated_image_path))
                    if not pixmap.isNull():
                        # Scale to thumbnail size
                        scaled_pixmap = pixmap.scaled(120, 120, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                        list_item.setIcon(QIcon(scaled_pixmap))
                    else:
                        # Create placeholder icon
                        list_item.setIcon(self.create_placeholder_icon("图片\n加载失败"))
                except Exception as e:
                    print(f"Failed to load thumbnail for {item.timestamp}: {e}")
                    list_item.setIcon(self.create_placeholder_icon("图片\n错误"))
            else:
                list_item.setIcon(self.create_placeholder_icon("图片\n不存在"))

            # Add text info below the icon
            # Get prompt preview (first 20 characters)
            prompt_preview = item.prompt[:20] + "..." if len(item.prompt) > 20 else item.prompt
            list_item.setText(f"{item.timestamp}\n{prompt_preview}")

            # Add to list
            self.history_list.addItem(list_item)

        # Update count label
        self.history_count_label.setText(f"共 {len(history_items)} 条历史记录")

        # Clear details panel if no items
        if not history_items:
            self.clear_details_panel()

    def create_placeholder_icon(self, text):
        """Create a placeholder icon with text"""
        # Create a 120x120 pixmap
        pixmap = QPixmap(120, 120)
        pixmap.fill(Qt.lightGray)

        # Create a painter to draw text
        from PySide6.QtGui import QPainter, QFont
        painter = QPainter(pixmap)
        painter.setPen(Qt.black)
        painter.setFont(QFont("Arial", 10))

        # Draw text in center
        rect = pixmap.rect()
        painter.drawText(rect, Qt.AlignCenter, text)

        painter.end()
        return QIcon(pixmap)

    def load_history_item(self, item):
        """Display history item details when selected"""
        timestamp = item.data(Qt.UserRole)
        if not timestamp:
            return

        history_item = self.history_manager.get_history_item(timestamp)
        if not history_item:
            return

        # Display details in the details panel
        self.display_history_details(history_item)

    def show_history_context_menu(self, position):
        """Show context menu for history items"""
        item = self.history_list.itemAt(position)
        if not item:
            return

        timestamp = item.data(Qt.UserRole)
        if not timestamp:
            return

        # Create context menu
        menu = QMenu(self)

        # Delete action
        delete_action = QAction("删除此项", self)
        delete_action.triggered.connect(lambda: self.delete_history_item(timestamp))
        menu.addAction(delete_action)

        # Open in file manager action
        open_action = QAction("在文件管理器中显示", self)
        open_action.triggered.connect(lambda: self.open_in_file_manager(timestamp))
        menu.addAction(open_action)

        # Show menu
        menu.exec_(self.history_list.mapToGlobal(position))

    def delete_history_item(self, timestamp):
        """Delete a history item"""
        reply = QMessageBox.question(
            self, "确认删除", "确定要删除这条历史记录吗?\n这将删除相关的所有文件。",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            success = self.history_manager.delete_history_item(timestamp)
            if success:
                self.refresh_history()
                self.status_label.setText("● 历史记录已删除")
                self.status_label.setStyleSheet("QLabel { color: #34C759; }")
            else:
                QMessageBox.critical(self, "错误", "删除历史记录失败")

    def open_in_file_manager(self, timestamp):
        """Open the history item directory in file manager"""
        history_item = self.history_manager.get_history_item(timestamp)
        if not history_item:
            return

        record_dir = history_item.generated_image_path.parent
        if record_dir.exists():
            import subprocess
            import platform

            try:
                if platform.system() == "Windows":
                    subprocess.run(["explorer", str(record_dir)])
                elif platform.system() == "Darwin":  # macOS
                    subprocess.run(["open", str(record_dir)])
                else:  # Linux
                    subprocess.run(["xdg-open", str(record_dir)])
            except Exception as e:
                QMessageBox.critical(self, "错误", f"无法打开文件管理器: {str(e)}")

    def clear_history(self):
        """Clear all history"""
        reply = QMessageBox.question(
            self, "确认清空", "确定要清空所有历史记录吗?\n这将删除所有历史图片文件,且无法恢复。",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                # Remove entire history directory
                import shutil
                if self.history_manager.base_path.exists():
                    shutil.rmtree(self.history_manager.base_path)
                    # Recreate empty directory
                    self.history_manager.base_path.mkdir(parents=True, exist_ok=True)

                self.refresh_history()
                self.status_label.setText("● 历史记录已清空")
                self.status_label.setStyleSheet("QLabel { color: #34C759; }")

            except Exception as e:
                QMessageBox.critical(self, "错误", f"清空历史记录失败: {str(e)}")

    def display_history_details(self, history_item):
        """Display history item details in the details panel"""
        try:
            # Update prompt display
            self.prompt_display.setText(history_item.prompt)
            self.copy_prompt_btn.setEnabled(True)
            self.current_history_prompt = history_item.prompt  # Store for copying

            # Update parameters
            self.time_label.setText(history_item.created_at.strftime('%Y-%m-%d %H:%M:%S'))
            self.aspect_ratio_label.setText(history_item.aspect_ratio)
            self.image_size_label.setText(history_item.image_size)

            # Display reference images
            self.display_reference_images(history_item.reference_image_paths)

            # Display generated image
            self.display_generated_image(history_item.generated_image_path)

        except Exception as e:
            print(f"Error displaying history details: {e}")

    def display_reference_images(self, reference_paths):
        """Display reference images in the details panel with adaptive sizing"""
        # Clear existing images
        for i in reversed(range(self.ref_images_layout.count())):
            child = self.ref_images_layout.itemAt(i).widget()
            if child:
                child.setParent(None)

        if not reference_paths:
            no_images_label = QLabel("无参考图片")
            no_images_label.setStyleSheet("color: #999;")
            self.ref_images_layout.addWidget(no_images_label)
            return

        # Calculate adaptive size based on number of images
        num_images = len(reference_paths)
        if num_images == 1:
            size = 180  # Single image gets more space
        elif num_images == 2:
            size = 140  # Two images get medium space
        else:
            size = 100  # Multiple images get smaller space

        for ref_path in reference_paths:
            if ref_path.exists():
                try:
                    pixmap = QPixmap(str(ref_path))
                    if not pixmap.isNull():
                        # Create adaptive thumbnail
                        thumbnail = pixmap.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                        image_label = QLabel()
                        image_label.setPixmap(thumbnail)
                        image_label.setFixedSize(size, size)
                        image_label.setAlignment(Qt.AlignCenter)
                        image_label.setStyleSheet("border: 1px solid #ddd; margin: 5px;")
                        image_label.mouseDoubleClickEvent = lambda e, path=ref_path: self.open_reference_image(path)
                        self.ref_images_layout.addWidget(image_label)
                except Exception as e:
                    print(f"Failed to load reference image {ref_path}: {e}")

    def display_generated_image(self, image_path):
        """Display the generated image in the details panel"""
        if image_path.exists():
            try:
                pixmap = QPixmap(str(image_path))
                if not pixmap.isNull():
                    # Scale to larger size while maintaining aspect ratio
                    available_size = self.generated_image_label.size()
                    scaled_pixmap = pixmap.scaled(
                        available_size.width(),
                        available_size.height(),
                        Qt.KeepAspectRatio,
                        Qt.SmoothTransformation
                    )
                    self.generated_image_label.setPixmap(scaled_pixmap)
                    self.generated_image_label.setStyleSheet(
                        "QLabel { border: 1px solid #ddd; background-color: white; }")
                    self.current_generated_image_path = image_path
                else:
                    self.generated_image_label.setText("图片加载失败")
                    self.generated_image_label.setStyleSheet(
                        "QLabel { background-color: #f5f5f5; border: 1px solid #ddd; color: #999; }")
            except Exception as e:
                print(f"Failed to load generated image {image_path}: {e}")
                self.generated_image_label.setText("图片加载失败")
                self.generated_image_label.setStyleSheet(
                    "QLabel { background-color: #f5f5f5; border: 1px solid #ddd; color: #999; }")
        else:
            self.generated_image_label.setText("图片文件不存在")
            self.generated_image_label.setStyleSheet(
                "QLabel { background-color: #f5f5f5; border: 1px solid #ddd; color: #999; }")

    def clear_details_panel(self):
        """Clear the details panel"""
        self.prompt_display.setText("请选择一个历史记录查看详情")
        self.copy_prompt_btn.setEnabled(False)
        self.time_label.setText("-")
        self.aspect_ratio_label.setText("-")
        self.image_size_label.setText("-")

        # Clear reference images
        for i in reversed(range(self.ref_images_layout.count())):
            child = self.ref_images_layout.itemAt(i).widget()
            if child:
                child.setParent(None)
        no_images_label = QLabel("无参考图片")
        no_images_label.setStyleSheet("color: #999;")
        self.ref_images_layout.addWidget(no_images_label)

        self.generated_image_label.setText("请选择一个历史记录查看生成图片")
        self.generated_image_label.setPixmap(QPixmap())
        self.generated_image_label.setStyleSheet(
            "QLabel { background-color: #f5f5f5; border: 1px solid #ddd; color: #999; }")

    def copy_prompt_text(self):
        """Copy the prompt text to clipboard"""
        if hasattr(self, 'current_history_prompt'):
            from PySide6.QtWidgets import QApplication
            clipboard = QApplication.clipboard()
            clipboard.setText(self.current_history_prompt)

            # Show success message briefly
            original_text = self.copy_prompt_btn.text()
            self.copy_prompt_btn.setText("✅ 已复制")
            self.copy_prompt_btn.setStyleSheet("QPushButton { background-color: #34C759; color: white; }")

            # Reset after 2 seconds
            QTimer.singleShot(2000, lambda: self.reset_copy_button())

    def reset_copy_button(self):
        """Reset the copy button appearance"""
        self.copy_prompt_btn.setText("📋 复制")
        self.copy_prompt_btn.setStyleSheet("")

    def open_generated_image_from_history(self, event):
        """Open the generated image from history in system viewer"""
        if hasattr(self, 'current_generated_image_path') and self.current_generated_image_path:
            self.open_image_in_system_viewer(self.current_generated_image_path)

    def open_reference_image(self, image_path):
        """Open a reference image in system viewer"""
        self.open_image_in_system_viewer(image_path)

    def open_image_in_system_viewer(self, image_path):
        """Open an image in the system default viewer"""
        try:
            QDesktopServices.openUrl(QUrl.fromLocalFile(str(image_path)))
        except Exception as e:
            QMessageBox.critical(self, "错误", f"无法打开图片: {str(e)}")


class ImageGenerationWorker(QThread):
    """Worker thread for image generation"""
    finished = Signal(bytes, str, list, str, str,
                      str)  # image_bytes, prompt, reference_images, aspect_ratio, image_size, model
    error = Signal(str)
    progress = Signal(str)

    def __init__(self, api_key, prompt, images, aspect_ratio, image_size, model="gemini-3-pro-image-preview"):
        super().__init__()
        self.logger = logging.getLogger(__name__)
        self.api_key = api_key
        self.prompt = prompt
        self.images = images
        self.aspect_ratio = aspect_ratio
        self.image_size = image_size
        self.model = model

        self.logger.info(f"图片生成任务初始化 - 模型: {model}, 尺寸: {image_size}, 宽高比: {aspect_ratio}")

    def run(self):
        """Execute image generation in background thread"""
        try:
            self.logger.info("开始图片生成任务")

            if not self.prompt:
                self.logger.error("图片描述为空")
                self.error.emit("请输入图片描述!")
                return

            if not self.api_key:
                self.logger.error("API密钥为空")
                self.error.emit("未找到API密钥,请在config.json中配置!")
                return

            self.progress.emit("正在连接 Gemini API...")
            self.logger.debug("正在连接 Gemini API")

            client = genai.Client(api_key=self.api_key)

            # Build content parts
            content_parts = [self.prompt]

            # Add reference images
            for img_path in self.images:
                with open(img_path, 'rb') as f:
                    img_data = f.read()

                mime_type = "image/png"
                if img_path.lower().endswith(('.jpg', '.jpeg')):
                    mime_type = "image/jpeg"

                content_parts.append(
                    types.Part.from_bytes(
                        data=img_data,
                        mime_type=mime_type
                    )
                )

            self.progress.emit("正在生成图片...")

            # Generation config
            config = types.GenerateContentConfig(
                response_modalities=["IMAGE"],
                image_config=types.ImageConfig(
                    aspect_ratio=self.aspect_ratio,
                    image_size=self.image_size
                )
            )

            # Generate
            response = client.models.generate_content(
                model="gemini-3-pro-image-preview",
                contents=content_parts,
                config=config
            )

            # Extract image
            for part in response.parts:
                if hasattr(part, 'inline_data') and part.inline_data:
                    if isinstance(part.inline_data.data, bytes):
                        image_bytes = part.inline_data.data
                    else:
                        image_bytes = base64.b64decode(part.inline_data.data)

                    # Convert reference images to bytes for history saving
                    reference_images_bytes = []
                    for img_path in self.images:
                        if img_path and os.path.exists(img_path):
                            with open(img_path, 'rb') as f:
                                reference_images_bytes.append(f.read())
                        else:
                            reference_images_bytes.append(b'')

                    self.logger.info(f"图片生成成功 - 模型: {self.model}, 尺寸: {self.image_size}")
                    self.finished.emit(image_bytes, self.prompt, reference_images_bytes,
                                       self.aspect_ratio, self.image_size, self.model)
                    return

            error_msg = "响应中没有图片数据"
            self.logger.error(error_msg)
            self.error.emit(error_msg)

        except Exception as e:
            error_msg = f"图片生成异常: {e}"
            self.logger.error(error_msg)
            self.error.emit(error_msg)


# ============================================================================
# 珠宝设计功能模块
# ============================================================================
DEFAULT_JEWELRY_LIBRARY = {
    "主石形状": [
        "圆形",
        "椭圆形",
        "梨形",
        "马眼形",
        "子弹形(Baguette 子弹刻面)",
        "垫形",
        "公主方形",
        "祖母绿形",
        "心形",
        "风筝形",
        "棺材形(Coffin Cut)",
        "菱形(Rhombus)",
        "正六边形",
        "四叶草形",
        "梯方形(Tapered Step)",
        "阿斯切形",
        "平底刻面风格"
    ],

    "主石材质": [
        "莫桑石",
        "钻石",
        "黑发晶",
        "蓝宝石",
        "红宝石",
        "粉蓝宝石",
        "绿碧玺",
        "黄水晶(天然包体)",
        "月光石",
        "摩根石",
        "海蓝宝",
        "天然白玉髓",
        "金绿宝石(猫眼)"
    ],

    "金属": [
        "14K黄金",
        "14K白金",
        "14K玫瑰金",
        "18K黄金",
        "18K白金",
        "18K玫瑰金",
        "双色金(白金+黄金)",
        "950铂金",
        "925银镀铑",
        "钛金属",
        "定制复古做旧金"
    ],

    "花头形式": [
        "全halo光环",
        "半halo光环",
        "双层halo",
        "花卉风格光环",
        "围圈雕刻光环",
        "围圈密钉镶",
        "经典圆形光环",
        "几何六边形光环",
        "非对称光环",
        "三石花头(cluster 结构)",
        "五石花头",
        "cluster堆砌花头(大小堆/不规则)",
        "双石结构(Two-stone)",
        "单石无光环(爪镶/包镶)",
        "花头侧面结构",
        "高耸花头(Cathedral halo)"
    ],

    "戒臂结构": [
        "直臂",
        "xox扭臂(交叉扭绞)",
        ">O< 戒臂结构",
        "<O> 戒臂结构",
        "V字戒臂",
        "交叉戒臂",
        "overlap重叠戒臂",
        "wave波浪戒臂",
        "刀锋臂",
        "大教堂戒臂(高肩设计)",
        "三股编织戒臂",
        "分裂戒臂(split shank)",
        "戒臂夹层",
        "小夹层戒臂(如莲花夹层设计)",
        "不对称戒臂"
    ],

    "戒臂处理": [
        "密钉镶戒臂",
        "微密钉镶",
        "镶石虎爪镶/逼镶",
        "抛光平滑戒臂",
        "珠边戒臂(milgrain)",
        "光金戒臂",
        "雕刻镂空花丝",
        "浮雕雕刻(凸雕)",
        "凹刻雕刻(内刻)",
        "几何雕刻纹理",
        "复古米粒边装饰(milgrain)",
        "编织纹理戒臂",
        "穿孔镂空细节",
        "锤纹处理"
    ],

    "辅石镶嵌": [
        "三石结构",
        "五石结构",
        "cluster自由堆砌侧石",
        "大小堆组合",
        "共爪镶侧钻",
        "包镶侧钻",
        "轨道镶",
        "槽镶"
    ],

    "特殊元素": [
        "花朵元素",
        "月亮元素",
        "星星元素",
        "日月星组合",
        "凯尔特结",
        "叶子图案",
        "自然植物藤蔓纹理",
        "蝴蝶结元素",
        "装饰艺术几何元素",
        "复古花纹",
        "哥特式结构元素"
    ]
}



class JewelryLibraryManager:
    """珠宝词库管理器"""

    def __init__(self, config_dir: Path):
        """初始化词库管理器

        Args:
            config_dir: 配置文件目录
        """
        self.logger = logging.getLogger(__name__)
        self.config_dir = config_dir
        self.config_path = config_dir / "jewelry_library.json"
        self.library = self.load_library()

    def load_library(self) -> Dict[str, List[str]]:
        """加载词库,优先使用用户配置,不存在则使用默认词库"""
        if self.config_path.exists():
            try:
                with open(self.config_path, 'r', encoding='utf-8') as f:
                    library = json.load(f)

                # 验证数据完整性,补全缺失的类别
                needs_update = False
                for category, default_items in DEFAULT_JEWELRY_LIBRARY.items():
                    if category not in library:
                        self.logger.warning(f"检测到缺失类别: {category},从默认配置补全")
                        library[category] = default_items.copy()
                        needs_update = True
                    elif not library[category] or len(library[category]) == 0:
                        self.logger.warning(f"检测到空类别: {category},从默认配置补全")
                        library[category] = default_items.copy()
                        needs_update = True
                    elif len(library[category]) < len(default_items) * 0.5:
                        # 如果类别数据量少于默认值的50%,认为数据不完整,使用默认数据
                        self.logger.warning(f"检测到类别 {category} 数据不完整(仅{len(library[category])}项,默认{len(default_items)}项),从默认配置补全")
                        library[category] = default_items.copy()
                        needs_update = True

                # 如果数据被补全,保存更新后的配置
                if needs_update:
                    self.logger.info("词库数据已补全,保存更新")
                    self.save_library(library)

                self.logger.info(f"珠宝词库加载成功: {self.config_path}")
                return library
            except Exception as e:
                self.logger.error(f"珠宝词库加载失败: {e},使用默认词库")
                library = DEFAULT_JEWELRY_LIBRARY.copy()
                # 尝试保存默认配置,覆盖损坏的文件
                try:
                    self.save_library(library)
                except:
                    pass
                return library
        else:
            # 首次使用,从代码中的默认配置创建用户配置文件
            self.logger.info("首次使用,创建用户配置文件")
            library = DEFAULT_JEWELRY_LIBRARY.copy()
            self.save_library(library)
            return library

    def save_library(self, library: Dict[str, List[str]] = None):
        """保存词库到用户配置目录

        Args:
            library: 要保存的词库,如果为None则保存当前词库
        """
        if library is None:
            library = self.library

        try:
            self.config_dir.mkdir(parents=True, exist_ok=True)
            with open(self.config_path, 'w', encoding='utf-8') as f:
                json.dump(library, f, ensure_ascii=False, indent=2)
            self.logger.info(f"珠宝词库保存成功: {self.config_path}")
        except Exception as e:
            self.logger.error(f"珠宝词库保存失败: {e}")
            raise

    def add_item(self, category: str, value: str):
        """添加词库项

        Args:
            category: 类别名称(如"主石")
            value: 词条内容(纯中文)
        """
        if category not in self.library:
            self.library[category] = []

        if value not in self.library[category]:
            self.library[category].append(value)
            self.save_library()
            self.logger.info(f"添加词库项: {category} -> {value}")
        else:
            self.logger.warning(f"词库项已存在: {category} -> {value}")

    def remove_item(self, category: str, value: str):
        """删除词库项

        Args:
            category: 类别名称
            value: 词条内容
        """
        if category in self.library and value in self.library[category]:
            self.library[category].remove(value)
            self.save_library()
            self.logger.info(f"删除词库项: {category} -> {value}")
        else:
            self.logger.warning(f"词库项不存在: {category} -> {value}")

    def reset_category(self, category: str):
        """恢复单个类别的默认词库

        Args:
            category: 类别名称
        """
        if category in DEFAULT_JEWELRY_LIBRARY:
            self.library[category] = DEFAULT_JEWELRY_LIBRARY[category].copy()
            self.save_library()
            self.logger.info(f"恢复默认词库: {category}")
        else:
            self.logger.warning(f"未知的类别: {category}")

    def reset_all(self):
        """恢复所有类别的默认词库"""
        self.library = DEFAULT_JEWELRY_LIBRARY.copy()
        self.save_library()
        self.logger.info("恢复所有默认词库")


class PromptAssembler:
    """Prompt 组装器(纯中文)"""

    BASE_TEMPLATE = """一款高端精品珠宝戒指设计,主石为{主石},镶嵌于{金属}中。戒头采用{花头形式}围绕主石。戒臂采用{戒臂结构}设计,表面处理为{戒臂处理}。风格元素包括{特殊元素}。辅石采用{辅石镶嵌}增加光彩。高端珠宝渲染,干净的摄影棚光线,精准的金属抛光,强调宝石清晰度,不要出现手部。"""

    @staticmethod
    def assemble(form_data: Dict[str, str]) -> str:
        """智能组装 prompt,处理空值

        Args:
            form_data: 表单数据,key为字段名,value为选中的值

        Returns:
            组装后的 prompt 字符串
        """
        # 提取字段值(支持新旧两种格式)
        center_stone = form_data.get("主石", "").strip()  # 向后兼容

        # 新格式:拆分形状和材质
        center_stone_shape = form_data.get("主石形状", "").strip()
        center_stone_material = form_data.get("主石材质", "").strip()
        metal = form_data.get("金属", "").strip()
        halo_style = form_data.get("花头形式", "").strip()
        shank_structure = form_data.get("戒臂结构", "").strip()
        shank_treatment = form_data.get("戒臂处理", "").strip()
        special_motifs = form_data.get("特殊元素", "").strip()
        accent_setting = form_data.get("辅石镶嵌", "").strip()

        # 构建 prompt 片段
        parts = []

        # 构建主石描述(优先使用新格式)
        if center_stone_shape and center_stone_material:
            # 新格式:形状+材质
            main_stone_desc = f"{center_stone_shape}{center_stone_material}"
        elif center_stone:
            # 旧格式:直接使用
            main_stone_desc = center_stone
        elif center_stone_shape:
            # 只有形状
            main_stone_desc = center_stone_shape
        elif center_stone_material:
            # 只有材质
            main_stone_desc = center_stone_material
        else:
            main_stone_desc = ""

        # 主体部分(主石和金属)
        if main_stone_desc and metal:
            parts.append(f"一款高端精品珠宝戒指设计,主石为{main_stone_desc},镶嵌于{metal}中。")
        elif metal:
            parts.append(f"一款高端精品珠宝戒指设计,镶嵌于{metal}中。")
        elif main_stone_desc:
            parts.append(f"一款高端精品珠宝戒指设计,主石为{main_stone_desc}。")
        else:
            parts.append("一款高端精品珠宝戒指设计。")

        # 戒头部分
        if halo_style:
            if main_stone_desc:
                parts.append(f"戒头采用{halo_style}围绕主石。")
            else:
                parts.append(f"戒头采用{halo_style}设计。")

        # 戒臂部分
        if shank_structure and shank_treatment:
            parts.append(f"戒臂采用{shank_structure}设计,表面处理为{shank_treatment}。")
        elif shank_structure:
            parts.append(f"戒臂采用{shank_structure}设计。")
        elif shank_treatment:
            parts.append(f"戒臂表面处理为{shank_treatment}。")

        # 特殊元素
        if special_motifs:
            parts.append(f"风格元素包括{special_motifs}。")

        # 辅石镶嵌
        if accent_setting:
            parts.append(f"辅石采用{accent_setting}增加光彩。")

        # 固定的渲染要求
        parts.append("高端珠宝渲染,干净的摄影棚光线,精准的金属抛光,强调宝石清晰度,不要出现手部。")

        return "".join(parts)


class StyleDesignerTab(QWidget):
    """款式设计 Tab(纯中文)"""

    def __init__(self, library_manager: JewelryLibraryManager, parent=None):
        super().__init__(parent)
        self.logger = logging.getLogger(__name__)
        self.library_manager = library_manager
        self.parent_window = parent

        # 字段顺序
        self.categories = ["主石形状", "主石材质", "金属", "花头形式", "戒臂结构", "戒臂处理", "特殊元素", "辅石镶嵌"]

        # 存储每个类别的 ComboBox
        self.combo_boxes = {}

        # 存储每个类别的锁定按钮
        self.lock_buttons = {}

        # 存储锁定的类别
        self.locked_fields = set()

        # 生成相关
        self.generated_image_bytes = None

        self.setup_ui()

    def setup_ui(self):
        """创建 UI 布局"""
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(15)

        # 表单区域 - 每行两列布局
        form_group = QGroupBox("珠宝元素选择")
        form_layout = QVBoxLayout()

        # 使用网格布局实现每行两列
        grid_layout = QGridLayout()
        grid_layout.setHorizontalSpacing(20)  # 列间距
        grid_layout.setVerticalSpacing(10)    # 行间距

        for i, category in enumerate(self.categories):
            field_widget = self.create_field_widget(category)
            row = i // 2
            col = i % 2
            grid_layout.addWidget(field_widget, row, col)

        form_layout.addLayout(grid_layout)

        # 全局按钮区域
        buttons_layout = QHBoxLayout()

        # 随机生成按钮
        random_btn = QPushButton("🎲 随机生成参数")
        random_btn.clicked.connect(self.randomize_parameters)
        random_btn.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                padding: 8px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)
        buttons_layout.addWidget(random_btn)

        # 全局恢复按钮
        reset_all_btn = QPushButton("🔄 恢复所有默认词库")
        reset_all_btn.clicked.connect(self.reset_all_library)
        reset_all_btn.setStyleSheet("""
            QPushButton {
                background-color: #ff9800;
                color: white;
                padding: 8px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #f57c00;
            }
        """)
        buttons_layout.addWidget(reset_all_btn)

        buttons_layout.addStretch()
        form_layout.addLayout(buttons_layout)

        form_group.setLayout(form_layout)
        main_layout.addWidget(form_group)

        # Content row: Prompt (left) + Settings (right) - 与图片生成页面保持一致
        content_row = QHBoxLayout()

        # Prompt section
        prompt_group = QGroupBox("Prompt 预览")
        prompt_layout = QVBoxLayout()
        self.prompt_preview = QTextEdit()
        self.prompt_preview.setReadOnly(True)
        prompt_layout.addWidget(self.prompt_preview)
        prompt_group.setLayout(prompt_layout)
        prompt_group.setStyleSheet("font-size: 16px;")

        content_row.addWidget(prompt_group, 2)

        # Settings section
        settings_group = QGroupBox("生成设置")
        settings_layout = QVBoxLayout()

        aspect_label = QLabel("宽高比")
        aspect_label.setStyleSheet("QLabel { font-size: 14px; line-height: 18px; }")
        settings_layout.addWidget(aspect_label)
        self.aspect_ratio = QComboBox()
        self.aspect_ratio.addItems(["1:1", "2:3", "3:2", "3:4", "4:3", "16:9"])
        settings_layout.addWidget(self.aspect_ratio)

        settings_layout.addSpacing(10)

        size_label = QLabel("图片尺寸")
        size_label.setStyleSheet("QLabel { font-size: 14px; line-height: 18px; }")
        settings_layout.addWidget(size_label)
        self.image_size = QComboBox()
        self.image_size.addItems(["1K", "2K", "4K"])
        self.image_size.setCurrentIndex(1)
        settings_layout.addWidget(self.image_size)

        settings_layout.addSpacing(10)

        settings_layout.addStretch()
        settings_group.setLayout(settings_layout)
        content_row.addWidget(settings_group, 1)

        main_layout.addLayout(content_row)

        # Action buttons - 与图片生成页面保持一致
        action_layout = QHBoxLayout()
        self.generate_btn = QPushButton("🎨 生成珠宝图片")
        self.generate_btn.clicked.connect(self.generate_image)
        self.generate_btn.setStyleSheet("""
            QPushButton {
                background-color: #007AFF;
                color: white;
                padding: 12px;
                border-radius: 4px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #0051D5;
            }
        """)
        action_layout.addWidget(self.generate_btn)

        self.download_btn = QPushButton("💾 下载图片")
        self.download_btn.clicked.connect(self.download_image)
        self.download_btn.setEnabled(False)
        action_layout.addWidget(self.download_btn)

        self.status_label = QLabel("● 就绪")
        self.status_label.setStyleSheet("QLabel { font-size: 14px; line-height: 18px; }")
        action_layout.addWidget(self.status_label)
        action_layout.addStretch()

        main_layout.addLayout(action_layout)

        # Preview section - 与图片生成页面保持一致
        preview_group = QGroupBox("预览")
        preview_layout = QVBoxLayout()

        self.result_label = QLabel("生成的图片将在这里显示\n双击用系统查看器打开")
        self.result_label.setAlignment(Qt.AlignCenter)
        self.result_label.setMinimumHeight(300)
        self.result_label.setMinimumWidth(400)
        self.result_label.setStyleSheet("""
            QLabel {
                color: #999999;
                font-size: 14px;
                line-height: 18px;
                border: 1px solid #ddd;
                border-radius: 4px;
                background-color: #f9f9f9;
            }
        """)
        self.result_label.setScaledContents(False)
        # 保存原始的双击处理方法引用
        self.original_mouseDoubleClickEvent = self.result_label.mouseDoubleClickEvent
        # 重写双击事件
        self.result_label.mouseDoubleClickEvent = self.open_fullsize_view
        preview_layout.addWidget(self.result_label)

        preview_group.setLayout(preview_layout)
        main_layout.addWidget(preview_group, 1)

        main_layout.addStretch()
        self.setLayout(main_layout)

        # 初始化 prompt 预览
        self.update_prompt_preview()

    def randomize_parameters(self):
        """随机生成一套参数(跳过锁定的字段)"""
        for category, combo in self.combo_boxes.items():
            if category not in self.locked_fields and combo.count() > 0:
                random_index = random.randint(0, combo.count() - 1)
                combo.setCurrentIndex(random_index)
        # 触发prompt预览更新
        self.update_prompt_preview()

    def create_field_widget(self, category: str) -> QWidget:
        """创建单个字段的 UI 组件"""
        widget = QWidget()
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        # 标签
        label = QLabel(f"{category}:")
        label.setMinimumWidth(70)  # 减小标签宽度以适应两列布局
        label.setStyleSheet("QLabel { font-size: 14px; line-height: 18px; }")
        layout.addWidget(label)

        # 下拉框
        combo = QComboBox()
        combo.addItem("")  # 空选项
        items = self.library_manager.library.get(category, [])
        combo.addItems(items)
        combo.currentTextChanged.connect(self.update_prompt_preview)
        self.combo_boxes[category] = combo
        layout.addWidget(combo, 3)

        # 添加按钮(使用表情符号)
        add_btn = QPushButton("➕")
        add_btn.clicked.connect(lambda: self.add_library_item(category))
        add_btn.setFixedWidth(40)
        add_btn.setToolTip("添加词库项")
        layout.addWidget(add_btn)

        # 删除按钮(使用表情符号)
        del_btn = QPushButton("🗑️")
        del_btn.clicked.connect(lambda: self.remove_library_item(category))
        del_btn.setFixedWidth(40)
        del_btn.setToolTip("删除词库项")
        layout.addWidget(del_btn)

        # 锁定/解锁按钮(使用表情符号)
        lock_btn = QPushButton("🔓")
        lock_btn.clicked.connect(lambda: self.toggle_field_lock(category))
        lock_btn.setFixedWidth(40)
        lock_btn.setToolTip("锁定/解锁字段")
        self.lock_buttons[category] = lock_btn
        layout.addWidget(lock_btn)

        widget.setLayout(layout)
        return widget

    def update_prompt_preview(self):
        """实时更新 prompt 预览"""
        form_data = {}
        for category, combo in self.combo_boxes.items():
            form_data[category] = combo.currentText()

        prompt = PromptAssembler.assemble(form_data)
        self.prompt_preview.setPlainText(prompt)

    def add_library_item(self, category: str):
        """添加词库项 UI"""
        value, ok = QInputDialog.getText(
            self,
            f"添加{category}词库项",
            f"请输入新的{category}词条(纯中文):",
            QLineEdit.Normal
        )

        if ok and value.strip():
            value = value.strip()
            try:
                self.library_manager.add_item(category, value)
                # 刷新下拉框
                self.refresh_combo_box(category)
                QMessageBox.information(self, "成功", f"已添加词库项: {value}")
            except Exception as e:
                self.logger.error(f"添加词库项失败: {e}")
                QMessageBox.warning(self, "错误", f"添加失败: {e}")
        else:
            self.logger.info(f"用户取消了添加{category}词库项的操作")

    def remove_library_item(self, category: str):
        """删除词库项 UI"""
        combo = self.combo_boxes.get(category)
        if not combo:
            return

        current_value = combo.currentText()
        if not current_value:
            QMessageBox.warning(self, "提示", "请先选择要删除的词库项")
            return

        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除词库项 \"{current_value}\" 吗?",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                self.library_manager.remove_item(category, current_value)
                # 刷新下拉框
                self.refresh_combo_box(category)
                QMessageBox.information(self, "成功", f"已删除词库项: {current_value}")
            except Exception as e:
                QMessageBox.warning(self, "错误", f"删除失败: {e}")

    def reset_category_library(self, category: str):
        """恢复单个类别的默认词库 UI"""
        reply = QMessageBox.question(
            self,
            "确认恢复",
            f"确定要恢复 \"{category}\" 的默认词库吗?\n这将删除所有自定义词条。",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                self.library_manager.reset_category(category)
                # 刷新下拉框
                self.refresh_combo_box(category)
                QMessageBox.information(self, "成功", f"已恢复 {category} 的默认词库")
            except Exception as e:
                QMessageBox.warning(self, "错误", f"恢复失败: {e}")

    def reset_all_library(self):
        """恢复所有字段的默认词库 UI"""
        reply = QMessageBox.question(
            self,
            "确认恢复所有默认词库",
            "确定要恢复所有字段的默认词库吗?\n这将删除所有自定义词条。",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                self.library_manager.reset_all()
                # 刷新所有下拉框
                for category in self.categories:
                    self.refresh_combo_box(category)
                QMessageBox.information(self, "成功", "已恢复所有默认词库")
            except Exception as e:
                QMessageBox.warning(self, "错误", f"恢复失败: {e}")

    def open_fullsize_view(self, event):
        """双击打开完整尺寸查看器"""
        if not self.generated_image_bytes:
            QMessageBox.warning(self, "提示", "没有可预览的图片")
            return

        # 保存为临时文件并使用系统查看器打开
        import tempfile
        with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp_file:
            tmp_file.write(self.generated_image_bytes)
            temp_path = Path(tmp_file.name)

        # 使用系统默认程序打开
        QDesktopServices.openUrl(QUrl.fromLocalFile(str(temp_path)))

    def refresh_combo_box(self, category: str):
        """刷新指定类别的下拉框"""
        combo = self.combo_boxes.get(category)
        if not combo:
            return

        # 保存当前选中值
        current_value = combo.currentText()

        # 清空并重新加载
        combo.clear()
        combo.addItem("")  # 空选项
        items = self.library_manager.library.get(category, [])
        combo.addItems(items)

        # 尝试恢复选中值
        index = combo.findText(current_value)
        if index >= 0:
            combo.setCurrentIndex(index)
        else:
            combo.setCurrentIndex(0)

    def toggle_field_lock(self, category: str):
        """切换字段锁定状态"""
        if category in self.locked_fields:
            # 解锁
            self.locked_fields.remove(category)
            button = self.lock_buttons[category]
            button.setText("🔓")
            button.setToolTip("字段已解锁")
        else:
            # 锁定
            self.locked_fields.add(category)
            button = self.lock_buttons[category]
            button.setText("🔒")
            button.setToolTip("字段已锁定")

    def generate_image(self):
        """Submit image generation task to queue"""
        from task_queue import TaskType

        # 获取 prompt
        prompt = self.prompt_preview.toPlainText()
        if not prompt.strip():
            QMessageBox.warning(self, "提示", "Prompt 不能为空")
            return

        # 获取设置
        aspect_ratio = self.aspect_ratio.currentText()
        image_size = self.image_size.currentText()
        model = "gemini-3-pro-image-preview"

        # 获取父窗口的 API key
        if not hasattr(self.parent_window, 'api_key') or not self.parent_window.api_key:
            QMessageBox.warning(self, "错误", "未找到 API 密钥,请在主窗口配置")
            return

        try:
            # Submit task to queue
            import socket
            task_id = self.parent_window.task_manager.submit_task(
                task_type=TaskType.STYLE_DESIGN,
                prompt=prompt,
                api_key=self.parent_window.api_key,
                reference_images=[],
                aspect_ratio=aspect_ratio,
                image_size=image_size,
                model=model,
                user_name=self.parent_window.authenticated_user,
                device_name=socket.gethostname()
            )

            # Connect to task completion signal
            self.parent_window.task_manager.task_completed.connect(
                lambda tid, img, p, refs, ar, size, mdl:
                    self._on_my_task_completed(task_id, tid, img, p, refs, ar, size, mdl)
            )

            # Update UI
            self.status_label.setText(f"● 任务已提交 (ID: {task_id[:8]})")

        except RuntimeError as e:
            QMessageBox.warning(self, "队列已满", str(e))

    def _on_my_task_completed(self, my_task_id, task_id, image_bytes, prompt,
                             reference_images, aspect_ratio, image_size, model):
        """Handle completion of my submitted task"""
        if my_task_id != task_id:
            return  # Not my task

        # Update display
        self.generated_image_bytes = image_bytes
        self._display_generated_image_from_bytes()
        self.status_label.setText("● 生成成功")

        # Save to history
        try:
            self.parent_window.history_manager.save_generation(
                image_bytes=image_bytes,
                prompt=prompt,
                reference_images=reference_images,
                aspect_ratio=aspect_ratio,
                image_size=image_size,
                model=model
            )
            self.parent_window.refresh_history()
        except Exception as e:
            self.logger.warning(f"保存到历史记录失败: {e}")

    def on_generation_success(self, image_bytes: bytes):
        """生成成功回调"""
        # 恢复按钮状态
        self.generate_btn.setEnabled(True)
        self.status_label.setText("● 就绪")

        self.generated_image_bytes = image_bytes

        # 启用下载按钮
        self.download_btn.setEnabled(True)

        # 显示图片
        pixmap = QPixmap()
        pixmap.loadFromData(image_bytes)

        # 清除之前的文本
        self.result_label.setText("")

        # 获取标签可用空间
        label_size = self.result_label.size()
        if label_size.width() < 100 or label_size.height() < 100:
            # 如果标签还没有正确的尺寸,使用默认尺寸
            label_size = QSize(400, 300)

        # 缩放图片以适应显示区域,保持宽高比且完整显示
        scaled_pixmap = pixmap.scaled(
            label_size,
            Qt.KeepAspectRatio,
            Qt.SmoothTransformation
        )

        # 设置缩放后的图片,并确保居中对齐
        self.result_label.setPixmap(scaled_pixmap)
        self.result_label.setAlignment(Qt.AlignCenter)

        # 保存到历史记录
        try:
            # 添加到历史记录管理器
            if hasattr(self.parent_window, 'history_manager'):
                timestamp = self.parent_window.history_manager.save_generation(
                    image_bytes=image_bytes,
                    prompt=self.prompt_preview.toPlainText(),
                    reference_images=[],  # 款式设计无参考图
                    aspect_ratio=self.aspect_ratio.currentText(),
                    image_size=self.image_size.currentText(),
                    model="gemini-3-pro-image-preview"
                )
                self.logger.info(f"款式设计已添加到历史记录: {timestamp}")

                # 刷新历史记录列表
                if hasattr(self.parent_window, 'refresh_history'):
                    self.parent_window.refresh_history()
            else:
                self.logger.warning("未找到历史记录管理器")

        except Exception as e:
            self.logger.error(f"保存历史记录失败: {e}")

        # 更新状态提示
        self.status_label.setText("● 图片生成成功")
        self.status_label.setStyleSheet("QLabel { color: #34C759; }")

    def on_generation_error(self, error_msg: str):
        """生成失败回调"""
        # 恢复按钮状态
        self.generate_btn.setEnabled(True)
        self.status_label.setText("● 就绪")
        QMessageBox.critical(self, "生成失败", error_msg)

    def _display_generated_image_from_bytes(self):
        """从字节数据显示生成的图片"""
        if not self.generated_image_bytes:
            return

        try:
            pixmap = QPixmap()
            pixmap.loadFromData(self.generated_image_bytes)

            if not pixmap.isNull():
                # 缩放以适应标签大小
                scaled_pixmap = pixmap.scaled(
                    self.result_label.size(),
                    Qt.KeepAspectRatio,
                    Qt.SmoothTransformation
                )
                self.result_label.setPixmap(scaled_pixmap)
                self.result_label.setStyleSheet("""
                    QLabel {
                        border: 1px solid #ddd;
                        background-color: white;
                    }
                """)
                # 启用下载按钮
                self.download_btn.setEnabled(True)
        except Exception as e:
            self.logger.error(f"显示图片失败: {e}")

    def download_image(self):
        """下载图片"""
        if not self.generated_image_bytes:
            QMessageBox.warning(self, "提示", "没有可下载的图片")
            return

        file_path, _ = QFileDialog.getSaveFileName(
            self,
            "保存图片",
            f"jewelry_design_{datetime.now().strftime('%Y%m%d%H%M%S')}.png",
            "PNG Files (*.png)"
        )

        if file_path:
            try:
                with open(file_path, 'wb') as f:
                    f.write(self.generated_image_bytes)
                # 使用状态栏提示而不是弹窗
                self.status_label.setText("● 图片已保存")
                self.status_label.setStyleSheet("QLabel { color: #34C759; }")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"保存失败: {e}")

    def preview_image(self):
        """预览大图"""
        if not self.generated_image_bytes:
            QMessageBox.warning(self, "提示", "没有可预览的图片")
            return

        # 创建预览对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("预览大图")
        dialog.resize(800, 600)

        layout = QVBoxLayout()

        # 图片标签
        label = QLabel()
        pixmap = QPixmap()
        pixmap.loadFromData(self.generated_image_bytes)
        label.setPixmap(pixmap)
        label.setScaledContents(True)

        # 滚动区域
        scroll = QScrollArea()
        scroll.setWidget(label)
        scroll.setWidgetResizable(True)
        layout.addWidget(scroll)

        # 关闭按钮
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(dialog.close)
        layout.addWidget(close_btn)

        dialog.setLayout(layout)
        dialog.exec()


def main():
    """Main application entry point"""
    # 初始化日志系统
    if not init_logging():
        print("警告:日志系统初始化失败,将继续运行但不记录日志")

    # Load config for database info
    config_dir = Path('.')
    if getattr(sys, 'frozen', False):
        system = platform.system()
        if system == 'Darwin':
            config_dir = Path.home() / 'Library' / 'Application Support' / 'ZB100ImageGenerator'
        elif system == 'Windows':
            config_dir = Path(os.getenv('APPDATA', Path.home())) / 'ZB100ImageGenerator'
        else:
            config_dir = Path.home() / '.config' / 'zb100imagegenerator'

    config_dir.mkdir(parents=True, exist_ok=True)
    config_path = config_dir / 'config.json'

    # Always try to ensure user config exists - copy from bundled if needed
    if not config_path.exists():
        if getattr(sys, 'frozen', False):
            # Running as bundled app - look for bundled config
            bundled_config = None

            if platform.system() == 'Darwin':
                # macOS: Contents/Resources/config.json
                bundled_config = Path(sys.executable).parent.parent / 'Resources' / 'config.json'
            else:
                # Windows/Linux: same directory as executable
                bundled_config = Path(sys.executable).parent / 'config.json'

            # Also try _MEIPASS directory (PyInstaller temp directory)
            if not bundled_config.exists():
                meipass_bundled = Path(sys._MEIPASS) / 'config.json'
                if meipass_bundled.exists():
                    bundled_config = meipass_bundled

            if bundled_config and bundled_config.exists():
                try:
                    # Create config directory if it doesn't exist
                    config_path.parent.mkdir(parents=True, exist_ok=True)
                    shutil.copy2(bundled_config, config_path)
                    print(f"✓ Copied config from {bundled_config} to {config_path}")
                except Exception as e:
                    print(f"✗ Failed to copy bundled config: {e}")
                    # If copy fails, try to use bundled config directly
                    config_path = bundled_config
            else:
                print(f"✗ Bundled config not found at {bundled_config}")
                # Try to use current directory config as fallback
                current_dir_config = Path('.') / 'config.json'
                if current_dir_config.exists():
                    config_path = current_dir_config
                    print(f"✓ Using current directory config: {config_path}")
                else:
                    print(f"✗ No config file found at all")

    db_config = None
    last_user = ""
    saved_password_hash = ""

    if config_path.exists():
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
                db_config = config.get("db_config")
                last_user = config.get("last_user", "")
                saved_password_hash = config.get("saved_password_hash", "")
        except Exception as e:
            print(f"Failed to load config: {e}")

    # Create QApplication
    app = QApplication(sys.argv)

    # Set application icon
    if getattr(sys, 'frozen', False):
        # Running as compiled executable
        if platform.system() == 'Windows':
            icon_path = os.path.join(sys._MEIPASS, 'zb100_windows.ico')
        elif platform.system() == 'Darwin':
            icon_path = os.path.join(sys._MEIPASS, 'zb100_mac.icns')
        else:
            icon_path = None
    else:
        # Running as script
        if platform.system() == 'Windows':
            icon_path = 'zb100_windows.ico'
        elif platform.system() == 'Darwin':
            icon_path = 'zb100_mac.icns'
        else:
            icon_path = None

    if icon_path and os.path.exists(icon_path):
        app_icon = QIcon(icon_path)
        app.setWindowIcon(app_icon)

    # Check database config - if missing, start app without database authentication
    if not db_config:
        print("警告:未找到数据库配置,将跳过数据库认证")
        # Create main window directly without login
        main_window = ImageGeneratorWindow()
        main_window.show()
        sys.exit(app.exec())

    # Show login dialog
    login_dialog = LoginDialog(db_config, last_user, saved_password_hash)

    if login_dialog.exec() == QDialog.Accepted:
        # Login successful
        authenticated_user = login_dialog.authenticated_user
        remember_user = login_dialog.get_remember_user()
        remember_password = login_dialog.get_remember_password()
        password_hash = login_dialog.get_password_hash()

        # Save/clear credentials
        if config_path.exists():
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)

                if remember_user:
                    config["last_user"] = authenticated_user
                else:
                    config["last_user"] = ""

                if remember_password:
                    config["saved_password_hash"] = password_hash
                else:
                    config["saved_password_hash"] = ""

                with open(config_path, 'w', encoding='utf-8') as f:
                    json.dump(config, f, indent=2, ensure_ascii=False)
            except Exception as e:
                print(f"Failed to save config: {e}")

        # Show main window
        main_window = ImageGeneratorWindow()
        main_window.authenticated_user = authenticated_user  # 设置登录用户名
        main_window.show()

        sys.exit(app.exec())
    else:
        # Login cancelled or failed
        sys.exit(0)


if __name__ == "__main__":
    main()