NeVasilek commited on
Commit
f9cde06
·
verified ·
1 Parent(s): 8132c10

Upload ai_core.py

Browse files
Files changed (1) hide show
  1. ai_core.py +49 -34
ai_core.py CHANGED
@@ -1,31 +1,39 @@
1
  import os
2
- import io
3
  import logging
 
4
  from typing import Optional
5
- from huggingface_hub import InferenceClient
6
  from PIL import Image
7
- from transformers import BlipProcessor, BlipForQuestionAnswering
8
- import torch
 
 
 
 
 
9
 
10
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
11
 
12
- # Используем самую мощную модель Qwen 72B через API (мгновенно и бесплатно)
13
- MODEL_ID = "Qwen/Qwen2.5-72B-Instruct"
14
 
15
  class GenesisAI:
16
  def __init__(self):
17
- logging.info(f"Инициализация Genesis AI через Serverless API ({MODEL_ID})")
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
- logging.info("Загрузка зрения (BLIP) на CPU...")
 
 
 
 
 
 
 
 
 
 
 
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. Тебя создал невасилек. Отвечай по-доброму, кратко и максимально понятно. Ты работаешь на самой мощной модели Qwen 72B."},
48
  {"role": "user", "content": question}
49
  ]
50
 
51
- try:
52
- # Вызываем API Hugging Face (это происходит на их GPU, поэтому мгновенно)
53
- for message in self.client.chat_completion(
54
- messages=messages,
55
- max_tokens=512,
56
- stream=True,
57
- temperature=0.7,
58
- top_p=0.9
59
- ):
60
- token = message.choices[0].delta.content
61
- if token:
62
- yield token
63
- except Exception as e:
64
- logging.error(f"Ошибка API: {e}")
65
- yield f"Ошибка связи с сервером AI. Проверьте HF_TOKEN в настройках Space. ({str(e)})"
 
 
 
 
 
 
 
 
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 = ""