Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,44 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import pipeline, AutoTokenizer
|
| 4 |
|
| 5 |
+
# Tải mô hình và tokenizer
|
| 6 |
+
# device_map="auto" sẽ tự động sử dụng GPU nếu có
|
| 7 |
+
model_id = "phamhoangf/struct-aware-baseline-qwen3-4b"
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 9 |
+
pipe = pipeline(
|
| 10 |
+
"text-generation",
|
| 11 |
+
model=model_id,
|
| 12 |
+
torch_dtype=torch.bfloat16,
|
| 13 |
+
device_map="auto",
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
def predict(message, history):
|
| 17 |
+
# Xây dựng prompt từ lịch sử trò chuyện theo template của Qwen2
|
| 18 |
+
messages = []
|
| 19 |
+
for user_msg, assistant_msg in history:
|
| 20 |
+
messages.append({"role": "user", "content": user_msg})
|
| 21 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
| 22 |
+
messages.append({"role": "user", "content": message})
|
| 23 |
+
|
| 24 |
+
# Tạo prompt hoàn chỉnh
|
| 25 |
+
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 26 |
|
| 27 |
+
# Tạo văn bản
|
| 28 |
+
outputs = pipe(
|
| 29 |
+
prompt,
|
| 30 |
+
max_new_tokens=256,
|
| 31 |
+
do_sample=True,
|
| 32 |
+
temperature=0.7,
|
| 33 |
+
top_k=50,
|
| 34 |
+
top_p=0.95,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# Trích xuất phần trả lời
|
| 38 |
+
generated_text = outputs[0]["generated_text"]
|
| 39 |
+
# Lấy phần văn bản mới được tạo ra (sau prompt)
|
| 40 |
+
response = generated_text[len(prompt):]
|
| 41 |
+
return response
|
| 42 |
+
|
| 43 |
+
# Tạo giao diện Chat, giao diện này cũng tự động tạo ra một API
|
| 44 |
+
gr.ChatInterface(predict).launch()
|