rahimdzx commited on
Commit
d761522
·
verified ·
1 Parent(s): 9200d3c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -98
app.py CHANGED
@@ -1,121 +1,62 @@
1
  import gradio as gr
2
- from llama_cpp import Llama
 
3
 
4
- print("⏳ جاري تحميل النموذج...")
5
- llm = Llama.from_pretrained(
6
- repo_id="rahimdzx/AraCode-7B-GGUF",
7
- filename="aracode-7b.Q4_K_M.gguf",
8
- n_ctx=2048,
9
- n_threads=4,
10
- n_gpu_layers=0,
11
- verbose=False,
12
- )
13
- print("✅ تم تحميل النموذج!")
14
-
15
- SYSTEM = """أنت AraCode، مساعد برمجي ذكي متخصص في اللغة العربية.
16
- تساعد المطورين العرب في كتابة وشرح وتصحيح الكود.
17
- تفكر خطوة بخطوة وتقدم كوداً نظيفاً وقابلاً للتنفيذ."""
18
 
 
19
 
20
  def chat(message, history, temperature, max_tokens):
21
- # تحويل history من gradio 6 (list of dicts) لـ messages
22
- messages = [{"role": "system", "content": SYSTEM}]
23
  for item in history:
24
- messages.append({"role": item["role"], "content": item["content"]})
25
- messages.append({"role": "user", "content": message})
26
-
27
- partial = ""
28
  try:
29
- stream = llm.create_chat_completion(
30
- messages=messages,
31
- max_tokens=int(max_tokens),
32
- temperature=float(temperature),
33
- stream=True,
34
- stop=["<|im_end|>", "<|endoftext|>"],
35
- )
36
- for chunk in stream:
37
- delta = chunk["choices"][0]["delta"]
38
- if "content" in delta and delta["content"]:
39
- partial += delta["content"]
40
- yield partial
41
  except Exception as e:
42
- yield f"❌ خطأ: {str(e)}"
43
-
44
 
45
  with gr.Blocks(title="AraCode-7B", theme=gr.themes.Soft()) as demo:
46
- gr.HTML("""
47
- <div style='text-align:center; padding:15px;'>
48
- <h1>🐪 AraCode-7B</h1>
49
- <p style='color:#555; font-size:16px;'>أول مساعد برمجي ذكي متخصص باللغة العربية</p>
50
- <div style='display:flex; justify-content:center; gap:8px; flex-wrap:wrap;'>
51
- <span style='background:#e8f4fd; padding:4px 10px; border-radius:15px; font-size:13px;'>✅ يشرح الكود</span>
52
- <span style='background:#e8f4fd; padding:4px 10px; border-radius:15px; font-size:13px;'>✅ يولد كود</span>
53
- <span style='background:#e8f4fd; padding:4px 10px; border-radius:15px; font-size:13px;'>✅ يصحح الأخطاء</span>
54
- <span style='background:#e8f4fd; padding:4px 10px; border-radius:15px; font-size:13px;'>✅ Apache 2.0</span>
55
- </div>
56
- </div>
57
- """)
58
-
59
  with gr.Row():
60
  with gr.Column(scale=4):
61
- chatbot = gr.Chatbot(
62
- height=480,
63
- show_copy_button=True,
64
- avatar_images=("👤", "🐪"),
65
- type="messages", # gradio 6 يستخدم type="messages"
66
- rtl=True,
67
- )
68
- msg = gr.Textbox(
69
- placeholder="اكتب سؤالك البرمجي هنا...",
70
- label="سؤالك", lines=2,
71
- )
72
  with gr.Row():
73
  send = gr.Button("إرسال 🚀", variant="primary")
74
  clear = gr.Button("🗑️ مسح")
75
-
76
  with gr.Column(scale=1):
77
- gr.Markdown("### ⚙️ الإعدادات")
78
- temperature = gr.Slider(0.1, 1.0, 0.3, step=0.1, label="الإبداع",
79
- info="أقل = أدق | أكثر = إبداعي")
80
  max_tokens = gr.Slider(128, 1024, 512, step=128, label="طول الرد")
81
- gr.Markdown("---")
82
- gr.Markdown("""
83
- ### 📊 النموذج
84
- - **AraCode-7B Q4_K_M**
85
- - عربي + إنجليزي
86
- - Apache 2.0
87
-
88
- 🔗 [النموذج](https://huggingface.co/rahimdzx/AraCode-7B-GGUF)
89
- 💻 [GitHub](https://github.com/Rahimdzx/AraCode-7B)
90
- """)
91
-
92
  gr.Examples([
93
- ["اكتب دالة بايثون للبحث الثنائي مع شرح"],
94
- ["ما الفرق بين list و tuple في بايثون؟"],
95
  ["اكتب API بسيط بـ Flask"],
96
- ["اشرح مفهوم Recursion بمثال"],
97
- ["كيف أصحح: IndexError: list index out of range"],
98
  ], inputs=msg)
99
 
100
- def submit(message, history):
101
- if not message.strip():
102
- return "", history
103
- history = history + [{"role": "user", "content": message}]
104
- return "", history
105
-
106
- def respond(history, temp, tokens):
107
- if not history:
108
- return history
109
- user_msg = history[-1]["content"]
110
- history = history + [{"role": "assistant", "content": ""}]
111
- for chunk in chat(user_msg, history[:-1], temp, tokens):
112
- history[-1]["content"] = chunk
113
- yield history
114
-
115
- msg.submit(submit, [msg, chatbot], [msg, chatbot]).then(
116
- respond, [chatbot, temperature, max_tokens], chatbot)
117
- send.click(submit, [msg, chatbot], [msg, chatbot]).then(
118
- respond, [chatbot, temperature, max_tokens], chatbot)
119
- clear.click(lambda: [], None, chatbot)
120
 
121
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import gradio as gr
2
+ import requests
3
+ import os
4
 
5
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
6
+ API_URL = "https://api-inference.huggingface.co/models/rahimdzx/AraCode-7B-Full"
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ SYSTEM = "أنت AraCode، مساعد برمجي ذكي باللغة العربية. تشرح وتكتب وتصحح الكود بدقة."
9
 
10
  def chat(message, history, temperature, max_tokens):
11
+ prompt = f"<|im_start|>system\n{SYSTEM}<|im_end|>\n"
 
12
  for item in history:
13
+ prompt += f"<|im_start|>{item['role']}\n{item['content']}<|im_end|>\n"
14
+ prompt += f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
15
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
 
16
  try:
17
+ r = requests.post(API_URL, headers=headers, json={
18
+ "inputs": prompt,
19
+ "parameters": {"max_new_tokens": int(max_tokens), "temperature": float(temperature), "return_full_text": False}
20
+ }, timeout=60)
21
+ if r.status_code == 200:
22
+ result = r.json()
23
+ yield result[0].get("generated_text", "لا يوجد رد") if isinstance(result, list) else str(result)
24
+ elif r.status_code == 503:
25
+ yield "⏳ النموذج يستيقظ... أعد المحاولة بعد 30 ثانية"
26
+ else:
27
+ yield f"❌ خطأ {r.status_code}"
 
28
  except Exception as e:
29
+ yield f"❌ {str(e)}"
 
30
 
31
  with gr.Blocks(title="AraCode-7B", theme=gr.themes.Soft()) as demo:
32
+ gr.HTML("<h1 style='text-align:center'>🐪 AraCode-7B — مساعد البرمجة العربي</h1>")
 
 
 
 
 
 
 
 
 
 
 
 
33
  with gr.Row():
34
  with gr.Column(scale=4):
35
+ chatbot = gr.Chatbot(height=480, type="messages", rtl=True, show_copy_button=True)
36
+ msg = gr.Textbox(placeholder="اكتب سؤالك هنا...", lines=2)
 
 
 
 
 
 
 
 
 
37
  with gr.Row():
38
  send = gr.Button("إرسال 🚀", variant="primary")
39
  clear = gr.Button("🗑️ مسح")
 
40
  with gr.Column(scale=1):
41
+ temperature = gr.Slider(0.1, 1.0, 0.3, step=0.1, label="الإبداع")
 
 
42
  max_tokens = gr.Slider(128, 1024, 512, step=128, label="طول الرد")
43
+ gr.Markdown("🔗 [النموذج](https://huggingface.co/rahimdzx/AraCode-7B-Full)")
 
 
 
 
 
 
 
 
 
 
44
  gr.Examples([
45
+ ["اكتب دالة بايثون للبحث الثنائي"],
46
+ ["ما الفرق بين list و tuple؟"],
47
  ["اكتب API بسيط بـ Flask"],
 
 
48
  ], inputs=msg)
49
 
50
+ def submit(m, h): return "", h + [{"role":"user","content":m}]
51
+ def respond(h, t, k):
52
+ if not h: return h
53
+ h = h + [{"role":"assistant","content":""}]
54
+ for c in chat(h[-2]["content"], h[:-1], t, k):
55
+ h[-1]["content"] = c
56
+ yield h
57
+
58
+ msg.submit(submit,[msg,chatbot],[msg,chatbot]).then(respond,[chatbot,temperature,max_tokens],chatbot)
59
+ send.click(submit,[msg,chatbot],[msg,chatbot]).then(respond,[chatbot,temperature,max_tokens],chatbot)
60
+ clear.click(lambda:[],None,chatbot)
 
 
 
 
 
 
 
 
 
61
 
62
  demo.launch(server_name="0.0.0.0", server_port=7860)