erhanmeydan commited on
Commit
686dd8c
·
verified ·
1 Parent(s): c2a5e32

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +221 -0
app.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
4
+ import warnings
5
+ warnings.filterwarnings("ignore")
6
+
7
+ # Model ve tokenizer'ı global olarak tanımla
8
+ model = None
9
+ tokenizer = None
10
+
11
+ def load_model():
12
+ """Modeli yükle"""
13
+ global model, tokenizer
14
+
15
+ model_name = "Intelligent-Internet/II-Medical-8B"
16
+
17
+ try:
18
+ # Tokenizer'ı yükle
19
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
20
+
21
+ # GPU kullanılabilir mi kontrol et
22
+ device = "cuda" if torch.cuda.is_available() else "cpu"
23
+
24
+ if device == "cuda":
25
+ # 4-bit quantization kullanarak modeli yükle (GPU bellek kullanımını azaltmak için)
26
+ quantization_config = BitsAndBytesConfig(
27
+ load_in_4bit=True,
28
+ bnb_4bit_compute_dtype=torch.float16,
29
+ bnb_4bit_use_double_quant=True,
30
+ bnb_4bit_quant_type="nf4"
31
+ )
32
+
33
+ model = AutoModelForCausalLM.from_pretrained(
34
+ model_name,
35
+ quantization_config=quantization_config,
36
+ device_map="auto",
37
+ trust_remote_code=True,
38
+ torch_dtype=torch.float16
39
+ )
40
+ else:
41
+ # CPU için daha hafif yükleme
42
+ model = AutoModelForCausalLM.from_pretrained(
43
+ model_name,
44
+ trust_remote_code=True,
45
+ torch_dtype=torch.float32,
46
+ device_map="cpu"
47
+ )
48
+
49
+ return f"✅ Model başarıyla yüklendi! ({device} üzerinde çalışıyor)"
50
+
51
+ except Exception as e:
52
+ return f"❌ Model yükleme hatası: {str(e)}"
53
+
54
+ def generate_response(message, history, max_tokens=512, temperature=0.7, top_p=0.9):
55
+ """Tıbbi sohbet için yanıt üret"""
56
+ global model, tokenizer
57
+
58
+ if model is None or tokenizer is None:
59
+ return "❌ Model henüz yüklenmedi. Lütfen bekleyin..."
60
+
61
+ try:
62
+ # Sohbet geçmişini formatla
63
+ conversation = ""
64
+ for human, assistant in history:
65
+ conversation += f"Hasta: {human}\nDoktor: {assistant}\n"
66
+
67
+ # Mevcut mesajı ekle
68
+ conversation += f"Hasta: {message}\nDoktor:"
69
+
70
+ # System prompt ekle
71
+ system_prompt = """Sen deneyimli bir tıp doktorusun. Hastalara yardımcı olmak, tıbbi sorularını yanıtlamak ve genel sağlık tavsiyeleri vermek için buradaSın. Her zaman:
72
+ 1. Empati göster ve sabırlı ol
73
+ 2. Karmaşık tıbbi terimleri basit dille açıkla
74
+ 3. Acil durumlar için hemen doktora başvurmasını öner
75
+ 4. Kesin tanı koymak yerine genel bilgiler ver
76
+ 5. Her zaman profesyonel bir doktor muayenesinin önemini vurgula
77
+
78
+ Lütfen yardımcı ve bilgilendirici bir yanıt ver."""
79
+
80
+ full_prompt = f"{system_prompt}\n\n{conversation}"
81
+
82
+ # Tokenize et
83
+ inputs = tokenizer.encode(full_prompt, return_tensors="pt")
84
+
85
+ # Cihaza gönder
86
+ device = next(model.parameters()).device
87
+ inputs = inputs.to(device)
88
+
89
+ # Yanıt üret
90
+ with torch.no_grad():
91
+ outputs = model.generate(
92
+ inputs,
93
+ max_new_tokens=max_tokens,
94
+ temperature=temperature,
95
+ top_p=top_p,
96
+ do_sample=True,
97
+ pad_token_id=tokenizer.eos_token_id,
98
+ repetition_penalty=1.1
99
+ )
100
+
101
+ # Yanıtı decode et
102
+ response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
103
+
104
+ # Yanıtı temizle
105
+ response = response.strip()
106
+ if response.startswith("Doktor:"):
107
+ response = response[7:].strip()
108
+
109
+ return response
110
+
111
+ except Exception as e:
112
+ return f"❌ Yanıt üretme hatası: {str(e)}"
113
+
114
+ def clear_chat():
115
+ """Sohbeti temizle"""
116
+ return [], ""
117
+
118
+ # Model yükleme durumu
119
+ model_status = load_model()
120
+
121
+ # Gradio arayüzü oluştur
122
+ with gr.Blocks(title="🏥 Tıbbi Asistan - II-Medical-8B", theme=gr.themes.Soft()) as demo:
123
+ gr.Markdown("""
124
+ # 🏥 Tıbbi Asistan - II-Medical-8B
125
+
126
+ Bu AI asistan, **II-Medical-8B** modeli kullanılarak geliştirilmiştir. Tıbbi sorularınızı sorabilir ve genel sağlık tavsiyeleri alabilirsiniz.
127
+
128
+ ⚠️ **Önemli Uyarı:** Bu asistan gerçek bir doktor değildir. Verilen bilgiler sadece genel amaçlıdır ve profesyonel tıbbi muayenenin yerini tutmaz.
129
+ """)
130
+
131
+ # Model durumu gösterge
132
+ status_display = gr.Markdown(f"**Model Durumu:** {model_status}")
133
+
134
+ with gr.Row():
135
+ with gr.Column(scale=3):
136
+ chatbot = gr.Chatbot(
137
+ label="🩺 Tıbbi Sohbet",
138
+ height=500,
139
+ show_copy_button=True
140
+ )
141
+
142
+ with gr.Row():
143
+ msg = gr.Textbox(
144
+ placeholder="Tıbbi sorunuzu buraya yazın... (örn: 'Baş ağrım var, ne yapmalıyım?')",
145
+ label="Mesajınız",
146
+ scale=4
147
+ )
148
+ send_btn = gr.Button("📨 Gönder", variant="primary", scale=1)
149
+
150
+ with gr.Row():
151
+ clear_btn = gr.Button("🗑️ Sohbeti Temizle", variant="secondary")
152
+ retry_btn = gr.Button("🔄 Tekrar Dene", variant="secondary")
153
+
154
+ with gr.Column(scale=1):
155
+ gr.Markdown("### ⚙️ Ayarlar")
156
+
157
+ max_tokens = gr.Slider(
158
+ minimum=100,
159
+ maximum=1000,
160
+ value=512,
161
+ step=50,
162
+ label="Maksimum Token Sayısı"
163
+ )
164
+
165
+ temperature = gr.Slider(
166
+ minimum=0.1,
167
+ maximum=1.5,
168
+ value=0.7,
169
+ step=0.1,
170
+ label="Temperature (Yaratıcılık)"
171
+ )
172
+
173
+ top_p = gr.Slider(
174
+ minimum=0.1,
175
+ maximum=1.0,
176
+ value=0.9,
177
+ step=0.05,
178
+ label="Top-p (Odaklanma)"
179
+ )
180
+
181
+ gr.Markdown("""
182
+ ### 📋 Örnek Sorular
183
+ - "Baş ağrım var, ne yapmalıyım?"
184
+ - "Grip belirtileri nelerdir?"
185
+ - "Sağlıklı beslenme için öneriler"
186
+ - "Egzersiz yaparken dikkat edilecekler"
187
+ - "Stres yönetimi teknikleri"
188
+ """)
189
+
190
+ # Event handlers
191
+ def respond(message, history, max_tokens, temperature, top_p):
192
+ if not message.strip():
193
+ return history, ""
194
+
195
+ bot_message = generate_response(message, history, max_tokens, temperature, top_p)
196
+ history.append((message, bot_message))
197
+ return history, ""
198
+
199
+ # Mesaj gönderme
200
+ msg.submit(respond, [msg, chatbot, max_tokens, temperature, top_p], [chatbot, msg])
201
+ send_btn.click(respond, [msg, chatbot, max_tokens, temperature, top_p], [chatbot, msg])
202
+
203
+ # Sohbeti temizle
204
+ clear_btn.click(clear_chat, [], [chatbot, msg])
205
+
206
+ # Tekrar dene
207
+ def retry_last():
208
+ return chatbot.value[:-1] if chatbot.value else [], ""
209
+
210
+ retry_btn.click(retry_last, [], [chatbot, msg])
211
+
212
+ gr.Markdown("""
213
+ ---
214
+ **⚠️ Feragatname:** Bu AI asistan eğitim ve bilgi amaçlıdır. Acil durumlarda 112'yi arayın.
215
+ Herhangi bir sağlık sorunu için mutlaka nitelikli bir sağlık profesyoneline başvurun.
216
+
217
+ **Model:** [II-Medical-8B](https://huggingface.co/Intelligent-Internet/II-Medical-8B) | **Geliştirici:** [Intelligent-Internet](https://huggingface.co/Intelligent-Internet)
218
+ """)
219
+
220
+ if __name__ == "__main__":
221
+ demo.launch()