-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnew_feature.py
More file actions
49 lines (43 loc) · 1.75 KB
/
new_feature.py
File metadata and controls
49 lines (43 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
from flask import Flask, request, jsonify
from pathlib import Path
from logging_utils import setup_logger
from textblob import TextBlob
import datetime
def analyze_sentiment(text: str) -> dict:
"""Analyze sentiment of the given text using TextBlob."""
blob = TextBlob(text)
polarity = blob.sentiment.polarity
subjectivity = blob.sentiment.subjectivity
sentiment = "positive" if polarity > 0.1 else "negative" if polarity < -0.1 else "neutral"
return {
"sentiment": sentiment,
"polarity": polarity,
"subjectivity": subjectivity
}
def log_sentiment_analysis(text: str, result: dict, logger):
timestamp = datetime.datetime.utcnow().isoformat()
logger.info(f"[{timestamp}] Sentiment analysis for text: '{text}' | Result: {result}")
def new_feature():
"""
Flask API endpoint for sentiment analysis.
POST /api/sentiment-analysis
Body: { "text": "..." }
Response: { "sentiment": "...", "polarity": ..., "subjectivity": ... }
"""
app = Flask(__name__)
LOG_PATH = Path(os.getenv("TARGET_REPO_PATH", os.getcwd())) / "sentiment_analysis.log"
logger = setup_logger("sentiment_api", str(LOG_PATH), level=os.getenv("API_LOG_LEVEL", "INFO"))
@app.route("/api/sentiment-analysis", methods=["POST"])
def sentiment_analysis():
data = request.get_json()
if not data or "text" not in data:
logger.warning("No text provided for sentiment analysis.")
return jsonify({"error": "Missing 'text' in request body"}), 400
text = data["text"]
result = analyze_sentiment(text)
log_sentiment_analysis(text, result, logger)
return jsonify(result), 200
app.run(host="0.0.0.0", port=5050)
if __name__ == "__main__":
new_feature()