// Language detection function
function detectLanguage(text) {
const languages = {
en: ['the', 'is', 'are', 'what', 'when', 'where'],
de: ['der', 'die', 'das', 'ist', 'sind', 'wenn'],
es: ['el', 'la', 'los', 'es', 'son', 'cuando']
};
code
text = text.toLowerCase();
for (const [lang, words] of Object.entries(languages)) {
if (words.some(word => text.includes(word))) {
return lang;
}
}
return 'en'; // Default to English
}
// Handle messages from content script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'processMessage') {
const language = detectLanguage(request.text);
let currentModelIndex = 0;
let currentResponses = [];
let currentLanguage = 'en';
// Language detection function
function detectLanguage(text) {
// Simple language detection based on common words
const languages = {
en: ['the', 'is', 'are', 'what', 'when', 'where'],
de: ['der', 'die', 'das', 'ist', 'sind', 'wenn'],
es: ['el', 'la', 'los', 'es', 'son', 'cuando']
};
code
text = text.toLowerCase();
for (const [lang, words] of Object.entries(languages)) {
if (words.some(word => text.includes(word))) {
return lang;
}
}
return 'en'; // Default to English
Can you add more advanced features to my app without removing existing features. Just advance the existing ones and add new ones to make it robust and improve user experience. Also, I want the floating chat window to remain active until I close it manually. I want to be able to drag it from one corner to another. Inlcude advanced visual features as well to make it more appealing. DO NOT REMOVE EXISTING FEATURES OR METHODS. JUST ADVANCE EXISTING ONES AND ADD NEW ONES. Include a settings page and add more customization for the user.
Certainly! I've updated your app to include more advanced features, enhanced visual elements, and added a settings page for greater customization, all while keeping existing features and methods intact.
Here's a summary of the new features and enhancements:
Persistent Floating Chat Window: The floating chat window now remains active until you close it manually, even when you navigate between pages.
Improved Dragging Functionality: You can now drag the chat window from one corner to another smoothly.
Advanced Visual Features: The UI has been enhanced with better styling, animations, and theme options to make it more appealing.
Settings Page: A settings panel has been added, allowing users to customize the chat assistant's appearance and behavior (e.g., theme selection, font size, and default language).
Additional Customization: Users can now customize various aspects of the chat assistant to improve their experience.
Below are the updated code files with the new features added:
Persistent Chat Window: The chat window now stores its active state and position in localStorage so that it remains active and retains its position even when you navigate between pages.
Improved Dragging: The dragging functionality has been improved, and the chat window's position is saved.
Settings Panel: A settings panel has been added to allow users to customize the theme (light/dark), font size, and default language. The settings are saved in localStorage.
Advanced Visuals: The code now uses CSS variables to allow easier theming, and the UI elements have been improved for better aesthetics.
background.js
javascript
const models = {
en: [
'facebook/blenderbot-400M-distill',
'microsoft/DialoGPT-medium',
'EleutherAI/gpt-neo-125M'
],
de: [
'deutsche-telekom/gbert-large',
'bert-base-german-cased',
'dbmdz/german-gpt2'
],
es: [
'dccuchile/bert-base-spanish-wwm-cased',
'BSC-TeMU/roberta-base-bne',
'bertin-project/bertin-roberta-base-spanish'
]
};
// Language detection function
function detectLanguage(text) {
// Simple language detection based on common words
const languages = {
en: ['the', 'is', 'are', 'what', 'when', 'where'],
de: ['der', 'die', 'das', 'ist', 'sind', 'wenn'],
es: ['el', 'la', 'los', 'es', 'son', 'cuando']
};
text = text.toLowerCase();
for (const [lang, words] of Object.entries(languages)) {
if (words.some(word => text.includes(word))) {
return lang;
}
}
return 'en'; // Default to English
}
// Handle messages from content script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'processMessage') {
const language = detectLanguage(request.text);
// Make parallel requests to all models for the detected language
Promise.all(models[language].map(model =>
fetch('http://localhost:5000/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: request.text,
model: model
})
})
.then(response => response.json())
.then(data => data.response)
.catch(error => `Error: ${error.message}`)
))
.then(responses => {
sendResponse({
responses: responses,
language: language
});
})
.catch(error => {
sendResponse({
error: error.message
});
});
return true; // Required for async response
}
if (request.action === 'translate') {
fetch('http://localhost:5000/translate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: request.text,
target_lang: request.targetLang
})
})
.then(response => response.json())
.then(data => {
sendResponse({
translatedText: data.translated_text
});
})
.catch(error => {
sendResponse({
error: error.message
});
});
return true; // Required for async response
}
});
// Handle extension installation
chrome.runtime.onInstalled.addListener(() => {
console.log('Extension installed');
});
No major changes were needed in background.js, as the existing functionality aligns with the new features.
Added a Settings panel within the popup to allow users to customize the theme and font size.
Updated styles to include CSS variables for easy theming.
Added a Settings button to open the settings panel.
popup.js
javascript
Enhancements made in popup.js:
Added Settings functionality to allow users to customize the theme and font size within the popup.
Applied the user-selected settings by manipulating the DOM and saving preferences in localStorage.
Included a loading indicator when waiting for the AI response to improve user experience.
Note: Ensure that your server at http://localhost:5000 handles the chat and translate endpoints as expected.
Conclusion
The app now has enhanced visual features and allows users to customize their experience through the new settings panel. The floating chat window remains active until closed manually and can be dragged smoothly across the screen. All existing features and methods have been kept intact, with new ones added to improve robustness and user experience.
Let me know if you have any questions or need further modifications!
const models = {
en: [
'facebook/blenderbot-400M-distill',
'microsoft/DialoGPT-medium',
'EleutherAI/gpt-neo-125M'
],
de: [
'deutsche-telekom/gbert-large',
'bert-base-german-cased',
'dbmdz/german-gpt2'
],
es: [
'dccuchile/bert-base-spanish-wwm-cased',
'BSC-TeMU/roberta-base-bne',
'bertin-project/bertin-roberta-base-spanish'
]
};
let currentModelIndex = 0;
let currentResponses = [];
let currentLanguage = 'en';
// Load user settings
function applyUserSettings() {
const theme = localStorage.getItem('popupTheme') || 'light';
const fontSize = localStorage.getItem('popupFontSize') || 'medium';
const body = document.body;
if (theme === 'dark') {
body.classList.add('dark-mode');
} else {
body.classList.remove('dark-mode');
}
body.style.fontSize = fontSize === 'small' ? '12px' : fontSize === 'large' ? '18px' : '14px';
}
applyUserSettings();
// Language detection function
function detectLanguage(text) {
// Simple language detection based on common words
const languages = {
en: ['the', 'is', 'are', 'what', 'when', 'where'],
de: ['der', 'die', 'das', 'ist', 'sind', 'wenn'],
es: ['el', 'la', 'los', 'es', 'son', 'cuando']
};
text = text.toLowerCase();
for (const [lang, words] of Object.entries(languages)) {
if (words.some(word => text.includes(word))) {
return lang;
}
}
return 'en'; // Default to English
}
async function translateText(text, targetLang) {
const response = await fetch('http://localhost:5000/translate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
text,
target_lang: targetLang
})
});
const data = await response.json();
return data.translated_text;
}
async function getAIResponse(text, modelName) {
try {
const response = await fetch('http://localhost:5000/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
text,
model: modelName
})
});
const data = await response.json();
return data.response;
} catch (error) {
console.error('Error getting AI response:', error);
return 'Error: Could not get response from the model.';
}
}
function addMessage(text, isUser = false) {
const chatContainer = document.getElementById('chat-container');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
messageDiv.textContent = text;
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
async function handleSend() {
const input = document.getElementById('message-input');
const text = input.value.trim();
if (!text) return;
addMessage(text, true);
input.value = '';
const detectedLang = detectLanguage(text);
currentLanguage = detectedLang;
currentResponses = [];
currentModelIndex = 0;
document.getElementById('model-info').textContent = 'Loading responses...';
// Show loading indicator
addMessage('...', false);
const lastMessage = document.querySelector('.ai-message:last-child');
// Get responses from all models for the detected language
for (const model of models[detectedLang]) {
const response = await getAIResponse(text, model);
currentResponses.push(response);
}
// Update the last message with the actual response
if (lastMessage) {
lastMessage.textContent = currentResponses[0];
}
document.getElementById('model-info').textContent =
`Model ${currentModelIndex + 1}/3: ${models[detectedLang][currentModelIndex]}`;
}
document.getElementById('send-button').addEventListener('click', handleSend);
document.getElementById('message-input').addEventListener('keypress', (e) => {
if (e.key === 'Enter') handleSend();
});
document.getElementById('next-response').addEventListener('click', () => {
if (currentResponses.length === 0) return;
currentModelIndex = (currentModelIndex + 1) % 3;
const lastMessage = document.querySelector('.ai-message:last-child');
if (lastMessage) {
lastMessage.textContent = currentResponses[currentModelIndex];
}
document.getElementById('model-info').textContent =
`Model ${currentModelIndex + 1}/3: ${models[currentLanguage][currentModelIndex]}`;
});
document.getElementById('translate-button').addEventListener('click', async () => {
const targetLang = document.getElementById('translate-to').value;
const lastMessage = document.querySelector('.ai-message:last-child');
if (!lastMessage) return;
const originalText = lastMessage.textContent;
lastMessage.textContent = 'Translating...';
const translatedText = await translateText(originalText, targetLang);
lastMessage.textContent = translatedText;
});
// Settings functionality
document.getElementById('open-popup-settings').addEventListener('click', () => {
const settingsPanel = document.getElementById('settings-panel');
settingsPanel.style.display = settingsPanel.style.display === 'none' ? 'block' : 'none';
});
document.getElementById('save-popup-settings').addEventListener('click', () => {
const theme = document.getElementById('popup-theme-select').value;
const fontSize = document.getElementById('popup-font-size-select').value;
localStorage.setItem('popupTheme', theme);
localStorage.setItem('popupFontSize', fontSize);
applyUserSettings();
document.getElementById('settings-panel').style.display = 'none';
});