
    1yi                       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	 	 dFdZ	 	 dGdZdHdZdIdZdIdZ d Z!d Z"d Z#dZ$d Z%d Z&d Z'd Z(d Z)d Z*dHdZ+d Z,d  Z-d! Z.d" Z/d# Z0d$ Z1d% Z2d& Z3d' Z4dHd(Z5dJd)Z6d* Z7d+ Z8d, Z9dId-Z:d. Z;d/ Z<d0 Z= ej|                  d1 ej~                  ej                        z   d2z         ZAd3 ZBd4 ZCd5 ZDdId6ZEd7 ZFd8 ZGd9 ZHd: ZId; ZJd< ZKd= ZL G d> d?      ZM G d@ dAeN      ZO G dB dC      ZP G dD dEeN      ZQy)KzQR 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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__     M/var/www/api/v1/venv_fitandmore/lib/python3.12/site-packages/segno/encoder.pyr   r      s    r   r   Codez"matrix version error mask segmentsc	                 ,   t        |      }|s,|*|t        j                  v rt        dt	        |       d      |r,|*|t        j                  vrt        dt	        |       d      t        |d      }t        |      }|2|0t        ||      s$t        dt        |       dt	        |       d      |t        j                  k(  r|s|t        j                  v rt        d	      |r|s|t        j                  v rt        d
      t        | ||      }	t        |	|||      }
||
}n(|
|kD  r#t        dt	        |       d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
    zA Micro QR Code version ("z-") is provided but parameter "micro" is FalsezIllegal Micro QR Code version ""Taccept_nonezMode "z" is not available in version "z>Error correction level "H" is not available for Micro QR Codesz0The ECI mode is not available for Micro QR Codesecimicroz-The provided data does not fit into version "z"Proposal: version r   )normalize_versionr   MICRO_VERSIONS
ValueError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56Fw6O5P QF F G 	G$8M8M)M:;KG;T:UUVWXX D9E$DG/%dG46-"5!66UVfgnVoUppqrss$$$%7f>S>S3SYZZ
F$9$99KLLGT84H"8U5IO!	7	""OP`ahPiOj k55Eo5V4W!Y Z 	Z}F$5$55$${H$)D8UGT3DDr   c	                 ^   fd}	d }
	 	 ddfd}t        |      }||dk  r%t        dt        |       d	      |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| d      t!        |       }|xs d}| || |||      }|dkD  rt        d|        |
| |      }|( |	t#        |t              |      }t        ||dd      }t%        t&        t        |      dz
  |      }t)        |      D cg c]$  \  }}t         |	||      |||| ||            & c}}S # t        $ r Y Yw 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.
        )r5   r7   )Segmentsadd_segmentmake_segment)chunkr5   segsr7   s      r   one_item_segmentsz*encode_sequence.<locals>.one_item_segmentsa   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_chunksi   s`    c$i%1MRSVZXZQUSAY&A{SQ]'BCZ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_NUMERICrF   MODE_ALPHANUMERIC
MODE_KANJI
MODE_HANZI)

char_count	ver_ranger5   r7   is_eciis_saoverheadbitsrK   	remainders
             r   calc_qrcode_bit_lengthz/encode_sequence.<locals>.calc_qrcode_bit_lengthm   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)rd   re   rS   r      r   )rG   version_ranger   SYMBOL_CAPACITYintmathceil)r2   r4   r3   r5   lengthrc   
bit_lengthcapacitycntri   r!   r7   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   zAThis function does not accept Micro QR Code versions. Provided: "r   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   z2The content is not long enough to be divided into z symbolsz5The data does not fit into Structured Append version )key)r!   r"   re   )totalparity)r3   r4   r6   r!   r8   sa_info)NFF)r#   r%   r&   r'   r   r/   r(   r0   r,   r-   r   r1   rG   modesr^   strcalc_structured_append_paritymaxr   _StructuredAppendInfo	enumerate)r2   r3   r4   r5   r6   r7   r!   r8   symbol_countrC   rO   ru   r9   r:   sa_parity_datanum_symbolschunksrz   rN   rA   ri   s        ``             @r   r   r   Z   s   Y FJ3825  (GQ; ++;G+D*EQH I I		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<$?Ml^[cdee27;N$"K27GUDQR"WX_W` abb5F$SS%94@xCuDQ+3v;?+-G 9B&8IK8IHAu %eT2%3K#AJ(8IK K9 ! 	 	8Ks   =H ,)H)	H&%H&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        |      }|}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re   rT   rQ   rR   )Bufferrl   boost_error_levelappend_bitsry   write_segmentr   rm   write_terminatorrG   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   rz   r;   sa_modebuffverrc   rN   segmentrs   widthheightmatrixs                     r   r1   r1      sw    {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'Fv.65&1&$( ,FE64HLD&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   r+   rG   r/   ERROR_LEVEL_MERROR_LEVEL_Qpop
VERSION_M4bit_length_with_overheadindexrm   )r4   r3   r9   r!   re   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.
    rQ   rR   Nr   rT   )r5   r   r   r\   r7   r]   MODE_ECIget_eci_assignment_numberra   r.   MODE_TO_MICRO_MODE_MAPPINGrb   r[   extendrg   )r   r   r   rc   r!   r5   r   subsets           r   r   r     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   rI   r   TERMINATOR_LENGTH)r   rs   r   rq   s       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   rR   N)r   r.   
VERSION_M3r   )r   r4   rq   s      r   r   r   J  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   rR   rW   N)r   r   r.   r   rH   )r   r4   rs   rq   writepad_codewordsrN   s          r   r   r   ]  sl    $ KKE6$$f&7&788qcX&'(Lx1}v{23A-A&' 4r   )		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 ]<  \  }}|dk(  rdnd}|dk7  rdnd}	|D ]   }
t        ||
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 tuple(int, int) matrix_size: Tuple of width and height of the matrix.
    r   r   r   rR   )r      )r   r   N)rG   rH   _FINDER_PATTERN)r   r   r   	is_squarecornersfinder_rangerN   joffset	sepoffsetrs              r   r   r     s     I3v;?+W5GURZ8L11f!aAQ	A%4VaZ%@9WX=%YF1q5M!AE"  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   rY   rR   r   N)rG   rH   )r   r;   r   stopcolbitrN   s          r   add_timing_patternr     sd     #+q#f+CK!O0DGAt
)C
C1d^q	!As
 r   c                 ,   ||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.
       rQ   rW   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_POSrH   r   )r   r   r   r   r4   pattern	positionsalignment_rangemin_posmax_posfinder_positionsxyrN   r   r   s                   r   r   r     s     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| dt        |       d      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   rW   rY   z9Internal error: Adding codewords to matrix failed. Added z of z
 codewordsN)rG   r   r.   r   rH   r%   )r   	codewordsr4   matrix_sizer;   incidxcodeword_length	range_tworightverticalzr   upwardsrN   rows                   r   r   r     sA    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 ""%d3y>*:*F G 	G 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   .0rN   vals     r   	<genexpr>z8make_final_message.<locals>.to_binary.<locals>.<genexpr>	  s     @(?1Q(?   )reversedrH   )r   rq   s   ` r   	to_binaryz%make_final_message.<locals>.to_binary  s    @v(?@@r   Nr   r   rQ   c              3   &   K   | ]	  }||  y wNr   r   r   s     r   r   z%make_final_message.<locals>.<genexpr>  s     %q1_Acdcpa1_   c              3   &   K   | ]	  }||  y wr   r   r   s     r   r   z%make_final_message.<locals>.<genexpr>  s     %r1`Adedqa1`r   )rW   rT   rQ   r   rY   rV   )      rv   r         rS                   !   "   rT   )r                         )rR   )r   ECCmake_blocksr.   r   r   r   r   r
   mapfrom_iterabler   )
r4   r3   r   r   ec_infosdata_blockserror_blockscw_fourresrh   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_POLYrH   
num_blocks	bytearrayr	   rG   r   )r  r   r   r  r  append_data_blockappend_error_blockgen_loggen_expec_infonum_error_wordsgenrange_error_wordsrN   blocklen_dataerror_blockrL   coeflcoefns                        r   r  r  ,  sO    I "BK#**%,,GG!++g.>.>>ooo.!/2w))*AfY0@0@ABEe$5zH#E*Ks_458_"1~19#DME.#AEAI.'%#a&.2II. /	 % {8956 +	 $ $$r   c                    t         }t        }t        }||k(  xr |dk  }|rt        }d}t        }t        ||      t        ||       t        ||       |sdd   d<   fd}t        |      }	|t        | |	|   |||       || fS d}
t        |	      D ]I  \  }}| D cg c]  }|dd 	 }}t        |||||        ||||      } |||      s;|}|}t        |      }
K |
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 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   rR   c                     |    |   dkD  S rE   r   )rN   r   function_matrixs     r   is_encoding_regionz4find_and_apply_best_mask.<locals>.is_encoding_regiont  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_maskr;   r+  mask_patternsbest_matrixmask_numbermask_patternbarM   scorebest_patternr*  s                    @r   r   r   N  s-   & I#JI-52:H 	
'	 "%0O7?E6:!$A+ ,H5M 6=7%	'f$$K%.}%=!\#$VrRUV$1lE63EF !UF+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)rH   )	r   r9  r   r   r+  width_rangerN   r   r   s	            r   r0  r0    sM     ,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22r   c                 n   t        d      fd}d}d}d}||k(  sJ |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   rV   rQ   (   )findanyr~   rI   )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   Nr   r   r   rW   rT   rU   d   2   )r  rH   floatrn   abs)r   r   r   rK  score_n1score_n2score_n3qr_module_rangedark_module_counterlast_row	n3_columnrN   r   row_prev_bitcol_prev_bitn1_row_countern1_col_counterr   row_current_bitcol_current_bitpercentscore_n4rI  rJ  s                         @@r   rA  rA    s   > >?J& HHHF??G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   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   c              3   .   K   | ]  }|   d      yw)r   Nr   )r   rN   r   s     r   r   z&evaluate_micro_mask.<locals>.<genexpr>%  s     3lvay}lr   c              3   (   K   | ]	  }|     y wr   r   )r   rN   rU  s     r   r   z&evaluate_micro_mask.<locals>.<genexpr>&  s     1Lqx{Ls   rv   )rH   r@  )r   r   r   module_rangesum1sum2rU  s   `     @r   r.  r.    s\     E?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   rR   rv   r  rW   )r   r/   r+   r   FORMAT_INFOERROR_LEVEL_TO_MICRO_MAPPINGFORMAT_INFO_MICRO)r4   r3   r9  fmtformat_infos        r   calc_format_infork  *  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   rR   r   rY   r   r   N)rk  rn   rH   )r   r4   r3   r9  r;   rj  voffsethoffset	row_eightrN   vbithbits               r   r   r   D  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)
    rV   NrY   rT   r   rW   )r   VERSION_INFOrH   )r   r4   version_inforN   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   rW   )	r>   r?   
isinstancer|   bytesrn   r@   r1  rG   )	r2   r5   r7   r9   r?   itemseg_contentseg_modeseg_encodings	            r   r,   r,     s      zH&&K'C,-L$9:.2D(|XdE"q'K4y1}7?d4y1}#Aw2(LhEF  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}  rG   r   r]   r|   r   UnicodeErrorKANJI_ENCODING)rJ   r7   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  r(t        dt        |       d|d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 n|t         j                  k(  r|D ]  } |
|d        n|t         j                  k(  rot        d|d      D ]^  }||   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|        |
|dz	  dz  |dz  z   d       ` nnt        d|d      D ]^  }||   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|        |
|dz	  dz  |dz  z   d       ` t%        |	j'                         |||      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 "z" is not applicable for z. Proposal: rW   r   rT   r   -   rX   rY   rR   i  i  i  i  i  zInvalid Hanzi bytes: `      rZ   @    @    i@  zInvalid Kanji bytes:    )r   ra   HANZI_ENCODINGr  r\   	find_moder%   r*   r`   r   r   r^   rH   rn   rG   r_   ALPHANUMERIC_CHARSrE  _Segmentgetbits)rJ   r5   r7   segment_datasegment_lengthsegment_encodingsegment_modeguessed_moderb   r   r   rN   rA   to_bytebcodediffs                    r   r@   r@     s=    v   ((5B45R2L."2L
 /;f>N>N.N9\*TZTdTdL,&2=3N2O P66B5E F**7*E)FH I I $v'''#/8I8I6K\K\7]#]cquvcvJ8D""Kv*** q.!,A 1q5)EE
CJNQ$67 - 
11	1++00q.!,A 1q5)E 5zA~GE!H-2WU1X5FFK
 GENA. - 
))	)A1 	**	* q.!,A Oq(LQ,??D'' f}4)6) f} #8!?@@ $!)t+t<bA -$ q.!,A Oq(LQ,??D'' f}4)6) f} #8!?@@ $!)t+t<bA -  DLLNJ>NOOr   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   rW   c              3   4   K   | ]  }t                y wr   )r  )r   rN   r   s     r   r   zmake_matrix.<locals>.<genexpr>d  s     9=a9S>=s   )   rY   r   rs  rt  ru  rR   	   )r1  rH   r   )
r   r   reserve_regions
add_timingr   r;   r   rN   ro  r   s
            @r   r   r   U  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  sZn | t        j                  vrFt        d|  dd	j                  t        t        j                  j                                      d
      | 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  zUnsupported version "z". Supported: , z and 1 .. 40)rn   r%   	TypeErrorr   MICRO_VERSION_MAPPINGupperKeyErrorAttributeErrorr$   joinsortedkeys)r4   r3   s     r   r#   r#     s    " Eg,! Q%2%'9N9N*N0	 :''+yy8T8T8Y8Y8[1\']&^^jl m 	mN 	" 	227==?CG.) 	E	s5   B   C!B21C2CCCCCc                 >   |  | t         j                  j                         v r| S 	 t         j                  | j                            S # t        t
        f$ rF t        d|  d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 "z". Supported values: r  )
r   MODE_MAPPINGvalueslowerr  r  r%   r  r  r  )r5   s    r   r(   r(     s     |tv2299;;_""4::<00n% _>$ 0..2iiv?R?R?W?W?Y8Z.[-\^ _ 	__s    A ABc                     | y	 t        |       } |rd| cxk  rdk  sn t        d|  d      | S d| cxk  rdk  sn t        d|  d      | S # t        $ r t        d|  d      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
    NzInvalid data mask "zD". Must be an integer or a string which represents an integer value.r   rQ   z," for Micro QR Code. Must be in range 0 .. 3rR   z". Must be in range 0 .. 7)rn   r%   )r6   r;   s     r   r0   r0     s     |^4y D}1}24&8deff K D}1}24&8RSTTK  ^.tf 5] ] ^ 	^^s   A A'c                     | |st        d      | S 	 t        j                  | j                            S # t        t
        f$ r4 | t        j                  j                         v r| cY S t        d|  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
    z The error level must be providedz!Illegal error correction level: "z". Supported levels: L, M, Q, H)r%   r   ERROR_MAPPINGr  r  r  r  )r3   r   s     r   r'   r'     s     }?@@e##EKKM22n% eF((//11L<UGCbcddes    4 1A7'A7c                 ~    t         j                  j                         D ]  \  }}|| k(  s|c S  t        d|  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 "r   )r   r  itemsr%   )
mode_constnamer   s      r   r*   r*     sD     ((..0	c*K 1 ~j\3
44r   c                 ~    t         j                  j                         D ]  \  }}|| k(  s|c S  t        d|  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 "r   )r   r  r  r%   )error_constr  r   s      r   get_error_namer    sE     ))//1	c+K 2 ,[M;
<<r   c                     d| cxk  rdk  r| S  t         j                  j                         D ]  \  }}|| k(  s|c S  t        d|  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 "r   )r   r  r  r%   )version_constr  vs      r   r&   r&     s]     	=2 //557aK 8 1-B
CCr   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rJ   s    r   is_alphanumericr     s     !&&t,,r   c                     t        |       }|r|dz  ry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
    rW   Fr   rR   r  r  r  r  T)rG   iterrH   next)rJ   data_len	data_iterrN   r  s        r   is_kanjir  *  sv     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   r^   r  r_   r  r`   r\   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|
 d      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   rD   z(Micro) zMicro zData too large. No z$QR Code can handle the provided data)r   r.   r   r~   r{   find_minimum_version_for_mode
VERSION_M2rH   r/   rm   r   r  r   )r9   r3   r!   r"   re   micro_allowedmin_versionmax_versionr5   r4   help_txts              r   r-   r-   M  s-    *Ud]M'4&##!K',&##"KQ8>>Z>48>>Z[]''kAo6=W(9(99((E	%%g.u59Z9Z[bdgin9oo p	 7 H}	
1(;_`
aa! [  		s   C>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   rQ   r   rW   r  r   )r   s    r   r   r   s  s*     737R<9qA(99r   c                    t        | t              st        |       } 	 | j                  d      }t        t        |      S # t        $ r< 	 | j                  d      }n&# t        t        f$ r | j                  d      }Y nw xY wY Tw 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  )r|  r|   r   r  LookupErrorr   r   )r2   rJ   s     r   r}   r}     s     gs#g,+~~l+ #t  +	+>>+.D\* 	+>>'*D	++s3   > 	BAB A=:B<A==BBc                 x    |dkD  rdn|}	 |t         j                  |    v S # t        $ r t        d|  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   )r   SUPPORTED_MODESr  r%   )r5   r   s     r   r)   r)     sO     '$sC3f,,T222 3>$q1223s     9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)   )r5   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|  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   rU   r  r  r  r  zUnknown version "r   )r   VERSION_RANGE_01_09VERSION_RANGE_10_26VERSION_RANGE_27_40r%   )r4   s    r   rl   rl     ss     	7R))) 	
W	r	))) 
	g		))) 

(	3
44r   c                     	 t         j                  t        j                  |       j                     S # t
        $ r t        d|  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.
    z,Unknown ECI assignment number for encoding "z".)r   ECI_ASSIGNMENT_NUMcodecslookupr  r  r%   )r7   s    r   r   r     sO    V((x)@)E)EFF VGzQSTUUV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   rN   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 NrT   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 )NrW   rT   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   rT   r   r   rN   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   r/  r/    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	)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
    )rr   r{   r9   c                 .    g | _         d| _        g | _        y )Nr   )r9   rr   r{   selfs    r   __init__zSegments.__init__  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)
r9   r5   r7   r  rg   rb   rr   rG   r{   r  )r  r   prev_segs      r   r?   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   )rG   r9   r  s    r   __len__zSegments.__len__-  s    4==!!r   c                      | j                   |   S r   )r9   r  r~  s     r   __getitem__zSegments.__getitem__0  s    }}T""r   c                 ,    t        | j                        S r   )r  r9   r  s    r   __iter__zSegments.__iter__3  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   )r5   r   r\   r7   r]   )r   r   s     r   r   z4Segments.bit_length_with_overhead.<locals>.<genexpr>:  s=      $Z]''.||v7G7G'G(/(8(8F<X<X(X %&]s   AArQ   rR   rS   rT   c              3   J   K   | ]  }t         j                  |        y wr   )r   r[   )r   r5   rc   s     r   r   z4Segments.bit_length_with_overhead.<locals>.<genexpr>J  s%     cXbPT::4@KXbs    #)r@  r9   rG   r{   r   r.   rl   rr   )r  r4   r!   re   rf   no_eci_indicatorsrc   s         @r   r   z!Segments.bit_length_with_overhead6  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  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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   )r1  __new__)clsrg   rb   r5   r7   s        r   r  z_Segment.__new__\  s    }}S4T8"DEEr   r   r   rW   rT   r   )r   r   r   r   r  r  propertyr   rg   rb   r5   r7   r   r   r   r  r  N  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__k  s    x(
r   c                 :    | j                   j                  |       y r   )r  r   r  s     r   r   zBuffer.extendn  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>r  s     J2IQ3!8q.2Ir   )r  r   r   rH   )r  r   rq   s    ` r   r   zBuffer.append_bitsq  s$    

J(5=2IJJr   c                     | j                   S r   r  r  s    r   r  zBuffer.getbitst  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  rW   N)rn   r  r	  r|   )r   gs     r   r   z Buffer.toints.<locals>.<genexpr>|  s)     h6gBGGCQK(!,6gs   35rR   	fillvaluer   )r   r  r  r  s    r   r  zBuffer.tointsw  s-    
 ikDDTCUXYCY6gef6ghhr   c                 ,    t        | j                        S r   )rG   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   e  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                 H    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   MODE_STRUCTURED_APPEND)r  numberrx   ry   	__class__s       r   r  z_StructuredAppendInfo.__new__  s&     wsV%B%BFESY$Z[[r   r   r   rW   rT   )r   r   r   r   r  r  r  r   r5   r'  rx   ry   __classcell__)r(  s   @r   r   r     sO     I\ JqM"Djm$FZ]#Ejm$Fr   r   )NNNNNFNT)NNNNNFTNr   r  )TT)Rr   operatorr   r   r   r   	functoolsr   r   	itertoolsr	   r
   r   rero   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   r0  r-  rA  r.  rk  r   r   r,   r  r@   r   r#   r(   r0   r'   r*   r  r&   compileescaper  r  r  r  r  r-   r   r}   r)   r  rl   r   r/  r>   r1  r  r   r   r   r   r   <module>r4     s   - , % , , 	   "  ! 
[[ 
<	
 	 &>? ?C=A*EZ HLMQmK`38l:>M.&(8BZ2&>D(GV,^%D;%|-(
3i2XB"4;|$NB#%LbPJ(V F_.6e45=D$ #

6IBIIf6O6O,P#PS[#[\ -$"#bL:&3&
5&
V52p?* ?*D'u '.   @%E %r   