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

Delete app.py

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