ahmadbeilouni commited on
Commit
1e149e3
·
verified ·
1 Parent(s): 6838cb1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -250
app.py CHANGED
@@ -1,26 +1,21 @@
1
- """
2
- Falcon 7B Damascus Real Estate Chatbot - Hugging Face Test (FIXED)
3
- =================================================================
4
- """
5
-
6
  import gradio as gr
7
  import torch
8
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
9
- import json
10
- from typing import List, Dict, Any
11
 
 
12
  # Configuration
 
13
  MODEL_NAME = "tiiuae/falcon-7b-instruct"
14
  MAX_LENGTH = 500
15
  TEMPERATURE = 0.7
16
 
17
  print("🚀 Loading Falcon 7B for Damascus Real Estate...")
18
 
 
19
  # Load model and tokenizer
 
20
  try:
21
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
22
-
23
- # FIXED: Removed trust_remote_code=True per HF warning
24
  model = AutoModelForCausalLM.from_pretrained(
25
  MODEL_NAME,
26
  torch_dtype=torch.float16,
@@ -43,253 +38,51 @@ except Exception as e:
43
  generator = None
44
  model_loaded = False
45
 
46
- # Damascus property listings
47
- DAMASCUS_LISTINGS = [
48
- "1. مفروشة بالكامل، غرفتين وصالون، المالكي، طابق ثالث، شرفة واسعة، غسالة صحون، مليون وثمانمائة ألف ليرة بالشهر.",
49
- "2. ستوديو مفروش، باب شرقي، طابق أول، شرفة صغيرة، مكيف، ثمانمائة ألف ليرة بالشهر.",
50
- "3. شقة فارغة، ثلاث غرف، المزة، طابق ثاني، شرفة كبيرة، موقف سيارة، مليونين وخمسمائة ألف ليرة بالشهر.",
51
- "4. مفروشة، غرفة وصالون، الشعلان، طابق رابع، مكيفات، غسالة ملابس، مليون ومائتا ألف ليرة بالشهر.",
52
- "5. دوبلكس فاخر، أربع غرف، أبو رمانة، طابقين، تراس كبير، مصعد، خمسة ملايين ليرة بالشهر.",
53
- "6. ستوديو فارغ، القصاع، طابق أرضي، بدون شرفة، خمسمائة ألف ليرة بالشهر.",
54
- "7. مفروشة جزئياً، غرفتين، الجرمانا، طابق ثالث، شرفة متوسطة، غسالة صحون، مليون وأربعمائة ألف ليرة بالشهر.",
55
- "8. شقة فارغة، غرفة وصالون، باب توما، طابق ثاني، شرفة صغيرة، تسعمائة ألف ليرة بالشهر.",
56
- "9. مفروشة بالكامل، ثلاث غرف، المالكي، طابق أول، شرفتين، مكيفات، موقف سيارة، ثلاثة ملايين ليرة بالشهر.",
57
- "10. ستوديو مفروش، الشعلان، طابق خامس، شرفة واسعة، مكيف، فرن كهربائي، مليون ليرة بالشهر."
58
  ]
59
 
60
- def create_falcon_prompt(user_query: str, listings: List[str]) -> str:
61
- """Create a prompt for Falcon 7B to respond in Syrian Arabic"""
62
- listings_text = "\n".join(listings)
63
-
64
- prompt = f"""You are a real estate agent in Damascus, Syria. You help people find apartments.
65
-
66
- Available Properties:
67
- {listings_text}
68
-
69
- User Query: "{user_query}"
70
-
71
- Instructions:
72
- 1. Respond ONLY in Syrian Arabic (Damascus dialect)
73
- 2. Only mention properties from the Available Properties list above
74
- 3. If no suitable properties exist, say "عذراً، ما في عندي شقة بهاي المواصفات حالياً"
75
- 4. Be natural and conversational
76
- 5. Recommend the best matching properties
77
-
78
- Response:"""
79
-
80
- return prompt
81
-
82
- def extract_entities_basic(query: str) -> Dict[str, Any]:
83
- """Extract basic entities from Syrian Arabic query"""
84
- entities = {
85
- 'location': None,
86
- 'furnished': None,
87
- 'rooms': None,
88
- 'features': [],
89
- 'price_pref': None
90
- }
91
-
92
- query_lower = query.lower()
93
-
94
- # Location extraction
95
- locations = ['المالكي', 'باب شرقي', 'المزة', 'الشعلان', 'أبو رمانة', 'القصاع', 'الجرمانا', 'باب توما']
96
- for loc in locations:
97
- if loc in query_lower:
98
- entities['location'] = loc
99
- break
100
-
101
- # Furnished status
102
- if 'مفروش' in query_lower:
103
- entities['furnished'] = 'furnished'
104
- elif 'فارغ' in query_lower:
105
- entities['furnished'] = 'unfurnished'
106
-
107
- # Room count
108
- if 'ستوديو' in query_lower:
109
- entities['rooms'] = 'studio'
110
- elif 'غرفتين' in query_lower:
111
- entities['rooms'] = '2_rooms'
112
- elif 'ثلاث غرف' in query_lower:
113
- entities['rooms'] = '3_rooms'
114
-
115
- # Features
116
- if 'شرفة' in query_lower:
117
- entities['features'].append('balcony')
118
- if 'موقف' in query_lower:
119
- entities['features'].append('parking')
120
- if 'مكيف' in query_lower:
121
- entities['features'].append('ac')
122
-
123
- # Price preference
124
- if 'رخيص' in query_lower:
125
- entities['price_pref'] = 'cheap'
126
- elif 'فاخر' in query_lower:
127
- entities['price_pref'] = 'luxury'
128
-
129
- return entities
130
-
131
- def filter_listings_by_entities(listings: List[str], entities: Dict[str, Any]) -> List[str]:
132
- """Filter listings based on extracted entities"""
133
- filtered = []
134
-
135
- for listing in listings:
136
- listing_lower = listing.lower()
137
- matches = True
138
-
139
- # Location filter
140
- if entities.get('location'):
141
- if entities['location'] not in listing_lower:
142
- matches = False
143
-
144
- # Furnished filter
145
- if entities.get('furnished'):
146
- if entities['furnished'] == 'furnished' and 'مفروش' not in listing_lower:
147
- matches = False
148
- elif entities['furnished'] == 'unfurnished' and 'فارغ' not in listing_lower:
149
- matches = False
150
-
151
- # Room filter
152
- if entities.get('rooms'):
153
- if entities['rooms'] == 'studio' and 'ستوديو' not in listing_lower:
154
- matches = False
155
- elif entities['rooms'] == '2_rooms' and 'غرفتين' not in listing_lower:
156
- matches = False
157
- elif entities['rooms'] == '3_rooms' and 'ثلاث غرف' not in listing_lower:
158
- matches = False
159
-
160
- # Feature filters
161
- for feature in entities.get('features', []):
162
- if feature == 'balcony' and 'شرفة' not in listing_lower:
163
- matches = False
164
- elif feature == 'parking' and 'موقف' not in listing_lower:
165
- matches = False
166
- elif feature == 'ac' and 'مكيف' not in listing_lower:
167
- matches = False
168
-
169
- if matches:
170
- filtered.append(listing)
171
-
172
- return filtered[:5]
173
-
174
- def generate_response(user_query: str) -> tuple:
175
- """Generate response using Falcon 7B"""
176
-
177
  if not model_loaded:
178
- return "❌ Model not loaded. Please check the setup.", "{}", "[]"
179
-
180
- try:
181
- # Extract entities
182
- entities = extract_entities_basic(user_query)
183
-
184
- # Filter listings
185
- relevant_listings = filter_listings_by_entities(DAMASCUS_LISTINGS, entities)
186
-
187
- # Create prompt
188
- prompt = create_falcon_prompt(user_query, relevant_listings if relevant_listings else DAMASCUS_LISTINGS[:3])
189
-
190
- # Generate with Falcon
191
- response = generator(
192
- prompt,
193
- max_length=len(prompt) + MAX_LENGTH,
194
- temperature=TEMPERATURE,
195
- do_sample=True,
196
- pad_token_id=tokenizer.eos_token_id,
197
- num_return_sequences=1
198
- )
199
-
200
- # Extract generated text
201
- full_response = response[0]['generated_text']
202
- generated_part = full_response[len(prompt):].strip()
203
-
204
- # Clean up response
205
- if generated_part:
206
- lines = generated_part.split('\n')
207
- arabic_lines = []
208
- for line in lines:
209
- if line.strip() and any('\u0600' <= c <= '\u06FF' for c in line):
210
- arabic_lines.append(line.strip())
211
- elif line.strip() and not any(c.isalpha() for c in line):
212
- arabic_lines.append(line.strip())
213
-
214
- final_response = '\n'.join(arabic_lines[:5])
215
-
216
- if not final_response:
217
- final_response = "عذراً، صار في مشكلة بالنظام. جرب مرة تانية."
218
- else:
219
- final_response = "عذراً، ما قدرت أفهم طلبك. ممكن تعيد صياغته؟"
220
-
221
- return final_response, json.dumps(entities, ensure_ascii=False), json.dumps(relevant_listings, ensure_ascii=False)
222
-
223
- except Exception as e:
224
- return f"❌ Error: {str(e)}", "{}", "[]"
225
-
226
- def chatbot_interface(message: str) -> tuple:
227
- """Gradio interface function"""
228
- response, entities, listings = generate_response(message)
229
- return response, entities, listings
230
 
231
- # Create Gradio app
232
- with gr.Blocks(title="Damascus Real Estate - Falcon 7B") as demo:
233
- gr.Markdown("# 🏠 Damascus Real Estate Chatbot")
234
- gr.Markdown("### Powered by Falcon 7B Instruct - Syrian Arabic Dialect")
235
- gr.Markdown("Ask about apartments in Damascus in Arabic!")
236
-
237
  with gr.Row():
238
  with gr.Column(scale=2):
239
- user_input = gr.Textbox(
240
- label="سؤالك بالعربي (Your Question in Arabic)",
241
- placeholder="مثال: بدي شقة مفروشة بالمالكي مع شرفة",
242
- lines=2
243
- )
244
- submit_btn = gr.Button("🔍 ابحث (Search)", variant="primary")
245
-
246
- with gr.Column(scale=3):
247
- # FIXED: Changed gr.Textbook to gr.Textbox
248
- chatbot_response = gr.Textbox(
249
- label="🤖 رد الوكيل العقاري (Real Estate Agent Response)",
250
- lines=6
251
- )
252
-
253
- with gr.Row():
254
- with gr.Column():
255
- extracted_entities = gr.Textbox(
256
- label="📋 المتطلبات المستخرجة (Extracted Requirements)",
257
- lines=3
258
- )
259
- with gr.Column():
260
- matched_listings = gr.Textbox(
261
- label="🏠 الشقق المطابقة (Matched Properties)",
262
- lines=3
263
- )
264
-
265
- # Example queries
266
- gr.Markdown("### أمثلة (Examples):")
267
- examples = [
268
- "بدي شقة مفروشة بالمالكي مع شرفة واسعة",
269
- "في شي ستوديو باب شرقي مفروش؟",
270
- "بدي شقة ثلاث غرف فارغة بالمزة",
271
- "شو عندك بالشعلان مفروش؟",
272
- "بدي شقة رخيصة مع مكيف"
273
- ]
274
 
275
- for example in examples:
276
- gr.Button(example).click(
277
- lambda x=example: x,
278
- outputs=user_input
279
- )
280
 
281
- # Event handlers
282
- submit_btn.click(
283
- chatbot_interface,
284
- inputs=user_input,
285
- outputs=[chatbot_response, extracted_entities, matched_listings]
286
- )
287
-
288
- user_input.submit(
289
- chatbot_interface,
290
- inputs=user_input,
291
- outputs=[chatbot_response, extracted_entities, matched_listings]
292
- )
293
 
294
- if __name__ == "__main__":
295
- demo.launch()
 
 
 
 
 
 
1
  import gradio as gr
2
  import torch
3
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
 
 
4
 
5
+ # ------------------------------
6
  # Configuration
7
+ # ------------------------------
8
  MODEL_NAME = "tiiuae/falcon-7b-instruct"
9
  MAX_LENGTH = 500
10
  TEMPERATURE = 0.7
11
 
12
  print("🚀 Loading Falcon 7B for Damascus Real Estate...")
13
 
14
+ # ------------------------------
15
  # Load model and tokenizer
16
+ # ------------------------------
17
  try:
18
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
 
 
19
  model = AutoModelForCausalLM.from_pretrained(
20
  MODEL_NAME,
21
  torch_dtype=torch.float16,
 
38
  generator = None
39
  model_loaded = False
40
 
41
+ # ------------------------------
42
+ # Test Questions (Pre-Filled)
43
+ # ------------------------------
44
+ test_questions = [
45
+ "بدي شقة بالمالكي فيها شرفة وغسالة صحون.",
46
+ "هل في شقة دوبلكس بالمزة الفيلات فيها موقفين سيارة؟",
47
+ "بدي بيت عربي قديم بباب توما مع حديقة داخلية.",
48
+ "أرخص شقة بالشعلان شو سعرها؟",
49
+ "هل يوجد شقق بإطلالة جبلية في أبو رمانة؟",
50
+ "بدي شقة مفروشة بالكامل بالمزة ٨٦، الطابق الأول.",
51
+ "عندك منزل مستقل بالمهاجرين مع موقد حطب؟"
 
52
  ]
53
 
54
+ # ------------------------------
55
+ # Falcon Chat Function
56
+ # ------------------------------
57
+ def chat_falcon(user_input):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  if not model_loaded:
59
+ return "❌ النموذج غير محمل. تحقق من الإعدادات."
60
+ prompt = f"السؤال: {user_input}\nالجواب:"
61
+ output = generator(
62
+ prompt,
63
+ max_new_tokens=MAX_LENGTH,
64
+ do_sample=True,
65
+ temperature=TEMPERATURE
66
+ )[0]["generated_text"]
67
+ return output
68
+
69
+ # ------------------------------
70
+ # Build Gradio Interface
71
+ # ------------------------------
72
+ with gr.Blocks() as demo:
73
+ gr.Markdown("## 🏠 Falcon 7B - Damascus Real Estate Test")
74
+ gr.Markdown("اختبر قدرة النموذج على فهم الأسئلة بالعربية (لهجة سورية أو فصحى)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
 
 
 
 
 
 
76
  with gr.Row():
77
  with gr.Column(scale=2):
78
+ user_input = gr.Textbox(label="اكتب سؤالك هنا", lines=3, placeholder="مثال: بدي شقة بالمزة فيها بلكون")
79
+ submit_btn = gr.Button("🔎 أرسل")
80
+ with gr.Column(scale=1):
81
+ suggestions = gr.Dropdown(choices=test_questions, label="🧾 أسئلة جاهزة", value=test_questions[0])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
+ output_box = gr.Textbox(label="إجابة النموذج", lines=8)
 
 
 
 
84
 
85
+ submit_btn.click(fn=chat_falcon, inputs=user_input, outputs=output_box)
86
+ suggestions.change(fn=chat_falcon, inputs=suggestions, outputs=output_box)
 
 
 
 
 
 
 
 
 
 
87
 
88
+ demo.launch(share=True)