Spaces:
Sleeping
Sleeping
File size: 4,024 Bytes
0ef66b6 bd5b754 2cf116a bd5b754 7a45448 2cf116a 7a45448 2cf116a bd5b754 7a45448 bd5b754 680256a 7a45448 7689ca0 61c5622 680256a 0ef66b6 c4d7fee 680256a 0ef66b6 bd5b754 0ef66b6 bd5b754 680256a 0ef66b6 bd5b754 0ef66b6 680256a 0ef66b6 bd5b754 7689ca0 bd5b754 f5f221e |
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 94 95 96 97 98 99 100 101 102 103 |
# 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 |