diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,17 +1,23 @@ -from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify -import json import os +import io +import base64 +import json import logging import threading import time from datetime import datetime +from uuid import uuid4 + +from flask import Flask, render_template_string, request, redirect, url_for, flash, jsonify, Response +from PIL import Image +import google.generativeai as genai +import numpy as np 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() @@ -24,8 +30,10 @@ SYNC_FILES = [DATA_FILE] REPO_ID = "Kgshop/oco" HF_TOKEN_WRITE = os.getenv("HF_TOKEN") HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") +GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") STORE_ADDRESS = "Рынок Кербент, 6 ряд , 43 контейнер " +WHATSAPP_NUMBER = "+996779075126" CURRENCY_CODE = 'KGS' CURRENCY_NAME = 'Кыргызский сом' @@ -42,14 +50,12 @@ def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWN 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, @@ -60,50 +66,42 @@ def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWN 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.") + json.dump({'products': [], 'categories': [], 'orders': {}, 'organization_info': {}}, f) except Exception as create_e: - logging.error(f"Failed to create empty local file {file_name}: {create_e}") + pass success = False break else: - logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") + pass except requests.exceptions.RequestException as e: - logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") + pass except Exception as e: - logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True) + pass 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): @@ -116,647 +114,1096 @@ def upload_db_to_hf(specific_file=None): 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}") + pass else: - logging.warning(f"File {file_name} not found locally, skipping upload.") - logging.info("Finished uploading files to HF.") + pass except Exception as e: - logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True) + pass 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': {}} + default_organization_info = { + "about_us": "Мы — O&CO, ваш надежный партнер в мире уникальных товаров. Мы предлагаем широкий ассортимент продукции, от электроники до товаров для дома, всегда стремясь к качеству и доступности. Наша миссия — сделать ваш шопинг приятным и удобным, предлагая только лучшие товары, тщательно отобранные для вас.", + "shipping": "Доставка осуществляется по всему Кыргызстану. Стоимость и сроки доставки зависят от региона и веса товара. По Бишкеку доставка возможна в течение 1-2 рабочих дней, в регионы — от 3 до 7 дней. Для уточнения деталей свяжитесь с нами.", + "returns": "Возврат и обмен товара возможен в течение 14 дней с момента покупки, при условии сохранения товарного вида, упаковки и чека. Некоторые категории товаров могут иметь особые условия возврата. Пожалуйста, свяжитесь с нами для оформления возврата или обмена.", + "contact": f"Наш магазин находится по адресу: {STORE_ADDRESS}. Связаться с нами можно по телефону: {WHATSAPP_NUMBER} или через WhatsApp по этому же номеру. Мы работаем ежедневно с 9:00 до 18:00." + } + default_data = {'products': [], 'categories': [], 'orders': {}, 'organization_info': default_organization_info} + data = default_data try: with open(DATA_FILE, 'r', encoding='utf-8') as file: data = json.load(file) - logging.info(f"Local data loaded successfully from {DATA_FILE}") if not isinstance(data, dict): - logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.") raise FileNotFoundError if 'products' not in data: data['products'] = [] if 'categories' not in data: data['categories'] = [] if 'orders' not in data: data['orders'] = {} - return data + if 'organization_info' not in data: data['organization_info'] = default_organization_info except FileNotFoundError: - logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.") + if download_db_from_hf(specific_file=DATA_FILE): + try: + with open(DATA_FILE, 'r', encoding='utf-8') as file: + data = json.load(file) + if not isinstance(data, dict): + data = default_data + if 'products' not in data: data['products'] = [] + if 'categories' not in data: data['categories'] = [] + if 'orders' not in data: data['orders'] = {} + if 'organization_info' not in data: data['organization_info'] = default_organization_info + except (FileNotFoundError, json.JSONDecodeError, Exception) as e: + data = default_data + else: + data = default_data except json.JSONDecodeError: - logging.error(f"Error decoding JSON in local {DATA_FILE}. File might be corrupt. Attempting download.") - - if download_db_from_hf(specific_file=DATA_FILE): - try: - with open(DATA_FILE, 'r', encoding='utf-8') as file: - data = json.load(file) - logging.info(f"Data loaded successfully from {DATA_FILE} after download.") - if not isinstance(data, dict): - logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.") - return default_data - if 'products' not in data: data['products'] = [] - if 'categories' not in data: data['categories'] = [] - if 'orders' not in data: data['orders'] = {} - return data - except FileNotFoundError: - logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.") - return default_data - except json.JSONDecodeError: - logging.error(f"Error decoding JSON in downloaded {DATA_FILE}. Using default.") - return default_data - except Exception as e: - logging.error(f"Unknown error loading downloaded {DATA_FILE}: {e}. Using default.", exc_info=True) - return default_data - else: - logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.") - if not os.path.exists(DATA_FILE): + if download_db_from_hf(specific_file=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 download.") - except Exception as create_e: - logging.error(f"Failed to create empty local file {DATA_FILE}: {create_e}") - return default_data + with open(DATA_FILE, 'r', encoding='utf-8') as file: + data = json.load(file) + if not isinstance(data, dict): + data = default_data + if 'products' not in data: data['products'] = [] + if 'categories' not in data: data['categories'] = [] + if 'orders' not in data: data['orders'] = {} + if 'organization_info' not in data: data['organization_info'] = default_organization_info + except (FileNotFoundError, json.JSONDecodeError, Exception) as e: + data = default_data + else: + data = default_data + except Exception as e: + data = default_data + for product in data['products']: + if 'product_id' not in product: + product['product_id'] = uuid4().hex + if any('product_id' not in p for p in data['products']): + save_data(data) + + if not os.path.exists(DATA_FILE): + try: + with open(DATA_FILE, 'w', encoding='utf-8') as f: + json.dump(default_data, f) + except Exception as create_e: + pass + return 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'] = {} + if 'organization_info' not in data: data['organization_info'] = {} 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) + pass +def configure_gemini(): + if not GOOGLE_API_KEY: + return False + try: + genai.configure(api_key=GOOGLE_API_KEY) + return True + except Exception as e: + return False -CATALOG_TEMPLATE = ''' - - -
- - -
-
- {% endif %}
- {{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}
-