Skip to content

Commit 8c31f2e

Browse files
CodeAvkericspod
andauthored
Read and write bundle and datalist files as UTF-8 (#9282)
Fixes #9277. ### Description On Windows, Python often uses cp1252 as the default file encoding instead of UTF-8. Some parts of the code, including `ConfigParser.load_config_file` / `export_config_file`, the bundle scripts (`_check_monai_version`, `init_bundle`, `_add_model_card_metadata`), `BundleWorkflow` (`properties_path`), and the Decathlon datalist helpers, were opening files without specifying an encoding. Because of this, UTF-8 config files containing special characters could either raise a `UnicodeDecodeError` or be read incorrectly. For example, "Größe" was displayed as "Größe". Writing files with `ensure_ascii=False` or `allow_unicode=True` could also raise a `UnicodeEncodeError`. This PR fixes the issue by explicitly setting `encoding="utf-8"` wherever these files are opened. I've also added tests that simulate cp1252 as the default encoding, so the issue can be caught on any OS, including Linux CI. I reproduced the issue and verified the fix on Windows 11 with Python 3.13. ### Types of changes - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [x] New tests added to cover the changes. Note: files that are not valid UTF-8 (for example saved as cp1252 or GBK) now raise `UnicodeDecodeError` instead of being read with the system's default encoding. --------- Signed-off-by: CodeAvk <avksmlavk@gmail.com> Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>
1 parent 379e8e3 commit 8c31f2e

6 files changed

Lines changed: 96 additions & 17 deletions

File tree

‎monai/bundle/config_parser.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -610,7 +610,7 @@ def load_config_file(cls, filepath: PathLike, **kwargs: Any) -> dict:
610610
_filepath: str = str(Path(filepath))
611611
if not re.compile(cls.path_match, re.IGNORECASE).findall(_filepath):
612612
raise ValueError(f'unknown file input: "{filepath}"')
613-
with open(_filepath) as f:
613+
with open(_filepath, encoding="utf-8") as f:
614614
if _filepath.lower().endswith(cls.suffixes[0]):
615615
return json.load(f, object_pairs_hook=check_key_duplicates, **kwargs) # type: ignore[no-any-return]
616616
if _filepath.lower().endswith(cls.suffixes[1:]):
@@ -658,7 +658,7 @@ def export_config_file(cls, config: dict, filepath: PathLike, fmt: str = "json",
658658
"""
659659
_filepath: str = str(Path(filepath))
660660
writer = look_up_option(fmt.lower(), {"json", "yaml", "yml"})
661-
with open(_filepath, "w") as f:
661+
with open(_filepath, "w", encoding="utf-8") as f:
662662
if writer == "json":
663663
json.dump(config, f, **kwargs)
664664
return

‎monai/bundle/scripts.py‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ def _check_monai_version(bundle_dir: PathLike, name: str) -> None:
339339
if not metadata_file.exists():
340340
logger.warning(f"metadata file not found in {metadata_file}.")
341341
return
342-
with open(metadata_file) as f:
342+
with open(metadata_file, encoding="utf-8") as f:
343343
metadata = json.load(f)
344344
is_compatible, msg = _examine_monai_version(metadata.get("monai_version", "0+unknown"))
345345
if not is_compatible:
@@ -1820,13 +1820,13 @@ def init_bundle(
18201820
if isinstance(inference_str, dict):
18211821
inference_str = json.dumps(inference_str, indent=4)
18221822

1823-
with open(str(configs_dir / "metadata.json"), "w") as o:
1823+
with open(str(configs_dir / "metadata.json"), "w", encoding="utf-8") as o:
18241824
o.write(metadata_str)
18251825

1826-
with open(str(configs_dir / "inference.json"), "w") as o:
1826+
with open(str(configs_dir / "inference.json"), "w", encoding="utf-8") as o:
18271827
o.write(inference_str)
18281828

1829-
with open(str(docs_dir / "README.md"), "w") as o:
1829+
with open(str(docs_dir / "README.md"), "w", encoding="utf-8") as o:
18301830
readme = """
18311831
# Your Model Name
18321832
@@ -1843,11 +1843,11 @@ def init_bundle(
18431843

18441844
o.write(dedent(readme))
18451845

1846-
with open(str(bundle_dir / "LICENSE"), "w") as o:
1846+
with open(str(bundle_dir / "LICENSE"), "w", encoding="utf-8") as o:
18471847
o.write("Select a license and place its terms here\n")
18481848

18491849
if dataset_license is True:
1850-
with open(str(docs_dir / "data_license.txt"), "w") as o:
1850+
with open(str(docs_dir / "data_license.txt"), "w", encoding="utf-8") as o:
18511851
o.write("Select a license for dataset and place its terms here\n")
18521852

18531853
if ckpt_file is not None:
@@ -1861,7 +1861,7 @@ def _add_model_card_metadata(new_modelcard_path):
18611861
license_name = "unknown"
18621862
license_path = os.path.join(os.path.dirname(new_modelcard_path), "LICENSE")
18631863
if os.path.exists(license_path):
1864-
with open(license_path) as file:
1864+
with open(license_path, encoding="utf-8") as file:
18651865
content = file.read()
18661866
if "Apache License" in content and "Version 2.0" in content:
18671867
license_name = "apache-2.0"
@@ -1873,10 +1873,10 @@ def _add_model_card_metadata(new_modelcard_path):
18731873
tag_content = f"---\ntags:\n{tags}license: {license_name}\n---"
18741874

18751875
# Update model card
1876-
with open(new_modelcard_path) as file:
1876+
with open(new_modelcard_path, encoding="utf-8") as file:
18771877
content = file.read()
18781878
new_content = tag_content + "\n" + content
1879-
with open(new_modelcard_path, "w") as file:
1879+
with open(new_modelcard_path, "w", encoding="utf-8") as file:
18801880
file.write(new_content)
18811881

18821882

‎monai/bundle/workflows.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ def __init__(
312312
properties_path = Path(properties_path)
313313
if not properties_path.is_file():
314314
raise ValueError(f"Property file {properties_path} does not exist.")
315-
with open(properties_path) as json_file:
315+
with open(properties_path, encoding="utf-8") as json_file:
316316
try:
317317
properties = json.load(json_file)
318318
self.properties: dict = {}

‎monai/data/decathlon_datalist.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def load_decathlon_datalist(
152152
data_list_file_path = Path(data_list_file_path)
153153
if not data_list_file_path.is_file():
154154
raise ValueError(f"Data list file {data_list_file_path} does not exist.")
155-
with open(data_list_file_path) as json_file:
155+
with open(data_list_file_path, encoding="utf-8") as json_file:
156156
json_data = json.load(json_file)
157157
if data_list_key not in json_data:
158158
raise ValueError(f'Data list {data_list_key} not specified in "{data_list_file_path}".')
@@ -182,7 +182,7 @@ def load_decathlon_properties(data_property_file_path: PathLike, property_keys:
182182
data_property_file_path = Path(data_property_file_path)
183183
if not data_property_file_path.is_file():
184184
raise ValueError(f"Data property file {data_property_file_path} does not exist.")
185-
with open(data_property_file_path) as json_file:
185+
with open(data_property_file_path, encoding="utf-8") as json_file:
186186
json_data = json.load(json_file)
187187

188188
properties = {}
@@ -281,7 +281,7 @@ def create_cross_validation_datalist(
281281
val_list = select_cross_validation_folds(partitions=data, folds=val_folds)
282282
ret = {train_key: train_list, val_key: val_list}
283283
if isinstance(filename, (str, Path)):
284-
with open(filename, "w") as f:
284+
with open(filename, "w", encoding="utf-8") as f:
285285
json.dump(ret, f, indent=4)
286286

287287
return ret

‎tests/bundle/test_config_parser.py‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111

1212
from __future__ import annotations
1313

14+
import builtins
1415
import copy
16+
import json
1517
import os
1618
import pickle
1719
import sys
@@ -32,7 +34,17 @@
3234
from tests.test_utils import TimedCall
3335

3436
_, has_tv = optional_import("torchvision", "0.8.0", min_version)
35-
_, has_yaml = optional_import("yaml")
37+
yaml, has_yaml = optional_import("yaml")
38+
39+
NON_ASCII_TEXT = "Lungenknoten ≥ 3 mm, Größe, 肺結節"
40+
_builtin_open = builtins.open
41+
42+
43+
def _open_with_cp1252_default(file, mode="r", *args, **kwargs):
44+
"""``open`` as on a system whose default encoding is cp1252 (e.g. Windows)."""
45+
if "b" not in mode:
46+
kwargs.setdefault("encoding", "cp1252")
47+
return _builtin_open(file, mode, *args, **kwargs)
3648

3749

3850
@TimedCall(seconds=100, force_quit=True)
@@ -524,5 +536,45 @@ def test_missing_raises(self):
524536
_ = self.parser.A.nonexistent
525537

526538

539+
class TestConfigFileEncoding(unittest.TestCase):
540+
"""Config files are UTF-8, whatever the default encoding of the system."""
541+
542+
@parameterized.expand([("json",), ("yaml",)])
543+
def test_load_utf8_config(self, fmt):
544+
if fmt == "yaml" and not has_yaml:
545+
self.skipTest("Requires pyyaml")
546+
with tempfile.TemporaryDirectory() as tempdir:
547+
filepath = Path(tempdir) / f"config.{fmt}"
548+
content = json.dumps({"note": NON_ASCII_TEXT}, ensure_ascii=False)
549+
filepath.write_bytes(content.encode("utf-8"))
550+
with mock.patch("builtins.open", _open_with_cp1252_default):
551+
config = ConfigParser.load_config_file(filepath)
552+
self.assertEqual(config["note"], NON_ASCII_TEXT)
553+
554+
def test_export_utf8_json(self):
555+
with tempfile.TemporaryDirectory() as tempdir:
556+
filepath = Path(tempdir) / "config.json"
557+
with mock.patch("builtins.open", _open_with_cp1252_default):
558+
ConfigParser.export_config_file({"note": NON_ASCII_TEXT}, filepath, ensure_ascii=False)
559+
self.assertEqual(json.loads(filepath.read_bytes().decode("utf-8")), {"note": NON_ASCII_TEXT})
560+
561+
@skipUnless(has_yaml, "Requires pyyaml")
562+
def test_export_utf8_yaml(self):
563+
with tempfile.TemporaryDirectory() as tempdir:
564+
filepath = Path(tempdir) / "config.yaml"
565+
with mock.patch("builtins.open", _open_with_cp1252_default):
566+
ConfigParser.export_config_file({"note": NON_ASCII_TEXT}, filepath, fmt="yaml", allow_unicode=True)
567+
self.assertEqual(yaml.safe_load(filepath.read_bytes().decode("utf-8")), {"note": NON_ASCII_TEXT})
568+
569+
def test_load_non_utf8_config_raises(self):
570+
# a cp1252-encoded file used to load under a cp1252 default; it is not valid UTF-8
571+
with tempfile.TemporaryDirectory() as tempdir:
572+
filepath = Path(tempdir) / "config.json"
573+
filepath.write_bytes('{"note": "Größe"}'.encode("cp1252"))
574+
with mock.patch("builtins.open", _open_with_cp1252_default):
575+
with self.assertRaises(UnicodeDecodeError):
576+
ConfigParser.load_config_file(filepath)
577+
578+
527579
if __name__ == "__main__":
528580
unittest.main()

‎tests/data/test_load_decathlon_datalist.py‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,25 @@
1111

1212
from __future__ import annotations
1313

14+
import builtins
1415
import json
1516
import os
1617
import tempfile
1718
import unittest
1819
from pathlib import Path
20+
from unittest import mock
1921

20-
from monai.data import load_decathlon_datalist
22+
from monai.data import load_decathlon_datalist, load_decathlon_properties
23+
24+
NON_ASCII_TEXT = "Lungenknoten ≥ 3 mm, Größe, 肺結節"
25+
_builtin_open = builtins.open
26+
27+
28+
def _open_with_cp1252_default(file, mode="r", *args, **kwargs):
29+
"""``open`` as on a system whose default encoding is cp1252 (e.g. Windows)."""
30+
if "b" not in mode:
31+
kwargs.setdefault("encoding", "cp1252")
32+
return _builtin_open(file, mode, *args, **kwargs)
2133

2234

2335
class TestLoadDecathlonDatalist(unittest.TestCase):
@@ -129,6 +141,21 @@ def test_additional_items(self):
129141
self.assertEqual(result[1]["mask"], os.path.join(tempdir, "mask31.txt"))
130142
self.assertEqual(result[0]["mask"], "spleen mask")
131143

144+
def test_utf8_file(self):
145+
with tempfile.TemporaryDirectory() as tempdir:
146+
test_data = {
147+
"name": NON_ASCII_TEXT,
148+
"description": NON_ASCII_TEXT,
149+
"training": [{"image": "größe_1.nii.gz", "label": "größe_1.nii.gz"}],
150+
}
151+
file_path = Path(tempdir) / "test_data.json"
152+
file_path.write_bytes(json.dumps(test_data, ensure_ascii=False).encode("utf-8"))
153+
with mock.patch("builtins.open", _open_with_cp1252_default):
154+
result = load_decathlon_datalist(file_path, True, "training")
155+
properties = load_decathlon_properties(file_path, ["name", "description"])
156+
self.assertEqual(result[0]["image"], os.path.join(tempdir, "größe_1.nii.gz"))
157+
self.assertEqual(properties, {"name": NON_ASCII_TEXT, "description": NON_ASCII_TEXT})
158+
132159

133160
if __name__ == "__main__":
134161
unittest.main()

0 commit comments

Comments
 (0)