zeroone229 commited on
Commit
52661ee
·
verified ·
1 Parent(s): 8b48205

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +26 -0
  2. app.py +308 -0
  3. requirements.txt +6 -0
Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /code
4
+
5
+ ENV PIP_NO_CACHE_DIR=1
6
+
7
+ # Обновляем pip
8
+ RUN pip install --upgrade pip
9
+
10
+ # Копируем список зависимостей
11
+ COPY ./requirements.txt /code/requirements.txt
12
+
13
+ # Сначала принудительно ставим легкий CPU-PyTorch с официального сервера
14
+ RUN pip install torch --index-url https://download.pytorch.org/whl/cpu
15
+
16
+ # Устанавливаем все остальные библиотеки из requirements.txt
17
+ RUN pip install -r /code/requirements.txt
18
+
19
+ # Копируем код нашего бота
20
+ COPY . .
21
+
22
+ # Открываем порт для Hugging Face
23
+ EXPOSE 7860
24
+
25
+ # Запуск бота
26
+ CMD ["python", "app.py"]
app.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import logging
4
+ import asyncio
5
+ import time
6
+ import random
7
+ from flask import Flask, request as flask_request
8
+ from threading import Thread
9
+ from telegram import Update
10
+ from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
11
+ from telegram.request import HTTPXRequest
12
+ from huggingface_hub import InferenceClient
13
+
14
+ # ==========================================
15
+ # НАСТРОЙКА ЛОГИРОВАНИЯ
16
+ # ==========================================
17
+ logging.basicConfig(
18
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
19
+ level=logging.INFO
20
+ )
21
+ logger = logging.getLogger(__name__)
22
+
23
+ flask_app = Flask(__name__)
24
+
25
+ # ==========================================
26
+ # ДАННЫЕ АВТОРИЗАЦИИ
27
+ # ==========================================
28
+ TELEGRAM_TOKEN = "8887560175:AAHb2oMpExWAc0Wz29Mt2x2UFiQBSsD4ASE"
29
+ WEBGET_LOGIN = "2.0"
30
+ CLIENT_ID = "8887560175"
31
+ CLIENT_SECRET = "eZLFPzWUIATbUHWU4Wh7IleniYyWJuk1NUZMPgXnZQveMqQXIPxFCg"
32
+
33
+ CF_PROXY_URL = "https://tg-proxy.artyomanisimov37.workers.dev/bot"
34
+ HF_TOKEN = os.environ.get("HF_TOKEN")
35
+
36
+ # ИСПОЛЬЗУЕМ МАКСИМАЛЬНО СТАБИЛЬНУЮ МОДЕЛЬ ДЛЯ БЕСПЛАТНОГО ТАРИФА
37
+ TEXT_MODEL = "Qwen/Qwen2.5-7B-Instruct"
38
+ IMAGE_MODEL = "black-forest-labs/FLUX.1-schnell"
39
+ VIDEO_MODEL = "multimodalart/stable-video-diffusion"
40
+
41
+ hf_client = InferenceClient(token=HF_TOKEN)
42
+
43
+ # ==========================================
44
+ # АДМИНЫ И ЭМОЦИОНАЛЬНЫЕ СТИКЕРЫ
45
+ # ==========================================
46
+ ADMINS = ["rid3_yt", "googleseervicesaccaunt"]
47
+
48
+ STICKERS = {
49
+ "hello": "CAACAgIAAxkBAAERRMdqEVyVj1Ig9YmpLqCCQoVnNKc8VgACzpkAAnmqiEjco0PFruuGPDsE", # привет / крута / лайк
50
+ "angry": "CAACAgIAAxkBAAERRMxqEWBGRhp2OIHxnsbRli3kmZ0avgACCZQAAiBUiUjyiFhlRlBNjTsE", # злой
51
+ "refuse": "CAACAgIAAxkBAAERRM5qEWBIykgPIzTnZ1QKq_AkuGhy6gAC1Y4AAstiiUgkyKD1My8FRTsE", # отказ / запрет
52
+ "kind_tg": "CAACAgIAAxkBAAERRNBqEWBM29k-iUios6-BjLmxxXHs3gACFaAAAlnkiEhrINIuFU50VDsE", # доброта / телеграм
53
+ "kind_music": "CAACAgIAAxkBAAERRNJqEWBNVXIypsbEHi_eUUoTvGHb-gACKY8AAsIskUi5wKprQ1Y1wjsE", # доброта 2 / спотифай
54
+ "thinking": "CAACAgIAAxkBAAERRNRqEWBPrm8I-okgu3xqQCddSIdzTwACQ6IAAqXpiUgvwZbRu83PYTsE" # думает
55
+ }
56
+
57
+ def analyze_emotion_and_get_sticker(text: str) -> str:
58
+ """Анализирует текст ответа и подбирает стикер"""
59
+ text_lower = text.lower()
60
+
61
+ # 1. Проверка на отказ / запрещенный контент
62
+ if any(word in text_lower for word in ["не могу", "отказываюсь", "запрещено", "ошибка", "не стану", "извини, но"]):
63
+ return STICKERS["refuse"]
64
+
65
+ # 2. Проверка на злость / агрессию (если бот отыгрывает эмоцию)
66
+ if any(word in text_lower for word in ["злой", "бесит", "разозлил", "отстань", "глупо"]):
67
+ return STICKERS["angry"]
68
+
69
+ # 3. Проверка на приветствие и одобрение
70
+ if any(word in text_lower for word in ["привет", "здравствуй", "круто", "отлично", "лайк", "супер", "молодец"]):
71
+ return STICKERS["hello"]
72
+
73
+ # 4. Музыка / Спотифай
74
+ if any(word in text_lower for word in ["спотифай", "музыка", "трек", "песня", "слушать", "плейлист"]):
75
+ return STICKERS["kind_music"]
76
+
77
+ # 5. Доброта / Телеграм / Помощь
78
+ if any(word in text_lower for word in ["пожалуйста", "рад помочь", "телеграм", "обращайся", "добро"]):
79
+ return STICKERS["kind_tg"]
80
+
81
+ # Если ничего не подошло, стикер не отправляем
82
+ return None
83
+
84
+ # ==========================================
85
+ # ПАМЯТЬ БОТА
86
+ # ==========================================
87
+ SYSTEM_PROMPT = (
88
+ "Ты — умный, эрудированный и дружелюбный ИИ-собеседник. "
89
+ "Общаешься просто и естественно. Всегда отвечай на русском языке."
90
+ )
91
+
92
+ chat_memory = {}
93
+ MAX_HISTORY_LENGTH = 6
94
+
95
+ def add_to_memory(chat_id, role, text):
96
+ if chat_id not in chat_memory:
97
+ chat_memory[chat_id] = []
98
+ chat_memory[chat_id].append({"role": role, "content": text})
99
+ if len(chat_memory[chat_id]) > MAX_HISTORY_LENGTH:
100
+ chat_memory[chat_id] = chat_memory[chat_id][-MAX_HISTORY_LENGTH:]
101
+
102
+ def is_admin(update: Update) -> bool:
103
+ if not update.effective_user or not update.effective_user.username:
104
+ return False
105
+ return update.effective_user.username.lower() in ADMINS
106
+
107
+ # ==========================================
108
+ # WEB СЕРВЕР FLASK
109
+ # ==========================================
110
+ @flask_app.route('/')
111
+ def home():
112
+ return f"Бот онлайн. Webget: {WEBGET_LOGIN}"
113
+
114
+ @flask_app.route('/telegram', methods=['POST'])
115
+ def telegram_webhook():
116
+ global main_loop, tg_application
117
+ if tg_application and main_loop:
118
+ try:
119
+ data = flask_request.get_json(force=True)
120
+ update = Update.de_json(data, tg_application.bot)
121
+ asyncio.run_coroutine_threadsafe(tg_application.process_update(update), main_loop)
122
+ except Exception as e:
123
+ logger.error(f"Ошибка вебхука: {e}")
124
+ return "OK", 200
125
+
126
+ # ==========================================
127
+ # ИИ ФУНКЦИИ
128
+ # ==========================================
129
+ def call_llm(user_text, chat_id):
130
+ if not HF_TOKEN:
131
+ return "Ошибка: отсутствует HF_TOKEN."
132
+
133
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
134
+ if chat_id in chat_memory:
135
+ for msg in chat_memory[chat_id]:
136
+ messages.append({"role": msg["role"], "content": msg["content"]})
137
+
138
+ messages.append({"role": "user", "content": user_text})
139
+
140
+ try:
141
+ response = hf_client.chat_completion(
142
+ model=TEXT_MODEL,
143
+ messages=messages,
144
+ max_tokens=800,
145
+ temperature=0.7
146
+ )
147
+ return response.choices[0].message.content
148
+ except Exception as e:
149
+ logger.error(f"Ошибка текстовой модели: {e}")
150
+ return "⚠️ Модель недоступна или перегружена. Подожди пару минут."
151
+
152
+ def generate_photo(prompt):
153
+ try:
154
+ image = hf_client.text_to_image(prompt, model=IMAGE_MODEL)
155
+ img_byte_arr = io.BytesIO()
156
+ image.save(img_byte_arr, format='JPEG')
157
+ return img_byte_arr.getvalue()
158
+ except Exception as e:
159
+ logger.error(f"Ошибка фото: {e}")
160
+ return None
161
+
162
+ def generate_video(prompt):
163
+ try:
164
+ response = hf_client.post(json={"inputs": prompt}, model=VIDEO_MODEL)
165
+ return response if isinstance(response, bytes) else None
166
+ except Exception as e:
167
+ logger.error(f"Ошибка видео: {e}")
168
+ return None
169
+
170
+ # ==========================================
171
+ # ОБРАБОТЧИКИ КОМАНД
172
+ # ==========================================
173
+ async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
174
+ chat_id = update.effective_chat.id
175
+ chat_memory[chat_id] = []
176
+
177
+ welcome = "Привет! Я готов к работе. Напиши мне что-нибудь!"
178
+ await update.message.reply_text(welcome)
179
+ await update.message.reply_sticker(STICKERS["hello"])
180
+
181
+ async def clear_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
182
+ chat_id = update.effective_chat.id
183
+ chat_memory[chat_id] = []
184
+ await update.message.reply_text("🧹 Память диалога очищена.")
185
+
186
+ async def text_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
187
+ if not update.message or not update.message.text:
188
+ return
189
+
190
+ user_text = update.message.text
191
+ chat_id = update.effective_chat.id
192
+
193
+ if user_text.startswith('/'):
194
+ return
195
+
196
+ # Отправляем стикер "думает" перед генерацией
197
+ thinking_msg = await update.message.reply_sticker(STICKERS["thinking"])
198
+ await update.effective_chat.send_action(action="typing")
199
+
200
+ loop = asyncio.get_running_loop()
201
+ ai_response = await loop.run_in_executor(None, call_llm, user_text, chat_id)
202
+
203
+ # Удаляем стикер "думает", так как ответ готов
204
+ try:
205
+ await thinking_msg.delete()
206
+ except Exception:
207
+ pass # Если бот не имеет прав на удаление в группе, просто игнорируем
208
+
209
+ if "⚠️" not in ai_response:
210
+ add_to_memory(chat_id, "user", user_text)
211
+ add_to_memory(chat_id, "assistant", ai_response)
212
+
213
+ # Отправляем текст
214
+ await update.message.reply_text(text=ai_response)
215
+
216
+ # Подбираем и отправляем эмоциональный стикер (если подходит по смыслу)
217
+ matched_sticker = analyze_emotion_and_get_sticker(ai_response)
218
+ if matched_sticker:
219
+ await update.message.reply_sticker(matched_sticker)
220
+
221
+ async def photo_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
222
+ prompt = " ".join(context.args)
223
+ if not prompt:
224
+ return await update.message.reply_text("Пример: `/photo космонавт на луне`")
225
+
226
+ status = await update.message.reply_text("🎨 Рисую...")
227
+ await update.message.reply_chat_action("upload_photo")
228
+
229
+ loop = asyncio.get_running_loop()
230
+ photo_bytes = await loop.run_in_executor(None, generate_photo, prompt)
231
+
232
+ if photo_bytes:
233
+ await status.delete()
234
+ await update.message.reply_photo(photo=photo_bytes, caption=f"Готово: {prompt}")
235
+ else:
236
+ await status.edit_text("❌ Ошибка генерации фото.")
237
+ await update.message.reply_sticker(STICKERS["refuse"])
238
+
239
+ async def video_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
240
+ prompt = " ".join(context.args)
241
+ if not prompt:
242
+ return await update.message.reply_text("Пример: `/video водопад`")
243
+
244
+ status = await update.message.reply_text("🎬 Генерирую видео...")
245
+ await update.message.reply_chat_action("upload_video")
246
+
247
+ loop = asyncio.get_running_loop()
248
+ video_bytes = await loop.run_in_executor(None, generate_video, prompt)
249
+
250
+ if video_bytes:
251
+ await status.delete()
252
+ await update.message.reply_video(video=video_bytes, caption=f"Видео: {prompt}")
253
+ else:
254
+ await status.edit_text("❌ Ошибка генерации видео.")
255
+ await update.message.reply_sticker(STICKERS["refuse"])
256
+
257
+ # ==========================================
258
+ # ЗАПУСК БОТА
259
+ # ==========================================
260
+ tg_application = None
261
+ main_loop = None
262
+
263
+ def background_bot_starter():
264
+ global tg_application, main_loop
265
+ time.sleep(2)
266
+ while True:
267
+ try:
268
+ loop = asyncio.new_event_loop()
269
+ asyncio.set_event_loop(loop)
270
+ main_loop = loop
271
+
272
+ loop.run_until_complete(tg_application.initialize())
273
+ loop.run_until_complete(tg_application.start())
274
+
275
+ SPACE_ID = os.environ.get("SPACE_ID")
276
+ if SPACE_ID:
277
+ user_part, space_part = SPACE_ID.split('/', 1)
278
+ webhook_url = f"https://{user_part}-{space_part.replace('_', '-')}.hf.space/telegram"
279
+ loop.run_until_complete(tg_application.bot.set_webhook(url=webhook_url))
280
+ logger.info(f"🚀 ВЕБХУК: {webhook_url}")
281
+
282
+ loop.run_forever()
283
+ except Exception as err:
284
+ logger.error(f"⚠️ Ошибка: {err}. Рестарт через 10 сек...")
285
+ time.sleep(10)
286
+
287
+ if __name__ == "__main__":
288
+ custom_request = HTTPXRequest(connect_timeout=30.0, read_timeout=30.0)
289
+
290
+ tg_application = (
291
+ Application.builder()
292
+ .token(TELEGRAM_TOKEN)
293
+ .base_url(CF_PROXY_URL)
294
+ .request(custom_request)
295
+ .updater(None)
296
+ .build()
297
+ )
298
+
299
+ tg_application.add_handler(CommandHandler("start", start_command))
300
+ tg_application.add_handler(CommandHandler("clear", clear_command))
301
+ tg_application.add_handler(CommandHandler("photo", photo_command))
302
+ tg_application.add_handler(CommandHandler("video", video_command))
303
+ tg_application.add_handler(MessageHandler(filters.TEXT, text_handler))
304
+
305
+ bot_thread = Thread(target=background_bot_starter, daemon=True)
306
+ bot_thread.start()
307
+
308
+ flask_app.run(host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ flask
2
+ python-telegram-bot --pre
3
+ requests
4
+ httpx
5
+ huggingface_hub
6
+ pillow