Skip to content

Commit

Permalink
Add svg export to CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
boidolr committed Jan 1, 2024
1 parent 1072b0e commit 6da7452
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
17 changes: 17 additions & 0 deletions test/test_wordcloud_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,23 @@ def test_cli_writes_to_imagefile(tmpdir, tmp_text_file):

# expecting image to be written to imagefile
assert tmp_image_file.size() > 0
# assert png header
assert tmp_image_file.read('rb').startswith(b'\x89PNG')


def test_cli_writes_to_svg_imagefile(tmpdir, tmp_text_file):
# ensure writing works with all python versions
tmp_image_file = tmpdir.join('word_cloud.svg')

tmp_text_file.write(b'some text')

args, text, image_file = cli.parse_args(['--text', str(tmp_text_file), '--imagefile', str(tmp_image_file)])
cli.main(args, text, image_file)

# expecting image to be written to imagefile
assert tmp_image_file.size() > 0
# assert svg header
assert tmp_image_file.read().startswith('<svg xmlns=')


# capsysbinary should be used here, but it's not supported in python 2.
Expand Down
10 changes: 7 additions & 3 deletions wordcloud/wordcloud_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,14 @@ def __call__(self, parser, namespace, values, option_string=None):
def main(args, text, imagefile):
wordcloud = wc.WordCloud(**args)
wordcloud.generate(text)
image = wordcloud.to_image()

with imagefile:
image.save(imagefile, format='png', optimize=True)
if imagefile.name.endswith('.svg'):
image = wordcloud.to_svg()
imagefile.write(image.encode('utf-8'))
else:
image = wordcloud.to_image()
image.save(imagefile, format='png', optimize=True)


def make_parser():
Expand All @@ -110,7 +114,7 @@ def make_parser():
parser.add_argument(
'--imagefile', metavar='file', type=FileType('wb'),
default='-',
help='file the completed PNG image should be written to'
help='file the completed image should be written to'
' (default: stdout)')
parser.add_argument(
'--fontfile', metavar='path', dest='font_path',
Expand Down

0 comments on commit 6da7452

Please sign in to comment.