Spaces:
Sleeping
Sleeping
File size: 3,398 Bytes
405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d 405a3f0 b9cb33d | 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 | import logging
import io
import base64
from flask import Flask, render_template, request, jsonify
from PIL import Image
from src.config import MAX_CONTENT_LENGTH, MODEL_PATH
from src.inference import get_or_load_resources, predict_review, generate_explanation
# Set up logging configuration
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s'
)
logger = logging.getLogger(__name__)
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH
# Global status tracker
models_loaded = False
# Warm up model weights, download sentiment lexicons, and cache-boot clients immediately at module import
try:
logger.info("Initializing SentinelReview AI backend resources at startup...")
get_or_load_resources()
models_loaded = True
logger.info("SentinelReview AI initialization complete. System fully operational.")
except Exception as e:
logger.critical(f"Failed to initialize server models during startup: {e}", exc_info=True)
models_loaded = False
@app.route('/')
def index():
"""Serves the main dashboard application interface."""
return render_template('index.html', models_status=models_loaded)
@app.route('/analyze', methods=['POST'])
def analyze():
"""
API Endpoint: Audits a review text and context image.
Performs classification and requests text explanations.
"""
if not models_loaded:
return jsonify({"error": "Platform models failed to load. Please audit server logs."}), 503
review_text = request.form.get('review_text', '').strip()
if not review_text:
return jsonify({"error": "No text review content was provided."}), 400
# 1. Process context image (if uploaded)
image_b64 = None
if 'review_image' in request.files and request.files['review_image'].filename != '':
image_file = request.files['review_image']
try:
image = Image.open(image_file)
image.thumbnail((400, 400))
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
image_b64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
logger.info("Context image successfully parsed and encoded.")
except Exception as e:
logger.warning(f"Failed to process context image: {e}")
# 2. Run core classification prediction
try:
logger.info(f"Auditing review text (Length: {len(review_text)} chars)...")
results = predict_review(review_text)
# 3. Retrieve explanation
explanation = generate_explanation(review_text, results['classification'])
# 4. Compile audit response
return jsonify({
"classification": results['classification'],
"confidence": f"{int(results['confidence'] * 100)}%",
"explanation": explanation,
"image": image_b64,
"metrics": results['metrics']
})
except ValueError as val_err:
logger.error(f"Validation error: {val_err}")
return jsonify({"error": str(val_err)}), 400
except Exception as err:
logger.error(f"Inference crash during review classification: {err}", exc_info=True)
return jsonify({"error": f"Internal classification pipeline error: {str(err)}"}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860) |