Spaces:
Sleeping
Sleeping
File size: 76,127 Bytes
2a32f00 a390f1a e6e4cd6 7c6b9af 77fc327 a359bcb 8b919e0 b4fd17f df9b2c4 8b919e0 c819f6a c4bb4cb e6e4cd6 a359bcb 864df9b a359bcb a390f1a 63e6b9a 7c6b9af 500c24f a359bcb 38eda2f a359bcb 500c24f 7c6b9af a359bcb 38eda2f 7c6b9af a359bcb 38eda2f 7c6b9af a359bcb 38eda2f 7c6b9af a359bcb 38eda2f 8b919e0 1b3b3ad 63e6b9a ce448b5 a359bcb ce448b5 a359bcb ce448b5 8b919e0 1fe96b2 a359bcb 1fe96b2 e6e4cd6 1fe96b2 500c24f e6e4cd6 a359bcb e6e4cd6 a359bcb e6e4cd6 a359bcb e6e4cd6 a359bcb 1fe96b2 e6e4cd6 a359bcb e6e4cd6 a359bcb 7c6b9af a359bcb e6e4cd6 a359bcb e6e4cd6 1b3b3ad a359bcb e6e4cd6 c3b4e1f 2a32f00 38eda2f a359bcb 373b35d 63e6b9a c4bb4cb a359bcb 98a25c5 a359bcb 51849f1 c4bb4cb 373b35d a359bcb 373b35d a359bcb c4bb4cb a359bcb c4bb4cb a359bcb c4bb4cb a359bcb c4bb4cb 98a25c5 a359bcb 864df9b 1b3b3ad 864df9b a359bcb 864df9b a359bcb 98a25c5 a359bcb 373b35d a359bcb 34e013d 98a25c5 a359bcb 98a25c5 a359bcb 98a25c5 34e013d c4bb4cb 38eda2f 98a25c5 38eda2f bd4b9f2 98a25c5 c4bb4cb bd4b9f2 1fe96b2 373b35d a359bcb bd4b9f2 a359bcb 98a25c5 a359bcb bd4b9f2 373b35d a359bcb c4bb4cb a359bcb 373b35d a359bcb 38eda2f a359bcb 38eda2f 98a25c5 1fe96b2 34e013d 1fe96b2 a359bcb 373b35d c4bb4cb a359bcb 373b35d a359bcb c4bb4cb a359bcb 373b35d a359bcb 98a25c5 373b35d 1fe96b2 98a25c5 a359bcb c4bb4cb 397b649 a359bcb e0103ae 373b35d c4bb4cb 34e013d a359bcb c4bb4cb a359bcb c4bb4cb 6c01b01 a359bcb 1fe96b2 a359bcb 1fe96b2 397b649 373b35d c4bb4cb 1fe96b2 a359bcb c4bb4cb 1fe96b2 a359bcb 6c01b01 373b35d a359bcb 1fe96b2 6c01b01 a359bcb 6c01b01 a359bcb 34e013d a359bcb c4bb4cb a359bcb c4bb4cb 1fe96b2 373b35d a359bcb c4bb4cb 98a25c5 51849f1 c4bb4cb a359bcb c4bb4cb a359bcb c4bb4cb a359bcb 6c01b01 a359bcb 373b35d 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb daa7bba 0318b2a daa7bba 0318b2a 373b35d a359bcb daa7bba a359bcb 98a25c5 373b35d a359bcb 373b35d a359bcb 1fe96b2 a359bcb 51849f1 daa7bba a359bcb 373b35d 1fe96b2 a359bcb 51849f1 98a25c5 daa7bba a359bcb 34e013d 0318b2a 51849f1 a359bcb 51849f1 98a25c5 a359bcb 51849f1 34e013d 98a25c5 a359bcb 0318b2a a359bcb 34e013d a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1b3b3ad a359bcb a4eb49c a359bcb a4eb49c a359bcb a4eb49c 10d0a8a 1fe96b2 10d0a8a a359bcb 373b35d 1fe96b2 1b3b3ad a359bcb 1b3b3ad 1fe96b2 a359bcb 1fe96b2 a359bcb 1b3b3ad a359bcb 1b3b3ad a359bcb 1b3b3ad a359bcb 1b3b3ad a359bcb 1b3b3ad a359bcb 1fe96b2 a359bcb 1b3b3ad 1fe96b2 1b3b3ad 1fe96b2 1b3b3ad 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 1b3b3ad a359bcb 1fe96b2 a359bcb 34e013d a359bcb c4bb4cb 98a25c5 a359bcb 98a25c5 38eda2f bd4b9f2 34e013d bd4b9f2 c4bb4cb 373b35d 38eda2f 51849f1 daa7bba 1fe96b2 373b35d daa7bba c4bb4cb 373b35d a359bcb 51849f1 1fe96b2 a359bcb daa7bba c4bb4cb 076b99d daa7bba 1b3b3ad daa7bba 0318b2a 1fe96b2 0318b2a 1b3b3ad 34e013d a4eb49c a359bcb 7003471 a359bcb c024b89 a359bcb a4eb49c 1b3b3ad 0318b2a 1b3b3ad a359bcb 1b3b3ad a359bcb 51849f1 daa7bba 1b3b3ad 0318b2a 1fe96b2 51849f1 daa7bba 0318b2a a4eb49c 0318b2a 98a25c5 a359bcb 98a25c5 a359bcb 98a25c5 daa7bba 51849f1 1b3b3ad 51849f1 0318b2a 34e013d 51849f1 daa7bba a359bcb 9eff9e1 a359bcb 1fe96b2 99c03dd a4eb49c c024b89 a359bcb c024b89 a359bcb c024b89 a359bcb c024b89 1b3b3ad 34e013d a4eb49c 98a25c5 a359bcb c024b89 7003471 1fe96b2 a359bcb bb97035 a359bcb bb97035 7003471 a359bcb 0318b2a a4eb49c a359bcb 1fe96b2 34e013d 1fe96b2 a359bcb 0318b2a 98a25c5 c024b89 0318b2a a359bcb c024b89 98a25c5 0318b2a bb97035 0318b2a a4eb49c 0318b2a a359bcb 0318b2a bb97035 1b3b3ad a359bcb 1b3b3ad a359bcb 1b3b3ad a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 1b3b3ad bb97035 a359bcb 7003471 1b3b3ad 0318b2a 10d0a8a a359bcb 10d0a8a a359bcb 10d0a8a a359bcb 10d0a8a a359bcb 1b3b3ad a359bcb 10d0a8a a4eb49c a359bcb 1fe96b2 a359bcb daa7bba 0318b2a 1b3b3ad a359bcb 1b3b3ad 98a25c5 38eda2f 98a25c5 38eda2f 98a25c5 a359bcb 38eda2f a359bcb bd4b9f2 38eda2f bd4b9f2 a359bcb 1b3b3ad a359bcb 1fe96b2 a359bcb daa7bba c4bb4cb 1b3b3ad 4051dff 38eda2f a359bcb da6d436 4051dff a359bcb 4051dff a359bcb 99c03dd a359bcb 0318b2a a359bcb 0318b2a 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 da6d436 4051dff da6d436 2a32f00 38eda2f a359bcb 34e013d 38eda2f 2a32f00 9425d2e 373b35d 38eda2f 1fe96b2 a359bcb 38eda2f a359bcb 38eda2f 373b35d a359bcb 1fe96b2 38eda2f 1b3b3ad a359bcb 1b3b3ad a359bcb 4051dff 24d83f7 a359bcb 373b35d 1b3b3ad a359bcb 34e013d 373b35d a359bcb 373b35d a359bcb 1b3b3ad a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 373b35d 500c24f a359bcb c024b89 a359bcb 500c24f a359bcb 38eda2f 373b35d c4bb4cb 373b35d a359bcb 1b3b3ad 373b35d a359bcb 1fe96b2 373b35d c4bb4cb 373b35d a359bcb 373b35d a359bcb 373b35d a359bcb c4bb4cb a359bcb c4bb4cb a359bcb 98a25c5 1fe96b2 98a25c5 a9bbef6 864df9b a359bcb 373b35d 864df9b a359bcb 864df9b a359bcb 864df9b 34e013d 1fe96b2 a359bcb 1fe96b2 38eda2f a359bcb 98a25c5 a359bcb a9bbef6 a359bcb 1fe96b2 a359bcb 98a25c5 c4bb4cb a359bcb 1fe96b2 a359bcb c4bb4cb a359bcb c4bb4cb 1fe96b2 a359bcb 1fe96b2 98a25c5 1fe96b2 7003471 a359bcb 34e013d 1b3b3ad a359bcb 98a25c5 c4bb4cb a359bcb c4bb4cb 1fe96b2 a359bcb 98a25c5 a359bcb c4bb4cb 1fe96b2 a359bcb 1fe96b2 38eda2f a359bcb 1fe96b2 38eda2f a359bcb 98a25c5 1fe96b2 c4bb4cb a359bcb 1fe96b2 a359bcb 373b35d a359bcb 373b35d a359bcb 373b35d a359bcb 373b35d a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb c4bb4cb 1fe96b2 a359bcb 1fe96b2 a359bcb 397b649 c024b89 a359bcb 7003471 a359bcb 1b3b3ad a359bcb c024b89 a359bcb c024b89 a359bcb 34e013d a359bcb c024b89 1fe96b2 864df9b a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1b3b3ad c4bb4cb 1b3b3ad 98a25c5 a359bcb 864df9b 1b3b3ad a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1fe96b2 a359bcb 1b3b3ad a359bcb 1fe96b2 a359bcb c024b89 a359bcb 1fe96b2 38eda2f a359bcb 1fe96b2 51849f1 1b3b3ad 1fe96b2 98a25c5 a359bcb 98a25c5 a359bcb 98a25c5 a359bcb 24d83f7 a359bcb 1b3b3ad 24d83f7 98a25c5 1b3b3ad 1fe96b2 98a25c5 a359bcb 98a25c5 7003471 98a25c5 1fe96b2 a359bcb c024b89 a359bcb c024b89 a359bcb 7003471 a359bcb 7003471 c024b89 a359bcb 1fe96b2 a359bcb 98a25c5 a359bcb 98a25c5 c4bb4cb a359bcb c4bb4cb 98a25c5 a359bcb c4bb4cb c024b89 1b3b3ad c024b89 7003471 373b35d 7003471 373b35d 7003471 a359bcb 7003471 373b35d 7003471 1b3b3ad c024b89 c4bb4cb 1b3b3ad c4bb4cb 1fe96b2 a359bcb 1fe96b2 c4bb4cb a359bcb c4bb4cb 34e013d 1b3b3ad 34e013d a359bcb 34e013d a359bcb 34e013d 1b3b3ad a359bcb 1b3b3ad a359bcb 34e013d 0318b2a |
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 |
import json
import os
import logging
import threading
import time
from datetime import datetime
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError
from werkzeug.utils import secure_filename
from flask import Flask, render_template_string, request, redirect, url_for
app = Flask(__name__)
DATA_FILE = 'data.json'
REPO_ID = "Kgshop/zalkar"
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
LOGO_URL = "https://cdn-avatars.huggingface.co/v1/production/uploads/67c280ccb9d3dfdee58ecfdd/4IIqefkClYrsa2euUC_Nh.jpeg"
logging.basicConfig(level=logging.DEBUG)
def load_data():
try:
download_db_from_hf()
with open(DATA_FILE, 'r', encoding='utf-8') as file:
data = json.load(file)
logging.info("Данные успешно загружены из JSON")
if not isinstance(data, dict) or 'products' not in data or 'categories' not in data:
# Handle cases where the data structure is not as expected
products = data if isinstance(data, list) else []
categories = []
# Attempt to find categories if products have a 'category' key
if products:
all_categories = {p.get('category') for p in products if p.get('category')}
categories = sorted(list(all_categories))
return {'products': products, 'categories': categories}
return data
except FileNotFoundError:
logging.warning("Локальный файл базы данных не найден после скачивания.")
return {'products': [], 'categories': []}
except json.JSONDecodeError:
logging.error("Ошибка: Невозможно декодировать JSON файл.")
return {'products': [], 'categories': []}
except RepositoryNotFoundError:
logging.error("Репозиторий не найден. Создание локальной базы данных.")
return {'products': [], 'categories': []}
except Exception as e:
logging.error(f"Произошла ошибка при загрузке данных: {e}")
return {'products': [], 'categories': []}
def save_data(data):
try:
with open(DATA_FILE, 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
logging.info("Данные успешно сохранены в JSON")
upload_db_to_hf()
except Exception as e:
logging.error(f"Ошибка при сохранении данных: {e}")
raise
def upload_db_to_hf():
if not HF_TOKEN_WRITE or not REPO_ID:
logging.warning("HF_TOKEN_WRITE или REPO_ID не установлены. Пропуск загрузки резервной копии.")
return
try:
api = HfApi()
api.upload_file(
path_or_fileobj=DATA_FILE,
path_in_repo=DATA_FILE,
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Автоматическое резервное копирование базы данных {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
)
logging.info("Резервная копия JSON базы успешно загружена на Hugging Face.")
except Exception as e:
logging.error(f"Ошибка при загрузке резервной копии: {e}")
def download_db_from_hf():
if not REPO_ID or not (HF_TOKEN_READ or HF_TOKEN_WRITE):
logging.warning("REPO_ID и/или токены Hugging Face не установлены. Пропуск скачивания базы данных.")
return
try:
hf_hub_download(
repo_id=REPO_ID,
filename=DATA_FILE,
repo_type="dataset",
token=HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE,
local_dir=".",
local_dir_use_symlinks=False
)
logging.info("JSON база успешно скачана из Hugging Face.")
except RepositoryNotFoundError as e:
logging.error(f"Репозиторий не найден: {e}")
# Decide if you want to create an empty local file or raise
if not os.path.exists(DATA_FILE):
logging.info(f"Создание пустого локального файла {DATA_FILE}.")
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump({'products': [], 'categories': []}, f)
raise # Re-raise to be caught by load_data
except Exception as e:
logging.error(f"Ошибка при скачивании JSON базы: {e}")
raise # Re-raise to be caught by load_data
def periodic_backup():
while True:
upload_db_to_hf()
time.sleep(800)
@app.route('/')
def catalog():
data = load_data()
products = data['products']
categories = data['categories']
catalog_html = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zalkar Textile - ткани на заказ </title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
<style>
:root {
--primary-color: #4a6e68; /* Deep Teal */
--secondary-color: #e0baa1; /* Muted Peach */
--background-color: #f8f5f0; /* Off-white/Linen */
--card-background: #ffffff;
--text-color: #333333;
--subtle-text: #666666;
--border-color: #e0e0e0;
--shadow-color: rgba(0, 0, 0, 0.1);
--error-color: #cc3300;
--success-color: #4CAF50;
}
body.dark-mode {
--primary-color: #81b29a; /* Lighter Teal */
--secondary-color: #f4f1de; /* Cream */
--background-color: #3d405b; /* Dark Blue-Gray */
--card-background: #455a64; /* Darker Blue-Gray */
--text-color: #f4f1de;
--subtle-text: #b0bec5;
--border-color: #5a6e78;
--shadow-color: rgba(255, 255, 255, 0.08);
--error-color: #ef9a9a;
--success-color: #a5d6a7;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
background-color: var(--background-color);
color: var(--text-color);
line-height: 1.6;
transition: background 0.5s ease, color 0.5s ease;
}
.container {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 0;
border-bottom: 1px solid var(--border-color);
margin-bottom: 30px;
}
.header-logo {
width: 70px;
height: 70px;
border-radius: 50%;
object-fit: cover;
box-shadow: 0 5px 20px var(--shadow-color);
transition: transform 0.4s ease, box-shadow 0.4s ease;
margin-right: 15px;
}
.header-logo:hover {
transform: scale(1.1);
box-shadow: 0 8px 25px var(--shadow-color);
}
.header h1 {
font-family: 'Playfair Display', serif;
font-size: 2rem;
font-weight: 700;
flex-grow: 1;
}
.theme-toggle {
background: none;
border: none;
font-size: 1.8rem;
cursor: pointer;
color: var(--text-color);
transition: color 0.3s ease;
}
.theme-toggle:hover {
color: var(--primary-color);
}
.filters-container {
margin: 20px 0;
display: flex;
flex-wrap: wrap;
gap: 10px;
justify-content: center;
}
.search-container {
margin: 20px 0;
text-align: center;
}
#search-input {
width: 95%;
max-width: 700px;
padding: 14px 20px;
font-size: 1.1rem;
border: 1px solid var(--border-color);
border-radius: 10px;
outline: none;
box-shadow: 0 2px 8px var(--shadow-color);
transition: all 0.3s ease;
background-color: var(--card-background);
color: var(--text-color);
}
#search-input:focus {
border-color: var(--primary-color);
box-shadow: 0 4px 15px rgba(var(--primary-color-rgb, 74, 110, 104), 0.3);
}
.category-filter {
padding: 10px 20px;
border: 1px solid var(--border-color);
border-radius: 10px;
background-color: var(--card-background);
color: var(--text-color);
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-size: 1rem;
font-weight: 400;
outline: none;
}
.category-filter.active, .category-filter:hover {
background-color: var(--primary-color);
color: white;
border-color: var(--primary-color);
box-shadow: 0 3px 12px var(--shadow-color);
}
.products-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 25px;
padding: 20px 0;
}
.product {
background: var(--card-background);
border-radius: 18px;
padding: 20px;
box-shadow: 0 5px 20px var(--shadow-color);
transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.4s ease;
overflow: hidden;
display: flex;
flex-direction: column;
}
.product:hover {
transform: translateY(-8px) scale(1.03);
box-shadow: 0 8px 25px var(--shadow-color);
}
.product-image {
width: 100%;
aspect-ratio: 4/3; /* Slightly wider than square */
background-color: #f0f0f0; /* Placeholder background */
border-radius: 12px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 15px;
}
.product-image img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
transition: transform 0.3s ease;
}
.product-image img:hover {
transform: scale(1.05);
}
.product h2 {
font-family: 'Playfair Display', serif;
font-size: 1.3rem;
font-weight: 700;
margin: 0 0 8px 0;
text-align: center;
color: var(--primary-color);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-price {
font-size: 1.2rem;
color: var(--error-color);
font-weight: 700;
text-align: center;
margin: 0 0 10px 0;
}
.product-description {
font-size: 0.9rem;
color: var(--subtle-text);
text-align: center;
margin-bottom: 15px;
flex-grow: 1;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2; /* Limit description to 2 lines */
-webkit-box-orient: vertical;
}
.button-group {
display: flex;
gap: 10px;
margin-top: auto; /* Push buttons to the bottom */
}
.product-button {
flex: 1;
padding: 12px;
border: none;
border-radius: 8px;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
text-align: center;
text-decoration: none;
display: inline-block; /* Ensure padding works */
}
.product-button.details-button {
background-color: var(--secondary-color);
color: var(--text-color);
}
.product-button.details-button:hover {
background-color: #cfa690; /* Darken secondary */
box-shadow: 0 4px 15px rgba(var(--secondary-color-rgb, 224, 186, 161), 0.4);
transform: translateY(-2px);
}
.product-button.add-to-cart {
background-color: var(--primary-color);
color: white;
}
.product-button.add-to-cart:hover {
background-color: #3a5e58; /* Darken primary */
box-shadow: 0 4px 15px rgba(var(--primary-color-rgb, 74, 110, 104), 0.4);
transform: translateY(-2px);
}
#cart-button {
position: fixed;
bottom: 30px;
right: 30px;
background-color: var(--error-color);
color: white;
border: none;
border-radius: 50%;
width: 60px;
height: 60px;
font-size: 1.5rem;
cursor: pointer;
display: none; /* Initially hidden */
box-shadow: 0 5px 20px rgba(var(--error-color-rgb, 204, 51, 0), 0.4);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 1000;
display: flex;
justify-content: center;
align-items: center;
}
#cart-button:hover {
background-color: #b32d00; /* Darken error color */
box-shadow: 0 6px 25px rgba(var(--error-color-rgb, 204, 51, 0), 0.5);
transform: scale(1.1);
}
.modal {
display: none;
position: fixed;
z-index: 1001;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.6);
backdrop-filter: blur(8px);
overflow: auto; /* Add scroll for long content */
}
.modal-content {
background: var(--card-background);
margin: 5% auto;
padding: 30px;
border-radius: 18px;
width: 95%;
max-width: 800px;
box-shadow: 0 15px 40px var(--shadow-color);
animation: slideIn 0.4s ease-out;
color: var(--text-color);
}
@keyframes slideIn {
from { transform: translateY(-80px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.close {
float: right;
font-size: 2rem;
font-weight: bold;
color: var(--subtle-text);
cursor: pointer;
transition: color 0.3s;
}
.close:hover {
color: var(--text-color);
}
.cart-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid var(--border-color);
}
.cart-item:last-child {
border-bottom: none;
}
.cart-item img {
width: 60px;
height: 60px;
object-fit: contain;
border-radius: 8px;
margin-right: 15px;
background-color: #eee; /* Placeholder */
}
.cart-item-info {
flex-grow: 1;
margin-right: 10px;
}
.cart-item-info strong {
display: block;
font-size: 1.1rem;
margin-bottom: 5px;
}
.cart-item-info p {
font-size: 0.9rem;
color: var(--subtle-text);
}
.cart-item span {
font-size: 1.1rem;
font-weight: 700;
color: var(--primary-color);
}
.quantity-input, .color-select {
width: 100%;
max-width: 200px; /* Increased width */
padding: 10px;
border: 1px solid var(--border-color);
border-radius: 8px;
font-size: 1rem;
margin: 10px 0;
background-color: var(--background-color);
color: var(--text-color);
}
#quantityModal h2 {
margin-bottom: 15px;
font-size: 1.5rem;
}
#quantityModal button {
width: 100%;
background-color: var(--success-color);
margin-top: 20px;
}
#quantityModal button:hover {
background-color: #388E3C; /* Darken success */
box-shadow: 0 4px 15px rgba(var(--success-color-rgb, 76, 175, 80), 0.4);
}
.cart-total {
margin-top: 30px;
text-align: right;
font-size: 1.4rem;
font-weight: 700;
color: var(--primary-color);
}
.cart-actions {
margin-top: 20px;
text-align: right;
}
.cart-actions button {
margin-left: 10px;
margin-top: 10px; /* Allow stacking on small screens */
width: auto; /* Reset width */
}
.clear-cart {
background-color: var(--error-color);
}
.clear-cart:hover {
background-color: #b32d00;
box-shadow: 0 4px 15px rgba(var(--error-color-rgb, 204, 51, 0), 0.4);
}
.order-button {
background-color: var(--success-color);
}
.order-button:hover {
background-color: #388E3C;
box-shadow: 0 4px 15px rgba(var(--success-color-rgb, 76, 175, 80), 0.4);
}
/* Responsive Adjustments */
@media (max-width: 768px) {
.header h1 {
font-size: 1.8rem;
}
.header-logo {
width: 50px;
height: 50px;
}
.theme-toggle {
font-size: 1.5rem;
}
.products-grid {
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}
.product {
padding: 15px;
}
.product h2 {
font-size: 1.2rem;
}
.product-price {
font-size: 1.1rem;
}
.product-description {
font-size: 0.85rem;
}
.product-button {
padding: 10px;
font-size: 0.85rem;
}
.button-group {
flex-direction: column;
gap: 8px;
}
.button-group .product-button {
width: 100%;
}
.modal-content {
padding: 20px;
margin: 10% auto;
}
.close {
font-size: 1.8rem;
}
.cart-item {
flex-direction: column;
align-items: flex-start;
padding: 10px 0;
}
.cart-item img {
margin-bottom: 10px;
}
.cart-item-info {
width: 100%;
margin-right: 0;
}
.cart-item span {
width: 100%;
text-align: right;
margin-top: 10px;
}
.cart-actions {
text-align: center;
}
.cart-actions button {
margin: 5px auto;
display: block;
width: 80%;
max-width: 300px;
}
}
@media (max-width: 480px) {
.products-grid {
grid-template-columns: 1fr; /* Stack products on very small screens */
}
.container {
padding: 10px;
}
.header {
padding: 10px 0;
}
.header h1 {
font-size: 1.5rem;
}
.header-logo {
width: 40px;
height: 40px;
}
.theme-toggle {
font-size: 1.3rem;
}
#search-input {
padding: 10px 15px;
font-size: 1rem;
}
.category-filter {
padding: 8px 15px;
font-size: 0.9rem;
}
.product {
padding: 15px;
}
.product h2 {
font-size: 1.1rem;
}
.product-price {
font-size: 1rem;
}
.product-description {
font-size: 0.8rem;
}
.product-button {
padding: 8px;
font-size: 0.8rem;
}
#cart-button {
width: 45px;
height: 45px;
font-size: 1.1rem;
bottom: 15px;
right: 15px;
}
.modal-content {
padding: 15px;
}
.close {
font-size: 1.5rem;
}
.cart-item img {
width: 40px;
height: 40px;
}
.cart-item-info strong {
font-size: 1rem;
}
.cart-item-info p {
font-size: 0.8rem;
}
.cart-item span {
font-size: 1rem;
}
.cart-total {
font-size: 1.2rem;
}
.cart-actions button {
width: 95%;
}
}
/* Define RGB variables for easier alpha manipulation */
body {
--primary-color-rgb: 74, 110, 104;
--secondary-color-rgb: 224, 186, 161;
--error-color-rgb: 204, 51, 0;
--success-color-rgb: 76, 175, 80;
}
body.dark-mode {
--primary-color-rgb: 129, 178, 154;
--secondary-color-rgb: 244, 241, 222;
--error-color-rgb: 239, 154, 154;
--success-color-rgb: 165, 214, 167;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<img src="''' + LOGO_URL + '''" alt="Logo" class="header-logo">
<h1>Zalkar Textile</h1>
<button class="theme-toggle" onclick="toggleTheme()">
<i class="fas fa-moon"></i>
</button>
</div>
<div class="filters-container">
<button class="category-filter active" data-category="all">Все категории</button>
{% for category in categories %}
<button class="category-filter" data-category="{{ category }}">{{ category }}</button>
{% endfor %}
</div>
<div class="search-container">
<input type="text" id="search-input" placeholder="Поиск товаров...">
</div>
<div class="products-grid" id="products-grid">
{% for product in products %}
<div class="product"
data-name="{{ product['name']|lower }}"
data-description="{{ product['description']|lower }}"
data-category="{{ product.get('category', 'Без категории') }}">
{% if product.get('photos') and product['photos']|length > 0 %}
<div class="product-image">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}"
alt="{{ product['name'] }}"
loading="lazy">
</div>
{% else %}
<div class="product-image">
<img src="https://via.placeholder.com/400x300?text=No+Image" alt="No image available">
</div>
{% endif %}
<h2>{{ product['name'] }}</h2>
<div class="product-price">{{ product['price'] }} $</div>
<p class="product-description">{{ product['description'] }}</p>
<div class="button-group">
<button class="product-button details-button" onclick="openModal({{ loop.index0 }})">Подробнее</button>
<button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})">В корзину</button>
</div>
</div>
{% endfor %}
</div>
</div>
<div id="productModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('productModal')">×</span>
<div id="modalContent"></div>
</div>
</div>
<div id="quantityModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('quantityModal')">×</span>
<h2>Укажите количество метров и цвет</h2>
<label for="quantityInput" style="font-weight: 500;">Количество метров:</label>
<input type="number" id="quantityInput" class="quantity-input" step="0.1" min="0.1" value="1">
<label for="colorSelect" style="font-weight: 500;">Цвет:</label>
<select id="colorSelect" class="color-select"></select>
<button class="product-button" onclick="confirmAddToCart()">Добавить</button>
</div>
</div>
<div id="cartModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('cartModal')">×</span>
<h2>Корзина</h2>
<div id="cartContent"></div>
<div class="cart-total">
<strong>Итого: <span id="cartTotal">0</span> $</strong>
</div>
<div class="cart-actions">
<button class="product-button clear-cart" onclick="clearCart()">Очистить корзину</button>
<button class="product-button order-button" onclick="orderViaWhatsApp()">Заказать через WhatsApp</button>
</div>
</div>
</div>
<button id="cart-button" onclick="openCartModal()">🛒</button>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
<script>
const products = {{ products|tojson }};
let selectedProductIndex = null;
function toggleTheme() {
document.body.classList.toggle('dark-mode');
const icon = document.querySelector('.theme-toggle i');
icon.classList.toggle('fa-moon');
icon.classList.toggle('fa-sun');
localStorage.setItem('theme', document.body.classList.contains('dark-mode') ? 'dark' : 'light');
}
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark-mode');
const icon = document.querySelector('.theme-toggle i');
if(icon) { // Check if icon exists before replacing class
icon.classList.replace('fa-moon', 'fa-sun');
}
}
function openModal(index) {
loadProductDetails(index);
document.getElementById('productModal').style.display = "block";
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = "none";
}
function loadProductDetails(index) {
fetch('/product/' + index)
.then(response => response.text())
.then(data => {
document.getElementById('modalContent').innerHTML = data;
initializeSwiper();
})
.catch(error => console.error('Ошибка загрузки деталей продукта:', error));
}
function initializeSwiper() {
// Check if a swiper container exists in the modal content
const swiperContainer = document.querySelector('#modalContent .swiper-container');
if (swiperContainer) {
new Swiper(swiperContainer, {
slidesPerView: 1,
spaceBetween: 20,
loop: true,
grabCursor: true,
pagination: { el: '.swiper-pagination', clickable: true },
navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
zoom: { maxRatio: 3 },
// Optional: Add keyboard control or other features
});
}
}
function openQuantityModal(index) {
selectedProductIndex = index;
const product = products[index];
const colorSelect = document.getElementById('colorSelect');
colorSelect.innerHTML = '';
if (product.colors && product.colors.length > 0) {
product.colors.forEach(color => {
const option = document.createElement('option');
option.value = color;
option.text = color;
colorSelect.appendChild(option);
});
} else {
const option = document.createElement('option');
option.value = 'Не указан'; // Change from 'Нет цвета' for clarity
option.text = 'Не указан';
colorSelect.appendChild(option);
}
document.getElementById('quantityModal').style.display = 'block';
document.getElementById('quantityInput').value = 1; // Reset quantity
}
function confirmAddToCart() {
if (selectedProductIndex === null) return;
const quantityInput = document.getElementById('quantityInput');
const quantity = parseFloat(quantityInput.value);
const color = document.getElementById('colorSelect').value;
if (isNaN(quantity) || quantity <= 0) {
alert("Укажите корректное количество метров больше 0");
quantityInput.classList.add('input-error'); // Optional: Add a visual error state
return;
} else {
quantityInput.classList.remove('input-error');
}
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
const product = products[selectedProductIndex];
// Using product name and color for a unique ID
const cartItemId = `${product.name.replace(/\s+/g, '_')}-${color}`; // Use replace for potential spaces
const existingItem = cart.find(item => item.id === cartItemId);
if (existingItem) {
existingItem.quantity = parseFloat((existingItem.quantity + quantity).toFixed(2)); // Ensure precision
} else {
cart.push({
id: cartItemId,
name: product.name,
price: product.price,
photo: product.photos && product.photos.length > 0 ? product.photos[0] : '',
quantity: parseFloat(quantity.toFixed(2)), // Ensure precision
color: color
});
}
localStorage.setItem('cart', JSON.stringify(cart));
closeModal('quantityModal');
updateCartButton();
}
function updateCartButton() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
document.getElementById('cart-button').style.display = cart.length > 0 ? 'flex' : 'none'; // Use flex for centering icon
}
function openCartModal() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
const cartContent = document.getElementById('cartContent');
let total = 0;
if (cart.length === 0) {
cartContent.innerHTML = '<p style="text-align: center; color: var(--subtle-text);">Корзина пуста</p>';
} else {
cartContent.innerHTML = cart.map(item => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
// Use placeholder image if photo is missing or invalid URL
const photoSrc = item.photo ? `https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}` : 'https://via.placeholder.com/60?text=No+Image';
return `
<div class="cart-item">
<img src="${photoSrc}" alt="${item.name}">
<div class="cart-item-info">
<strong>${item.name}</strong>
<p>${item.price} $ × ${item.quantity.toFixed(2)} метров (Цвет: ${item.color})</p>
</div>
<span>${itemTotal.toFixed(2)} $</span>
</div>
`;
}).join('');
}
document.getElementById('cartTotal').textContent = total.toFixed(2);
document.getElementById('cartModal').style.display = 'block';
}
function orderViaWhatsApp() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
if (cart.length === 0) {
alert("Корзина пуста!");
return;
}
let total = 0;
let orderText = "Заказ:%0A"; // %0A is newline for WhatsApp URL encoding
cart.forEach((item, index) => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
orderText += `${index + 1}. ${item.name} - ${item.price} $ × ${item.quantity.toFixed(2)} метров (Цвет: ${item.color})%0A`;
});
orderText += `Итого: ${total.toFixed(2)} $`;
// Ensure the phone number is correct
const phoneNumber = "996707842888";
window.open(`https://api.whatsapp.com/send?phone=${phoneNumber}&text=${orderText}`, '_blank');
}
function clearCart() {
if (confirm("Вы уверены, что хотите очистить корзину?")) {
localStorage.removeItem('cart');
closeModal('cartModal');
updateCartButton();
}
}
window.onclick = function(event) {
// Close modals if clicked outside the modal content
const productModal = document.getElementById('productModal');
const quantityModal = document.getElementById('quantityModal');
const cartModal = document.getElementById('cartModal');
if (event.target === productModal) {
productModal.style.display = "none";
}
if (event.target === quantityModal) {
quantityModal.style.display = "none";
}
if (event.target === cartModal) {
cartModal.style.display = "none";
}
}
document.getElementById('search-input').addEventListener('input', filterProducts);
document.querySelectorAll('.category-filter').forEach(filter => {
filter.addEventListener('click', function() {
document.querySelectorAll('.category-filter').forEach(f => f.classList.remove('active'));
this.classList.add('active');
filterProducts();
});
});
function filterProducts() {
const searchTerm = document.getElementById('search-input').value.toLowerCase();
const activeCategory = document.querySelector('.category-filter.active').dataset.category;
document.querySelectorAll('.product').forEach(product => {
const name = product.getAttribute('data-name') || ''; // Handle potential missing attribute
const description = product.getAttribute('data-description') || ''; // Handle potential missing attribute
const category = product.getAttribute('data-category') || ''; // Handle potential missing attribute
const matchesSearch = name.includes(searchTerm) || description.includes(searchTerm);
const matchesCategory = activeCategory === 'all' || category.toLowerCase() === activeCategory.toLowerCase(); // Case-insensitive category match
product.style.display = matchesSearch && matchesCategory ? 'flex' : 'none'; // Use flex as product is flex container
});
}
// Initialize the cart button display on page load
updateCartButton();
// Initial filter application
filterProducts();
// Add event listener for closing modals with Escape key
document.addEventListener('keydown', function(event) {
if (event.key === "Escape") {
closeModal('productModal');
closeModal('quantityModal');
closeModal('cartModal');
}
});
</script>
</body>
</html>
'''
return render_template_string(catalog_html, products=products, categories=categories, repo_id=REPO_ID)
@app.route('/product/<int:index>')
def product_detail(index):
data = load_data()
products = data['products']
try:
product = products[index]
except IndexError:
return "Продукт не найден", 404
detail_html = '''
<div class="container" style="padding: 0;"> <!-- Adjust padding inside modal -->
<h2 style="font-family: 'Playfair Display', serif; font-size: 1.8rem; font-weight: 700; margin-bottom: 20px; color: var(--primary-color);">{{ product['name'] }}</h2>
<div class="swiper-container" style="max-width: 500px; margin: 0 auto 20px; border-radius: 12px; overflow: hidden; background-color: #f0f0f0;">
<div class="swiper-wrapper">
{% if product.get('photos') %}
{% for photo in product['photos'] %}
<div class="swiper-slide" style="background-color: #fff; display: flex; justify-content: center; align-items: center;">
<div class="swiper-zoom-container">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}"
alt="{{ product['name'] }}"
style="max-width: 100%; max-height: 400px; object-fit: contain;">
</div>
</div>
{% endfor %}
{% else %}
<div class="swiper-slide" style="display: flex; justify-content: center; align-items: center;">
<img src="https://via.placeholder.com/400x300?text=No+Image" alt="No Image" style="max-width: 100%; max-height: 300px; object-fit: contain;">
</div>
{% endif %}
</div>
<div class="swiper-pagination"></div>
<div class="swiper-button-next" style="color: var(--primary-color);"></div>
<div class="swiper-button-prev" style="color: var(--primary-color);"></div>
</div>
<p style="margin-bottom: 10px;"><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
<p style="margin-bottom: 10px;"><strong>Цена:</strong> {{ product['price'] }} $</p>
<p style="margin-bottom: 10px;"><strong>Описание:</strong> {{ product['description'] }}</p>
<p><strong>Доступные цвета:</strong> {{ product.get('colors', ['Не указаны'])|join(', ') }}</p> <!-- Changed from 'Нет цветов' -->
</div>
'''
return render_template_string(detail_html, product=product, repo_id=REPO_ID)
@app.route('/admin', methods=['GET', 'POST'])
def admin():
data = load_data()
products = data.get('products', []) # Ensure lists exist
categories = data.get('categories', [])
if request.method == 'POST':
action = request.form.get('action')
if action == 'add_category':
category_name = request.form.get('category_name', '').strip()
if category_name and category_name not in categories:
categories.append(category_name)
categories.sort() # Keep categories sorted
data['categories'] = categories # Update data dict
save_data(data)
return redirect(url_for('admin'))
return "Ошибка: Категория уже существует или не указано название", 400
elif action == 'delete_category':
try:
category_index = int(request.form.get('category_index'))
if 0 <= category_index < len(categories):
deleted_category = categories.pop(category_index)
data['categories'] = categories # Update data dict
# Reassign products in the deleted category
for product in products:
if product.get('category') == deleted_category:
product['category'] = 'Без категории'
data['products'] = products # Update data dict
save_data(data)
return redirect(url_for('admin'))
return "Ошибка: Неверный индекс категории", 400
except ValueError:
return "Ошибка: Неверный индекс категории", 400
elif action == 'add':
name = request.form.get('name', '').strip()
price_str = request.form.get('price', '0').replace(',', '.')
description = request.form.get('description', '').strip()
category = request.form.get('category')
photos_files = request.files.getlist('photos')
colors = request.form.getlist('colors')
photos_list = []
if not name or not price_str or not description:
return "Ошибка: Заполните все обязательные поля", 400
try:
price = float(price_str)
if price < 0:
raise ValueError("Цена не может быть отрицательной")
except ValueError:
return "Ошибка: Неверный формат цены", 400
if photos_files:
uploads_dir = 'uploads'
os.makedirs(uploads_dir, exist_ok=True)
api = HfApi(token=HF_TOKEN_WRITE) # Pass token explicitly
for photo in photos_files[:10]: # Limit to 10 photos
if photo and photo.filename:
original_filename = secure_filename(photo.filename)
# Prevent overwriting files with the same name if uploaded at different times
photo_filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{original_filename}"
temp_path = os.path.join(uploads_dir, photo_filename)
try:
photo.save(temp_path)
api.upload_file(
path_or_fileobj=temp_path,
path_in_repo=f"photos/{photo_filename}",
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Добавлено фото {photo_filename} для товара {name}"
)
photos_list.append(photo_filename)
except Exception as e:
logging.error(f"Ошибка загрузки фото {original_filename} на HF: {e}")
# Optionally return an error or log and continue
finally:
if os.path.exists(temp_path):
os.remove(temp_path) # Clean up temporary file
new_product = {
'name': name,
'price': price,
'description': description,
'category': category if category in categories else 'Без категории',
'photos': photos_list,
'colors': [c.strip() for c in colors if c.strip()] # Clean up color strings
}
products.append(new_product)
data['products'] = products # Update data dict
save_data(data)
return redirect(url_for('admin'))
elif action == 'edit':
try:
index = int(request.form.get('index'))
if not (0 <= index < len(products)):
return "Ошибка: Неверный индекс товара", 400
product = products[index]
name = request.form.get('name', '').strip()
price_str = request.form.get('price', '0').replace(',', '.')
description = request.form.get('description', '').strip()
category = request.form.get('category')
photos_files = request.files.getlist('photos')
colors = request.form.getlist('colors')
if not name or not price_str or not description:
return "Ошибка: Заполните все обязательные поля при редактировании", 400
try:
price = float(price_str)
if price < 0:
raise ValueError("Цена не может быть отрицательной")
except ValueError:
return "Ошибка: Неверный формат цены при редактировании", 400
product['name'] = name
product['price'] = price
product['description'] = description
product['category'] = category if category in categories else 'Без категории'
product['colors'] = [c.strip() for c in colors if c.strip()] # Clean up color strings
# Handle photo updates only if new photos are provided
if photos_files and any(photo.filename for photo in photos_files):
new_photos_list = []
uploads_dir = 'uploads'
os.makedirs(uploads_dir, exist_ok=True)
api = HfApi(token=HF_TOKEN_WRITE) # Pass token explicitly
for photo in photos_files[:10]: # Limit to 10 photos
if photo and photo.filename:
original_filename = secure_filename(photo.filename)
photo_filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{original_filename}"
temp_path = os.path.join(uploads_dir, photo_filename)
try:
photo.save(temp_path)
api.upload_file(
path_or_fileobj=temp_path,
path_in_repo=f"photos/{photo_filename}",
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Обновлено фото {photo_filename} для товара {name}"
)
new_photos_list.append(photo_filename)
except Exception as e:
logging.error(f"Ошибка загрузки обновленного фото {original_filename} на HF: {e}")
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
# Replace old photos list only if new photos were successfully uploaded
if new_photos_list:
product['photos'] = new_photos_list
data['products'] = products # Update data dict
save_data(data)
return redirect(url_for('admin'))
except ValueError:
return "Ошибка: Неверный индекс товара", 400
elif action == 'delete':
try:
index = int(request.form.get('index'))
if 0 <= index < len(products):
del products[index]
data['products'] = products # Update data dict
save_data(data)
return redirect(url_for('admin'))
return "Ошибка: Неверный индекс товара", 400
except ValueError:
return "Ошибка: Неверный индекс товара", 400
admin_html = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Админ-панель</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Roboto', sans-serif;
background: linear-gradient(135deg, #f0f2f5, #e9ecef);
color: #2d3748;
padding: 20px;
line-height: 1.6;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.header {
display: flex;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid #e2e8f0;
margin-bottom: 30px;
}
.header-logo {
width: 60px;
height: 60px;
border-radius: 50%;
object-fit: cover;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
transition: transform 0.3s ease, box-shadow 0.3s ease;
margin-right: 15px;
}
.header-logo:hover {
transform: scale(1.1);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}
h1, h2 {
font-weight: 700;
margin-bottom: 20px;
color: #333;
}
h2 {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #eee;
}
form {
background: #fff;
padding: 25px;
border-radius: 15px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
margin-bottom: 30px;
}
label {
font-weight: 500;
margin-top: 15px;
margin-bottom: 5px;
display: block;
color: #4a5568;
}
input, textarea, select {
width: 100%;
padding: 12px;
border: 1px solid #e2e8f0;
border-radius: 8px;
font-size: 1rem;
transition: all 0.3s ease;
box-sizing: border-box;
background-color: #fff;
color: #2d3748;
}
input:focus, textarea:focus, select:focus {
border-color: #3b82f6;
box-shadow: 0 0 8px rgba(59, 130, 246, 0.2);
outline: none;
}
button {
padding: 12px 20px;
border: none;
border-radius: 8px;
background-color: #3b82f6;
color: white;
font-weight: 500;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
margin-top: 15px;
display: inline-block;
text-decoration: none;
}
button:hover {
background-color: #2563eb;
box-shadow: 0 4px 15px rgba(37, 99, 235, 0.4);
transform: translateY(-2px);
}
.delete-button {
background-color: #ef4444;
margin-left: 10px; /* Space from edit/other buttons */
}
.delete-button:hover {
background-color: #dc2626;
box-shadow: 0 4px 15px rgba(220, 38, 38, 0.4);
}
.product-list, .category-list {
display: grid;
gap: 20px;
}
.product-item, .category-item {
background: #fff;
padding: 20px;
border-radius: 15px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
word-wrap: break-word; /* Prevent overflow */
}
.product-item h3, .category-item h3 {
margin-top: 0;
margin-bottom: 10px;
color: #3b82f6;
}
.category-item {
display: flex;
justify-content: space-between;
align-items: center;
}
.category-item form {
margin-bottom: 0;
padding: 0;
background: none;
box-shadow: none;
}
.category-item button {
margin-top: 0;
padding: 8px 15px;
font-size: 0.9rem;
}
.edit-form {
margin-top: 20px;
padding: 20px;
background: #f7fafc;
border-radius: 10px;
box-shadow: inset 0 1px 5px rgba(0,0,0,0.05);
}
.color-input-group {
display: flex;
gap: 10px;
margin-top: 10px;
align-items: center;
}
.color-input-group input {
flex-grow: 1;
margin-top: 0;
}
.color-input-group button {
margin-top: 0;
flex-shrink: 0;
padding: 8px 12px;
font-size: 0.9rem;
}
.remove-color-btn {
background-color: #ef4444;
}
.remove-color-btn:hover {
background-color: #dc2626;
}
.add-color-btn {
background-color: #10b981;
margin-bottom: 10px;
margin-top: 10px;
}
.add-color-btn:hover {
background-color: #059669;
}
.product-item p {
margin-bottom: 8px;
color: #4a5568;
}
.product-item p strong {
color: #2d3748;
}
.product-photos {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 15px;
margin-bottom: 15px;
border-top: 1px solid #eee;
padding-top: 15px;
}
.product-photos img {
max-width: 100px;
height: auto;
border-radius: 8px;
border: 1px solid #e2e8f0;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}
.db-actions form {
display: inline-block;
margin-right: 15px;
margin-bottom: 0;
padding: 0;
background: none;
box-shadow: none;
}
.db-actions button {
margin-top: 0;
}
.db-actions .download-button {
background-color: #4299e1; /* Blue */
}
.db-actions .download-button:hover {
background-color: #3182ce;
}
/* Responsive adjustments */
@media (max-width: 768px) {
body {
padding: 10px;
}
.container {
padding: 0;
}
.header {
padding: 10px 0;
margin-bottom: 20px;
}
.header-logo {
width: 50px;
height: 50px;
}
h1 { font-size: 1.8rem; }
h2 { font-size: 1.5rem; margin-top: 20px; padding-top: 15px;}
form {
padding: 20px;
margin-bottom: 20px;
}
label {
margin-top: 10px;
margin-bottom: 3px;
}
input, textarea, select {
padding: 10px;
font-size: 0.95rem;
}
button {
padding: 10px 15px;
font-size: 0.95rem;
margin-top: 10px;
}
.delete-button {
margin-left: 5px;
}
.product-item, .category-item {
padding: 15px;
}
.product-item h3, .category-item h3 {
font-size: 1.3rem;
}
.edit-form {
padding: 15px;
margin-top: 15px;
}
.color-input-group {
flex-direction: column;
align-items: stretch;
gap: 5px;
margin-top: 8px;
}
.color-input-group input, .color-input-group button {
width: 100%;
margin-top: 0;
}
.add-color-btn, .remove-color-btn {
padding: 10px;
font-size: 0.95rem;
}
.db-actions form {
display: block;
margin-right: 0;
margin-bottom: 10px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<img src="''' + LOGO_URL + '''" alt="Logo" class="header-logo">
<h1>Админ-панель</h1>
</div>
<h1>Добавление нового товара</h1>
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="add">
<label for="add-name">Название товара:</label>
<input type="text" name="name" id="add-name" required>
<label for="add-price">Цена ($):</label>
<input type="number" name="price" id="add-price" step="0.01" min="0" required>
<label for="add-description">Описание:</label>
<textarea name="description" id="add-description" rows="4" required></textarea>
<label for="add-category">Категория:</label>
<select name="category" id="add-category">
<option value="Без категории">Без категории</option>
{% for category in categories %}
<option value="{{ category }}">{{ category }}</option>
{% endfor %}
</select>
<label for="add-photos">Фотографии (до 10):</label>
<input type="file" name="photos" id="add-photos" accept="image/*" multiple>
<label>Цвета (оставьте пустым, если нет):</label>
<div id="color-inputs-add">
<div class="color-input-group">
<input type="text" name="colors" placeholder="Например: Красный">
<button type="button" class="remove-color-btn" onclick="this.parentElement.remove()">Удалить</button>
</div>
</div>
<button type="button" class="add-color-btn" onclick="addColorInput('color-inputs-add')">Добавить цвет</button>
<button type="submit">Добавить товар</button>
</form>
<h1>Управление категориями</h1>
<form method="POST">
<input type="hidden" name="action" value="add_category">
<label for="add-category-name">Название категории:</label>
<input type="text" name="category_name" id="add-category-name" required>
<button type="submit">Добавить категорию</button>
</form>
<h2>Список категорий ({{ categories|length }})</h2>
<div class="category-list">
{% for category in categories %}
<div class="category-item">
<h3>{{ category }}</h3>
<form method="POST">
<input type="hidden" name="action" value="delete_category">
<input type="hidden" name="category_index" value="{{ loop.index0 }}">
<button type="submit" class="delete-button" onclick="return confirm('Вы уверены, что хотите удалить категорию \\'{{ category }}\\'? Связанные товары будут перенесены в \\'Без категории\\'.');">Удалить</button>
</form>
</div>
{% endfor %}
{% if not categories %}
<p style="text-align: center; color: #666;">Нет добавленных категорий.</p>
{% endif %}
</div>
<h2>Управление базой данных</h2>
<div class="db-actions">
<form method="POST" action="{{ url_for('backup') }}">
<button type="submit">Создать резервную копию (Загрузить на HF)</button>
</form>
<form method="GET" action="{{ url_for('download') }}">
<button type="submit" class="download-button">Скачать последнюю базу с HF</button>
</form>
</div>
<h2>Список товаров ({{ products|length }})</h2>
<div class="product-list">
{% for product in products %}
<div class="product-item">
<h3>{{ product.get('name', 'Без названия') }}</h3>
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
<p><strong>Цена:</strong> {{ product.get('price', 0)|float|round(2) }} $</p>
<p><strong>Описание:</strong> {{ product.get('description', 'Без описания') }}</p>
<p><strong>Цвета:</strong> {{ product.get('colors', ['Не указаны'])|join(', ') }}</p>
{% if product.get('photos') and product['photos']|length > 0 %}
<div class="product-photos">
{% for photo in product['photos'] %}
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}"
alt="{{ product.get('name', 'Фото товара') }}"
loading="lazy">
{% endfor %}
</div>
{% endif %}
<details>
<summary>Редактировать товар</summary>
<form method="POST" enctype="multipart/form-data" class="edit-form">
<input type="hidden" name="action" value="edit">
<input type="hidden" name="index" value="{{ loop.index0 }}">
<label for="edit-name-{{ loop.index0 }}">Название:</label>
<input type="text" name="name" id="edit-name-{{ loop.index0 }}" value="{{ product.get('name', '') }}" required>
<label for="edit-price-{{ loop.index0 }}">Цена ($):</label>
<input type="number" name="price" id="edit-price-{{ loop.index0 }}" step="0.01" min="0" value="{{ product.get('price', 0)|float|round(2) }}" required>
<label for="edit-description-{{ loop.index0 }}">Описание:</label>
<textarea name="description" id="edit-description-{{ loop.index0 }}" rows="4" required>{{ product.get('description', '') }}</textarea>
<label for="edit-category-{{ loop.index0 }}">Категория:</label>
<select name="category" id="edit-category-{{ loop.index0 }}">
<option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option>
{% for category_item in categories %}
<option value="{{ category_item }}" {% if product.get('category') == category_item %}selected{% endif %}>{{ category_item }}</option>
{% endfor %}
</select>
<label for="edit-photos-{{ loop.index0 }}">Фотографии (до 10, выберите новые, чтобы заменить старые):</label>
<input type="file" name="photos" id="edit-photos-{{ loop.index0 }}" accept="image/*" multiple>
<label>Цвета (оставьте пустым, если нет):</label>
<div id="edit-color-inputs-{{ loop.index0 }}">
{% for color in product.get('colors', []) %}
<div class="color-input-group">
<input type="text" name="colors" value="{{ color|default('') }}">
<button type="button" class="remove-color-btn" onclick="this.parentElement.remove()">Удалить</button>
</div>
{% endfor %}
{% if not product.get('colors') %}
<div class="color-input-group">
<input type="text" name="colors" placeholder="Например: Синий">
<button type="button" class="remove-color-btn" onclick="this.parentElement.remove()">Удалить</button>
</div>
{% endif %}
</div>
<button type="button" class="add-color-btn" onclick="addColorInput('edit-color-inputs-{{ loop.index0 }}')">Добавить цвет</button>
<button type="submit">Сохранить изменения</button>
</form>
</details>
<form method="POST" style="display: inline;">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="index" value="{{ loop.index0 }}">
<button type="submit" class="delete-button" onclick="return confirm('Вы уверены, что хотите удалить товар \\'{{ product.get('name', 'Без названия') }}\\'?');">Удалить товар</button>
</form>
</div>
{% endfor %}
{% if not products %}
<p style="text-align: center; color: #666;">Нет добавленных товаров.</p>
{% endif %}
</div>
</div>
<script>
function addColorInput(containerId) {
const container = document.getElementById(containerId);
const newInputGroup = document.createElement('div');
newInputGroup.className = 'color-input-group';
const newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'colors';
newInput.placeholder = 'Например: Красный';
const removeBtn = document.createElement('button');
removeBtn.type = 'button';
removeBtn.className = 'remove-color-btn';
removeBtn.textContent = 'Удалить';
removeBtn.onclick = function() {
newInputGroup.remove();
};
newInputGroup.appendChild(newInput);
newInputGroup.appendChild(removeBtn);
container.appendChild(newInputGroup);
}
</script>
</body>
</html>
'''
return render_template_string(admin_html, products=products, categories=categories, repo_id=REPO_ID)
@app.route('/backup', methods=['POST'])
def backup():
try:
upload_db_to_hf()
return "Резервная копия успешно создана.", 200
except Exception as e:
return f"Ошибка при создании резервной копии: {e}", 500
@app.route('/download', methods=['GET'])
def download():
try:
download_db_from_hf()
return "База данных успешно скачана.", 200
except Exception as e:
return f"Ошибка при скачивании базы данных: {e}", 500
if __name__ == '__main__':
if HF_TOKEN_WRITE and REPO_ID:
logging.info("Запуск потока периодического резервного копирования.")
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
backup_thread.start()
else:
logging.warning("Отсутствуют токены Hugging Face или REPO_ID. Периодическое резервное копирование отключено.")
try:
# Attempt initial data load to create local file if not exists/download fails
load_data()
except Exception as e:
logging.error(f"Не удалось выполнить начальную загрузку или создать базу данных: {e}")
app.run(debug=True, host='0.0.0.0', port=7860) |