qr.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. # https://raw.githubusercontent.com/lincolnloop/python-qrcode/b80fea6ee7e75f3024b9ed7adf891a143e0b14e3/qrcode/main.py
  2. # The code was copied in such weird way since the original project requires Pillow
  3. import math
  4. import re
  5. import sys
  6. from bisect import bisect_left
  7. from typing import Dict, List, NamedTuple, Optional, cast
  8. ERROR_CORRECT_L = 1
  9. ERROR_CORRECT_M = 0
  10. ERROR_CORRECT_Q = 3
  11. ERROR_CORRECT_H = 2
  12. EXP_TABLE = list(range(256))
  13. LOG_TABLE = list(range(256))
  14. for i in range(8):
  15. EXP_TABLE[i] = 1 << i
  16. for i in range(8, 256):
  17. EXP_TABLE[i] = (
  18. EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8]
  19. )
  20. for i in range(255):
  21. LOG_TABLE[EXP_TABLE[i]] = i
  22. def rs_blocks(version, error_correction):
  23. if error_correction not in RS_BLOCK_OFFSET: # pragma: no cover
  24. raise Exception(
  25. "bad rs block @ version: %s / error_correction: %s"
  26. % (version, error_correction)
  27. )
  28. offset = RS_BLOCK_OFFSET[error_correction]
  29. rs_block = RS_BLOCK_TABLE[(version - 1) * 4 + offset]
  30. blocks = []
  31. for i in range(0, len(rs_block), 3):
  32. count, total_count, data_count = rs_block[i : i + 3]
  33. for _ in range(count):
  34. blocks.append(RSBlock(total_count, data_count))
  35. return blocks
  36. RS_BLOCK_OFFSET = {
  37. ERROR_CORRECT_L: 0,
  38. ERROR_CORRECT_M: 1,
  39. ERROR_CORRECT_Q: 2,
  40. ERROR_CORRECT_H: 3,
  41. }
  42. RS_BLOCK_TABLE = (
  43. # L
  44. # M
  45. # Q
  46. # H
  47. # 1
  48. (1, 26, 19),
  49. (1, 26, 16),
  50. (1, 26, 13),
  51. (1, 26, 9),
  52. # 2
  53. (1, 44, 34),
  54. (1, 44, 28),
  55. (1, 44, 22),
  56. (1, 44, 16),
  57. # 3
  58. (1, 70, 55),
  59. (1, 70, 44),
  60. (2, 35, 17),
  61. (2, 35, 13),
  62. # 4
  63. (1, 100, 80),
  64. (2, 50, 32),
  65. (2, 50, 24),
  66. (4, 25, 9),
  67. # 5
  68. (1, 134, 108),
  69. (2, 67, 43),
  70. (2, 33, 15, 2, 34, 16),
  71. (2, 33, 11, 2, 34, 12),
  72. # 6
  73. (2, 86, 68),
  74. (4, 43, 27),
  75. (4, 43, 19),
  76. (4, 43, 15),
  77. # 7
  78. (2, 98, 78),
  79. (4, 49, 31),
  80. (2, 32, 14, 4, 33, 15),
  81. (4, 39, 13, 1, 40, 14),
  82. # 8
  83. (2, 121, 97),
  84. (2, 60, 38, 2, 61, 39),
  85. (4, 40, 18, 2, 41, 19),
  86. (4, 40, 14, 2, 41, 15),
  87. # 9
  88. (2, 146, 116),
  89. (3, 58, 36, 2, 59, 37),
  90. (4, 36, 16, 4, 37, 17),
  91. (4, 36, 12, 4, 37, 13),
  92. # 10
  93. (2, 86, 68, 2, 87, 69),
  94. (4, 69, 43, 1, 70, 44),
  95. (6, 43, 19, 2, 44, 20),
  96. (6, 43, 15, 2, 44, 16),
  97. # 11
  98. (4, 101, 81),
  99. (1, 80, 50, 4, 81, 51),
  100. (4, 50, 22, 4, 51, 23),
  101. (3, 36, 12, 8, 37, 13),
  102. # 12
  103. (2, 116, 92, 2, 117, 93),
  104. (6, 58, 36, 2, 59, 37),
  105. (4, 46, 20, 6, 47, 21),
  106. (7, 42, 14, 4, 43, 15),
  107. # 13
  108. (4, 133, 107),
  109. (8, 59, 37, 1, 60, 38),
  110. (8, 44, 20, 4, 45, 21),
  111. (12, 33, 11, 4, 34, 12),
  112. # 14
  113. (3, 145, 115, 1, 146, 116),
  114. (4, 64, 40, 5, 65, 41),
  115. (11, 36, 16, 5, 37, 17),
  116. (11, 36, 12, 5, 37, 13),
  117. # 15
  118. (5, 109, 87, 1, 110, 88),
  119. (5, 65, 41, 5, 66, 42),
  120. (5, 54, 24, 7, 55, 25),
  121. (11, 36, 12, 7, 37, 13),
  122. # 16
  123. (5, 122, 98, 1, 123, 99),
  124. (7, 73, 45, 3, 74, 46),
  125. (15, 43, 19, 2, 44, 20),
  126. (3, 45, 15, 13, 46, 16),
  127. # 17
  128. (1, 135, 107, 5, 136, 108),
  129. (10, 74, 46, 1, 75, 47),
  130. (1, 50, 22, 15, 51, 23),
  131. (2, 42, 14, 17, 43, 15),
  132. # 18
  133. (5, 150, 120, 1, 151, 121),
  134. (9, 69, 43, 4, 70, 44),
  135. (17, 50, 22, 1, 51, 23),
  136. (2, 42, 14, 19, 43, 15),
  137. # 19
  138. (3, 141, 113, 4, 142, 114),
  139. (3, 70, 44, 11, 71, 45),
  140. (17, 47, 21, 4, 48, 22),
  141. (9, 39, 13, 16, 40, 14),
  142. # 20
  143. (3, 135, 107, 5, 136, 108),
  144. (3, 67, 41, 13, 68, 42),
  145. (15, 54, 24, 5, 55, 25),
  146. (15, 43, 15, 10, 44, 16),
  147. # 21
  148. (4, 144, 116, 4, 145, 117),
  149. (17, 68, 42),
  150. (17, 50, 22, 6, 51, 23),
  151. (19, 46, 16, 6, 47, 17),
  152. # 22
  153. (2, 139, 111, 7, 140, 112),
  154. (17, 74, 46),
  155. (7, 54, 24, 16, 55, 25),
  156. (34, 37, 13),
  157. # 23
  158. (4, 151, 121, 5, 152, 122),
  159. (4, 75, 47, 14, 76, 48),
  160. (11, 54, 24, 14, 55, 25),
  161. (16, 45, 15, 14, 46, 16),
  162. # 24
  163. (6, 147, 117, 4, 148, 118),
  164. (6, 73, 45, 14, 74, 46),
  165. (11, 54, 24, 16, 55, 25),
  166. (30, 46, 16, 2, 47, 17),
  167. # 25
  168. (8, 132, 106, 4, 133, 107),
  169. (8, 75, 47, 13, 76, 48),
  170. (7, 54, 24, 22, 55, 25),
  171. (22, 45, 15, 13, 46, 16),
  172. # 26
  173. (10, 142, 114, 2, 143, 115),
  174. (19, 74, 46, 4, 75, 47),
  175. (28, 50, 22, 6, 51, 23),
  176. (33, 46, 16, 4, 47, 17),
  177. # 27
  178. (8, 152, 122, 4, 153, 123),
  179. (22, 73, 45, 3, 74, 46),
  180. (8, 53, 23, 26, 54, 24),
  181. (12, 45, 15, 28, 46, 16),
  182. # 28
  183. (3, 147, 117, 10, 148, 118),
  184. (3, 73, 45, 23, 74, 46),
  185. (4, 54, 24, 31, 55, 25),
  186. (11, 45, 15, 31, 46, 16),
  187. # 29
  188. (7, 146, 116, 7, 147, 117),
  189. (21, 73, 45, 7, 74, 46),
  190. (1, 53, 23, 37, 54, 24),
  191. (19, 45, 15, 26, 46, 16),
  192. # 30
  193. (5, 145, 115, 10, 146, 116),
  194. (19, 75, 47, 10, 76, 48),
  195. (15, 54, 24, 25, 55, 25),
  196. (23, 45, 15, 25, 46, 16),
  197. # 31
  198. (13, 145, 115, 3, 146, 116),
  199. (2, 74, 46, 29, 75, 47),
  200. (42, 54, 24, 1, 55, 25),
  201. (23, 45, 15, 28, 46, 16),
  202. # 32
  203. (17, 145, 115),
  204. (10, 74, 46, 23, 75, 47),
  205. (10, 54, 24, 35, 55, 25),
  206. (19, 45, 15, 35, 46, 16),
  207. # 33
  208. (17, 145, 115, 1, 146, 116),
  209. (14, 74, 46, 21, 75, 47),
  210. (29, 54, 24, 19, 55, 25),
  211. (11, 45, 15, 46, 46, 16),
  212. # 34
  213. (13, 145, 115, 6, 146, 116),
  214. (14, 74, 46, 23, 75, 47),
  215. (44, 54, 24, 7, 55, 25),
  216. (59, 46, 16, 1, 47, 17),
  217. # 35
  218. (12, 151, 121, 7, 152, 122),
  219. (12, 75, 47, 26, 76, 48),
  220. (39, 54, 24, 14, 55, 25),
  221. (22, 45, 15, 41, 46, 16),
  222. # 36
  223. (6, 151, 121, 14, 152, 122),
  224. (6, 75, 47, 34, 76, 48),
  225. (46, 54, 24, 10, 55, 25),
  226. (2, 45, 15, 64, 46, 16),
  227. # 37
  228. (17, 152, 122, 4, 153, 123),
  229. (29, 74, 46, 14, 75, 47),
  230. (49, 54, 24, 10, 55, 25),
  231. (24, 45, 15, 46, 46, 16),
  232. # 38
  233. (4, 152, 122, 18, 153, 123),
  234. (13, 74, 46, 32, 75, 47),
  235. (48, 54, 24, 14, 55, 25),
  236. (42, 45, 15, 32, 46, 16),
  237. # 39
  238. (20, 147, 117, 4, 148, 118),
  239. (40, 75, 47, 7, 76, 48),
  240. (43, 54, 24, 22, 55, 25),
  241. (10, 45, 15, 67, 46, 16),
  242. # 40
  243. (19, 148, 118, 6, 149, 119),
  244. (18, 75, 47, 31, 76, 48),
  245. (34, 54, 24, 34, 55, 25),
  246. (20, 45, 15, 61, 46, 16),
  247. )
  248. def glog(n):
  249. if n < 1: # pragma: no cover
  250. raise ValueError(f"glog({n})")
  251. return LOG_TABLE[n]
  252. def gexp(n):
  253. return EXP_TABLE[n % 255]
  254. class Polynomial:
  255. def __init__(self, num, shift):
  256. if not num: # pragma: no cover
  257. raise Exception(f"{len(num)}/{shift}")
  258. offset = 0
  259. for offset in range(len(num)):
  260. if num[offset] != 0:
  261. break
  262. self.num = num[offset:] + [0] * shift
  263. def __getitem__(self, index):
  264. return self.num[index]
  265. def __iter__(self):
  266. return iter(self.num)
  267. def __len__(self):
  268. return len(self.num)
  269. def __mul__(self, other):
  270. num = [0] * (len(self) + len(other) - 1)
  271. for i, item in enumerate(self):
  272. for j, other_item in enumerate(other):
  273. num[i + j] ^= gexp(glog(item) + glog(other_item))
  274. return Polynomial(num, 0)
  275. def __mod__(self, other):
  276. difference = len(self) - len(other)
  277. if difference < 0:
  278. return self
  279. ratio = glog(self[0]) - glog(other[0])
  280. num = [
  281. item ^ gexp(glog(other_item) + ratio)
  282. for item, other_item in zip(self, other)
  283. ]
  284. if difference:
  285. num.extend(self[-difference:])
  286. # recursive call
  287. return Polynomial(num, 0) % other
  288. class RSBlock(NamedTuple):
  289. total_count: int
  290. data_count: int
  291. rsPoly_LUT = {
  292. 7: [1, 127, 122, 154, 164, 11, 68, 117],
  293. 10: [1, 216, 194, 159, 111, 199, 94, 95, 113, 157, 193],
  294. 13: [1, 137, 73, 227, 17, 177, 17, 52, 13, 46, 43, 83, 132, 120],
  295. 15: [1, 29, 196, 111, 163, 112, 74, 10, 105, 105, 139, 132, 151, 32, 134, 26],
  296. 16: [1, 59, 13, 104, 189, 68, 209, 30, 8, 163, 65, 41, 229, 98, 50, 36, 59],
  297. 17: [1, 119, 66, 83, 120, 119, 22, 197, 83, 249, 41, 143, 134, 85, 53, 125, 99, 79],
  298. 18: [
  299. 1,
  300. 239,
  301. 251,
  302. 183,
  303. 113,
  304. 149,
  305. 175,
  306. 199,
  307. 215,
  308. 240,
  309. 220,
  310. 73,
  311. 82,
  312. 173,
  313. 75,
  314. 32,
  315. 67,
  316. 217,
  317. 146,
  318. ],
  319. 20: [
  320. 1,
  321. 152,
  322. 185,
  323. 240,
  324. 5,
  325. 111,
  326. 99,
  327. 6,
  328. 220,
  329. 112,
  330. 150,
  331. 69,
  332. 36,
  333. 187,
  334. 22,
  335. 228,
  336. 198,
  337. 121,
  338. 121,
  339. 165,
  340. 174,
  341. ],
  342. 22: [
  343. 1,
  344. 89,
  345. 179,
  346. 131,
  347. 176,
  348. 182,
  349. 244,
  350. 19,
  351. 189,
  352. 69,
  353. 40,
  354. 28,
  355. 137,
  356. 29,
  357. 123,
  358. 67,
  359. 253,
  360. 86,
  361. 218,
  362. 230,
  363. 26,
  364. 145,
  365. 245,
  366. ],
  367. 24: [
  368. 1,
  369. 122,
  370. 118,
  371. 169,
  372. 70,
  373. 178,
  374. 237,
  375. 216,
  376. 102,
  377. 115,
  378. 150,
  379. 229,
  380. 73,
  381. 130,
  382. 72,
  383. 61,
  384. 43,
  385. 206,
  386. 1,
  387. 237,
  388. 247,
  389. 127,
  390. 217,
  391. 144,
  392. 117,
  393. ],
  394. 26: [
  395. 1,
  396. 246,
  397. 51,
  398. 183,
  399. 4,
  400. 136,
  401. 98,
  402. 199,
  403. 152,
  404. 77,
  405. 56,
  406. 206,
  407. 24,
  408. 145,
  409. 40,
  410. 209,
  411. 117,
  412. 233,
  413. 42,
  414. 135,
  415. 68,
  416. 70,
  417. 144,
  418. 146,
  419. 77,
  420. 43,
  421. 94,
  422. ],
  423. 28: [
  424. 1,
  425. 252,
  426. 9,
  427. 28,
  428. 13,
  429. 18,
  430. 251,
  431. 208,
  432. 150,
  433. 103,
  434. 174,
  435. 100,
  436. 41,
  437. 167,
  438. 12,
  439. 247,
  440. 56,
  441. 117,
  442. 119,
  443. 233,
  444. 127,
  445. 181,
  446. 100,
  447. 121,
  448. 147,
  449. 176,
  450. 74,
  451. 58,
  452. 197,
  453. ],
  454. 30: [
  455. 1,
  456. 212,
  457. 246,
  458. 77,
  459. 73,
  460. 195,
  461. 192,
  462. 75,
  463. 98,
  464. 5,
  465. 70,
  466. 103,
  467. 177,
  468. 22,
  469. 217,
  470. 138,
  471. 51,
  472. 181,
  473. 246,
  474. 72,
  475. 25,
  476. 18,
  477. 46,
  478. 228,
  479. 74,
  480. 216,
  481. 195,
  482. 11,
  483. 106,
  484. 130,
  485. 150,
  486. ],
  487. }
  488. # QR encoding modes.
  489. MODE_NUMBER = 1 << 0
  490. MODE_ALPHA_NUM = 1 << 1
  491. MODE_8BIT_BYTE = 1 << 2
  492. MODE_KANJI = 1 << 3
  493. # Encoding mode sizes.
  494. MODE_SIZE_SMALL = {
  495. MODE_NUMBER: 10,
  496. MODE_ALPHA_NUM: 9,
  497. MODE_8BIT_BYTE: 8,
  498. MODE_KANJI: 8,
  499. }
  500. MODE_SIZE_MEDIUM = {
  501. MODE_NUMBER: 12,
  502. MODE_ALPHA_NUM: 11,
  503. MODE_8BIT_BYTE: 16,
  504. MODE_KANJI: 10,
  505. }
  506. MODE_SIZE_LARGE = {
  507. MODE_NUMBER: 14,
  508. MODE_ALPHA_NUM: 13,
  509. MODE_8BIT_BYTE: 16,
  510. MODE_KANJI: 12,
  511. }
  512. ALPHA_NUM = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
  513. RE_ALPHA_NUM = re.compile(b"^[" + re.escape(ALPHA_NUM) + rb"]*\Z")
  514. # The number of bits for numeric delimited data lengths.
  515. NUMBER_LENGTH = {3: 10, 2: 7, 1: 4}
  516. PATTERN_POSITION_TABLE = [
  517. [],
  518. [6, 18],
  519. [6, 22],
  520. [6, 26],
  521. [6, 30],
  522. [6, 34],
  523. [6, 22, 38],
  524. [6, 24, 42],
  525. [6, 26, 46],
  526. [6, 28, 50],
  527. [6, 30, 54],
  528. [6, 32, 58],
  529. [6, 34, 62],
  530. [6, 26, 46, 66],
  531. [6, 26, 48, 70],
  532. [6, 26, 50, 74],
  533. [6, 30, 54, 78],
  534. [6, 30, 56, 82],
  535. [6, 30, 58, 86],
  536. [6, 34, 62, 90],
  537. [6, 28, 50, 72, 94],
  538. [6, 26, 50, 74, 98],
  539. [6, 30, 54, 78, 102],
  540. [6, 28, 54, 80, 106],
  541. [6, 32, 58, 84, 110],
  542. [6, 30, 58, 86, 114],
  543. [6, 34, 62, 90, 118],
  544. [6, 26, 50, 74, 98, 122],
  545. [6, 30, 54, 78, 102, 126],
  546. [6, 26, 52, 78, 104, 130],
  547. [6, 30, 56, 82, 108, 134],
  548. [6, 34, 60, 86, 112, 138],
  549. [6, 30, 58, 86, 114, 142],
  550. [6, 34, 62, 90, 118, 146],
  551. [6, 30, 54, 78, 102, 126, 150],
  552. [6, 24, 50, 76, 102, 128, 154],
  553. [6, 28, 54, 80, 106, 132, 158],
  554. [6, 32, 58, 84, 110, 136, 162],
  555. [6, 26, 54, 82, 110, 138, 166],
  556. [6, 30, 58, 86, 114, 142, 170],
  557. ]
  558. G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)
  559. G18 = (
  560. (1 << 12)
  561. | (1 << 11)
  562. | (1 << 10)
  563. | (1 << 9)
  564. | (1 << 8)
  565. | (1 << 5)
  566. | (1 << 2)
  567. | (1 << 0)
  568. )
  569. G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1)
  570. PAD0 = 0xEC
  571. PAD1 = 0x11
  572. # Precompute bit count limits, indexed by error correction level and code size
  573. def _data_count(block):
  574. return block.data_count
  575. BIT_LIMIT_TABLE = [
  576. [0]
  577. + [
  578. 8 * sum(map(_data_count, rs_blocks(version, error_correction)))
  579. for version in range(1, 41)
  580. ]
  581. for error_correction in range(4)
  582. ]
  583. def BCH_type_info(data):
  584. d = data << 10
  585. while BCH_digit(d) - BCH_digit(G15) >= 0:
  586. d ^= G15 << (BCH_digit(d) - BCH_digit(G15))
  587. return ((data << 10) | d) ^ G15_MASK
  588. def BCH_type_number(data):
  589. d = data << 12
  590. while BCH_digit(d) - BCH_digit(G18) >= 0:
  591. d ^= G18 << (BCH_digit(d) - BCH_digit(G18))
  592. return (data << 12) | d
  593. def BCH_digit(data):
  594. digit = 0
  595. while data != 0:
  596. digit += 1
  597. data >>= 1
  598. return digit
  599. def pattern_position(version):
  600. return PATTERN_POSITION_TABLE[version - 1]
  601. def mask_func(pattern):
  602. """
  603. Return the mask function for the given mask pattern.
  604. """
  605. if pattern == 0: # 000
  606. return lambda i, j: (i + j) % 2 == 0
  607. if pattern == 1: # 001
  608. return lambda i, j: i % 2 == 0
  609. if pattern == 2: # 010
  610. return lambda i, j: j % 3 == 0
  611. if pattern == 3: # 011
  612. return lambda i, j: (i + j) % 3 == 0
  613. if pattern == 4: # 100
  614. return lambda i, j: (math.floor(i / 2) + math.floor(j / 3)) % 2 == 0
  615. if pattern == 5: # 101
  616. return lambda i, j: (i * j) % 2 + (i * j) % 3 == 0
  617. if pattern == 6: # 110
  618. return lambda i, j: ((i * j) % 2 + (i * j) % 3) % 2 == 0
  619. if pattern == 7: # 111
  620. return lambda i, j: ((i * j) % 3 + (i + j) % 2) % 2 == 0
  621. raise TypeError("Bad mask pattern: " + pattern) # pragma: no cover
  622. def mode_sizes_for_version(version):
  623. if version < 10:
  624. return MODE_SIZE_SMALL
  625. elif version < 27:
  626. return MODE_SIZE_MEDIUM
  627. else:
  628. return MODE_SIZE_LARGE
  629. def length_in_bits(mode, version):
  630. if mode not in (MODE_NUMBER, MODE_ALPHA_NUM, MODE_8BIT_BYTE, MODE_KANJI):
  631. raise TypeError(f"Invalid mode ({mode})") # pragma: no cover
  632. check_version(version)
  633. return mode_sizes_for_version(version)[mode]
  634. def check_version(version):
  635. if version < 1 or version > 40:
  636. raise ValueError(f"Invalid version (was {version}, expected 1 to 40)")
  637. def lost_point(modules):
  638. modules_count = len(modules)
  639. lost_point_ = 0
  640. lost_point_ = _lost_point_level1(modules, modules_count)
  641. lost_point_ += _lost_point_level2(modules, modules_count)
  642. lost_point_ += _lost_point_level3(modules, modules_count)
  643. lost_point_ += _lost_point_level4(modules, modules_count)
  644. return lost_point_
  645. def _lost_point_level1(modules, modules_count):
  646. lost_point = 0
  647. modules_range = range(modules_count)
  648. container = [0] * (modules_count + 1)
  649. for row in modules_range:
  650. this_row = modules[row]
  651. previous_color = this_row[0]
  652. length = 0
  653. for col in modules_range:
  654. if this_row[col] == previous_color:
  655. length += 1
  656. else:
  657. if length >= 5:
  658. container[length] += 1
  659. length = 1
  660. previous_color = this_row[col]
  661. if length >= 5:
  662. container[length] += 1
  663. for col in modules_range:
  664. previous_color = modules[0][col]
  665. length = 0
  666. for row in modules_range:
  667. if modules[row][col] == previous_color:
  668. length += 1
  669. else:
  670. if length >= 5:
  671. container[length] += 1
  672. length = 1
  673. previous_color = modules[row][col]
  674. if length >= 5:
  675. container[length] += 1
  676. lost_point += sum(
  677. container[each_length] * (each_length - 2)
  678. for each_length in range(5, modules_count + 1)
  679. )
  680. return lost_point
  681. def _lost_point_level2(modules, modules_count):
  682. lost_point = 0
  683. modules_range = range(modules_count - 1)
  684. for row in modules_range:
  685. this_row = modules[row]
  686. next_row = modules[row + 1]
  687. # use iter() and next() to skip next four-block. e.g.
  688. # d a f if top-right a != b bottom-right,
  689. # c b e then both abcd and abef won't lost any point.
  690. modules_range_iter = iter(modules_range)
  691. for col in modules_range_iter:
  692. top_right = this_row[col + 1]
  693. if top_right != next_row[col + 1]:
  694. # reduce 33.3% of runtime via next().
  695. # None: raise nothing if there is no next item.
  696. next(modules_range_iter, None)
  697. elif top_right != this_row[col]:
  698. continue
  699. elif top_right != next_row[col]:
  700. continue
  701. else:
  702. lost_point += 3
  703. return lost_point
  704. def _lost_point_level3(modules, modules_count):
  705. # 1 : 1 : 3 : 1 : 1 ratio (dark:light:dark:light:dark) pattern in
  706. # row/column, preceded or followed by light area 4 modules wide. From ISOIEC.
  707. # pattern1: 10111010000
  708. # pattern2: 00001011101
  709. modules_range = range(modules_count)
  710. modules_range_short = range(modules_count - 10)
  711. lost_point = 0
  712. for row in modules_range:
  713. this_row = modules[row]
  714. modules_range_short_iter = iter(modules_range_short)
  715. col = 0
  716. for col in modules_range_short_iter:
  717. if (
  718. not this_row[col + 1]
  719. and this_row[col + 4]
  720. and not this_row[col + 5]
  721. and this_row[col + 6]
  722. and not this_row[col + 9]
  723. and (
  724. this_row[col + 0]
  725. and this_row[col + 2]
  726. and this_row[col + 3]
  727. and not this_row[col + 7]
  728. and not this_row[col + 8]
  729. and not this_row[col + 10]
  730. or not this_row[col + 0]
  731. and not this_row[col + 2]
  732. and not this_row[col + 3]
  733. and this_row[col + 7]
  734. and this_row[col + 8]
  735. and this_row[col + 10]
  736. )
  737. ):
  738. lost_point += 40
  739. # horspool algorithm.
  740. # if this_row[col + 10]:
  741. # pattern1 shift 4, pattern2 shift 2. So min=2.
  742. # else:
  743. # pattern1 shift 1, pattern2 shift 1. So min=1.
  744. if this_row[col + 10]:
  745. next(modules_range_short_iter, None)
  746. for col in modules_range:
  747. modules_range_short_iter = iter(modules_range_short)
  748. row = 0
  749. for row in modules_range_short_iter:
  750. if (
  751. not modules[row + 1][col]
  752. and modules[row + 4][col]
  753. and not modules[row + 5][col]
  754. and modules[row + 6][col]
  755. and not modules[row + 9][col]
  756. and (
  757. modules[row + 0][col]
  758. and modules[row + 2][col]
  759. and modules[row + 3][col]
  760. and not modules[row + 7][col]
  761. and not modules[row + 8][col]
  762. and not modules[row + 10][col]
  763. or not modules[row + 0][col]
  764. and not modules[row + 2][col]
  765. and not modules[row + 3][col]
  766. and modules[row + 7][col]
  767. and modules[row + 8][col]
  768. and modules[row + 10][col]
  769. )
  770. ):
  771. lost_point += 40
  772. if modules[row + 10][col]:
  773. next(modules_range_short_iter, None)
  774. return lost_point
  775. def _lost_point_level4(modules, modules_count):
  776. dark_count = sum(map(sum, modules))
  777. percent = float(dark_count) / (modules_count**2)
  778. # Every 5% departure from 50%, rating++
  779. rating = int(abs(percent * 100 - 50) / 5)
  780. return rating * 10
  781. def optimal_data_chunks(data, minimum=4):
  782. """
  783. An iterator returning QRData chunks optimized to the data content.
  784. :param minimum: The minimum number of bytes in a row to split as a chunk.
  785. """
  786. data = to_bytestring(data)
  787. num_pattern = rb"\d"
  788. alpha_pattern = b"[" + re.escape(ALPHA_NUM) + b"]"
  789. if len(data) <= minimum:
  790. num_pattern = re.compile(b"^" + num_pattern + b"+$")
  791. alpha_pattern = re.compile(b"^" + alpha_pattern + b"+$")
  792. else:
  793. re_repeat = b"{" + str(minimum).encode("ascii") + b",}"
  794. num_pattern = re.compile(num_pattern + re_repeat)
  795. alpha_pattern = re.compile(alpha_pattern + re_repeat)
  796. num_bits = _optimal_split(data, num_pattern)
  797. for is_num, chunk in num_bits:
  798. if is_num:
  799. yield QRData(chunk, mode=MODE_NUMBER, check_data=False)
  800. else:
  801. for is_alpha, sub_chunk in _optimal_split(chunk, alpha_pattern):
  802. mode = MODE_ALPHA_NUM if is_alpha else MODE_8BIT_BYTE
  803. yield QRData(sub_chunk, mode=mode, check_data=False)
  804. def _optimal_split(data, pattern):
  805. while data:
  806. match = re.search(pattern, data)
  807. if not match:
  808. break
  809. start, end = match.start(), match.end()
  810. if start:
  811. yield False, data[:start]
  812. yield True, data[start:end]
  813. data = data[end:]
  814. if data:
  815. yield False, data
  816. def to_bytestring(data):
  817. """
  818. Convert data to a (utf-8 encoded) byte-string if it isn't a byte-string
  819. already.
  820. """
  821. if not isinstance(data, bytes):
  822. data = str(data).encode("utf-8")
  823. return data
  824. def optimal_mode(data):
  825. """
  826. Calculate the optimal mode for this chunk of data.
  827. """
  828. if data.isdigit():
  829. return MODE_NUMBER
  830. if RE_ALPHA_NUM.match(data):
  831. return MODE_ALPHA_NUM
  832. return MODE_8BIT_BYTE
  833. class QRData:
  834. """
  835. Data held in a QR compatible format.
  836. Doesn't currently handle KANJI.
  837. """
  838. def __init__(self, data, mode=None, check_data=True):
  839. """
  840. If ``mode`` isn't provided, the most compact QR data type possible is
  841. chosen.
  842. """
  843. if check_data:
  844. data = to_bytestring(data)
  845. if mode is None:
  846. self.mode = optimal_mode(data)
  847. else:
  848. self.mode = mode
  849. if mode not in (MODE_NUMBER, MODE_ALPHA_NUM, MODE_8BIT_BYTE):
  850. raise TypeError(f"Invalid mode ({mode})") # pragma: no cover
  851. if check_data and mode < optimal_mode(data): # pragma: no cover
  852. raise ValueError(f"Provided data can not be represented in mode {mode}")
  853. self.data = data
  854. def __len__(self):
  855. return len(self.data)
  856. def write(self, buffer):
  857. if self.mode == MODE_NUMBER:
  858. for i in range(0, len(self.data), 3):
  859. chars = self.data[i : i + 3]
  860. bit_length = NUMBER_LENGTH[len(chars)]
  861. buffer.put(int(chars), bit_length)
  862. elif self.mode == MODE_ALPHA_NUM:
  863. for i in range(0, len(self.data), 2):
  864. chars = self.data[i : i + 2]
  865. if len(chars) > 1:
  866. buffer.put(
  867. ALPHA_NUM.find(chars[0]) * 45 + ALPHA_NUM.find(chars[1]), 11
  868. )
  869. else:
  870. buffer.put(ALPHA_NUM.find(chars), 6)
  871. else:
  872. # Iterating a bytestring in Python 3 returns an integer,
  873. # no need to ord().
  874. data = self.data
  875. for c in data:
  876. buffer.put(c, 8)
  877. def __repr__(self):
  878. return repr(self.data)
  879. class BitBuffer:
  880. def __init__(self):
  881. self.buffer: List[int] = []
  882. self.length = 0
  883. def __repr__(self):
  884. return ".".join([str(n) for n in self.buffer])
  885. def get(self, index):
  886. buf_index = math.floor(index / 8)
  887. return ((self.buffer[buf_index] >> (7 - index % 8)) & 1) == 1
  888. def put(self, num, length):
  889. for i in range(length):
  890. self.put_bit(((num >> (length - i - 1)) & 1) == 1)
  891. def __len__(self):
  892. return self.length
  893. def put_bit(self, bit):
  894. buf_index = self.length // 8
  895. if len(self.buffer) <= buf_index:
  896. self.buffer.append(0)
  897. if bit:
  898. self.buffer[buf_index] |= 0x80 >> (self.length % 8)
  899. self.length += 1
  900. def create_bytes(buffer: BitBuffer, rs_blocks: List[RSBlock]):
  901. offset = 0
  902. maxDcCount = 0
  903. maxEcCount = 0
  904. dcdata: List[List[int]] = []
  905. ecdata: List[List[int]] = []
  906. for rs_block in rs_blocks:
  907. dcCount = rs_block.data_count
  908. ecCount = rs_block.total_count - dcCount
  909. maxDcCount = max(maxDcCount, dcCount)
  910. maxEcCount = max(maxEcCount, ecCount)
  911. current_dc = [0xFF & buffer.buffer[i + offset] for i in range(dcCount)]
  912. offset += dcCount
  913. # Get error correction polynomial.
  914. if ecCount in rsPoly_LUT:
  915. rsPoly = Polynomial(rsPoly_LUT[ecCount], 0)
  916. else:
  917. rsPoly = Polynomial([1], 0)
  918. for i in range(ecCount):
  919. rsPoly = rsPoly * Polynomial([1, gexp(i)], 0)
  920. rawPoly = Polynomial(current_dc, len(rsPoly) - 1)
  921. modPoly = rawPoly % rsPoly
  922. current_ec = []
  923. mod_offset = len(modPoly) - ecCount
  924. for i in range(ecCount):
  925. modIndex = i + mod_offset
  926. current_ec.append(modPoly[modIndex] if (modIndex >= 0) else 0)
  927. dcdata.append(current_dc)
  928. ecdata.append(current_ec)
  929. data = []
  930. for i in range(maxDcCount):
  931. for dc in dcdata:
  932. if i < len(dc):
  933. data.append(dc[i])
  934. for i in range(maxEcCount):
  935. for ec in ecdata:
  936. if i < len(ec):
  937. data.append(ec[i])
  938. return data
  939. def create_data(version, error_correction, data_list):
  940. buffer = BitBuffer()
  941. for data in data_list:
  942. buffer.put(data.mode, 4)
  943. buffer.put(len(data), length_in_bits(data.mode, version))
  944. data.write(buffer)
  945. # Calculate the maximum number of bits for the given version.
  946. rs_blocks_ = rs_blocks(version, error_correction)
  947. bit_limit = sum(block.data_count * 8 for block in rs_blocks_)
  948. if len(buffer) > bit_limit:
  949. raise DataOverflowError(
  950. "Code length overflow. Data size (%s) > size available (%s)"
  951. % (len(buffer), bit_limit)
  952. )
  953. # Terminate the bits (add up to four 0s).
  954. for _ in range(min(bit_limit - len(buffer), 4)):
  955. buffer.put_bit(False)
  956. # Delimit the string into 8-bit words, padding with 0s if necessary.
  957. delimit = len(buffer) % 8
  958. if delimit:
  959. for _ in range(8 - delimit):
  960. buffer.put_bit(False)
  961. # Add special alternating padding bitstrings until buffer is full.
  962. bytes_to_fill = (bit_limit - len(buffer)) // 8
  963. for i in range(bytes_to_fill):
  964. if i % 2 == 0:
  965. buffer.put(PAD0, 8)
  966. else:
  967. buffer.put(PAD1, 8)
  968. return create_bytes(buffer, rs_blocks_)
  969. class DataOverflowError(Exception):
  970. pass
  971. ModulesType = List[List[Optional[bool]]]
  972. # Cache modules generated just based on the QR Code version
  973. precomputed_qr_blanks: Dict[int, ModulesType] = {}
  974. def _check_box_size(size):
  975. if int(size) <= 0:
  976. raise ValueError(f"Invalid box size (was {size}, expected larger than 0)")
  977. def _check_border(size):
  978. if int(size) < 0:
  979. raise ValueError(
  980. "Invalid border value (was %s, expected 0 or larger than that)" % size
  981. )
  982. def _check_mask_pattern(mask_pattern):
  983. if mask_pattern is None:
  984. return
  985. if not isinstance(mask_pattern, int):
  986. raise TypeError(
  987. f"Invalid mask pattern (was {type(mask_pattern)}, expected int)"
  988. )
  989. if mask_pattern < 0 or mask_pattern > 7:
  990. raise ValueError(f"Mask pattern should be in range(8) (got {mask_pattern})")
  991. def copy_2d_array(x):
  992. return [row[:] for row in x]
  993. class ActiveWithNeighbors(NamedTuple):
  994. NW: bool
  995. N: bool
  996. NE: bool
  997. W: bool
  998. me: bool
  999. E: bool
  1000. SW: bool
  1001. S: bool
  1002. SE: bool
  1003. def __bool__(self) -> bool:
  1004. return self.me
  1005. class QRCode:
  1006. modules: ModulesType
  1007. _version: Optional[int] = None
  1008. def __init__(
  1009. self,
  1010. version=None,
  1011. error_correction=ERROR_CORRECT_M,
  1012. box_size=10,
  1013. border=4,
  1014. ):
  1015. _check_box_size(box_size)
  1016. _check_border(border)
  1017. self.version = version
  1018. self.error_correction = int(error_correction)
  1019. self.box_size = int(box_size)
  1020. # Spec says border should be at least four boxes wide, but allow for
  1021. # any (e.g. for producing printable QR codes).
  1022. self.border = int(border)
  1023. self.clear()
  1024. self._mask_pattern = None
  1025. @property
  1026. def version(self) -> int:
  1027. if self._version is None:
  1028. self.best_fit()
  1029. return cast(int, self._version)
  1030. @version.setter
  1031. def version(self, value) -> None:
  1032. if value is not None:
  1033. value = int(value)
  1034. check_version(value)
  1035. self._version = value
  1036. @property
  1037. def mask_pattern(self):
  1038. return self._mask_pattern
  1039. @mask_pattern.setter
  1040. def mask_pattern(self, pattern):
  1041. _check_mask_pattern(pattern)
  1042. self._mask_pattern = pattern
  1043. def clear(self):
  1044. """
  1045. Reset the internal data.
  1046. """
  1047. self.modules = [[]]
  1048. self.modules_count = 0
  1049. self.data_cache = None
  1050. self.data_list = []
  1051. def add_data(self, data, optimize=20):
  1052. """
  1053. Add data to this QR Code.
  1054. :param optimize: Data will be split into multiple chunks to optimize
  1055. the QR size by finding to more compressed modes of at least this
  1056. length. Set to ``0`` to avoid optimizing at all.
  1057. """
  1058. if isinstance(data, QRData):
  1059. self.data_list.append(data)
  1060. elif optimize:
  1061. self.data_list.extend(optimal_data_chunks(data, minimum=optimize))
  1062. else:
  1063. self.data_list.append(QRData(data))
  1064. self.data_cache = None
  1065. def make(self, fit=True):
  1066. """
  1067. Compile the data into a QR Code array.
  1068. :param fit: If ``True`` (or if a size has not been provided), find the
  1069. best fit for the data to avoid data overflow errors.
  1070. """
  1071. if fit or (self.version is None):
  1072. self.best_fit(start=self.version)
  1073. if self.mask_pattern is None:
  1074. self.makeImpl(False, self.best_mask_pattern())
  1075. else:
  1076. self.makeImpl(False, self.mask_pattern)
  1077. def makeImpl(self, test, mask_pattern):
  1078. self.modules_count = self.version * 4 + 17
  1079. if self.version in precomputed_qr_blanks:
  1080. self.modules = copy_2d_array(precomputed_qr_blanks[self.version])
  1081. else:
  1082. self.modules = [
  1083. [None] * self.modules_count for i in range(self.modules_count)
  1084. ]
  1085. self.setup_position_probe_pattern(0, 0)
  1086. self.setup_position_probe_pattern(self.modules_count - 7, 0)
  1087. self.setup_position_probe_pattern(0, self.modules_count - 7)
  1088. self.setup_position_adjust_pattern()
  1089. self.setup_timing_pattern()
  1090. precomputed_qr_blanks[self.version] = copy_2d_array(self.modules)
  1091. self.setup_type_info(test, mask_pattern)
  1092. if self.version >= 7:
  1093. self.setup_type_number(test)
  1094. if self.data_cache is None:
  1095. self.data_cache = create_data(
  1096. self.version, self.error_correction, self.data_list
  1097. )
  1098. self.map_data(self.data_cache, mask_pattern)
  1099. def setup_position_probe_pattern(self, row, col):
  1100. for r in range(-1, 8):
  1101. if row + r <= -1 or self.modules_count <= row + r:
  1102. continue
  1103. for c in range(-1, 8):
  1104. if col + c <= -1 or self.modules_count <= col + c:
  1105. continue
  1106. if (
  1107. (0 <= r <= 6 and c in {0, 6})
  1108. or (0 <= c <= 6 and r in {0, 6})
  1109. or (2 <= r <= 4 and 2 <= c <= 4)
  1110. ):
  1111. self.modules[row + r][col + c] = True
  1112. else:
  1113. self.modules[row + r][col + c] = False
  1114. def best_fit(self, start=None):
  1115. """
  1116. Find the minimum size required to fit in the data.
  1117. """
  1118. if start is None:
  1119. start = 1
  1120. check_version(start)
  1121. # Corresponds to the code in create_data, except we don't yet know
  1122. # version, so optimistically assume start and check later
  1123. mode_sizes = mode_sizes_for_version(start)
  1124. buffer = BitBuffer()
  1125. for data in self.data_list:
  1126. buffer.put(data.mode, 4)
  1127. buffer.put(len(data), mode_sizes[data.mode])
  1128. data.write(buffer)
  1129. needed_bits = len(buffer)
  1130. self.version = bisect_left(
  1131. BIT_LIMIT_TABLE[self.error_correction], needed_bits, start
  1132. )
  1133. if self.version == 41:
  1134. raise DataOverflowError()
  1135. # Now check whether we need more bits for the mode sizes, recursing if
  1136. # our guess was too low
  1137. if mode_sizes is not mode_sizes_for_version(self.version):
  1138. self.best_fit(start=self.version)
  1139. return self.version
  1140. def best_mask_pattern(self):
  1141. """
  1142. Find the most efficient mask pattern.
  1143. """
  1144. min_lost_point = 0
  1145. pattern = 0
  1146. for i in range(8):
  1147. self.makeImpl(True, i)
  1148. lost_point_ = lost_point(self.modules)
  1149. if i == 0 or min_lost_point > lost_point_:
  1150. min_lost_point = lost_point_
  1151. pattern = i
  1152. return pattern
  1153. def print_tty(self, out=None):
  1154. """
  1155. Output the QR Code only using TTY colors.
  1156. If the data has not been compiled yet, make it first.
  1157. """
  1158. if out is None:
  1159. import sys
  1160. out = sys.stdout
  1161. if not out.isatty():
  1162. raise OSError("Not a tty")
  1163. if self.data_cache is None:
  1164. self.make()
  1165. modcount = self.modules_count
  1166. out.write("\x1b[1;47m" + (" " * (modcount * 2 + 4)) + "\x1b[0m\n")
  1167. for r in range(modcount):
  1168. out.write("\x1b[1;47m \x1b[40m")
  1169. for c in range(modcount):
  1170. if self.modules[r][c]:
  1171. out.write(" ")
  1172. else:
  1173. out.write("\x1b[1;47m \x1b[40m")
  1174. out.write("\x1b[1;47m \x1b[0m\n")
  1175. out.write("\x1b[1;47m" + (" " * (modcount * 2 + 4)) + "\x1b[0m\n")
  1176. out.flush()
  1177. def print_ascii(self, out=None, tty=False, invert=False):
  1178. """
  1179. Output the QR Code using ASCII characters.
  1180. :param tty: use fixed TTY color codes (forces invert=True)
  1181. :param invert: invert the ASCII characters (solid <-> transparent)
  1182. """
  1183. if out is None:
  1184. out = sys.stdout
  1185. if tty and not out.isatty():
  1186. raise OSError("Not a tty")
  1187. if self.data_cache is None:
  1188. self.make()
  1189. modcount = self.modules_count
  1190. codes = [bytes((code,)).decode("cp437") for code in (255, 223, 220, 219)]
  1191. if tty:
  1192. invert = True
  1193. if invert:
  1194. codes.reverse()
  1195. def get_module(x, y) -> int:
  1196. if invert and self.border and max(x, y) >= modcount + self.border:
  1197. return 1
  1198. if min(x, y) < 0 or max(x, y) >= modcount:
  1199. return 0
  1200. return cast(int, self.modules[x][y])
  1201. for r in range(-self.border, modcount + self.border, 2):
  1202. if tty:
  1203. if not invert or r < modcount + self.border - 1:
  1204. out.write("\x1b[48;5;232m") # Background black
  1205. out.write("\x1b[38;5;255m") # Foreground white
  1206. for c in range(-self.border, modcount + self.border):
  1207. pos = get_module(r, c) + (get_module(r + 1, c) << 1)
  1208. out.write(codes[pos])
  1209. if tty:
  1210. out.write("\x1b[0m")
  1211. out.write("\n")
  1212. out.flush()
  1213. # return true if and only if (row, col) is in the module
  1214. def is_constrained(self, row: int, col: int) -> bool:
  1215. return (
  1216. row >= 0
  1217. and row < len(self.modules)
  1218. and col >= 0
  1219. and col < len(self.modules[row])
  1220. )
  1221. def setup_timing_pattern(self):
  1222. for r in range(8, self.modules_count - 8):
  1223. if self.modules[r][6] is not None:
  1224. continue
  1225. self.modules[r][6] = r % 2 == 0
  1226. for c in range(8, self.modules_count - 8):
  1227. if self.modules[6][c] is not None:
  1228. continue
  1229. self.modules[6][c] = c % 2 == 0
  1230. def setup_position_adjust_pattern(self):
  1231. pos = pattern_position(self.version)
  1232. for i in range(len(pos)):
  1233. row = pos[i]
  1234. for j in range(len(pos)):
  1235. col = pos[j]
  1236. if self.modules[row][col] is not None:
  1237. continue
  1238. for r in range(-2, 3):
  1239. for c in range(-2, 3):
  1240. if (
  1241. r == -2
  1242. or r == 2
  1243. or c == -2
  1244. or c == 2
  1245. or (r == 0 and c == 0)
  1246. ):
  1247. self.modules[row + r][col + c] = True
  1248. else:
  1249. self.modules[row + r][col + c] = False
  1250. def setup_type_number(self, test):
  1251. bits = BCH_type_number(self.version)
  1252. for i in range(18):
  1253. mod = not test and ((bits >> i) & 1) == 1
  1254. self.modules[i // 3][i % 3 + self.modules_count - 8 - 3] = mod
  1255. for i in range(18):
  1256. mod = not test and ((bits >> i) & 1) == 1
  1257. self.modules[i % 3 + self.modules_count - 8 - 3][i // 3] = mod
  1258. def setup_type_info(self, test, mask_pattern):
  1259. data = (self.error_correction << 3) | mask_pattern
  1260. bits = BCH_type_info(data)
  1261. # vertical
  1262. for i in range(15):
  1263. mod = not test and ((bits >> i) & 1) == 1
  1264. if i < 6:
  1265. self.modules[i][8] = mod
  1266. elif i < 8:
  1267. self.modules[i + 1][8] = mod
  1268. else:
  1269. self.modules[self.modules_count - 15 + i][8] = mod
  1270. # horizontal
  1271. for i in range(15):
  1272. mod = not test and ((bits >> i) & 1) == 1
  1273. if i < 8:
  1274. self.modules[8][self.modules_count - i - 1] = mod
  1275. elif i < 9:
  1276. self.modules[8][15 - i - 1 + 1] = mod
  1277. else:
  1278. self.modules[8][15 - i - 1] = mod
  1279. # fixed module
  1280. self.modules[self.modules_count - 8][8] = not test
  1281. def map_data(self, data, mask_pattern):
  1282. inc = -1
  1283. row = self.modules_count - 1
  1284. bitIndex = 7
  1285. byteIndex = 0
  1286. mask_func_ = mask_func(mask_pattern)
  1287. data_len = len(data)
  1288. for col in range(self.modules_count - 1, 0, -2):
  1289. if col <= 6:
  1290. col -= 1
  1291. col_range = (col, col - 1)
  1292. while True:
  1293. for c in col_range:
  1294. if self.modules[row][c] is None:
  1295. dark = False
  1296. if byteIndex < data_len:
  1297. dark = ((data[byteIndex] >> bitIndex) & 1) == 1
  1298. if mask_func_(row, c):
  1299. dark = not dark
  1300. self.modules[row][c] = dark
  1301. bitIndex -= 1
  1302. if bitIndex == -1:
  1303. byteIndex += 1
  1304. bitIndex = 7
  1305. row += inc
  1306. if row < 0 or self.modules_count <= row:
  1307. row -= inc
  1308. inc = -inc
  1309. break
  1310. def get_matrix(self):
  1311. """
  1312. Return the QR Code as a multidimensional array, including the border.
  1313. To return the array without a border, set ``self.border`` to 0 first.
  1314. """
  1315. if self.data_cache is None:
  1316. self.make()
  1317. if not self.border:
  1318. return self.modules
  1319. width = len(self.modules) + self.border * 2
  1320. code = [[False] * width] * self.border
  1321. x_border = [False] * self.border
  1322. for module in self.modules:
  1323. code.append(x_border + cast(List[bool], module) + x_border)
  1324. code += [[False] * width] * self.border
  1325. return code
  1326. def active_with_neighbors(self, row: int, col: int) -> ActiveWithNeighbors:
  1327. context: List[bool] = []
  1328. for r in range(row - 1, row + 2):
  1329. for c in range(col - 1, col + 2):
  1330. context.append(self.is_constrained(r, c) and bool(self.modules[r][c]))
  1331. return ActiveWithNeighbors(*context)