views.py
from django.http import JsonResponse
from django import views
from django.views.decorators.csrf import csrf_exempt
import json
import logging
from langdetect import detect
import asyncio
import aiohttp

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s:%(message)s')

# Model configuration
MODEL_MAP = {
    'en': ['Undi95/Unholy-v2-13B', 'SanjiWatsuki/Loyal-Macaroni-Maid-7B', 'Undi95/Amethyst-13B'],  # Two models for English
    'de': ['dbmdz/german-gpt2'],                     # One model for German
    'fr': ['Helsinki-NLP/opus-mt-en-fr'],            # One model for French
    'es': ['Helsinki-NLP/opus-mt-en-es']             # One model for Spanish
}

HUGGING_FACE_API_KEY = '<TRUFFLEHOG_REDACTED_HUGGINGFACE>'  # Replace with your API key

@csrf_exempt
async def generate_response(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            message = data.get('message', '')

            # Detect language
            detected_language = detect(message)
            logging.info(f"Detected language: {detected_language}")

            # Get appropriate models based on detected language
            model_names = MODEL_MAP.get(detected_language.lower())
            if not model_names:
                return JsonResponse({'error': f'No model available for detected language: {detected_language}'}, status=400)

            # Perform asynchronous requests
            responses = await asyncio.gather(*[fetch_response(model_name, message) for model_name in model_names])

            # Aggregate responses
            aggregated_response = ' '.join(responses)
            return JsonResponse({'response': aggregated_response})

        except Exception as e:
            logging.error(f"Error during request processing: {str(e)}")
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': 'Invalid HTTP method'}, status=405)

async def fetch_response(model_name, message):
    """
    Helper function to fetch response from Hugging Face asynchronously.
    """
    headers = {
        'Authorization': f'Bearer {HUGGING_FACE_API_KEY}',
        'Content-Type': 'application/json'
    }
    api_url = f'https://api-inference.huggingface.co/models/{model_name}'
    
    async with aiohttp.ClientSession() as session:
        async with session.post(api_url, headers=headers, json={'inputs': message}) as response:
            if response.status == 200:
                result = await response.json()
                return result.get('generated_text', '')
            else:
                response_text = await response.text()
                logging.error(f"Error fetching from {model_name}: {response_text}")
                return ''

background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  fetch('YOUR_BACKEND_ENDPOINT_URL', { // Replace with your server endpoint
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ message: request.message })
  })
  .then(response => response.json())
  .then(data => {
    sendResponse({ reply: data.response }); // Match key with your Django view response
  })
  .catch(error => console.error('Error fetching from server:', error));

  return true;  // Indicates asynchronous response
});

content.js
function createFloatingWindow(message, response) {
  // Remove any existing floating window
  const existingWindow = document.getElementById('floating-window');
  if (existingWindow) {
    existingWindow.remove();
  }

  // Create a new floating window
  const floatingWindow = document.createElement('div');
  floatingWindow.id = 'floating-window';
  floatingWindow.style.position = 'fixed';
  floatingWindow.style.width = '15cm';
  floatingWindow.style.height = '5cm';
  floatingWindow.style.bottom = '10px';
  floatingWindow.style.right = '10px';
  floatingWindow.style.border = '1px solid #ccc';
  floatingWindow.style.backgroundColor = '#fff';
  floatingWindow.style.zIndex = '9999';
  floatingWindow.style.padding = '10px';
  floatingWindow.style.boxShadow = '0 2px 10px rgba(0,0,0,0.1)';

  // Add content to the floating window
  floatingWindow.innerHTML = `
    <p><strong>Detected Message:</strong> <span id="detected-message">${message}</span></p>
    <textarea id="manual-message" rows="3" style="width: 100%;">${message}</textarea>
    <button id="paste-button">Paste</button>
    <p><strong>Generated Response:</strong> <span id="generated-response">${response}</span></p>
    <button id="generate-new">Generate New</button>
    <button id="insert-text">Insert Text</button>
  `;

  document.body.appendChild(floatingWindow);

  // Add event listeners
  document.getElementById('paste-button').addEventListener('click', () => {
    const newMessage = document.getElementById('manual-message').value;
    document.getElementById('detected-message').innerText = newMessage;
  });

  document.getElementById('generate-new').addEventListener('click', () => {
    const messageText = document.getElementById('detected-message').innerText;
    chrome.runtime.sendMessage({ message: messageText }, function (response) {
      if (response && response.reply) {
        document.getElementById('generated-response').innerText = response.reply;
      }
    });
  });

  document.getElementById('insert-text').addEventListener('click', () => {
    const textField = document.querySelector('.text-input'); // Identify the correct CSS selector
    const generatedResponse = document.getElementById('generated-response').innerText;
    if (textField) {
      textField.value = generatedResponse;
    }
  });
}

setInterval(() => {
  const chatMessages = document.querySelectorAll('.message'); // Identify the correct CSS selector
  if (chatMessages.length > 0) {
    const lastMessage = chatMessages[chatMessages.length - 1];
    const messageText = lastMessage.textContent;

    chrome.runtime.sendMessage({ message: messageText }, function (response) {
      if (response && response.reply) {
        createFloatingWindow(messageText, response.reply);
      }
    });
  }
}, 5000); // Adjust interval as needed

manifest.json
{
  "manifest_version": 3,
  "name": "Chat Responder",
  "version": "1.0",
  "permissions": [
    "activeTab",
    "scripting"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

popup.html
<!DOCTYPE html>
<html>
<head>
    <title>Chat Responder</title>
</head>
<body>
    <h1>Chat Responder</h1>
    <p>Automatically responds to the last message using AI.</p>
</body>
</html>

I wanted to create a browser extension that automatically reads messages on a chat site and responds to the last message using the code above. Unfortunately it is not working. Can you analyze the code to identify what might be causing the problem? Also, please modify the code where necessary so that it only works when I click on it's icon on the pinned extension list and stops working when I click on it again. I have already pinned it.