Daemontatox commited on
Commit
12aabae
·
verified ·
1 Parent(s): 466dbe3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +293 -17
app.py CHANGED
@@ -1,3 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def main():
2
  """Main function to set up and launch the Gradio interface"""
3
  with gr.Blocks(css=CSS, theme="soft") as demo:
@@ -10,25 +195,22 @@ def main():
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(
@@ -75,9 +257,103 @@ def main():
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
- #
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ chat_display: str,
138
+ system_prompt: str,
139
+ temperature: float = 0.3,
140
+ max_new_tokens: int = 8192,
141
+ top_p: float = 0.8,
142
+ top_k: int = 40,
143
+ penalty: float = 1.2,
144
+ api_key: str = os.getenv("COHERE_API_KEY")
145
+ ) -> Iterator[Tuple[List[List[str]], str]]:
146
+ """Generate chat responses using Cohere API"""
147
+ co = cohere.Client(api_key=api_key)
148
+
149
+ # Convert history to Cohere format
150
+ chat_history = convert_history_to_cohere_format(history)
151
+
152
+ # Initialize buffer for streaming
153
+ buffer = ""
154
+ history = history + [[message, ""]]
155
+
156
+ # Process stream
157
+ try:
158
+ # Initialize stream
159
+ stream = co.chat_stream(
160
+ model='c4ai-aya-expanse-32b',
161
+ message=message,
162
+ temperature=temperature,
163
+ chat_history=chat_history,
164
+ prompt_truncation='AUTO',
165
+ preamble=system_prompt
166
+ )
167
+
168
+ for event in stream:
169
+ if event.event_type == "text-generation":
170
+ buffer += event.text
171
+ formatted_buffer = format_text(buffer)
172
+ history[-1][1] = formatted_buffer
173
+ chat_display = format_chat_history(history)
174
+ yield history, chat_display
175
+
176
+ except Exception as e:
177
+ error_message = f"Error: {str(e)}"
178
+ history[-1][1] = error_message
179
+ chat_display = format_chat_history(history)
180
+ yield history, chat_display
181
+
182
+ def process_example(example: str) -> tuple:
183
+ """Process example query and return empty history and updated display"""
184
+ return [], f"User: {example}\n\n"
185
+
186
  def main():
187
  """Main function to set up and launch the Gradio interface"""
188
  with gr.Blocks(css=CSS, theme="soft") as demo:
 
195
  with gr.Row():
196
  with gr.Column():
197
  chat_history = gr.State([])
198
+ chat_display = gr.TextArea(
199
+ value="",
200
+ label="Chat History",
201
+ interactive=False,
202
  elem_classes=["chat-area"],
203
  )
204
 
205
+ message = gr.TextArea(
206
+ placeholder=PLACEHOLDER,
207
+ label="Your message",
208
+ lines=3
209
+ )
210
+
211
  with gr.Row():
212
+ submit = gr.Button("Send")
213
+ clear = gr.Button("Clear")
 
 
 
 
 
 
 
 
 
214
 
215
  with gr.Accordion("⚙️ Advanced Settings", open=False):
216
  system_prompt = gr.TextArea(
 
257
  examples = gr.Examples(
258
  examples=create_examples(),
259
  inputs=[message],
260
+ outputs=[chat_history, chat_display],
261
  fn=process_example,
262
  cache_examples=False,
263
  )
264
 
265
+ # Set up event handlers
266
+ submit_click = submit.click(
267
+ chat_response,
268
+ inputs=[
269
+ message,
270
+ chat_history,
271
+ chat_display,
272
+ system_prompt,
273
+ temperature,
274
+ max_tokens,
275
+ top_p,
276
+ top_k,
277
+ penalty,
278
+ ],
279
+ outputs=[chat_history, chat_display],
280
+ show_progress=True,
281
+ )
282
+
283
+ # Bind Enter key to submit
284
+ message.submit(
285
+ chat_response,
286
+ inputs=[
287
+ message,
288
+ chat_history,
289
+ chat_display,
290
+ system_prompt,
291
+ temperature,
292
+ max_tokens,
293
+ top_p,
294
+ top_k,
295
+ penalty,
296
+ ],
297
+ outputs=[chat_history, chat_display],
298
+ show_progress=True,
299
+ )
300
+
301
+ clear.click(
302
+ lambda: ([], ""),
303
+ outputs=[chat_history, chat_display],
304
+ show_progress=True,
305
+ )
306
+
307
+ # Clear input after submission
308
+ submit_click.then(lambda: "", outputs=message)
309
+ message.submit(lambda: "", outputs=message)
310
+
311
+ return demo
312
+
313
+ if __name__ == "__main__":
314
+ demo = main()
315
+ demo.launch()
316
+
317
+
318
+ modify the send function and use the following asa reference :
319
+
320
+
321
+
322
+ with gr.Blocks() as iface:
323
+ gr.Image("Image.jpg", width=750, height=300, show_label=False, show_download_button=False)
324
+ gr.Markdown("# Mawared HR Assistant 3.0.0")
325
+ gr.Markdown('### Instructions')
326
+ gr.Markdown("Ask a question about MawaredHR and get a detailed answer")
327
+
328
+ chatbot = gr.Chatbot(
329
+ height=750,
330
+ show_label=False,
331
+ bubble_full_width=False,
332
+ )
333
+
334
+ with gr.Row():
335
+ with gr.Column(scale=20):
336
+ question_input = gr.Textbox(
337
+ label="Ask a question:",
338
+ placeholder="Type your question here...",
339
+ show_label=False
340
+ )
341
+ with gr.Column(scale=4):
342
+ with gr.Row():
343
+ with gr.Column():
344
+ send_button = gr.Button("Send", variant="primary", size="sm")
345
+ clear_button = gr.Button("Clear Chat", size="sm")
346
+
347
+ # Handle both submit events (Enter key and Send button)
348
+ submit_events = [question_input.submit, send_button.click]
349
+ for submit_event in submit_events:
350
+ submit_event(
351
+ ask_question_gradio,
352
+ inputs=[question_input, chatbot],
353
+ outputs=[question_input, chatbot]
354
+ )
355
+
356
+ clear_button.click(
357
+ clear_chat,
358
+ outputs=[chatbot, question_input]
359
+ )