From 44f2d0213b7e6e02ab604551b5099b11ada8e6e7 Mon Sep 17 00:00:00 2001 From: Yeuoly Date: Fri, 15 Mar 2024 13:04:13 +0800 Subject: [PATCH] fix: charts encoding --- .../tools/provider/builtin/chart/chart.py | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/api/core/tools/provider/builtin/chart/chart.py b/api/core/tools/provider/builtin/chart/chart.py index 813b4abcf21c7..f5e42e766d276 100644 --- a/api/core/tools/provider/builtin/chart/chart.py +++ b/api/core/tools/provider/builtin/chart/chart.py @@ -1,4 +1,6 @@ import matplotlib.pyplot as plt +from fontTools.ttLib import TTFont +from matplotlib.font_manager import findSystemFonts from core.tools.errors import ToolProviderCredentialValidationError from core.tools.provider.builtin.chart.tools.line import LinearChartTool @@ -6,6 +8,37 @@ # use a business theme plt.style.use('seaborn-v0_8-darkgrid') +plt.rcParams['axes.unicode_minus'] = False + +def init_fonts(): + fonts = findSystemFonts() + + popular_unicode_fonts = [ + 'Arial Unicode MS', 'DejaVu Sans', 'DejaVu Sans Mono', 'DejaVu Serif', 'FreeMono', 'FreeSans', 'FreeSerif', + 'Liberation Mono', 'Liberation Sans', 'Liberation Serif', 'Noto Mono', 'Noto Sans', 'Noto Serif', 'Open Sans', + 'Roboto', 'Source Code Pro', 'Source Sans Pro', 'Source Serif Pro', 'Ubuntu', 'Ubuntu Mono' + ] + + supported_fonts = [] + + for font_path in fonts: + try: + font = TTFont(font_path) + # get family name + family_name = font['name'].getName(1, 3, 1).toUnicode() + if family_name in popular_unicode_fonts: + supported_fonts.append(family_name) + except: + pass + + plt.rcParams['font.family'] = 'sans-serif' + # sort by order of popular_unicode_fonts + for font in popular_unicode_fonts: + if font in supported_fonts: + plt.rcParams['font.sans-serif'] = font + break + +init_fonts() class ChartProvider(BuiltinToolProviderController): def _validate_credentials(self, credentials: dict) -> None: