YussefGAFeer commited on
Commit
f63af94
·
verified ·
1 Parent(s): 1af5396

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +215 -0
app.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
3
+ import torch
4
+ import gc
5
+
6
+ # =============================================================================
7
+ # إعداد النموذج (يحمّل مرة واحدة فقط عند بدء الخادم)
8
+ # =============================================================================
9
+
10
+ MODEL_ID = "WeiboAI/VibeThinker-1.5B"
11
+
12
+ print(f"✅ [إعداد]: جاري تحميل النموذج {MODEL_ID}...")
13
+ print(" - هذا قد يستغرق 1-3 دقائق أول مرة...")
14
+
15
+ try:
16
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
17
+ model = AutoModelForCausalLM.from_pretrained(
18
+ MODEL_ID,
19
+ torch_dtype=torch.bfloat16,
20
+ device_map="auto",
21
+ low_cpu_mem_usage=True,
22
+ trust_remote_code=True
23
+ )
24
+ print("✅ [جاهز]: تم تحميل النموذج بنجاح!")
25
+ except Exception as e:
26
+ print(f"❌ [خطأ]: فشل تحميل النموذج: {e}")
27
+ raise
28
+
29
+ # =============================================================================
30
+ # دوال التوليد
31
+ # =============================================================================
32
+
33
+ def generate_response(prompt, temperature=0.6, max_tokens=2048):
34
+ """توليد إجابة من النموذج"""
35
+ try:
36
+ messages = [{"role": "user", "content": prompt}]
37
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
38
+ inputs = tokenizer([text], return_tensors="pt").to(model.device)
39
+
40
+ generation_config = {
41
+ "max_new_tokens": max_tokens,
42
+ "do_sample": True,
43
+ "temperature": temperature,
44
+ "top_p": 0.95,
45
+ "top_k": None
46
+ }
47
+
48
+ with torch.no_grad():
49
+ outputs = model.generate(**inputs, generation_config=GenerationConfig(**generation_config))
50
+
51
+ response = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
52
+ # استخراج الإجابة فقط (إزالة Prompt)
53
+ response = response.split("assistant\n")[-1].strip()
54
+
55
+ return response
56
+ except Exception as e:
57
+ return f"❌ حدث خطأ: {str(e)}"
58
+
59
+ def clear_memory():
60
+ """تنظيف الذاكرة"""
61
+ gc.collect()
62
+ torch.cuda.empty_cache()
63
+ return "✅ تم تنظيف الذاكرة"
64
+
65
+ # =============================================================================
66
+ # واجهة Gradio
67
+ # =============================================================================
68
+
69
+ css = """
70
+ /* تنسيق مشابه للـ Colab */
71
+ body { background: linear-gradient(135deg, #1a1a2e, #16213e); color: white; }
72
+ .gradio-container { background: rgba(0,0,0,0.3); border-radius: 15px; }
73
+ """
74
+
75
+ with gr.Blocks(title="VibeThinker API | HF Space", css=css, theme=gr.themes.Soft()) as demo:
76
+
77
+ gr.Markdown("""
78
+ # 🚀 VibeThinker-1.5B API على Hugging Face Space
79
+
80
+ **نموذج التفكير المنطقي والرياضيات من WeiboAI**
81
+
82
+ ⚡ **النموذج**: `WeiboAI/VibeThinker-1.5B`
83
+ 🔗 **المصدر**: [Hugging Face Hub](https://huggingface.co/WeiboAI/VibeThinker-1.5B)
84
+ 📄 **الترخيص**: MIT (مجاني للاستخدام التجاري)
85
+ """)
86
+
87
+ with gr.Row():
88
+ with gr.Column(scale=4):
89
+ chatbot = gr.Chatbot(
90
+ label="💬 محادثة",
91
+ height=500,
92
+ bubble_full_width=False,
93
+ avatar_images=(None, "https://huggingface.co/WeiboAI/VibeThinker-1.5B/resolve/main/logo.png")
94
+ )
95
+
96
+ with gr.Row():
97
+ prompt_input = gr.Textbox(
98
+ label="اكتب سؤالك هنا...",
99
+ placeholder="أدخل مسألة رياضية أو سؤال منطقي...",
100
+ lines=2,
101
+ scale=8
102
+ )
103
+ submit_btn = gr.Button("🚀 إرسال", scale=1, variant="primary")
104
+
105
+ with gr.Accordion("⚙️ إعدادات متقدمة", open=False):
106
+ temperature = gr.Slider(0.1, 1.5, value=0.6, label="Temperature", info="درجة الإبداع")
107
+ max_tokens = gr.Slider(512, 8192, value=2048, label="Max Tokens", info="أقصى طول للإجابة")
108
+ clear_btn = gr.Button("🗑️ مسح الذاكرة", variant="stop")
109
+
110
+ with gr.Column(scale=1):
111
+ gr.Markdown("### 📋 معلومات")
112
+ gr.Markdown("""
113
+ - **سرعة الاستجابة**: ~2-5 ثانية/سؤال
114
+ - **دعم اللغة**: الإنجليزية (المهام الرياضية)
115
+ - **استخدام الذاكرة**: ~4GB VRAM
116
+ """)
117
+
118
+ status_box = gr.Textbox(
119
+ label="حالة النظام",
120
+ value="✅ النموذج جاهز",
121
+ interactive=False
122
+ )
123
+
124
+ # =============================================================================
125
+ # أحداث التحكم
126
+ # =============================================================================
127
+
128
+ def chat_function(message, history, temp, max_tok):
129
+ """معالجة المحادثة"""
130
+ # بناء السياق من المحادثة السابقة
131
+ full_prompt = ""
132
+ for human, assistant in history:
133
+ full_prompt += f"Human: {human}\nAssistant: {assistant}\n"
134
+ full_prompt += f"Human: {message}\nAssistant: "
135
+
136
+ response = generate_response(full_prompt, temp, max_tok)
137
+ return response
138
+
139
+ def handle_submit(prompt, history, temp, max_tok):
140
+ """معالجة إرسال السؤال"""
141
+ if not prompt.strip():
142
+ return "", history
143
+
144
+ # إضافة السؤال للمحادثة
145
+ history.append([prompt, None])
146
+
147
+ # توليد الإجابة
148
+ response = chat_function(prompt, history[:-1], temp, max_tok)
149
+
150
+ # تحديث المحادثة بالإجابة
151
+ history[-1][1] = response
152
+
153
+ # تنظيف الذاكرة بعد كل استجابة
154
+ clear_memory()
155
+
156
+ return "", history
157
+
158
+ # ربط الأحداث
159
+ submit_btn.click(
160
+ handle_submit,
161
+ inputs=[prompt_input, chatbot, temperature, max_tokens],
162
+ outputs=[prompt_input, chatbot]
163
+ )
164
+
165
+ prompt_input.submit(
166
+ handle_submit,
167
+ inputs=[prompt_input, chatbot, temperature, max_tokens],
168
+ outputs=[prompt_input, chatbot]
169
+ )
170
+
171
+ clear_btn.click(
172
+ clear_memory,
173
+ outputs=[status_box]
174
+ )
175
+
176
+ # =============================================================================
177
+ # معلومات مخصصة لـ API
178
+ # =============================================================================
179
+
180
+ gr.Markdown("""
181
+ ---
182
+ ### 🔌 **استخدام كـ API**
183
+
184
+ يمكنك استخدام هذا Space كـ API خارجي:
185
+
186
+ **Endpoint**: `https://YOUR-SPACE-NAME.hf.space/v1/chat/completions`
187
+
188
+ **Headers**:
189
+ ```json
190
+ {
191
+ "Content-Type": "application/json"
192
+ }
193
+ ```
194
+
195
+ **Body**:
196
+ ```json
197
+ {
198
+ "model": "VibeThinker-1.5B",
199
+ "messages": [{"role": "user", "content": "مسألتك"}],
200
+ "temperature": 0.6
201
+ }
202
+ ```
203
+ """)
204
+
205
+ # =============================================================================
206
+ # تشغيل التطبيق
207
+ # =============================================================================
208
+
209
+ demo.queue(max_size=20).launch(
210
+ server_name="0.0.0.0",
211
+ server_port=7860,
212
+ share=False, # لا تحتاج لـ share لأن Space عام
213
+ show_api=True, # إظهار وثائق API تلقائياً
214
+ show_error=True
215
+ )