Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,66 +1,101 @@
|
|
| 1 |
-
|
| 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 |
-
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
# 1
|
| 20 |
-
|
| 21 |
-
|
|
|
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
model_name = MODEL_LOCAL_DIR
|
| 28 |
-
except Exception as e:
|
| 29 |
-
print(f"⚠️ Primary model download failed: {e}")
|
| 30 |
-
print("➡️ Falling back to Falcon 7B Instruct")
|
| 31 |
-
snapshot_download(MODEL_NAME_FALLBACK, local_dir=MODEL_LOCAL_DIR, force_download=True)
|
| 32 |
-
model_name = MODEL_LOCAL_DIR
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
)
|
| 53 |
-
print("✅ Model loaded successfully")
|
| 54 |
-
model_loaded = True
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
except Exception as e:
|
| 57 |
-
print(f"
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
test_questions = [
|
| 65 |
"بدي شقة بالمالكي فيها شرفة وغسالة صحون.",
|
| 66 |
"هل في شقة دوبلكس بالمزة الفيلات فيها موقفين سيارة؟",
|
|
@@ -71,43 +106,45 @@ test_questions = [
|
|
| 71 |
"عندك منزل مستقل بالمهاجرين مع موقد حطب؟"
|
| 72 |
]
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
output = generator(
|
| 84 |
prompt,
|
| 85 |
-
max_new_tokens=
|
| 86 |
do_sample=True,
|
| 87 |
temperature=TEMPERATURE,
|
|
|
|
| 88 |
repetition_penalty=REPETITION_PENALTY,
|
| 89 |
-
|
| 90 |
)[0]["generated_text"]
|
| 91 |
|
| 92 |
-
|
|
|
|
| 93 |
|
| 94 |
-
#
|
| 95 |
-
# Build Gradio Interface
|
| 96 |
-
# ================================
|
| 97 |
with gr.Blocks() as demo:
|
| 98 |
-
gr.Markdown("## 🏠 Falcon H1 7B Instruct
|
| 99 |
-
gr.Markdown("اختبر قدرة النموذج على فهم الأسئلة بالعربية (
|
| 100 |
|
| 101 |
with gr.Row():
|
| 102 |
with gr.Column(scale=2):
|
| 103 |
-
|
| 104 |
-
|
| 105 |
with gr.Column(scale=1):
|
| 106 |
-
|
| 107 |
|
| 108 |
-
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
|
| 113 |
-
demo.launch()
|
|
|
|
| 1 |
+
# app.py — Falcon H1 7B Instruct loader + Gradio UI (HF Spaces)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
import os, sys, subprocess
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
# ---- 0) Environment hygiene (Spaces shows "libgomp" warning) ----
|
| 6 |
+
os.environ["OMP_NUM_THREADS"] = "1"
|
| 7 |
+
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" # faster downloads when available
|
| 8 |
|
| 9 |
+
# ---- 1) Upgrade critical deps BEFORE importing transformers ----
|
| 10 |
+
def pipi(cmd: str):
|
| 11 |
+
print(f"[pip] {cmd}")
|
| 12 |
+
subprocess.run([sys.executable, "-m", "pip"] + cmd.split(), check=True)
|
| 13 |
|
| 14 |
+
pipi("install --upgrade pip")
|
| 15 |
+
pipi("install --upgrade --no-cache-dir safetensors>=0.4.5 tokenizers>=0.19.1 accelerate>=0.33.0")
|
| 16 |
+
# Falcon-H1 needs the newest transformers; install from GitHub to be safe (per model card)
|
| 17 |
+
pipi("install --no-cache-dir git+https://github.com/huggingface/transformers.git")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
# ---- 2) Imports AFTER upgrades ----
|
| 20 |
+
import torch
|
| 21 |
+
import gradio as gr
|
| 22 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 23 |
+
from huggingface_hub import snapshot_download
|
| 24 |
+
|
| 25 |
+
# ---- 3) Config ----
|
| 26 |
+
MODEL_NAME_PRIMARY = "tiiuae/Falcon-H1-7B-Instruct"
|
| 27 |
+
MODEL_NAME_FALLBACK = "tiiuae/falcon-7b-instruct" # stable fallback
|
| 28 |
+
MODEL_LOCAL_DIR = "./falcon_local"
|
| 29 |
+
MAX_NEW_TOKENS = 120
|
| 30 |
+
TEMPERATURE = 0.30
|
| 31 |
+
TOP_P = 0.90
|
| 32 |
+
REPETITION_PENALTY = 1.8
|
| 33 |
+
|
| 34 |
+
print("🚀 Preparing model…")
|
| 35 |
+
print("ℹ️ Target primary model:", MODEL_NAME_PRIMARY)
|
| 36 |
+
|
| 37 |
+
# ---- 4) Get a clean local snapshot (avoid corrupted cache) ----
|
| 38 |
+
def get_model_snapshot(repo_id: str, local_dir: str) -> str:
|
| 39 |
+
# allow_patterns keeps it lean; remove if anything’s missing
|
| 40 |
+
return snapshot_download(
|
| 41 |
+
repo_id,
|
| 42 |
+
local_dir=local_dir,
|
| 43 |
+
local_dir_use_symlinks=False,
|
| 44 |
+
force_download=True # ensure fresh download if previous attempt was partial
|
| 45 |
)
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
model_path = None
|
| 48 |
+
primary_ok = True
|
| 49 |
+
try:
|
| 50 |
+
print(f"⬇️ Downloading {MODEL_NAME_PRIMARY} …")
|
| 51 |
+
model_path = get_model_snapshot(MODEL_NAME_PRIMARY, MODEL_LOCAL_DIR)
|
| 52 |
except Exception as e:
|
| 53 |
+
print(f"⚠️ Primary download failed: {e}")
|
| 54 |
+
primary_ok = False
|
| 55 |
+
|
| 56 |
+
if not primary_ok:
|
| 57 |
+
try:
|
| 58 |
+
print(f"➡️ Falling back to {MODEL_NAME_FALLBACK} …")
|
| 59 |
+
model_path = get_model_snapshot(MODEL_NAME_FALLBACK, MODEL_LOCAL_DIR)
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(f"❌ Fallback download failed: {e}")
|
| 62 |
+
model_path = None
|
| 63 |
+
|
| 64 |
+
# ---- 5) Load model/tokenizer ----
|
| 65 |
+
generator = None
|
| 66 |
+
model_loaded = False
|
| 67 |
+
|
| 68 |
+
if model_path:
|
| 69 |
+
try:
|
| 70 |
+
print("🔄 Loading tokenizer & model…")
|
| 71 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
|
| 72 |
+
|
| 73 |
+
# H1 is BF16 on card; FP16 may work but BF16 is safer if hardware supports it.
|
| 74 |
+
dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
|
| 75 |
+
|
| 76 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 77 |
+
model_path,
|
| 78 |
+
torch_dtype=dtype,
|
| 79 |
+
device_map="auto",
|
| 80 |
+
trust_remote_code=True,
|
| 81 |
+
low_cpu_mem_usage=True,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
generator = pipeline(
|
| 85 |
+
"text-generation",
|
| 86 |
+
model=model,
|
| 87 |
+
tokenizer=tokenizer,
|
| 88 |
+
torch_dtype=dtype,
|
| 89 |
+
device=0 if torch.cuda.is_available() else -1
|
| 90 |
+
)
|
| 91 |
+
model_loaded = True
|
| 92 |
+
print("✅ Model loaded successfully")
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"❌ Model loading failed: {e}")
|
| 96 |
+
model_loaded = False
|
| 97 |
+
|
| 98 |
+
# ---- 6) App logic ----
|
| 99 |
test_questions = [
|
| 100 |
"بدي شقة بالمالكي فيها شرفة وغسالة صحون.",
|
| 101 |
"هل في شقة دوبلكس بالمزة الفيلات فيها موقفين سيارة؟",
|
|
|
|
| 106 |
"عندك منزل مستقل بالمهاجرين مع موقد حطب؟"
|
| 107 |
]
|
| 108 |
|
| 109 |
+
def chat_falcon(user_input: str) -> str:
|
| 110 |
+
if not model_loaded or generator is None:
|
| 111 |
+
return "❌ النموذج غير محمّل. الرجاء إعادة المحاولة لاحقاً."
|
| 112 |
+
|
| 113 |
+
# Compact, anchored instruction to reduce looping & keep it on-topic.
|
| 114 |
+
prompt = (
|
| 115 |
+
"أنت مساعد عقارات ذكي. أجب بجملة أو جملتين واضحتين فقط.\n"
|
| 116 |
+
f"السؤال: {user_input}\n"
|
| 117 |
+
"الجواب:"
|
| 118 |
+
)
|
| 119 |
|
| 120 |
+
out = generator(
|
|
|
|
|
|
|
| 121 |
prompt,
|
| 122 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
| 123 |
do_sample=True,
|
| 124 |
temperature=TEMPERATURE,
|
| 125 |
+
top_p=TOP_P,
|
| 126 |
repetition_penalty=REPETITION_PENALTY,
|
| 127 |
+
eos_token_id=generator.tokenizer.eos_token_id
|
| 128 |
)[0]["generated_text"]
|
| 129 |
|
| 130 |
+
# remove prompt echo if present
|
| 131 |
+
return out.replace(prompt, "").strip()
|
| 132 |
|
| 133 |
+
# ---- 7) Gradio UI (no share=True inside Spaces) ----
|
|
|
|
|
|
|
| 134 |
with gr.Blocks() as demo:
|
| 135 |
+
gr.Markdown("## 🏠 Falcon H1 7B Instruct — Damascus Real Estate Test")
|
| 136 |
+
gr.Markdown("اختبر قدرة النموذج على فهم الأسئلة بالعربية (فصحى ولهجة شامية).")
|
| 137 |
|
| 138 |
with gr.Row():
|
| 139 |
with gr.Column(scale=2):
|
| 140 |
+
tb = gr.Textbox(label="اكتب سؤالك هنا", lines=3, placeholder="مثال: بدي شقة بالمزة فيها بلكون")
|
| 141 |
+
btn = gr.Button("🔎 أرسل")
|
| 142 |
with gr.Column(scale=1):
|
| 143 |
+
dd = gr.Dropdown(choices=test_questions, value=test_questions[0], label="🧾 أسئلة جاهزة")
|
| 144 |
|
| 145 |
+
out = gr.Textbox(label="إجابة النموذج", lines=8)
|
| 146 |
|
| 147 |
+
btn.click(chat_falcon, inputs=tb, outputs=out)
|
| 148 |
+
dd.change(chat_falcon, inputs=dd, outputs=out)
|
| 149 |
|
| 150 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|