Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,6 @@ 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
|
|
@@ -11,6 +10,10 @@ from telegram.ext import Application, CommandHandler, MessageHandler, filters, C
|
|
| 11 |
from telegram.request import HTTPXRequest
|
| 12 |
from huggingface_hub import InferenceClient
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
# ==========================================
|
| 15 |
# НАСТРОЙКА ЛОГИРОВАНИЯ
|
| 16 |
# ==========================================
|
|
@@ -33,53 +36,67 @@ CLIENT_SECRET = "eZLFPzWUIATbUHWU4Wh7IleniYyWJuk1NUZMPgXnZQveMqQXIPxFCg"
|
|
| 33 |
CF_PROXY_URL = "https://tg-proxy.artyomanisimov37.workers.dev/bot"
|
| 34 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 35 |
|
| 36 |
-
#
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
IMAGE_MODEL = "zeroone229/for-bot/"
|
| 40 |
-
VIDEO_MODEL = "zeroone229/for-bot/"
|
| 41 |
|
| 42 |
hf_client = InferenceClient(token=HF_TOKEN)
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
# ==========================================
|
| 45 |
# АДМИНЫ И ЭМОЦИОНАЛЬНЫЕ СТИКЕРЫ
|
| 46 |
# ==========================================
|
| 47 |
ADMINS = ["rid3_yt", "googleseervicesaccaunt"]
|
| 48 |
|
| 49 |
STICKERS = {
|
| 50 |
-
"hello": "CAACAgIAAxkBAAERRMdqEVyVj1Ig9YmpLqCCQoVnNKc8VgACzpkAAnmqiEjco0PFruuGPDsE",
|
| 51 |
-
"angry": "CAACAgIAAxkBAAERRMxqEWBGRhp2OIHxnsbRli3kmZ0avgACCZQAAiBUiUjyiFhlRlBNjTsE",
|
| 52 |
-
"refuse": "CAACAgIAAxkBAAERRM5qEWBIykgPIzTnZ1QKq_AkuGhy6gAC1Y4AAstiiUgkyKD1My8FRTsE",
|
| 53 |
-
"kind_tg": "CAACAgIAAxkBAAERRNBqEWBM29k-iUios6-BjLmxxXHs3gACFaAAAlnkiEhrINIuFU50VDsE",
|
| 54 |
-
"kind_music": "CAACAgIAAxkBAAERRNJqEWBNVXIypsbEHi_eUUoTvGHb-gACKY8AAsIskUi5wKprQ1Y1wjsE",
|
| 55 |
-
"thinking": "CAACAgIAAxkBAAERRNRqEWBPrm8I-okgu3xqQCddSIdzTwACQ6IAAqXpiUgvwZbRu83PYTsE"
|
| 56 |
}
|
| 57 |
|
| 58 |
def analyze_emotion_and_get_sticker(text: str) -> str:
|
| 59 |
-
"""Анализирует текст ответа и подбирает стикер"""
|
| 60 |
text_lower = text.lower()
|
| 61 |
-
|
| 62 |
-
# 1. Проверка на отказ / запрещенный контент
|
| 63 |
if any(word in text_lower for word in ["не могу", "отказываюсь", "запрещено", "ошибка", "не стану", "извини, но"]):
|
| 64 |
return STICKERS["refuse"]
|
| 65 |
-
|
| 66 |
-
# 2. Проверка на злость / агрессию (если бот отыгрывает эмоцию)
|
| 67 |
if any(word in text_lower for word in ["злой", "бесит", "разозлил", "отстань", "глупо"]):
|
| 68 |
return STICKERS["angry"]
|
| 69 |
-
|
| 70 |
-
# 3. Проверка на приветствие и одобрение
|
| 71 |
if any(word in text_lower for word in ["привет", "здравствуй", "круто", "отлично", "лайк", "супер", "молодец"]):
|
| 72 |
return STICKERS["hello"]
|
| 73 |
-
|
| 74 |
-
# 4. Музыка / Спотифай
|
| 75 |
if any(word in text_lower for word in ["спотифай", "музыка", "трек", "песня", "слушать", "плейлист"]):
|
| 76 |
return STICKERS["kind_music"]
|
| 77 |
-
|
| 78 |
-
# 5. Доброта / Телеграм / Помощь
|
| 79 |
if any(word in text_lower for word in ["пожалуйста", "рад помочь", "телеграм", "обращайся", "добро"]):
|
| 80 |
return STICKERS["kind_tg"]
|
| 81 |
-
|
| 82 |
-
# Если ничего не подошло, стикер не отправляем
|
| 83 |
return None
|
| 84 |
|
| 85 |
# ==========================================
|
|
@@ -100,11 +117,6 @@ def add_to_memory(chat_id, role, text):
|
|
| 100 |
if len(chat_memory[chat_id]) > MAX_HISTORY_LENGTH:
|
| 101 |
chat_memory[chat_id] = chat_memory[chat_id][-MAX_HISTORY_LENGTH:]
|
| 102 |
|
| 103 |
-
def is_admin(update: Update) -> bool:
|
| 104 |
-
if not update.effective_user or not update.effective_user.username:
|
| 105 |
-
return False
|
| 106 |
-
return update.effective_user.username.lower() in ADMINS
|
| 107 |
-
|
| 108 |
# ==========================================
|
| 109 |
# WEB СЕРВЕР FLASK
|
| 110 |
# ==========================================
|
|
@@ -128,9 +140,10 @@ def telegram_webhook():
|
|
| 128 |
# ИИ ФУНКЦИИ
|
| 129 |
# ==========================================
|
| 130 |
def call_llm(user_text, chat_id):
|
| 131 |
-
if
|
| 132 |
-
return "Ошибка: о
|
| 133 |
|
|
|
|
| 134 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 135 |
if chat_id in chat_memory:
|
| 136 |
for msg in chat_memory[chat_id]:
|
|
@@ -139,16 +152,25 @@ def call_llm(user_text, chat_id):
|
|
| 139 |
messages.append({"role": "user", "content": user_text})
|
| 140 |
|
| 141 |
try:
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
)
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
except Exception as e:
|
| 150 |
-
logger.error(f"Ошибка текст
|
| 151 |
-
return "⚠️
|
| 152 |
|
| 153 |
def generate_photo(prompt):
|
| 154 |
try:
|
|
@@ -174,9 +196,7 @@ def generate_video(prompt):
|
|
| 174 |
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 175 |
chat_id = update.effective_chat.id
|
| 176 |
chat_memory[chat_id] = []
|
| 177 |
-
|
| 178 |
-
welcome = "Привет! Я готов к работе. Напиши мне что-нибудь!"
|
| 179 |
-
await update.message.reply_text(welcome)
|
| 180 |
await update.message.reply_sticker(STICKERS["hello"])
|
| 181 |
|
| 182 |
async def clear_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
@@ -194,27 +214,23 @@ async def text_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
| 194 |
if user_text.startswith('/'):
|
| 195 |
return
|
| 196 |
|
| 197 |
-
# Отправляем стикер "думает" перед генерацией
|
| 198 |
thinking_msg = await update.message.reply_sticker(STICKERS["thinking"])
|
| 199 |
await update.effective_chat.send_action(action="typing")
|
| 200 |
|
| 201 |
loop = asyncio.get_running_loop()
|
| 202 |
ai_response = await loop.run_in_executor(None, call_llm, user_text, chat_id)
|
| 203 |
|
| 204 |
-
# Удаляем стикер "думает", так как ответ готов
|
| 205 |
try:
|
| 206 |
await thinking_msg.delete()
|
| 207 |
except Exception:
|
| 208 |
-
pass
|
| 209 |
|
| 210 |
if "⚠️" not in ai_response:
|
| 211 |
add_to_memory(chat_id, "user", user_text)
|
| 212 |
add_to_memory(chat_id, "assistant", ai_response)
|
| 213 |
|
| 214 |
-
# Отправляем текст
|
| 215 |
await update.message.reply_text(text=ai_response)
|
| 216 |
|
| 217 |
-
# Подбираем и отправляем эмоциональный стикер (если подходит по смыслу)
|
| 218 |
matched_sticker = analyze_emotion_and_get_sticker(ai_response)
|
| 219 |
if matched_sticker:
|
| 220 |
await update.message.reply_sticker(matched_sticker)
|
|
|
|
| 3 |
import logging
|
| 4 |
import asyncio
|
| 5 |
import time
|
|
|
|
| 6 |
from flask import Flask, request as flask_request
|
| 7 |
from threading import Thread
|
| 8 |
from telegram import Update
|
|
|
|
| 10 |
from telegram.request import HTTPXRequest
|
| 11 |
from huggingface_hub import InferenceClient
|
| 12 |
|
| 13 |
+
# Импортируем библиотеки для локального запуска GGUF без llama-cpp
|
| 14 |
+
import torch
|
| 15 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 16 |
+
|
| 17 |
# ==========================================
|
| 18 |
# НАСТРОЙКА ЛОГИРОВАНИЯ
|
| 19 |
# ==========================================
|
|
|
|
| 36 |
CF_PROXY_URL = "https://tg-proxy.artyomanisimov37.workers.dev/bot"
|
| 37 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 38 |
|
| 39 |
+
# Модели для фото и видео из твоего репозитория
|
| 40 |
+
IMAGE_MODEL = "zeroone229/for-bot"
|
| 41 |
+
VIDEO_MODEL = "zeroone229/for-bot"
|
|
|
|
|
|
|
| 42 |
|
| 43 |
hf_client = InferenceClient(token=HF_TOKEN)
|
| 44 |
|
| 45 |
+
# ==========================================
|
| 46 |
+
# ЛОКАЛЬНАЯ ЗАГРУЗКА GGUF ЧЕРЕЗ TRANSFORMERS
|
| 47 |
+
# ==========================================
|
| 48 |
+
REPO_ID = "zeroone229/for-bot"
|
| 49 |
+
FILENAME = "gemma-2-2b-it-IQ3_M.gguf"
|
| 50 |
+
|
| 51 |
+
logger.info("Загружаем GGUF модель через transformers (потребуется время на загрузку и распаковку)...")
|
| 52 |
+
try:
|
| 53 |
+
# Загружаем токенизатор (если его нет в GGUF, берем оригинальный от Gemma)
|
| 54 |
+
try:
|
| 55 |
+
tokenizer = AutoTokenizer.from_pretrained(REPO_ID, gguf_file=FILENAME, token=HF_TOKEN)
|
| 56 |
+
except Exception:
|
| 57 |
+
logger.info("Токенизатор не найден в GGUF, используем стандартный google/gemma-2-2b-it...")
|
| 58 |
+
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it", token=HF_TOKEN)
|
| 59 |
+
|
| 60 |
+
# Загружаем саму GGUF модель в оперативную память (CPU)
|
| 61 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 62 |
+
REPO_ID,
|
| 63 |
+
gguf_file=FILENAME,
|
| 64 |
+
token=HF_TOKEN,
|
| 65 |
+
device_map="cpu",
|
| 66 |
+
torch_dtype=torch.float32 # Бесплатный спейс работает на обычных CPU
|
| 67 |
+
)
|
| 68 |
+
logger.info("✅ GGUF модель успешно загружена в память Space!")
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.error(f"❌ Ошибка при загрузке модели: {e}")
|
| 71 |
+
model = None
|
| 72 |
+
tokenizer = None
|
| 73 |
+
|
| 74 |
# ==========================================
|
| 75 |
# АДМИНЫ И ЭМОЦИОНАЛЬНЫЕ СТИКЕРЫ
|
| 76 |
# ==========================================
|
| 77 |
ADMINS = ["rid3_yt", "googleseervicesaccaunt"]
|
| 78 |
|
| 79 |
STICKERS = {
|
| 80 |
+
"hello": "CAACAgIAAxkBAAERRMdqEVyVj1Ig9YmpLqCCQoVnNKc8VgACzpkAAnmqiEjco0PFruuGPDsE",
|
| 81 |
+
"angry": "CAACAgIAAxkBAAERRMxqEWBGRhp2OIHxnsbRli3kmZ0avgACCZQAAiBUiUjyiFhlRlBNjTsE",
|
| 82 |
+
"refuse": "CAACAgIAAxkBAAERRM5qEWBIykgPIzTnZ1QKq_AkuGhy6gAC1Y4AAstiiUgkyKD1My8FRTsE",
|
| 83 |
+
"kind_tg": "CAACAgIAAxkBAAERRNBqEWBM29k-iUios6-BjLmxxXHs3gACFaAAAlnkiEhrINIuFU50VDsE",
|
| 84 |
+
"kind_music": "CAACAgIAAxkBAAERRNJqEWBNVXIypsbEHi_eUUoTvGHb-gACKY8AAsIskUi5wKprQ1Y1wjsE",
|
| 85 |
+
"thinking": "CAACAgIAAxkBAAERRNRqEWBPrm8I-okgu3xqQCddSIdzTwACQ6IAAqXpiUgvwZbRu83PYTsE"
|
| 86 |
}
|
| 87 |
|
| 88 |
def analyze_emotion_and_get_sticker(text: str) -> str:
|
|
|
|
| 89 |
text_lower = text.lower()
|
|
|
|
|
|
|
| 90 |
if any(word in text_lower for word in ["не могу", "отказываюсь", "запрещено", "ошибка", "не стану", "извини, но"]):
|
| 91 |
return STICKERS["refuse"]
|
|
|
|
|
|
|
| 92 |
if any(word in text_lower for word in ["злой", "бесит", "разозлил", "отстань", "глупо"]):
|
| 93 |
return STICKERS["angry"]
|
|
|
|
|
|
|
| 94 |
if any(word in text_lower for word in ["привет", "здравствуй", "круто", "отлично", "лайк", "супер", "молодец"]):
|
| 95 |
return STICKERS["hello"]
|
|
|
|
|
|
|
| 96 |
if any(word in text_lower for word in ["спотифай", "музыка", "трек", "песня", "слушать", "плейлист"]):
|
| 97 |
return STICKERS["kind_music"]
|
|
|
|
|
|
|
| 98 |
if any(word in text_lower for word in ["пожалуйста", "рад помочь", "телеграм", "обращайся", "добро"]):
|
| 99 |
return STICKERS["kind_tg"]
|
|
|
|
|
|
|
| 100 |
return None
|
| 101 |
|
| 102 |
# ==========================================
|
|
|
|
| 117 |
if len(chat_memory[chat_id]) > MAX_HISTORY_LENGTH:
|
| 118 |
chat_memory[chat_id] = chat_memory[chat_id][-MAX_HISTORY_LENGTH:]
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
# ==========================================
|
| 121 |
# WEB СЕРВЕР FLASK
|
| 122 |
# ==========================================
|
|
|
|
| 140 |
# ИИ ФУНКЦИИ
|
| 141 |
# ==========================================
|
| 142 |
def call_llm(user_text, chat_id):
|
| 143 |
+
if model is None or tokenizer is None:
|
| 144 |
+
return "⚠️ Ошибка: Модель GGUF не загружена. Проверьте логи Space."
|
| 145 |
|
| 146 |
+
# Собираем историю диалога
|
| 147 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 148 |
if chat_id in chat_memory:
|
| 149 |
for msg in chat_memory[chat_id]:
|
|
|
|
| 152 |
messages.append({"role": "user", "content": user_text})
|
| 153 |
|
| 154 |
try:
|
| 155 |
+
# Конвертируем сообщения в формат, понятный модели
|
| 156 |
+
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 157 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 158 |
+
|
| 159 |
+
# Генерируем ответ (этот процесс выполняется на процессоре)
|
| 160 |
+
with torch.no_grad():
|
| 161 |
+
outputs = model.generate(
|
| 162 |
+
**inputs,
|
| 163 |
+
max_new_tokens=600,
|
| 164 |
+
temperature=0.7,
|
| 165 |
+
do_sample=True
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# Вырезаем из ответа промпт, оставляя только текст нейросети
|
| 169 |
+
response_text = tokenizer.decode(outputs[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True)
|
| 170 |
+
return response_text.strip()
|
| 171 |
except Exception as e:
|
| 172 |
+
logger.error(f"Ошибка генерации текста: {e}")
|
| 173 |
+
return "⚠️ Возникла проблема при создании ответа."
|
| 174 |
|
| 175 |
def generate_photo(prompt):
|
| 176 |
try:
|
|
|
|
| 196 |
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 197 |
chat_id = update.effective_chat.id
|
| 198 |
chat_memory[chat_id] = []
|
| 199 |
+
await update.message.reply_text("Привет! Я готов к работе. Напиши мне что-нибудь!")
|
|
|
|
|
|
|
| 200 |
await update.message.reply_sticker(STICKERS["hello"])
|
| 201 |
|
| 202 |
async def clear_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
|
|
| 214 |
if user_text.startswith('/'):
|
| 215 |
return
|
| 216 |
|
|
|
|
| 217 |
thinking_msg = await update.message.reply_sticker(STICKERS["thinking"])
|
| 218 |
await update.effective_chat.send_action(action="typing")
|
| 219 |
|
| 220 |
loop = asyncio.get_running_loop()
|
| 221 |
ai_response = await loop.run_in_executor(None, call_llm, user_text, chat_id)
|
| 222 |
|
|
|
|
| 223 |
try:
|
| 224 |
await thinking_msg.delete()
|
| 225 |
except Exception:
|
| 226 |
+
pass
|
| 227 |
|
| 228 |
if "⚠️" not in ai_response:
|
| 229 |
add_to_memory(chat_id, "user", user_text)
|
| 230 |
add_to_memory(chat_id, "assistant", ai_response)
|
| 231 |
|
|
|
|
| 232 |
await update.message.reply_text(text=ai_response)
|
| 233 |
|
|
|
|
| 234 |
matched_sticker = analyze_emotion_and_get_sticker(ai_response)
|
| 235 |
if matched_sticker:
|
| 236 |
await update.message.reply_sticker(matched_sticker)
|