qrcodegen.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. #
  2. # QR Code generator library (Python)
  3. #
  4. # Copyright (c) Project Nayuki. (MIT License)
  5. # https://www.nayuki.io/page/qr-code-generator-library
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. # this software and associated documentation files (the "Software"), to deal in
  9. # the Software without restriction, including without limitation the rights to
  10. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. # the Software, and to permit persons to whom the Software is furnished to do so,
  12. # subject to the following conditions:
  13. # - The above copyright notice and this permission notice shall be included in
  14. # all copies or substantial portions of the Software.
  15. # - The Software is provided "as is", without warranty of any kind, express or
  16. # implied, including but not limited to the warranties of merchantability,
  17. # fitness for a particular purpose and noninfringement. In no event shall the
  18. # authors or copyright holders be liable for any claim, damages or other
  19. # liability, whether in an action of contract, tort or otherwise, arising from,
  20. # out of or in connection with the Software or the use or other dealings in the
  21. # Software.
  22. #
  23. from __future__ import annotations
  24. import collections, itertools, re
  25. from collections.abc import Sequence
  26. from typing import Callable, Dict, List, Optional, Tuple, Union
  27. # ---- QR Code symbol class ----
  28. class QrCode:
  29. """A QR Code symbol, which is a type of two-dimension barcode.
  30. Invented by Denso Wave and described in the ISO/IEC 18004 standard.
  31. Instances of this class represent an immutable square grid of dark and light cells.
  32. The class provides static factory functions to create a QR Code from text or binary data.
  33. The class covers the QR Code Model 2 specification, supporting all versions (sizes)
  34. from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
  35. Ways to create a QR Code object:
  36. - High level: Take the payload data and call QrCode.encode_text() or QrCode.encode_binary().
  37. - Mid level: Custom-make the list of segments and call QrCode.encode_segments().
  38. - Low level: Custom-make the array of data codeword bytes (including
  39. segment headers and final padding, excluding error correction codewords),
  40. supply the appropriate version number, and call the QrCode() constructor.
  41. (Note that all ways require supplying the desired error correction level.)"""
  42. # ---- Static factory functions (high level) ----
  43. @staticmethod
  44. def encode_text(text: str, ecl: QrCode.Ecc) -> QrCode:
  45. """Returns a QR Code representing the given Unicode text string at the given error correction level.
  46. As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
  47. Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
  48. QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
  49. ecl argument if it can be done without increasing the version."""
  50. segs: List[QrSegment] = QrSegment.make_segments(text)
  51. return QrCode.encode_segments(segs, ecl)
  52. @staticmethod
  53. def encode_binary(data: Union[bytes,Sequence[int]], ecl: QrCode.Ecc) -> QrCode:
  54. """Returns a QR Code representing the given binary data at the given error correction level.
  55. This function always encodes using the binary segment mode, not any text mode. The maximum number of
  56. bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
  57. The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version."""
  58. return QrCode.encode_segments([QrSegment.make_bytes(data)], ecl)
  59. # ---- Static factory functions (mid level) ----
  60. @staticmethod
  61. def encode_segments(segs: Sequence[QrSegment], ecl: QrCode.Ecc, minversion: int = 1, maxversion: int = 40, mask: int = -1, boostecl: bool = True) -> QrCode:
  62. """Returns a QR Code representing the given segments with the given encoding parameters.
  63. The smallest possible QR Code version within the given range is automatically
  64. chosen for the output. Iff boostecl is true, then the ECC level of the result
  65. may be higher than the ecl argument if it can be done without increasing the
  66. version. The mask number is either between 0 to 7 (inclusive) to force that
  67. mask, or -1 to automatically choose an appropriate mask (which may be slow).
  68. This function allows the user to create a custom sequence of segments that switches
  69. between modes (such as alphanumeric and byte) to encode text in less space.
  70. This is a mid-level API; the high-level API is encode_text() and encode_binary()."""
  71. if not (QrCode.MIN_VERSION <= minversion <= maxversion <= QrCode.MAX_VERSION) or not (-1 <= mask <= 7):
  72. raise ValueError("Invalid value")
  73. # Find the minimal version number to use
  74. for version in range(minversion, maxversion + 1):
  75. datacapacitybits: int = QrCode._get_num_data_codewords(version, ecl) * 8 # Number of data bits available
  76. datausedbits: Optional[int] = QrSegment.get_total_bits(segs, version)
  77. if (datausedbits is not None) and (datausedbits <= datacapacitybits):
  78. break # This version number is found to be suitable
  79. if version >= maxversion: # All versions in the range could not fit the given data
  80. msg: str = "Segment too long"
  81. if datausedbits is not None:
  82. msg = f"Data length = {datausedbits} bits, Max capacity = {datacapacitybits} bits"
  83. raise DataTooLongError(msg)
  84. assert datausedbits is not None
  85. # Increase the error correction level while the data still fits in the current version number
  86. for newecl in (QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH): # From low to high
  87. if boostecl and (datausedbits <= QrCode._get_num_data_codewords(version, newecl) * 8):
  88. ecl = newecl
  89. # Concatenate all segments to create the data bit string
  90. bb = _BitBuffer()
  91. for seg in segs:
  92. bb.append_bits(seg.get_mode().get_mode_bits(), 4)
  93. bb.append_bits(seg.get_num_chars(), seg.get_mode().num_char_count_bits(version))
  94. bb.extend(seg._bitdata)
  95. assert len(bb) == datausedbits
  96. # Add terminator and pad up to a byte if applicable
  97. datacapacitybits = QrCode._get_num_data_codewords(version, ecl) * 8
  98. assert len(bb) <= datacapacitybits
  99. bb.append_bits(0, min(4, datacapacitybits - len(bb)))
  100. bb.append_bits(0, -len(bb) % 8) # Note: Python's modulo on negative numbers behaves better than C family languages
  101. assert len(bb) % 8 == 0
  102. # Pad with alternating bytes until data capacity is reached
  103. for padbyte in itertools.cycle((0xEC, 0x11)):
  104. if len(bb) >= datacapacitybits:
  105. break
  106. bb.append_bits(padbyte, 8)
  107. # Pack bits into bytes in big endian
  108. datacodewords = bytearray([0] * (len(bb) // 8))
  109. for (i, bit) in enumerate(bb):
  110. datacodewords[i >> 3] |= bit << (7 - (i & 7))
  111. # Create the QR Code object
  112. return QrCode(version, ecl, datacodewords, mask)
  113. # ---- Private fields ----
  114. # The version number of this QR Code, which is between 1 and 40 (inclusive).
  115. # This determines the size of this barcode.
  116. _version: int
  117. # The width and height of this QR Code, measured in modules, between
  118. # 21 and 177 (inclusive). This is equal to version * 4 + 17.
  119. _size: int
  120. # The error correction level used in this QR Code.
  121. _errcorlvl: QrCode.Ecc
  122. # The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
  123. # Even if a QR Code is created with automatic masking requested (mask = -1),
  124. # the resulting object still has a mask value between 0 and 7.
  125. _mask: int
  126. # The modules of this QR Code (False = light, True = dark).
  127. # Immutable after constructor finishes. Accessed through get_module().
  128. _modules: List[List[bool]]
  129. # Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
  130. _isfunction: List[List[bool]]
  131. # ---- Constructor (low level) ----
  132. def __init__(self, version: int, errcorlvl: QrCode.Ecc, datacodewords: Union[bytes,Sequence[int]], msk: int) -> None:
  133. """Creates a new QR Code with the given version number,
  134. error correction level, data codeword bytes, and mask number.
  135. This is a low-level API that most users should not use directly.
  136. A mid-level API is the encode_segments() function."""
  137. # Check scalar arguments and set fields
  138. if not (QrCode.MIN_VERSION <= version <= QrCode.MAX_VERSION):
  139. raise ValueError("Version value out of range")
  140. if not (-1 <= msk <= 7):
  141. raise ValueError("Mask value out of range")
  142. self._version = version
  143. self._size = version * 4 + 17
  144. self._errcorlvl = errcorlvl
  145. # Initialize both grids to be size*size arrays of Boolean false
  146. self._modules = [[False] * self._size for _ in range(self._size)] # Initially all light
  147. self._isfunction = [[False] * self._size for _ in range(self._size)]
  148. # Compute ECC, draw modules
  149. self._draw_function_patterns()
  150. allcodewords: bytes = self._add_ecc_and_interleave(bytearray(datacodewords))
  151. self._draw_codewords(allcodewords)
  152. # Do masking
  153. if msk == -1: # Automatically choose best mask
  154. minpenalty: int = 1 << 32
  155. for i in range(8):
  156. self._apply_mask(i)
  157. self._draw_format_bits(i)
  158. penalty = self._get_penalty_score()
  159. if penalty < minpenalty:
  160. msk = i
  161. minpenalty = penalty
  162. self._apply_mask(i) # Undoes the mask due to XOR
  163. assert 0 <= msk <= 7
  164. self._mask = msk
  165. self._apply_mask(msk) # Apply the final choice of mask
  166. self._draw_format_bits(msk) # Overwrite old format bits
  167. del self._isfunction
  168. # ---- Accessor methods ----
  169. def get_version(self) -> int:
  170. """Returns this QR Code's version number, in the range [1, 40]."""
  171. return self._version
  172. def get_size(self) -> int:
  173. """Returns this QR Code's size, in the range [21, 177]."""
  174. return self._size
  175. def get_error_correction_level(self) -> QrCode.Ecc:
  176. """Returns this QR Code's error correction level."""
  177. return self._errcorlvl
  178. def get_mask(self) -> int:
  179. """Returns this QR Code's mask, in the range [0, 7]."""
  180. return self._mask
  181. def get_module(self, x: int, y: int) -> bool:
  182. """Returns the color of the module (pixel) at the given coordinates, which is False
  183. for light or True for dark. The top left corner has the coordinates (x=0, y=0).
  184. If the given coordinates are out of bounds, then False (light) is returned."""
  185. return (0 <= x < self._size) and (0 <= y < self._size) and self._modules[y][x]
  186. # ---- Private helper methods for constructor: Drawing function modules ----
  187. def _draw_function_patterns(self) -> None:
  188. """Reads this object's version field, and draws and marks all function modules."""
  189. # Draw horizontal and vertical timing patterns
  190. for i in range(self._size):
  191. self._set_function_module(6, i, i % 2 == 0)
  192. self._set_function_module(i, 6, i % 2 == 0)
  193. # Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
  194. self._draw_finder_pattern(3, 3)
  195. self._draw_finder_pattern(self._size - 4, 3)
  196. self._draw_finder_pattern(3, self._size - 4)
  197. # Draw numerous alignment patterns
  198. alignpatpos: List[int] = self._get_alignment_pattern_positions()
  199. numalign: int = len(alignpatpos)
  200. skips: Sequence[Tuple[int,int]] = ((0, 0), (0, numalign - 1), (numalign - 1, 0))
  201. for i in range(numalign):
  202. for j in range(numalign):
  203. if (i, j) not in skips: # Don't draw on the three finder corners
  204. self._draw_alignment_pattern(alignpatpos[i], alignpatpos[j])
  205. # Draw configuration data
  206. self._draw_format_bits(0) # Dummy mask value; overwritten later in the constructor
  207. self._draw_version()
  208. def _draw_format_bits(self, mask: int) -> None:
  209. """Draws two copies of the format bits (with its own error correction code)
  210. based on the given mask and this object's error correction level field."""
  211. # Calculate error correction code and pack bits
  212. data: int = self._errcorlvl.formatbits << 3 | mask # errCorrLvl is uint2, mask is uint3
  213. rem: int = data
  214. for _ in range(10):
  215. rem = (rem << 1) ^ ((rem >> 9) * 0x537)
  216. bits: int = (data << 10 | rem) ^ 0x5412 # uint15
  217. assert bits >> 15 == 0
  218. # Draw first copy
  219. for i in range(0, 6):
  220. self._set_function_module(8, i, _get_bit(bits, i))
  221. self._set_function_module(8, 7, _get_bit(bits, 6))
  222. self._set_function_module(8, 8, _get_bit(bits, 7))
  223. self._set_function_module(7, 8, _get_bit(bits, 8))
  224. for i in range(9, 15):
  225. self._set_function_module(14 - i, 8, _get_bit(bits, i))
  226. # Draw second copy
  227. for i in range(0, 8):
  228. self._set_function_module(self._size - 1 - i, 8, _get_bit(bits, i))
  229. for i in range(8, 15):
  230. self._set_function_module(8, self._size - 15 + i, _get_bit(bits, i))
  231. self._set_function_module(8, self._size - 8, True) # Always dark
  232. def _draw_version(self) -> None:
  233. """Draws two copies of the version bits (with its own error correction code),
  234. based on this object's version field, iff 7 <= version <= 40."""
  235. if self._version < 7:
  236. return
  237. # Calculate error correction code and pack bits
  238. rem: int = self._version # version is uint6, in the range [7, 40]
  239. for _ in range(12):
  240. rem = (rem << 1) ^ ((rem >> 11) * 0x1F25)
  241. bits: int = self._version << 12 | rem # uint18
  242. assert bits >> 18 == 0
  243. # Draw two copies
  244. for i in range(18):
  245. bit: bool = _get_bit(bits, i)
  246. a: int = self._size - 11 + i % 3
  247. b: int = i // 3
  248. self._set_function_module(a, b, bit)
  249. self._set_function_module(b, a, bit)
  250. def _draw_finder_pattern(self, x: int, y: int) -> None:
  251. """Draws a 9*9 finder pattern including the border separator,
  252. with the center module at (x, y). Modules can be out of bounds."""
  253. for dy in range(-4, 5):
  254. for dx in range(-4, 5):
  255. xx, yy = x + dx, y + dy
  256. if (0 <= xx < self._size) and (0 <= yy < self._size):
  257. # Chebyshev/infinity norm
  258. self._set_function_module(xx, yy, max(abs(dx), abs(dy)) not in (2, 4))
  259. def _draw_alignment_pattern(self, x: int, y: int) -> None:
  260. """Draws a 5*5 alignment pattern, with the center module
  261. at (x, y). All modules must be in bounds."""
  262. for dy in range(-2, 3):
  263. for dx in range(-2, 3):
  264. self._set_function_module(x + dx, y + dy, max(abs(dx), abs(dy)) != 1)
  265. def _set_function_module(self, x: int, y: int, isdark: bool) -> None:
  266. """Sets the color of a module and marks it as a function module.
  267. Only used by the constructor. Coordinates must be in bounds."""
  268. assert type(isdark) is bool
  269. self._modules[y][x] = isdark
  270. self._isfunction[y][x] = True
  271. # ---- Private helper methods for constructor: Codewords and masking ----
  272. def _add_ecc_and_interleave(self, data: bytearray) -> bytes:
  273. """Returns a new byte string representing the given data with the appropriate error correction
  274. codewords appended to it, based on this object's version and error correction level."""
  275. version: int = self._version
  276. assert len(data) == QrCode._get_num_data_codewords(version, self._errcorlvl)
  277. # Calculate parameter numbers
  278. numblocks: int = QrCode._NUM_ERROR_CORRECTION_BLOCKS[self._errcorlvl.ordinal][version]
  279. blockecclen: int = QrCode._ECC_CODEWORDS_PER_BLOCK [self._errcorlvl.ordinal][version]
  280. rawcodewords: int = QrCode._get_num_raw_data_modules(version) // 8
  281. numshortblocks: int = numblocks - rawcodewords % numblocks
  282. shortblocklen: int = rawcodewords // numblocks
  283. # Split data into blocks and append ECC to each block
  284. blocks: List[bytes] = []
  285. rsdiv: bytes = QrCode._reed_solomon_compute_divisor(blockecclen)
  286. k: int = 0
  287. for i in range(numblocks):
  288. dat: bytearray = data[k : k + shortblocklen - blockecclen + (0 if i < numshortblocks else 1)]
  289. k += len(dat)
  290. ecc: bytes = QrCode._reed_solomon_compute_remainder(dat, rsdiv)
  291. if i < numshortblocks:
  292. dat.append(0)
  293. blocks.append(dat + ecc)
  294. assert k == len(data)
  295. # Interleave (not concatenate) the bytes from every block into a single sequence
  296. result = bytearray()
  297. for i in range(len(blocks[0])):
  298. for (j, blk) in enumerate(blocks):
  299. # Skip the padding byte in short blocks
  300. if (i != shortblocklen - blockecclen) or (j >= numshortblocks):
  301. result.append(blk[i])
  302. assert len(result) == rawcodewords
  303. return result
  304. def _draw_codewords(self, data: bytes) -> None:
  305. """Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
  306. data area of this QR Code. Function modules need to be marked off before this is called."""
  307. assert len(data) == QrCode._get_num_raw_data_modules(self._version) // 8
  308. i: int = 0 # Bit index into the data
  309. # Do the funny zigzag scan
  310. for right in range(self._size - 1, 0, -2): # Index of right column in each column pair
  311. if right <= 6:
  312. right -= 1
  313. for vert in range(self._size): # Vertical counter
  314. for j in range(2):
  315. x: int = right - j # Actual x coordinate
  316. upward: bool = (right + 1) & 2 == 0
  317. y: int = (self._size - 1 - vert) if upward else vert # Actual y coordinate
  318. if (not self._isfunction[y][x]) and (i < len(data) * 8):
  319. self._modules[y][x] = _get_bit(data[i >> 3], 7 - (i & 7))
  320. i += 1
  321. # If this QR Code has any remainder bits (0 to 7), they were assigned as
  322. # 0/false/light by the constructor and are left unchanged by this method
  323. assert i == len(data) * 8
  324. def _apply_mask(self, mask: int) -> None:
  325. """XORs the codeword modules in this QR Code with the given mask pattern.
  326. The function modules must be marked and the codeword bits must be drawn
  327. before masking. Due to the arithmetic of XOR, calling _apply_mask() with
  328. the same mask value a second time will undo the mask. A final well-formed
  329. QR Code needs exactly one (not zero, two, etc.) mask applied."""
  330. if not (0 <= mask <= 7):
  331. raise ValueError("Mask value out of range")
  332. masker: Callable[[int,int],int] = QrCode._MASK_PATTERNS[mask]
  333. for y in range(self._size):
  334. for x in range(self._size):
  335. self._modules[y][x] ^= (masker(x, y) == 0) and (not self._isfunction[y][x])
  336. def _get_penalty_score(self) -> int:
  337. """Calculates and returns the penalty score based on state of this QR Code's current modules.
  338. This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score."""
  339. result: int = 0
  340. size: int = self._size
  341. modules: List[List[bool]] = self._modules
  342. # Adjacent modules in row having same color, and finder-like patterns
  343. for y in range(size):
  344. runcolor: bool = False
  345. runx: int = 0
  346. runhistory = collections.deque([0] * 7, 7)
  347. for x in range(size):
  348. if modules[y][x] == runcolor:
  349. runx += 1
  350. if runx == 5:
  351. result += QrCode._PENALTY_N1
  352. elif runx > 5:
  353. result += 1
  354. else:
  355. self._finder_penalty_add_history(runx, runhistory)
  356. if not runcolor:
  357. result += self._finder_penalty_count_patterns(runhistory) * QrCode._PENALTY_N3
  358. runcolor = modules[y][x]
  359. runx = 1
  360. result += self._finder_penalty_terminate_and_count(runcolor, runx, runhistory) * QrCode._PENALTY_N3
  361. # Adjacent modules in column having same color, and finder-like patterns
  362. for x in range(size):
  363. runcolor = False
  364. runy = 0
  365. runhistory = collections.deque([0] * 7, 7)
  366. for y in range(size):
  367. if modules[y][x] == runcolor:
  368. runy += 1
  369. if runy == 5:
  370. result += QrCode._PENALTY_N1
  371. elif runy > 5:
  372. result += 1
  373. else:
  374. self._finder_penalty_add_history(runy, runhistory)
  375. if not runcolor:
  376. result += self._finder_penalty_count_patterns(runhistory) * QrCode._PENALTY_N3
  377. runcolor = modules[y][x]
  378. runy = 1
  379. result += self._finder_penalty_terminate_and_count(runcolor, runy, runhistory) * QrCode._PENALTY_N3
  380. # 2*2 blocks of modules having same color
  381. for y in range(size - 1):
  382. for x in range(size - 1):
  383. if modules[y][x] == modules[y][x + 1] == modules[y + 1][x] == modules[y + 1][x + 1]:
  384. result += QrCode._PENALTY_N2
  385. # Balance of dark and light modules
  386. dark: int = sum((1 if cell else 0) for row in modules for cell in row)
  387. total: int = size**2 # Note that size is odd, so dark/total != 1/2
  388. # Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
  389. k: int = (abs(dark * 20 - total * 10) + total - 1) // total - 1
  390. assert 0 <= k <= 9
  391. result += k * QrCode._PENALTY_N4
  392. assert 0 <= result <= 2568888 # Non-tight upper bound based on default values of PENALTY_N1, ..., N4
  393. return result
  394. # ---- Private helper functions ----
  395. def _get_alignment_pattern_positions(self) -> List[int]:
  396. """Returns an ascending list of positions of alignment patterns for this version number.
  397. Each position is in the range [0,177), and are used on both the x and y axes.
  398. This could be implemented as lookup table of 40 variable-length lists of integers."""
  399. ver: int = self._version
  400. if ver == 1:
  401. return []
  402. else:
  403. numalign: int = ver // 7 + 2
  404. step: int = 26 if (ver == 32) else \
  405. (ver * 4 + numalign * 2 + 1) // (numalign * 2 - 2) * 2
  406. result: List[int] = [(self._size - 7 - i * step) for i in range(numalign - 1)] + [6]
  407. return list(reversed(result))
  408. @staticmethod
  409. def _get_num_raw_data_modules(ver: int) -> int:
  410. """Returns the number of data bits that can be stored in a QR Code of the given version number, after
  411. all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
  412. The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table."""
  413. if not (QrCode.MIN_VERSION <= ver <= QrCode.MAX_VERSION):
  414. raise ValueError("Version number out of range")
  415. result: int = (16 * ver + 128) * ver + 64
  416. if ver >= 2:
  417. numalign: int = ver // 7 + 2
  418. result -= (25 * numalign - 10) * numalign - 55
  419. if ver >= 7:
  420. result -= 36
  421. assert 208 <= result <= 29648
  422. return result
  423. @staticmethod
  424. def _get_num_data_codewords(ver: int, ecl: QrCode.Ecc) -> int:
  425. """Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
  426. QR Code of the given version number and error correction level, with remainder bits discarded.
  427. This stateless pure function could be implemented as a (40*4)-cell lookup table."""
  428. return QrCode._get_num_raw_data_modules(ver) // 8 \
  429. - QrCode._ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver] \
  430. * QrCode._NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]
  431. @staticmethod
  432. def _reed_solomon_compute_divisor(degree: int) -> bytes:
  433. """Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
  434. implemented as a lookup table over all possible parameter values, instead of as an algorithm."""
  435. if not (1 <= degree <= 255):
  436. raise ValueError("Degree out of range")
  437. # Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
  438. # For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
  439. result = bytearray([0] * (degree - 1) + [1]) # Start off with the monomial x^0
  440. # Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
  441. # and drop the highest monomial term which is always 1x^degree.
  442. # Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
  443. root: int = 1
  444. for _ in range(degree): # Unused variable i
  445. # Multiply the current product by (x - r^i)
  446. for j in range(degree):
  447. result[j] = QrCode._reed_solomon_multiply(result[j], root)
  448. if j + 1 < degree:
  449. result[j] ^= result[j + 1]
  450. root = QrCode._reed_solomon_multiply(root, 0x02)
  451. return result
  452. @staticmethod
  453. def _reed_solomon_compute_remainder(data: bytes, divisor: bytes) -> bytes:
  454. """Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials."""
  455. result = bytearray([0] * len(divisor))
  456. for b in data: # Polynomial division
  457. factor: int = b ^ result.pop(0)
  458. result.append(0)
  459. for (i, coef) in enumerate(divisor):
  460. result[i] ^= QrCode._reed_solomon_multiply(coef, factor)
  461. return result
  462. @staticmethod
  463. def _reed_solomon_multiply(x: int, y: int) -> int:
  464. """Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
  465. are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8."""
  466. if (x >> 8 != 0) or (y >> 8 != 0):
  467. raise ValueError("Byte out of range")
  468. # Russian peasant multiplication
  469. z: int = 0
  470. for i in reversed(range(8)):
  471. z = (z << 1) ^ ((z >> 7) * 0x11D)
  472. z ^= ((y >> i) & 1) * x
  473. assert z >> 8 == 0
  474. return z
  475. def _finder_penalty_count_patterns(self, runhistory: collections.deque) -> int:
  476. """Can only be called immediately after a light run is added, and
  477. returns either 0, 1, or 2. A helper function for _get_penalty_score()."""
  478. n: int = runhistory[1]
  479. assert n <= self._size * 3
  480. core: bool = n > 0 and (runhistory[2] == runhistory[4] == runhistory[5] == n) and runhistory[3] == n * 3
  481. return (1 if (core and runhistory[0] >= n * 4 and runhistory[6] >= n) else 0) \
  482. + (1 if (core and runhistory[6] >= n * 4 and runhistory[0] >= n) else 0)
  483. def _finder_penalty_terminate_and_count(self, currentruncolor: bool, currentrunlength: int, runhistory: collections.deque) -> int:
  484. """Must be called at the end of a line (row or column) of modules. A helper function for _get_penalty_score()."""
  485. if currentruncolor: # Terminate dark run
  486. self._finder_penalty_add_history(currentrunlength, runhistory)
  487. currentrunlength = 0
  488. currentrunlength += self._size # Add light border to final run
  489. self._finder_penalty_add_history(currentrunlength, runhistory)
  490. return self._finder_penalty_count_patterns(runhistory)
  491. def _finder_penalty_add_history(self, currentrunlength: int, runhistory: collections.deque) -> None:
  492. if runhistory[0] == 0:
  493. currentrunlength += self._size # Add light border to initial run
  494. runhistory.appendleft(currentrunlength)
  495. # ---- Constants and tables ----
  496. MIN_VERSION: int = 1 # The minimum version number supported in the QR Code Model 2 standard
  497. MAX_VERSION: int = 40 # The maximum version number supported in the QR Code Model 2 standard
  498. # For use in _get_penalty_score(), when evaluating which mask is best.
  499. _PENALTY_N1: int = 3
  500. _PENALTY_N2: int = 3
  501. _PENALTY_N3: int = 40
  502. _PENALTY_N4: int = 10
  503. _ECC_CODEWORDS_PER_BLOCK: Sequence[Sequence[int]] = (
  504. # Version: (note that index 0 is for padding, and is set to an illegal value)
  505. # 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
  506. (-1, 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
  507. (-1, 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
  508. (-1, 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
  509. (-1, 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
  510. _NUM_ERROR_CORRECTION_BLOCKS: Sequence[Sequence[int]] = (
  511. # Version: (note that index 0 is for padding, and is set to an illegal value)
  512. # 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
  513. (-1, 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
  514. (-1, 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
  515. (-1, 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
  516. (-1, 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
  517. _MASK_PATTERNS: Sequence[Callable[[int,int],int]] = (
  518. (lambda x, y: (x + y) % 2 ),
  519. (lambda x, y: y % 2 ),
  520. (lambda x, y: x % 3 ),
  521. (lambda x, y: (x + y) % 3 ),
  522. (lambda x, y: (x // 3 + y // 2) % 2 ),
  523. (lambda x, y: x * y % 2 + x * y % 3 ),
  524. (lambda x, y: (x * y % 2 + x * y % 3) % 2 ),
  525. (lambda x, y: ((x + y) % 2 + x * y % 3) % 2),
  526. )
  527. # ---- Public helper enumeration ----
  528. class Ecc:
  529. ordinal: int # (Public) In the range 0 to 3 (unsigned 2-bit integer)
  530. formatbits: int # (Package-private) In the range 0 to 3 (unsigned 2-bit integer)
  531. """The error correction level in a QR Code symbol. Immutable."""
  532. # Private constructor
  533. def __init__(self, i: int, fb: int) -> None:
  534. self.ordinal = i
  535. self.formatbits = fb
  536. # Placeholders
  537. LOW : QrCode.Ecc
  538. MEDIUM : QrCode.Ecc
  539. QUARTILE: QrCode.Ecc
  540. HIGH : QrCode.Ecc
  541. # Public constants. Create them outside the class.
  542. Ecc.LOW = Ecc(0, 1) # The QR Code can tolerate about 7% erroneous codewords
  543. Ecc.MEDIUM = Ecc(1, 0) # The QR Code can tolerate about 15% erroneous codewords
  544. Ecc.QUARTILE = Ecc(2, 3) # The QR Code can tolerate about 25% erroneous codewords
  545. Ecc.HIGH = Ecc(3, 2) # The QR Code can tolerate about 30% erroneous codewords
  546. # ---- Data segment class ----
  547. class QrSegment:
  548. """A segment of character/binary/control data in a QR Code symbol.
  549. Instances of this class are immutable.
  550. The mid-level way to create a segment is to take the payload data
  551. and call a static factory function such as QrSegment.make_numeric().
  552. The low-level way to create a segment is to custom-make the bit buffer
  553. and call the QrSegment() constructor with appropriate values.
  554. This segment class imposes no length restrictions, but QR Codes have restrictions.
  555. Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
  556. Any segment longer than this is meaningless for the purpose of generating QR Codes."""
  557. # ---- Static factory functions (mid level) ----
  558. @staticmethod
  559. def make_bytes(data: Union[bytes,Sequence[int]]) -> QrSegment:
  560. """Returns a segment representing the given binary data encoded in byte mode.
  561. All input byte lists are acceptable. Any text string can be converted to
  562. UTF-8 bytes (s.encode("UTF-8")) and encoded as a byte mode segment."""
  563. bb = _BitBuffer()
  564. for b in data:
  565. bb.append_bits(b, 8)
  566. return QrSegment(QrSegment.Mode.BYTE, len(data), bb)
  567. @staticmethod
  568. def make_numeric(digits: str) -> QrSegment:
  569. """Returns a segment representing the given string of decimal digits encoded in numeric mode."""
  570. if not QrSegment.is_numeric(digits):
  571. raise ValueError("String contains non-numeric characters")
  572. bb = _BitBuffer()
  573. i: int = 0
  574. while i < len(digits): # Consume up to 3 digits per iteration
  575. n: int = min(len(digits) - i, 3)
  576. bb.append_bits(int(digits[i : i + n]), n * 3 + 1)
  577. i += n
  578. return QrSegment(QrSegment.Mode.NUMERIC, len(digits), bb)
  579. @staticmethod
  580. def make_alphanumeric(text: str) -> QrSegment:
  581. """Returns a segment representing the given text string encoded in alphanumeric mode.
  582. The characters allowed are: 0 to 9, A to Z (uppercase only), space,
  583. dollar, percent, asterisk, plus, hyphen, period, slash, colon."""
  584. if not QrSegment.is_alphanumeric(text):
  585. raise ValueError("String contains unencodable characters in alphanumeric mode")
  586. bb = _BitBuffer()
  587. for i in range(0, len(text) - 1, 2): # Process groups of 2
  588. temp: int = QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[i]] * 45
  589. temp += QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[i + 1]]
  590. bb.append_bits(temp, 11)
  591. if len(text) % 2 > 0: # 1 character remaining
  592. bb.append_bits(QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[-1]], 6)
  593. return QrSegment(QrSegment.Mode.ALPHANUMERIC, len(text), bb)
  594. @staticmethod
  595. def make_segments(text: str) -> List[QrSegment]:
  596. """Returns a new mutable list of zero or more segments to represent the given Unicode text string.
  597. The result may use various segment modes and switch modes to optimize the length of the bit stream."""
  598. # Select the most efficient segment encoding automatically
  599. if text == "":
  600. return []
  601. elif QrSegment.is_numeric(text):
  602. return [QrSegment.make_numeric(text)]
  603. elif QrSegment.is_alphanumeric(text):
  604. return [QrSegment.make_alphanumeric(text)]
  605. else:
  606. return [QrSegment.make_bytes(text.encode("UTF-8"))]
  607. @staticmethod
  608. def make_eci(assignval: int) -> QrSegment:
  609. """Returns a segment representing an Extended Channel Interpretation
  610. (ECI) designator with the given assignment value."""
  611. bb = _BitBuffer()
  612. if assignval < 0:
  613. raise ValueError("ECI assignment value out of range")
  614. elif assignval < (1 << 7):
  615. bb.append_bits(assignval, 8)
  616. elif assignval < (1 << 14):
  617. bb.append_bits(0b10, 2)
  618. bb.append_bits(assignval, 14)
  619. elif assignval < 1000000:
  620. bb.append_bits(0b110, 3)
  621. bb.append_bits(assignval, 21)
  622. else:
  623. raise ValueError("ECI assignment value out of range")
  624. return QrSegment(QrSegment.Mode.ECI, 0, bb)
  625. # Tests whether the given string can be encoded as a segment in numeric mode.
  626. # A string is encodable iff each character is in the range 0 to 9.
  627. @staticmethod
  628. def is_numeric(text: str) -> bool:
  629. return QrSegment._NUMERIC_REGEX.fullmatch(text) is not None
  630. # Tests whether the given string can be encoded as a segment in alphanumeric mode.
  631. # A string is encodable iff each character is in the following set: 0 to 9, A to Z
  632. # (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
  633. @staticmethod
  634. def is_alphanumeric(text: str) -> bool:
  635. return QrSegment._ALPHANUMERIC_REGEX.fullmatch(text) is not None
  636. # ---- Private fields ----
  637. # The mode indicator of this segment. Accessed through get_mode().
  638. _mode: QrSegment.Mode
  639. # The length of this segment's unencoded data. Measured in characters for
  640. # numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
  641. # Always zero or positive. Not the same as the data's bit length.
  642. # Accessed through get_num_chars().
  643. _numchars: int
  644. # The data bits of this segment. Accessed through get_data().
  645. _bitdata: List[int]
  646. # ---- Constructor (low level) ----
  647. def __init__(self, mode: QrSegment.Mode, numch: int, bitdata: Sequence[int]) -> None:
  648. """Creates a new QR Code segment with the given attributes and data.
  649. The character count (numch) must agree with the mode and the bit buffer length,
  650. but the constraint isn't checked. The given bit buffer is cloned and stored."""
  651. if numch < 0:
  652. raise ValueError()
  653. self._mode = mode
  654. self._numchars = numch
  655. self._bitdata = list(bitdata) # Make defensive copy
  656. # ---- Accessor methods ----
  657. def get_mode(self) -> QrSegment.Mode:
  658. """Returns the mode field of this segment."""
  659. return self._mode
  660. def get_num_chars(self) -> int:
  661. """Returns the character count field of this segment."""
  662. return self._numchars
  663. def get_data(self) -> List[int]:
  664. """Returns a new copy of the data bits of this segment."""
  665. return list(self._bitdata) # Make defensive copy
  666. # Package-private function
  667. @staticmethod
  668. def get_total_bits(segs: Sequence[QrSegment], version: int) -> Optional[int]:
  669. """Calculates the number of bits needed to encode the given segments at
  670. the given version. Returns a non-negative number if successful. Otherwise
  671. returns None if a segment has too many characters to fit its length field."""
  672. result = 0
  673. for seg in segs:
  674. ccbits: int = seg.get_mode().num_char_count_bits(version)
  675. if seg.get_num_chars() >= (1 << ccbits):
  676. return None # The segment's length doesn't fit the field's bit width
  677. result += 4 + ccbits + len(seg._bitdata)
  678. return result
  679. # ---- Constants ----
  680. # Describes precisely all strings that are encodable in numeric mode.
  681. _NUMERIC_REGEX: re.Pattern = re.compile(r"[0-9]*")
  682. # Describes precisely all strings that are encodable in alphanumeric mode.
  683. _ALPHANUMERIC_REGEX: re.Pattern = re.compile(r"[A-Z0-9 $%*+./:-]*")
  684. # Dictionary of "0"->0, "A"->10, "$"->37, etc.
  685. _ALPHANUMERIC_ENCODING_TABLE: Dict[str,int] = {ch: i for (i, ch) in enumerate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:")}
  686. # ---- Public helper enumeration ----
  687. class Mode:
  688. """Describes how a segment's data bits are interpreted. Immutable."""
  689. _modebits: int # The mode indicator bits, which is a uint4 value (range 0 to 15)
  690. _charcounts: Tuple[int,int,int] # Number of character count bits for three different version ranges
  691. # Private constructor
  692. def __init__(self, modebits: int, charcounts: Tuple[int,int,int]):
  693. self._modebits = modebits
  694. self._charcounts = charcounts
  695. # Package-private method
  696. def get_mode_bits(self) -> int:
  697. """Returns an unsigned 4-bit integer value (range 0 to 15) representing the mode indicator bits for this mode object."""
  698. return self._modebits
  699. # Package-private method
  700. def num_char_count_bits(self, ver: int) -> int:
  701. """Returns the bit width of the character count field for a segment in this mode
  702. in a QR Code at the given version number. The result is in the range [0, 16]."""
  703. return self._charcounts[(ver + 7) // 17]
  704. # Placeholders
  705. NUMERIC : QrSegment.Mode
  706. ALPHANUMERIC: QrSegment.Mode
  707. BYTE : QrSegment.Mode
  708. KANJI : QrSegment.Mode
  709. ECI : QrSegment.Mode
  710. # Public constants. Create them outside the class.
  711. Mode.NUMERIC = Mode(0x1, (10, 12, 14))
  712. Mode.ALPHANUMERIC = Mode(0x2, ( 9, 11, 13))
  713. Mode.BYTE = Mode(0x4, ( 8, 16, 16))
  714. Mode.KANJI = Mode(0x8, ( 8, 10, 12))
  715. Mode.ECI = Mode(0x7, ( 0, 0, 0))
  716. # ---- Private helper class ----
  717. class _BitBuffer(list):
  718. """An appendable sequence of bits (0s and 1s). Mainly used by QrSegment."""
  719. def append_bits(self, val: int, n: int) -> None:
  720. """Appends the given number of low-order bits of the given
  721. value to this buffer. Requires n >= 0 and 0 <= val < 2^n."""
  722. if (n < 0) or (val >> n != 0):
  723. raise ValueError("Value out of range")
  724. self.extend(((val >> i) & 1) for i in reversed(range(n)))
  725. def _get_bit(x: int, i: int) -> bool:
  726. """Returns true iff the i'th bit of x is set to 1."""
  727. return (x >> i) & 1 != 0
  728. class DataTooLongError(ValueError):
  729. """Raised when the supplied data does not fit any QR Code version. Ways to handle this exception include:
  730. - Decrease the error correction level if it was greater than Ecc.LOW.
  731. - If the encode_segments() function was called with a maxversion argument, then increase
  732. it if it was less than QrCode.MAX_VERSION. (This advice does not apply to the other
  733. factory functions because they search all versions up to QrCode.MAX_VERSION.)
  734. - Split the text data into better or optimal segments in order to reduce the number of bits required.
  735. - Change the text or binary data to be shorter.
  736. - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric).
  737. - Propagate the error upward to the caller/user."""
  738. pass