| import gradio as gr |
| import requests |
| import os |
|
|
| HF_TOKEN = os.environ.get("HF_TOKEN", "") |
| API_URL = "https://api-inference.huggingface.co/models/rahimdzx/AraCode-7B-Full" |
|
|
| SYSTEM = "أنت AraCode، مساعد برمجي ذكي باللغة العربية. تشرح وتكتب وتصحح الكود بدقة." |
|
|
| def chat(message, history, temperature, max_tokens): |
| prompt = f"<|im_start|>system\n{SYSTEM}<|im_end|>\n" |
| for item in history: |
| prompt += f"<|im_start|>{item['role']}\n{item['content']}<|im_end|>\n" |
| prompt += f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n" |
| headers = {"Authorization": f"Bearer {HF_TOKEN}"} |
| try: |
| r = requests.post(API_URL, headers=headers, json={ |
| "inputs": prompt, |
| "parameters": {"max_new_tokens": int(max_tokens), "temperature": float(temperature), "return_full_text": False} |
| }, timeout=60) |
| if r.status_code == 200: |
| result = r.json() |
| yield result[0].get("generated_text", "لا يوجد رد") if isinstance(result, list) else str(result) |
| elif r.status_code == 503: |
| yield "⏳ النموذج يستيقظ... أعد المحاولة بعد 30 ثانية" |
| else: |
| yield f"❌ خطأ {r.status_code}" |
| except Exception as e: |
| yield f"❌ {str(e)}" |
|
|
| with gr.Blocks(title="AraCode-7B", theme=gr.themes.Soft()) as demo: |
| gr.HTML("<h1 style='text-align:center'>🐪 AraCode-7B — مساعد البرمجة العربي</h1>") |
| with gr.Row(): |
| with gr.Column(scale=4): |
| chatbot = gr.Chatbot(height=480, type="messages", rtl=True, show_copy_button=True) |
| msg = gr.Textbox(placeholder="اكتب سؤالك هنا...", lines=2) |
| with gr.Row(): |
| send = gr.Button("إرسال 🚀", variant="primary") |
| clear = gr.Button("🗑️ مسح") |
| with gr.Column(scale=1): |
| temperature = gr.Slider(0.1, 1.0, 0.3, step=0.1, label="الإبداع") |
| max_tokens = gr.Slider(128, 1024, 512, step=128, label="طول الرد") |
| gr.Markdown("🔗 [النموذج](https://huggingface.co/rahimdzx/AraCode-7B-Full)") |
| gr.Examples([ |
| ["اكتب دالة بايثون للبحث الثنائي"], |
| ["ما الفرق بين list و tuple؟"], |
| ["اكتب API بسيط بـ Flask"], |
| ], inputs=msg) |
|
|
| def submit(m, h): return "", h + [{"role":"user","content":m}] |
| def respond(h, t, k): |
| if not h: return h |
| h = h + [{"role":"assistant","content":""}] |
| for c in chat(h[-2]["content"], h[:-1], t, k): |
| h[-1]["content"] = c |
| yield h |
|
|
| msg.submit(submit,[msg,chatbot],[msg,chatbot]).then(respond,[chatbot,temperature,max_tokens],chatbot) |
| send.click(submit,[msg,chatbot],[msg,chatbot]).then(respond,[chatbot,temperature,max_tokens],chatbot) |
| clear.click(lambda:[],None,chatbot) |
|
|
| demo.launch(server_name="0.0.0.0", server_port=7860) |