Arabic250 commited on
Commit
1d01078
·
verified ·
1 Parent(s): 67b89dc

Create app. py

Browse files
Files changed (1) hide show
  1. app. py +54 -0
app. py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import torch
4
+
5
+ # تحديث اسم النموذج إلى إصدار Gemma 4 (يمكنك تغيير الحجم حسب المتوفر مثل 2b أو 8b)
6
+ model_name = "google/gemma4:e4b"
7
+
8
+ # تحميل النموذج والمحلل اللفظي (Tokenizer)
9
+ # ملاحظة: قد تحتاج إلى تمرير token=True إذا كان النموذج يتطلب الموافقة على الشروط
10
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
11
+ model = AutoModelForCausalLM.from_pretrained(
12
+ model_name,
13
+ torch_dtype=torch.float16,
14
+ device_map="auto"
15
+ )
16
+
17
+ def chat(message, history):
18
+ # 1. بناء سياق المحادثة (الذاكرة)
19
+ messages = []
20
+ for human, assistant in history:
21
+ messages.append({"role": "user", "content": human})
22
+ messages.append({"role": "assistant", "content": assistant})
23
+
24
+ # 2. إضافة الرسالة الجديدة للمستخدم
25
+ messages.append({"role": "user", "content": message})
26
+
27
+ # 3. تنسيق الرسائل بالشكل الذي يفهمه نموذج Gemma
28
+ input_ids = tokenizer.apply_chat_template(
29
+ messages,
30
+ add_generation_prompt=True,
31
+ return_tensors="pt"
32
+ ).to(model.device)
33
+
34
+ # 4. توليد الرد
35
+ outputs = model.generate(
36
+ input_ids,
37
+ max_new_tokens=512,
38
+ do_sample=True,
39
+ temperature=0.7,
40
+ top_p=0.9
41
+ )
42
+
43
+ # 5. استخراج الرد الجديد فقط (تجاهل النص المدخل)
44
+ input_length = input_ids.shape[1]
45
+ response = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True)
46
+
47
+ return response
48
+
49
+ # تشغيل واجهة المستخدم
50
+ gr.ChatInterface(
51
+ chat,
52
+ title="Gemma 4 Chatbot",
53
+ description="روبوت محادثة مدعوم بنموذج Gemma 4 من جوجل"
54
+ ).launch()