File size: 6,039 Bytes
09ec0b8
 
 
 
 
 
 
 
 
 
 
 
d049900
09ec0b8
d049900
09ec0b8
d049900
 
09ec0b8
 
d049900
09ec0b8
d049900
 
 
 
 
 
 
 
 
09ec0b8
d049900
09ec0b8
 
 
 
d049900
09ec0b8
d049900
 
 
 
09ec0b8
 
d049900
 
 
09ec0b8
 
 
 
 
 
d049900
09ec0b8
d049900
 
 
 
09ec0b8
d049900
 
 
09ec0b8
 
 
d049900
09ec0b8
d049900
 
 
 
09ec0b8
 
d049900
09ec0b8
d049900
072d28e
 
d049900
 
072d28e
d049900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
072d28e
d049900
 
 
 
09ec0b8
d049900
09ec0b8
d049900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09ec0b8
d049900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09ec0b8
d049900
 
 
 
 
 
09ec0b8
 
d049900
 
 
 
 
 
 
 
 
09ec0b8
 
d049900
09ec0b8
 
d049900
 
09ec0b8
 
d049900
 
 
 
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
from flask import Flask, request, jsonify
from flask_cors import CORS
import cv2
import numpy as np
import base64
import io
from pyzbar.pyzbar import decode
from PIL import Image
import os
import logging
import requests

# ================== INITIALISATION ==================
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})

HF_SPACE = os.environ.get("SPACE_ID") is not None
PORT = 7860 if HF_SPACE else int(os.environ.get("PORT", 5000))

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("barcode-api")

# ================== UTILS ==================

def safe_b64decode(data: str) -> bytes:
    """Base64 decode safe (Flutter/Web compatible)"""
    return base64.b64decode(data + "=" * (-len(data) % 4))


def decode_barcode(image_bytes: bytes) -> dict:
    """Decode barcode using PIL then OpenCV"""
    try:
        # --- PIL first ---
        try:
            pil_image = Image.open(io.BytesIO(image_bytes))
            barcodes = decode(pil_image)
            if barcodes:
                b = barcodes[0]
                return {
                    "success": True,
                    "barcode": b.data.decode("utf-8"),
                    "type": b.type,
                    "method": "pil"
                }
        except Exception as e:
            logger.debug(f"PIL failed: {e}")

        # --- OpenCV fallback ---
        try:
            nparr = np.frombuffer(image_bytes, np.uint8)
            img = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE)
            if img is not None:
                barcodes = decode(img)
                if barcodes:
                    b = barcodes[0]
                    return {
                        "success": True,
                        "barcode": b.data.decode("utf-8"),
                        "type": b.type,
                        "method": "opencv"
                    }

                # Contrast enhancement
                clahe = cv2.createCLAHE(2.0, (8, 8))
                enhanced = clahe.apply(img)
                barcodes = decode(enhanced)
                if barcodes:
                    b = barcodes[0]
                    return {
                        "success": True,
                        "barcode": b.data.decode("utf-8"),
                        "type": b.type,
                        "method": "enhanced"
                    }
        except Exception as e:
            logger.debug(f"OpenCV failed: {e}")

        return {"success": False, "error": "No barcode detected"}

    except Exception as e:
        logger.error(e)
        return {"success": False, "error": str(e)}

# ================== FLUTTER API ==================

@app.route("/api/decode-barcode", methods=["POST"])
def api_decode_barcode():
    if not request.is_json:
        return jsonify({"success": False, "error": "JSON required"}), 400

    data = request.get_json()
    image_data = data.get("image")
    if not image_data:
        return jsonify({"success": False, "error": "Image missing"}), 400

    if "," in image_data:
        image_data = image_data.split(",")[1]

    if len(image_data) > 3 * 1024 * 1024:
        return jsonify({"success": False, "error": "Image too large"}), 400

    image_bytes = safe_b64decode(image_data)
    result = decode_barcode(image_bytes)
    return jsonify(result)


@app.route("/api/product-info/<barcode>", methods=["GET"])
def api_product_info(barcode):
    local_db = {
        "3017620422003": {
            "name": "Nutella",
            "brand": "Ferrero",
            "category": "Food",
            "price": 4.99,
            "description": "Hazelnut spread"
        },
        "5901234123457": {
            "name": "Milk UHT",
            "brand": "Candia",
            "category": "Food",
            "price": 1.20,
            "description": "UHT milk"
        }
    }

    if barcode in local_db:
        return jsonify({"success": True, "product": local_db[barcode], "source": "local"})

    # OpenFoodFacts fallback
    try:
        r = requests.get(
            f"https://world.openfoodfacts.org/api/v0/product/{barcode}.json",
            timeout=4
        )
        if r.status_code == 200:
            data = r.json()
            if data.get("status") == 1:
                p = data["product"]
                return jsonify({
                    "success": True,
                    "source": "openfoodfacts",
                    "product": {
                        "name": p.get("product_name"),
                        "brand": p.get("brands"),
                        "category": p.get("categories"),
                        "description": p.get("generic_name"),
                        "image": p.get("image_url")
                    }
                })
    except Exception as e:
        logger.debug(e)

    return jsonify({"success": False, "error": "Product not found"}), 404

# ================== WEB SCAN ==================

@app.route("/api/scan", methods=["POST"])
def api_scan():
    if not request.is_json:
        return jsonify({"success": False, "error": "JSON required"}), 400

    image_data = request.json.get("image")
    if not image_data:
        return jsonify({"success": False, "error": "Image missing"}), 400

    if "," in image_data:
        image_data = image_data.split(",")[1]

    image_bytes = safe_b64decode(image_data)
    return jsonify(decode_barcode(image_bytes))

# ================== HEALTH ==================

@app.route("/api/health")
def health():
    return jsonify({
        "status": "ok",
        "service": "Barcode Scanner API",
        "platform": "HuggingFace" if HF_SPACE else "Local",
        "endpoints": [
            "/api/decode-barcode",
            "/api/product-info/<barcode>",
            "/api/scan",
            "/api/health"
        ]
    })

@app.route("/")
def home():
    return jsonify({
        "message": "Barcode Scanner API",
        "use": "/api/decode-barcode (POST)"
    })

# ================== MAIN ==================

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=PORT, debug=False)