Huy0502 commited on
Commit
d67b7fe
·
verified ·
1 Parent(s): 36b23b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -144
app.py CHANGED
@@ -1,145 +1,34 @@
1
- import gradio as gr
2
- from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer
3
- import torch
4
-
5
- # Tải hình và tokenizer cục bộ với tối ưu hóa tài nguyên
6
- model_name = "Qwen/Qwen2.5-VL-3B-Instruct"
7
- tokenizer = AutoTokenizer.from_pretrained(model_name)
8
- model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
9
- model_name,
10
- device_map="auto", # Tự động phân bổ GPU/CPU
11
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, # Giảm bộ nhớ với float16 nếu có GPU
12
- low_cpu_mem_usage=True, # Tối ưu hóa tài nguyên CPU
13
- )
14
-
15
- # Hàm xử lý phản hồi của chatbot
16
- def respond(
17
- message,
18
- history: list[dict[str, str]],
19
- system_message,
20
- max_tokens,
21
- temperature,
22
- top_p,
23
- ):
24
- # Định dạng messages cho hình
25
- messages = [{"role": "system", "content": system_message}]
26
- messages.extend(history)
27
- messages.append({"role": "user", "content": message})
28
-
29
- # Chuyển messages thành chuỗi đầu vào
30
- input_text = ""
31
- for msg in messages:
32
- role = "System" if msg["role"] == "system" else "User"
33
- input_text += f"{role}: {msg['content']}\n"
34
-
35
- # Tokenize và tạo phản hồi
36
- inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
37
- outputs = model.generate(
38
- **inputs,
39
- max_new_tokens=max_tokens,
40
- temperature=temperature,
41
- top_p=top_p,
42
- do_sample=True,
43
- )
44
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
45
-
46
- # Trả về phản hồi dần dần (giả lập stream)
47
- words = response.split()
48
- full_response = ""
49
- for i in range(0, len(words), 5): # Trả về từng nhóm 5 từ để giả lập stream
50
- full_response += " ".join(words[i:i+5]) + " "
51
- yield full_response.strip()
52
-
53
- # Hàm trung gian để xử lý đúng số tham số
54
- def handle_submit(message, chatbot, system_message, max_tokens, temperature, top_p):
55
- return respond(message, chatbot, system_message, max_tokens, temperature, top_p)
56
-
57
- # Định nghĩa theme cho giao diện
58
- theme = gr.themes.Soft(
59
- primary_hue="blue",
60
- secondary_hue="gray",
61
- neutral_hue="slate",
62
- ).set(
63
- body_background_fill="*neutral_50",
64
- panel_background_fill="*neutral_100",
65
- button_primary_background_fill="*primary_500",
66
- button_primary_text_color="white",
67
- )
68
-
69
- # CSS tùy chỉnh để cải thiện giao diện
70
- custom_css = """
71
- #chatbot-container {
72
- height: 80vh;
73
- border-radius: 10px;
74
- overflow-y: auto;
75
- }
76
- #sidebar {
77
- background-color: #f8fafc;
78
- padding: 20px;
79
- border-right: 1px solid #e2e8f0;
80
- }
81
- #input-section {
82
- padding: 10px;
83
- background-color: #ffffff;
84
- border-top: 1px solid #e2e8f0;
85
- }
86
- """
87
-
88
- # Tạo giao diện với Gradio Blocks
89
- with gr.Blocks(theme=theme, css=custom_css, title="Research Assistant Chatbot") as demo:
90
- with gr.Row():
91
- # Sidebar cho các thông số điều chỉnh
92
- with gr.Column(scale=1, min_width=300, elem_id="sidebar"):
93
- gr.Markdown("## Cài đặt Chatbot")
94
- system_message = gr.Textbox(
95
- value="""Bạn là một trợ lý nghiên cứu viên, có thể hỗ trợ các nhà nghiên cứu viết các bài báo khoa học chính xác, hoàn thiện. Bạn sẽ viết nội dung "Tổng quan" - Abstract - cho bài báo dựa trên các ý chính trong bài nghiên cứu được cung cấp. Nội dung được viết trong khoảng 8 đến 10 câu, viết thành đoạn và không xuống dòng, đảm bảo thông tin bao phủ gồm thực trạng, chủ đề, phương pháp nghiên cứu, kết quả và điểm mạnh của nghiên cứu. Hãy yêu cầu người dùng cung cấp các ý chính của bài nghiên cứu để bạn có thể viết nội dung Tổng quan đầy đủ và chính xác.""",
96
- label="System Message",
97
- lines=10,
98
- )
99
- max_tokens = gr.Slider(
100
- minimum=1,
101
- maximum=2048,
102
- value=512,
103
- step=1,
104
- label="Max New Tokens",
105
- )
106
- temperature = gr.Slider(
107
- minimum=0.1,
108
- maximum=4.0,
109
- value=0.7,
110
- step=0.1,
111
- label="Temperature",
112
- )
113
- top_p = gr.Slider(
114
- minimum=0.1,
115
- maximum=1.0,
116
- value=0.95,
117
- step=0.05,
118
- label="Top-p (Nucleus Sampling)",
119
- )
120
-
121
- # Khu vực chính cho chatbot
122
- with gr.Column(scale=3):
123
- gr.Markdown("## Trợ lý nghiên cứu khoa học")
124
- chatbot = gr.Chatbot(
125
- type="messages",
126
- elem_id="chatbot-container",
127
- height=600,
128
- )
129
- with gr.Row(elem_id="input-section"):
130
- message = gr.Textbox(
131
- placeholder="Nhập các ý chính của bài nghiên cứu hoặc câu hỏi của bạn...",
132
- show_label=False,
133
- container=False,
134
- )
135
- submit_button = gr.Button("Gửi", variant="primary")
136
-
137
- # Liên kết hàm handle_submit với các inputs
138
- submit_button.click(
139
- fn=handle_submit,
140
- inputs=[message, chatbot, system_message, max_tokens, temperature, top_p],
141
- outputs=chatbot,
142
- )
143
-
144
- if __name__ == "__main__":
145
  demo.launch()
 
1
+ import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+
4
+ def respond( message, history: list[dict[str, str]], system_message, max_tokens, temperature, top_p, hf_token: gr.OAuthToken, ):
5
+ client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
6
+ messages = [{"role": "system", "content": system_message}] messages.extend(history)
7
+ messages.append({"role": "user", "content": message})
8
+ response = ""
9
+
10
+ for message in client.chat_completion( messages, max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p, ):
11
+ choices = message.choices
12
+ token = ""
13
+
14
+ if len(choices) and choices[0].delta.content:
15
+ token = choices[0].delta.content
16
+
17
+ response += token
18
+ yield response
19
+
20
+ chatbot = gr.ChatInterface( respond, type="messages",
21
+ additional_inputs=[ gr.Textbox(value="""Bạn là một trợ lý nghiên cứu viên, có thể hỗ trợ các nhà nghiên cứu viết các bài báo khoa học chính xác, hoàn thiện. \ Bạn sẽ viết nội dung "Tổng quan" - Abstract - cho bài báo dựa trên các ý chính trong bài nghiên cứu được cung cấp. \ Nội dung được viết trong khoảng 8 đến 10 câu, viết thành đoạn và không xuống dòng, đảm bảo thông tin bao phủ gồm thực trạng, chủ đề, phương pháp nghiên cứu, \ kết quả và điểm mạnh của nghiên cứu. Hãy yêu cầu người dùng cung cấp các ý chính của bài nghiên cứu để bạn có thể viết nội dung Tổng quan đầy đủ và chính xác.""", label="System message"),
22
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
23
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
24
+ gr.Slider( minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)", ),
25
+ ],
26
+ )
27
+
28
+ with gr.Blocks() as demo:
29
+ with gr.Sidebar():
30
+ gr.LoginButton()
31
+ chatbot.render()
32
+
33
+ if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  demo.launch()