Ruurd commited on
Commit
0115682
·
1 Parent(s): 5e84c69

Make it into a chatbot

Browse files
Files changed (1) hide show
  1. app.py +40 -23
app.py CHANGED
@@ -4,11 +4,11 @@ import gradio as gr
4
  import spaces
5
  from transformers import AutoTokenizer, AutoModelForCausalLM
6
 
7
-
8
- # Use a global variable to hold the current model and tokenizer
9
  current_model = None
10
  current_tokenizer = None
11
 
 
12
  def load_model_on_selection(model_name, progress=gr.Progress(track_tqdm=False)):
13
  global current_model, current_tokenizer
14
  token = os.getenv("HF_TOKEN")
@@ -27,17 +27,27 @@ def load_model_on_selection(model_name, progress=gr.Progress(track_tqdm=False)):
27
  progress(1, desc="Model ready.")
28
  return f"{model_name} loaded and ready!"
29
 
 
30
  @spaces.GPU
31
- def generate_text(prompt):
32
  global current_model, current_tokenizer
33
  if current_model is None or current_tokenizer is None:
34
- yield "⚠️ No model loaded yet. Please select a model first."
35
 
36
  current_model.to("cuda")
37
- inputs = current_tokenizer(prompt, return_tensors="pt").to(current_model.device)
38
 
 
 
 
 
 
 
 
39
  output_ids = []
40
- streamer_output = ""
 
 
 
41
 
42
  for token_id in current_model.generate(
43
  **inputs,
@@ -45,14 +55,17 @@ def generate_text(prompt):
45
  do_sample=False,
46
  return_dict_in_generate=True,
47
  output_scores=False
48
- ).sequences[0]:
49
-
50
  output_ids.append(token_id.item())
 
 
 
51
 
52
- yield current_tokenizer.decode(output_ids, skip_special_tokens=True)
53
-
 
54
 
55
- # Model options
56
  model_choices = [
57
  "meta-llama/Llama-3.2-3B-Instruct",
58
  "deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
@@ -61,26 +74,30 @@ model_choices = [
61
 
62
  # Gradio UI
63
  with gr.Blocks() as demo:
64
- gr.Markdown("## Clinical Text Testing with LLaMA, DeepSeek, and Gemma")
65
 
66
- # State to track initial model to load
67
  default_model = gr.State("meta-llama/Llama-3.2-3B-Instruct")
68
 
69
- model_selector = gr.Dropdown(choices=model_choices, label="Select Model")
70
- model_status = gr.Textbox(label="Model Status", interactive=False)
 
71
 
72
- input_text = gr.Textbox(label="Input Clinical Text")
73
- generate_btn = gr.Button("Generate")
74
- output_text = gr.Textbox(label="Generated Output")
75
 
76
- # Auto-load default model on launch
77
  demo.load(fn=load_model_on_selection, inputs=default_model, outputs=model_status)
78
 
79
- # Manual model selection
80
  model_selector.change(fn=load_model_on_selection, inputs=model_selector, outputs=model_status)
81
 
82
- # Generate with current model
83
- generate_btn.click(fn=generate_text, inputs=input_text, outputs=output_text)
84
- input_text.submit(fn=generate_text, inputs=input_text, outputs=output_text)
 
 
 
 
85
 
86
  demo.launch()
 
4
  import spaces
5
  from transformers import AutoTokenizer, AutoModelForCausalLM
6
 
7
+ # Global model/tokenizer
 
8
  current_model = None
9
  current_tokenizer = None
10
 
11
+ # Load model when selected
12
  def load_model_on_selection(model_name, progress=gr.Progress(track_tqdm=False)):
13
  global current_model, current_tokenizer
14
  token = os.getenv("HF_TOKEN")
 
27
  progress(1, desc="Model ready.")
28
  return f"{model_name} loaded and ready!"
29
 
30
+ # Inference - yields response token-by-token
31
  @spaces.GPU
32
+ def chat_with_model(history):
33
  global current_model, current_tokenizer
34
  if current_model is None or current_tokenizer is None:
35
+ yield history + [("⚠️ No model loaded.", "")]
36
 
37
  current_model.to("cuda")
 
38
 
39
+ # Combine conversation history into prompt
40
+ prompt = ""
41
+ for user_msg, bot_msg in history:
42
+ prompt += f"[INST] {user_msg.strip()} [/INST] {bot_msg.strip()} "
43
+ prompt += f"[INST] {history[-1][0]} [/INST]"
44
+
45
+ inputs = current_tokenizer(prompt, return_tensors="pt").to(current_model.device)
46
  output_ids = []
47
+
48
+ # Clone history to avoid mutating during yield
49
+ updated_history = history.copy()
50
+ updated_history[-1] = (history[-1][0], "")
51
 
52
  for token_id in current_model.generate(
53
  **inputs,
 
55
  do_sample=False,
56
  return_dict_in_generate=True,
57
  output_scores=False
58
+ ).sequences[0]:
 
59
  output_ids.append(token_id.item())
60
+ decoded = current_tokenizer.decode(output_ids, skip_special_tokens=True)
61
+ updated_history[-1] = (history[-1][0], decoded)
62
+ yield updated_history
63
 
64
+ # When user submits a message
65
+ def add_user_message(message, history):
66
+ return "", history + [(message, "")]
67
 
68
+ # Model choices
69
  model_choices = [
70
  "meta-llama/Llama-3.2-3B-Instruct",
71
  "deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
 
74
 
75
  # Gradio UI
76
  with gr.Blocks() as demo:
77
+ gr.Markdown("## Clinical Chatbot LLaMA, DeepSeek, Gemma")
78
 
 
79
  default_model = gr.State("meta-llama/Llama-3.2-3B-Instruct")
80
 
81
+ with gr.Row():
82
+ model_selector = gr.Dropdown(choices=model_choices, label="Select Model")
83
+ model_status = gr.Textbox(label="Model Status", interactive=False)
84
 
85
+ chatbot = gr.Chatbot(label="Chat")
86
+ msg = gr.Textbox(label="Your Message", placeholder="Enter your clinical query...", show_label=False)
87
+ clear_btn = gr.Button("Clear Chat")
88
 
89
+ # Load model on launch
90
  demo.load(fn=load_model_on_selection, inputs=default_model, outputs=model_status)
91
 
92
+ # Load model on dropdown selection
93
  model_selector.change(fn=load_model_on_selection, inputs=model_selector, outputs=model_status)
94
 
95
+ # On message submit: update history, then stream bot reply
96
+ msg.submit(add_user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
97
+ fn=chat_with_model, inputs=chatbot, outputs=chatbot
98
+ )
99
+
100
+ # Clear chat
101
+ clear_btn.click(lambda: [], None, chatbot, queue=False)
102
 
103
  demo.launch()