alex-petrenko / sample-factory

High throughput synchronous and asynchronous reinforcement learning
https://samplefactory.dev
MIT License
773 stars 106 forks source link

Better relative path for nle font package resource #293

Closed im-ant closed 4 months ago

im-ant commented 4 months ago

If python -m sf_examples.nethack.train_nethack (e.g. from the example experiment ) is run from outside of sample-factory, the font resource would not be found, e.g.:

Traceback (most recent call last):
  File "/home/anthony/miniconda3/envs/nle/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
    self.run()
  File "/home/anthony/miniconda3/envs/nle/lib/python3.10/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/home/anthony/Project/sample-factory-ppo/sample_factory/algo/utils/env_info.py", line 98, in spawn_tmp_env_and_get_info
    tmp_env = make_env_func_batched(cfg, env_config=None)
  File "/home/anthony/Project/sample-factory-ppo/sample_factory/algo/utils/make_env.py", line 343, in make_env_func_batched
    env = create_env(cfg.env, cfg=cfg, env_config=env_config, render_mode=render_mode)
  File "/home/anthony/Project/sample-factory-ppo/sample_factory/envs/create_env.py", line 39, in create_env
    env = env_factory(full_env_name, cfg, env_config, render_mode)
  File "/home/anthony/Project/sample-factory-ppo/sf_examples/nethack/nethack_env.py", line 85, in make_nethack_env
    env = RenderCharImagesWithNumpyWrapperV2(
  File "/home/anthony/Project/sample-factory-ppo/sf_examples/nethack/utils/wrappers/screen_image.py", line 228, in __init__
    self.char_array = _initialize_char_array(font_size, rescale_font_size)
  File "/home/anthony/Project/sample-factory-ppo/sf_examples/nethack/utils/wrappers/screen_image.py", line 98, in _initialize_char_array
    font = ImageFont.truetype(SMALL_FONT_PATH, font_size)
  File "/home/anthony/miniconda3/envs/nle/lib/python3.10/site-packages/PIL/ImageFont.py", line 819, in truetype
    return freetype(font)
  File "/home/anthony/miniconda3/envs/nle/lib/python3.10/site-packages/PIL/ImageFont.py", line 816, in freetype
    return FreeTypeFont(font, size, index, encoding, layout_engine)
  File "/home/anthony/miniconda3/envs/nle/lib/python3.10/site-packages/PIL/ImageFont.py", line 245, in __init__
    self.font = core.getfont(
OSError: cannot open resource

Fixed by using importlib.resources to make the resource path dependent on the package path rather than the current working directory