wordcloud.py 14.7 KB
Newer Older
1
2
3
4
5
6
# Author: Andreas Christian Mueller <amueller@ais.uni-bonn.de>
# (c) 2012
# Modified by: Paul Nechifor <paul@nechifor.net>
#
# License: MIT

7
from random import Random
8
9
import os
import re
10
import sys
11
12
13
14
15
16
import numpy as np
from operator import itemgetter

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
17
from .query_integral_image import query_integral_image
18
19
20

item1 = itemgetter(1)

21
FONT_PATH = os.environ.get("FONT_PATH", "/usr/share/fonts/truetype/droid/DroidSansMono.ttf")
22
23
24
25
26
STOPWORDS = set([x.strip() for x in open(os.path.join(os.path.dirname(__file__),
                                                      'stopwords')).read().split('\n')])


def random_color_func(word, font_size, position, orientation, random_state=None):
Andreas Mueller's avatar
Andreas Mueller committed
27
28
29
30
31
32
33
34
35
36
37
38
39
    """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.

    """
40
    if random_state is None:
41
        random_state = Random()
42
43
44
45
46
47
48
49
50
51
    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
52
53
        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.
54
55
56
57
58
59
60
61
62
63

    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
64
    prefer_horizontal : float (default=0.90)
65
66
67
        The ratio of times to try horizontal fitting as opposed to vertical.

    mask : nd-array or None (default=None)
68
69
70
71
        If not None, gives a binary mask on where to draw words. All zero
        entries will be considered "free" to draw on, while all non-zero
        entries will be deemed occupied. If mask is not None, width and height will be
        ignored and the shape of mask will be used instead.
72

Andreas Mueller's avatar
Andreas Mueller committed
73
    max_words : number (default=200)
74
75
76
77
78
        The maximum number of words.

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

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

Andreas Mueller's avatar
Andreas Mueller committed
82
83
84
85
    max_font_size : int or None (default=None)
        Maximum font size for the largest word. If None, height of the image is
        used.

86
87
    Attributes
    ----------
Andreas Mueller's avatar
Andreas Mueller committed
88
    ``words_``: list of tuples (string, float)
89
90
        Word tokens with associated frequency.

Andreas Mueller's avatar
Andreas Mueller committed
91
    ``layout_`` : list of tuples (string, int, (int, int), int, color))
92
93
94
95
96
        Encodes the fitted word cloud. Encodes for each word the string, font
        size, position, orientation and color.
    """

    def __init__(self, font_path=None, width=400, height=200, margin=5,
Andreas Mueller's avatar
Andreas Mueller committed
97
                 ranks_only=False, prefer_horizontal=0.9, mask=None, scale=1,
98
                 color_func=random_color_func, max_words=200, stopwords=None,
Andreas Mueller's avatar
Andreas Mueller committed
99
                 random_state=None, background_color='black', max_font_size=None):
100
101
102
103
104
105
106
107
        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
108
        self.ranks_only = ranks_only
109
110
111
112
        self.prefer_horizontal = prefer_horizontal
        self.mask = mask
        self.scale = scale
        self.color_func = color_func
Andreas Mueller's avatar
Andreas Mueller committed
113
114
        self.max_words = max_words
        self.stopwords = stopwords
115
116
117
        if isinstance(random_state, int):
            random_state = Random(random_state)
        self.random_state = random_state
118
        self.background_color = background_color
Andreas Mueller's avatar
Andreas Mueller committed
119
120
121
        if max_font_size is None:
            max_font_size = height
        self.max_font_size = max_font_size
122

123
124
125
126
    def fit_words(self, frequencies):
        """Create a word_cloud from words and frequencies.

        Alias to generate_from_frequencies.
127
128
129

        Parameters
        ----------
130
        frequencies : array of tuples
131
132
133
134
            A tuple contains the word and its frequency.

        Returns
        -------
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
        self

        Notes
        -----
        Larger canvases with make the code significantly slower. If you need a large
        word cloud, run this function with a lower canvas size, and draw it with a
        larger scale.

        In the current form it actually just uses the rank of the counts, i.e. the
        relative differences don't matter. Play with setting the font_size in the
        main loop for different styles.
        """
        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
160
161
162
163
164
165
166
167
168
169
170

        Notes
        -----
        Larger canvases with make the code significantly slower. If you need a large
        word cloud, run this function with a lower canvas size, and draw it with a
        larger scale.

        In the current form it actually just uses the rank of the counts, i.e. the
        relative differences don't matter. Play with setting the font_size in the
        main loop for different styles.
        """
171
172
173
174
        if self.random_state is not None:
            random_state = self.random_state
        else:
            random_state = Random()
175

176
        if len(frequencies) <= 0:
177
            print("We need at least 1 word to plot a word cloud, got %d."
178
                  % len(frequencies))
179
180
181
182
183
184
185

        if self.mask is not None:
            width = self.mask.shape[1]
            height = self.mask.shape[0]
            # the order of the cumsum's is important for speed ?!
            integral = np.cumsum(np.cumsum(self.mask, axis=1), axis=0).astype(np.uint32)
        else:
Andreas Mueller's avatar
Andreas Mueller committed
186
            height, width = self.height, self.width
187
188
189
190
191
192
193
194
            integral = np.zeros((height, width), dtype=np.uint32)

        # 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
195
        font_size = self.max_font_size
196
197

        # start drawing grey image
198
        for word, count in frequencies:
199
200
201
202
203
204
205
            # alternative way to set the font size
            if not self.ranks_only:
                font_size = min(font_size, int(100 * np.log(count + 100)))
            while True:
                # try to find a position
                font = ImageFont.truetype(self.font_path, font_size)
                # transpose font optionally
206
                if random_state.random() < self.prefer_horizontal:
207
208
209
210
211
212
213
214
215
216
                    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:
                result = query_integral_image(integral, box_size[1] + self.margin,
217
                                              box_size[0] + self.margin, random_state)
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
                if result is not None or font_size == 0:
                    break
                # if we didn't find a place, make font smaller
                font_size -= 1

            if font_size == 0:
                # 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)
233
234
            colors.append(self.color_func(word, font_size, (x, y), orientation,
                                          random_state=random_state))
235
            # recompute integral image
Andreas Mueller's avatar
Andreas Mueller committed
236
237
238
239
            if self.mask is None:
                img_array = np.asarray(img_grey)
            else:
                img_array = np.asarray(img_grey) + self.mask
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
            # recompute bottom right
            # the order of the cumsum's is important for speed ?!
            partial_integral = np.cumsum(np.cumsum(img_array[x:, y:], axis=1),
                                         axis=0)
            # paste recomputed part into old image
            # if x or y is zero it is a bit annoying
            if x > 0:
                if y > 0:
                    partial_integral += (integral[x - 1, y:]
                                         - integral[x - 1, y - 1])
                else:
                    partial_integral += integral[x - 1, y:]
            if y > 0:
                partial_integral += integral[x:, y - 1][:, np.newaxis]

            integral[x:, y:] = partial_integral

257
258
        self.layout_ = list(zip(frequencies, font_sizes, positions, orientations, colors))
        return self
259

260
    def process_text(self, text):
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
        """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 = {}
281
282
        flags = (re.UNICODE if sys.version < '3' and type(text) is unicode
                 else 0)
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
        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
304
            first = max(d2.items(), key=item1)[0]
305
306
307
            d3[first] = sum(d2.values())

        # merge plurals into the singular count (simple cases only)
defacto133's avatar
defacto133 committed
308
        for key in list(d3.keys()):
309
310
311
312
313
314
315
316
            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]

defacto133's avatar
defacto133 committed
317
        words = sorted(d3.items(), key=item1, reverse=True)
Andreas Mueller's avatar
Andreas Mueller committed
318
        words = words[:self.max_words]
319
320
321
322
323
324
325
326
        maximum = float(max(d3.values()))
        for i, (word, count) in enumerate(words):
            words[i] = word, count / maximum

        self.words_ = words

        return words

327
    def generate_from_text(self, text):
328
329
        """Generate wordcloud from text.

330
        Calls process_text and fit_words.
331
332
333
334
335

        Returns
        -------
        self
        """
336
337
        self.process_text(text)
        self.fit_words(self.words_)
338
339
        return self

340
341
342
343
344
345
346
347
348
349
350
351
352
    def generate(self, text):
        """Generate wordcloud from text.

        Alias to generate_from_text.

        Calls process_text and fit_words.

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

353
    def _check_generated(self):
Andreas Mueller's avatar
Andreas Mueller committed
354
        """Check if ``layout_`` was computed, otherwise raise error."""
355
356
        if not hasattr(self, "layout_"):
            raise ValueError("WordCloud has not been calculated, call generate first.")
357
358
359
360
361
362
363
364
365

    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

366
        img = Image.new("RGB", (width * self.scale, height * self.scale), self.background_color)
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
        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
        ----------
384
385
386
        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.
387
388
389
390
391
392
393
394
395

        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
        """
396
397
        if isinstance(random_state, int):
            random_state = Random(random_state)
398
        self._check_generated()
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431

        if color_func is None:
            color_func = self.color_func
        self.layout_ = [(word, font_size, position, orientation,
                         color_func(word, font_size, position, orientation, random_state))
                        for word, font_size, position, orientation, _ in self.layout_]
        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
432
        return np.array(self.to_image())
433

Andreas Mueller's avatar
Andreas Mueller committed
434
    def __array__(self):
435
436
437
438
439
440
441
        """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
442
        return self.to_array()
443
444
445

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