Spaces:
Running
Running
import os | |
os.system('pip install dashscope') | |
import gradio as gr | |
from http import HTTPStatus | |
import dashscope | |
from dashscope import Generation | |
from dashscope.api_entities.dashscope_response import Role | |
from typing import List, Optional, Tuple, Dict | |
from urllib.error import HTTPError | |
# الإعدادات الافتراضية | |
default_system = 'You are a helpful assistant.' | |
default_temp = 0.7 | |
default_top_p = 0.9 | |
default_max_tokens = 1024 | |
default_max_history = 5 | |
YOUR_API_TOKEN = os.getenv('YOUR_API_TOKEN') | |
dashscope.api_key = YOUR_API_TOKEN | |
# تعريف أنواع البيانات | |
History = List[Tuple[str, str]] | |
Messages = List[Dict[str, str]] | |
def clear_session() -> History: | |
return '', [] | |
def modify_system_session(system: str) -> str: | |
if not system: | |
system = default_system | |
return system, system, [] | |
def history_to_messages(history: History, system: str, max_history: int) -> Messages: | |
# تحديد عدد الرسائل التاريخية المسموح بها | |
if max_history > 0: | |
history = history[-max_history:] | |
messages = [{'role': Role.SYSTEM, 'content': system}] | |
for h in history: | |
messages.append({'role': Role.USER, 'content': h[0]}) | |
messages.append({'role': Role.ASSISTANT, 'content': h[1]}) | |
return messages | |
def messages_to_history(messages: Messages) -> Tuple[str, History]: | |
assert messages[0]['role'] == Role.SYSTEM | |
system = messages[0]['content'] | |
history = [] | |
for q, r in zip(messages[1::2], messages[2::2]): | |
history.append([q['content'], r['content']]) | |
return system, history | |
def model_chat( | |
query: Optional[str], | |
history: Optional[History], | |
system: str, | |
temperature: float, | |
top_p: float, | |
max_tokens: int, | |
max_history: int | |
) -> Tuple[str, str, History]: | |
if not query: | |
query = '' | |
history = history or [] | |
# تحويل التاريخ إلى رسائل مع تطبيق الحد الأقصى | |
messages = history_to_messages(history, system, max_history) | |
messages.append({'role': Role.USER, 'content': query}) | |
try: | |
gen = Generation.call( | |
model="qwen-72b-chat", | |
messages=messages, | |
result_format='message', | |
stream=True, | |
temperature=temperature, | |
top_p=top_p, | |
max_tokens=max_tokens | |
) | |
for response in gen: | |
if response.status_code == HTTPStatus.OK: | |
role = response.output.choices[0].message.role | |
content = response.output.choices[0].message.content | |
system, history = messages_to_history(messages + [{'role': role, 'content': content}]) | |
yield '', history, system | |
else: | |
raise HTTPError(f'Error: {response.code} - {response.message}') | |
except Exception as e: | |
raise gr.Error(f'حدث خطأ في الاتصال: {str(e)}') | |
# واجهة المستخدم | |
with gr.Blocks() as demo: | |
gr.Markdown("""<center><font size=8>Qwen-72B-Chat</center>""") | |
gr.Markdown("""<center><font size=4>نموذج محادثة متقدم بدعم الذاكرة والإعدادات</center>""") | |
# قسم إعدادات النظام | |
with gr.Row(): | |
with gr.Column(scale=3): | |
system_input = gr.Textbox(value=default_system, lines=2, label='تعليمات النظام') | |
gr.Markdown(""" | |
**ملاحظة:** يمكنك كتابة توجيهات خاصة للنموذج هنا. مثال: | |
- "أنت مساعد يتحدث العربية بطلاقة" | |
- "أجب دائمًا بصيغة الشعر" | |
""") | |
with gr.Column(scale=1): | |
modify_system = gr.Button("🛠️ تحديث التعليمات ومسح الذاكرة") | |
system_state = gr.Textbox(value=default_system, visible=False) | |
# عناصر التحكم في النموذج | |
with gr.Accordion("الإعدادات المتقدمة", open=False): | |
with gr.Row(): | |
temperature = gr.Slider(0.0, 2.0, value=default_temp, label="الابتكار (Temperature)") | |
top_p = gr.Slider(0.0, 1.0, value=default_top_p, label="الدقة (Top-P)") | |
with gr.Row(): | |
max_tokens = gr.Number(default_max_tokens, label="الحد الأقصى للرموز") | |
max_history = gr.Number(default_max_history, label="الحد الأقصى للذاكرة (عدد الدورات)") | |
# منطقة المحادثة | |
chatbot = gr.Chatbot(label='المحادثة') | |
textbox = gr.Textbox(lines=2, label='الرسالة') | |
# أزرار التحكم | |
with gr.Row(): | |
clear_history = gr.Button("🧹 مسح المحادثة") | |
submit = gr.Button("🚀 إرسال") | |
# معالجة الأحداث | |
submit.click( | |
model_chat, | |
inputs=[textbox, chatbot, system_state, temperature, top_p, max_tokens, max_history], | |
outputs=[textbox, chatbot, system_input] | |
) | |
clear_history.click( | |
fn=clear_session, | |
inputs=[], | |
outputs=[textbox, chatbot] | |
) | |
modify_system.click( | |
fn=modify_system_session, | |
inputs=[system_input], | |
outputs=[system_state, system_input, chatbot] | |
) | |
# تشغيل التطبيق | |
demo.queue(api_open=False).launch( | |
max_threads=10, | |
height=800, | |
share=False | |
) |