-
Notifications
You must be signed in to change notification settings - Fork 16
/
barcode.py
31 lines (27 loc) · 869 Bytes
/
barcode.py
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
import requests, json
import re
from pyzbar.pyzbar import decode
from PIL import Image
def get_barcode(image):
"""
Read the barcode from the picture and return the barcode number in EAN 13 format
"""
barcode = info = None
img_raw = Image.open(image)
decoded = decode(img_raw)
if decoded:
try:
barcode = int(re.findall("[+-]?[0-9][0-9]*|0$",
str(decoded[0].data))[0])
info = _get_product_info(barcode)
except:
pass
return barcode, info
def _get_product_info(barcode):
"""
Query a product by the barcode number the openFoodFact DB trought API
"""
address = "https://world.openfoodfacts.org/api/v0/product/{}.json".format(barcode)
#print(address) use for logging
r = requests.get(address)
return json.loads(r.text)