2016-04-11 05:40:00 +00:00
|
|
|
#
|
|
|
|
# QR Code generator library (Python 2, 3)
|
|
|
|
#
|
2017-04-24 20:41:54 +00:00
|
|
|
# Copyright (c) Project Nayuki. (MIT License)
|
2016-04-11 05:40:00 +00:00
|
|
|
# https://www.nayuki.io/page/qr-code-generator-library
|
|
|
|
#
|
|
|
|
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
|
|
# this software and associated documentation files (the "Software"), to deal in
|
|
|
|
# the Software without restriction, including without limitation the rights to
|
|
|
|
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
|
|
# the Software, and to permit persons to whom the Software is furnished to do so,
|
|
|
|
# subject to the following conditions:
|
|
|
|
# - The above copyright notice and this permission notice shall be included in
|
|
|
|
# all copies or substantial portions of the Software.
|
|
|
|
# - The Software is provided "as is", without warranty of any kind, express or
|
|
|
|
# implied, including but not limited to the warranties of merchantability,
|
|
|
|
# fitness for a particular purpose and noninfringement. In no event shall the
|
|
|
|
# authors or copyright holders be liable for any claim, damages or other
|
|
|
|
# liability, whether in an action of contract, tort or otherwise, arising from,
|
|
|
|
# out of or in connection with the Software or the use or other dealings in the
|
|
|
|
# Software.
|
|
|
|
#
|
|
|
|
|
|
|
|
import itertools, re, sys
|
|
|
|
|
|
|
|
|
|
|
|
"""
|
2016-04-20 20:27:41 +00:00
|
|
|
This module "qrcodegen", public members:
|
2016-04-11 05:40:00 +00:00
|
|
|
- Class QrCode:
|
2016-04-20 20:27:41 +00:00
|
|
|
- Function encode_text(str text, QrCode.Ecc ecl) -> QrCode
|
|
|
|
- Function encode_binary(bytes data, QrCode.Ecc ecl) -> QrCode
|
2016-04-18 18:40:14 +00:00
|
|
|
- Function encode_segments(list<QrSegment> segs, QrCode.Ecc ecl,
|
|
|
|
int minversion=1, int maxversion=40, mask=-1, boostecl=true) -> QrCode
|
2017-10-23 04:42:53 +00:00
|
|
|
- Constants int MIN_VERSION, MAX_VERSION
|
2018-10-05 00:56:29 +00:00
|
|
|
- Constructor QrCode(int version, QrCode.Ecc ecl, bytes datacodewords, int mask)
|
2016-04-11 05:40:00 +00:00
|
|
|
- Method get_version() -> int
|
|
|
|
- Method get_size() -> int
|
|
|
|
- Method get_error_correction_level() -> QrCode.Ecc
|
|
|
|
- Method get_mask() -> int
|
2017-08-31 20:39:29 +00:00
|
|
|
- Method get_module(int x, int y) -> bool
|
2016-04-11 05:40:00 +00:00
|
|
|
- Method to_svg_str(int border) -> str
|
|
|
|
- Enum Ecc:
|
|
|
|
- Constants LOW, MEDIUM, QUARTILE, HIGH
|
2016-04-20 20:40:49 +00:00
|
|
|
- Field int ordinal
|
2016-04-11 05:40:00 +00:00
|
|
|
- Class QrSegment:
|
|
|
|
- Function make_bytes(bytes data) -> QrSegment
|
|
|
|
- Function make_numeric(str digits) -> QrSegment
|
|
|
|
- Function make_alphanumeric(str text) -> QrSegment
|
2016-04-16 01:44:24 +00:00
|
|
|
- Function make_segments(str text) -> list<QrSegment>
|
2017-05-08 18:04:10 +00:00
|
|
|
- Function make_eci(int assignval) -> QrSegment
|
2016-04-11 05:40:00 +00:00
|
|
|
- Constructor QrSegment(QrSegment.Mode mode, int numch, list<int> bitdata)
|
|
|
|
- Method get_mode() -> QrSegment.Mode
|
|
|
|
- Method get_num_chars() -> int
|
|
|
|
- Method get_bits() -> list<int>
|
2016-04-20 20:46:46 +00:00
|
|
|
- Constants regex NUMERIC_REGEX, ALPHANUMERIC_REGEX
|
2016-04-11 05:40:00 +00:00
|
|
|
- Enum Mode:
|
2017-05-08 18:04:10 +00:00
|
|
|
- Constants NUMERIC, ALPHANUMERIC, BYTE, KANJI, ECI
|
2016-04-11 05:40:00 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
2016-04-18 18:40:14 +00:00
|
|
|
# ---- QR Code symbol class ----
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2016-04-18 18:40:14 +00:00
|
|
|
class QrCode(object):
|
2018-10-05 21:17:52 +00:00
|
|
|
"""A QR Code symbol, which is a type of two-dimension barcode.
|
|
|
|
Invented by Denso Wave and described in the ISO/IEC 18004 standard.
|
|
|
|
Instances of this class represent an immutable square grid of black and white cells.
|
|
|
|
The class provides static factory functions to create a QR Code from text or binary data.
|
|
|
|
The class covers the QR Code Model 2 specification, supporting all versions (sizes)
|
|
|
|
from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
|
|
|
|
|
|
|
|
Ways to create a QR Code object:
|
|
|
|
- High level: Take the payload data and call QrCode.encode_text() or QrCode.encode_binary().
|
|
|
|
- Mid level: Custom-make the list of segments and call QrCode.encode_segments().
|
|
|
|
- Low level: Custom-make the array of data codeword bytes (including
|
|
|
|
segment headers and final padding, excluding error correction codewords),
|
|
|
|
supply the appropriate version number, and call the QrCode() constructor.
|
|
|
|
(Note that all ways require supplying the desired error correction level.)"""
|
2016-04-16 03:53:58 +00:00
|
|
|
|
2018-10-04 19:56:07 +00:00
|
|
|
# ---- Static factory functions (high level) ----
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2016-04-20 20:59:31 +00:00
|
|
|
@staticmethod
|
2016-04-18 18:40:14 +00:00
|
|
|
def encode_text(text, ecl):
|
2018-10-05 20:30:26 +00:00
|
|
|
"""Returns a QR Code representing the given Unicode text string at the given error correction level.
|
2017-08-31 19:51:31 +00:00
|
|
|
As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
|
|
|
|
Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
|
|
|
|
QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
|
|
|
|
ecl argument if it can be done without increasing the version."""
|
2016-04-18 18:40:14 +00:00
|
|
|
segs = QrSegment.make_segments(text)
|
|
|
|
return QrCode.encode_segments(segs, ecl)
|
2016-04-16 03:53:58 +00:00
|
|
|
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2016-04-20 20:59:31 +00:00
|
|
|
@staticmethod
|
2016-04-18 18:40:14 +00:00
|
|
|
def encode_binary(data, ecl):
|
2018-10-05 20:30:26 +00:00
|
|
|
"""Returns a QR Code representing the given binary data string at the given error correction level.
|
2016-04-18 18:40:14 +00:00
|
|
|
This function always encodes using the binary segment mode, not any text mode. The maximum number of
|
2016-05-24 18:41:34 +00:00
|
|
|
bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
|
|
|
|
The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version."""
|
2017-05-06 12:14:59 +00:00
|
|
|
if not isinstance(data, (bytes, bytearray)):
|
|
|
|
raise TypeError("Byte string/list expected")
|
2016-04-18 18:40:14 +00:00
|
|
|
return QrCode.encode_segments([QrSegment.make_bytes(data)], ecl)
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
2018-10-04 19:56:07 +00:00
|
|
|
# ---- Static factory functions (mid level) ----
|
|
|
|
|
2016-04-18 18:40:14 +00:00
|
|
|
@staticmethod
|
|
|
|
def encode_segments(segs, ecl, minversion=1, maxversion=40, mask=-1, boostecl=True):
|
2018-10-05 20:30:26 +00:00
|
|
|
"""Returns a QR Code representing the given segments with the given encoding parameters.
|
2017-01-03 18:31:49 +00:00
|
|
|
The smallest possible QR Code version within the given range is automatically chosen for the output.
|
2016-04-18 18:40:14 +00:00
|
|
|
This function allows the user to create a custom sequence of segments that switches
|
|
|
|
between modes (such as alphanumeric and binary) to encode text more efficiently.
|
|
|
|
This function is considered to be lower level than simply encoding text or binary data."""
|
|
|
|
|
2017-10-23 04:42:53 +00:00
|
|
|
if not (QrCode.MIN_VERSION <= minversion <= maxversion <= QrCode.MAX_VERSION) or not (-1 <= mask <= 7):
|
2016-04-18 18:40:14 +00:00
|
|
|
raise ValueError("Invalid value")
|
|
|
|
|
|
|
|
# Find the minimal version number to use
|
|
|
|
for version in range(minversion, maxversion + 1):
|
|
|
|
datacapacitybits = QrCode._get_num_data_codewords(version, ecl) * 8 # Number of data bits available
|
|
|
|
datausedbits = QrSegment.get_total_bits(segs, version)
|
|
|
|
if datausedbits is not None and datausedbits <= datacapacitybits:
|
|
|
|
break # This version number is found to be suitable
|
|
|
|
if version >= maxversion: # All versions in the range could not fit the given data
|
|
|
|
raise ValueError("Data too long")
|
|
|
|
if datausedbits is None:
|
|
|
|
raise AssertionError()
|
|
|
|
|
|
|
|
# Increase the error correction level while the data still fits in the current version number
|
2018-08-22 19:22:00 +00:00
|
|
|
for newecl in (QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH): # From low to high
|
2016-04-18 18:40:14 +00:00
|
|
|
if boostecl and datausedbits <= QrCode._get_num_data_codewords(version, newecl) * 8:
|
|
|
|
ecl = newecl
|
|
|
|
|
2018-08-22 19:22:00 +00:00
|
|
|
# Concatenate all segments to create the data bit string
|
2016-04-18 18:40:14 +00:00
|
|
|
bb = _BitBuffer()
|
|
|
|
for seg in segs:
|
|
|
|
bb.append_bits(seg.get_mode().get_mode_bits(), 4)
|
|
|
|
bb.append_bits(seg.get_num_chars(), seg.get_mode().num_char_count_bits(version))
|
2017-08-17 20:03:19 +00:00
|
|
|
bb.extend(seg._bitdata)
|
2018-08-28 06:22:22 +00:00
|
|
|
assert len(bb) == datausedbits
|
2016-04-18 18:40:14 +00:00
|
|
|
|
|
|
|
# Add terminator and pad up to a byte if applicable
|
2018-08-26 02:03:27 +00:00
|
|
|
datacapacitybits = QrCode._get_num_data_codewords(version, ecl) * 8
|
|
|
|
assert len(bb) <= datacapacitybits
|
2017-08-17 20:03:19 +00:00
|
|
|
bb.append_bits(0, min(4, datacapacitybits - len(bb)))
|
|
|
|
bb.append_bits(0, -len(bb) % 8) # Note: Python's modulo on negative numbers behaves better than C family languages
|
2018-08-26 02:03:27 +00:00
|
|
|
assert len(bb) % 8 == 0
|
2016-04-18 18:40:14 +00:00
|
|
|
|
2018-08-26 02:03:27 +00:00
|
|
|
# Pad with alternating bytes until data capacity is reached
|
2016-04-18 18:40:14 +00:00
|
|
|
for padbyte in itertools.cycle((0xEC, 0x11)):
|
2017-08-17 20:03:19 +00:00
|
|
|
if len(bb) >= datacapacitybits:
|
2016-04-18 18:40:14 +00:00
|
|
|
break
|
|
|
|
bb.append_bits(padbyte, 8)
|
|
|
|
|
2018-10-05 20:30:26 +00:00
|
|
|
# Create the QR Code object
|
2018-10-05 00:56:29 +00:00
|
|
|
return QrCode(version, ecl, bb.get_bytes(), mask)
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
2018-10-04 19:56:07 +00:00
|
|
|
# ---- Constructor (low level) ----
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2018-10-05 00:56:29 +00:00
|
|
|
def __init__(self, version, errcorlvl, datacodewords, mask):
|
2018-10-05 20:30:26 +00:00
|
|
|
"""Creates a new QR Code with the given version number, error correction level, binary data array,
|
2017-10-23 03:45:24 +00:00
|
|
|
and mask number. mask = -1 is for automatic choice, or 0 to 7 for fixed choice. This is a cumbersome low-level constructor
|
|
|
|
that should not be invoked directly by the user. To go one level up, see the QrCode.encode_segments() function."""
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2018-10-05 02:14:43 +00:00
|
|
|
# Check scalar arguments and set fields
|
2017-10-23 04:42:53 +00:00
|
|
|
if not (QrCode.MIN_VERSION <= version <= QrCode.MAX_VERSION):
|
2017-10-23 03:45:24 +00:00
|
|
|
raise ValueError("Version value out of range")
|
2018-10-05 02:14:43 +00:00
|
|
|
if not (-1 <= mask <= 7):
|
|
|
|
raise ValueError("Mask value out of range")
|
2017-10-23 03:45:24 +00:00
|
|
|
if not isinstance(errcorlvl, QrCode.Ecc):
|
|
|
|
raise TypeError("QrCode.Ecc expected")
|
2018-10-05 20:56:50 +00:00
|
|
|
|
|
|
|
# The version number of this QR Code, which is between 1 and 40 (inclusive).
|
|
|
|
# This determines the size of this barcode.
|
2016-04-11 05:40:00 +00:00
|
|
|
self._version = version
|
2018-10-05 20:56:50 +00:00
|
|
|
|
|
|
|
# The width and height of this QR Code, measured in modules, between
|
|
|
|
# 21 and 177 (inclusive). This is equal to version * 4 + 17.
|
2016-04-11 05:40:00 +00:00
|
|
|
self._size = version * 4 + 17
|
2018-10-05 20:56:50 +00:00
|
|
|
|
|
|
|
# The error correction level used in this QR Code.
|
2018-10-05 02:14:43 +00:00
|
|
|
self._errcorlvl = errcorlvl
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2018-10-05 02:14:43 +00:00
|
|
|
# Initialize both grids to be size*size arrays of Boolean false
|
2018-10-05 20:30:26 +00:00
|
|
|
# The modules of this QR Code (False = white, True = black). Immutable after constructor finishes
|
2018-10-05 01:47:05 +00:00
|
|
|
self._modules = [[False] * self._size for _ in range(self._size)] # Initially all white
|
2018-10-05 00:40:49 +00:00
|
|
|
# Indicates function modules that are not subjected to masking. Discarded when constructor finishes
|
|
|
|
self._isfunction = [[False] * self._size for _ in range(self._size)]
|
|
|
|
|
2018-10-05 01:47:05 +00:00
|
|
|
# Compute ECC, draw modules
|
2017-10-23 03:45:24 +00:00
|
|
|
self._draw_function_patterns()
|
2018-08-26 01:33:06 +00:00
|
|
|
allcodewords = self._add_ecc_and_interleave(datacodewords)
|
2017-10-23 03:45:24 +00:00
|
|
|
self._draw_codewords(allcodewords)
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2018-10-05 01:44:06 +00:00
|
|
|
# Do masking
|
2016-04-11 05:40:00 +00:00
|
|
|
if mask == -1: # Automatically choose best mask
|
|
|
|
minpenalty = 1 << 32
|
|
|
|
for i in range(8):
|
|
|
|
self._draw_format_bits(i)
|
|
|
|
self._apply_mask(i)
|
|
|
|
penalty = self._get_penalty_score()
|
|
|
|
if penalty < minpenalty:
|
|
|
|
mask = i
|
|
|
|
minpenalty = penalty
|
|
|
|
self._apply_mask(i) # Undoes the mask due to XOR
|
|
|
|
assert 0 <= mask <= 7
|
|
|
|
self._draw_format_bits(mask) # Overwrite old format bits
|
|
|
|
self._apply_mask(mask) # Apply the final choice of mask
|
2018-10-05 20:56:50 +00:00
|
|
|
|
|
|
|
# The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
|
|
|
|
# Even if a QR Code is created with automatic masking requested (mask = -1),
|
|
|
|
# the resulting object still has a mask value between 0 and 7.
|
2016-04-11 05:40:00 +00:00
|
|
|
self._mask = mask
|
2018-10-05 01:44:06 +00:00
|
|
|
|
2018-08-26 02:17:47 +00:00
|
|
|
del self._isfunction
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
# ---- Accessor methods ----
|
|
|
|
|
|
|
|
def get_version(self):
|
2018-10-05 20:30:26 +00:00
|
|
|
"""Returns this QR Code's version number, which is always between 1 and 40 (inclusive)."""
|
2016-04-11 05:40:00 +00:00
|
|
|
return self._version
|
|
|
|
|
|
|
|
def get_size(self):
|
2018-10-05 20:30:26 +00:00
|
|
|
"""Returns the width and height of this QR Code, measured in modules.
|
2016-04-11 05:40:00 +00:00
|
|
|
Always equal to version * 4 + 17, in the range 21 to 177."""
|
|
|
|
return self._size
|
|
|
|
|
|
|
|
def get_error_correction_level(self):
|
2018-10-05 20:30:26 +00:00
|
|
|
"""Returns the error correction level used in this QR Code."""
|
2016-04-11 05:40:00 +00:00
|
|
|
return self._errcorlvl
|
|
|
|
|
|
|
|
def get_mask(self):
|
2018-10-05 20:30:26 +00:00
|
|
|
"""Returns the mask pattern used in this QR Code, in the range 0 to 7 (i.e. unsigned 3-bit integer).
|
2016-04-11 05:40:00 +00:00
|
|
|
Note that even if a constructor was called with automatic masking requested
|
|
|
|
(mask = -1), the resulting object will still have a mask value between 0 and 7."""
|
|
|
|
return self._mask
|
|
|
|
|
|
|
|
def get_module(self, x, y):
|
2017-08-31 20:18:41 +00:00
|
|
|
"""Returns the color of the module (pixel) at the given coordinates, which is either
|
2017-08-31 20:39:29 +00:00
|
|
|
False for white or True for black. The top left corner has the coordinates (x=0, y=0).
|
|
|
|
If the given coordinates are out of bounds, then False (white) is returned."""
|
|
|
|
return (0 <= x < self._size) and (0 <= y < self._size) and self._modules[y][x]
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
# ---- Public instance methods ----
|
|
|
|
|
|
|
|
def to_svg_str(self, border):
|
2018-10-05 20:30:26 +00:00
|
|
|
"""Returns a string of SVG XML code representing an image of this QR Code with the given
|
2018-08-28 21:08:00 +00:00
|
|
|
number of border modules. Note that Unix newlines (\n) are always used, regardless of the platform."""
|
2016-04-11 05:40:00 +00:00
|
|
|
if border < 0:
|
|
|
|
raise ValueError("Border must be non-negative")
|
|
|
|
parts = []
|
2018-08-22 19:32:03 +00:00
|
|
|
for y in range(self._size):
|
|
|
|
for x in range(self._size):
|
2017-08-31 20:39:29 +00:00
|
|
|
if self.get_module(x, y):
|
2016-04-11 05:40:00 +00:00
|
|
|
parts.append("M{},{}h1v1h-1z".format(x + border, y + border))
|
|
|
|
return """<?xml version="1.0" encoding="UTF-8"?>
|
|
|
|
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
2017-07-26 20:34:29 +00:00
|
|
|
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 {0} {0}" stroke="none">
|
|
|
|
<rect width="100%" height="100%" fill="#FFFFFF"/>
|
|
|
|
<path d="{1}" fill="#000000"/>
|
2016-04-11 05:40:00 +00:00
|
|
|
</svg>
|
2016-04-21 02:19:50 +00:00
|
|
|
""".format(self._size + border * 2, " ".join(parts))
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
# ---- Private helper methods for constructor: Drawing function modules ----
|
|
|
|
|
|
|
|
def _draw_function_patterns(self):
|
2018-08-22 19:23:40 +00:00
|
|
|
"""Reads this object's version field, and draws and marks all function modules."""
|
2017-04-20 06:39:59 +00:00
|
|
|
# Draw horizontal and vertical timing patterns
|
2016-04-11 05:40:00 +00:00
|
|
|
for i in range(self._size):
|
|
|
|
self._set_function_module(6, i, i % 2 == 0)
|
|
|
|
self._set_function_module(i, 6, i % 2 == 0)
|
|
|
|
|
|
|
|
# Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
|
|
|
|
self._draw_finder_pattern(3, 3)
|
|
|
|
self._draw_finder_pattern(self._size - 4, 3)
|
|
|
|
self._draw_finder_pattern(3, self._size - 4)
|
|
|
|
|
2017-04-20 06:39:59 +00:00
|
|
|
# Draw numerous alignment patterns
|
2018-08-28 19:10:47 +00:00
|
|
|
alignpatpos = self._get_alignment_pattern_positions()
|
2016-04-11 05:40:00 +00:00
|
|
|
numalign = len(alignpatpos)
|
2018-08-26 01:49:27 +00:00
|
|
|
skips = ((0, 0), (0, numalign - 1), (numalign - 1, 0))
|
2016-04-11 05:40:00 +00:00
|
|
|
for i in range(numalign):
|
|
|
|
for j in range(numalign):
|
2018-08-26 01:49:27 +00:00
|
|
|
if (i, j) not in skips: # Don't draw on the three finder corners
|
2016-04-11 05:40:00 +00:00
|
|
|
self._draw_alignment_pattern(alignpatpos[i], alignpatpos[j])
|
|
|
|
|
|
|
|
# Draw configuration data
|
|
|
|
self._draw_format_bits(0) # Dummy mask value; overwritten later in the constructor
|
|
|
|
self._draw_version()
|
|
|
|
|
|
|
|
|
|
|
|
def _draw_format_bits(self, mask):
|
|
|
|
"""Draws two copies of the format bits (with its own error correction code)
|
|
|
|
based on the given mask and this object's error correction level field."""
|
|
|
|
# Calculate error correction code and pack bits
|
|
|
|
data = self._errcorlvl.formatbits << 3 | mask # errCorrLvl is uint2, mask is uint3
|
|
|
|
rem = data
|
|
|
|
for _ in range(10):
|
|
|
|
rem = (rem << 1) ^ ((rem >> 9) * 0x537)
|
2018-08-22 19:48:29 +00:00
|
|
|
bits = (data << 10 | rem) ^ 0x5412 # uint15
|
|
|
|
assert bits >> 15 == 0
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
# Draw first copy
|
|
|
|
for i in range(0, 6):
|
2018-08-22 19:48:29 +00:00
|
|
|
self._set_function_module(8, i, _get_bit(bits, i))
|
|
|
|
self._set_function_module(8, 7, _get_bit(bits, 6))
|
|
|
|
self._set_function_module(8, 8, _get_bit(bits, 7))
|
|
|
|
self._set_function_module(7, 8, _get_bit(bits, 8))
|
2016-04-11 05:40:00 +00:00
|
|
|
for i in range(9, 15):
|
2018-08-22 19:48:29 +00:00
|
|
|
self._set_function_module(14 - i, 8, _get_bit(bits, i))
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
# Draw second copy
|
|
|
|
for i in range(0, 8):
|
2018-08-22 19:48:29 +00:00
|
|
|
self._set_function_module(self._size - 1 - i, 8, _get_bit(bits, i))
|
2016-04-11 05:40:00 +00:00
|
|
|
for i in range(8, 15):
|
2018-08-22 19:48:29 +00:00
|
|
|
self._set_function_module(8, self._size - 15 + i, _get_bit(bits, i))
|
2018-08-22 19:22:00 +00:00
|
|
|
self._set_function_module(8, self._size - 8, True) # Always black
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _draw_version(self):
|
|
|
|
"""Draws two copies of the version bits (with its own error correction code),
|
2018-08-22 19:23:40 +00:00
|
|
|
based on this object's version field, iff 7 <= version <= 40."""
|
2016-04-11 05:40:00 +00:00
|
|
|
if self._version < 7:
|
|
|
|
return
|
|
|
|
|
|
|
|
# Calculate error correction code and pack bits
|
|
|
|
rem = self._version # version is uint6, in the range [7, 40]
|
|
|
|
for _ in range(12):
|
|
|
|
rem = (rem << 1) ^ ((rem >> 11) * 0x1F25)
|
2018-08-22 19:52:50 +00:00
|
|
|
bits = self._version << 12 | rem # uint18
|
|
|
|
assert bits >> 18 == 0
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
# Draw two copies
|
|
|
|
for i in range(18):
|
2018-08-22 19:52:50 +00:00
|
|
|
bit = _get_bit(bits, i)
|
2018-08-22 19:56:24 +00:00
|
|
|
a = self._size - 11 + i % 3
|
|
|
|
b = i // 3
|
2016-04-11 05:40:00 +00:00
|
|
|
self._set_function_module(a, b, bit)
|
|
|
|
self._set_function_module(b, a, bit)
|
|
|
|
|
|
|
|
|
|
|
|
def _draw_finder_pattern(self, x, y):
|
2018-08-22 19:23:40 +00:00
|
|
|
"""Draws a 9*9 finder pattern including the border separator,
|
|
|
|
with the center module at (x, y). Modules can be out of bounds."""
|
2018-09-17 03:47:58 +00:00
|
|
|
for dy in range(-4, 5):
|
|
|
|
for dx in range(-4, 5):
|
|
|
|
xx, yy = x + dx, y + dy
|
2017-05-08 06:22:53 +00:00
|
|
|
if (0 <= xx < self._size) and (0 <= yy < self._size):
|
2017-08-27 00:05:52 +00:00
|
|
|
# Chebyshev/infinity norm
|
2018-09-17 03:51:57 +00:00
|
|
|
self._set_function_module(xx, yy, max(abs(dx), abs(dy)) not in (2, 4))
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _draw_alignment_pattern(self, x, y):
|
2018-08-22 19:23:40 +00:00
|
|
|
"""Draws a 5*5 alignment pattern, with the center module
|
|
|
|
at (x, y). All modules must be in bounds."""
|
2018-09-17 03:47:58 +00:00
|
|
|
for dy in range(-2, 3):
|
|
|
|
for dx in range(-2, 3):
|
2018-09-17 03:51:57 +00:00
|
|
|
self._set_function_module(x + dx, y + dy, max(abs(dx), abs(dy)) != 1)
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _set_function_module(self, x, y, isblack):
|
|
|
|
"""Sets the color of a module and marks it as a function module.
|
2018-08-22 19:23:40 +00:00
|
|
|
Only used by the constructor. Coordinates must be in bounds."""
|
2016-04-11 05:40:00 +00:00
|
|
|
assert type(isblack) is bool
|
|
|
|
self._modules[y][x] = isblack
|
|
|
|
self._isfunction[y][x] = True
|
|
|
|
|
|
|
|
|
|
|
|
# ---- Private helper methods for constructor: Codewords and masking ----
|
|
|
|
|
2018-08-26 01:33:06 +00:00
|
|
|
def _add_ecc_and_interleave(self, data):
|
2016-04-11 05:40:00 +00:00
|
|
|
"""Returns a new byte string representing the given data with the appropriate error correction
|
|
|
|
codewords appended to it, based on this object's version and error correction level."""
|
|
|
|
version = self._version
|
|
|
|
assert len(data) == QrCode._get_num_data_codewords(version, self._errcorlvl)
|
2016-04-21 01:57:58 +00:00
|
|
|
|
|
|
|
# Calculate parameter numbers
|
2016-04-11 05:40:00 +00:00
|
|
|
numblocks = QrCode._NUM_ERROR_CORRECTION_BLOCKS[self._errcorlvl.ordinal][version]
|
2018-08-31 17:23:16 +00:00
|
|
|
blockecclen = QrCode._ECC_CODEWORDS_PER_BLOCK [self._errcorlvl.ordinal][version]
|
2017-05-06 17:19:00 +00:00
|
|
|
rawcodewords = QrCode._get_num_raw_data_modules(version) // 8
|
|
|
|
numshortblocks = numblocks - rawcodewords % numblocks
|
|
|
|
shortblocklen = rawcodewords // numblocks
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2016-04-21 01:57:58 +00:00
|
|
|
# Split data into blocks and append ECC to each block
|
2016-04-11 05:40:00 +00:00
|
|
|
blocks = []
|
2016-04-21 01:57:58 +00:00
|
|
|
rs = _ReedSolomonGenerator(blockecclen)
|
2016-04-11 05:40:00 +00:00
|
|
|
k = 0
|
|
|
|
for i in range(numblocks):
|
2016-04-21 01:57:58 +00:00
|
|
|
dat = data[k : k + shortblocklen - blockecclen + (0 if i < numshortblocks else 1)]
|
2016-04-11 05:40:00 +00:00
|
|
|
k += len(dat)
|
|
|
|
ecc = rs.get_remainder(dat)
|
|
|
|
if i < numshortblocks:
|
|
|
|
dat.append(0)
|
2018-08-22 20:19:04 +00:00
|
|
|
blocks.append(dat + ecc)
|
2016-04-11 05:40:00 +00:00
|
|
|
assert k == len(data)
|
|
|
|
|
2016-04-21 01:57:58 +00:00
|
|
|
# Interleave (not concatenate) the bytes from every block into a single sequence
|
2016-04-11 05:40:00 +00:00
|
|
|
result = []
|
|
|
|
for i in range(len(blocks[0])):
|
|
|
|
for (j, blk) in enumerate(blocks):
|
2016-04-21 01:57:58 +00:00
|
|
|
# Skip the padding byte in short blocks
|
|
|
|
if i != shortblocklen - blockecclen or j >= numshortblocks:
|
2016-04-11 05:40:00 +00:00
|
|
|
result.append(blk[i])
|
2017-05-06 17:19:00 +00:00
|
|
|
assert len(result) == rawcodewords
|
2016-04-11 05:40:00 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def _draw_codewords(self, data):
|
|
|
|
"""Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
|
2018-10-05 20:30:26 +00:00
|
|
|
data area of this QR Code. Function modules need to be marked off before this is called."""
|
2016-04-11 05:40:00 +00:00
|
|
|
assert len(data) == QrCode._get_num_raw_data_modules(self._version) // 8
|
|
|
|
|
|
|
|
i = 0 # Bit index into the data
|
|
|
|
# Do the funny zigzag scan
|
|
|
|
for right in range(self._size - 1, 0, -2): # Index of right column in each column pair
|
|
|
|
if right <= 6:
|
|
|
|
right -= 1
|
|
|
|
for vert in range(self._size): # Vertical counter
|
|
|
|
for j in range(2):
|
|
|
|
x = right - j # Actual x coordinate
|
2017-08-25 22:38:32 +00:00
|
|
|
upward = (right + 1) & 2 == 0
|
2017-04-20 04:06:46 +00:00
|
|
|
y = (self._size - 1 - vert) if upward else vert # Actual y coordinate
|
2016-04-11 05:40:00 +00:00
|
|
|
if not self._isfunction[y][x] and i < len(data) * 8:
|
2018-04-13 19:48:59 +00:00
|
|
|
self._modules[y][x] = _get_bit(data[i >> 3], 7 - (i & 7))
|
2016-04-11 05:40:00 +00:00
|
|
|
i += 1
|
2018-08-28 21:08:00 +00:00
|
|
|
# If this QR Code has any remainder bits (0 to 7), they were assigned as
|
|
|
|
# 0/false/white by the constructor and are left unchanged by this method
|
2016-04-11 05:40:00 +00:00
|
|
|
assert i == len(data) * 8
|
|
|
|
|
|
|
|
|
|
|
|
def _apply_mask(self, mask):
|
2018-08-22 19:22:00 +00:00
|
|
|
"""XORs the codeword modules in this QR Code with the given mask pattern.
|
|
|
|
The function modules must be marked and the codeword bits must be drawn
|
|
|
|
before masking. Due to the arithmetic of XOR, calling applyMask() with
|
|
|
|
the same mask value a second time will undo the mask. A final well-formed
|
2018-10-05 20:30:26 +00:00
|
|
|
QR Code needs exactly one (not zero, two, etc.) mask applied."""
|
2017-05-08 06:22:53 +00:00
|
|
|
if not (0 <= mask <= 7):
|
2016-04-11 05:40:00 +00:00
|
|
|
raise ValueError("Mask value out of range")
|
|
|
|
masker = QrCode._MASK_PATTERNS[mask]
|
|
|
|
for y in range(self._size):
|
|
|
|
for x in range(self._size):
|
|
|
|
self._modules[y][x] ^= (masker(x, y) == 0) and (not self._isfunction[y][x])
|
|
|
|
|
|
|
|
|
|
|
|
def _get_penalty_score(self):
|
|
|
|
"""Calculates and returns the penalty score based on state of this QR Code's current modules.
|
|
|
|
This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score."""
|
|
|
|
result = 0
|
|
|
|
size = self._size
|
|
|
|
modules = self._modules
|
|
|
|
|
|
|
|
# Adjacent modules in row having same color
|
|
|
|
for y in range(size):
|
2017-05-08 07:30:53 +00:00
|
|
|
for x in range(size):
|
|
|
|
if x == 0 or modules[y][x] != colorx:
|
2016-04-11 05:40:00 +00:00
|
|
|
colorx = modules[y][x]
|
|
|
|
runx = 1
|
|
|
|
else:
|
|
|
|
runx += 1
|
|
|
|
if runx == 5:
|
|
|
|
result += QrCode._PENALTY_N1
|
|
|
|
elif runx > 5:
|
|
|
|
result += 1
|
|
|
|
# Adjacent modules in column having same color
|
|
|
|
for x in range(size):
|
2017-05-08 07:30:53 +00:00
|
|
|
for y in range(size):
|
|
|
|
if y == 0 or modules[y][x] != colory:
|
2016-04-11 05:40:00 +00:00
|
|
|
colory = modules[y][x]
|
|
|
|
runy = 1
|
|
|
|
else:
|
|
|
|
runy += 1
|
|
|
|
if runy == 5:
|
|
|
|
result += QrCode._PENALTY_N1
|
|
|
|
elif runy > 5:
|
|
|
|
result += 1
|
|
|
|
|
|
|
|
# 2*2 blocks of modules having same color
|
|
|
|
for y in range(size - 1):
|
|
|
|
for x in range(size - 1):
|
2016-10-24 07:27:48 +00:00
|
|
|
if modules[y][x] == modules[y][x + 1] == modules[y + 1][x] == modules[y + 1][x + 1]:
|
2016-04-11 05:40:00 +00:00
|
|
|
result += QrCode._PENALTY_N2
|
|
|
|
|
|
|
|
# Finder-like pattern in rows
|
|
|
|
for y in range(size):
|
|
|
|
bits = 0
|
|
|
|
for x in range(size):
|
|
|
|
bits = ((bits << 1) & 0x7FF) | (1 if modules[y][x] else 0)
|
|
|
|
if x >= 10 and bits in (0x05D, 0x5D0): # Needs 11 bits accumulated
|
|
|
|
result += QrCode._PENALTY_N3
|
|
|
|
# Finder-like pattern in columns
|
|
|
|
for x in range(size):
|
|
|
|
bits = 0
|
|
|
|
for y in range(size):
|
|
|
|
bits = ((bits << 1) & 0x7FF) | (1 if modules[y][x] else 0)
|
|
|
|
if y >= 10 and bits in (0x05D, 0x5D0): # Needs 11 bits accumulated
|
|
|
|
result += QrCode._PENALTY_N3
|
|
|
|
|
|
|
|
# Balance of black and white modules
|
2017-05-08 06:41:17 +00:00
|
|
|
black = sum((1 if cell else 0) for row in modules for cell in row)
|
2018-08-26 03:55:03 +00:00
|
|
|
total = size**2 # Note that size is odd, so black/total != 1/2
|
2018-08-26 03:20:12 +00:00
|
|
|
# Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)%
|
|
|
|
k = (abs(black * 20 - total * 10) + total - 1) // total - 1
|
|
|
|
result += k * QrCode._PENALTY_N4
|
2016-04-11 05:40:00 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
2018-10-05 00:30:10 +00:00
|
|
|
# ---- Private helper functions ----
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2018-08-28 19:10:47 +00:00
|
|
|
def _get_alignment_pattern_positions(self):
|
|
|
|
"""Returns an ascending list of positions of alignment patterns for this version number.
|
|
|
|
Each position is in the range [0,177), and are used on both the x and y axes.
|
|
|
|
This could be implemented as lookup table of 40 variable-length lists of integers."""
|
|
|
|
ver = self._version
|
|
|
|
if ver == 1:
|
2016-04-11 05:40:00 +00:00
|
|
|
return []
|
|
|
|
else:
|
|
|
|
numalign = ver // 7 + 2
|
2018-08-22 20:58:16 +00:00
|
|
|
step = 26 if (ver == 32) else \
|
|
|
|
(ver*4 + numalign*2 + 1) // (numalign*2 - 2) * 2
|
2018-08-28 19:10:47 +00:00
|
|
|
result = [(self._size - 7 - i * step) for i in range(numalign - 1)] + [6]
|
2018-04-13 18:56:36 +00:00
|
|
|
return list(reversed(result))
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _get_num_raw_data_modules(ver):
|
2017-05-06 11:51:21 +00:00
|
|
|
"""Returns the number of data bits that can be stored in a QR Code of the given version number, after
|
|
|
|
all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
|
|
|
|
The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table."""
|
2017-10-23 04:42:53 +00:00
|
|
|
if not (QrCode.MIN_VERSION <= ver <= QrCode.MAX_VERSION):
|
2016-04-11 05:40:00 +00:00
|
|
|
raise ValueError("Version number out of range")
|
|
|
|
result = (16 * ver + 128) * ver + 64
|
|
|
|
if ver >= 2:
|
|
|
|
numalign = ver // 7 + 2
|
|
|
|
result -= (25 * numalign - 10) * numalign - 55
|
|
|
|
if ver >= 7:
|
2018-08-28 03:53:17 +00:00
|
|
|
result -= 36
|
2016-04-11 05:40:00 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _get_num_data_codewords(ver, ecl):
|
|
|
|
"""Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
|
|
|
|
QR Code of the given version number and error correction level, with remainder bits discarded.
|
|
|
|
This stateless pure function could be implemented as a (40*4)-cell lookup table."""
|
2017-08-31 20:19:41 +00:00
|
|
|
return QrCode._get_num_raw_data_modules(ver) // 8 \
|
2018-08-31 17:23:16 +00:00
|
|
|
- QrCode._ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver] \
|
2017-08-31 20:19:41 +00:00
|
|
|
* QrCode._NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
2018-10-04 19:40:43 +00:00
|
|
|
# ---- Constants and tables ----
|
|
|
|
|
2018-10-05 20:56:50 +00:00
|
|
|
MIN_VERSION = 1 # The minimum version number supported in the QR Code Model 2 standard
|
|
|
|
MAX_VERSION = 40 # The maximum version number supported in the QR Code Model 2 standard
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
# For use in getPenaltyScore(), when evaluating which mask is best.
|
2018-08-31 17:57:57 +00:00
|
|
|
_PENALTY_N1 = 3
|
|
|
|
_PENALTY_N2 = 3
|
2016-04-11 05:40:00 +00:00
|
|
|
_PENALTY_N3 = 40
|
|
|
|
_PENALTY_N4 = 10
|
|
|
|
|
2017-04-19 23:06:40 +00:00
|
|
|
_ECC_CODEWORDS_PER_BLOCK = (
|
2016-04-11 05:40:00 +00:00
|
|
|
# Version: (note that index 0 is for padding, and is set to an illegal value)
|
2017-04-19 23:06:40 +00:00
|
|
|
# 0, 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 Error correction level
|
|
|
|
(None, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30), # Low
|
|
|
|
(None, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28), # Medium
|
|
|
|
(None, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30), # Quartile
|
|
|
|
(None, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30)) # High
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
_NUM_ERROR_CORRECTION_BLOCKS = (
|
|
|
|
# Version: (note that index 0 is for padding, and is set to an illegal value)
|
|
|
|
# 0, 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 Error correction level
|
|
|
|
(None, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25), # Low
|
|
|
|
(None, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49), # Medium
|
|
|
|
(None, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68), # Quartile
|
|
|
|
(None, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81)) # High
|
|
|
|
|
|
|
|
_MASK_PATTERNS = (
|
|
|
|
(lambda x, y: (x + y) % 2 ),
|
|
|
|
(lambda x, y: y % 2 ),
|
|
|
|
(lambda x, y: x % 3 ),
|
|
|
|
(lambda x, y: (x + y) % 3 ),
|
|
|
|
(lambda x, y: (x // 3 + y // 2) % 2 ),
|
|
|
|
(lambda x, y: x * y % 2 + x * y % 3 ),
|
|
|
|
(lambda x, y: (x * y % 2 + x * y % 3) % 2 ),
|
|
|
|
(lambda x, y: ((x + y) % 2 + x * y % 3) % 2),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# ---- Public helper enumeration ----
|
2016-04-12 05:17:45 +00:00
|
|
|
|
2016-04-11 05:40:00 +00:00
|
|
|
class Ecc(object):
|
2018-10-05 17:58:16 +00:00
|
|
|
"""The error correction level in a QR Code symbol. Immutable."""
|
2016-04-11 05:40:00 +00:00
|
|
|
# Private constructor
|
|
|
|
def __init__(self, i, fb):
|
2016-04-20 20:46:46 +00:00
|
|
|
self.ordinal = i # (Public) In the range 0 to 3 (unsigned 2-bit integer)
|
2016-04-20 20:40:49 +00:00
|
|
|
self.formatbits = fb # (Package-private) In the range 0 to 3 (unsigned 2-bit integer)
|
2016-04-12 05:17:45 +00:00
|
|
|
|
2016-04-20 20:27:41 +00:00
|
|
|
# Public constants. Create them outside the class.
|
2018-10-05 17:58:16 +00:00
|
|
|
Ecc.LOW = Ecc(0, 1) # The QR Code can tolerate about 7% erroneous codewords
|
|
|
|
Ecc.MEDIUM = Ecc(1, 0) # The QR Code can tolerate about 15% erroneous codewords
|
|
|
|
Ecc.QUARTILE = Ecc(2, 3) # The QR Code can tolerate about 25% erroneous codewords
|
|
|
|
Ecc.HIGH = Ecc(3, 2) # The QR Code can tolerate about 30% erroneous codewords
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ---- Data segment class ----
|
|
|
|
|
|
|
|
class QrSegment(object):
|
2018-10-05 19:38:36 +00:00
|
|
|
"""A segment of character/binary/control data in a QR Code symbol.
|
|
|
|
Instances of this class are immutable.
|
|
|
|
The mid-level way to create a segment is to take the payload data
|
|
|
|
and call a static factory function such as QrSegment.make_numeric().
|
|
|
|
The low-level way to create a segment is to custom-make the bit buffer
|
|
|
|
and call the QrSegment() constructor with appropriate values.
|
2016-04-11 05:40:00 +00:00
|
|
|
This segment class imposes no length restrictions, but QR Codes have restrictions.
|
|
|
|
Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
|
|
|
|
Any segment longer than this is meaningless for the purpose of generating QR Codes."""
|
|
|
|
|
2018-10-04 19:56:07 +00:00
|
|
|
# ---- Static factory functions (mid level) ----
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def make_bytes(data):
|
2018-10-05 19:38:36 +00:00
|
|
|
"""Returns a segment representing the given binary data encoded in byte mode.
|
|
|
|
All input byte lists are acceptable. Any text string can be converted to
|
|
|
|
UTF-8 bytes (s.encode("UTF-8")) and encoded as a byte mode segment."""
|
2016-10-24 07:27:48 +00:00
|
|
|
py3 = sys.version_info.major >= 3
|
2017-05-06 12:14:59 +00:00
|
|
|
if (py3 and isinstance(data, str)) or (not py3 and isinstance(data, unicode)):
|
|
|
|
raise TypeError("Byte string/list expected")
|
|
|
|
if not py3 and isinstance(data, str):
|
|
|
|
data = bytearray(data)
|
|
|
|
bb = _BitBuffer()
|
2016-04-11 05:40:00 +00:00
|
|
|
for b in data:
|
2017-05-06 12:14:59 +00:00
|
|
|
bb.append_bits(b, 8)
|
2017-08-17 20:03:19 +00:00
|
|
|
return QrSegment(QrSegment.Mode.BYTE, len(data), bb)
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def make_numeric(digits):
|
|
|
|
"""Returns a segment representing the given string of decimal digits encoded in numeric mode."""
|
|
|
|
if QrSegment.NUMERIC_REGEX.match(digits) is None:
|
|
|
|
raise ValueError("String contains non-numeric characters")
|
|
|
|
bb = _BitBuffer()
|
2018-08-31 17:54:39 +00:00
|
|
|
i = 0
|
|
|
|
while i < len(digits): # Consume up to 3 digits per iteration
|
|
|
|
n = min(len(digits) - i, 3)
|
|
|
|
bb.append_bits(int(digits[i : i + n]), n * 3 + 1)
|
|
|
|
i += n
|
2017-08-17 20:03:19 +00:00
|
|
|
return QrSegment(QrSegment.Mode.NUMERIC, len(digits), bb)
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def make_alphanumeric(text):
|
2017-08-31 20:13:05 +00:00
|
|
|
"""Returns a segment representing the given text string encoded in alphanumeric mode.
|
|
|
|
The characters allowed are: 0 to 9, A to Z (uppercase only), space,
|
|
|
|
dollar, percent, asterisk, plus, hyphen, period, slash, colon."""
|
2016-04-11 05:40:00 +00:00
|
|
|
if QrSegment.ALPHANUMERIC_REGEX.match(text) is None:
|
|
|
|
raise ValueError("String contains unencodable characters in alphanumeric mode")
|
|
|
|
bb = _BitBuffer()
|
|
|
|
for i in range(0, len(text) - 1, 2): # Process groups of 2
|
2016-04-20 20:45:18 +00:00
|
|
|
temp = QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[i]] * 45
|
|
|
|
temp += QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[i + 1]]
|
2016-04-11 05:40:00 +00:00
|
|
|
bb.append_bits(temp, 11)
|
|
|
|
if len(text) % 2 > 0: # 1 character remaining
|
2016-04-20 20:45:18 +00:00
|
|
|
bb.append_bits(QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[-1]], 6)
|
2017-08-17 20:03:19 +00:00
|
|
|
return QrSegment(QrSegment.Mode.ALPHANUMERIC, len(text), bb)
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
2016-04-16 01:44:24 +00:00
|
|
|
@staticmethod
|
|
|
|
def make_segments(text):
|
|
|
|
"""Returns a new mutable list of zero or more segments to represent the given Unicode text string.
|
|
|
|
The result may use various segment modes and switch modes to optimize the length of the bit stream."""
|
2016-10-24 07:27:48 +00:00
|
|
|
if not (isinstance(text, str) or (sys.version_info.major < 3 and isinstance(text, unicode))):
|
2016-04-16 01:44:24 +00:00
|
|
|
raise TypeError("Text string expected")
|
|
|
|
|
|
|
|
# Select the most efficient segment encoding automatically
|
|
|
|
if text == "":
|
|
|
|
return []
|
|
|
|
elif QrSegment.NUMERIC_REGEX.match(text) is not None:
|
|
|
|
return [QrSegment.make_numeric(text)]
|
|
|
|
elif QrSegment.ALPHANUMERIC_REGEX.match(text) is not None:
|
|
|
|
return [QrSegment.make_alphanumeric(text)]
|
|
|
|
else:
|
|
|
|
return [QrSegment.make_bytes(text.encode("UTF-8"))]
|
|
|
|
|
|
|
|
|
2017-05-08 18:04:10 +00:00
|
|
|
@staticmethod
|
|
|
|
def make_eci(assignval):
|
|
|
|
"""Returns a segment representing an Extended Channel Interpretation
|
|
|
|
(ECI) designator with the given assignment value."""
|
|
|
|
bb = _BitBuffer()
|
2018-10-04 19:26:21 +00:00
|
|
|
if assignval < 0:
|
|
|
|
raise ValueError("ECI assignment value out of range")
|
|
|
|
elif assignval < (1 << 7):
|
2017-05-08 18:04:10 +00:00
|
|
|
bb.append_bits(assignval, 8)
|
2018-10-04 19:26:21 +00:00
|
|
|
elif assignval < (1 << 14):
|
2017-05-08 18:04:10 +00:00
|
|
|
bb.append_bits(2, 2)
|
|
|
|
bb.append_bits(assignval, 14)
|
2018-10-04 19:26:21 +00:00
|
|
|
elif assignval < 1000000:
|
2017-05-08 18:04:10 +00:00
|
|
|
bb.append_bits(6, 3)
|
|
|
|
bb.append_bits(assignval, 21)
|
|
|
|
else:
|
|
|
|
raise ValueError("ECI assignment value out of range")
|
2017-08-17 20:03:19 +00:00
|
|
|
return QrSegment(QrSegment.Mode.ECI, 0, bb)
|
2017-05-08 18:04:10 +00:00
|
|
|
|
|
|
|
|
2018-10-04 19:56:07 +00:00
|
|
|
# ---- Constructor (low level) ----
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
def __init__(self, mode, numch, bitdata):
|
2018-10-05 19:38:36 +00:00
|
|
|
"""Creates a new QR Code segment with the given attributes and data.
|
2018-10-05 00:21:12 +00:00
|
|
|
The character count (numch) must agree with the mode and the bit buffer length,
|
|
|
|
but the constraint isn't checked. The given bit buffer is cloned and stored."""
|
2018-10-05 00:23:09 +00:00
|
|
|
if not isinstance(mode, QrSegment.Mode):
|
|
|
|
raise TypeError("QrSegment.Mode expected")
|
|
|
|
if numch < 0:
|
2016-04-11 05:40:00 +00:00
|
|
|
raise ValueError()
|
2018-10-05 00:23:28 +00:00
|
|
|
|
2018-10-05 19:27:11 +00:00
|
|
|
# The mode indicator of this segment. Accessed through get_mode().
|
2016-04-11 05:40:00 +00:00
|
|
|
self._mode = mode
|
2018-10-05 00:21:12 +00:00
|
|
|
|
2018-10-05 19:27:11 +00:00
|
|
|
# The length of this segment's unencoded data. Measured in characters for
|
2018-10-05 00:21:12 +00:00
|
|
|
# numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
|
2018-10-05 19:27:11 +00:00
|
|
|
# Always zero or positive. Not the same as the data's bit length.
|
|
|
|
# Accessed through get_num_chars().
|
2016-04-11 05:40:00 +00:00
|
|
|
self._numchars = numch
|
2018-10-05 00:21:12 +00:00
|
|
|
|
2018-10-05 00:23:28 +00:00
|
|
|
# The data bits of this segment. Accessed through get_bits().
|
2017-08-18 03:36:00 +00:00
|
|
|
self._bitdata = list(bitdata) # Make defensive copy
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
2016-04-20 20:19:57 +00:00
|
|
|
# ---- Accessor methods ----
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
def get_mode(self):
|
2018-10-05 19:30:21 +00:00
|
|
|
"""Returns the mode field of this segment."""
|
2016-04-11 05:40:00 +00:00
|
|
|
return self._mode
|
|
|
|
|
|
|
|
def get_num_chars(self):
|
2018-10-05 19:30:21 +00:00
|
|
|
"""Returns the character count field of this segment."""
|
2016-04-11 05:40:00 +00:00
|
|
|
return self._numchars
|
|
|
|
|
|
|
|
def get_bits(self):
|
2018-10-05 19:30:21 +00:00
|
|
|
"""Returns a new copy of the data bits of this segment."""
|
2017-08-18 03:36:00 +00:00
|
|
|
return list(self._bitdata) # Make defensive copy
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
2018-08-28 19:40:35 +00:00
|
|
|
# Package-private function
|
2016-04-16 03:53:58 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_total_bits(segs, version):
|
2018-08-28 19:40:35 +00:00
|
|
|
"""Calculates the number of bits needed to encode the given segments at
|
|
|
|
the given version. Returns a non-negative number if successful. Otherwise
|
|
|
|
returns None if a segment has too many characters to fit its length field."""
|
2016-04-16 03:53:58 +00:00
|
|
|
result = 0
|
|
|
|
for seg in segs:
|
|
|
|
ccbits = seg.get_mode().num_char_count_bits(version)
|
|
|
|
if seg.get_num_chars() >= (1 << ccbits):
|
2018-08-28 16:36:07 +00:00
|
|
|
return None # The segment's length doesn't fit the field's bit width
|
2017-08-17 20:03:19 +00:00
|
|
|
result += 4 + ccbits + len(seg._bitdata)
|
2016-04-16 03:53:58 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
2016-04-20 20:19:57 +00:00
|
|
|
# ---- Constants ----
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2018-10-05 19:34:42 +00:00
|
|
|
# (Public) Describes precisely all strings that are encodable in numeric mode.
|
|
|
|
# To test whether a string s is encodable: ok = NUMERIC_REGEX.fullmatch(s) is not None
|
|
|
|
# A string is encodable iff each character is in the range 0 to 9.
|
2017-04-20 22:48:13 +00:00
|
|
|
NUMERIC_REGEX = re.compile(r"[0-9]*\Z")
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2018-10-05 19:34:42 +00:00
|
|
|
# (Public) Describes precisely all strings that are encodable in alphanumeric mode.
|
|
|
|
# To test whether a string s is encodable: ok = ALPHANUMERIC_REGEX.fullmatch(s) is not None
|
|
|
|
# A string is encodable iff each character is in the following set: 0 to 9, A to Z
|
|
|
|
# (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
|
|
|
|
|
2017-04-20 22:48:13 +00:00
|
|
|
ALPHANUMERIC_REGEX = re.compile(r"[A-Z0-9 $%*+./:-]*\Z")
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2016-04-20 20:45:18 +00:00
|
|
|
# (Private) Dictionary of "0"->0, "A"->10, "$"->37, etc.
|
|
|
|
_ALPHANUMERIC_ENCODING_TABLE = {ch: i for (i, ch) in enumerate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:")}
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
2016-04-20 20:19:57 +00:00
|
|
|
# ---- Public helper enumeration ----
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
class Mode(object):
|
2018-10-05 17:58:16 +00:00
|
|
|
"""Describes how a segment's data bits are interpreted. Immutable."""
|
2016-04-20 20:27:41 +00:00
|
|
|
|
2016-04-11 05:40:00 +00:00
|
|
|
# Private constructor
|
|
|
|
def __init__(self, modebits, charcounts):
|
2018-08-28 21:08:00 +00:00
|
|
|
self._modebits = modebits # The mode indicator bits, which is a uint4 value (range 0 to 15)
|
2018-10-04 22:16:25 +00:00
|
|
|
self._charcounts = charcounts # Number of character count bits for three different version ranges
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2016-04-20 20:40:49 +00:00
|
|
|
# Package-private method
|
2016-04-11 05:40:00 +00:00
|
|
|
def get_mode_bits(self):
|
2016-04-20 20:27:41 +00:00
|
|
|
"""Returns an unsigned 4-bit integer value (range 0 to 15) representing the mode indicator bits for this mode object."""
|
2016-04-11 05:40:00 +00:00
|
|
|
return self._modebits
|
|
|
|
|
2016-04-20 20:40:49 +00:00
|
|
|
# Package-private method
|
2016-04-11 05:40:00 +00:00
|
|
|
def num_char_count_bits(self, ver):
|
2018-10-04 22:16:25 +00:00
|
|
|
"""Returns the bit width of the character count field for a segment in this mode
|
|
|
|
in a QR Code at the given version number. The result is in the range [0, 16]."""
|
2018-08-28 20:11:05 +00:00
|
|
|
return self._charcounts[(ver + 7) // 17]
|
2016-04-11 05:40:00 +00:00
|
|
|
|
2016-04-20 20:27:41 +00:00
|
|
|
# Public constants. Create them outside the class.
|
2016-04-11 05:40:00 +00:00
|
|
|
Mode.NUMERIC = Mode(0x1, (10, 12, 14))
|
|
|
|
Mode.ALPHANUMERIC = Mode(0x2, ( 9, 11, 13))
|
|
|
|
Mode.BYTE = Mode(0x4, ( 8, 16, 16))
|
|
|
|
Mode.KANJI = Mode(0x8, ( 8, 10, 12))
|
2017-05-08 18:04:10 +00:00
|
|
|
Mode.ECI = Mode(0x7, ( 0, 0, 0))
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ---- Private helper classes ----
|
|
|
|
|
|
|
|
class _ReedSolomonGenerator(object):
|
|
|
|
"""Computes the Reed-Solomon error correction codewords for a sequence of data codewords
|
|
|
|
at a given degree. Objects are immutable, and the state only depends on the degree.
|
2017-08-31 19:51:31 +00:00
|
|
|
This class exists because each data block in a QR Code shares the same the divisor polynomial."""
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
def __init__(self, degree):
|
|
|
|
"""Creates a Reed-Solomon ECC generator for the given degree. This could be implemented
|
|
|
|
as a lookup table over all possible parameter values, instead of as an algorithm."""
|
|
|
|
if degree < 1 or degree > 255:
|
|
|
|
raise ValueError("Degree out of range")
|
|
|
|
|
|
|
|
# Start with the monomial x^0
|
|
|
|
self.coefficients = [0] * (degree - 1) + [1]
|
|
|
|
|
|
|
|
# Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
|
|
|
|
# drop the highest term, and store the rest of the coefficients in order of descending powers.
|
|
|
|
# Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
|
|
|
|
root = 1
|
2017-08-28 01:06:43 +00:00
|
|
|
for _ in range(degree): # Unused variable i
|
2016-04-11 05:40:00 +00:00
|
|
|
# Multiply the current product by (x - r^i)
|
|
|
|
for j in range(degree):
|
2017-05-08 06:40:58 +00:00
|
|
|
self.coefficients[j] = _ReedSolomonGenerator._multiply(self.coefficients[j], root)
|
2016-04-11 05:40:00 +00:00
|
|
|
if j + 1 < degree:
|
|
|
|
self.coefficients[j] ^= self.coefficients[j + 1]
|
2017-05-08 06:40:58 +00:00
|
|
|
root = _ReedSolomonGenerator._multiply(root, 0x02)
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
def get_remainder(self, data):
|
2017-08-31 20:13:05 +00:00
|
|
|
"""Computes and returns the Reed-Solomon error correction codewords for the given
|
|
|
|
sequence of data codewords. The returned object is always a new byte list.
|
|
|
|
This method does not alter this object's state (because it is immutable)."""
|
2016-04-11 05:40:00 +00:00
|
|
|
# Compute the remainder by performing polynomial division
|
|
|
|
result = [0] * len(self.coefficients)
|
|
|
|
for b in data:
|
2017-08-27 00:05:52 +00:00
|
|
|
factor = b ^ result.pop(0)
|
2016-04-11 05:40:00 +00:00
|
|
|
result.append(0)
|
2016-06-14 17:10:55 +00:00
|
|
|
for i in range(len(result)):
|
2017-05-08 06:40:58 +00:00
|
|
|
result[i] ^= _ReedSolomonGenerator._multiply(self.coefficients[i], factor)
|
2016-04-11 05:40:00 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
2017-05-08 06:40:58 +00:00
|
|
|
def _multiply(x, y):
|
2016-04-11 05:40:00 +00:00
|
|
|
"""Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
|
|
|
|
are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8."""
|
2016-04-12 05:17:45 +00:00
|
|
|
if x >> 8 != 0 or y >> 8 != 0:
|
2016-04-11 05:40:00 +00:00
|
|
|
raise ValueError("Byte out of range")
|
|
|
|
# Russian peasant multiplication
|
|
|
|
z = 0
|
|
|
|
for i in reversed(range(8)):
|
|
|
|
z = (z << 1) ^ ((z >> 7) * 0x11D)
|
|
|
|
z ^= ((y >> i) & 1) * x
|
2016-04-12 05:17:45 +00:00
|
|
|
assert z >> 8 == 0
|
2016-04-11 05:40:00 +00:00
|
|
|
return z
|
|
|
|
|
|
|
|
|
|
|
|
|
2017-08-17 20:03:19 +00:00
|
|
|
class _BitBuffer(list):
|
2018-10-05 17:35:18 +00:00
|
|
|
"""An appendable sequence of bits (0s and 1s). Mainly used by QrSegment."""
|
2016-04-11 05:40:00 +00:00
|
|
|
|
|
|
|
def get_bytes(self):
|
2018-10-05 17:35:18 +00:00
|
|
|
"""Returns a new list representing this buffer's bits packed into bytes in big endian. If the
|
|
|
|
bit length isn't a multiple of 8, then the remaining bits of the final byte are all '0'."""
|
2017-08-17 20:03:19 +00:00
|
|
|
result = [0] * ((len(self) + 7) // 8)
|
|
|
|
for (i, bit) in enumerate(self):
|
2016-04-11 05:40:00 +00:00
|
|
|
result[i >> 3] |= bit << (7 - (i & 7))
|
|
|
|
return result
|
|
|
|
|
|
|
|
def append_bits(self, val, n):
|
2018-10-05 17:35:18 +00:00
|
|
|
"""Appends the given number of low-order bits of the given
|
|
|
|
value to this buffer. Requires n >= 0 and 0 <= val < 2^n."""
|
2017-05-08 06:41:17 +00:00
|
|
|
if n < 0 or val >> n != 0:
|
2016-04-11 05:40:00 +00:00
|
|
|
raise ValueError("Value out of range")
|
2017-08-17 20:03:19 +00:00
|
|
|
self.extend(((val >> i) & 1) for i in reversed(range(n)))
|
2018-04-13 19:48:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _get_bit(x, i):
|
|
|
|
"""Returns true iff the i'th bit of x is set to 1."""
|
|
|
|
return (x >> i) & 1 != 0
|