Spaces:
Sleeping
Sleeping
Upload ai_core.py
Browse files- ai_core.py +49 -34
ai_core.py
CHANGED
|
@@ -1,31 +1,39 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
import logging
|
|
|
|
| 4 |
from typing import Optional
|
| 5 |
-
from huggingface_hub import InferenceClient
|
| 6 |
from PIL import Image
|
| 7 |
-
from transformers import
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 11 |
|
| 12 |
-
# Используем
|
| 13 |
-
MODEL_ID = "Qwen/Qwen2.5-
|
| 14 |
|
| 15 |
class GenesisAI:
|
| 16 |
def __init__(self):
|
| 17 |
-
logging.info(f"Инициализация Genesis AI
|
| 18 |
-
|
| 19 |
-
# Хардкодим токен для стопроцентной работы (исправлено: I -> 1)
|
| 20 |
-
# Если в коде не сработает, попробуем взять из Secrets (HF_TOKEN)
|
| 21 |
-
self.hf_token = os.getenv("HF_TOKEN") or "hf_McPYfqhXAYQfekcob1FFGFbFoBgaUEhQSS"
|
| 22 |
-
self.client = InferenceClient(model=MODEL_ID, token=self.hf_token)
|
| 23 |
-
logging.info(f"Авторизация выполнена (длина токена: {len(self.hf_token)})")
|
| 24 |
-
|
| 25 |
-
# Оставляем локальное зрение (BLIP), оно легкое и работает на CPU быстро
|
| 26 |
self.device = torch.device("cpu")
|
| 27 |
self.dtype = torch.float32
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
self.blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
|
| 30 |
self.blip_model = BlipForQuestionAnswering.from_pretrained(
|
| 31 |
"Salesforce/blip-vqa-base",
|
|
@@ -33,7 +41,7 @@ class GenesisAI:
|
|
| 33 |
).to(self.device)
|
| 34 |
self.blip_model.eval()
|
| 35 |
|
| 36 |
-
logging.info("Genesis AI готов
|
| 37 |
|
| 38 |
def answer_image_question(self, image: Image.Image, question: str) -> str:
|
| 39 |
inputs = self.blip_processor(image, question, return_tensors="pt").to(self.device, dtype=self.dtype)
|
|
@@ -42,27 +50,34 @@ class GenesisAI:
|
|
| 42 |
return self.blip_processor.decode(out[0], skip_special_tokens=True)
|
| 43 |
|
| 44 |
def answer_text_stream(self, question: str):
|
| 45 |
-
"""Мгновенный стриминг через сервера Hugging Face"""
|
| 46 |
messages = [
|
| 47 |
-
{"role": "system", "content": "Ты ИИ-ассистент Genesis. Тебя создал невасилек. Отвечай
|
| 48 |
{"role": "user", "content": question}
|
| 49 |
]
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
def answer_text_question(self, question: str) -> str:
|
| 68 |
result = ""
|
|
|
|
| 1 |
import os
|
| 2 |
+
import torch
|
| 3 |
import logging
|
| 4 |
+
import threading
|
| 5 |
from typing import Optional
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
+
from transformers import (
|
| 8 |
+
AutoModelForCausalLM,
|
| 9 |
+
AutoTokenizer,
|
| 10 |
+
TextIteratorStreamer,
|
| 11 |
+
BlipProcessor,
|
| 12 |
+
BlipForQuestionAnswering
|
| 13 |
+
)
|
| 14 |
|
| 15 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 16 |
|
| 17 |
+
# Используем модель 0.5B — она самая быстрая для работы БЕЗ токенов на бесплатном CPU
|
| 18 |
+
MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 19 |
|
| 20 |
class GenesisAI:
|
| 21 |
def __init__(self):
|
| 22 |
+
logging.info(f"Инициализация Genesis AI локально ({MODEL_ID})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
self.device = torch.device("cpu")
|
| 24 |
self.dtype = torch.float32
|
| 25 |
+
|
| 26 |
+
# Загрузка текстовой модели
|
| 27 |
+
logging.info("Загрузка текста...")
|
| 28 |
+
self.tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 29 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 30 |
+
MODEL_ID,
|
| 31 |
+
torch_dtype=self.dtype,
|
| 32 |
+
device_map="auto"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# Загрузка зрения (BLIP)
|
| 36 |
+
logging.info("Загрузка зрения...")
|
| 37 |
self.blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
|
| 38 |
self.blip_model = BlipForQuestionAnswering.from_pretrained(
|
| 39 |
"Salesforce/blip-vqa-base",
|
|
|
|
| 41 |
).to(self.device)
|
| 42 |
self.blip_model.eval()
|
| 43 |
|
| 44 |
+
logging.info("Genesis AI готов! Работает локально на CPU.")
|
| 45 |
|
| 46 |
def answer_image_question(self, image: Image.Image, question: str) -> str:
|
| 47 |
inputs = self.blip_processor(image, question, return_tensors="pt").to(self.device, dtype=self.dtype)
|
|
|
|
| 50 |
return self.blip_processor.decode(out[0], skip_special_tokens=True)
|
| 51 |
|
| 52 |
def answer_text_stream(self, question: str):
|
|
|
|
| 53 |
messages = [
|
| 54 |
+
{"role": "system", "content": "Ты ИИ-ассистент Genesis. Тебя создал невасилек. Отвечай кратко и понятно."},
|
| 55 |
{"role": "user", "content": question}
|
| 56 |
]
|
| 57 |
|
| 58 |
+
text = self.tokenizer.apply_chat_template(
|
| 59 |
+
messages,
|
| 60 |
+
tokenize=False,
|
| 61 |
+
add_generation_prompt=True
|
| 62 |
+
)
|
| 63 |
+
model_inputs = self.tokenizer([text], return_tensors="pt").to(self.device)
|
| 64 |
+
|
| 65 |
+
streamer = TextIteratorStreamer(self.tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 66 |
+
|
| 67 |
+
generation_kwargs = dict(
|
| 68 |
+
model_inputs,
|
| 69 |
+
streamer=streamer,
|
| 70 |
+
max_new_tokens=128,
|
| 71 |
+
do_sample=True,
|
| 72 |
+
temperature=0.7,
|
| 73 |
+
repetition_penalty=1.2
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
thread = threading.Thread(target=self.model.generate, kwargs=generation_kwargs)
|
| 77 |
+
thread.start()
|
| 78 |
+
|
| 79 |
+
for new_text in streamer:
|
| 80 |
+
yield new_text
|
| 81 |
|
| 82 |
def answer_text_question(self, question: str) -> str:
|
| 83 |
result = ""
|