ocrsensitive / app /routes.py
mashaelalbu's picture
Update app/routes.py
f5f221e verified
# routes.py (معدل)
from flask import Blueprint, jsonify, request, current_app
import io
import pandas as pd
from app.utils import OCRModel, AllergyAnalyzer
import logging
import os
import requests
from PIL import Image
import nltk
nltk.download('punkt', quiet=True)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
main = Blueprint('main', __name__)
ocr_model = OCRModel()
allergy_analyzer = None
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
def init_allergy_analyzer(app):
"""تهيئة محلل الحساسيات باستخدام سياق التطبيق"""
global allergy_analyzer
if allergy_analyzer is None:
with app.app_context():
allergy_analyzer = AllergyAnalyzer(current_app.config['ALLERGY_DATASET_PATH'])
def allowed_file(filename):
"""Validate file extension"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@main.route('/api/ocr', methods=['POST'])
def process_image():
global allergy_analyzer
try:
if 'file' not in request.files:
logger.warning("No file uploaded")
return jsonify({"error": "No file uploaded"}), 400
file = request.files['file']
if file.filename == '':
logger.warning("No file selected")
return jsonify({"error": "No file selected"}), 400
if not allowed_file(file.filename):
logger.warning(f"Invalid file type: {file.filename}")
return jsonify({
"error": "File type not supported",
"supported_formats": list(ALLOWED_EXTENSIONS)
}), 400
# الحصول على حساسيات المستخدم من الطلب
user_allergies = request.form.get('user_allergies', '').split(',')
user_allergies = [a.strip().lower() for a in user_allergies if a.strip()]
if not user_allergies:
logger.warning("No user allergies provided")
return jsonify({"error": "User allergies not provided"}), 400
# تأكد من تهيئة محلل الحساسيات
if allergy_analyzer is None:
init_allergy_analyzer(current_app._get_current_object())
# معالجة الصورة
file_bytes = file.read()
file_stream = io.BytesIO(file_bytes)
image = Image.open(file_stream)
# تحليل الصورة مع مراعاة حساسيات المستخدم
analysis_results = allergy_analyzer.analyze_image(
image,
current_app.config['CLAUDE_API_KEY'],
user_allergies=user_allergies
)
# بناء الاستجابة
response = {
"success": True,
"user_allergies": user_allergies,
"extracted_text": analysis_results.get("extracted_text", ""),
"analysis": {
"detected_allergens": analysis_results.get("detected_allergens", []),
"database_matches": analysis_results.get("database_matches", {}),
"claude_matches": analysis_results.get("claude_matches", {}),
"analyzed_tokens": analysis_results.get("analyzed_tokens", [])
},
"warnings": {
"has_allergens": len(analysis_results.get("detected_allergens", [])) > 0,
"message": "⚠️ Warning: Allergens found that match your allergies!" if analysis_results.get("detected_allergens") else "✅ No allergens found that match your allergies",
"severity": "high" if analysis_results.get("detected_allergens") else "none"
}
}
logger.info("Analysis completed successfully")
return jsonify(response)
except Exception as e:
logger.error(f"Error processing request: {str(e)}", exc_info=True)
return jsonify({
"error": "An error occurred while processing the image.",
"details": str(e)
}), 500