Spaces:
Sleeping

rrtata commited on
Commit
6b4cb7a
·
1 Parent(s): 75ce186

Fix Gradio compatibility

Browse files
Files changed (1) hide show
  1. app.py +16 -102
app.py CHANGED
@@ -4,30 +4,17 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
4
  from peft import PeftModel
5
  import spaces
6
 
7
- # =============================================================================
8
- # ONCOLOGY SYSTEM PROMPT
9
- # =============================================================================
10
-
11
  SYSTEM_PROMPT = """You are OncLLM, a specialized oncology clinical decision support assistant.
12
 
13
  CRITICAL RULES:
14
  1. Provide evidence-based medical information with proper citations when available
15
  2. Use clinical/formal tone appropriate for healthcare professionals
16
- 3. For drug information, include:
17
- - FDA-approved indications
18
- - Standard dosing
19
- - Common adverse effects
20
- - Black box warnings (if any)
21
- - Contraindications
22
  4. Always include this disclaimer: "This information is for clinical decision support only. All treatment decisions must be made by qualified healthcare providers."
23
- 5. When discussing treatment recommendations, mention evidence levels when known (1A, 1B, 2A, 2B, etc.)
24
  6. Be accurate and conservative - if uncertain, say so
25
 
26
- You specialize in: breast cancer, lung cancer (NSCLC/SCLC), colorectal cancer, prostate cancer, melanoma, lymphoma, leukemia, pancreatic cancer, ovarian cancer, kidney cancer, liver cancer, brain tumors, gastric cancer, and multiple myeloma."""
27
-
28
- # =============================================================================
29
- # MODEL LOADING
30
- # =============================================================================
31
 
32
  print("🏥 OncLLM - Loading oncology model...")
33
  print("=" * 50)
@@ -35,7 +22,6 @@ print("=" * 50)
35
  BASE_MODEL = "Qwen/Qwen2.5-14B-Instruct"
36
 
37
  tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, trust_remote_code=True)
38
-
39
  if tokenizer.pad_token is None:
40
  tokenizer.pad_token = tokenizer.eos_token
41
 
@@ -54,118 +40,46 @@ model.eval()
54
  print("✅ OncLLM ready!")
55
  print("=" * 50)
56
 
57
- # =============================================================================
58
- # INFERENCE FUNCTION
59
- # =============================================================================
60
-
61
  @spaces.GPU
62
  def oncology_chat(message, history):
63
- """Generate oncology clinical response."""
64
-
65
- # Build conversation history
66
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
67
 
68
- for human, assistant in history:
69
- messages.append({"role": "user", "content": human})
70
- messages.append({"role": "assistant", "content": assistant})
71
 
72
  messages.append({"role": "user", "content": message})
73
 
74
- # Tokenize
75
- text = tokenizer.apply_chat_template(
76
- messages,
77
- tokenize=False,
78
- add_generation_prompt=True
79
- )
80
-
81
- inputs = tokenizer(
82
- text,
83
- return_tensors="pt",
84
- max_length=4096,
85
- truncation=True
86
- ).to(model.device)
87
 
88
- # Generate response
89
  with torch.no_grad():
90
  outputs = model.generate(
91
  **inputs,
92
  max_new_tokens=1024,
93
- temperature=0.1, # Low temperature for medical accuracy
94
  do_sample=True,
95
  top_p=0.9,
96
  repetition_penalty=1.1,
97
  pad_token_id=tokenizer.eos_token_id
98
  )
99
 
100
- # Decode response
101
- response = tokenizer.decode(
102
- outputs[0][inputs['input_ids'].shape[1]:],
103
- skip_special_tokens=True
104
- )
105
-
106
  return response
107
 
108
- # =============================================================================
109
- # GRADIO INTERFACE
110
- # =============================================================================
111
-
112
  EXAMPLES = [
113
  "What is the first-line treatment for EGFR-mutated NSCLC?",
114
  "What are the black box warnings for pembrolizumab?",
115
  "What is the standard dosing for osimertinib?",
116
  "What are the treatment options for HER2-positive breast cancer?",
117
- "What is the role of immunotherapy in melanoma?",
118
- "What are the common adverse effects of FOLFOX chemotherapy?",
119
- "What clinical trials are available for triple-negative breast cancer?",
120
- "What is the mechanism of action of trastuzumab?",
121
  ]
122
 
123
- CSS = """
124
- .disclaimer {
125
- background-color: #fff3cd;
126
- border: 1px solid #ffc107;
127
- border-radius: 5px;
128
- padding: 10px;
129
- margin: 10px 0;
130
- font-size: 0.9em;
131
- }
132
- """
133
-
134
- with gr.Blocks(css=CSS, title="OncLLM - Oncology Assistant") as demo:
135
- gr.Markdown("""
136
- # 🏥 OncLLM - Oncology Clinical Decision Support
137
-
138
- A fine-tuned **Qwen 2.5 14B** model specialized for oncology clinical decision support.
139
-
140
- <div class="disclaimer">
141
- ⚠️ <strong>Medical Disclaimer:</strong> This tool is for clinical decision support and educational purposes only.
142
- All treatment recommendations must be verified by qualified healthcare providers.
143
- This system does not replace professional medical judgment.
144
- </div>
145
- """)
146
-
147
- chatbot = gr.ChatInterface(
148
- fn=oncology_chat,
149
- examples=EXAMPLES,
150
- title="",
151
- retry_btn="🔄 Retry",
152
- undo_btn="↩️ Undo",
153
- clear_btn="🗑️ Clear",
154
- )
155
-
156
- gr.Markdown("""
157
- ---
158
- ### Supported Topics
159
- - **Treatment Protocols**: First-line, second-line, and salvage therapies
160
- - **Drug Information**: FDA dosing, adverse effects, black box warnings
161
- - **Cancer Types**: Breast, lung, colorectal, prostate, melanoma, lymphoma, leukemia, and more
162
- - **Clinical Trials**: Information about ongoing research
163
-
164
- ### Model Details
165
- - **Base**: Qwen/Qwen2.5-14B-Instruct
166
- - **Fine-tuning**: LoRA (rank=16, alpha=32)
167
- - **Training Data**: 878 oncology Q&A pairs from medical literature
168
- """)
169
 
170
  if __name__ == "__main__":
171
  demo.launch()
 
4
  from peft import PeftModel
5
  import spaces
6
 
 
 
 
 
7
  SYSTEM_PROMPT = """You are OncLLM, a specialized oncology clinical decision support assistant.
8
 
9
  CRITICAL RULES:
10
  1. Provide evidence-based medical information with proper citations when available
11
  2. Use clinical/formal tone appropriate for healthcare professionals
12
+ 3. For drug information, include: FDA-approved indications, standard dosing, common adverse effects, black box warnings, contraindications
 
 
 
 
 
13
  4. Always include this disclaimer: "This information is for clinical decision support only. All treatment decisions must be made by qualified healthcare providers."
14
+ 5. When discussing treatment recommendations, mention evidence levels when known
15
  6. Be accurate and conservative - if uncertain, say so
16
 
17
+ You specialize in: breast cancer, lung cancer, colorectal cancer, prostate cancer, melanoma, lymphoma, leukemia, pancreatic cancer, ovarian cancer, kidney cancer, liver cancer, brain tumors, gastric cancer, and multiple myeloma."""
 
 
 
 
18
 
19
  print("🏥 OncLLM - Loading oncology model...")
20
  print("=" * 50)
 
22
  BASE_MODEL = "Qwen/Qwen2.5-14B-Instruct"
23
 
24
  tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, trust_remote_code=True)
 
25
  if tokenizer.pad_token is None:
26
  tokenizer.pad_token = tokenizer.eos_token
27
 
 
40
  print("✅ OncLLM ready!")
41
  print("=" * 50)
42
 
 
 
 
 
43
  @spaces.GPU
44
  def oncology_chat(message, history):
 
 
 
45
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
46
 
47
+ for msg in history:
48
+ messages.append({"role": msg["role"], "content": msg["content"]})
 
49
 
50
  messages.append({"role": "user", "content": message})
51
 
52
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
53
+ inputs = tokenizer(text, return_tensors="pt", max_length=4096, truncation=True).to(model.device)
 
 
 
 
 
 
 
 
 
 
 
54
 
 
55
  with torch.no_grad():
56
  outputs = model.generate(
57
  **inputs,
58
  max_new_tokens=1024,
59
+ temperature=0.1,
60
  do_sample=True,
61
  top_p=0.9,
62
  repetition_penalty=1.1,
63
  pad_token_id=tokenizer.eos_token_id
64
  )
65
 
66
+ response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
 
 
 
 
 
67
  return response
68
 
 
 
 
 
69
  EXAMPLES = [
70
  "What is the first-line treatment for EGFR-mutated NSCLC?",
71
  "What are the black box warnings for pembrolizumab?",
72
  "What is the standard dosing for osimertinib?",
73
  "What are the treatment options for HER2-positive breast cancer?",
 
 
 
 
74
  ]
75
 
76
+ demo = gr.ChatInterface(
77
+ fn=oncology_chat,
78
+ title="🏥 OncLLM - Oncology Clinical Decision Support",
79
+ description="A fine-tuned **Qwen 2.5 14B** model for oncology.\n\n⚠️ **Disclaimer:** For clinical decision support only.",
80
+ examples=EXAMPLES,
81
+ type="messages"
82
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  if __name__ == "__main__":
85
  demo.launch()