amadmateen's picture
Refactor: Production-grade modular layout, NLTK permissions fix, and editorial audit dashboard overhaul
405a3f0
Raw History Blame Contribute Delete
3.4 kB
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)