ahmadbeilouni commited on
Commit
00e87e2
·
verified ·
1 Parent(s): 7bd4818

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -33
app.py CHANGED
@@ -1,43 +1,65 @@
 
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-H1-7B-Instruct"
9
- MAX_LENGTH = 120 # safer than 50
 
 
10
  TEMPERATURE = 0.3
11
  REPETITION_PENALTY = 1.8
12
 
13
- print("🚀 Loading Falcon 7B Arabic Instruct...")
14
 
15
- # ------------------------------
16
- # Load model and tokenizer
17
- # ------------------------------
 
18
  try:
19
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
 
 
 
 
 
 
 
 
 
 
 
 
20
  model = AutoModelForCausalLM.from_pretrained(
21
- MODEL_NAME,
22
  torch_dtype=torch.float16,
 
23
  device_map="auto",
24
- trust_remote_code=True
25
  )
26
-
27
- print("✅ Falcon 7B Arabic model loaded successfully")
28
- model_loaded = True
29
 
30
- print("✅ Falcon 7B Arabic model loaded successfully")
 
 
 
 
 
 
 
31
  model_loaded = True
32
-
33
  except Exception as e:
34
  print(f"❌ Model loading failed: {e}")
35
  generator = None
36
  model_loaded = False
37
 
38
- # ------------------------------
39
  # Test Questions (Pre-Filled)
40
- # ------------------------------
41
  test_questions = [
42
  "بدي شقة بالمالكي فيها شرفة وغسالة صحون.",
43
  "هل في شقة دوبلكس بالمزة الفيلات فيها موقفين سيارة؟",
@@ -48,14 +70,13 @@ test_questions = [
48
  "عندك منزل مستقل بالمهاجرين مع موقد حطب؟"
49
  ]
50
 
51
- # ------------------------------
52
  # Falcon Chat Function
53
- # ------------------------------
54
  def chat_falcon(user_input):
55
  if not model_loaded:
56
  return "❌ النموذج غير محمل. تحقق من الإعدادات."
57
-
58
- # Structured prompt for clarity
59
  prompt = f"أنت مساعد عقارات ذكي. أجب بجملة أو جملتين واضحتين.\nالسؤال: {user_input}\nالجواب:"
60
 
61
  output = generator(
@@ -66,16 +87,14 @@ def chat_falcon(user_input):
66
  repetition_penalty=REPETITION_PENALTY,
67
  top_p=0.9
68
  )[0]["generated_text"]
69
-
70
- # Strip the prompt part from the output
71
- cleaned_output = output.replace(prompt, "").strip()
72
- return cleaned_output
73
 
74
- # ------------------------------
 
 
75
  # Build Gradio Interface
76
- # ------------------------------
77
  with gr.Blocks() as demo:
78
- gr.Markdown("## 🏠 Falcon 7B Arabic Instruct - Damascus Real Estate Test")
79
  gr.Markdown("اختبر قدرة النموذج على فهم الأسئلة بالعربية (لهجة سورية أو فصحى)")
80
 
81
  with gr.Row():
@@ -84,10 +103,10 @@ with gr.Blocks() as demo:
84
  submit_btn = gr.Button("🔎 أرسل")
85
  with gr.Column(scale=1):
86
  suggestions = gr.Dropdown(choices=test_questions, label="🧾 أسئلة جاهزة", value=test_questions[0])
87
-
88
  output_box = gr.Textbox(label="إجابة النموذج", lines=8)
89
-
90
  submit_btn.click(fn=chat_falcon, inputs=user_input, outputs=output_box)
91
  suggestions.change(fn=chat_falcon, inputs=suggestions, outputs=output_box)
92
 
93
- demo.launch(share=True)
 
1
+ import os
2
  import gradio as gr
3
  import torch
4
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
5
+ from huggingface_hub import snapshot_download
6
 
7
+ # ================================
8
+ # CONFIGURATION
9
+ # ================================
10
+ MODEL_NAME_PRIMARY = "tiiuae/Falcon-H1-7B-Instruct"
11
+ MODEL_NAME_FALLBACK = "tiiuae/falcon-7b-instruct"
12
+ MODEL_LOCAL_DIR = "./falcon_model"
13
+ MAX_LENGTH = 120
14
  TEMPERATURE = 0.3
15
  REPETITION_PENALTY = 1.8
16
 
17
+ print("🚀 Preparing environment...")
18
 
19
+ # 1️⃣ Upgrade transformers & accelerate
20
+ os.system("pip install --upgrade transformers accelerate > /dev/null")
21
+
22
+ # 2️⃣ Ensure clean download of model
23
  try:
24
+ print(f"⬇️ Downloading model: {MODEL_NAME_PRIMARY}")
25
+ snapshot_download(MODEL_NAME_PRIMARY, local_dir=MODEL_LOCAL_DIR, force_download=True)
26
+ model_name = MODEL_LOCAL_DIR
27
+ except Exception as e:
28
+ print(f"⚠️ Primary model download failed: {e}")
29
+ print("➡️ Falling back to Falcon 7B Instruct")
30
+ snapshot_download(MODEL_NAME_FALLBACK, local_dir=MODEL_LOCAL_DIR, force_download=True)
31
+ model_name = MODEL_LOCAL_DIR
32
+
33
+ # 3️⃣ Load tokenizer and model
34
+ try:
35
+ print("🔄 Loading tokenizer and model...")
36
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
37
  model = AutoModelForCausalLM.from_pretrained(
38
+ model_name,
39
  torch_dtype=torch.float16,
40
+ trust_remote_code=True,
41
  device_map="auto",
42
+ low_cpu_mem_usage=True
43
  )
 
 
 
44
 
45
+ generator = pipeline(
46
+ "text-generation",
47
+ model=model,
48
+ tokenizer=tokenizer,
49
+ torch_dtype=torch.float16,
50
+ device=0 if torch.cuda.is_available() else -1
51
+ )
52
+ print("✅ Model loaded successfully")
53
  model_loaded = True
54
+
55
  except Exception as e:
56
  print(f"❌ Model loading failed: {e}")
57
  generator = None
58
  model_loaded = False
59
 
60
+ # ================================
61
  # Test Questions (Pre-Filled)
62
+ # ================================
63
  test_questions = [
64
  "بدي شقة بالمالكي فيها شرفة وغسالة صحون.",
65
  "هل في شقة دوبلكس بالمزة الفيلات فيها موقفين سيارة؟",
 
70
  "عندك منزل مستقل بالمهاجرين مع موقد حطب؟"
71
  ]
72
 
73
+ # ================================
74
  # Falcon Chat Function
75
+ # ================================
76
  def chat_falcon(user_input):
77
  if not model_loaded:
78
  return "❌ النموذج غير محمل. تحقق من الإعدادات."
79
+
 
80
  prompt = f"أنت مساعد عقارات ذكي. أجب بجملة أو جملتين واضحتين.\nالسؤال: {user_input}\nالجواب:"
81
 
82
  output = generator(
 
87
  repetition_penalty=REPETITION_PENALTY,
88
  top_p=0.9
89
  )[0]["generated_text"]
 
 
 
 
90
 
91
+ return output.replace(prompt, "").strip()
92
+
93
+ # ================================
94
  # Build Gradio Interface
95
+ # ================================
96
  with gr.Blocks() as demo:
97
+ gr.Markdown("## 🏠 Falcon H1 7B Instruct - Damascus Real Estate Test")
98
  gr.Markdown("اختبر قدرة النموذج على فهم الأسئلة بالعربية (لهجة سورية أو فصحى)")
99
 
100
  with gr.Row():
 
103
  submit_btn = gr.Button("🔎 أرسل")
104
  with gr.Column(scale=1):
105
  suggestions = gr.Dropdown(choices=test_questions, label="🧾 أسئلة جاهزة", value=test_questions[0])
106
+
107
  output_box = gr.Textbox(label="إجابة النموذج", lines=8)
108
+
109
  submit_btn.click(fn=chat_falcon, inputs=user_input, outputs=output_box)
110
  suggestions.change(fn=chat_falcon, inputs=suggestions, outputs=output_box)
111
 
112
+ demo.launch()