From ce5a43c0955585106750662909c5db0ad206d52b Mon Sep 17 00:00:00 2001 From: adhavan18 Date: Sun, 6 Dec 2026 10:46:41 +0530 Subject: [PATCH] fix: read annotation files and labelmaps as utf-8 on every platform MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit folder uploads, Project.upload() and roboflow image annotate opened annotation files and labelmaps without an encoding, so on windows they were decoded with the locale code page (cp1252). a utf-8 class name like café was uploaded as café, and characters like ď failed the whole upload with UnicodeDecodeError. --- CHANGELOG.md | 10 +++++++ roboflow/cli/handlers/image.py | 4 +-- roboflow/core/project.py | 4 +-- roboflow/util/folderparser.py | 8 +++--- roboflow/util/image_utils.py | 4 +-- tests/util/test_folderparser.py | 47 +++++++++++++++++++++++++++++++++ 6 files changed, 67 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0646637c..9af61745 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented in this file. +## Unreleased + +### Fixed + +- Folder uploads, `Project.upload()` and `roboflow image annotate` read + annotation files and labelmaps (COCO, CreateML, CSV, JSONL, VOC, `data.yaml`) + as UTF-8 instead of the locale encoding. On Windows a class name like + `café` was uploaded as `café`, and some characters (ex: `ď`) failed the + whole upload with `UnicodeDecodeError`. + ## 1.7.5 ### Added diff --git a/roboflow/cli/handlers/image.py b/roboflow/cli/handlers/image.py index 3f3b2bf1..f2d4cb59 100644 --- a/roboflow/cli/handlers/image.py +++ b/roboflow/cli/handlers/image.py @@ -673,13 +673,13 @@ def _handle_annotate(args): # noqa: ANN001 output_error(args, f"Annotation file not found: {annotation_path}") return - with open(annotation_path) as f: + with open(annotation_path, encoding="utf-8") as f: annotation_string = f.read() annotation_name = os.path.basename(annotation_path) labelmap = None if args.labelmap: - with open(args.labelmap) as f: + with open(args.labelmap, encoding="utf-8") as f: labelmap = json.load(f) rfapi.save_annotation( diff --git a/roboflow/core/project.py b/roboflow/core/project.py index 05a8853d..68c523f8 100644 --- a/roboflow/core/project.py +++ b/roboflow/core/project.py @@ -716,8 +716,8 @@ def _annotation_params(self, annotation_path): annotation_name = annotation_path["name"] annotation_string = annotation_path["rawText"] elif os.path.exists(annotation_path): # type: ignore[arg-type] - with open(annotation_path): # type: ignore[arg-type] - annotation_string = open(annotation_path).read() # type: ignore[arg-type] + with open(annotation_path, encoding="utf-8") as f: # type: ignore[arg-type] + annotation_string = f.read() annotation_name = os.path.basename(annotation_path) # type: ignore[arg-type] elif self.type == "classification": print(f"-> using {annotation_path} as classname for classification project") diff --git a/roboflow/util/folderparser.py b/roboflow/util/folderparser.py index 32be6bde..ca591360 100644 --- a/roboflow/util/folderparser.py +++ b/roboflow/util/folderparser.py @@ -294,7 +294,7 @@ def _loadAnnotations(folder, annotations): for ann in annotations: extension = ann["extension"] if extension == ".json": - with open(f"{folder}{ann['file']}") as f: + with open(f"{folder}{ann['file']}", encoding="utf-8") as f: parsed = json.load(f) parsedType = _guessAnnotationFileFormat(parsed, extension) if parsedType: @@ -316,7 +316,7 @@ def _is_annotation_csv(folder, ann): # holds no annotations. if ann["name"] == "_classes.csv": return True - with open(f"{folder}{ann['file']}") as f: + with open(f"{folder}{ann['file']}", encoding="utf-8") as f: columns = len(f.readline().split(",")) if columns < 6: print(f"warning: skipping {ann['file']}: annotation CSVs have at least six columns") @@ -325,7 +325,7 @@ def _is_annotation_csv(folder, ann): def _read_jsonl(path): data = [] - with open(path) as file: + with open(path, encoding="utf-8") as file: for linenum, line in enumerate(file, 1): if not line: continue @@ -339,7 +339,7 @@ def _read_jsonl(path): def _parseAnnotationCSV(filename): # TODO: use a proper CSV library? - with open(filename) as f: + with open(filename, encoding="utf-8") as f: lines = f.readlines() headers = [h.strip() for h in lines[0].split(",")] # Multi-label classification csv typically named _classes.csv diff --git a/roboflow/util/image_utils.py b/roboflow/util/image_utils.py index 90266f90..839828a8 100644 --- a/roboflow/util/image_utils.py +++ b/roboflow/util/image_utils.py @@ -107,7 +107,7 @@ def file2jpeg(image_path): def load_labelmap(f): if f.lower().endswith(".yaml") or f.lower().endswith(".yml"): - with open(f) as file: + with open(f, encoding="utf-8") as file: data = yaml.safe_load(file) names = data.get("names", []) if isinstance(names, dict): @@ -115,6 +115,6 @@ def load_labelmap(f): else: return {i: name for i, name in enumerate(names)} else: - with open(f) as file: + with open(f, encoding="utf-8") as file: lines = [line for line in file.readlines() if line.strip()] return {i: line.strip() for i, line in enumerate(lines)} diff --git a/tests/util/test_folderparser.py b/tests/util/test_folderparser.py index 89373b01..6634b1ca 100644 --- a/tests/util/test_folderparser.py +++ b/tests/util/test_folderparser.py @@ -2,6 +2,8 @@ import io import json import os +import subprocess +import sys import tempfile import unittest from os.path import abspath, dirname @@ -227,6 +229,51 @@ def test_coco_root_annotation_matches_images_in_subdirs(self): self.assertEqual(len(ann_data["annotations"]), 1, "Should have one annotation") self.assertEqual(ann_data["annotations"][0]["bbox"], [10, 20, 100, 200]) + def test_reads_non_ascii_class_names_as_utf8_whatever_the_locale(self): + """UTF-8 COCO categories and data.yaml names survive a non-UTF-8 locale (cp1252 on Windows).""" + with tempfile.TemporaryDirectory() as tmpdir: + os.makedirs(os.path.join(tmpdir, "train")) + open(os.path.join(tmpdir, "train", "a.jpg"), "wb").close() + coco = { + "info": {}, + "licenses": [], + "categories": [{"id": 0, "name": "café"}, {"id": 1, "name": "loďka"}], + "images": [{"id": 1, "file_name": "a.jpg", "width": 10, "height": 10}], + "annotations": [{"id": 1, "image_id": 1, "category_id": 0, "bbox": [1, 1, 2, 2]}], + } + with open(os.path.join(tmpdir, "train", "_annotations.coco.json"), "w", encoding="utf-8") as f: + json.dump(coco, f, ensure_ascii=False) + with open(os.path.join(tmpdir, "data.yaml"), "w", encoding="utf-8") as f: + f.write("names: ['café', 'loďka']\n") + + # parse in a child with UTF-8 mode off, so open() falls back to the locale encoding + # the way it does on a default Windows install (CI sets PYTHONUTF8=1, which hides it) + script = ( + "import json, sys\n" + "from roboflow.util.folderparser import parsefolder\n" + "from roboflow.util.image_utils import load_labelmap\n" + "parsed = parsefolder(sys.argv[1])\n" + "coco = json.loads(parsed['images'][0]['annotationfile']['rawText'])\n" + "names = [c['name'] for c in coco['categories']]\n" + "labelmap = load_labelmap(sys.argv[1] + '/data.yaml')\n" + "print(json.dumps({'coco': names, 'yaml': [labelmap[0], labelmap[1]]}))\n" + ) + env = {k: v for k, v in os.environ.items() if k not in ("PYTHONUTF8", "LC_ALL", "LANG")} + env.update({"LC_ALL": "C", "PYTHONCOERCECLOCALE": "0"}) + result = subprocess.run( + [sys.executable, "-X", "utf8=0", "-c", script, tmpdir], + capture_output=True, + text=True, + encoding="utf-8", + env=env, + ) + + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + json.loads(result.stdout.splitlines()[-1]), + {"coco": ["café", "loďka"], "yaml": ["café", "loďka"]}, + ) + def _assertJsonMatchesFile(actual, filename): with open(filename) as file: