Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# تثبيت المكتبات
|
| 2 |
+
!pip install transformers torch datasets gradio
|
| 3 |
+
|
| 4 |
+
# استيراد المكتبات
|
| 5 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration, MarianMTModel, MarianTokenizer
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
# تحميل نموذج BLIP ومعالج البيانات
|
| 10 |
+
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 11 |
+
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 12 |
+
|
| 13 |
+
# تحميل نموذج الترجمة
|
| 14 |
+
tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-ar")
|
| 15 |
+
model_mt = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-ar")
|
| 16 |
+
|
| 17 |
+
# دالة لترجمة التوصيفات إلى العربية
|
| 18 |
+
def translate_to_arabic(text):
|
| 19 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True)
|
| 20 |
+
translated = model_mt.generate(**inputs)
|
| 21 |
+
translated_text = [tokenizer.decode(t, skip_special_tokens=True) for t in translated]
|
| 22 |
+
return translated_text[0]
|
| 23 |
+
|
| 24 |
+
# دالة لتوليد التوصيفات
|
| 25 |
+
def generate_caption(image, language):
|
| 26 |
+
# معالجة الصورة
|
| 27 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 28 |
+
# توليد التوصيف
|
| 29 |
+
outputs = model.generate(**inputs)
|
| 30 |
+
caption = processor.decode(outputs[0], skip_special_tokens=True)
|
| 31 |
+
|
| 32 |
+
# ترجمة التوصيف إلى العربية إذا تم اختيارها
|
| 33 |
+
if language == "Arabic":
|
| 34 |
+
caption = translate_to_arabic(caption)
|
| 35 |
+
|
| 36 |
+
return caption
|
| 37 |
+
|
| 38 |
+
# إعداد واجهة Gradio
|
| 39 |
+
iface = gr.Interface(
|
| 40 |
+
fn=generate_caption,
|
| 41 |
+
inputs=[gr.inputs.Image(type="pil"), gr.inputs.Dropdown(choices=["English", "Arabic"])],
|
| 42 |
+
outputs="text",
|
| 43 |
+
title="Image Captioning System",
|
| 44 |
+
description="Upload an image and choose the language for caption generation."
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# تشغيل واجهة Gradio
|
| 48 |
+
iface.launch()
|