import gradio as gr from huggingface_hub import hf_hub_download from llama_cpp import Llama # 1. إعدادات النموذج # ⚠️ لا تنسَ تغيير USERNAME إلى اسم حسابك الفعلي في Hugging Face REPO_ID = "aab20abdullah/Llama-3.2-3B-Turkmen-GGUF" # هذا هو الاسم الصحيح الذي قمت بإحضاره: FILENAME = "Llama-3.2-3B-Instruct.Q4_K_M.gguf" # 2. تحميل ملف النموذج من المستودع إلى سيرفر الـ Space print("⏳ جاري تحميل النموذج... قد يستغرق هذا بضع دقائق في المرة الأولى.") model_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME) # 3. تشغيل النموذج عبر Llama.cpp llm = Llama( model_path=model_path, n_ctx=2048, # طول السياق (الذاكرة المؤقتة للمحادثة) n_threads=2, # عدد مسارات المعالج (مناسب للنسخة المجانية) ) # 4. دالة الدردشة وتنسيق Llama-3 def chat_with_model(message, history): # بناء قالب Llama-3.2 prompt = "<|begin_of_text|>" # إضافة المحادثات السابقة للذاكرة for user_msg, bot_msg in history: prompt += f"<|start_header_id|>user<|end_header_id|>\n\n{user_msg}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n{bot_msg}<|eot_id|>" # إضافة السؤال الجديد prompt += f"<|start_header_id|>user<|end_header_id|>\n\n{message}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n" # توليد الإجابة stream = llm( prompt, max_tokens=512, stop=["<|eot_id|>"], stream=True # تفعيل ظهور الكلمات تباعاً ) response = "" for output in stream: response += output['choices'][0]['text'] yield response # 5. تصميم واجهة الويب demo = gr.ChatInterface( fn=chat_with_model, title="🕊️ Llama-3.2-3B Turkmen Martyrs", description="مرحباً بك! يمكنك سؤالي عن الشهداء التركمان وسأقوم بإجابتك بالتفاصيل. (النموذج يعمل بصيغة GGUF الخفيفة).", examples=["حدثني عن الشهيد التركماني أحمد.", "من هم أبرز الشهداء التركمان في كركوك؟"], theme="soft", ) # تشغيل التطبيق if __name__ == "__main__": demo.launch()