~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
feat: Add pre-commit hook to enforce pathlib usage (issue #640) (#656)
LearningCircuit0c6635ecc270
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 02bb3e2d5e..fd2367232d 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -77,3 +77,9 @@ repos:language: scriptfiles: \.py$description: "Ensure SQLAlchemy sessions use context managers instead of try/finally blocks"+ - id: check-pathlib-usage+ name: Check for os.path usage+ entry: .pre-commit-hooks/check-pathlib-usage.py+ language: script+ files: \.py$+ description: "Enforce using pathlib.Path instead of os.path for better cross-platform compatibility"diff --git a/.pre-commit-hooks/check-pathlib-usage.py b/.pre-commit-hooks/check-pathlib-usage.pynew file mode 100755index 0000000000..c61fb24d19--- /dev/null+++ b/.pre-commit-hooks/check-pathlib-usage.py@@ -0,0 +1,217 @@+#!/usr/bin/env python3+"""+Pre-commit hook to enforce using pathlib.Path instead of os.path.++This hook checks for os.path usage in Python files and suggests+using pathlib.Path instead for better cross-platform compatibility+and more modern Python code.+"""++import argparse+import ast+import sys+from pathlib import Path+from typing import List, Tuple+++class OsPathChecker(ast.NodeVisitor):+ """AST visitor to find os.path usage."""++ def __init__(self, filename: str):+ self.filename = filename+ self.violations: List[Tuple[int, str]] = []+ self.has_os_import = False+ self.has_os_path_import = False++ def visit_Import(self, node: ast.Import) -> None:+ """Check for 'import os' statements."""+ for alias in node.names:+ if alias.name == "os":+ self.has_os_import = True+ self.generic_visit(node)++ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:+ """Check for 'from os import path' or 'from os.path import ...' statements."""+ if node.module == "os" and any(+ alias.name == "path" for alias in node.names+ ):+ self.has_os_path_import = True+ self.violations.append(+ (+ node.lineno,+ "Found 'from os import path' - use 'from pathlib import Path' instead",+ )+ )+ elif node.module == "os.path":+ self.has_os_path_import = True+ imported_names = [alias.name for alias in node.names]+ self.violations.append(+ (+ node.lineno,+ f"Found 'from os.path import {', '.join(imported_names)}' - use pathlib.Path methods instead",+ )+ )+ self.generic_visit(node)++ def visit_Attribute(self, node: ast.Attribute) -> None:+ """Check for os.path.* usage."""+ if (+ isinstance(node.value, ast.Name)+ and node.value.id == "os"+ and node.attr == "path"+ and self.has_os_import+ ):+ # This is os.path usage+ # Try to get the specific method being called+ parent = getattr(node, "parent", None)+ if parent and isinstance(parent, ast.Attribute):+ method = parent.attr+ # Skip os.path.expandvars as it has no pathlib equivalent+ if method == "expandvars":+ return+ suggestion = get_pathlib_equivalent(f"os.path.{method}")+ else:+ suggestion = "Use pathlib.Path instead"++ self.violations.append(+ (node.lineno, f"Found os.path usage - {suggestion}")+ )+ self.generic_visit(node)++ def visit_Call(self, node: ast.Call) -> None:+ """Check for direct calls to os.path functions."""+ if isinstance(node.func, ast.Attribute):+ # Store parent reference for better context+ node.func.parent = node++ # Check for os.path.* calls+ if (+ isinstance(node.func.value, ast.Attribute)+ and isinstance(node.func.value.value, ast.Name)+ and node.func.value.value.id == "os"+ and node.func.value.attr == "path"+ ):+ method = node.func.attr+ # Skip os.path.expandvars as it has no pathlib equivalent+ if method == "expandvars":+ return+ suggestion = get_pathlib_equivalent(f"os.path.{method}")+ self.violations.append(+ (node.lineno, f"Found os.path.{method}() - {suggestion}")+ )+ self.generic_visit(node)+++def get_pathlib_equivalent(os_path_call: str) -> str:+ """Get the pathlib equivalent for common os.path operations."""+ equivalents = {+ "os.path.join": "Use Path() / 'subpath' or Path().joinpath()",+ "os.path.exists": "Use Path().exists()",+ "os.path.isfile": "Use Path().is_file()",+ "os.path.isdir": "Use Path().is_dir()",+ "os.path.dirname": "Use Path().parent",+ "os.path.basename": "Use Path().name",+ "os.path.abspath": "Use Path().resolve()",+ "os.path.realpath": "Use Path().resolve()",+ "os.path.expanduser": "Use Path().expanduser()",+ "os.path.split": "Use Path().parent and Path().name",+ "os.path.splitext": "Use Path().stem and Path().suffix",+ "os.path.getsize": "Use Path().stat().st_size",+ "os.path.getmtime": "Use Path().stat().st_mtime",+ "os.path.normpath": "Use Path() - it normalizes automatically",+ # Note: os.path.expandvars has no pathlib equivalent and is allowed+ "os.path.expandvars": "(No pathlib equivalent - allowed)",+ }+ return equivalents.get(os_path_call, "Use pathlib.Path equivalent method")+++def check_file(+ filepath: Path, allow_legacy: bool = False+) -> List[Tuple[str, int, str]]:+ """+ Check a Python file for os.path usage.++ Args:+ filepath: Path to the Python file to check+ allow_legacy: If True, only check modified lines (not implemented yet)++ Returns:+ List of (filename, line_number, violation_message) tuples+ """+ try:+ content = filepath.read_text()+ tree = ast.parse(content, filename=str(filepath))+ except SyntaxError as e:+ print(f"Syntax error in {filepath}: {e}", file=sys.stderr)+ return []+ except Exception as e:+ print(f"Error reading {filepath}: {e}", file=sys.stderr)+ return []++ checker = OsPathChecker(str(filepath))+ checker.visit(tree)++ return [(str(filepath), line, msg) for line, msg in checker.violations]+++def main() -> int:+ """Main entry point for the pre-commit hook."""+ parser = argparse.ArgumentParser(+ description="Check for os.path usage and suggest pathlib alternatives"+ )+ parser.add_argument(+ "filenames",+ nargs="*",+ help="Python files to check",+ )+ parser.add_argument(+ "--allow-legacy",+ action="store_true",+ help="Allow os.path in existing code (only check new/modified lines)",+ )++ args = parser.parse_args()++ # List of files that are allowed to use os.path (legacy or special cases)+ ALLOWED_FILES = {+ "src/local_deep_research/utilities/log_utils.py", # May need os.path for low-level operations+ "src/local_deep_research/config/paths.py", # Already migrated but may have legacy code+ ".pre-commit-hooks/check-pathlib-usage.py", # This file itself+ }++ violations = []+ for filename in args.filenames:+ filepath = Path(filename)++ # Skip non-Python files+ if not filename.endswith(".py"):+ continue++ # Skip allowed files+ if any(filename.endswith(allowed) for allowed in ALLOWED_FILES):+ continue++ file_violations = check_file(filepath, args.allow_legacy)+ violations.extend(file_violations)++ if violations:+ print("\n❌ Found os.path usage - please use pathlib.Path instead:\n")+ for filename, line, message in violations:+ print(f" {filename}:{line}: {message}")++ print(+ "\n💡 Tip: pathlib.Path provides a more modern and cross-platform API."+ )+ print(+ " Example: Path('dir') / 'file.txt' instead of os.path.join('dir', 'file.txt')"+ )+ print(+ "\n📚 See https://docs.python.org/3/library/pathlib.html for more information.\n"+ )+ return 1++ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/examples/benchmarks/browsecomp/run_browsecomp_fixed_v2.py b/examples/benchmarks/browsecomp/run_browsecomp_fixed_v2.pyindex 37d6674529..f150b77349 100755--- a/examples/benchmarks/browsecomp/run_browsecomp_fixed_v2.py+++ b/examples/benchmarks/browsecomp/run_browsecomp_fixed_v2.py@@ -11,12 +11,13 @@ import osimport randomimport reimport sys+from pathlib import Pathfrom typing import Optionalimport pandas as pd# Set up Python path-current_dir = os.path.dirname(os.path.abspath(__file__))+current_dir = str(Path(__file__).parent.resolve())sys.path.insert(0, current_dir)try:@@ -91,8 +92,8 @@ def run_browsecomp_evaluation(Run the BrowseComp evaluation using Local Deep Research."""# Ensure output directory exists- os.makedirs(output_dir, exist_ok=True)- output_path = os.path.join(output_dir, output_file)+ Path(output_dir).mkdir(parents=True, exist_ok=True)+ output_path = str(Path(output_dir) / output_file)# Load BrowseComp datasetprint(f"Loading dataset from {dataset_path}")@@ -113,7 +114,7 @@ def run_browsecomp_evaluation(print(f"Sampled {num_examples} examples from {len(df)} total examples")# Remove output file if it exists to avoid appending- if os.path.exists(output_path):+ if Path(output_path).exists():os.remove(output_path)results = []@@ -245,7 +246,7 @@ def run_browsecomp_evaluation("search_tool": search_tool,}- report_path = os.path.join(output_dir, "browsecomp_summary.json")+ report_path = str(Path(output_dir) / "browsecomp_summary.json")with open(report_path, "w") as f:json.dump(report, f, indent=2)diff --git a/examples/benchmarks/claude_grading/benchmark.py b/examples/benchmarks/claude_grading/benchmark.pyindex b037bb2d58..7afecafde0 100755--- a/examples/benchmarks/claude_grading/benchmark.py+++ b/examples/benchmarks/claude_grading/benchmark.py@@ -16,10 +16,11 @@ import osimport sysimport timefrom datetime import datetime, UTC+from pathlib import Path# Set up Python path-src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "src"))+src_dir = str((Path(__file__).parent / "src").resolve())if src_dir not in sys.path:sys.path.insert(0, src_dir)@@ -145,10 +146,8 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):# Create timestamp for outputtimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join(- "benchmark_results", f"claude_grading_{timestamp}"- )- os.makedirs(output_dir, exist_ok=True)+ output_dir = str(Path("benchmark_results") / f"claude_grading_{timestamp}")+ Path(output_dir).mkdir(parents=True, exist_ok=True)config = {"search_strategy": strategy,@@ -175,7 +174,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):simpleqa_results = simpleqa.evaluate(config,num_examples=examples,- output_dir=os.path.join(output_dir, "simpleqa"),+ output_dir=str(Path(output_dir) / "simpleqa"),)simpleqa_duration = time.time() - simpleqa_start@@ -188,7 +187,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):# Save resultsimport json- with open(os.path.join(output_dir, "simpleqa_results.json"), "w") as f:+ with open(Path(output_dir) / "simpleqa_results.json", "w") as f:json.dump(simpleqa_results, f, indent=2)except Exception as e:print(f"Error during SimpleQA evaluation: {e}")@@ -211,7 +210,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):browsecomp_results = browsecomp.evaluate(config,num_examples=examples,- output_dir=os.path.join(output_dir, "browsecomp"),+ output_dir=str(Path(output_dir) / "browsecomp"),)browsecomp_duration = time.time() - browsecomp_start@@ -222,9 +221,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):print(f"BrowseComp metrics: {browsecomp_results.get('metrics', {})}")# Save results- with open(- os.path.join(output_dir, "browsecomp_results.json"), "w"- ) as f:+ with open(Path(output_dir) / "browsecomp_results.json", "w") as f:json.dump(browsecomp_results, f, indent=2)except Exception as e:print(f"Error during BrowseComp evaluation: {e}")@@ -247,7 +244,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):composite_results = composite.evaluate(config,num_examples=examples,- output_dir=os.path.join(output_dir, "composite"),+ output_dir=str(Path(output_dir) / "composite"),)composite_duration = time.time() - composite_start@@ -257,7 +254,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):print(f"Composite score: {composite_results.get('score', 0):.4f}")# Save results- with open(os.path.join(output_dir, "composite_results.json"), "w") as f:+ with open(Path(output_dir) / "composite_results.json", "w") as f:json.dump(composite_results, f, indent=2)except Exception as e:print(f"Error during composite evaluation: {e}")diff --git a/examples/benchmarks/gemini/run_gemini_benchmark_fixed.py b/examples/benchmarks/gemini/run_gemini_benchmark_fixed.pyindex fcaf55612d..77ec27f042 100755--- a/examples/benchmarks/gemini/run_gemini_benchmark_fixed.py+++ b/examples/benchmarks/gemini/run_gemini_benchmark_fixed.py@@ -3,10 +3,10 @@Fixed benchmark with Gemini 2.0 Flash via OpenRouter"""-import osimport sysimport timefrom datetime import datetime, UTC+from pathlib import Path# Import the benchmark functionsfrom local_deep_research.benchmarks.benchmark_functions import (@@ -63,10 +63,12 @@ def run_benchmark(examples=1):try:# Create timestamp for outputtimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join(- "../../benchmark_results", f"gemini_eval_{timestamp}"+ output_dir = str(+ Path(__file__).parent.parent.parent+ / "benchmark_results"+ / f"gemini_eval_{timestamp}")- os.makedirs(output_dir, exist_ok=True)+ Path(output_dir).mkdir(parents=True, exist_ok=True)# Setup the Gemini configurationgemini_config = setup_gemini_config()@@ -82,7 +84,7 @@ def run_benchmark(examples=1):search_tool="searxng",evaluation_model=gemini_config["model_name"],evaluation_provider=gemini_config["provider"],- output_dir=os.path.join(output_dir, "simpleqa"),+ output_dir=str(Path(output_dir) / "simpleqa"),)simpleqa_duration = time.time() - simpleqa_start@@ -110,7 +112,7 @@ def run_benchmark(examples=1):search_tool="searxng",evaluation_model=gemini_config["model_name"],evaluation_provider=gemini_config["provider"],- output_dir=os.path.join(output_dir, "browsecomp"),+ output_dir=str(Path(output_dir) / "browsecomp"),)browsecomp_duration = time.time() - browsecomp_startdiff --git a/examples/benchmarks/run_browsecomp.py b/examples/benchmarks/run_browsecomp.pyindex 463bfc1a8b..2aa48d06a6 100644--- a/examples/benchmarks/run_browsecomp.py+++ b/examples/benchmarks/run_browsecomp.py@@ -21,6 +21,7 @@ import osimport reimport sysimport time+from pathlib import Pathfrom typing import Any, Dictfrom loguru import logger@@ -83,16 +84,16 @@ def run_browsecomp_with_canary(# Set up output filestimestamp = time.strftime("%Y%m%d_%H%M%S")- results_file = os.path.join(- output_dir, f"browsecomp_{timestamp}_results.jsonl"+ results_file = str(+ Path(output_dir) / f"browsecomp_{timestamp}_results.jsonl")- evaluation_file = os.path.join(- output_dir, f"browsecomp_{timestamp}_evaluation.jsonl"+ evaluation_file = str(+ Path(output_dir) / f"browsecomp_{timestamp}_evaluation.jsonl")# Make sure output files don't existfor file in [results_file, evaluation_file]:- if os.path.exists(file):+ if Path(file).exists():os.remove(file)# Process each example@@ -266,7 +267,7 @@ def main():parser.add_argument("--output-dir",type=str,- default=os.path.join("examples", "benchmarks", "results", "browsecomp"),+ default=str(Path("examples") / "benchmarks" / "results" / "browsecomp"),help="Output directory",)diff --git a/examples/benchmarks/run_gemini_benchmark.py b/examples/benchmarks/run_gemini_benchmark.pyindex 010a0d427e..d64e699848 100644--- a/examples/benchmarks/run_gemini_benchmark.py+++ b/examples/benchmarks/run_gemini_benchmark.py@@ -17,6 +17,7 @@ import argparseimport osimport timefrom datetime import datetime+from pathlib import Path# Import the benchmark functionalityfrom local_deep_research.benchmarks.benchmark_functions import (@@ -64,10 +65,10 @@ def run_benchmark(args):from datetime import timezonetimestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")- base_output_dir = os.path.join(- "examples", "benchmarks", "results", f"gemini_{timestamp}"+ base_output_dir = str(+ Path("examples") / "benchmarks" / "results" / f"gemini_{timestamp}")- os.makedirs(base_output_dir, exist_ok=True)+ Path(base_output_dir).mkdir(parents=True, exist_ok=True)# Configure benchmark settingsresults = {}@@ -78,7 +79,7 @@ def run_benchmark(args):{"name": "SimpleQA","function": evaluate_simpleqa,- "output_dir": os.path.join(base_output_dir, "simpleqa"),+ "output_dir": str(Path(base_output_dir) / "simpleqa"),})@@ -87,7 +88,7 @@ def run_benchmark(args):{"name": "BrowseComp","function": evaluate_browsecomp,- "output_dir": os.path.join(base_output_dir, "browsecomp"),+ "output_dir": str(Path(base_output_dir) / "browsecomp"),})diff --git a/examples/benchmarks/run_resumable_parallel_benchmark.py b/examples/benchmarks/run_resumable_parallel_benchmark.pyindex f63f0648a4..963bbbf8d6 100644--- a/examples/benchmarks/run_resumable_parallel_benchmark.py+++ b/examples/benchmarks/run_resumable_parallel_benchmark.py@@ -39,9 +39,7 @@ from local_deep_research.benchmarks.metrics import (from local_deep_research.benchmarks.runners import format_query# Add the src directory to the Python path-project_root = os.path.abspath(- os.path.dirname(os.path.dirname(os.path.dirname(__file__)))-)+project_root = str(Path(__file__).parent.parent.parent.resolve())logger.enable("local_deep_research")@@ -49,7 +47,7 @@ logger.enable("local_deep_research")def load_existing_results(results_file: str) -> Dict[str, Dict]:"""Load existing results from JSONL file."""results = {}- if os.path.exists(results_file):+ if Path(results_file).exists():logger.info(f"Loading existing results from: {results_file}")with open(results_file, "r") as f:for line in f:@@ -73,8 +71,8 @@ def find_latest_results_file() -> Optional[str]:"""Find the most recent results file for a dataset."""# First try dataset subdirectory- dataset_dir = os.path.join(output_dir, dataset_type)- if os.path.exists(dataset_dir):+ dataset_dir = str(Path(output_dir) / dataset_type)+ if Path(dataset_dir).exists():pattern = f"{dataset_type}_*_results.jsonl"files = list(Path(dataset_dir).glob(pattern))if files:@@ -112,14 +110,14 @@ def run_resumable_benchmark(# Determine output filestimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- results_file = os.path.join(- output_dir, f"{dataset_type}_{timestamp}_results.jsonl"+ results_file = str(+ Path(output_dir) / f"{dataset_type}_{timestamp}_results.jsonl")- evaluation_file = os.path.join(- output_dir, f"{dataset_type}_{timestamp}_evaluation.jsonl"+ evaluation_file = str(+ Path(output_dir) / f"{dataset_type}_{timestamp}_evaluation.jsonl")- report_file = os.path.join(- output_dir, f"{dataset_type}_{timestamp}_report.md"+ report_file = str(+ Path(output_dir) / f"{dataset_type}_{timestamp}_report.md")# Load existing results if resuming@@ -297,7 +295,7 @@ def run_simpleqa_benchmark_wrapper(args: Tuple) -> Dict[str, Any]:results = run_resumable_benchmark(dataset_type="simpleqa",num_examples=num_examples,- output_dir=os.path.join(output_dir, "simpleqa"),+ output_dir=str(Path(output_dir) / "simpleqa"),search_config=search_config,evaluation_config=evaluation_config,resume_from=resume_from,@@ -324,7 +322,7 @@ def run_browsecomp_benchmark_wrapper(args: Tuple) -> Dict[str, Any]:results = run_resumable_benchmark(dataset_type="browsecomp",num_examples=num_examples,- output_dir=os.path.join(output_dir, "browsecomp"),+ output_dir=str(Path(output_dir) / "browsecomp"),search_config=browsecomp_config,evaluation_config=evaluation_config,resume_from=resume_from,@@ -411,18 +409,22 @@ def main():if args.resume_from:# Create new directory but link to old resultstimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join(- project_root, "benchmark_results", f"resumed_benchmark_{timestamp}"+ output_dir = str(+ Path(project_root)+ / "benchmark_results"+ / f"resumed_benchmark_{timestamp}")- os.makedirs(output_dir, exist_ok=True)+ Path(output_dir).mkdir(parents=True, exist_ok=True)logger.info(f"Resuming from {args.resume_from}, new results in {output_dir}")else:# Create new timestamp directorytimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join(- project_root, "benchmark_results", f"parallel_benchmark_{timestamp}"+ output_dir = str(+ Path(project_root)+ / "benchmark_results"+ / f"parallel_benchmark_{timestamp}")os.makedirs(output_dir, exist_ok=True)logger.info(f"Starting new benchmark in: {output_dir}")@@ -565,7 +567,7 @@ def main():}with open(- os.path.join(output_dir, "parallel_benchmark_summary.json"), "w"+ Path(output_dir) / "parallel_benchmark_summary.json", "w") as f:json.dump(summary, f, indent=2)diff --git a/examples/benchmarks/run_simpleqa.py b/examples/benchmarks/run_simpleqa.pyindex 187c34f01f..4b95a15bc0 100644--- a/examples/benchmarks/run_simpleqa.py+++ b/examples/benchmarks/run_simpleqa.py@@ -14,8 +14,8 @@ Usage:"""import argparse-import osimport sys+from pathlib import Path# Import the benchmark functionalityfrom local_deep_research.benchmarks.benchmark_functions import evaluate_simpleqa@@ -39,7 +39,7 @@ def main():parser.add_argument("--output-dir",type=str,- default=os.path.join("examples", "benchmarks", "results", "simpleqa"),+ default=str(Path("examples") / "benchmarks" / "results" / "simpleqa"),help="Output directory",)parser.add_argument(diff --git a/examples/benchmarks/scripts/run_benchmark_with_claude_grading.py b/examples/benchmarks/scripts/run_benchmark_with_claude_grading.pyindex f7e90904e3..0b2408166e 100755--- a/examples/benchmarks/scripts/run_benchmark_with_claude_grading.py+++ b/examples/benchmarks/scripts/run_benchmark_with_claude_grading.py@@ -16,10 +16,11 @@ import osimport sysimport timefrom datetime import datetime, UTC+from pathlib import Path# Set up Python path-src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "src"))+src_dir = str((Path(__file__).parent / "src").resolve())if src_dir not in sys.path:sys.path.insert(0, src_dir)@@ -144,10 +145,8 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):# Create timestamp for outputtimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join(- "benchmark_results", f"claude_grading_{timestamp}"- )- os.makedirs(output_dir, exist_ok=True)+ output_dir = str(Path("benchmark_results") / f"claude_grading_{timestamp}")+ Path(output_dir).mkdir(parents=True, exist_ok=True)config = {"search_strategy": strategy,@@ -174,7 +173,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):simpleqa_results = simpleqa.evaluate(config,num_examples=examples,- output_dir=os.path.join(output_dir, "simpleqa"),+ output_dir=str(Path(output_dir) / "simpleqa"),)simpleqa_duration = time.time() - simpleqa_start@@ -187,7 +186,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):# Save resultsimport json- with open(os.path.join(output_dir, "simpleqa_results.json"), "w") as f:+ with open(Path(output_dir) / "simpleqa_results.json", "w") as f:json.dump(simpleqa_results, f, indent=2)except Exception as e:print(f"Error during SimpleQA evaluation: {e}")@@ -210,7 +209,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):browsecomp_results = browsecomp.evaluate(config,num_examples=examples,- output_dir=os.path.join(output_dir, "browsecomp"),+ output_dir=str(Path(output_dir) / "browsecomp"),)browsecomp_duration = time.time() - browsecomp_start@@ -221,9 +220,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):print(f"BrowseComp metrics: {browsecomp_results.get('metrics', {})}")# Save results- with open(- os.path.join(output_dir, "browsecomp_results.json"), "w"- ) as f:+ with open(Path(output_dir) / "browsecomp_results.json", "w") as f:json.dump(browsecomp_results, f, indent=2)except Exception as e:print(f"Error during BrowseComp evaluation: {e}")@@ -246,7 +243,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):composite_results = composite.evaluate(config,num_examples=examples,- output_dir=os.path.join(output_dir, "composite"),+ output_dir=str(Path(output_dir) / "composite"),)composite_duration = time.time() - composite_start@@ -256,7 +253,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):print(f"Composite score: {composite_results.get('score', 0):.4f}")# Save results- with open(os.path.join(output_dir, "composite_results.json"), "w") as f:+ with open(Path(output_dir) / "composite_results.json", "w") as f:json.dump(composite_results, f, indent=2)except Exception as e:print(f"Error during composite evaluation: {e}")diff --git a/examples/benchmarks/scripts/run_focused_benchmark_fixed.py b/examples/benchmarks/scripts/run_focused_benchmark_fixed.pyindex 0b3bfe48dc..2c9fca8c8a 100755--- a/examples/benchmarks/scripts/run_focused_benchmark_fixed.py+++ b/examples/benchmarks/scripts/run_focused_benchmark_fixed.py@@ -13,10 +13,11 @@ import osimport sysimport timefrom datetime import datetime, UTC+from pathlib import Path# Set up Python path-src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "src"))+src_dir = str((Path(__file__).parent / "src").resolve())if src_dir not in sys.path:sys.path.insert(0, src_dir)@@ -25,7 +26,7 @@ if src_dir not in sys.path:# - ANTHROPIC_API_KEY for Anthropic API access# - OPENROUTER_API_KEY for OpenRouter API access (if used)# - LDR_DATA_DIR for data directory location (if needed)-data_dir = os.environ.get("LDR_DATA_DIR", os.path.join(src_dir, "data"))+data_dir = os.environ.get("LDR_DATA_DIR", str(Path(src_dir) / "data"))def setup_grading_config():@@ -139,8 +140,8 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):# Create timestamp for outputtimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join("benchmark_results", f"direct_eval_{timestamp}")- os.makedirs(output_dir, exist_ok=True)+ output_dir = str(Path("benchmark_results") / f"direct_eval_{timestamp}")+ Path(output_dir).mkdir(parents=True, exist_ok=True)config = {"search_strategy": strategy,@@ -167,7 +168,7 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):simpleqa_results = simpleqa.evaluate(config,num_examples=examples,- output_dir=os.path.join(output_dir, "simpleqa"),+ output_dir=str(Path(output_dir) / "simpleqa"),)simpleqa_duration = time.time() - simpleqa_start@@ -180,7 +181,7 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):# Save resultsimport json- with open(os.path.join(output_dir, "simpleqa_results.json"), "w") as f:+ with open(Path(output_dir) / "simpleqa_results.json", "w") as f:json.dump(simpleqa_results, f, indent=2)except Exception as e:print(f"Error during SimpleQA evaluation: {e}")@@ -203,7 +204,7 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):browsecomp_results = browsecomp.evaluate(config,num_examples=examples,- output_dir=os.path.join(output_dir, "browsecomp"),+ output_dir=str(Path(output_dir) / "browsecomp"),)browsecomp_duration = time.time() - browsecomp_start@@ -214,9 +215,7 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):print(f"BrowseComp metrics: {browsecomp_results.get('metrics', {})}")# Save results- with open(- os.path.join(output_dir, "browsecomp_results.json"), "w"- ) as f:+ with open(Path(output_dir) / "browsecomp_results.json", "w") as f:json.dump(browsecomp_results, f, indent=2)except Exception as e:print(f"Error during BrowseComp evaluation: {e}")@@ -239,7 +238,7 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):composite_results = composite.evaluate(config,num_examples=examples,- output_dir=os.path.join(output_dir, "composite"),+ output_dir=str(Path(output_dir) / "composite"),)composite_duration = time.time() - composite_start@@ -249,7 +248,7 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):print(f"Composite score: {composite_results.get('score', 0):.4f}")# Save results- with open(os.path.join(output_dir, "composite_results.json"), "w") as f:+ with open(Path(output_dir) / "composite_results.json", "w") as f:json.dump(composite_results, f, indent=2)except Exception as e:print(f"Error during composite evaluation: {e}")diff --git a/examples/benchmarks/scripts/run_grader_only.py b/examples/benchmarks/scripts/run_grader_only.pyindex e5eb7842f1..0ce7455354 100644--- a/examples/benchmarks/scripts/run_grader_only.py+++ b/examples/benchmarks/scripts/run_grader_only.py@@ -10,10 +10,11 @@ import argparseimport osimport sysimport time+from pathlib import Path# Set up Python path-src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "src"))+src_dir = str((Path(__file__).parent / "src").resolve())if src_dir not in sys.path:sys.path.insert(0, src_dir)@@ -22,7 +23,7 @@ if src_dir not in sys.path:# - ANTHROPIC_API_KEY for Anthropic API access# - OPENROUTER_API_KEY for OpenRouter API access (if used)# - LDR_DATA_DIR for data directory location (if needed)-data_dir = os.environ.get("LDR_DATA_DIR", os.path.join(src_dir, "data"))+data_dir = os.environ.get("LDR_DATA_DIR", str(Path(src_dir) / "data"))def setup_grading_config():@@ -125,12 +126,12 @@ def grade_benchmark_results(results_path, dataset_type="simpleqa"):traceback.print_exc()# Create the evaluation output path- results_dir = os.path.dirname(results_path)- results_filename = os.path.basename(results_path)+ results_dir = str(Path(results_path).parent)+ results_filename = Path(results_path).nameevaluation_filename = results_filename.replace("_results.jsonl", "_evaluation.jsonl")- evaluation_path = os.path.join(results_dir, evaluation_filename)+ evaluation_path = str(Path(results_dir) / evaluation_filename)# Run the gradingprint("Starting grading of benchmark results...")@@ -210,10 +211,10 @@ def generate_summary(evaluation_path, output_dir=None):# Determine output directoryif output_dir is None:- output_dir = os.path.dirname(evaluation_path)+ output_dir = str(Path(evaluation_path).parent)# Generate report- report_path = os.path.join(output_dir, "evaluation_report.md")+ report_path = str(Path(output_dir) / "evaluation_report.md")generate_report(metrics=metrics,output_file=report_path,@@ -269,7 +270,7 @@ def main():args = parser.parse_args()# Check if the results file exists- if not os.path.exists(args.results):+ if not Path(args.results).exists():print(f"Error: Results file not found: {args.results}")return 1diff --git a/examples/optimization/browsecomp_optimization.py b/examples/optimization/browsecomp_optimization.pyindex 61312dfe88..4ded57581e 100755--- a/examples/optimization/browsecomp_optimization.py+++ b/examples/optimization/browsecomp_optimization.py@@ -15,18 +15,16 @@ Usage:"""import json-import osimport sysfrom datetime import datetime+from pathlib import Pathfrom local_deep_research.benchmarks.optimization import optimize_parameters# Add the src directory to the Python path-project_root = os.path.abspath(- os.path.dirname(os.path.dirname(os.path.dirname(__file__)))-)-sys.path.insert(0, os.path.join(project_root, "src"))+project_root = str(Path(__file__).parent.parent.parent.resolve())+sys.path.insert(0, str(Path(project_root) / "src"))def main():@@ -34,10 +32,13 @@ def main():from datetime import timezonetimestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join(- "examples", "optimization", "results", f"browsecomp_opt_{timestamp}"+ output_dir = str(+ Path("examples")+ / "optimization"+ / "results"+ / f"browsecomp_opt_{timestamp}")- os.makedirs(output_dir, exist_ok=True)+ Path(output_dir).mkdir(parents=True, exist_ok=True)print(f"Starting BrowseComp optimization - results will be saved to {output_dir}"@@ -91,7 +92,7 @@ def main():}with open(- os.path.join(output_dir, "browsecomp_optimization_summary.json"), "w"+ Path(output_dir) / "browsecomp_optimization_summary.json", "w") as f:json.dump(summary, f, indent=2)diff --git a/examples/optimization/example_multi_benchmark.py b/examples/optimization/example_multi_benchmark.pyindex 1ecbb5fa0c..60da992936 100644--- a/examples/optimization/example_multi_benchmark.py+++ b/examples/optimization/example_multi_benchmark.py@@ -8,6 +8,7 @@ SimpleQA and BrowseComp benchmarks with custom weights.import osimport sysfrom datetime import datetime+from pathlib import Pathfrom typing import Any, Dict@@ -16,9 +17,7 @@ print(f"Current directory: {os.getcwd()}")print(f"Python path: {sys.path}")# Add appropriate paths-sys.path.insert(- 0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))-)+sys.path.insert(0, str(Path(__file__).parent.parent.resolve()))try:# Try to import from the local module structure@@ -141,7 +140,7 @@ def main():params1, score1 = optimize_parameters(query=query,n_trials=3, # Using a small number for quick demonstration- output_dir=os.path.join(output_dir, "simpleqa_only"),+ output_dir=str(Path(output_dir) / "simpleqa_only"),)print_optimization_results(params1, score1)@@ -150,7 +149,7 @@ def main():params2, score2 = optimize_parameters(query=query,n_trials=3, # Using a small number for quick demonstration- output_dir=os.path.join(output_dir, "browsecomp_only"),+ output_dir=str(Path(output_dir) / "browsecomp_only"),benchmark_weights={"browsecomp": 1.0},)print_optimization_results(params2, score2)@@ -160,7 +159,7 @@ def main():params3, score3 = optimize_parameters(query=query,n_trials=5, # Using a small number for quick demonstration- output_dir=os.path.join(output_dir, "weighted_combination"),+ output_dir=str(Path(output_dir) / "weighted_combination"),benchmark_weights={"simpleqa": 0.6, # 60% weight for SimpleQA"browsecomp": 0.4, # 40% weight for BrowseComp@@ -173,7 +172,7 @@ def main():params4, score4 = optimize_for_quality(query=query,n_trials=3,- output_dir=os.path.join(output_dir, "quality_focused"),+ output_dir=str(Path(output_dir) / "quality_focused"),benchmark_weights={"simpleqa": 0.6, "browsecomp": 0.4},)print_optimization_results(params4, score4)@@ -183,7 +182,7 @@ def main():params5, score5 = optimize_for_speed(query=query,n_trials=3,- output_dir=os.path.join(output_dir, "speed_focused"),+ output_dir=str(Path(output_dir) / "speed_focused"),benchmark_weights={"simpleqa": 0.5, "browsecomp": 0.5},)print_optimization_results(params5, score5)diff --git a/examples/optimization/example_optimization.py b/examples/optimization/example_optimization.pyindex 5e1bb125cf..de6781e1cf 100644--- a/examples/optimization/example_optimization.py+++ b/examples/optimization/example_optimization.py@@ -14,8 +14,8 @@ Usage:"""import json-import osfrom datetime import datetime, UTC+from pathlib import Path# Import the optimization functionality@@ -29,13 +29,13 @@ from local_deep_research.benchmarks.optimization import (def main():# Create timestamp for unique output directorytimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join(- "examples",- "optimization",- "results",- f"optimization_results_{timestamp}",+ output_dir = str(+ Path("examples")+ / "optimization"+ / "results"+ / f"optimization_results_{timestamp}")- os.makedirs(output_dir, exist_ok=True)+ Path(output_dir).mkdir(parents=True, exist_ok=True)print(f"Starting quick optimization demo - results will be saved to {output_dir}"@@ -68,7 +68,7 @@ def main():query="SimpleQA quick demo", # Task descriptorsearch_tool="searxng", # Using SearXNGn_trials=2, # Just 2 trials for quick demo- output_dir=os.path.join(output_dir, "demo"),+ output_dir=str(Path(output_dir) / "demo"),param_space=param_space, # Limited parameter spacemetric_weights={"quality": 0.5, "speed": 0.5},)@@ -82,7 +82,7 @@ def main():"demo": {"parameters": balanced_params, "score": balanced_score},}- with open(os.path.join(output_dir, "optimization_summary.json"), "w") as f:+ with open(Path(output_dir) / "optimization_summary.json", "w") as f:json.dump(summary, f, indent=2)print(f"\nDemo complete! Results saved to {output_dir}")diff --git a/examples/optimization/example_quick_optimization.py b/examples/optimization/example_quick_optimization.pyindex 5bfabdfc83..a80cb6d905 100644--- a/examples/optimization/example_quick_optimization.py+++ b/examples/optimization/example_quick_optimization.py@@ -14,10 +14,10 @@ Usage:"""import json-import osimport randomimport timefrom datetime import datetime, UTC+from pathlib import Pathfrom typing import Any, Dict, Tuplefrom loguru import logger@@ -188,10 +188,13 @@ def optimize_for_quality(def main():# Create timestamp for unique output directorytimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join(- "examples", "optimization", "results", f"optimization_demo_{timestamp}"+ output_dir = str(+ Path("examples")+ / "optimization"+ / "results"+ / f"optimization_demo_{timestamp}")- os.makedirs(output_dir, exist_ok=True)+ Path(output_dir).mkdir(parents=True, exist_ok=True)print(f"Starting quick optimization demo - results will be saved to {output_dir}"@@ -254,7 +257,7 @@ def main():},}- with open(os.path.join(output_dir, "optimization_summary.json"), "w") as f:+ with open(Path(output_dir) / "optimization_summary.json", "w") as f:json.dump(summary, f, indent=2)print(diff --git a/examples/optimization/gemini_optimization.py b/examples/optimization/gemini_optimization.pyindex e513d509a4..3d85ffb5b8 100644--- a/examples/optimization/gemini_optimization.py+++ b/examples/optimization/gemini_optimization.py@@ -22,6 +22,7 @@ import jsonimport osimport sysfrom datetime import datetime, timezone+from pathlib import Pathfrom loguru import logger@@ -99,10 +100,13 @@ def main():if args.output_dir:output_dir = args.output_direlse:- output_dir = os.path.join(- "examples", "optimization", "results", f"gemini_opt_{timestamp}"+ output_dir = str(+ Path("examples")+ / "optimization"+ / "results"+ / f"gemini_opt_{timestamp}")- os.makedirs(output_dir, exist_ok=True)+ Path(output_dir).mkdir(parents=True, exist_ok=True)print(f"Starting optimization with Gemini 2.0 Flash - results will be saved to {output_dir}"@@ -191,7 +195,7 @@ def main():}with open(- os.path.join(output_dir, "gemini_optimization_summary.json"), "w"+ Path(output_dir) / "gemini_optimization_summary.json", "w") as f:json.dump(summary, f, indent=2)diff --git a/examples/optimization/llm_multi_benchmark.py b/examples/optimization/llm_multi_benchmark.pyindex 444f4ad846..8cdcc5c35d 100644--- a/examples/optimization/llm_multi_benchmark.py+++ b/examples/optimization/llm_multi_benchmark.py@@ -14,6 +14,7 @@ import argparseimport osimport sysfrom datetime import datetime, UTC+from pathlib import Pathfrom typing import Any, Dict, Optionalfrom loguru import logger@@ -116,11 +117,11 @@ def main():if args.output_dir:output_dir = args.output_direlse:- output_dir = os.path.join(- "examples",- "optimization",- "results",- f"llm_multi_benchmark_{timestamp}",+ output_dir = str(+ Path("examples")+ / "optimization"+ / "results"+ / f"llm_multi_benchmark_{timestamp}")os.makedirs(output_dir, exist_ok=True)@@ -215,9 +216,7 @@ def main():# Save results to fileimport json- with open(- os.path.join(output_dir, "multi_benchmark_results.json"), "w"- ) as f:+ with open(Path(output_dir) / "multi_benchmark_results.json", "w") as f:json.dump({"timestamp": timestamp,@@ -235,7 +234,7 @@ def main():)print(- f"Results saved to {os.path.join(output_dir, 'multi_benchmark_results.json')}"+ f"Results saved to {Path(output_dir) / 'multi_benchmark_results.json'}")except Exception:diff --git a/examples/optimization/multi_benchmark_simulation.py b/examples/optimization/multi_benchmark_simulation.pyindex 83233fe079..d692f95bfb 100644--- a/examples/optimization/multi_benchmark_simulation.py+++ b/examples/optimization/multi_benchmark_simulation.py@@ -6,10 +6,10 @@ without actually running real benchmarks (just simulation)."""import json-import osimport randomimport timefrom datetime import datetime, UTC+from pathlib import Pathfrom typing import Any, Dict, Optional, Tuplefrom loguru import logger@@ -336,7 +336,7 @@ def main():# Create a timestamp-based directory for resultstimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")output_dir = "optimization_sim_" + timestamp- os.makedirs(output_dir, exist_ok=True)+ Path(output_dir).mkdir(parents=True, exist_ok=True)print("\n🔬 Multi-Benchmark Optimization Simulation 🔬")print(f"Results will be saved to: {output_dir}")@@ -387,7 +387,7 @@ def main():},}- results_file = os.path.join(output_dir, "multi_benchmark_results.json")+ results_file = str(Path(output_dir) / "multi_benchmark_results.json")with open(results_file, "w") as f:# Convert all values to serializable typesjson.dump(diff --git a/examples/optimization/multi_benchmark_speed_demo.py b/examples/optimization/multi_benchmark_speed_demo.pyindex e1c2085175..9d487b30e5 100644--- a/examples/optimization/multi_benchmark_speed_demo.py+++ b/examples/optimization/multi_benchmark_speed_demo.py@@ -13,12 +13,12 @@ Usage:python ../examples/optimization/multi_benchmark_speed_demo.py"""-import osimport sys+from pathlib import Pathfrom typing import Any, Dict# Add src directory to Python path-src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../src"))+src_dir = str((Path(__file__).parent.parent / "src").resolve())if src_dir not in sys.path:sys.path.insert(0, src_dir)diff --git a/examples/optimization/run_gemini_benchmark.py b/examples/optimization/run_gemini_benchmark.pyindex f7ae27caf6..2024058c9f 100755--- a/examples/optimization/run_gemini_benchmark.py+++ b/examples/optimization/run_gemini_benchmark.py@@ -15,19 +15,17 @@ Usage:"""import argparse-import osimport sysimport timefrom datetime import datetime, UTC+from pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom loguru import logger# Add the src directory to the Python path-project_root = os.path.abspath(- os.path.dirname(os.path.dirname(os.path.dirname(__file__)))-)-sys.path.insert(0, os.path.join(project_root, "src"))+project_root = str(Path(__file__).parent.parent.parent.resolve())+sys.path.insert(0, str(Path(project_root) / "src"))# Loguru automatically handles logging configuration@@ -115,11 +113,13 @@ def run_benchmarks(# Create timestamp for outputtimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")if not output_dir:- output_dir = os.path.join(- project_root, "benchmark_results", f"gemini_eval_{timestamp}"+ output_dir = str(+ Path(project_root)+ / "benchmark_results"+ / f"gemini_eval_{timestamp}")- os.makedirs(output_dir, exist_ok=True)+ Path(output_dir).mkdir(parents=True, exist_ok=True)# Set benchmark listif not benchmarks:@@ -144,7 +144,7 @@ def run_benchmarks(search_model=gemini_config["model_name"],search_provider=gemini_config["provider"],endpoint_url=gemini_config["endpoint_url"],- output_dir=os.path.join(output_dir, "simpleqa"),+ output_dir=str(Path(output_dir) / "simpleqa"),)elif benchmark.lower() == "browsecomp":logger.info(@@ -158,7 +158,7 @@ def run_benchmarks(search_model=gemini_config["model_name"],search_provider=gemini_config["provider"],endpoint_url=gemini_config["endpoint_url"],- output_dir=os.path.join(output_dir, "browsecomp"),+ output_dir=str(Path(output_dir) / "browsecomp"),)else:logger.warning(f"Unknown benchmark: {benchmark}")@@ -213,7 +213,7 @@ def run_benchmarks(logger.info("=" * 50)# Save summary to a file- summary_file = os.path.join(output_dir, "benchmark_summary.json")+ summary_file = str(Path(output_dir) / "benchmark_summary.json")try:import jsondiff --git a/examples/optimization/run_multi_benchmark.py b/examples/optimization/run_multi_benchmark.pyindex dba6c5e4d3..f0c417f4d6 100755--- a/examples/optimization/run_multi_benchmark.py+++ b/examples/optimization/run_multi_benchmark.py@@ -16,12 +16,13 @@ Usage:import osimport sysfrom datetime import datetime, UTC+from pathlib import Pathfrom typing import Any, Dictfrom loguru import logger# Add src directory to Python path-src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../src"))+src_dir = str((Path(__file__).parent.parent / "src").resolve())if src_dir not in sys.path:sys.path.insert(0, src_dir)@@ -30,7 +31,7 @@ if src_dir not in sys.path:# - ANTHROPIC_API_KEY for Anthropic API access# - OPENROUTER_API_KEY for OpenRouter API access (if used)# - LDR_DATA_DIR for data directory location (if needed)-data_dir = os.environ.get("LDR_DATA_DIR", os.path.join(src_dir, "data"))+data_dir = os.environ.get("LDR_DATA_DIR", str(Path(src_dir) / "data"))# Import benchmark optimization functionstry:@@ -63,13 +64,15 @@ def main():timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")# Put results in the data directory for easier access- if os.path.isdir(data_dir):- output_dir = os.path.join(- data_dir, "optimization_results", "multi_benchmark_" + timestamp+ if Path(data_dir).is_dir():+ output_dir = str(+ Path(data_dir)+ / "optimization_results"+ / f"multi_benchmark_{timestamp}")else:- output_dir = os.path.join(- "optimization_results", "multi_benchmark_" + timestamp+ output_dir = str(+ Path("optimization_results") / f"multi_benchmark_{timestamp}")os.makedirs(output_dir, exist_ok=True)@@ -146,7 +149,7 @@ def main():quality_results = evaluator.evaluate(system_config=mini_system_config,num_examples=1, # Use just 1 example for speed- output_dir=os.path.join(output_dir, "simpleqa_test"),+ output_dir=str(Path(output_dir) / "simpleqa_test"),)print("Benchmark evaluation complete!")@@ -165,7 +168,7 @@ def main():params1, score1 = optimize_parameters(query=query,param_space=tiny_param_space, # Use tiny param space- output_dir=os.path.join(output_dir, "simpleqa_only"),+ output_dir=str(Path(output_dir) / "simpleqa_only"),n_trials=1, # Just one trial for testingbenchmark_weights={"simpleqa": 1.0}, # SimpleQA onlytimeout=5, # Limit to 5 seconds@@ -185,7 +188,7 @@ def main():bc_results = browsecomp_evaluator.evaluate(system_config=mini_system_config,num_examples=1, # Just 1 example for speed- output_dir=os.path.join(output_dir, "browsecomp_test"),+ output_dir=str(Path(output_dir) / "browsecomp_test"),)print("BrowseComp evaluation complete!")@@ -216,7 +219,7 @@ def main():combo_results = composite_evaluator.evaluate(system_config=mini_system_config,num_examples=1, # Just 1 example for speed- output_dir=os.path.join(output_dir, "combined_test"),+ output_dir=str(Path(output_dir) / "combined_test"),)print("Combined benchmark evaluation complete!")@@ -246,7 +249,7 @@ def main():# Very minimal run with just 1 trial for demonstrationparams_speed, score_speed = optimize_for_speed(query=query,- output_dir=os.path.join(output_dir, "speed_optimization"),+ output_dir=str(Path(output_dir) / "speed_optimization"),n_trials=1, # Just one trial for testingbenchmark_weights={"simpleqa": 0.6, "browsecomp": 0.4},timeout=5, # Limit to 5 seconds@@ -274,7 +277,7 @@ def main():# Very minimal run with just 1 trial for demonstrationparams_efficiency, score_efficiency = optimize_for_efficiency(query=query,- output_dir=os.path.join(output_dir, "efficiency_optimization"),+ output_dir=str(Path(output_dir) / "efficiency_optimization"),n_trials=1, # Just one trial for testingbenchmark_weights={"simpleqa": 0.6, "browsecomp": 0.4},timeout=5, # Limit to 5 secondsdiff --git a/examples/optimization/run_optimization.py b/examples/optimization/run_optimization.pyindex 9367284a6d..c7dd87a001 100644--- a/examples/optimization/run_optimization.py+++ b/examples/optimization/run_optimization.py@@ -18,6 +18,7 @@ import jsonimport osimport sysfrom datetime import datetime, UTC+from pathlib import Path# Import the optimization functionalityfrom local_deep_research.benchmarks.optimization import (@@ -36,7 +37,7 @@ def main():parser.add_argument("query", help="Research query to optimize for")parser.add_argument("--output-dir",- default=os.path.join("examples", "optimization", "results"),+ default=str(Path("examples") / "optimization" / "results"),help="Directory to save results",)parser.add_argument(@@ -85,7 +86,7 @@ def main():# Create timestamp for unique output directorytimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join(args.output_dir, f"opt_{timestamp}")+ output_dir = str(Path(args.output_dir) / f"opt_{timestamp}")os.makedirs(output_dir, exist_ok=True)print(@@ -185,7 +186,7 @@ def main():"custom_weights": custom_weights,}- with open(os.path.join(output_dir, "optimization_summary.json"), "w") as f:+ with open(Path(output_dir) / "optimization_summary.json", "w") as f:json.dump(summary, f, indent=2)return 0diff --git a/examples/optimization/run_parallel_benchmark.py b/examples/optimization/run_parallel_benchmark.pyindex 66ebe39de3..df7e903e3f 100755--- a/examples/optimization/run_parallel_benchmark.py+++ b/examples/optimization/run_parallel_benchmark.py@@ -19,14 +19,13 @@ import osimport sysimport timefrom datetime import datetime, UTC+from pathlib import Pathfrom loguru import logger# Add the src directory to the Python path-project_root = os.path.abspath(- os.path.dirname(os.path.dirname(os.path.dirname(__file__)))-)-sys.path.insert(0, os.path.join(project_root, "src"))+project_root = str(Path(__file__).parent.parent.parent.resolve())+sys.path.insert(0, str(Path(project_root) / "src"))def run_simpleqa_benchmark(@@ -55,7 +54,7 @@ def run_simpleqa_benchmark(search_model=model,search_provider=provider,endpoint_url=endpoint_url,- output_dir=os.path.join(output_dir, "simpleqa"),+ output_dir=str(Path(output_dir) / "simpleqa"),evaluation_provider="ANTHROPIC",evaluation_model="claude-3-7-sonnet-20250219",)@@ -95,7 +94,7 @@ def run_browsecomp_benchmark(search_model=model,search_provider=provider,endpoint_url=endpoint_url,- output_dir=os.path.join(output_dir, "browsecomp"),+ output_dir=str(Path(output_dir) / "browsecomp"),evaluation_provider="ANTHROPIC",evaluation_model="claude-3-7-sonnet-20250219",)@@ -171,10 +170,12 @@ def main():# Create timestamp for unique output directorytimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- output_dir = os.path.join(- project_root, "benchmark_results", f"parallel_benchmark_{timestamp}"+ output_dir = str(+ Path(project_root)+ / "benchmark_results"+ / f"parallel_benchmark_{timestamp}")- os.makedirs(output_dir, exist_ok=True)+ Path(output_dir).mkdir(parents=True, exist_ok=True)# Display start informationprint(f"Starting parallel benchmarks with {args.examples} examples each")@@ -283,7 +284,7 @@ def main():}with open(- os.path.join(output_dir, "parallel_benchmark_summary.json"), "w"+ Path(output_dir) / "parallel_benchmark_summary.json", "w") as f:json.dump(summary, f, indent=2)diff --git a/examples/optimization/strategy_benchmark_plan.py b/examples/optimization/strategy_benchmark_plan.pyindex c47a0648cb..83cbf148a6 100755--- a/examples/optimization/strategy_benchmark_plan.py+++ b/examples/optimization/strategy_benchmark_plan.py@@ -15,6 +15,7 @@ import randomimport sysimport timefrom datetime import datetime, UTC+from pathlib import Pathfrom typing import Any, Dict, Tuplefrom loguru import logger@@ -23,10 +24,8 @@ from loguru import logger# flake8: noqa: E402# Add the src directory to the Python path before local imports-project_root = os.path.abspath(- os.path.dirname(os.path.dirname(os.path.dirname(__file__)))-)-sys.path.insert(0, os.path.join(project_root, "src"))+project_root = str(Path(__file__).parent.parent.parent.resolve())+sys.path.insert(0, str(Path(project_root) / "src"))# Now we can import from the local projectfrom local_deep_research.benchmarks.optimization.optuna_optimizer import (@@ -128,8 +127,8 @@ def run_strategy_comparison():# ====== EXPERIMENT 1: Quality-focused optimization ======logger.info("Starting quality-focused benchmark with 500 examples")- quality_output_dir = os.path.join(base_output_dir, "quality_focused")- os.makedirs(quality_output_dir, exist_ok=True)+ quality_output_dir = str(Path(base_output_dir) / "quality_focused")+ Path(quality_output_dir).mkdir(parents=True, exist_ok=True)# Create optimizer for qualityquality_optimizer = OptunaOptimizer(@@ -165,13 +164,13 @@ def run_strategy_comparison():logger.info(f"Best quality score: {best_quality_score}")logger.info(f"Duration: {quality_end - quality_start} seconds")- with open(os.path.join(quality_output_dir, "results.json"), "w") as f:+ with open(Path(quality_output_dir) / "results.json", "w") as f:json.dump(quality_result, f, indent=2)# ====== EXPERIMENT 2: Speed-focused optimization ======logger.info("Starting speed-focused benchmark with 500 examples")- speed_output_dir = os.path.join(base_output_dir, "speed_focused")- os.makedirs(speed_output_dir, exist_ok=True)+ speed_output_dir = str(Path(base_output_dir) / "speed_focused")+ Path(speed_output_dir).mkdir(parents=True, exist_ok=True)# Create optimizer for speedspeed_optimizer = OptunaOptimizer(@@ -207,13 +206,13 @@ def run_strategy_comparison():logger.info(f"Best speed score: {best_speed_score}")logger.info(f"Duration: {speed_end - speed_start} seconds")- with open(os.path.join(speed_output_dir, "results.json"), "w") as f:+ with open(Path(speed_output_dir) / "results.json", "w") as f:json.dump(speed_result, f, indent=2)# ====== EXPERIMENT 3: Balanced optimization ======logger.info("Starting balanced benchmark with 500 examples")- balanced_output_dir = os.path.join(base_output_dir, "balanced")- os.makedirs(balanced_output_dir, exist_ok=True)+ balanced_output_dir = str(Path(base_output_dir) / "balanced")+ Path(balanced_output_dir).mkdir(parents=True, exist_ok=True)# Create optimizer for balanced approachbalanced_optimizer = OptunaOptimizer(@@ -249,13 +248,13 @@ def run_strategy_comparison():logger.info(f"Best balanced score: {best_balanced_score}")logger.info(f"Duration: {balanced_end - balanced_start} seconds")- with open(os.path.join(balanced_output_dir, "results.json"), "w") as f:+ with open(Path(balanced_output_dir) / "results.json", "w") as f:json.dump(balanced_result, f, indent=2)# ====== EXPERIMENT 4: Multi-Benchmark (SimpleQA + BrowseComp) ======logger.info("Starting multi-benchmark optimization with 500 examples")- multi_output_dir = os.path.join(base_output_dir, "multi_benchmark")- os.makedirs(multi_output_dir, exist_ok=True)+ multi_output_dir = str(Path(base_output_dir) / "multi_benchmark")+ Path(multi_output_dir).mkdir(parents=True, exist_ok=True)# Create optimizer with multi-benchmark weightsmulti_optimizer = OptunaOptimizer(@@ -292,7 +291,7 @@ def run_strategy_comparison():logger.info(f"Best multi-benchmark score: {best_multi_score}")logger.info(f"Duration: {multi_end - multi_start} seconds")- with open(os.path.join(multi_output_dir, "results.json"), "w") as f:+ with open(Path(multi_output_dir) / "results.json", "w") as f:json.dump(multi_result, f, indent=2)# ====== Save summary of all executions ======@@ -301,7 +300,7 @@ def run_strategy_comparison():)execution_stats["timestamp"] = timestamp- with open(os.path.join(base_output_dir, "summary.json"), "w") as f:+ with open(Path(base_output_dir) / "summary.json", "w") as f:json.dump(execution_stats, f, indent=2)# Generate summary report@@ -362,7 +361,7 @@ significant sample size of 500 examples per experiment."""# Write summary to file- with open(os.path.join(base_dir, "summary_report.md"), "w") as f:+ with open(Path(base_dir) / "summary_report.md", "w") as f:f.write(summary_text)@@ -452,9 +451,7 @@ def run_strategy_simulation(num_examples=10):"best_score": best_score,}- with open(- os.path.join(sim_output_dir, "simulation_results.json"), "w"- ) as f:+ with open(Path(sim_output_dir) / "simulation_results.json", "w") as f:json.dump(sim_result, f, indent=2)return sim_resultdiff --git a/examples/optimization/update_llm_config.py b/examples/optimization/update_llm_config.pyindex 4b7536bc81..93990c3423 100755--- a/examples/optimization/update_llm_config.py+++ b/examples/optimization/update_llm_config.py@@ -18,17 +18,15 @@ Usage:"""import argparse-import osimport sys+from pathlib import Pathfrom typing import Optionalfrom loguru import logger# Add the src directory to the Python path-project_root = os.path.abspath(- os.path.dirname(os.path.dirname(os.path.dirname(__file__)))-)-sys.path.insert(0, os.path.join(project_root, "src"))+project_root = str(Path(__file__).parent.parent.parent.resolve())+sys.path.insert(0, str(Path(project_root) / "src"))def update_llm_configuration(diff --git a/examples/show_env_vars.py b/examples/show_env_vars.pyindex f8879a9663..17712d83a4 100644--- a/examples/show_env_vars.py+++ b/examples/show_env_vars.py@@ -6,9 +6,10 @@ This demonstrates the centralized environment variable management in SettingsManimport sysimport os+from pathlib import Path# Add parent directory to path-sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))+sys.path.insert(0, str(Path(__file__).parent.parent / "src"))from local_deep_research.settings.manager import SettingsManagerdiff --git a/scripts/check_benchmark_db.py b/scripts/check_benchmark_db.pyindex 19e47edf4e..5d8417b1a0 100755--- a/scripts/check_benchmark_db.py+++ b/scripts/check_benchmark_db.py@@ -20,28 +20,29 @@ def check_benchmark_database():try:# Try to find the most recent benchmark userimport glob- import osfrom local_deep_research.config.paths import get_data_directorydata_dir = get_data_directory()- db_pattern = os.path.join(- data_dir, "encrypted_databases", "benchmark_*.db"+ db_pattern = str(+ Path(data_dir) / "encrypted_databases" / "benchmark_*.db")benchmark_dbs = glob.glob(db_pattern)if benchmark_dbs:# Get the most recent benchmark user- latest_db = max(benchmark_dbs, key=os.path.getmtime)- username = os.path.basename(latest_db).replace(".db", "")+ latest_db = max(+ benchmark_dbs, key=lambda x: Path(x).stat().st_mtime+ )+ username = Path(latest_db).stemprint(f"Checking database for user: {username}")else:# Try to find most recent user databaseall_dbs = glob.glob(- os.path.join(data_dir, "encrypted_databases", "*.db")+ str(Path(data_dir) / "encrypted_databases" / "*.db"))if all_dbs:- latest_db = max(all_dbs, key=os.path.getmtime)- username = os.path.basename(latest_db).replace(".db", "")+ latest_db = max(all_dbs, key=lambda x: Path(x).stat().st_mtime)+ username = Path(latest_db).stemprint(f"No benchmark users found, using most recent user: {username}")diff --git a/scripts/check_research_db.py b/scripts/check_research_db.pyindex 7fc685b9e8..492770aed9 100755--- a/scripts/check_research_db.py+++ b/scripts/check_research_db.py@@ -1,10 +1,10 @@#!/usr/bin/env python"""Check if there are any researches in the database."""-import osimport sys+from pathlib import Path-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+sys.path.insert(0, str(Path(__file__).parent.parent.resolve()))from src.local_deep_research.database.models import ResearchLogfrom src.local_deep_research.utilities.db_utils import get_db_session@@ -16,19 +16,22 @@ def check_researches():try:# Check for the most recently created test user# The test creates a user with pattern "simple_" + timestamp- import os# Look for any user databases that might have been created- db_dir = os.path.expanduser(- "~/.local/share/local-deep-research/encrypted_databases"+ db_dir = (+ Path.home()+ / ".local"+ / "share"+ / "local-deep-research"+ / "encrypted_databases")- if os.path.exists(db_dir):+ if db_dir.exists():db_files = [- f- for f in os.listdir(db_dir)- if f.endswith(".db")- and not f.endswith("-wal")- and not f.endswith("-shm")+ f.name+ for f in db_dir.iterdir()+ if f.name.endswith(".db")+ and not f.name.endswith("-wal")+ and not f.name.endswith("-shm")]print(f"Found {len(db_files)} user database(s)")diff --git a/scripts/dev/kill_servers.py b/scripts/dev/kill_servers.pyindex 7c3ef23979..babe589ec2 100644--- a/scripts/dev/kill_servers.py+++ b/scripts/dev/kill_servers.py@@ -3,6 +3,7 @@ import signalimport subprocessimport sysimport time+from pathlib import Pathimport psutil@@ -95,17 +96,17 @@ def start_flask_server(port=5000):# Get the virtual environment Python executable# Try multiple common venv locationsvenv_paths = [- os.path.join("venv_dev", "bin", "python"), # Linux/Mac- os.path.join("venv", "bin", "python"), # Linux/Mac- os.path.join(".venv", "Scripts", "python.exe"), # Windows- os.path.join("venv_dev", "Scripts", "python.exe"), # Windows- os.path.join("venv", "Scripts", "python.exe"), # Windows+ Path("venv_dev") / "bin" / "python", # Linux/Mac+ Path("venv") / "bin" / "python", # Linux/Mac+ Path(".venv") / "Scripts" / "python.exe", # Windows+ Path("venv_dev") / "Scripts" / "python.exe", # Windows+ Path("venv") / "Scripts" / "python.exe", # Windows]venv_path = Nonefor path in venv_paths:- if os.path.exists(path):- venv_path = path+ if path.exists():+ venv_path = str(path)breakif not venv_path:@@ -235,15 +236,15 @@ def start_flask_server_windows(port=5000):# Get the virtual environment Python executable# Try multiple common venv locationsvenv_paths = [- os.path.join("venv_dev", "Scripts", "python.exe"), # Windows- os.path.join("venv", "Scripts", "python.exe"), # Windows- os.path.join(".venv", "Scripts", "python.exe"), # Windows+ Path("venv_dev") / "Scripts" / "python.exe", # Windows+ Path("venv") / "Scripts" / "python.exe", # Windows+ Path(".venv") / "Scripts" / "python.exe", # Windows]venv_path = Nonefor path in venv_paths:- if os.path.exists(path):- venv_path = path+ if path.exists():+ venv_path = str(path)breakif not venv_path:diff --git a/src/local_deep_research/api/benchmark_functions.py b/src/local_deep_research/api/benchmark_functions.pyindex 7452e8b22a..3fc9e8a488 100644--- a/src/local_deep_research/api/benchmark_functions.py+++ b/src/local_deep_research/api/benchmark_functions.py@@ -5,6 +5,7 @@ This module provides functions for running benchmarks programmatically."""from loguru import logger+from pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom ..benchmarks import (@@ -218,7 +219,7 @@ def compare_configurations(benchmark_result = run_benchmark(dataset_type=dataset_type,num_examples=num_examples,- output_dir=os.path.join(output_dir, config_name.replace(" ", "_")),+ output_dir=str(Path(output_dir) / config_name.replace(" ", "_")),search_config=search_config,run_evaluation=True,)@@ -233,8 +234,8 @@ def compare_configurations(import timetimestamp = time.strftime("%Y%m%d_%H%M%S")- report_file = os.path.join(- output_dir, f"comparison_{dataset_type}_{timestamp}.md"+ report_file = str(+ Path(output_dir) / f"comparison_{dataset_type}_{timestamp}.md")with open(report_file, "w") as f:diff --git a/src/local_deep_research/benchmarks/benchmark_functions.py b/src/local_deep_research/benchmarks/benchmark_functions.pyindex d10b7d0b71..a055c7565d 100644--- a/src/local_deep_research/benchmarks/benchmark_functions.py+++ b/src/local_deep_research/benchmarks/benchmark_functions.py@@ -4,7 +4,7 @@ API functions for benchmarking.This module provides functions for running benchmarks programmatically."""-import os+from pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom loguru import logger@@ -262,7 +262,7 @@ def compare_configurations(# Create output directory- os.makedirs(output_dir, exist_ok=True)+ Path(output_dir).mkdir(parents=True, exist_ok=True)# Run benchmarks for each configurationresults = []@@ -285,7 +285,7 @@ def compare_configurations(benchmark_result = run_benchmark(dataset_type=dataset_type,num_examples=num_examples,- output_dir=os.path.join(output_dir, config_name.replace(" ", "_")),+ output_dir=str(Path(output_dir) / config_name.replace(" ", "_")),search_config=search_config,run_evaluation=True,)@@ -300,8 +300,8 @@ def compare_configurations(import timetimestamp = time.strftime("%Y%m%d_%H%M%S")- report_file = os.path.join(- output_dir, f"comparison_{dataset_type}_{timestamp}.md"+ report_file = str(+ Path(output_dir) / f"comparison_{dataset_type}_{timestamp}.md")with open(report_file, "w") as f:diff --git a/src/local_deep_research/benchmarks/cli.py b/src/local_deep_research/benchmarks/cli.pyindex 5035385597..6aab827eb2 100644--- a/src/local_deep_research/benchmarks/cli.py+++ b/src/local_deep_research/benchmarks/cli.py@@ -10,6 +10,7 @@ import argparse# import logging - replaced with logurufrom loguru import loggerimport os+from pathlib import Pathimport sysfrom datetime import datetime, UTC@@ -310,8 +311,8 @@ def run_profiling(args):# Save resultstimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- results_file = os.path.join(- args.output_dir, f"profiling_results_{timestamp}.json"+ results_file = str(+ Path(args.output_dir) / f"profiling_results_{timestamp}.json")with open(results_file, "w") as f:diff --git a/src/local_deep_research/benchmarks/comparison/evaluator.py b/src/local_deep_research/benchmarks/comparison/evaluator.pyindex bff09ec0c9..a19161410a 100644--- a/src/local_deep_research/benchmarks/comparison/evaluator.py+++ b/src/local_deep_research/benchmarks/comparison/evaluator.py@@ -8,6 +8,7 @@ and evaluating their performance across various metrics.import jsonimport osfrom datetime import datetime, UTC+from pathlib import Pathfrom typing import Any, Dict, List, Optionalimport matplotlib.pyplot as plt@@ -185,16 +186,15 @@ def compare_configurations(# Save results to filetimestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")- result_file = os.path.join(- output_dir, f"comparison_results_{timestamp}.json"- )+ result_file = str(Path(output_dir) / f"comparison_results_{timestamp}.json")with open(result_file, "w") as f:json.dump(comparison_report, f, indent=2)# Generate visualizations- visualizations_dir = os.path.join(output_dir, "visualizations")- os.makedirs(visualizations_dir, exist_ok=True)+ visualizations_dir = Path(output_dir) / "visualizations"+ visualizations_dir.mkdir(parents=True, exist_ok=True)+ visualizations_dir = str(visualizations_dir)_create_comparison_visualizations(comparison_report, output_dir=visualizations_dir, timestamp=timestamp@@ -441,7 +441,7 @@ def _create_comparison_visualizations(plt.grid(axis="x", linestyle="--", alpha=0.7)plt.tight_layout()plt.savefig(- os.path.join(output_dir, f"overall_score_comparison_{timestamp}.png")+ str(Path(output_dir) / f"overall_score_comparison_{timestamp}.png"))plt.close()@@ -453,7 +453,7 @@ def _create_comparison_visualizations(quality_metrics,"quality_metrics","Quality Metrics Comparison",- os.path.join(output_dir, f"quality_metrics_comparison_{timestamp}.png"),+ str(Path(output_dir) / f"quality_metrics_comparison_{timestamp}.png"),)# 3. Speed metrics comparison@@ -464,7 +464,7 @@ def _create_comparison_visualizations(speed_metrics,"speed_metrics","Speed Metrics Comparison",- os.path.join(output_dir, f"speed_metrics_comparison_{timestamp}.png"),+ str(Path(output_dir) / f"speed_metrics_comparison_{timestamp}.png"),)# 4. Resource metrics comparison@@ -479,22 +479,20 @@ def _create_comparison_visualizations(resource_metrics,"resource_metrics","Resource Usage Comparison",- os.path.join(- output_dir, f"resource_metrics_comparison_{timestamp}.png"- ),+ str(Path(output_dir) / f"resource_metrics_comparison_{timestamp}.png"),)# 5. Spider chart for multi-dimensional comparison_create_spider_chart(successful_results,config_names,- os.path.join(output_dir, f"spider_chart_comparison_{timestamp}.png"),+ str(Path(output_dir) / f"spider_chart_comparison_{timestamp}.png"),)# 6. Pareto frontier chart for quality vs. speed_create_pareto_chart(successful_results,- os.path.join(output_dir, f"pareto_chart_comparison_{timestamp}.png"),+ str(Path(output_dir) / f"pareto_chart_comparison_{timestamp}.png"),)diff --git a/src/local_deep_research/benchmarks/evaluators/base.py b/src/local_deep_research/benchmarks/evaluators/base.pyindex 4f35a0d829..ad0cc08263 100644--- a/src/local_deep_research/benchmarks/evaluators/base.py+++ b/src/local_deep_research/benchmarks/evaluators/base.py@@ -5,8 +5,8 @@ This module defines the abstract base class that all benchmark evaluatorsmust implement, establishing a common interface for different benchmark types."""-import osfrom abc import ABC, abstractmethod+from pathlib import Pathfrom typing import Any, Dict@@ -66,6 +66,6 @@ class BaseBenchmarkEvaluator(ABC):Returns:Path to the benchmark-specific directory"""- benchmark_dir = os.path.join(output_dir, self.name)- os.makedirs(benchmark_dir, exist_ok=True)- return benchmark_dir+ benchmark_dir = Path(output_dir) / self.name+ benchmark_dir.mkdir(parents=True, exist_ok=True)+ return str(benchmark_dir)diff --git a/src/local_deep_research/benchmarks/evaluators/simpleqa.py b/src/local_deep_research/benchmarks/evaluators/simpleqa.pyindex d4420f3681..5f97ecdbfd 100644--- a/src/local_deep_research/benchmarks/evaluators/simpleqa.py+++ b/src/local_deep_research/benchmarks/evaluators/simpleqa.py@@ -7,7 +7,7 @@ benchmark, which tests simple question-answering capabilities.import jsonfrom loguru import logger-import os+from pathlib import Pathimport timefrom typing import Any, Dict@@ -131,14 +131,14 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):# Set up output filestimestamp = time.strftime("%Y%m%d_%H%M%S")- results_file = os.path.join(- output_dir, f"simpleqa_{timestamp}_results.jsonl"+ results_file = str(+ Path(output_dir) / f"simpleqa_{timestamp}_results.jsonl")- evaluation_file = os.path.join(- output_dir, f"simpleqa_{timestamp}_evaluation.jsonl"+ evaluation_file = str(+ Path(output_dir) / f"simpleqa_{timestamp}_evaluation.jsonl")- report_file = os.path.join(- output_dir, f"simpleqa_{timestamp}_report.md"+ report_file = str(+ Path(output_dir) / f"simpleqa_{timestamp}_report.md")# Process each examplediff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.pyindex 24174f514e..f97307dc97 100644--- a/src/local_deep_research/benchmarks/graders.py+++ b/src/local_deep_research/benchmarks/graders.py@@ -6,7 +6,7 @@ This module provides tools for evaluating model outputs against reference answerimport jsonfrom loguru import logger-import os+from pathlib import Pathimport refrom typing import Any, Callable, Dict, List, Optional@@ -321,8 +321,9 @@ def grade_results(results.append(json.loads(line))# Remove output file if it exists- if os.path.exists(output_file):- os.remove(output_file)+ output_path = Path(output_file)+ if output_path.exists():+ output_path.unlink()graded_results = []correct_count = 0@@ -520,8 +521,9 @@ def human_evaluation(results.append(json.loads(line))# Remove output file if it exists- if os.path.exists(output_file):- os.remove(output_file)+ output_path = Path(output_file)+ if output_path.exists():+ output_path.unlink()human_graded_results = []correct_count = 0diff --git a/src/local_deep_research/benchmarks/metrics/calculation.py b/src/local_deep_research/benchmarks/metrics/calculation.pyindex 17cd66fb97..e5e09affe1 100644--- a/src/local_deep_research/benchmarks/metrics/calculation.py+++ b/src/local_deep_research/benchmarks/metrics/calculation.py@@ -7,7 +7,7 @@ standard benchmarks and optimization tasks.import jsonfrom loguru import logger-import os+from pathlib import Pathimport tempfileimport timefrom datetime import datetime, UTC@@ -174,7 +174,7 @@ def evaluate_benchmark_quality(finally:# Clean up temporary directory if we created it- if temp_dir and os.path.exists(temp_dir):+ if temp_dir and Path(temp_dir).exists():import shutiltry:diff --git a/src/local_deep_research/benchmarks/optimization/api.py b/src/local_deep_research/benchmarks/optimization/api.pyindex 943d6b5271..f20314b2dd 100644--- a/src/local_deep_research/benchmarks/optimization/api.py+++ b/src/local_deep_research/benchmarks/optimization/api.py@@ -5,7 +5,7 @@ This module provides a simplified interface for parameter optimizationwithout having to directly work with the optimizer classes."""-import os+from pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Tuple# No metrics imports needed here, they're used in the OptunaOptimizer@@ -15,7 +15,7 @@ from .optuna_optimizer import OptunaOptimizerdef optimize_parameters(query: str,param_space: Optional[Dict[str, Any]] = None,- output_dir: str = os.path.join("data", "optimization_results"),+ output_dir: str = str(Path("data") / "optimization_results"),model_name: Optional[str] = None,provider: Optional[str] = None,search_tool: Optional[str] = None,@@ -79,7 +79,7 @@ def optimize_parameters(def optimize_for_speed(query: str,n_trials: int = 20,- output_dir: str = os.path.join("data", "optimization_results"),+ output_dir: str = str(Path("data") / "optimization_results"),model_name: Optional[str] = None,provider: Optional[str] = None,search_tool: Optional[str] = None,@@ -145,7 +145,7 @@ def optimize_for_speed(def optimize_for_quality(query: str,n_trials: int = 30,- output_dir: str = os.path.join("data", "optimization_results"),+ output_dir: str = str(Path("data") / "optimization_results"),model_name: Optional[str] = None,provider: Optional[str] = None,search_tool: Optional[str] = None,@@ -190,7 +190,7 @@ def optimize_for_quality(def optimize_for_efficiency(query: str,n_trials: int = 25,- output_dir: str = os.path.join("data", "optimization_results"),+ output_dir: str = str(Path("data") / "optimization_results"),model_name: Optional[str] = None,provider: Optional[str] = None,search_tool: Optional[str] = None,diff --git a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.pyindex 4e75ac9eec..b5d52c8e55 100644--- a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py+++ b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py@@ -8,6 +8,7 @@ and performance metrics.import jsonimport os+from pathlib import Pathimport timefrom datetime import datetime, UTCfrom functools import partial@@ -439,7 +440,7 @@ class OptunaOptimizer:# Evaluate quality using composite benchmark evaluator# Use a small number of examples for efficiency- benchmark_dir = os.path.join(self.output_dir, "benchmark_temp")+ benchmark_dir = str(Path(self.output_dir) / "benchmark_temp")quality_results = self.benchmark_evaluator.evaluate(system_config=system_config,num_examples=5, # Small number for optimization efficiency@@ -505,8 +506,8 @@ class OptunaOptimizer:timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")# Save trial history- history_file = os.path.join(- self.output_dir, f"{self.study_name}_history.json"+ history_file = str(+ Path(self.output_dir) / f"{self.study_name}_history.json")with open(history_file, "w") as f:# Convert numpy values to native Python types for JSON serialization@@ -533,8 +534,8 @@ class OptunaOptimizer:and hasattr(self.study, "best_params")and self.study.best_params):- best_params_file = os.path.join(- self.output_dir, f"{self.study_name}_best_params.json"+ best_params_file = str(+ Path(self.output_dir) / f"{self.study_name}_best_params.json")with open(best_params_file, "w") as f:json.dump(@@ -556,8 +557,8 @@ class OptunaOptimizer:# Save the Optuna studyif self.study:- study_file = os.path.join(- self.output_dir, f"{self.study_name}_study.pkl"+ study_file = str(+ Path(self.output_dir) / f"{self.study_name}_study.pkl")joblib.dump(self.study, study_file)@@ -576,8 +577,9 @@ class OptunaOptimizer:return# Create directory for visualizations- viz_dir = os.path.join(self.output_dir, "visualizations")- os.makedirs(viz_dir, exist_ok=True)+ viz_dir = Path(self.output_dir) / "visualizations"+ viz_dir.mkdir(parents=True, exist_ok=True)+ viz_dir = str(viz_dir)# Create Optuna visualizationsself._create_optuna_visualizations(viz_dir)@@ -597,16 +599,17 @@ class OptunaOptimizer:return# Create directory for visualizations- viz_dir = os.path.join(self.output_dir, "visualizations")- os.makedirs(viz_dir, exist_ok=True)+ viz_dir = Path(self.output_dir) / "visualizations"+ viz_dir.mkdir(parents=True, exist_ok=True)+ viz_dir = str(viz_dir)# Create optimization history only (faster than full visualization)try:fig = plot_optimization_history(self.study)fig.write_image(- os.path.join(- viz_dir,- f"{self.study_name}_optimization_history_current.png",+ str(+ Path(viz_dir)+ / f"{self.study_name}_optimization_history_current.png"))except Exception as e:@@ -625,9 +628,9 @@ class OptunaOptimizer:try:fig = plot_optimization_history(self.study)fig.write_image(- os.path.join(- viz_dir,- f"{self.study_name}_optimization_history_{timestamp}.png",+ str(+ Path(viz_dir)+ / f"{self.study_name}_optimization_history_{timestamp}.png"))except Exception as e:@@ -637,9 +640,9 @@ class OptunaOptimizer:try:fig = plot_param_importances(self.study)fig.write_image(- os.path.join(- viz_dir,- f"{self.study_name}_param_importances_{timestamp}.png",+ str(+ Path(viz_dir)+ / f"{self.study_name}_param_importances_{timestamp}.png"))except Exception as e:@@ -652,9 +655,9 @@ class OptunaOptimizer:for param_name in self.study.best_params.keys():fig = plot_slice(self.study, [param_name])fig.write_image(- os.path.join(- viz_dir,- f"{self.study_name}_slice_{param_name}_{timestamp}.png",+ str(+ Path(viz_dir)+ / f"{self.study_name}_slice_{param_name}_{timestamp}.png"))except Exception as e:@@ -673,9 +676,9 @@ class OptunaOptimizer:self.study, params=[param_names[i], param_names[j]])fig.write_image(- os.path.join(- viz_dir,- f"{self.study_name}_contour_{param_names[i]}_{param_names[j]}_{timestamp}.png",+ str(+ Path(viz_dir)+ / f"{self.study_name}_contour_{param_names[i]}_{param_names[j]}_{timestamp}.png"))except Exception as e:@@ -828,9 +831,9 @@ class OptunaOptimizer:# Save the figureplt.tight_layout()plt.savefig(- os.path.join(- viz_dir,- f"{self.study_name}_quality_vs_speed_{timestamp}.png",+ str(+ Path(viz_dir)+ / f"{self.study_name}_quality_vs_speed_{timestamp}.png"))plt.close()@@ -907,9 +910,9 @@ class OptunaOptimizer:# Save the figureplt.tight_layout()plt.savefig(- os.path.join(- viz_dir,- f"{self.study_name}_param_evolution_{param_name}_{timestamp}.png",+ str(+ Path(viz_dir)+ / f"{self.study_name}_param_evolution_{param_name}_{timestamp}.png"))plt.close()@@ -989,9 +992,9 @@ class OptunaOptimizer:# Save the figureplt.tight_layout()plt.savefig(- os.path.join(- viz_dir,- f"{self.study_name}_duration_vs_score_{timestamp}.png",+ str(+ Path(viz_dir)+ / f"{self.study_name}_duration_vs_score_{timestamp}.png"))plt.close()@@ -1002,7 +1005,7 @@ class OptunaOptimizer:def optimize_parameters(query: str,param_space: Optional[Dict[str, Any]] = None,- output_dir: str = os.path.join("data", "optimization_results"),+ output_dir: str = str(Path("data") / "optimization_results"),model_name: Optional[str] = None,provider: Optional[str] = None,search_tool: Optional[str] = None,@@ -1066,7 +1069,7 @@ def optimize_parameters(def optimize_for_speed(query: str,n_trials: int = 20,- output_dir: str = os.path.join("data", "optimization_results"),+ output_dir: str = str(Path("data") / "optimization_results"),model_name: Optional[str] = None,provider: Optional[str] = None,search_tool: Optional[str] = None,@@ -1132,7 +1135,7 @@ def optimize_for_speed(def optimize_for_quality(query: str,n_trials: int = 30,- output_dir: str = os.path.join("data", "optimization_results"),+ output_dir: str = str(Path("data") / "optimization_results"),model_name: Optional[str] = None,provider: Optional[str] = None,search_tool: Optional[str] = None,@@ -1177,7 +1180,7 @@ def optimize_for_quality(def optimize_for_efficiency(query: str,n_trials: int = 25,- output_dir: str = os.path.join("data", "optimization_results"),+ output_dir: str = str(Path("data") / "optimization_results"),model_name: Optional[str] = None,provider: Optional[str] = None,search_tool: Optional[str] = None,diff --git a/src/local_deep_research/benchmarks/runners.py b/src/local_deep_research/benchmarks/runners.pyindex dfe0948928..572f35590d 100644--- a/src/local_deep_research/benchmarks/runners.py+++ b/src/local_deep_research/benchmarks/runners.py@@ -7,6 +7,7 @@ This module provides the main functions for running benchmarks using LDR.import jsonfrom loguru import loggerimport os+from pathlib import Pathimport timefrom typing import Any, Callable, Dict, Optional@@ -107,20 +108,21 @@ def run_benchmark(# Set up output filestimestamp = time.strftime("%Y%m%d_%H%M%S")- results_file = os.path.join(- output_dir, f"{dataset_type}_{timestamp}_results.jsonl"+ results_file = str(+ Path(output_dir) / f"{dataset_type}_{timestamp}_results.jsonl")- evaluation_file = os.path.join(- output_dir, f"{dataset_type}_{timestamp}_evaluation.jsonl"+ evaluation_file = str(+ Path(output_dir) / f"{dataset_type}_{timestamp}_evaluation.jsonl")- report_file = os.path.join(- output_dir, f"{dataset_type}_{timestamp}_report.md"+ report_file = str(+ Path(output_dir) / f"{dataset_type}_{timestamp}_report.md")# Make sure output files don't existfor file in [results_file, evaluation_file, report_file]:- if os.path.exists(file):- os.remove(file)+ file_path = Path(file)+ if file_path.exists():+ file_path.unlink()# Progress trackingtotal_examples = len(dataset)diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex 8d37b2fa0a..d509673ca0 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -1,5 +1,6 @@import osfrom functools import cache+from pathlib import Pathfrom langchain_anthropic import ChatAnthropicfrom langchain_community.llms import VLLM@@ -165,6 +166,7 @@ def is_llamacpp_available(settings_snapshot=None):settings_snapshot=settings_snapshot,)+# If no path configured, LlamaCpp is not availableif not model_path_str:return False@@ -182,6 +184,7 @@ def is_llamacpp_available(settings_snapshot=None):except ImportError:# LlamaCpp library not installedreturn False+except Exception:return Falsediff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.pyindex 37f7cc1646..394b20894a 100644--- a/src/local_deep_research/metrics/token_counter.py+++ b/src/local_deep_research/metrics/token_counter.py@@ -2,9 +2,9 @@import inspectimport json-import osimport timefrom datetime import datetime, timedelta, UTC+from pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom langchain_core.callbacks import BaseCallbackHandler@@ -118,7 +118,7 @@ class TokenCountingCallback(BaseCallbackHandler):-1].lstrip("/")else:- relative_path = os.path.basename(file_path)+ relative_path = Path(file_path).nameself.calling_file = relative_pathself.calling_function = frame_info.function@@ -131,7 +131,7 @@ class TokenCountingCallback(BaseCallbackHandler):and "site-packages" not in frame.filenameand "venv" not in frame.filename):- frame_name = f"{os.path.basename(frame.filename)}:{frame.function}:{frame.lineno}"+ frame_name = f"{Path(frame.filename).name}:{frame.function}:{frame.lineno}"call_stack_frames.append(frame_name)self.call_stack = (diff --git a/src/local_deep_research/settings/env_settings.py b/src/local_deep_research/settings/env_settings.pyindex 614a934402..28be92f011 100644--- a/src/local_deep_research/settings/env_settings.py+++ b/src/local_deep_research/settings/env_settings.py@@ -172,6 +172,8 @@ class PathSetting(StringSetting):# Use pathlib for path operationspath = Path(path_str).expanduser()# Expand environment variables manually since pathlib doesn't have expandvars+ # Note: os.path.expandvars is kept here as there's no pathlib equivalent+ # noqa: PLR0402 - Suppress pathlib check for this linepath_str = os.path.expandvars(str(path))path = Path(path_str)diff --git a/src/local_deep_research/utilities/es_utils.py b/src/local_deep_research/utilities/es_utils.pyindex e6e729cb8b..c5a000e8e3 100644--- a/src/local_deep_research/utilities/es_utils.py+++ b/src/local_deep_research/utilities/es_utils.py@@ -3,7 +3,7 @@ Elasticsearch utilities for indexing and managing documents."""from loguru import logger-import os+from pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom elasticsearch import Elasticsearch@@ -293,7 +293,7 @@ class ElasticsearchManager:content = "\n\n".join([doc.page_content for doc in documents])# Get the filename for the title- filename = os.path.basename(file_path)+ filename = Path(file_path).nametitle = filename# Prepare the document@@ -312,9 +312,7 @@ class ElasticsearchManager:# Add file-specific metadatadocument["source"] = file_path- document["file_extension"] = os.path.splitext(filename)[- 1- ].lstrip(".")+ document["file_extension"] = Path(filename).suffix.lstrip(".")document["filename"] = filename# Index the document@@ -355,14 +353,12 @@ class ElasticsearchManager:int: Number of successfully indexed files"""try:- import glob-# Find all matching filesall_files = []+ directory = Path(directory_path)for pattern in file_patterns:- pattern_path = os.path.join(directory_path, pattern)- matching_files = glob.glob(pattern_path)- all_files.extend(matching_files)+ matching_files = list(directory.glob(pattern))+ all_files.extend([str(f) for f in matching_files])logger.info(f"Found {len(all_files)} files matching patterns {file_patterns} in {directory_path}"diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex f32bd351d1..9275bcf38c 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -1,5 +1,5 @@# import logging - replaced with loguru-import os+from pathlib import Pathfrom importlib import resources as importlib_resourcesfrom flask import (@@ -50,8 +50,8 @@ def create_app():logger.exception("Package directories not found, using fallback paths")app = Flask(__name__,- static_folder=os.path.abspath("static"),- template_folder=os.path.abspath("templates"),+ static_folder=str(Path("static").resolve()),+ template_folder=str(Path("templates").resolve()),)# App configuration@@ -59,8 +59,8 @@ def create_app():import secretsfrom ..config.paths import get_data_directory- secret_key_file = os.path.join(get_data_directory(), ".secret_key")- if os.path.exists(secret_key_file):+ secret_key_file = Path(get_data_directory()) / ".secret_key"+ if secret_key_file.exists():try:with open(secret_key_file, "r") as f:app.config["SECRET_KEY"] = f.read().strip()@@ -71,10 +71,10 @@ def create_app():# Generate a new key on first runnew_key = secrets.token_hex(32)try:- os.makedirs(os.path.dirname(secret_key_file), exist_ok=True)+ secret_key_file.parent.mkdir(parents=True, exist_ok=True)with open(secret_key_file, "w") as f:f.write(new_key)- os.chmod(secret_key_file, 0o600) # Secure file permissions+ secret_key_file.chmod(0o600) # Secure file permissionsapp.config["SECRET_KEY"] = new_keylogger.info("Generated new SECRET_KEY for this installation")except Exception as e:diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex e03a87fb9d..08e7fe06bc 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -3,8 +3,8 @@ Authentication routes for login, register, and logout.Uses SQLCipher encrypted databases with browser password manager support."""-import osfrom datetime import datetime, timezone, UTC+from pathlib import PurePosixPathfrom flask import (Blueprint,@@ -153,8 +153,9 @@ def login():# Validate the URL: must be relative (no netloc) and safeif next_page and not parsed_url.netloc and not parsed_url.scheme:# Normalize the path to prevent tricks like //example.com+ # Using PurePosixPath for URL path normalization (not filesystem paths)normalized_path = (- os.path.normpath(parsed_url.path) if parsed_url.path else ""+ str(PurePosixPath(parsed_url.path)) if parsed_url.path else "")# Check if it's in the whitelist or is a safe relative pathdiff --git a/src/local_deep_research/web/routes/benchmark_routes.py b/src/local_deep_research/web/routes/benchmark_routes.pyindex b6bc38c680..17c2554485 100644--- a/src/local_deep_research/web/routes/benchmark_routes.py+++ b/src/local_deep_research/web/routes/benchmark_routes.py@@ -4,8 +4,8 @@ Web routes for benchmarking.This module provides Flask routes for the benchmark web interface."""-import osimport threading+from pathlib import Pathfrom flask import Blueprint, jsonify, render_template, requestfrom loguru import logger@@ -92,7 +92,7 @@ def run_benchmark_endpoint():"questions_per_iteration": data.get("questions_per_iteration", 3),"search_tool": data.get("search_tool", "searxng"),"human_evaluation": data.get("human_evaluation", False),- "output_dir": os.path.join("benchmark_results", job_id),+ "output_dir": str(Path("benchmark_results") / job_id),}# Add optional parameters if present@@ -227,14 +227,12 @@ def register_blueprint(app):app.register_blueprint(benchmark_bp)# Create templates directory if it doesn't exist- template_dir = os.path.join(- os.path.dirname(app.root_path), "templates", "benchmark"- )- os.makedirs(template_dir, exist_ok=True)+ template_dir = Path(app.root_path).parent / "templates" / "benchmark"+ template_dir.mkdir(parents=True, exist_ok=True)# Create dashboard template if it doesn't exist- dashboard_template = os.path.join(template_dir, "dashboard.html")- if not os.path.exists(dashboard_template):+ dashboard_template = template_dir / "dashboard.html"+ if not dashboard_template.exists():with open(dashboard_template, "w") as f:f.write("""diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 62d51bf416..3397b55326 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -1,8 +1,8 @@import json-import osimport platformimport subprocessfrom datetime import datetime, UTC+from pathlib import Pathfrom flask import (Blueprint,@@ -43,9 +43,8 @@ research_bp = Blueprint("research", __name__)@research_bp.route("/static/<path:path>")def serve_static(path):"""Serve static files"""- return send_from_directory(- os.path.join(os.path.dirname(os.path.dirname(__file__)), "static"), path- )+ static_dir = Path(__file__).parent.parent / "static"+ return send_from_directory(str(static_dir), path)# Add static route at the root level@@ -846,9 +845,9 @@ def delete_research(research_id):)# Delete report file if it exists- if report_path and os.path.exists(report_path):+ if report_path and Path(report_path).exists():try:- os.remove(report_path)+ Path(report_path).unlink()except Exception:logger.exception("Error removing report file")@@ -884,11 +883,9 @@ def clear_history():continue# Delete report file if it exists- if research.report_path and os.path.exists(- research.report_path- ):+ if research.report_path and Path(research.report_path).exists():try:- os.remove(research.report_path)+ Path(research.report_path).unlink()except Exception:logger.exception("Error removing report file")@@ -925,15 +922,15 @@ def open_file_location():# Get the user's data directory as the safe rootfrom ...config.paths import get_data_directory- safe_root = os.path.abspath(get_data_directory())+ safe_root = Path(get_data_directory()).resolve()# Normalize the path and ensure it's within the safe root directorytry:# Convert to absolute path and normalize- file_path = os.path.abspath(os.path.normpath(file_path))+ file_path = Path(file_path).resolve()# Check if the path is within the safe data directory- if not file_path.startswith(safe_root):+ if not str(file_path).startswith(str(safe_root)):logger.warning(f"Blocked access to path outside data directory: {file_path}")@@ -948,7 +945,7 @@ def open_file_location():return jsonify({"status": "error", "message": "Invalid path"}), 400# Check if path exists- if not os.path.exists(file_path):+ if not file_path.exists():return jsonify({"status": "error", "message": "Path does not exist"}), 404@@ -956,15 +953,17 @@ def open_file_location():try:if platform.system() == "Windows":# On Windows, open the folder and select the file- if os.path.isfile(file_path):- subprocess.run(["explorer", "/select,", file_path], check=True)+ if file_path.is_file():+ subprocess.run(+ ["explorer", "/select,", str(file_path)], check=True+ )else:# If it's a directory, just open it- subprocess.run(["explorer", file_path], check=True)+ subprocess.run(["explorer", str(file_path)], check=True)elif platform.system() == "Darwin": # macOS- subprocess.run(["open", file_path], check=True)+ subprocess.run(["open", str(file_path)], check=True)else: # Linux and others- subprocess.run(["xdg-open", os.path.dirname(file_path)], check=True)+ subprocess.run(["xdg-open", str(file_path.parent)], check=True)return jsonify({"status": "success"})except Exception:@@ -991,11 +990,9 @@ def save_raw_config():try:# Get the config file path- config_dir = os.path.join(- os.path.expanduser("~"), ".local_deep_research"- )- os.makedirs(config_dir, exist_ok=True)- config_path = os.path.join(config_dir, "config.toml")+ config_dir = Path.home() / ".local_deep_research"+ config_dir.mkdir(parents=True, exist_ok=True)+ config_path = config_dir / "config.toml"# Write the configuration to filewith open(config_path, "w", encoding="utf-8") as f:diff --git a/src/local_deep_research/web/routes/research_routes_orm.py b/src/local_deep_research/web/routes/research_routes_orm.pyindex ee982e77ee..b5aabf09bb 100644--- a/src/local_deep_research/web/routes/research_routes_orm.py+++ b/src/local_deep_research/web/routes/research_routes_orm.py@@ -4,8 +4,8 @@ This is a converted version showing how to replace raw SQL with ORM queries."""import json-import osfrom datetime import datetime, UTC+from pathlib import Pathfrom flask import (Blueprint,@@ -259,9 +259,9 @@ def delete_research(research_id):db_session.commit()# Delete report file if exists- if report_path and os.path.exists(report_path):+ if report_path and Path(report_path).exists():try:- os.remove(report_path)+ Path(report_path).unlink()logger.info(f"Deleted report file: {report_path}")except Exception:logger.exception("Failed to delete report file")@@ -296,9 +296,9 @@ def clear_history():# Delete report filesdeleted_files = 0for research in all_research:- if research.report_path and os.path.exists(research.report_path):+ if research.report_path and Path(research.report_path).exists():try:- os.remove(research.report_path)+ Path(research.report_path).unlink()deleted_files += 1except Exception as e:logger.exception(diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 7fa76cdb59..34d39e601f 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -1,7 +1,7 @@import json-import osimport platformimport subprocess+from pathlib import Pathfrom typing import Any, Optional, Tuplefrom datetime import datetime, UTC, timedelta@@ -1567,21 +1567,21 @@ def open_file_location():try:# Validate the file path- file_path = os.path.abspath(file_path)- if not os.path.exists(file_path):+ file_path = Path(file_path).resolve()+ if not file_path.exists():flash("File path does not exist", "error")return redirect(url_for("settings.settings_page"))# Get the directory containing the file- dir_path = os.path.dirname(file_path)+ dir_path = file_path.parent# Open the directory in the file explorerif platform.system() == "Windows":- subprocess.Popen(["explorer", dir_path])+ subprocess.Popen(["explorer", str(dir_path)])elif platform.system() == "Darwin": # macOS- subprocess.Popen(["open", dir_path])+ subprocess.Popen(["open", str(dir_path)])else: # Linux- subprocess.Popen(["xdg-open", dir_path])+ subprocess.Popen(["xdg-open", str(dir_path)])flash(f"Opening folder: {dir_path}", "success")except Exception as e:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local.py b/src/local_deep_research/web_search_engines/engines/search_engine_local.pyindex da6d406249..dd782c02de 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_local.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local.py@@ -714,12 +714,13 @@ class LocalSearchEngine(BaseSearchEngine):# Validate folder pathsself.folder_paths = pathsself.valid_folder_paths = []- for path in paths:- if os.path.exists(path) and os.path.isdir(path):- self.valid_folder_paths.append(path)+ for path_str in paths:+ path = Path(path_str)+ if path.exists() and path.is_dir():+ self.valid_folder_paths.append(path_str)else:logger.warning(- f"Folder not found or is not a directory: {path}"+ f"Folder not found or is not a directory: {path_str}")# If no valid folders, log a clear message@@ -854,7 +855,7 @@ class LocalSearchEngine(BaseSearchEngine):# Extract filename and pathsource_path = result["metadata"].get("source", "Unknown")filename = result["metadata"].get(- "filename", os.path.basename(source_path)+ "filename", Path(source_path).name)# Create preview snippet (first ~200 chars of content)diff --git a/tests/api_tests/fix_search_engines.py b/tests/api_tests/fix_search_engines.pyindex 0b026fd345..98a65888be 100644--- a/tests/api_tests/fix_search_engines.py+++ b/tests/api_tests/fix_search_engines.py@@ -4,11 +4,12 @@ Quick fix to ensure search engine settings are loaded for test user.import osimport sys+from pathlib import Pathfrom loguru import logger# Add parent directory to path for imports-sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))+sys.path.insert(0, str(Path(__file__).parent.parent.parent))from src.local_deep_research.database.encrypted_db import db_managerfrom src.local_deep_research.web.services.settings_manager import (diff --git a/tests/api_tests/migrate_research_mode.py b/tests/api_tests/migrate_research_mode.pyindex 67f65fad9d..071849bfb3 100644--- a/tests/api_tests/migrate_research_mode.py+++ b/tests/api_tests/migrate_research_mode.py@@ -7,9 +7,10 @@ This script adds the missing research_mode column to TokenUsage and SearchCall timport osimport sqlite3import sys+from pathlib import Path# Add parent directory to path for imports-sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))+sys.path.insert(0, str(Path(__file__).parent.parent.parent))from loguru import loggerdiff --git a/tests/api_tests/populate_search_engines.py b/tests/api_tests/populate_search_engines.pyindex b872137ca5..8f15cd425c 100644--- a/tests/api_tests/populate_search_engines.py+++ b/tests/api_tests/populate_search_engines.py@@ -5,11 +5,12 @@ Populate search engine settings in the databaseimport osimport sys+from pathlib import Pathfrom loguru import logger# Add parent directory to path-sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))+sys.path.insert(0, str(Path(__file__).parent.parent.parent))from src.local_deep_research.database.models import Settingfrom src.local_deep_research.utilities.db_utils import get_db_sessiondiff --git a/tests/api_tests/run_api_tests.py b/tests/api_tests/run_api_tests.pyindex b89dd606fd..9d76d2f91e 100644--- a/tests/api_tests/run_api_tests.py+++ b/tests/api_tests/run_api_tests.py@@ -7,16 +7,16 @@ Usage:python run_api_tests.py search # Run search engines test only"""-import osimport subprocessimport sys+from pathlib import Pathdef run_all_tests():"""Run all API tests."""print("Running all API tests...")result = subprocess.run(- [sys.executable, "test_all_apis.py"], cwd=os.path.dirname(__file__)+ [sys.executable, "test_all_apis.py"], cwd=str(Path(__file__).parent))return result.returncode@@ -26,7 +26,7 @@ def run_search_engines_test():print("Running search engines API test...")result = subprocess.run([sys.executable, "test_search_engines_api.py"],- cwd=os.path.dirname(__file__),+ cwd=str(Path(__file__).parent),)return result.returncodediff --git a/tests/api_tests/run_basic_api_tests.py b/tests/api_tests/run_basic_api_tests.pyindex df2a9901ac..c512796611 100644--- a/tests/api_tests/run_basic_api_tests.py+++ b/tests/api_tests/run_basic_api_tests.py@@ -4,8 +4,9 @@ Run basic API tests that are known to work.import osimport sys+from pathlib import Path-sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))+sys.path.insert(0, str(Path(__file__).parent.parent.parent))os.environ["LDR_ALLOW_UNENCRYPTED"] = "true"from loguru import loggerdiff --git a/tests/api_tests_with_login/pytest_tests/conftest.py b/tests/api_tests_with_login/pytest_tests/conftest.pyindex ab4d99e8b2..f9811e213b 100644--- a/tests/api_tests_with_login/pytest_tests/conftest.py+++ b/tests/api_tests_with_login/pytest_tests/conftest.py@@ -65,7 +65,7 @@ class AuthHelper:finally:# Clean up temp file- if os.path.exists(cookie_file.name):+ if Path(cookie_file.name).exists():os.unlink(cookie_file.name)diff --git a/tests/api_tests_with_login/run_pytest_tests.py b/tests/api_tests_with_login/run_pytest_tests.pyindex 7631484684..fb785a7136 100755--- a/tests/api_tests_with_login/run_pytest_tests.py+++ b/tests/api_tests_with_login/run_pytest_tests.py@@ -4,11 +4,11 @@ Standalone test runner for pytest API tests"""import sys-import osimport subprocess+from pathlib import Path# Add the pytest_tests directory to Python path-test_dir = os.path.join(os.path.dirname(__file__), "pytest_tests")+test_dir = str(Path(__file__).parent / "pytest_tests")sys.path.insert(0, test_dir)# Run pytest with the testsdiff --git a/tests/api_tests_with_login/test_research_api_pytest.py b/tests/api_tests_with_login/test_research_api_pytest.pyindex a896c78920..ab4ff118d4 100644--- a/tests/api_tests_with_login/test_research_api_pytest.py+++ b/tests/api_tests_with_login/test_research_api_pytest.py@@ -71,7 +71,7 @@ class AuthHelper:finally:# Clean up temp file- if os.path.exists(cookie_file.name):+ if Path(cookie_file.name).exists():os.unlink(cookie_file.name)diff --git a/tests/auth_tests/conftest.py b/tests/auth_tests/conftest.pyindex 402c32fdf8..a3a806d737 100644--- a/tests/auth_tests/conftest.py+++ b/tests/auth_tests/conftest.py@@ -4,11 +4,12 @@ Pytest configuration for authentication tests.import osimport sys+from pathlib import Pathimport pytest# Add src to path for imports-sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "src"))+sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))# Disable HTTPS for testingos.environ["LDR_HTTPS_TESTING"] = "1"diff --git a/tests/auth_tests/run_auth_tests.py b/tests/auth_tests/run_auth_tests.pyindex 201927bb75..cf03fb587c 100755--- a/tests/auth_tests/run_auth_tests.py+++ b/tests/auth_tests/run_auth_tests.py@@ -6,11 +6,10 @@ Run authentication tests with proper configuration.import osimport subprocessimport sys+from pathlib import Path# Add project root to Python path-project_root = os.path.abspath(- os.path.join(os.path.dirname(__file__), "..", "..")-)+project_root = str(Path(__file__).parent.parent.parent.resolve())sys.path.insert(0, project_root)# Set test environmentdiff --git a/tests/database/test_database_init.py b/tests/database/test_database_init.pyindex fe2b31962b..feb71755a4 100644--- a/tests/database/test_database_init.py+++ b/tests/database/test_database_init.py@@ -1,9 +1,9 @@"""Tests for database initialization and encryption functionality."""-import osimport shutilimport tempfileimport uuid+from pathlib import Pathimport pytestfrom sqlalchemy import create_engine, event, inspect@@ -30,14 +30,14 @@ class TestDatabaseInitialization:def test_basic_database_creation(self, temp_dir):"""Test creating a basic SQLite database."""- db_path = os.path.join(temp_dir, "test.db")+ db_path = str(Path(temp_dir) / "test.db")engine = create_engine(f"sqlite:///{db_path}")# Create all tablesBase.metadata.create_all(engine)# Verify database file exists- assert os.path.exists(db_path)+ assert Path(db_path).exists()# Verify tables were createdinspector = inspect(engine)@@ -53,7 +53,7 @@ class TestDatabaseInitialization:def test_database_creation_with_function(self, temp_dir):"""Test database creation through standard SQLAlchemy."""- db_path = os.path.join(temp_dir, "test_user.db")+ db_path = str(Path(temp_dir) / "test_user.db")# Create engine and initialize databaseengine = create_engine(f"sqlite:///{db_path}")@@ -63,7 +63,7 @@ class TestDatabaseInitialization:assert engine is not None# Verify database exists- assert os.path.exists(db_path)+ assert Path(db_path).exists()# Test connectionfrom sqlalchemy import text@@ -74,7 +74,7 @@ class TestDatabaseInitialization:def test_encrypted_database_creation(self, temp_dir):"""Test creating an encrypted database with SQLCipher."""- db_path = os.path.join(temp_dir, "encrypted.db")+ db_path = str(Path(temp_dir) / "encrypted.db")password = "test_password_123"# Try to create encrypted database (will fail if sqlcipher not available)@@ -123,7 +123,7 @@ class TestDatabaseInitialization:def test_database_schema_completeness(self, temp_dir):"""Test that all expected tables and columns are created."""- db_path = os.path.join(temp_dir, "schema_test.db")+ db_path = str(Path(temp_dir) / "schema_test.db")engine = create_engine(f"sqlite:///{db_path}")Base.metadata.create_all(engine)@@ -189,7 +189,7 @@ class TestDatabaseInitialization:def test_database_indexes(self, temp_dir):"""Test that proper indexes are created."""- db_path = os.path.join(temp_dir, "index_test.db")+ db_path = str(Path(temp_dir) / "index_test.db")engine = create_engine(f"sqlite:///{db_path}")Base.metadata.create_all(engine)@@ -211,7 +211,7 @@ class TestDatabaseInitialization:def test_database_foreign_keys(self, temp_dir):"""Test that foreign key relationships work correctly."""- db_path = os.path.join(temp_dir, "fk_test.db")+ db_path = str(Path(temp_dir) / "fk_test.db")engine = create_engine(f"sqlite:///{db_path}")Base.metadata.create_all(engine)@@ -265,7 +265,7 @@ class TestDatabaseInitialization:def test_database_cascade_deletes(self, temp_dir):"""Test cascade delete behavior."""- db_path = os.path.join(temp_dir, "cascade_test.db")+ db_path = str(Path(temp_dir) / "cascade_test.db")engine = create_engine(f"sqlite:///{db_path}")Base.metadata.create_all(engine)@@ -327,7 +327,7 @@ class TestDatabaseInitialization:def test_database_transactions(self, temp_dir):"""Test transaction rollback behavior."""- db_path = os.path.join(temp_dir, "transaction_test.db")+ db_path = str(Path(temp_dir) / "transaction_test.db")engine = create_engine(f"sqlite:///{db_path}")Base.metadata.create_all(engine)@@ -374,7 +374,7 @@ class TestDatabaseInitialization:def test_database_performance_with_large_dataset(self, temp_dir):"""Test database performance with larger datasets."""- db_path = os.path.join(temp_dir, "performance_test.db")+ db_path = str(Path(temp_dir) / "performance_test.db")engine = create_engine(f"sqlite:///{db_path}")Base.metadata.create_all(engine)@@ -432,12 +432,12 @@ class TestDatabaseInitialization:def test_user_specific_database_path(self, temp_dir):"""Test user-specific database paths for multi-user support."""# Test database path generation for different users- user1_path = os.path.join(temp_dir, "user1", "user1_encrypted.db")- user2_path = os.path.join(temp_dir, "user2", "user2_encrypted.db")+ user1_path = str(Path(temp_dir) / "user1" / "user1_encrypted.db")+ user2_path = str(Path(temp_dir) / "user2" / "user2_encrypted.db")# Create directories- os.makedirs(os.path.dirname(user1_path))- os.makedirs(os.path.dirname(user2_path))+ Path(user1_path).parent.mkdir(parents=True, exist_ok=True)+ Path(user2_path).parent.mkdir(parents=True, exist_ok=True)# Create separate databasesengine1 = create_engine(f"sqlite:///{user1_path}")diff --git a/tests/database/test_encrypted_database_orm.py b/tests/database/test_encrypted_database_orm.pyindex 9af5e3352d..3796f4cc74 100644--- a/tests/database/test_encrypted_database_orm.py+++ b/tests/database/test_encrypted_database_orm.py@@ -1,7 +1,6 @@#!/usr/bin/env python3"""Test ORM operations with encrypted user databases."""-import osimport sysimport tempfileimport uuid@@ -12,9 +11,7 @@ import pytestsys.path.insert(0,- os.path.dirname(- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- ),+ str(Path(__file__).parent.parent.parent.resolve()),)from src.local_deep_research.database.encrypted_db import DatabaseManagerdiff --git a/tests/database/test_model_consolidation.py b/tests/database/test_model_consolidation.pyindex 57dfa99fc6..d4ff160146 100644--- a/tests/database/test_model_consolidation.py+++ b/tests/database/test_model_consolidation.py@@ -1,14 +1,12 @@#!/usr/bin/env python3"""Test that all models are properly consolidated in the database.models package."""-import osimport sys+from pathlib import Pathsys.path.insert(0,- os.path.dirname(- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- ),+ str(Path(__file__).parent.parent.parent.resolve()),)diff --git a/tests/database/test_no_raw_sql.py b/tests/database/test_no_raw_sql.pyindex 336bba895e..37d5b4bc93 100644--- a/tests/database/test_no_raw_sql.py+++ b/tests/database/test_no_raw_sql.py@@ -1,18 +1,15 @@#!/usr/bin/env python3"""Test to verify no raw SQL is used in the codebase (except in allowed locations)."""-import osimport sys+from pathlib import Pathsys.path.insert(0,- os.path.dirname(- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- ),+ str(Path(__file__).parent.parent.parent.resolve()),)import re-from pathlib import Pathdef check_file_for_raw_sql(filepath):diff --git a/tests/database/test_orm_conversions.py b/tests/database/test_orm_conversions.pyindex 8772ef9e71..5b1c8fa817 100644--- a/tests/database/test_orm_conversions.py+++ b/tests/database/test_orm_conversions.py@@ -1,14 +1,12 @@#!/usr/bin/env python3"""Test that ORM conversions work correctly (no more raw SQL)."""-import osimport sys+from pathlib import Pathsys.path.insert(0,- os.path.dirname(- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- ),+ str(Path(__file__).parent.parent.parent.resolve()),)import pytestdiff --git a/tests/health_check/run_quick_health_check.py b/tests/health_check/run_quick_health_check.pyindex 443b98839d..2b98e594b6 100755--- a/tests/health_check/run_quick_health_check.py+++ b/tests/health_check/run_quick_health_check.py@@ -4,9 +4,9 @@ Quick health check runner - automatically detects if server is runningand provides helpful feedback"""-import osimport subprocessimport sys+from pathlib import Pathdef check_server_running():@@ -22,11 +22,11 @@ def check_server_running():def run_health_check():"""Run the appropriate health check script"""- script_dir = os.path.dirname(os.path.abspath(__file__))+ script_dir = Path(__file__).parent.resolve()# Try Python version first (more detailed output)- python_script = os.path.join(script_dir, "test_endpoints_health.py")- shell_script = os.path.join(script_dir, "test_endpoints_health.sh")+ python_script = str(script_dir / "test_endpoints_health.py")+ shell_script = str(script_dir / "test_endpoints_health.sh")print("🚀 Quick Health Check for Local Deep Research")print("=" * 50)@@ -57,7 +57,7 @@ def run_health_check():print("📦 requests module not available, falling back to curl...")# Fall back to shell script- if os.path.exists(shell_script):+ if Path(shell_script).exists():print("🐚 Running shell health check...")result = subprocess.run([shell_script], capture_output=False, text=True)return result.returncode == 0diff --git a/tests/settings/test_env_settings.py b/tests/settings/test_env_settings.pyindex 4f7bc3d11e..c79e98f2d1 100644--- a/tests/settings/test_env_settings.py+++ b/tests/settings/test_env_settings.py@@ -1,6 +1,7 @@"""Test suite for the environment settings system."""import os+from pathlib import Pathimport pytestfrom local_deep_research.settings.env_registry import (@@ -143,7 +144,7 @@ class TestEnvRegistry:# Test home expansionos.environ["LDR_BOOTSTRAP_DATA_DIR"] = "~/test_path"data_dir = get_env_setting("bootstrap.data_dir")- assert data_dir.startswith(os.path.expanduser("~"))+ assert data_dir.startswith(str(Path.home()))assert "test_path" in data_dirdef test_secret_setting(self):diff --git a/tests/test_database_initialization.py b/tests/test_database_initialization.pyindex 35e5532fe1..c65edf0e14 100644--- a/tests/test_database_initialization.py+++ b/tests/test_database_initialization.py@@ -2,6 +2,7 @@import osimport tempfile+from pathlib import Pathimport pytestfrom sqlalchemy import create_engine, inspectfrom sqlalchemy.orm import sessionmaker@@ -29,7 +30,7 @@ class TestDatabaseInitialization:# Cleanupengine.dispose()- if os.path.exists(db_path):+ if Path(db_path).exists():os.unlink(db_path)def test_initialize_core_tables(self, temp_db):diff --git a/tests/test_openai_api_key_e2e.py b/tests/test_openai_api_key_e2e.pyindex aae1a7b595..642789f661 100755--- a/tests/test_openai_api_key_e2e.py+++ b/tests/test_openai_api_key_e2e.py@@ -22,10 +22,11 @@ Or set environment variables:import argparseimport osimport sys+from pathlib import Pathfrom typing import Optional# Add project root to path-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+sys.path.insert(0, str(Path(__file__).parent.parent.resolve()))from local_deep_research.database.session_context import get_user_db_sessionfrom local_deep_research.config.llm_config import get_llmdiff --git a/tests/ui_tests/test_direct_uuid_insert.py b/tests/ui_tests/test_direct_uuid_insert.pyindex 20231bc7cc..77d464365c 100644--- a/tests/ui_tests/test_direct_uuid_insert.py+++ b/tests/ui_tests/test_direct_uuid_insert.py@@ -6,6 +6,7 @@ Test direct database insertion with UUIDimport osimport uuidfrom datetime import datetime+from pathlib import Path# Allow unencrypted databases for testingos.environ["LDR_ALLOW_UNENCRYPTED"] = "true"@@ -14,9 +15,7 @@ import syssys.path.insert(0,- os.path.dirname(- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- ),+ str(Path(__file__).parent.parent.parent.resolve()),)from sqlalchemy import inspectdiff --git a/tests/ui_tests/test_mixed_id_handling.py b/tests/ui_tests/test_mixed_id_handling.pyindex 389b4177e8..28a918cc42 100644--- a/tests/ui_tests/test_mixed_id_handling.py+++ b/tests/ui_tests/test_mixed_id_handling.py@@ -4,6 +4,7 @@ Test handling of mixed integer and UUID IDs"""import os+from pathlib import Pathos.environ["LDR_ALLOW_UNENCRYPTED"] = "true"@@ -11,9 +12,7 @@ import syssys.path.insert(0,- os.path.dirname(- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- ),+ str(Path(__file__).parent.parent.parent.resolve()),)import requestsdiff --git a/tests/ui_tests/test_trace_error.py b/tests/ui_tests/test_trace_error.pyindex 7e8f032178..6470a858fa 100644--- a/tests/ui_tests/test_trace_error.py+++ b/tests/ui_tests/test_trace_error.py@@ -4,6 +4,7 @@ Trace the exact error when accessing history for UUID user"""import os+from pathlib import Pathos.environ["LDR_ALLOW_UNENCRYPTED"] = "true"@@ -11,9 +12,7 @@ import syssys.path.insert(0,- os.path.dirname(- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- ),+ str(Path(__file__).parent.parent.parent.resolve()),)from src.local_deep_research.web.app_factory import create_appdiff --git a/tests/ui_tests/test_uuid_fresh_db.py b/tests/ui_tests/test_uuid_fresh_db.pyindex a557a189ff..64169d1087 100644--- a/tests/ui_tests/test_uuid_fresh_db.py+++ b/tests/ui_tests/test_uuid_fresh_db.py@@ -7,6 +7,7 @@ import jsonimport osimport randomimport string+from pathlib import Pathimport requests@@ -18,9 +19,7 @@ import syssys.path.insert(0,- os.path.dirname(- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- ),+ str(Path(__file__).parent.parent.parent.resolve()),)from sqlalchemy import inspect, textdiff --git a/tests/ui_tests/test_uuid_research.py b/tests/ui_tests/test_uuid_research.pyindex 0862a76034..ab71856ca1 100644--- a/tests/ui_tests/test_uuid_research.py+++ b/tests/ui_tests/test_uuid_research.py@@ -163,12 +163,11 @@ def check_database_directly():try:import sys+ from pathlib import Pathsys.path.insert(0,- os.path.dirname(- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- ),+ str(Path(__file__).parent.parent.parent.resolve()),)from sqlalchemy import inspect