Spaces:
Sleeping
Sleeping
Download flask_api.py from dkvbabu/fdp-flask-api: direct link, hf CLI and curl.
- Browser
- Download file 1.81 kB
-
https://huggingface.co/spaces/dkvbabu/fdp-flask-api/resolve/main/flask_api.py
- Command line
-
hf download hf://spaces/dkvbabu/fdp-flask-api/flask_api.py
-
curl -L -o flask_api.py https://huggingface.co/spaces/dkvbabu/fdp-flask-api/resolve/main/flask_api.py
1.81 kB
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| import joblib | |
| import os | |
| app = Flask(__name__) | |
| CORS(app) # Allows Streamlit Space to call this API | |
| # Load model | |
| model = joblib.load('sentiment_model.pkl') | |
| def home(): | |
| return jsonify({ | |
| 'message': 'FDP Sentiment API is running on Hugging Face!', | |
| 'endpoints': ['/predict POST', '/batch_predict POST', '/health GET'] | |
| }) | |
| def health(): | |
| return jsonify({'status': 'healthy', 'model': 'TF-IDF + Logistic Regression'}) | |
| def predict(): | |
| data = request.get_json() | |
| text = data.get('text', '').strip() | |
| if not text: | |
| return jsonify({"error": "Empty text provided"}), 400 | |
| if len(text) < 3: | |
| return jsonify({"error": "Text too short"}), 400 | |
| pred_label = model.predict([text])[0] | |
| confidence = 0.95 | |
| if hasattr(model, 'predict_proba'): | |
| try: | |
| proba = model.predict_proba([text])[0] | |
| classes = list(model.classes_) | |
| idx = classes.index(str(pred_label)) | |
| confidence = float(proba[idx]) | |
| except Exception: | |
| pass | |
| return jsonify({ | |
| "sentiment": str(pred_label), | |
| "confidence": round(confidence, 4) | |
| }) | |
| def batch(): | |
| data = request.get_json() | |
| preds = model.predict(data['texts']) | |
| probas = model.predict_proba(data['texts']) | |
| results = [ | |
| {'text': t, 'sentiment': p, 'confidence': float(round(max(pr), 4))} | |
| for t, p, pr in zip(data['texts'], preds, probas) | |
| ] | |
| return jsonify({'results': results}) | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) # HF Spaces requires port 7860 | |