~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(settings): specify UTF-8 encoding for all file reads (#3797)
LearningCircuit6a1a6ae28df6
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 568f4c93a4..f80ca82dab 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -203,6 +203,13 @@ repos:language: scriptfiles: \.py$description: "Prevent printf-style %s/%d placeholders in loguru logger calls"+ - id: check-open-encoding+ name: Check open() calls have explicit encoding+ entry: .pre-commit-hooks/check-open-encoding.py+ language: script+ files: \.py$+ exclude: ^(tests/|examples/|scripts/)+ description: "Enforce explicit encoding= on text-mode open() calls (issue #3743)"- id: check-image-pinningname: Check Docker Image Pinningentry: .pre-commit-hooks/check-image-pinning.shdiff --git a/.pre-commit-hooks/check-codeowners-sync.py b/.pre-commit-hooks/check-codeowners-sync.pyindex 7c7eb7b86d..d16b886f06 100755--- a/.pre-commit-hooks/check-codeowners-sync.py+++ b/.pre-commit-hooks/check-codeowners-sync.py@@ -16,8 +16,8 @@ def main():return 0try:- codeowners_text = codeowners_file.read_text()- workflow_text = workflow_file.read_text()+ codeowners_text = codeowners_file.read_text(encoding="utf-8")+ workflow_text = workflow_file.read_text(encoding="utf-8")except OSError as e:print(f"ERROR: Could not read file: {e}")return 1diff --git a/.pre-commit-hooks/check-css-class-prefix.py b/.pre-commit-hooks/check-css-class-prefix.pyindex a4270fb954..6ae6dab351 100755--- a/.pre-commit-hooks/check-css-class-prefix.py+++ b/.pre-commit-hooks/check-css-class-prefix.py@@ -138,7 +138,7 @@ def check_css_file(file_path: Path) -> List[Tuple[int, str, str]]:errors = []try:- content = file_path.read_text()+ content = file_path.read_text(encoding="utf-8")lines = content.split("\n")# Pattern to match CSS class selectors, including compound@@ -185,7 +185,7 @@ def check_html_file(file_path: Path) -> List[Tuple[int, str, str]]:errors = []try:- content = file_path.read_text()+ content = file_path.read_text(encoding="utf-8")lines = content.split("\n")# Pattern to match class attributes in HTML@@ -339,7 +339,7 @@ def check_js_file(file_path: Path) -> List[Tuple[int, str, str]]:errors = []try:- content = file_path.read_text()+ content = file_path.read_text(encoding="utf-8")lines = content.split("\n")# Patterns to match class usage in JavaScript (excluding querySelector/jQuery)diff --git a/.pre-commit-hooks/check-deprecated-settings-wrapper.py b/.pre-commit-hooks/check-deprecated-settings-wrapper.pyindex 64cf56099d..e4fe1e41ed 100755--- a/.pre-commit-hooks/check-deprecated-settings-wrapper.py+++ b/.pre-commit-hooks/check-deprecated-settings-wrapper.py@@ -25,7 +25,7 @@ def check_file(filepath: Path) -> List[Tuple[int, str]]:errors = []try:- content = filepath.read_text()+ content = filepath.read_text(encoding="utf-8")# Short-circuit: no mention at all → nothing to check.if "get_setting_from_db_main_thread" not in content:diff --git a/.pre-commit-hooks/check-open-encoding.py b/.pre-commit-hooks/check-open-encoding.pynew file mode 100755index 0000000000..b9e15eb3b8--- /dev/null+++ b/.pre-commit-hooks/check-open-encoding.py@@ -0,0 +1,179 @@+#!/usr/bin/env python3+"""+Pre-commit hook to enforce explicit ``encoding=`` on text-mode file I/O calls.++On Windows the default encoding is the system locale (often cp1252), not UTF-8.+Omitting ``encoding`` causes silent failures or ``UnicodeDecodeError`` when+reading/writing UTF-8 files. See issue #3743.++Detects:+ * Bare ``open(...)`` — second positional arg is the mode.+ * ``<expr>.open(<mode>, ...)`` — only when the first positional arg is a+ constant string that looks like a real file mode (avoids false positives+ on ``tarfile.open`` / ``zipfile.open`` etc., which take a path first).+ * ``<expr>.read_text(...)`` and ``<expr>.write_text(...)`` — these are+ effectively pathlib-only, so any bare call without ``encoding=`` is flagged.+"""++import ast+import sys+from pathlib import Path++_FILE_MODE_CHARS = frozenset("rwxabt+")+++def _looks_like_file_mode(value: object) -> bool:+ """True if value is a string that plausibly is a file ``open`` mode."""+ return (+ isinstance(value, str)+ and 0 < len(value) <= 3+ and set(value) <= _FILE_MODE_CHARS+ )+++def _has_encoding_keyword(call: ast.Call) -> bool:+ """True if the call has an explicit ``encoding=`` kwarg.++ Treats ``**kwargs`` spreads as "may contain encoding" to avoid false+ positives — we can't statically prove the spread doesn't supply it.+ """+ for kw in call.keywords:+ if kw.arg is None: # **kwargs spread+ return True+ if kw.arg == "encoding":+ return True+ return False+++def _get_mode_arg(call: ast.Call, positional_index: int) -> ast.expr | None:+ """Return the mode AST node, looking at both positional and ``mode=`` kwarg.++ Returns None if no mode was supplied (caller defaults to text mode).+ """+ if len(call.args) > positional_index:+ return call.args[positional_index]++ for kw in call.keywords:+ if kw.arg == "mode":+ return kw.value++ return None+++def _is_text_mode_at(call: ast.Call, mode_arg_index: int) -> bool | None:+ """Return True if the mode argument is text mode.++ Inspects both the positional slot and the ``mode=`` kwarg, so calls like+ ``open(f, mode="rb")`` are correctly classified as binary even though the+ positional slot is empty.++ Returns ``None`` (falsy) when the mode can't be determined statically —+ e.g. ``open(filepath, mode)`` where ``mode`` is a variable.+ """+ mode_arg = _get_mode_arg(call, mode_arg_index)+ if mode_arg is None:+ return True # default mode is "r" (text)++ if not isinstance(mode_arg, ast.Constant):+ return None++ return "b" not in str(mode_arg.value)+++def _violations_for_call(node: ast.Call) -> list[tuple[int, str]]:+ func = node.func++ # Bare open(...) — second positional arg is mode.+ if isinstance(func, ast.Name) and func.id == "open":+ if _is_text_mode_at(node, 1) and not _has_encoding_keyword(node):+ return [(node.lineno, "open() called without explicit encoding=")]+ return []++ if not isinstance(func, ast.Attribute):+ return []++ attr = func.attr++ # Path.read_text() / Path.write_text() — encoding= is the only safe option.+ if attr in {"read_text", "write_text"}:+ if not _has_encoding_keyword(node):+ return [+ (+ node.lineno,+ f".{attr}() called without explicit encoding=",+ )+ ]+ return []++ # <expr>.open(<mode>, ...) — first positional arg is the mode (or mode= kwarg).+ # When the mode looks like a file mode (or is omitted entirely, defaulting+ # to "r"), flag missing encoding. The mode-shape filter avoids false+ # positives on tarfile.open("foo.tar") / zipfile.ZipFile.open("inner") etc.+ # — bare ``.open()`` is the same gap that bare ``open(f)`` already catches.+ if attr == "open":+ mode_arg = _get_mode_arg(node, 0)+ flag = False+ if mode_arg is None:+ flag = True # defaults to "r" — same risk as bare open(f)+ elif isinstance(mode_arg, ast.Constant) and _looks_like_file_mode(+ mode_arg.value+ ):+ flag = "b" not in mode_arg.value+ if flag and not _has_encoding_keyword(node):+ return [+ (+ node.lineno,+ ".open() called without explicit encoding=",+ )+ ]++ return []+++def check_file(file_path: str) -> list[tuple[int, str]]:+ path = Path(file_path)+ if path.suffix != ".py":+ return []++ try:+ source = path.read_text(encoding="utf-8")+ except Exception:+ return []++ try:+ tree = ast.parse(source, filename=file_path)+ except SyntaxError:+ return []++ violations: list[tuple[int, str]] = []+ for node in ast.walk(tree):+ if isinstance(node, ast.Call):+ violations.extend(_violations_for_call(node))++ return violations+++def main() -> int:+ exit_code = 0++ for file_path in sys.argv[1:]:+ violations = check_file(file_path)+ for lineno, message in violations:+ print(f"{file_path}:{lineno}: {message}")+ exit_code = 1++ if exit_code:+ print()+ print(+ "Hint: add encoding='utf-8' (or 'utf-8-sig' for JSON config files)"+ )+ print(+ " to all text-mode open() / Path.open() / read_text() / write_text() calls."+ )+ print(" See issue #3743.")++ return exit_code+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.pre-commit-hooks/check-pathlib-usage.py b/.pre-commit-hooks/check-pathlib-usage.pyindex c61fb24d19..42347c818a 100755--- a/.pre-commit-hooks/check-pathlib-usage.py+++ b/.pre-commit-hooks/check-pathlib-usage.py@@ -139,7 +139,7 @@ def check_file(List of (filename, line_number, violation_message) tuples"""try:- content = filepath.read_text()+ content = filepath.read_text(encoding="utf-8")tree = ast.parse(content, filename=str(filepath))except SyntaxError as e:print(f"Syntax error in {filepath}: {e}", file=sys.stderr)diff --git a/.pre-commit-hooks/check-session-context-manager.py b/.pre-commit-hooks/check-session-context-manager.pyindex 75f1c46a6e..2f2da836e2 100755--- a/.pre-commit-hooks/check-session-context-manager.py+++ b/.pre-commit-hooks/check-session-context-manager.py@@ -115,7 +115,7 @@ def check_file(filepath: Path) -> List[Tuple[str, int, str]]:issues = []try:- content = filepath.read_text()+ content = filepath.read_text(encoding="utf-8")tree = ast.parse(content, filename=str(filepath))checker = SessionPatternChecker(str(filepath))diff --git a/.pre-commit-hooks/check-settings-manager-thread-safety.py b/.pre-commit-hooks/check-settings-manager-thread-safety.pyindex 712fb6cf62..e599af51de 100755--- a/.pre-commit-hooks/check-settings-manager-thread-safety.py+++ b/.pre-commit-hooks/check-settings-manager-thread-safety.py@@ -138,7 +138,7 @@ def check_file(filepath: Path) -> List[Tuple[str, int, str]]:"""Check a single Python file."""issues = []try:- content = filepath.read_text()+ content = filepath.read_text(encoding="utf-8")tree = ast.parse(content, filename=str(filepath))checker = SettingsManagerThreadSafetyChecker(str(filepath))checker.visit(tree)diff --git a/.pre-commit-hooks/check-version-sync.py b/.pre-commit-hooks/check-version-sync.pyindex dbb2371736..8482a7d590 100755--- a/.pre-commit-hooks/check-version-sync.py+++ b/.pre-commit-hooks/check-version-sync.py@@ -17,7 +17,7 @@ def main():return 1try:- version_content = version_file.read_text()+ version_content = version_file.read_text(encoding="utf-8")except OSError as e:print(f"ERROR: Could not read {version_file}: {e}")return 1@@ -35,7 +35,7 @@ def main():return 1try:- package_content = package_file.read_text()+ package_content = package_file.read_text(encoding="utf-8")package_data = json.loads(package_content)except OSError as e:print(f"ERROR: Could not read {package_file}: {e}")diff --git a/changelog.d/3797.bugfix.md b/changelog.d/3797.bugfix.mdnew file mode 100644index 0000000000..cebba42b46--- /dev/null+++ b/changelog.d/3797.bugfix.md@@ -0,0 +1 @@+Fixed `UnicodeDecodeError` on Windows when loading settings, security config, benchmark results, and Vite manifest files. All text-mode `open()` calls now use explicit UTF-8 encoding, and JSON config files use `utf-8-sig` to handle BOM-prefixed files from Windows editors. Fixes #3743.diff --git a/cookiecutter-docker/hooks/pre_prompt.py b/cookiecutter-docker/hooks/pre_prompt.pyindex 4323d6aa98..9546cf904a 100644--- a/cookiecutter-docker/hooks/pre_prompt.py+++ b/cookiecutter-docker/hooks/pre_prompt.py@@ -91,7 +91,7 @@ def check_gpu_windows(context: Dict[str, Any]) -> None:def main() -> None:# Load the context.- with open("cookiecutter.json", "r") as config:+ with open("cookiecutter.json", "r", encoding="utf-8") as config:context = json.load(config)# Check GPU information based on the operating system.@@ -103,7 +103,7 @@ def main() -> None:config_ollama(context)# Save the updated context back to cookiecutter.json.- with open("cookiecutter.json", "w") as config:+ with open("cookiecutter.json", "w", encoding="utf-8") as config:json.dump(context, config, indent=4)diff --git a/src/local_deep_research/api/settings_utils.py b/src/local_deep_research/api/settings_utils.pyindex 69c61dbe9b..e66dda90d8 100644--- a/src/local_deep_research/api/settings_utils.py+++ b/src/local_deep_research/api/settings_utils.py@@ -92,7 +92,9 @@ class InMemorySettingsManager(ISettingsManager):if search_engines_dir.exists() and search_engines_dir.is_dir():for json_file in search_engines_dir.glob("*.json"):try:- engine_settings = json.loads(json_file.read_text())+ engine_settings = json.loads(+ json_file.read_text(encoding="utf-8-sig")+ )# Merge into main settingsfor key, setting_data in engine_settings.items():if key not in self._settings:diff --git a/src/local_deep_research/benchmarks/comparison/results.py b/src/local_deep_research/benchmarks/comparison/results.pyindex f3f55e5e19..f8a0c8e19e 100644--- a/src/local_deep_research/benchmarks/comparison/results.py+++ b/src/local_deep_research/benchmarks/comparison/results.py@@ -60,7 +60,7 @@ class Benchmark_results:# Load results from filetry:- with open(self.results_file, "r") as f:+ with open(self.results_file, "r", encoding="utf-8") as f:return json.load(f)except FileNotFoundError:return []diff --git a/src/local_deep_research/benchmarks/datasets/base.py b/src/local_deep_research/benchmarks/datasets/base.pyindex 74176c6f20..e9c52fe168 100644--- a/src/local_deep_research/benchmarks/datasets/base.py+++ b/src/local_deep_research/benchmarks/datasets/base.py@@ -105,7 +105,7 @@ class BenchmarkDataset(ABC):else:import json- with open(self.dataset_path, "r") as f:+ with open(self.dataset_path, "r", encoding="utf-8") as f:if self.dataset_path.endswith(".jsonl"):raw_examples = [json.loads(line) for line in f if line.strip()diff --git a/src/local_deep_research/benchmarks/evaluators/simpleqa.py b/src/local_deep_research/benchmarks/evaluators/simpleqa.pyindex 914e127e38..90a11aeea3 100644--- a/src/local_deep_research/benchmarks/evaluators/simpleqa.py+++ b/src/local_deep_research/benchmarks/evaluators/simpleqa.py@@ -215,7 +215,7 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):results.append(result)# Write result to file- with open(results_file, "a") as f:+ with open(results_file, "a", encoding="utf-8") as f:f.write(json.dumps(result) + "\n")except Exception as e:@@ -234,7 +234,7 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):results.append(error_result)# Write error result to file- with open(results_file, "a") as f:+ with open(results_file, "a", encoding="utf-8") as f:f.write(json.dumps(error_result) + "\n")# Grade resultsdiff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.pyindex 6472694abb..74738f1df0 100644--- a/src/local_deep_research/benchmarks/graders.py+++ b/src/local_deep_research/benchmarks/graders.py@@ -350,7 +350,7 @@ def _grade_results_inner(# Load resultsresults = []- with open(results_file, "r") as f:+ with open(results_file, "r", encoding="utf-8") as f:for line in f:if line.strip():results.append(json.loads(line))@@ -488,7 +488,7 @@ def _grade_results_inner(graded_results.append(graded_result)# Write to output file- with open(output_file, "a") as f:+ with open(output_file, "a", encoding="utf-8") as f:f.write(json.dumps(graded_result) + "\n")# Call progress callback if provided@@ -510,7 +510,7 @@ def _grade_results_inner(error_result = result.copy()error_result["grading_error"] = str(e)- with open(output_file, "a") as f:+ with open(output_file, "a", encoding="utf-8") as f:f.write(json.dumps(error_result) + "\n")graded_results.append(error_result)@@ -550,7 +550,7 @@ def human_evaluation("""# Load resultsresults = []- with open(results_file, "r") as f:+ with open(results_file, "r", encoding="utf-8") as f:for line in f:if line.strip():results.append(json.loads(line))@@ -623,7 +623,7 @@ def human_evaluation(human_graded_results.append(human_result)# Write to output file- with open(output_file, "a") as f:+ with open(output_file, "a", encoding="utf-8") as f:f.write(json.dumps(human_result) + "\n")accuracy = correct_count / len(results) if results else 0diff --git a/src/local_deep_research/benchmarks/metrics/calculation.py b/src/local_deep_research/benchmarks/metrics/calculation.pyindex f288acb3ef..e19b6707f2 100644--- a/src/local_deep_research/benchmarks/metrics/calculation.py+++ b/src/local_deep_research/benchmarks/metrics/calculation.py@@ -27,7 +27,7 @@ def calculate_metrics(results_file: str) -> Dict[str, Any]:# Load resultsresults = []try:- with open(results_file, "r") as f:+ with open(results_file, "r", encoding="utf-8") as f:for line in f:if line.strip():results.append(json.loads(line))diff --git a/src/local_deep_research/benchmarks/metrics/reporting.py b/src/local_deep_research/benchmarks/metrics/reporting.pyindex e40e842a00..8dd1c7272d 100644--- a/src/local_deep_research/benchmarks/metrics/reporting.py+++ b/src/local_deep_research/benchmarks/metrics/reporting.py@@ -37,7 +37,7 @@ def generate_report(# Load a sample of results for examplesresults = []try:- with open(results_file, "r") as f:+ with open(results_file, "r", encoding="utf-8") as f:for line in f:if line.strip():results.append(json.loads(line))diff --git a/src/local_deep_research/benchmarks/runners.py b/src/local_deep_research/benchmarks/runners.pyindex 1d2ca76093..2b23aaa11a 100644--- a/src/local_deep_research/benchmarks/runners.py+++ b/src/local_deep_research/benchmarks/runners.py@@ -228,7 +228,7 @@ def run_benchmark(results.append(result)# Write result to file- with open(results_file, "a") as f:+ with open(results_file, "a", encoding="utf-8") as f:f.write(json.dumps(result) + "\n")# Update progress@@ -262,7 +262,7 @@ def run_benchmark(results.append(error_result)# Write error result to file- with open(results_file, "a") as f:+ with open(results_file, "a", encoding="utf-8") as f:f.write(json.dumps(error_result) + "\n")# Update progressdiff --git a/src/local_deep_research/journal_quality/db.py b/src/local_deep_research/journal_quality/db.pyindex dfd04f00f3..b3c0afbd27 100644--- a/src/local_deep_research/journal_quality/db.py+++ b/src/local_deep_research/journal_quality/db.py@@ -222,7 +222,7 @@ class JournalQualityDB:if not version_file.exists():return # Brand-new install — the dashboard's banner handles this.try:- with open(version_file) as f:+ with open(version_file, encoding="utf-8") as f:info = json.load(f)installed = info.get("version")except (json.JSONDecodeError, OSError):diff --git a/src/local_deep_research/journal_quality/downloader.py b/src/local_deep_research/journal_quality/downloader.pyindex 7698c60b4d..437d7496ae 100644--- a/src/local_deep_research/journal_quality/downloader.py+++ b/src/local_deep_research/journal_quality/downloader.py@@ -230,7 +230,7 @@ def get_journal_data_status() -> dict:installed_version: Optional[str] = Noneif version_file.exists():try:- with open(version_file) as f:+ with open(version_file, encoding="utf-8") as f:info = json.load(f)installed_version = info.get("version")except (json.JSONDecodeError, OSError):@@ -350,7 +350,7 @@ def download_journal_data(force: bool = False) -> tuple[bool, str]:def _sentinel_owner_alive() -> bool:try:- owner_pid = int(sentinel.read_text().strip())+ owner_pid = int(sentinel.read_text(encoding="utf-8").strip())except (OSError, ValueError):return False # unreadable / malformed → treat as orphanif owner_pid == os.getpid():@@ -372,7 +372,7 @@ def download_journal_data(force: bool = False) -> tuple[bool, str]:def _try_claim_sentinel() -> bool:"""Create the sentinel + stamp our PID. Returns True on success."""try:- with sentinel.open("x") as f:+ with sentinel.open("x", encoding="utf-8") as f:f.write(str(os.getpid()))return Trueexcept FileExistsError:@@ -512,7 +512,7 @@ def download_journal_data(force: bool = False) -> tuple[bool, str]:# any external consumer that might read them, even though no# production code does today.version_file = data_dir / "version.json"- with open(version_file, "w") as f:+ with open(version_file, "w", encoding="utf-8") as f:json.dump({"version": JOURNAL_DATA_VERSION,diff --git a/src/local_deep_research/security/security_settings.py b/src/local_deep_research/security/security_settings.pyindex 7fd9d4f53f..9cb7e4b14d 100644--- a/src/local_deep_research/security/security_settings.py+++ b/src/local_deep_research/security/security_settings.py@@ -31,7 +31,7 @@ def _load_security_settings() -> dict:"""try:if _SETTINGS_PATH.exists():- with open(_SETTINGS_PATH, "r") as f:+ with open(_SETTINGS_PATH, "r", encoding="utf-8-sig") as f:return json.load(f)except Exception:logger.warning(diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.pyindex 183a1e0ba7..ad03c50e0a 100644--- a/src/local_deep_research/settings/manager.py+++ b/src/local_deep_research/settings/manager.py@@ -411,7 +411,7 @@ class SettingsManager(ISettingsManager):# Load and merge all JSON filesfor json_file in json_files:try:- with open(json_file, "r") as f:+ with open(json_file, "r", encoding="utf-8-sig") as f:file_settings = json.load(f)# Get relative path for loggingdiff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex ab38348f07..10cbc6c607 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -241,7 +241,7 @@ def create_app():logger.info("Generated new SECRET_KEY for this installation")except FileExistsError:try:- with open(secret_key_file, "r") as f:+ with open(secret_key_file, "r", encoding="utf-8") as f:app.config["SECRET_KEY"] = f.read().strip()except Exception:logger.warning("Could not read secret key file")diff --git a/src/local_deep_research/web/utils/vite_helper.py b/src/local_deep_research/web/utils/vite_helper.pyindex aefd0da854..58b28e83e1 100644--- a/src/local_deep_research/web/utils/vite_helper.py+++ b/src/local_deep_research/web/utils/vite_helper.py@@ -38,7 +38,7 @@ class ViteHelper:manifest_path = Path(static_dir) / "dist" / ".vite" / "manifest.json"if manifest_path.exists():- with open(manifest_path, "r") as f:+ with open(manifest_path, "r", encoding="utf-8-sig") as f:self.manifest = json.load(f)else:# Fallback if manifest doesn't exist yet