diff --git a/hesabixAPI/app/core/runtime_paths.py b/hesabixAPI/app/core/runtime_paths.py new file mode 100644 index 00000000..1405f1b8 --- /dev/null +++ b/hesabixAPI/app/core/runtime_paths.py @@ -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" diff --git a/hesabixAPI/app/core/settings.py b/hesabixAPI/app/core/settings.py index 2c8b96c1..70134af3 100755 --- a/hesabixAPI/app/core/settings.py +++ b/hesabixAPI/app/core/settings.py @@ -3,9 +3,11 @@ from urllib.parse import quote_plus from pydantic import BaseModel, Field from pydantic_settings import BaseSettings, SettingsConfigDict +from app.core.runtime_paths import settings_env_file, voice_data_dir + 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_version: str = "0.1.0" @@ -161,7 +163,9 @@ class Settings(BaseSettings): voice_tts_model_path: str | None = None # Piper (پیش‌فرض برای Python 3.12+) 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 موجود نیست) voice_tts_coqui_model_fa: str = "tts_models/fa/cv/vits/glow-tts" voice_tts_output_sample_rate_hz: int = 16000 @@ -169,7 +173,7 @@ class Settings(BaseSettings): # Data collection (اختیاری، برای بهبود کیفیت در آینده) 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_stt_max_seconds: int = 30 @@ -182,4 +186,4 @@ class Settings(BaseSettings): @lru_cache(maxsize=1) def get_settings() -> Settings: - return Settings() + return Settings(_env_file=settings_env_file(), _env_file_encoding="utf-8") diff --git a/hesabixAPI/app/services/ai/ai_tool_discovery_eval.py b/hesabixAPI/app/services/ai/ai_tool_discovery_eval.py index 2dfa4293..8ccc8e36 100644 --- a/hesabixAPI/app/services/ai/ai_tool_discovery_eval.py +++ b/hesabixAPI/app/services/ai/ai_tool_discovery_eval.py @@ -7,9 +7,9 @@ from __future__ import annotations import json import math from dataclasses import dataclass -from pathlib import Path 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 ( CONTEXT_INPUT_TOKEN_BUDGET, 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) 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 # values so CI catches regressions, not noise. diff --git a/hesabixAPI/app/services/ai/ai_tool_phase10_eval.py b/hesabixAPI/app/services/ai/ai_tool_phase10_eval.py index 4f2b5533..a173831d 100644 --- a/hesabixAPI/app/services/ai/ai_tool_phase10_eval.py +++ b/hesabixAPI/app/services/ai/ai_tool_phase10_eval.py @@ -5,9 +5,9 @@ Does not enable production flags. Adaptive K and Hybrid stay off. from __future__ import annotations import json -from pathlib import Path from typing import Any, Dict, List, Sequence +from app.core.runtime_paths import docs_root from app.services.ai.ai_constants import ( ADAPTIVE_DISCOVERY_K, 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_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) FINAL_KS = (10, 15, 20) TARGET_CANDIDATE_RECALL = 0.99 diff --git a/hesabixAPI/app/services/ai/ai_tool_phase11_eval.py b/hesabixAPI/app/services/ai/ai_tool_phase11_eval.py index c6a6c752..d471229c 100644 --- a/hesabixAPI/app/services/ai/ai_tool_phase11_eval.py +++ b/hesabixAPI/app/services/ai/ai_tool_phase11_eval.py @@ -6,9 +6,9 @@ from __future__ import annotations import json import time -from pathlib import Path from typing import Any, Dict, List, Sequence +from app.core.runtime_paths import docs_root from app.services.ai.ai_constants import ( ADAPTIVE_DISCOVERY_K, 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_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) PHASE6_BASELINE = { 10: 0.9549, diff --git a/hesabixAPI/app/services/ai/ai_tool_phase12_eval.py b/hesabixAPI/app/services/ai/ai_tool_phase12_eval.py index 7706c0c3..df4913bd 100644 --- a/hesabixAPI/app/services/ai/ai_tool_phase12_eval.py +++ b/hesabixAPI/app/services/ai/ai_tool_phase12_eval.py @@ -2,9 +2,9 @@ from __future__ import annotations import json -from pathlib import Path from typing import Any, Dict +from app.core.runtime_paths import docs_root from app.services.ai.ai_constants import ( ADAPTIVE_DISCOVERY_K, 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_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]: diff --git a/hesabixAPI/app/services/ai/ai_tool_phase13_eval.py b/hesabixAPI/app/services/ai/ai_tool_phase13_eval.py index 67cc0c48..dc8f259e 100644 --- a/hesabixAPI/app/services/ai/ai_tool_phase13_eval.py +++ b/hesabixAPI/app/services/ai/ai_tool_phase13_eval.py @@ -6,9 +6,9 @@ Gold Recall is never copied as Production Recall. from __future__ import annotations import json -from pathlib import Path from typing import Any, Dict +from app.core.runtime_paths import docs_root from app.services.ai.ai_constants import ( ADAPTIVE_DISCOVERY_K, 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 -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]: diff --git a/hesabixAPI/app/services/ai/ai_tool_phase14_eval.py b/hesabixAPI/app/services/ai/ai_tool_phase14_eval.py index 5d3f64ac..7f5fafad 100644 --- a/hesabixAPI/app/services/ai/ai_tool_phase14_eval.py +++ b/hesabixAPI/app/services/ai/ai_tool_phase14_eval.py @@ -6,9 +6,9 @@ Gold Recall is never copied as Production Recall. from __future__ import annotations import json -from pathlib import Path from typing import Any, Dict +from app.core.runtime_paths import docs_root from app.services.ai.ai_constants import ( ADAPTIVE_DISCOVERY_K, CANDIDATE_RETRIEVAL_N, @@ -30,8 +30,9 @@ from app.services.ai.ai_tool_indexed_evidence import ( offline_performance_evidence, ) -PHASE13_JSON = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-13/latest.json") -PHASE14_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-14") +_EVALS_ROOT = docs_root() / "ai-agent" / "evals" +PHASE13_JSON = _EVALS_ROOT / "phase-13" / "latest.json" +PHASE14_DIR = _EVALS_ROOT / "phase-14" def _offline_gold() -> Dict[str, Any]: diff --git a/hesabixAPI/app/services/ai/ai_tool_phase8_eval.py b/hesabixAPI/app/services/ai/ai_tool_phase8_eval.py index 183d9aa6..0dc9599f 100644 --- a/hesabixAPI/app/services/ai/ai_tool_phase8_eval.py +++ b/hesabixAPI/app/services/ai/ai_tool_phase8_eval.py @@ -2,9 +2,9 @@ from __future__ import annotations import json -from pathlib import Path 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 ( AdaptiveKPolicy, 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 -ADAPTIVE_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/tool-adaptive-k") -HYBRID_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/tool-hybrid") -PHASE8_DIR = Path("/opt/hesabix/app/docs/ai-agent/evals/phase-8") +_EVALS_ROOT = docs_root() / "ai-agent" / "evals" +ADAPTIVE_DIR = _EVALS_ROOT / "tool-adaptive-k" +HYBRID_DIR = _EVALS_ROOT / "tool-hybrid" +PHASE8_DIR = _EVALS_ROOT / "phase-8" TARGET_RECALL = 0.95 diff --git a/hesabixAPI/app/services/ai/ai_tool_phase9_eval.py b/hesabixAPI/app/services/ai/ai_tool_phase9_eval.py index a8c8169b..9e265f59 100644 --- a/hesabixAPI/app/services/ai/ai_tool_phase9_eval.py +++ b/hesabixAPI/app/services/ai/ai_tool_phase9_eval.py @@ -6,9 +6,9 @@ from __future__ import annotations import json from collections import defaultdict -from pathlib import Path from typing import Any, Dict, List, Sequence +from app.core.runtime_paths import docs_root from app.services.ai.ai_constants import ( ADAPTIVE_DISCOVERY_K, 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_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} diff --git a/hesabixAPI/app/services/ai/ai_tool_scale_bench.py b/hesabixAPI/app/services/ai/ai_tool_scale_bench.py index 5ffd479f..76435df2 100644 --- a/hesabixAPI/app/services/ai/ai_tool_scale_bench.py +++ b/hesabixAPI/app/services/ai/ai_tool_scale_bench.py @@ -5,9 +5,9 @@ import json import time import tracemalloc from concurrent.futures import ThreadPoolExecutor, as_completed -from pathlib import Path 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_tool_candidates import retrieve_candidates 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, ) -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) LARGE_SIZE = 100000 QUERY = "فاکتور فروش این ماه را پیدا کن" diff --git a/hesabixAPI/app/services/ai/ai_tool_schema_eval.py b/hesabixAPI/app/services/ai/ai_tool_schema_eval.py index 8ec4e59a..c863b39d 100644 --- a/hesabixAPI/app/services/ai/ai_tool_schema_eval.py +++ b/hesabixAPI/app/services/ai/ai_tool_schema_eval.py @@ -6,9 +6,9 @@ Wire vs construction token costs are simulated without an LLM provider. from __future__ import annotations import json -from pathlib import Path from typing import Any, Dict, List, Optional, Sequence +from app.core.runtime_paths import docs_root from app.services.ai.ai_constants import ( MAX_TOOLS_PER_REQUEST, 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 -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. PHASE6_RECALL_AT_10 = 0.90 diff --git a/hesabixAPI/app/services/file_storage_service.py b/hesabixAPI/app/services/file_storage_service.py index 78db0f7c..4e7ac967 100755 --- a/hesabixAPI/app/services/file_storage_service.py +++ b/hesabixAPI/app/services/file_storage_service.py @@ -14,6 +14,7 @@ from adapters.db.repositories.file_storage_repository import ( FileVerificationRepository, ) from adapters.db.models.file_storage import FileStorage, StorageConfig +from app.core.runtime_paths import file_storage_dir from PIL import Image import io @@ -425,7 +426,7 @@ class FileStorageService: # Helper methods 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) return os.path.join(base_path, stored_name) diff --git a/hesabixAPI/app/services/hscript/docs_catalog.py b/hesabixAPI/app/services/hscript/docs_catalog.py index 4264ae27..bdd51bca 100644 --- a/hesabixAPI/app/services/hscript/docs_catalog.py +++ b/hesabixAPI/app/services/hscript/docs_catalog.py @@ -2,12 +2,12 @@ from __future__ import annotations -from pathlib import Path 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]] = [ diff --git a/hesabixAPI/env.example b/hesabixAPI/env.example index acb6dc80..dd0f149f 100755 --- a/hesabixAPI/env.example +++ b/hesabixAPI/env.example @@ -28,6 +28,12 @@ REDIS_PASSWORD= # Logging 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_BOT_TOKEN= TELEGRAM_BOT_USERNAME= diff --git a/hesabixAPI/tests/test_runtime_paths.py b/hesabixAPI/tests/test_runtime_paths.py new file mode 100644 index 00000000..7a59130d --- /dev/null +++ b/hesabixAPI/tests/test_runtime_paths.py @@ -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()