Coder Social home page Coder Social logo

stylecloud's Introduction

stylecloud

Generate stylistic wordclouds, including gradients and icon shapes!

stylecloud is a Python package that leverages the popular word_cloud package, adding useful features to create truly unique word clouds!

  • Icon shapes (of any size!) for wordclouds (via Font Awesome 5.13.0 Free, or your own Font Awesome Pro)
  • Support for advanced color palettes (via palettable)
  • Manual color selection for text and backgrounds,
  • Directional gradients w/ the aforementioned palettes.
  • Supports reading text files and CSVs (either one-column w/ texts, or two columns w/ words+weights).
  • Command Line Interface!

This package is a more formal implementation of my stylistic word cloud project from 2016.

Installation

You can install stylecloud via pip:

pip3 install stylecloud

Usage

You can use stylecloud in a Python script or as a standalone CLI app. For example, let's say you have a text of the U.S. Constitution constitution.txt.

Python script:

import stylecloud

stylecloud.gen_stylecloud(file_path='constitution.txt')

But you can do so much more! You can use the free Font Awesome icons to change the shape, change the color palette to one from palettable for a custom style, change the background color, and, most importantly, add a gradient so the colors flow in a specified direction!

import stylecloud

stylecloud.gen_stylecloud(file_path='constitution.txt',
                          icon_name='fas fa-dog',
                          palette='colorbrewer.diverging.Spectral_11',
                          background_color='black',
                          gradient='horizontal')

You can also use the CLI for even faster stylecloud generation! For the simple flag stylecloud above:

stylecloud --file_path constitution.txt

For the more complex dog-gradient stylecloud:

stylecloud --file_path constitution.txt --icon_name 'fas fa-dog' --palette colorbrewer.diverging.Spectral_11 --background_color black --gradient horizontal

You can find more examples of styleclouds, including how to make styleclouds from Twitter and Reddit data, in the stylecloud-examples repo.

Custom Colors for stylecloud Text

You can manually specify the color(s) of the text with the colors parameter, overriding the palettes. This can be useful for specific branding, or high-contrast visualizations. However, manual color selection will not work with gradients.

import stylecloud

stylecloud.gen_stylecloud(file_path='constitution.txt',
                          colors=['#ecf0f1', '#3498db', '#e74c3c'],
                          background_color='#1A1A1A')
stylecloud --file_path constitution.txt --colors "['#ecf0f1', '#3498db', '#e74c3c']" --background_color '#1A1A1A'

Stopwords

In order to filter out stopwords in non-English languages or use custom stopwords, you can pass a list of words to the custom_stopwords parameter:

import stylecloud
my_long_list = ["thereof", "may", "state", "united states"]

stylecloud.gen_stylecloud(file_path='constitution.txt',
                          custom_stopwords=my_long_list)
stylecloud --file_path constitution.txt --custom_stopwords "[thereof, may, state, united states]"

Good resources for stopwords in other languages are the stop-words Python package and the ISO stopword collections.

Helpful Parameters

These parameters are valid for both the Python function and the CLI (you can use stylecloud -h to get this information as well).

  • text: Input text. Best used if calling the function directly.
  • file_path: File path of the input text/CSV. Best used on the CLI.
  • gradient: Direction of gradient. (if not None, the stylecloud will use a directional gradient) [default: None]
  • size: Size (length and width in pixels) of the stylecloud, or a two-element tuple representing the width and height of the stylecloud (e.g. '(1024, 512)' for a 1024x512 stylecloud). [default: 512]
  • icon_name: Icon Name for the stylecloud shape. (e.g. 'fas fa-grin') [default: fas fa-flag]
  • palette: Color palette (via palettable) [default: cartocolors.qualitative.Bold_5]
  • colors: Color(s) to use as the text colors. Overrides both gradient and palette if specified [default: None]
  • background_color: Background color (name or hex) [default: white]
  • max_font_size: Maximum font size in the stylecloud. [default: 200]
  • max_words: Maximum number of words to include in the stylecloud. [default: 2000]
  • stopwords: Boolean to filter out common stopwords. [default: True]
  • custom_stopwords: list of custom stopwords. e.g: For other languages than english [default: STOPWORDS, via word_cloud]
  • output_name: Output file name of the stylecloud. [default: stylecloud.png]
  • font_path: Path to .ttf file for font to use in stylecloud. [default: uses included Staatliches font]
  • random_state: Controls random state of words and colors. [default: None]
  • collocations: Whether to include collocations (bigrams) of two words. Same behavior as base word_cloud package. [default: True]
  • invert_mask: Whether to invert the icon mask, so the words fill the space except the icon mask. [default: False]
  • pro_icon_path: Path to Font Awesome Pro .ttf file if using FA Pro. [default: None]
  • pro_css_path: Path to Font Awesome Pro .css file if using FA Pro. [default: None]

Helpful Notes

  • The primary goal of this package is to create data visualizations of text that provide a unique aesthetic. Word clouds have tradeoffs in terms of a statistically robust data visualization, but this is explicitly prioritizing coolness!
  • This package is released as a separate package from word_cloud due to the increase in scope and Python dependencies.
  • The ideal fonts for generating a good stylecloud are a) bold/high weight in order to increase readability, and b) condensed/low kerning to fit more text. Both of these traits are why Staatliches is the default font for stylecloud (overriding Droid Sans in the base word_cloud).
  • You may want to consider doing post-processing after generating a stylecloud: for example, adding color masks, adding perception skew, feed it to a style transfer AI model, etc.
  • The default max_font_size of 200 is calibrated for the default size of 512. If you increase the size, you may want to consider increasing max_font_size as well.
  • Due to the size of the included Font Awesome font files, they will not be updated on every new minor FA release.
  • It's recommended to use FA icons which are large with heavy weight; thin icons might constrain the text too much.
  • If using the default random-color-sampling method, it's recommended to use a qualitative palette. Inversely, if using a gradient, it's recommended to use a nonqualitative palette (e.g. a sequential palette).

Projects Using stylecloud

  • twcloud — Python package + CLI to generate wordclouds of Twitter tweets.

Maintainer/Creator

Max Woolf (@minimaxir)

Max's open-source projects are supported by his Patreon and GitHub Sponsors. If you found this project helpful, any monetary contributions to the Patreon are appreciated and will be put to good creative use.

License

MIT

Font Awesome icon font files included per the terms in its SIL OFL 1.1 License.

Staatliches font included per the terms in its SIL OFL 1.1 License.

stylecloud's People

Contributors

amrrs avatar minimaxir avatar naqi324 avatar xoeseko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stylecloud's Issues

Can't display Japanese

I use stylecloud for japanese but it displays wrong font. How can I fix it? Thank you!

Inline in Jupyter Notebook?

Would it be possible to display inline in Jupyter notebook? right now gen_stylecloud seems to be saving the png

Generate from frequency

Hi,

Thanks for this useful tool! May I kindly ask if it is possible to have the function generate the image from a frequency dictionary just like what wordcloud did?

Best,
Jun

'ImageDraw' object has no attribute 'textsize'

Trying to use stylecloud gives me this error: 'ImageDraw' object has no attribute 'textsize'

I found this on stack overflow, sounds like it's probably the cause:

"The ImageDraw.textsize() method was deprecated in PIL version 9.2.0 and completely removed beginning with version 10.0.0 on 2023-07-01. The ImageDraw.textbbox() method was introduced in version 8.0.0 as a more robust solution."
https://stackoverflow.com/questions/76189891/imagedraw-object-has-no-attribute-textbbox

Automatically guess an appropriate icon?

Thanks for stylecloud, it produces awesome results!

One thought: rather than defaulting to a specific icon, could you scan through the common words above a certain minimum threshold, in order, and see if any match the name of an icon? (You could still have a fallback in case none match.) That seems likely to produce amusing, self-describing results; the word describing the icon used as a mask will also appear large in the image.

About Chinese

You project seems not to support Chinese. Will you add this function in the future?

AttributeError: 'CartoColorsMap' object has no attribute 'split'

my code is:
from stylecloud import gen_stylecloud gen_stylecloud( text=' '.join(list3), size=512, font_path=r'‪C:\Windows\Fonts\msyh.ttc', output_name='C:/Users/.../Desktop/wordcloud.png', icon_name='fab fa-twitter', palette= cartocolors.qualitative.Bold_5 )
And this error occurred.

Is there a way to have no icon?

As stated in the title I was wondering if there was a way to have no icon at all, so the words just fill up the entirety of the specified image

More algorithmically-efficient gradient generator

Current implementation is O(n^2). There really should be a O(n) implementation with numpy (calculate gradient vector once, multiply by n) but the data formats for everything involved are fickle.

Extra parameters to be passed directly into word_cloud

stylecloud is a great library! It really simplifies the mask-array-based approach of word_cloud when generate wordcloud constrained by a mask. But I want to get more control over the wordcloud it generate, e.g. I want to generate pure-horizontal wordcloud by set prefer_horizontal to 1, seems there's no way to pass this extra parameter into the constructor of WordCloud.

BTW, is there any way to shrink space between words?

Allowing words to be repeated

Hi. Is it possible to allow words to be repeated until the mask is full? If my text is not long enough, it doesn't fill the entire image. Like in wordcloud we can set repeat = True to repeat words until image is full or smallest text size is reached. Thanks

File Decode Error

While I try to read a file contain Chinese:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 22: character maps to

Could you change code in both lines 22 and 27 in stylecloud.py to
with open(file_path, 'r', encoding="utf8") as f:

Thanks!

ImportError: cannot import name 'makeMappingArray' from 'matplotlib.colors'

Attempting to run your example code:

import stylecloud
stylecloud.gen_stylecloud(file_path='constitution.txt')

I get the following traceback error:

Traceback (most recent call last):
  File "/Users/d/Documents/word-clouds/generate_clouds.py", line 1, in <module>
    import stylecloud
  File "/usr/local/lib/python3.9/site-packages/stylecloud/__init__.py", line 1, in <module>
    from .stylecloud import gen_stylecloud
  File "/usr/local/lib/python3.9/site-packages/stylecloud/stylecloud.py", line 6, in <module>
    from matplotlib.colors import makeMappingArray, to_rgb
ImportError: cannot import name 'makeMappingArray' from 'matplotlib.colors' (/usr/local/lib/python3.9/site-packages/matplotlib/colors.py)

Any suggestions on how to remedy this would be greatly appreciated!

It seems that frozen modules are being used, which may

Encountered a problem when using Python 3.12, problem one is causing an exception:'ImageDraw' object has no attribute 'textsize',I attempted to downgrade PIL to version 9.5 and resolved the issue. However, when used in 'jupyter', it will continue to occupy the process and cannot calculate the result, and even when executed directly in '. py', the result cannot be obtained.I noticed a warning in the background while running in 'jupyter',It seems that frozen modules are being used, which may.I'm not sure if it's related to this issue.

ERROR import palettable

Hi,

when I run stylecloud on my PC I have no problem, but then I deploy it on an ubuntu machine and make it run inside a docker container activated through flask.

When I do so, I get an error as it seem the way palettable is imported (line 91 of your function) generates an error. Could you help me solve that? Can I avoid importing palettable and just give it the colors (even if I use the colors the palette is generated)?

File "/usr/lib/python3.8/site-packages/stylecloud/stylecloud.py", line 237, in gen_stylecloud
palette_func = gen_palette(palette)
File "/usr/lib/python3.8/site-packages/stylecloud/stylecloud.py", line 91, in gen_palette
return self.__local()
File "/usr/lib/python3.8/site-packages/flask/globals.py", line 38, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
import(
ModuleNotFoundError: No module named 'palettable.'

Thanks a lot for this nice package! :)

FR: Allow use of a single color or manually specified palettes

Single colors might look nice as duotones between stylecloud and background. Manual palettes could work well for branding.

In this case, gradient support would have to be disabled unless there's an easy way to interpolate colors. (maybe in matplotlib?)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.