Daemontatox commited on
Commit
40ce582
·
verified ·
1 Parent(s): 6654033

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -311
app.py CHANGED
@@ -1,332 +1,160 @@
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
- """
42
 
43
- TITLE = "<h1><center>Arabic localizer Translation Assistant </center></h1>"
44
- PLACEHOLDER = "اسأل عن أي شيء! سأفكر فيه خطوة بخطوة."
 
 
 
 
 
 
 
 
 
 
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
- .arabic-input {
83
- direction: rtl;
84
- text-align: right;
85
- font-family: 'Arabic', Arial, sans-serif;
86
- }
87
  """
88
 
89
- def is_arabic_text(text: str) -> bool:
90
- """Detect if the text contains Arabic characters"""
91
- return any('\u0600' <= char <= '\u06FF' for char in text)
 
 
 
 
92
 
93
- def format_text(text: str) -> str:
94
- """Format text with proper spacing and tag highlighting"""
95
- tag_patterns = [
96
- (r'<Thinking>', '\n<Thinking>\n'),
97
- (r'</Thinking>', '\n</Thinking>\n'),
98
- (r'<Critique>', '\n<Critique>\n'),
99
- (r'</Critique>', '\n</Critique>\n'),
100
- (r'<Revising>', '\n<Revising>\n'),
101
- (r'</Revising>', '\n</Revising>\n'),
102
- (r'<Final>', '\n<Final>\n'),
103
- (r'</Final>', '\n</Final>\n')
104
- ]
105
-
106
- formatted = text
107
- for pattern, replacement in tag_patterns:
108
- formatted = re.sub(pattern, replacement, formatted)
109
 
110
- formatted = '\n'.join(line for line in formatted.split('\n') if line.strip())
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
- return formatted
 
 
113
 
114
- def format_chat_history(history: List[List[str]]) -> str:
115
- """Format chat history for display"""
116
- formatted = []
117
- for user_msg, assistant_msg in history:
118
- formatted.append(f"User: {user_msg}")
119
- if assistant_msg:
120
- formatted.append(f"Assistant: {assistant_msg}")
121
- return "\n\n".join(formatted)
 
 
 
 
 
 
 
 
122
 
123
- def create_examples() -> List[str]:
124
- """Create example queries for the UI"""
125
- return [
126
- "اشرح مفهوم الذكاء الاصطناعي",
127
- "كيف تعمل عملية التمثيل الضوئي؟",
128
- "ما هي الأسباب الرئيسية لتغير المناخ؟",
129
- "صف عملية تخليق البروتين",
130
- "ما هي الميزات الرئيسية للحكومة الديمقراطية؟",
131
- ]
132
 
133
- def convert_history_to_cohere_format(history: List[List[str]]) -> List[dict]:
134
- """Convert chat history to Cohere's format"""
135
- cohere_history = []
136
- for user_msg, assistant_msg in history:
137
- if user_msg:
138
- cohere_history.append({"role": "User", "message": user_msg})
139
- if assistant_msg:
140
- cohere_history.append({"role": "Chatbot", "message": assistant_msg})
141
- return cohere_history
 
 
 
 
 
 
 
 
 
142
 
143
- def chat_response(
144
- message: str,
145
- history: List[List[str]],
146
- chat_display: str,
147
- system_prompt: str,
148
- temperature: float = 0,
149
- max_new_tokens: int = 8192,
150
- top_p: float = 0.8,
151
- top_k: int = 40,
152
- penalty: float = 1.2,
153
- api_key: str = os.getenv("COHERE_API_KEY")
154
- ) -> Iterator[Tuple[List[List[str]], str]]:
155
- """Generate chat responses using Cohere API"""
156
- co = cohere.Client(api_key=api_key)
157
 
158
- # Convert history to Cohere format
159
- chat_history = convert_history_to_cohere_format(history)
 
 
 
 
 
 
 
160
 
161
- # Initialize buffer for streaming
162
- buffer = ""
163
- history = history + [[message, ""]]
164
 
165
- # Process stream
166
- try:
167
- # Initialize stream
168
- stream = co.chat_stream(
169
- model='c4ai-aya-expanse-32b',
170
- message=message,
171
- temperature=temperature,
172
- chat_history=chat_history,
173
- prompt_truncation='AUTO',
174
- preamble=system_prompt
175
- )
176
-
177
- for event in stream:
178
- if event.event_type == "text-generation":
179
- buffer += event.text
180
- formatted_buffer = format_text(buffer)
181
- history[-1][1] = formatted_buffer
182
- chat_display = format_chat_history(history)
183
- yield history, chat_display
184
-
185
- except Exception as e:
186
- error_message = f"Error: {str(e)}"
187
- history[-1][1] = error_message
188
- chat_display = format_chat_history(history)
189
- yield history, chat_display
190
-
191
- def process_example(example: str) -> tuple:
192
- """Process example query and return empty history and updated display"""
193
- return [], f"User: {example}\n\n"
194
 
195
- def main():
196
- """Main function to set up and launch the Gradio interface"""
197
- with gr.Blocks(css=CSS, theme="JohnSmith9982/small_and_pretty'") as demo:
198
- gr.HTML(TITLE)
199
- gr.DuplicateButton(
200
- value="",
201
- elem_classes="duplicate-button"
202
- )
203
-
204
- with gr.Row():
205
- with gr.Column():
206
- chat_history = gr.State([])
207
- chat_display = gr.TextArea(
208
- value="",
209
- label="Chat History",
210
- interactive=True,
211
- elem_classes=["chat-area"],
212
- )
213
-
214
- message = gr.TextArea(
215
- placeholder=PLACEHOLDER,
216
- label="Your message",
217
- lines=3,
218
- elem_classes=["message-input"]
219
- )
220
-
221
- with gr.Row():
222
- submit = gr.Button("Send")
223
- clear = gr.Button("Clear")
224
-
225
- with gr.Accordion("⚙️ Advanced Settings", open=False):
226
- system_prompt = gr.TextArea(
227
- value=DEFAULT_SYSTEM_PROMPT,
228
- label="System Prompt",
229
- lines=7,
230
- )
231
- temperature = gr.Slider(
232
- minimum=0,
233
- maximum=1,
234
- step=0.1,
235
- value=0,
236
- label="Temperature",
237
- )
238
- max_tokens = gr.Slider(
239
- minimum=128,
240
- maximum=32000,
241
- step=128,
242
- value=8192,
243
- label="Max Tokens",
244
- )
245
- top_p = gr.Slider(
246
- minimum=0.1,
247
- maximum=1.0,
248
- step=0.1,
249
- value=0.8,
250
- label="Top-p",
251
- )
252
- top_k = gr.Slider(
253
- minimum=1,
254
- maximum=100,
255
- step=1,
256
- value=40,
257
- label="Top-k",
258
- )
259
- penalty = gr.Slider(
260
- minimum=1.0,
261
- maximum=2.0,
262
- step=0.1,
263
- value=1.2,
264
- label="Repetition Penalty",
265
- )
266
-
267
- examples = gr.Examples(
268
- examples=create_examples(),
269
- inputs=[message],
270
- outputs=[chat_history, chat_display],
271
- fn=process_example,
272
- cache_examples=False,
273
- )
274
-
275
- # JavaScript to handle Enter key submission and RTL direction
276
- js_handler = """
277
- function handleKeyPress(textArea, submitButton) {
278
- textArea.addEventListener('keydown', function(e) {
279
- // Check for Arabic characters
280
- const containsArabic = /[\u0600-\u06FF]/.test(textArea.value);
281
-
282
- // Apply RTL class for Arabic text
283
- if (containsArabic) {
284
- textArea.classList.add('arabic-input');
285
- } else {
286
- textArea.classList.remove('arabic-input');
287
- }
288
-
289
- // Handle Enter key for submission (without Shift)
290
- if (e.key === 'Enter' && !e.shiftKey) {
291
- e.preventDefault(); // Prevent default new line
292
- submitButton.click(); // Trigger submit button click
293
- }
294
- });
295
- }
296
- """
297
-
298
- # Set up event handlers
299
- submit_click = submit.click(
300
- chat_response,
301
- inputs=[
302
- message,
303
- chat_history,
304
- chat_display,
305
- system_prompt,
306
- temperature,
307
- max_tokens,
308
- top_p,
309
- top_k,
310
- penalty,
311
- ],
312
- outputs=[chat_history, chat_display],
313
- show_progress=True,
314
- )
315
-
316
- # Clear input after submission
317
- submit_click.then(lambda: "", outputs=message)
318
-
319
- # Add JavaScript to handle Enter key and RTL
320
- demo.load(None, inputs=[message, submit], js=js_handler)
321
-
322
- clear.click(
323
- lambda: ([], ""),
324
- outputs=[chat_history, chat_display],
325
- show_progress=True,
326
- )
327
 
328
- return demo
 
 
 
 
 
 
329
 
330
  if __name__ == "__main__":
331
- demo = main()
332
- demo.launch()
 
 
 
 
 
 
1
  import gradio as gr
2
+ from threading import Thread
3
+ import requests
4
+ from typing import List, Tuple
5
+ import json
6
+ import os
7
+ from queue import Queue
8
 
9
+ # Replace with your Hugging Face API token
10
+ HF_API_TOKEN = os.getenv("HF_API_TOKEN")
11
+ API_URL = f"https://api-inference.huggingface.co/models/FuseAI/FuseO1-DeepSeekR1-QwQ-SkyT1-32B-Preview"
12
+
13
+ DEFAULT_SYSTEM_PROMPT = """
14
+ You are an Advanced AI Coding Assistant, designed to solve complex challenges and deliver efficient, dependable solutions. Follow this structured workflow for every task:
15
+
16
+ 1. Understand: Analyze the problem thoroughly. Identify core objectives, resolve ambiguities, and ask clarifying questions if needed to ensure a complete understanding.
17
+
18
+ 2. Plan: Outline a clear, step-by-step approach, detailing the tools, frameworks, and algorithms required to achieve the solution effectively.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ 3. Implement: Execute the plan with well-structured, efficient, and well-commented code. Provide a clear explanation of your thought process and the rationale behind key decisions as you proceed.
21
+
22
+ 4. Validate: Test the solution rigorously to ensure accuracy, efficiency, and alignment with best practices. Debug and optimize where necessary.
23
+
24
+ 5. Conclude: Summarize the solution with a clear conclusion, highlighting its effectiveness. Suggest improvements, optimizations, or alternative approaches if applicable.
25
+
26
+ Guiding Principles:
27
+ Use code as a tool for reasoning, with clear and educational explanations.
28
+ Prioritize code readability, scalability, and maintainability.
29
+ Adapt explanations to the user's skill level to maximize learning value.
30
+ Refine solutions iteratively, incorporating feedback or evolving requirements.
31
+ """
32
 
33
  CSS = """
34
+ .gr-chatbot { min-height: 500px; border-radius: 15px; }
35
+ .special-tag { color: #2ecc71; font-weight: 600; }
36
+ footer { display: none !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  """
38
 
39
+ def format_response(text: str) -> str:
40
+ """Format the response by adding HTML styling to special tags."""
41
+ return text.replace("[Understand]", '\n<strong class="special-tag">[Understand]</strong>\n') \
42
+ .replace("[Plan]", '\n<strong class="special-tag">[Plan]</strong>\n') \
43
+ .replace("[Conclude]", '\n<strong class="special-tag">[Conclude]</strong>\n') \
44
+ .replace("[Reason]", '\n<strong class="special-tag">[Reason]</strong>\n') \
45
+ .replace("[Verify]", '\n<strong class="special-tag">[Verify]</strong>\n')
46
 
47
+ def query_huggingface(
48
+ payload: dict,
49
+ api_url: str = API_URL,
50
+ headers: dict = {"Authorization": f"Bearer {HF_API_TOKEN}"}
51
+ ) -> requests.Response:
52
+ """Send a request to the Hugging Face API endpoint."""
53
+ return requests.post(api_url, headers=headers, json=payload)
54
+
55
+ def stream_response(response_queue: Queue, chat_history: List[Tuple[str, str]], message: str):
56
+ """Stream the response from the API and update the chat history."""
57
+ partial_message = ""
58
+ new_history = chat_history + [(message, "")]
 
 
 
 
59
 
60
+ while True:
61
+ try:
62
+ token = response_queue.get()
63
+ if token is None: # End of stream
64
+ break
65
+
66
+ partial_message += token
67
+ formatted = format_response(partial_message)
68
+ new_history[-1] = (message, formatted + "▌")
69
+ yield new_history
70
+
71
+ except Exception as e:
72
+ print(f"Error in streaming: {e}")
73
+ break
74
 
75
+ # Final update without cursor
76
+ new_history[-1] = (message, format_response(partial_message))
77
+ yield new_history
78
 
79
+ def generate_response(
80
+ message: str,
81
+ chat_history: List[Tuple[str, str]],
82
+ system_prompt: str,
83
+ temperature: float,
84
+ max_tokens: int
85
+ ) -> List[Tuple[str, str]]:
86
+ """Generate a response using the Hugging Face API."""
87
+ # Create conversation history
88
+ conversation = [{"role": "system", "content": system_prompt}]
89
+ for user_msg, bot_msg in chat_history:
90
+ conversation.extend([
91
+ {"role": "user", "content": user_msg},
92
+ {"role": "assistant", "content": bot_msg}
93
+ ])
94
+ conversation.append({"role": "user", "content": message})
95
 
96
+ # Prepare the payload
97
+ payload = {
98
+ "inputs": conversation,
99
+ "parameters": {
100
+ "max_new_tokens": max_tokens,
101
+ "temperature": temperature,
102
+ "stream": True
103
+ }
104
+ }
105
 
106
+ # Create a queue for streaming tokens
107
+ response_queue = Queue()
108
+
109
+ def process_stream():
110
+ try:
111
+ response = query_huggingface(payload)
112
+
113
+ # Parse streaming response
114
+ for line in response.iter_lines():
115
+ if line:
116
+ json_response = json.loads(line)
117
+ if "token" in json_response:
118
+ response_queue.put(json_response["token"]["text"])
119
+
120
+ response_queue.put(None) # Signal end of stream
121
+ except Exception as e:
122
+ print(f"Error in API call: {e}")
123
+ response_queue.put(None)
124
 
125
+ # Start processing thread
126
+ Thread(target=process_stream).start()
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
+ # Return generator for streaming
129
+ return stream_response(response_queue, chat_history, message)
130
+
131
+ # Create Gradio interface
132
+ with gr.Blocks(css=CSS, theme=gr.themes.Soft()) as demo:
133
+ gr.Markdown("""
134
+ <h1 align="center">🧠 AI Reasoning Assistant</h1>
135
+ <p align="center">Ask me Hard questions</p>
136
+ """)
137
 
138
+ chatbot = gr.Chatbot(label="Conversation", elem_id="chatbot")
139
+ msg = gr.Textbox(label="Your Question", placeholder="Type your question...")
 
140
 
141
+ with gr.Accordion("⚙️ Settings", open=False):
142
+ system_prompt = gr.TextArea(value=DEFAULT_SYSTEM_PROMPT, label="System Instructions")
143
+ temperature = gr.Slider(0, 1, value=0.5, label="Creativity")
144
+ max_tokens = gr.Slider(128, 4096, value=2048, label="Max Response Length")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
+ clear = gr.Button("Clear History")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
+ msg.submit(
149
+ generate_response,
150
+ [msg, chatbot, system_prompt, temperature, max_tokens],
151
+ [chatbot],
152
+ show_progress=True
153
+ )
154
+ clear.click(lambda: None, None, chatbot, queue=False)
155
 
156
  if __name__ == "__main__":
157
+ if not HF_API_TOKEN:
158
+ print("Please set your Hugging Face API token as environment variable HF_API_TOKEN")
159
+ else:
160
+ demo.queue().launch()