Spaces:
Zienab
/
Runtime error

File size: 2,337 Bytes
9db4439
 
 
 
 
71c8ab5
9db4439
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71c8ab5
 
 
9db4439
 
 
 
71c8ab5
 
 
 
9db4439
71c8ab5
 
 
9db4439
 
71c8ab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9db4439
 
 
 
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
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