Spaces:
Running
Running
import gradio as gr | |
from transformers import AutoProcessor, PaliGemmaForConditionalGeneration | |
import torch | |
from PIL import Image | |
import os | |
from huggingface_hub import login | |
# Token ayarları | |
HF_TOKEN = os.getenv("HF_TOKEN") | |
if not HF_TOKEN: | |
raise ValueError("HF_TOKEN bulunamadı. Lütfen Space ayarlarından token’ı ekleyin.") | |
login(HF_TOKEN) | |
# PaliGemma modelini yükle | |
model_id = "google/paligemma-3b-mix-224" | |
model = PaliGemmaForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.bfloat16) | |
processor = AutoProcessor.from_pretrained(model_id) | |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
model.to(device) | |
# Soru yanıtlama fonksiyonu | |
def answer_question(image, question): | |
if not question: | |
return "Lütfen bir soru girin." | |
inputs = processor(images=image, text=question, return_tensors="pt").to(device) | |
with torch.no_grad(): | |
output = model.generate( | |
**inputs, | |
max_new_tokens=500, # Daha uzun cevaplar için artırıldı | |
temperature=0.7, # Yaratıcılığı biraz artırmak için | |
do_sample=True # Örnekleme ile daha çeşitli cevaplar | |
) | |
answer = processor.decode(output[0], skip_special_tokens=True)[len(question):].strip() | |
return f"PaliGemma’ya göre: {answer}" | |
# Örnek görseller (Space’in kök dizininde olmalı) | |
example_image_1 = "example_1.jpg" # İlk örnek görsel | |
example_image_2 = "example_2.jpg" # İkinci örnek görsel | |
# Gradio arayüzü | |
interface = gr.Interface( | |
fn=answer_question, | |
inputs=[ | |
gr.Image(type="pil", label="Görüntüyü Yükle"), | |
gr.Textbox(label="Sorunuzu Sorun", placeholder="Bu görüntüde ne var?") | |
], | |
outputs=gr.Textbox(label="Cevap"), | |
title="PaliGemma 2 Mix ile Görsel Soru Yanıtlama", | |
description="Bir görüntü yükleyin ve hakkında istediğiniz soruyu sorun. PaliGemma 2 Mix cevaplayacak!", | |
examples=[ | |
[example_image_1, "Bu görselde kaç kedi var?"], | |
[example_image_2, "Bu görseli bana detaylı açıklayabilir misin?"] | |
] | |
) | |
interface.launch() |