Spaces:
Zienab
/
Runtime error

ocr-3 / app /routes.py
Zienab's picture
Update app/routes.py
71c8ab5 verified
raw
history blame
2.34 kB
from flask import Blueprint, jsonify, request, current_app
import os
from werkzeug.utils import secure_filename
from app.utils import OCRModel
import torch
import io
main = Blueprint('main', __name__)
ocr_model = OCRModel()
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@main.route('/')
def index():
return jsonify({"message": "Welcome to OCR API!"})
@main.route('/api/ocr', methods=['POST'])
def process_image():
if 'file' not in request.files:
return jsonify({"error": "No file part"}), 400
if 'allergens' not in request.form:
return jsonify({"error": "No allergens specified"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
# تحويل الحساسيات إلى قائمة
user_allergens = request.form['allergens'].lower().split(',')
user_allergens = {allergen.strip() for allergen in user_allergens}
if file and allowed_file(file.filename):
# قراءة الصورة في الذاكرة بدلاً من حفظها
file_bytes = file.read()
file_stream = io.BytesIO(file_bytes)
try:
# معالجة الصورة واستخراج النص
result = ocr_model.process_image(file_stream)
# تحليل النص وفحص الحساسيات
found_allergens = set()
text_lower = result.lower()
for allergen in user_allergens:
if allergen in text_lower:
found_allergens.add(allergen)
response = {
"text": result,
"found_allergens": list(found_allergens),
"has_allergens": len(found_allergens) > 0,
"warning": "تحذير: هذا المنتج يحتوي على مواد قد تسبب لك حساسية!" if found_allergens else "لم يتم العثور على مواد مسببة للحساسية"
}
return jsonify(response)
except Exception as e:
return jsonify({"error": str(e)}), 500
return jsonify({"error": "Invalid file type"}), 400