Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -11,30 +11,32 @@ import threading
|
|
11 |
# Setup: Load data and models
|
12 |
# --------------------------
|
13 |
|
14 |
-
# Load
|
15 |
df = pd.read_excel("mau_bao_cao.xlsx")
|
16 |
|
17 |
-
# (
|
18 |
conn = duckdb.connect('mau_bao_cao.db')
|
19 |
conn.execute("""\
|
20 |
CREATE TABLE IF NOT EXISTS production_data AS
|
21 |
SELECT * FROM read_xlsx('mau_bao_cao.xlsx');
|
22 |
""")
|
23 |
|
24 |
-
# Load
|
25 |
embedding_model = SentenceTransformer("intfloat/multilingual-e5-large-instruct")
|
26 |
column_names = df.columns.tolist()
|
27 |
column_embeddings = embedding_model.encode(column_names, convert_to_tensor=True)
|
28 |
row_texts = df.apply(lambda row: " | ".join(row.astype(str)), axis=1)
|
29 |
row_embeddings = embedding_model.encode(row_texts.tolist(), convert_to_tensor=True)
|
30 |
|
31 |
-
# Load
|
32 |
-
fc_model = AutoModelForCausalLM.from_pretrained(
|
33 |
-
|
|
|
|
|
|
|
|
|
34 |
|
35 |
-
|
36 |
-
# Helper function: Trích xuất bảng dữ liệu
|
37 |
-
# --------------------------
|
38 |
|
39 |
def extract_table(user_query: str):
|
40 |
"""
|
@@ -64,21 +66,37 @@ def extract_table(user_query: str):
|
|
64 |
return filtered_df, best_column_names, table_text
|
65 |
|
66 |
# --------------------------
|
67 |
-
#
|
68 |
# --------------------------
|
69 |
|
70 |
def generate_response(user_query: str):
|
71 |
"""
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
|
|
77 |
"""
|
78 |
-
#
|
79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
|
81 |
-
#
|
82 |
system_prompt = f"""\
|
83 |
Bạn là một trợ lý báo cáo sản xuất thông minh, chuyên phân tích và tổng hợp dữ liệu một cách rõ ràng, dễ hiểu.
|
84 |
**_Chỉ báo cáo nếu người dùng yêu cầu mà nếu không thì cứ giao tiếp bình thường với họ._**
|
@@ -116,18 +134,20 @@ Ví dụ:
|
|
116 |
Bạn đã sẵn sàng phân tích và đưa ra báo cáo!
|
117 |
"""
|
118 |
|
|
|
119 |
messages = [
|
120 |
{'role': 'system', 'content': system_prompt},
|
121 |
{'role': 'user', 'content': user_query}
|
122 |
]
|
123 |
|
|
|
124 |
response_template = fc_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
125 |
response_inputs = fc_tokenizer(response_template, return_tensors="pt").to(fc_model.device)
|
126 |
|
127 |
-
#
|
128 |
streamer = TextIteratorStreamer(fc_tokenizer, skip_prompt=True, skip_special_tokens=True)
|
129 |
|
130 |
-
#
|
131 |
thread = threading.Thread(
|
132 |
target=lambda: fc_model.generate(
|
133 |
**response_inputs,
|
@@ -139,40 +159,33 @@ Bạn đã sẵn sàng phân tích và đưa ra báo cáo!
|
|
139 |
)
|
140 |
thread.start()
|
141 |
|
|
|
142 |
collected_text = ""
|
143 |
for new_text in streamer:
|
144 |
collected_text += new_text
|
145 |
yield collected_text
|
146 |
|
147 |
# --------------------------
|
148 |
-
#
|
149 |
# --------------------------
|
150 |
|
151 |
def chat_interface(user_message, history):
|
152 |
"""
|
153 |
-
|
154 |
-
-
|
155 |
-
-
|
156 |
-
|
157 |
-
Lịch sử cuộc trò chuyện được duy trì dưới dạng danh sách các cặp [tin nhắn người dùng, phản hồi AI].
|
158 |
-
Hàm trả về 3 giá trị: giá trị cho Textbox (reset), lịch sử chat, và bảng dữ liệu (dạng DataFrame).
|
159 |
"""
|
160 |
-
#
|
161 |
-
filtered_df, _, _ = extract_table(user_message)
|
162 |
-
|
163 |
-
# Thêm một cặp tin nhắn mới với phản hồi AI ban đầu là chuỗi rỗng.
|
164 |
history.append([user_message, ""])
|
165 |
-
# Yield
|
166 |
-
yield "", history
|
167 |
|
168 |
-
# Stream
|
169 |
for partial_response in generate_response(user_message):
|
|
|
170 |
history[-1][1] = partial_response
|
171 |
-
yield "", history
|
172 |
-
|
173 |
-
# --------------------------
|
174 |
-
# Xây dựng giao diện Gradio
|
175 |
-
# --------------------------
|
176 |
|
177 |
with gr.Blocks() as demo:
|
178 |
gr.Markdown("## Giao diện Chat với Streaming và Hiển thị Bảng Dữ liệu")
|
@@ -189,4 +202,5 @@ with gr.Blocks() as demo:
|
|
189 |
txt.submit(chat_interface, inputs=[txt, state], outputs=[txt, chatbot, table_display], queue=True)
|
190 |
send_btn.click(chat_interface, inputs=[txt, state], outputs=[txt, chatbot, table_display], queue=True)
|
191 |
|
|
|
192 |
demo.launch()
|
|
|
11 |
# Setup: Load data and models
|
12 |
# --------------------------
|
13 |
|
14 |
+
# Load Excel data into a pandas DataFrame.
|
15 |
df = pd.read_excel("mau_bao_cao.xlsx")
|
16 |
|
17 |
+
# (Optional) Create a DuckDB table if needed.
|
18 |
conn = duckdb.connect('mau_bao_cao.db')
|
19 |
conn.execute("""\
|
20 |
CREATE TABLE IF NOT EXISTS production_data AS
|
21 |
SELECT * FROM read_xlsx('mau_bao_cao.xlsx');
|
22 |
""")
|
23 |
|
24 |
+
# Load embedding model for computing embeddings.
|
25 |
embedding_model = SentenceTransformer("intfloat/multilingual-e5-large-instruct")
|
26 |
column_names = df.columns.tolist()
|
27 |
column_embeddings = embedding_model.encode(column_names, convert_to_tensor=True)
|
28 |
row_texts = df.apply(lambda row: " | ".join(row.astype(str)), axis=1)
|
29 |
row_embeddings = embedding_model.encode(row_texts.tolist(), convert_to_tensor=True)
|
30 |
|
31 |
+
# Load Qwen model and tokenizer for conversational generation.
|
32 |
+
fc_model = AutoModelForCausalLM.from_pretrained(
|
33 |
+
"Qwen/Qwen2.5-3B-Instruct",
|
34 |
+
torch_dtype=torch.float16, # Sử dụng float16 để tiết kiệm VRAM
|
35 |
+
device_map="cuda", # Ép mô hình chạy trên GPU
|
36 |
+
trust_remote_code=True # Cho phép tải mã nguồn từ repo
|
37 |
+
).cuda() # Chắc chắn mô hình được chuyển lên GPU
|
38 |
|
39 |
+
fc_tokenizer = AutoTokenizer.from_pretrained('Qwen/Qwen2.5-3B-Instruct')
|
|
|
|
|
40 |
|
41 |
def extract_table(user_query: str):
|
42 |
"""
|
|
|
66 |
return filtered_df, best_column_names, table_text
|
67 |
|
68 |
# --------------------------
|
69 |
+
# Define the streaming generation function
|
70 |
# --------------------------
|
71 |
|
72 |
def generate_response(user_query: str):
|
73 |
"""
|
74 |
+
A generator function that:
|
75 |
+
1. Embeds the query.
|
76 |
+
2. Selects top matching columns and rows from the data.
|
77 |
+
3. Prepares a system prompt with the extracted table.
|
78 |
+
4. Uses TextIteratorStreamer to stream the generated response.
|
79 |
+
Yields the partial generated text as it is updated.
|
80 |
"""
|
81 |
+
# 1. Embed the user query.
|
82 |
+
question_embedding = embedding_model.encode(user_query, convert_to_tensor=True)
|
83 |
+
|
84 |
+
# 2. Find best matching columns (top 10).
|
85 |
+
k = 10
|
86 |
+
column_similarities = util.cos_sim(question_embedding, column_embeddings)[0]
|
87 |
+
best_column_indices = torch.topk(column_similarities, k).indices.tolist()
|
88 |
+
best_column_names = [column_names[i] for i in best_column_indices]
|
89 |
+
|
90 |
+
# 3. Select top matching rows (top 10).
|
91 |
+
row_similarities = util.cos_sim(question_embedding, row_embeddings).squeeze(0)
|
92 |
+
m = 10
|
93 |
+
best_row_indices = torch.topk(row_similarities, m).indices.tolist()
|
94 |
+
filtered_df = df.iloc[best_row_indices][best_column_names]
|
95 |
+
|
96 |
+
# 4. Format the filtered data as a table.
|
97 |
+
table_output = tabulate(filtered_df, headers=best_column_names, tablefmt="grid")
|
98 |
|
99 |
+
# 5. Build the system prompt.
|
100 |
system_prompt = f"""\
|
101 |
Bạn là một trợ lý báo cáo sản xuất thông minh, chuyên phân tích và tổng hợp dữ liệu một cách rõ ràng, dễ hiểu.
|
102 |
**_Chỉ báo cáo nếu người dùng yêu cầu mà nếu không thì cứ giao tiếp bình thường với họ._**
|
|
|
134 |
Bạn đã sẵn sàng phân tích và đưa ra báo cáo!
|
135 |
"""
|
136 |
|
137 |
+
# 6. Create the conversation messages.
|
138 |
messages = [
|
139 |
{'role': 'system', 'content': system_prompt},
|
140 |
{'role': 'user', 'content': user_query}
|
141 |
]
|
142 |
|
143 |
+
# 7. Prepare the prompt for the model.
|
144 |
response_template = fc_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
145 |
response_inputs = fc_tokenizer(response_template, return_tensors="pt").to(fc_model.device)
|
146 |
|
147 |
+
# 8. Use TextIteratorStreamer to yield tokens as they are generated.
|
148 |
streamer = TextIteratorStreamer(fc_tokenizer, skip_prompt=True, skip_special_tokens=True)
|
149 |
|
150 |
+
# Start generation in a separate thread so we can yield tokens as they arrive.
|
151 |
thread = threading.Thread(
|
152 |
target=lambda: fc_model.generate(
|
153 |
**response_inputs,
|
|
|
159 |
)
|
160 |
thread.start()
|
161 |
|
162 |
+
# 9. Yield tokens incrementally.
|
163 |
collected_text = ""
|
164 |
for new_text in streamer:
|
165 |
collected_text += new_text
|
166 |
yield collected_text
|
167 |
|
168 |
# --------------------------
|
169 |
+
# Build the Gradio conversation interface
|
170 |
# --------------------------
|
171 |
|
172 |
def chat_interface(user_message, history):
|
173 |
"""
|
174 |
+
A generator function for Gradio that:
|
175 |
+
- Updates the conversation history with the user message.
|
176 |
+
- Streams the model's response token-by-token in real time.
|
177 |
+
The history is maintained as a list of pairs [user_message, bot_response].
|
|
|
|
|
178 |
"""
|
179 |
+
# Create a new conversation entry with user message and an empty bot response.
|
|
|
|
|
|
|
180 |
history.append([user_message, ""])
|
181 |
+
# Yield the initial state.
|
182 |
+
yield "", history
|
183 |
|
184 |
+
# Stream tokens from the generate_response generator.
|
185 |
for partial_response in generate_response(user_message):
|
186 |
+
# Update the latest conversation entry with the partial bot response.
|
187 |
history[-1][1] = partial_response
|
188 |
+
yield "", history
|
|
|
|
|
|
|
|
|
189 |
|
190 |
with gr.Blocks() as demo:
|
191 |
gr.Markdown("## Giao diện Chat với Streaming và Hiển thị Bảng Dữ liệu")
|
|
|
202 |
txt.submit(chat_interface, inputs=[txt, state], outputs=[txt, chatbot, table_display], queue=True)
|
203 |
send_btn.click(chat_interface, inputs=[txt, state], outputs=[txt, chatbot, table_display], queue=True)
|
204 |
|
205 |
+
|
206 |
demo.launch()
|