wordcloud.py 19.6 KB
Newer Older
Andreas Mueller's avatar
Andreas Mueller committed
1
2
# Author: Andreas Christian Mueller <t3kcit@gmail.com>
#
3
4
5
6
7
# (c) 2012
# Modified by: Paul Nechifor <paul@nechifor.net>
#
# License: MIT

Andreas Mueller's avatar
Andreas Mueller committed
8
import warnings
9
from random import Random
10
11
import os
import re
12
import sys
13
import colorsys
14
15
16
17
import numpy as np
from operator import itemgetter

from PIL import Image
18
from PIL import ImageColor
19
20
from PIL import ImageDraw
from PIL import ImageFont
21

22
from .query_integral_image import query_integral_image
23
24
25

item1 = itemgetter(1)

26
27
FONT_PATH = os.environ.get("FONT_PATH", os.path.join(os.path.dirname(__file__),
                                                     "DroidSansMono.ttf"))
28
29
30
31
STOPWORDS = set([x.strip() for x in open(os.path.join(os.path.dirname(__file__),
                                                      'stopwords')).read().split('\n')])


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class IntegralOccupancyMap(object):
    def __init__(self, height, width, mask):
        self.height = height
        self.width = width
        if mask is not None:
            # the order of the cumsum's is important for speed ?!
            self.integral = np.cumsum(np.cumsum(255 * mask, axis=1),
                                      axis=0).astype(np.uint32)
        else:
            self.integral = np.zeros((height, width), dtype=np.uint32)

    def sample_position(self, size_x, size_y, random_state):
        return query_integral_image(self.integral, size_x, size_y, random_state)

    def update(self, img_array, pos_x, pos_y):
        partial_integral = np.cumsum(np.cumsum(img_array[pos_x:, pos_y:], axis=1),
                                     axis=0)
        # paste recomputed part into old image
        # if x or y is zero it is a bit annoying
        if pos_x > 0:
            if pos_y > 0:
                partial_integral += (self.integral[pos_x - 1, pos_y:]
                                     - self.integral[pos_x - 1, pos_y - 1])
            else:
                partial_integral += self.integral[pos_x - 1, pos_y:]
        if pos_y > 0:
            partial_integral += self.integral[pos_x:, pos_y - 1][:, np.newaxis]

        self.integral[pos_x:, pos_y:] = partial_integral


Andreas Mueller's avatar
Andreas Mueller committed
63
64
def random_color_func(word=None, font_size=None, position=None,
                      orientation=None, font_path=None, random_state=None):
Andreas Mueller's avatar
Andreas Mueller committed
65
66
67
68
69
70
71
72
73
74
75
76
77
    """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.

    """
78
    if random_state is None:
79
        random_state = Random()
80
81
    return "hsl(%d, 80%%, 50%%)" % random_state.randint(0, 255)

82

83
84
85
86
87
88
89
90
91
def get_single_color_func(color):
    """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')
    """
    old_r, old_g, old_b = ImageColor.getrgb(color)
    rgb_max = 255.
92
93
    h, s, v = colorsys.rgb_to_hsv(old_r / rgb_max, old_g / rgb_max, old_b / rgb_max)

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    def single_color_func(word=None, font_size=None, position=None,
                          orientation=None, font_path=None, random_state=None):
        """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.

        """
        if random_state is None:
            random_state = Random()
        r, g, b = colorsys.hsv_to_rgb(h, s, random_state.uniform(0.2, 1))
        return 'rgb({:.0f}, {:.0f}, {:.0f})'.format(r * rgb_max, g * rgb_max, b * rgb_max)
    return single_color_func

115
116
117
118
119
120
121
122

class WordCloud(object):
    """Word cloud object for generating and drawing.

    Parameters
    ----------
    font_path : string
        Font path to the font that will be used (OTF or TTF).
Andreas Mueller's avatar
Andreas Mueller committed
123
124
        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.
125
126
127
128
129
130
131

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

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

Andreas Mueller's avatar
Andreas Mueller committed
132
    prefer_horizontal : float (default=0.90)
133
134
135
        The ratio of times to try horizontal fitting as opposed to vertical.

    mask : nd-array or None (default=None)
Andreas Mueller's avatar
Andreas Mueller committed
136
137
138
139
140
        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!]
141

142
143
144
145
146
    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.

147
148
149
150
151
152
153
154
    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.

Andreas Mueller's avatar
Andreas Mueller committed
155
    max_words : number (default=200)
156
157
158
159
160
        The maximum number of words.

    stopwords : set of strings
        The words that will be eliminated.

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

Andreas Mueller's avatar
Andreas Mueller committed
164
165
166
    max_font_size : int or None (default=None)
        Maximum font size for the largest word. If None, height of the image is
        used.
167

168
    mode : string (default="RGB")
169
170
        Transparent background will be generated when mode is "RGBA" and
        background_color is None.
Andreas Mueller's avatar
Andreas Mueller committed
171

172
173
174
175
176
177
178
    relative_scaling : float (default=0)
        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.

Andreas Mueller's avatar
Andreas Mueller committed
179
180
181
182
    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.

183
184
    Attributes
    ----------
Andreas Mueller's avatar
Andreas Mueller committed
185
    ``words_``: list of tuples (string, float)
186
187
        Word tokens with associated frequency.

Andreas Mueller's avatar
Andreas Mueller committed
188
    ``layout_`` : list of tuples (string, int, (int, int), int, color))
189
190
        Encodes the fitted word cloud. Encodes for each word the string, font
        size, position, orientation and color.
191
192
193
194
195
196
197
198
199

    Notes
    -----
    Larger canvases with 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.
200
201
    """

202
    def __init__(self, font_path=None, width=400, height=200, margin=2,
203
                 ranks_only=None, prefer_horizontal=0.9, mask=None, scale=1,
204
205
                 color_func=random_color_func, max_words=200, min_font_size=4,
                 stopwords=None, random_state=None, background_color='black',
Andreas Mueller's avatar
Andreas Mueller committed
206
                 max_font_size=None, font_step=1, mode="RGB", relative_scaling=0, regexp=None):
207
208
209
210
211
212
213
214
215
216
        if font_path is None:
            font_path = FONT_PATH
        self.font_path = font_path
        self.width = width
        self.height = height
        self.margin = margin
        self.prefer_horizontal = prefer_horizontal
        self.mask = mask
        self.scale = scale
        self.color_func = color_func
Andreas Mueller's avatar
Andreas Mueller committed
217
        self.max_words = max_words
218
        self.stopwords = stopwords or STOPWORDS
219
220
        self.min_font_size = min_font_size
        self.font_step = font_step
Andreas Mueller's avatar
Andreas Mueller committed
221
        self.regexp = regexp
222
223
224
        if isinstance(random_state, int):
            random_state = Random(random_state)
        self.random_state = random_state
225
        self.background_color = background_color
Andreas Mueller's avatar
Andreas Mueller committed
226
227
228
        if max_font_size is None:
            max_font_size = height
        self.max_font_size = max_font_size
229
        self.mode = mode
230
231
232
233
234
235
236
        if relative_scaling < 0 or relative_scaling > 1:
            raise ValueError("relative_scaling needs to be between 0 and 1, got %f."
                             % relative_scaling)
        self.relative_scaling = relative_scaling
        if ranks_only is not None:
            warnings.warn("ranks_only is deprecated and will be removed as"
                          " it had no effect. Look into relative_scaling.", DeprecationWarning)
237

238
239
240
241
    def fit_words(self, frequencies):
        """Create a word_cloud from words and frequencies.

        Alias to generate_from_frequencies.
242
243
244

        Parameters
        ----------
245
        frequencies : array of tuples
246
247
248
249
            A tuple contains the word and its frequency.

        Returns
        -------
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
        self
        """
        return self.generate_from_frequencies(frequencies)

    def generate_from_frequencies(self, frequencies):
        """Create a word_cloud from words and frequencies.

        Parameters
        ----------
        frequencies : array of tuples
            A tuple contains the word and its frequency.

        Returns
        -------
        self
265
266

        """
267
        # make sure frequencies are sorted and normalized
268
        frequencies = sorted(frequencies, key=item1, reverse=True)
269
270
        frequencies = frequencies[:self.max_words]
        # largest entry will be 1
271
        max_frequency = float(frequencies[0][1])
272

273
        frequencies = [(word, freq / max_frequency) for word, freq in frequencies]
274

275
276
        self.words_ = frequencies

277
278
279
280
        if self.random_state is not None:
            random_state = self.random_state
        else:
            random_state = Random()
281

282
        if len(frequencies) <= 0:
283
            print("We need at least 1 word to plot a word cloud, got %d."
284
                  % len(frequencies))
285
286

        if self.mask is not None:
287
            mask = self.mask
Andreas Mueller's avatar
Andreas Mueller committed
288
289
            width = mask.shape[1]
            height = mask.shape[0]
290
            if mask.dtype.kind == 'f':
Andreas Mueller's avatar
Andreas Mueller committed
291
                warnings.warn("mask image should be unsigned byte between 0 and"
Andreas Mueller's avatar
Andreas Mueller committed
292
                              " 255. Got a float array")
Andreas Mueller's avatar
Andreas Mueller committed
293
294
295
            if mask.ndim == 2:
                boolean_mask = mask == 255
            elif mask.ndim == 3:
Andreas Mueller's avatar
Andreas Mueller committed
296
297
                # if all channels are white, mask out
                boolean_mask = np.all(mask[:, :, :3] == 255, axis=-1)
Andreas Mueller's avatar
Andreas Mueller committed
298
            else:
299
                raise ValueError("Got mask of invalid shape: %s" % str(mask.shape))
300
        else:
301
            boolean_mask = None
Andreas Mueller's avatar
Andreas Mueller committed
302
            height, width = self.height, self.width
303
        occupancy = IntegralOccupancyMap(height, width, boolean_mask)
304
305
306
307
308
309
310

        # create image
        img_grey = Image.new("L", (width, height))
        draw = ImageDraw.Draw(img_grey)
        img_array = np.asarray(img_grey)
        font_sizes, positions, orientations, colors = [], [], [], []

Andreas Mueller's avatar
Andreas Mueller committed
311
        font_size = self.max_font_size
312
        last_freq = 1.
313
314

        # start drawing grey image
315
        for word, freq in frequencies:
316
317
318
319
            # select the font size
            rs = self.relative_scaling
            if rs != 0:
                font_size = int(round((rs * (freq / float(last_freq)) + (1 - rs)) * font_size))
320
321
322
323
            while True:
                # try to find a position
                font = ImageFont.truetype(self.font_path, font_size)
                # transpose font optionally
324
                if random_state.random() < self.prefer_horizontal:
325
326
327
328
329
330
                    orientation = None
                else:
                    orientation = Image.ROTATE_90
                transposed_font = ImageFont.TransposedFont(font,
                                                           orientation=orientation)
                # get size of resulting text
331
                box_size = draw.textsize(word, font=transposed_font)
332
                # find possible places using integral image:
333
334
335
                result = occupancy.sample_position(box_size[1] + self.margin,
                                                   box_size[0] + self.margin,
                                                   random_state)
336
337
338
                if result is not None or font_size == 0:
                    break
                # if we didn't find a place, make font smaller
339
                font_size -= self.font_step
340

341
            if font_size < self.min_font_size:
342
343
344
345
346
                # we were unable to draw any more
                break

            x, y = np.array(result) + self.margin // 2
            # actually draw the text
347
            draw.text((y, x), word, fill="white", font=transposed_font)
348
349
350
            positions.append((x, y))
            orientations.append(orientation)
            font_sizes.append(font_size)
Andreas Mueller's avatar
Andreas Mueller committed
351
352
353
354
355
            colors.append(self.color_func(word, font_size=font_size,
                                          position=(x, y),
                                          orientation=orientation,
                                          random_state=random_state,
                                          font_path=self.font_path))
356
            # recompute integral image
Andreas Mueller's avatar
Andreas Mueller committed
357
358
359
            if self.mask is None:
                img_array = np.asarray(img_grey)
            else:
Andreas Mueller's avatar
Andreas Mueller committed
360
                img_array = np.asarray(img_grey) + boolean_mask
361
362
            # recompute bottom right
            # the order of the cumsum's is important for speed ?!
363
            occupancy.update(img_array, x, y)
364
            last_freq = freq
365

366
367
        self.layout_ = list(zip(frequencies, font_sizes, positions, orientations, colors))
        return self
368

369
    def process_text(self, text):
370
371
372
373
374
375
376
377
378
        """Splits a long text into words, eliminates the stopwords.

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

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

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

385
386
387
388
389
390
        Notes
        -----
        There are better ways to do word tokenization, but I don't want to
        include all those things.
        """

391
        self.stopwords_lower_ = set(map(str.lower, self.stopwords))
392

393
        d = {}
394
395
        flags = (re.UNICODE if sys.version < '3' and type(text) is unicode
                 else 0)
Andreas Mueller's avatar
Andreas Mueller committed
396
397
        regexp = self.regexp if self.regexp is not None else r"\w[\w']+"
        for word in re.findall(regexp, text, flags=flags):
398
399
400
401
            if word.isdigit():
                continue

            word_lower = word.lower()
402
            if word_lower in self.stopwords_lower_:
403
404
405
                continue

            # Look in lowercase dict.
406
            try:
407
                d2 = d[word_lower]
408
            except KeyError:
409
410
411
412
413
414
                d2 = {}
                d[word_lower] = d2

            # Look in any case dict.
            d2[word] = d2.get(word, 0) + 1

415
416
417
418
419
420
421
422
423
424
425
426
        # merge plurals into the singular count (simple cases only)
        for key in list(d.keys()):
            if key.endswith('s'):
                key_singular = key[:-1]
                if key_singular in d:
                    dict_plural = d[key]
                    dict_singular = d[key_singular]
                    for word, count in dict_plural.items():
                        singular = word[:-1]
                        dict_singular[singular] = dict_singular.get(singular, 0) + count
                    del d[key]

427
428
429
        d3 = {}
        for d2 in d.values():
            # Get the most popular case.
defacto133's avatar
defacto133 committed
430
            first = max(d2.items(), key=item1)[0]
431
432
            d3[first] = sum(d2.values())

433
        return d3
434

435
    def generate_from_text(self, text):
436
437
        """Generate wordcloud from text.

438
        Calls process_text and generate_from_frequencies.
439

440
441
442
443
        ..versionchanged:: 1.2.2
            Argument of generate_from_frequencies() is not return of
            process_text() any more.

444
445
446
447
        Returns
        -------
        self
        """
448
        words = self.process_text(text)
449
        self.generate_from_frequencies(words.items())
450
451
        return self

452
453
454
455
456
    def generate(self, text):
        """Generate wordcloud from text.

        Alias to generate_from_text.

457
        Calls process_text and generate_from_frequencies.
458
459
460
461
462
463
464

        Returns
        -------
        self
        """
        return self.generate_from_text(text)

465
    def _check_generated(self):
Andreas Mueller's avatar
Andreas Mueller committed
466
        """Check if ``layout_`` was computed, otherwise raise error."""
467
468
        if not hasattr(self, "layout_"):
            raise ValueError("WordCloud has not been calculated, call generate first.")
469
470
471
472
473
474
475
476
477

    def to_image(self):
        self._check_generated()
        if self.mask is not None:
            width = self.mask.shape[1]
            height = self.mask.shape[0]
        else:
            height, width = self.height, self.width

478
        img = Image.new(self.mode, (int(width * self.scale), int(height * self.scale)),
479
                        self.background_color)
480
481
        draw = ImageDraw.Draw(img)
        for (word, count), font_size, position, orientation, color in self.layout_:
482
            font = ImageFont.truetype(self.font_path, int(font_size * self.scale))
483
484
            transposed_font = ImageFont.TransposedFont(font,
                                                       orientation=orientation)
485
            pos = (int(position[1] * self.scale), int(position[0] * self.scale))
486
            draw.text(pos, word, fill=color, font=transposed_font)
487
488
489
490
491
492
493
494
495
        return img

    def recolor(self, random_state=None, color_func=None):
        """Recolor existing layout.

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

        Parameters
        ----------
496
497
498
        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.
499
500
501
502
503
504
505
506
507

        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.

        Returns
        -------
        self
        """
508
509
        if isinstance(random_state, int):
            random_state = Random(random_state)
510
        self._check_generated()
511
512
513

        if color_func is None:
            color_func = self.color_func
514
515
        self.layout_ = [(word_freq, font_size, position, orientation,
                         color_func(word=word_freq[0], font_size=font_size,
Andreas Mueller's avatar
Andreas Mueller committed
516
517
                                    position=position, orientation=orientation,
                                    random_state=random_state, font_path=self.font_path))
518
                        for word_freq, font_size, position, orientation, _ in self.layout_]
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
        return self

    def to_file(self, filename):
        """Export to image file.

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

        Returns
        -------
        self
        """

        img = self.to_image()
        img.save(filename)
        return self

    def to_array(self):
        """Convert to numpy array.

        Returns
        -------
        image : nd-array size (width, height, 3)
            Word cloud image as numpy matrix.
        """
Andreas Mueller's avatar
Andreas Mueller committed
546
        return np.array(self.to_image())
547

Andreas Mueller's avatar
Andreas Mueller committed
548
    def __array__(self):
549
550
551
552
553
554
555
        """Convert to numpy array.

        Returns
        -------
        image : nd-array size (width, height, 3)
            Word cloud image as numpy matrix.
        """
Andreas Mueller's avatar
Andreas Mueller committed
556
        return self.to_array()
557
558
559

    def to_html(self):
        raise NotImplementedError("FIXME!!!")