This project implements a lightweight Flask-based RESTful API for real-time sentiment analysis. It leverages a pre-trained transformer model from Hugging Face — StatsGary/setfit-ft-sentinent-eval — to classify user-input text into positive, negative, or neutral sentiment. The app provides a single /analyze endpoint and returns structured JSON responses, making it suitable for integration into larger applications or services.
Backend: Flask (Python)
Model: Hugging Face setfit-ft-sentinent-eval (SetFit architecture for few-shot learning)
Frontend: Basic HTML5/CSS3 interface for user input
Workflow:
User submits text via web form.
Taking an input and analyzing the sentiment.
Flask backend processes and routes the text to the pre-trained transformer.
Sentiment is inferred and returned as a JSON object.
# Route of sentiment analysis api @app.route('/analyze', methods=['POST']) def sentiment_analysis(): try: # The text to be analyzed from the form data text = request.form['text'] # Analyze the sentiment of text using pre-trained model result = model(text)[0] sentiment = result['label'] sentiment_jsonify = {} # text_jsonify = {} # Create JSON response. json_text = {'text': text} json_data = {'sentiment': sentiment} # Print JSON respone to command prompt sentiment_jsonify = json_data print(json.dumps(json_data)) # Return the rendered template with sentiment and text return render_template('home.html', sentiment=sentiment, sentiment_json=sentiment_jsonify, json_text=json_text) except Exception as e: # If an exception occurs, display an error message in the template error_msg = str(e) return render_template('home.html', error_msg=error_msg)
Output is rendered on the page and optionally displayed in raw JSON.
The system demonstrates strong performance in detecting positive and negative sentiments in diverse examples. Output is consistently accurate with clear sentiment categories. Sample API usage shows proper structuring of responses such as:
json
{
"sentiment": "Positive"
}
| Input Text | Output Text |
|---|---|
| I enjoyed the food but the staff was rude. | Negative |
| I love drinking cold water in summer. | Positive |
| There is a road by our house. | Positive (borderline neutral) |
While the model performs well on strongly polarized text, it tends to over-classify neutral or mixed sentiments as positive, which is a known limitation of many sentiment models. To enhance accuracy and robustness:
Fine-tuning on custom datasets with better neutral representation is recommended.
Alternative architectures like LSTMs or CNNs, or further tuning of SetFit hyperparameters, could help the model better capture subtle or ambiguous tones.
Github repository, codes of this will be found below.