Spaces:
Sleeping
Sleeping
File size: 3,079 Bytes
59b54d3 | 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | from flask import Blueprint, request, jsonify, session
import os
import re
from src.services import supabase_service
from src.models import emotion_engine
from src.core.config import Config
from src.core.exceptions import ValidationError, AuthError
from src.utils.logger import setup_logging
logger = setup_logging("analysis_api")
analysis_bp = Blueprint('analysis', __name__)
def is_gibberish(text):
alpha_text = ''.join(filter(str.isalpha, text))
if not alpha_text: return False
if re.search(r'[^aeiouyAEIOUY]{6,}', alpha_text): return True
if not re.search(r'[aeiouyAEIOUY]', alpha_text): return True
return False
def require_auth():
user = session.get('user')
if not user:
raise AuthError("Please sign in to use the analyzer.")
return user
@analysis_bp.route('/api/analyze/text', methods=['POST'])
def analyze_text_route():
user = require_auth()
data = request.get_json() or {}
text = data.get('text', '').strip()
if not text:
raise ValidationError("Text cannot be empty")
if is_gibberish(text):
raise ValidationError("Invalid input; please enter a valid sentence.")
result = emotion_engine.analyze_text(text)
supabase_service.log_analysis(
user.get('id'), 'text', text,
result['emotion'], result['stress_level'],
result['confidence'], result.get('stress_score', 0.0)
)
session['last_emotion'] = result['emotion']
return jsonify(result)
@analysis_bp.route('/api/analyze/image', methods=['POST'])
def analyze_image_route():
user = require_auth()
if 'image' not in request.files:
raise ValidationError("No image provided")
file = request.files['image']
if file.filename == '':
raise ValidationError("No image selected")
temp_path = os.path.join(Config.UPLOAD_FOLDER, f"temp_{user['id']}.jpg")
os.makedirs(Config.UPLOAD_FOLDER, exist_ok=True)
file.save(temp_path)
try:
result = emotion_engine.analyze_image_emotion(temp_path)
if result.get('face_detected'):
supabase_service.log_analysis(
user.get('id'), 'image', None,
result['emotion'], result['stress_level'],
result['confidence'], result.get('stress_score', 0.0)
)
session['last_emotion'] = result['emotion']
return jsonify(result)
finally:
if os.path.exists(temp_path): os.remove(temp_path)
@analysis_bp.route('/api/analyze/image_string', methods=['POST'])
def analyze_image_string_route():
user = require_auth()
data = request.get_json() or {}
img_data = data.get('image')
if not img_data:
raise ValidationError("No image data provided")
result = emotion_engine.analyze_image_base64(img_data)
supabase_service.log_analysis(
user.get('id'), 'image_camera', None,
result['emotion'], result['stress_level'],
result['confidence'], result.get('stress_score', 0.0)
)
session['last_emotion'] = result['emotion']
return jsonify(result)
|