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 ''

urls.py
from django.contrib import admin
from django import views
from django.urls import path
from .views import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('generate-response/', views.generate_response, name='generate_response'),

]

background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  fetch('YOUR_BACKEND_ENDPOINT_URL', { // Replace with your server endpoint handling HF API calls
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ message: request.message })
  })
  .then(response => response.json())
  .then(data => {
    sendResponse({ reply: data['generated_text'] });
  });

  return true;  // Indicates asynchronous response
});

content.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:', error));

  return true;  // Indicates asynchronous response
});

// Script to dynamically interact with chat DOM
setInterval(() => {
  const chatMessages = document.querySelectorAll('.message'); // Identify the correct CSS selector
  if (chatMessages.length > 0) {
    const lastMessage = chatMessages[chatMessages.length - 1];
    const textField = document.querySelector('.text-input'); // Identify the correct CSS selector

    if (lastMessage && textField) {
      const messageText = lastMessage.textContent;

      // Send message to background script
      chrome.runtime.sendMessage({ message: messageText }, function(response) {
        if (response && response.reply) {
          textField.value = response.reply; // Populate the text input with AI response
        }
      });
    }
  }
}, 5000); // Change interval as needed

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>

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"]
    }
  ]
}

I am using the above code to create a floating browser extension that automatically reads the last message in a chatting site and automatically responds to it. I however want you to modify it with advanced features so that after identifying the message it wants to responds to, it also show which message so that I can be sure it is responding to the right message. There should be a paste option in case it captured the wrong message, I can paste the message I want it to respond to. Also, I want it to show me the message it generated with two options, 1. Generate new (It automatically generates a new response to the same message) 2. Insert text (It inserts the message in the text box in the chat site) The floating window should be around 15 cm long and 5 cm height. Include any complex features to make it amazing