Aleksmorshen commited on
Commit
089e63e
·
verified ·
1 Parent(s): 5cc5b45

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -980
app.py DELETED
@@ -1,980 +0,0 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
-
4
- import os
5
- from flask import Flask, request, Response, render_template_string, jsonify, redirect, url_for
6
- import hmac
7
- import hashlib
8
- import json
9
- from urllib.parse import unquote, parse_qs, quote
10
- import time
11
- from datetime import datetime
12
- import logging
13
- import threading
14
- import asyncio
15
- from huggingface_hub import HfApi, hf_hub_download
16
- from huggingface_hub.utils import RepositoryNotFoundError
17
-
18
- from aiogram import Bot, Dispatcher, types, F
19
- from google import genai
20
- from google.genai import types as genai_types
21
-
22
- BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvtVsqEJVG5SYK5hUlc_Ewo")
23
- HOST = '0.0.0.0'
24
- PORT = 7860
25
- DATA_FILE = 'data.json'
26
-
27
- REPO_ID = "flpolprojects/teledata"
28
- HF_DATA_FILE_PATH = "data.json"
29
- HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE")
30
- HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
31
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
32
- GENAI_MODEL = "learnlm-2.0-flash-experimental"
33
-
34
- app = Flask(__name__)
35
- logging.basicConfig(level=logging.INFO)
36
- app.secret_key = os.urandom(24)
37
-
38
- _data_lock = threading.Lock()
39
- visitor_data_cache = {}
40
-
41
- def download_data_from_hf():
42
- global visitor_data_cache
43
- if not HF_TOKEN_READ:
44
- return False
45
- try:
46
- hf_hub_download(
47
- repo_id=REPO_ID,
48
- filename=HF_DATA_FILE_PATH,
49
- repo_type="dataset",
50
- token=HF_TOKEN_READ,
51
- local_dir=".",
52
- local_dir_use_symlinks=False,
53
- force_download=True,
54
- etag_timeout=10
55
- )
56
- with _data_lock:
57
- try:
58
- with open(DATA_FILE, 'r', encoding='utf-8') as f:
59
- visitor_data_cache = json.load(f)
60
- except (FileNotFoundError, json.JSONDecodeError) as e:
61
- visitor_data_cache = {}
62
- return True
63
- except RepositoryNotFoundError:
64
- pass
65
- except Exception as e:
66
- pass
67
- return False
68
-
69
- def load_visitor_data():
70
- global visitor_data_cache
71
- with _data_lock:
72
- if not visitor_data_cache:
73
- try:
74
- with open(DATA_FILE, 'r', encoding='utf-8') as f:
75
- visitor_data_cache = json.load(f)
76
- except FileNotFoundError:
77
- visitor_data_cache = {}
78
- except json.JSONDecodeError:
79
- visitor_data_cache = {}
80
- except Exception as e:
81
- visitor_data_cache = {}
82
- return visitor_data_cache
83
-
84
- def save_visitor_data(data):
85
- with _data_lock:
86
- try:
87
- visitor_data_cache.update(data)
88
- with open(DATA_FILE, 'w', encoding='utf-8') as f:
89
- json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4)
90
- upload_data_to_hf_async()
91
- except Exception as e:
92
- pass
93
-
94
- def upload_data_to_hf():
95
- if not HF_TOKEN_WRITE:
96
- return
97
- if not os.path.exists(DATA_FILE):
98
- return
99
-
100
- try:
101
- api = HfApi()
102
- with _data_lock:
103
- file_content_exists = os.path.getsize(DATA_FILE) > 0
104
- if not file_content_exists:
105
- return
106
-
107
- api.upload_file(
108
- path_or_fileobj=DATA_FILE,
109
- path_in_repo=HF_DATA_FILE_PATH,
110
- repo_id=REPO_ID,
111
- repo_type="dataset",
112
- token=HF_TOKEN_WRITE,
113
- commit_message=f"Update visitor data {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
114
- )
115
- except Exception as e:
116
- pass
117
-
118
- def upload_data_to_hf_async():
119
- upload_thread = threading.Thread(target=upload_data_to_hf, daemon=True)
120
- upload_thread.start()
121
-
122
- def periodic_backup():
123
- if not HF_TOKEN_WRITE:
124
- return
125
- while True:
126
- time.sleep(3600)
127
- upload_data_to_hf()
128
-
129
- def verify_telegram_data(init_data_str):
130
- try:
131
- parsed_data = parse_qs(init_data_str)
132
- received_hash = parsed_data.pop('hash', [None])[0]
133
-
134
- if not received_hash:
135
- return None, False
136
-
137
- data_check_list = []
138
- for key, value in sorted(parsed_data.items()):
139
- data_check_list.append(f"{key}={value[0]}")
140
- data_check_string = "\n".join(data_check_list)
141
-
142
- secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest()
143
- calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
144
-
145
- if calculated_hash == received_hash:
146
- auth_date = int(parsed_data.get('auth_date', [0])[0])
147
- current_time = int(time.time())
148
- if current_time - auth_date > 86400:
149
- pass
150
- return parsed_data, True
151
- else:
152
- pass
153
- return parsed_data, False
154
- except Exception as e:
155
- return None, False
156
-
157
- TEMPLATE = """
158
- <!DOCTYPE html>
159
- <html lang="ru">
160
- <head>
161
- <meta charset="UTF-8">
162
- <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no, viewport-fit=cover">
163
- <title>Morshen Group</title>
164
- <script src="https://telegram.org/js/telegram-web-app.js"></script>
165
- <link rel="preconnect" href="https://fonts.googleapis.com">
166
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
167
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
168
- <style>
169
- :root {
170
- --tg-theme-bg-color: {{ theme.bg_color | default('#121212') }};
171
- --tg-theme-text-color: {{ theme.text_color | default('#ffffff') }};
172
- --tg-theme-hint-color: {{ theme.hint_color | default('#aaaaaa') }};
173
- --tg-theme-link-color: {{ theme.link_color | default('#62bcf9') }};
174
- --tg-theme-button-color: {{ theme.button_color | default('#31a5f5') }};
175
- --tg-theme-button-text-color: {{ theme.button_text_color | default('#ffffff') }};
176
- --tg-theme-secondary-bg-color: {{ theme.secondary_bg_color | default('#1e1e1e') }};
177
-
178
- --bg-gradient: linear-gradient(160deg, #1a232f 0%, #121212 100%);
179
- --card-bg: rgba(44, 44, 46, 0.8);
180
- --card-bg-solid: #2c2c2e;
181
- --text-color: var(--tg-theme-text-color);
182
- --text-secondary-color: var(--tg-theme-hint-color);
183
- --accent-gradient: linear-gradient(95deg, var(--tg-theme-button-color, #007aff), #5856d6);
184
- --accent-gradient-green: linear-gradient(95deg, #34c759, #30d158);
185
- --tag-bg: rgba(255, 255, 255, 0.1);
186
- --border-radius-s: 8px;
187
- --border-radius-m: 14px;
188
- --border-radius-l: 18px;
189
- --padding-s: 10px;
190
- --padding-m: 18px;
191
- --padding-l: 28px;
192
- --font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
193
- --shadow-color: rgba(0, 0, 0, 0.3);
194
- --shadow-light: 0 4px 15px var(--shadow-color);
195
- --shadow-medium: 0 6px 25px var(--shadow-color);
196
- --backdrop-blur: 10px;
197
- }
198
- * { box-sizing: border-box; margin: 0; padding: 0; }
199
- html {
200
- background-color: var(--tg-theme-bg-color);
201
- scroll-behavior: smooth;
202
- }
203
- body {
204
- font-family: var(--font-family);
205
- background: var(--bg-gradient);
206
- color: var(--text-color);
207
- padding: var(--padding-m);
208
- padding-bottom: 120px;
209
- overscroll-behavior-y: none;
210
- -webkit-font-smoothing: antialiased;
211
- -moz-osx-font-smoothing: grayscale;
212
- visibility: hidden;
213
- min-height: 100vh;
214
- }
215
- .container {
216
- max-width: 650px;
217
- margin: 0 auto;
218
- display: flex;
219
- flex-direction: column;
220
- gap: var(--padding-l);
221
- }
222
- .header {
223
- display: flex;
224
- justify-content: space-between;
225
- align-items: center;
226
- margin-bottom: var(--padding-m);
227
- padding: var(--padding-s) 0;
228
- }
229
- .logo { display: flex; align-items: center; gap: var(--padding-s); }
230
- .logo img {
231
- width: 50px;
232
- height: 50px;
233
- border-radius: 50%;
234
- background-color: var(--card-bg-solid);
235
- object-fit: cover;
236
- border: 2px solid rgba(255, 255, 255, 0.15);
237
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
238
- }
239
- .logo span { font-size: 1.6em; font-weight: 700; letter-spacing: -0.5px; }
240
- .btn {
241
- display: inline-flex; align-items: center; justify-content: center;
242
- padding: 12px var(--padding-m); border-radius: var(--border-radius-m);
243
- background: var(--accent-gradient); color: var(--tg-theme-button-text-color);
244
- text-decoration: none; font-weight: 600;
245
- border: none; cursor: pointer;
246
- transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
247
- gap: 8px; font-size: 1em;
248
- box-shadow: var(--shadow-light);
249
- letter-spacing: 0.3px;
250
- }
251
- .btn:hover {
252
- opacity: 0.9;
253
- box-shadow: var(--shadow-medium);
254
- transform: translateY(-2px);
255
- }
256
- .btn-secondary {
257
- background: var(--card-bg);
258
- color: var(--tg-theme-link-color);
259
- box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.1), var(--shadow-light);
260
- }
261
- .btn-secondary:hover {
262
- background: rgba(44, 44, 46, 0.95);
263
- box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), var(--shadow-medium);
264
- }
265
- .tag {
266
- display: inline-block; background: var(--tag-bg); color: var(--text-secondary-color);
267
- padding: 6px 12px; border-radius: var(--border-radius-s); font-size: 0.85em;
268
- margin: 4px 6px 4px 0; white-space: nowrap;
269
- font-weight: 500;
270
- border: 1px solid rgba(255, 255, 255, 0.05);
271
- }
272
- .tag i { margin-right: 5px; opacity: 0.8; }
273
- .section-card {
274
- background-color: var(--card-bg);
275
- border-radius: var(--border-radius-l);
276
- padding: var(--padding-l);
277
- margin-bottom: 0;
278
- box-shadow: var(--shadow-medium);
279
- border: 1px solid rgba(255, 255, 255, 0.08);
280
- backdrop-filter: blur(var(--backdrop-blur));
281
- -webkit-backdrop-filter: blur(var(--backdrop-blur));
282
- }
283
- .section-title {
284
- font-size: 2em;
285
- font-weight: 700; margin-bottom: var(--padding-s); line-height: 1.25;
286
- letter-spacing: -0.6px;
287
- }
288
- .section-subtitle {
289
- font-size: 1.2em; font-weight: 500; color: var(--text-secondary-color);
290
- margin-bottom: var(--padding-m);
291
- }
292
- .description {
293
- font-size: 1.05em; line-height: 1.6; color: var(--text-secondary-color);
294
- margin-bottom: var(--padding-m);
295
- }
296
- .stats-grid {
297
- display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
298
- gap: var(--padding-m); margin-top: var(--padding-m); text-align: center;
299
- }
300
- .stat-item {
301
- background-color: rgba(255, 255, 255, 0.05);
302
- padding: var(--padding-m); border-radius: var(--border-radius-m);
303
- border: 1px solid rgba(255, 255, 255, 0.05);
304
- transition: background-color 0.2s ease;
305
- }
306
- .stat-item:hover { background-color: rgba(255, 255, 255, 0.08); }
307
- .stat-value { font-size: 1.7em; font-weight: 600; display: block; color: var(--tg-theme-link-color);}
308
- .stat-label { font-size: 0.9em; color: var(--text-secondary-color); display: block; margin-top: 4px;}
309
- .list-item {
310
- background-color: var(--card-bg-solid);
311
- padding: var(--padding-m); border-radius: var(--border-radius-m);
312
- margin-bottom: var(--padding-s); display: flex; align-items: center;
313
- gap: var(--padding-m);
314
- font-size: 1.1em; font-weight: 500;
315
- border: 1px solid rgba(255, 255, 255, 0.08);
316
- transition: background-color 0.2s ease, transform 0.2s ease;
317
- }
318
- .list-item:hover {
319
- background-color: rgba(44, 44, 46, 0.9);
320
- transform: translateX(3px);
321
- }
322
- .list-item i { font-size: 1.4em; color: var(--accent-gradient-start, #34c759); opacity: 0.9; width: 25px; text-align: center;}
323
- .footer-greeting {
324
- text-align: center; color: var(--text-secondary-color); font-size: 0.95em;
325
- margin-top: var(--padding-l); padding-bottom: var(--padding-l);
326
- }
327
- .save-card-button {
328
- position: fixed;
329
- bottom: 30px;
330
- left: 50%;
331
- transform: translateX(-50%);
332
- padding: 14px 28px;
333
- border-radius: 30px;
334
- background: var(--accent-gradient-green);
335
- color: var(--tg-theme-button-text-color);
336
- text-decoration: none;
337
- font-weight: 600;
338
- border: none;
339
- cursor: pointer;
340
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
341
- z-index: 1000;
342
- box-shadow: var(--shadow-medium), 0 0 0 4px rgba(var(--tg-theme-bg-color-rgb, 18, 18, 18), 0.5);
343
- font-size: 1.05em;
344
- display: flex;
345
- align-items: center;
346
- gap: 10px;
347
- backdrop-filter: blur(5px);
348
- -webkit-backdrop-filter: blur(5px);
349
- }
350
- .save-card-button:hover {
351
- opacity: 0.95;
352
- transform: translateX(-50%) scale(1.05);
353
- box-shadow: var(--shadow-medium), 0 0 0 4px rgba(var(--tg-theme-bg-color-rgb, 18, 18, 18), 0.3);
354
- }
355
- .save-card-button i { font-size: 1.2em; }
356
-
357
- .modal {
358
- display: none; position: fixed; z-index: 1001;
359
- left: 0; top: 0; width: 100%; height: 100%;
360
- overflow: auto; background-color: rgba(0,0,0,0.7);
361
- backdrop-filter: blur(8px);
362
- -webkit-backdrop-filter: blur(8px);
363
- animation: fadeIn 0.3s ease-out;
364
- }
365
- @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
366
- .modal-content {
367
- background-color: var(--card-bg-solid); color: var(--text-color);
368
- margin: 15% auto; padding: var(--padding-l);
369
- border: 1px solid rgba(255, 255, 255, 0.1);
370
- width: 88%; max-width: 480px;
371
- border-radius: var(--border-radius-l);
372
- text-align: center; position: relative;
373
- box-shadow: var(--shadow-medium);
374
- animation: scaleUp 0.3s ease-out;
375
- }
376
- @keyframes scaleUp { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } }
377
- .modal-close {
378
- color: var(--text-secondary-color);
379
- position: absolute; top: 15px; right: 20px;
380
- font-size: 32px; font-weight: bold; cursor: pointer;
381
- line-height: 1; transition: color 0.2s ease;
382
- }
383
- .modal-close:hover, .modal-close:focus { color: var(--text-color); }
384
- .modal-text { font-size: 1.2em; line-height: 1.6; margin-bottom: var(--padding-s); word-wrap: break-word; }
385
- .modal-text b { color: var(--tg-theme-link-color); font-weight: 600; }
386
- .modal-instruction { font-size: 1em; color: var(--text-secondary-color); margin-top: var(--padding-m); }
387
-
388
- .icon { display: inline-block; width: 1.2em; text-align: center; margin-right: 8px; opacity: 0.9; }
389
- .icon-save::before { content: '💾'; }
390
- .icon-web::before { content: '🌐'; }
391
- .icon-mobile::before { content: '📱'; }
392
- .icon-code::before { content: '💻'; }
393
- .icon-ai::before { content: '🧠'; }
394
- .icon-quantum::before { content: '⚛️'; }
395
- .icon-business::before { content: '💼'; }
396
- .icon-speed::before { content: '⚡️'; }
397
- .icon-complexity::before { content: '🧩'; }
398
- .icon-experience::before { content: '⏳'; }
399
- .icon-clients::before { content: '👥'; }
400
- .icon-market::before { content: '📈'; }
401
- .icon-location::before { content: '📍'; }
402
- .icon-global::before { content: '🌍'; }
403
- .icon-innovation::before { content: '💡'; }
404
- .icon-contact::before { content: '💬'; }
405
- .icon-link::before { content: '🔗'; }
406
- .icon-leader::before { content: '🏆'; }
407
- .icon-company::before { content: '🏢'; }
408
-
409
- @media (max-width: 480px) {
410
- .section-title { font-size: 1.8em; }
411
- .logo span { font-size: 1.4em; }
412
- .btn { padding: 10px var(--padding-m); font-size: 0.95em; }
413
- .save-card-button { padding: 12px 24px; font-size: 1em; bottom: 20px; }
414
- .stats-grid { grid-template-columns: repeat(auto-fit, minmax(90px, 1fr)); gap: var(--padding-s); }
415
- .stat-value { font-size: 1.5em; }
416
- .modal-content { margin: 25% auto; width: 92%; }
417
- }
418
- </style>
419
- </head>
420
- <body>
421
- <div class="container">
422
-
423
- <section class="morshen-group-intro section-card">
424
- <div class="header">
425
- <div class="logo">
426
- <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Group Logo">
427
- <span>Morshen Group</span>
428
- </div>
429
- <a href="#" class="btn contact-link"><i class="icon icon-contact"></i>Связаться</a>
430
- </div>
431
- <div>
432
- <span class="tag"><i class="icon icon-leader"></i>Лидер инноваций 2025</span>
433
- </div>
434
- <h1 class="section-title">Международный IT холдинг</h1>
435
- <p class="description">
436
- Объединяем передовые технологические компании для создания инновационных
437
- решений мирового уровня. Мы строим будущее технологий сегодня.
438
- </p>
439
- <a href="#" class="btn contact-link" style="background: var(--accent-gradient-green); width: 100%; margin-top: var(--padding-s);">
440
- <i class="icon icon-contact"></i>Написать нам в Telegram
441
- </a>
442
- </section>
443
-
444
- <section class="ecosystem-header">
445
- <h2 class="section-title"><i class="icon icon-company"></i>Экосистема инноваций</h2>
446
- <p class="description">
447
- В состав холдинга входят компании, специализирующиеся на различных
448
- направлениях передовых технологий, создавая синергию для прорывных решений.
449
- </p>
450
- </section>
451
-
452
- <section class="section-card">
453
- <div class="logo" style="margin-bottom: var(--padding-m);">
454
- <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Alpha Logo">
455
- <span style="font-size: 1.4em; font-weight: 600;">Morshen Alpha</span>
456
- </div>
457
- <div style="margin-bottom: var(--padding-m);">
458
- <span class="tag"><i class="icon icon-ai"></i>Искусственный интеллект</span>
459
- <span class="tag"><i class="icon icon-quantum"></i>Квантовые технологии</span>
460
- <span class="tag"><i class="icon icon-business"></i>Бизнес-решения</span>
461
- </div>
462
- <p class="description">
463
- Флагманская компания холдинга. Разрабатываем передовые бизнес-решения, проводим R&D в сфере AI
464
- и квантовых технологий. Наши инновации формируют будущее индустрии.
465
- </p>
466
- <div class="stats-grid">
467
- <div class="stat-item">
468
- <span class="stat-value"><i class="icon icon-global"></i> 3+</span>
469
- <span class="stat-label">Страны присутствия</span>
470
- </div>
471
- <div class="stat-item">
472
- <span class="stat-value"><i class="icon icon-clients"></i> 3K+</span>
473
- <span class="stat-label">Готовых клиентов</span>
474
- </div>
475
- <div class="stat-item">
476
- <span class="stat-value"><i class="icon icon-market"></i> 5+</span>
477
- <span class="stat-label">Лет на рынке</span>
478
- </div>
479
- </div>
480
- </section>
481
-
482
- <section class="section-card">
483
- <div class="logo" style="margin-bottom: var(--padding-m);">
484
- <img src="https://huggingface.co/spaces/holmgardstudio/dev/resolve/main/image.jpg" alt="Holmgard Logo" style="width: 50px; height: 50px;">
485
- <span style="font-size: 1.4em; font-weight: 600;">Holmgard Studio</span>
486
- </div>
487
- <div style="margin-bottom: var(--padding-m);">
488
- <span class="tag"><i class="icon icon-web"></i>Веб-разработка</span>
489
- <span class="tag"><i class="icon icon-mobile"></i>Мобильные приложения</span>
490
- <span class="tag"><i class="icon icon-code"></i>ПО на заказ</span>
491
- </div>
492
- <p class="description">
493
- Инновационная студия разработки, создающая высокотехнологичные веб-сайты,
494
- мобильные приложения и ПО для бизнеса любого масштаба.
495
- Используем передовые технологии и гибкие методологии.
496
- </p>
497
- <div class="stats-grid">
498
- <div class="stat-item">
499
- <span class="stat-value"><i class="icon icon-experience"></i> 10+</span>
500
- <span class="stat-label">Лет опыта</span>
501
- </div>
502
- <div class="stat-item">
503
- <span class="stat-value"><i class="icon icon-complexity"></i> PRO</span>
504
- <span class="stat-label">Любая сложность</span>
505
- </div>
506
- <div class="stat-item">
507
- <span class="stat-value"><i class="icon icon-speed"></i> FAST</span>
508
- <span class="stat-label">Высокая скорость</span>
509
- </div>
510
- </div>
511
- <div style="display: flex; gap: var(--padding-s); margin-top: var(--padding-m); flex-wrap: wrap;">
512
- <a href="https://holmgard.ru" target="_blank" class="btn btn-secondary" style="flex-grow: 1;"><i class="icon icon-link"></i>Веб-сайт студии</a>
513
- <a href="#" class="btn contact-link" style="flex-grow: 1;"><i class="icon icon-contact"></i>Связаться</a>
514
- </div>
515
- </section>
516
-
517
- <section class="section-card">
518
- <h2 class="section-title"><i class="icon icon-global"></i>Глобальное присутствие</h2>
519
- <p class="description">Наши инновационные решения и экспертиза доступны в странах Центральной Азии и за ее пределами:</p>
520
- <div>
521
- <div class="list-item"><i class="icon icon-location"></i>Узбекистан</div>
522
- <div class="list-item"><i class="icon icon-location"></i>Казахстан</div>
523
- <div class="list-item"><i class="icon icon-location"></i>Кыргызстан</div>
524
- <div class="list-item"><i class="icon icon-innovation"></i>Расширяем горизонты...</div>
525
- </div>
526
- </section>
527
-
528
- <footer class="footer-greeting">
529
- <p id="greeting">Инициализация...</p>
530
- </footer>
531
-
532
- </div>
533
-
534
- <button class="save-card-button" id="save-card-btn">
535
- <i class="icon icon-save"></i>Сохранить визитку
536
- </button>
537
-
538
- <div id="saveModal" class="modal">
539
- <div class="modal-content">
540
- <span class="modal-close" id="modal-close-btn">×</span>
541
- <p class="modal-text"><b>+996 500 398 754</b></p>
542
- <p class="modal-text">Morshen Group</p>
543
- <p class="modal-text" style="font-size: 1em; color: var(--text-secondary-color);">Международный IT Холдинг</p>
544
- <p class="modal-instruction">Сделайте скриншот экрана, чтобы сохранить контакт.</p>
545
- </div>
546
- </div>
547
-
548
- <script>
549
- const tg = window.Telegram.WebApp;
550
-
551
- function applyTheme(themeParams) {
552
- const root = document.documentElement;
553
- root.style.setProperty('--tg-theme-bg-color', themeParams.bg_color || '#121212');
554
- root.style.setProperty('--tg-theme-text-color', themeParams.text_color || '#ffffff');
555
- root.style.setProperty('--tg-theme-hint-color', themeParams.hint_color || '#aaaaaa');
556
- root.style.setProperty('--tg-theme-link-color', themeParams.link_color || '#62bcf9');
557
- root.style.setProperty('--tg-theme-button-color', themeParams.button_color || '#31a5f5');
558
- root.style.setProperty('--tg-theme-button-text-color', themeParams.button_text_color || '#ffffff');
559
- root.style.setProperty('--tg-theme-secondary-bg-color', themeParams.secondary_bg_color || '#1e1e1e');
560
-
561
- try {
562
- const bgColor = themeParams.bg_color || '#121212';
563
- const r = parseInt(bgColor.slice(1, 3), 16);
564
- const g = parseInt(bgColor.slice(3, 5), 16);
565
- const b = parseInt(bgColor.slice(5, 7), 16);
566
- root.style.setProperty('--tg-theme-bg-color-rgb', `${r}, ${g}, ${b}`);
567
- } catch (e) {
568
- root.style.setProperty('--tg-theme-bg-color-rgb', `18, 18, 18`);
569
- }
570
- }
571
-
572
- function setupTelegram() {
573
- if (!tg || !tg.initData) {
574
- const greetingElement = document.getElementById('greeting');
575
- if(greetingElement) greetingElement.textContent = 'Не удалось связаться с Telegram.';
576
- document.body.style.visibility = 'visible';
577
- return;
578
- }
579
-
580
- tg.ready();
581
- tg.expand();
582
-
583
- applyTheme(tg.themeParams);
584
- tg.onEvent('themeChanged', () => applyTheme(tg.themeParams));
585
-
586
- fetch('/verify', {
587
- method: 'POST',
588
- headers: {
589
- 'Content-Type': 'application/json',
590
- 'Accept': 'application/json'
591
- },
592
- body: JSON.stringify({ initData: tg.initData }),
593
- })
594
- .then(response => {
595
- if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
596
- return response.json();
597
- })
598
- .then(data => {
599
- if (data.status === 'ok' && data.verified) {
600
-
601
- } else {
602
-
603
- }
604
- })
605
- .catch(error => {
606
-
607
- });
608
-
609
- const user = tg.initDataUnsafe?.user;
610
- const greetingElement = document.getElementById('greeting');
611
- if (user) {
612
- const name = user.first_name || user.username || 'Гость';
613
- greetingElement.textContent = `Добро пожаловать, ${name}! 👋`;
614
- } else {
615
- greetingElement.textContent = 'Добро пожаловать!';
616
-
617
- }
618
-
619
- const contactButtons = document.querySelectorAll('.contact-link');
620
- contactButtons.forEach(button => {
621
- button.addEventListener('click', (e) => {
622
- e.preventDefault();
623
- tg.openTelegramLink('https://t.me/morshenkhan');
624
- });
625
- });
626
-
627
- const modal = document.getElementById("saveModal");
628
- const saveCardBtn = document.getElementById("save-card-btn");
629
- const closeBtn = document.getElementById("modal-close-btn");
630
-
631
- if (saveCardBtn && modal && closeBtn) {
632
- saveCardBtn.addEventListener('click', (e) => {
633
- e.preventDefault();
634
- modal.style.display = "block";
635
- if (tg.HapticFeedback) {
636
- tg.HapticFeedback.impactOccurred('light');
637
- }
638
- });
639
-
640
- closeBtn.addEventListener('click', () => {
641
- modal.style.display = "none";
642
- });
643
-
644
- window.addEventListener('click', (event) => {
645
- if (event.target == modal) {
646
- modal.style.display = "none";
647
- }
648
- });
649
- } else {
650
-
651
- }
652
-
653
- document.body.style.visibility = 'visible';
654
- }
655
-
656
- if (window.Telegram && window.Telegram.WebApp) {
657
- setupTelegram();
658
- } else {
659
-
660
- window.addEventListener('load', setupTelegram);
661
- setTimeout(() => {
662
- if (document.body.style.visibility !== 'visible') {
663
- const greetingElement = document.getElementById('greeting');
664
- if(greetingElement) greetingElement.textContent = 'Ошибка загрузки интерфейса Telegram.';
665
- document.body.style.visibility = 'visible';
666
- }
667
- }, 3500);
668
- }
669
-
670
- </script>
671
- </body>
672
- </html>
673
- """
674
-
675
- ADMIN_TEMPLATE = """
676
- <!DOCTYPE html>
677
- <html lang="ru">
678
- <head>
679
- <meta charset="UTF-8">
680
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
681
- <title>Admin - Посетители</title>
682
- <link rel="preconnect" href="https://fonts.googleapis.com">
683
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
684
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
685
- <style>
686
- :root {
687
- --admin-bg: #f8f9fa;
688
- --admin-text: #212529;
689
- --admin-card-bg: #ffffff;
690
- --admin-border: #dee2e6;
691
- --admin-shadow: rgba(0, 0, 0, 0.05);
692
- --admin-primary: #0d6efd;
693
- --admin-secondary: #6c757d;
694
- --admin-success: #198754;
695
- --admin-danger: #dc3545;
696
- --admin-warning: #ffc107;
697
- --border-radius: 12px;
698
- --padding: 1.5rem;
699
- --font-family: 'Inter', sans-serif;
700
- }
701
- body {
702
- font-family: var(--font-family);
703
- background-color: var(--admin-bg);
704
- color: var(--admin-text);
705
- margin: 0;
706
- padding: var(--padding);
707
- line-height: 1.6;
708
- }
709
- .container { max-width: 1140px; margin: 0 auto; }
710
- h1 { text-align: center; color: var(--admin-secondary); margin-bottom: var(--padding); font-weight: 600; }
711
- .user-grid {
712
- display: grid;
713
- grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
714
- gap: var(--padding);
715
- margin-top: var(--padding);
716
- }
717
- .user-card {
718
- background-color: var(--admin-card-bg);
719
- border-radius: var(--border-radius);
720
- padding: var(--padding);
721
- box-shadow: 0 4px 15px var(--admin-shadow);
722
- border: 1px solid var(--admin-border);
723
- display: flex;
724
- flex-direction: column;
725
- align-items: center;
726
- text-align: center;
727
- transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
728
- }
729
- .user-card:hover {
730
- transform: translateY(-5px);
731
- box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
732
- }
733
- .user-card img {
734
- width: 80px; height: 80px;
735
- border-radius: 50%; margin-bottom: 1rem;
736
- object-fit: cover; border: 3px solid var(--admin-border);
737
- background-color: #eee;
738
- }
739
- .user-card .name { font-weight: 600; font-size: 1.2em; margin-bottom: 0.3rem; color: var(--admin-primary); }
740
- .user-card .username { color: var(--admin-secondary); margin-bottom: 0.8rem; font-size: 0.95em; }
741
- .user-card .details { font-size: 0.9em; color: #495057; word-break: break-word; }
742
- .user-card .detail-item { margin-bottom: 0.3rem; }
743
- .user-card .detail-item strong { color: var(--admin-text); }
744
- .user-card .timestamp { font-size: 0.8em; color: var(--admin-secondary); margin-top: 1rem; }
745
- .no-users { text-align: center; color: var(--admin-secondary); margin-top: 2rem; font-size: 1.1em; }
746
- .alert {
747
- background-color: #fff3cd; border-left: 6px solid var(--admin-warning);
748
- margin-bottom: var(--padding); padding: 1rem 1.5rem;
749
- color: #664d03; border-radius: 8px; text-align: center; font-weight: 500;
750
- }
751
- .refresh-btn {
752
- display: block;
753
- margin: 1rem auto;
754
- padding: 10px 20px;
755
- font-size: 1em;
756
- font-weight: 500;
757
- color: #fff;
758
- background-color: var(--admin-primary);
759
- border: none;
760
- border-radius: 8px;
761
- cursor: pointer;
762
- transition: background-color 0.2s ease;
763
- }
764
- .refresh-btn:hover { background-color: #0b5ed7; }
765
-
766
- .admin-controls {
767
- background: var(--admin-card-bg);
768
- padding: var(--padding);
769
- border-radius: var(--border-radius);
770
- box-shadow: 0 4px 15px var(--admin-shadow);
771
- border: 1px solid var(--admin-border);
772
- margin-bottom: var(--padding);
773
- text-align: center;
774
- }
775
- .admin-controls h2 { margin-top: 0; margin-bottom: 1rem; font-weight: 600; color: var(--admin-secondary); }
776
- .admin-controls .btn {
777
- padding: 10px 18px;
778
- font-size: 0.95em;
779
- font-weight: 500;
780
- border: none;
781
- border-radius: 8px;
782
- cursor: pointer;
783
- transition: all 0.2s ease;
784
- margin: 0.5rem;
785
- color: #fff;
786
- }
787
- .admin-controls .btn-backup { background-color: var(--admin-success); }
788
- .admin-controls .btn-backup:hover { background-color: #157347; }
789
- .admin-controls .btn-download { background-color: var(--admin-primary); }
790
- .admin-controls .btn-download:hover { background-color: #0b5ed7; }
791
- .admin-controls .status { font-size: 0.9em; margin-top: 1rem; color: var(--admin-secondary); }
792
- .admin-controls .loader {
793
- border: 4px solid #f3f3f3; border-radius: 50%; border-top: 4px solid var(--admin-primary);
794
- width: 20px; height: 20px; animation: spin 1s linear infinite; display: inline-block; margin-left: 10px; vertical-align: middle;
795
- display: none;
796
- }
797
- @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
798
- </style>
799
- </head>
800
- <body>
801
- <div class="container">
802
- <h1>Посетители Mini App</h1>
803
- <div class="alert">ВНИМАНИЕ: Этот раздел не защищен! Добавьте аутентификацию для реального использования.</div>
804
-
805
- <div class="admin-controls">
806
- <h2>Управление данными</h2>
807
- <button class="btn btn-download" onclick="triggerDownload()">Скачать данные с HF</button>
808
- <button class="btn btn-backup" onclick="triggerUpload()">Загрузить данные на HF</button>
809
- <div class="loader" id="loader"></div>
810
- <div class="status" id="status-message"></div>
811
- </div>
812
-
813
- <button class="refresh-btn" onclick="location.reload()">Обновить список</button>
814
-
815
- {% if users %}
816
- <div class="user-grid">
817
- {% for user in users|sort(attribute='visited_at', reverse=true) %}
818
- <div class="user-card">
819
- <img src="{{ user.photo_url if user.photo_url else 'data:image/svg+xml;charset=UTF-8,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 100 100%27%3e%3crect width=%27100%27 height=%27100%27 fill=%27%23e9ecef%27/%3e%3ctext x=%2750%25%27 y=%2755%25%27 dominant-baseline=%27middle%27 text-anchor=%27middle%27 font-size=%2745%27 font-family=%27sans-serif%27 fill=%27%23adb5bd%27%3e?%3c/text%3e%3c/svg%3e' }}" alt="User Avatar">
820
- <div class="name">{{ user.first_name or '' }} {{ user.last_name or '' }}</div>
821
- {% if user.username %}
822
- <div class="username"><a href="https://t.me/{{ user.username }}" target="_blank" style="color: inherit; text-decoration: none;">@{{ user.username }}</a></div>
823
- {% else %}
824
- <div class="username" style="height: 1.3em;"></div>
825
- {% endif %}
826
- <div class="details">
827
- <div class="detail-item"><strong>ID:</strong> {{ user.id }}</div>
828
- <div class="detail-item"><strong>Язык:</strong> {{ user.language_code or 'N/A' }}</div>
829
- <div class="detail-item"><strong>Premium:</strong> {{ 'Да' if user.is_premium else 'Нет' }}</div>
830
- <div class="detail-item"><strong>Телефон:</strong> {{ user.phone_number or 'Недоступен' }}</div>
831
- </div>
832
- <div class="timestamp">Визит: {{ user.visited_at_str }}</div>
833
- </div>
834
- {% endfor %}
835
- </div>
836
- {% else %}
837
- <p class="no-users">Данных о посетителях пока нет.</p>
838
- {% endif %}
839
- </div>
840
-
841
- <script>
842
- const loader = document.getElementById('loader');
843
- const statusMessage = document.getElementById('status-message');
844
-
845
- async function handleFetch(url, action) {
846
- loader.style.display = 'inline-block';
847
- statusMessage.textContent = `Выполняется ${action}...`;
848
- statusMessage.style.color = 'var(--admin-secondary)';
849
- try {
850
- const response = await fetch(url, { method: 'POST' });
851
- const data = await response.json();
852
- if (response.ok && data.status === 'ok') {
853
- statusMessage.textContent = data.message;
854
- statusMessage.style.color = 'var(--admin-success)';
855
- if (action === 'скачивание') {
856
- setTimeout(() => location.reload(), 1500);
857
- }
858
- } else {
859
- throw new Error(data.message || 'Произошла ошибка');
860
- }
861
- } catch (error) {
862
- statusMessage.textContent = `Ошибка ${action}: ${error.message}`;
863
- statusMessage.style.color = 'var(--admin-danger)';
864
-
865
- } finally {
866
- loader.style.display = 'none';
867
- }
868
- }
869
-
870
- function triggerDownload() {
871
- handleFetch('/admin/download_data', 'скачивание');
872
- }
873
-
874
- function triggerUpload() {
875
- handleFetch('/admin/upload_data', 'загрузка');
876
- }
877
- </script>
878
- </body>
879
- </html>
880
- """
881
-
882
- bot = Bot(token=BOT_TOKEN)
883
- dp = Dispatcher()
884
-
885
- def generate_bot_response(query: str, context: str):
886
- if not GEMINI_API_KEY:
887
- return "Извините, функция ответа с использованием AI временно недоступна."
888
-
889
- lower_query = query.lower()
890
- code_keywords = ["код", "скрипт", "программа", "напиши", "сделай", "код на", "пример кода"]
891
- if any(keyword in lower_query for keyword in code_keywords):
892
- return "Извините, я не могу предоставить вам код. Могу ли я ответить на другие вопросы о Morshen Group или Holmgard Studio?"
893
-
894
- try:
895
- client = genai.Client(api_key=GEMINI_API_KEY)
896
-
897
- prompt = f"""You are a helpful assistant answering questions about the following website content for "Morshen Group" and "Holmgard Studio".
898
- Only use information explicitly provided in the CONTENT below. Do not invent or assume information not present in the content.
899
- If the user asks for code, *you must refuse* and explain that you cannot provide code.
900
- Keep responses concise and directly related to the query and content.
901
-
902
- CONTENT:
903
- {context}
904
-
905
- USER QUERY: {query}
906
-
907
- ASSISTANT RESPONSE:"""
908
-
909
- contents = [
910
- genai_types.Content(
911
- role="user",
912
- parts=[
913
- genai_types.Part.from_text(text=prompt),
914
- ],
915
- ),
916
- ]
917
- generate_content_config = genai_types.GenerateContentConfig(
918
- response_mime_type="text/plain",
919
- temperature=0.1,
920
- max_output_tokens=500
921
- )
922
-
923
- response = client.models.generate_content(
924
- model=GENAI_MODEL,
925
- contents=contents,
926
- config=generate_content_config,
927
- )
928
- return response.text.strip()
929
-
930
- except Exception as e:
931
- return "Извините, произошла ошибка при обработке вашего запроса."
932
-
933
- @dp.message()
934
- async def handle_message(message: types.Message):
935
- logging.info(f"Received message from user {message.from_user.id}: {message.text}")
936
- user_query = message.text
937
- if not user_query:
938
- return
939
-
940
- try:
941
- await message.answer("Думаю...")
942
- logging.info("Sent 'Thinking...' message.")
943
-
944
- context = TEMPLATE
945
-
946
- response_text = generate_bot_response(user_query, context)
947
-
948
- await message.answer(response_text)
949
- logging.info(f"Sent AI response to user {message.from_user.id}")
950
-
951
- except Exception as e:
952
- logging.exception(f"Error handling message from user {message.from_user.id}")
953
- try:
954
- await message.answer("Извините, произошла внутренняя ошибка при обработке вашего сообщения.")
955
- except Exception:
956
- pass
957
-
958
-
959
- def start_bot_polling():
960
- logging.info("Starting bot polling thread (signals disabled)...")
961
- try:
962
- loop = asyncio.new_event_loop()
963
- asyncio.set_event_loop(loop)
964
- loop.run_until_complete(dp.start_polling(bot, handle_signals=False))
965
- logging.info("Bot polling stopped.")
966
- except Exception as e:
967
- logging.exception("Bot polling failed")
968
-
969
- if __name__ == '__main__':
970
- download_data_from_hf()
971
- load_visitor_data()
972
-
973
- if HF_TOKEN_WRITE:
974
- backup_thread = threading.Thread(target=periodic_backup, daemon=True)
975
- backup_thread.start()
976
-
977
- bot_thread = threading.Thread(target=start_bot_polling, daemon=True)
978
- bot_thread.start()
979
-
980
- app.run(host=HOST, port=PORT, debug=False)