fix(backend): use cross-platform runtime paths #33

Merged
morrning merged 1 commit from Seyyed/Seyyed_arc:codex/cross-platform-runtime-paths into master 2026-10-25 17:15:05 +03:30
16 changed files with 179 additions and 31 deletions

View file

@ -0,0 +1,72 @@
"""Central, OS-aware runtime paths for the API."""
from __future__ import annotations
import os
from collections.abc import Mapping
from pathlib import Path
API_ROOT = Path(__file__).resolve().parents[2]
REPOSITORY_ROOT = API_ROOT.parent
def _absolute_override(value: str, *, relative_to: Path = API_ROOT) -> Path:
path = Path(value).expanduser()
if not path.is_absolute():
path = relative_to / path
return path.resolve()
def settings_env_file(environment: Mapping[str, str] | None = None) -> Path:
"""Return an explicit env file or the API-root ``.env`` file."""
if environment is None:
environment = os.environ
configured = environment.get("HESABIX_ENV_FILE", "").strip()
return _absolute_override(configured) if configured else API_ROOT / ".env"
def application_data_dir(
environment: Mapping[str, str] | None = None,
*,
platform: str | None = None,
) -> Path:
"""Return a persistent application-data directory for the current OS."""
if environment is None:
environment = os.environ
configured = environment.get("HESABIX_DATA_DIR", "").strip()
if configured:
return _absolute_override(configured)
platform = platform or os.name
if platform == "nt":
windows_root = (
environment.get("LOCALAPPDATA")
or environment.get("PROGRAMDATA")
or environment.get("TEMP")
)
if windows_root:
return Path(windows_root).expanduser().resolve() / "Hesabix"
return API_ROOT / ".runtime-data"
return Path("/var/lib/hesabix")
def file_storage_dir(environment: Mapping[str, str] | None = None) -> Path:
if environment is None:
environment = os.environ
configured = environment.get("HESABIX_FILE_STORAGE_DIR", "").strip()
if configured:
return _absolute_override(configured)
return application_data_dir(environment) / "files"
def voice_data_dir(environment: Mapping[str, str] | None = None) -> Path:
return application_data_dir(environment) / "voice-data"
def docs_root(environment: Mapping[str, str] | None = None) -> Path:
if environment is None:
environment = os.environ
configured = environment.get("HESABIX_DOCS_DIR", "").strip()
if configured:
return _absolute_override(configured)
return REPOSITORY_ROOT / "docs"

View file

@ -3,9 +3,11 @@ from urllib.parse import quote_plus
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict
from app.core.runtime_paths import settings_env_file, voice_data_dir
class Settings(BaseSettings): class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore") model_config = SettingsConfigDict(env_file=None, env_file_encoding="utf-8", extra="ignore")
app_name: str = "Hesabix API" app_name: str = "Hesabix API"
app_version: str = "0.1.0" app_version: str = "0.1.0"
@ -161,7 +163,9 @@ class Settings(BaseSettings):
voice_tts_model_path: str | None = None voice_tts_model_path: str | None = None
# Piper (پیش‌فرض برای Python 3.12+) # Piper (پیش‌فرض برای Python 3.12+)
voice_tts_piper_voice_fa: str = "fa_IR-ganji-medium" voice_tts_piper_voice_fa: str = "fa_IR-ganji-medium"
voice_tts_piper_models_dir: str = "/var/lib/hesabix/voice-data/piper" voice_tts_piper_models_dir: str = Field(
default_factory=lambda: str(voice_data_dir() / "piper")
)
# Coqui (legacy؛ روی Python 3.12 در PyPI موجود نیست) # Coqui (legacy؛ روی Python 3.12 در PyPI موجود نیست)
voice_tts_coqui_model_fa: str = "tts_models/fa/cv/vits/glow-tts" voice_tts_coqui_model_fa: str = "tts_models/fa/cv/vits/glow-tts"
voice_tts_output_sample_rate_hz: int = 16000 voice_tts_output_sample_rate_hz: int = 16000
@ -169,7 +173,7 @@ class Settings(BaseSettings):
# Data collection (اختیاری، برای بهبود کیفیت در آینده) # Data collection (اختیاری، برای بهبود کیفیت در آینده)
voice_data_collection_enabled: bool = False voice_data_collection_enabled: bool = False
voice_data_collection_dir: str = "/var/lib/hesabix/voice-data" voice_data_collection_dir: str = Field(default_factory=lambda: str(voice_data_dir()))
voice_max_concurrent_sessions_per_user: int = 2 voice_max_concurrent_sessions_per_user: int = 2
voice_stt_max_seconds: int = 30 voice_stt_max_seconds: int = 30
@ -182,4 +186,4 @@ class Settings(BaseSettings):
@lru_cache(maxsize=1) @lru_cache(maxsize=1)
def get_settings() -> Settings: def get_settings() -> Settings:
return Settings() return Settings(_env_file=settings_env_file(), _env_file_encoding="utf-8")

View file

@ -7,9 +7,9 @@ from __future__ import annotations
import json import json
import math import math
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
from app.core.runtime_paths import docs_root
from app.services.ai.ai_constants import ( from app.services.ai.ai_constants import (
CONTEXT_INPUT_TOKEN_BUDGET, CONTEXT_INPUT_TOKEN_BUDGET,
MAX_TOOLS_AUTONOMOUS, MAX_TOOLS_AUTONOMOUS,
@ -36,7 +36,7 @@ from app.services.ai.ai_tool_manifest import get_manifest_entry, iter_manifest_n
K_SWEEP: Tuple[int, ...] = (3, 5, 8, 10, 12, 15, 20, 30, 48, 64, 128) K_SWEEP: Tuple[int, ...] = (3, 5, 8, 10, 12, 15, 20, 30, 48, 64, 128)
PRIMARY_KS: Tuple[int, ...] = (5, 10, 15, 20, 48) PRIMARY_KS: Tuple[int, ...] = (5, 10, 15, 20, 48)
EVAL_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/tool-discovery") EVAL_DIR = docs_root() / "ai-agent" / "evals" / "tool-discovery"
# Floors set after Phase 6 ranking correction. Slightly below observed # Floors set after Phase 6 ranking correction. Slightly below observed
# values so CI catches regressions, not noise. # values so CI catches regressions, not noise.

View file

@ -5,9 +5,9 @@ Does not enable production flags. Adaptive K and Hybrid stay off.
from __future__ import annotations from __future__ import annotations
import json import json
from pathlib import Path
from typing import Any, Dict, List, Sequence from typing import Any, Dict, List, Sequence
from app.core.runtime_paths import docs_root
from app.services.ai.ai_constants import ( from app.services.ai.ai_constants import (
ADAPTIVE_DISCOVERY_K, ADAPTIVE_DISCOVERY_K,
ADAPTIVE_K_ROLLOUT_PERCENT, ADAPTIVE_K_ROLLOUT_PERCENT,
@ -32,7 +32,7 @@ from app.services.ai.ai_tool_discovery_gold import (
from app.services.ai.ai_tool_intent import query_expects_tool_use, ranking_intent_domains from app.services.ai.ai_tool_intent import query_expects_tool_use, ranking_intent_domains
from app.services.ai.ai_tool_retrieval_index import ToolRetrievalIndex from app.services.ai.ai_tool_retrieval_index import ToolRetrievalIndex
PHASE10_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-10") PHASE10_DIR = docs_root() / "ai-agent" / "evals" / "phase-10"
CANDIDATE_NS = (20, 50, 100, 200) CANDIDATE_NS = (20, 50, 100, 200)
FINAL_KS = (10, 15, 20) FINAL_KS = (10, 15, 20)
TARGET_CANDIDATE_RECALL = 0.99 TARGET_CANDIDATE_RECALL = 0.99

View file

@ -6,9 +6,9 @@ from __future__ import annotations
import json import json
import time import time
from pathlib import Path
from typing import Any, Dict, List, Sequence from typing import Any, Dict, List, Sequence
from app.core.runtime_paths import docs_root
from app.services.ai.ai_constants import ( from app.services.ai.ai_constants import (
ADAPTIVE_DISCOVERY_K, ADAPTIVE_DISCOVERY_K,
ADAPTIVE_K_ROLLOUT_PERCENT, ADAPTIVE_K_ROLLOUT_PERCENT,
@ -44,7 +44,7 @@ from app.services.ai.ai_tool_rank import score_tool_for_query
from app.services.ai.ai_tool_retrieval_index import ToolRetrievalIndex from app.services.ai.ai_tool_retrieval_index import ToolRetrievalIndex
from app.services.ai.ai_tool_scale_bench import QUERY, SIZES, _build_index, _catalog from app.services.ai.ai_tool_scale_bench import QUERY, SIZES, _build_index, _catalog
PHASE11_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-11") PHASE11_DIR = docs_root() / "ai-agent" / "evals" / "phase-11"
FINAL_KS = (10, 15, 20, 48) FINAL_KS = (10, 15, 20, 48)
PHASE6_BASELINE = { PHASE6_BASELINE = {
10: 0.9549, 10: 0.9549,

View file

@ -2,9 +2,9 @@
from __future__ import annotations from __future__ import annotations
import json import json
from pathlib import Path
from typing import Any, Dict from typing import Any, Dict
from app.core.runtime_paths import docs_root
from app.services.ai.ai_constants import ( from app.services.ai.ai_constants import (
ADAPTIVE_DISCOVERY_K, ADAPTIVE_DISCOVERY_K,
ADAPTIVE_K_ROLLOUT_PERCENT, ADAPTIVE_K_ROLLOUT_PERCENT,
@ -20,7 +20,7 @@ from app.services.ai.ai_tool_canary import recommend_indexed_promotion
from app.services.ai.ai_tool_discovery_telemetry import telemetry_snapshot from app.services.ai.ai_tool_discovery_telemetry import telemetry_snapshot
from app.services.ai.ai_tool_phase11_eval import run_phase11_evaluation from app.services.ai.ai_tool_phase11_eval import run_phase11_evaluation
PHASE12_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-12") PHASE12_DIR = docs_root() / "ai-agent" / "evals" / "phase-12"
def run_phase12_evaluation(*, write_files: bool = False) -> Dict[str, Any]: def run_phase12_evaluation(*, write_files: bool = False) -> Dict[str, Any]:

View file

@ -6,9 +6,9 @@ Gold Recall is never copied as Production Recall.
from __future__ import annotations from __future__ import annotations
import json import json
from pathlib import Path
from typing import Any, Dict from typing import Any, Dict
from app.core.runtime_paths import docs_root
from app.services.ai.ai_constants import ( from app.services.ai.ai_constants import (
ADAPTIVE_DISCOVERY_K, ADAPTIVE_DISCOVERY_K,
CANDIDATE_RETRIEVAL_N, CANDIDATE_RETRIEVAL_N,
@ -32,7 +32,7 @@ from app.services.ai.ai_tool_indexed_evidence import (
) )
from app.services.ai.ai_tool_phase11_eval import run_phase11_evaluation from app.services.ai.ai_tool_phase11_eval import run_phase11_evaluation
PHASE13_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-13") PHASE13_DIR = docs_root() / "ai-agent" / "evals" / "phase-13"
def run_phase13_evaluation(*, write_files: bool = False) -> Dict[str, Any]: def run_phase13_evaluation(*, write_files: bool = False) -> Dict[str, Any]:

View file

@ -6,9 +6,9 @@ Gold Recall is never copied as Production Recall.
from __future__ import annotations from __future__ import annotations
import json import json
from pathlib import Path
from typing import Any, Dict from typing import Any, Dict
from app.core.runtime_paths import docs_root
from app.services.ai.ai_constants import ( from app.services.ai.ai_constants import (
ADAPTIVE_DISCOVERY_K, ADAPTIVE_DISCOVERY_K,
CANDIDATE_RETRIEVAL_N, CANDIDATE_RETRIEVAL_N,
@ -30,8 +30,9 @@ from app.services.ai.ai_tool_indexed_evidence import (
offline_performance_evidence, offline_performance_evidence,
) )
PHASE13_JSON = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-13/latest.json") _EVALS_ROOT = docs_root() / "ai-agent" / "evals"
PHASE14_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-14") PHASE13_JSON = _EVALS_ROOT / "phase-13" / "latest.json"
PHASE14_DIR = _EVALS_ROOT / "phase-14"
def _offline_gold() -> Dict[str, Any]: def _offline_gold() -> Dict[str, Any]:

View file

@ -2,9 +2,9 @@
from __future__ import annotations from __future__ import annotations
import json import json
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence from typing import Any, Dict, List, Optional, Sequence
from app.core.runtime_paths import docs_root
from app.services.ai.ai_tool_adaptive_k import ( from app.services.ai.ai_tool_adaptive_k import (
AdaptiveKPolicy, AdaptiveKPolicy,
DEFAULT_ADAPTIVE_POLICY, DEFAULT_ADAPTIVE_POLICY,
@ -31,9 +31,10 @@ from app.services.ai.ai_tool_hybrid import (
) )
from app.services.ai.ai_tool_intent import iterations_for_query from app.services.ai.ai_tool_intent import iterations_for_query
ADAPTIVE_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/tool-adaptive-k") _EVALS_ROOT = docs_root() / "ai-agent" / "evals"
HYBRID_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/tool-hybrid") ADAPTIVE_DIR = _EVALS_ROOT / "tool-adaptive-k"
PHASE8_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-8") HYBRID_DIR = _EVALS_ROOT / "tool-hybrid"
PHASE8_DIR = _EVALS_ROOT / "phase-8"
TARGET_RECALL = 0.95 TARGET_RECALL = 0.95

View file

@ -6,9 +6,9 @@ from __future__ import annotations
import json import json
from collections import defaultdict from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List, Sequence from typing import Any, Dict, List, Sequence
from app.core.runtime_paths import docs_root
from app.services.ai.ai_constants import ( from app.services.ai.ai_constants import (
ADAPTIVE_DISCOVERY_K, ADAPTIVE_DISCOVERY_K,
ADAPTIVE_K_MIN_LIVE_SAMPLES, ADAPTIVE_K_MIN_LIVE_SAMPLES,
@ -41,7 +41,7 @@ from app.services.ai.ai_tool_discovery_gold import (
from app.services.ai.ai_tool_discovery_telemetry import telemetry_snapshot from app.services.ai.ai_tool_discovery_telemetry import telemetry_snapshot
from app.services.ai.ai_tool_intent import iterations_for_query from app.services.ai.ai_tool_intent import iterations_for_query
PHASE9_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-9") PHASE9_DIR = docs_root() / "ai-agent" / "evals" / "phase-9"
HIGH_RISK = {INTENT_WRITE, INTENT_DELETE, INTENT_EXPORT, INTENT_EXECUTE} HIGH_RISK = {INTENT_WRITE, INTENT_DELETE, INTENT_EXPORT, INTENT_EXECUTE}

View file

@ -5,9 +5,9 @@ import json
import time import time
import tracemalloc import tracemalloc
from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any, Dict, List from typing import Any, Dict, List
from app.core.runtime_paths import docs_root
from app.services.ai.ai_embedding_service import cosine_similarity from app.services.ai.ai_embedding_service import cosine_similarity
from app.services.ai.ai_tool_candidates import retrieve_candidates from app.services.ai.ai_tool_candidates import retrieve_candidates
from app.services.ai.ai_tool_embedding import hashed_ngram_vector from app.services.ai.ai_tool_embedding import hashed_ngram_vector
@ -20,7 +20,7 @@ from app.services.ai.ai_tool_schema import (
reset_schema_cache_for_tests, reset_schema_cache_for_tests,
) )
BENCH_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/tool-scale") BENCH_DIR = docs_root() / "ai-agent" / "evals" / "tool-scale"
SIZES = (180, 500, 1200, 5000, 10000) SIZES = (180, 500, 1200, 5000, 10000)
LARGE_SIZE = 100000 LARGE_SIZE = 100000
QUERY = "فاکتور فروش این ماه را پیدا کن" QUERY = "فاکتور فروش این ماه را پیدا کن"

View file

@ -6,9 +6,9 @@ Wire vs construction token costs are simulated without an LLM provider.
from __future__ import annotations from __future__ import annotations
import json import json
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence from typing import Any, Dict, List, Optional, Sequence
from app.core.runtime_paths import docs_root
from app.services.ai.ai_constants import ( from app.services.ai.ai_constants import (
MAX_TOOLS_PER_REQUEST, MAX_TOOLS_PER_REQUEST,
QUERY_COMPLEXITY_ITERATIONS, QUERY_COMPLEXITY_ITERATIONS,
@ -26,7 +26,7 @@ from app.services.ai.ai_tool_discovery_gold import (
) )
from app.services.ai.ai_tool_intent import iterations_for_query from app.services.ai.ai_tool_intent import iterations_for_query
EVAL_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/tool-schema-loading") EVAL_DIR = docs_root() / "ai-agent" / "evals" / "tool-schema-loading"
# Phase 6 floors — schema loading must not change retrieval. # Phase 6 floors — schema loading must not change retrieval.
PHASE6_RECALL_AT_10 = 0.90 PHASE6_RECALL_AT_10 = 0.90

View file

@ -14,6 +14,7 @@ from adapters.db.repositories.file_storage_repository import (
FileVerificationRepository, FileVerificationRepository,
) )
from adapters.db.models.file_storage import FileStorage, StorageConfig from adapters.db.models.file_storage import FileStorage, StorageConfig
from app.core.runtime_paths import file_storage_dir
from PIL import Image from PIL import Image
import io import io
@ -425,7 +426,7 @@ class FileStorageService:
# Helper methods # Helper methods
async def _get_local_file_path(self, stored_name: str, config_data: Dict) -> str: async def _get_local_file_path(self, stored_name: str, config_data: Dict) -> str:
base_path = config_data.get("base_path", "/tmp/hesabix_files") base_path = config_data.get("base_path") or str(file_storage_dir())
os.makedirs(base_path, exist_ok=True) os.makedirs(base_path, exist_ok=True)
return os.path.join(base_path, stored_name) return os.path.join(base_path, stored_name)

View file

@ -2,12 +2,12 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path
from typing import Any from typing import Any
from app.core.runtime_paths import docs_root
# ریشهٔ docs در ریپو (/opt/hesabix/app/docs/hscript)
_DOCS_ROOT = Path(__file__).resolve().parents[4] / "docs" / "hscript" _DOCS_ROOT = docs_root() / "hscript"
DOC_ENTRIES: list[dict[str, Any]] = [ DOC_ENTRIES: list[dict[str, Any]] = [

View file

@ -28,6 +28,12 @@ REDIS_PASSWORD=
# Logging # Logging
LOG_LEVEL=INFO LOG_LEVEL=INFO
# Optional cross-platform path overrides. Relative values are resolved from hesabixAPI.
# HESABIX_ENV_FILE=.env
# HESABIX_DATA_DIR=
# HESABIX_FILE_STORAGE_DIR=
# HESABIX_DOCS_DIR=../docs
# Telegram (optional) # Telegram (optional)
TELEGRAM_BOT_TOKEN= TELEGRAM_BOT_TOKEN=
TELEGRAM_BOT_USERNAME= TELEGRAM_BOT_USERNAME=

View file

@ -0,0 +1,63 @@
from __future__ import annotations
from pathlib import Path
from app.core import runtime_paths
from app.core.settings import get_settings
def test_windows_data_path_uses_local_app_data(tmp_path: Path) -> None:
result = runtime_paths.application_data_dir(
{"LOCALAPPDATA": str(tmp_path)},
platform="nt",
)
assert result == tmp_path.resolve() / "Hesabix"
def test_posix_data_path_keeps_production_default() -> None:
assert runtime_paths.application_data_dir({}, platform="posix") == Path("/var/lib/hesabix")
def test_path_overrides_are_resolved_from_api_root() -> None:
assert (
runtime_paths.settings_env_file({"HESABIX_ENV_FILE": "config/test.env"})
== (runtime_paths.API_ROOT / "config" / "test.env").resolve()
)
assert (
runtime_paths.docs_root({"HESABIX_DOCS_DIR": "../custom-docs"})
== (runtime_paths.REPOSITORY_ROOT / "custom-docs").resolve()
)
def test_default_docs_root_matches_repository_layout() -> None:
assert runtime_paths.docs_root() == runtime_paths.REPOSITORY_ROOT / "docs"
assert runtime_paths.docs_root().is_dir()
def test_settings_env_file_is_independent_of_working_directory(
monkeypatch,
tmp_path: Path,
) -> None:
env_file = tmp_path / "test.env"
env_file.write_text("APP_NAME=loaded-from-explicit-env\n", encoding="utf-8")
unrelated_cwd = tmp_path / "unrelated"
unrelated_cwd.mkdir()
monkeypatch.setenv("HESABIX_ENV_FILE", str(env_file))
monkeypatch.chdir(unrelated_cwd)
get_settings.cache_clear()
try:
assert get_settings().app_name == "loaded-from-explicit-env"
finally:
get_settings.cache_clear()
def test_file_storage_override_is_cross_platform(tmp_path: Path) -> None:
storage_root = tmp_path / "files"
result = runtime_paths.file_storage_dir(
{"HESABIX_FILE_STORAGE_DIR": str(storage_root)}
)
assert result == storage_root.resolve()