
    Pf                       d 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d	l	mZ ddlZej        Z[d
Z G d de          Z edd          Z	 	 dHdZ	 	 	 dIdZdJdZdKdZdKdZ d Z!d Z"d Z#dZ$d Z%d Z&d Z'd Z(d Z)d Z*dJd Z+d! Z,d" Z-d# Z.d$ Z/d% Z0d& Z1d' Z2d( Z3d) Z4dJd*Z5dLd+Z6d, Z7d- Z8d. Z9dKd/Z:d0 Z;d1 Z<d2 Z= ej>        d3 ej?        ej@                  z   d4z             ZAd5 ZBd6 ZCd7 ZDdKd8ZEd9 ZFd: ZGd; ZHd< ZId= ZJd> ZKd? ZL G d@ dA          ZM G dB dCeN          ZO G dD dE          ZP G dF dGeN          ZQdS )MzQR 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.
    )
itemgettergtltxor)partialreduce)islicechainproductN)
namedtuple   )consts)zip_longest)encodeencode_sequenceDataOverflowErrorc                       e Zd ZdZdS )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__     ?/var/www/html/env/lib/python3.11/site-packages/segno/encoder.pyr   r      s           r   r   Codez"matrix version error mask segmentsFTc	                    t          |          }|s?|=|t          j        v r/t          d                    t          |                              |r?|=|t          j        vr/t          d                    t          |                              t          |d          }t          |          }|O|Mt          ||          s=t          d                    t          |          t          |                              |t          j
        k    r|s|t          j        v rt          d          |r|s|t          j        v rt          d          t          | ||          }	t          |	|||	          }
||
}nC|
|k    r=t          d
                    t          |          t          |
                              ||t          j        k    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
    NzJA 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   .   s1      ((G =U&7f6K+K+K 6 &!1'!:!:;;= = 	=  =$8M)M)M> &!1'!:!:;;= = 	= D999E$DG/%dG44 0G &t!4!46Fw6O6OPPR R 	R$$$%$7f>S3S3SYZZZ
 M MF$999KLLLGT844H"8U5IIIO!	7	"	" j!'(8(A(ACSTcCdCd!e!eg g 	g}F$555${H$))D8UGT3DDDr   c	                 &   fdd }		 	 ddfd}
t                    6dk     r/t          d                    t                                        n|t          d	          |d|cxk    rd
k    sn t          d          t	          d          t
          j        t                    t          d          t          |           }d}|G	 t          |d          }n# t          $ r Y nw xY w|r |p|k    rt          |p|          gS t          |j                  dk    rt          d          |j        d         t
          j        k    rt!          |           } |5t          |           |k     r"t          d                    |                    t#          |           }|pd
} |
|           }|d
k    r"t          d                                         |	| |          }|4 t%          |t                              }t          |dd          t'          t(          t          |          dz
  |          fdt+          |          D             S )z    EXPERIMENTAL: Creates a sequence of QR codes in Structured Append mode.

    :return: Iterable of named tuples, see :py:func:`encode` for details.
    c                 n    t                      }|                    t          | |                     |S )z;        Creates a Segments sequence with one item.
        )r5   r7   )Segmentsadd_segmentmake_segment)chunkr5   segsr7   s      r   one_item_segmentsz*encode_sequence.<locals>.one_item_segmentsf   s6     zze$JJJKKKr   c                      t          t                     |          \   fdt          |          D             S )Nc           	          g | ]:}|z  t          |          z   |d z   z  t          |d z             z            ;S )r   )min).0idatakms     r   
<listcomp>z?encode_sequence.<locals>.divide_into_chunks.<locals>.<listcomp>p   sM    XXXQUSAYY&A{SQ]]'BBCXXXr   )divmodlenrange)rI   numrJ   rK   s   ` @@r   divide_into_chunksz+encode_sequence.<locals>.divide_into_chunksn   sE    c$ii%%1XXXXXXUSVZZXXXXr   NFc                    d}|t           j        |         |         z  }|r*|t           j        k    r|t           j        k    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  }nn|t           j        k    r#t          | d	          \  }}	||d
z  |	rdndz   z  }n;|t           j        k    r	|| dz  z  }n"|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_NUMERICrM   MODE_ALPHANUMERIC
MODE_KANJI
MODE_HANZI)

char_count	ver_ranger5   r7   is_eciis_saoverheadbitsrP   	remainders
             r   calc_qrcode_bit_lengthz/encode_sequence.<locals>.calc_qrcode_bit_lengthr   s8   F6t<YGG 	df...8v?[3[3[MHMH 	 H6&&&#J22NCC"HY!^^;;DDV---#J22NCC"HY 5A66DDV%%%JN"DDf'):;;;JO#D$r   c                 R   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)rf   rg   rU   r      r   )rN   version_ranger   SYMBOL_CAPACITYintmathceil)r2   r4   r3   r5   lengthre   
bit_lengthcapacitycntrk   r    r7   s            r   number_of_symbols_by_versionz5encode_sequence.<locals>.number_of_symbols_by_version   s     W!'**	++FItX36dD D D
)'259$)J12233esQw'S+G2q>>aHH
49Z(2334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   )r3   r4   r6   r    r8   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!   rg   )totalparityc                 h    g | ].\  }}t           |          
 	|                     /S ))r3   r4   r6   r    r8   sa_info)r1   )rG   rH   rA   r8   r    r3   r6   r5   rC   r}   r4   s      r   rL   z#encode_sequence.<locals>.<listcomp>   sh     K K K,4Au %%eT22%3K#GAJJ( ( ( K K Kr   )NFF)r"   r$   r%   r&   r'   r   r/   r(   r0   r,   r-   r   r1   rN   modesr`   strcalc_structured_append_paritymaxr   _StructuredAppendInfo	enumerate)r2   r3   r4   r5   r6   r7   r    r8   symbol_countrQ   rw   r9   r:   sa_parity_datanum_symbolschunksrk   rC   r}   s    ```````        @@@r   r   r   ^   s       Y Y Y FJ38   25 5 5 5 5 5 5  ((GQ;; //5v6Fw6O6O/P/PR R R  
	VWWW\(?(?(?(?R(?(?(?(?DEEE D999E}$$D$///DGT844HO	*8U5QQQOO  	 	 	 D	  	J73MoNNHEG<V!%3KI I I J J
8>QWXXX>!Dv"""g,,CLL<$?$?X__`lmmnnn27;;N$"K227GUDQQR Z a abi j jkkk55F$$SS%9%9%94@@xCuDQQQ+3v;;?+- - -GK K K K K K K K K K K8A&8I8IK K K Ks   -D 
DDc                    |dk     }|du}t                      }	|}
|}|sd}
t          |          }|rt          ||| ||          }|r>|dd         D ]}|	                    |d           |	                    |j        d           | D ]}t          |	||
||           t          j        |         |         }t          |	||
t          |	                     t          |	|t          |	                     t          |	||t          |	                     t          |||	          }	t          |          }|}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rg   rV   rS   rT   )Bufferrn   boost_error_levelappend_bitsr{   write_segmentr   ro   write_terminatorrN   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   )r9   r3   r4   r6   r    r8   r}   r;   sa_modebuffverre   rH   segmentru   widthheightmatrixs                     r   r1   r1      s    {HT!G88D
CI +!'**	 P!'5(CwOOO ,! 	# 	#AQ""""+++ : :dGS)S9999%g.u5HT8S#d))444tWc$ii000gxT;;;gud33DW%%EF''Fv...65&111&$((( ,FE64HHLD&FGUD111VW%%%h777r   c                    |t           j        dfvrt          |          dk    rt           j        t           j        t           j        t           j        g}| dk     r8|                                 | t           j        k     r|                                 |                    | ||          }||	                    |          dz   d         D ]!}t           j
        |          |         |k    r|}! |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   r+   rN   r/   ERROR_LEVEL_MERROR_LEVEL_Qpop
VERSION_M4bit_length_with_overheadindexro   )r4   r3   r9   r    rg   levelsdata_lengtherror_levels           r   r   r     s     V)4000S]]a5G5G&(<&(<>Q;;JJLLL***

77E7RR!&,,u"5"5"9":":; 	 	K%g.{;{JJ#Lr   c                    |j         }| j        }|rY|t          j        k    rI|j        t          j        k    r4 |t          j        d            |t          |j                  d           |+ ||d           |t          j        k    rd} ||d           n/|t          j	        k    r |t          j
        |         |dz               ||j        t          j        |         |                    |                     |j                   dS )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.
    rS   rT   Nr   rV   )r5   r   r   r^   r7   r_   MODE_ECIget_eci_assignment_numberrc   r.   MODE_TO_MICRO_MODE_MAPPINGrd   r]   extendri   )r   r   r   re   r    r5   r   subsets           r   r   r   "  s    <D"K
 Dtv''' F$@@@FOQ'''-g.>??CCC
{D!6$$$FK"""	v 	 	 F5d;S1WEEEK"248CE E EKKr   c                 z    |                      dgt          ||z
  t          j        |                   z             dS )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   rF   r   TERMINATOR_LENGTH)r   ru   r   rs   s       r   r   r   A  s:     	KKc(V+V-Ec-JKKKLLLLLr   c                 |    |t           j        t           j        fvr!|                     dgd|dz  z
  z             dS dS )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   rT   N)r   r.   
VERSION_M3r   )r   r4   rs   s      r   r   r   O  sJ     v(&*;<<<QC1
+,----- =<r   c                     | j         }|t          j        t          j        fv r |dg||z
  z             dS d}t	          |dz  |dz  z
            D ]} |||dz                      dS )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   rT   rY   N)r   r   r.   r   rO   )r   r4   ru   rs   writepad_codewordsrH   s          r   r   r   b  s    $ KE6$f&7888qcX&'(((((Lx1}v{233 	( 	(AE-A&''''	( 	(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   c                    ||k    }ddt          |           dz
  fdf}|r|dk     rd}t          d          }|D ]J\  }}|dk    rdnd}|dk    rdnd}	|D ].}
t          ||
z            |	|	dz            | ||
z            ||dz   <   /KdS )	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 tuple(int, int) matrix_size: Tuple of width and height of the matrix.
    r   r   r   rT   )r      )r   r   N)rN   rO   _FINDER_PATTERN)r   r   r   	is_squarecornersfinder_rangerH   joffset	sepoffsetrs              r   r   r     s     I3v;;?+W5G URZZ88L Z Z11ff!aAAQ	 	Z 	ZA%4VaZ%@9WX=AX%YF1q5M!AE'""	ZZ Zr   c                     |rdt          |           fndt          |           dz
  f\  }}| |         }d}t          d|          D ]}|| |         |<   |||<   |dz  }dS )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[   rT   r   N)rN   rO   )r   r;   r   stopcolbitrH   s          r   add_timing_patternr     s     #+Dq#f++CKK!O0DGAt
)C
C1d^^  q	!As
 r   c                 Z   ||k    }|dz
  dz  }|r|dk     rdS d}t           j        |dz
           }t          d          }|d         }|d         }	||f||	f|	|ff}
t          |d	          D ]?\  }}||f|
v r|dz
  |dz
  }}|D ]&}||dz  |dz  dz            | ||z            ||dz   <   '@dS )
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.
       rS   rY   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_POSrO   r   )r   r   r   r   r4   pattern	positionsalignment_rangemin_posmax_posfinder_positionsxyrH   r   r   s                   r   r   r     s    IrzaG Wq[[(G
 $Wq[1IAhhOlGmG '*Wg,>'@RS	!,,, > >1q6%%%1ua!e1  	> 	>A%,QU1q519_%=F1q5M!AE'""	>> >r   c                 L   t          |           }|dk     }|t          j        t          j        fvrdnd}d}t          |          }t	          d          }t	          |dz
  dd          D ]x}	|s|	dk    r|	dz  }	t	          |          D ]Y}
|D ]T}|	|z
  }|	|z   dz  dk    }|s	||dk     z  }|r|dz
  |
z
  n|
}| |         }||         dk    r||k     r||         ||<   |dz  }UZy|t          |          k    r0t          d                    |t          |                              dS )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   rY   r[   zMInternal error: Adding codewords to matrix failed. Added {0} of {1} codewordsN)rN   r   r.   r   rO   r$   r%   )r   	codewordsr4   matrix_sizer;   incidxcodeword_length	range_tworightverticalzr   upwardsrH   rows                   r   r   r     s    f++K{H v0&2CDDD!!!C
C )nnOaI{Q2..   	EQJJQJEk** 
	 
	H 	 	AI!CK1,2 %q1u$G4;I[1_x//Qiq6S==S?%:%:&s^CF1HC	
	 c)nn 66<fS#i..6Q6QS S 	S r   c                    dd}t           j        |          |         }t          ||          \  }}d}| t           j        t           j        fv r( ||d                             d          dz	  d          }t                      }|                    t          t          |d t          j
        t          |           D                                   ||                    |           |                    t          t          |d t          j
        t          |           D                                   d}	| d	v rd
}	n| dv rd}	n| dv rd}	|                    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.
    rT   c                 T      fdt          t          |                    D             S )Nc              3   (   K   | ]}|z	  d z  V  dS r   Nr   rG   rH   vals     r   	<genexpr>z8make_final_message.<locals>.to_binary.<locals>.<genexpr>  s+      @@1Q@@@@@@r   )reversedrO   )r   rs   s   ` r   	to_binaryz%make_final_message.<locals>.to_binary  s+    @@@@v(?(?@@@@r   Nr   r   rS   c              3      K   | ]}||V  	d S Nr   rG   r   s     r   r   z%make_final_message.<locals>.<genexpr>  s(      %q%qAcdcpacpcpcpcp%q%qr   c              3      K   | ]}||V  	d S r   r   r   s     r   r   z%make_final_message.<locals>.<genexpr>  s(      %r%rAdedqadqdqdqdq%r%rr   )rY   rV   rS   r   r[   rX   )      rx   r         rU                   !   "   rV   )r                         )rT   )r   ECCmake_blocksr.   r   r   r   r   r
   mapfrom_iterabler   )
r4   r3   r   r   ec_infosdata_blockserror_blockscw_fourresrj   s
             r   r   r     s   A A A A z'"5)H +Hd ; ;KG6$f&7888
 )KN..r22a7;;
((CJJuc)%q%q1D[R]E^1_1_%q%q%qrrsttt

7JJuc)%r%r1D[R^E_1`1`%r%r%rsstuuu I/!!			L	L	L			0	0	0	JJuy !!!Jr   c                    |                                 }g g }}|j        }|j        }t          j        }t          j        }| D ]}	|	j        |	j        z
  }
t          j        |
         }t          |
          }t          |	j	                  D ]}t          t          ||	j                            } ||           t          |          }t          |          }|                    dg|
z             t          |          D ]B}||         }|dk    r2||         }|D ]'}|||z   dz   xx         ||||         z            z  cc<   (C |||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_POLYrO   
num_blocks	bytearrayr	   rN   r   )r  r   r   r  r  append_data_blockappend_error_blockgen_loggen_expec_infonum_error_wordsgenrange_error_wordsrH   blocklen_dataerror_blockrJ   coeflcoefns                        r   r  r  1  s    I "BK#*%,GG 7 7!+g.>>oo.!/22w)** 	7 	7AfY0@AABBEe$$$5zzH#E**Ks_45558__ J J"1~199#DME. J J#AEAI...'%#a&.2II....{89956666	7 $$r   c                    t           }t          }t          }||k    o|dk     }|rt          }d}t          }t          ||          t          ||           t          ||           |sdd         d<   fd}t          |          }	|t          | |	|         |||           || fS d}
t          |	          D ]P\  }}d | D             }t          |||||            ||||          } |||          r|}|}t          |          }
Q||
fS )	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 tuple(int, int) matrix_size: Tuple of width and height of the matrix.
    :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   r   rT   c                 (    |          |         dk    S )Nr   r   )rH   r   function_matrixs     r   is_encoding_regionz4find_and_apply_best_mask.<locals>.is_encoding_regiony  s    q!!$s**r   Nc                 "    g | ]}|d d          S r   r   )rG   bas     r   rL   z,find_and_apply_best_mask.<locals>.<listcomp>  s     $$$rRU$$$r   )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_maskr;   r+  mask_patternsbest_matrixmask_numbermask_patternrK   scorebest_patternr*  s                   @r   r   r   S  s{   & I#JI-52:H ( 	
'	 "%00O777?E6::: %!$A+ + + + + ,H55M 6=7%	' 	' 	'f$$K%.}%=%= 	# 	#!\$$V$$$1lE63EFFF 	!UF++9UJ'' 	#J&L((K$$r   c           	          t          |          }t          |          D ]5}| |         }|D ](} |||          r||xx          |||          z  cc<   )6dS )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)rO   )	r   r;  r   r   r+  width_rangerH   r   r   s	            r   r2  r2    s     ,,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   r   s      r   r/  r/    s     {65&11222r   c                    t          d          fd}d}d}d}||k    sJ |t                    }d}d}	t                    }
|D ]}| |         }d}d}d}d}|D ]}||         }| |         |         }||
|<   ||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  }|}|}|}	| ||          z  }| ||
          z  }|dk    r||dz
  z  }|dk    r||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}|                                }|dk    r|dz   }|ddz
  fv slt          | t          |dz
  d          t          |                             r6t          | t          |d          t          |dz                                s|dz  }n|dz   }|                      |          }|dk    |S )Nr   r   rX   rS   (   )findanyr   rF   )seqcountr   r   
n3_patternqr_sizes       r   n3_pattern_occurrencesz+mask_scores.<locals>.n3_pattern_occurrences  s    hhz""Rii1WFq'A+&&&s3sQw??3sG3D3D#DEFF 's3vq>>#fqj'2J2J#JKLL '  q((:v..C Rii r   r   Nr   r   r   rY   rV   rW   d   2   )r  rO   floatrp   abs)r   r   r   rL  score_n1score_n2score_n3qr_module_rangedark_module_counterlast_row	n3_columnrH   r   row_prev_bitcol_prev_bitn1_row_countern1_col_counterr   row_current_bitcol_current_bitpercentscore_n4rJ  rK  s                         @@r   rB  rB    sa   > >??J     & HHHF????GGnnOH'""I '+ '+Qi  	+ 	+A!!fO$QilO*IaL?2,..!#!Q&& 22H!",..!#!Q&& 22H!" A /\"c"c"c"cXa["c"c"c"cT\]^ab]bTc"c"c"c"c"cA*L*LL**3///**9555Q**HQ**H'((GqL9GCGcMB.//!3444HXx11r   c                      t          d|          } d         t           fd|D                       }t          fd|D                       }||k    r|dz  |z   n|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   c              3   4   K   | ]}|         d          V  dS )r   Nr   )rG   rH   r   s     r   r   z&evaluate_micro_mask.<locals>.<genexpr>*  s+      33vay}333333r   c              3   (   K   | ]}|         V  d S r   r   )rG   rH   rV  s     r   r   z&evaluate_micro_mask.<locals>.<genexpr>+  s'      11qx{111111r   rx   )rO   rA  )r   r   r   module_rangesum1sum2rV  s   `     @r   r0  r0    s     E??LbzH3333l33333D1111L11111D#t||4"9tT1AAr   c                    |}| dk    rT|t           j        k    r|dz  }n+|t           j        k    r|dz  }n|t           j        k    r|dz  }t           j        |         }n0|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   rT   rx   r  rY   )r   r/   r+   r   FORMAT_INFOERROR_LEVEL_TO_MICRO_MAPPINGFORMAT_INFO_MICRO)r4   r3   r;  fmtformat_infos        r   calc_format_inforl  /  s     C{{F(((4KCCf***4KCCf***4KC(-v27;EBaGG.s3r   c                 H   |dk     }t          |||          }t          |          }|}| d         }t          d          D ]R}	||	z	  dz  }
|d|	z
  z	  dz  }|	dk    r	|s|dz  }d}|
| |	|z            d<   |||	|z   <   |s|
|d|	z
  <   || d|	z
           d<   S|sd| d         d<   dS dS )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   rT   r   r[   r   r   N)rl  rp   rO   )r   r4   r3   r;  r;   rk  voffsethoffset	row_eightrH   vbithbits               r   r   r   I  s    J {H"7E<@@K(mmGGq	I1XX % %q D(Q'4/66(6qLGG!%q7{A!%	!g+ 	% $Ib1f $F26N1 r
1 r   c                 "   |dk     rdS t           j        |dz
           }t          d          D ]a}||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	<   bdS )
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)
    rX   Nr[   rV   r   rY   )r   VERSION_INFOrO   )r   r4   version_inforH   bit1bit2bit3r   s           r   r   r     s    * {{&w{3L1XX  Q'4/!a%1-5!a%1-5sAsAr
1QiCCB r   c                    t                      }|j        }t          | t          t          t
          f          r |t          | ||                     |S | D ]y}|||}}}t          |t                    rB|d         }t          |          dk    r
|d         p|}t          |          dk    r
|d         p|} |t          |||                     z|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   rY   )	r>   r?   
isinstancer   bytesrp   r@   r3  rN   )	r2   r5   r7   r9   r?   itemseg_contentseg_modeseg_encodings	            r   r,   r,     s      zzH&K'C,-- L$99::: G G.2D(|XdE"" 	3q'K4yy1}}7?d4yy1}}#Aw2(LhEEFFFFOr   c                    t          | t                    r| t          |           |pt          j        fS t          |           } ||                     |          } n}	 t          j        }|                     |          } nZ# t          $ rM 	 t          j        }|                     |          } n'# t          $ r d}|                     |          } Y nw xY wY nw xY w| t          |           |fS )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
    Nutf-8)	r}  r~  rN   r   r_   r   r   UnicodeErrorKANJI_ENCODING)rI   r7   s     r   data_to_bytesr    s     $ ISYY HF,HHHt99D{{8$$	-3H;;x((DD 	- 	- 	--!0{{8,, - - -"{{8,,-	- TH$$s6   !A> >
C	!B+*C+!CCCCCc           	         |t           j        k    rt           j        }t          | |          \  }}}|}|t           j        k    rt          |          nt           j        }|R||k     rKt          d                    t          |          t          |          t          |                              n|}|t           j        k    rd}|t           j
        t           j        fvr|n|dz  }t                      }	|	j        }
|t           j        k    rOt          d|d          D ];}|||dz            } |
t          |          t!          |          dz  dz              <n|t           j        k    rt           j        j        }t          d|d          D ]h}|||dz            }t!          |          dk    r1 |
 ||d                   dz   ||d                   z   d           S |
 ||          d	           inV|t           j        k    r|D ]} |
|d
           n3|t           j        k    rt          d|d          D ]}||         d
z  ||dz            z  }d|cxk    rdk    r	n n|dz
  }n8d|cxk    rdk    r	n n|dz
  }n"t          d                    |                     |
|d
z	  dz  |dz  z   d           nt          d|d          D ]}||         d
z  ||dz            z  }d|cxk    rdk    r	n n|dz
  }n8d|cxk    rdk    r	n n|dz
  }n"t          d                    |                     |
|d
z	  dz  |dz  z   d           t)          |	                                |||          S )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}rY   r   rV   r   -   rZ   r[   rT   i  i  i  i  i  zInvalid Hanzi bytes: {0}`      r\   @    @    i@  zInvalid Kanji bytes: {0}   )r   rc   HANZI_ENCODINGr  r^   	find_moder$   r%   r*   reprrb   r   r   r`   rO   rp   rN   ra   ALPHANUMERIC_CHARSrF  _Segmentgetbits)rI   r5   r7   segment_datasegment_lengthsegment_encodingsegment_modeguessed_moderd   r   r   rH   rA   to_bytebcodediffs                    r   r@   r@     sW    v   (5B45R5R2L."2L
 /;f>N.N.N9\***TZTdL,&&_$f]<%@%@%),%7%7%2<%@%@B BC C C ' $v'''#/8I6K\7]#]#]cquvcvJ88D"Kv*** q.!,, 	8 	8A 1q5)EKE

CJJNQ$67777	8 
1	1	1+0q.!,, 	/ 	/A 1q5)E 5zzA~~GGE!H--2WWU1X5F5FFKKKK
 GGENNA....	/ 
)	)	) 	 	AK1		*	*	* q.!,, 	B 	BA Oq(LQ,??D''''''''' f}4))))6))))) f} !;!B!B4!H!HIII K$!)t+t<bAAAA	B$ q.!,, 	B 	BA Oq(LQ,??D''''''''' f}4))))6))))) f} !;!B!B4!H!HIII K$!)t+t<bAAAADLLNNJ>NOOOr   c                   	 | |k    }|o| dk     }dg| z  	t          	fdt          |          D                       }|r|rP| dk    rJt          d          D ]:}||         	d	d<   d	d<   d	d	<   d|d         |<   d|d         |<   d|d	         |<   ;|d
         }t          d          D ]&}d||         d
<   d||<   |s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   rY   c              3   6   K   | ]}t                    V  d S r   )r  )rG   rH   r   s     r   r   zmake_matrix.<locals>.<genexpr>j  s)      99a9S>>999999r   )   r[   r   rt  ru  rv  rT   	   )r3  rO   r   )
r   r   reserve_regions
add_timingr   r;   r   rH   rp  r   s
            @r   r   r   [  s=    I'URZH%%-C99995==99999F $ 	$1XX 	$ 	$QiCCB!$sA!$sA #r
11I	q 	$ 	$AF1IaLIaL $ #r
1 #	1" -68,,,Mr   c                    | dS d}	 t          |           } | dk     }nV# t          t          f$ rB 	 t          j        |                                          } n# t          t          f$ r d}Y nw xY wY nw xY w|sd| cxk     rdk     son | t          j        vr_t          d	                    | d
                    t          t          j                                                                                | S )	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, )rp   r$   	TypeErrorr   MICRO_VERSION_MAPPINGupperKeyErrorAttributeErrorr#   r%   joinsortedkeys)r4   r3   s     r   r"   r"     s   " tEg,,!	"   	27==??CGG.) 	 	 	EEE	
  cA$$$$"$$$$8M)M)MP &$))F6;W;\;\;^;^4_4_*`*`aac c 	cNs2    A1$AA1A+(A1*A++A10A1c                 |   |  | t           j                                        v r| S 	 t           j        |                                          S # t          t
          f$ r` t          d                    | d                    t          t           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
    Nz)Illegal mode "{0}". Supported values: {1}r  )r   MODE_MAPPINGvalueslowerr  r  r$   r%   r  r  r  )r5   s    r   r(   r(     s     |tv299;;;;W"4::<<00n% W W WD &tyy8K8P8P8R8R1S1S'T'TUUW W 	WWs   #A
 
A1B;c                 Z   | dS 	 t          |           } n0# t          $ r# t          d                    |                     w xY w|r2d| cxk    rdk     s$n t          d                    |                     n1d| cxk    rdk     s$n t          d                    |                     | S )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   rS   zBInvalid data mask "{0}" for Micro QR Code. Must be in range 0 .. 3rT   z0Invalid data mask "{0}". Must be in range 0 .. 7)rp   r$   r%   )r6   r;   s     r   r0   r0     s     |tk4yy k k k ]]c]cdh]i]ik k 	kk  ^D}}}}1}}}}ahhimnnooo  D}}}}1}}}}OVVW[\\]]]Ks	    -Ac                 ,   | |st          d          | S 	 t          j        |                                          S # t          t
          f$ rG | t          j                                        v r| cY S t          d                    |                     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
    Nz The error level must be providedzCIllegal error correction level: "{0}". Supported levels: L, M, Q, H)r$   r   ERROR_MAPPINGr  r  r  r  r%   )r3   r   s     r   r'   r'     s     } 	A?@@@)#EKKMM22n% ) ) )F(//1111LLL^ &--) ) 	))s   #; 3B0#Bc                     t           j                                        D ]\  }}|| k    r|c S t          d                    |                     )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*     s\     (..00  	c*KKK 
)00<<
=
==r   c                     t           j                                        D ]\  }}|| k    r|c S t          d                    |                     )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    s\     )//11  	c+KKK 
077DD
E
EEr   c                     d| cxk     rdk     rn n| S t           j                                        D ]\  }}|| k    r|c S t          d                    |                     )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&     s     	=2/5577  aKKK 
5<<]KK
L
LLr   s   ^[s   ]+\Zc                 6    t                               |           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rI   s    r   is_alphanumericr  '  s     !&&t,,,r   c                    t          |           }|r|dz  rdS t          |           }t          d|d          D ]E}t          |          dz  t          |          z  }d|cxk    rdk    sn d|cxk    rdk    sn  dS Fd	S )
zz    Returns if the `data` can be encoded in "kanji" mode.

    :param bytes data: The data to check.
    :rtype: bool
    rY   Fr   rT   r  r  r  r  T)rN   iterrO   next)rI   data_len	data_iterrH   r  s        r   is_kanjir  1  s     4yyH x!| uT

I1h""  Y1$Y7$((((&((((Fd,D,D,D,Df,D,D,D,D554r   c                     |                                  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   r`   r  ra   r  rb   r^   r  s    r   r  r  C  sV     ||~~ #""t (''~~ !  r   c                    |r|rJ |p|du }|rt           j        nd}|rt           j        nd}|dk     rt          d | j        D                       }||rt           j        }t          ||dz             D ]f}||t           j        k    rt           j        }	 t           j        |         |         | 	                    |||          k    r|c S W# t          $ r Y cw xY wd}	|d}	n|rd}	t          d                    |	                    )	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   rE  c                 ,    g | ]}t          |          S r   )find_minimum_version_for_mode)rG   r5   s     r   rL   z find_version.<locals>.<listcomp>g  s!    ZZZ48>>ZZZr    z(Micro) zMicro z:Data too large. No {0}QR Code can handle the provided data)r   r.   r   r   r~   
VERSION_M2rO   r/   ro   r   r  r   r%   )
r9   r3   r    r!   rg   micro_allowedmin_versionmax_versionr4   help_txts
             r   r-   r-   T  sU    *Ud]M'4;&##!K',4&##"KQZZ8>ZZZ[[]'kAo66  =W(999(E	%g.u59Z9Z[bdgin9o9ooo p 	 	 	D	H}	 
X__`hii
j
jjs   2C
CCc                 4    | dk    r| dz  dz   n
| 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   rS   r   rY   r  r   )r   s    r   r   r   z  s+     7737R<<qA(99r   c                 H   t          | t                    st          |           } 	 |                     d          }nS# t          $ rF 	 |                     d          }n,# t          t          f$ r |                     d          }Y nw xY wY nw xY wt          t          |          S )zy    Calculates the parity data for the Structured Append mode.

    :param str content: The content.
    :rtype: int
    z
iso-8859-1z	shift-jisr  )r}  r   r   r  LookupErrorr   r   )r2   rI   s     r   r   r     s     gs## g,,+~~l++ + + +	+>>+..DD\* 	+ 	+ 	+>>'**DDD	++
 #ts3   < 
BAB&BBBBBc                     |dk    rdn|}	 |t           j        |          v S # t          $ r# t          d                    |                     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%   )r5   r   s     r   r)   r)     se     ''$$sC<f,T222 < < <-44T::;;;<s	     -Ac                 L    t           j        D ]}t          | |          r|c S dS )z    Returns the minimum Micro QR Code version which supports the provided mode.

    :param int mode: Canonicalized mode.
    :rtype: int
    r   )r   r#   r)   )r5   r  s     r   r  r    s;     "  T1%% 	HHH	1r   c                     d| cxk     rdk     rn nt           j        S d| cxk     rdk     rn nt           j        S d| cxk     rdk     rn nt           j        S t	          d                    |                     )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   rW   r  r  r  r  zUnknown version "{0}")r   VERSION_RANGE_01_09VERSION_RANGE_10_26VERSION_RANGE_27_40r$   r%   )r4   s    r   rn   rn     s     	7R))	
W				r					))	g									))
,33G<<
=
==r   c                     	 t           j        t          j        |           j                 S # t
          $ r# t          d                    |                     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%   )r7   s    r   r   r     s_    ,(x)@)@)EFF , , ,L &**, , 	,,s	   (+ -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   rH   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 NrV   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 )NrY   rV   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   rV   r   r   rH   r   tmps      r   fn5z$get_data_mask_functions.<locals>.fn5  s#    !ec	cAg&!++r   c                 0    | |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                 2    | |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   r1  r1    s    2" " "         , , ,, , ,4 4 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
d
S )r>   z    Represents a sequence of `Segment` instances.

    Note: len(segments) returns the number of Segments and not the data length;
    use segments.data_length
    r9   rt   r~   c                 0    g | _         d| _        g | _        d S )Nr   r  selfs    r   __init__zSegments.__init__  s    


r   c                    | j         r| j         d         }|j        |j        k    rx|j        |j        k    rht          |j        |j        z   |j        |j        z   |j        |j                  }| xj        t          |j                  z  c_        | j         d= | j        d= | j         	                    |           | xj        t          |j                  z  c_        | j        	                    |j                   dS )z:
        :param _Segment segment: Segment to add.
        r   N)
r9   r5   r7   r  ri   rd   rt   rN   r~   r  )r  r   prev_segs      r   r?   zSegments.add_segment"  s    
 = 		#}R(H},,1BgFV1V1V"8=7<#?#+#69K#K#*<1AC C 3x}#5#55M"%JrNW%%%3w|,,,
','''''r   c                 *    t          | j                  S r   )rN   r9   r   s    r   __len__zSegments.__len__5  s    4=!!!r   c                     | j         |         S r   )r9   r  r  s     r   __getitem__zSegments.__getitem__8  s    }T""r   c                 *    t          | j                  S r   )r  r9   r   s    r   __iter__zSegments.__iter__;  s    DM"""r   Fc                    d}|r.t          d | j        D                       }||dz  z  }||dz  z  }|r|dz  }|dk    r|t          | j                  dz  z  }n-|t          j        k    r|t          | j                  |dz   z  z  }|dk    rt          |          n||t          fd| j        D                       z  }|| j        z   S )Nr   c              3   n   K   | ]0}|j         t          j        k    r|j        t          j        k    ,d V  1dS r   )r5   r   r^   r7   r_   )rG   r   s     r   r   z4Segments.bit_length_with_overhead.<locals>.<genexpr>B  sR       $Z $Z''.|v7G'G'G(/(8F<X(X(X %&(X(X(X(X$Z $Zr   rS   rT   rU   rV   c              3   H   K   | ]}t           j        |                  V  d S r   )r   r]   )rG   r5   re   s     r   r   z4Segments.bit_length_with_overhead.<locals>.<genexpr>R  s1      ccPT:4@Kccccccr   )rA  r9   rN   r~   r   r.   rn   rt   )r  r4   r    rg   rh   no_eci_indicatorsre   s         @r   r   z!Segments.bit_length_with_overhead>  s    	. # $Z $ZT] $Z $Z $Z !Z !Z )A--H)A--H 	 HQ;;DJ!++HHv(((DJ7Q;77H.5kkM'***w	CccccX\Xbcccccc$/))r   NF)r   r   r   r   	__slots__r  r?   r  r	  r  r   r   r   r   r>   r>     s          4I  
( ( (&" " "# # ## # #* * * * * *r   r>   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dS )
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                 @    t                               | ||||f          S r   )r3  __new__)clsri   rd   r5   r7   s        r   r  z_Segment.__new__d  s    }}S4T8"DEEEr   r   r   rY   rV   r   )r   r   r   r   r  r  propertyr   ri   rd   r5   r7   r   r   r   r  r  V  s        
 
 IF F F F 8JJqMM""D**Q--((J8JJqMM""Dx

1&&HHHr   r  c                   D    e Zd ZdZdgZddZd Zd Zd Zd Z	d	 Z
d
 ZdS )r   zO    Wraps a :cls:`bytearray` and provides some useful methods to add bits.
    _datar   c                 .    t          |          | _        d S r   )r  r  r  iterables     r   r  zBuffer.__init__s  s    x((


r   c                 :    | j                             |           d S r   )r  r   r  s     r   r   zBuffer.extendv  s    
(#####r   c                     | j                             fdt          t          |                    D                        d S )Nc              3   (   K   | ]}|z	  d z  V  dS r   r   r   s     r   r   z%Buffer.append_bits.<locals>.<genexpr>z  s+      JJQ3!8q.JJJJJJr   )r  r   r   rO   )r  r   rs   s    ` r   r   zBuffer.append_bitsy  sB    
JJJJ(5==2I2IJJJJJJJJr   c                     | j         S r   r  r   s    r   r  zBuffer.getbits|  s
    zr   c                 Z    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      K   | ]:}t          d                     t          t          |                    d          V  ;dS )r  rY   N)rp   r  r	  r   )rG   gs     r   r   z Buffer.toints.<locals>.<genexpr>  s@      hhBGGCQKK((!,,hhhhhhr   rT   	fillvaluer   )r   r  r  r   s    r   r  zBuffer.toints  s:    
 ihkDDTDTCUXYCY6gef6g6ghhhhr   c                 *    t          | j                  S r   )rN   r  r   s    r   r  zBuffer.__len__  s    4:r   c                     | j         |         S r   r   r  s     r   r	  zBuffer.__getitem__  s    z$r   N)r   )r   r   r   r   r  r  r   r   r  r  r  r	  r   r   r   r   r   m  s          	I) ) ) )$ $ $K K K  i i 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                 r    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  numberrz   r{   	__class__s       r   r  z_StructuredAppendInfo.__new__  s5     *C0088v?\^dfkms>tuuur   r   r   rY   rV   )r   r   r   r   r  r  r  r   r5   r+  rz   r{   __classcell__)r,  s   @r   r   r     s          Iv v v v v 8JJqMM""DXjjmm$$FHZZ]]##EXjjmm$$FFFFFr   r   )NNNNNFNT)NNNNNFTNr   r  )TT)Rr   operatorr   r   r   r   	functoolsr   r   	itertoolsr	   r
   r   rerq   r  collectionsr   r  r   r   sysmaxsizer.  __all__r$   r   r   r   r   r1   r   r   r   r   r   r   r   r   r   r   r   r  r   r2  r/  rB  r0  rl  r   r   r,   r  r@   r   r"   r(   r0   r'   r*   r  r&   compileescaper  r  r  r  r  r-   r   r   r)   r  rn   r   r1  r>   r3  r  r   r   r   r   r   <module>r8     s    - , , , , , , , , , , , % % % % % % % % , , , , , , , , , , 				   " " " " " "       ! ! ! ! ! ! 



[ 
<	 	 	 	 	
 	 	 	 z&>?? ?C=A-E -E -E -E` =AEI!%nK nK nK nKb38 38 38 38l   :   >M M M. . .&( ( (8BZ Z Z2  &> > >D(S (S (SV, , ,^% % %D;% ;% ;% ;%|- - -(
3 
3 
3i2 i2 i2XB B B"  4; ; ;|$ $ $N  B#% #% #%LcP cP cP cPL( ( ( (V     FW W W.  6) ) ) )6> > >F F FM M M$ #
6IBIf6O,P,P#PS[#[\\ - - -  $  "#k #k #k #kL: : :  &< < <&
 
 
> > >&, , ,52 52 52p?* ?* ?* ?* ?* ?* ?* ?*D' ' ' ' 'u ' ' '.               @% % % % %E % % % % %r   