This project is a sentiment analysis application with a web app and the potential to be adapted into a browser plugin. The project is structured with a front folder for the frontend and a back folder for the FastAPI-based backend, which uses the Groq API to analyze text sentiment.
main/
├── front/ # Frontend code (e.g., React, Vue)
├── back/ # Backend code (FastAPI)
│ ├── main.py # FastAPI application
│ ├── model.py # SentimentAnalyzer class
│ └── .env # Environment variables (GROQ_API_KEY, FRONTEND_URL)
└── README.md # This file
The backend (back/) is a FastAPI application that accepts text input via a POST request to /analyze and returns the sentiment (Positive/Negative) with a confidence score. The frontend (front/) is assumed to be an existing web interface that interacts with the backend. The sentiment analysis logic can also be adapted for a browser plugin to analyze selected text on webpages.
- Python 3.8+ (for backend)
- Node.js (for frontend, if using React/Vue)
- Dependencies (install in the
backfolder):- FastAPI (
pip install fastapi) - Uvicorn (
pip install uvicorn) - Pydantic (
pip install pydantic) - Requests (
pip install requests) - python-dotenv (
pip install python-dotenv)
- FastAPI (
- A Groq API key (set in
back/.env)
-
Clone the Repository:
git clone <repository-url> cd main
-
Backend Setup (in
back/):- Install dependencies:
cd back pip install -r requirements.txt - Create a
.envfile inback/with:GROQ_API_KEY=your_api_key_here FRONTEND_URL=http://localhost:3000 # Adjust to match your frontend URL - Run the FastAPI server:
uvicorn main:app --reload
- The API will be available at
http://localhost:8000. Access the interactive API docs athttp://localhost:8000/docs.
- Install dependencies:
-
Frontend Setup (in
front/):- Navigate to the frontend directory:
cd front - Install dependencies (assuming a Node.js-based frontend):
npm install
- Start the frontend (e.g., for React):
npm start
- Ensure the frontend is configured to send POST requests to
http://localhost:8000/analyzewith a JSON payload like{ "text": "your text here" }.
- Navigate to the frontend directory:
The web app is fully functional with the provided backend and frontend:
- The frontend (e.g., running at
http://localhost:3000) allows users to input text and submit it to the backend. - The backend processes the text using the Groq API and returns the sentiment and confidence score.
- Example API request:
Example response:
curl -X POST http://localhost:8000/analyze -H "Content-Type: application/json" -d '{"text": "I love this product!"}'
{"sentiment": "Positive", "confidence": 0.92}
Ensure the FRONTEND_URL in back/.env matches the frontend's URL to avoid CORS issues.
The sentiment analysis logic in back/model.py can be adapted into a browser plugin (e.g., for Chrome or Firefox) to analyze selected text on webpages without modifying the existing web app.
-
Create a Plugin Directory: Create a new folder outside the
main/directory (e.g.,sentiment-plugin/) with the following structure:sentiment-plugin/ ├── manifest.json ├── popup.html ├── popup.js └── background.js -
Configure
manifest.json:{ "manifest_version": 3, "name": "Sentiment Analyzer Plugin", "version": "1.0", "description": "Analyze sentiment of selected text using Groq API", "permissions": ["activeTab", "contextMenus"], "background": { "service_worker": "background.js" }, "action": { "default_popup": "popup.html" }, "content_security_policy": { "extension_pages": "script-src 'self'; object-src 'self'" } } -
Create
popup.html:<!DOCTYPE html> <html> <head> <title>Sentiment Analyzer</title> <style> body { width: 300px; padding: 10px; font-family: Arial; } textarea { width: 100%; height: 100px; } button { width: 100%; margin-top: 10px; } </style> </head> <body> <textarea id="textInput"></textarea> <button onclick="analyze()">Analyze Sentiment</button> <div id="result"></div> <script src="popup.js"></script> </body> </html>
-
Implement
popup.js(adapted frommodel.py):async function analyze() { const text = document.getElementById('textInput').value; if (!text.trim()) { document.getElementById('result').innerText = 'Please enter text'; return; } // Use the same API endpoint and model as in model.py const apiKey = 'your_groq_api_key_here'; // Replace with Groq API key or use a proxy const endpoint = 'https://api.groq.com/openai/v1/chat/completions'; const prompt = `Analyze the sentiment of the following text and respond with ONLY "Positive" or "Negative" followed by a confidence score between 0 and 1, separated by a comma.\n\nText to analyze: "${text}"\n\nResponse:`; try { const response = await fetch(endpoint, { method: 'POST', headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'llama3-70b-8192', messages: [{ role: 'user', content: prompt }], temperature: 0.0, max_tokens: 20 }) }); if (!response.ok) throw new Error('API request failed'); const result = await response.json(); const content = result.choices[0].message.content.trim(); const [sentiment, confidence] = content.split(','); document.getElementById('result').innerText = `Sentiment: ${sentiment}, Confidence: ${confidence}`; } catch (error) { document.getElementById('result').innerText = 'Error analyzing sentiment'; console.error(error); } } // Auto-populate with selected text chrome.runtime.sendMessage({ action: 'getSelectedText' }, (response) => { if (response && response.text) { document.getElementById('textInput').value = response.text; } });
-
Implement
background.js:chrome.contextMenus.create({ id: 'analyze-sentiment', title: 'Analyze Sentiment', contexts: ['selection'] }); chrome.contextMenus.onClicked.addListener((info, tab) => { if (info.menuItemId === 'analyze-sentiment') { chrome.action.openPopup(); chrome.runtime.sendMessage({ action: 'setSelectedText', text: info.selectionText }); } }); chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.action === 'getSelectedText') { sendResponse({ text: localStorage.getItem('selectedText') || '' }); } else if (request.action === 'setSelectedText') { localStorage.setItem('selectedText', request.text); } });
-
Secure the API Key:
- Option 1: Use the Backend: Instead of hardcoding the Groq API key in
popup.js, proxy requests through the existing FastAPI backend to keep the key secure. Modifypopup.jsto send requests tohttp://localhost:8000/analyze:async function analyze() { const text = document.getElementById('textInput').value; if (!text.trim()) { document.getElementById('result').innerText = 'Please enter text'; return; } try { const response = await fetch('http://localhost:8000/analyze', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) }); if (!response.ok) throw new Error('API request failed'); const result = await response.json(); document.getElementById('result').innerText = `Sentiment: ${result.sentiment}, Confidence: ${result.confidence}`; } catch (error) { document.getElementById('result').innerText = 'Error analyzing sentiment'; console.error(error); } }
- Option 2: Hardcode the Key (Not Recommended): Replace
'your_groq_api_key_here'inpopup.jswith your Groq API key, but this exposes the key in the client-side code.
- Option 1: Use the Backend: Instead of hardcoding the Groq API key in
-
Load the Plugin in Chrome:
- Open Chrome and go to
chrome://extensions/. - Enable "Developer mode" (top right).
- Click "Load unpacked" and select the
sentiment-plugin/directory.
- Open Chrome and go to
-
Test the Plugin:
- Right-click selected text on a webpage and choose "Analyze Sentiment" from the context menu, or click the plugin icon to open the popup.
- If using the backend proxy, ensure the FastAPI server is running (
uvicorn main:app --reloadinback/). - The popup will display the sentiment analysis results.
- API Key: Store the Groq API key securely in
back/.envfor the web app. For the plugin, use the FastAPI backend as a proxy to avoid exposing the key in client-side code. - CORS: Ensure
FRONTEND_URLinback/.envincludes the frontend's URL (e.g.,http://localhost:3000) and, if using the backend for the plugin, add the plugin's origin or use a wildcard (*) temporarily for testing. - Production: For production, deploy the backend to a secure server (e.g., with HTTPS) and update the plugin to use the deployed endpoint.
- The Groq API key must be valid and active.
- The plugin requires an internet connection to communicate with the Groq API or the FastAPI backend.
- If using the backend proxy, the FastAPI server must be running for the plugin to work.
Submit issues or pull requests to improve the project. Ensure changes are compatible with the existing front and back structure and the Groq API.
This project is licensed under the MIT License.