
    Q/Ph?                     t   d dl mZ d dlZd dlmZ d dlZd dlZd dlZd dlZd dl	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mZ d dlmZ d d	lmZ d d
lmZ ddlmZ ddlmZmZ ej                            e          Zej         !                    dej        "                    ed                    Z# e$ e%e&j'         e(ej        "                    ed                    )                                                    Z* G d de+          Z,	 	 ddZ- G d de+          Z.d Z/ G d de+          Z0dS )    )divisionN)Random)
itemgetter)saxutils)Image)
ImageColor)	ImageDraw)ImageFilter)	ImageFont   )query_integral_image)unigrams_and_bigramsprocess_tokens	FONT_PATHzDroidSansMono.ttf	stopwordsc                        e Zd Zd Zd Zd ZdS )IntegralOccupancyMapc                    || _         || _        |Qt          j        t          j        d|z  d          d                              t          j                  | _        d S t          j        ||ft          j                  | _        d S )N   r   axisr   )dtype)heightwidthnpcumsumastypeuint32integralzeros)selfr   r   masks       S/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/wordcloud/wordcloud.py__init__zIntegralOccupancyMap.__init__'   s~    
Ibid
&C&C&C+,. . ..4fRY.?.? MMM Hfe_BIFFFDMMM    c                 0    t          | j        |||          S N)r   r   )r!   size_xsize_yrandom_states       r#   sample_positionz$IntegralOccupancyMap.sample_position1   s    #DM66$02 2 	2r%   c                    t          j        t          j        ||d |d f         d          d          }|dk    rK|dk    r.|| j        |dz
  |d f         | j        |dz
  |dz
  f         z
  z  }n|| j        |dz
  |d f         z  }|dk    r+|| j        |d |dz
  f         d d t           j        f         z  }|| j        |d |d f<   d S )Nr   r   r   )r   r   r   newaxis)r!   	img_arraypos_xpos_ypartial_integrals        r#   updatezIntegralOccupancyMap.update5   s   9RYy/H45&7 &7 &7=>@ @ @ 199qyy T]519eff3D%E'+}UQY	5I'J&K L   !DM%!)UVV2C$DD 199effeai.? @BJ OO(8effeffn%%%r%   N)__name__
__module____qualname__r$   r+   r2    r%   r#   r   r   &   sD        G G G2 2 29 9 9 9 9r%   r   c                 T    |t                      }d|                    dd          z  S )at  Random hue color generation.

    Default coloring method. This just picks a random hue with value 80% and
    lumination 50%.

    Parameters
    ----------
    word, font_size, position, orientation  : ignored.

    random_state : random.Random object or None, (default=None)
        If a random object is given, this is used for generating random
        numbers.

    Nzhsl(%d, 80%%, 50%%)r   r   )r   randint)word	font_sizepositionorientation	font_pathr*   s         r#   random_color_funcr>   F   s.      xx <#7#73#?#???r%   c                   "    e Zd ZdZd Z	 ddZdS )colormap_color_funczColor func created from matplotlib colormap.

    Parameters
    ----------
    colormap : string or matplotlib colormap
        Colormap to sample from

    Example
    -------
    >>> WordCloud(color_func=colormap_color_func("magma"))

    c                 F    dd l m} |                    |          | _        d S )Nr   )matplotlib.pyplotpyplotget_cmapcolormap)r!   rE   plts      r#   r$   zcolormap_color_func.__init__h   s+    ''''''X..r%   Nc                     |t                      }t          j        ddt          j        |                     |                    dd                              z            \  }}}	}
d                    |||	          S )Nr   r   r   rgb({:.0f}, {:.0f}, {:.0f}))r   r   maximumarrayrE   uniformformat)r!   r9   r:   r;   r<   r*   kwargsrgb_s              r#   __call__zcolormap_color_func.__call__l   s|    !88LZ3$--  A&&3( 3( *) *) $) * *
1a,33Aq!<<<r%   r'   )r3   r4   r5   __doc__r$   rR   r6   r%   r#   r@   r@   [   sF         / / /
 #= = = = = =r%   r@   c                     t          j        |           \  }}}dt          j        |z  |z  |z            \  }	 	 dfd	}|S )a  Create a color function which returns a single hue and saturation with.
    different values (HSV). Accepted values are color strings as usable by
    PIL/Pillow.

    >>> color_func1 = get_single_color_func('deepskyblue')
    >>> color_func2 = get_single_color_func('#00b4d2')
    g     o@Nc                     |t                      }t          j        	|                    dd                    \  }}}d                    |
z  |
z  |
z            S )a  Random color generation.

        Additional coloring method. It picks a random value with hue and
        saturation based on the color given to the generating function.

        Parameters
        ----------
        word, font_size, position, orientation  : ignored.

        random_state : random.Random object or None, (default=None)
          If a random object is given, this is used for generating random
          numbers.

        Ng?r   rH   )r   colorsys
hsv_to_rgbrK   rL   )r9   r:   r;   r<   r=   r*   rN   rO   rP   hrgb_maxss            r#   single_color_funcz0get_single_color_func.<locals>.single_color_func   sl      !88L%aL,@,@a,H,HII1a,33AKW45KA A 	Ar%   NNNNNN)r   getrgbrV   
rgb_to_hsv)	colorold_rold_gold_bvr[   rX   rY   rZ   s	         @@@r#   get_single_color_funcrd   u   s     %+E22E5%G!%'/57?"''/3 3GAq! ?CIMA A A A A A A A* r%   c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 ddZd Zd dZd Zd Zd Z	d Z
d Zd!dZd Zd Zd Zd"dZd Zd ZdS )#	WordClouduO  Word cloud object for generating and drawing.

    Parameters
    ----------
    font_path : string
        Font path to the font that will be used (OTF or TTF).
        Defaults to DroidSansMono path on a Linux machine. If you are on
        another OS or don't have this font, you need to adjust this path.

    width : int (default=400)
        Width of the canvas.

    height : int (default=200)
        Height of the canvas.

    prefer_horizontal : float (default=0.90)
        The ratio of times to try horizontal fitting as opposed to vertical.
        If prefer_horizontal < 1, the algorithm will try rotating the word
        if it doesn't fit. (There is currently no built-in way to get only
        vertical words.)

    mask : nd-array or None (default=None)
        If not None, gives a binary mask on where to draw words. If mask is not
        None, width and height will be ignored and the shape of mask will be
        used instead. All white (#FF or #FFFFFF) entries will be considerd
        "masked out" while other entries will be free to draw on. [This
        changed in the most recent version!]

    contour_width: float (default=0)
        If mask is not None and contour_width > 0, draw the mask contour.

    contour_color: color value (default="black")
        Mask contour color.

    scale : float (default=1)
        Scaling between computation and drawing. For large word-cloud images,
        using scale instead of larger canvas size is significantly faster, but
        might lead to a coarser fit for the words.

    min_font_size : int (default=4)
        Smallest font size to use. Will stop when there is no more room in this
        size.

    font_step : int (default=1)
        Step size for the font. font_step > 1 might speed up computation but
        give a worse fit.

    max_words : number (default=200)
        The maximum number of words.

    stopwords : set of strings or None
        The words that will be eliminated. If None, the build-in STOPWORDS
        list will be used. Ignored if using generate_from_frequencies.

    background_color : color value (default="black")
        Background color for the word cloud image.

    max_font_size : int or None (default=None)
        Maximum font size for the largest word. If None, height of the image is
        used.

    mode : string (default="RGB")
        Transparent background will be generated when mode is "RGBA" and
        background_color is None.

    relative_scaling : float (default='auto')
        Importance of relative word frequencies for font-size.  With
        relative_scaling=0, only word-ranks are considered.  With
        relative_scaling=1, a word that is twice as frequent will have twice
        the size.  If you want to consider the word frequencies and not only
        their rank, relative_scaling around .5 often looks good.
        If 'auto' it will be set to 0.5 unless repeat is true, in which
        case it will be set to 0.

        .. versionchanged: 2.0
            Default is now 'auto'.

    color_func : callable, default=None
        Callable with parameters word, font_size, position, orientation,
        font_path, random_state that returns a PIL color for each word.
        Overwrites "colormap".
        See colormap for specifying a matplotlib colormap instead.
        To create a word cloud with a single color, use
        ``color_func=lambda *args, **kwargs: "white"``.
        The single color can also be specified using RGB code. For example
        ``color_func=lambda *args, **kwargs: (255,0,0)`` sets color to red.

    regexp : string or None (optional)
        Regular expression to split the input text into tokens in process_text.
        If None is specified, ``r"\w[\w']+"`` is used. Ignored if using
        generate_from_frequencies.

    collocations : bool, default=True
        Whether to include collocations (bigrams) of two words. Ignored if using
        generate_from_frequencies.


        .. versionadded: 2.0

    colormap : string or matplotlib colormap, default="viridis"
        Matplotlib colormap to randomly draw colors from for each word.
        Ignored if "color_func" is specified.

        .. versionadded: 2.0

    normalize_plurals : bool, default=True
        Whether to remove trailing 's' from words. If True and a word
        appears with and without a trailing 's', the one with trailing 's'
        is removed and its counts are added to the version without
        trailing 's' -- unless the word ends with 'ss'. Ignored if using
        generate_from_frequencies.

    repeat : bool, default=False
        Whether to repeat words and phrases until max_words or min_font_size
        is reached.

    include_numbers : bool, default=False
        Whether to include numbers as phrases or not.

    min_word_length : int, default=0
        Minimum number of letters a word must have to be included.

    collocation_threshold: int, default=30
        Bigrams must have a Dunning likelihood collocation score greater than this
        parameter to be counted as bigrams. Default of 30 is arbitrary.

        See Manning, C.D., Manning, C.D. and Schütze, H., 1999. Foundations of
        Statistical Natural Language Processing. MIT press, p. 162
        https://nlp.stanford.edu/fsnlp/promo/colloc.pdf#page=22

    Attributes
    ----------
    ``words_`` : dict of string to float
        Word tokens with associated frequency.

        .. versionchanged: 2.0
            ``words_`` is now a dictionary

    ``layout_`` : list of tuples ((string, float), int, (int, int), int, color))
        Encodes the fitted word cloud. For each word, it encodes the string,
        normalized frequency, font size, position, orientation, and color.
        The frequencies are normalized by the most commonly occurring word.
        The color is in the format of 'rgb(R, G, B).'

    Notes
    -----
    Larger canvases make the code significantly slower. If you need a
    large word cloud, try a lower canvas size, and set the scale parameter.

    The algorithm might give more weight to the ranking of the words
    than their actual frequencies, depending on the ``max_font_size`` and the
    scaling heuristic.
    N        ?r      blackRGBautoTr   F   c                 B   |t           }|	+|)t          j        }|d         dk     r|d         dk     rd}nd}|| _        || _        || _        || _        || _        || _        || _	        || _
        || _        || _        || _        |	pt          |          | _        |
| _        ||nt"          | _        || _        || _        || _        t-          |t.                    rt1          |          }|| _        || _        || _        || _        |dk    r|rd}nd}|dk     s|d	k    rt;          d
|z            || _        |t?          j         dtB                     || _"        || _#        || _$        || _%        || _&        |&|j'        d	         | _        |j'        d         | _        d S d S )Nr   2ri   5hsvviridisrn   g      ?r   z5relative_scaling needs to be between 0 and 1, got %f.z]ranks_only is deprecated and will be removed as it had no effect. Look into relative_scaling.)(r   
matplotlib__version__rE   collocationsr=   r   r   marginprefer_horizontalr"   contour_colorcontour_widthscaler@   
color_func	max_words	STOPWORDSr   min_font_size	font_stepregexp
isinstanceintr   r*   background_colormax_font_sizemode
ValueErrorrelative_scalingwarningswarnDeprecationWarningnormalize_pluralsrepeatinclude_numbersmin_word_lengthcollocation_thresholdshape)r!   r=   r   r   rx   
ranks_onlyry   r"   r|   r}   r~   r   r   r*   r   r   r   r   r   r   rw   rE   r   r{   rz   r   r   r   r   versions                                 r#   r$   zWordCloud.__init__5  s    !I("2 ,GqzCGAJ$4$4 $ ("
!2	**
$E(;H(E(E"&/&;*"lC(( 	0!,//L( 0*	v%% &#$  #% a#3a#7#7 8:JK L L L 0!M K,. . . "3..%:" ADJ*Q-DKKK r%   c                 ,    |                      |          S )a!  Create a word_cloud from words and frequencies.

        Alias to generate_from_frequencies.

        Parameters
        ----------
        frequencies : dict from string to float
            A contains words and associated frequency.

        Returns
        -------
        self
        )generate_from_frequencies)r!   frequenciess     r#   	fit_wordszWordCloud.fit_wordsw  s     --k:::r%   c                 
   ! t          |                                t          d          d          }t          |          dk    rt	          dt          |          z            |d| j                 }t          |d         d                   !!fd|D             }| j        | j        }nt                      }| j	        ?| 
                    | j	                  }| j	        j        d         }| j	        j        d         }nd}| j        | j        }}t          |||          }t          j        d||f          }t#          j        |          }	t'          j        |          }
g g g g f\  }}}}d	}|| j        }|t          |          dk    r| j        }n|                     t/          |dd
                   | j                   d | j        D             }	 t3          d
|d         z  |d         z  |d         |d         z   z            }n9# t4          $ r* 	 |d         }n# t4          $ r t	          d          w xY wY nw xY w|}t/          |          | _        | j        rt          |          | j        k     rt3          t'          j        | j        t          |          z                      dz
  }t=          |          }|d         d         t?          |          D ]$ |                      fd|D                        %|D ]P\  }}|dk    r| j!        }|dk    r8t3          tE          ||t          |          z  z  d|z
  z   |z                      }|#                                | j$        k     rd}nt          j%        }d}	 || j&        k     rntO          j(        | j)        |          }tO          j*        ||          }|	+                    d||d          }|,                    |d         | j-        z   |d
         | j-        z   |          }|n7|s(| j$        dk     r|t          j%        nt          j%        }d}n|| j.        z  }d}|| j&        k     r nt'          j/        |          | j-        d
z  z   \  }}|	0                    ||f|d|           |1                    ||f           |1                    |           |1                    |           |1                    | 2                    ||||f||| j)                             | j	        t'          j        |          }
nt'          j        |          |z   }
|3                    |
||           |}Rt=          ti          |||||                    | _        | S )aO  Create a word_cloud from words and frequencies.

        Parameters
        ----------
        frequencies : dict from string to float
            A contains words and associated frequency.

        max_font_size : int
            Use this font-size instead of self.max_font_size

        Returns
        -------
        self

        r   T)keyreverser   z5We need at least 1 word to plot a word cloud, got %d.Nc                 $    g | ]\  }}||z  fS r6   r6   ).0r9   freqmax_frequencys      r#   
<listcomp>z7WordCloud.generate_from_frequencies.<locals>.<listcomp>  s7     6 6 6%4 d]23 6 6 6r%   Lg      ?ri   )r   c                     g | ]
}|d          S r   r6   )r   xs     r#   r   z7WordCloud.generate_from_frequencies.<locals>.<listcomp>  s    444!1444r%   zhCouldn't find space to draw. Either the Canvas size is too small or too much of the image is masked out.c                 0    g | ]\  }}||d z   z  z  fS r   r6   )r   r9   r   
downweightis      r#   r   z7WordCloud.generate_from_frequencies.<locals>.<listcomp>  sF     $G $G $G(2d &*4*Q2G+G$H $G $G $Gr%   Fr<   )r   r   lt)fontanchor   whitefillr   )r:   r;   r<   r*   r=   )5sorteditemsr   lenr   r~   floatr*   r   r"   _get_bolean_maskr   r   r   r   r   newr	   Drawr   asarrayr   r   dictlayout_r   
IndexErrorwords_r   ceillistrangeextendr   roundrandomry   	ROTATE_90r   r   truetyper=   TransposedFonttextbboxr+   rx   r   rJ   textappendr}   r2   zip)"r!   r   r   r*   boolean_maskr   r   	occupancyimg_greydrawr.   
font_sizes	positionsorientationscolors	last_freqr:   sizestimes_extendfrequencies_orgr9   r   rsr<   tried_other_orientationr   transposed_fontbox_sizeresultr   yr   r   r   s"                                  @@@r#   r   z#WordCloud.generate_from_frequencies  s}   " [..00jmmTRRR{q   '),[)9)9: ; ; ;!/4>/2 k!nQ/006 6 6 6)46 6 6 (,LL!88L9 00;;LIOA&EY_Q'FFL KEF(EE	 9S5&/22~h''Jx((	68"b"n3
I|V	  .M  ;1$$ K		..tKO/D/D=A[ / J J J 54t|444$ #AaL58$;',Qx%(':%< != !=II " $ $ $$$)!H		% $ $ $(#$ $ $$ "	$ &I ;''; 	H3{++dn<<rwt~K8H8H'HIIJJQNL";//O$R+J<(( H H"" $G $G $G $G $G6E$G $G $G H H H H & @	 @	JD$qyy&BQwwrTE)4D4D-D'E*+b&(25>'? !@ !@ A A	""$$t'==="#o&+#'t111 )$.)DD"+":k#3 #3 #3  ==OTX=YY"228A;3L3;A;3L3?A A % / '43IA3M3M6A6I5??#(?  .2++/I"&K5'8 4---8F##dkQ&66DAqIIq!fdIGGGaV$$$,,,i(((MM$//$)45q66A7C48N	 * D D E E E y Jx00		Jx00<?	 Y1---IICZ ,f6 6 7 7s*   3H 
I H I  H::I ?I c                     t           j        dk     r"t          |          t          u rt          j        nd} j        dk    rdnd} j         j        n|}t	          j        |||          }d |D             } j	        sd |D             } j        r fd	|D             }t          d
  j        D                        j        rt          | j         j                  }n&fd|D             }t!          | j                  \  }}|S )a  Splits a long text into words, eliminates the stopwords.

        Parameters
        ----------
        text : string
            The text to be processed.

        Returns
        -------
        words : dict (string, int)
            Word tokens with associated frequency.

        ..versionchanged:: 1.2.2
            Changed return type from list of tuples to dict.

        Notes
        -----
        There are better ways to do word tokenization, but I don't want to
        include all those things.
        3r   r   z\w[\w']*z\w[\w']+Nc                 t    g | ]5}|                                                     d           r
|dd         n|6S )z'sN)lowerendswithr   r9   s     r#   r   z*WordCloud.process_text.<locals>.<listcomp>K  sO     $ $ $ #jjll33D99Ccrct $ $ $r%   c                 :    g | ]}|                                 |S r6   )isdigitr   s     r#   r   z*WordCloud.process_text.<locals>.<listcomp>O  s%    BBBd4<<>>BTBBBr%   c                 D    g | ]}t          |          j        k    |S r6   )r   r   )r   r9   r!   s     r#   r   z*WordCloud.process_text.<locals>.<listcomp>R  s,    QQQds4yyD<P/P/PT/P/P/Pr%   c                 6    g | ]}|                                 S r6   r   )r   r   s     r#   r   z*WordCloud.process_text.<locals>.<listcomp>T  s     ;;;q;;;r%   c                 @    g | ]}|                                 v|S r6   r   )r   r9   r   s     r#   r   z*WordCloud.process_text.<locals>.<listcomp>Y  s+    MMMdtzz||9/L/LT/L/L/Lr%   )sysr   typeunicodereUNICODEr   r   findallr   setr   rw   r   r   r   r   )	r!   r   flagspatternr   wordsword_countsrQ   r   s	   `       @r#   process_textzWordCloud.process_text.  sN   ,  #{S00T$ZZ75J5J 	!%!5!:!:++ $ 7W
64//$ $"$ $ $ # 	CBBeBBBE 	RQQQQeQQQE;;DN;;;<<	 	K.uiAWY]YsttKK NMMMeMMME+E43IJJNKr%   c                 Z    |                      |          }|                     |           | S )a  Generate wordcloud from text.

        The input "text" is expected to be a natural text. If you pass a sorted
        list of words, words will appear in your output twice. To remove this
        duplication, set ``collocations=False``.

        Calls process_text and generate_from_frequencies.

        ..versionchanged:: 1.2.2
            Argument of generate_from_frequencies() is not return of
            process_text() any more.

        Returns
        -------
        self
        )r   r   )r!   r   r   s      r#   generate_from_textzWordCloud.generate_from_text^  s0    " !!$''&&u---r%   c                 ,    |                      |          S )a  Generate wordcloud from text.

        The input "text" is expected to be a natural text. If you pass a sorted
        list of words, words will appear in your output twice. To remove this
        duplication, set ``collocations=False``.

        Alias to generate_from_text.

        Calls process_text and generate_from_frequencies.

        Returns
        -------
        self
        )r   )r!   r   s     r#   generatezWordCloud.generates  s     &&t,,,r%   c                 D    t          | d          st          d          dS )z9Check if ``layout_`` was computed, otherwise raise error.r   z7WordCloud has not been calculated, call generate first.N)hasattrr   r!   s    r#   _check_generatedzWordCloud._check_generated  s5    tY'' 	( ' ( ( (	( 	(r%   c                    |                                   | j        %| j        j        d         }| j        j        d         }n| j        | j        }}t          j        | j        t          || j	        z            t          || j	        z            f| j
                  }t          j        |          }| j        D ]\  \  }}}}}	}
t          j        | j        t          || j	        z                      }t          j        ||	          }t          |d         | j	        z            t          |d         | j	        z            f}|                    |||
|           |                     |          S )Nr   r   r   r   )img)r   r"   r   r   r   r   r   r   r   r|   r   r	   r   r   r   r   r=   r   r   _draw_contour)r!   r   r   r   r   r9   countr:   r;   r<   r_   r   r   poss                 r#   to_imagezWordCloud.to_image  sj   9 IOA&EY_Q'FF KEFi	C
(:$;$;$'(;$<$<$>-/ / ~c""FJl 	C 	CBMT59hU%dn&))dj*@&A&AC CD'6+/ / /Ox{TZ/00x{TZ/002CIIc4e/IBBBB!!c!***r%   c                      t          t                    rt                                                      | j        nt          |           fd j        D              _         S )a:  Recolor existing layout.

        Applying a new coloring is much faster than generating the whole
        wordcloud.

        Parameters
        ----------
        random_state : RandomState, int, or None, default=None
            If not None, a fixed random state is used. If an int is given, this
            is used as seed for a random.Random state.

        color_func : function or None, default=None
            Function to generate new color from word count, font size, position
            and orientation.  If None, self.color_func is used.

        colormap : string or matplotlib colormap, default=None
            Use this colormap to generate new colors. Ignored if color_func
            is specified. If None, self.color_func (or self.color_map) is used.

        Returns
        -------
        self
        Nc                 ^    g | ])\  }}}}}|||| |d          |||j                   f*S )r   )r9   r:   r;   r<   r*   r=   )r=   )	r   	word_freqr:   r;   r<   rQ   r}   r*   r!   s	         r#   r   z%WordCloud.recolor.<locals>.<listcomp>  sj     ) ) )
 KIy(K #Ix#1-5;1=.2n> > >? ) ) )r%   )r   r   r   r   r}   r@   r   )r!   r*   r}   rE   s   ``` r#   recolorzWordCloud.recolor  s    0 lC(( 	0!,//L!_

0::
) ) ) ) ) )  <) ) ) r%   c                 \    |                                  }|                    |d           | S )zExport to image file.

        Parameters
        ----------
        filename : string
            Location to write to.

        Returns
        -------
        self
        T)optimize)r  save)r!   filenamer   s      r#   to_filezWordCloud.to_file  s,     mmooD)))r%   c                 N    t          j        |                                           S zConvert to numpy array.

        Returns
        -------
        image : nd-array size (width, height, 3)
            Word cloud image as numpy matrix.
        )r   rJ   r  r   s    r#   to_arrayzWordCloud.to_array  s     x(((r%   c                 *    |                                  S r  )r  r   s    r#   	__array__zWordCloud.__array__  s     }}r%   c                    |                                   | j        %| j        j        d         }| j        j        d         }n| j        | j        }}| j        t          d | j        D                       }n| j        }g }t          j	        | j
        t          || j        z                      }|                                \  }	}
t          |	          }|
                                }
d|
v rd}nd}d|
v rd}n	d|
v rd}nd}|                    d	                    || j        z  || j        z                       |rddl}ddl}|j                            | |d
          }|j                            | j
        |          }|j                            |          }d | j        D             }d                    |          }|                    |           |                    |           t5          j                    }|                    |           |                    d           |j                            d          }|                     |           t5          j                    }|!                    |           tE          j#        |$                                          %                    d          }d|z   }|                    d                    ||||                     |                    d                    |||                     | j&        -|                    d                    | j&                             |r| '                                }t5          j                    }|!                    |d           tE          j#        |$                                          %                    d          }|                    d                    |                     | j        D ]e\  \  }}}\  }}}}|| j        z  }|| j        z  }t          j	        | j
        t          || j        z                      }|j(        )                    |          \  \  } }!\  }"}#|*                                \  }$}%|" }&| |"z
  }'|$|#z
  }(i })|tV          j,        k    r$||(z  }||'|&z
  z  }d                    ||          }*n ||&z  }||(z  }d                    ||          }*d                    d |)-                                D                       })|                    d                    |*|| j        z  |t]          j/        |                               g|                    d           d                    |          S ) aA  Export to SVG.

        Font is assumed to be available to the SVG reader. Otherwise, text
        coordinates may produce artifacts when rendered with replacement font.
        It is also possible to include a subset of the original font in WOFF
        format using ``embed_font`` (requires `fontTools`).

        Note that some renderers do not handle glyphs the same way, and may
        differ from ``to_image`` result. In particular, Complex Text Layout may
        not be supported. In this typesetting, the shape or positioning of a
        grapheme depends on its relation to other graphemes.

        Pillow, since version 4.2.0, supports CTL using ``libraqm``. However,
        due to dependencies, this feature is not always enabled. Hence, the
        same rendering differences may appear in ``to_image``. As this
        rasterized output is used to compute the layout, this also affects the
        layout generation. Use ``PIL.features.check`` to test availability of
        ``raqm``.

        Consistant rendering is therefore expected if both Pillow and the SVG
        renderer have the same support of CTL.

        Contour drawing is not supported.

        Parameters
        ----------
        embed_font : bool, default=False
            Whether to include font inside resulting SVG file.

        optimize_embedded_font : bool, default=True
            Whether to be aggressive when embedding a font, to reduce size. In
            particular, hinting tables are dropped, which may introduce slight
            changes to character shapes (w.r.t. `to_image` baseline).

        embed_image : bool, default=False
            Whether to include rasterized image inside resulting SVG file.
            Useful for debugging.

        Returns
        -------
        content : string
            Word cloud image as SVG string
        Nr   r   c              3   &   K   | ]}|d          V  dS )r   Nr6   )r   ws     r#   	<genexpr>z#WordCloud.to_svg.<locals>.<genexpr>+  s&      ;;!;;;;;;r%   boldnormalitalicobliquez?<svg xmlns="http://www.w3.org/2000/svg" width="{}" height="{}">T)hintingdesubroutinizeignore_missing_glyphsc                 4    h | ]}|d          d          D ]}|S )r   r6   )r   itemcs      r#   	<setcomp>z#WordCloud.to_svg.<locals>.<setcomp>h  s-    IIId1gajII!IIIIr%    )r   woff)flavorasciiz0data:application/font-woff;charset=utf-8;base64,ze<style>@font-face{{font-family:{};font-weight:{};font-style:{};src:url("{}")format("woff");}}</style>zC<style>text{{font-family:{};font-weight:{};font-style:{};}}</style>z8<rect width="100%" height="100%" style="fill:{}"></rect>JPEGrL   zC<image width="100%" height="100%" href="data:image/jpg;base64,{}"/>ztranslate({},{}) rotate(-90)ztranslate({},{}) c              3   H   K   | ]\  }}d                      ||          V  dS )z{}="{}"Nr%  )r   krc   s      r#   r  z#WordCloud.to_svg.<locals>.<genexpr>  s6      !X!XTQ)"2"21a"8"8!X!X!X!X!X!Xr%   z=<text transform="{}" font-size="{}" style="fill:{}">{}</text>z</svg>
)0r   r"   r   r   r   r   maxr   r   r   r=   r   r|   getnamereprr   r   rL   	fontToolsfontTools.subsetsubsetOptions	load_font	SubsetterjoinpopulateioBytesIOsaveXMLseekttLibTTFont	importXMLr	  base64	b64encode	getbufferdecoder   r  r   getsize
getmetricsr   r   r   r   escape)+r!   
embed_fontoptimize_embedded_fontembed_imager   r   r   r   r   raw_font_familyraw_font_stylefont_familyfont_weight
font_styler-  optionsttf	subsetter
charactersr   bufferr!  dataurlimager9   r   r:   r   r   r<   r_   r(   r)   offset_xoffset_yascentdescentmin_xmax_xmax_y
attributes	transforms+                                              r#   to_svgzWordCloud.to_svg  s   ` 	 9 IOA&EY_Q'FF KEF %;;dl;;;;;MM .M  !$.#mdj6P2Q2QRR*.,,..'?++'--//^## KK"K~%%!JJ.(("JJ!J 	
 V
"# 
	
 
	
 
	
  7	 ####  &.. 32  6 '+ / 
 
G ",,T^WEEC!(227;;IIIIIIJ77:&&DD)))S!!! Z\\FKKKKNNN?)))88DNN6""" Z\\FIIf#F$4$4$6$677>>wGGDDtKCMM 	   $ 	 V 	
 	
 	
   ,MM -..    	MMOOE:<<DJJtFJ+++#DNN$4$455<<WEEDMM
    EIL )	 )	@MT59fq!k5OAOA %dnc)dj:P6Q6QRRD59Y5F5Ft5L5L2VV2x"oo//OFG IEX%EX%E Jeo--U
UU]":AA!QGG		U
U
.55a;;	 !X!XZEUEUEWEW!X!X!XXXJMM 
*OD))	    & 	hyy   r%   c                 $   |j         j        dk    rt          j        d           |j        dk    r|dk    }nY|j        dk    r*t          j        |ddddddf         dk    d          }n$t          d	t          |j	                  z            |S )
z%Cast to two dimensional boolean mask.fzGmask image should be unsigned byte between 0 and 255. Got a float arrayri   r   r   Nr   r   zGot mask of invalid shape: %s)
r   kindr   r   ndimr   allr   strr   )r!   r"   r   s      r#   r   zWordCloud._get_bolean_mask  s    :?c!!M 8 9 9 99>>3;LLY!^^6$qqq!!!RaRx.C"7bAAALL<s4:NOOOr%   c                    | j         | j        dk    r|S |                     | j                   dz  }t          j        |                    t          j                            }|                    |j	                  }|
                    t          j                  }t          j        |          }d|ddgddf<   d|ddddgf<   | j        dz  }t          j        |          }|
                    t          j        |                    }t          j        |          dk    }t          j        |||f          }t          j        |          t          j        |          z  }| j        dk    r?t          j        |j        |j	        | j                  }|t          j        |          |z  z  }t          j        |          S )z$Draw mask contour on a pillow image.Nr   r   r   
   )radiusrl   )r"   r{   r   r   	fromarrayr   r   uint8resizesizefilterr
   
FIND_EDGESrJ   GaussianBlurdstackinvertrz   r   r   )r!   r   r"   contourre  retr_   s          r#   r   zWordCloud._draw_contour  s   9 2a 7 7J$$TY//#5/$++bh"7"788..**..!788(7##  B
Ar7
 #b(/'**..!9!H!H!HII(7##a')Wgw788 hsmmbi000((Ich$2DEEE28E??W,,Cs###r%   )Nrg   rh   ri   Nrj   Nr   Nrh   rk   NNrl   Nr   rm   rn   NTNTr   rl   FFr   ro   r'   )NNN)FTF)r3   r4   r5   rS   r$   r   r   r   r   r   r   r  r  r  r  r  r\  r   r   r6   r%   r#   rf   rf      sF       X Xt FGIJ?@EL7<DHFG/4QS@( @( @( @(D; ; ; e e e eN. . .`  *- - -"( ( (+ + +.( ( ( (T  ") ) )  v! v! v! v!p  $ $ $ $ $r%   rf   r\   )1
__future__r   r   r   r   r5  osr   r<  r   rV   ru   numpyr   operatorr   xml.saxr   PILr   r   r	   r
   r   r   tokenizationr   r   pathdirname__file__FILEenvirongetr3  r   r   maprb  stripopen	readlinesr   objectr   r>   r@   rd   rf   r6   r%   r#   <module>r     si                 				 				 				  



                                                    6 6 6 6 6 6 > > > > > > > >	wx  JNN;T;N(O(OPP	CCIttBGLL{$C$CDDNNPPQQRR	9 9 9 9 96 9 9 9@ ;?EI@ @ @ @*= = = = =& = = =4" " "Jx$ x$ x$ x$ x$ x$ x$ x$ x$ x$r%   