File size: 9,246 Bytes
3f5d3d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20709bb
 
 
3f5d3d8
 
20709bb
3f5d3d8
 
 
 
 
 
20709bb
 
 
3f5d3d8
 
 
 
 
20709bb
3f5d3d8
 
 
 
 
 
 
 
 
 
 
 
20709bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f5d3d8
 
 
 
 
 
 
 
 
 
20709bb
 
3f5d3d8
 
 
 
 
20709bb
3f5d3d8
 
 
 
 
 
20709bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f5d3d8
 
 
 
 
 
 
 
 
 
20709bb
 
 
 
 
 
 
 
3f5d3d8
 
 
 
20709bb
3f5d3d8
 
 
 
 
 
 
 
20709bb
 
 
 
3f5d3d8
 
 
 
20709bb
3f5d3d8
 
20709bb
3f5d3d8
 
 
20709bb
 
 
 
 
 
 
 
 
 
3f5d3d8
 
 
 
 
 
 
 
 
 
 
 
 
20709bb
 
3f5d3d8
 
 
 
 
 
 
 
 
 
 
 
20709bb
3f5d3d8
 
 
 
 
 
 
 
 
 
 
20709bb
3f5d3d8
 
 
 
20709bb
 
 
 
 
 
 
3f5d3d8
20709bb
 
 
 
 
 
 
 
 
 
 
3f5d3d8
 
 
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تطبيق المحادثة الصوتية</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f0f2f5;
        }
        .chat-container {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .controls {
            display: flex;
            gap: 10px;
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            background-color: #0084ff;
            color: white;
            cursor: pointer;
        }
        button:hover {
            background-color: #0066cc;
        }
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .messages {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-top: 20px;
            max-height: 400px;
            overflow-y: auto;
            padding: 10px;
        }
        .message {
            padding: 10px;
            border-radius: 10px;
            max-width: 80%;
            word-wrap: break-word;
        }
        .user-message {
            background-color: #e3f2fd;
            align-self: flex-end;
        }
        .bot-message {
            background-color: #f5f5f5;
            align-self: flex-start;
        }
        #status {
            margin-top: 10px;
            color: #666;
            padding: 10px;
            border-radius: 5px;
        }
        .error {
            color: #d32f2f;
            background-color: #ffebee;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
        }
        #textInput {
            width: 100%;
            padding: 10px;
            margin-top: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="controls">
            <button id="startRecording">ابدأ التسجيل</button>
            <button id="stopRecording" disabled>أوقف التسجيل</button>
        </div>
        <div id="status">جاهز للتسجيل...</div>
        <textarea id="textInput" placeholder="أو اكتب رسالتك هنا..." rows="3"></textarea>
        <button id="sendText">إرسال النص</button>
        <div class="messages" id="messages"></div>
    </div>

    <script>
        const API_URL = 'https://8o1mzdgh9f40t4-7777.proxy.runpod.net/proxy/8000/chat';
        let mediaRecorder = null;
        let audioChunks = [];

        const startButton = document.getElementById('startRecording');
        const stopButton = document.getElementById('stopRecording');
        const statusDiv = document.getElementById('status');
        const messagesDiv = document.getElementById('messages');
        const textInput = document.getElementById('textInput');
        const sendTextButton = document.getElementById('sendText');

        // التحقق من دعم المتصفح للميزات المطلوبة
        function checkBrowserSupport() {
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                showError('متصفحك لا يدعم تسجيل الصوت. الرجاء استخدام متصفح حديث.');
                startButton.disabled = true;
                return false;
            }
            if (!window.SpeechRecognition && !window.webkitSpeechRecognition) {
                showError('متصفحك لا يدعم التعرف على الكلام. الرجاء استخدام Google Chrome.');
                startButton.disabled = true;
                return false;
            }
            return true;
        }

        function showError(message) {
            statusDiv.innerHTML = `<div class="error">${message}</div>`;
        }

        function addMessage(text, isUser) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`;
            messageDiv.textContent = text;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        async function speakText(text) {
            try {
                const utterance = new SpeechSynthesisUtterance(text);
                utterance.lang = 'ar-SA';
                speechSynthesis.speak(utterance);
            } catch (error) {
                console.error('Error speaking:', error);
                showError('حدث خطأ في تحويل النص إلى كلام');
            }
        }

        async function sendToModel(text) {
            try {
                statusDiv.textContent = 'جارِ إرسال الرسالة...';
                const response = await fetch(API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ message: text })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                const botResponse = data.response || 'عذراً، حدث خطأ في الاستجابة';
                addMessage(botResponse, false);
                speakText(botResponse);
                statusDiv.textContent = 'جاهز للتسجيل...';
            } catch (error) {
                console.error('Error:', error);
                showError('حدث خطأ في الاتصال بالنموذج. الرجاء المحاولة مرة أخرى.');
            }
        }

        // إرسال النص المكتوب
        sendTextButton.onclick = () => {
            const text = textInput.value.trim();
            if (text) {
                addMessage(text, true);
                sendToModel(text);
                textInput.value = '';
            }
        };

        startButton.onclick = async () => {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);
                
                mediaRecorder.ondataavailable = (event) => {
                    audioChunks.push(event.data);
                };

                mediaRecorder.onstop = async () => {
                    const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                    audioChunks = [];
                    
                    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
                    const recognition = new SpeechRecognition();
                    recognition.lang = 'ar-SA';
                    recognition.continuous = false;
                    recognition.interimResults = false;

                    recognition.onresult = (event) => {
                        const text = event.results[0][0].transcript;
                        addMessage(text, true);
                        sendToModel(text);
                    };

                    recognition.onerror = (event) => {
                        console.error('Speech recognition error:', event.error);
                        showError('حدث خطأ في التعرف على الكلام');
                    };

                    recognition.start();
                };

                mediaRecorder.start();
                startButton.disabled = true;
                stopButton.disabled = false;
                statusDiv.textContent = 'جارِ التسجيل...';
            } catch (error) {
                console.error('Error:', error);
                showError('حدث خطأ في الوصول إلى الميكروفون. تأكد من السماح للموقع باستخدام الميكروفون.');
            }
        };

        stopButton.onclick = () => {
            if (mediaRecorder && mediaRecorder.state === 'recording') {
                mediaRecorder.stop();
                mediaRecorder.stream.getTracks().forEach(track => track.stop());
                startButton.disabled = false;
                stopButton.disabled = true;
                statusDiv.textContent = 'تم إيقاف التسجيل، جارِ معالجة الكلام...';
            }
        };

        // التحقق من دعم المتصفح عند تحميل الصفحة
        window.onload = checkBrowserSupport;

        // إضافة دعم للإرسال بضغط Enter
        textInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendTextButton.click();
            }
        });
    </script>
</body>
</html>