Kgshop commited on
Commit
b686fca
·
verified ·
1 Parent(s): 931c016

Upload app (7).py

Browse files
Files changed (1) hide show
  1. app (7).py +1556 -0
app (7).py ADDED
@@ -0,0 +1,1556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import base64
4
+ import json
5
+ import logging
6
+ import threading
7
+ import time
8
+ from datetime import datetime, timedelta
9
+ import random
10
+ import string
11
+
12
+ from flask import Flask, render_template_string, request, redirect, url_for, flash, make_response, jsonify
13
+ from huggingface_hub import HfApi, hf_hub_download
14
+ from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
15
+ from dotenv import load_dotenv
16
+ import requests
17
+
18
+ load_dotenv()
19
+
20
+ app = Flask(__name__)
21
+ app.secret_key = 'your_unique_secret_key_gippo_312_shop_54321_no_login_synkris'
22
+ DATA_FILE = 'data.json'
23
+
24
+ SYNC_FILES = [DATA_FILE]
25
+
26
+ REPO_ID = "Kgshop/synkrisnew"
27
+ HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
28
+ HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
29
+
30
+ DOWNLOAD_RETRIES = 3
31
+ DOWNLOAD_DELAY = 5
32
+
33
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
34
+
35
+ def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):
36
+ if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
37
+ pass
38
+ token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE
39
+ files_to_download = [specific_file] if specific_file else SYNC_FILES
40
+ all_successful = True
41
+ for file_name in files_to_download:
42
+ success = False
43
+ for attempt in range(retries + 1):
44
+ try:
45
+ hf_hub_download(
46
+ repo_id=REPO_ID,
47
+ filename=file_name,
48
+ repo_type="dataset",
49
+ token=token_to_use,
50
+ local_dir=".",
51
+ local_dir_use_symlinks=False,
52
+ force_download=True,
53
+ resume_download=False
54
+ )
55
+ success = True
56
+ break
57
+ except RepositoryNotFoundError:
58
+ return False
59
+ except HfHubHTTPError as e:
60
+ if e.response.status_code == 404:
61
+ if attempt == 0 and not os.path.exists(file_name):
62
+ try:
63
+ if file_name == DATA_FILE:
64
+ with open(file_name, 'w', encoding='utf-8') as f:
65
+ json.dump({}, f)
66
+ except Exception:
67
+ pass
68
+ success = True
69
+ break
70
+ else:
71
+ pass
72
+ except Exception:
73
+ pass
74
+ if attempt < retries:
75
+ time.sleep(delay)
76
+ if not success:
77
+ all_successful = False
78
+ return all_successful
79
+
80
+ def upload_db_to_hf(specific_file=None):
81
+ if not HF_TOKEN_WRITE:
82
+ return
83
+ try:
84
+ api = HfApi()
85
+ files_to_upload = [specific_file] if specific_file else SYNC_FILES
86
+ for file_name in files_to_upload:
87
+ if os.path.exists(file_name):
88
+ try:
89
+ api.upload_file(
90
+ path_or_fileobj=file_name,
91
+ path_in_repo=file_name,
92
+ repo_id=REPO_ID,
93
+ repo_type="dataset",
94
+ token=HF_TOKEN_WRITE,
95
+ commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
96
+ )
97
+ except Exception:
98
+ pass
99
+ except Exception:
100
+ pass
101
+
102
+ def periodic_backup():
103
+ backup_interval = 1800
104
+ while True:
105
+ time.sleep(backup_interval)
106
+ upload_db_to_hf()
107
+
108
+ def load_data():
109
+ try:
110
+ with open(DATA_FILE, 'r', encoding='utf-8') as f:
111
+ data = json.load(f)
112
+ if not isinstance(data, dict):
113
+ data = {}
114
+ except (FileNotFoundError, json.JSONDecodeError):
115
+ if download_db_from_hf(specific_file=DATA_FILE):
116
+ try:
117
+ with open(DATA_FILE, 'r', encoding='utf-8') as f:
118
+ data = json.load(f)
119
+ if not isinstance(data, dict):
120
+ data = {}
121
+ except (FileNotFoundError, json.JSONDecodeError):
122
+ data = {}
123
+ else:
124
+ data = {}
125
+ return data
126
+
127
+ def save_data(data):
128
+ try:
129
+ with open(DATA_FILE, 'w', encoding='utf-8') as file:
130
+ json.dump(data, file, ensure_ascii=False, indent=4)
131
+ upload_db_to_hf(specific_file=DATA_FILE)
132
+ except Exception:
133
+ pass
134
+
135
+ LANDING_PAGE_TEMPLATE = '''
136
+ <!DOCTYPE html>
137
+ <html lang="ru">
138
+ <head>
139
+ <meta charset="UTF-8">
140
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
141
+ <title> MetaStore - AI система для Вашего Бизнеса</title>
142
+ <style>
143
+ body, html {
144
+ margin: 0;
145
+ padding: 0;
146
+ height: 100%;
147
+ overflow: hidden;
148
+ }
149
+ iframe {
150
+ border: none;
151
+ width: 100%;
152
+ height: 100%;
153
+ }
154
+ </style>
155
+ </head>
156
+ <body>
157
+ <iframe src="https://v0-ai-agent-landing-page-smoky-six.vercel.app/"></iframe>
158
+ </body>
159
+ </html>
160
+ '''
161
+
162
+ ADMHOSTO_TEMPLATE = '''
163
+ <!DOCTYPE html>
164
+ <html lang="ru">
165
+ <head>
166
+ <meta charset="UTF-8">
167
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
168
+ <title>Админ-панель</title>
169
+ <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
170
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
171
+ <style>
172
+ :root {
173
+ --bg-light: #f4f6f9;
174
+ --bg-medium: #135D66;
175
+ --accent: #48D1CC;
176
+ --accent-hover: #77E4D8;
177
+ --text-dark: #333;
178
+ --text-on-accent: #003C43;
179
+ --danger: #E57373;
180
+ --warning: #ffcc80;
181
+ }
182
+ * { box-sizing: border-box; }
183
+ body { font-family: 'Montserrat', sans-serif; background-color: var(--bg-light); color: var(--text-dark); margin: 0; padding: 15px; }
184
+ .container { max-width: 900px; margin: 0 auto; background-color: #fff; padding: 20px; border-radius: 12px; box-shadow: 0 3px 15px rgba(0,0,0,0.08); }
185
+ h1 { font-weight: 600; color: var(--bg-medium); margin-bottom: 25px; text-align: center; font-size: 1.5rem; }
186
+
187
+ .section { margin-bottom: 25px; }
188
+
189
+ .add-env-form {
190
+ display: flex;
191
+ flex-direction: column;
192
+ gap: 15px;
193
+ background: #f8f9fa;
194
+ padding: 15px;
195
+ border-radius: 10px;
196
+ border: 1px solid #e9ecef;
197
+ }
198
+
199
+ input[type="text"] {
200
+ width: 100%;
201
+ padding: 12px;
202
+ border: 1px solid #ddd;
203
+ border-radius: 8px;
204
+ font-size: 1rem;
205
+ font-family: inherit;
206
+ background: #fff;
207
+ -webkit-appearance: none;
208
+ }
209
+
210
+ .controls-row {
211
+ display: flex;
212
+ align-items: center;
213
+ justify-content: space-between;
214
+ gap: 15px;
215
+ flex-wrap: wrap;
216
+ }
217
+
218
+ .radio-group { display: flex; gap: 15px; }
219
+ .radio-group label { cursor: pointer; display: flex; align-items: center; gap: 6px; font-weight: 500; font-size: 0.95rem; }
220
+
221
+ .button {
222
+ padding: 12px 20px;
223
+ border: none;
224
+ border-radius: 8px;
225
+ background-color: var(--accent);
226
+ color: var(--text-on-accent);
227
+ font-weight: 600;
228
+ cursor: pointer;
229
+ text-decoration: none;
230
+ display: inline-flex;
231
+ align-items: center;
232
+ justify-content: center;
233
+ gap: 8px;
234
+ font-size: 1rem;
235
+ transition: opacity 0.2s;
236
+ }
237
+ .button:hover { opacity: 0.9; }
238
+ .button:active { transform: scale(0.98); }
239
+
240
+ .env-list { list-style: none; padding: 0; margin: 0; }
241
+ .env-item {
242
+ background: #fff;
243
+ border: 1px solid #e0e0e0;
244
+ border-radius: 10px;
245
+ padding: 15px;
246
+ margin-bottom: 12px;
247
+ display: grid;
248
+ grid-template-columns: 1fr auto;
249
+ align-items: center;
250
+ gap: 15px;
251
+ box-shadow: 0 2px 5px rgba(0,0,0,0.02);
252
+ }
253
+
254
+ .env-details { display: flex; flex-direction: column; gap: 4px; overflow: hidden; }
255
+ .env-header { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
256
+ .env-id { font-weight: 700; color: var(--bg-medium); font-size: 1.1rem; }
257
+ .env-keyword { font-style: italic; color: #666; font-size: 0.9rem;}
258
+
259
+ .env-link {
260
+ font-size: 0.9rem;
261
+ color: #007bff;
262
+ word-break: break-all;
263
+ text-decoration: none;
264
+ padding: 5px 0;
265
+ display: block;
266
+ }
267
+
268
+ .env-type-badge {
269
+ font-size: 0.75rem;
270
+ padding: 3px 8px;
271
+ border-radius: 20px;
272
+ font-weight: bold;
273
+ text-transform: uppercase;
274
+ white-space: nowrap;
275
+ }
276
+ .type-open { background-color: #d4edda; color: #155724; }
277
+ .type-closed { background-color: #f8d7da; color: #721c24; }
278
+
279
+ .env-actions { display: flex; gap: 8px; }
280
+ .stats-button { background-color: #5d4037; color: white; padding: 10px 15px; font-size: 0.9rem;}
281
+ .delete-button { background-color: var(--danger); color: white; padding: 10px 15px; font-size: 0.9rem;}
282
+
283
+ .message { padding: 12px; border-radius: 8px; margin-bottom: 20px; text-align: center; font-size: 0.95rem; }
284
+ .message.success { background-color: #d4edda; color: #155724; }
285
+ .message.error { background-color: #f8d7da; color: #721c24; }
286
+
287
+ /* Modal */
288
+ .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.6); backdrop-filter: blur(2px); }
289
+ .modal-content { background-color: #fff; margin: 15% auto; padding: 25px; width: 90%; max-width: 600px; border-radius: 12px; position: relative; box-shadow: 0 5px 20px rgba(0,0,0,0.2); }
290
+ .close-modal { color: #888; position: absolute; right: 15px; top: 10px; font-size: 30px; font-weight: bold; cursor: pointer; padding: 5px; }
291
+ .stats-table { width: 100%; border-collapse: collapse; margin-top: 15px; font-size: 0.85rem; }
292
+ .stats-table th, .stats-table td { border: 1px solid #eee; padding: 10px 8px; text-align: left; }
293
+ .stats-table th { background-color: var(--bg-medium); color: white; }
294
+ .stats-table tr:nth-child(even) { background-color: #f9f9f9; }
295
+
296
+ /* Mobile Optimization */
297
+ @media (max-width: 600px) {
298
+ body { padding: 10px; }
299
+ .container { padding: 15px; }
300
+ h1 { font-size: 1.3rem; margin-bottom: 20px; }
301
+
302
+ .controls-row {
303
+ flex-direction: column;
304
+ align-items: stretch;
305
+ }
306
+ .radio-group {
307
+ justify-content: space-between;
308
+ background: #fff;
309
+ padding: 10px;
310
+ border-radius: 8px;
311
+ border: 1px solid #ddd;
312
+ }
313
+ .button { width: 100%; padding: 14px; }
314
+
315
+ .env-item {
316
+ grid-template-columns: 1fr;
317
+ gap: 12px;
318
+ position: relative;
319
+ padding-bottom: 60px; /* Space for buttons */
320
+ }
321
+
322
+ .env-actions {
323
+ position: absolute;
324
+ bottom: 15px;
325
+ left: 15px;
326
+ right: 15px;
327
+ display: grid;
328
+ grid-template-columns: 3fr 1fr;
329
+ gap: 10px;
330
+ }
331
+
332
+ .env-actions button { width: 100%; }
333
+ .env-actions form { width: 100%; }
334
+
335
+ .modal-content { margin: 10% auto; width: 95%; padding: 20px 15px; }
336
+ .stats-table th, .stats-table td { font-size: 0.75rem; padding: 6px 4px; }
337
+ }
338
+ </style>
339
+ </head>
340
+ <body>
341
+ <div class="container">
342
+ <h1><i class="fas fa-server"></i> Управление Средами</h1>
343
+ {% with messages = get_flashed_messages(with_categories=true) %}
344
+ {% if messages %}
345
+ {% for category, message in messages %}
346
+ <div class="message {{ category }}">{{ message }}</div>
347
+ {% endfor %}
348
+ {% endif %}
349
+ {% endwith %}
350
+
351
+ <div class="section">
352
+ <form method="POST" action="{{ url_for('create_environment') }}" class="add-env-form">
353
+ <input type="text" id="keyword" name="keyword" placeholder="Ключевое слово (например, 'магазин')" required>
354
+ <div class="controls-row">
355
+ <div class="radio-group">
356
+ <label><input type="radio" name="env_type" value="closed" checked> <i class="fas fa-lock"></i> Закрытая</label>
357
+ <label><input type="radio" name="env_type" value="open"> <i class="fas fa-globe"></i> Открытая</label>
358
+ </div>
359
+ <button type="submit" class="button"><i class="fas fa-plus-circle"></i> Создать</button>
360
+ </div>
361
+ </form>
362
+ </div>
363
+
364
+ <div class="section">
365
+ <input type="text" id="search-env" placeholder="🔍 Поиск...">
366
+ </div>
367
+
368
+ <div class="section">
369
+ {% if environments %}
370
+ <ul class="env-list">
371
+ {% for env in environments %}
372
+ <li class="env-item">
373
+ <div class="env-details">
374
+ <div class="env-header">
375
+ <span class="env-id">{{ env.id }}</span>
376
+ <span class="env-type-badge type-{{ env.type }}">
377
+ {{ 'ЗАКРЫТАЯ' if env.type == 'closed' else 'ОТКРЫТАЯ' }}
378
+ </span>
379
+ <small style="color:#888">{{ env.hits }} <i class="fas fa-eye"></i></small>
380
+ </div>
381
+ <span class="env-keyword">{{ env.keyword }}</span>
382
+ <a href="{{ env.link }}" class="env-link" target="_blank">{{ env.link }}</a>
383
+ </div>
384
+ <div class="env-actions">
385
+ <button class="button stats-button" onclick="openStats('{{ env.id }}')"><i class="fas fa-chart-bar"></i> Инфо</button>
386
+ <form method="POST" action="{{ url_for('delete_environment', env_id=env.id) }}" style="display:contents;" onsubmit="return confirm('Удалить среду {{ env.id }}?');">
387
+ <button type="submit" class="button delete-button"><i class="fas fa-trash"></i></button>
388
+ </form>
389
+ </div>
390
+ </li>
391
+ {% endfor %}
392
+ </ul>
393
+ {% else %}
394
+ <div style="text-align:center; padding: 20px; color: #888;">Список пуст</div>
395
+ {% endif %}
396
+ </div>
397
+ </div>
398
+
399
+ <!-- Modal -->
400
+ <div id="statsModal" class="modal">
401
+ <div class="modal-content">
402
+ <span class="close-modal" onclick="closeStats()">&times;</span>
403
+ <h3 id="modalTitle" style="margin-top:0; color: var(--bg-medium)">Статистика</h3>
404
+ <p style="font-size: 0.8rem; color: #666;">Время: Алматы (UTC+5)</p>
405
+ <div id="statsContent" style="overflow-x: auto;">Загрузка...</div>
406
+ </div>
407
+ </div>
408
+
409
+ <script>
410
+ document.getElementById('search-env').addEventListener('input', function() {
411
+ const searchTerm = this.value.toLowerCase().trim();
412
+ document.querySelectorAll('.env-item').forEach(item => {
413
+ const text = item.innerText.toLowerCase();
414
+ item.style.display = text.includes(searchTerm) ? 'grid' : 'none';
415
+ });
416
+ });
417
+
418
+ function openStats(envId) {
419
+ const modal = document.getElementById('statsModal');
420
+ const content = document.getElementById('statsContent');
421
+ const title = document.getElementById('modalTitle');
422
+
423
+ title.innerText = `Среда: ${envId}`;
424
+ content.innerHTML = '<div style="text-align:center; padding: 20px;"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';
425
+ modal.style.display = 'block';
426
+
427
+ fetch(`/admhosto/stats/${envId}`)
428
+ .then(response => response.json())
429
+ .then(data => {
430
+ if (data.error) {
431
+ content.innerHTML = `<p style="color:red">${data.error}</p>`;
432
+ return;
433
+ }
434
+
435
+ let html = `<div style="display:flex; justify-content:space-between; margin-bottom:10px;">
436
+ <span><strong>Всего входов:</strong> ${data.hits}</span>
437
+ <span><strong>Тип:</strong> ${data.type === 'closed' ? 'Закрытая' : 'Открытая'}</span>
438
+ </div>`;
439
+
440
+ if (data.logs && data.logs.length > 0) {
441
+ html += `<table class="stats-table">
442
+ <thead><tr><th>Время</th><th>IP</th><th>Browser</th></tr></thead>
443
+ <tbody>`;
444
+ data.logs.forEach(log => {
445
+ html += `<tr>
446
+ <td>${log.time.split(' ')[1]}<br><small style="color:#999">${log.time.split(' ')[0]}</small></td>
447
+ <td>${log.ip}</td>
448
+ <td style="max-width: 100px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="${log.ua}">
449
+ ${log.ua.includes('iPhone') ? '<i class="fab fa-apple"></i>' : (log.ua.includes('Android') ? '<i class="fab fa-android"></i>' : '<i class="fas fa-desktop"></i>')}
450
+ </td>
451
+ </tr>`;
452
+ });
453
+ html += `</tbody></table>`;
454
+ } else {
455
+ html += `<p>Журнал пуст.</p>`;
456
+ }
457
+ content.innerHTML = html;
458
+ })
459
+ .catch(err => {
460
+ content.innerHTML = '<p style="color:red">Ошибка сети.</p>';
461
+ });
462
+ }
463
+
464
+ function closeStats() {
465
+ document.getElementById('statsModal').style.display = 'none';
466
+ }
467
+
468
+ window.onclick = function(event) {
469
+ const modal = document.getElementById('statsModal');
470
+ if (event.target == modal) {
471
+ modal.style.display = 'none';
472
+ }
473
+ }
474
+ </script>
475
+ </body>
476
+ </html>
477
+ '''
478
+
479
+ SYNKRIS_LOOK_TEMPLATE = '''
480
+ <!DOCTYPE html>
481
+ <html lang="ru">
482
+ <head>
483
+ <meta charset="UTF-8">
484
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
485
+ <title>Synkris Look</title>
486
+ <style>
487
+ :root {
488
+ --bg: #000000;
489
+ --card-bg: #0a0a0a;
490
+ --primary: #ccff00;
491
+ --primary-hover: #b3e600;
492
+ --primary-gradient: linear-gradient(45deg, #ccff00, #b3e600);
493
+ --text: #ffffff;
494
+ --text-secondary: #a1a1a1;
495
+ --border: #333333;
496
+ --input-bg: #111111;
497
+ }
498
+
499
+ body {
500
+ font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
501
+ background-color: var(--bg);
502
+ color: var(--text);
503
+ margin: 0;
504
+ padding: 20px;
505
+ display: flex;
506
+ justify-content: center;
507
+ align-items: flex-start;
508
+ min-height: 100vh;
509
+ }
510
+
511
+ .container {
512
+ background-color: var(--card-bg);
513
+ width: 100%;
514
+ max-width: 750px;
515
+ padding: 35px;
516
+ border-radius: 20px;
517
+ border: 1px solid #222;
518
+ box-shadow: 0 0 40px rgba(204, 255, 0, 0.08);
519
+ }
520
+
521
+ h1 {
522
+ text-align: center;
523
+ color: var(--primary);
524
+ margin-top: 0;
525
+ margin-bottom: 5px;
526
+ font-size: 2.2rem;
527
+ text-transform: uppercase;
528
+ letter-spacing: 2px;
529
+ text-shadow: 0 0 10px rgba(204, 255, 0, 0.3);
530
+ }
531
+
532
+ p.subtitle {
533
+ text-align: center;
534
+ color: var(--text-secondary);
535
+ margin-bottom: 30px;
536
+ font-size: 0.9rem;
537
+ letter-spacing: 0.5px;
538
+ }
539
+
540
+ .mode-selector {
541
+ display: grid;
542
+ grid-template-columns: repeat(3, 1fr);
543
+ margin-bottom: 30px;
544
+ background-color: var(--input-bg);
545
+ border-radius: 12px;
546
+ padding: 5px;
547
+ border: 1px solid var(--border);
548
+ }
549
+
550
+ .mode-btn {
551
+ padding: 12px 10px;
552
+ background-color: transparent;
553
+ border: none;
554
+ color: var(--text-secondary);
555
+ font-size: 0.85rem;
556
+ font-weight: 700;
557
+ cursor: pointer;
558
+ border-radius: 8px;
559
+ transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
560
+ text-transform: uppercase;
561
+ letter-spacing: 0.5px;
562
+ }
563
+
564
+ .mode-btn.active {
565
+ background-color: var(--primary);
566
+ color: #000;
567
+ box-shadow: 0 0 15px rgba(204, 255, 0, 0.4);
568
+ transform: scale(1.02);
569
+ }
570
+
571
+ .form-grid {
572
+ display: grid;
573
+ grid-template-columns: 1fr 1fr;
574
+ gap: 22px;
575
+ }
576
+
577
+ .full-width {
578
+ grid-column: span 2;
579
+ }
580
+
581
+ .form-group {
582
+ display: flex;
583
+ flex-direction: column;
584
+ }
585
+
586
+ label, .checkbox-label {
587
+ font-weight: 600;
588
+ margin-bottom: 8px;
589
+ font-size: 0.8rem;
590
+ color: var(--primary);
591
+ text-transform: uppercase;
592
+ letter-spacing: 0.8px;
593
+ }
594
+
595
+ label i {
596
+ margin-right: 6px;
597
+ font-size: 0.9em;
598
+ }
599
+
600
+ select, textarea, input[type="text"] {
601
+ padding: 12px 14px;
602
+ border: 1px solid var(--border);
603
+ border-radius: 8px;
604
+ font-size: 1rem;
605
+ background-color: var(--input-bg);
606
+ color: var(--text);
607
+ transition: all 0.3s ease;
608
+ outline: none;
609
+ width: 100%;
610
+ box-sizing: border-box;
611
+ }
612
+
613
+ select:disabled, textarea:disabled, input[type="text"]:disabled {
614
+ background-color: #222;
615
+ opacity: 0.5;
616
+ cursor: not-allowed;
617
+ }
618
+
619
+
620
+ select:focus, textarea:focus, input[type="text"]:focus {
621
+ border-color: var(--primary);
622
+ box-shadow: 0 0 10px rgba(204, 255, 0, 0.2);
623
+ }
624
+
625
+ textarea {
626
+ resize: vertical;
627
+ min-height: 80px;
628
+ font-family: inherit;
629
+ }
630
+
631
+ .btn-container {
632
+ margin-top: 35px;
633
+ text-align: center;
634
+ }
635
+
636
+ .action-btn {
637
+ background-image: var(--primary-gradient);
638
+ color: #000;
639
+ border: none;
640
+ padding: 16px 30px;
641
+ font-size: 1.1rem;
642
+ font-weight: 800;
643
+ border-radius: 12px;
644
+ cursor: pointer;
645
+ width: 100%;
646
+ transition: all 0.2s ease;
647
+ box-shadow: 0 0 20px rgba(204, 255, 0, 0.4);
648
+ display: flex;
649
+ justify-content: center;
650
+ align-items: center;
651
+ gap: 12px;
652
+ text-transform: uppercase;
653
+ }
654
+
655
+ .action-btn:hover {
656
+ transform: scale(1.02);
657
+ box-shadow: 0 0 30px rgba(204, 255, 0, 0.6);
658
+ }
659
+
660
+ .action-btn:active {
661
+ transform: scale(0.98);
662
+ }
663
+
664
+ select option {
665
+ background-color: #000;
666
+ color: #fff;
667
+ }
668
+
669
+ .form-mode {
670
+ display: none;
671
+ }
672
+
673
+ .form-mode.active {
674
+ display: contents;
675
+ }
676
+
677
+ .checkbox-container {
678
+ display: flex;
679
+ align-items: center;
680
+ background-color: var(--input-bg);
681
+ border: 1px solid var(--border);
682
+ border-radius: 8px;
683
+ padding: 12px 14px;
684
+ }
685
+
686
+ .checkbox-container input {
687
+ margin-right: 10px;
688
+ }
689
+
690
+ .sub-mode-selector {
691
+ display: flex;
692
+ justify-content: center;
693
+ background-color: #000;
694
+ border-radius: 10px;
695
+ padding: 4px;
696
+ border: 1px solid var(--border);
697
+ margin-bottom: 25px;
698
+ }
699
+ .sub-mode-btn {
700
+ flex: 1;
701
+ padding: 9px 15px;
702
+ background: transparent;
703
+ border: none;
704
+ color: var(--text-secondary);
705
+ font-size: 0.8rem;
706
+ font-weight: 600;
707
+ cursor: pointer;
708
+ border-radius: 7px;
709
+ transition: all 0.3s ease;
710
+ text-transform: uppercase;
711
+ }
712
+ .sub-mode-btn.active {
713
+ background-color: var(--primary);
714
+ color: #000;
715
+ box-shadow: 0 0 10px rgba(204, 255, 0, 0.3);
716
+ }
717
+ .sub-form-mode {
718
+ display: none;
719
+ }
720
+ .sub-form-mode.active {
721
+ display: contents;
722
+ }
723
+
724
+ .style-grid {
725
+ display: grid;
726
+ grid-template-columns: 1fr 1fr;
727
+ gap: 10px;
728
+ }
729
+
730
+ .style-btn {
731
+ padding: 12px 10px;
732
+ background-color: var(--input-bg);
733
+ border: 1px solid var(--border);
734
+ color: var(--text-secondary);
735
+ font-size: 0.85rem;
736
+ font-weight: 600;
737
+ cursor: pointer;
738
+ border-radius: 8px;
739
+ transition: all 0.3s ease;
740
+ text-align: center;
741
+ width: 100%;
742
+ }
743
+
744
+ .style-btn:hover {
745
+ border-color: var(--primary);
746
+ color: var(--text);
747
+ }
748
+
749
+ .style-btn.active {
750
+ background-color: var(--primary);
751
+ color: #000;
752
+ border-color: var(--primary);
753
+ box-shadow: 0 0 10px rgba(204, 255, 0, 0.3);
754
+ }
755
+
756
+ @media (max-width: 600px) {
757
+ .form-grid {
758
+ grid-template-columns: 1fr;
759
+ }
760
+ .full-width {
761
+ grid-column: span 1;
762
+ }
763
+ .container {
764
+ padding: 20px;
765
+ }
766
+ h1 {
767
+ font-size: 1.8rem;
768
+ }
769
+ .mode-selector {
770
+ grid-template-columns: 1fr;
771
+ gap: 5px;
772
+ }
773
+ }
774
+ </style>
775
+ </head>
776
+ <body>
777
+
778
+ <div class="container">
779
+ <h1>Synkris Look</h1>
780
+ <p class="subtitle">PROMPT GENERATOR & LAUNCHER</p>
781
+
782
+ <div class="mode-selector">
783
+ <button id="modeModelBtn" class="mode-btn" onclick="switchMode('model')">Фото на модели</button>
784
+ <button id="modeChildrenBtn" class="mode-btn" onclick="switchMode('children')">Модели (дети)</button>
785
+ <button id="modeObjectBtn" class="mode-btn" onclick="switchMode('object')">Предметное фото</button>
786
+ </div>
787
+
788
+ <form id="promptForm">
789
+ <div class="form-grid">
790
+
791
+ <div id="modelMode" class="form-mode">
792
+ <div class="form-group full-width">
793
+ <label class="checkbox-label">Своя модель (Virtual Try-On)</label>
794
+ <div class="checkbox-container">
795
+ <input type="checkbox" id="my_model_checkbox" onchange="toggleMyModelMode()">
796
+ <label for="my_model_checkbox" style="color: var(--text); text-transform: none; letter-spacing: 0;">
797
+ Использовать свое фото модели и одежды (требует 2 изображения в ИИ)
798
+ </label>
799
+ </div>
800
+ </div>
801
+ <div class="form-group">
802
+ <label for="gender">Пол</label>
803
+ <select id="gender" onchange="autoAdjustDefaults()">
804
+ <option value="Woman">Женщина</option>
805
+ <option value="Man">Мужчина</option>
806
+ </select>
807
+ </div>
808
+ <div class="form-group">
809
+ <label for="age">Возраст</label>
810
+ <select id="age">
811
+ <option value="18 years old">18 лет</option>
812
+ <option value="20-25 years old" selected>20-25 лет</option>
813
+ <option value="25-30 years old">25-30 лет</option>
814
+ <option value="30-40 years old">30-40 лет</option>
815
+ </select>
816
+ </div>
817
+ <div class="form-group">
818
+ <label for="nationality">Внешность/Этнос</label>
819
+ <select id="nationality">
820
+ <option value="Eastern European">Восточная Европа</option>
821
+ <option value="Northern European">Скандинавская</option>
822
+ <option value="Asian">Азиатская</option>
823
+ <option value="Latin American">Латиноамериканская</option>
824
+ <option value="Mixed Race">Смешанная</option>
825
+ </select>
826
+ </div>
827
+ <div class="form-group">
828
+ <label for="bodyType">Телосложение</label>
829
+ <select id="bodyType">
830
+ </select>
831
+ </div>
832
+ <div class="form-group">
833
+ <label for="hairColor">Цвет волос</label>
834
+ <select id="hairColor">
835
+ <option value="Brunette">Брюнет</option>
836
+ <option value="Blonde">Блонд</option>
837
+ <option value="Black">Черные</option>
838
+ <option value="Redhead">Рыжие</option>
839
+ </select>
840
+ </div>
841
+ <div class="form-group">
842
+ <label for="hairstyle">Стрижка</label>
843
+ <select id="hairstyle">
844
+ <option value="Long loose wavy hair">Длинные волны</option>
845
+ <option value="Straight long hair">Длинные прямые</option>
846
+ <option value="Messy bun">Небрежный пучок</option>
847
+ <option value="Bob cut">Каре</option>
848
+ <option value="Fade cut">Фейд (Мужской)</option>
849
+ </select>
850
+ </div>
851
+ <div class="form-group">
852
+ <label for="emotion">Эмоция/Выражение лица</label>
853
+ <select id="emotion">
854
+ <option value="Confident look">Уверенный взгляд</option>
855
+ <option value="Smiling gently">Легкая улыбка</option>
856
+ <option value="Serious and thoughtful">Серьезное и вдумчивое</option>
857
+ <option value="Playful wink">Игривое подмигивание</option>
858
+ <option value="Mysterious gaze">Загадочный взгляд</option>
859
+ </select>
860
+ </div>
861
+ <div class="form-group">
862
+ <label for="pose">Поза</label>
863
+ <select id="pose">
864
+ <option value="standing confidently">Стоит уверенно</option>
865
+ <option value="walking towards camera">Идет на камеру</option>
866
+ <option value="sitting relaxed">Сидит расслабленно</option>
867
+ <option value="leaning against a wall">Оперевшись о стену</option>
868
+ <option value="dynamic high fashion editorial pose" selected>Динамичная поза</option>
869
+ </select>
870
+ </div>
871
+ <div class="form-group">
872
+ <label for="shotType">Ракурс/План</label>
873
+ <select id="shotType">
874
+ <option value="Full body shot">В полный рост</option>
875
+ <option value="Medium shot, waist up">По пояс</option>
876
+ <option value="Cowboy shot, mid-thigh up">"Ковбойский" план</option>
877
+ <option value="Portrait shot">Портрет</option>
878
+ <option value="Close-up">Крупный план</option>
879
+ </select>
880
+ </div>
881
+ <div class="form-group">
882
+ <label for="light">Свет</label>
883
+ <select id="light">
884
+ <option value="volumetric studio lighting">Объемный студийный</option>
885
+ <option value="cinematic lighting">Кинематографичный</option>
886
+ <option value="natural morning light">Естественный утренний</option>
887
+ <option value="dramatic side light">Драматичный боковой</option>
888
+ <option value="neon lights">Неоновый</option>
889
+ </select>
890
+ </div>
891
+ <div class="form-group full-width">
892
+ <label>Эстетика</label>
893
+ <div id="styleSelector" class="style-grid">
894
+ <button type="button" class="style-btn active" data-value="Raw Candid Photography">Живое фото (Raw)</button>
895
+ <button type="button" class="style-btn" data-value="Cinematic Movie Still">Кадр из фильма</button>
896
+ <button type="button" class="style-btn" data-value="Fashion Editorial">Модный журнал</button>
897
+ <button type="button" class="style-btn" data-value="Street Style Photo">Уличный стиль</button>
898
+ <button type="button" class="style-btn" data-value="Dark Moody Atmosphere">Мрачная атмосфера</button>
899
+ <button type="button" class="style-btn" data-value="Vintage Analog Film">Пленка (Vintage)</button>
900
+ </div>
901
+ </div>
902
+ <div class="form-group">
903
+ <label for="camera">Камера/Объектив</label>
904
+ <select id="camera">
905
+ <option value="Fujifilm XT4, 56mm F1.2 lens">Fuji 56mm (Портрет)</option>
906
+ <option value="Sony A7III, 35mm F1.4 lens">Sony 35mm (Универсал)</option>
907
+ <option value="Canon EOS R5, 85mm F1.2 lens">Canon 85mm (Боке)</option>
908
+ <option value="Leica M11, Summilux 50mm">Leica 50mm (Стрит)</option>
909
+ <option value="shot on 35mm film, Kodak Portra 400">Пленка Kodak Portra</option>
910
+ </select>
911
+ </div>
912
+ <div class="form-group full-width">
913
+ <label for="location">Локация</label>
914
+ <select id="location">
915
+ <option value="in a clean white seamless studio background">Студия (белый фон)</option>
916
+ <option value="in a creative editorial studio with mirrors and geometric shapes">Студия "Эдиториал" (зеркала)</option>
917
+ <option value="on a rainy night street in Tokyo with neon lights">Улица (ночной Токио, неон)</option>
918
+ <option value="in a minimalist modern interior with concrete walls">Минимализм (лофт, бетон)</option>
919
+ <option value="on a rooftop overlooking the city skyline at sunset">Крыша с видом на город</option>
920
+ <option value="in a luxurious vintage room with classic furniture">Роскошный интерьер (винтаж)</option>
921
+ <option value="in a dense, magical forest with sunbeams filtering through">Природа (сказочный лес)</option>
922
+ <option value="on a beautiful sandy beach during the golden hour">Природа (пляж, закат)</option>
923
+ <option value="in a vibrant, bustling urban market">Город (оживленный рынок)</option>
924
+ <option value="inside a futuristic, sci-fi corridor with glowing lines">Фантастика (коридор)</option>
925
+ </select>
926
+ </div>
927
+ <div class="form-group full-width">
928
+ <label for="model_details">Одежда и Детали (Опишите ткань и фасон!)</label>
929
+ <textarea id="model_details" placeholder="Укажите ткань и детали. Пример: в черном кожаном плаще с грубой текстурой, заметные швы, массивная металлическая фурнитура, шелковый шарф"></textarea>
930
+ </div>
931
+ </div>
932
+
933
+ <div id="childrenMode" class="form-mode">
934
+ <div class="full-width sub-mode-selector">
935
+ <button id="newbornBtn" type="button" class="sub-mode-btn" onclick="switchChildrenSubMode('newborn')">Новорождённые</button>
936
+ <button id="olderChildrenBtn" type="button" class="sub-mode-btn" onclick="switchChildrenSubMode('older')">Дети и подростки</button>
937
+ </div>
938
+
939
+ <div id="newbornSubMode" class="sub-form-mode">
940
+ <div class="form-group">
941
+ <label>Пол</label>
942
+ <select disabled><option>Нейтральный</option></select>
943
+ </div>
944
+ <div class="form-group">
945
+ <label for="newborn_age">Возраст</label>
946
+ <select id="newborn_age">
947
+ <option value="1 month old newborn baby">0-3 месяца</option>
948
+ <option value="4 months old baby">3-6 месяцев</option>
949
+ </select>
950
+ </div>
951
+ <div class="form-group">
952
+ <label for="newborn_ethnicity">Внешность/Этнос</label>
953
+ <select id="newborn_ethnicity">
954
+ <option value="European">Европейская</option>
955
+ <option value="Asian">Азиатская</option>
956
+ <option value="Latin">Латиноамериканская</option>
957
+ <option value="Mixed Race">Смешанная</option>
958
+ </select>
959
+ </div>
960
+ <div class="form-group">
961
+ <label for="newborn_emotion">Эмоция/Состояние</label>
962
+ <select id="newborn_emotion">
963
+ <option value="sleeping peacefully">Мирно спит</option>
964
+ <option value="calm and awake">Спокоен и бодрствует</option>
965
+ <option value="cute yawn">Мило зевает</option>
966
+ <option value="gentle smile in sleep">Улыбается во сне</option>
967
+ </select>
968
+ </div>
969
+ <div class="form-group full-width">
970
+ <label for="newborn_pose">Поза</label>
971
+ <select id="newborn_pose">
972
+ <option value="wrapped in a soft swaddle">Завернут в пеленку</option>
973
+ <option value="lying in a cozy basket">Лежит в уютной корзинке</option>
974
+ <option value="on a fluffy white blanket">На пушистом белом пледе</option>
975
+ <option value="tummy time pose">Лежит на животике</option>
976
+ </select>
977
+ </div>
978
+ <div class="form-group full-width">
979
+ <label for="newborn_details">Одежда и Детали (Ткань, вязка)</label>
980
+ <textarea id="newborn_details" placeholder="Пример: в вязаной шапочке крупной вязки (шерсть мериноса), хлопковая пеленка с текстурой муслина"></textarea>
981
+ </div>
982
+ </div>
983
+
984
+ <div id="olderChildrenSubMode" class="sub-form-mode">
985
+ <div class="form-group">
986
+ <label for="child_gender">Пол</label>
987
+ <select id="child_gender">
988
+ <option value="Boy">Мальчик</option>
989
+ <option value="Girl">Девочка</option>
990
+ </select>
991
+ </div>
992
+ <div class="form-group">
993
+ <label for="child_age">Возраст</label>
994
+ <select id="child_age">
995
+ <option value="2 years old toddler">1-3 года</option>
996
+ <option value="5 years old child">4-6 лет</option>
997
+ <option value="8 years old child">7-10 лет</option>
998
+ <option value="12 years old pre-teen">11-14 лет</option>
999
+ <option value="16 years old teenager">15-17 лет</option>
1000
+ </select>
1001
+ </div>
1002
+ <div class="form-group">
1003
+ <label for="child_ethnicity">Внешность/Этнос</label>
1004
+ <select id="child_ethnicity">
1005
+ <option value="Eastern European">Восточная Европа</option>
1006
+ <option value="Northern European">Скандинавская</option>
1007
+ <option value="Asian">Азиатская</option>
1008
+ <option value="Latin American">Латиноамериканская</option>
1009
+ </select>
1010
+ </div>
1011
+ <div class="form-group">
1012
+ <label for="child_emotion">Эмоция/Выражение лица</label>
1013
+ <select id="child_emotion">
1014
+ <option value="happy and laughing">Счастливый, смеется</option>
1015
+ <option value="curious and looking at camera">Любопытный взгляд</option>
1016
+ <option value="thoughtful and calm">Задумчивый</option>
1017
+ <option value="energetic and playful">Энергичный, игривый</option>
1018
+ </select>
1019
+ </div>
1020
+ <div class="form-group full-width">
1021
+ <label for="child_pose">Поза/Действие</label>
1022
+ <select id="child_pose">
1023
+ <option value="running in a field">Бежит по полю</option>
1024
+ <option value="playing with toys">Играет с игрушками</option>
1025
+ <option value="sitting and reading a book">Сидит с книгой</option>
1026
+ <option value="hugging a pet">Обнимает питомца</option>
1027
+ <option value="posing for a school photo">Позирует для фото</option>
1028
+ </select>
1029
+ </div>
1030
+ <div class="form-group full-width">
1031
+ <label for="child_details">Одежда и Детали (Опишите материалы!)</label>
1032
+ <textarea id="child_details" placeholder="Пример: джинсовый комбинезон с потертостями и металлическими пуговицами, вельветовая рубашка в рубчик"></textarea>
1033
+ </div>
1034
+ </div>
1035
+
1036
+ <div class="form-group">
1037
+ <label for="child_shotType">Ракурс/План</label>
1038
+ <select id="child_shotType">
1039
+ <option value="Full body shot">В полный рост</option>
1040
+ <option value="Medium shot, waist up">По пояс</option>
1041
+ <option value="Portrait shot">Портрет</option>
1042
+ <option value="Candid action shot">Репортажный (в движении)</option>
1043
+ </select>
1044
+ </div>
1045
+ <div class="form-group">
1046
+ <label for="child_light">Свет</label>
1047
+ <select id="child_light">
1048
+ <option value="soft natural daylight">Мягкий дневной свет</option>
1049
+ <option value="golden hour lighting">Свет "золотого часа"</option>
1050
+ <option value="bright studio light">Яркий студийный</option>
1051
+ <option value="cinematic lighting">Кинематографичный</option>
1052
+ </select>
1053
+ </div>
1054
+ <div class="form-group full-width">
1055
+ <label for="child_location">Локация</label>
1056
+ <select id="child_location">
1057
+ <option value="in a clean white seamless studio background">Студия (белый фон)</option>
1058
+ <option value="in a sunlit green park">Солнечный парк</option>
1059
+ <option value="on a sandy beach">Песчаный пляж</option>
1060
+ <option value="in a cozy, decorated children's room">Уютная детская комната</option>
1061
+ <option value="in a magical forest">Сказочный лес</option>
1062
+ <option value="at an urban playground">Городская площадка</option>
1063
+ </select>
1064
+ </div>
1065
+ <div class="form-group full-width">
1066
+ <label for="child_style">Эстетика</label>
1067
+ <select id="child_style">
1068
+ <option value="Candid lifestyle photography">Лайфстайл фото</option>
1069
+ <option value="Fine art portrait">Художественный портрет</option>
1070
+ <option value="Cinematic Movie Still">Кадр из фильма</option>
1071
+ <option value="Vintage Analog Film">Пленка (Vintage)</option>
1072
+ </select>
1073
+ </div>
1074
+ </div>
1075
+
1076
+ <div id="objectMode" class="form-mode">
1077
+ <div class="form-group full-width">
1078
+ <label for="object_name">Название/Описание предмета</label>
1079
+ <input type="text" id="object_name" placeholder="Например: флакон духов 'Noir', кроссовки 'CyberRun', часы 'Classic Timepiece'">
1080
+ </div>
1081
+ <div class="form-group">
1082
+ <label for="object_style">Стилистика съемки</label>
1083
+ <select id="object_style">
1084
+ <option value="Minimalism on a cyclorama">Минимализм на циклораме</option>
1085
+ <option value="Lifestyle, in context">Лайфстайл (в контексте)</option>
1086
+ <option value="Detailed macro shot">Макросъемка деталей</option>
1087
+ <option value="Levitation shot">Левитация (в воздухе)</option>
1088
+ <option value="Creative flat lay">Креативная раскладка (Flat lay)</option>
1089
+ </select>
1090
+ </div>
1091
+ <div class="form-group">
1092
+ <label for="object_lighting">Освещение</label>
1093
+ <select id="object_lighting">
1094
+ <option value="soft, diffused studio light">Мягкий студийный свет</option>
1095
+ <option value="hard direct sunlight with dramatic shadows">Жесткий солнечный с тенями</option>
1096
+ <option value="backlit with a beautiful glow">Контровой свет (с сиянием)</option>
1097
+ <option value="moody, low-key lighting">Мрачное, низкий ключ</option>
1098
+ <option value="vibrant neon and colored gels">Цветной/неоновый свет</option>
1099
+ </select>
1100
+ </div>
1101
+ <div class="form-group">
1102
+ <label for="object_composition">Композиция</label>
1103
+ <select id="object_composition">
1104
+ <option value="centered composition">Центральная</option>
1105
+ <option value="dynamic diagonal angle">Динамичная диагональная</option>
1106
+ <option value="rule of thirds">По правилу третей</option>
1107
+ <option value="symmetrical composition">Симметричная</option>
1108
+ </select>
1109
+ </div>
1110
+ <div class="form-group">
1111
+ <label for="object_background">Тип фона</label>
1112
+ <select id="object_background">
1113
+ <option value="clean studio background (white/grey)">Однотонный студийный</option>
1114
+ <option value="on a wooden surface">Деревянная поверхность</option>
1115
+ <option value="on a marble surface">Мрамор</option>
1116
+ <option value="on a concrete texture">Бетон</option>
1117
+ <option value="on a silk/linen fabric">Ткань (шелк/лен)</option>
1118
+ <option value="in a natural environment (moss, sand, water)">Природное окружение (мох, песок)</option>
1119
+ </select>
1120
+ </div>
1121
+ <div class="form-group full-width">
1122
+ <label for="object_details">Дополнительные детали окружения</label>
1123
+ <textarea id="object_details" placeholder="Пример: капли воды на флаконе, текстура кожи ремешка, гравировка на металле"></textarea>
1124
+ </div>
1125
+ <div class="form-group full-width">
1126
+ <label class="checkbox-label">Креативность</label>
1127
+ <div class="checkbox-container">
1128
+ <input type="checkbox" id="creative_mode" onchange="toggleCreativeMode()">
1129
+ <label for="creative_mode" style="color: var(--text); text-transform: none; letter-spacing: 0;">Креативный фон от ИИ (игнорирует "Тип фона")</label>
1130
+ </div>
1131
+ </div>
1132
+ </div>
1133
+ </div>
1134
+
1135
+ <div class="btn-container">
1136
+ <button type="button" class="action-btn" onclick="processAndOpen()">
1137
+ <span>Launch Synkris AI</span>
1138
+ <span style="font-size: 1.2em">⚡</span>
1139
+ </button>
1140
+ </div>
1141
+ </form>
1142
+ </div>
1143
+
1144
+ <script>
1145
+ let currentMode = 'model';
1146
+ let currentChildrenSubMode = 'newborn';
1147
+ const envKeyword = {{ keyword|tojson|safe }};
1148
+
1149
+ const bodyTypes = {
1150
+ Woman: {
1151
+ 'Fit and slim': 'Стройное/Подтянутое',
1152
+ 'Curvy': 'Пышное (Curvy)',
1153
+ 'Athletic': 'Спортивное',
1154
+ 'Skinny model look': 'Модельная худоба',
1155
+ 'Hourglass figure': 'Песочные часы',
1156
+ 'Plus-size': 'Плюс-сайз'
1157
+ },
1158
+ Man: {
1159
+ 'Athletic': 'Спортивное',
1160
+ 'Lean and toned': 'Поджарое',
1161
+ 'Muscular build': 'Мускулистое',
1162
+ 'Broad build': 'Крупное',
1163
+ 'Slim build': 'Худощавое'
1164
+ }
1165
+ };
1166
+
1167
+ function switchMode(mode) {
1168
+ currentMode = mode;
1169
+ document.getElementById('modelMode').classList.toggle('active', mode === 'model');
1170
+ document.getElementById('childrenMode').classList.toggle('active', mode === 'children');
1171
+ document.getElementById('objectMode').classList.toggle('active', mode === 'object');
1172
+
1173
+ document.getElementById('modeModelBtn').classList.toggle('active', mode === 'model');
1174
+ document.getElementById('modeChildrenBtn').classList.toggle('active', mode === 'children');
1175
+ document.getElementById('modeObjectBtn').classList.toggle('active', mode === 'object');
1176
+ }
1177
+
1178
+ function switchChildrenSubMode(subMode) {
1179
+ currentChildrenSubMode = subMode;
1180
+ document.getElementById('newbornSubMode').classList.toggle('active', subMode === 'newborn');
1181
+ document.getElementById('olderChildrenSubMode').classList.toggle('active', subMode === 'older');
1182
+
1183
+ document.getElementById('newbornBtn').classList.toggle('active', subMode === 'newborn');
1184
+ document.getElementById('olderChildrenBtn').classList.toggle('active', subMode === 'older');
1185
+ }
1186
+
1187
+ function populateBodyTypes(gender) {
1188
+ const bodyTypeSelect = document.getElementById('bodyType');
1189
+ bodyTypeSelect.innerHTML = '';
1190
+ const types = bodyTypes[gender];
1191
+ for (const value in types) {
1192
+ const option = document.createElement('option');
1193
+ option.value = value;
1194
+ option.textContent = types[value];
1195
+ bodyTypeSelect.appendChild(option);
1196
+ }
1197
+ }
1198
+
1199
+ function autoAdjustDefaults() {
1200
+ if (currentMode !== 'model') return;
1201
+ const gender = document.getElementById('gender').value;
1202
+ const hairstyle = document.getElementById('hairstyle');
1203
+
1204
+ populateBodyTypes(gender);
1205
+
1206
+ const bodyType = document.getElementById('bodyType');
1207
+
1208
+ if (gender === 'Man') {
1209
+ hairstyle.value = 'Fade cut';
1210
+ bodyType.value = 'Athletic';
1211
+ } else {
1212
+ hairstyle.value = 'Long loose wavy hair';
1213
+ bodyType.value = 'Fit and slim';
1214
+ }
1215
+ }
1216
+
1217
+ function toggleMyModelMode() {
1218
+ const isMyModel = document.getElementById('my_model_checkbox').checked;
1219
+ const fieldsToToggle = ['gender', 'age', 'nationality', 'hairColor', 'hairstyle', 'emotion'];
1220
+
1221
+ fieldsToToggle.forEach(fieldId => {
1222
+ const element = document.getElementById(fieldId);
1223
+ if (element) {
1224
+ element.disabled = isMyModel;
1225
+ }
1226
+ });
1227
+ }
1228
+
1229
+ function toggleCreativeMode() {
1230
+ const isCreative = document.getElementById('creative_mode').checked;
1231
+ document.getElementById('object_background').disabled = isCreative;
1232
+ }
1233
+
1234
+ function setupStyleSelector() {
1235
+ const styleContainer = document.getElementById('styleSelector');
1236
+ if (!styleContainer) return;
1237
+ const styleButtons = styleContainer.querySelectorAll('.style-btn');
1238
+
1239
+ styleButtons.forEach(btn => {
1240
+ btn.addEventListener('click', () => {
1241
+ styleButtons.forEach(innerBtn => innerBtn.classList.remove('active'));
1242
+ btn.classList.add('active');
1243
+ });
1244
+ });
1245
+ }
1246
+
1247
+ async function processAndOpen() {
1248
+ const btn = document.querySelector('.action-btn');
1249
+ const originalText = btn.innerHTML;
1250
+ let fullPrompt = '';
1251
+
1252
+ if (currentMode === 'model') {
1253
+ const isMyModel = document.getElementById('my_model_checkbox').checked;
1254
+ const style = document.querySelector('#styleSelector .style-btn.active').dataset.value;
1255
+ const shotType = document.getElementById('shotType').value;
1256
+ const bodyType = document.getElementById('bodyType').value;
1257
+ const pose = document.getElementById('pose').value;
1258
+ const location = document.getElementById('location').value;
1259
+ const light = document.getElementById('light').value;
1260
+ const camera = document.getElementById('camera').value;
1261
+
1262
+ if (isMyModel) {
1263
+ const details = document.getElementById('model_details').value || "the clothing from the reference image";
1264
+ fullPrompt = `${envKeyword}, VIRTUAL TRY-ON.
1265
+ INSTRUCTIONS FOR AI: This is a virtual try-on task. You will be given two images.
1266
+ - Image 1 (Model): Use this as the reference for the model's face, identity, pose, and body shape.
1267
+ - Image 2 (Garment): Use this image for the clothing item.
1268
+ Task: Accurately dress the model from Image 1 in the clothing from Image 2. The final image must preserve the model's exact likeness and facial identity. The model should have a body type of "${bodyType}".
1269
+ Style: ${style}, hyper-detailed, luxury brand campaign, Vogue aesthetic, impeccable.
1270
+ Composition: ${shotType}.
1271
+ Final Scene: Place the model in the following environment: ${location}.
1272
+ Lighting: The scene should have ${light}.
1273
+ Technical: Masterpiece professional photograph, shot on ${camera}, 8k UHD, tack sharp focus, breathtaking detail, perfect color grading.`;
1274
+ } else {
1275
+ const age = document.getElementById('age').value;
1276
+ const nationality = document.getElementById('nationality').value;
1277
+ const gender = document.getElementById('gender').value;
1278
+ const hairColor = document.getElementById('hairColor').value;
1279
+ const hairstyle = document.getElementById('hairstyle').value;
1280
+ const emotion = document.getElementById('emotion').value;
1281
+ const details = document.getElementById('model_details').value || "high-end fashion garments";
1282
+
1283
+ fullPrompt = `${envKeyword}, style:: ${style}, high fashion editorial, luxury brand campaign (like Dior, D&G), Vogue aesthetic, hyper-detailed, impeccable.
1284
+ composition:: ${shotType}.
1285
+ subject:: An ultra-high-resolution, flawless photograph of a striking ${age} ${nationality} high fashion model.
1286
+ model_characteristics:: physique ${bodyType}, ${hairColor} ${hairstyle} styled to perfection, expression ${emotion} (powerful yet serene), pose ${pose}.
1287
+ clothing_focus:: The model is wearing ${details}, emphasizing haute couture craftsmanship.
1288
+ texture_&_material_fidelity:: Extreme macro precision on textiles. Render the fabric weave, thread count, visible stitching, material weight, realistic creases and folds, tactile surface imperfections, and how light interacts with the fabric.
1289
+ human_realism_details:: Capture flawless yet realistic skin texture. Perfect complexion, highlighting bone structure with expert contouring light. The image must look professionally retouched for a high-end magazine, but retain believability. Avoid any hint of digital artifacting.
1290
+ scene_environment:: ${location}, creating a sophisticated and aspirational atmosphere.
1291
+ technical:: Masterpiece professional photograph, ${light} meticulously crafted to sculpt the subject, shot on ${camera}, 8k UHD, tack sharp focus, breathtaking detail, uncompressed, color graded to perfection, award-winning photography.`;
1292
+ }
1293
+
1294
+ } else if (currentMode === 'children') {
1295
+ const style = document.getElementById('child_style').value;
1296
+ const shotType = document.getElementById('child_shotType').value;
1297
+ const location = document.getElementById('child_location').value;
1298
+ const light = document.getElementById('child_light').value;
1299
+ let subject = '';
1300
+ let pose_info = '';
1301
+ let clothing_details = '';
1302
+
1303
+ if(currentChildrenSubMode === 'newborn') {
1304
+ const age = document.getElementById('newborn_age').value;
1305
+ const ethnicity = document.getElementById('newborn_ethnicity').value;
1306
+ const emotion = document.getElementById('newborn_emotion').value;
1307
+ const pose = document.getElementById('newborn_pose').value;
1308
+ clothing_details = document.getElementById('newborn_details').value || "soft knitted fabric";
1309
+ subject = `A beautiful, ultra-photorealistic portrait of a ${age} ${ethnicity} baby. Face expression is ${emotion}.`;
1310
+ pose_info = `The baby is ${pose}.`;
1311
+ } else {
1312
+ const age = document.getElementById('child_age').value;
1313
+ const gender = document.getElementById('child_gender').value;
1314
+ const ethnicity = document.getElementById('child_ethnicity').value;
1315
+ const emotion = document.getElementById('child_emotion').value;
1316
+ const pose = document.getElementById('child_pose').value;
1317
+ clothing_details = document.getElementById('child_details').value || "detailed textured casual clothes";
1318
+ subject = `A beautiful, ultra-photorealistic portrait of a ${age} ${ethnicity} ${gender}. Face expression is ${emotion}.`;
1319
+ pose_info = `The child is ${pose}.`;
1320
+ }
1321
+
1322
+ fullPrompt = `${envKeyword}, style:: ${style}, luxury children's fashion campaign, cinematic storytelling, enchanting, ultra-photorealistic.
1323
+ composition:: ${shotType}.
1324
+ subject:: ${subject} The photograph must look like a cover shot for a high-end children's fashion magazine.
1325
+ clothing_focus:: The child is wearing ${clothing_details}, presented as a luxury garment.
1326
+ texture_&_material_fidelity:: Macro-level detail on clothing textures. Focus on the weave of cotton, the softness of wool, the texture of denim. Show realistic wrinkles, creases from movement, and even subtle fabric pilling. 100% texture fidelity is crucial.
1327
+ human_realism_details:: Capture the pure, innocent beauty of the child. Flawless, dewy skin with a natural glow. The light should have a painterly, almost magical quality, highlighting their features beautifully. Eyes must be expressive and full of life.
1328
+ scene_activity:: ${pose_info} The location is ${location}, creating a whimsical and high-end narrative.
1329
+ technical:: Masterpiece photograph, ${light} creating a magical and soft atmosphere, shot on Fujifilm XT4, 56mm F1.2 lens, 8k, tack sharp focus, impeccable detail, perfect color grading, looks like a real captured moment of wonder from a luxury campaign.`;
1330
+
1331
+ } else {
1332
+ const objectName = document.getElementById('object_name').value || "a product";
1333
+ const objectStyle = document.getElementById('object_style').value;
1334
+ const objectLighting = document.getElementById('object_lighting').value;
1335
+ const objectComposition = document.getElementById('object_composition').value;
1336
+ const isCreative = document.getElementById('creative_mode').checked;
1337
+ const objectDetails = document.getElementById('object_details').value || "rich textures";
1338
+
1339
+ let background = '';
1340
+ if (isCreative) {
1341
+ background = "on a creative, surreal, and artistic background generated by AI to complement the product's essence";
1342
+ } else {
1343
+ background = document.getElementById('object_background').value;
1344
+ }
1345
+
1346
+ fullPrompt = `${envKeyword}, style:: Luxury product advertising, ${objectStyle}, sophisticated, sleek, ultra-photorealistic.
1347
+ subject:: A breathtaking, hyper-realistic photograph of the luxury product: ${objectName}. The image must evoke desire and exclusivity.
1348
+ material_focus:: Achieve 100% physical accuracy with an emphasis on perfection. Render pristine, flawless surfaces. Showcase the intricate details of the material grain, polished metal sheen, or crystal-clear refractions. Even microscopic details should look clean and perfect.
1349
+ scene_context:: Placed ${background}. Additional details: ${objectDetails}, arranged with artistic precision.
1350
+ composition:: ${objectComposition}, creating a powerful and elegant visual statement.
1351
+ technical:: Advertisement-grade photograph, ${objectLighting} designed to accentuate the product's luxury form, 8k UHD resolution, flawless focus, extreme macro detail, advanced ray-traced reflections, impeccably clean, exudes quality and high-end appeal, masterpiece.`;
1352
+ }
1353
+
1354
+ const cleanPrompt = fullPrompt.replace(/\\s+/g, ' ').replace(/\\n/g, ' ').trim();
1355
+
1356
+ try {
1357
+ await navigator.clipboard.writeText(cleanPrompt);
1358
+ btn.style.backgroundImage = "linear-gradient(45deg, #ffffff, #e0e0e0)";
1359
+ btn.style.color = "#000";
1360
+ btn.innerHTML = "ПРОМПТ СКОПИРОВАН. ЗАПУСК... 🚀";
1361
+
1362
+ setTimeout(() => {
1363
+ window.open('https://lmarena.ai/ru?chat-modality=image&mode=direct', '_blank');
1364
+ setTimeout(() => {
1365
+ btn.style.backgroundImage = "";
1366
+ btn.innerHTML = originalText;
1367
+ }, 1000);
1368
+ }, 800);
1369
+ } catch (err) {
1370
+ console.error('Failed to copy: ', err);
1371
+ alert("Не удалось скопировать. Промпт в консоли разработчика.");
1372
+ console.log("Ваш промпт:\\n", cleanPrompt);
1373
+ }
1374
+ }
1375
+
1376
+ document.addEventListener('DOMContentLoaded', () => {
1377
+ switchMode('model');
1378
+ switchChildrenSubMode('newborn');
1379
+ autoAdjustDefaults();
1380
+ setupStyleSelector();
1381
+ });
1382
+ </script>
1383
+
1384
+ </body>
1385
+ </html>
1386
+ '''
1387
+
1388
+ @app.route('/')
1389
+ def index():
1390
+ return render_template_string(LANDING_PAGE_TEMPLATE)
1391
+
1392
+ @app.route('/admhosto', methods=['GET'])
1393
+ def admhosto():
1394
+ data = load_data()
1395
+ environments_data = []
1396
+ for env_id, env_data in data.items():
1397
+ environments_data.append({
1398
+ "id": env_id,
1399
+ "keyword": env_data.get("keyword", "N/A"),
1400
+ "type": env_data.get("type", "closed"),
1401
+ "hits": env_data.get("hits", 0),
1402
+ "created_at": env_data.get("created_at", ""),
1403
+ "link": url_for('serve_env', env_id=env_id, _external=True)
1404
+ })
1405
+
1406
+ environments_data.sort(key=lambda x: x['created_at'], reverse=True)
1407
+
1408
+ return render_template_string(ADMHOSTO_TEMPLATE, environments=environments_data)
1409
+
1410
+ @app.route('/admhosto/create', methods=['POST'])
1411
+ def create_environment():
1412
+ all_data = load_data()
1413
+ keyword = request.form.get('keyword', '').strip()
1414
+ env_type = request.form.get('env_type', 'closed')
1415
+
1416
+ if not keyword:
1417
+ flash('Ключевое слово не может быть пустым.', 'error')
1418
+ return redirect(url_for('admhosto'))
1419
+
1420
+ while True:
1421
+ new_id = ''.join(random.choices(string.digits, k=6))
1422
+ if new_id not in all_data:
1423
+ break
1424
+
1425
+ all_data[new_id] = {
1426
+ "keyword": keyword,
1427
+ "type": env_type,
1428
+ "device_token": None,
1429
+ "hits": 0,
1430
+ "logs": [],
1431
+ "created_at": datetime.utcnow().isoformat()
1432
+ }
1433
+ save_data(all_data)
1434
+ flash(f'Новая {env_type} среда с ID {new_id} создана.', 'success')
1435
+ return redirect(url_for('admhosto'))
1436
+
1437
+ @app.route('/admhosto/delete/<env_id>', methods=['POST'])
1438
+ def delete_environment(env_id):
1439
+ all_data = load_data()
1440
+ if env_id in all_data:
1441
+ del all_data[env_id]
1442
+ save_data(all_data)
1443
+ flash(f'Среда {env_id} была удалена.', 'success')
1444
+ else:
1445
+ flash(f'Среда {env_id} не найдена.', 'error')
1446
+ return redirect(url_for('admhosto'))
1447
+
1448
+ @app.route('/admhosto/stats/<env_id>')
1449
+ def get_env_stats(env_id):
1450
+ data = load_data()
1451
+ env_data = data.get(env_id)
1452
+ if not env_data:
1453
+ return jsonify({"error": "Среда не найдена"}), 404
1454
+
1455
+ raw_logs = env_data.get("logs", [])
1456
+ formatted_logs = []
1457
+
1458
+ for log in reversed(raw_logs):
1459
+ try:
1460
+ utc_dt = datetime.fromisoformat(log['time'])
1461
+ almaty_dt = utc_dt + timedelta(hours=5)
1462
+ time_str = almaty_dt.strftime('%Y-%m-%d %H:%M:%S')
1463
+ formatted_logs.append({
1464
+ "time": time_str,
1465
+ "ip": log.get('ip', 'unknown'),
1466
+ "ua": log.get('ua', 'unknown')
1467
+ })
1468
+ except:
1469
+ continue
1470
+
1471
+ response_data = {
1472
+ "id": env_id,
1473
+ "keyword": env_data.get("keyword"),
1474
+ "type": env_data.get("type", "closed"),
1475
+ "hits": env_data.get("hits", 0),
1476
+ "logs": formatted_logs
1477
+ }
1478
+ return jsonify(response_data)
1479
+
1480
+ @app.route('/env/<env_id>')
1481
+ def serve_env(env_id):
1482
+ data = load_data()
1483
+ env_data = data.get(env_id)
1484
+ if not env_data:
1485
+ return "Среда не найдена.", 404
1486
+
1487
+ keyword = env_data.get("keyword", "")
1488
+ env_type = env_data.get("type", "closed")
1489
+
1490
+ current_log = {
1491
+ "time": datetime.utcnow().isoformat(),
1492
+ "ip": request.remote_addr,
1493
+ "ua": request.headers.get('User-Agent')[:50]
1494
+ }
1495
+
1496
+ env_data['hits'] = env_data.get('hits', 0) + 1
1497
+ if 'logs' not in env_data:
1498
+ env_data['logs'] = []
1499
+
1500
+ env_data['logs'].append(current_log)
1501
+ if len(env_data['logs']) > 30:
1502
+ env_data['logs'] = env_data['logs'][-30:]
1503
+
1504
+ data[env_id] = env_data
1505
+ save_data(data)
1506
+
1507
+ if env_type == 'open':
1508
+ return render_template_string(SYNKRIS_LOOK_TEMPLATE, keyword=keyword)
1509
+
1510
+ stored_token = env_data.get("device_token")
1511
+ user_token = request.cookies.get(f'access_token_{env_id}')
1512
+
1513
+ if stored_token:
1514
+ if user_token != stored_token:
1515
+ return """
1516
+ <!DOCTYPE html>
1517
+ <html lang="ru">
1518
+ <head>
1519
+ <meta charset="UTF-8">
1520
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1521
+ <title>Доступ запрещен</title>
1522
+ <style>
1523
+ body { font-family: 'Segoe UI', sans-serif; background: #000; color: #fff; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; text-align: center; }
1524
+ .container { padding: 20px; }
1525
+ h1 { color: #E57373; margin-bottom: 10px; }
1526
+ p { color: #aaa; }
1527
+ </style>
1528
+ </head>
1529
+ <body>
1530
+ <div class="container">
1531
+ <h1>⛔ Доступ запрещен</h1>
1532
+ <p>Эта ссылка уже привязана к другому устройству или браузеру.</p>
1533
+ </div>
1534
+ </body>
1535
+ </html>
1536
+ """, 403
1537
+ return render_template_string(SYNKRIS_LOOK_TEMPLATE, keyword=keyword)
1538
+ else:
1539
+ new_token = ''.join(random.choices(string.ascii_letters + string.digits, k=40))
1540
+ env_data['device_token'] = new_token
1541
+ data[env_id] = env_data
1542
+ save_data(data)
1543
+
1544
+ resp = make_response(render_template_string(SYNKRIS_LOOK_TEMPLATE, keyword=keyword))
1545
+ resp.set_cookie(f'access_token_{env_id}', new_token, max_age=31536000, httponly=True)
1546
+ return resp
1547
+
1548
+ if __name__ == '__main__':
1549
+ download_db_from_hf()
1550
+ if HF_TOKEN_WRITE:
1551
+ backup_thread = threading.Thread(target=periodic_backup, daemon=True)
1552
+ backup_thread.start()
1553
+ else:
1554
+ pass
1555
+ port = int(os.environ.get('PORT', 7860))
1556
+ app.run(debug=False, host='0.0.0.0', port=port)