Spaces:
Sleeping
Sleeping
Update app/routes.py
Browse files- app/routes.py +111 -139
app/routes.py
CHANGED
@@ -1,140 +1,112 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
import
|
4 |
-
from app.utils import OCRModel
|
5 |
-
import logging
|
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 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
"success": True,
|
113 |
-
"extracted_text": extracted_text,
|
114 |
-
"analysis": {
|
115 |
-
"found_allergens": list(found_allergens),
|
116 |
-
"allergen_details": allergen_details,
|
117 |
-
"allergen_locations": allergen_locations,
|
118 |
-
"has_allergens": len(found_allergens) > 0,
|
119 |
-
"warning": "⚠️ Warning: Allergens found!" if found_allergens else "✅ No allergens found",
|
120 |
-
"severity": "high" if len(found_allergens) > 0 else "none"
|
121 |
-
}
|
122 |
-
}
|
123 |
-
|
124 |
-
logger.info(f"Analysis completed successfully: {found_allergens}")
|
125 |
-
return jsonify(response)
|
126 |
-
|
127 |
-
except Exception as e:
|
128 |
-
logger.error(f"Error processing request: {str(e)}", exc_info=True)
|
129 |
-
return jsonify({
|
130 |
-
"error": "An error occurred while processing the image.",
|
131 |
-
"details": str(e)
|
132 |
-
}), 500
|
133 |
-
|
134 |
-
@main.route('/api/allergens', methods=['GET'])
|
135 |
-
def get_known_allergens():
|
136 |
-
return jsonify({
|
137 |
-
"allergens": KNOWN_ALLERGENS,
|
138 |
-
"total_count": len(KNOWN_ALLERGENS),
|
139 |
-
"last_updated": "2024-03-24" # Update this date when the list is updated.
|
140 |
})
|
|
|
1 |
+
from flask import Blueprint, jsonify, request, current_app
|
2 |
+
import io
|
3 |
+
import pandas as pd
|
4 |
+
from app.utils import OCRModel, AllergyAnalyzer
|
5 |
+
import logging
|
6 |
+
import os
|
7 |
+
import requests
|
8 |
+
from PIL import Image
|
9 |
+
import nltk
|
10 |
+
nltk.download('punkt', quiet=True)
|
11 |
+
|
12 |
+
logging.basicConfig(level=logging.INFO)
|
13 |
+
logger = logging.getLogger(__name__)
|
14 |
+
|
15 |
+
main = Blueprint('main', __name__)
|
16 |
+
ocr_model = OCRModel()
|
17 |
+
allergy_analyzer = AllergyAnalyzer(current_app.config['ALLERGY_DATASET_PATH'])
|
18 |
+
|
19 |
+
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
|
20 |
+
|
21 |
+
def allowed_file(filename):
|
22 |
+
"""Validate file extension"""
|
23 |
+
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
24 |
+
|
25 |
+
@main.route('/')
|
26 |
+
def index():
|
27 |
+
return jsonify({
|
28 |
+
"message": "Welcome to the Advanced OCR and Allergy Detection Service",
|
29 |
+
"endpoints": {
|
30 |
+
"/api/ocr": "POST - Image analysis and allergy detection",
|
31 |
+
"/api/allergens": "GET - List of known allergens from dataset"
|
32 |
+
},
|
33 |
+
"supported_formats": list(ALLOWED_EXTENSIONS),
|
34 |
+
"features": [
|
35 |
+
"OCR text extraction",
|
36 |
+
"Allergy detection from database",
|
37 |
+
"AI-powered allergy risk assessment"
|
38 |
+
]
|
39 |
+
})
|
40 |
+
|
41 |
+
@main.route('/api/ocr', methods=['POST'])
|
42 |
+
def process_image():
|
43 |
+
try:
|
44 |
+
# التحقق من وجود الملف
|
45 |
+
if 'file' not in request.files:
|
46 |
+
logger.warning("No file uploaded")
|
47 |
+
return jsonify({"error": "No file uploaded"}), 400
|
48 |
+
|
49 |
+
# التحقق من وجود قائمة الحساسيات
|
50 |
+
if 'allergens' not in request.form:
|
51 |
+
logger.warning("Allergens not specified")
|
52 |
+
return jsonify({"error": "Allergens not specified"}), 400
|
53 |
+
|
54 |
+
file = request.files['file']
|
55 |
+
if file.filename == '':
|
56 |
+
logger.warning("No file selected")
|
57 |
+
return jsonify({"error": "No file selected"}), 400
|
58 |
+
|
59 |
+
# التحقق من نوع الملف
|
60 |
+
if not allowed_file(file.filename):
|
61 |
+
logger.warning(f"Invalid file type: {file.filename}")
|
62 |
+
return jsonify({
|
63 |
+
"error": "File type not supported",
|
64 |
+
"supported_formats": list(ALLOWED_EXTENSIONS)
|
65 |
+
}), 400
|
66 |
+
|
67 |
+
# تحضير قائمة الحساسيات
|
68 |
+
user_allergens = [a.strip().lower() for a in request.form['allergens'].split(',')]
|
69 |
+
logger.info(f"Processing image for allergens: {user_allergens}")
|
70 |
+
|
71 |
+
# قراءة الصورة
|
72 |
+
file_bytes = file.read()
|
73 |
+
file_stream = io.BytesIO(file_bytes)
|
74 |
+
image = Image.open(file_stream)
|
75 |
+
|
76 |
+
# معالجة الصورة واستخراج النص
|
77 |
+
extracted_text = ocr_model.process_image(image)
|
78 |
+
logger.info(f"Extracted text: {extracted_text}")
|
79 |
+
|
80 |
+
# تحليل الحساسيات
|
81 |
+
analysis_results = allergy_analyzer.analyze_text(extracted_text, user_allergens)
|
82 |
+
|
83 |
+
# إعداد الرد
|
84 |
+
response = {
|
85 |
+
"success": True,
|
86 |
+
"extracted_text": extracted_text,
|
87 |
+
"analysis": analysis_results,
|
88 |
+
"warnings": {
|
89 |
+
"has_allergens": len(analysis_results['detected_allergens']) > 0,
|
90 |
+
"message": "⚠️ Warning: Allergens found!" if analysis_results['detected_allergens'] else "✅ No allergens found",
|
91 |
+
"severity": "high" if analysis_results['detected_allergens'] else "none"
|
92 |
+
}
|
93 |
+
}
|
94 |
+
|
95 |
+
logger.info(f"Analysis completed successfully")
|
96 |
+
return jsonify(response)
|
97 |
+
|
98 |
+
except Exception as e:
|
99 |
+
logger.error(f"Error processing request: {str(e)}", exc_info=True)
|
100 |
+
return jsonify({
|
101 |
+
"error": "An error occurred while processing the image.",
|
102 |
+
"details": str(e)
|
103 |
+
}), 500
|
104 |
+
|
105 |
+
@main.route('/api/allergens', methods=['GET'])
|
106 |
+
def get_known_allergens():
|
107 |
+
allergens = allergy_analyzer.get_allergen_list()
|
108 |
+
return jsonify({
|
109 |
+
"allergens": allergens,
|
110 |
+
"total_count": len(allergens),
|
111 |
+
"last_updated": "2024-03-24"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
})
|