Automation foundation model for tiny devices: 2-bit, 8-29 MB, tool calls, ASR, structured extraction and embeddings on phones, wearables, smart homes, robots, cars and microcontrollers.
fix: read and write tool and training files as UTF-8 on every platform (#159)
kevin1e135551e563
diff --git a/needle/model/finetune.py b/needle/model/finetune.pyindex 9a0c212..7063fcb 100644--- a/needle/model/finetune.py+++ b/needle/model/finetune.py@@ -163,7 +163,7 @@ def _collect_tools(examples):def augment_jsonl(path, num_samples, model=DEFAULT_MODEL, batch_size=25, out_path=None, workers=8):- with open(path) as handle:+ with open(path, encoding="utf-8") as handle:examples = [json.loads(line) for line in handle if line.strip()]tools = _collect_tools(examples)if not tools:@@ -171,7 +171,7 @@ def augment_jsonl(path, num_samples, model=DEFAULT_MODEL, batch_size=25, out_patout_path = out_path or path.replace(".jsonl", "") + ".augmented.jsonl"generated = generate_dataset(tools, num_samples, model=model or DEFAULT_MODEL,batch_size=batch_size, workers=workers)- with open(out_path, "w") as handle:+ with open(out_path, "w", encoding="utf-8") as handle:for example in examples + generated:handle.write(json.dumps(example) + "\n")print(f" {'wrote':<9} {len(examples) + len(generated)} examples {out_path}")@@ -182,12 +182,12 @@ def generate_main(args):model = args.model or DEFAULT_MODELworkers = getattr(args, "workers", 8)if args.tools:- with open(args.tools) as handle:+ with open(args.tools, encoding="utf-8") as handle:tools = json.load(handle)out = args.output or "needle_data.jsonl"rows = generate_dataset(tools, args.num_samples, model=model,batch_size=args.batch_size, workers=workers)- with open(out, "w") as handle:+ with open(out, "w", encoding="utf-8") as handle:for row in rows:handle.write(json.dumps(row) + "\n")print(f" {'wrote':<9} {len(rows)} examples {out}")@@ -253,7 +253,7 @@ def from_chat(example):def read_examples(path, report=False):skipped = 0- with open(path) as handle:+ with open(path, encoding="utf-8") as handle:for line in handle:line = line.strip()if not line:diff --git a/needle/model/run.py b/needle/model/run.pyindex 487fcd8..5e3a17b 100644--- a/needle/model/run.py+++ b/needle/model/run.py@@ -114,7 +114,7 @@ def main(args):prompt = args.query or "The most surprising thing about"if getattr(args, "tools", None):- with open(args.tools) as handle:+ with open(args.tools, encoding="utf-8") as handle:prompt = build_prompt(prompt, json.load(handle))print(f"prompt: {prompt!r}")generate(diff --git a/needle/platform.py b/needle/platform.pyindex 6aa01f3..d0b3955 100644--- a/needle/platform.py+++ b/needle/platform.py@@ -346,7 +346,7 @@ def _cmd_finetune(client, args):def _cmd_generate(client, args):_print_usage(client)- with open(args.tools) as handle:+ with open(args.tools, encoding="utf-8") as handle:tools = json.load(handle)job = client.generate(tools, args.examples, description=args.description,messages=args.message, suffix=args.suffix)diff --git a/needle/playground/server.py b/needle/playground/server.pyindex d5911cd..fe5383a 100644--- a/needle/playground/server.py+++ b/needle/playground/server.py@@ -73,7 +73,7 @@ def _finetune_worker(tools_json, api_key, samples, engine):tools, samples, api_key=api_key,progress=lambda done, total: _log(f"generated {done}/{total}"))data_path = str(_DOWNLOADS / "needle_playground_data.jsonl")- with open(data_path, "w") as handle:+ with open(data_path, "w", encoding="utf-8") as handle:for row in rows:handle.write(json.dumps(row) + "\n")diff --git a/tests/test_platform.py b/tests/test_platform.pyindex aa9690e..f7df2d2 100644--- a/tests/test_platform.py+++ b/tests/test_platform.py@@ -221,3 +221,65 @@ def test_confidence_head_detected_from_manifest(tmp_path, fake_cact):assert needle._confidence_head_present(str(tmp_path / "platform.cact")) is Trueassert needle._confidence_head_present(str(tmp_path / "local.cact")) is Falseassert needle._confidence_head_present(str(tmp_path / "bare.cact")) is False+++def _locale_open(encoding):+ """open() as it behaves where the locale's encoding is `encoding` (Windows'+ ANSI code page): a text-mode open without an encoding decodes with it."""+ import builtins++ def locale_open(file, mode="r", *args, **kwargs):+ if "b" not in mode and not args and kwargs.get("encoding") is None:+ kwargs["encoding"] = encoding+ return builtins.open(file, mode, *args, **kwargs)+ return locale_open++[email protected]("locale_encoding", ["cp1252", "cp949"])+def test_data_and_tool_files_are_utf8_whatever_the_locale(tmp_path, monkeypatch, locale_encoding):+ # The JSON these commands read is UTF-8, but a text-mode open() without an+ # encoding decodes with the locale's. On Windows "café" came back as+ # "café" (cp1252) or "caf챕" (cp949) with no error, and an emoji stopped+ # the read with UnicodeDecodeError.+ import types++ import needle.model.finetune as finetune+ import needle.platform as platform++ for module in (finetune, platform):+ monkeypatch.setattr(module, "open", _locale_open(locale_encoding), raising=False)+ query = "set the café lights to 22°C and play 🎵"+ tools = [{"name": "set_lights", "description": "Réglez la lumière à 22°C",+ "parameters": {"type": "object", "properties": {}}}]+ tools_path = tmp_path / "tools.json"+ tools_path.write_text(json.dumps(tools, ensure_ascii=False), encoding="utf-8")+ data = tmp_path / "data.jsonl"+ data.write_text(json.dumps({"query": query, "tools": tools, "answers": []}, ensure_ascii=False) + "\n",+ encoding="utf-8")++ assert [row["query"] for row in finetune.read_examples(str(data))] == [query]++ seen = {}++ def generate_dataset(tools, num_samples, **kwargs):+ seen["generate"] = tools+ return [{"query": query, "tools": tools, "answers": []}]+ monkeypatch.setattr(finetune, "generate_dataset", generate_dataset)+ out = tmp_path / "generated.jsonl"+ finetune.generate_main(types.SimpleNamespace(+ model=None, workers=1, tools=str(tools_path), output=str(out), num_samples=1,+ batch_size=1, augment=None))+ assert seen["generate"] == tools+ assert [row["query"] for row in finetune.read_examples(str(out))] == [query]++ class Client:+ def billing(self):+ return {}++ def generate(self, tools, examples, **kwargs):+ seen["platform"] = tools+ return {"id": "gen-1"}+ platform._cmd_generate(Client(), types.SimpleNamespace(+ tools=str(tools_path), examples=10, description=None, message=None, suffix=None,+ no_wait=True))+ assert seen["platform"] == tools