degide commited on
Commit
b1a4d14
·
verified ·
1 Parent(s): 214a968

Upload requirements.txt and app.py

Browse files
Files changed (2) hide show
  1. app.py +116 -0
  2. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: app.py
3
+ Usage: Hugging Face Spaces Deployment
4
+ Description: Academic submission for Domain-Specific Assistant via LLMs Fine-Tuning.
5
+ """
6
+
7
+ import gradio as gr
8
+ import torch
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer
10
+
11
+ # Hugging Face Hub repository containing the fine-tuned model
12
+ MODEL_REPO = "degide/tinyllama-medical-assistant"
13
+
14
+ print("Downloading and loading the fine-tuned medical chatbot...")
15
+
16
+ # 1. Load the Tokenizer and Model directly from Hugging Face Hub
17
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, trust_remote_code=True)
18
+
19
+ # Configuring the model for efficient CPU loading.
20
+ model = AutoModelForCausalLM.from_pretrained(
21
+ MODEL_REPO,
22
+ device_map="cpu",
23
+ trust_remote_code=True,
24
+ torch_dtype=torch.float32,
25
+ low_cpu_mem_usage=True,
26
+ )
27
+ model.eval()
28
+
29
+ print("Model loaded successfully!")
30
+
31
+ def detect_ood(query):
32
+ """Heuristic-based Out-Of-Domain (OOD) detection."""
33
+ medical_keywords = [
34
+ 'symptom', 'disease', 'treatment', 'medicine', 'doctor', 'health',
35
+ 'diabetes', 'blood', 'pressure', 'heart', 'pain', 'sick', 'hospital',
36
+ 'care', 'diagnosis', 'patient', 'clinic', 'drug', 'therapy', 'cancer',
37
+ 'syndrome', 'infection', 'virus', 'bacteria', 'pill', 'dosage'
38
+ ]
39
+
40
+ query_lower = query.lower()
41
+ has_medical = any(kw in query_lower for kw in medical_keywords)
42
+
43
+ non_medical_patterns = [
44
+ 'cook', 'recipe', 'weather', 'capital', 'python', 'code',
45
+ 'movie', 'song', 'game', 'sports', 'programming', 'math'
46
+ ]
47
+ is_non_medical = any(pattern in query_lower for pattern in non_medical_patterns)
48
+
49
+ return is_non_medical or not has_medical
50
+
51
+ def generate_medical_response(message, history):
52
+ """Generates the chatbot response with OOD handling."""
53
+
54
+ if detect_ood(message):
55
+ return (
56
+ "**Out of Domain Detected:** I apologize, but I am a specialized medical "
57
+ "assistant and can only answer health-related questions. Could you please "
58
+ "ask me about medical symptoms, conditions, or treatments?\n\n"
59
+ "*Examples:*\n"
60
+ "- What are the symptoms of asthma?\n"
61
+ "- How is high blood pressure diagnosed?"
62
+ )
63
+
64
+ prompt = f"<|system|>\nYou are a highly accurate and helpful medical assistant.</s>\n<|user|>\n{message}</s>\n<|assistant|>\n"
65
+ inputs = tokenizer(prompt, return_tensors="pt")
66
+
67
+ with torch.no_grad():
68
+ outputs = model.generate(
69
+ **inputs,
70
+ max_new_tokens=256,
71
+ temperature=0.3,
72
+ top_p=0.85,
73
+ repetition_penalty=1.1,
74
+ do_sample=True,
75
+ eos_token_id=tokenizer.eos_token_id,
76
+ pad_token_id=tokenizer.eos_token_id
77
+ )
78
+
79
+ decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=False)
80
+ final_answer = decoded_output.split("<|assistant|>\n")[-1].replace("</s>", "").strip()
81
+
82
+ disclaimer = (
83
+ "\n\n---\n"
84
+ "**Medical Disclaimer:** *This chatbot provides general health information "
85
+ "only based on fine-tuned data. It is not a replacement for professional "
86
+ "medical advice. Always consult a qualified healthcare provider.*"
87
+ )
88
+
89
+ return final_answer + disclaimer
90
+
91
+ # --- USER INTERFACE ---
92
+ demo = gr.ChatInterface(
93
+ fn=generate_medical_response,
94
+ title="Domain-Specific Medical Assistant (TinyLlama)",
95
+ description=(
96
+ "An LLM fine-tuned via LoRA on the Medical Meadow Flashcards dataset. "
97
+ "Ask questions about medical symptoms, conditions, and treatments."
98
+ ),
99
+ examples=[
100
+ "What are the common symptoms of type 2 diabetes?",
101
+ "Explain the mechanism of action of metformin.",
102
+ "What is the prognosis for patients with stage 3 chronic kidney disease?",
103
+ "Describe the side effects of chemotherapy for breast cancer."
104
+ ],
105
+ chatbot=gr.Chatbot(height=600),
106
+ save_history=True,
107
+ fill_height=True,
108
+ fill_width=True,
109
+ submit_btn="Ask",
110
+ stop_btn="Stop"
111
+ )
112
+
113
+ if __name__ == "__main__":
114
+ demo.launch(
115
+ share=True,
116
+ )
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ datasets
4
+ gradio>=6.6.0
5
+ accelerate
6
+ bitsandbytes
7
+ peft
8
+ trl
9
+ evaluate
10
+ rouge_score