gijl commited on
Commit
be7c04d
·
verified ·
1 Parent(s): ad3cd05

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -0
app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from PIL import Image
4
+ from transformers import AutoProcessor, AutoModelForImageTextToText
5
+
6
+ # 1. تحديد المعالج والنموذج
7
+ model_id = "gijl/gemma-4-E4B-it"
8
+ device = "cuda" if torch.cuda.is_available() else "cpu"
9
+
10
+ # تحميل المعالج
11
+ processor = AutoProcessor.from_pretrained(model_id)
12
+
13
+ # تحميل النموذج مع ضبط الدقة لتوفير الذاكرة وتفعيل التوزيع التلقائي على كرت الشاشة
14
+ model = AutoModelForImageTextToText.from_pretrained(
15
+ model_id,
16
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32,
17
+ device_map="auto"
18
+ )
19
+
20
+ # 2. دالة المحادثة (التي ستقوم بتوليد الردود)
21
+ def chat_with_model(message, history):
22
+ # الواجهة متعددة الوسائط تعطينا رسالة كقاموس يحتوي على نص وملفات (صور)
23
+ text = message.get("text", "")
24
+ files = message.get("files", [])
25
+
26
+ # قراءة الصور إذا تم رفعها
27
+ images = [Image.open(f).convert("RGB") for f in files] if files else None
28
+
29
+ # بناء سياق المحادثة (History)
30
+ conversation = []
31
+ for user_msg, bot_msg in history:
32
+ # إذا كانت الرسالة السابقة تحتوي على صورة (يتم تمريرها كـ Tuple في Gradio)
33
+ if isinstance(user_msg, tuple):
34
+ user_msg = "[صورة مرفقة]"
35
+
36
+ conversation.append({"role": "user", "content": user_msg})
37
+ if bot_msg:
38
+ conversation.append({"role": "assistant", "content": bot_msg})
39
+
40
+ # إضافة رسالة المستخدم الحالية
41
+ # بعض النماذج تتطلب وضع وسم خاص بالصورة، لكننا سنفترض النص الافتراضي
42
+ conversation.append({"role": "user", "content": text if text else "[تحليل الصورة]"})
43
+
44
+ # تحضير المدخلات باستخدام القالب الخاص بالنموذج (Chat Template)
45
+ prompt = processor.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True)
46
+
47
+ # دمج النص والصور ومعالجتها للنموذج
48
+ inputs = processor(text=prompt, images=images, return_tensors="pt").to(model.device)
49
+
50
+ # 3. توليد الرد
51
+ with torch.no_grad():
52
+ outputs = model.generate(**inputs, max_new_tokens=1024)
53
+
54
+ # استخراج النص المولد فقط (تجاهل نص الإدخال)
55
+ input_length = inputs["input_ids"].shape[-1]
56
+ response = processor.decode(outputs[0][input_length:], skip_special_tokens=True)
57
+
58
+ return response
59
+
60
+ # 4. بناء واجهة المستخدم باستخدام Gradio
61
+ demo = gr.ChatInterface(
62
+ fn=chat_with_model,
63
+ multimodal=True, # تفعيل خيار رفع الصور
64
+ title="Gemma-4 Vision Chatbot",
65
+ description="واجهة دردشة متقدمة لنموذج `gijl/gemma-4-E4B-it`. يمكنك الدردشة النصية أو رفع صور ليقوم النموذج بتحليلها.",
66
+ theme=gr.themes.Soft(),
67
+ textbox=gr.MultimodalTextbox(placeholder="اكتب رسالتك هنا أو قم برفع صورة...", scale=7)
68
+ )
69
+
70
+ # تشغيل التطبيق
71
+ if __name__ == "__main__":
72
+ demo.launch()