Update app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,7 @@
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
from transformers import pipeline
|
|
|
4 |
|
5 |
# Global variable to store the model
|
6 |
pipe = None
|
@@ -19,17 +20,157 @@ def load_model():
|
|
19 |
print("✅ Model loaded successfully!")
|
20 |
return pipe
|
21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
def chat_with_atlas(message, history):
|
23 |
-
"""Generate response from Atlas-Chat model"""
|
24 |
if not message.strip():
|
25 |
-
return "مرحبا! أهلا وسهلا. Please enter a message!"
|
26 |
|
27 |
try:
|
28 |
# Load model if not already loaded
|
29 |
model = load_model()
|
30 |
|
31 |
-
#
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
# Generate response
|
35 |
outputs = model(
|
@@ -42,10 +183,19 @@ def chat_with_atlas(message, history):
|
|
42 |
|
43 |
# Extract the response
|
44 |
response = outputs[0]["generated_text"][-1]["content"].strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
return response
|
46 |
|
47 |
except Exception as e:
|
48 |
-
return f"عذراً، واجهت خطأ: {str(e)}. جرب مرة أخرى!"
|
49 |
|
50 |
# Create the Gradio interface
|
51 |
demo = gr.ChatInterface(
|
@@ -54,18 +204,25 @@ demo = gr.ChatInterface(
|
|
54 |
description="""
|
55 |
**مرحبا بك في أطلس شات!** Welcome to Atlas-Chat! 🇲🇦
|
56 |
|
57 |
-
I'm an AI assistant specialized in **Moroccan Arabic (Darija)**
|
58 |
-
|
|
|
|
|
|
|
59 |
|
60 |
**جرب هذه الأسئلة / Try these questions:**
|
61 |
""",
|
62 |
examples=[
|
63 |
"شكون لي صنعك؟",
|
64 |
-
"
|
|
|
|
|
65 |
"شنو كيتسمى المنتخب المغربي؟",
|
|
|
66 |
"What is Morocco famous for?",
|
67 |
"Tell me about Casablanca",
|
68 |
-
"كيفاش نقدر نتعلم الدارجة؟"
|
|
|
69 |
],
|
70 |
cache_examples=False
|
71 |
)
|
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
from transformers import pipeline
|
4 |
+
import re
|
5 |
|
6 |
# Global variable to store the model
|
7 |
pipe = None
|
|
|
20 |
print("✅ Model loaded successfully!")
|
21 |
return pipe
|
22 |
|
23 |
+
def detect_arabizi(text):
|
24 |
+
"""
|
25 |
+
Detect if input text is written in Arabizi (Latin script with numbers)
|
26 |
+
Returns True if Arabizi is detected
|
27 |
+
"""
|
28 |
+
if not text or len(text.strip()) < 2:
|
29 |
+
return False
|
30 |
+
|
31 |
+
# Remove spaces and convert to lowercase for analysis
|
32 |
+
clean_text = text.lower().replace(" ", "")
|
33 |
+
|
34 |
+
# Check for Arabic script - if present, it's NOT Arabizi
|
35 |
+
arabic_pattern = r'[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]'
|
36 |
+
if re.search(arabic_pattern, text):
|
37 |
+
return False
|
38 |
+
|
39 |
+
# Arabizi indicators
|
40 |
+
arabizi_numbers = ['2', '3', '7', '9'] # Common Arabic letter substitutions
|
41 |
+
arabizi_patterns = [
|
42 |
+
'wach', 'wash', 'ach', 'achno', 'chno', 'shno', # What
|
43 |
+
'kif', 'kifash', 'ki', 'kayf', # How
|
44 |
+
'feen', 'fin', 'fen', # Where
|
45 |
+
'imta', 'meta', 'waqt', # When
|
46 |
+
'3la', '3ala', 'ala', # On/about
|
47 |
+
'hna', '7na', 'ahna', # We/us
|
48 |
+
'nta', 'nti', 'ntuma', # You
|
49 |
+
'howa', 'hiya', 'huma', # He/she/they
|
50 |
+
'ma3', 'maa3', 'maak', 'maaki', # With
|
51 |
+
'had', 'hadchi', 'hada', 'hadi', # This
|
52 |
+
'bghit', 'bghiti', 'bgha', # Want
|
53 |
+
'galt', 'galti', 'gal', # Said
|
54 |
+
'rah', 'raha', 'rahi', # Going
|
55 |
+
'kan', 'kanu', 'kana', # Was/were
|
56 |
+
'ghadi', 'ghad', 'gha', # Will/going to
|
57 |
+
'daba', 'dak', 'dakchi', # Now/that
|
58 |
+
'bzf', 'bzzaf', 'bezzaf', # A lot
|
59 |
+
'chway', 'chwiya', 'shwiya', # A little
|
60 |
+
'khoya', 'khuya', 'akhi', # Brother
|
61 |
+
'khti', 'khtiya', 'ukhti', # Sister
|
62 |
+
'allah', 'llah', 'rabi', # God
|
63 |
+
'inchallah', 'insha allah', # God willing
|
64 |
+
'hamdulillah', 'alhamdulillah', # Praise God
|
65 |
+
'salam', 'salamu aleikum', # Peace
|
66 |
+
'baraka', 'barakallahu', # Blessing
|
67 |
+
'yallah', 'yalla', 'hya' # Come on/let's go
|
68 |
+
]
|
69 |
+
|
70 |
+
# Count Latin letters
|
71 |
+
latin_letters = sum(1 for c in clean_text if c.isalpha() and ord(c) < 128)
|
72 |
+
|
73 |
+
# Count Arabizi number substitutions
|
74 |
+
arabizi_number_count = sum(1 for num in arabizi_numbers if num in clean_text)
|
75 |
+
|
76 |
+
# Count Arabizi word patterns
|
77 |
+
arabizi_word_count = sum(1 for pattern in arabizi_patterns if pattern in clean_text)
|
78 |
+
|
79 |
+
# Decision logic
|
80 |
+
total_chars = len(clean_text)
|
81 |
+
|
82 |
+
# Strong indicators
|
83 |
+
if arabizi_number_count >= 2: # Multiple number substitutions
|
84 |
+
return True
|
85 |
+
|
86 |
+
if arabizi_word_count >= 2: # Multiple Arabizi words
|
87 |
+
return True
|
88 |
+
|
89 |
+
# Medium indicators
|
90 |
+
if arabizi_number_count >= 1 and latin_letters > total_chars * 0.7:
|
91 |
+
return True
|
92 |
+
|
93 |
+
if arabizi_word_count >= 1 and latin_letters > total_chars * 0.8:
|
94 |
+
return True
|
95 |
+
|
96 |
+
# Weak but possible indicators
|
97 |
+
if latin_letters > total_chars * 0.9 and total_chars > 10:
|
98 |
+
# Mostly Latin letters in longer text - could be Arabizi
|
99 |
+
if arabizi_number_count >= 1 or arabizi_word_count >= 1:
|
100 |
+
return True
|
101 |
+
|
102 |
+
return False
|
103 |
+
|
104 |
+
def determine_response_language(user_input):
|
105 |
+
"""
|
106 |
+
Determine what language/script the response should be in
|
107 |
+
Returns: 'arabizi', 'arabic', or 'english'
|
108 |
+
"""
|
109 |
+
if detect_arabizi(user_input):
|
110 |
+
return 'arabizi'
|
111 |
+
|
112 |
+
# Check for Arabic script
|
113 |
+
arabic_pattern = r'[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]'
|
114 |
+
if re.search(arabic_pattern, user_input):
|
115 |
+
return 'arabic'
|
116 |
+
|
117 |
+
# Default to English for Latin-only text without Arabizi indicators
|
118 |
+
return 'english'
|
119 |
+
|
120 |
+
def create_system_prompt(response_lang):
|
121 |
+
"""Create appropriate system prompt based on desired response language"""
|
122 |
+
|
123 |
+
if response_lang == 'arabizi':
|
124 |
+
return """You are Atlas-Chat, an AI assistant specialized in Moroccan Arabic (Darija).
|
125 |
+
|
126 |
+
CRITICAL INSTRUCTION: The user has written in Arabizi (Latin script), so you MUST respond ONLY in Arabizi using Latin letters and numbers.
|
127 |
+
|
128 |
+
ARABIZI RULES YOU MUST FOLLOW:
|
129 |
+
- Use ONLY Latin letters (a-z) and numbers for Arabic sounds
|
130 |
+
- Use these number substitutions: 3=ع, 7=ح, 9=ق, 2=ء, 5=خ, 6=ط, 8=غ
|
131 |
+
- Write naturally in Moroccan Darija but with Latin script
|
132 |
+
- Examples: "ana" (أنا), "hna" (حنا), "3la" (على), "7na" (حنا), "wach" (واش)
|
133 |
+
- Do NOT use any Arabic script characters
|
134 |
+
- Do NOT switch to English unless the user specifically asks for translation
|
135 |
+
|
136 |
+
Respond naturally in Arabizi about Moroccan culture, language, and general topics."""
|
137 |
+
|
138 |
+
elif response_lang == 'arabic':
|
139 |
+
return """You are Atlas-Chat, an AI assistant specialized in Moroccan Arabic (Darija). Respond in Arabic script (Darija) as this is what the user is using. Be helpful and culturally aware about Morocco and its traditions."""
|
140 |
+
|
141 |
+
else: # English
|
142 |
+
return """You are Atlas-Chat, an AI assistant specialized in Moroccan Arabic (Darija) but also fluent in English. The user has written in English, so respond in English while being knowledgeable about Moroccan culture and language."""
|
143 |
+
|
144 |
def chat_with_atlas(message, history):
|
145 |
+
"""Generate response from Atlas-Chat model with language detection"""
|
146 |
if not message.strip():
|
147 |
+
return "مرحبا! أهلا وسهلا. Please enter a message! / Ahlan wa sahlan!"
|
148 |
|
149 |
try:
|
150 |
# Load model if not already loaded
|
151 |
model = load_model()
|
152 |
|
153 |
+
# Determine response language
|
154 |
+
response_lang = determine_response_language(message)
|
155 |
+
|
156 |
+
# Create appropriate system prompt
|
157 |
+
system_prompt = create_system_prompt(response_lang)
|
158 |
+
|
159 |
+
# Prepare messages with system context
|
160 |
+
if response_lang == 'arabizi':
|
161 |
+
# Extra emphasis for Arabizi responses
|
162 |
+
enhanced_message = f"""System: {system_prompt}
|
163 |
+
|
164 |
+
User message (in Arabizi): {message}
|
165 |
+
|
166 |
+
Remember: Respond ONLY in Arabizi (Latin letters + numbers). Do not use Arabic script."""
|
167 |
+
|
168 |
+
messages = [{"role": "user", "content": enhanced_message}]
|
169 |
+
else:
|
170 |
+
messages = [
|
171 |
+
{"role": "system", "content": system_prompt},
|
172 |
+
{"role": "user", "content": message}
|
173 |
+
]
|
174 |
|
175 |
# Generate response
|
176 |
outputs = model(
|
|
|
183 |
|
184 |
# Extract the response
|
185 |
response = outputs[0]["generated_text"][-1]["content"].strip()
|
186 |
+
|
187 |
+
# Post-process for Arabizi if needed
|
188 |
+
if response_lang == 'arabizi':
|
189 |
+
# Remove any Arabic script that might have leaked through
|
190 |
+
arabic_pattern = r'[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]'
|
191 |
+
if re.search(arabic_pattern, response):
|
192 |
+
# If Arabic script is detected, provide a fallback Arabizi response
|
193 |
+
response = "ana Atlas-Chat, kay3jebni n7der m3ak! chno bghiti t3ref 3la lmaghrib? (I'm Atlas-Chat, I'd love to chat with you! What do you want to know about Morocco?)"
|
194 |
+
|
195 |
return response
|
196 |
|
197 |
except Exception as e:
|
198 |
+
return f"عذراً، واجهت خطأ: {str(e)}. جرب مرة أخرى! / Sorry, error occurred. Try again!"
|
199 |
|
200 |
# Create the Gradio interface
|
201 |
demo = gr.ChatInterface(
|
|
|
204 |
description="""
|
205 |
**مرحبا بك في أطلس شات!** Welcome to Atlas-Chat! 🇲🇦
|
206 |
|
207 |
+
I'm an AI assistant specialized in **Moroccan Arabic (Darija)** with smart language detection:
|
208 |
+
|
209 |
+
- **Arabic Script (العربية)** → I respond in Arabic
|
210 |
+
- **Arabizi (3arabi bi 7oruf latin)** → I respond in Arabizi
|
211 |
+
- **English** → I respond in English
|
212 |
|
213 |
**جرب هذه الأسئلة / Try these questions:**
|
214 |
""",
|
215 |
examples=[
|
216 |
"شكون لي صنعك؟",
|
217 |
+
"shkoun li sna3ek?",
|
218 |
+
"اشنو هو الطاجين؟",
|
219 |
+
"achno howa tajine?",
|
220 |
"شنو كيتسمى المنتخب المغربي؟",
|
221 |
+
"chno kaytsma lmontakhab lmaghribi?",
|
222 |
"What is Morocco famous for?",
|
223 |
"Tell me about Casablanca",
|
224 |
+
"كيفاش نقدر نتعلم الدارجة؟",
|
225 |
+
"kifash n9der nt3elem darija?"
|
226 |
],
|
227 |
cache_examples=False
|
228 |
)
|