
    VeIia                         d Z ddlmZmZmZmZmZ ddlmZ ddl	Z	ddl
Z
ddlZ G d d          Zd ZddZddZddZddZ	 	 	 ddZ	 	 ddZ	 	 d dZd ZdS )!zThis module does the actual generation of the QR codes. The QRCodeBuilder
builds the code. While the various output methods draw the code into a file.
    )absolute_importdivisionprint_functionwith_statementunicode_literalsNc                       e Zd ZdZd ZddZd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZdS )QRCodeBuildera   This class generates a QR code based on the standard. It is meant to
    be used internally, not by users!!!

    This class implements the tutorials found at:

    * http://www.thonky.com/qr-code-tutorial/

    * http://www.matchadesign.com/blog/qr-code-demystified-part-6/

    This class also uses the standard, which can be read online at:
        http://raidenii.net/files/datasheets/misc/qr_code.pdf

    Test codes were tested against:
        http://zxing.org/w/decode.jspx

    Also, reference codes were generat/ed at:
        http://www.morovia.com/free-online-barcode-generator/qrcode-maker.php
        http://demos.telerik.com/aspnet-ajax/barcode/examples/qrcode/defaultcs.aspx

    QR code Debugger:
        http://qrlogo.kaarposoft.dk/qrdecode.html
    c                 l   || _         |t          j        v rt          j        |         | _        n"t	          d                    |                    |t          j        v rt          j        |         | _        n"t	          d                    |                    d|cxk    rdk    rn n|| _        n"t	          d                    |                    t          j	        |         | j                 | _
        t          j                    | _        |                                  |                                  dS )zBSee :py:class:`pyqrcode.QRCode` for information on the parameters.z{0} is not a valid mode.z{0} is not a valid error level.   (   z6Illegal version {0}, version must be between 1 and 40.N)datatablesmodesmode
ValueErrorformaterror_levelerrorversioneccwbierror_code_wordsioStringIObufferadd_data	make_code)selfr   r   r   r   s        U/var/www/html/MCyber-Diagnostic/venv/lib/python3.11/site-packages/pyqrcode/builder.py__init__zQRCodeBuilder.__init__=   s'    	 6<T*DII7>>tDDEEE F&&&+E2DJJ &&,fUmm5 5 5 2"DLL ))/: : : !'g 6tz B kmm 	 	    Nc                     t          |          g|z  }t          t          d          rt          j        |d|iS t          j        |d|iS )a8  This generator yields a set of tuples, where the
        iterable is broken into n sized chunks. If the
        iterable is not evenly sized then fillvalue will
        be appended to the last tuple to make up the difference.

        This function is copied from the standard docs on
        itertools.
        zip_longest	fillvalue)iterhasattr	itertoolsr"   izip_longest)r   niterabler#   argss        r   grouperzQRCodeBuilder.grouperb   sV     X!#9m,, 	E($D)DDD%tAyAAAr    c                 l    d                     |                               t          |                    S )zThis method returns a string of length n that is the binary
        representation of the given data. This function is used to
        basically create bit fields of a given size.
        {{0:0{0}b}})r   int)r   r   lengths      r   binary_stringzQRCodeBuilder.binary_stringp   s,    
 ##F++223t99===r    c                    d| j         cxk    rdk    rn nd}n/d| j         cxk    rdk    rn nd}nd| j         cxk    rdk    rn nd}t          j        |         | j                 }| j        t          j        d         k    r)|                     t          | j                  |          }n+|                     t          | j                  dz  |          }t          |          |k    rt          d	          |S )
zQR codes contain a "data length" field. This method creates this
        field. A binary string representing the appropriate length is
        returned.
        r   	   
         r   kanji   z?The supplied data will not fit within this version of a QRCode.)	r   r   data_length_fieldr   r   r0   lenr   r   )r   max_versiondata_lengthlength_strings       r   get_data_lengthzQRCodeBuilder.get_data_lengthw   s     !!!!!!!!!KK4<%%%%2%%%%%KK4<%%%%2%%%%%K.{;DIF9W--- ..s49~~{KKMM ..s49~~/A;OOM}++ B C C Cr    c                    | j         t          j        d         k    r|                                 }n| j         t          j        d         k    r|                                 }n_| j         t          j        d         k    r|                                 }n/| j         t          j        d         k    r|                                 }|S )zyThis method encodes the data into a binary string using
        the appropriate algorithm specified by the mode.
        alphanumericnumericbinaryr6   )r   r   r   encode_alphanumericencode_numericencode_bytesencode_kanji)r   encodeds     r   encodezQRCodeBuilder.encode   s     9^444..00GGY&,y111))++GGY&,x000''))GGY&,w///''))Gr    c                    | j                                         | _         g }| j         D ]o}t          |t                    r3|                    t
          j        t          |                              J|                    t
          j        |                    pt          j	                    5 }| 
                    d|          D ]`\  }}|0|                    |                     d|z  |z   d                     7|                    |                     |d                     a|                                cddd           S # 1 swxY w Y   dS )zThis method encodes the QR code's data if its mode is
        alphanumeric. It returns the data encoded as a binary string.
        r7   N-         )r   upper
isinstancer.   appendr   ascii_codeschrr   r   r+   writer0   getvalue)r   asciicharbufabs         r   rB   z!QRCodeBuilder.encode_alphanumeric   sw   
 IOO%%	 I 	7 	7D$$$ 7V/D		:;;;;V/56666 []] 
	"ca// 8 81=IId00"Q$2>>???? IId00A667777 <<>>
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	" 
	"s   +BEE
Ec                 H   t          j                    5 }|                     d| j                  D ]}d}|D ]@}t	          |t
                    rt          |          }|rd                    ||g          }@ t          |          dk    r| 	                    |d          }n@t          |          dk    r| 	                    |d          }n| 	                    |d          }|
                    |           |                                cddd           S # 1 swxY w Y   dS )	zThis method encodes the QR code's data if its mode is
        numeric. It returns the data encoded as a binary string.
            r      r7      r3   N)r   r   r+   r   rM   r.   rP   joinr9   r0   rQ   rR   )r   rU   tripletnumberdigitbins         r   rC   zQRCodeBuilder.encode_numeric   sl    []] 	"c<<4955  $  E!%-- + #E

  !#&%!9!9 v;;!##,,VQ77CC [[A%%,,VQ77CC ,,VR88C		#<<>>7	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"s   C6DDDc           	         t          j                    5 }| j        D ]}t          |t                    sI|                    d                    d                              t          |                               `|                    d                    d                              |                     |                                cddd           S # 1 swxY w Y   dS )zThis method encodes the QR code's data if its mode is
        8 bit mode. It returns the data encoded as a binary string.
        r-      N)	r   r   r   rM   r.   rQ   r   ordrR   )r   rU   rT   s      r   rD   zQRCodeBuilder.encode_bytes   s
    []] 	"c	 D D!$,, DIIm22155<<SYYGGHHHHIIm22155<<TBBCCCC<<>>	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"s   B7CCCc                 0   d }t          | j        t                    r.| j                            d                              d          }n| j                            d          }t          j                    5 } ||          D ]e}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
  }|dz	  }|d	z  }|                    d
                    |dz  |z                        f|	                                cddd           S # 1 swxY w Y   dS )z}This method encodes the QR code's data if its mode is
        kanji. It returns the data encoded as a binary string.
        c              3      K   d }t          dt          |           d          D ]-} || |                   dz   || |dz                      z  V  .dS )z3Output two byte character code as a single integer.c                 N    t          | t                    st          |           S | S )zgMake sure that character code is an int. Python 2 and
                3 compatibility.
                )rM   r.   rd   )rW   s    r   	next_bytez@QRCodeBuilder.encode_kanji.<locals>.two_bytes.<locals>.next_byte   s&     "!S)) q66MHr    r   r7   rc   r   N)ranger9   )r   rh   is      r   	two_bytesz-QRCodeBuilder.encode_kanji.<locals>.two_bytes   s         1c$ii++ G G ya))Q.))D1I2F2FFFFFFG Gr    shiftjisi@  i  i@  i  i@  rc      z{0:013b}   N)
rM   r   bytesdecoderG   r   r   rQ   r   rR   )r   rk   r   rU   asint
differencemsblsbs           r   rE   zQRCodeBuilder.encode_kanji   s   	G 	G 	G  di'' 	09##J//66zBBDD9##J//D []] 	"c"4 A AU,,,,f,,,,,!&JJu.........!&J "Q!F* 		*++S4Z3,>??@@@@<<>>	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"s   9BDDDc                    | j                             |                     | j        d                     | j                             |                                            | j                             |                                            |                     | j                                                   }|| j                             |           |                                 }|r| j                             |           | 	                                }|r| j                             |           d | 
                    d| j                                                   D             }t          j        | j                 | j                 }g }g }|d         g|d         z  }|d         dk    r%|                    |d         g|d         z             d}	|D ]'}
|                    ||	|	|
z                       |	|
z  }	(|	t#          |          k     rt%          d	          t'          |          D ].\  }}|                    |                     ||                     /t+          j                    }t/          |d         |d                   |d         z   }t1          |          D ]I}|D ]D}|t#          |          k     r/|                    |                     ||         d                     EJt1          |d                   D ]6}|D ]1}|                    |                     ||         d                     27|| _         dS )
zThis function properly constructs a QR code's data string. It takes
        into account the interleaving pattern required by the standard.
        r[   Nc                 T    g | ]%}t          d                     |          d          &S )rZ   r7   )r.   r]   .0xs     r   
<listcomp>z*QRCodeBuilder.add_data.<locals>.<listcomp>:  sB     F F F BGGAJJq!! F F Fr    rc   r7   r   rY   r   z$Too much data for this code version.)r   rQ   r0   r   r=   rG   terminate_bitsrR   delimit_words	add_wordsr+   r   r   r   r   extendrN   r9   r   	enumeratemake_error_blockr   r   maxri   )r   bitsadd_bits
fill_bytesr   
error_infodata_blockserror_blocksdata_block_sizescurrent_byten_data_blocksr(   blockdata_bufferlargest_blockrj   s                   r   r   zQRCodeBuilder.add_data  sh   
 	$,,TY::;;;$..00111$++--(((  ""4;#7#7#9#9::Kd### %%'' 	(Kh'''^^%%
 	*Kj)))F F!\\!T[-A-A-C-CDDF F F ]4<0<
  
 'qM?Z]:a=A##Z]Ojm$CDDD - 	* 	*MtLm1K$KLMMMM)LL #d))##CDDD "+.. 	A 	AHAu 5 5eQ ? ?@@@@ kmm JqM:a=99*Q-G}%% 	G 	GA$ G Gs5zz>>%%d&8&8q1&E&EFFFG z!}%% 	C 	CA% C C!!$"4"4U1Xq"A"ABBBBC "r    c                 j   t           j        | j                 | j                 d         }t	          |          |k    rt          d          t	          |          |k    rdS t	          |          |dz
  k    r|                     dd          }n&|                     d|t	          |          z
            }|S )zThis method adds zeros to the end of the encoded data so that the
        encoded data is of the correct length. It returns a binary string
        containing the bits to be added.
        r   z@The supplied data will not fit within this version of a QR code.Nr[   )r   data_capacityr   r   r9   r   r0   )r   payloadr   r   s       r   r{   zQRCodeBuilder.terminate_bits{  s    
 ,T\:4:FqIw<<-'' A B B B
 w<<=((4\\]1_,,%%a**DD %%aW)EFFDr    c                     dt          | j                                                  dz  z
  }|dk    s|dk    rdS |                     d|          S )zThis method takes the existing encoded binary string
        and returns a binary string that will pad it such that
        the encoded string contains only full bytes.
        rc   r   N)r9   r   rR   r0   )r   
bits_shorts     r   r|   zQRCodeBuilder.delimit_words  sW    
 #dk2244559:
 ??jAoo4%%a444r    c                 N   t          | j                                                  dz  }t          j        | j                 | j                 d         dz  }||z
  }|dk    rdS t          j        ddg          d	                    fdt          |          D                       S )zThe data block must fill the entire data capacity of the QR code.
        If we fall short, then we must add bytes to the end of the encoded
        data field. The value of these bytes are specified in the standard.
        rc   r   N1110110000010001rZ   c                 .    g | ]}t                    S  )next)rx   ry   r   s     r   rz   z+QRCodeBuilder.add_words.<locals>.<listcomp>  s    BBBUBBBr    )r9   r   rR   r   r   r   r   r&   cycler]   ri   )r   r   total_blocksneeded_blocksr   s       @r   r}   zQRCodeBuilder.add_words  s     $+..0011Q6+DL9$*EaHAM${2A4 Z 899 wwBBBBU=-A-ABBBCCCr    c                    t           j        | j                 | j                 }||d         k     r	|d         }n|d         }|d         }|dd         }|                    dg|z             t           j        |         }dgt          |          z  }t          |          D ]}	|                    d          }
|
dk    rt           j	        |
         }t          t          |                    D ]Y}|||         z   ||<   ||         dk    r||         dz  ||<   t           j
        ||                  ||<   ||         ||         z  ||<   Zt          |          |k     r)|                    dg|t          |          z
  z             |S )aD  This function constructs the error correction block of the
        given data block. This is *very complicated* process. To
        understand the code you need to read:

        * http://www.thonky.com/qr-code-tutorial/part-2-error-correction/
        * http://www.matchadesign.com/blog/qr-code-demystified-part-4/
        r   r7   r[   r   Nrm   )r   r   r   r   r~   generator_polynomialsr9   ri   popgalois_antilog
galois_log)r   r   block_numberr   code_words_per_blockerror_block_sizemp_co	generator
gen_resultrj   coefficient	alpha_expr(   s                r   r   zQRCodeBuilder.make_error_block  s    ]4<0<
 *Q-''#-a=  #-a=  &a= aaa 	aS,-... 01AB	 S3y>>)
 +,, 	4 	4A))A,,K a #1+>	 3y>>** 	4 	4 )IaL 8
1a=3&&$.qMC$7JqM !' 1*Q- @
1 &a=583a	4 u::,,,LL! 4s5zz ABCCCr    c                    ddl m t          j        | j                 }d t          |          D             fdt          |          D             }|                     |           |                     |           |                     |           | 	                    |          | _
        |                                 | _        | j
        | j                 | _        dS )z.This method returns the best possible QR code.r   deepcopyc                     g | ]}d S ) r   rw   s     r   rz   z+QRCodeBuilder.make_code.<locals>.<listcomp>  s    ///qs///r    c                 &    g | ]}           S r   r   )rx   ry   r   rows     r   rz   z+QRCodeBuilder.make_code.<locals>.<listcomp>  s!    >>>aHHSMM>>>r    N)copyr   r   version_sizer   ri   add_detection_patternadd_position_patternadd_version_pattern
make_masksmaskschoose_best_mask	best_maskcode)r   matrix_sizetemplater   r   s      @@r   r   zQRCodeBuilder.make_code  s    !!!!!! )$,7 0/E+..///>>>>>5+=+=>>> 	""8,,,!!(+++  *** __X..
..00Jt~.			r    c                    t          d          D ]9}|dz    }dD ].}d||         |<   d||         |<   d||         |<   d||         |<   /:t          dd          D ]9}|dz    }dD ].}d||         |<   d||         |<   d||         |<   d||         |<   /:t          dd          D ]<}t          dd          D ])}|dz    }d||         |<   d||         |<   d||         |<   *=t          d	          D ]9}|dz    }d
D ].}d||         |<   d||         |<   d||         |<   d||         |<   /:t          dd          D ] }t          dd          D ]}d||         |<   !t          j        ddg          }t          d	t          |          d	z
            D ]'}t	          |          }|||         d<   ||d         |<   (d|d         d	<   dS )a  This method add the detection patterns to the QR code. This lets
        the scanner orient the pattern. It is required for all QR codes.
        The detection pattern consists of three boxes located at the upper
        left, upper right, and lower left corners of the matrix. Also, two
        special lines called the timing pattern is also necessary. Finally,
        a single black pixel is added just above the lower left black box.
        r\   r   )r   rK   irK   )r      ir   r7   r   rc   )r\   r   r   N)ri   r&   r   r9   r   )r   mrj   invjbitrW   s          r   r   z#QRCodeBuilder.add_detection_pattern  sg    q 	 	AaC&C   !Q!Q#q	!S			 q! 	 	AaC&C#  !Q!Q#q	!S			 q! 	 	A1a[[  !f!Q#q	!S			 q 	 	AaC&C  !Q!Q#q	!S			 r1 	 	A2q\\  !Q oqe$$q3q66!8%% 	 	AS		AAaDGAaDGG "ar    c                 H   | j         dk    rdS t          j        | j                  }|d         }|d         }|D ]}|D ]}||k    r||k    s||k    r||k    s||k    r||k    r'd||         |<   dD ]Q}d|||z            ||z   <   d|||z            |<   d||         ||z   <   d|||z
           ||z   <   d|||z            ||z
  <   RdD ]\}dD ]W}d|||z            ||z   <   d|||z            ||z   <   d|||z            ||z   <   d|||z
           ||z   <   d|||z            ||z
  <   X]dS )zThis method draws the position adjustment patterns onto the QR
        Code. All QR code versions larger than one require these special boxes
        called position adjustment patterns.
        r   Nr   r   )r   r   )r   r7   )r   r   r   )r   r   position_adjustment)	r   r   coordinates	min_coord	max_coordrj   r   ry   ys	            r   r   z"QRCodeBuilder.add_position_patternC  s    <1F 0>  N	O	  	( 	(A  ( ( NNqI~~NNqI~~NNqI~~ !Q   $ $A"#AacF1Q3K !AacF1I !AaD1I"#AacF1Q3K"#AacF1Q3KK   ( (A% ( (&'!A#qs&'!A#qs&'!A#qs&'!A#qs&'!A#qs(()(	( 	(r    c                 R   | j         dk     rdS t          t          j        | j                  ddd                   }t	          |          dz
  }t          d          D ]J}t          ||dz             D ]4}t          t          |                    }|||         |<   |||         |<   5KdS )a  For QR codes with a version 7 or higher, a special pattern
        specifying the code's version is required.

        For further information see:
        http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string
        r\   Nr   rJ   rK   rY   )r   r$   r   version_patternr9   ri   r.   r   )r   r   fieldstartrj   r   r   s          r   r   z!QRCodeBuilder.add_version_patternq  s     <!F
 V+DL9$$B$?@@ Ar	 q 		 		A5%'**  $u++&& !Q !Q		 		r    c           	      4   ddl m} t          t          j                  }dg|z  }d}t          |          D ]} ||          }|||<   |                     |t          j        | j                 |                    t          j        |         }t          | j
                                                  }	t          j        t          |          dz
  dg          }
t          j        dt          |          g          }t          j        ddg          }t          t          |          dz
  dd          D ]}|dk    r|dz
  }t          j        ||dz
  g          }t          t          |
          t          |          t          |                    D ]}t          d          D ]q}t          |          }||         |         d	k    r$	 t          t          |	                    }n	#  d}Y nxY w |||          r|dz  ||         |<   f|||         |<   r|S )
zThis method generates all seven masks so that the best mask can
        be determined. The template parameter is a code matrix that will
        server as the base for all the generated masks.
        r   r   rZ   r   r   r   rK   r7   r   )r   r   r9   r   mask_patternsri   add_type_pattern	type_bitsr   r$   r   rR   r&   r   r   r.   )r   r   r   nmasksr   countr(   cur_maskpatternr   	row_startrow_stop	directioncolumncolumn_pairr   rj   colr   s                      r   r   zQRCodeBuilder.make_masks  sF   
 	"!!!!!V)**vv 8	5 8	5Ax))HE!H !!(F,<TZ,H,KLLL *1-G ,,..//D "Xq!(<==I 3x=='9::H!Q00I  HaB77 %5 %5 Q;;#aZF (ovvax.@AA !i$x..!%i2 2 5 5C #1XX 5 5";// $C=-44$
$"%d4jj//CC$"#CCC #73,, 514qHSM#..14HSM#..+5	5%5X s   G$$G*c           	      0	   g | _         t          t          | j                            D ]}| j                             g d           t          | j                  D ],\  }}|d         d         }d}d}t          dt          |                    D ]d}d}t          dt          |                    D ]1}||         |         }||k    r|dz  }|dk    r||dz
  dz   z  }d}|}2|dk    r||dz
  dz   z  }et          dt          |                    D ]d}d}t          dt          |                    D ]1}||         |         }||k    r|dz  }|dk    r||dz
  dz   z  }d}|}2|dk    r||dz
  dz   z  }e|| j         |         d<   .t          | j                  D ]\  }}d}	t          dt          |          dz
            D ]}
t          dt          |          dz
            D ]m}||
         |         ||
dz            |         k    rJ||
         |         ||
         |dz            k    r)||
         |         ||
dz            |dz            k    r|	dz  }	n|	dz  | j         |         d<   g dg dg}t          | j                  D ]\  }}d}t          t          |                    D ]}
t          t          |                    D ]}|D ]~}d}|}|D ]0}|t          |          k    s||
         |         |k    rd	} n|dz  }1|r|dz  }d}|}|D ]0}|t          |          k    s||         |
         |k    rd	} n|dz  }1|r|dz  }|d
z  | j         |         d<   t          | j                  D ]z\  }}d}|D ]}|t          |          z  }t          |          dz  }||z  }|dz  dz
  }t          t          t          |                    dz  dz            | j         |         d<   {dgt          | j                   z  }t          t          | j                             D ]M}
t          t          | j         |
                             D ]#}||
xx         | j         |
         |         z  cc<   $N|	                    t          |                    S )a  This method returns the index of the "best" mask as defined by
        having the lowest total penalty score. The penalty rules are defined
        by the standard. The mask with the lowest total score should be the
        easiest to read by optical scanners.
        )r   r   r   r   r   r   r   rY   )r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   TFr   r7   d   2   r3   )scoresri   r9   r   rN   r   sumr.   absindexmin)r   r(   maskcurrentcountertotalr   r   r   r   rj   r   patternsnmatchesr   matchkpnblacktotal_pixelsratiopercenttotalss                          r   r   zQRCodeBuilder.choose_best_mask  s    s4:'' 	* 	*AKyyy)))) #4:.. %	& %	&IQ1gajGGE Qs4yy)) / /!!CII.. 	& 	&Cs)C.Cg~~1"a<<!gkQ%66E"#"%a<<gkQ..E Qs4yy)) / / 3t99-- 	& 	&Cs)C.Cg~~1"a<<!gkQ%66E"#"%a<<gkQ..E %DKN1
 #4:.. 
	* 
	*IQE1c$iik** # #q#d))A+.. # #AAwqzT!A#Yq\11AwqzT!WQqS\11AwqzT!A#Yqs^33
	# !&	DKN1
 ,+++++. #4:.. 	. 	.IQH3t99%% * *s4yy)) * *A#+ * * $!( # #A CII~~aq(- %FAA  *$MH $!( # #A CII~~aq(- %FAA  *$MH+**2 !)2DKN1
 #4:.. 	B 	BIQF # ##c(("t99a<L\)Es{b(G #SW%6%6%:b$@ A ADKN1 s4;'''s4;''(( 	0 	0A3t{1~..// 0 0q			dk!nQ//				0 ||CKK(((r    c                    t          |          }t          d          D ]W}t          t          |                    }|dk     r||d         |<   n||d         |dz   <   d|dz    k     r|||dz             d<   Xt          dd          D ]L}t          t          |                    }||d         |<   | }|dk    r|||         d<   >|||dz
           d<   MdS )zThis will add the pattern to the QR code that represents the error
        level and the type of mask used to make the code.
        r\   rK   rc   r   r   r   N)r$   ri   r.   r   )r   r   r   r   rj   r   s         r   r   zQRCodeBuilder.add_type_patternf  s     Yq 
	# 
	#Ad5kk""C 1uu!Q!QqS	acF{{"AaC&	!r! 
	  
	 Ad5kk""CAaDGA1uu!Q!A#q		
	  
	 r    N)__name__
__module____qualname____doc__r   r+   r0   r=   rG   rB   rC   rD   rE   r   r{   r|   r}   r   r   r   r   r   r   r   r   r   r    r   r	   r	   &   sw        ,# # #JB B B B> > >  6  " " "8" " "B
" 
" 
")" )" )"Xd" d" d"L  .5 5 5D D D&= = =~/ / /,: : :x,( ,( ,(\  <J J JXI) I) I)V         r    r	   c                 P    t          | d          }|st          | |          } | | fS )a  This method returns a tuple containing the stream and a flag to indicate
    if the stream should be automatically closed.

    The `stream_or_path` parameter is returned if it is an open writable stream.
    Otherwise, it treats the `stream_or_path` parameter as a file path and
    opens it with the given mode.

    It is used by the svg and png methods to interpret the file parameter.

    :type stream_or_path: str | io.BufferedIOBase
    :type mode: str | unicode
    :rtype: (io.BufferedIOBase, bool)
    rQ   )r%   open)stream_or_pathr   	is_streams      r   _get_writabler     s7     00I 4nd33y=((r    r[   c                 r    t          |          t          j        |          z  d|z  t          |          z  z   S )a  See: QRCode.get_png_size

    This function was abstracted away from QRCode to allow for the output of
    QR codes during the build process, i.e. for debugging. It works
    just the same except you must specify the code's version. This is needed
    to calculate the PNG's size.
    r7   )r.   r   r   )r   scale
quiet_zones      r   _get_png_sizer    s1     JJ,W55!j.3u:::UVVr    defaultreversec                 ~  
 t          j                    

fd}|t          j        v r&d                    t          j        |                   }nHd|cxk    rdk    rn nd                    |          }n"t          d                    |                    t          j        v r&d                    t          j                           nHdcxk    rdk    rn nd                              n"t          d                                        t          | d                   dz  z   z  }
                    d	           t                    D ],}
                    |           
                    d	           -| D ]g} |             |D ]9}	|	d
k    r
                    |           |	dk    r
                               : |             
                    d	           ht                    D ],}
                    |           
                    d	           -
	                                S )aR  This method returns a string containing ASCII escape codes,
    such that if printed to a terminal, it will display a vaild
    QR code. The module_color and the background color should be keys
    in the tables.term_colors table for printing using the 8/16
    color scheme. Alternatively, they can be a number between 0 and
    256 in order to use the 88/256 color scheme. Otherwise, a
    ValueError will be raised.

    Note, the code is outputted by changing the background color. Then
    two spaces are written to the terminal. Finally, the terminal is
    reset back to how it was.
    c                  V    t                    D ]}                                d S r   )ri   rQ   )rj   
backgroundrU   r   s    r   draw_borderz_terminal.<locals>.draw_border  s9    z"" 	" 	"AIIj!!!!	" 	"r    z[{0}m  [0mr      z[48;5;{0}m  [0mz_The module color, {0}, must a key in pyqrcode.tables.term_colors or a number between 0 and 256.zcThe background color, {0}, must a key in pyqrcode.tables.term_colors or a number between 0 and 256.r7   
r   )
r   r   r   term_colorsr   r   r9   rQ   ri   rR   )r   module_colorr  r   r  r   
border_rowrj   r   r   rU   s     ``      @r   	_terminalr    s    +--C" " " " " " " v)))#**|,. .	
l	!	!	!	!c	!	!	!	!	!(//== ..4f%/' /'( ( 	(
 V''')00z*, ,

	
j				C					.55jAA

 ..4f#/% /%& & 	& s47||q:~>?J IIdOOO :  		*		$   	 	& 	&Caxx		$		*%%% 			$ :  		*		$<<>>r    c                    t          j                    }dt          | d                   |dz  z   z  }t          |          D ],}|                    |           |                    d           -| D ]}t          |          D ]}|                    d           |D ]O}|dk    r|                    d           |dk    r|                    d           :|                    d           Pt          |          D ]}|                    d           |                    d           t          |          D ],}|                    |           |                    d           -|                                S )zoThis method returns a text based representation of the QR code.
    This is useful for debugging purposes.
    0r   r7   r	  r   1r   )r   r   r9   ri   rQ   rR   )r   r   rU   r  rW   r   r   s          r   _textr    s|    +--CDG
156J :  		*		$  z"" 	 	AIIcNNNN  	 	Caxx		#		# 		# z"" 	 	AIIcNNNN		$ :  		*		$<<>>r    r   c                 X   	 t           }n# t          $ r t          d         }Y nw xY wt          j                    }t          | d                   |dz  z   |z  }|                    d           |                     ||                     |                    d           |                    d           |                     ||                     |                    d           |                    d           t          t          j	        |dz                      }|                    d	|z  dz   |z  |z             | D ]}d
|z  |z  }|D ]}	| ||	          |z  z  }|d
|z  |z  z  }d}
t          |          D ]C}|
d                    t          |dd         ddd         d                    z  }
|dd         }D|
dz  }
|                    |
|z             |                    d	|z  dz   |z  |z             |                    d           |                                S )zsThis function will format the QR code as a X BitMap.
    This can be used to display the QR code with Tkinter.
    strr   r7   z#define im_width r	  z#define im_height zstatic char im_bits[] = {
g       @z0x00,r  rZ   z
0x{0:02x},Nrc   r   z};)unicode	NameError__builtins__r   r   r9   rQ   r.   mathceilri   r   rR   )r   r   r   r  rU   pixel_width
byte_widthr   row_bitspixelformated_rowrW   s               r   _xbmr  !  s[   " " " "5!" +--C tAw<<*q.0E9K II!"""IIcc+IIdOOOII"###IIcc+IIdOOOII+,,, TY{S01122J IIw#d*j85@AAA ( (#e+ 	+ 	+EE

U**HHC*$u,,z"" 	$ 	$AL//HRaRL24F0J0JKKKL|HH		,&''''IIw#d*j85@AAAIIdOOO<<>>s   
 $$#000TpyqrcodepyqrlineFc           	        " ddl m} ddlm} d }d ""fd}t	          |d          \  }} |||j                  }|j        }|r |d            |d	           |r |d
           t          j        |         |z  dz  |z  z   }|s |d                    |                     n |d                    |                     |
 |d            | ||
                      |d           |	 |d                    |	                     | |d                    ||                      |d           |dk    r |d                    |                     | |d            | ||                     | |d            | ||                      |d           d} dz
  }}d}t          |           D ]\  }}d}d}|dz  }d}t          |          D ]Q\  } }!|!dk    r|dz  }|r"||z
  }| "||||          z  }||z   }d}d}d}| dz   }|r|!dk    r| || |          z  }R|r||z
  }| "||||          z  }||z   }d} ||            |d           |rO|rM |d           |dk    r |d                    |                      |d                    |                      |d           |r|
                                 dS dS ) aG  This function writes the QR code out as an SVG document. The
    code is drawn by drawing only the modules corresponding to a 1. They
    are drawn using a line, such that contiguous modules in a row
    are drawn with a single line. The file parameter is used to
    specify where to write the document to. It can either be a writable (binary)
    stream or a file path. The scale parameter is sets how large to draw
    a single module. By default one pixel is used to draw a single
    module. This may make the code to small to be read efficiently.
    Increasing the scale will make the code larger. This method will accept
    fractional scales (e.g. 2.5).

    :param module_color: Color of the QR code (default: ``#000`` (black))
    :param background: Optional background color.
            (default: ``None`` (no background))
    :param quiet_zone: Border around the QR code (also known as  quiet zone)
            (default: ``4``). Set to zero (``0``) if the code shouldn't
            have a border.
    :param xmldecl: Inidcates if the XML declaration header should be written
            (default: ``True``)
    :param svgns: Indicates if the SVG namespace should be written
            (default: ``True``)
    :param title: Optional title of the generated SVG document.
    :param svgclass: The CSS class of the SVG document
            (if set to ``None``, the SVG element won't have a class).
    :param lineclass: The CSS class of the path element
            (if set to ``None``, the path won't have a class).
    :param omithw: Indicates if width and height attributes should be
            omitted (default: ``False``). If these attributes are omitted,
            a ``viewBox`` attribute will be added to the document.
    :param debug: Inidicates if errors in the QR code should be added to the
            output (default: ``False``).
    r   partial)	quoteattrc                 B     | |                     d                     dS )zm        Encodes the provided string into UTF-8 and writes the result using
        the `write_meth`.
        zutf-8N)rG   )
write_methunicode_strs     r   write_unicodez_svg.<locals>.write_unicodey  s(    
 	
;%%g../////r    c                 :    d                     |rdnd| ||          S )zEReturns coordinates to draw a line with the provided length.
        z{0}{1} {2}h{3}r   Mr   )ry   r   r/   relatives       r   linez_svg.<locals>.line  s'      &&x(@S1aPPPr    c                 2     | z   |z   dz   dd          S )z6Returns the coordinates to draw an error bit.
              ?r   Fr   )
col_number
row_numberr.  r   s     r   errlinez_svg.<locals>.errline  s*    
 tJ+Z*-Dr-I1eTTTr    wbs'   <?xml version="1.0" encoding="UTF-8"?>
s   <svgs#    xmlns="http://www.w3.org/2000/svg"r7   z height="{0}" width="{0}"z viewBox="0 0 {0} {0}"Ns    class=   >z<title>{0}</title>z)<path fill="{1}" d="M0 0h{0}v{0}h-{0}z"/>s   <pathr   z transform="scale({0})"s    stroke=s    d="rZ   r0  F)r-  Ts   "/>z' class="pyqrerr" stroke="red" d="{0}"/>s   </svg>
)	functoolsr$  xml.sax.saxutilsr%  r   rQ   r   r   r   r   close)#r   r   filer   r  r  r   xmldeclsvgnstitlesvgclass	lineclassomithwdebugr$  r%  r)  r3  f	autocloserQ   write_bytessize
debug_pathry   r   	wrote_bitrnumberr   start_columncoordr/   	colnumberr   r.  s#         `                           @r   _svgrK  S  sm   F "!!!!!******0 0 0Q Q Q
U U U U U U !t,,LAyGM17++E'K A?@@@K <:;;;w'%/1z>E3IJD 5)00667777&--d33444Jii!!"""K"))%00111 9j))	+ 	+ 	+Kzz'..u55666K   ii%%&&&Jii	""###KJ;
RqAI!$  	Q'nn 	> 	>NIsaxx! %$q(ATT!QCCCCE$v-AAF $I(1} >SAXX'')W"="==J 	q ATT!Q;;;;Ev%AIeK L LHA::E+22599:::7>>zJJKKKK 						 r    r   r   r   rm   rm   rm   rm   rm   c                     ddl }	 t                    n# t          $ r t          d          w xY w fd}	d }
|t          d          d} |
|          }|du }| |
|          nt          d |D                       }|dd	         d
k    o
 r|p|dk    }|r|rdnd}|s||gnd}r|                    d           d}t          |          } |	|          }t          |d          \  }}|                    ||||||          }	 |                    ||           |r|	                                 dS dS # |r|	                                 w w xY w)a  See: pyqrcode.QRCode.png()

    This function was abstracted away from QRCode to allow for the output of
    QR codes during the build process, i.e. for debugging. It works
    just the same except you must specify the code's version. This is needed
    to calculate the PNG's size.

    This method will write the given file out as a PNG file. Note, it
    depends on the PyPNG module to do this.

    :param module_color: Color of the QR code (default: ``(0, 0, 0, 255)`` (black))
    :param background: Optional background color. If set to ``None`` the PNG
            will have a transparent background.
            (default: ``(255, 255, 255, 255)`` (white))
    :param quiet_zone: Border around the QR code (also known as quiet zone)
            (default: ``4``). Set to zero (``0``) if the code shouldn't
            have a border.
    :param debug: Inidicates if errors in the QR code should be added (as red
            modules) to the output (default: ``False``).
    r   Nz&The scale parameter must be an integerc                    dgz  }dgz  }||rdgz  n|f}|z  }dg| z  gz  z  }g }|                     |           D ]{}g }|                     |           |D ]#}	|                     ||	dv r|	nd                    $|                     |           t                    D ]}
|                    |           ||                     |           |S )zTo perform the scaling we need to inflate the number of bits.
        The PNG library expects all of the bits when it draws the PNG.
        Effectively, we double, tripple, etc. the number of columns and
        the number of rows.
        r   r   r7   )r   r   )r~   ri   rN   )rD  blackwhitecolorsborder_moduler  r   r   tmp_rowr   r(   r   r@  r   r   s              r   
scale_codez_png.<locals>.scale_code  s7    ee %!B1#++UD 
*cDj\E)J6
  	J  	% 	%CG NN=)))  F FvcVmmssDEEEE NN=))) 5\\ % %G$$$$% 	Jr    c                    | dS t          | t          t          f          st          |           \  }}}|||dfS g }dt	          |           cxk    rdk    s$n t          d                    |                     | D ]R}t          |          }d|cxk    rdk    r&n n#|                    t          |                     Dt          d          t	          |          dk    r|                    d           t          |          S )	aL  This creates a palette color from a list or tuple. The list or
        tuple must be of length 3 (for rgb) or 4 (for rgba). The values
        must be between 0 and 255. Note rgb colors will be given an added
        alpha component set to 255.

        The pallete color is represented as a list, this is what is returned.
        Nr   rm   rY   r[   zFColors must be a list or tuple of length  3 or 4. You passed in "{0}".r   z*Color components must be between 0 and 255)	rM   tuplelist_hex_to_rgbr9   r   r   r.   rN   )colorrgrW   rgbacs         r   png_pallete_colorz_png.<locals>.png_pallete_color0  s     =2%%// 	 !%((GAq!aC<SZZ$$$$1$$$$ ==CVE]]L L L 	O 	OAAAA}}}}}}}}}CFF#### !MNNNt99>>KKT{{r    z!The module_color must not be Noner   c                     g | ]}d |z
  S )rm   r   )rx   r^  s     r   rz   z_png.<locals>.<listcomp>U  s     PiPiPi]^QTWXQXPiPiPir    rY   r   r   r   rM  )rm   r   r   rm   r7   r4  )widthheight	greyscaletransparentpalettebitdepth)
pngr.   r   rW  rN   r  r   WriterrQ   r8  )r   r   r9  r   r  r  r   r@  rh  rU  r_  rg  fg_colre  bg_colrd  transparent_colorrf  rD  	code_rowsrA  rB  ws   `  `  ``               r   _pngro    s    , JJJCE

 C C CABBBC4 4 4 4 4 4 4 4l  8 <===H|,,F$K /9.Dz***%PiPibhPiPiPiJjJjFrr
i'iY-F;-h&ThJhI(@Y@D&/9vvTG '((( %44D 
4  I !t,,LAy

di0'$ 	 	& 	&A	9 	GGIIIII	 	9 	GGIIII	s    4E E ra  c                 j   ddl m} ddl}ddlfd}	d }
d }t	          |d          \  }} ||	|j                  }t          j        |         |z  d|z  |z  z   } |d	            |d
            |d                    |	                    d                                |d            |d                    |                      |d            |d            |d           |dk    r|n
 ||          }|- | dj         ||                      |dk    r |d           |dk    r | dj        |            |dk    r |d                    |                      |d           t          j        |         |z   dz   }d}| D ]p}d}d}|dz  }d                    ||          }|D ]0}||k    r|r| |
||          z  }d}d}|}|dk    r|dz  }+|dz  }1|r| |
||          z  } ||           q |d            |d           |r|
                                 dS dS )a  This function writes the QR code out as an EPS document. The
    code is drawn by drawing only the modules corresponding to a 1. They
    are drawn using a line, such that contiguous modules in a row
    are drawn with a single line. The file parameter is used to
    specify where to write the document to. It can either be a writable (text)
    stream or a file path. The scale parameter is sets how large to draw
    a single module. By default one point (1/72 inch) is used to draw a single
    module. This may make the code to small to be read efficiently.
    Increasing the scale will make the code larger. This function will accept
    fractional scales (e.g. 2.5).

    :param module_color: Color of the QR code (default: ``(0, 0, 0)`` (black))
            The color can be specified as triple of floats (range: 0 .. 1) or
            triple of integers (range: 0 .. 255) or as hexadecimal value (i.e.
            ``#36c`` or ``#33B200``).
    :param background: Optional background color.
            (default: ``None`` (no background)). See `module_color` for the
            supported values.
    :param quiet_zone: Border around the QR code (also known as  quiet zone)
            (default: ``4``). Set to zero (``0``) if the code shouldn't
            have a border.
    r   r#  Nc                 f                         |d          D ]} | |            | d           dS )z-        Writes `content` and ``LF``.
        rm   r	  N)wrap)	writemethcontentr.  textwraps      r   
write_linez_eps.<locals>.write_line  sH    
 MM'3// 	 	DIdOOOIdOOOO	 	r    c                 p    d}| dk    rd                     |           }|d                     |          z  }|S )zM        Returns coordinates to draw a line with the provided length.
        rZ   r   z {0} 0 mz {0} 0 lr,  )offsetr/   ress      r   r.  z_eps.<locals>.line  sB     A::##F++Cz  (((
r    c                     d t          | t          t          f          st          |           } t          fd| D                       S )zp        Converts the provided color into an acceptable format for Postscript's
         ``setrgbcolor``
        c                    t          | t                    r3d| cxk    rdk    s$n t          d                    |                     | S d| cxk    rdk    s$n t          d                    |                     | dk    rd| z  n| S )	Ng        g      ?z(Invalid color "{0}". Not in range 0 .. 1r   rm   z*Invalid color "{0}". Not in range 0 .. 255r   gp?)rM   floatr   r   )clrs    r   to_floatz-_eps.<locals>.rgb_to_floats.<locals>.to_float  s    #u%% c((((S(((($%O&,fSkk3 3 3
????s???? !M"(&++/ / /$'1HH7S==#5r    c                 &    g | ]} |          S r   r   )rx   rj   r~  s     r   rz   z/_eps.<locals>.rgb_to_floats.<locals>.<listcomp>  s!    111ahhqkk111r    )rM   rW  rX  rY  )rZ  r~  s    @r   rgb_to_floatsz_eps.<locals>.rgb_to_floats  sZ    
		6 		6 		6 %%// 	'&&E11115111222r    rn  r7   z%!PS-Adobe-3.0 EPSF-3.0z<%%Creator: PyQRCode <https://pypi.python.org/pypi/PyQRCode/>z%%CreationDate: {0}z%Y-%m-%d %H:%M:%Sz%%DocumentData: Clean7Bitz%%BoundingBox: 0 0 {0} {0}z/M { moveto } bind defz/m { rmoveto } bind defz/l { rlineto } bind defra  z+{0:f} {1:f} {2:f} setrgbcolor clippath fillz0 0 0 setrgbcolorz{0:f} {1:f} {2:f} setrgbcolorr   z{0} {0} scalenewpathr0  z	{0} {1} Mstrokez%%EOF)r6  r$  timeru  r   rQ   r   r   r   strftimer8  )r   r   file_or_pathr   r  r  r   r$  r  rv  r.  r  rA  rB  	writelinerD  	mod_colorr   last_bitr   rx  r/   rI  r   ru  s                           @r   _epsr  r  sU   0 "!!!!!KKKOOO      3 3 3( !s33LAy
AG,,Iw'%/1z>E3IJDI'(((ILMMMI#**4==9L+M+MNNOOOI)***I*11$77888I&'''I'(((I'((( ,	 9 9}}\?Z?ZI	 ?==446 	7 	7 	7	!! I)***I	818)DEEEzz	/((//000Ii 	G$z1B6AH  	Q"":q11 
	 
	Ch TT&&111EFFaxx!! 	*TT&&)))E	%IhIg 						 r    c                 R   | d         dk    r
| dd         } t          |           dk    r#| d         dz  | d         dz  z   | d         dz  z   } t          |           dk    r"t          d                    |                     d	 | dd         | dd
         | d
d         fD             S )z]    Helper function to convert a color provided in hexadecimal format
    as RGB triple.
    r   #r   NrY   r7   rK   z#Input #{0} is not in #RRGGBB formatc                 .    g | ]}t          |d           S )   )r.   )rx   r(   s     r   rz   z_hex_to_rgb.<locals>.<listcomp>  s     CCC1C2JJCCCr    r[   )r9   r   r   )rZ  s    r   rY  rY    s    
 Qx3abb	
5zzQa1uQx!|+eAhl:
5zzQ>EEeLLMMMCCrrE!A#Jabb	 BCCCCr    )r[   )r  r  r[   )r   r[   )r   r  Nr[   TTNr   r!  FF)r   rL  rM  r[   F)r   ra  Nr[   )r   
__future__r   r   r   r   r   pyqrcode.tablesr   r   r&   r  r	   r   r  r  r  r  rK  ro  r  rY  r   r    r   <module>r     s  4 
 c b b b b b b b b b b b b b             				     [  [  [  [  [  [  [  [ J) ) )*	W 	W 	W 	WJ J J JX' ' ' 'R0 0 0 0d HLFP38F F F FR 5C>CS S S Sl =F%&x x x xvD D D D Dr    