RaghadAbdulaziz commited on
Commit
3e803bf
·
1 Parent(s): 269ac07
Files changed (1) hide show
  1. app.py +91 -57
app.py CHANGED
@@ -1,67 +1,101 @@
1
- import gradio as gr
2
- from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
 
 
4
 
5
- # ===== 1) كلمات مفتاحية =====
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  allowed_keywords = [
7
- "عجوة", "Ajwa", "جالكسي", "Galaxy", "مجدول", "Medjool", "منيفي", "Meneifi",
8
- "نبتة علي", "Nabtat Ali", "رطب", "Rutab", "شائشة", "Shaishe", "صقعي", "Sokari",
9
- "مبروم", "Mabroom", "سكري", "Sukkary",
10
- "اللفحة السوداء", "Black Scorch", "حرق النخيل", "احتراق الجريد",
11
- "ذبول الفيوزاريم", "Fusarium Wilt", "ذبول النخل", "النخل ناشف من جوّا",
12
- "تبقعات الأوراق", "Leaf Spots", "نقاط على الجريد", "بقع بالنخل",
13
- "نقص المغنيسيوم", "Magnesium Deficiency", "صفرة في الجريد", "ضعف العذوق",
14
- "نقص المنغنيز", "Manganese Deficiency", "اصفرار الخوص", "النخل ما يعصر زين",
15
- "نقص البوتاسيوم", "Potassium Deficiency", "الجريد يطيح بسرعة", "النخل ما يعطي ثمر واجد",
16
- "بارلاتوريا بلانشارد", "Parlatoria Blanchardi", "حشرة بالنخل", "نخلتي فيها قمل أبيض",
17
- "لفحة الشماريخ", "Rachis Blight", "الشماريخ يابسة", "الثمر ما يكمل",
18
- "نخيل", "نخلة", "فسيلة", "فسائل", "مزرعة نخل", "نخل السعودية", "تمور", "تمر",
19
- "أنواع التمر", "جودة التمر", "وش أفضل تمر", "تمور المملكة", "تمور القصيم",
20
- "تمور المدينة", "تمر المدينة", "تمر القصيم", "تمر فاخر", "تمور فاخرة",
21
- "تمر سكري", "خلاص", "نخلة مريضة", "مرض النخيل", "مشاكل النخيل", "أمراض التمر"
 
 
 
 
 
 
 
 
 
 
22
  ]
23
 
24
- def is_relevant_question(user_input):
25
- return any(keyword in user_input for keyword in allowed_keywords)
26
 
27
- model_name = "ALLaM-AI/ALLaM-7B-Instruct-preview"
 
 
 
28
 
29
- device = "cuda" if torch.cuda.is_available() else "cpu"
30
- dtype = torch.float16 if device == "cuda" else torch.float32
31
 
32
- tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False, trust_remote_code=True)
33
- model = AutoModelForCausalLM.from_pretrained(
34
- model_name,
35
- trust_remote_code=True,
36
- torch_dtype=dtype,
37
- device_map="auto"
38
- )
 
 
39
 
40
- def chatbot_response(user_input):
41
- if not is_relevant_question(user_input):
42
- return "أنا متخصص فقط في النخيل والتمور. يرجى طرح أسئلة ذات صلة."
43
-
44
- prompt = f"سؤال: {user_input}\nجواب:"
45
- inputs = tokenizer(prompt, return_tensors="pt")
46
- inputs = {k: v.to(model.device) for k, v in inputs.items()}
47
-
48
- outputs = model.generate(
49
- **inputs,
50
- max_new_tokens=256,
51
- do_sample=True,
52
- top_p=0.9,
53
- temperature=0.8
54
- )
55
-
56
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
57
- return response.replace(prompt, "").strip()
58
-
59
- iface = gr.Interface(
60
- fn=chatbot_response,
61
- inputs=gr.Textbox(lines=3, placeholder="اكتب سؤالك هنا..."),
62
- outputs=gr.Textbox(label="رد الشات بوت"),
63
- title="مساعد التمور والنخيل",
64
- description="روبوت دردشة متخصص في النخيل والتمور"
65
- )
66
 
67
- iface.launch()
 
 
 
1
  import torch
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
+ import gradio as gr
4
 
5
+ # ====================== 1) Load Model ======================
6
+ model_name = "TheBloke/arabic-llama-7b-chat-GPTQ" # Example Arabic model
7
+ tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
8
+ model = AutoModelForCausalLM.from_pretrained(
9
+ model_name,
10
+ device_map="auto",
11
+ torch_dtype=torch.float16,
12
+ trust_remote_code=True
13
+ )
14
+ pipe = pipeline(
15
+ "text-generation",
16
+ model=model,
17
+ tokenizer=tokenizer,
18
+ device=0,
19
+ max_new_tokens=512,
20
+ temperature=0.6,
21
+ repetition_penalty=1.1
22
+ )
23
+
24
+ # ====================== 2) Helper function ======================
25
+ def build_prompt(history, user_input):
26
+ prompt = ""
27
+ for user_msg, bot_msg in history:
28
+ prompt += f"<|user|>\n{user_msg}\n<|assistant|>\n{bot_msg}\n"
29
+ prompt += f"<|user|>\n{user_input}\n<|assistant|>\n"
30
+ return prompt
31
+
32
+ # ====================== 3) Keywords ======================
33
  allowed_keywords = [
34
+ # 🌴 Palm-related
35
+ "palm", "palms", "نخلة", "نخل", "نخلي", "فسيلة", "فسائل", "جذع", "سعف", "خوص", "جريد", "شماريخ", "عذوق", "مزرعة نخل", "offshoot", "date palm",
36
+
37
+ # 🐛 Diseases
38
+ "مرض النخيل", "ذبول", "لفحة", "اللفحة السوداء", "فطريات", "قمل أبيض", "ذبول الفيوزاريم", "تبقعات الأوراق", "نقص المغنيسيوم", "نقص البوتاسيوم", "اصفرار الخوص", "احتراق الجريد", "الثمر ما يكتمل",
39
+ "Black scorch", "Fusarium wilt", "Rachis blight", "Leaf spot", "Mites", "Insects", "White bugs", "Parlatoria", "Magnesium deficiency", "Potassium deficiency", "Manganese deficiency",
40
+
41
+ # 🍇 Dates
42
+ "تمر", "تمور", "تمر سكري", "سكري", "خلاص", "عجوة", "مجدول", "روثانة", "رطب", "برني", "عنبري", "صفاوي", "صقعي", "خضري", "فاخر", "premium dates", "best dates", "Ajwa", "Medjool", "Sukkary", "Khalas", "Safawi", "Sagai", "Khudri", "Ruthana", "Barni", "Anbara",
43
+
44
+ # 🌱 Care & Maintenance
45
+ "ري", "سقي", "تسميد", "مبيد", "متى أسقي النخلة", "نصائح العناية", "رش", "تقليم", "عناية", "كيف أعتني",
46
+ "palm care", "how to water", "fertilizer", "pest control", "sunlight", "organic spray", "how to prune",
47
+
48
+ # 🌦️ Stats & Weather
49
+ "كم نخلة", "كم تمر", "عدد النخل", "الجو", "الطقس", "الحرارة", "الرطوبة", "مناسب للتلقيح", "is it good weather", "weather", "temperature", "total palms", "healthy palms", "sick palms",
50
+
51
+ # 🛒 Consumer
52
+ "أين أشتري تمر", "أفضل تمر", "تمور مغشوشة", "تمور القصيم", "تمور المدينة", "جودة التمر", "التغليف", "شراء تمر", "buy dates", "where to find", "identify good dates", "how to store dates",
53
+
54
+ # 📸 App features
55
+ "افتح الكاميرا", "حلل الصورة", "قيم النخلة", "قيم التمر", "camera", "analyze", "scan", "image detection",
56
+
57
+ # ℹ️ General
58
+ "تطبيق لينة", "نظام لينة", "عن لينة", "Lina app", "explain Lina", "help with Lina", "what is Lina"
59
  ]
60
 
61
+ greetings = ["سلام", "السلام عليكم", "أهلاً", "هاي", "hi", "hello", "hey"]
62
+ intro_questions = ["من أنت", "مين انت", "what is this", "who are you", "explain the app", "about lina"]
63
 
64
+ # ====================== 4) Chat Function ======================
65
+ def chat(user_input, history):
66
+ if history is None:
67
+ history = []
68
 
69
+ lower_input = user_input.lower()
 
70
 
71
+ # If greeting detected
72
+ if any(greet in lower_input for greet in greetings):
73
+ output = "وعليكم السلام ورحمة الله وبركاته! 👋 كيف يمكنني مساعدتك؟"
74
+ # If asking about app intro
75
+ elif any(intro in lower_input for intro in intro_questions):
76
+ output = "أنا مساعد ذكي مختص بالنخيل والتمور. 🌴🍇 اسألني عن أي شيء!"
77
+ else:
78
+ prompt = build_prompt(history, user_input)
79
+ generated = pipe(prompt)[0]['generated_text']
80
 
81
+ # Extract the latest assistant output
82
+ if "<|assistant|>" in generated:
83
+ output = generated.split("<|assistant|>")[-1].strip()
84
+ else:
85
+ output = generated.strip()
86
+
87
+ history.append((user_input, output))
88
+ return history, history
89
+
90
+ # ====================== 5) Gradio UI ======================
91
+ with gr.Blocks() as demo:
92
+ gr.Markdown("<h1>🕌 Arabic Palm Chatbot (نظام لينة)</h1>")
93
+ chatbot = gr.Chatbot(label="المحادثة")
94
+ with gr.Row():
95
+ txt = gr.Textbox(placeholder="اكتب رسالتك هنا...", label="أدخل نصك").style(container=False)
96
+ send = gr.Button("إرسال")
97
+
98
+ send.click(chat, inputs=[txt, chatbot], outputs=[chatbot, chatbot])
99
+ txt.submit(chat, inputs=[txt, chatbot], outputs=[chatbot, chatbot])
 
 
 
 
 
 
 
100
 
101
+ demo.launch()