Spaces:
Sleeping
Sleeping
| 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) | |
| 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) | |
| 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) | |
| 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) | |
| def backup(): | |
| try: | |
| upload_db_to_hf() | |
| return "Резервная копия успешно создана.", 200 | |
| except Exception as e: | |
| return f"Ошибка при создании резервной копии: {e}", 500 | |
| 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) |