Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add svg export to CLI #756

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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