Spaces:
Paused
Paused
Update app.py
Browse files3 unmodified lines456789102 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717284 unmodified lines1571581591601611621632 unmodified lines166167168169170171172332 unmodified lines50550650750850951051118 unmodified lines53053153253353453553649 unmodified lines586587588589590591115 unmodified lines7077087097107117127131 unmodified line71571671771871972072114 unmodified lines73673773873974074174274374440 unmodified lines7857867877887897907917921 unmodified line79479579679779879980026 unmodified lines8278288298308318328333 unmodified lines8378388398408418428438 unmodified lines85285385485585685710 unmodified lines86886987087187287364 unmodified lines938939940941942943135 unmodified lines107910801081108210831084106 unmodified lines11911192119311941195119671 unmodified lines1268126912701271127212731274127512761277127823 unmodified lines13021303130413051306130758 unmodified lines136613671368136913701371137245 unmodified lines1418141914201421142214237 unmodified lines14311432143314341435143614373 unmodified linesimport loggingimport threadingimport timeimport requestsfrom datetime import datetimefrom huggingface_hub import HfApi, hf_hub_downloadfrom huggingface_hub.utils import RepositoryNotFoundError2 unmodified linesapp = Flask(__name__)app.secret_key = 'your_unique_secret_key_12345' # Уникальный секретный ключDATA_FILE = 'data_detobuv.json'USERS_FILE = 'users_detobuv.json'# Настройки Hugging FaceREPO_ID = "Kgshop/clients"HF_TOKEN_WRITE = os.getenv("HF_TOKEN")HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")# Адрес магазинаSTORE_ADDRESS = "Бишкек, Рынок Дордой, 9 ряд, 06 контейнер"# API для получения актуальных курсов валютEXCHANGE_RATE_API_KEY = "a1bbe02a37d9584ab12ffc1f" # Замените на ваш ключ от ExchangeRate-APIEXCHANGE_RATE_API_URL = f"https://v6.exchangerate-api.com/v6/{EXCHANGE_RATE_API_KEY}/latest/USD"# Поддерживаемые валютыCURRENCIES = {'USD': 'Доллар США ($)','KGS': 'Кыргызский сом (с)','RUB': 'Российский рубль (₽)','KZT': 'Казахский тенге (₸)'}# Настройка логированияlogging.basicConfig(level=logging.DEBUG)def get_exchange_rates():"""Получение актуальных курсов валют из API."""try:response = requests.get(EXCHANGE_RATE_API_URL)data = response.json()if data['result'] == 'success':rates = {'USD': 1.0,'KGS': data['conversion_rates']['KGS'],'RUB': data['conversion_rates']['RUB'],'KZT': data['conversion_rates']['KZT']}logging.info("Курсы валют успешно обновлены из API")return rateselse:raise Exception("Ошибка API: " + data['error-type'])except Exception as e:logging.error(f"Не удалось получить курсы валют: {e}")# Резервные фиксированные курсы в случае сбоя APIreturn {'USD': 1.0,'KGS': 89.0,'RUB': 97.0,'KZT': 480.0}def convert_price(price_usd, currency, rates):"""Конвертация цены из USD в указанную валюту."""return round(price_usd * rates[currency], 2)def load_data():try:84 unmodified linesproducts = data['products']categories = data['categories']is_authenticated = 'user' in sessionrates = get_exchange_rates()selected_currency = session.get('currency', 'USD') if is_authenticated else 'USD'catalog_html = '''2 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Детская обувь оптом, Дордой, ряд 9, контейнер 06</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">332 unmodified lines<i class="fas fa-moon"></i></button></div><div class="store-address">{{ store_address }}</div><div class="filters-container"><button class="category-filter active" data-category="all">Все категории</button>{% for category in categories %}18 unmodified lines{% endif %}<h2>{{ product['name'] }}</h2>{% if is_authenticated %}<div class="product-price">{{ convert_price(product['price'], selected_currency, rates) }} {{ selected_currency }}</div>{% else %}<div class="product-price">Цена доступна после входа</div>{% endif %}49 unmodified linesconst products = {{ products|tojson }};let selectedProductIndex = null;const selectedCurrency = '{{ selected_currency }}';function toggleTheme() {document.body.classList.toggle('dark-mode');115 unmodified lineslet total = 0;cartContent.innerHTML = cart.length === 0 ? '<p>Корзина пуста</p>' : cart.map(item => {const itemTotal = item.price * item.quantity * {{ rates[selected_currency]|tojson }};total += itemTotal;return `<div class="cart-item">1 unmodified line${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 * {{ rates[selected_currency]|tojson }}).toFixed(2)} ${selectedCurrency} × ${item.quantity} (Цвет: ${item.color})</p></div></div><span>${itemTotal.toFixed(2)} ${selectedCurrency}</span>14 unmodified lineslet total = 0;let orderText = "Заказ:%0A";cart.forEach((item, index) => {const itemTotal = item.price * item.quantity * {{ rates[selected_currency]|tojson }};total += itemTotal;orderText += `${index + 1}. ${item.name} - ${(item.price * {{ rates[selected_currency]|tojson }}).toFixed(2)} ${selectedCurrency} × ${item.quantity} (Цвет: ${item.color})%0A`;});orderText += `Итого: ${total.toFixed(2)} ${selectedCurrency}%0A`;orderText += `Страна: {{ session.get('country', 'Не указана') }}%0A`;40 unmodified lines'''return render_template_string(catalog_html, products=products, categories=categories,repo_id=REPO_ID, is_authenticated=is_authenticated,store_address=STORE_ADDRESS, session=session,convert_price=convert_price, rates=rates,selected_currency=selected_currency, currencies=CURRENCIES)@app.route('/product/<int:index>')1 unmodified linedata = load_data()products = data['products']is_authenticated = 'user' in sessionrates = get_exchange_rates()selected_currency = session.get('currency', 'USD') if is_authenticated else 'USD'try:product = products[index]26 unmodified lines</div><p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>{% if is_authenticated %}<p><strong>Цена:</strong> {{ convert_price(product['price'], selected_currency, rates) }} {{ selected_currency }}</p>{% else %}<p><strong>Цена:</strong> Доступна после входа</p>{% endif %}3 unmodified lines'''return render_template_string(detail_html, product=product, repo_id=REPO_ID,is_authenticated=is_authenticated, convert_price=convert_price,rates=rates, selected_currency=selected_currency)@app.route('/set_currency', methods=['POST'])def set_currency():8 unmodified linesif request.method == 'POST':login = request.form.get('login')password = request.form.get('password')country = request.form.get('country')city = request.form.get('city')purchase_type = request.form.get('purchase_type')10 unmodified linesusers[login] = {'password': password,'country': country,'city': city,'purchase_type': purchase_type64 unmodified lines<input type="text" name="login" required><label>Пароль:</label><input type="password" name="password" required><label>Страна:</label><input type="text" name="country" required><label>Город:</label>135 unmodified linesdata = load_data()products = data['products']categories = data['categories']if request.method == 'POST':action = request.form.get('action')106 unmodified linesdel products[index]save_data(data)return redirect(url_for('admin'))admin_html = '''<!DOCTYPE html>71 unmodified linesbackground-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;23 unmodified lines<div class="header"><h1>Админ-панель</h1></div><h1>Добавление товара</h1><form method="POST" enctype="multipart/form-data"><input type="hidden" name="action" value="add">58 unmodified lines<div class="product-item"><h3>{{ product['name'] }}</h3><p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p><p><strong>Цена:</strong> {{ product['price'] }} USD</p><p><strong>Описание:</strong> {{ product['description'] }}</p><p><strong>Цвета:</strong> {{ product.get('colors', ['Нет цветов'])|join(', ') }}</p>{% if product.get('photos') and product['photos']|length > 0 %}45 unmodified lines</div>{% endfor %}</div></div><script>function addColorInput(containerId = 'color-inputs') {7 unmodified lines</body></html>'''return render_template_string(admin_html, products=products, categories=categories, repo_id=REPO_ID)@app.route('/backup', methods=['POST'])def backup():3 unmodified lines4567892 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575884 unmodified lines1431441451461471482 unmodified lines151152153154155156157332 unmodified lines49049149249349449549618 unmodified lines51551651751851952052149 unmodified lines571572573574575576577115 unmodified lines6936946956966976986997001 unmodified line70270370470570670770814 unmodified lines72372472572672772872973073173240 unmodified lines7737747757767777787797801 unmodified line78278378478578678726 unmodified lines8148158168178188198203 unmodified lines8248258268278288298308 unmodified lines83984084184284384484584610 unmodified lines85785885986086186286386464 unmodified lines929930931932933934935936937938135 unmodified lines10741075107610771078107910801081106 unmodified lines11881189119011911192119311941195119611971198119912001201120212031204120571 unmodified lines1277127812791280128112821283128412851286128723 unmodified lines13111312131313141315131613171318131913201321132213231324132558 unmodified lines138413851386138713881389139045 unmodified lines1436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814597 unmodified lines1467146814691470147114721473147414753 unmodified linesimport loggingimport threadingimport timefrom datetime import datetimefrom huggingface_hub import HfApi, hf_hub_downloadfrom huggingface_hub.utils import RepositoryNotFoundError2 unmodified linesapp = Flask(__name__)app.secret_key = 'your_unique_secret_key_12345' # Уникальный секретный ключDATA_FILE = 'data_detobuv.json'USERS_FILE = 'users.json'CONFIG_FILE = 'config.json' # Файл для хранения курса KGS к USD# Настройки Hugging FaceREPO_ID = "Kgshop/clients"HF_TOKEN_WRITE = os.getenv("HF_TOKEN")HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")# Адреса магазинаWHOLESALE_ADDRESS = "Дордой, рынок Кербен, 9 ряд, 06 бутик" # ОптRETAIL_ADDRESS = "Дордой Мир Обуви, номер 150" # Розница# Поддерживаемые валютыCURRENCIES = {'USD': 'Доллар США ($)','KGS': 'Кыргызский сом (с)'}# Настройка логированияlogging.basicConfig(level=logging.DEBUG)def load_config():"""Загрузка конфигурации (курс KGS к USD)."""try:with open(CONFIG_FILE, 'r', encoding='utf-8') as file:config = json.load(file)return config.get('kgs_to_usd', 89.0) # Значение по умолчаниюexcept (FileNotFoundError, json.JSONDecodeError):return 89.0 # Резервное значениеdef save_config(kgs_to_usd):"""Сохранение конфигурации."""with open(CONFIG_FILE, 'w', encoding='utf-8') as file:json.dump({'kgs_to_usd': kgs_to_usd}, file, ensure_ascii=False, indent=4)def convert_price(price_usd, currency):"""Конвертация цены из USD в указанную валюту."""kgs_to_usd = load_config()if currency == 'KGS':return round(price_usd * kgs_to_usd, 2)return round(price_usd, 2)def load_data():try:84 unmodified linesproducts = data['products']categories = data['categories']is_authenticated = 'user' in sessionselected_currency = session.get('currency', 'USD') if is_authenticated else 'USD'catalog_html = '''2 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><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">332 unmodified lines<i class="fas fa-moon"></i></button></div><div class="store-address">Опт: {{ wholesale_address }} | ��озница: {{ retail_address }}</div><div class="filters-container"><button class="category-filter active" data-category="all">Все категории</button>{% for category in categories %}18 unmodified lines{% endif %}<h2>{{ product['name'] }}</h2>{% if is_authenticated %}<div class="product-price">{{ convert_price(product['price'], selected_currency) }} {{ selected_currency }}</div>{% else %}<div class="product-price">Цена доступна после входа</div>{% endif %}49 unmodified linesconst products = {{ products|tojson }};let selectedProductIndex = null;const selectedCurrency = '{{ selected_currency }}';const kgsToUsd = {{ load_config()|tojson }};function toggleTheme() {document.body.classList.toggle('dark-mode');115 unmodified lineslet total = 0;cartContent.innerHTML = cart.length === 0 ? '<p>Корзина пуста</p>' : cart.map(item => {const itemPrice = selectedCurrency === 'KGS' ? (item.price * kgsToUsd) : item.price;const itemTotal = itemPrice * item.quantity;total += itemTotal;return `<div class="cart-item">1 unmodified line${item.photo ? `<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}" alt="${item.name}">` : ''}<div><strong>${item.name}</strong><p>${itemPrice.toFixed(2)} ${selectedCurrency} × ${item.quantity} (Цвет: ${item.color})</p></div></div><span>${itemTotal.toFixed(2)} ${selectedCurrency}</span>14 unmodified lineslet total = 0;let orderText = "Заказ:%0A";cart.forEach((item, index) => {const itemPrice = selectedCurrency === 'KGS' ? (item.price * kgsToUsd) : item.price;const itemTotal = itemPrice * item.quantity;total += itemTotal;orderText += `${index + 1}. ${item.name} - ${itemPrice.toFixed(2)} ${selectedCurrency} × ${item.quantity} (Цвет: ${item.color})%0A`;});orderText += `Итого: ${total.toFixed(2)} ${selectedCurrency}%0A`;orderText += `Страна: {{ session.get('country', 'Не указана') }}%0A`;40 unmodified lines'''return render_template_string(catalog_html, products=products, categories=categories,repo_id=REPO_ID, is_authenticated=is_authenticated,wholesale_address=WHOLESALE_ADDRESS, retail_address=RETAIL_ADDRESS,session=session, convert_price=convert_price,selected_currency=selected_currency, currencies=CURRENCIES)@app.route('/product/<int:index>')1 unmodified linedata = load_data()products = data['products']is_authenticated = 'user' in sessionselected_currency = session.get('currency', 'USD') if is_authenticated else 'USD'try:product = products[index]26 unmodified lines</div><p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>{% if is_authenticated %}<p><strong>Цена:</strong> {{ convert_price(product['price'], selected_currency) }} {{ selected_currency }}</p>{% else %}<p><strong>Цена:</strong> Доступна после входа</p>{% endif %}3 unmodified lines'''return render_template_string(detail_html, product=product, repo_id=REPO_ID,is_authenticated=is_authenticated, convert_price=convert_price,selected_currency=selected_currency)@app.route('/set_currency', methods=['POST'])def set_currency():8 unmodified linesif request.method == 'POST':login = request.form.get('login')password = request.form.get('password')first_name = request.form.get('first_name')last_name = request.form.get('last_name')country = request.form.get('country')city = request.form.get('city')purchase_type = request.form.get('purchase_type')10 unmodified linesusers[login] = {'password': password,'first_name': first_name,'last_name': last_name,'country': country,'city': city,'purchase_type': purchase_type64 unmodified lines<input type="text" name="login" required><label>Пароль:</label><input type="password" name="password" required><label>Имя:</label><input type="text" name="first_name" required><label>Фамилия:</label><input type="text" name="last_name" required><label>Страна:</label><input type="text" name="country" required><label>Город:</label>135 unmodified linesdata = load_data()products = data['products']categories = data['categories']users = load_users()kgs_to_usd = load_config()if request.method == 'POST':action = request.form.get('action')106 unmodified linesdel products[index]save_data(data)return redirect(url_for('admin'))elif action == 'set_exchange_rate':kgs_to_usd = float(request.form.get('kgs_to_usd').replace(',', '.'))save_config(kgs_to_usd)return redirect(url_for('admin'))elif action == 'delete_user':login = request.form.get('login')if login in users:del users[login]save_users(users)return redirect(url_for('admin'))admin_html = '''<!DOCTYPE html>71 unmodified linesbackground-color: #dc2626;box-shadow: 0 4px 15px rgba(220, 38, 38, 0.4);}.product-list, .category-list, .user-list {display: grid;gap: 20px;}.product-item, .category-item, .user-item {background: #fff;padding: 20px;border-radius: 15px;23 unmodified lines<div class="header"><h1>Админ-панель</h1></div><h1>Установка курса KGS к USD</h1><form method="POST"><input type="hidden" name="action" value="set_exchange_rate"><label>Курс KGS к USD (1 USD = ? KGS):</label><input type="number" name="kgs_to_usd" step="0.01" value="{{ kgs_to_usd }}" required><button type="submit">Сохранить</button></form><h1>Добавление товара</h1><form method="POST" enctype="multipart/form-data"><input type="hidden" name="action" value="add">58 unmodified lines<div class="product-item"><h3>{{ product['name'] }}</h3><p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p><p><strong>Цена:</strong> {{ product['price'] }} USD ({{ convert_price(product['price'], 'KGS') }} KGS)</p><p><strong>Описание:</strong> {{ product['description'] }}</p><p><strong>Цвета:</strong> {{ product.get('colors', ['Нет цветов'])|join(', ') }}</p>{% if product.get('photos') and product['photos']|length > 0 %}45 unmodified lines</div>{% endfor %}</div><h2>Список пользователей</h2><div class="user-list">{% for login, user in users.items() %}<div class="user-item"><p><strong>Логин:</strong> {{ login }}</p><p><strong>Имя:</strong> {{ user['first_name'] }}</p><p><strong>Фlastname:</strong> {{ user['last_name'] }}</p><p><strong>Страна:</strong> {{ user['country'] }}</p><p><strong>Город:</strong> {{ user['city'] }}</p><form method="POST"><input type="hidden" name="action" value="delete_user"><input type="hidden" name="login" value="{{ login }}"><button type="submit" class="delete-button">Удалить</button></form></div>{% endfor %}</div></div><script>function addColorInput(containerId = 'color-inputs') {7 unmodified lines</body></html>'''return render_template_string(admin_html, products=products, categories=categories,repo_id=REPO_ID, users=users, kgs_to_usd=kgs_to_usd,convert_price=convert_price)@app.route('/backup', methods=['POST'])def backup():
app.py+92-54