diff --git "a/app.py" "b/app.py" deleted file mode 100644--- "a/app.py" +++ /dev/null @@ -1,1783 +0,0 @@ - -from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify -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 -from dotenv import load_dotenv -import requests -import uuid - -load_dotenv() - -app = Flask(__name__) -app.secret_key = 'your_unique_secret_key_santehopt_12345_no_login' -DATA_FILE = 'data.json' - -SYNC_FILES = [DATA_FILE] - -REPO_ID = "Kgshop/santehopt" -HF_TOKEN_WRITE = os.getenv("HF_TOKEN") -HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") - -STORE_ADDRESS = "Рынок Евразия (Дордой ) , 29 контейнер " - -CURRENCY_CODE = 'KGS' -CURRENCY_NAME = 'Кыргызский сом' - -DOWNLOAD_RETRIES = 3 -DOWNLOAD_DELAY = 5 - -logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') - -def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY): - if not HF_TOKEN_READ and not HF_TOKEN_WRITE: - logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.") - - token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE - - files_to_download = [specific_file] if specific_file else SYNC_FILES - logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...") - all_successful = True - - for file_name in files_to_download: - success = False - for attempt in range(retries + 1): - try: - logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...") - local_path = hf_hub_download( - repo_id=REPO_ID, - filename=file_name, - repo_type="dataset", - token=token_to_use, - local_dir=".", - local_dir_use_symlinks=False, - force_download=True, - resume_download=False - ) - logging.info(f"Successfully downloaded {file_name} to {local_path}.") - success = True - break - except RepositoryNotFoundError: - logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.") - return False - except HfHubHTTPError as e: - if e.response.status_code == 404: - logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.") - if attempt == 0 and not os.path.exists(file_name): - try: - if file_name == DATA_FILE: - with open(file_name, 'w', encoding='utf-8') as f: - json.dump({'products': [], 'categories': [], 'orders': {}}, f) - logging.info(f"Created empty local file {file_name} because it was not found on HF.") - except Exception as create_e: - logging.error(f"Failed to create empty local file {file_name}: {create_e}") - success = False - break - else: - logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") - except requests.exceptions.RequestException as e: - logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") - except Exception as e: - logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True) - - if attempt < retries: - time.sleep(delay) - - if not success: - logging.error(f"Failed to download {file_name} after {retries + 1} attempts.") - all_successful = False - - logging.info(f"Download process finished. Overall success: {all_successful}") - return all_successful - -def upload_db_to_hf(specific_file=None): - if not HF_TOKEN_WRITE: - logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.") - return - try: - api = HfApi() - files_to_upload = [specific_file] if specific_file else SYNC_FILES - logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...") - - for file_name in files_to_upload: - if os.path.exists(file_name): - try: - api.upload_file( - path_or_fileobj=file_name, - path_in_repo=file_name, - repo_id=REPO_ID, - repo_type="dataset", - token=HF_TOKEN_WRITE, - commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" - ) - logging.info(f"File {file_name} successfully uploaded to Hugging Face.") - except Exception as e: - logging.error(f"Error uploading file {file_name} to Hugging Face: {e}") - else: - logging.warning(f"File {file_name} not found locally, skipping upload.") - logging.info("Finished uploading files to HF.") - except Exception as e: - logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True) - -def periodic_backup(): - backup_interval = 1800 - logging.info(f"Setting up periodic backup every {backup_interval} seconds.") - while True: - time.sleep(backup_interval) - logging.info("Starting periodic backup...") - upload_db_to_hf() - logging.info("Periodic backup finished.") - -def load_data(): - default_data = {'products': [], 'categories': [], 'orders': {}} - - def attempt_load_file(): - try: - with open(DATA_FILE, 'r', encoding='utf-8') as file: - data = json.load(file) - if not isinstance(data, dict): - raise TypeError("Data structure is not a dictionary.") - if 'products' not in data: data['products'] = [] - if 'categories' not in data: data['categories'] = [] - if 'orders' not in data: data['orders'] = {} - - # Ensure all products have unique IDs - for product in data['products']: - if 'id' not in product: - product['id'] = uuid.uuid4().hex - - return data - except FileNotFoundError: - logging.warning(f"Local file {DATA_FILE} not found.") - return None - except (json.JSONDecodeError, TypeError) as e: - logging.error(f"Error decoding or validating JSON in local {DATA_FILE}: {e}. File might be corrupt.") - return None - except Exception as e: - logging.error(f"Unknown error during local load: {e}", exc_info=True) - return None - - data = attempt_load_file() - - if data is None: - logging.info(f"Attempting download from HF.") - if download_db_from_hf(specific_file=DATA_FILE): - data = attempt_load_file() - if data is not None: - logging.info(f"Data loaded successfully from {DATA_FILE} after download.") - return data - - logging.error(f"Failed to load data after retries and download attempts. Using empty default data structure.") - - if not os.path.exists(DATA_FILE): - try: - with open(DATA_FILE, 'w', encoding='utf-8') as f: - json.dump(default_data, f) - logging.info(f"Created empty local file {DATA_FILE} after failed load.") - except Exception as create_e: - logging.error(f"Failed to create empty local file {DATA_FILE}: {create_e}") - - return default_data - - -def save_data(data): - try: - if not isinstance(data, dict): - logging.error("Attempted to save invalid data structure (not a dict). Aborting save.") - return - if 'products' not in data: data['products'] = [] - if 'categories' not in data: data['categories'] = [] - if 'orders' not in data: data['orders'] = {} - - with open(DATA_FILE, 'w', encoding='utf-8') as file: - json.dump(data, file, ensure_ascii=False, indent=4) - logging.info(f"Data successfully saved to {DATA_FILE}") - upload_db_to_hf(specific_file=DATA_FILE) - except Exception as e: - logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True) - - -CATALOG_TEMPLATE = ''' - - - - - - Сантехника оптом - Каталог - - - - - - -
-
-

Сантехника оптом

-
- -
Наш адрес: {{ store_address }}
- -
- - {% for category in categories %} - - {% endfor %} -
- -
- -
- -
- {% for product in products_list %} -
- {% if product.get('is_top', False) %} - Топ - {% endif %} -
- {% if product.get('photos') and product['photos']|length > 0 %} - {{ product['name'] }} - {% else %} - No Image - {% endif %} -
-
-

{{ product['name'] }}

-
{{ "%.2f"|format(product['price']) }} {{ currency_code }}
-

{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}

-
-
- -
-
- {% endfor %} - {% if not products_list %} -

Товары пока не добавлены.

- {% endif %} -
-
- - - - - - - - - -
- - - - - -''' - -PRODUCT_DETAIL_TEMPLATE = ''' -
-

{{ product['name'] }}

-
-
- {% if product.get('photos') and product['photos']|length > 0 %} - {% for photo in product['photos'] %} -
-
- {{ product['name'] }} - фото {{ loop.index }} -
-
- {% endfor %} - {% else %} -
- Изображение отсутствует -
- {% endif %} -
- {% if product.get('photos') and product['photos']|length > 1 %} -
-
-
- {% endif %} -
- -
-

Категория: {{ product.get('category', 'Без категории') }}

-

Цена: {{ "%.2f"|format(product['price']) }} {{ currency_code }}

-

Описание:
{{ product.get('description', 'Описание отсутствует.')|replace('\\n', '
')|safe }}

- {% set colors = product.get('colors', []) %} - {% if colors and colors|select('ne', '')|list|length > 0 %} -

Доступные цвета/варианты: {{ colors|select('ne', '')|join(', ') }}

- {% endif %} -
-
-''' - -ORDER_TEMPLATE = ''' - - - - - - Заказ №{{ order.id }} - Сантехника оптом - - - - - -
- {% if order %} -

Ваш Заказ №{{ order.id }}

-

Дата создания: {{ order.created_at }}

- -

Товары в заказе

-
- {% for item in order.cart %} -
- {{ item.name }} -
- {{ item.name }} {% if item.color != 'N/A' %}({{ item.color }}){% endif %} - {{ "%.2f"|format(item.price) }} {{ currency_code }} × {{ item.quantity }} -
-
- {{ "%.2f"|format(item.price * item.quantity) }} {{ currency_code }} -
-
- {% endfor %} -
- -
-

Общая сумма товаров: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}

-

ИТОГО К ОПЛАТЕ: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}

-
- -
-

Статус заказа

-

Этот заказ был оформлен без входа в систему.

-

Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.

-
- -
- -
- - ← Вернуться в каталог - - - - {% else %} -

Ошибка

-

Заказ с таким ID не найден.

- ← Вернуться в каталог - {% endif %} -
- - -''' - -ADMIN_TEMPLATE = ''' - - - - - - Админ-панель - Сантехника оптом - - - - - -
-
-

Админ-панель Сантехника оптом

- Перейти в каталог -
- - {% with messages = get_flashed_messages(with_categories=true) %} - {% if messages %} - {% for category, message in messages %} -
{{ message }}
- {% endfor %} - {% endif %} - {% endwith %} - -
-

Синхронизация с Датацентром

-
-
- -
-
- -
-
-

Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.

-
- -
-
-
-

Управление категориями

-
- Добавить новую категорию -
-
- - - - -
-
-
- -

Существующие категории:

- {% if categories %} -
- {% for category in categories %} -
- {{ category }} -
- - - -
-
- {% endfor %} -
- {% else %} -

Категорий пока нет.

- {% endif %} -
-
- -
-
-

Информация

-

Управление пользователями отключено, так как сайт не требует входа.

-

Заказы создаются анонимно и должны быть подтверждены через WhatsApp.

-
-
-
- -
-

Управление товарами

-
- Добавить новый товар -
-
- - - - - - - - - - - - -
-
- - -
-
- -
-
- - -
-
- - -
-
- -
-
-
- -

Список товаров:

-
- -
- {% if products %} -
- {% for product in products %} -
-
-
- {% if product.get('photos') %} - - Фото - - {% else %} - Нет фото - {% endif %} -
-
-

- {{ product['name'] }} - {% if product.get('in_stock', True) %} - В наличии - {% else %} - Нет в наличии - {% endif %} - {% if product.get('is_top', False) %} - Топ - {% endif %} -

-

Категория: {{ product.get('category', 'Без категории') }}

-

Цена: {{ "%.2f"|format(product['price']) }} {{ currency_code }}

-

Описание: {{ product.get('description', 'N/A')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}

- {% set colors = product.get('colors', []) %} -

Цвета/Вар-ts: {{ colors|select('ne', '')|join(', ') if colors|select('ne', '')|list|length > 0 else 'Нет' }}

- {% if product.get('photos') and product['photos']|length > 1 %} -

(Всего фото: {{ product['photos']|length }})

- {% endif %} -
-
- -
- -
- - - -
-
- -
-

Редактирование: {{ product['name'] }}

-
- - - - - - - - - - - - - {% if product.get('photos') %} -

Текущие фото:

-
- {% for photo in product['photos'] %} - Фото {{ loop.index }} - {% endfor %} -
- {% endif %} - -
- {% set current_colors = product.get('colors', []) %} - {% if current_colors and current_colors|select('ne', '')|list|length > 0 %} - {% for color in current_colors %} - {% if color.strip() %} -
- - -
- {% endif %} - {% endfor %} - {% else %} -
- - -
- {% endif %} -
- -
-
- - -
-
- - -
-
- -
-
-
- {% endfor %} -
- {% else %} -

Товаров пока нет.

- {% endif %} -
- -
- - - - -''' - -def find_product_by_id(data, product_id): - """Finds product by ID and returns its index and object.""" - return next(((i, p) for i, p in enumerate(data.get('products', [])) if p.get('id') == product_id), (None, None)) - -@app.route('/') -def catalog(): - data = load_data() - all_products = data.get('products', []) - categories = sorted(data.get('categories', [])) - - products_in_stock = [p for p in all_products if p.get('in_stock', True)] - products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower())) - - products_map = {p['id']: p for p in products_sorted} - - return render_template_string( - CATALOG_TEMPLATE, - products_list=products_sorted, - products_map=products_map, - categories=categories, - repo_id=REPO_ID, - store_address=STORE_ADDRESS, - currency_code=CURRENCY_CODE - ) - -@app.route('/product/') -def product_detail(product_id): - data = load_data() - all_products = data.get('products', []) - - product = next((p for p in all_products if p.get('id') == product_id), None) - - if not product or not product.get('in_stock', True): - logging.warning(f"Attempted access to non-existent or out-of-stock product with ID {product_id}") - return "Товар не найден или отсутствует в наличии.", 404 - - return render_template_string( - PRODUCT_DETAIL_TEMPLATE, - product=product, - repo_id=REPO_ID, - currency_code=CURRENCY_CODE - ) - -@app.route('/create_order', methods=['POST']) -def create_order(): - order_data = request.get_json() - - if not order_data or 'cart' not in order_data or not order_data['cart']: - logging.warning("Create order request missing cart data or cart is empty.") - return jsonify({"error": "Корзина пуста или не передана."}), 400 - - cart_items = order_data['cart'] - - total_price = 0 - processed_cart = [] - for item in cart_items: - if not all(k in item for k in ('name', 'price', 'quantity')): - logging.error(f"Invalid cart item structure received: {item}") - return jsonify({"error": "Неверный формат товара в корзине."}), 400 - try: - price = float(item['price']) - quantity = int(item['quantity']) - if price < 0 or quantity <= 0: - raise ValueError("Invalid price or quantity") - total_price += price * quantity - processed_cart.append({ - "name": item['name'], - "price": price, - "quantity": quantity, - "color": item.get('color', 'N/A'), - "product_id": item.get('product_id'), - "photo": item.get('photo'), - "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item['photo']}" if item.get('photo') else "https://via.placeholder.com/60x60.png?text=N/A" - }) - except (ValueError, TypeError) as e: - logging.error(f"Invalid price/quantity in cart item: {item}. Error: {e}") - return jsonify({"error": "Неверная цена или количество в товаре."}), 400 - - order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}" - order_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') - - new_order = { - "id": order_id, - "created_at": order_timestamp, - "cart": processed_cart, - "total_price": round(total_price, 2), - "user_info": None, - "status": "new" - } - - try: - data = load_data() - if 'orders' not in data or not isinstance(data.get('orders'), dict): - data['orders'] = {} - - data['orders'][order_id] = new_order - save_data(data) - logging.info(f"Order {order_id} created successfully (anonymously).") - return jsonify({"order_id": order_id}), 201 - - except Exception as e: - logging.error(f"Failed to save order {order_id}: {e}", exc_info=True) - return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500 - - -@app.route('/order/') -def view_order(order_id): - data = load_data() - order = data.get('orders', {}).get(order_id) - - if order: - logging.info(f"Displaying order {order_id}") - else: - logging.warning(f"Order {order_id} not found.") - - return render_template_string(ORDER_TEMPLATE, - order=order, - repo_id=REPO_ID, - currency_code=CURRENCY_CODE) - - -@app.route('/admin', methods=['GET', 'POST']) -def admin(): - data = load_data() - products = data.get('products', []) - categories = data.get('categories', []) - if 'orders' not in data or not isinstance(data.get('orders'), dict): - data['orders'] = {} - - if request.method == 'POST': - action = request.form.get('action') - logging.info(f"Admin action received: {action}") - - try: - 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) - data['categories'] = categories - save_data(data) - logging.info(f"Category '{category_name}' added.") - flash(f"Категория '{category_name}' успешно добавлена.", 'success') - elif not category_name: - logging.warning("Attempted to add empty category.") - flash("Название категории не может быть пустым.", 'error') - else: - logging.warning(f"Category '{category_name}' already exists.") - flash(f"Категория '{category_name}' уже существует.", 'error') - - elif action == 'delete_category': - category_to_delete = request.form.get('category_name') - if category_to_delete and category_to_delete in categories: - categories.remove(category_to_delete) - updated_count = 0 - for product in products: - if product.get('category') == category_to_delete: - product['category'] = 'Без категории' - updated_count += 1 - data['categories'] = categories - data['products'] = products - save_data(data) - logging.info(f"Category '{category_to_delete}' deleted. Updated products: {updated_count}.") - flash(f"Категория '{category_to_delete}' удалена. {updated_count} товаров обновлено.", 'success') - else: - logging.warning(f"Attempted to delete non-existent or empty category: {category_to_delete}") - flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error') - - elif action == 'add_product': - name = request.form.get('name', '').strip() - price_str = request.form.get('price', '').replace(',', '.') - 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()] - in_stock = 'in_stock' in request.form - is_top = 'is_top' in request.form - - if not name or not price_str: - flash("Название и цена товара обязательны.", 'error') - return redirect(url_for('admin')) - - try: - price = round(float(price_str), 2) - if price < 0: price = 0 - except ValueError: - flash("Неверный формат цены.", 'error') - return redirect(url_for('admin')) - - photos_list = [] - if photos_files and HF_TOKEN_WRITE: - uploads_dir = 'uploads_temp' - os.makedirs(uploads_dir, exist_ok=True) - api = HfApi() - photo_limit = 10 - uploaded_count = 0 - for photo in photos_files: - if uploaded_count >= photo_limit: - logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.") - flash(f"Загружено только первые {photo_limit} фото.", "warning") - break - if photo and photo.filename: - try: - ext = os.path.splitext(photo.filename)[1].lower() - if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']: - logging.warning(f"Skipping non-image file upload: {photo.filename}") - flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning") - continue - - safe_name = secure_filename(name.replace(' ', '_'))[:50] - photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}" - temp_path = os.path.join(uploads_dir, photo_filename) - photo.save(temp_path) - logging.info(f"Uploading photo {photo_filename} to HF for product {name}...") - 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"Add photo for product {name}" - ) - photos_list.append(photo_filename) - logging.info(f"Photo {photo_filename} uploaded successfully.") - os.remove(temp_path) - uploaded_count += 1 - except Exception as e: - logging.error(f"Error uploading photo {photo.filename} to HF: {e}", exc_info=True) - flash(f"Ошибка при загрузке фото {photo.filename}.", 'error') - if os.path.exists(temp_path): - try: os.remove(temp_path) - except OSError: pass - elif photo and not photo.filename: - logging.warning("Received an empty photo file object when adding product.") - try: - if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): - os.rmdir(uploads_dir) - except OSError as e: - logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}") - elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files): - flash("HF_TOKEN (write) не настроен. Фотографии не были загружены.", "warning") - - - new_product = { - 'id': uuid.uuid4().hex, - 'name': name, 'price': price, 'description': description, - 'category': category if category in categories else 'Без категории', - 'photos': photos_list, 'colors': colors, - 'in_stock': in_stock, 'is_top': is_top - } - products.append(new_product) - data['products'] = products - save_data(data) - logging.info(f"Product '{name}' added with ID {new_product['id']}.") - flash(f"Товар '{name}' успешно добавлен.", 'success') - - elif action == 'edit_product': - product_id = request.form.get('product_id') - if not product_id: - flash("Ошибка редактирования: ID товара не передан.", 'error') - return redirect(url_for('admin')) - - index, product_to_edit = find_product_by_id(data, product_id) - - if product_to_edit is None: - flash(f"Ошибка редактирования: товар с ID '{product_id}' не найден.", 'error') - logging.error(f"Product with ID '{product_id}' not found for editing.") - return redirect(url_for('admin')) - - original_name = product_to_edit.get('name', 'N/A') - - product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip() - price_str = request.form.get('price', str(product_to_edit['price'])).replace(',', '.') - product_to_edit['description'] = request.form.get('description', product_to_edit.get('description', '')).strip() - category = request.form.get('category') - product_to_edit['category'] = category if category in categories else 'Без категории' - product_to_edit['colors'] = [c.strip() for c in request.form.getlist('colors') if c.strip()] - product_to_edit['in_stock'] = 'in_stock' in request.form - product_to_edit['is_top'] = 'is_top' in request.form - - try: - price = round(float(price_str), 2) - if price < 0: price = 0 - product_to_edit['price'] = price - except ValueError: - logging.warning(f"Invalid price format '{price_str}' during edit of product {original_name}. Price not changed.") - flash(f"Неверный формат цены для товара '{original_name}'. Цена не изменена.", 'warning') - - photos_files = request.files.getlist('photos') - if photos_files and any(f.filename for f in photos_files) and HF_TOKEN_WRITE: - uploads_dir = 'uploads_temp' - os.makedirs(uploads_dir, exist_ok=True) - api = HfApi() - new_photos_list = [] - photo_limit = 10 - uploaded_count = 0 - logging.info(f"Uploading new photos for product {product_to_edit['name']}...") - - # 1. Upload new photos - for photo in photos_files: - if uploaded_count >= photo_limit: - logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.") - flash(f"Загружено только первые {photo_limit} фото.", "warning") - break - if photo and photo.filename: - try: - ext = os.path.splitext(photo.filename)[1].lower() - if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']: - logging.warning(f"Skipping non-image file upload during edit: {photo.filename}") - flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning") - continue - - safe_name = secure_filename(product_to_edit['name'].replace(' ', '_'))[:50] - photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}" - temp_path = os.path.join(uploads_dir, photo_filename) - photo.save(temp_path) - logging.info(f"Uploading new photo {photo_filename} to HF...") - 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"Update photo for product {product_to_edit['name']}") - new_photos_list.append(photo_filename) - logging.info(f"New photo {photo_filename} uploaded successfully.") - os.remove(temp_path) - uploaded_count += 1 - except Exception as e: - logging.error(f"Error uploading new photo {photo.filename}: {e}", exc_info=True) - flash(f"Ошибка при загрузке нового фото {photo.filename}.", 'error') - if os.path.exists(temp_path): - try: os.remove(temp_path) - except OSError: pass - - try: - if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): - os.rmdir(uploads_dir) - except OSError as e: - logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}") - - # 2. Replace photo list and delete old ones - if new_photos_list: - old_photos = product_to_edit.get('photos', []) - if old_photos: - logging.info(f"Attempting to delete old photos: {old_photos}") - try: - api = HfApi() - api.delete_files( - repo_id=REPO_ID, - paths_in_repo=[f"photos/{p}" for p in old_photos], - repo_type="dataset", - token=HF_TOKEN_WRITE, - commit_message=f"Delete old photos for product {product_to_edit['name']}" - ) - logging.info(f"Old photos for product {product_to_edit['name']} deleted from HF.") - except Exception as e: - logging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True) - flash("Не удалось удалить старые фотографии с сервера. Новые фото загружены.", "warning") - product_to_edit['photos'] = new_photos_list - flash("Фотог��афии товара успешно обновлены.", "success") - elif uploaded_count == 0 and any(f.filename for f in photos_files): - flash("Не удалось загрузить новые фотографии (возможно, неверный формат).", "error") - elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files): - flash("HF_TOKEN (write) не настроен. Фотографии не были обновлены.", "warning") - - products[index] = product_to_edit - data['products'] = products - save_data(data) - logging.info(f"Product '{original_name}' (ID {product_id}) updated to '{product_to_edit['name']}'.") - flash(f"Товар '{product_to_edit['name']}' успешно обновлен.", 'success') - - elif action == 'delete_product': - product_id = request.form.get('product_id') - if not product_id: - flash("Ошибка удаления: ID товара не передан.", 'error') - return redirect(url_for('admin')) - - index, deleted_product = find_product_by_id(data, product_id) - - if deleted_product is None: - flash(f"Ошибка удаления: товар с ID '{product_id}' не найден.", 'error') - logging.error(f"Product with ID '{product_id}' not found for deletion.") - return redirect(url_for('admin')) - - product_name = deleted_product.get('name', 'N/A') - - photos_to_delete = deleted_product.get('photos', []) - if photos_to_delete and HF_TOKEN_WRITE: - logging.info(f"Attempting to delete photos for product '{product_name}' from HF: {photos_to_delete}") - try: - api = HfApi() - api.delete_files( - repo_id=REPO_ID, - paths_in_repo=[f"photos/{p}" for p in photos_to_delete], - repo_type="dataset", - token=HF_TOKEN_WRITE, - commit_message=f"Delete photos for deleted product {product_name}" - ) - logging.info(f"Photos for product '{product_name}' deleted from HF.") - except Exception as e: - logging.error(f"Error deleting photos {photos_to_delete} for product '{product_name}' from HF: {e}", exc_info=True) - flash(f"Не удалось удалить фото для товара '{product_name}' с сервера. Товар удален локально.", "warning") - elif photos_to_delete and not HF_TOKEN_WRITE: - logging.warning(f"HF_TOKEN (write) not set. Cannot delete photos {photos_to_delete} for deleted product '{product_name}'.") - flash(f"Товар '{product_name}' удален локально, но фото не удалены с сервера (токен не задан).", "warning") - - products.pop(index) - data['products'] = products - save_data(data) - logging.info(f"Product '{product_name}' (ID {product_id}) deleted.") - flash(f"Товар '{product_name}' удален.", 'success') - else: - logging.warning(f"Received unknown admin action: {action}") - flash(f"Неизвестное действие: {action}", 'warning') - - return redirect(url_for('admin')) - - except Exception as e: - logging.error(f"Произошла внутренняя ошибка при выполнении действия '{action}': {e}", exc_info=True) - flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'. Подробности в логе сервера.", 'error') - return redirect(url_for('admin')) - - current_data = load_data() - display_products = sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower()) - display_categories = sorted(current_data.get('categories', [])) - - return render_template_string( - ADMIN_TEMPLATE, - products=display_products, - categories=display_categories, - repo_id=REPO_ID, - currency_code=CURRENCY_CODE - ) - -@app.route('/force_upload', methods=['POST']) -def force_upload(): - logging.info("Forcing upload to Hugging Face...") - try: - upload_db_to_hf() - flash("Данные успешно загружены на Hugging Face.", 'success') - except Exception as e: - logging.error(f"Error during forced upload: {e}", exc_info=True) - flash(f"Ошибка при загрузке на Hugging Face: {e}", 'error') - return redirect(url_for('admin')) - -@app.route('/force_download', methods=['POST']) -def force_download(): - logging.info("Forcing download from Hugging Face...") - try: - if download_db_from_hf(): - flash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success') - load_data() - else: - flash("Не удалось скачать данные с Hugging Face после нескольких попыток. Проверьте логи.", 'error') - except Exception as e: - logging.error(f"Error during forced download: {e}", exc_info=True) - flash(f"Ошибка при скачивании с Hugging Face: {e}", 'error') - return redirect(url_for('admin')) - - -if __name__ == '__main__': - logging.info("Application starting up. Performing initial data load/download...") - download_db_from_hf() - load_data() - logging.info("Initial data load complete.") - - if HF_TOKEN_WRITE: - backup_thread = threading.Thread(target=periodic_backup, daemon=True) - backup_thread.start() - logging.info("Periodic backup thread started.") - else: - logging.warning("Periodic backup will NOT run (HF_TOKEN for writing not set).") - - port = int(os.environ.get('PORT', 7860)) - logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}") - app.run(debug=False, host='0.0.0.0', port=port)