jason-moore commited on
Commit
b72c9d3
·
1 Parent(s): db1d784

update reqs

Browse files
Files changed (2) hide show
  1. app.py +100 -50
  2. requirements.txt +6 -1
app.py CHANGED
@@ -1,64 +1,114 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("jason-moore/deepseek-soap")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
27
 
28
- response = ""
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ import torch
2
  import gradio as gr
3
+ from peft import PeftModel
4
+ from unsloth import FastLanguageModel
5
 
6
+ # Load the model using Unsloth's method
7
+ def load_model():
8
+ # Base model that was used for fine-tuning
9
+ base_model_id = "unsloth/DeepSeek-R1-Distill-Llama-8B"
10
+
11
+ # Load the base model using Unsloth
12
+ max_seq_length = 2048
13
+ base_model, tokenizer = FastLanguageModel.from_pretrained(
14
+ model_name=base_model_id,
15
+ max_seq_length=max_seq_length,
16
+ dtype=torch.float16,
17
+ load_in_4bit=False, # Avoid 4-bit to reduce complexity for testing
18
+ )
19
+
20
+ # Load the LoRA adapter from HuggingFace
21
+ lora_model_id = "your-username/your-model-repo" # Replace with your HF model path
22
+ model = PeftModel.from_pretrained(base_model, lora_model_id)
23
+
24
+ # Optimize for inference
25
+ FastLanguageModel.for_inference(model)
26
+
27
+ return model, tokenizer
28
 
29
+ # Function to generate SOAP notes
30
+ def generate_soap_note(doctor_patient_conversation):
31
+ if not doctor_patient_conversation.strip():
32
+ return "Please enter a doctor-patient conversation."
33
+
34
+ # Format prompt identical to how it was done during training
35
+ prompt = """Below is an instruction that describes a task, paired with an input that provides further context.
36
+ Write a response that appropriately completes the request. Pay special attention to the format of the response.
37
 
38
+ ### Instruction:
39
+ You are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning.
40
+ Summarize the following medical conversation between Doctor and Patient into a SOAP note with the following structure:
 
 
 
 
 
 
41
 
42
+ SUBJECTIVE: This section focuses on the patient's perspective, including their chief complaint, symptoms, and any relevant personal or medical history.
 
 
 
 
43
 
44
+ OBJECTIVE: This section contains factual, measurable observations and data
45
+ collected during the encounter, such as vital signs, test results, and physical exam findings.
46
+ Only include information actually present in the conversation
47
 
48
+ ASSESSMENT: This section involves the healthcare provider's analysis and
49
+ interpretation of the subjective and objective data, leading to a diagnosis or a proposed problem.
50
 
51
+ PLAN: This section outlines the next steps in the patient's care, including treatment recommendations, follow-up plans, or referrals.
 
 
 
 
 
 
 
52
 
53
+ ### Conversation:
54
+ {}
55
 
56
+ ### Response:
57
+ {}"""
58
+
59
+ # Use the same formatting pattern you used during inference
60
+ formatted_prompt = prompt.format(doctor_patient_conversation, "")
61
+
62
+ # Tokenize using your pattern
63
+ inputs = tokenizer([formatted_prompt], return_tensors="pt").to(model.device)
64
+
65
+ # Generate using the same parameters you used
66
+ outputs = model.generate(
67
+ input_ids=inputs.input_ids,
68
+ attention_mask=inputs.attention_mask,
69
+ max_new_tokens=1200,
70
+ use_cache=True,
71
+ temperature=0.1,
72
+ top_p=0.95,
73
+ )
74
+
75
+ # Decode and extract the response part
76
+ response = tokenizer.batch_decode(outputs)[0]
77
+ soap_note = response.split("### Response:")[1].strip()
78
+
79
+ return soap_note
80
 
81
+ # Load model and tokenizer (this will run once when the app starts)
82
+ model, tokenizer = load_model()
83
+
84
+ # Sample conversation for the example
85
+ sample_conversation = """
86
+ Doctor: Good morning, how are you feeling today?
87
+ Patient: Not so great, doctor. I've had this persistent cough for about two weeks now.
88
+ Doctor: I'm sorry to hear that. Can you tell me more about the cough? Is it dry or are you coughing up anything?
89
+ Patient: It started as a dry cough, but for the past few days I've been coughing up some yellowish phlegm.
90
+ Doctor: Do you have any other symptoms like fever, chills, or shortness of breath?
91
+ Patient: I had a fever of 100.5°F two days ago. I've been feeling more tired than usual, and sometimes it's a bit hard to catch my breath after coughing a lot.
92
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
+ # Create Gradio interface
95
+ demo = gr.Interface(
96
+ fn=generate_soap_note,
97
+ inputs=gr.Textbox(
98
+ lines=15,
99
+ placeholder="Enter doctor-patient conversation here...",
100
+ label="Doctor-Patient Conversation",
101
+ value=sample_conversation
102
+ ),
103
+ outputs=gr.Textbox(
104
+ label="Generated SOAP Note",
105
+ lines=15
106
+ ),
107
+ title="Medical SOAP Note Generator",
108
+ description="Enter a doctor-patient conversation to generate a structured SOAP note using a fine-tuned DeepSeek-R1-Distill-Llama-8B model.",
109
+ examples=[[sample_conversation]],
110
+ allow_flagging="never"
111
+ )
112
 
113
+ # Launch the app
114
+ demo.launch()
requirements.txt CHANGED
@@ -1 +1,6 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
1
+ torch>=2.0.0
2
+ transformers>=4.36.0
3
+ peft>=0.6.0
4
+ gradio>=3.50.0
5
+ accelerate>=0.25.0
6
+ unsloth>=2023.11.28