Spaces:
Running
Running
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| from transformers import pipeline | |
| app = Flask(__name__) | |
| CORS(app) # Allow requests from the HTML frontend | |
| # Load model once on startup (same model as original Streamlit project) | |
| print("Loading model... (this may take a minute on first run)") | |
| nlp = pipeline( | |
| "sentiment-analysis", | |
| model="w11wo/indonesian-roberta-base-sentiment-classifier" | |
| ) | |
| print("Model loaded! Server ready.") | |
| def analyze(): | |
| data = request.get_json() | |
| comments = data.get("comments", []) | |
| if not comments: | |
| return jsonify({"error": "No comments provided"}), 400 | |
| if len(comments) > 10: | |
| comments = comments[:10] | |
| results = [] | |
| for text in comments: | |
| try: | |
| prediction = nlp(text) | |
| label = prediction[0]["label"] # e.g. "positive" | |
| score = prediction[0]["score"] | |
| # Normalize label to Title Case | |
| label_map = {"positive": "Positive", "negative": "Negative", "neutral": "Neutral"} | |
| sentiment = label_map.get(label.lower(), label.capitalize()) | |
| results.append({ | |
| "comment": text, | |
| "sentiment": sentiment, | |
| "score": round(score, 4) | |
| }) | |
| except Exception as e: | |
| results.append({ | |
| "comment": text, | |
| "sentiment": "Neutral", | |
| "score": 0.5, | |
| "error": str(e) | |
| }) | |
| return jsonify({"results": results}) | |
| def health(): | |
| return jsonify({"status": "ok", "model": "w11wo/indonesian-roberta-base-sentiment-classifier"}) | |
| def index(): | |
| return jsonify({ | |
| "name": "SentiMind API", | |
| "description": "Indonesian Sentiment Analysis API", | |
| "endpoints": { | |
| "POST /analyze": "Analyze sentiment of comments", | |
| "GET /health": "Check server status" | |
| } | |
| }) | |
| # Hugging Face Spaces uses port 7860 | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860, debug=False) | |