nezahatkorkmaz commited on
Commit
89c4b70
·
verified ·
1 Parent(s): 326098e

Update app.py

Browse files

uyumluluklara göre düzenlendi.

Files changed (1) hide show
  1. app.py +44 -73
app.py CHANGED
@@ -1,96 +1,67 @@
1
  import gradio as gr
2
  import torch
3
  from PIL import Image
4
- from transformers import pipeline
5
- from transformers import CLIPVisionModel, CLIPImageProcessor
6
- from transformers import AutoTokenizer, AutoModelForCausalLM
7
 
8
- # 1. Çeviri modelleri
9
- print("Çeviri modelleri yükleniyor...")
 
 
 
 
 
 
 
 
10
  tr_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-tr-en")
11
  en_to_tr = pipeline("translation", model="Helsinki-NLP/opus-mt-tc-big-en-tr")
12
 
13
  def turkish_to_english(text):
14
- result = tr_to_en(text, max_length=512)
15
- return result[0]['translation_text']
16
 
17
  def english_to_turkish(text):
18
- result = en_to_tr(text, max_length=512)
19
- return result[0]['translation_text']
20
 
21
- print("Çeviri modelleri hazır!")
 
 
22
 
23
- # 2. LLaVA-Med bileşenleri
24
- print("LLaVA-Med bileşenleri yükleniyor...")
25
- vision_model_path = "openai/clip-vit-large-patch14"
26
- vision_model = CLIPVisionModel.from_pretrained(vision_model_path)
27
- image_processor = CLIPImageProcessor.from_pretrained(vision_model_path)
28
 
29
- model_path = "microsoft/llava-med-v1.5-mistral-7b"
30
- tokenizer = AutoTokenizer.from_pretrained(model_path)
31
- model = AutoModelForCausalLM.from_pretrained(
32
- model_path,
33
- torch_dtype=torch.float16,
34
- load_in_8bit=True,
35
- device_map="auto"
36
- )
37
 
38
- print("LLaVA-Med modeli yüklendi!")
 
 
 
 
 
 
39
 
40
- def predict_turkish(image, turkish_question):
41
- try:
42
- # Görüntüyü işle
43
- image_inputs = image_processor(images=image, return_tensors="pt").to(model.device)
44
- image_features = vision_model(**image_inputs).last_hidden_state
45
-
46
- # Türkçe -> İngilizce çeviri
47
- english_question = turkish_to_english(turkish_question)
48
-
49
- # Prompt hazırla
50
- prompt = f"Image description: [No text content in the image].\\n\\nQuestion: {english_question}\\n\\nAnswer:"
51
-
52
- # Yanıt oluştur
53
- inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
54
-
55
- with torch.no_grad():
56
- outputs = model.generate(
57
- **inputs,
58
- max_new_tokens=500,
59
- do_sample=False
60
- )
61
-
62
- english_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
63
-
64
- # İngilizce -> Türkçe çeviri
65
- turkish_response = english_to_turkish(english_response)
66
- return turkish_response
67
- except Exception as e:
68
- # Hata durumunda yedek sistem
69
- english_question = turkish_to_english(turkish_question)
70
-
71
- # Basit anahtar kelime tabanlı yapay yanıtlar
72
- if "symptom" in english_question.lower() or "semptom" in turkish_question.lower():
73
- english_response = "Yes, the image shows signs of pulmonary edema with bilateral infiltrates. There are also indications of cardiomegaly. These findings are consistent with heart failure."
74
- elif "diagnosis" in english_question.lower() or "tanı" in turkish_question.lower():
75
- english_response = "The radiograph shows pulmonary edema with bilateral infiltrates, consistent with congestive heart failure. There's also evidence of cardiomegaly (enlarged heart)."
76
- elif "normal" in english_question.lower() or "normal" in turkish_question.lower():
77
- english_response = "No, this chest X-ray is not normal. It shows pulmonary edema with bilateral infiltrates and cardiomegaly, consistent with heart failure."
78
- else:
79
- english_response = "The chest X-ray shows pulmonary edema with bilateral infiltrates, particularly in the lower lung fields. There is also cardiomegaly (enlarged heart). These findings are consistent with congestive heart failure."
80
-
81
- turkish_response = english_to_turkish(english_response)
82
- return turkish_response
83
 
84
- # Gradio arayüzü oluştur
85
  interface = gr.Interface(
86
  fn=predict_turkish,
87
  inputs=[
88
  gr.Image(type="pil", label="Tıbbi Görüntü"),
89
- gr.Textbox(label="Türkçe Sorunuz", placeholder="Örn: Bu görüntüde akciğerlerde bir anormallik görüyor musunuz?")
90
  ],
91
- outputs=gr.Textbox(label="Cevap"),
92
- title="Türkçe Tıbbi Görüntü Analiz Modeli",
93
- description="Bu model, Microsoft'un LLaVA-Med modelini Türkçe kullanım için özelleştirilmiş şekilde kullanmanızı sağlar."
94
  )
95
 
96
- interface.launch()
 
 
1
  import gradio as gr
2
  import torch
3
  from PIL import Image
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPImageProcessor, pipeline
5
+ from llava.conversation import conv_templates
6
+ from llava.constants import DEFAULT_IMAGE_TOKEN
7
 
8
+ device = "cuda" if torch.cuda.is_available() else "cpu"
9
+
10
+ # 1. LLaVA-Med yükle
11
+ print("Model yükleniyor...")
12
+ model = AutoModelForCausalLM.from_pretrained(".", torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32).to(device)
13
+ tokenizer = AutoTokenizer.from_pretrained(".")
14
+ image_processor = CLIPImageProcessor.from_pretrained(".")
15
+
16
+ # 2. Çeviri modelleri (pipeline üzerinden)
17
+ print("Çeviri yükleniyor...")
18
  tr_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-tr-en")
19
  en_to_tr = pipeline("translation", model="Helsinki-NLP/opus-mt-tc-big-en-tr")
20
 
21
  def turkish_to_english(text):
22
+ return tr_to_en(text)[0]['translation_text']
 
23
 
24
  def english_to_turkish(text):
25
+ return en_to_tr(text)[0]['translation_text']
 
26
 
27
+ # 3. Tahmin fonksiyonu
28
+ def predict_turkish(image, turkish_question):
29
+ english_question = turkish_to_english(turkish_question)
30
 
31
+ # Görüntü formatı
32
+ image = image.convert("RGB")
33
+ image_tensor = image_processor.preprocess(image, return_tensors="pt")["pixel_values"].half().to(device)
 
 
34
 
35
+ # LLaVA prompt
36
+ conv = conv_templates["llava-v1"].copy()
37
+ conv.messages = []
38
+ conv.append_message(conv.roles[0], DEFAULT_IMAGE_TOKEN + "\n" + english_question)
39
+ conv.append_message(conv.roles[1], None)
40
+ prompt = conv.get_prompt()
41
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
 
42
 
43
+ with torch.inference_mode():
44
+ output_ids = model.generate(
45
+ input_ids=input_ids,
46
+ images=image_tensor,
47
+ do_sample=False,
48
+ max_new_tokens=512
49
+ )
50
 
51
+ english_response = tokenizer.decode(output_ids[0, input_ids.shape[1]:], skip_special_tokens=True)
52
+ return english_to_turkish(english_response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ # 4. Gradio arayüzü
55
  interface = gr.Interface(
56
  fn=predict_turkish,
57
  inputs=[
58
  gr.Image(type="pil", label="Tıbbi Görüntü"),
59
+ gr.Textbox(label="Türkçe Sorunuz", placeholder="Örn: Bu görüntüde bir tümör var mı?")
60
  ],
61
+ outputs=gr.Textbox(label="Model Cevabı"),
62
+ title="Türkçe LLaVA-Med Görsel Soru-Cevaplama",
63
+ description="LLaVA-Med v1.5 (Mistral 7B) modelinin Türkçe destekli demo arayüzüdür. Görüntü yükleyin, Türkçe soru sorun, Türkçe cevap alın."
64
  )
65
 
66
+ if __name__ == "__main__":
67
+ interface.launch()