Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,35 +1,60 @@
|
|
1 |
import gradio as gr
|
2 |
-
from ctransformers import AutoModelForCausalLM
|
3 |
import os
|
4 |
|
|
|
5 |
model = None
|
6 |
|
7 |
def load_model():
|
8 |
global model
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
raise
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
def respond(message, history, system_message, max_new_tokens, temperature, top_p):
|
23 |
try:
|
|
|
24 |
if model is None:
|
25 |
-
load_model()
|
26 |
|
27 |
# Формируем контекст из истории
|
28 |
-
context = system_message
|
29 |
for user_msg, assistant_msg in history:
|
30 |
context += f"User: {user_msg}\nAssistant: {assistant_msg}\n"
|
31 |
context += f"User: {message}\nAssistant: "
|
32 |
|
|
|
|
|
33 |
# Генерируем ответ
|
34 |
response = model(
|
35 |
context,
|
@@ -39,10 +64,13 @@ def respond(message, history, system_message, max_new_tokens, temperature, top_p
|
|
39 |
stop=["User:", "\n\n", "<|endoftext|>"]
|
40 |
)
|
41 |
|
|
|
42 |
return response.strip()
|
43 |
|
44 |
except Exception as e:
|
45 |
-
|
|
|
|
|
46 |
|
47 |
# Создаем интерфейс
|
48 |
demo = gr.ChatInterface(
|
@@ -61,7 +89,7 @@ demo = gr.ChatInterface(
|
|
61 |
),
|
62 |
gr.Slider(
|
63 |
minimum=0.1,
|
64 |
-
maximum=
|
65 |
value=0.7,
|
66 |
step=0.1,
|
67 |
label="Temperature"
|
@@ -86,4 +114,12 @@ demo = gr.ChatInterface(
|
|
86 |
|
87 |
# Запускаем приложение
|
88 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
from ctransformers import AutoModelForCausalLM, Config
|
3 |
import os
|
4 |
|
5 |
+
# Глобальная переменная для модели
|
6 |
model = None
|
7 |
|
8 |
def load_model():
|
9 |
global model
|
10 |
+
try:
|
11 |
+
# Выводим текущую директорию и список файлов
|
12 |
+
current_dir = os.getcwd()
|
13 |
+
files = os.listdir(current_dir)
|
14 |
+
print(f"Текущая директория: {current_dir}")
|
15 |
+
print(f"Список файлов: {files}")
|
16 |
+
|
17 |
+
# Проверяем существование файла модели
|
18 |
+
model_path = "Llight.Q8_0.gguf"
|
19 |
+
if not os.path.exists(model_path):
|
20 |
+
raise FileNotFoundError(f"Модель не найдена по пути: {model_path}")
|
21 |
+
|
22 |
+
# Конфигурация модели
|
23 |
+
config = Config(
|
24 |
+
model_path=model_path,
|
25 |
+
model_type="llama",
|
26 |
+
context_length=2048,
|
27 |
+
gpu_layers=0,
|
28 |
+
threads=4
|
29 |
+
)
|
30 |
+
|
31 |
+
# Пробуем загрузить модель с конфигурацией
|
32 |
+
print("Начинаем загрузку модели...")
|
33 |
+
model = AutoModelForCausalLM.from_pretrained(
|
34 |
+
model_path,
|
35 |
+
config=config
|
36 |
+
)
|
37 |
+
print("Модель успешно загружена!")
|
38 |
+
return model
|
39 |
+
|
40 |
+
except Exception as e:
|
41 |
+
print(f"Подробная ошибка при загрузке модели: {str(e)}")
|
42 |
+
raise e
|
43 |
|
44 |
def respond(message, history, system_message, max_new_tokens, temperature, top_p):
|
45 |
try:
|
46 |
+
global model
|
47 |
if model is None:
|
48 |
+
model = load_model()
|
49 |
|
50 |
# Формируем контекст из истории
|
51 |
+
context = f"{system_message}\n\n"
|
52 |
for user_msg, assistant_msg in history:
|
53 |
context += f"User: {user_msg}\nAssistant: {assistant_msg}\n"
|
54 |
context += f"User: {message}\nAssistant: "
|
55 |
|
56 |
+
print(f"Генерируем ответ для контекста длиной {len(context)} символов")
|
57 |
+
|
58 |
# Генерируем ответ
|
59 |
response = model(
|
60 |
context,
|
|
|
64 |
stop=["User:", "\n\n", "<|endoftext|>"]
|
65 |
)
|
66 |
|
67 |
+
print(f"Ответ сгенерирован успешно, длина: {len(response)}")
|
68 |
return response.strip()
|
69 |
|
70 |
except Exception as e:
|
71 |
+
error_msg = f"Произошла ошибка: {str(e)}"
|
72 |
+
print(error_msg)
|
73 |
+
return error_msg
|
74 |
|
75 |
# Создаем интерфейс
|
76 |
demo = gr.ChatInterface(
|
|
|
89 |
),
|
90 |
gr.Slider(
|
91 |
minimum=0.1,
|
92 |
+
maximum=2.0,
|
93 |
value=0.7,
|
94 |
step=0.1,
|
95 |
label="Temperature"
|
|
|
114 |
|
115 |
# Запускаем приложение
|
116 |
if __name__ == "__main__":
|
117 |
+
# Пробуем загрузить модель при запуске
|
118 |
+
try:
|
119 |
+
print("Инициализация приложения...")
|
120 |
+
model = load_model()
|
121 |
+
print("Модель загружена успешно при старте")
|
122 |
+
except Exception as e:
|
123 |
+
print(f"Ошибка при инициализации: {str(e)}")
|
124 |
+
|
125 |
demo.launch()
|