Skip to content

8-chems/Sentiment-Analysis-App

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sentiment Analysis Application

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.

Project Structure

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

Overview

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.

Prerequisites

  • Python 3.8+ (for backend)
  • Node.js (for frontend, if using React/Vue)
  • Dependencies (install in the back folder):
    • FastAPI (pip install fastapi)
    • Uvicorn (pip install uvicorn)
    • Pydantic (pip install pydantic)
    • Requests (pip install requests)
    • python-dotenv (pip install python-dotenv)
  • A Groq API key (set in back/.env)

Setup

  1. Clone the Repository:

    git clone <repository-url>
    cd main
  2. Backend Setup (in back/):

    • Install dependencies:
      cd back
      pip install -r requirements.txt
    • Create a .env file in back/ 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 at http://localhost:8000/docs.
  3. 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/analyze with a JSON payload like { "text": "your text here" }.

Using the Web App

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:
    curl -X POST http://localhost:8000/analyze -H "Content-Type: application/json" -d '{"text": "I love this product!"}'
    Example response:
    {"sentiment": "Positive", "confidence": 0.92}

Ensure the FRONTEND_URL in back/.env matches the frontend's URL to avoid CORS issues.

Adapting for a Browser Plugin

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.

Steps to Implement a Browser Plugin

  1. 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
    
  2. 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'"
      }
    }
  3. 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>
  4. Implement popup.js (adapted from model.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;
      }
    });
  5. 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);
      }
    });
  6. 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. Modify popup.js to send requests to http://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' in popup.js with your Groq API key, but this exposes the key in the client-side code.
  7. 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.
  8. 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 --reload in back/).
    • The popup will display the sentiment analysis results.

Security Notes

  • API Key: Store the Groq API key securely in back/.env for 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_URL in back/.env includes 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.

Limitations

  • 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.

Contributing

Submit issues or pull requests to improve the project. Ensure changes are compatible with the existing front and back structure and the Groq API.

License

This project is licensed under the MIT License.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors