Debian Codegraph @

wordcloud/wordcloud_cli.py

raw
1 # -*- coding: utf-8 -*-
2 """Command-line tool interface to generate word clouds.
3 """
4 from __future__ import absolute_import
5
6 import sys
7 import textwrap
8
9 if __name__ == '__main__': # pragma: no cover
10 sys.exit(textwrap.dedent(
11 """
12 To execute the CLI, instead consider running:
13
14 wordcloud_cli --help
15
16 or
17
18 python -m wordcloud --help
19 """))
20
21 import io
22 import re
23 import argparse
24 import wordcloud as wc
25 import numpy as np
26 from PIL import Image
27
28 from . import __version__
29
30
31 class FileType(object):
32 """Factory for creating file object types.
33
34 Port from argparse so we can support unicode file reading in Python2
35
36 Instances of FileType are typically passed as type= arguments to the
37 ArgumentParser add_argument() method.
38
39 Keyword Arguments:
40 - mode -- A string indicating how the file is to be opened. Accepts the
41 same values as the builtin open() function.
42 - bufsize -- The file's desired buffer size. Accepts the same values as
43 the builtin open() function.
44
45 """
46
47 def __init__(self, mode='r', bufsize=-1):
48 self._mode = mode
49 self._bufsize = bufsize
50
51 def __call__(self, string):
52 # the special argument "-" means sys.std{in,out}
53 if string == '-':
54 if 'r' in self._mode:
55 return sys.stdin
56 elif 'w' in self._mode:
57 return sys.stdout.buffer if 'b' in self._mode else sys.stdout
58 else:
59 msg = 'argument "-" with mode %r' % self._mode
60 raise ValueError(msg)
61
62 # all other arguments are used as file names
63 try:
64 encoding = None if 'b' in self._mode else "UTF-8"
65 return io.open(string, self._mode, self._bufsize, encoding=encoding)
66 except IOError as e:
67 message = "can't open '%s': %s"
68 raise argparse.ArgumentTypeError(message % (string, e))
69
70 def __repr__(self):
71 args = self._mode, self._bufsize
72 args_str = ', '.join(repr(arg) for arg in args if arg != -1)
73 return '%s(%s)' % (type(self).__name__, args_str)
74
75
76 class RegExpAction(argparse.Action):
77 def __init__(self, option_strings, dest, **kwargs):
78 super(RegExpAction, self).__init__(option_strings, dest, **kwargs)
79
80 def __call__(self, parser, namespace, values, option_string=None):
81 try:
82 re.compile(values)
83 except re.error as e:
84 raise argparse.ArgumentError(self, 'Invalid regular expression: ' + str(e))
85 setattr(namespace, self.dest, values)
86
87
88 def main(args, text, imagefile):
89 wordcloud = wc.WordCloud(**args)
90 wordcloud.generate(text)
91 image = wordcloud.to_image()
92
93 with imagefile:
94 image.save(imagefile, format='png', optimize=True)
95
96
97 def make_parser():
98 description = 'A simple command line interface for wordcloud module.'
99 parser = argparse.ArgumentParser(description=description)
100 parser.add_argument(
101 '--text', metavar='file', type=FileType(), default='-',
102 help='specify file of words to build the word cloud (default: stdin)')
103 parser.add_argument(
104 '--regexp', metavar='regexp', default=None, action=RegExpAction,
105 help='override the regular expression defining what constitutes a word')
106 parser.add_argument(
107 '--stopwords', metavar='file', type=FileType(),
108 help='specify file of stopwords (containing one word per line)'
109 ' to remove from the given text after parsing')
110 parser.add_argument(
111 '--imagefile', metavar='file', type=FileType('wb'),
112 default='-',
113 help='file the completed PNG image should be written to'
114 ' (default: stdout)')
115 parser.add_argument(
116 '--fontfile', metavar='path', dest='font_path',
117 help='path to font file you wish to use (default: DroidSansMono)')
118 parser.add_argument(
119 '--mask', metavar='file', type=argparse.FileType('rb'),
120 help='mask to use for the image form')
121 parser.add_argument(
122 '--colormask', metavar='file', type=argparse.FileType('rb'),
123 help='color mask to use for image coloring')
124 parser.add_argument(
125 '--contour_width', metavar='width', default=0, type=float,
126 dest='contour_width',
127 help='if greater than 0, draw mask contour (default: 0)')
128 parser.add_argument(
129 '--contour_color', metavar='color', default='black', type=str,
130 dest='contour_color',
131 help='use given color as mask contour color -'
132 ' accepts any value from PIL.ImageColor.getcolor')
133 parser.add_argument(
134 '--relative_scaling', type=float, default=0,
135 metavar='rs', help=' scaling of words by frequency (0 - 1)')
136 parser.add_argument(
137 '--margin', type=int, default=2,
138 metavar='width', help='spacing to leave around words')
139 parser.add_argument(
140 '--width', type=int, default=400,
141 metavar='width', help='define output image width')
142 parser.add_argument(
143 '--height', type=int, default=200,
144 metavar='height', help='define output image height')
145 parser.add_argument(
146 '--color', metavar='color',
147 help='use given color as coloring for the image -'
148 ' accepts any value from PIL.ImageColor.getcolor')
149 parser.add_argument(
150 '--background', metavar='color', default='black', type=str,
151 dest='background_color',
152 help='use given color as background color for the image -'
153 ' accepts any value from PIL.ImageColor.getcolor')
154 parser.add_argument(
155 '--no_collocations', action='store_false', dest='collocations',
156 help='do not add collocations (bigrams) to word cloud '
157 '(default: add unigrams and bigrams)')
158 parser.add_argument(
159 '--include_numbers',
160 action='store_true',
161 dest='include_numbers',
162 help='include numbers in wordcloud?')
163 parser.add_argument(
164 '--min_word_length',
165 type=int,
166 default=0,
167 metavar='min_word_length',
168 dest='min_word_length',
169 help='only include words with more than X letters')
170 parser.add_argument(
171 '--prefer_horizontal',
172 type=float, default=.9, metavar='ratio',
173 help='ratio of times to try horizontal fitting as opposed to vertical')
174 parser.add_argument(
175 '--scale',
176 type=float, default=1, metavar='scale',
177 help='scaling between computation and drawing')
178 parser.add_argument(
179 '--colormap',
180 type=str, default='viridis', metavar='map',
181 help='matplotlib colormap name')
182 parser.add_argument(
183 '--mode',
184 type=str, default='RGB', metavar='mode',
185 help='use RGB or RGBA for transparent background')
186 parser.add_argument(
187 '--max_words',
188 type=int, default=200, metavar='N',
189 help='maximum number of words')
190 parser.add_argument(
191 '--min_font_size',
192 type=int, default=4, metavar='size',
193 help='smallest font size to use')
194 parser.add_argument(
195 '--max_font_size',
196 type=int, default=None, metavar='size',
197 help='maximum font size for the largest word')
198 parser.add_argument(
199 '--font_step',
200 type=int, default=1, metavar='step',
201 help='step size for the font')
202 parser.add_argument(
203 '--random_state',
204 type=int, default=None, metavar='seed',
205 help='random seed')
206 parser.add_argument(
207 '--no_normalize_plurals',
208 action='store_false',
209 dest='normalize_plurals',
210 help='whether to remove trailing \'s\' from words')
211 parser.add_argument(
212 '--repeat',
213 action='store_true',
214 dest='repeat',
215 help='whether to repeat words and phrases')
216 parser.add_argument(
217 '--version', action='version',
218 version='%(prog)s {version}'.format(version=__version__))
219 return parser
220
221
222 def parse_args(arguments):
223 # prog = 'python wordcloud_cli.py'
224 parser = make_parser()
225 args = parser.parse_args(arguments)
226 if args.background_color == 'None':
227 args.background_color = None
228
229 if args.colormask and args.color:
230 raise ValueError('specify either a color mask or a color function')
231
232 args = vars(args)
233
234 with args.pop('text') as f:
235 text = f.read()
236
237 if args['stopwords']:
238 with args.pop('stopwords') as f:
239 args['stopwords'] = set(map(lambda l: l.strip(), f.readlines()))
240
241 if args['mask']:
242 mask = args.pop('mask')
243 args['mask'] = np.array(Image.open(mask))
244
245 color_func = wc.random_color_func
246 colormask = args.pop('colormask')
247 color = args.pop('color')
248 if colormask:
249 image = np.array(Image.open(colormask))
250 color_func = wc.ImageColorGenerator(image)
251 if color:
252 color_func = wc.get_single_color_func(color)
253 args['color_func'] = color_func
254
255 imagefile = args.pop('imagefile')
256
257 return args, text, imagefile