Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,69 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
""
|
| 15 |
-
|
| 16 |
-
"""
|
| 17 |
-
client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
|
| 18 |
-
|
| 19 |
-
messages = [{"role": "system", "content": system_message}]
|
| 20 |
-
|
| 21 |
-
messages.extend(history)
|
| 22 |
-
|
| 23 |
-
messages.append({"role": "user", "content": message})
|
| 24 |
-
|
| 25 |
-
response = ""
|
| 26 |
-
|
| 27 |
-
for message in client.chat_completion(
|
| 28 |
-
messages,
|
| 29 |
-
max_tokens=max_tokens,
|
| 30 |
-
stream=True,
|
| 31 |
-
temperature=temperature,
|
| 32 |
-
top_p=top_p,
|
| 33 |
-
):
|
| 34 |
-
choices = message.choices
|
| 35 |
-
token = ""
|
| 36 |
-
if len(choices) and choices[0].delta.content:
|
| 37 |
-
token = choices[0].delta.content
|
| 38 |
-
|
| 39 |
-
response += token
|
| 40 |
-
yield response
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
"""
|
| 44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
| 45 |
-
"""
|
| 46 |
-
chatbot = gr.ChatInterface(
|
| 47 |
-
respond,
|
| 48 |
-
additional_inputs=[
|
| 49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 52 |
-
gr.Slider(
|
| 53 |
-
minimum=0.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
if __name__ == "__main__":
|
| 69 |
demo.launch()
|
|
|
|
|
|
| 1 |
+
#basic code to play around with the api:
|
| 2 |
+
|
| 3 |
+
from openai import OpenAI
|
| 4 |
import gradio as gr
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 7 |
+
from openai import OpenAI
|
| 8 |
+
|
| 9 |
+
# ==========================================
|
| 10 |
+
# 1. تحميل نموذج Qwen3 محلياً داخل السبيس
|
| 11 |
+
# ==========================================
|
| 12 |
+
print("⏳ loading Qwen .....")
|
| 13 |
+
model_name = "Qwen/Qwen3-0.6B"
|
| 14 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 15 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 16 |
+
model_name,
|
| 17 |
+
torch_dtype="auto",
|
| 18 |
+
device_map="auto"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
)
|
| 20 |
|
| 21 |
+
# تحديد الشخصية الثابتة للبوت
|
| 22 |
+
SYSTEM_PROMPT = """You are a smart, friendly assistant who answers concisely and accurately.
|
| 23 |
+
You can understand questions written in either Arabic or English,
|
| 24 |
+
but you must ALWAYS reply in clear English regardless of the language of the question."""
|
| 25 |
+
|
| 26 |
+
# ==========================================
|
| 27 |
+
# 2. الدالة الأساسية لمعالجة المحادثة
|
| 28 |
+
# ==========================================
|
| 29 |
+
def chat_engine(user_input, chat_history, model_choice, enable_thinking, api_key):
|
| 30 |
+
if not user_input.strip():
|
| 31 |
+
return chat_history, ""
|
| 32 |
+
|
| 33 |
+
# تهيئة الذاكرة التراكمية بصيغة الرسائل (Messages Format)
|
| 34 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 35 |
+
|
| 36 |
+
# تنظيف التاريخ القديم من تاغات الـ HTML قبل إرساله للنموذج لكي لا تختلط عليه الذاكرة
|
| 37 |
+
for user_msg, bot_msg in chat_history:
|
| 38 |
+
messages.append({"role": "user", "content": user_msg})
|
| 39 |
+
clean_bot_msg = bot_msg.split("</details>")[-1].strip() if "</details>" in bot_msg else bot_msg
|
| 40 |
+
messages.append({"role": "assistant", "content": clean_bot_msg})
|
| 41 |
+
|
| 42 |
+
# إضافة السؤال الحالي
|
| 43 |
+
messages.append({"role": "user", "content": user_input})
|
| 44 |
+
|
| 45 |
+
# ------------------------------------------
|
| 46 |
+
# المسار الأول: تشغيل نموذج Qwen3 المحلي
|
| 47 |
+
# ------------------------------------------
|
| 48 |
+
if model_choice == "Qwen/Qwen3-0.6B":
|
| 49 |
+
try:
|
| 50 |
+
# تجهيز التمبلت الخاص بالمحادثة والتفكير
|
| 51 |
+
text = tokenizer.apply_chat_template(
|
| 52 |
+
messages,
|
| 53 |
+
tokenize=False,
|
| 54 |
+
add_generation_prompt=True,
|
| 55 |
+
enable_thinking=enable_thinking
|
| 56 |
+
)
|
| 57 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
| 58 |
+
|
| 59 |
+
# التوليد بحد آمن يناسب السبيس
|
| 60 |
+
generated_ids = model.generate(
|
| 61 |
+
**model_inputs,
|
| 62 |
+
max_new_tokens=1024
|
| 63 |
+
)
|
| 64 |
+
output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
|
| 65 |
+
|
| 66 |
+
if enable_thinking:
|
| 67 |
+
try:
|
| 68 |
+
# البحث عن تاغ إغلاق التفكير 151668 (</think>)
|
| 69 |
+
index = len(output_ids) - output_ids[::-1].index(151668)
|
| 70 |
+
except ValueError:
|
| 71 |
+
index = 0
|
| 72 |
+
|
| 73 |
+
thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
|
| 74 |
+
assistant_content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
|
| 75 |
+
|
| 76 |
+
# صياغة النص بـ Markdown لإظهار التفكير بشكل منسدل أنيق
|
| 77 |
+
if thinking_content:
|
| 78 |
+
final_output = f"<details><summary>🧠 كواليس تفكير النموذج (اضغط للتوسيع)</summary>\n\n{thinking_content}\n\n</details>\n\n{assistant_content}"
|
| 79 |
+
else:
|
| 80 |
+
final_output = assistant_content
|
| 81 |
+
else:
|
| 82 |
+
final_output = tokenizer.decode(output_ids, skip_special_tokens=True).strip("\n")
|
| 83 |
+
except Exception as e:
|
| 84 |
+
final_output = f"❌ خطأ أثناء توليد رد النموذج المحلي:\n{str(e)}"
|
| 85 |
+
|
| 86 |
+
chat_history.append((user_input, final_output))
|
| 87 |
+
return chat_history, ""
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------
|
| 90 |
+
# المسار الثاني: تشغيل GPT-5 عبر الـ API الخارجي
|
| 91 |
+
# ------------------------------------------
|
| 92 |
+
elif model_choice == "GPT-5 (OpenAI API)":
|
| 93 |
+
if not api_key.strip():
|
| 94 |
+
chat_history.append((user_input, "⚠️ الرجاء إدخال مفتاح OpenAI API في خانة الإعدادات لاستخدام GPT-5."))
|
| 95 |
+
return chat_history, ""
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
# إنشاء اتصال مع OpenAI باستخدام الـ API الممرر من الواجهة
|
| 99 |
+
client = OpenAI(api_key=api_key)
|
| 100 |
+
|
| 101 |
+
response = client.chat.completions.create(
|
| 102 |
+
model="gpt-5", # اسم الموديل الخاص بالـ API لديك
|
| 103 |
+
messages=messages,
|
| 104 |
+
max_completion_tokens=4096
|
| 105 |
+
)
|
| 106 |
|
| 107 |
+
gpt_response = response.choices[0].message.content
|
| 108 |
+
chat_history.append((user_input, gpt_response))
|
| 109 |
+
except Exception as e:
|
| 110 |
+
chat_history.append((user_input, f"❌ connecation to API faild :\n{str(e)}"))
|
| 111 |
|
| 112 |
+
return chat_history, ""
|
| 113 |
+
|
| 114 |
+
# ==========================================
|
| 115 |
+
# 3. (Gradio UI Layout)
|
| 116 |
+
# ==========================================
|
| 117 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="slate")) as demo:
|
| 118 |
+
gr.Markdown("# 🤖 Multi Model chat bot (Level 4)")
|
| 119 |
+
gr.Markdown("changing model and thinking mode ")
|
| 120 |
+
|
| 121 |
+
with gr.Row():
|
| 122 |
+
# القائمة الجانبية للتحكم والإعدادات
|
| 123 |
+
with gr.Column(scale=1, min_width=280):
|
| 124 |
+
gr.Markdown("### ⚙️ sting")
|
| 125 |
+
|
| 126 |
+
model_dropdown = gr.Dropdown(
|
| 127 |
+
choices=["Qwen/Qwen3-0.6B", "GPT-5 (OpenAI API)"],
|
| 128 |
+
value="Qwen/Qwen3-0.6B",
|
| 129 |
+
label="choose active model"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
thinking_checkbox = gr.Checkbox(
|
| 133 |
+
label="activate thinking mode (for Qwen)",
|
| 134 |
+
value=True
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
api_key_input = gr.Textbox(
|
| 138 |
+
label="OpenAI API Key (لـ GPT-5)",
|
| 139 |
+
placeholder="sk-...",
|
| 140 |
+
type="password"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
clear_button = gr.Button("🧹 clear chat", variant="secondary")
|
| 144 |
+
|
| 145 |
+
# الشاشة الرئيسية للمحادثة
|
| 146 |
+
with gr.Column(scale=4):
|
| 147 |
+
chatbot = gr.Chatbot(
|
| 148 |
+
label="CHAT",
|
| 149 |
+
height=550,
|
| 150 |
+
show_copy_button=True
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
with gr.Row():
|
| 154 |
+
user_msg = gr.Textbox(
|
| 155 |
+
label="ask your question and press ENTER",
|
| 156 |
+
placeholder="What do yiu want for christmas?",
|
| 157 |
+
scale=4
|
| 158 |
+
)
|
| 159 |
+
submit_button = gr.Button("send🚀", variant="primary", scale=1)
|
| 160 |
+
|
| 161 |
+
# ------------------------------------------
|
| 162 |
+
# ربط العناصر والأحداث (Event Handling)
|
| 163 |
+
# ------------------------------------------
|
| 164 |
+
|
| 165 |
+
# التفاعل عند الضغط على زر إرسال أو Enter
|
| 166 |
+
submit_event = submit_button.click(
|
| 167 |
+
chat_engine,
|
| 168 |
+
inputs=[user_msg, chatbot, model_dropdown, thinking_checkbox, api_key_input],
|
| 169 |
+
outputs=[chatbot, user_msg]
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
user_msg.submit(
|
| 173 |
+
chat_engine,
|
| 174 |
+
inputs=[user_msg, chatbot, model_dropdown, thinking_checkbox, api_key_input],
|
| 175 |
+
outputs=[chatbot, user_msg]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# تفاعل زر مسح الذاكرة
|
| 179 |
+
clear_button.click(
|
| 180 |
+
fn=lambda: [],
|
| 181 |
+
inputs=None,
|
| 182 |
+
outputs=chatbot,
|
| 183 |
+
queue=False
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# تشغيل التطبيق
|
| 187 |
if __name__ == "__main__":
|
| 188 |
demo.launch()
|
| 189 |
+
|