|
| 1 | +import logging |
| 2 | +import tempfile |
| 3 | +import chepy.core |
| 4 | + |
| 5 | +try: |
| 6 | + from PIL import Image |
| 7 | + from pyzbar import pyzbar |
| 8 | + import zxing |
| 9 | +except ImportError: |
| 10 | + logging.error("Could not import PIL, zxing or pyzbar") |
| 11 | + |
| 12 | + |
| 13 | +class Chepy_QR(chepy.core.ChepyCore): |
| 14 | + pass |
| 15 | + |
| 16 | + @chepy.core.ChepyDecorators.call_stack |
| 17 | + def qr_decode(self, show_all: bool = False): # pragma: no cover |
| 18 | + """Decode a qr code. This method does require zbar to be installed in the system |
| 19 | +
|
| 20 | + Args: |
| 21 | + show_all: If true, show all decoded data. If false, show only the first decoded data. |
| 22 | +
|
| 23 | + Returns: |
| 24 | + ChepyPlugin: The Chepy object. |
| 25 | + """ |
| 26 | + data = Image.open(self._load_as_file()) |
| 27 | + texts = list(map(lambda x: x.data, pyzbar.decode(data))) |
| 28 | + if len(texts) == 0: |
| 29 | + logging.error("Could not decode QR code") |
| 30 | + else: |
| 31 | + if show_all: |
| 32 | + self.state = texts |
| 33 | + else: |
| 34 | + self.state = texts[0] |
| 35 | + return self |
| 36 | + |
| 37 | + @chepy.core.ChepyDecorators.call_stack |
| 38 | + def qr_decode_other(self): |
| 39 | + """Decode a qr code |
| 40 | +
|
| 41 | + This method does require zxing to be installed. For this method to work, |
| 42 | + it creates a temporary file and then deletes it. |
| 43 | +
|
| 44 | + Returns: |
| 45 | + ChepyPlugin: The Chepy object. |
| 46 | + """ |
| 47 | + formats = {"PNG": "png", "JPEG": "jpg", "GIF": "gif"} |
| 48 | + data = Image.open(self._load_as_file()) |
| 49 | + fmat = formats.get(data.format) |
| 50 | + if fmat is None: |
| 51 | + logging.error("Could not decode QR code") |
| 52 | + return self |
| 53 | + # create temp file |
| 54 | + with tempfile.NamedTemporaryFile(delete=True, suffix=".{}".format(fmat)) as tf: |
| 55 | + data.save(tf) |
| 56 | + # tf.write(data.tobytes()) |
| 57 | + reader = zxing.BarCodeReader() |
| 58 | + result = reader.decode(tf.name) |
| 59 | + if result is None: |
| 60 | + logging.error("Could not decode QR code") |
| 61 | + else: |
| 62 | + self.state = result.parsed |
| 63 | + return self |
| 64 | + |
| 65 | + # @chepy.core.ChepyDecorators.call_stack |
| 66 | + # def qr_to_ascii(self): |
| 67 | + # """ |
| 68 | + # Convert a qr code to ascii |
| 69 | + |
| 70 | + # Returns: |
| 71 | + # ChepyPlugin: The Chepy object. |
| 72 | + # """ |
| 73 | + # # TODO: Implement this |
| 74 | + # logging.warning("Not implemented yet") |
| 75 | + # pass |
0 commit comments