Enabling Japanese fonts for matplotlib in VertexAiCodeExecutor
Is your feature request related to a problem? Please describe. When I create a graph using VertexAiCodeExecutor, the labels and legends are garbled because my data contains Japanese characters. I'm having trouble displaying the Japanese text correctly because it's not possible to install additional libraries (like font packages) in the Code Executor environment.
Describe the solution you'd like I would like for graph labels and legends to display Japanese characters correctly when using VertexAiCodeExecutor.
@enisher will take a look at this issue
Root Cause
The VertexAiCodeExecutor sandbox does not include fonts with Japanese glyphs. The only fonts available in the environment are: 'DejaVu Sans', 'DejaVu Sans Display', 'DejaVu Sans Mono', 'DejaVu Serif', 'DejaVu Serif Display', 'STIXGeneral', 'STIXNonUnicode', 'STIXSizeFiveSym', 'STIXSizeFourSym', 'STIXSizeOneSym', 'STIXSizeThreeSym', 'STIXSizeTwoSym', 'cmb10', 'cmex10', 'cmmi10', 'cmr10', 'cmss10', 'cmsy10', 'cmtt10'
The environment is also locked down for security, which prevents common workarounds:
- Dynamic package installation via
pip installis not permitted. - Outbound network access to download resources from a URL is blocked.
The Solution
The solution involves extending the VertexAiCodeExecutor to programmatically load a Japanese font. Here’s a step-by-step breakdown of how this is achieved:
-
Create a Custom Executor: A new class,
CustomCodeExecutor, is created that inherits fromVertexAiCodeExecutor. This allows us to add custom logic while reusing the base executor's functionality. -
Bundle the Font File: A Japanese font file (
NotoSerifJP-Regular.ttf) is added to the project. This font is loaded and its content is base64-encoded to be sent to the execution environment. -
Override Code Execution: The
execute_codemethod is overridden. In this new method, we prepend custom setup code to the user's script. This setup code decodes the font file and registers it withmatplotlib's font manager. -
Execute the Combined Code: Finally, the combined code (our setup logic + the user's original code) is executed in the
VertexAiCodeExecutorsandbox. This ensures the font is available before any plotting commands are run.
I created a sample agent that uses this CustomCodeExecutor to showcase how it works. You can find the full implementation here: contributing/samples/custom_code_execution/agent.py
You can try it out by running:
adk web contributing/samples/
Then select custom_code_execution from the list of agents and ask to generate a chart with Japanese labels.
Enisher,
Thank you for your assistance. I will be away from work for a short period this week, so I will try it next week or later.