wordcloud.py 17 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
14
15
16
17
18
import numpy as np
from operator import itemgetter

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
19

20
from .query_integral_image import query_integral_image
21
22
23

item1 = itemgetter(1)

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


30
31
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
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
61
62
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
63
64
65
66
67
68
69
70
71
72
73
74
75
    """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.

    """
76
    if random_state is None:
77
        random_state = Random()
78
79
80
81
82
83
84
85
86
87
    return "hsl(%d, 80%%, 50%%)" % random_state.randint(0, 255)


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
88
89
        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.
90
91
92
93
94
95
96
97
98
99

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

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

    ranks_only : boolean (default=False)
        Only use the rank of the words, not the actual counts.

Andreas Mueller's avatar
Andreas Mueller committed
100
    prefer_horizontal : float (default=0.90)
101
102
103
        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
104
105
106
107
108
        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!]
109

110
111
112
113
114
    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.

115
116
117
118
119
120
121
122
    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
123
    max_words : number (default=200)
124
125
126
127
128
        The maximum number of words.

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

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

Andreas Mueller's avatar
Andreas Mueller committed
132
133
134
    max_font_size : int or None (default=None)
        Maximum font size for the largest word. If None, height of the image is
        used.
135

136
137
138
    mode: string (default="RGB")
        Transparent background will be generated when mode is "RGBA" and
        background_color is None.
Andreas Mueller's avatar
Andreas Mueller committed
139

140
141
    Attributes
    ----------
Andreas Mueller's avatar
Andreas Mueller committed
142
    ``words_``: list of tuples (string, float)
143
144
        Word tokens with associated frequency.

Andreas Mueller's avatar
Andreas Mueller committed
145
    ``layout_`` : list of tuples (string, int, (int, int), int, color))
146
147
        Encodes the fitted word cloud. Encodes for each word the string, font
        size, position, orientation and color.
148
149
150
151
152
153
154
155
156

    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.
157
158
    """

159
    def __init__(self, font_path=None, width=400, height=200, margin=2,
Andreas Mueller's avatar
Andreas Mueller committed
160
                 ranks_only=False, prefer_horizontal=0.9, mask=None, scale=1,
161
162
163
                 color_func=random_color_func, max_words=200, min_font_size=4,
                 stopwords=None, random_state=None, background_color='black',
                 max_font_size=None, font_step=1, mode="RGB"):
164
165
166
167
168
169
170
171
        if stopwords is None:
            stopwords = STOPWORDS
        if font_path is None:
            font_path = FONT_PATH
        self.font_path = font_path
        self.width = width
        self.height = height
        self.margin = margin
Andreas Mueller's avatar
Andreas Mueller committed
172
        self.ranks_only = ranks_only
173
174
175
176
        self.prefer_horizontal = prefer_horizontal
        self.mask = mask
        self.scale = scale
        self.color_func = color_func
Andreas Mueller's avatar
Andreas Mueller committed
177
178
        self.max_words = max_words
        self.stopwords = stopwords
179
180
        self.min_font_size = min_font_size
        self.font_step = font_step
181
182
183
        if isinstance(random_state, int):
            random_state = Random(random_state)
        self.random_state = random_state
184
        self.background_color = background_color
Andreas Mueller's avatar
Andreas Mueller committed
185
186
187
        if max_font_size is None:
            max_font_size = height
        self.max_font_size = max_font_size
188
        self.mode = mode
189

190
191
192
193
    def fit_words(self, frequencies):
        """Create a word_cloud from words and frequencies.

        Alias to generate_from_frequencies.
194
195
196

        Parameters
        ----------
197
        frequencies : array of tuples
198
199
200
201
            A tuple contains the word and its frequency.

        Returns
        -------
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
        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
217
218

        """
219
220
221
222
        # make sure frequencies are sorted and normalized
        frequencies = sorted(frequencies, key=lambda x: x[1], reverse=True)
        frequencies = frequencies[:self.max_words]
        # largest entry will be 1
223
        max_frequency = float(np.max([freq for word, freq in frequencies]))
224
225
226
227

        for i, (word, freq) in enumerate(frequencies):
            frequencies[i] = word, freq / max_frequency

228
229
        self.words_ = frequencies

230
231
232
233
        if self.random_state is not None:
            random_state = self.random_state
        else:
            random_state = Random()
234

235
        if len(frequencies) <= 0:
236
            print("We need at least 1 word to plot a word cloud, got %d."
237
                  % len(frequencies))
238
239

        if self.mask is not None:
240
            mask = self.mask
Andreas Mueller's avatar
Andreas Mueller committed
241
242
            width = mask.shape[1]
            height = mask.shape[0]
243
            if mask.dtype.kind == 'f':
Andreas Mueller's avatar
Andreas Mueller committed
244
                warnings.warn("mask image should be unsigned byte between 0 and"
Andreas Mueller's avatar
Andreas Mueller committed
245
                              " 255. Got a float array")
Andreas Mueller's avatar
Andreas Mueller committed
246
247
248
            if mask.ndim == 2:
                boolean_mask = mask == 255
            elif mask.ndim == 3:
Andreas Mueller's avatar
Andreas Mueller committed
249
250
                # if all channels are white, mask out
                boolean_mask = np.all(mask[:, :, :3] == 255, axis=-1)
Andreas Mueller's avatar
Andreas Mueller committed
251
            else:
252
                raise ValueError("Got mask of invalid shape: %s" % str(mask.shape))
253
        else:
254
            boolean_mask = None
Andreas Mueller's avatar
Andreas Mueller committed
255
            height, width = self.height, self.width
256
        occupancy = IntegralOccupancyMap(height, width, boolean_mask)
257
258
259
260
261
262
263

        # 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
264
        font_size = self.max_font_size
265
        last_freq = 1.
266
267

        # start drawing grey image
268
        for word, freq in frequencies:
269
270
            # alternative way to set the font size
            if not self.ranks_only:
271
                font_size = freq / float(last_freq) * font_size
272
273
274
275
            while True:
                # try to find a position
                font = ImageFont.truetype(self.font_path, font_size)
                # transpose font optionally
276
                if random_state.random() < self.prefer_horizontal:
277
278
279
280
281
282
283
284
285
                    orientation = None
                else:
                    orientation = Image.ROTATE_90
                transposed_font = ImageFont.TransposedFont(font,
                                                           orientation=orientation)
                draw.setfont(transposed_font)
                # get size of resulting text
                box_size = draw.textsize(word)
                # find possible places using integral image:
286
287
288
                result = occupancy.sample_position(box_size[1] + self.margin,
                                                   box_size[0] + self.margin,
                                                   random_state)
289
290
291
                if result is not None or font_size == 0:
                    break
                # if we didn't find a place, make font smaller
292
                font_size -= self.font_step
293

294
            if font_size < self.min_font_size:
295
296
297
298
299
300
301
302
303
                # we were unable to draw any more
                break

            x, y = np.array(result) + self.margin // 2
            # actually draw the text
            draw.text((y, x), word, fill="white")
            positions.append((x, y))
            orientations.append(orientation)
            font_sizes.append(font_size)
Andreas Mueller's avatar
Andreas Mueller committed
304
305
306
307
308
            colors.append(self.color_func(word, font_size=font_size,
                                          position=(x, y),
                                          orientation=orientation,
                                          random_state=random_state,
                                          font_path=self.font_path))
309
            # recompute integral image
Andreas Mueller's avatar
Andreas Mueller committed
310
311
312
            if self.mask is None:
                img_array = np.asarray(img_grey)
            else:
Andreas Mueller's avatar
Andreas Mueller committed
313
                img_array = np.asarray(img_grey) + boolean_mask
314
315
            # recompute bottom right
            # the order of the cumsum's is important for speed ?!
316
            occupancy.update(img_array, x, y)
317
            last_freq = freq
318

319
320
        self.layout_ = list(zip(frequencies, font_sizes, positions, orientations, colors))
        return self
321

322
    def process_text(self, text):
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
        """Splits a long text into words, eliminates the stopwords.

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

        Returns
        -------
        words : list of tuples (string, float)
            Word tokens with associated frequency.

        Notes
        -----
        There are better ways to do word tokenization, but I don't want to
        include all those things.
        """

        d = {}
342
343
        flags = (re.UNICODE if sys.version < '3' and type(text) is unicode
                 else 0)
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
        for word in re.findall(r"\w[\w']*", text, flags=flags):
            if word.isdigit():
                continue

            word_lower = word.lower()
            if word_lower in self.stopwords:
                continue

            # Look in lowercase dict.
            if word_lower in d:
                d2 = d[word_lower]
            else:
                d2 = {}
                d[word_lower] = d2

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

        d3 = {}
        for d2 in d.values():
            # Get the most popular case.
defacto133's avatar
defacto133 committed
365
            first = max(d2.items(), key=item1)[0]
366
367
368
            d3[first] = sum(d2.values())

        # merge plurals into the singular count (simple cases only)
defacto133's avatar
defacto133 committed
369
        for key in list(d3.keys()):
370
371
372
373
374
375
376
377
            if key.endswith('s'):
                key_singular = key[:-1]
                if key_singular in d3:
                    val_plural = d3[key]
                    val_singular = d3[key_singular]
                    d3[key_singular] = val_singular + val_plural
                    del d3[key]

378
        return d3.items()
379

380
    def generate_from_text(self, text):
381
382
        """Generate wordcloud from text.

383
        Calls process_text and generate_from_frequencies.
384
385
386
387
388

        Returns
        -------
        self
        """
389
390
        words = self.process_text(text)
        self.generate_from_frequencies(words)
391
392
        return self

393
394
395
396
397
    def generate(self, text):
        """Generate wordcloud from text.

        Alias to generate_from_text.

398
        Calls process_text and generate_from_frequencies.
399
400
401
402
403
404
405

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

406
    def _check_generated(self):
Andreas Mueller's avatar
Andreas Mueller committed
407
        """Check if ``layout_`` was computed, otherwise raise error."""
408
409
        if not hasattr(self, "layout_"):
            raise ValueError("WordCloud has not been calculated, call generate first.")
410
411
412
413
414
415
416
417
418

    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

419
420
        img = Image.new(self.mode, (width * self.scale, height * self.scale),
                        self.background_color)
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
        draw = ImageDraw.Draw(img)
        for (word, count), font_size, position, orientation, color in self.layout_:
            font = ImageFont.truetype(self.font_path, font_size * self.scale)
            transposed_font = ImageFont.TransposedFont(font,
                                                       orientation=orientation)
            draw.setfont(transposed_font)
            pos = (position[1] * self.scale, position[0] * self.scale)
            draw.text(pos, word, fill=color)
        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
        ----------
438
439
440
        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.
441
442
443
444
445
446
447
448
449

        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
        """
450
451
        if isinstance(random_state, int):
            random_state = Random(random_state)
452
        self._check_generated()
453
454
455

        if color_func is None:
            color_func = self.color_func
456
457
        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
458
459
                                    position=position, orientation=orientation,
                                    random_state=random_state, font_path=self.font_path))
460
                        for word_freq, font_size, position, orientation, _ in self.layout_]
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
        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
488
        return np.array(self.to_image())
489

Andreas Mueller's avatar
Andreas Mueller committed
490
    def __array__(self):
491
492
493
494
495
496
497
        """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
498
        return self.to_array()
499
500
501

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