Spaces:
Runtime error
Runtime error
| from flask import Flask, render_template_string, request, redirect, url_for, send_from_directory | |
| 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, HfHubHTTPError | |
| from werkzeug.utils import secure_filename | |
| import urllib.parse | |
| app = Flask(__name__) | |
| DATA_FILE = 'dataasdem.json' | |
| PHOTOS_DIR = 'photos' | |
| REPO_ID = "flpolprojects/tonjob" | |
| 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/67b22aaeae9b6a59f1cfb849/NQvBksXzJItYt6hfFjyaB.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: | |
| if isinstance(data, list): | |
| return {'products': data, 'categories': []} | |
| else: | |
| logging.warning("Неожиданный формат данных в JSON.") | |
| return {'products': [], 'categories': []} | |
| return data | |
| except FileNotFoundError: | |
| logging.warning(f"Локальный файл базы данных ({DATA_FILE}) не найден после скачивания.") | |
| return {'products': [], 'categories': []} | |
| except json.JSONDecodeError: | |
| logging.error("Ошибка: Невозможно декодировать JSON файл.") | |
| return {'products': [], 'categories': []} | |
| except RepositoryNotFoundError: | |
| logging.error(f"Репозиторий '{REPO_ID}' не найден на Hugging Face. Создание локальной базы данных.") | |
| return {'products': [], 'categories': []} | |
| except HfHubHTTPError as e: | |
| logging.error(f"Ошибка HTTP при скачивании из Hugging Face: {e}") | |
| logging.warning(f"Попытка загрузить локальный файл '{DATA_FILE}' если существует.") | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info("Данные успешно загружены из локального JSON после ошибки HF.") | |
| if not isinstance(data, dict) or 'products' not in data or 'categories' not in data: | |
| if isinstance(data, list): | |
| return {'products': data, 'categories': []} | |
| else: | |
| logging.warning("Неожиданный формат данных в локальном JSON.") | |
| return {'products': [], 'categories': []} | |
| return data | |
| except FileNotFoundError: | |
| logging.warning(f"Локальный файл '{DATA_FILE}' также не найден.") | |
| return {'products': [], 'categories': []} | |
| except json.JSONDecodeError: | |
| logging.error("Ошибка: Невозможно декодировать локальный JSON файл.") | |
| 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: | |
| logging.warning("HF_TOKEN не установлен. Пропуск загрузки на Hugging Face.") | |
| 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"Ошибка при загрузке резервной копии на Hugging Face: {e}") | |
| def download_db_from_hf(): | |
| if not HF_TOKEN_READ: | |
| logging.warning("HF_TOKEN_READ не установлен. Пропуск скачивания из Hugging Face.") | |
| return | |
| try: | |
| hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=DATA_FILE, | |
| repo_type="dataset", | |
| token=HF_TOKEN_READ, | |
| local_dir=".", | |
| local_dir_use_symlinks=False | |
| ) | |
| logging.info("JSON база успешно скачана из Hugging Face.") | |
| except RepositoryNotFoundError: | |
| logging.warning(f"Репозиторий '{REPO_ID}' не найден. Скачивание невозможно.") | |
| raise | |
| except Exception as e: | |
| logging.error(f"Ошибка при скачивании JSON базы из Hugging Face: {e}") | |
| raise | |
| def periodic_backup(): | |
| while True: | |
| upload_db_to_hf() | |
| time.sleep(800) | |
| catalog_html = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Asdem - нижнее белье оптом </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=Poppins:wght@300;400;600&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: #F48FB1; | |
| --secondary-color: #CE93D8; | |
| --text-color: #333; | |
| --bg-color: #FCE4EC; | |
| --light-text: #fff; | |
| --shadow-color: rgba(0, 0, 0, 0.1); | |
| } | |
| * { | |
| margin: 0; | |
| padding: 0; | |
| box-sizing: border-box; | |
| } | |
| body { | |
| font-family: 'Poppins', sans-serif; | |
| background-color: var(--bg-color); | |
| color: var(--text-color); | |
| line-height: 1.6; | |
| transition: background-color 0.3s, color 0.3s; | |
| } | |
| .container { | |
| max-width: 1300px; | |
| margin: 0 auto; | |
| padding: 20px; | |
| } | |
| .header { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| padding: 15px 0; | |
| border-bottom: 1px solid var(--primary-color); | |
| } | |
| .header-logo { | |
| width: 60px; | |
| height: 60px; | |
| border-radius: 50%; | |
| object-fit: cover; | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| transition: transform 0.3s ease, box-shadow 0.3s ease; | |
| } | |
| .header-logo:hover { | |
| transform: scale(1.1); | |
| box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3); | |
| } | |
| .header h1 { | |
| font-size: 1.5rem; | |
| font-weight: 600; | |
| margin-left: 15px; | |
| 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: 90%; | |
| max-width: 600px; | |
| padding: 12px 18px; | |
| font-size: 1rem; | |
| border: 1px solid var(--secondary-color); | |
| border-radius: 8px; | |
| outline: none; | |
| box-shadow: 0 2px 5px var(--shadow-color); | |
| transition: all 0.3s ease; | |
| } | |
| #search-input:focus { | |
| border-color: var(--primary-color); | |
| box-shadow: 0 4px 15px rgba(244, 143, 177, 0.3); | |
| } | |
| .category-filter { | |
| padding: 8px 16px; | |
| border: 1px solid var(--secondary-color); | |
| border-radius: 8px; | |
| background-color: var(--light-text); | |
| color: var(--text-color); | |
| cursor: pointer; | |
| transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); | |
| font-size: 0.9rem; | |
| font-weight: 400; | |
| } | |
| .category-filter.active, .category-filter:hover { | |
| background-color: var(--primary-color); | |
| color: var(--light-text); | |
| border-color: var(--primary-color); | |
| box-shadow: 0 2px 10px rgba(244, 143, 177, 0.4); | |
| } | |
| .products-grid { | |
| display: grid; | |
| grid-template-columns: repeat(2, 1fr); | |
| gap: 15px; | |
| padding: 10px; | |
| } | |
| .product { | |
| background: var(--light-text); | |
| border-radius: 15px; | |
| padding: 15px; | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; | |
| overflow: hidden; | |
| display: flex; | |
| flex-direction: column; | |
| } | |
| .product:hover { | |
| transform: translateY(-5px) scale(1.02); | |
| box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15); | |
| } | |
| .product-image { | |
| width: 100%; | |
| aspect-ratio: 1; | |
| background-color: #fff; | |
| border-radius: 10px; | |
| overflow: hidden; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| } | |
| .product-image img { | |
| max-width: 100%; | |
| max-height: 100%; | |
| object-fit: contain; | |
| transition: transform 0.3s ease; | |
| } | |
| .product-image img:hover { | |
| transform: scale(1.1); | |
| } | |
| .product h2 { | |
| font-size: 1rem; | |
| font-weight: 600; | |
| margin: 10px 0 5px 0; | |
| text-align: center; | |
| white-space: nowrap; | |
| overflow: hidden; | |
| text-overflow: ellipsis; | |
| } | |
| .product-price { | |
| font-size: 1.1rem; | |
| color: #ef4444; | |
| font-weight: 700; | |
| text-align: center; | |
| margin: 5px 0; | |
| } | |
| .product-description { | |
| font-size: 0.8rem; | |
| color: #718096; | |
| text-align: center; | |
| margin-bottom: 15px; | |
| overflow: hidden; | |
| text-overflow: ellipsis; | |
| display: -webkit-box; | |
| -webkit-line-clamp: 2; | |
| -webkit-box-orient: vertical; | |
| flex-grow: 1; | |
| } | |
| .product-buttons { | |
| margin-top: auto; | |
| } | |
| .product-button { | |
| display: block; | |
| width: 100%; | |
| padding: 8px; | |
| border: none; | |
| border-radius: 8px; | |
| background-color: var(--primary-color); | |
| color: var(--light-text); | |
| font-size: 0.8rem; | |
| font-weight: 500; | |
| cursor: pointer; | |
| transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); | |
| margin: 5px 0; | |
| text-align: center; | |
| text-decoration: none; | |
| } | |
| .product-button:hover { | |
| background-color: #E91E63; | |
| box-shadow: 0 4px 15px rgba(233, 30, 99, 0.4); | |
| transform: translateY(-2px); | |
| } | |
| .add-to-cart { | |
| background-color: var(--secondary-color); | |
| } | |
| .add-to-cart:hover { | |
| background-color: #BA68C8; | |
| box-shadow: 0 4px 15px rgba(186, 104, 200, 0.4); | |
| } | |
| #cart-button { | |
| position: fixed; | |
| bottom: 20px; | |
| right: 20px; | |
| background-color: #ef4444; | |
| color: var(--light-text); | |
| border: none; | |
| border-radius: 50%; | |
| width: 50px; | |
| height: 50px; | |
| font-size: 1.2rem; | |
| cursor: pointer; | |
| display: none; | |
| box-shadow: 0 4px 15px rgba(239, 68, 68, 0.4); | |
| transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); | |
| z-index: 1000; | |
| } | |
| #cart-button #cart-count { | |
| position: absolute; | |
| top: -5px; | |
| right: -5px; | |
| background-color: red; | |
| color: white; | |
| border-radius: 50%; | |
| padding: 2px 5px; | |
| font-size: 0.7em; | |
| display: none; | |
| min-width: 20px; | |
| text-align: center; | |
| line-height: 1.2; | |
| } | |
| .modal { | |
| display: none; | |
| position: fixed; | |
| z-index: 1001; | |
| left: 0; | |
| top: 0; | |
| width: 100%; | |
| height: 100%; | |
| background-color: rgba(0,0,0,0.5); | |
| backdrop-filter: blur(5px); | |
| overflow: auto; | |
| } | |
| .modal-content { | |
| background: var(--light-text); | |
| margin: 5% auto; | |
| padding: 20px; | |
| border-radius: 15px; | |
| width: 90%; | |
| max-width: 700px; | |
| box-shadow: 0 10px 30px rgba(0,0,0,0.2); | |
| animation: slideIn 0.3s ease-out; | |
| } | |
| @keyframes slideIn { | |
| from { transform: translateY(-50px); opacity: 0; } | |
| to { transform: translateY(0); opacity: 1; } | |
| } | |
| .close { | |
| float: right; | |
| font-size: 1.5rem; | |
| color: #718096; | |
| cursor: pointer; | |
| transition: color 0.3s; | |
| } | |
| .close:hover { | |
| color: var(--primary-color); | |
| } | |
| .cart-item { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| padding: 15px 0; | |
| border-bottom: 1px solid var(--secondary-color); | |
| } | |
| .cart-item:last-child { | |
| border-bottom: none; | |
| } | |
| .cart-item .item-info { | |
| display: flex; | |
| align-items: center; | |
| flex-grow: 1; | |
| margin-right: 15px; | |
| } | |
| .cart-item img { | |
| width: 50px; | |
| height: 50px; | |
| object-fit: contain; | |
| border-radius: 8px; | |
| margin-right: 15px; | |
| flex-shrink: 0; | |
| } | |
| .cart-item .item-details { | |
| flex-grow: 1; | |
| } | |
| .cart-item .item-details strong { | |
| display: block; | |
| font-size: 1rem; | |
| white-space: nowrap; | |
| overflow: hidden; | |
| text-overflow: ellipsis; | |
| } | |
| .cart-item .item-details p { | |
| font-size: 0.9rem; | |
| color: #718096; | |
| } | |
| .cart-item span { | |
| font-size: 1rem; | |
| font-weight: 600; | |
| color: #ef4444; | |
| flex-shrink: 0; | |
| } | |
| .quantity-input, .color-select { | |
| width: 100%; | |
| max-width: 200px; | |
| padding: 8px; | |
| border: 1px solid var(--secondary-color); | |
| border-radius: 8px; | |
| font-size: 1rem; | |
| margin: 5px 0; | |
| display: block; | |
| margin-bottom: 15px; | |
| } | |
| .modal-content button { | |
| margin-top: 0; | |
| } | |
| .modal-content .product-button { | |
| margin-top: 15px; | |
| } | |
| .clear-cart { | |
| background-color: #ef4444; | |
| } | |
| .clear-cart:hover { | |
| background-color: #dc2626; | |
| box-shadow: 0 4px 15px rgba(220, 38, 38, 0.4); | |
| } | |
| .order-button { | |
| background-color: var(--secondary-color); | |
| } | |
| .order-button:hover { | |
| background-color: #BA68C8; | |
| box-shadow: 0 4px 15px rgba(186, 104, 200, 0.4); | |
| } | |
| @media (max-width: 768px) { | |
| .header { | |
| flex-direction: column; | |
| text-align: center; | |
| } | |
| .header-logo { | |
| margin-right: 0; | |
| margin-bottom: 10px; | |
| } | |
| .modal-content { | |
| margin: 10% auto; | |
| } | |
| .quantity-input, .color-select { | |
| max-width: none; | |
| } | |
| } | |
| @media (max-width: 480px) { | |
| .modal-content { | |
| margin: 15% auto; | |
| } | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <img src="''' + LOGO_URL + '''" alt="Logo" class="header-logo"> | |
| <h1>Каталог</h1> | |
| </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|e }}">{{ category|e }}</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|e }}" | |
| data-description="{{ product['description']|lower|e }}" | |
| data-category="{{ product.get('category', 'Без категории')|e }}"> | |
| {% 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]|e }}" | |
| alt="{{ product['name']|e }}" | |
| loading="lazy"> | |
| </div> | |
| {% endif %} | |
| <h2>{{ product['name']|e }}</h2> | |
| <div class="product-price">{{ product['price'] }} с</div> | |
| <p class="product-description">{{ product['description'][:100] }}{% if product['description']|length > 100 %}...{% endif %}</p> | |
| <div class="product-buttons"> | |
| <button class="product-button" onclick="openProductModal('{{ product['name']|e }}')">Подробнее</button> | |
| <button class="product-button add-to-cart" onclick="openQuantityModal('{{ product['name']|e }}')">В корзину</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">Количество:</label> | |
| <input type="number" id="quantityInput" class="quantity-input" min="1" value="1"> | |
| <label for="colorSelect">Цвет:</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 style="margin-top: 20px; text-align: right;"> | |
| <strong>Итого: <span id="cartTotal">0</span> с</strong> | |
| <button class="product-button clear-cart" onclick="clearCart()">Очистить</button> | |
| <button class="product-button order-button" onclick="orderViaWhatsApp()">Заказать</button> | |
| </div> | |
| </div> | |
| </div> | |
| <button id="cart-button" onclick="openCartModal()">🛒<span id="cart-count">0</span></button> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script> | |
| <script> | |
| const allProducts = {{ products|tojson }}; | |
| let selectedProductName = null; | |
| function openProductModal(productName) { | |
| loadProductDetails(productName); | |
| document.getElementById('productModal').style.display = "block"; | |
| } | |
| function closeModal(modalId) { | |
| document.getElementById(modalId).style.display = "none"; | |
| } | |
| function loadProductDetails(productName) { | |
| const encodedProductName = encodeURIComponent(productName); | |
| fetch('/product_by_name/' + encodedProductName) | |
| .then(response => response.text()) | |
| .then(data => { | |
| document.getElementById('modalContent').innerHTML = data; | |
| initializeSwiper(); | |
| }) | |
| .catch(error => console.error('Ошибка загрузки деталей продукта:', error)); | |
| } | |
| function initializeSwiper() { | |
| if (document.querySelector('.swiper-container')) { | |
| const swiper = new Swiper('.swiper-container', { | |
| slidesPerView: 1, | |
| spaceBetween: 20, | |
| loop: document.querySelectorAll('.swiper-slide').length > 1, | |
| grabCursor: true, | |
| pagination: { el: '.swiper-pagination', clickable: true }, | |
| navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, | |
| zoom: { maxRatio: 3 }, | |
| keyboard: { enabled: true }, | |
| mousewheel: { enabled: true }, | |
| }); | |
| // Hide navigation if there's only one slide | |
| if (document.querySelectorAll('.swiper-slide').length <= 1) { | |
| document.querySelector('.swiper-button-next').style.display = 'none'; | |
| document.querySelector('.swiper-button-prev').style.display = 'none'; | |
| document.querySelector('.swiper-pagination').style.display = 'none'; | |
| } else { | |
| document.querySelector('.swiper-button-next').style.display = ''; | |
| document.querySelector('.swiper-button-prev').style.display = ''; | |
| document.querySelector('.swiper-pagination').style.display = ''; | |
| } | |
| } else { | |
| console.warn("Swiper container not found. Swiper not initialized."); | |
| } | |
| } | |
| function openQuantityModal(productName) { | |
| selectedProductName = productName; | |
| const product = allProducts.find(p => p.name === productName); | |
| if (!product) { | |
| alert("Продукт не найден!"); | |
| return; | |
| } | |
| 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 = 'Без цвета'; | |
| option.text = 'Без цвета'; | |
| colorSelect.appendChild(option); | |
| } | |
| document.getElementById('quantityModal').style.display = 'block'; | |
| document.getElementById('quantityInput').value = 1; | |
| } | |
| function confirmAddToCart() { | |
| if (selectedProductName === null) return; | |
| const quantityInput = document.getElementById('quantityInput'); | |
| const quantity = parseInt(quantityInput.value) || 1; | |
| const color = document.getElementById('colorSelect').value; | |
| if (quantity <= 0) { | |
| alert("Укажите количество больше 0"); | |
| quantityInput.value = 1; | |
| return; | |
| } | |
| let cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const product = allProducts.find(p => p.name === selectedProductName); | |
| if (!product) { | |
| alert("Ошибка: Товар не найден."); | |
| return; | |
| } | |
| const cartItemId = `${product.name}-${color}`; | |
| const existingItem = cart.find(item => item.id === cartItemId); | |
| if (existingItem) { | |
| existingItem.quantity += quantity; | |
| } else { | |
| cart.push({ | |
| id: cartItemId, | |
| name: product.name, | |
| price: product.price, | |
| photo: product.photos && product.photos.length > 0 ? product.photos[0] : '', | |
| quantity: quantity, | |
| color: color | |
| }); | |
| } | |
| localStorage.setItem('cart', JSON.stringify(cart)); | |
| closeModal('quantityModal'); | |
| updateCartButton(); | |
| alert(`Товар "${product.name}" добавлен в корзину!`); | |
| } | |
| function updateCartButton() { | |
| const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const cartButton = document.getElementById('cart-button'); | |
| const cartCount = document.getElementById('cart-count'); | |
| const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0); | |
| if (cart.length > 0) { | |
| cartButton.style.display = 'block'; | |
| cartCount.textContent = totalItems; | |
| cartCount.style.display = 'block'; | |
| } else { | |
| cartButton.style.display = 'none'; | |
| cartCount.style.display = 'none'; | |
| } | |
| } | |
| function openCartModal() { | |
| const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const cartContent = document.getElementById('cartContent'); | |
| let total = 0; | |
| if (cart.length === 0) { | |
| cartContent.innerHTML = '<p>Корзина пуста</p>'; | |
| } else { | |
| cartContent.innerHTML = cart.map(item => { | |
| const itemTotal = parseFloat(item.price) * item.quantity; | |
| total += itemTotal; | |
| const photoUrl = item.photo ? `https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}` : ''; | |
| return ` | |
| <div class="cart-item"> | |
| <div class="item-info"> | |
| ${photoUrl ? `<img src="${photoUrl}" alt="${item.name}">` : ''} | |
| <div class="item-details"> | |
| <strong>${item.name}</strong> | |
| <p>${item.price} с × ${item.quantity} (Цвет: ${item.color})</p> | |
| </div> | |
| </div> | |
| <span>${itemTotal} с</span> | |
| </div> | |
| `; | |
| }).join(''); | |
| } | |
| document.getElementById('cartTotal').textContent = total; | |
| 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"; | |
| cart.forEach((item, index) => { | |
| const itemTotal = parseFloat(item.price) * item.quantity; | |
| total += itemTotal; | |
| orderText += `${index + 1}. ${item.name} - ${item.price} с × ${item.quantity} шт. (Цвет: ${item.color})%0A`; | |
| }); | |
| orderText += `Итого к оплате: ${total} с`; | |
| const phoneNumber = '996772179559'; | |
| const whatsappUrl = `https://api.whatsapp.com/send?phone=${phoneNumber}&text=${encodeURIComponent(orderText)}`; | |
| window.open(whatsappUrl, '_blank'); | |
| } | |
| function clearCart() { | |
| if (confirm("Вы уверены, что хотите очистить корзину?")) { | |
| localStorage.removeItem('cart'); | |
| closeModal('cartModal'); | |
| updateCartButton(); | |
| } | |
| } | |
| window.onclick = function(event) { | |
| if (event.target.classList && event.target.classList.contains('modal')) { | |
| event.target.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(productDiv => { | |
| const name = productDiv.getAttribute('data-name'); | |
| const description = productDiv.getAttribute('data-description'); | |
| const category = productDiv.getAttribute('data-category'); | |
| const matchesSearch = name.includes(searchTerm) || description.includes(searchTerm); | |
| const matchesCategory = activeCategory === 'all' || category === activeCategory; | |
| productDiv.style.display = matchesSearch && matchesCategory ? 'flex' : 'none'; | |
| }); | |
| } | |
| updateCartButton(); | |
| filterProducts(); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| detail_html = ''' | |
| <div class="product-detail-content" style="padding: 20px;"> | |
| <h2 style="font-size: 1.5rem; font-weight: 600; margin-bottom: 20px; text-align: center;">{{ product['name']|e }}</h2> | |
| <div class="swiper-container" style="max-width: 400px; margin: 0 auto 20px;"> | |
| <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; border-radius: 10px;"> | |
| <div class="swiper-zoom-container"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo|e }}" | |
| alt="{{ product['name']|e }}" | |
| style="max-width: 100%; max-height: 300px; object-fit: contain; display: block;"> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <div class="swiper-slide" style="background-color: #fff; display: flex; justify-content: center; align-items: center; border-radius: 10px;"> | |
| <img src="https://via.placeholder.com/300?text=No+Image" alt="No Image" style="max-width: 100%; max-height: 300px; object-fit: contain;"> | |
| </div> | |
| {% endif %} | |
| </div> | |
| {% if product.get('photos') and product['photos']|length > 1 %} | |
| <div class="swiper-pagination"></div> | |
| <div class="swiper-button-next"></div> | |
| <div class="swiper-button-prev"></div> | |
| {% endif %} | |
| </div> | |
| <p style="margin-bottom: 10px;"><strong>Категория:</strong> {{ product.get('category', 'Без категории')|e }}</p> | |
| <p style="font-size: 1.2rem; font-weight: 700; color: #ef4444; margin-bottom: 15px;"><strong>Цена:</strong> {{ product['price'] }} с</p> | |
| <p style="margin-bottom: 15px;"><strong>Описание:</strong> {{ product['description']|e }}</p> | |
| <p style="margin-bottom: 15px;"><strong>Доступные цвета:</strong> {{ product.get('colors', ['Нет цветов'])|join(', ')|e }}</p> | |
| <button class="product-button add-to-cart" onclick="closeModal('productModal'); openQuantityModal('{{ product['name']|e }}')" style="display: block; width: 100%; margin-top: 20px;">Добавить в корзину</button> | |
| </div> | |
| ''' | |
| 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=Poppins:wght@300;400;600&display=swap" rel="stylesheet"> | |
| <style> | |
| :root { | |
| --primary-color: #F48FB1; | |
| --secondary-color: #CE93D8; | |
| --text-color: #333; | |
| --bg-color: #FCE4EC; | |
| --light-text: #fff; | |
| --shadow-color: rgba(0, 0, 0, 0.1); | |
| } | |
| body { | |
| font-family: 'Poppins', sans-serif; | |
| background: var(--bg-color); | |
| color: var(--text-color); | |
| padding: 20px; | |
| } | |
| .container { | |
| max-width: 1200px; | |
| margin: 0 auto; | |
| } | |
| .header { | |
| display: flex; | |
| align-items: center; | |
| padding: 15px 0; | |
| border-bottom: 1px solid var(--primary-color); | |
| margin-bottom: 20px; | |
| } | |
| .header-logo { | |
| width: 50px; | |
| height: 50px; | |
| border-radius: 50%; | |
| object-fit: cover; | |
| box-shadow: 0 4px 10px var(--shadow-color); | |
| margin-right: 15px; | |
| } | |
| h1, h2 { | |
| font-weight: 600; | |
| margin-bottom: 20px; | |
| color: var(--primary-color); | |
| border-bottom: 1px dashed var(--secondary-color); | |
| padding-bottom: 10px; | |
| } | |
| form { | |
| background: var(--light-text); | |
| padding: 20px; | |
| border-radius: 15px; | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| margin-bottom: 30px; | |
| } | |
| label { | |
| font-weight: 500; | |
| margin-top: 15px; | |
| display: block; | |
| margin-bottom: 5px; | |
| } | |
| input, textarea, select { | |
| width: 100%; | |
| padding: 10px; | |
| border: 1px solid var(--secondary-color); | |
| border-radius: 8px; | |
| font-size: 1rem; | |
| transition: all 0.3s ease; | |
| box-sizing: border-box; | |
| } | |
| input:focus, textarea:focus, select:focus { | |
| border-color: var(--primary-color); | |
| box-shadow: 0 0 5px rgba(244, 143, 177, 0.3); | |
| outline: none; | |
| } | |
| button { | |
| padding: 10px 15px; | |
| border: none; | |
| border-radius: 8px; | |
| background-color: var(--primary-color); | |
| color: var(--light-text); | |
| 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: #E91E63; | |
| box-shadow: 0 4px 15px rgba(233, 30, 99, 0.4); | |
| transform: translateY(-2px); | |
| } | |
| .delete-button { | |
| background-color: #ef4444; | |
| } | |
| .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; | |
| margin-top: 20px; | |
| } | |
| .product-item, .category-item { | |
| background: var(--light-text); | |
| padding: 20px; | |
| border-radius: 15px; | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| } | |
| .category-item { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| flex-wrap: wrap; | |
| } | |
| .category-item h3 { | |
| margin: 0; | |
| padding: 0; | |
| border-bottom: none; | |
| flex-grow: 1; | |
| margin-right: 10px; | |
| } | |
| .category-item form { | |
| margin: 0; | |
| padding: 0; | |
| box-shadow: none; | |
| background: none; | |
| } | |
| .category-item button { | |
| margin-top: 0; | |
| } | |
| .edit-form { | |
| margin-top: 20px; | |
| padding: 15px; | |
| background: #f7fafc; | |
| border-radius: 10px; | |
| box-shadow: inset 0 1px 3px rgba(0,0,0,0.05); | |
| } | |
| .color-input-group { | |
| display: flex; | |
| gap: 10px; | |
| margin-top: 5px; | |
| align-items: center; | |
| } | |
| .color-input-group input { | |
| flex-grow: 1; | |
| margin-top: 0; | |
| } | |
| .remove-color-btn { | |
| background-color: #ccc; | |
| margin-top: 0; | |
| padding: 5px 10px; | |
| font-size: 0.9rem; | |
| border-radius: 5px; | |
| } | |
| .remove-color-btn:hover { | |
| background-color: #bbb; | |
| box-shadow: none; | |
| transform: none; | |
| } | |
| .add-color-btn { | |
| background-color: var(--secondary-color); | |
| } | |
| .add-color-btn:hover { | |
| background-color: #BA68C8; | |
| } | |
| .product-images-preview { | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| margin-top: 15px; | |
| } | |
| .product-images-preview img { | |
| max-width: 80px; | |
| height: auto; | |
| border-radius: 8px; | |
| border: 1px solid #eee; | |
| box-shadow: 0 2px 5px rgba(0,0,0,0.05); | |
| } | |
| .db-buttons button { | |
| margin-right: 10px; | |
| } | |
| details { | |
| margin-top: 15px; | |
| border: 1px solid #eee; | |
| border-radius: 8px; | |
| padding: 10px; | |
| background-color: #fafafa; | |
| } | |
| summary { | |
| font-weight: 600; | |
| cursor: pointer; | |
| color: var(--primary-color); | |
| } | |
| </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" id="add_name" name="name" required> | |
| <label for="add_price">Цена (с):</label> | |
| <input type="number" id="add_price" name="price" step="0.01" required> | |
| <label for="add_description">Описание:</label> | |
| <textarea id="add_description" name="description" rows="4" required></textarea> | |
| <label for="add_category">Категория:</label> | |
| <select id="add_category" name="category"> | |
| <option value="Без категории">Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category|e }}">{{ category|e }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="add_photos">Фотографии (до 10, заменят старые при редактировании):</label> | |
| <input type="file" id="add_photos" name="photos" accept="image/*" multiple> | |
| <label>Цвета:</label> | |
| <div id="add-color-inputs"> | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" placeholder="Например: Красный"> | |
| </div> | |
| </div> | |
| <button type="button" class="add-color-btn" onclick="addColorInput('add-color-inputs')">Добавить цвет</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" id="add_category_name" name="category_name" required> | |
| <button type="submit">Добавить</button> | |
| </form> | |
| <h2>Список категорий</h2> | |
| <div class="category-list"> | |
| {% for category in categories %} | |
| <div class="category-item"> | |
| <h3>{{ category|e }}</h3> | |
| <form method="POST" style="display: inline;"> | |
| <input type="hidden" name="action" value="delete_category"> | |
| <input type="hidden" name="category_name_to_delete" value="{{ category|e }}"> | |
| <button type="submit" class="delete-button" onclick="return confirm('Вы уверены, что хотите удалить категорию «{{ category|e }}»? Товары в этой категории будут перемещены в «Без категории».')">Удалить</button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| <h2>Управление базой данных</h2> | |
| <form method="POST" action="{{ url_for('backup') }}" style="display: inline-block;"> | |
| <button type="submit">Создать резервную копию на HF</button> | |
| </form> | |
| <form method="GET" action="{{ url_for('download') }}" style="display: inline-block;"> | |
| <button type="submit">Скачать базу с HF</button> | |
| </form> | |
| <h2>Список товаров ({{ products|length }})</h2> | |
| <div class="product-list"> | |
| {% for product in products %} | |
| <div class="product-item"> | |
| <h3>{{ product['name']|e }}</h3> | |
| <p><strong>Категория:</strong> {{ product.get('category', 'Без категории')|e }}</p> | |
| <p><strong>Цена:</strong> {{ product['price'] }} с</p> | |
| <p><strong>Описание:</strong> {{ product['description'][:150] }}{% if product['description']|length > 150 %}...{% endif %}</p> | |
| <p><strong>Цвета:</strong> {{ product.get('colors', ['Нет цветов'])|join(', ')|e }}</p> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <div class="product-images-preview"> | |
| {% for photo in product['photos'] %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo|e }}" | |
| alt="{{ product['name']|e }}" | |
| 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" id="edit_name_{{ loop.index0 }}" name="name" value="{{ product['name']|e }}" required> | |
| <label for="edit_price_{{ loop.index0 }}">Цена (с):</label> | |
| <input type="number" id="edit_price_{{ loop.index0 }}" name="price" step="0.01" value="{{ product['price'] }}" required> | |
| <label for="edit_description_{{ loop.index0 }}">Описание:</label> | |
| <textarea id="edit_description_{{ loop.index0 }}" name="description" rows="4" required>{{ product['description']|e }}</textarea> | |
| <label for="edit_category_{{ loop.index0 }}">Категория:</label> | |
| <select id="edit_category_{{ loop.index0 }}" name="category"> | |
| <option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category|e }}" {% if product.get('category') == category %}selected{% endif %}>{{ category|e }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="edit_photos_{{ loop.index0 }}">Загрузить новые фотографии (заменят текущие):</label> | |
| <input type="file" id="edit_photos_{{ loop.index0 }}" name="photos" 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|e }}"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)">Удалить</button> | |
| </div> | |
| {% endfor %} | |
| </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="margin-top: 10px;"> | |
| <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['name']|e }}»?')">Удалить товар</button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| </div> | |
| <script> | |
| function addColorInput(containerId) { | |
| const container = document.getElementById(containerId); | |
| const newInputGroup = document.createElement('div'); | |
| newInputGroup.className = 'color-input-group'; | |
| newInputGroup.innerHTML = ` | |
| <input type="text" name="colors" placeholder="Например: Красный"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)">Удалить</button> | |
| `; | |
| container.appendChild(newInputGroup); | |
| } | |
| function removeColorInput(buttonElement) { | |
| buttonElement.closest('.color-input-group').remove(); | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| def catalog(): | |
| data = load_data() | |
| products_for_display = sorted(data.get('products', []), key=lambda x: x.get('added_at', ''), reverse=True) | |
| categories = data.get('categories', []) | |
| return render_template_string(catalog_html, products=products_for_display, categories=categories, repo_id=REPO_ID, LOGO_URL=LOGO_URL) | |
| def product_detail_by_name(product_name): | |
| data = load_data() | |
| product = next((p for p in data.get('products', []) if p['name'] == product_name), None) | |
| if product: | |
| return render_template_string(detail_html, product=product, repo_id=REPO_ID) | |
| else: | |
| return "Продукт не найден", 404 | |
| def admin(): | |
| data = load_data() | |
| products = data.get('products', []) | |
| 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) | |
| save_data(data) | |
| return redirect(url_for('admin')) | |
| return "Ошибка: Категория уже существует или не указано название", 400 | |
| elif action == 'delete_category': | |
| try: | |
| category_name_to_delete = request.form.get('category_name_to_delete') | |
| if category_name_to_delete in categories: | |
| categories.remove(category_name_to_delete) | |
| for product in products: | |
| if product.get('category') == category_name_to_delete: | |
| product['category'] = 'Без категории' | |
| save_data(data) | |
| return redirect(url_for('admin')) | |
| else: | |
| return "Ошибка: Категория не найдена.", 400 | |
| except Exception as e: | |
| logging.error(f"Ошибка при удалении категории: {e}") | |
| return f"Ошибка при удалении категории: {e}", 500 | |
| elif action == 'add': | |
| name = request.form.get('name').strip() | |
| price_str = request.form.get('price').strip() | |
| description = request.form.get('description').strip() | |
| category = request.form.get('category') | |
| photos_files = request.files.getlist('photos') | |
| colors = [c.strip() for c in request.form.getlist('colors') if c.strip()] | |
| try: | |
| price = float(price_str.replace(',', '.')) | |
| except ValueError: | |
| return "Ошибка: Неверный формат цены", 400 | |
| if not name or price is None or not description: | |
| return "Ошибка: Заполните все обязательные поля", 400 | |
| photos_list = [] | |
| if photos_files: | |
| for photo in photos_files: | |
| if photo and photo.filename: | |
| original_filename = secure_filename(photo.filename) | |
| timestamp = datetime.now().strftime("%Y%m%d%H%M%S%f") | |
| photo_filename = f"{timestamp}_{original_filename}" | |
| uploads_dir = 'uploads' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| try: | |
| photo.save(temp_path) | |
| api = HfApi() | |
| 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"Добавлено фото '{original_filename}' для товара '{name}'" | |
| ) | |
| photos_list.append(photo_filename) | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке фото {original_filename} на HF: {e}") | |
| pass | |
| finally: | |
| if os.path.exists(temp_path): | |
| os.remove(temp_path) | |
| new_product = { | |
| 'name': name, | |
| 'price': price, | |
| 'description': description, | |
| 'category': category if category in categories else 'Без категории', | |
| 'photos': photos_list, | |
| 'colors': colors, | |
| 'added_at': datetime.now().isoformat() | |
| } | |
| products.append(new_product) | |
| save_data(data) | |
| return redirect(url_for('admin')) | |
| elif action == 'edit': | |
| try: | |
| index = int(request.form.get('index')) | |
| if 0 <= index < len(products): | |
| product_to_edit = products[index] | |
| name = request.form.get('name').strip() | |
| price_str = request.form.get('price').strip() | |
| description = request.form.get('description').strip() | |
| category = request.form.get('category') | |
| photos_files = request.files.getlist('photos') | |
| colors = [c.strip() for c in request.form.getlist('colors') if c.strip()] | |
| try: | |
| price = float(price_str.replace(',', '.')) | |
| except ValueError: | |
| return "Ошибка: Неверный формат цены", 400 | |
| if not name or price is None or not description: | |
| return "Ошибка: Заполните все обязательные поля для редактирования", 400 | |
| if photos_files and any(photo.filename for photo in photos_files): | |
| new_photos_list = [] | |
| for photo in photos_files: | |
| if photo and photo.filename: | |
| original_filename = secure_filename(photo.filename) | |
| timestamp = datetime.now().strftime("%Y%m%d%H%M%S%f") | |
| photo_filename = f"{timestamp}_{original_filename}" | |
| uploads_dir = 'uploads' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| try: | |
| photo.save(temp_path) | |
| api = HfApi() | |
| 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"Обновлено/добавлено фото '{original_filename}' для товара '{name}'" | |
| ) | |
| new_photos_list.append(photo_filename) | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке фото {original_filename} на HF во время редактирования: {e}") | |
| pass | |
| finally: | |
| if os.path.exists(temp_path): | |
| os.remove(temp_path) | |
| product_to_edit['photos'] = new_photos_list | |
| product_to_edit['name'] = name | |
| product_to_edit['price'] = price | |
| product_to_edit['description'] = description | |
| product_to_edit['category'] = category if category in categories else 'Без категории' | |
| product_to_edit['colors'] = colors | |
| save_data(data) | |
| return redirect(url_for('admin')) | |
| else: | |
| return "Ошибка: Товар с указанным индексом не найден.", 404 | |
| except ValueError: | |
| return "Ошибка: Неверный индекс товара.", 400 | |
| except Exception as e: | |
| logging.error(f"Ошибка при редактировании товара: {e}") | |
| return f"Ошибка при редактировании товара: {e}", 500 | |
| elif action == 'delete': | |
| try: | |
| index = int(request.form.get('index')) | |
| if 0 <= index < len(products): | |
| del products[index] | |
| save_data(data) | |
| return redirect(url_for('admin')) | |
| else: | |
| return "Ошибка: Товар с указанным индексом не найден.", 404 | |
| except ValueError: | |
| return "Ошибка: Неверный индекс товара.", 400 | |
| except Exception as e: | |
| logging.error(f"Ошибка при удалении товара: {e}") | |
| return f"Ошибка при удалении товара: {e}", 500 | |
| return render_template_string(admin_html, products=products, categories=categories, repo_id=REPO_ID, LOGO_URL=LOGO_URL) | |
| def backup(): | |
| try: | |
| upload_db_to_hf() | |
| return "Резервная копия базы данных успешно создана на Hugging Face.", 200 | |
| except Exception as e: | |
| return f"Ошибка при создании резервной копии: {e}", 500 | |
| def download(): | |
| try: | |
| download_db_from_hf() | |
| return "База данных успешно скачана с Hugging Face.", 200 | |
| except Exception as e: | |
| return f"Ошибка при скачивании базы данных: {e}", 500 | |
| if __name__ == '__main__': | |
| os.makedirs('uploads', exist_ok=True) | |
| backup_thread = threading.Thread(target=periodic_backup, daemon=True) | |
| backup_thread.start() | |
| try: | |
| load_data() | |
| except Exception as e: | |
| logging.error(f"Не удалось выполнить начальную загрузку базы данных при запуске: {e}") | |
| app.run(debug=True, host='0.0.0.0', port=7860) |