File size: 7,767 Bytes
686dd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
import warnings
warnings.filterwarnings("ignore")

# Model ve tokenizer'ı global olarak tanımla
model = None
tokenizer = None

def load_model():
    """Modeli yükle"""
    global model, tokenizer
    
    model_name = "Intelligent-Internet/II-Medical-8B"
    
    try:
        # Tokenizer'ı yükle
        tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
        
        # GPU kullanılabilir mi kontrol et
        device = "cuda" if torch.cuda.is_available() else "cpu"
        
        if device == "cuda":
            # 4-bit quantization kullanarak modeli yükle (GPU bellek kullanımını azaltmak için)
            quantization_config = BitsAndBytesConfig(
                load_in_4bit=True,
                bnb_4bit_compute_dtype=torch.float16,
                bnb_4bit_use_double_quant=True,
                bnb_4bit_quant_type="nf4"
            )
            
            model = AutoModelForCausalLM.from_pretrained(
                model_name,
                quantization_config=quantization_config,
                device_map="auto",
                trust_remote_code=True,
                torch_dtype=torch.float16
            )
        else:
            # CPU için daha hafif yükleme
            model = AutoModelForCausalLM.from_pretrained(
                model_name,
                trust_remote_code=True,
                torch_dtype=torch.float32,
                device_map="cpu"
            )
        
        return f"✅ Model başarıyla yüklendi! ({device} üzerinde çalışıyor)"
    
    except Exception as e:
        return f"❌ Model yükleme hatası: {str(e)}"

def generate_response(message, history, max_tokens=512, temperature=0.7, top_p=0.9):
    """Tıbbi sohbet için yanıt üret"""
    global model, tokenizer
    
    if model is None or tokenizer is None:
        return "❌ Model henüz yüklenmedi. Lütfen bekleyin..."
    
    try:
        # Sohbet geçmişini formatla
        conversation = ""
        for human, assistant in history:
            conversation += f"Hasta: {human}\nDoktor: {assistant}\n"
        
        # Mevcut mesajı ekle
        conversation += f"Hasta: {message}\nDoktor:"
        
        # System prompt ekle
        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:
1. Empati göster ve sabırlı ol
2. Karmaşık tıbbi terimleri basit dille açıkla
3. Acil durumlar için hemen doktora başvurmasını öner
4. Kesin tanı koymak yerine genel bilgiler ver
5. Her zaman profesyonel bir doktor muayenesinin önemini vurgula

Lütfen yardımcı ve bilgilendirici bir yanıt ver."""
        
        full_prompt = f"{system_prompt}\n\n{conversation}"
        
        # Tokenize et
        inputs = tokenizer.encode(full_prompt, return_tensors="pt")
        
        # Cihaza gönder
        device = next(model.parameters()).device
        inputs = inputs.to(device)
        
        # Yanıt üret
        with torch.no_grad():
            outputs = model.generate(
                inputs,
                max_new_tokens=max_tokens,
                temperature=temperature,
                top_p=top_p,
                do_sample=True,
                pad_token_id=tokenizer.eos_token_id,
                repetition_penalty=1.1
            )
        
        # Yanıtı decode et
        response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
        
        # Yanıtı temizle
        response = response.strip()
        if response.startswith("Doktor:"):
            response = response[7:].strip()
        
        return response
    
    except Exception as e:
        return f"❌ Yanıt üretme hatası: {str(e)}"

def clear_chat():
    """Sohbeti temizle"""
    return [], ""

# Model yükleme durumu
model_status = load_model()

# Gradio arayüzü oluştur
with gr.Blocks(title="🏥 Tıbbi Asistan - II-Medical-8B", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # 🏥 Tıbbi Asistan - II-Medical-8B
    
    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.
    
    ⚠️ **Ö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.
    """)
    
    # Model durumu gösterge
    status_display = gr.Markdown(f"**Model Durumu:** {model_status}")
    
    with gr.Row():
        with gr.Column(scale=3):
            chatbot = gr.Chatbot(
                label="🩺 Tıbbi Sohbet",
                height=500,
                show_copy_button=True
            )
            
            with gr.Row():
                msg = gr.Textbox(
                    placeholder="Tıbbi sorunuzu buraya yazın... (örn: 'Baş ağrım var, ne yapmalıyım?')",
                    label="Mesajınız",
                    scale=4
                )
                send_btn = gr.Button("📨 Gönder", variant="primary", scale=1)
            
            with gr.Row():
                clear_btn = gr.Button("🗑️ Sohbeti Temizle", variant="secondary")
                retry_btn = gr.Button("🔄 Tekrar Dene", variant="secondary")
        
        with gr.Column(scale=1):
            gr.Markdown("### ⚙️ Ayarlar")
            
            max_tokens = gr.Slider(
                minimum=100,
                maximum=1000,
                value=512,
                step=50,
                label="Maksimum Token Sayısı"
            )
            
            temperature = gr.Slider(
                minimum=0.1,
                maximum=1.5,
                value=0.7,
                step=0.1,
                label="Temperature (Yaratıcılık)"
            )
            
            top_p = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.9,
                step=0.05,
                label="Top-p (Odaklanma)"
            )
            
            gr.Markdown("""
            ### 📋 Örnek Sorular
            - "Baş ağrım var, ne yapmalıyım?"
            - "Grip belirtileri nelerdir?"
            - "Sağlıklı beslenme için öneriler"
            - "Egzersiz yaparken dikkat edilecekler"
            - "Stres yönetimi teknikleri"
            """)
    
    # Event handlers
    def respond(message, history, max_tokens, temperature, top_p):
        if not message.strip():
            return history, ""
        
        bot_message = generate_response(message, history, max_tokens, temperature, top_p)
        history.append((message, bot_message))
        return history, ""
    
    # Mesaj gönderme
    msg.submit(respond, [msg, chatbot, max_tokens, temperature, top_p], [chatbot, msg])
    send_btn.click(respond, [msg, chatbot, max_tokens, temperature, top_p], [chatbot, msg])
    
    # Sohbeti temizle
    clear_btn.click(clear_chat, [], [chatbot, msg])
    
    # Tekrar dene
    def retry_last():
        return chatbot.value[:-1] if chatbot.value else [], ""
    
    retry_btn.click(retry_last, [], [chatbot, msg])
    
    gr.Markdown("""
    ---
    **⚠️ Feragatname:** Bu AI asistan eğitim ve bilgi amaçlıdır. Acil durumlarda 112'yi arayın. 
    Herhangi bir sağlık sorunu için mutlaka nitelikli bir sağlık profesyoneline başvurun.
    
    **Model:** [II-Medical-8B](https://huggingface.co/Intelligent-Internet/II-Medical-8B) | **Geliştirici:** [Intelligent-Internet](https://huggingface.co/Intelligent-Internet)
    """)

if __name__ == "__main__":
    demo.launch()