medikal / app.py
erhanmeydan's picture
Create app.py
686dd8c verified
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()