Vladislav Krasnov commited on
Commit
c1fbe89
·
1 Parent(s): 2aa5988

Update space 6

Browse files
Files changed (1) hide show
  1. app.py +62 -66
app.py CHANGED
@@ -1,84 +1,80 @@
1
  import gradio as gr
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
 
4
 
5
- # Загрузка модели (остается такой же)
 
 
 
 
 
 
 
 
 
 
 
 
6
  model_name = "microsoft/phi-2"
 
7
  tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
8
  if tokenizer.pad_token is None:
9
  tokenizer.pad_token = tokenizer.eos_token
10
 
 
11
  model = AutoModelForCausalLM.from_pretrained(
12
  model_name,
13
  torch_dtype=torch.float32,
14
  device_map="cpu",
15
  trust_remote_code=True
16
  )
 
17
 
18
- def respond(message, history):
19
- """Адаптированная функция для Blocks"""
20
- history = history or []
21
-
22
- # Формируем промпт
23
- prompt = "Ты - ассистент для помощи в программировании. Отвечай кратко и по делу.\n\n"
24
- for human, assistant in history:
25
- prompt += f"Человек: {human}\nАссистент: {assistant}\n"
26
- prompt += f"Человек: {message}\nАссистент:"
27
-
28
- # Генерация
29
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
30
-
31
- with torch.no_grad():
32
- outputs = model.generate(
33
- inputs.input_ids,
34
- max_new_tokens=300,
35
- temperature=0.7,
36
- do_sample=True,
37
- top_p=0.9
38
- )
39
-
40
- response = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
41
-
42
- # Обновляем историю
43
- history.append((message, response))
44
- return history, history, "" # Возвращаем историю и очищаем поле ввода
 
 
 
45
 
46
- # СОЗДАЕМ ИНТЕРФЕЙС ВРУЧНУЮ
47
- with gr.Blocks(title="LiveCoder LLM API", theme=gr.themes.Soft()) as demo:
48
- gr.Markdown("# 🚀 LiveCoder LLM API")
49
- gr.Markdown("Модель Phi-2 для помощи в написании кода")
50
-
51
- chatbot = gr.Chatbot(height=400, label="Диалог")
52
- msg = gr.Textbox(label="Ваш вопрос", placeholder="Введите вопрос по программированию...")
53
- clear = gr.Button("Очистить чат")
54
-
55
- # Состояние (история диалога)
56
- state = gr.State([])
57
-
58
- # Обработчики
59
- def user_message(message, history):
60
- return "", history + [[message, None]]
61
-
62
- def bot_message(history):
63
- message = history[-1][0]
64
- # Вызываем функцию respond
65
- new_history, _, _ = respond(message, history[:-1])
66
- history[-1][1] = new_history[-1][1]
67
- return history
68
-
69
- # Привязка событий
70
- msg.submit(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
71
- bot_message, chatbot, chatbot
72
- )
73
-
74
- clear.click(lambda: None, None, chatbot, queue=False)
75
-
76
- # Выводим информацию о запуске
77
- print("=" * 20)
78
- print(f"Space name: {YOUR_SPACE_NAME}")
79
- print(f"Username: {YOUR_USERNAME}")
80
- print(f"Local URL: http://0.0.0.0:7860")
81
- print(f"Public API endpoint: https://{YOUR_USERNAME}-{YOUR_SPACE_NAME}.hf.space/run/predict")
82
- print("=" * 20)
83
 
84
- demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
 
1
  import gradio as gr
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
4
+ import os
5
 
6
+ # ЗАМЕНИТЕ ЭТИ ЗНАЧЕНИЯ НА СВОИ!
7
+ SPACE_NAME = "livecoder" # Имя вашего Space
8
+ USERNAME = "sarekuwa" # Ваш username на Hugging Face
9
+
10
+ # Выводим endpoint сразу при запуске
11
+ print("=" * 50)
12
+ print(f"Space name: {SPACE_NAME}")
13
+ print(f"Username: {USERNAME}")
14
+ print(f"Local URL: http://0.0.0.0:7860")
15
+ print(f"Public API endpoint: https://{USERNAME}-{SPACE_NAME}.hf.space/run/predict")
16
+ print("=" * 50)
17
+
18
+ # Загрузка модели
19
  model_name = "microsoft/phi-2"
20
+ print("Loading tokenizer...")
21
  tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
22
  if tokenizer.pad_token is None:
23
  tokenizer.pad_token = tokenizer.eos_token
24
 
25
+ print("Loading model...")
26
  model = AutoModelForCausalLM.from_pretrained(
27
  model_name,
28
  torch_dtype=torch.float32,
29
  device_map="cpu",
30
  trust_remote_code=True
31
  )
32
+ print("Model loaded successfully!")
33
 
34
+ def predict(message, history):
35
+ """Обработчик сообщений"""
36
+ try:
37
+ # Формируем промпт
38
+ prompt = ""
39
+ if history:
40
+ for human_msg, ai_msg in history:
41
+ prompt += f"### Human: {human_msg}\n### Assistant: {ai_msg}\n"
42
+ prompt += f"### Human: {message}\n### Assistant:"
43
+
44
+ # Токенизация и генерация
45
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
46
+
47
+ with torch.no_grad():
48
+ outputs = model.generate(
49
+ inputs.input_ids,
50
+ max_new_tokens=256,
51
+ temperature=0.7,
52
+ do_sample=True,
53
+ top_p=0.9,
54
+ pad_token_id=tokenizer.pad_token_id,
55
+ eos_token_id=tokenizer.eos_token_id
56
+ )
57
+
58
+ response = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
59
+ response = response.split("### Human:")[0].strip()
60
+ return response
61
+
62
+ except Exception as e:
63
+ return f"Ошибка: {str(e)}"
64
 
65
+ # Исправляем предупреждение: добавляем type='messages'
66
+ demo = gr.ChatInterface(
67
+ fn=predict,
68
+ title="LiveCoder LLM API",
69
+ description="Модель Phi-2 для помощи в написании кода",
70
+ chatbot=gr.Chatbot(height=400, type='messages'), # ИСПРАВЛЕНО ЗДЕСЬ
71
+ textbox=gr.Textbox(placeholder="Введите вопрос по программированию...", lines=3),
72
+ examples=[
73
+ ["Напиши hello world на C++"],
74
+ ["Объясни принцип ООП"],
75
+ ["Как работает указатель в C++?"]
76
+ ]
77
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
+ if __name__ == "__main__":
80
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)