VisoLearn commited on
Commit
f6ac5ae
·
verified ·
1 Parent(s): 7336213

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -32
app.py CHANGED
@@ -11,10 +11,10 @@ device = "cuda:0" if torch.cuda.is_available() else "cpu"
11
  phi4_model = AutoModelForCausalLM.from_pretrained(phi4_model_path, device_map="auto", torch_dtype="auto")
12
  phi4_tokenizer = AutoTokenizer.from_pretrained(phi4_model_path)
13
 
14
- @spaces.GPU(duration=120)
15
- def generate_response(user_message, max_tokens, temperature, top_k, top_p, repetition_penalty, history_state):
16
  if not user_message.strip():
17
- return history_state, history_state
18
 
19
  model = phi4_model
20
  tokenizer = phi4_tokenizer
@@ -32,12 +32,17 @@ Use LaTeX for any formulas or values (e.g., $\\text{BMI} = \\frac{\\text{weight
32
 
33
  Now, analyze the following case:"""
34
 
 
35
  prompt = f"{start_tag}system{sep_tag}{system_message}{end_tag}"
36
- for message in history_state:
37
- if message["role"] == "user":
38
- prompt += f"{start_tag}user{sep_tag}{message['content']}{end_tag}"
39
- elif message["role"] == "assistant" and message["content"]:
40
- prompt += f"{start_tag}assistant{sep_tag}{message['content']}{end_tag}"
 
 
 
 
41
  prompt += f"{start_tag}user{sep_tag}{user_message}{end_tag}{start_tag}assistant{sep_tag}"
42
 
43
  inputs = tokenizer(prompt, return_tensors="pt").to(device)
@@ -58,19 +63,19 @@ Now, analyze the following case:"""
58
  thread = Thread(target=model.generate, kwargs=generation_kwargs)
59
  thread.start()
60
 
61
- assistant_response = ""
62
- new_history = history_state + [
63
- {"role": "user", "content": user_message},
64
- {"role": "assistant", "content": ""}
65
- ]
66
 
 
 
67
  for new_token in streamer:
68
  cleaned_token = new_token.replace("<|im_start|>", "").replace("<|im_sep|>", "").replace("<|im_end|>", "")
69
  assistant_response += cleaned_token
70
- new_history[-1]["content"] = assistant_response.strip()
71
- yield new_history, new_history
72
-
73
- yield new_history, new_history
 
74
 
75
 
76
  example_messages = {
@@ -120,7 +125,8 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
120
  </script>
121
  """)
122
 
123
- history_state = gr.State([])
 
124
 
125
  with gr.Row():
126
  with gr.Column(scale=1):
@@ -133,7 +139,6 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
133
  repetition_penalty_slider = gr.Slider(1.0, 2.0, value=1.0, label="Repetition Penalty")
134
 
135
  with gr.Column(scale=4):
136
- chatbot = gr.Chatbot(label="Chat", render_markdown=True, show_copy_button=True)
137
  with gr.Row():
138
  user_input = gr.Textbox(label="Describe symptoms or ask a medical question", placeholder="Type your message here...", scale=3)
139
  submit_button = gr.Button("Send", variant="primary", scale=1)
@@ -145,26 +150,19 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
145
  example3 = gr.Button("Abdominal pain")
146
  example4 = gr.Button("BMI calculation")
147
 
148
- # Replace the streaming approach with a standard click event
149
- def process_input(message, max_tokens, temperature, top_k, top_p, repetition_penalty, history):
150
- # Call the generator function and get the final result
151
- generator = generate_response(message, max_tokens, temperature, top_k, top_p, repetition_penalty, history)
152
- result = None
153
- for res in generator:
154
- result = res
155
- return result
156
-
157
  submit_button.click(
158
- fn=process_input,
159
- inputs=[user_input, max_tokens_slider, temperature_slider, top_k_slider, top_p_slider, repetition_penalty_slider, history_state],
160
- outputs=[chatbot, history_state]
 
161
  ).then(
162
  fn=lambda: gr.update(value=""),
163
  inputs=None,
164
  outputs=user_input
165
  )
166
 
167
- clear_button.click(fn=lambda: ([], []), inputs=None, outputs=[chatbot, history_state])
168
 
169
  example1.click(lambda: gr.update(value=example_messages["Headache case"]), None, user_input)
170
  example2.click(lambda: gr.update(value=example_messages["Chest pain"]), None, user_input)
 
11
  phi4_model = AutoModelForCausalLM.from_pretrained(phi4_model_path, device_map="auto", torch_dtype="auto")
12
  phi4_tokenizer = AutoTokenizer.from_pretrained(phi4_model_path)
13
 
14
+ @spaces.GPU(duration=60)
15
+ def generate_response(user_message, max_tokens, temperature, top_k, top_p, repetition_penalty, history):
16
  if not user_message.strip():
17
+ return history, history
18
 
19
  model = phi4_model
20
  tokenizer = phi4_tokenizer
 
32
 
33
  Now, analyze the following case:"""
34
 
35
+ # Build conversation history in the format the model expects
36
  prompt = f"{start_tag}system{sep_tag}{system_message}{end_tag}"
37
+
38
+ # Convert chat history format from the Gradio Chatbot format to prompt format
39
+ for user_msg, bot_msg in history:
40
+ if user_msg:
41
+ prompt += f"{start_tag}user{sep_tag}{user_msg}{end_tag}"
42
+ if bot_msg:
43
+ prompt += f"{start_tag}assistant{sep_tag}{bot_msg}{end_tag}"
44
+
45
+ # Add the current user message
46
  prompt += f"{start_tag}user{sep_tag}{user_message}{end_tag}{start_tag}assistant{sep_tag}"
47
 
48
  inputs = tokenizer(prompt, return_tensors="pt").to(device)
 
63
  thread = Thread(target=model.generate, kwargs=generation_kwargs)
64
  thread.start()
65
 
66
+ # Create a new history with the current user message
67
+ new_history = history.copy() + [[user_message, ""]]
 
 
 
68
 
69
+ # Collect the generated response
70
+ assistant_response = ""
71
  for new_token in streamer:
72
  cleaned_token = new_token.replace("<|im_start|>", "").replace("<|im_sep|>", "").replace("<|im_end|>", "")
73
  assistant_response += cleaned_token
74
+ # Update the last message in history with the current response
75
+ new_history[-1][1] = assistant_response.strip()
76
+
77
+ # Return the updated history
78
+ return new_history, new_history
79
 
80
 
81
  example_messages = {
 
125
  </script>
126
  """)
127
 
128
+ chatbot = gr.Chatbot(label="Chat", render_markdown=True, show_copy_button=True)
129
+ history = gr.State([])
130
 
131
  with gr.Row():
132
  with gr.Column(scale=1):
 
139
  repetition_penalty_slider = gr.Slider(1.0, 2.0, value=1.0, label="Repetition Penalty")
140
 
141
  with gr.Column(scale=4):
 
142
  with gr.Row():
143
  user_input = gr.Textbox(label="Describe symptoms or ask a medical question", placeholder="Type your message here...", scale=3)
144
  submit_button = gr.Button("Send", variant="primary", scale=1)
 
150
  example3 = gr.Button("Abdominal pain")
151
  example4 = gr.Button("BMI calculation")
152
 
153
+ # Use click instead of stream
 
 
 
 
 
 
 
 
154
  submit_button.click(
155
+ fn=generate_response,
156
+ inputs=[user_input, max_tokens_slider, temperature_slider, top_k_slider, top_p_slider,
157
+ repetition_penalty_slider, history],
158
+ outputs=[chatbot, history]
159
  ).then(
160
  fn=lambda: gr.update(value=""),
161
  inputs=None,
162
  outputs=user_input
163
  )
164
 
165
+ clear_button.click(fn=lambda: ([], []), inputs=None, outputs=[chatbot, history])
166
 
167
  example1.click(lambda: gr.update(value=example_messages["Headache case"]), None, user_input)
168
  example2.click(lambda: gr.update(value=example_messages["Chest pain"]), None, user_input)