Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,189 +1,3 @@
|
|
1 |
-
import os
|
2 |
-
import re
|
3 |
-
import cohere
|
4 |
-
import gradio as gr
|
5 |
-
from typing import Iterator, List, Tuple
|
6 |
-
|
7 |
-
# Configuration Constants
|
8 |
-
DEFAULT_SYSTEM_PROMPT = """
|
9 |
-
أنت مترجم ثنائي اللغة متخصص في الترجمة بين العربية والإنجليزية. هدفك هو تقديم ترجمات دقيقة، ملائمة للسياق، ومتسقة من الناحية الأسلوبية، مع الالتزام بالإرشادات التالية:
|
10 |
-
أسلوب الكتابة:
|
11 |
-
1. الدقة النحوية: احرص دائمًا على أن تكون الترجمة صحيحة نحويًا.
|
12 |
-
2. الملاءمة السياقية: قم بتكييف الترجمة مع السياق والجمهور المستهدف:
|
13 |
-
استخدم جملًا موجزة وواضحة في المحتوى الطبي والقانوني.
|
14 |
-
اعتمد لغة جذابة وخيالية في المواد التسويقية.
|
15 |
-
حافظ على الرسمية والبلاغة في المحتوى القانوني.
|
16 |
-
3. البنية السليمة: احترم تراكيب الجمل العربية وتجنب النسخ المباشر لقواعد لغة المصدر. فضل استخدام "الجملة الفعلية" إلا إذا كانت "الجملة الاسمية" أكثر ملاءمة (مثلًا في العناوين أو التنويهات).
|
17 |
-
الخيارات الأسلوبية:
|
18 |
-
استخدم التشكيل فقط عند الضرورة لتوضيح المعنى.
|
19 |
-
تعامل مع الأسماء والأحرف المختصرة حسب السياق:
|
20 |
-
قم بتعريب الأسماء وأسماء الأدوية إلا إذا وُجدت لها مرادفات عربية.
|
21 |
-
ترجم أسماء البرامج والإدارات والهيئات عندما يكون ذلك مفيدًا.
|
22 |
-
استخدم الأرقام العربية وتأكد من التعامل الصحيح مع الوحدات والعناوين والمراجع.
|
23 |
-
علامات الترقيم:
|
24 |
-
طبق قواعد الترقيم العربية لضمان وضوح النص.
|
25 |
-
استخدم الفاصلة العربية (،) والفاصلة المنقوطة (؛) حسب الأعراف.
|
26 |
-
تجنب الإفراط في استخدام علامات الاقتباس واحرص على وضع النقطتين (:) بشكل منطقي.
|
27 |
-
الأخطاء الشائعة التي يجب تجنبها:
|
28 |
-
تجنب ترجمة "is" بـ "يُعتبر" إلا إذا كان ذلك مناسبًا للسياق.
|
29 |
-
استخدم حروف الجر والعطف بشكل صحيح لضمان تدفق الجمل بسلاسة.
|
30 |
-
قلل من التكرار واستخدم الضمائر حيثما أمكن.
|
31 |
-
تجنب الإفراط في استخدام تراكيب مثل "(قام + الفعل)" و"الخاص بـ."
|
32 |
-
المصطلحات المحددة:
|
33 |
-
في الترجمات القانونية، حافظ على النبرة الرسمية وتأكد من دقة المصطلحات.
|
34 |
-
في الترجمات الطبية، بسّط المصطلحات التقنية للجمهور العام مع الاحتفاظ بالتعقيد عند مخاطبة المتخصصين.
|
35 |
-
في الترجمات التسويقية، ركّز على الإبداع بدلًا من الترجمة الحرفية، مع الحفاظ على الرسالة الأساسية.
|
36 |
-
إرشادات التنسيق:
|
37 |
-
التزم بمعايير الطباعة العربية بشكل متسق.
|
38 |
-
حافظ على تنسيق البيانات المهمة (مثل التواريخ، والقياسات، والاستشهادات القانونية).
|
39 |
-
عند الشك:
|
40 |
-
قدم الأولوية للوضوح، والتناسق، والملاءمة مع احتياجات الجمهور المستهدف. قم دائمًا بموازنة التعليمات الخاصة بالمشروع مع هذه الإرشادات، مع إعطاء الأولوية لمتطلبات العميل عند وجود أي تعارض.
|
41 |
-
""" # (keeping the full prompt as in original)
|
42 |
-
|
43 |
-
TITLE = "<h1><center>Mawared T Assistant</center></h1>"
|
44 |
-
PLACEHOLDER = "Ask me anything! I'll think through it step by step."
|
45 |
-
|
46 |
-
CSS = """
|
47 |
-
.duplicate-button {
|
48 |
-
margin: auto !important;
|
49 |
-
color: white !important;
|
50 |
-
background: black !important;
|
51 |
-
border-radius: 100vh !important;
|
52 |
-
}
|
53 |
-
h3 {
|
54 |
-
text-align: center;
|
55 |
-
}
|
56 |
-
.message-wrap {
|
57 |
-
overflow-x: auto;
|
58 |
-
}
|
59 |
-
.message-wrap p {
|
60 |
-
margin-bottom: 1em;
|
61 |
-
}
|
62 |
-
.message-wrap pre {
|
63 |
-
background-color: #f6f8fa;
|
64 |
-
border-radius: 3px;
|
65 |
-
padding: 16px;
|
66 |
-
overflow-x: auto;
|
67 |
-
}
|
68 |
-
.message-wrap code {
|
69 |
-
background-color: rgba(175,184,193,0.2);
|
70 |
-
border-radius: 3px;
|
71 |
-
padding: 0.2em 0.4em;
|
72 |
-
font-family: monospace;
|
73 |
-
}
|
74 |
-
.custom-tag {
|
75 |
-
color: #0066cc;
|
76 |
-
font-weight: bold;
|
77 |
-
}
|
78 |
-
.chat-area {
|
79 |
-
height: 500px !important;
|
80 |
-
overflow-y: auto !important;
|
81 |
-
}
|
82 |
-
"""
|
83 |
-
|
84 |
-
def format_text(text: str) -> str:
|
85 |
-
"""Format text with proper spacing and tag highlighting"""
|
86 |
-
tag_patterns = [
|
87 |
-
(r'<Thinking>', '\n<Thinking>\n'),
|
88 |
-
(r'</Thinking>', '\n</Thinking>\n'),
|
89 |
-
(r'<Critique>', '\n<Critique>\n'),
|
90 |
-
(r'</Critique>', '\n</Critique>\n'),
|
91 |
-
(r'<Revising>', '\n<Revising>\n'),
|
92 |
-
(r'</Revising>', '\n</Revising>\n'),
|
93 |
-
(r'<Final>', '\n<Final>\n'),
|
94 |
-
(r'</Final>', '\n</Final>\n')
|
95 |
-
]
|
96 |
-
|
97 |
-
formatted = text
|
98 |
-
for pattern, replacement in tag_patterns:
|
99 |
-
formatted = re.sub(pattern, replacement, formatted)
|
100 |
-
|
101 |
-
formatted = '\n'.join(line for line in formatted.split('\n') if line.strip())
|
102 |
-
|
103 |
-
return formatted
|
104 |
-
|
105 |
-
def format_chat_history(history: List[List[str]]) -> str:
|
106 |
-
"""Format chat history for display"""
|
107 |
-
formatted = []
|
108 |
-
for user_msg, assistant_msg in history:
|
109 |
-
formatted.append(f"User: {user_msg}")
|
110 |
-
if assistant_msg:
|
111 |
-
formatted.append(f"Assistant: {assistant_msg}")
|
112 |
-
return "\n\n".join(formatted)
|
113 |
-
|
114 |
-
def create_examples() -> List[str]:
|
115 |
-
"""Create example queries for the UI"""
|
116 |
-
return [
|
117 |
-
"Explain the concept of artificial intelligence.",
|
118 |
-
"How does photosynthesis work?",
|
119 |
-
"What are the main causes of climate change?",
|
120 |
-
"Describe the process of protein synthesis.",
|
121 |
-
"What are the key features of a democratic government?",
|
122 |
-
]
|
123 |
-
|
124 |
-
def convert_history_to_cohere_format(history: List[List[str]]) -> List[dict]:
|
125 |
-
"""Convert chat history to Cohere's format"""
|
126 |
-
cohere_history = []
|
127 |
-
for user_msg, assistant_msg in history:
|
128 |
-
if user_msg:
|
129 |
-
cohere_history.append({"role": "User", "message": user_msg})
|
130 |
-
if assistant_msg:
|
131 |
-
cohere_history.append({"role": "Chatbot", "message": assistant_msg})
|
132 |
-
return cohere_history
|
133 |
-
|
134 |
-
def chat_response(
|
135 |
-
message: str,
|
136 |
-
history: List[List[str]],
|
137 |
-
system_prompt: str,
|
138 |
-
temperature: float = 0.3,
|
139 |
-
max_new_tokens: int = 8192,
|
140 |
-
top_p: float = 0.8,
|
141 |
-
top_k: int = 40,
|
142 |
-
penalty: float = 1.2,
|
143 |
-
api_key: str = os.getenv("COHERE_API_KEY")
|
144 |
-
) -> Iterator[Tuple[List[List[str]], str]]:
|
145 |
-
"""Generate chat responses using Cohere API"""
|
146 |
-
co = cohere.Client(api_key=api_key)
|
147 |
-
|
148 |
-
# Convert history to Cohere format
|
149 |
-
chat_history = convert_history_to_cohere_format(history)
|
150 |
-
|
151 |
-
# Initialize buffer for streaming
|
152 |
-
buffer = ""
|
153 |
-
history = history + [[message, ""]]
|
154 |
-
|
155 |
-
# Process stream
|
156 |
-
try:
|
157 |
-
# Initialize stream
|
158 |
-
stream = co.chat_stream(
|
159 |
-
model='c4ai-aya-expanse-32b',
|
160 |
-
message=message,
|
161 |
-
temperature=temperature,
|
162 |
-
chat_history=chat_history,
|
163 |
-
prompt_truncation='AUTO',
|
164 |
-
preamble=system_prompt
|
165 |
-
)
|
166 |
-
|
167 |
-
for event in stream:
|
168 |
-
if event.event_type == "text-generation":
|
169 |
-
buffer += event.text
|
170 |
-
formatted_buffer = format_text(buffer)
|
171 |
-
history[-1][1] = formatted_buffer
|
172 |
-
yield history, history[-1][1]
|
173 |
-
|
174 |
-
except Exception as e:
|
175 |
-
error_message = f"Error: {str(e)}"
|
176 |
-
history[-1][1] = error_message
|
177 |
-
yield history, history[-1][1]
|
178 |
-
|
179 |
-
def process_example(example: str) -> tuple:
|
180 |
-
"""Process example query and return empty history and updated display"""
|
181 |
-
return [], f"User: {example}\n\n"
|
182 |
-
|
183 |
-
def clear_chat() -> tuple:
|
184 |
-
"""Clear chat history and input"""
|
185 |
-
return [], ""
|
186 |
-
|
187 |
def main():
|
188 |
"""Main function to set up and launch the Gradio interface"""
|
189 |
with gr.Blocks(css=CSS, theme="soft") as demo:
|
@@ -193,92 +7,77 @@ def main():
|
|
193 |
elem_classes="duplicate-button"
|
194 |
)
|
195 |
|
196 |
-
chatbot = gr.Chatbot(
|
197 |
-
height=750,
|
198 |
-
show_label=False,
|
199 |
-
bubble_full_width=False,
|
200 |
-
elem_classes=["chat-area"],
|
201 |
-
)
|
202 |
-
|
203 |
with gr.Row():
|
204 |
-
with gr.Column(
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
|
|
210 |
)
|
211 |
-
|
212 |
with gr.Row():
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
|
275 |
-
|
276 |
-
clear_chat,
|
277 |
-
outputs=[chatbot, message]
|
278 |
-
)
|
279 |
-
|
280 |
-
return demo
|
281 |
-
|
282 |
-
if __name__ == "__main__":
|
283 |
-
demo = main()
|
284 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
def main():
|
2 |
"""Main function to set up and launch the Gradio interface"""
|
3 |
with gr.Blocks(css=CSS, theme="soft") as demo:
|
|
|
7 |
elem_classes="duplicate-button"
|
8 |
)
|
9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
with gr.Row():
|
11 |
+
with gr.Column():
|
12 |
+
chat_history = gr.State([])
|
13 |
+
chatbot = gr.Chatbot(
|
14 |
+
height=750,
|
15 |
+
show_label=False,
|
16 |
+
bubble_full_width=False,
|
17 |
+
elem_classes=["chat-area"],
|
18 |
)
|
19 |
+
|
20 |
with gr.Row():
|
21 |
+
with gr.Column(scale=20):
|
22 |
+
message = gr.Textbox(
|
23 |
+
placeholder=PLACEHOLDER,
|
24 |
+
label="Your message",
|
25 |
+
lines=3,
|
26 |
+
show_label=False
|
27 |
+
)
|
28 |
+
with gr.Column(scale=4):
|
29 |
+
with gr.Row():
|
30 |
+
submit = gr.Button("Send", variant="primary", size="sm")
|
31 |
+
clear = gr.Button("Clear Chat", size="sm")
|
32 |
+
|
33 |
+
with gr.Accordion("⚙️ Advanced Settings", open=False):
|
34 |
+
system_prompt = gr.TextArea(
|
35 |
+
value=DEFAULT_SYSTEM_PROMPT,
|
36 |
+
label="System Prompt",
|
37 |
+
lines=5,
|
38 |
+
)
|
39 |
+
temperature = gr.Slider(
|
40 |
+
minimum=0,
|
41 |
+
maximum=1,
|
42 |
+
step=0.1,
|
43 |
+
value=0.3,
|
44 |
+
label="Temperature",
|
45 |
+
)
|
46 |
+
max_tokens = gr.Slider(
|
47 |
+
minimum=128,
|
48 |
+
maximum=32000,
|
49 |
+
step=128,
|
50 |
+
value=8192,
|
51 |
+
label="Max Tokens",
|
52 |
+
)
|
53 |
+
top_p = gr.Slider(
|
54 |
+
minimum=0.1,
|
55 |
+
maximum=1.0,
|
56 |
+
step=0.1,
|
57 |
+
value=0.8,
|
58 |
+
label="Top-p",
|
59 |
+
)
|
60 |
+
top_k = gr.Slider(
|
61 |
+
minimum=1,
|
62 |
+
maximum=100,
|
63 |
+
step=1,
|
64 |
+
value=40,
|
65 |
+
label="Top-k",
|
66 |
+
)
|
67 |
+
penalty = gr.Slider(
|
68 |
+
minimum=1.0,
|
69 |
+
maximum=2.0,
|
70 |
+
step=0.1,
|
71 |
+
value=1.2,
|
72 |
+
label="Repetition Penalty",
|
73 |
+
)
|
74 |
+
|
75 |
+
examples = gr.Examples(
|
76 |
+
examples=create_examples(),
|
77 |
+
inputs=[message],
|
78 |
+
outputs=[chat_history, chatbot],
|
79 |
+
fn=process_example,
|
80 |
+
cache_examples=False,
|
81 |
+
)
|
82 |
|
83 |
+
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|