Spaces:
Running
Running
from flask import Flask, render_template_string, request, redirect, url_for | |
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 | |
app = Flask(__name__) | |
DATA_FILE = 'data_ordotech.json' | |
# Настройки Hugging Face | |
REPO_ID = "flpolprojects/Clients" | |
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/ru1ZigdIOp66ylQNXKkHx.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: | |
return {'products': [], 'categories': [] if not isinstance(data, list) else data} | |
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(): | |
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(): | |
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 as e: | |
logging.error(f"Репозиторий не найден: {e}") | |
raise | |
except Exception as e: | |
logging.error(f"Ошибка при скачивании JSON базы: {e}") | |
raise | |
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"> | |
<meta name="google-site-verification" content="V6EqDTA9Oj9V1OfNbnBHj5RKrdcXlABD8tqfEFVUHJY" /> | |
<title>Техно Ордо Бишкек бытовая техника </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> | |
/* Существующие стили остаются без изменений */ | |
* { | |
margin: 0; | |
padding: 0; | |
box-sizing: border-box; | |
} | |
body { | |
font-family: 'Poppins', sans-serif; | |
background: linear-gradient(135deg, #f0f2f5, #e9ecef); | |
color: #2d3748; | |
line-height: 1.6; | |
transition: background 0.3s, color 0.3s; | |
} | |
body.dark-mode { | |
background: linear-gradient(135deg, #1a202c, #2d3748); | |
color: #e2e8f0; | |
} | |
.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 #e2e8f0; | |
} | |
.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; | |
} | |
.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; | |
} | |
.theme-toggle { | |
background: none; | |
border: none; | |
font-size: 1.5rem; | |
cursor: pointer; | |
color: #4a5568; | |
transition: color 0.3s ease; | |
} | |
.theme-toggle:hover { | |
color: #3b82f6; | |
} | |
.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 #e2e8f0; | |
border-radius: 8px; | |
outline: none; | |
box-shadow: 0 2px 5px rgba(0,0,0,0.05); | |
transition: all 0.3s ease; | |
} | |
#search-input:focus { | |
border-color: #3b82f6; | |
box-shadow: 0 4px 15px rgba(59, 130, 246, 0.2); | |
} | |
.category-filter { | |
padding: 8px 16px; | |
border: 1px solid #e2e8f0; | |
border-radius: 8px; | |
background-color: #fff; | |
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: #3b82f6; | |
color: white; | |
border-color: #3b82f6; | |
box-shadow: 0 2px 10px rgba(59, 130, 246, 0.3); | |
} | |
.products-grid { | |
display: grid; | |
grid-template-columns: repeat(2, minmax(200px, 1fr)); | |
gap: 15px; | |
padding: 10px; | |
} | |
.product { | |
background: #fff; | |
border-radius: 15px; | |
padding: 15px; | |
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1); | |
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; | |
overflow: hidden; | |
} | |
body.dark-mode .product { | |
background: #2d3748; | |
color: #fff; | |
} | |
.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; | |
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; | |
white-space: nowrap; | |
} | |
body.dark-mode .product-description { | |
color: #a0aec0; | |
} | |
.product-button { | |
display: block; | |
width: 100%; | |
padding: 8px; | |
border: none; | |
border-radius: 8px; | |
background-color: #3b82f6; | |
color: white; | |
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: #2563eb; | |
box-shadow: 0 4px 15px rgba(37, 99, 235, 0.4); | |
transform: translateY(-2px); | |
} | |
.add-to-cart { | |
background-color: #10b981; | |
} | |
.add-to-cart:hover { | |
background-color: #059669; | |
box-shadow: 0 4px 15px rgba(5, 150, 105, 0.4); | |
} | |
#cart-button { | |
position: fixed; | |
bottom: 20px; | |
right: 20px; | |
background-color: #ef4444; | |
color: white; | |
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; | |
} | |
.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); | |
} | |
.modal-content { | |
background: #fff; | |
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; | |
} | |
body.dark-mode .modal-content { | |
background: #2d3748; | |
color: #e2e8f0; | |
} | |
@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: #2d3748; | |
} | |
body.dark-mode .close { | |
color: #a0aec0; | |
} | |
body.dark-mode .close:hover { | |
color: #fff; | |
} | |
.cart-item { | |
display: flex; | |
justify-content: space-between; | |
align-items: center; | |
padding: 15px 0; | |
border-bottom: 1px solid #e2e8f0; | |
} | |
body.dark-mode .cart-item { | |
border-bottom: 1px solid #4a5568; | |
} | |
.cart-item img { | |
width: 50px; | |
height: 50px; | |
object-fit: contain; | |
border-radius: 8px; | |
margin-right: 15px; | |
} | |
.quantity-input, .color-select { | |
width: 100%; | |
max-width: 150px; | |
padding: 8px; | |
border: 1px solid #e2e8f0; | |
border-radius: 8px; | |
font-size: 1rem; | |
margin: 5px 0; | |
} | |
.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: #10b981; | |
} | |
.order-button:hover { | |
background-color: #059669; | |
box-shadow: 0 4px 15px rgba(5, 150, 105, 0.4); | |
} | |
</style> | |
</head> | |
<body> | |
<div class="container"> | |
<div class="header"> | |
<img src="''' + LOGO_URL + '''" alt="Logo" class="header-logo"> | |
<h1>Каталог</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> | |
{% endif %} | |
<h2>{{ product['name'] }}</h2> | |
<div class="product-price">{{ product['price'] }} с</div> | |
<p class="product-description">{{ product['description'][:50] }}{% if product['description']|length > 50 %}...{% endif %}</p> | |
<button class="product-button" onclick="openModal({{ loop.index0 }})">Подробнее</button> | |
<button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})">В корзину</button> | |
</div> | |
{% endfor %} | |
</div> | |
</div> | |
<!-- Product Modal --> | |
<div id="productModal" class="modal"> | |
<div class="modal-content"> | |
<span class="close" onclick="closeModal('productModal')">×</span> | |
<div id="modalContent"></div> | |
</div> | |
</div> | |
<!-- Quantity and Color Modal --> | |
<div id="quantityModal" class="modal"> | |
<div class="modal-content"> | |
<span class="close" onclick="closeModal('quantityModal')">×</span> | |
<h2>Укажите количество и цвет</h2> | |
<input type="number" id="quantityInput" class="quantity-input" min="1" value="1"> | |
<select id="colorSelect" class="color-select"></select> | |
<button class="product-button" onclick="confirmAddToCart()">Добавить</button> | |
</div> | |
</div> | |
<!-- Cart Modal --> | |
<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()">🛒</button> | |
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> | |
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/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'); | |
document.querySelector('.theme-toggle i').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() { | |
new Swiper('.swiper-container', { | |
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 } | |
}); | |
} | |
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 = 'Нет цвета'; | |
option.text = 'Нет цвета'; | |
colorSelect.appendChild(option); | |
} | |
document.getElementById('quantityModal').style.display = 'block'; | |
document.getElementById('quantityInput').value = 1; | |
} | |
function confirmAddToCart() { | |
if (selectedProductIndex === null) return; | |
const quantity = parseInt(document.getElementById('quantityInput').value) || 1; | |
const color = document.getElementById('colorSelect').value; | |
if (quantity <= 0) { | |
alert("Укажите количество больше 0"); | |
return; | |
} | |
let cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
const product = products[selectedProductIndex]; | |
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(); | |
} | |
function updateCartButton() { | |
const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
document.getElementById('cart-button').style.display = cart.length > 0 ? 'block' : 'none'; | |
} | |
function openCartModal() { | |
const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
const cartContent = document.getElementById('cartContent'); | |
let total = 0; | |
cartContent.innerHTML = cart.length === 0 ? '<p>Корзина пуста</p>' : cart.map(item => { | |
const itemTotal = item.price * item.quantity; | |
total += itemTotal; | |
return ` | |
<div class="cart-item"> | |
<div style="display: flex; align-items: center;"> | |
${item.photo ? `<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}" alt="${item.name}">` : ''} | |
<div> | |
<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 = item.price * item.quantity; | |
total += itemTotal; | |
orderText += `${index + 1}. ${item.name} - ${item.price} с × ${item.quantity} (Цвет: ${item.color})%0A`; | |
}); | |
orderText += `Итого: ${total} с`; | |
window.open(`https://api.whatsapp.com/send?phone=996503133188&text=${orderText}`, '_blank'); | |
} | |
function clearCart() { | |
localStorage.removeItem('cart'); | |
closeModal('cartModal'); | |
updateCartButton(); | |
} | |
window.onclick = function(event) { | |
if (event.target.className === '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(product => { | |
const name = product.getAttribute('data-name'); | |
const description = product.getAttribute('data-description'); | |
const category = product.getAttribute('data-category'); | |
const matchesSearch = name.includes(searchTerm) || description.includes(searchTerm); | |
const matchesCategory = activeCategory === 'all' || category === activeCategory; | |
product.style.display = matchesSearch && matchesCategory ? 'block' : 'none'; | |
}); | |
} | |
updateCartButton(); | |
</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: 20px;"> | |
<h2 style="font-size: 1.8rem; font-weight: 600; margin-bottom: 20px;">{{ product['name'] }}</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;"> | |
<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: 300px; object-fit: contain;"> | |
</div> | |
</div> | |
{% endfor %} | |
{% else %} | |
<div class="swiper-slide"> | |
<img src="https://via.placeholder.com/300" alt="No Image"> | |
</div> | |
{% endif %} | |
</div> | |
<div class="swiper-pagination"></div> | |
<div class="swiper-button-next"></div> | |
<div class="swiper-button-prev"></div> | |
</div> | |
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> | |
<p><strong>Цена:</strong> {{ product['price'] }} с</p> | |
<p><strong>Описание:</strong> {{ product['description'] }}</p> | |
<p><strong>Доступные цвета:</strong> {{ product.get('colors', ['Нет цветов'])|join(', ') }}</p> | |
</div> | |
''' | |
return render_template_string(detail_html, product=product, repo_id=REPO_ID) | |
def admin(): | |
data = load_data() | |
products = data['products'] | |
categories = data['categories'] | |
if request.method == 'POST': | |
action = request.form.get('action') | |
if action == 'add_category': | |
category_name = request.form.get('category_name') | |
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': | |
category_index = int(request.form.get('category_index')) | |
deleted_category = categories.pop(category_index) | |
for product in products: | |
if product.get('category') == deleted_category: | |
product['category'] = 'Без категории' | |
save_data(data) | |
return redirect(url_for('admin')) | |
elif action == 'add': | |
name = request.form.get('name') | |
price = request.form.get('price') | |
description = request.form.get('description') | |
category = request.form.get('category') | |
photos_files = request.files.getlist('photos') | |
colors = request.form.getlist('colors') # Получаем список цветов | |
photos_list = [] | |
if photos_files: | |
for photo in photos_files[:2]: | |
if photo and photo.filename: | |
photo_filename = secure_filename(photo.filename) | |
uploads_dir = 'uploads' | |
os.makedirs(uploads_dir, exist_ok=True) | |
temp_path = os.path.join(uploads_dir, photo_filename) | |
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"Добавлено фото для товара {name}" | |
) | |
photos_list.append(photo_filename) | |
if os.path.exists(temp_path): | |
os.remove(temp_path) | |
if not name or not price or not description: | |
return "Ошибка: Заполните все обязательные поля", 400 | |
price = float(price.replace(',', '.')) | |
new_product = { | |
'name': name, | |
'price': price, | |
'description': description, | |
'category': category if category in categories else 'Без категории', | |
'photos': photos_list, | |
'colors': colors if colors else [] # Добавляем цвета | |
} | |
products.append(new_product) | |
save_data(data) | |
return redirect(url_for('admin')) | |
elif action == 'edit': | |
index = int(request.form.get('index')) | |
name = request.form.get('name') | |
price = request.form.get('price') | |
description = request.form.get('description') | |
category = request.form.get('category') | |
photos_files = request.files.getlist('photos') | |
colors = request.form.getlist('colors') # Обновляем цвета | |
if photos_files and any(photo.filename for photo in photos_files): | |
new_photos_list = [] | |
for photo in photos_files[:2]: | |
if photo and photo.filename: | |
photo_filename = secure_filename(photo.filename) | |
uploads_dir = 'uploads' | |
os.makedirs(uploads_dir, exist_ok=True) | |
temp_path = os.path.join(uploads_dir, photo_filename) | |
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"Обновлено фото для товара {name}" | |
) | |
new_photos_list.append(photo_filename) | |
if os.path.exists(temp_path): | |
os.remove(temp_path) | |
products[index]['photos'] = new_photos_list | |
products[index]['name'] = name | |
products[index]['price'] = float(price.replace(',', '.')) | |
products[index]['description'] = description | |
products[index]['category'] = category if category in categories else 'Без категории' | |
products[index]['colors'] = colors if colors else [] # Обновляем цвета | |
save_data(data) | |
return redirect(url_for('admin')) | |
elif action == 'delete': | |
index = int(request.form.get('index')) | |
del products[index] | |
save_data(data) | |
return redirect(url_for('admin')) | |
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> | |
body { | |
font-family: 'Poppins', sans-serif; | |
background: linear-gradient(135deg, #f0f2f5, #e9ecef); | |
color: #2d3748; | |
padding: 20px; | |
} | |
.container { | |
max-width: 1200px; | |
margin: 0 auto; | |
} | |
.header { | |
display: flex; | |
align-items: center; | |
padding: 15px 0; | |
border-bottom: 1px solid #e2e8f0; | |
} | |
.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: 600; | |
margin-bottom: 20px; | |
} | |
form { | |
background: #fff; | |
padding: 20px; | |
border-radius: 15px; | |
box-shadow: 0 4px 15px rgba(0,0,0,0.1); | |
margin-bottom: 30px; | |
} | |
label { | |
font-weight: 500; | |
margin-top: 15px; | |
display: block; | |
} | |
input, textarea, select { | |
width: 100%; | |
padding: 12px; | |
margin-top: 5px; | |
border: 1px solid #e2e8f0; | |
border-radius: 8px; | |
font-size: 1rem; | |
transition: all 0.3s ease; | |
} | |
input:focus, textarea:focus, select:focus { | |
border-color: #3b82f6; | |
box-shadow: 0 0 5px rgba(59, 130, 246, 0.3); | |
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; | |
} | |
button:hover { | |
background-color: #2563eb; | |
box-shadow: 0 4px 15px rgba(37, 99, 235, 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; | |
} | |
.product-item, .category-item { | |
background: #fff; | |
padding: 20px; | |
border-radius: 15px; | |
box-shadow: 0 4px 15px rgba(0,0,0,0.1); | |
} | |
.edit-form { | |
margin-top: 15px; | |
padding: 15px; | |
background: #f7fafc; | |
border-radius: 10px; | |
} | |
.color-input-group { | |
display: flex; | |
gap: 10px; | |
margin-top: 5px; | |
} | |
.add-color-btn { | |
background-color: #10b981; | |
} | |
.add-color-btn:hover { | |
background-color: #059669; | |
} | |
</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>Название товара:</label> | |
<input type="text" name="name" required> | |
<label>Цена:</label> | |
<input type="number" name="price" step="0.01" required> | |
<label>Описание:</label> | |
<textarea name="description" rows="4" required></textarea> | |
<label>Категория:</label> | |
<select name="category"> | |
<option value="Без категории">Без категории</option> | |
{% for category in categories %} | |
<option value="{{ category }}">{{ category }}</option> | |
{% endfor %} | |
</select> | |
<label>Фотографии (до 2):</label> | |
<input type="file" name="photos" accept="image/*" multiple> | |
<label>Цвета:</label> | |
<div id="color-inputs"> | |
<div class="color-input-group"> | |
<input type="text" name="colors" placeholder="Например: Красный"> | |
</div> | |
</div> | |
<button type="button" class="add-color-btn" onclick="addColorInput()">Добавить цвет</button> | |
<button type="submit">Добавить товар</button> | |
</form> | |
<h1>Управление категориями</h1> | |
<form method="POST"> | |
<input type="hidden" name="action" value="add_category"> | |
<label>Название категории:</label> | |
<input type="text" 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 }}</h3> | |
<form method="POST" style="display: inline;"> | |
<input type="hidden" name="action" value="delete_category"> | |
<input type="hidden" name="category_index" value="{{ loop.index0 }}"> | |
<button type="submit" class="delete-button">Удалить</button> | |
</form> | |
</div> | |
{% endfor %} | |
</div> | |
<h2>Управление базой данных</h2> | |
<form method="POST" action="{{ url_for('backup') }}" style="display: inline;"> | |
<button type="submit">Создать копию</button> | |
</form> | |
<form method="GET" action="{{ url_for('download') }}" style="display: inline;"> | |
<button type="submit">Скачать базу</button> | |
</form> | |
<h2>Список товаров</h2> | |
<div class="product-list"> | |
{% for product in products %} | |
<div class="product-item"> | |
<h3>{{ product['name'] }}</h3> | |
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> | |
<p><strong>Цена:</strong> {{ product['price'] }} с</p> | |
<p><strong>Описание:</strong> {{ product['description'] }}</p> | |
<p><strong>Цвета:</strong> {{ product.get('colors', ['Нет цветов'])|join(', ') }}</p> | |
{% if product.get('photos') and product['photos']|length > 0 %} | |
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" | |
alt="{{ product['name'] }}" | |
style="max-width: 100px; border-radius: 10px;"> | |
{% 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>Название:</label> | |
<input type="text" name="name" value="{{ product['name'] }}" required> | |
<label>Цена:</label> | |
<input type="number" name="price" step="0.01" value="{{ product['price'] }}" required> | |
<label>Описание:</label> | |
<textarea name="description" rows="4" required>{{ product['description'] }}</textarea> | |
<label>Категория:</label> | |
<select name="category"> | |
<option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option> | |
{% for category in categories %} | |
<option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option> | |
{% endfor %} | |
</select> | |
<label>Фотографии:</label> | |
<input type="file" 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 }}"> | |
</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"> | |
<input type="hidden" name="action" value="delete"> | |
<input type="hidden" name="index" value="{{ loop.index0 }}"> | |
<button type="submit" class="delete-button">Удалить</button> | |
</form> | |
</div> | |
{% endfor %} | |
</div> | |
</div> | |
<script> | |
function addColorInput(containerId = 'color-inputs') { | |
const container = document.getElementById(containerId); | |
const newInput = document.createElement('div'); | |
newInput.className = 'color-input-group'; | |
newInput.innerHTML = '<input type="text" name="colors" placeholder="Например: Красный">'; | |
container.appendChild(newInput); | |
} | |
</script> | |
</body> | |
</html> | |
''' | |
return render_template_string(admin_html, products=products, categories=categories, repo_id=REPO_ID) | |
def backup(): | |
upload_db_to_hf() | |
return "Резервная копия создана.", 200 | |
def download(): | |
download_db_from_hf() | |
return "База данных скачана.", 200 | |
if __name__ == '__main__': | |
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) |