
    .~h                       d Z ddlmZmZ ddlmZmZmZmZ ddl	m
Z
mZ ddlmZmZmZ ddlZddlZddlZddlmZ dd	lmZ d
Z	 ddlmZ eZeZddl'Z'e'jP                  Z)['dZ*e+Z, G d de-      Z. edd      Z/	 	 dJdZ0	 	 	 dKdZ1dLdZ2dMdZ3dMdZ4d Z5d Z6d Z7d Z8d Z9d Z:d Z;d  Z<d! Z=dLd"Z>d# Z?d$ Z@d% ZAd& ZBd' ZCd( ZDd) ZEd* ZFd+ ZGdLd,ZHdNd-ZId. ZJd/ ZKd0 ZLdMd1ZMd2 ZNd3 ZOd4 ZP ej                  d5 ej                  ej                        z   d6z         ZTd7 ZUd8 ZVd9 ZWdMd:ZXd; ZYd< ZZd= Z[d> Z\d? Z]d@ Z^dA Z_ G dB dC      Z` G dD dEea      Zb G dF dG      Zc G dH dIea      Zdy# e$ r dZddlmZmZ  e!Zddl"m#Z# e#Ze$Ze%Z&Y 9w xY w)OzQR Code and Micro QR Code encoder.

DOES NOT belong to the public API.

"QR Code" and "Micro QR Code" are registered trademarks of DENSO WAVE INCORPORATED.
    )absolute_importdivision)
itemgettergtltxor)partialreduce)islicechainproductN)
namedtuple   )constsF)zip_longestT)izip_longestimap)Number)encodeencode_sequenceDataOverflowErrorc                       e Zd ZdZy)r   ab      Indicates a problem that the provided data does not fit into the
    provided QR Code version or the data is too large in general.

    This exception is inherited from :py:exc:`ValueError` and is only raised
    if the data does not fit into the provided (Micro) QR Code version.

    Basically it is sufficient to catch a :py:exc:`ValueError`.
    N)__name__
__module____qualname____doc__     V/var/www/peopleoo.sandbox-dev.co.uk/venv/lib/python3.12/site-packages/segno/encoder.pyr   r   /   s    r   r   Codez"matrix version error mask segmentsc	                 ~   t        |      }|s7|5|t        j                  v r#t        dj	                  t        |                  |r7|5|t        j                  vr#t        dj	                  t        |                  t        |d      }t        |      }|;|9t        ||      s-t        dj	                  t        |      t        |                  |t        j                  k(  r|s|t        j                  v rt        d      |r|s|t        j                  v rt        d      t        | ||      }	t        |	|||      }
||
}n2|
|kD  r-t        d	j	                  t        |      t        |
                  |#|t        j                  k7  rt        j                  }|d
k  }t!        ||      }t#        |	|||||      S )a      Creates a (Micro) QR code.

    See :py:func:`segno.make` for a detailed description of the parameters.

    Contrary to ``make`` this function returns a named tuple:
    ``(matrix, version, error, mask, segments)``

    Note that ``version`` is always an integer referring
    to the values of the :py:mod:`segno.consts` constants. ``error`` is ``None``
    iff a M1 QR Code was generated, otherwise it is always an integer.

    :rtype: namedtuple
    zJA Micro QR Code version ("{0}") is provided but parameter "micro" is Falsez#Illegal Micro QR Code version "{0}"Taccept_nonez,Mode "{0}" is not available in version "{1}"z>Error correction level "H" is not available for Micro QR Codesz0The ECI mode is not available for Micro QR CodesecimicrozHThe provided data does not fit into version "{0}". Proposal: version {1}r   )normalize_versionr   MICRO_VERSIONS
ValueErrorformatget_version_namenormalize_errorlevelnormalize_modeis_mode_supportedget_mode_nameERROR_LEVEL_Hprepare_datafind_versionr   
VERSION_M1ERROR_LEVEL_Lnormalize_mask_encode)contenterrorversionmodemaskencodingr%   r&   boost_errorsegmentsguessed_versionis_micros               r   r   r   >   s      (GU&7f6K6K+K 6 &!1'!:;= 	= $8M8M)M> &!1'!:;= 	= D9E$DG/%dG4G &t!46Fw6OPR 	R$$$%7f>S>S3SYZZ
F$9$99KLLGT84H"8U5IO!	7	" j!'(8(ACSTcCd!eg 	g}F$5$55$${H$)D8UGT3DDr   c	                    fd}	d }
	 	 ddfd}t        |      }|(|dk  r0t        dj                  t        |                  |t        d	      |"d|cxk  rd
k  st        d       t        d      t	        |d      }|t
        j                  }t        |      }t        |d      }t        | |      }d}|1	 t        ||d      }|r||xs |k  rt        |||xs |||      gS t        |j                        dkD  rt        d      |j                  d   }|t
        j                  k(  rt!        |       } |(t        |       |k  rt        dj                  |            t#        |       }|xs d
}| || |||      }|d
kD  rt        dj                  |             |
| |      }|( |	t%        |t              |      }t        ||dd      }t'        t(        t        |      dz
  |      }t+        |      D cg c]$  \  }}t         |	||      |||| ||            & c}}S # t        $ r Y pw xY wc c}}w )z    EXPERIMENTAL: Creates a sequence of QR codes in Structured Append mode.

    :return: Iterable of named tuples, see :py:func:`encode` for details.
    c                 V    t               }|j                  t        | |             |S )z;        Creates a Segments sequence with one item.
        )r:   r<   )Segmentsadd_segmentmake_segment)chunkr:   segsr<   s      r   one_item_segmentsz*encode_sequence.<locals>.one_item_segmentsv   s(     ze$JKr   c           
          t        t        |       |      \  }}t        |      D cg c]-  }| ||z  t        ||      z   |dz   |z  t        |dz   |      z    / c}S c c}w Nr   )divmodlenrangemin)datanumkmis        r   divide_into_chunksz+encode_sequence.<locals>.divide_into_chunks~   s\    c$i%1MRSVZXQUSAY&A{SQ]'BCXXXs   2ANFc                 *   d}|t         j                  |   |   z  }|r0|t         j                  k(  r|t         j                  k7  r
|dz  }|dz  }|r|dz  }d}|t         j                  k(  r&t        | d      \  }}	||dz  |	dk(  rdndz   z  }||z   S |t         j                  k(  r#t        | d	      \  }}	||d
z  |	rdndz   z  }||z   S |t         j                  k(  r|| dz  z  }||z   S |t         j                  t         j                  fv r|| dz  z  }||z   S )N         r      
   r                  )	r   CHAR_COUNT_INDICATOR_LENGTH	MODE_BYTEDEFAULT_BYTE_ENCODINGMODE_NUMERICrK   MODE_ALPHANUMERIC
MODE_KANJI
MODE_HANZI)

char_count	ver_ranger:   r<   is_eciis_saoverheadbitsrP   	remainders
             r   calc_qrcode_bit_lengthz/encode_sequence.<locals>.calc_qrcode_bit_length   sI   F66t<YGGdf...8v?[?[3[MHMH H6&&&#J2NCC"HY!^;;D $ V---#J2NCC"HYA66D
 $	 V%%%JN"D $ f''):):;;JO#D$r   c                 ,   t        |       }t        |      } 	|||
d      }t        j                  |   |   }t	        t        j                  ||z              }|d|dz
  z  
rd|dz
  z  ndz   z  }t	        t        j                  ||z              S )zH        Returns the number of symbols for the provided version.
        T)ri   rj   rX   r      r   )rL   version_ranger   SYMBOL_CAPACITYintmathceil)r7   r9   r8   r:   lengthrh   
bit_lengthcapacitycntrn   r%   r<   s            r   number_of_symbols_by_versionz5encode_sequence.<locals>.number_of_symbols_by_version   s     W!'*	+FItX36dD
))'259$))J123esQw'S2q>aHH
499Z(2344r   r   zEThis function does not accept Micro QR Code versions. Provided: "{0}"z;Please provide either a QR Code version or the symbol count   z)The symbol count must be in range 1 .. 16Tr"   )r@   r$   )r8   r9   r;   r%   r=   z<This function cannot handle more than one mode (yet). Sorry.r   z=The content is not long enough to be divided into {0} symbolsz8The data does not fit into Structured Append version {0})key)r%   r&   rj   )totalparity)r8   r9   r;   r%   r=   sa_info)NFF)r'   r)   r*   r+   r,   r   r4   r-   r5   r1   r2   r   r6   rL   modesrc   strcalc_structured_append_paritymaxr	   _StructuredAppendInfo	enumerate)r7   r8   r9   r:   r;   r<   r%   r=   symbol_countrH   rT   rz   r>   r?   sa_parity_datanum_symbolschunksr   rS   rF   rn   s        ``             @r   r   r   n   s   Y FJ3825  (GQ; //5v6Fw6O/PR R		VWW\(?R(?DEE )@DEE D9E}$$$D$/DGT84HO	*8U5QO
 73MoNHEG<V!%3KI J J
8>>QWXX>>!Dv"""g,CL<$?X__`lmnn27;N$"K27GUDQR Z a abi jkk5F$SS%94@xCuDQ+3v;?+-G 9B&8IK,4Au %eT2%3K#AJ( K K9 ! 	 	8Ks   H; )I;	IIc                    |dk  }|du}t               }	|}
|}|sd}
t        |      }|rt        ||| ||      }|r8|dd D ]  }|	j                  |d        |	j                  |j                  d       | D ]  }t        |	||
||        t        j                  |   |   }t        |	||
t        |	             t        |	|t        |	             t        |	||t        |	             t        |||	      }	t        |      }|}||f}t        ||      }t        ||       t!        ||       t#        ||	|       t%        ||||      \  }}t'        ||||       t)        ||       t+        |||||       S )z    Creates a (Micro) QR code.

    NOTE: This function does not check if the input is valid and does not belong
    to the public API.
    r   Nrj   rY   rV   rW   )Bufferrq   boost_error_levelappend_bitsr~   write_segmentr   rr   write_terminatorrL   write_padding_bitswrite_pad_codewordsmake_final_messagecalc_matrix_sizemake_matrixadd_finder_patternsadd_alignment_patternsadd_codewordsfind_and_apply_best_maskadd_format_infoadd_version_infor    )r>   r8   r9   r;   r%   r=   r   r@   sa_modebuffverrh   rS   segmentrx   widthheightmatrix_sizematrixs                      r   r6   r6      s    {HT!G8D
CI!'*	!'5(CwO! 	#AQ"	#+ :dGS)S9:%%g.u5HT8S#d)4tWc$i0gxT;gud3DW%EF-K'F)6;/&$( ,FK4PLD&FGUD1VW%h77r   c                    |t         j                  dfvrt        |      dk(  rt         j                  t         j                  t         j
                  t         j                  g}| dk  r3|j                          | t         j                  k  r|j                          |j                  | ||      }||j                  |      dz   d D ]   }t         j                  |    |   |k\  r|} |S  |S )a      Increases the error correction level if possible.

    Returns either the provided or a better error correction level which works
    while keeping the (Micro) QR Code version.

    :param int version: Version constant.
    :param int|None error: Error level constant or ``None``
    :param Segments segments: Instance of :py:class:`Segments`
    :param bool eci: Indicates if ECI designator should be written.
    :param bool is_sa: Indicates if Structured Append mode is used.
    Nr   r   )r   r0   rL   r4   ERROR_LEVEL_MERROR_LEVEL_Qpop
VERSION_M4bit_length_with_overheadindexrr   )r9   r8   r>   r%   rj   levelsdata_lengtherror_levels           r   r   r     s     V))400S]a5G&&(<(<&&(<(<>Q;JJL***

77E7R!&,,u"5"9":; 	K%%g.{;{J#L	
 Lr   c                 6   |j                   }| j                  }|rc|t        j                  k(  rP|j                  t        j
                  k7  r3 |t        j                  d        |t        |j                        d       |( ||d       |t        j                  k(  r<d} ||d       n0|t        j                  kD  r |t        j                  |   |dz           ||j                  t        j                  |   |          | j                  |j                         y)a      Writes a segment.

    :param buff: The byte buffer.
    :param _Segment segment: The segment to serialize.
    :param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a
            Micro QR Code is written.
    :param ver_range: "M1", "M2", "M3", or "M4" if a Micro QR Code is written,
            otherwise a constant representing a range of QR Code versions.
    rV   rW   Nr   rY   )r:   r   r   ra   r<   rb   MODE_ECIget_eci_assignment_numberrf   r3   MODE_TO_MICRO_MODE_MAPPINGrg   r`   extendrl   )r   r   r   rh   r%   r:   r   subsets           r   r   r   3  s     <<D""K
tv'''  F$@$@@FOOQ'-g.>.>?C
{D!6$$$F"	v  	 F55d;S1WE""2248CEKKr   c                 j    | j                  dgt        ||z
  t        j                  |         z         y)a      Writes the terminator.

    :param buff: The byte buffer.
    :param capacity: Symbol capacity.
    :param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a
            Micro QR Code is written.
    :param length: Length of the data bit stream.
    r   N)r   rN   r   TERMINATOR_LENGTH)r   rx   r   rv   s       r   r   r   R  s.     	KKc(V+V-E-Ec-JKKLr   c                     |t         j                  t         j                  fvr| j                  dgd|dz  z
  z         yy)z    Writes padding bits if the data stream does not meet the codeword boundary.

    :param buff: The byte buffer.
    :param int length: Data stream length.
    r   rW   N)r   r3   
VERSION_M3r   )r   r9   rv   s      r   r   r   `  s>     v((&*;*;<<QC1
+,- =r   c                     | j                   }|t        j                  t        j                  fv r |dg||z
  z         yd}t	        |dz  |dz  z
        D ]  } |||dz             y)a=      Writes the pad codewords iff the data does not fill the capacity of the
    symbol.

    :param buff: The byte buffer.
    :param int version: The (Micro) QR Code version.
    :param int capacity: The total capacity of the symbol (incl. error correction)
    :param int length: Length of the data bit stream.
    r   ))r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   rW   r\   N)r   r   r3   r   rM   )r   r9   rx   rv   writepad_codewordsrS   s          r   r   r   s  sq    $ KKE6$$f&7&788qcX&'(Lx1}v{23 	(A-A&'	(r   c                     d}ddt        |       dz
  fdf}|rd}t        d      }|D ]8  \  }}|dk(  rdnd}|dk7  rdnd}|D ]  }	|||	z      ||dz    | ||	z      ||dz     : y)	a      Adds the finder pattern(s) with the separators to the matrix.

    QR Codes get three finder patterns, Micro QR Codes have just one finder
    pattern.

    ISO/IEC 18004:2015(E) -- 6.3.3 Finder pattern (page 16)
    ISO/IEC 18004:2015(E) -- 6.3.4 Separator (page 17)

    :param matrix: The matrix.
    :param bool is_micro: Indicates if the matrix represents a Micro QR Code.
    )		r   r   r   r   r   r   r   r   r   	r   r   r   r   r   r   r   r   r   	r   r   r   r   r   r   r   r   r   	r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rW   )r   )r   r   NrL   rM   )
r   r@   patterncornersfinder_rangerS   joffset	sepoffsetrs
             r   r   r     s    >G 3v;?+W5G8L R11f!aAQ	 	RA%,VaZ%89q=%QF1q5M!AE"	RRr   c                     |rdt        |       fndt        |       dz
  f\  }}| |   }d}t        d|      D ]  }|| |   |<   |||<   |dz  } y)a4      Adds the (horizontal and vertical) timinig pattern to the provided `matrix`.

    ISO/IEC 18004:2015(E) -- 6.3.5 Timing pattern (page 17)

    :param matrix: Matrix to add the timing pattern into.
    :param bool is_micro: Indicates if the timing pattern for a Micro QR Code
        should be added.
    r   r^   rW   r   Nr   )r   r@   r   stopcolbitrS   s          r   add_timing_patternr     si     #+q#f+CK!O0DGAt
)C
C1d^ q	!As
r   c                 6   |\  }}||k(  }|dz
  dz  }|r|dk  ryd}t         j                  |dz
     }t        d      }|d   }	|d   }
|	|	f|	|
f|
|	ff}t        |d	      D ]7  \  }}||f|v r|dz
  |dz
  }}|D ]  }||dz  |dz  dz    | ||z      ||dz     9 y)
ai      Adds the adjustment patterns to the matrix. For versions < 2 this is a
    no-op.

    ISO/IEC 18004:2015(E) -- 6.3.6 Alignment patterns (page 17)
    ISO/IEC 18004:2015(E) -- Annex E Position of alignment patterns (page 83)

    :param matrix: An iterable of bytearrays.
    :param tuple(int, int) matrix_size: Tuple of width and height of the matrix.
       rV   r\   N)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r      r   )repeat)r   ALIGNMENT_POSrM   r   )r   r   r   r   	is_squarer9   r   	positionsalignment_rangemin_posmax_posfinder_positionsxyrS   r   r   s                    r   r   r     s      ME6IrzaGWq[(G
 $$Wq[1IAhOlGmG '*Wg,>'@RS	!, >1q6%%1ua!e1  	>A%,QU1q519%=F1q5M!AE"	>>r   c                    t        |       }|dk  }|t        j                  t        j                  fvrdnd}d}t        |      }t	        d      }t	        |dz
  dd      D ]l  }	|s
|	dk  r|	dz  }	t	        |      D ]P  }
|D ]I  }|	|z
  }|	|z   dz  dk(  }|s||dk  z  }|r|dz
  |
z
  n|
}| |   }||   dk(  s7||k  s=||   ||<   |dz  }K R n |t        |      k7  r$t        dj                  |t        |                  y)a7      Adds the codewords (data and error correction) to the provided matrix.

    ISO/IEC 18004:2015(E) -- 7.7.3 Symbol character placement (page 46)

    :param matrix: The matrix to add the codewords into.
    :param codewords: Sequence of bits
    :param int version: The (Micro) QR Code version constant.
    r   r   r\   r^   zMInternal error: Adding codewords to matrix failed. Added {0} of {1} codewordsN)rL   r   r3   r   rM   r)   r*   )r   	codewordsr9   r   r@   incidxcodeword_length	range_tworightverticalzr   upwardsrS   rows                   r   r   r     sH    f+K{H v00&2C2CDD!!C
C )nOaI{Q2. EQJQJEk* 
	H 	AI!CK1,2q1u$G4;[1_x/Qiq6S=S?%:&s^CF1HC	
	 c)n 66<fS#i.6QS 	S r   c                 n   dd}t         j                  |    |   }t        ||      \  }}d}| t         j                  t         j                  fv r ||d   j                  d      dz	  d      }t               }|j                  t        t        |d t        j                  t        |       D                      ||j                  |       |j                  t        t        |d t        j                  t        |       D                      d}	| dv rd	}	n| d
v rd}	n| dv rd}	|j                  d|	z         |S )ad      Constructs the final message (codewords incl. error correction).

    ISO/IEC 18004:2015(E) -- 7.6 Constructing the final message codeword sequence (page 45)

    :param int version: (Micro) QR Code version constant.
    :param int error: Error level constant.
    :param buff: Byte buffer.
    :return: Byte buffer representing the final message.
    c                 >      fdt        t        |            D        S )Nc              3   .   K   | ]  }|z	  d z    ywr   Nr   .0rS   vals     r   	<genexpr>z8make_final_message.<locals>.to_binary.<locals>.<genexpr>  s     @1Q@   )reversedrM   )r   rv   s   ` r   	to_binaryz%make_final_message.<locals>.to_binary  s    @v(?@@r   Nr   r   rV   c              3   &   K   | ]	  }||  y wNr   r   r   s     r   r   z%make_final_message.<locals>.<genexpr>*  s     %qAcdcpa%q   c              3   &   K   | ]	  }||  y wr   r   r   s     r   r   z%make_final_message.<locals>.<genexpr>.  s     %rAdedqa%rr   )r\   rY   rV   r   r^   r[   )      r{   r         rX                   !   "   rY   )                         )rW   )r   ECCmake_blocksr3   r   r   r   r   r   mapfrom_iterabler   )
r9   r8   r   r   ec_infosdata_blockserror_blockscw_fourresrm   s
             r   r   r     s+   A zz'"5)H +Hd ;KG6$$f&7&788
 KN..r2a7;
(CJJuc)%q1D1D[R]E^1_%qrst

7JJuc)%r1D1D[R^E_1`%rstu I/!		L	L		0	0	JJuy !Jr   c                    |j                         }g g }}|j                  }|j                  }t        j                  }t        j                  }| D ]  }	|	j
                  |	j                  z
  }
t        j                  |
   }t        |
      }t        |	j                        D ]  }t        t        ||	j                              } ||       t        |      }t        |      }|j                  dg|
z         t        |      D ]5  }||   }|dk7  s||   }|D ]  }|||z   dz   xx   ||||   z      z  cc<     7  |||d          ||fS )z{    Returns the data and error blocks.

    :param ec_infos: Iterable of ECC information
    :param buff: Byte buffer.
    r   r   N)tointsappendr   
GALIOS_LOG
GALIOS_EXP	num_totalnum_dataGEN_POLYrM   
num_blocks	bytearrayr   rL   r   )r  r   r   r  r  append_data_blockappend_error_blockgen_loggen_expec_infonum_error_wordsgenrange_error_wordsrS   blocklen_dataerror_blockrQ   coeflcoefns                        r   r  r  @  sg    I "BK#**%,,GG 7!++g.>.>>ooo.!/2w))* 	7AfY0@0@ABEe$5zH#E*Ks_458_ J"1~19#DME. J#AEAI.'%#a&.2II.J	J {8956	7	7$ $$r   c                    t         }t        }t        }|rt        }d}t        }t        | t        |       t        |       |sdd   d<   fd}t        |      }|t        | ||   ||       || fS d}	t        |      D ]G  \  }
}| D cg c]  }|dd 	 }}t        ||||        |||      } |||      s9|}|
}t        |      }	I |	fS c c}w )a      Applies all mask patterns against the provided QR Code matrix and returns
    the best matrix and best pattern.

    ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
    ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results (page 53)
    ISO/IEC 18004:2015(E) -- 7.8.3.1 Evaluation of QR Code symbols (page 53/54)
    ISO/IEC 18004:2015(E) -- 7.8.3.2 Evaluation of Micro QR Code symbols (page 54/55)

    :param matrix: A matrix.
    :param int version: A version (Micro) QR Code version constant.
    :param bool is_micro: Indicates if the matrix represents a Micro QR Code
    :param proposed_mask: Optional int to indicate the preferred mask.
    :rtype: tuple
    :return: A tuple of the best matrix and best data mask pattern index.
    r   r   r   rW   c                     |    |   dkD  S rJ   r   )rS   r   function_matrixs     r   is_encoding_regionz4find_and_apply_best_mask.<locals>.is_encoding_region  s    q!!$s**r   N)r   _MAX_PENALTY_SCOREevaluate_maskr   evaluate_micro_maskr   r   r   get_data_mask_functions
apply_maskr   tuple)r   r   r@   proposed_mask	is_better
best_score	eval_maskr0  mask_patternsbest_matrixmask_numbermask_patternbarR   scorebest_patternr/  s                   @r   r   r   b  s   ( I#JI 	
'	 ";/O2?K8!$A+ ,H5M 6=7%	'f$$K%.}%= 	#!\#$rRU$$1lK1CD ![)UJ'J&L(K	# $$ %s   Cc           	          |\  }}t        |      }t        |      D ],  }| |   }|D ]   }	 |||	      s||	xx    |||	      z  cc<   " . y)a      Applies the provided mask pattern on the `matrix`.

    ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)

    :param tuple matrix: A tuple of bytearrays
    :param mask_pattern: A mask pattern (a function)
    :param int matrix_size: width or height of the matrix
    :param is_encoding_region: A function which returns ``True`` iff the
            row index / col index belongs to the data region.
    N)rM   )
r   r>  r   r0  r   r   width_rangerS   r   r   s
             r   r5  r5    s`      ME6,K6] -Qi 	-A!!Q'A,q!,,	--r   c                 ,    t        t        | |            S )a!      Evaluates the provided `matrix` of a QR code.

    ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results (page 53)

    :param matrix: The matrix to evaluate
    :param matrix_size: The width (or height) of the matrix.
    :return int: The penalty score of the matrix.
    )summask_scores)r   r   s     r   r2  r2    s     {6;/00r   c                    t        d      fd}d}d}d}|d   |d   k(  sJ |d   t              }d}d}t              }	|D ]  }
| |
   }d}d}d}d}|D ]w  }||   }| |   |
   }||	|<   ||z  }||k(  r|dz  }n|dk\  r||dz
  z  }d}||k(  r|dz  }n|dk\  r||dz
  z  }d}|r$|r"||cxk(  r||   cxk(  r||dz
     k(  rn n|d	z  }|}|}y |}| ||      z  }| ||	      z  }|dk\  r||dz
  z  }|dk\  s||dz
  z  } t        |      dz  z  }d
t        t	        |dz  dz
        dz        z  }||||fS )u      Returns the penalty score features of the matrix.

    The returned value is a tuple of all penalty scores (N1, N2, N3, N4).
    Use :py:func:`evaluate_mask` for a single value (sum of all scores).


    ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)

    ============================================   ====================================   ===============
    Feature                                        Evaluation condition                   Points
    ============================================   ====================================   ===============
    Adjacent modules in row/column in same color   No. of modules = (5 + i)               N1 + i
    Block of modules in same color                 Block size = m × n                     N2 ×(m-1)×(n-1)
    1 : 1 : 3 : 1 : 1 ratio                        Existence of the pattern               N3
    (dark:light:dark:light:dark) pattern in
    row/column, preceded or followed by light
    area 4 modules wide
    Proportion of dark modules in entire symbol    50 × (5 × k)% to 50 × (5 × (k + 1))%   N4 × k
    ============================================   ====================================   ===============

    N1 = 3
    N2 = 3
    N3 = 40
    N4 = 10

    :param matrix: The matrix to evaluate
    :param matrix_size: The width (or height) of the matrix.
    :return tuple: A tuple of penalty scores (ints): ``(n1, n2, n3, n4)``.
    )r   r   r   r   r   r   r   c                 .   d}| j                        }|dk7  r{|dz   }|ddz
  fv sJt        | t        |dz
  d      t        |             r%t        | t        |d      t        |dz                s|dz  }n|dz   }| j                  |      }|dk7  r{|S )Nr   r   r[   rV   (   )findanyr   rN   )seqcountr   r   
n3_patternqr_sizes       r   n3_pattern_occurrencesz+mask_scores.<locals>.n3_pattern_occurrences  s    hhz"Ri1WFq'A+&&s3sQw?3sG3DEFs3vq>#fqj'2JKL q((:v.C Ri r   r   r   Nr   r   r\   rY   rZ   d   2   )r  rM   floatrs   abs)r   r   rP  score_n1score_n2score_n3qr_module_rangedark_module_counterlast_row	n3_columnrS   r   row_prev_bitcol_prev_bitn1_row_countern1_col_counterr   row_current_bitcol_current_bitpercentscore_n4rN  rO  s                        @@r   rF  rF    s   > >?J& HHHq>[^+++!nGGnOH'"I '+Qi  	+A!!fO$QilO*IaL?2,.!#!Q& 22H!",.!#!Q& 22H!"A/\"cXa["cT\]^ab]bTc"cA*L*L/	+0 *3//*955Q**HQ**HO'+R '(GqL9GCGcMB./!344HXx11r   c                      t        d|d         } d   t         fd|D              }t        fd|D              }||k  r|dz  |z   S |dz  |z   S )a*      Evaluates the provided `matrix` of a Micro QR code.

    ISO/IEC 18004:2015(E) -- 7.8.3.2 Evaluation of Micro QR Code symbols (page 54)

    :param matrix: The matrix to evaluate
    :param matrix_size: The width (or height) of the matrix.
    :return int: The penalty score of the matrix.
    r   r   r   c              3   .   K   | ]  }|   d      yw)r   Nr   )r   rS   r   s     r   r   z&evaluate_micro_mask.<locals>.<genexpr>:  s     3vay}3r   c              3   (   K   | ]	  }|     y wr   r   )r   rS   rZ  s     r   r   z&evaluate_micro_mask.<locals>.<genexpr>;  s     1qx{1s   r{   )rM   rE  )r   r   module_rangesum1sum2rZ  s   `    @r   r3  r3  .  sa     KN+LbzH3l33D1L11D#t|4"9tAT1AAr   c                 0   |}| dkD  r_|t         j                  k(  r|dz  }n1|t         j                  k(  r|dz  }n|t         j                  k(  r|dz  }t         j                  |   }|S |t         j
                  |    |   dz  z  }t         j                  |   }|S )uz      Returns the format information for the provided error level and mask patttern.

    ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55)
    ISO/IEC 18004:2015(E) -- Table C.1 — Valid format information bit sequences (page 80)

    :param int version: Version constant
    :param int error: Error level constant.
    :param int mask_pattern: Mask pattern number.
    r   rW   r{   r  r\   )r   r4   r0   r   FORMAT_INFOERROR_LEVEL_TO_MICRO_MAPPINGFORMAT_INFO_MICRO)r9   r8   r>  fmtformat_infos        r   calc_format_inforp  ?  s     C{F(((4KCf***4KCf***4KC((-  	v227;EBaGG..s3r   c                    |dk  }t        |||      }t        |      }|}| d   }t        d      D ]L  }	||	z	  dz  }
|d|	z
  z	  dz  }|	dk(  r	|s|dz  }d}|
| |	|z      d<   |||	|z   <   |r:|
|d|	z
  <   || d|	z
     d<   N |s	d| d   d<   yy)a      Adds the format information into the provided matrix.

    ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55)
    ISO/IEC 18004:2015(E) -- 7.9.1 QR Code symbols
    ISO/IEC 18004:2015(E) -- 7.9.2 Micro QR Code symbols

    :param matrix: The matrix.
    :param int version: Version constant
    :param int error: Error level constant.
    :param int mask_pattern: Mask pattern number.
    r   rW   r   r^   r   r   N)rp  rs   rM   )r   r9   r8   r>  r@   ro  voffsethoffset	row_eightrS   vbithbits               r   r   r   Y  s    J {H"7E<@K(mGGq	I1X %q D(Q'4/6(qLGG!%q7{A!%	!g+ $Ib1f $F26N1% r
1 r   c                    |dk  ryt         j                  |dz
     }t        d      D ]U  }||dz  z	  dz  }||dz  dz   z	  dz  }||dz  dz   z	  dz  }|| d   |<   || d   |<   || d	   |<   | |   }||d<   ||d<   ||d	<   W y)
z    Adds the version information to the matrix, for versions < 7 this is a no-op.

    ISO/IEC 18004:2015(E) -- 7.10 Version information (page 58)
    r[   Nr^   rY   r   r\   )r   VERSION_INFOrM   )r   r9   version_inforS   bit1bit2bit3r   s           r   r   r     s    * {&&w{3L1X Q'4/!a%1-5!a%1-5sAsAr
1QiCCBr   c                 X   t               }|j                  }t        | t        t        t
        f      r |t        | ||             |S | D ]^  }|||}}}t        |t              r3|d   }t        |      dkD  r	|d   xs |}t        |      dkD  r	|d   xs |} |t        |||             ` |S )a      Returns an iterable of `Segment` instances.

    If `content` is a string, an integer, or bytes, the returned tuple will
    have a single item. If `content` is a list or a tuple, a tuple of
    `Segment` instances of the same length is returned.

    :param content: Either a string, bytes, an integer or an iterable.
    :type content: str, bytes, int, tuple, list or any iterable
    :param mode: The global mode. If `content` is list/tuple, the `Segment`
            instances may have a different mode.
    :param encoding: The global encoding. If `content` is a list or a tuple,
            the `Segment` instances may have a different encoding.
    :rtype: Segments
    r   r   r\   )	rC   rD   
isinstancestr_typebytesnumericrE   r6  rL   )	r7   r:   r<   r>   rD   itemseg_contentseg_modeseg_encodings	            r   r1   r1     s      zH&&K'HeW56L$9: G.2D(|XdE"q'K4y1}7?d4y1}#Aw2(LhEFG Or   c                    t        | t              r | t        |       |xs t        j                  fS t        |       } || j                  |      } n"	 t        j                  }| j                  |      } | t        |       |fS # t        $ rH 	 t        j                  }| j                  |      } n"# t        $ r d}| j                  |      } Y nw xY wY ^w xY w)a      Converts the provided data into bytes. If the data is already a byte
    sequence, it will be left unchanged.

    This function tries to use the provided `encoding` (if not ``None``)
    or the default encoding (ISO/IEC 8859-1). It uses UTF-8 as fallback.

    Returns the (byte) data, the length of the data and the encoding of the data.

    :param data: The data to encode
    :type data: str or bytes
    :param encoding: str or ``None``
    :rtype: tuple: data, data length, encoding
    utf-8)	r  r  rL   r   rb   r   r   UnicodeErrorKANJI_ENCODING)rO   r<   s     r   data_to_bytesr    s     $SY HF,H,HHHt9D{{8$	-33H;;x(D TH$$  	--!00{{8, -"{{8,-	-s6   !B   	C
!B,+C,CC
CCCc           	         |t         j                  k(  rt         j                  }t        | |      \  }}}|}|t         j                  k7  rt        |      nt         j                  }|<||k  r9t        dj                  t        |      t        |      t        |                  |}|t         j                  k7  rd}|t         j                  t         j                  fvr|n|dz  }t               }	|	j                  }
|t         j                  k(  r=t        d|d      D ]+  }|||dz    } |
t        |      t!        |      dz  dz          - n |t         j"                  k(  rut         j$                  j&                  }t        d|d      D ]I  }|||dz    }t!        |      dkD  r" |
 ||d         dz   ||d         z   d       ; |
 ||      d	       K nx|t         j                  k(  r!t(        r	d
 |D        }|D ]  } |
|d        nD|t         j                  k(  rt(        r|D cg c]  }t+        |       }}t        d|d      D ]j  }||   dz  ||dz      z  }d|cxk  rdk  r	n n|dz
  }n.d|cxk  rdk  r	n n|dz
  }nt        dj                  |             |
|dz	  dz  |dz  z   d       l nt(        r|D cg c]  }t+        |       }}t        d|d      D ]j  }||   dz  ||dz      z  }d|cxk  rdk  r	n n|dz
  }n.d|cxk  rdk  r	n n|dz
  }nt        dj                  |             |
|dz	  dz  |dz  z   d       l t-        |	j/                         |||      S c c}w c c}w )z    Creates a :py:class:`Segment`.

    :param data: The segment data
    :param mode: The mode.
    :param encoding: The encoding.
    :rtype: _Segment
    Nz@The provided mode "{0}" is not applicable for {1}. Proposal: {2}r\   r   rY   r   -   r]   r^   c              3   2   K   | ]  }t        |        y wr   ord)r   bs     r   r   zmake_segment.<locals>.<genexpr>B  s     9qCF9   rW   i  i  i  i  i  zInvalid Hanzi bytes: {0}`      r_   @    @    i@  zInvalid Kanji bytes: {0}   )r   rf   HANZI_ENCODINGr  ra   	find_moder)   r*   r/   reprre   r   r   rc   rM   rs   rL   rd   ALPHANUMERIC_CHARSrJ  _PY2r  _Segmentgetbits)rO   r:   r<   segment_datasegment_lengthsegment_encodingsegment_modeguessed_moderg   r   r   rS   rF   to_byter  codediffs                    r   rE   rE     s    v   ((5B45R2L."2L
 /;f>N>N.N9\*TZTdTdL,&_$f]<%@%),%7%2<%@BC C
 $v'''#/8I8I6K\K\7]#]cquvcvJ8D""Kv*** q.!, 	8A 1q5)EE
CJNQ$67	8 
11	1++00q.!, 	/A 1q5)E 5zA~GE!H-2WU1X5FFK
 GENA.	/ 
))	)9L9L 	A1		**	*,89qCF9L9q.!, 	BA Oq(LQ,??D'' f}4)6) f} !;!B!B4!HII $!)t+t<bA	B$ ,89qCF9L9q.!, 	BA Oq(LQ,??D'' f}4)6) f} !;!B!B4!HII $!)t+t<bA	B  DLLNJ>NOOM :* :s   !M$:M)c                 x  	 | |k(  }|xr | dk  }dg| z  	t        	fdt        |      D              }|rw|rA| dkD  r<t        d      D ].  }||   	d	d<   d	d<   d	d	<   d|d   |<   d|d   |<   d|d	   |<   0 |d
   }t        d      D ]!  }d||   d
<   d||<   |rd||    d
<   d|| <   # |rt        ||       |S )aH      Creates a matrix of the provided `size` (w x h) initialized with the
    (illegal) value 0x2.

    The "timing pattern" is already added to the matrix and the version
    and format areas are initialized with 0x0.

    :param int width: Matrix width
    :param int height: Matrix height.
    :rtype: tuple of bytearrays
    r  r\   c              3   4   K   | ]  }t                y wr   )r  )r   rS   r   s     r   r   zmake_matrix.<locals>.<genexpr>  s     9a9S>9s   )   r^   r   rx  ry  rz  rW   	   )r6  rM   r   )
r   r   reserve_regions
add_timingr   r@   r   rS   rt  r   s
            @r   r   r   q  s
    I'URZH%%-C95=99F1X 	$QiCCB!$sA!$sA #r
1	$ 1I	q 	$AF1IaLIaL #r
1 #	1"	$ 68,Mr   c                    | yd}	 t        |       } | dk  }|sd| cxk  rdk  scn | t        j                  vrOt        dj                  | dj                  t        t        j                  j                                                 | S # t        t        f$ r= 	 t        j                  | j                            } n# t        t        f$ r d}Y nw xY wY w xY w)	a      Canonicalization of the provided `version`.

    If the `version` is ``None``, this function returns ``None``. Otherwise
    this function checks if `version` is an integer or a Micro QR Code version.
    In case the string represents a Micro QR Code version, an uppercased
    string identifier is returned.

    If the `version` does not represent a valid version identifier (aside of
    ``None``) a :py:exc:`ValueError` is raised.

    :param version: An integer, a string or ``None``.
    :raises: :py:exc:`ValueError`: In case the version is not ``None`` and does not
                represent a valid (Micro) QR Code version.
    :rtype: int, str or ``None``
    NFr   Tr   r  z5Unsupported version "{0}". Supported: {1} and 1 .. 40, )rs   r)   	TypeErrorr   MICRO_VERSION_MAPPINGupperKeyErrorAttributeErrorr(   r*   joinsortedkeys)r9   r8   s     r   r'   r'     s    " Eg,! A$"$8M8M)MP &$))F6;W;W;\;\;^4_*`ac 	cN 	" 	227==?CG.) 	E	s5   B	 	C!B;:C;CCCCCc                 R   |  | t         j                  j                         v r| S 	 t         j                  | j                            S # t        t
        f$ rP t        dj                  | dj                  t        t         j                  j                                                 w xY w)a      Returns a (Micro) QR Code mode constant which is equivalent to the
    provided `mode`.

    In case the provided `mode` is ``None``, this function returns ``None``.
    Otherwise a mode constant is returned unless the provided parameter cannot
    be mapped to a valid mode. In the latter case, a :py:exc:`ValueError` is raised.

    :param mode: An integer or string or ``None``.
    :raises: :py:exc:`ValueError` In case the provided `mode` does not represent a valid
             QR Code mode.
    :rtype: int or None
    z)Illegal mode "{0}". Supported values: {1}r  )r   MODE_MAPPINGvalueslowerr  r  r)   r*   r  r  r  )r:   s    r   r-   r-     s     |tv2299;;W""4::<00n% WD &tyy8K8K8P8P8R1S'TUW 	WWs    A AB&c                    | y	 t        |       } |r)d| cxk  rdk  sn t        dj                  |             | S d| cxk  rdk  sn t        dj                  |             | S # t        $ r t        dj                  |             w xY w)a      Normalizes the (user specified) mask.

    :param mask: A mask constant
    :type mask: int or None
    :param bool is_micro: Indicates if the mask is meant to be used for a
            Micro QR Code.
    :raises: :py:exc:`ValueError` in case of an invalid mask.
    :rtype: int
    NzZInvalid data mask "{0}". Must be an integer or a string which represents an integer value.r   rV   zBInvalid data mask "{0}" for Micro QR Code. Must be in range 0 .. 3rW   z0Invalid data mask "{0}". Must be in range 0 .. 7)rs   r)   r*   )r;   r@   s     r   r5   r5     s     |k4y D}1}ahhimnoo K D}1}OVVW[\]]K  k ]]c]cdh]ik 	kks   A$ $$Bc                 
   | |st        d      | S 	 t        j                  | j                            S # t        t
        f$ r? | t        j                  j                         v r| cY S t        dj                  |             w xY w)a4      Returns a constant for the provided error level.

    This function returns ``None`` if the provided parameter is ``None`` and
    `accept_none` is set to ``True`` (default: ``False``). If `error` is ``None``
    and `accept_none` is ``False`` or if the provided parameter cannot be
    mapped to a valid QR Code error level, a :py:exc:`ValueError` is raised.

    :param error: String or ``None``.
    :param bool accept_none: Indicates if ``None`` is accepted as error level.
    :raises: :py:exc:`ValueError` in case of an invalid mode.
    :rtype: int
    z The error level must be providedzCIllegal error correction level: "{0}". Supported levels: L, M, Q, H)r)   r   ERROR_MAPPINGr  r  r  r  r*   )r8   r#   s     r   r,   r,     s     }?@@)##EKKM22n% )F((//11L^ &-) 	))s    4 1B'Bc                     t         j                  j                         D ]  \  }}|| k(  s|c S  t        dj	                  |             )z    Returns the mode name for the provided mode constant.

    :param int mode_const: The mode constant (see :py:module:`segno.consts`)
    :raises: :py:exc:`ValueError` in case of an unknown mode constant.
    :rtype: str
    Unknown mode "{0}")r   r  itemsr)   r*   )
mode_constnamer   s      r   r/   r/     sL     ((..0 	c*K )00<
==r   c                     t         j                  j                         D ]  \  }}|| k(  s|c S  t        dj	                  |             )z    Returns the error name for the provided error constant.

    :param int error_const: The error constant (see :py:module:`segno.consts`)
    :raises: :py:exc:`ValueError` in case of an unknown error correction level.
    :rtype: str
    zUnknown error level "{0}")r   r  r  r)   r*   )error_constr  r   s      r   get_error_namer    sL     ))//1 	c+K 077D
EEr   c                     d| cxk  rdk  r| S  t         j                  j                         D ]  \  }}|| k(  s|c S  t        dj	                  |             )a      Returns the version name.

    For version 1 .. 40 it returns the version as integer, for Micro QR Codes
    it returns a string like ``M1`` etc.

    :raises: :py:exc:`VersionError`: In case the `version_constant` is unknown.
    :rtype: str or int
    r   r  zUnknown version constant "{0}")r   r  r  r)   r*   )version_constr  vs      r   r+   r+   (  sd     	=2 //557 aK 5<<]K
LLr   s   ^[s   ]+\Zc                 ,    t         j                  |       S )z    Returns if the provided `data` can be encoded in "alphanumeric" mode.

    :param bytes data: The data to check.
    :rtype: bool
    )_ALPHANUMERIC_PATTERNmatchrO   s    r   is_alphanumericr  =  s     !&&t,,r   c                     t        |       }|r|dz  ryt        r	d | D        } t        |       }t        d|d      D ]:  }t	        |      dz  t	        |      z  }d|cxk  rdk  r)n d|cxk  rd	k  r7 y  y y
)zz    Returns if the `data` can be encoded in "kanji" mode.

    :param bytes data: The data to check.
    :rtype: bool
    r\   Fc              3   2   K   | ]  }t        |        y wr   r  r   cs     r   r   zis_kanji.<locals>.<genexpr>R       %1A%r  r   rW   r  r  r  r  T)rL   r  iterrM   next)rO   data_len	data_iterrS   r  s        r   is_kanjir  G  s     4yHx!|%%T
I1h" Y1$Y7$(&(Fd,Df,D -E r   c                     | j                         rt        j                  S t        |       rt        j                  S t        |       rt        j                  S t        j                  S )z    Returns the appropriate QR Code mode (an integer constant) for the
    provided `data`.

    :param bytes data: Data to check.
    :rtype: int
    )isdigitr   rc   r  rd   r  re   ra   r  s    r   r  r  [  sL     ||~"""t'''~   r   c                 :   |r|rJ |xs |du }|rt         j                  nd}|rt         j                  nd}|dk  r,t        | j                  D cg c]  }t        |       c}      }||rt         j                  }t        ||dz         D ]V  }	|#|	t         j                  k7  rt         j                  }	 t         j                  |	   |   | j                  |	||      k\  r|	c S X d}
|d}
n|rd}
t        dj                  |
            c c}w # t        $ r Y w xY w)a)      Returns the minimal (Micro) QR Code version constant for the provided input.

    :param segments: Iterable of Segment instances.
    :param error: The error correction level constant.
    :type error: int or None
    :param bool eci: Indicates if the ECI mode should be used.
    :param micro: Boolean value if a Micro QR Code should be created or ``None``
    :type micro: bool or None
    :param bool is_sa: Indicator if Structured Append is used.
    :raises: :py:exc:`ValueError` if the content does not fit into a QR Code.
    :rtype: int
    Nr   rI   z(Micro) zMicro z:Data too large. No {0}QR Code can handle the provided data)r   r3   r   r   r   find_minimum_version_for_mode
VERSION_M2rM   r4   rr   r   r  r   r*   )r>   r8   r%   r&   rj   micro_allowedmin_versionmax_versionr:   r9   help_txts              r   r2   r2   l  s0    *Ud]M'4&##!K',&##"KQ8>>Z48>Z[]''kAo6 =W(9(99((E	%%g.u59Z9Z[bdgin9oo p	 H}	
X__`hi
jj! [  		s   D	4+D	DDc                 2    | dkD  r| dz  dz   S | dz   dz  dz   S )a.      Returns the matrix size according to the provided `version`.

    Note: This function does not check if `version` is actually a valid
    (Micro) QR Code version. Invalid versions like ``41`` may return a
    size as well.

    :param int ver: (Micro) QR Code version constant.
    :rtype: int
    r   rV   r   r\   r  r   )r   s    r   r   r     s*     737R<9qA(99r   c                 *   t        | t              st        |       } 	 | j                  d      }t        r	d |D        }t        t        |      S # t        $ r< 	 | j                  d      }n&# t
        t        f$ r | j                  d      }Y nw xY wY cw xY w)zy    Calculates the parity data for the Structured Append mode.

    :param str content: The content.
    :rtype: int
    z
iso-8859-1z	shift-jisr  c              3   2   K   | ]  }t        |        y wr   r  r  s     r   r   z0calc_structured_append_parity.<locals>.<genexpr>  r  r  )	r  r  r   r   r  LookupErrorr  r
   r   )r7   rO   s     r   r   r     s     gx(g,+~~l+ %%#t  +	+>>+.D\* 	+>>'*D	++s5   A 	BA)(B) B	BBBBc                     |dkD  rdn|}	 |t         j                  |    v S # t        $ r t        dj	                  |             w xY w)aR      Returns if `mode` is supported by `version`.

    Note: This function does not check if `version` is actually a valid
    (Micro) QR Code version. Invalid versions like ``41`` may return an illegal
    value.

    :param int mode: Canonicalized mode.
    :param int or None ver: (Micro) QR Code version constant.
    :rtype: bool
    r   Nr  )r   SUPPORTED_MODESr  r)   r*   )r:   r   s     r   r.   r.     sR     '$sC<f,,T222 <-44T:;;<s	     $Ac                 N    t         j                  D ]  }t        | |      s|c S  y)z    Returns the minimum Micro QR Code version which supports the provided mode.

    :param int mode: Canonicalized mode.
    :rtype: int
    r   )r   r(   r.   )r:   r  s     r   r  r    s-     "" T1%H r   c                     d| cxk  rdk  rt         j                  S  d| cxk  rdk  rt         j                  S  d| cxk  rdk  rt         j                  S  t	        dj                  |             )z    Returns the version range for the provided version. This applies to QR Code
    versions, only.

    :param int version: The QR Code version (1 .. 40)
    :rtype: int
    r   rZ   r  r
  r	  r  zUnknown version "{0}")r   VERSION_RANGE_01_09VERSION_RANGE_10_26VERSION_RANGE_27_40r)   r*   )r9   s    r   rq   rq     su     	7R))) 	
W	r	))) 
	g		))) 

,33G<
==r   c                     	 t         j                  t        j                  |       j                     S # t
        $ r t        dj                  |             w xY w)z    Returns the ECI number for the provided encoding.

    :param str encoding: A encoding name
    :return str: The ECI number.
    z1Unknown ECI assignment number for encoding "{0}".)r   ECI_ASSIGNMENT_NUMcodecslookupr  r  r)   r*   )r<   s    r   r   r     sP    ,((x)@)E)EFF ,L &*, 	,,s	   /2 $Ac                 V    d }d }d }d }d }d }d }d }| r||||fS ||||||||fS )	u  
    Returns the data mask functions.

    ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
    Table 10 — Data mask pattern generation conditions (page 50)

    ===============     =====================   =====================================
    QR Code Pattern     Micro QR Code Pattern￼  Condition
    ===============     =====================   =====================================
    000                                         (i + j) mod 2 = 0
    001                 00                      i mod 2 = 0
    010                                         j mod 3 = 0
    011                                         (i + j) mod 3 = 0
    100                 01                      ((i div 2) + (j div 3)) mod 2 = 0
    101                                         (i j) mod 2 + (i j) mod 3 = 0
    110                 10                      ((i j) mod 2 + (i j) mod 3) mod 2 = 0
    111                 11                      ((i+j) mod 2 + (i j) mod 3) mod 2 = 0
    ===============     =====================   =====================================

    :param is_micro: Indicates if data mask functions for a Micro QR Code
            should be returned
    :return: A tuple of functions
    c                     | |z   dz  dk(  S Nr   r   r   rS   r   s     r   fn0z$get_data_mask_functions.<locals>.fn0  s    A}!!r   c                     | dz  dk(  S r  r   r  s     r   fn1z$get_data_mask_functions.<locals>.fn1  s    3w!|r   c                     |dz  dk(  S NrY   r   r   r  s     r   fn2z$get_data_mask_functions.<locals>.fn2  s    1uzr   c                     | |z   dz  dk(  S r  r   r  s     r   fn3z$get_data_mask_functions.<locals>.fn3  s    A{ar   c                 $    | dz  |dz  z   dz  dk(  S )Nr\   rY   r   r   r   r  s     r   fn4z$get_data_mask_functions.<locals>.fn4  s    Qa3&!++r   c                 (    | |z  }|dz  |dz  z   dk(  S Nr   rY   r   r   rS   r   tmps      r   fn5z$get_data_mask_functions.<locals>.fn5  s#    !ec	cAg&!++r   c                 .    | |z  }|dz  |dz  z   dz  dk(  S r  r   r  s      r   fn6z$get_data_mask_functions.<locals>.fn6"  s(    !essQw'3.!33r   c                 0    | |z   dz  | |z  dz  z   dz  dk(  S r  r   r  s     r   fn7z$get_data_mask_functions.<locals>.fn7&  s'    a%31q5A+-499r   r   )	r@   r  r  r  r   r  r  r	  r  s	            r   r4  r4    sU    2" ,,4: Cc!!S#sCc11r   c                   :    e Zd ZdZdZd Zd Zd Zd Zd Z	d
dZ
y	)rC   z    Represents a sequence of `Segment` instances.

    Note: len(segments) returns the number of Segments and not the data length;
    use segments.data_length
    r>   rw   r   c                 .    g | _         d| _        g | _        y )Nr   r  selfs    r   __init__zSegments.__init__7  s    
r   c                    | j                   r| j                   d   }|j                  |j                  k(  r|j                  |j                  k(  rt        |j                  |j                  z   |j
                  |j
                  z   |j                  |j                        }| xj                  t        |j                        z  c_        | j                   d= | j                  d= | j                   j                  |       | xj                  t        |j                        z  c_        | j                  j                  |j                         y)z:
        :param _Segment segment: Segment to add.
        r   N)
r>   r:   r<   r  rl   rg   rw   rL   r   r  )r  r   prev_segs      r   rD   zSegments.add_segment<  s    
 ==}}R(H}},1B1BgFVFV1V"8==7<<#?#+#6#69K9K#K#*<<1A1AC 3x}}#55MM"%JJrNW%3w||,,

',,'r   c                 ,    t        | j                        S r   )rL   r>   r  s    r   __len__zSegments.__len__O  s    4==!!r   c                      | j                   |   S r   )r>   r  r  s     r   __getitem__zSegments.__getitem__R  s    }}T""r   c                 ,    t        | j                        S r   )r  r>   r  s    r   __iter__zSegments.__iter__U  s    DMM""r   c                    d}|r,t        d | j                  D              }||dz  z  }||dz  z  }|r|dz  }|dkD  r|t        | j                        dz  z  }n1|t        j
                  kD  r|t        | j                        |dz   z  z  }|dkD  rt        |      n||t        fd| j                  D              z  }|| j                  z   S )Nr   c              3      K   | ]@  }|j                   t        j                  k(  r!|j                  t        j                  k7  rd  B ywr   )r:   r   ra   r<   rb   )r   r   s     r   r   z4Segments.bit_length_with_overhead.<locals>.<genexpr>\  s?      $Z''.||v7G7G'G(/(8(8F<X<X(X %& $Zs   AArV   rW   rX   rY   c              3   J   K   | ]  }t         j                  |        y wr   )r   r`   )r   r:   rh   s     r   r   z4Segments.bit_length_with_overhead.<locals>.<genexpr>l  s"     cPT::4@Kcs    #)rE  r>   rL   r   r   r3   rq   rw   )r  r9   r%   rj   rk   no_eci_indicatorsrh   s         @r   r   z!Segments.bit_length_with_overheadX  s     # $ZT]] $Z !Z )A--H)A--H HQ;DJJ!++Hv(((DJJ7Q;77H.5kM'*w	CcX\XbXbccc$//))r   NF)r   r   r   r   	__slots__r  rD   r  r  r  r   r   r   r   rC   rC   .  s,     4I
(&"##*r   rC   c                       e Zd ZdZdZd	dZ e ed            Z e ed            Z	 e ed            Z
 e ed            Zy)
r  aN      Represents a data segment.

    A segment provides the (encoding specific) byte data, the data length,
    the QR Code mode, and the used encoding. The latter is ``None`` iff mode
    is not "byte".

    Note that `data_length` may not be equal to len(data)!

    See also ISO/IEC 18004:2015(E) - 7.4.7 Mixing modes (page 30)
    r   Nc                 6    t         j                  | ||||f      S r   )r6  __new__)clsrl   rg   r:   r<   s        r   r#  z_Segment.__new__~  s    }}S4T8"DEEr   r   r   r\   rY   r   )r   r   r   r   r   r#  propertyr   rl   rg   r:   r<   r   r   r   r  r  p  sN    
 IF JqM"D*Q-(JJqM"D
1&Hr   r  c                   B    e Zd ZdZdgZddZd Zd Zd Zd Z	d Z
d	 Zy
)r   zO    Wraps a :cls:`bytearray` and provides some useful methods to add bits.
    _datac                 $    t        |      | _        y r   )r  r'  r  iterables     r   r  zBuffer.__init__  s    x(
r   c                 :    | j                   j                  |       y r   )r'  r   r)  s     r   r   zBuffer.extend  s    

(#r   c                 r    | j                   j                  fdt        t        |            D               y )Nc              3   .   K   | ]  }|z	  d z    ywr   r   r   s     r   r   z%Buffer.append_bits.<locals>.<genexpr>  s     JQ3!8q.Jr   )r'  r   r   rM   )r  r   rv   s    ` r   r   zBuffer.append_bits  s$    

J(5=2IJJr   c                     | j                   S r   r'  r  s    r   r  zBuffer.getbits  s    zzr   c                 T    d t        t        | j                        gdz  ddiD        S )z        Returns an iterable of integers interpreting the content of `seq`
        as sequence of binary numbers of length 8.
        c           	   3   n   K   | ]-  }t        d j                  t        t        |            d       / yw)r  r\   N)rs   r  r  r   )r   gs     r   r   z Buffer.toints.<locals>.<genexpr>  s&     hBGGCQK(!,hs   35rW   	fillvaluer   )r   r  r'  r  s    r   r  zBuffer.toints  s-    
 ikDDTCUXYCY6gef6ghhr   c                 ,    t        | j                        S r   )rL   r'  r  s    r   r  zBuffer.__len__  s    4::r   c                      | j                   |   S r   r/  r  s     r   r  zBuffer.__getitem__  s    zz$r   N)r   )r   r   r   r   r   r  r   r   r  r  r  r  r   r   r   r   r     s5     	I)$Ki r   r   c                        e Zd ZdZdZ fdZ e ed            Z e ed            Z	 e ed            Z
 e ed            Z xZS )r   z    Represents Structured Append information.

    Note: This class provides the Structured Append header information in
    correct order (incl. Structured Append mode indicator); cf.
    ISO/IEC 18004:2015(E) -- 8 Structured Append (page 59).
    r   c                 P    t         t        |   | t        j                  |||f      S )z        :param int number: Symbol number ``[0 .. 15]``
        :param int total: Total symbol count ``[2 .. 15]``
        :param int parity: Parity data.
        )superr   r#  r   MODE_STRUCTURED_APPEND)r$  numberr}   r~   	__class__s       r   r#  z_StructuredAppendInfo.__new__  s,     *C8v?\?\^dfkms>tuur   r   r   r\   rY   )r   r   r   r   r   r#  r%  r   r:   r:  r}   r~   __classcell__)r;  s   @r   r   r     sO     Iv JqM"Djm$FZ]#Ejm$Fr   r   )NNNNNFNT)NNNNNFTNr   r  )TT)er   
__future__r   r   operatorr   r   r   r   	functoolsr	   r
   	itertoolsr   r   r   rert   r  collectionsr   r  r   r  r   r   r  rs   r  ImportErrorr   r   r  
basestringnumbersr   unicodexrangerM   sysmaxsizer1  __all__type__metaclass__r)   r   r    r   r   r6   r   r   r   r   r   r   r   r   r   r   r  r   r5  r2  rF  r3  rp  r   r   r1   r  rE   r   r'   r-   r5   r,   r/   r  r+   compileescaper  r  r  r  r  r2   r   r   r.   r  rq   r   r4  rC   r6  r  r   r   r   r   r   <module>rO     s   1 , , % , , 	   " %HG [[ 
< 	
 	 &>? ?C=A-E` =AEI!%nKb48n:>M.&(6RD& >F(SV,^%D;%|-*
1i2XB"4;|$NB#%LiPX(V FW.6)6>FM$ #

6IBIIf6O6O,P#PS[#[\ -("#kL:*<&
>&,52p?* ?*D'u '.   @%E %U4  DBHG
CEs   
E' 'FF