cody82 commited on
Commit
97e1b0e
·
verified ·
1 Parent(s): 23729ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -23
app.py CHANGED
@@ -2,54 +2,58 @@ import os
2
  import torch
3
  import gradio as gr
4
  from transformers import AutoModelForCausalLM, AutoTokenizer
5
- import spaces
6
 
7
- model_repo = "cody82/innopolis_bot_model"
8
- cache_dir = "/data/model"
 
 
 
9
  os.makedirs(cache_dir, exist_ok=True)
10
 
 
11
  tokenizer = AutoTokenizer.from_pretrained(model_repo, cache_dir=cache_dir)
12
  model = AutoModelForCausalLM.from_pretrained(model_repo, cache_dir=cache_dir)
13
- device = torch.device("cpu")
14
- model.to(device)
15
 
16
- @spaces.GPU
17
  def respond(message, history):
18
  history = history or []
19
 
20
- # Собираем всю историю в строку
21
  full_input = ""
22
- for user_msg, bot_msg in history:
23
- full_input += f"User: {user_msg}\nAssistant: {bot_msg}\n"
 
 
 
24
  full_input += f"User: {message}\nAssistant:"
25
 
26
- # Генерация ответа
27
- inputs = tokenizer(full_input, return_tensors="pt").to(device)
28
  outputs = model.generate(
29
  **inputs,
30
- max_new_tokens=200,
31
  do_sample=True,
32
  temperature=0.7,
33
  top_p=0.95,
34
  pad_token_id=tokenizer.eos_token_id,
35
  )
36
- output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
37
- response = output_text.split("Assistant:")[-1].strip()
38
 
39
- # Возвращаем в виде списка кортежей (user, assistant)
40
- history.append((message, response))
41
- return history
42
 
 
43
 
 
44
  chat = gr.ChatInterface(
45
  fn=respond,
46
- chatbot=gr.Chatbot(label="Innopolis Bot", type="messages"),
47
- title="Innopolis Chatbot",
48
  theme="soft",
49
- examples=[
50
- "Когда был основан университет Иннополис?",
51
- "Какие программы есть в магистратуре?"
52
- ],
53
  )
54
 
55
  if __name__ == "__main__":
 
2
  import torch
3
  import gradio as gr
4
  from transformers import AutoModelForCausalLM, AutoTokenizer
 
5
 
6
+ # Параметры
7
+ model_repo = "cody82/unitrip"
8
+ cache_dir = "/data/model" # Persistent storage путь на HF Spaces
9
+
10
+ # Создаём каталог, если не существует
11
  os.makedirs(cache_dir, exist_ok=True)
12
 
13
+ # Загрузка модели и токенизатора
14
  tokenizer = AutoTokenizer.from_pretrained(model_repo, cache_dir=cache_dir)
15
  model = AutoModelForCausalLM.from_pretrained(model_repo, cache_dir=cache_dir)
16
+ model.to("cpu") # Используем CPU, так как у нас ZeroGPU
 
17
 
18
+ @spaces.gpu
19
  def respond(message, history):
20
  history = history or []
21
 
22
+ # Формируем текст истории
23
  full_input = ""
24
+ for turn in history:
25
+ if turn["role"] == "user":
26
+ full_input += f"User: {turn['content']}\n"
27
+ elif turn["role"] == "assistant":
28
+ full_input += f"Assistant: {turn['content']}\n"
29
  full_input += f"User: {message}\nAssistant:"
30
 
31
+ # Токенизация и генерация
32
+ inputs = tokenizer(full_input, return_tensors="pt").to(model.device)
33
  outputs = model.generate(
34
  **inputs,
35
+ max_new_tokens=256,
36
  do_sample=True,
37
  temperature=0.7,
38
  top_p=0.95,
39
  pad_token_id=tokenizer.eos_token_id,
40
  )
41
+ decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
42
+ response = decoded.split("Assistant:")[-1].strip()
43
 
44
+ # Обновление истории
45
+ history.append({"role": "user", "content": message})
46
+ history.append({"role": "assistant", "content": response})
47
 
48
+ return history
49
 
50
+ # Интерфейс
51
  chat = gr.ChatInterface(
52
  fn=respond,
53
+ chatbot=gr.Chatbot(label="Unitrip Assistant", type="messages"),
54
+ title="Unitrip Travel Assistant",
55
  theme="soft",
56
+ examples=["Какие города ты рекомендуешь посетить в Италии?", "Лучшее время для поездки в Японию?"],
 
 
 
57
  )
58
 
59
  if __name__ == "__main__":