Home > Back-end >  How to set custom "font_path" in python WordCloud App in Heroku?
How to set custom "font_path" in python WordCloud App in Heroku?

Time:12-08

I am making a fastapi app in Heroku with Python WordCloud package.

In my local test environment, I set my "font_path" like this code.

from wordcloud import WordCloud

wc = WordCloud(font_path='C:/Windows/Fonts/malgun.ttf')

Then, How Should I set my "font_path" in Heroku environment?

I tried to set font_path=None, and it works to English.(by default font(DroidSansMono)).

But, in my case, I should use custom font instead of default font. Because I need to make WordCloud in Korean language.

Thank you!

CodePudding user response:

To use a custom font with the WordCloud package in Heroku, you will need to make sure the font file is included in your app's deployment package. This can be done by adding the font file to your app's directory and including it in the files attribute of your app's setup.py file.

Once the font file has been included in your app's deployment package, you can use the font by specifying its path relative to your app's root directory. For example, if your font file is located at /app/fonts/malgun.ttf, you can use it in your WordCloud object like this:

from wordcloud import WordCloud

wc = WordCloud(font_path='fonts/malgun.ttf')

Note that the path you specify for the font file should use forward slashes, even on Windows systems.

It's also a good idea to include a check in your code to handle the case where the font file is not found. You can do this by using the os.path.exists function to check if the font file exists before attempting to use it.

import os
from wordcloud import WordCloud

if os.path.exists('fonts/malgun.ttf'):
    wc = WordCloud(font_path='fonts/malgun.ttf')
else:
    wc = WordCloud()

In this example, if the font file is not found, the WordCloud object will be created with the default font. You can also specify a different font to use in this case, if desired.

I hope this helps! Let me know if you have any other questions.

  • Related