File size: 6,535 Bytes
298575c
cbaa149
a0ae92e
 
cbaa149
dd308b8
 
 
06b5910
df6accb
 
 
 
dd308b8
df6accb
dd308b8
df6accb
 
 
 
 
 
 
 
 
 
 
dd308b8
df6accb
cbaa149
 
 
df6accb
cbaa149
a0ae92e
df6accb
2471e1c
df6accb
 
2471e1c
df6accb
 
 
 
dd308b8
 
2471e1c
 
 
8e0056e
2471e1c
8e0056e
 
dd308b8
2471e1c
8e0056e
dd308b8
 
a0ae92e
 
df6accb
 
 
 
 
 
 
 
 
 
dd308b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df6accb
dd308b8
 
cbaa149
 
a0ae92e
dd308b8
df6accb
dd308b8
df6accb
dd308b8
 
2471e1c
 
 
df6accb
dd308b8
 
a0ae92e
 
df6accb
8e0056e
dd308b8
8e0056e
df6accb
dd308b8
8e0056e
cbaa149
 
a0ae92e
2471e1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd308b8
 
 
a0ae92e
 
df6accb
 
cbaa149
 
 
 
 
 
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

// Configuration Backend - Auto-detect environment
const BACKEND_URL = window.location.hostname === 'localhost' 
  ? "http://localhost:3000" 
  : "https://rosalinda-backend.onrender.com"; // Replace with your actual Render/Railway URL
let isRecording = false;
let mediaRecorder;
let audioChunks = [];

// Éléments DOM
const chatMessages = document.getElementById('chatMessages');
const chatInput = document.querySelector('.chat-input input');
const sendButton = document.querySelector('.chat-input button[title="Envoyer"]');
const micButton = document.querySelector('.chat-input button[title="Micro"]');
const codeOutput = document.getElementById('codeOutput');
const activityMonitor = document.querySelector('.activity-monitor');
// Gestionnaire d'envoi de message
sendButton.addEventListener('click', sendMessage);
chatInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') sendMessage();
});
async function sendMessage() {
    const message = chatInput.value.trim();
    if (!message) return;

    addMessage('user', message);
    chatInput.value = '';
    activityMonitor.textContent = '[ Rosalinda réfléchit... ]';

    // Check if we're on Hugging Face Spaces
    const isHuggingFace = window.location.hostname.includes('hf.space');
    
    try {
        const response = await fetch(`${isHuggingFace ? 'https://rosalinda-backend.onrender.com' : BACKEND_URL}/api/chat`, {
method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                message: message
            })
        });

        const data = await response.json();
        activityMonitor.textContent = '[ Rosalinda en ligne ]';
        
        if (data.reply) {
            addMessage('assistant', data.reply);
// Détection de code dans la réponse
            // Détection de code dans la réponse
            const codeBlocks = data.reply.match(/```[\s\S]*?```/g);
            if (codeBlocks) {
                codeOutput.innerHTML = `<pre><code>${codeBlocks.join('\n\n')}</code></pre>`;
            }
}
} catch (error) {
        console.error('Erreur backend:', error);
        activityMonitor.textContent = '[ Erreur de connexion ]';
            addMessage('assistant', `Désolé, une erreur s'est produite (${error.message}). Veuillez réessayer.`);
}
}
function addMessage(sender, content) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${sender}`;
    messageDiv.innerHTML = `
        <div class="message-content">${content}</div>
    `;
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Gestion de la voix
micButton.addEventListener('click', toggleRecording);

async function toggleRecording() {
    if (!isRecording) {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            mediaRecorder = new MediaRecorder(stream);
            audioChunks = [];
            
            mediaRecorder.ondataavailable = (e) => {
                audioChunks.push(e.data);
            };
            
            mediaRecorder.onstop = async () => {
                const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                await sendAudioMessage(audioBlob);
            };
            
            mediaRecorder.start();
            isRecording = true;
            micButton.innerHTML = '<i class="fas fa-stop"></i>';
            activityMonitor.textContent = '[ Enregistrement en cours... ]';
        } catch (err) {
            console.error('Erreur microphone:', err);
            addMessage('assistant', "Impossible d'accéder au microphone. Vérifiez les permissions.");
        }
    } else {
        mediaRecorder.stop();
        isRecording = false;
        micButton.innerHTML = '<i class="fas fa-microphone"></i>';
        activityMonitor.textContent = '[ Traitement audio... ]';
    }
}
async function sendAudioMessage(audioBlob) {
    try {
        const formData = new FormData();
        formData.append('audio', audioBlob, 'recording.wav');
        const isHuggingFace = window.location.hostname.includes('hf.space');
        const response = await fetch(`${isHuggingFace ? 'https://rosalinda-backend.onrender.com' : BACKEND_URL}/api/whisper`, {
method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        activityMonitor.textContent = '[ Rosalinda en ligne ]';
        
        if (data.text) {
            addMessage('assistant', data.text);
}
    } catch (error) {
        console.error('Erreur audio:', error);
        activityMonitor.textContent = '[ Erreur de connexion ]';
            addMessage('assistant', `Erreur audio: ${error.message}. Vérifiez la connexion au serveur.`);
}
}
// Bouton Génération d'image
document.querySelector('.menu button:nth-child(1)').addEventListener('click', async () => {
    const prompt = prompt("Décrivez l'image que vous souhaitez générer avec DALL·E:");
    if (prompt) {
        try {
            activityMonitor.textContent = '[ Génération image en cours... ]';
            const isHuggingFace = window.location.hostname.includes('hf.space');
            const response = await fetch(`${isHuggingFace ? 'https://rosalinda-backend.onrender.com' : BACKEND_URL}/api/image`, {
method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                prompt: prompt
            })
        });
        
        const data = await response.json();
        activityMonitor.textContent = '[ Image générée ]';
        
        if (data.imageUrl) {
            const resultOutput = document.querySelector('.result-output');
            resultOutput.innerHTML = `<img src="${data.imageUrl}" alt="Image générée" style="max-width:100%;">`;
            addMessage('assistant', `Voici l'image générée pour "${prompt}"`);
}
        } catch (error) {
            console.error('Erreur génération:', error);
            activityMonitor.textContent = '[ Erreur de génération ]';
            addMessage('assistant', `Erreur de génération: ${error.message}. Vérifiez votre description.`);
}
    }
});
// Detect environment and log appropriate message
if (window.location.hostname.includes('hf.space')) {
    console.log("Interface Espace Codage connectée au backend de production sur Render");
} else {
    console.log("Interface Espace Codage connectée au backend local");
}