Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration, MarianMTModel, MarianTokenizer
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
# Load translation model
|
| 7 |
+
translator_model_ar = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-ar")
|
| 8 |
+
translator_tokenizer_ar = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-ar")
|
| 9 |
+
|
| 10 |
+
# Load BLIP model (fine-tuned)
|
| 11 |
+
model_path = "saja003/MuniVis"
|
| 12 |
+
processor_en = BlipProcessor.from_pretrained(model_path)
|
| 13 |
+
model_en = BlipForConditionalGeneration.from_pretrained(model_path)
|
| 14 |
+
model_en.eval()
|
| 15 |
+
|
| 16 |
+
# Function to describe image
|
| 17 |
+
def describe_image(image, language):
|
| 18 |
+
if language == "Arabic":
|
| 19 |
+
inputs = processor_en(image, return_tensors="pt")
|
| 20 |
+
with torch.no_grad():
|
| 21 |
+
out = model_en.generate(**inputs)
|
| 22 |
+
description = processor_en.decode(out[0], skip_special_tokens=True)
|
| 23 |
+
inputs_ar = translator_tokenizer_ar(description, return_tensors="pt")
|
| 24 |
+
with torch.no_grad():
|
| 25 |
+
translated_tokens = translator_model_ar.generate(**inputs_ar)
|
| 26 |
+
arabic_description = translator_tokenizer_ar.decode(translated_tokens[0], skip_special_tokens=True)
|
| 27 |
+
return arabic_description
|
| 28 |
+
|
| 29 |
+
elif language == "English":
|
| 30 |
+
inputs_en = processor_en(image, return_tensors="pt")
|
| 31 |
+
with torch.no_grad():
|
| 32 |
+
out_en = model_en.generate(**inputs_en)
|
| 33 |
+
description_en = processor_en.decode(out_en[0], skip_special_tokens=True)
|
| 34 |
+
return description_en
|
| 35 |
+
|
| 36 |
+
# Gradio UI
|
| 37 |
+
iface = gr.Interface(
|
| 38 |
+
fn=describe_image,
|
| 39 |
+
inputs=[
|
| 40 |
+
gr.Image(type="pil", label="Upload an Image"),
|
| 41 |
+
gr.Dropdown(choices=["Arabic", "English"], label="Select Language")
|
| 42 |
+
],
|
| 43 |
+
outputs="text",
|
| 44 |
+
title="Image Captioning with Arabic Translation",
|
| 45 |
+
description="Select the language and upload an image to get a description."
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
iface.launch()
|