File size: 5,398 Bytes
bbda575
 
 
 
 
 
 
 
 
2ca0144
 
bbda575
2ca0144
 
 
 
bbda575
 
 
 
2ca0144
bbda575
 
 
 
 
 
 
2ca0144
bbda575
 
 
2ca0144
 
 
 
 
bbda575
 
 
 
 
 
 
 
 
 
 
 
 
 
2ca0144
 
 
 
 
 
 
 
bbda575
2ca0144
bbda575
2ca0144
 
 
 
bbda575
2ca0144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbda575
2ca0144
bbda575
513d654
2ca0144
 
 
bbda575
 
2ca0144
 
 
 
 
 
bbda575
2ca0144
bbda575
2ca0144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbda575
2ca0144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbda575
2ca0144
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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
)