Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions roboflow/cli/handlers/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
4 changes: 2 additions & 2 deletions roboflow/core/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
8 changes: 4 additions & 4 deletions roboflow/util/folderparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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")
Expand All @@ -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
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions roboflow/util/image_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,14 @@ 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):
return {int(k): v for k, v in names.items()}
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)}
47 changes: 47 additions & 0 deletions tests/util/test_folderparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import io
import json
import os
import subprocess
import sys
import tempfile
import unittest
from os.path import abspath, dirname
Expand Down Expand Up @@ -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:
Expand Down