diff --git "a/backend/web_api.py" "b/backend/web_api.py"
new file mode 100644
--- /dev/null
+++ "b/backend/web_api.py"
@@ -0,0 +1,3727 @@
+"""web_api.py β FastAPI backend for the custom (non-Gradio) LocalAiLab UI.
+
+Serves the built Svelte SPA from ``ui/web/dist`` and exposes a small JSON +
+WebSocket API. The chat WebSocket streams the SAME generator the Gradio UI
+uses (``backend/chat.chat_general``), so every tested code path (agent build,
+step formatting, final-answer chunking, docx export text) is reused unchanged β
+the new UI is a different frontend over the same backend, not a reimplementation.
+
+Run for development: python tools/_launch_web.py
+Run inside pywebview: python run_webview.py --ui web
+"""
+
+import asyncio
+import os
+import re
+import secrets
+import shutil
+import sys
+import threading
+import time
+import traceback
+from pathlib import Path
+
+from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response, StreamingResponse
+from fastapi.staticfiles import StaticFiles
+
+from backend import model_registry as mr
+from backend import models
+from backend import user_config
+
+DIST = Path(__file__).resolve().parent.parent / "ui" / "web" / "dist"
+APP_ICON = Path(__file__).resolve().parent.parent / "ui" / "image" / "logo_round.png"
+
+# Xet (hf_xet) reports 0 bytes through its tqdm progress callback, which makes
+# the model-download progress bar sit frozen at 0% (the "static progress" bug).
+# Force the standard http_get download path β it reports real chunk sizes via
+# tqdm.update(len(chunk)) so the live progress bar actually moves. http_get is
+# the universally-compatible baseline, so this is also a robustness win.
+os.environ["HF_HUB_DISABLE_XET"] = "1"
+
+# (tab key, icon, i18n label key)
+TABS = [
+ ("general", "π¬", "tab_general"),
+ ("rag", "π", "tab_rag"),
+ ("deep_research", "π¬", "tab_deep_research"),
+ ("stt", "ποΈ", "tab_stt"),
+ ("data", "π", "tab_data"),
+ ("kb", "π", "tab_kb"),
+ ("vision", "πΌοΈ", "tab_vision"),
+ ("about", "βΉοΈ", "tab_about"),
+ ("feedback", "βοΈ", "tab_feedback"),
+ ("settings", "βοΈ", "tab_settings"),
+]
+
+_PROVIDER_OPTIONS = mr.LLM_PROVIDER_OPTIONS
+# VLM provider map β a separate, smaller set (no LiteLLM) used by the Vision
+# tab's picker and by /api/mmproj's provider resolution.
+_VLM_PROVIDER_OPTIONS = mr.VLM_PROVIDER_OPTIONS
+
+# Client-facing tab keys (TABS above) β canonical backend keys used by
+# model_registry._PROVIDER_KEYS / REPORT_DIRS ("gen", "rag", "dr", "vis",
+# "stt", "data"). Without this mapping the provider would silently never
+# persist and reports would land in the wrong folder.
+_BACKEND_TAB = {
+ "general": "gen",
+ "rag": "rag",
+ "deep_research": "dr",
+ "vision": "vis",
+ "stt": "stt",
+ "data": "data",
+ "kb": "kb",
+ "about": "about",
+ "feedback": "feedback",
+ "settings": "settings",
+}
+
+
+def _backend_tab(tab: str) -> str:
+ return _BACKEND_TAB.get(tab) or "gen"
+
+
+# Provider persistence keys (model_registry._PROVIDER_KEYS) β NOT the same as
+# report-folder keys above: the Vision tab persists under "vlm" (provider_vlm),
+# while its reports live in the "vis" folder. Calling set_saved_provider("vis")
+# would silently no-op (no _PROVIDER_KEYS entry), so provider saves MUST go
+# through this map.
+_PROVIDER_TAB = {
+ "general": "gen",
+ "rag": "rag",
+ "deep_research": "dr",
+ "vision": "vlm",
+ "stt": "stt",
+ "data": "data",
+ # KB's provider/model persist under the embed slots (provider_embed /
+ # model_embed) β the tab maps to "embed" like the STT tab maps to "stt".
+ "kb": "embed",
+}
+
+
+def _provider_tab(tab: str) -> str:
+ return _PROVIDER_TAB.get(tab) or _backend_tab(tab)
+
+
+# smolagents' LocalPythonExecutor `timeout_seconds` default β the AUTO value
+# the General / RAG / Deep Research "Exec timeout" controls resolve to
+# (build_smol_agent passes executor_kwargs only when the control holds an
+# explicit number, so this is what actually runs when it is empty).
+_SMOLAGENTS_EXEC_TIMEOUT_DEFAULT = 30
+
+
+def _auto_defaults() -> dict:
+ """The concrete values the chat tabs' "auto" controls resolve to, keyed
+ by CLIENT tab name (same keys as savedStepBudgets / savedExecutionTimeout).
+ Step budgets are the agents' *_DEFAULT_MAX_STEPS base constants (the
+ frontend scales them per the LIVE model picker label, mirroring
+ mr.get_max_steps_for_model β see ui/web/src/lib/autoDefaults.js); exec
+ timeouts are the CodeAgent-path executor defaults; runTimeout None means
+ auto = no explicit whole-run deadline. All constants live here (or in the
+ agent modules they reference), never duplicated in the web UI."""
+ from agents import (
+ data_analysis,
+ deep_research_agent,
+ general_agent,
+ rag_agent,
+ )
+
+ return {
+ "stepBudgets": {
+ "general": general_agent.GENERAL_AGENT_DEFAULT_MAX_STEPS,
+ "rag": rag_agent.RAG_AGENT_DEFAULT_MAX_STEPS,
+ "rag_searcher": rag_agent.SEARCHER_DEFAULT_MAX_STEPS,
+ "deep_research": deep_research_agent.MANAGER_DEFAULT_MAX_STEPS,
+ "deep_research_search": deep_research_agent.SEARCH_AGENT_DEFAULT_MAX_STEPS,
+ "data": mr.DATA_AGENT_MAX_STEPS,
+ "data_worker": data_analysis.DATA_WORKER_DEFAULT_MAX_STEPS,
+ },
+ "execTimeout": {
+ "general": _SMOLAGENTS_EXEC_TIMEOUT_DEFAULT,
+ "rag": _SMOLAGENTS_EXEC_TIMEOUT_DEFAULT,
+ "deep_research": _SMOLAGENTS_EXEC_TIMEOUT_DEFAULT,
+ "data": data_analysis.DATA_EXECUTION_TIMEOUT_DEFAULT,
+ },
+ "runTimeout": None,
+ }
+
+
+# Per-tab context-window persistence keys β DERIVED from the backend's own
+# _CONTEXT_WINDOW_KEYS (gen/rag/data/dr/vlm) through the same clientβbackend
+# mapping as _PROVIDER_TAB (vision β vlm), so a context-window key added to
+# model_registry is automatically exposed here instead of needing a second
+# hand-maintained map to stay in sync. The five chat tabs that run an
+# LLM/VLM each get their own n_ctx dropdown in Settings.
+_CTX_WINDOW_TABS = {
+ client: backend
+ for client, backend in _PROVIDER_TAB.items()
+ if backend in mr._CONTEXT_WINDOW_KEYS
+}
+
+
+def _ctx_window_payload() -> dict:
+ """The per-tab context-window dropdown contract β the dropdown options
+ are the CONTEXT_WINDOW_OPTIONS LABELS (the label IS the value the UI
+ posts back β the backend maps it to the token count), and savedCtxWindow
+ holds each chat tab's currently-saved label so its dropdown initializes
+ to whatever was last chosen. Shared by /api/meta (the chat panes' shared
+ startup payload) and the /api/settings-family endpoint β the helper IS
+ the contract, so the two endpoints can never drift."""
+ return {
+ "contextWindowOptions": list(mr.CONTEXT_WINDOW_OPTIONS.keys()),
+ "savedCtxWindow": {
+ client: mr.get_saved_context_window_label(backend)
+ for client, backend in _CTX_WINDOW_TABS.items()
+ },
+ }
+
+
+def _i18n_dict():
+ from ui.i18n import LANGUAGES # dicts only β lightweight, no UI framework
+
+ return LANGUAGES
+
+
+def _lang(lang_key: str) -> dict:
+ d = _i18n_dict()
+ return d.get(lang_key) or d.get("kh") or {}
+
+
+def _tab_label(tab_key: str, lang_key: str) -> str:
+ i18n_key = next((k for (_t, _i, k) in TABS if _t == tab_key), None)
+ if i18n_key:
+ return _lang(lang_key).get(i18n_key, tab_key)
+ return tab_key
+
+
+def _reset_agents_for(backend_tab: str):
+ """Drop the cached agent for the affected tab so the next run rebuilds
+ with the newly chosen provider/model (mirrors the Gradio reload handlers)."""
+ try:
+ if backend_tab == "gen":
+ from agents import general_agent
+
+ general_agent.reset_agent()
+ elif backend_tab == "rag":
+ from agents import rag_agent
+
+ rag_agent.reset_agent()
+ elif backend_tab == "dr":
+ from agents import deep_research_agent
+
+ deep_research_agent.reset_agent()
+ elif backend_tab == "data":
+ # Data's agent is cached per model choice β a header provider/model
+ # switch must drop it so the next run rebuilds with the new pick
+ # (mirrors the Gradio do_reload_data handler).
+ from agents import data_analysis
+
+ data_analysis.reset_agent()
+ except Exception:
+ pass
+
+
+_SESSION_TOKEN = os.environ.get("LOCALAILAB_SESSION_TOKEN") or secrets.token_urlsafe(32)
+
+
+def get_session_token() -> str:
+ """Return the active local session authentication token."""
+ return _SESSION_TOKEN
+
+
+app = FastAPI(title="LocalAiLab Assistant", docs_url=None, redoc_url=None)
+
+# Explicit CORS: restrict origins to local loopback and webview custom schemes
+app.add_middleware(
+ CORSMiddleware,
+ allow_origin_regex=r"^(http://(127\.0\.0\.1|localhost)(:\d+)?|null|app://.*|pywebview://.*)$",
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+
+@app.middleware("http")
+async def verify_session_token(request: Request, call_next):
+ path = request.url.path
+ # Allow static assets, health check, favicon, and root SPA HTML without token
+ if (
+ path.startswith("/assets/")
+ or path in ("/favicon.png", "/api/health")
+ or not path.startswith("/api/")
+ ):
+ return await call_next(request)
+
+ token = request.headers.get("X-Session-Token") or request.query_params.get("token")
+ if not token or token != _SESSION_TOKEN:
+ return JSONResponse(
+ {"ok": False, "message": "Unauthorized: invalid or missing session token"},
+ status_code=401,
+ )
+ return await call_next(request)
+
+
+# βοΏ½οΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+# JSON API
+# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+@app.get("/api/health")
+def health():
+ from ui.branding import APP_NAME_EN, APP_NAME_KH, APP_VERSION
+
+ return {"ok": True, "app": APP_NAME_EN, "app_kh": APP_NAME_KH, "version": APP_VERSION}
+
+
+@app.get("/api/meta")
+def meta():
+ from backend import knowledge_base as kb
+ from ui.branding import APP_NAME_EN, APP_NAME_KH, APP_VERSION
+
+ lang_key = str(user_config.USER_CONFIG.get("lang", "kh")) or "kh"
+ app_name = APP_NAME_KH if lang_key == "kh" else APP_NAME_EN
+ kb_themes, kb_subthemes = kb.get_existing_themes_and_subthemes()
+ models = {
+ label: list(mr.get_model_options_for_provider(sentinel, "llm").keys())
+ for label, sentinel in _PROVIDER_OPTIONS.items()
+ }
+ # The Data tab's model lists β the LLM chat tabs' list with the
+ # verified-ladder exclusions applied (a GGUF whose Data harness leg
+ # failed is still fine for General / RAG / Deep Research but is NOT
+ # offered on the Data tab β see
+ # mr.is_data_tab_excluded_model / DATA_TAB_EXCLUDED_MODEL_MARKERS).
+ data_models = {
+ label: [
+ m for m in list(mr.get_model_options_for_provider(sentinel, "llm").keys())
+ if not mr.is_data_tab_excluded_model(m)
+ ]
+ for label, sentinel in _PROVIDER_OPTIONS.items()
+ }
+ # Per-tab saved provider/model for the migrated chat tabs (client-facing
+ # keys) β the header pickers rebind per active tab, like Gradio's
+ # per-tab dropdowns.
+ saved_provider = {}
+ saved_model = {}
+ for client_key, backend_key, model_type, provider_map in (
+ ("general", "gen", "llm", _PROVIDER_OPTIONS),
+ ("rag", "rag", "llm", _PROVIDER_OPTIONS),
+ ("deep_research", "dr", "llm", _PROVIDER_OPTIONS),
+ ("vision", "vlm", "vlm", _VLM_PROVIDER_OPTIONS),
+ ("data", "data", "llm", _PROVIDER_OPTIONS),
+ ):
+ sentinel = mr.get_saved_provider(backend_key)
+ saved_provider[client_key] = mr.get_provider_label(provider_map, sentinel)
+ _choices, default_model = mr.get_model_dropdown_defaults(backend_key, model_type)
+ # The user's LAST model pick (persisted label) when it's still a
+ # valid choice for the tab's provider; otherwise the provider's
+ # default β a GGUF file removed / CSV edited between sessions must
+ # degrade to a valid model, never a stale label.
+ saved_label = mr.get_saved_model(backend_key)
+ saved_model[client_key] = saved_label if saved_label in _choices else default_model
+ vlm_models = {
+ label: list(mr.get_model_options_for_provider(sentinel, "vlm").keys())
+ for label, sentinel in _VLM_PROVIDER_OPTIONS.items()
+ }
+ # STT β provider dropdown (STT_PROVIDER_OPTIONS) + a flat STT model list
+ # (STT_OPTIONS labels, mirroring the Gradio stt_dd choices).
+ stt_providers = [
+ {"label": label, "value": sentinel}
+ for label, sentinel in mr.STT_PROVIDER_OPTIONS.items()
+ ]
+ stt_models = {
+ label: list(mr.get_model_options_for_provider(sentinel, "stt").keys())
+ for label, sentinel in mr.STT_PROVIDER_OPTIONS.items()
+ }
+ _stt_choices, _stt_model_default = mr.get_model_dropdown_defaults("stt", "stt")
+ _stt_model_saved = mr.get_saved_model("stt")
+ if _stt_model_saved in _stt_choices:
+ _stt_model_default = _stt_model_saved
+ _stt_llm_choices, _stt_llm_default = mr.get_llm_dropdown_defaults("stt_report")
+ _stt_llm_saved = mr.get_saved_model("stt_report")
+ if _stt_llm_saved in _stt_llm_choices:
+ _stt_llm_default = _stt_llm_saved
+ # Embeddings β per-provider model lists (mirrors the KB tab's embed_dd).
+ embed_providers = [
+ {"label": label, "value": sentinel}
+ for label, sentinel in mr.EMBED_PROVIDER_OPTIONS.items()
+ ]
+ embed_models = {
+ label: list(mr.get_model_options_for_provider(sentinel, "embed").keys())
+ for label, sentinel in mr.EMBED_PROVIDER_OPTIONS.items()
+ }
+ _embed_choices, _embed_default = mr.get_model_dropdown_defaults("embed", "embed")
+ _embed_saved = mr.get_saved_model("embed")
+ if _embed_saved in _embed_choices:
+ _embed_default = _embed_saved
+ return {
+ "app": {"name": app_name, "version": APP_VERSION, "lang": lang_key},
+ # True on the very first launch (the onboarding was never dismissed)
+ # β the SPA lands on the Settings tab and shows the setup popup.
+ "firstRun": user_config.is_first_run(),
+ "tabs": [
+ {"key": key, "icon": icon, "label": _tab_label(key, lang_key)}
+ for (key, icon, _k) in TABS
+ ],
+ "providers": [
+ {"label": label, "value": sentinel}
+ for label, sentinel in _PROVIDER_OPTIONS.items()
+ ],
+ "vlmProviders": [
+ {"label": label, "value": sentinel}
+ for label, sentinel in _VLM_PROVIDER_OPTIONS.items()
+ ],
+ "vlmModels": vlm_models,
+ "savedProvider": saved_provider,
+ "models": models,
+ "dataModels": data_models,
+ "savedModel": saved_model,
+ # STT tab
+ "sttProviders": stt_providers,
+ "sttModels": stt_models,
+ "savedStt": {
+ "provider": mr.get_provider_label(mr.STT_PROVIDER_OPTIONS, mr.get_saved_provider("stt")),
+ "model": _stt_model_default,
+ "llmProvider": mr.get_provider_label(mr.LLM_PROVIDER_OPTIONS, mr.get_saved_provider("stt_report")),
+ "llmModel": _stt_llm_default,
+ },
+ # KB tab
+ "embedProviders": embed_providers,
+ "embedModels": embed_models,
+ "savedEmbed": {
+ "provider": mr.get_provider_label(mr.EMBED_PROVIDER_OPTIONS, mr.get_saved_provider("embed")),
+ "model": _embed_default,
+ },
+ "visualRetrievers": list(mr.VISUAL_RETRIEVER_OPTIONS.keys()),
+ "themes": kb_themes or [],
+ "subthemes": kb_subthemes or [],
+ # STT language picker (value β label) β DERIVED from the registry's
+ # STT_LANG_OPTIONS constant (the single source of truth, shared with
+ # the /api/settings/save stt_lang validator) so the option list and
+ # the persistence contract can never drift. 'auto' is the only value
+ # whose label isn't just the capitalized name.
+ "sttLanguages": [
+ {
+ "value": v,
+ "label": "Auto-detect" if v == "auto" else v.capitalize(),
+ }
+ for v in mr.STT_LANG_OPTIONS
+ ],
+ # Data Analysis tab
+ "analysisTypes": ["exploratory", "sales", "customer", "financial", "payroll"],
+ "reportBaseDir": mr.REPORT_BASE_DIR,
+ # Per-tab agentic step budgets (Max Steps / Search steps) β the chat
+ # panes initialize their step controls from these on mount. A value
+ # is the user's explicit budget; None = AUTO (model-scaled default).
+ "savedStepBudgets": {
+ "general": mr.get_saved_agent_steps("gen"),
+ "rag": mr.get_saved_agent_steps("rag"),
+ "rag_searcher": mr.get_saved_sub_agent_steps("rag"),
+ "deep_research": mr.get_saved_agent_steps("dr"),
+ "deep_research_search": mr.get_saved_sub_agent_steps("dr"),
+ "deep_research_timeout": mr.get_saved_agent_run_timeout("dr"),
+ "data": mr.get_saved_agent_steps("data"),
+ "data_worker": mr.get_saved_sub_agent_steps("data"),
+ },
+ # Per-tab agentic execution timeout (each agentic tab's "Exec
+ # timeout" control β General / RAG / Deep Research / Data) β an int
+ # is the user's per-step code-executor timeout; null = AUTO (the
+ # agent factory's default). Same shape as savedStepBudgets so panes
+ # initialize their controls from meta.
+ "savedExecutionTimeout": {
+ "general": mr.get_saved_execution_timeout("gen"),
+ "rag": mr.get_saved_execution_timeout("rag"),
+ "deep_research": mr.get_saved_execution_timeout("dr"),
+ "data": mr.get_saved_execution_timeout("data"),
+ },
+ # Per-tab generation RUN timeout (each chat tab's Generation Settings
+ # "Timeout" control; Deep Research was the first to expose it) β an
+ # int is the user's whole-run wall-clock deadline in seconds; null =
+ # no explicit deadline. Keyed by CLIENT tab name (the panes read
+ # app.meta.savedRunTimeout[tab]); the backend keys are gen/rag/dr/vlm/data.
+ "savedRunTimeout": {
+ "general": mr.get_saved_agent_run_timeout("gen"),
+ "rag": mr.get_saved_agent_run_timeout("rag"),
+ "deep_research": mr.get_saved_agent_run_timeout("dr"),
+ "vision": mr.get_saved_agent_run_timeout("vlm"),
+ "data": mr.get_saved_agent_run_timeout("data"),
+ },
+ # Whether the RAG tab's resource-intensive visual path (the agentic
+ # `visual_retriever` page-image tool + the VLM grounding pass) is
+ # enabled β DEFAULT OFF (pure text-retrieval + text-LLM pipeline).
+ "savedVisualRetrieval": mr.get_rag_visual_retrieval(),
+ # The concrete values the chat tabs' "auto" controls resolve to β
+ # the web UI renders these IN the empty fields instead of the opaque
+ # word "auto", so the user sees the real default (e.g. "8" steps, a
+ # "no limit" run). stepBudgets are the agents' *_DEFAULT_MAX_STEPS
+ # BASE constants (Python-owned); the frontend applies the same
+ # model-size scaling as mr.get_max_steps_for_model against the LIVE
+ # picker label (ui/web/src/lib/autoDefaults.js) so the shown value
+ # stays accurate after a mid-session model switch. execTimeout is
+ # smolagents' LocalPythonExecutor default (30s β build_smol_agent
+ # passes nothing when the control is None) for the CodeAgent-path
+ # tabs, and Data's own DATA_EXECUTION_TIMEOUT_DEFAULT (120s).
+ # runTimeout None = auto means "no explicit deadline β the run
+ # finishes naturally" (the frontend renders it as "no limit").
+ "autoDefaults": _auto_defaults(),
+ # NOTE: the llama-server per-request timeout is NOT in /api/meta β it
+ # is a GLOBAL setting (one shared llama-server subprocess) edited
+ # ONLY from the Settings tab (its number input), persisted under the
+ # 'llama_server_timeout' user_config key and exposed via /api/settings.
+ # Per-tab context window (n_ctx) β RELOCATED into each relevant
+ # tab's settings (the four chat panes' collapsed Generation Settings
+ # section + the Data tab card), so it must ride the shared /api/meta
+ # payload the panes initialize from, not just /api/settings (the
+ # chat panes read app.meta β a restart would otherwise render the
+ # dropdowns with zero options).
+ **_ctx_window_payload(),
+ # App-wide Alt+Delete clear-confirmation threshold (messages) β the
+ # chat panes' confirm() closures read this live at keypress time, so
+ # a Settings-tab change takes effect without a restart.
+ "clearConfirmMin": mr.get_saved_clear_confirm_min() or mr.CLEAR_CONFIRM_MIN_DEFAULT,
+ # STT tab's π§ Reduce Noise strength preset β the picker initializes
+ # from this on mount, so the tab reopens on the user's last pick.
+ "denoiseStrength": mr.get_saved_denoise_strength(),
+ # STT tab's transcription language β the language dropdown
+ # initializes from this on mount, so the tab reopens on the user's
+ # last pick (auto / english / khmer / french / chinese / japanese).
+ "sttLanguage": mr.get_saved_stt_lang(),
+ "sttMicDevice": mr.get_saved_stt_mic(),
+ # Set by packaging later; when non-empty the placeholder tabs show a
+ # "Open Classic UI" button pointing here.
+ "classicUrl": "",
+ }
+
+
+@app.get("/api/i18n")
+def i18n(lang: str = "kh"):
+ d = _i18n_dict()
+ return d.get(lang) or d.get("kh") or {}
+
+
+@app.post("/api/first-run/dismiss")
+async def first_run_dismiss():
+ """Mark the first-run onboarding as seen (the Settings-tab landing + popup
+ shown on the very first launch). Idempotent β called when the user
+ dismisses the popup, so it never shows again on later launches."""
+ user_config.mark_first_run_done()
+ return {"ok": True}
+
+
+@app.get("/api/model-notice")
+def model_notice(provider: str = "", model: str = "", type: str = "llm", lang: str = "kh"):
+ """The 'already downloaded?' notice for the header model picker β the web
+ port of report_tools.get_model_download_notice, the single source of
+ truth. Returns {ok, notice}; the notice is empty when no model is
+ selected or the lookup fails."""
+ if not model:
+ return {"ok": True, "notice": ""}
+ from backend.report_tools import get_model_download_notice # Gradio-free
+
+ try:
+ notice = get_model_download_notice(
+ provider or "", model, option_type=type or "llm", lang_key=lang or "kh"
+ )
+ except Exception:
+ notice = ""
+ return {"ok": True, "notice": notice}
+
+
+# ββ Model pre-download endpoint βββββββββββββββββββββββββββββββββββββββββ
+# Triggers a background download of a HuggingFace model (transformers or
+# GGUF preset) so the "Download Now" button can kick off the download
+# without waiting for the first chat message. Uses its OWN shared state
+# (separate from the component _DL_STATE) so component and model downloads
+# never block each other.
+_MODEL_DL_STATE: dict = {
+ "running": False,
+ "model_id": "",
+ "model_label": "",
+ "progress": None,
+ "dl_mb": "",
+ "total_mb": "",
+ "speed_mb": "",
+ "label": "",
+ "status_line": "",
+ "done": False,
+ "error": "",
+ "cancelled": False,
+}
+_MODEL_DL_LOCK = threading.Lock()
+
+# Cancellation signal for an in-flight model download. Set by
+# POST /api/model-download-cancel; checked inside _ModelDownloadProgress so the
+# blocking hf_hub_download call is aborted mid-stream.
+_MODEL_DL_CANCEL = threading.Event()
+
+
+class _ModelDownloadCancelled(Exception):
+ """Raised from the tqdm callback to abort an in-flight download."""
+ pass
+
+
+# Module-level cumulative tracking for snapshot_download's multi-tqdm pattern.
+# huggingface_hub.snapshot_download (>= 1.25) does NOT pass the user's
+# tqdm_class to individual file downloads. Instead it:
+#
+# 1. Creates two tqdm instances with the user's tqdm_class:
+# - transfer_progress total=0 (Xet transfer bytes)
+# - reconstruct_progress total=0 (byte reconstruction)
+# 2. Wraps each hf_hub_download in an _AggregatedTqdm that:
+# a) Adds each file's size to reconstruct_progress.total (total grows)
+# b) Forwards update(n) bytes to reconstruct_progress.update(n)
+# 3. Creates a thread-map tqdm for hf_thread_map with total=N (file count)
+#
+# For hf_hub_download (GGUF path), each file gets its own tqdm with
+# total=file_size β standard per-instance accumulation.
+#
+# The tricky part: reconstruct_progress starts with total=0, so a cached
+# "is_real_file" flag computed at __init__ stays False forever, ignoring
+# all update() calls. We solve this with LAZY registration: _is_registered
+# starts False and _ensure_registered() promotes it when total first becomes
+# positive (or grows further via _AggregatedTqdm).
+_DL_ACCUM_BYTES = 0 # cumulative bytes downloaded across real files
+_DL_ACCUM_TOTAL = 0 # sum of sizes of real files we have registered
+_DL_ACCUM_START = 0.0 # time.time() when the first real tqdm was created
+_DL_ACCUM_LAST_UPDATE = 0.0 # throttle for state writes
+
+
+def _dl_accum_reset():
+ global _DL_ACCUM_BYTES, _DL_ACCUM_TOTAL, _DL_ACCUM_START, _DL_ACCUM_LAST_UPDATE
+ _DL_ACCUM_BYTES = 0
+ _DL_ACCUM_TOTAL = 0
+ _DL_ACCUM_START = 0.0
+ _DL_ACCUM_LAST_UPDATE = 0.0
+
+
+def _dl_accum_push_state(desc: str = ""):
+ """Write the cumulative progress into _MODEL_DL_STATE (throttled)."""
+ global _DL_ACCUM_LAST_UPDATE
+ now = time.time()
+ if now - _DL_ACCUM_LAST_UPDATE < 0.25 and _DL_ACCUM_BYTES < _DL_ACCUM_TOTAL:
+ return # throttle
+ _DL_ACCUM_LAST_UPDATE = now
+
+ total = _DL_ACCUM_TOTAL
+ done = _DL_ACCUM_BYTES
+ pct = int(min(100, max(0, (done / total * 100)))) if total > 0 else 0
+ elapsed = now - _DL_ACCUM_START if _DL_ACCUM_START else 0.0
+ speed = (done / elapsed / (1024 * 1024)) if elapsed > 0.1 else 0.0
+
+ total_mb = (total / (1024 * 1024)) if total else 0.0
+ dl_mb = (done / (1024 * 1024))
+ d = desc or "model files"
+ if d.startswith("Downloading "):
+ d = d[12:]
+ line = f"Downloading {d} ({pct}%)"
+ if total_mb > 0:
+ line += f" Β· {dl_mb:.1f} / {total_mb:.1f} MB"
+ if speed > 0:
+ line += f" ({speed:.1f} MB/s)"
+
+ with _MODEL_DL_LOCK:
+ _MODEL_DL_STATE["progress"] = pct
+ _MODEL_DL_STATE["dl_mb"] = f"{dl_mb:.1f}" if total_mb > 0 else ""
+ _MODEL_DL_STATE["total_mb"] = f"{total_mb:.1f}" if total_mb > 0 else ""
+ _MODEL_DL_STATE["speed_mb"] = f"{speed:.1f}" if speed > 0 else ""
+ _MODEL_DL_STATE["label"] = d
+ _MODEL_DL_STATE["status_line"] = line
+
+
+# Minimum total bytes to register a tqdm as a "real file download".
+# Filters out metadata phases (total=0) and file-count progress bars (total=N)
+# that huggingface_hub creates before the actual per-file downloads start.
+_DL_MIN_FILE_BYTES = 1024
+
+
+class _ModelDownloadProgress:
+ """tqdm-compatible progress tracker that updates _MODEL_DL_STATE in real-time.
+
+ Two usage patterns:
+
+ 1. **hf_hub_download (GGUF path)**: each file gets its own instance with
+ total=file_size. Registered immediately in __init__.
+
+ 2. **snapshot_download (HF model path)**: the user's tqdm_class is used for
+ ``reconstruct_progress`` which starts with total=0. ``_AggregatedTqdm``
+ (huggingface_hub internal) later sets ``self.total`` to the cumulative
+ file sizes and calls ``self.update(n)`` with cumulative bytes. We detect
+ the total transition via _ensure_registered() and start tracking.
+ """
+
+ def __init__(self, *args, **kwargs):
+ global _DL_ACCUM_BYTES, _DL_ACCUM_TOTAL, _DL_ACCUM_START
+ self.total = kwargs.get("total") or 0
+ self.n = kwargs.get("initial") or 0
+ self.desc = kwargs.get("desc") or ""
+ self.start_time = time.time()
+ self.last_time = self.start_time
+ self._instance_n_at_start = 0 # snapshot of cumulative bytes at creation
+ self._is_registered = False # whether registered in _DL_ACCUM_TOTAL
+ self._registered_total = 0 # total at time of registration (for delta)
+
+ # Immediate registration for hf_hub_download path (total known at init)
+ if self.total >= _DL_MIN_FILE_BYTES:
+ if _DL_ACCUM_START == 0.0:
+ _DL_ACCUM_START = self.start_time
+ self._instance_n_at_start = _DL_ACCUM_BYTES
+ _DL_ACCUM_TOTAL += self.total
+ self._registered_total = self.total
+ self._is_registered = True
+
+ def _ensure_registered(self):
+ """Lazily register when total first becomes positive.
+
+ snapshot_download creates tqdm(total=0) then _AggregatedTqdm later
+ sets self.total to the cumulative file sizes. We detect this and
+ register lazily. Also handles total growing further as more files
+ are added to _AggregatedTqdm.
+ """
+ global _DL_ACCUM_BYTES, _DL_ACCUM_TOTAL, _DL_ACCUM_START
+ if self._is_registered:
+ # Total may have grown β update the delta in _DL_ACCUM_TOTAL.
+ if self.total > self._registered_total:
+ _DL_ACCUM_TOTAL += (self.total - self._registered_total)
+ self._registered_total = self.total
+ return
+ if self.total >= _DL_MIN_FILE_BYTES:
+ if _DL_ACCUM_START == 0.0:
+ _DL_ACCUM_START = self.start_time
+ self._instance_n_at_start = _DL_ACCUM_BYTES
+ _DL_ACCUM_TOTAL += self.total
+ self._registered_total = self.total
+ self._is_registered = True
+
+ # ββ tqdm interface ββββββββββββββββββββββββββββββββββββββββββ
+
+ def update(self, n=1):
+ if _MODEL_DL_CANCEL.is_set():
+ raise _ModelDownloadCancelled()
+ global _DL_ACCUM_BYTES
+ self.n += n
+ self._ensure_registered()
+ if self._is_registered:
+ _DL_ACCUM_BYTES = self._instance_n_at_start + self.n
+ now = time.time()
+ if now - self.last_time >= 0.25 or (self.total and self.n >= self.total):
+ _dl_accum_push_state(self.desc)
+ self.last_time = now
+
+ def refresh(self):
+ """Called by huggingface_hub after update(); push current state."""
+ self._ensure_registered()
+ if self._is_registered:
+ global _DL_ACCUM_BYTES
+ _DL_ACCUM_BYTES = self._instance_n_at_start + self.n
+ _dl_accum_push_state(self.desc)
+ self.last_time = time.time()
+
+ def set_description(self, desc, refresh=True):
+ """huggingface_hub sets a new description mid-download."""
+ self.desc = desc or self.desc
+ if self._is_registered:
+ _dl_accum_push_state(self.desc)
+
+ def set_postfix(self, *args, **kwargs):
+ """huggingface_hub may set postfix info β accept silently."""
+ pass
+
+ def set_postfix_str(self, s, refresh=True):
+ """huggingface_hub's Xet progress reporting calls this."""
+ pass
+
+ @property
+ def format_dict(self):
+ """Some huggingface_hub code reads bar.format_dict for rate info."""
+ return {"rate": 0}
+
+ def close(self):
+ self._ensure_registered()
+ if self._is_registered:
+ global _DL_ACCUM_BYTES
+ _DL_ACCUM_BYTES = self._instance_n_at_start + self.n
+ if self.total and self.n >= self.total:
+ global _DL_ACCUM_LAST_UPDATE
+ _DL_ACCUM_LAST_UPDATE = 0 # reset throttle
+ _dl_accum_push_state(self.desc)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ self.close()
+
+
+def _model_download_worker(model_id: str):
+ """Background worker that pre-downloads a HuggingFace or GGUF model."""
+ _dl_accum_reset() # clear cumulative counters from any prior download
+ _MODEL_DL_CANCEL.clear() # allow a fresh cancel signal for this run
+ # Make sure xet is off for this download (see module-level note). The env var
+ # is read by huggingface_hub at import time, but hf may have been imported
+ # earlier in this process, so force the live flag on the already-loaded module.
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
+ try:
+ import huggingface_hub
+ huggingface_hub.constants.HF_HUB_DISABLE_XET = True
+ except Exception:
+ pass
+ try:
+ from backend import model_registry as mr, models as mdl
+ with _MODEL_DL_LOCK:
+ _MODEL_DL_STATE["status_line"] = "Starting downloadβ¦"
+ _MODEL_DL_STATE["label"] = model_id
+ _MODEL_DL_STATE["progress"] = 0
+
+ # If it's a quant-pinned GGUF or GGUF repo
+ if (
+ "#" in model_id
+ or str(model_id).lower().endswith(".gguf")
+ or model_id in mr.PRESET_GGUF_MODELS.values()
+ or model_id in mr.PRESET_GGUF_VLM_MODELS.values()
+ or model_id in mr.PRESET_GGUF_EMBED_MODELS.values()
+ ):
+ from backend import llama_backend
+ with _MODEL_DL_LOCK:
+ _MODEL_DL_STATE["status_line"] = "Downloading GGUF model filesβ¦"
+ llama_backend.resolve_or_download_gguf_model(model_id, tqdm_class=_ModelDownloadProgress)
+ else:
+ import huggingface_hub as hf
+ hf.snapshot_download(
+ repo_id=model_id,
+ tqdm_class=_ModelDownloadProgress,
+ )
+
+ with _MODEL_DL_LOCK:
+ _MODEL_DL_STATE["progress"] = 100
+ _MODEL_DL_STATE["status_line"] = "Download complete"
+ _MODEL_DL_STATE["done"] = True
+ except _ModelDownloadCancelled:
+ with _MODEL_DL_LOCK:
+ _MODEL_DL_STATE["cancelled"] = True
+ _MODEL_DL_STATE["running"] = False
+ _MODEL_DL_STATE["done"] = False
+ _MODEL_DL_STATE["error"] = ""
+ _MODEL_DL_STATE["status_line"] = "Download cancelled"
+ except Exception as e:
+ with _MODEL_DL_LOCK:
+ _MODEL_DL_STATE["error"] = str(e)
+ _MODEL_DL_STATE["status_line"] = f"β Error: {e}"
+ finally:
+ with _MODEL_DL_LOCK:
+ _MODEL_DL_STATE["running"] = False
+
+
+@app.post("/api/model-download")
+async def start_model_download(payload: dict):
+ """POST /api/model-download β trigger a background download of a
+ HuggingFace or GGUF model. The model_id is the HF repo id or quant pin (e.g.
+ 'google/gemma-4-E2B-it-qat-q4_0-gguf'). Returns {ok, running}."""
+ model_id = (payload.get("model_id") or "").strip()
+ model_label = (payload.get("model_label") or model_id).strip()
+ if not model_id:
+ return JSONResponse({"ok": False, "message": "model_id is required"}, status_code=400)
+ with _MODEL_DL_LOCK:
+ if _MODEL_DL_STATE["running"]:
+ return JSONResponse({"ok": False, "message": "a model download is already running"}, status_code=409)
+ _MODEL_DL_STATE["running"] = True
+ _MODEL_DL_STATE["model_id"] = model_id
+ _MODEL_DL_STATE["model_label"] = model_label
+ _MODEL_DL_STATE["progress"] = 0
+ _MODEL_DL_STATE["dl_mb"] = ""
+ _MODEL_DL_STATE["total_mb"] = ""
+ _MODEL_DL_STATE["speed_mb"] = ""
+ _MODEL_DL_STATE["label"] = model_label
+ _MODEL_DL_STATE["status_line"] = "Starting downloadβ¦"
+ _MODEL_DL_STATE["done"] = False
+ _MODEL_DL_STATE["error"] = ""
+ _MODEL_DL_STATE["cancelled"] = False
+ _MODEL_DL_CANCEL.clear()
+ threading.Thread(target=_model_download_worker, args=(model_id,), daemon=True).start()
+ return {"ok": True, "running": True}
+
+
+@app.post("/api/model-download-cancel")
+async def cancel_model_download():
+ """POST /api/model-download-cancel β signal an in-flight model download
+ to abort. The blocking hf_hub_download call raises inside its tqdm
+ callback, and the worker marks the state cancelled."""
+ _MODEL_DL_CANCEL.set()
+ with _MODEL_DL_LOCK:
+ _MODEL_DL_STATE["running"] = False
+ _MODEL_DL_STATE["cancelled"] = True
+ _MODEL_DL_STATE["status_line"] = "Download cancelled"
+ return {"ok": True}
+
+
+@app.get("/api/model-download")
+async def model_download_status():
+ """GET /api/model-download β poll the model download progress."""
+ from backend import models as mdl
+ with _MODEL_DL_LOCK:
+ mid = _MODEL_DL_STATE["model_id"]
+ return {
+ "ok": True,
+ "running": _MODEL_DL_STATE["running"],
+ "model_id": mid,
+ "model_label": _MODEL_DL_STATE["model_label"],
+ "progress": _MODEL_DL_STATE["progress"],
+ "dl_mb": _MODEL_DL_STATE["dl_mb"],
+ "total_mb": _MODEL_DL_STATE["total_mb"],
+ "speed_mb": _MODEL_DL_STATE["speed_mb"],
+ "label": _MODEL_DL_STATE["label"],
+ "status_line": _MODEL_DL_STATE["status_line"],
+ "done": _MODEL_DL_STATE["done"],
+ "error": _MODEL_DL_STATE["error"],
+ "cancelled": _MODEL_DL_STATE.get("cancelled", False),
+ "cached": mdl.is_model_cached(mid) if mid else False,
+ }
+
+
+@app.get("/api/model-check")
+async def model_check(provider: str = "", model: str = "", type: str = "llm", lang: str = "kh"):
+ """GET /api/model-check β returns whether the given model is cached, its resolved model_id,
+ and estimated download size."""
+ if not model:
+ return {"ok": True, "cached": True, "needs_download": False, "size_gb": 0, "model_id": "", "label": ""}
+
+ from backend import model_registry as mr, models as mdl
+
+ if type == "vlm":
+ provider_map = mr.VLM_PROVIDER_OPTIONS
+ elif type == "stt":
+ provider_map = mr.STT_PROVIDER_OPTIONS
+ elif type == "embed":
+ provider_map = mr.EMBED_PROVIDER_OPTIONS
+ else:
+ provider_map = mr.LLM_PROVIDER_OPTIONS
+
+ provider_id = provider_map.get(provider, provider)
+
+ if provider_id in (mr.PROVIDER_HF_API, mr.PROVIDER_LITELLM):
+ return {
+ "ok": True,
+ "cached": True,
+ "needs_download": False,
+ "size_gb": 0,
+ "model_id": model,
+ "label": model,
+ }
+
+ opts = mr.get_model_options_for_provider(provider_id, type or "llm")
+ model_id = opts.get(model, model)
+ if model_id == model and model in mr.PRESET_GGUF_MODELS:
+ model_id = mr.PRESET_GGUF_MODELS[model]
+ elif model_id == model and model in mr.PRESET_GGUF_VLM_MODELS:
+ model_id = mr.PRESET_GGUF_VLM_MODELS[model]
+ elif model_id == model and model in mr.PRESET_GGUF_EMBED_MODELS:
+ model_id = mr.PRESET_GGUF_EMBED_MODELS[model]
+ elif model_id == model and model in mr.PRESET_GGUF_STT_MODELS:
+ model_id = mr.PRESET_GGUF_STT_MODELS[model]
+
+ if provider_id == mr.PROVIDER_SERVER and os.path.isfile(model_id):
+ return {
+ "ok": True,
+ "cached": True,
+ "needs_download": False,
+ "size_gb": 0,
+ "model_id": model_id,
+ "label": model,
+ }
+
+ cached = mdl.is_model_cached(model_id)
+ size_gb = mdl.get_download_size_gb(model_id)
+ needs_download = not cached and bool(model_id and ("/" in model_id or str(model_id).lower().endswith(".gguf")))
+
+ return {
+ "ok": True,
+ "cached": cached,
+ "needs_download": needs_download,
+ "size_gb": size_gb,
+ "model_id": model_id,
+ "label": model,
+ }
+
+
+@app.get("/api/disk-space")
+def disk_space():
+ """GET /api/disk-space β available disk space on the drive where user_data
+ lives. Returns {available_gb, total_gb, path} so the UI can warn when a
+ model download won't fit."""
+ from backend.paths import user_data_dir
+ try:
+ usage = shutil.disk_usage(str(user_data_dir()))
+ return {
+ "ok": True,
+ "available_gb": round(usage.free / (1024 ** 3), 1),
+ "total_gb": round(usage.total / (1024 ** 3), 1),
+ "path": str(user_data_dir()),
+ }
+ except Exception:
+ return {"ok": False, "available_gb": None, "total_gb": None, "path": ""}
+
+
+@app.post("/api/model-delete")
+async def delete_model(payload: dict):
+ """POST /api/model-delete β delete downloaded model files from disk."""
+ model_id = (payload.get("model_id") or "").strip()
+ if not model_id:
+ return JSONResponse({"ok": False, "message": "model_id is required"}, status_code=400)
+
+ deleted_files = []
+
+ # 1. Direct file on disk
+ if os.path.isfile(model_id):
+ try:
+ os.remove(model_id)
+ deleted_files.append(model_id)
+ except Exception as e:
+ return JSONResponse({"ok": False, "message": f"Failed to delete file: {e}"}, status_code=500)
+
+ # 2. GGUF pinned file / repo
+ from backend import llama_backend
+ if "#" in model_id:
+ parts = model_id.split("#")
+ for part in parts[1:]:
+ if part.lower().endswith(".gguf"):
+ found = llama_backend.find_downloaded_model_file(part)
+ if found and os.path.isfile(found):
+ try:
+ os.remove(found)
+ deleted_files.append(found)
+ except Exception:
+ pass
+ repo_id = parts[0]
+ else:
+ repo_id = model_id
+
+ if repo_id in llama_backend.KNOWN_GGUF_REPOS:
+ info = llama_backend.KNOWN_GGUF_REPOS[repo_id]
+ for key in ("main", "mmproj"):
+ fn = info.get(key)
+ if fn:
+ found = llama_backend.find_downloaded_model_file(fn)
+ if found and os.path.isfile(found):
+ try:
+ os.remove(found)
+ deleted_files.append(found)
+ except Exception:
+ pass
+
+ # 3. Check user_data/gguf_models/repo--name
+ from backend.paths import user_data_dir
+ default_dir = user_data_dir() / "gguf_models" / repo_id.replace("/", "--")
+ if default_dir.exists() and default_dir.is_dir():
+ try:
+ shutil.rmtree(str(default_dir))
+ deleted_files.append(str(default_dir))
+ except Exception:
+ pass
+
+ # 4. Hugging Face cache
+ try:
+ import huggingface_hub as hf
+ cache_info = hf.scan_cache_dir()
+ for repo in cache_info.repos:
+ if repo.repo_id == repo_id or repo.repo_id == model_id:
+ hashes = [r.commit_hash for r in repo.revisions]
+ if hashes:
+ del_strategy = cache_info.delete_revisions(*hashes)
+ del_strategy.execute()
+ deleted_files.append(f"HF cache: {repo.repo_id}")
+ except Exception:
+ pass
+
+ return {"ok": True, "deleted": deleted_files, "model_id": model_id}
+
+
+@app.post("/api/settings")
+async def save_settings(payload: dict):
+ tab = _provider_tab(payload.get("tab", "general"))
+ provider_label = payload.get("provider_label")
+ model_label = payload.get("model_label")
+ try:
+ if provider_label:
+ if tab == "embed":
+ sentinel = mr.EMBED_PROVIDER_OPTIONS.get(provider_label)
+ elif tab == "stt":
+ sentinel = mr.STT_PROVIDER_OPTIONS.get(provider_label)
+ elif tab == "vlm":
+ sentinel = mr.VLM_PROVIDER_OPTIONS.get(provider_label)
+ else:
+ sentinel = _PROVIDER_OPTIONS.get(provider_label)
+ if sentinel:
+ mr.set_saved_provider(tab, sentinel)
+ if tab == "embed":
+ models.unload_embed_model_fn()
+ _reset_agents_for(tab)
+ if model_label:
+ # Persist the model label too β the header picker's reload
+ # contract (savedProvider + savedModel in /api/meta). The label
+ # is validated against live choices at read time; a stale label
+ # falls back to the provider's default model.
+ mr.set_saved_model(tab, model_label)
+ # For the KB (embed) tab, also write the "embed_model" key
+ # that get_default_embed_model() reads at indexing time β the
+ # header picker saves to model_embed via set_saved_model(),
+ # but the actual model load uses embed_model.
+ if tab == "embed":
+ mr.set_embed_model(model_label)
+ models.unload_embed_model_fn()
+ _reset_agents_for(tab)
+ return {"ok": True}
+ except Exception as e: # pragma: no cover β defensive
+ return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
+
+
+@app.post("/api/agent/reset")
+async def reset_agent(payload: dict):
+ """Drop the cached agent for a tab (mirrors Gradio's clear handlers, which
+ reset the agent so a "cleared" conversation starts with empty memory)."""
+ tab = _backend_tab(payload.get("tab", "general"))
+ _reset_agents_for(tab)
+ return {"ok": True}
+
+
+@app.post("/api/upload")
+async def upload_image(request: Request):
+ """Accept a raw image body (the Vision tab's file picker POSTs the File
+ bytes directly), validate it really is an image, and stash it in a temp
+ file. Returns {path}; the WS chat handler feeds that path to
+ chat.chat_vision() (which accepts a path) and deletes it after the run."""
+ body = await request.body()
+ if not body:
+ return JSONResponse({"ok": False, "message": "empty upload"}, status_code=400)
+ if len(body) > 25 * 1024 * 1024:
+ return JSONResponse({"ok": False, "message": "image too large (25 MB max)"}, status_code=400)
+
+ import io
+ import tempfile
+ import uuid
+
+ from PIL import Image
+
+ try:
+ with Image.open(io.BytesIO(body)) as probe:
+ w, h = probe.size
+ fmt = (probe.format or "PNG").lower()
+ # verify() only validates structure β the size check stops
+ # decompression-bomb uploads before chat_vision decodes them.
+ probe.verify()
+ except Exception:
+ return JSONResponse({"ok": False, "message": "not a valid image"}, status_code=400)
+ if w * h > 50_000_000: # ~50 MP β far beyond any real photo
+ return JSONResponse({"ok": False, "message": "image dimensions too large"}, status_code=400)
+ fmt = "jpg" if fmt == "jpeg" else fmt
+ up_dir = Path(tempfile.gettempdir()) / "localailab_uploads"
+ up_dir.mkdir(parents=True, exist_ok=True)
+ path = up_dir / f"vis-{uuid.uuid4().hex}.{fmt}"
+ path.write_bytes(body)
+ return {"ok": True, "path": str(path)}
+
+
+@app.get("/api/mmproj")
+def mmproj(vlm: str = "", provider: str = ""):
+ """Choices for the Vision tab's mmproj dropdown β mirrors the Gradio
+ vlm_dd.change handler: only GGUF VLMs under a llama.cpp provider expose
+ mmproj candidates, and the auto candidate (GGUF_VLM_MMPROJ_MAP) is
+ returned as the default selection. The payload's mmproj_label is resolved
+ back to a path inside chat.chat_vision()."""
+ sentinel = _VLM_PROVIDER_OPTIONS.get(provider) or mr.get_saved_provider("vlm")
+ mid = mr.resolve_model_id(vlm, provider=sentinel, model_type="vlm")
+ choices = []
+ saved = None
+ if "llama.cpp" in provider and str(mid).lower().endswith(".gguf"):
+ candidates = mr.get_mmproj_choices_for_vlm(mid)
+ choices = list(candidates.keys())
+ auto = mr.GGUF_VLM_MMPROJ_MAP.get(mid)
+ for lbl, path in candidates.items():
+ if path == auto:
+ saved = lbl
+ break
+ return {"visible": bool(choices), "choices": choices, "saved": saved}
+
+
+def _copy_report_images(markdown: str, out_dir: Path) -> None:
+ """Copy every chart image the report markdown references into `out_dir`
+ (the report's attached folder), as well as all generated PNG charts in
+ the active report folder and mr.DATA_OUTPUT_DIR. Best-effort: a missing/
+ invalid reference, a URL, or a data: URI is skipped β never raises."""
+ import shutil
+
+ refs = re.findall(r"!\[[^\]]*\]\(\s*([^)\s]+)\s*\)", markdown or "")
+ refs += re.findall(r"
]+src=[\"']([^\"']+)[\"']", markdown or "")
+ charts = Path(mr.DATA_OUTPUT_DIR)
+ for ref in refs:
+ try:
+ ref = (ref or "").strip().strip('"').strip("'")
+ if not ref or ref.startswith(("http://", "https://", "data:")):
+ continue
+ src = Path(ref)
+ if not src.is_absolute():
+ src = charts / src.name
+ if src.is_file():
+ dst = out_dir / src.name
+ if not dst.exists():
+ shutil.copy2(src, dst)
+ except OSError:
+ pass
+
+ # Ensure all generated PNG graphs from DATA_OUTPUT_DIR are in out_dir
+ try:
+ if charts.is_dir():
+ for png in charts.glob("*.png"):
+ try:
+ dst = out_dir / png.name
+ if not dst.exists():
+ shutil.copy2(png, dst)
+ except OSError:
+ pass
+ except OSError:
+ pass
+
+ # Also copy all charts from the active report directory if different
+ try:
+ from agents import data_analysis as da
+ active = da.get_active_report_dir()
+ if active and active.is_dir() and active.resolve() != out_dir.resolve():
+ for png in active.glob("*.png"):
+ try:
+ dst = out_dir / png.name
+ if not dst.exists():
+ shutil.copy2(png, dst)
+ except OSError:
+ pass
+ except Exception:
+ pass
+
+
+@app.post("/api/reports")
+async def save_report(payload: dict):
+ """Save an answer as .docx into user_data/reports// (never auto β
+ the user clicks πΎ Save Report, same contract as the Gradio UI).
+
+ The DATA tab saves into a per-report ATTACHED FOLDER
+ (user_data/reports/data_analysis//) containing the .docx AND the
+ chart images the report references β so the images live with the report
+ instead of only in the shared charts output dir. Every other tab keeps
+ the flat per-tab folder layout."""
+ tab = _backend_tab(payload.get("tab", "general"))
+ markdown = payload.get("markdown") or ""
+ filename = payload.get("filename") or ""
+ if not markdown.strip():
+ return {"ok": False, "message": "empty answer"}
+
+ import datetime
+
+ from backend.docx_export import markdown_text_to_docx
+ from backend.paths import user_data_dir
+ from backend.report_tools import _sanitize_report_filename # Gradio-free
+
+ folder = Path(mr.REPORT_DIRS.get(tab)) if mr.REPORT_DIRS.get(tab) else (
+ user_data_dir() / "reports" / tab
+ )
+ folder.mkdir(parents=True, exist_ok=True)
+ stem = _sanitize_report_filename(filename, ".docx") if filename else ""
+ if not stem:
+ stem = datetime.datetime.now().strftime("report-%Y-%m-%d-%H%M%S")
+
+ if tab == "data":
+ # Per-report attached folder: // holding the .docx
+ # and the charts it references.
+ from agents import data_analysis as da
+ active_dir = da.get_active_report_dir()
+
+ # If no custom filename was provided and an active report folder exists
+ if not filename and active_dir and active_dir.is_dir() and active_dir.parent.resolve() == folder.resolve():
+ out_dir = active_dir
+ stem = out_dir.name
+ else:
+ out_dir = folder / stem
+ if not ((out_dir / f"{stem}.docx").exists()) and active_dir and active_dir.is_dir() and active_dir.name == stem and active_dir.parent.resolve() == folder.resolve():
+ out_dir = active_dir
+ else:
+ n = 2
+ while out_dir.exists() and (out_dir / f"{stem}.docx").exists():
+ out_dir = folder / f"{stem}-{n}"
+ n += 1
+ out_dir.mkdir(parents=True, exist_ok=True)
+ _copy_report_images(markdown, out_dir)
+ path = out_dir / f"{stem}.docx"
+ ok = bool(markdown_text_to_docx(
+ markdown, str(path),
+ image_search_dirs=[str(out_dir), mr.DATA_OUTPUT_DIR],
+ ))
+ return {"ok": ok, "path": str(path), "folder": str(out_dir)}
+ else:
+ path = folder / f"{stem}.docx"
+ n = 2
+ while path.exists():
+ path = folder / f"{stem}-{n}.docx"
+ n += 1
+ ok = bool(markdown_text_to_docx(markdown, str(path)))
+ return {"ok": ok, "path": str(path), "folder": str(folder)}
+
+
+# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+# Migrated tabs: STT / Data Analysis / Knowledge Base / Settings / About
+# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+
+def _save_uploads(files, prefix: str, with_names: bool = False) -> list:
+ """Persist uploaded File objects to a per-purpose temp dir and return
+ their paths (string paths β knowledge_base.get_file_path handles str).
+
+ The temp file itself gets a UUID prefix so same-named uploads never
+ collide, but the ORIGINAL filename travels with it: with
+ ``with_names=True`` each returned item is
+ ``{"path": str, "name": original_filename}`` so the Knowledge Base can
+ index chunks under the user's real file name instead of the long
+ ``-`` temp name."""
+ import tempfile
+ import uuid
+
+ up_dir = Path(tempfile.gettempdir()) / f"localailab_{prefix}"
+ up_dir.mkdir(parents=True, exist_ok=True)
+ paths = []
+ for f in files:
+ data = f.file.read()
+ if not data:
+ continue
+ name = Path(f.filename or "upload.bin").name
+ path = up_dir / f"{uuid.uuid4().hex}-{name}"
+ path.write_bytes(data)
+ item = str(path)
+ if with_names:
+ item = {"path": str(path), "name": name}
+ paths.append(item)
+ return paths
+
+
+def _device_label() -> str:
+ try:
+ from backend import hardware
+
+ return (hardware.HardwareManager.get_system_status().get("current_device") or "cpu").upper()
+ except Exception:
+ return "CPU"
+
+
+# ββ About βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+def _about_content(lang_key: str) -> str:
+ from ui import branding
+
+ try:
+ if lang_key == "kh":
+ base = branding.about_content_kh(_device_label(), _about_version())
+ else:
+ base = branding.about_content_en(_device_label(), _about_version())
+ except Exception:
+ base = ""
+ # Append the same venv/packages diagnostic as the Settings card so users
+ # can check package recognition without opening Settings. Single source
+ # of truth is `_env_status_text` β never a second copy of the check.
+ try:
+ env = _env_status_text(lang_key)
+ except Exception:
+ env = ""
+ if env:
+ heading = (
+ "### π§ͺ ααα·ααΆααΆααααααα·ααΈ & αααα
αα (Env & Packages)"
+ if lang_key == "kh"
+ else "### π§ͺ App Environment & Packages"
+ )
+ base = f"{base}\n\n---\n\n{heading}\n\n```text\n{env}\n```"
+ return base
+
+
+def _about_version() -> str:
+ try:
+ from ui.branding import APP_VERSION
+
+ return APP_VERSION
+ except Exception:
+ return ""
+
+
+@app.get("/api/about")
+def about(lang: str = "kh"):
+ return {"ok": True, "content": _about_content(lang or "kh"), "version": _about_version()}
+
+
+# ββ Feedback ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+@app.get("/api/feedback/diagnostics")
+def feedback_diagnostics(lang: str = "kh"):
+ """Return sanitized system diagnostics and recent log context for
+ feedback and error reporting."""
+ import platform
+ import sys
+ from backend import paths
+ from ui.branding import APP_VERSION
+
+ diag_lines = [
+ f"App: LocalAiLab v{APP_VERSION}",
+ f"OS: {platform.system()} {platform.release()} ({platform.machine()})",
+ f"Python: {sys.version.split()[0]}",
+ ]
+ # Hardware / GPU detection
+ try:
+ from backend.hardware import detect_hardware, detect_cuda
+
+ hw = detect_hardware()
+ cuda = detect_cuda()
+ if hw:
+ summary = hw.get("summary") or hw.get("cpu") or ""
+ if summary:
+ diag_lines.append(f"Hardware: {summary}")
+ if hw.get("vram_gb"):
+ diag_lines.append(f"VRAM: {hw.get('vram_gb')} GB")
+ if cuda:
+ cuda_sum = cuda.get("summary") or cuda.get("driver") or ""
+ if cuda_sum:
+ diag_lines.append(f"CUDA: {cuda_sum}")
+ except Exception:
+ pass
+
+ # Active provider / models
+ try:
+ diag_lines.append(f"Saved Provider (General): {mr.get_saved_provider('general') or 'default'}")
+ diag_lines.append(f"Saved Model (General): {mr.get_saved_model('general') or 'default'}")
+ except Exception:
+ pass
+
+ # Recent log tail if available
+ recent_logs = ""
+ try:
+ log_file = paths.user_data_dir() / "logs" / "app.log"
+ if log_file.is_file():
+ content = log_file.read_text(encoding="utf-8", errors="ignore").strip().splitlines()
+ recent_logs = "\n".join(content[-30:])
+ except Exception:
+ pass
+
+ return {
+ "ok": True,
+ "diagnostics": "\n".join(diag_lines),
+ "recent_logs": recent_logs,
+ "email_target": "aidgcreator@gmail.com",
+ }
+
+
+@app.post("/api/feedback")
+async def submit_feedback(payload: dict):
+ """Process feedback or error report, save a local copy to user_data/feedback/,
+ and return pre-built mailto and Gmail web URLs for 1-click emailing to
+ aidgcreator@gmail.com."""
+ import datetime
+ import urllib.parse
+ from backend.paths import user_data_dir
+
+ fb_type = str(payload.get("type") or "feedback").strip()
+ subject = str(payload.get("subject") or "").strip()
+ message = str(payload.get("message") or "").strip()
+ user_email = str(payload.get("email") or "").strip()
+ include_diag = bool(payload.get("include_diag", True))
+ diag_text = str(payload.get("diagnostics") or "").strip()
+ logs_text = str(payload.get("logs") or "").strip()
+
+ if not subject:
+ subject_title = f"LocalAiLab {fb_type.capitalize()} Report"
+ else:
+ subject_title = f"[LocalAiLab] [{fb_type.upper()}] {subject}"
+
+ body_parts = [
+ f"Feedback Type: {fb_type.upper()}",
+ f"Sender Email: {user_email or 'Not provided'}",
+ f"Date: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
+ "",
+ "--- Description ---",
+ message or "(No message provided)",
+ ]
+
+ if include_diag and (diag_text or logs_text):
+ body_parts.append("\n--- System Diagnostics ---")
+ if diag_text:
+ body_parts.append(diag_text)
+ if logs_text:
+ body_parts.append("\n--- Recent Logs ---")
+ body_parts.append(logs_text)
+
+ full_body = "\n".join(body_parts)
+
+ # Save local copy in user_data/feedback/
+ saved_path = ""
+ try:
+ fb_dir = user_data_dir() / "feedback"
+ fb_dir.mkdir(parents=True, exist_ok=True)
+ ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
+ fb_file = fb_dir / f"feedback-{ts}.txt"
+ fb_file.write_text(full_body, encoding="utf-8-sig")
+ saved_path = str(fb_file)
+ except Exception:
+ pass
+
+ target_email = "aidgcreator@gmail.com"
+ mailto_url = f"mailto:{target_email}?subject={urllib.parse.quote(subject_title)}&body={urllib.parse.quote(full_body)}"
+ gmail_url = f"https://mail.google.com/mail/?view=cm&fs=1&to={target_email}&su={urllib.parse.quote(subject_title)}&body={urllib.parse.quote(full_body)}"
+
+ return {
+ "ok": True,
+ "target_email": target_email,
+ "subject": subject_title,
+ "body": full_body,
+ "mailto_url": mailto_url,
+ "gmail_url": gmail_url,
+ "saved_path": saved_path,
+ }
+
+
+# ββ STT βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+@app.post("/api/stt/transcribe")
+async def stt_transcribe(request: Request):
+ """Upload an audio file + STT model label + language β transcript text
+ (the whisper generator's emoji status lines are dropped; the LAST
+ non-status yield is the complete transcript β status lines like
+ "π΅ Loadingβ¦" / "ποΈ Transcribingβ¦" must never leak into the text, and
+ the old per-chunk cumulative yields must never duplicate it)."""
+ form = await request.form()
+ files = form.getlist("audio")
+ stt_label = str(form.get("stt_label") or "").strip()
+ language = str(form.get("language") or "auto").strip()
+ paths = _save_uploads(files, "stt")
+ if not paths:
+ return JSONResponse({"ok": False, "message": "no audio uploaded"}, status_code=400)
+ try:
+ from backend import models
+
+ mid = mr.resolve_stt_model_id(stt_label) or mr.DEFAULT_STT_MODEL or None
+ transcript = ""
+ for chunk in models.transcribe_audio_stream(paths[0], language=language or None, model_id=mid):
+ text = str(chunk or "").strip()
+ if text and not text.startswith(("β³", "π", "π‘", "π΅", "ποΈ")):
+ transcript = text
+ return {"ok": True, "transcript": transcript}
+ except Exception as e: # pragma: no cover β defensive
+ return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
+ finally:
+ for p in paths:
+ try:
+ Path(p).unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+@app.post("/api/stt/analyse")
+async def stt_analyse(payload: dict):
+ """Raw transcript β structured Markdown report via the STT-tab LLM
+ (chat.analyse_transcript_to_report β empty transcript is refused
+ without any LLM call)."""
+ import backend.chat as chat
+
+ transcript = payload.get("transcript") or ""
+ model_label = payload.get("model_label") or ""
+ lang_key = payload.get("lang", "kh")
+ if not (transcript or "").strip():
+ l = _lang(lang_key)
+ return {"ok": False, "message": l.get("err_stt_no_transcript", "no transcript"), "report": ""}
+ try:
+ status, report = "", ""
+ for s, r in chat.analyse_transcript_to_report(transcript, model_label, lang_key=lang_key):
+ if r:
+ report = r
+ if s and not report:
+ status = s
+ return {"ok": True, "report": report or status, "status": status}
+ except Exception as e: # pragma: no cover β defensive
+ return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
+
+
+@app.post("/api/stt/save-txt")
+async def stt_save_txt(payload: dict):
+ """Save the raw transcript as a UTF-8-BOM .txt under user_data/reports/stt/."""
+ from backend.report_tools import _transcript_txt_path # Gradio-free
+
+ path = _transcript_txt_path(payload.get("transcript") or "", payload.get("filename") or "")
+ return {"ok": bool(path), "path": path or ""}
+
+
+@app.post("/api/stt/save-audio")
+async def stt_save_audio(request: Request):
+ """Save the current audio (recorded / uploaded / trimmed) into
+ user_data/outputs/ β the STT tab's "πΎ Save Audio" button. The optional
+ `filename` field becomes the stem when typed; otherwise the upload's OWN
+ filename is used (sanitized) β e.g. uploading `my voice.wav` saves as
+ `my voice.wav` instead of an anonymous timestamp. The extension is
+ preserved from the upload (the record/trim paths send WAV, the one
+ format every consumer reads). Sanitized + deduped exactly like report
+ saves; an unusable name falls back to the timestamped name. Never
+ auto-saved β only ever called on the button click."""
+ import datetime
+
+ form = await request.form()
+ files = form.getlist("audio")
+ filename = str(form.get("filename") or "").strip()
+ if not files or not files[0].filename:
+ return JSONResponse({"ok": False, "message": "no audio to save"}, status_code=400)
+ data = files[0].file.read()
+ if not data:
+ return JSONResponse({"ok": False, "message": "empty audio"}, status_code=400)
+ # 100 MB cap β generous for any voice recording, stops an unbounded
+ # body from being written straight to user_data/outputs (the image
+ # upload endpoint carries the same guard at 25 MB).
+ if len(data) > 100 * 1024 * 1024:
+ return JSONResponse({"ok": False, "message": "audio too large (100 MB max)"}, status_code=413)
+ try:
+ from backend.paths import user_data_dir
+ from backend.report_tools import _dedupe_report_path, _sanitize_report_filename # Gradio-free
+
+ upload_name = Path(files[0].filename or "").name
+ ext = Path(upload_name).suffix.lower()
+ if not ext or len(ext) > 5 or not ext[1:].isalnum():
+ ext = ".wav"
+ stem = _sanitize_report_filename(filename or upload_name, ext)
+ if not stem:
+ # datetime (not time.strftime): %f microseconds isn't supported
+ # by time.strftime on Windows and would raise.
+ ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S-%f")
+ stem = f"audio-{ts}"
+ out_dir = user_data_dir() / "outputs"
+ out_dir.mkdir(parents=True, exist_ok=True)
+ out_path = _dedupe_report_path(out_dir, stem, ext)
+ out_path.write_bytes(data)
+ return {"ok": True, "path": str(out_path)}
+ except Exception as e: # pragma: no cover β defensive
+ return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
+
+
+@app.post("/api/stt/denoise")
+async def stt_denoise(request: Request):
+ """Reduce background noise in the uploaded audio and return the cleaned
+ WAV bytes β the STT tab's "π§ Reduce Noise" button swaps the denoised
+ file in as the current audio, so transcribe / save / trim all use it.
+ Returns binary audio/wav on success; a JSON error otherwise (the client
+ inspects Content-Type to tell them apart)."""
+ import tempfile
+ import uuid
+
+ form = await request.form()
+ files = form.getlist("audio")
+ if not files or not files[0].filename:
+ return JSONResponse({"ok": False, "message": "no audio to denoise"}, status_code=400)
+ data = files[0].file.read()
+ if not data:
+ return JSONResponse({"ok": False, "message": "empty audio"}, status_code=400)
+ # Same cap as the save-audio endpoint β a sane recording size, never an
+ # unbounded body read into memory.
+ if len(data) > 100 * 1024 * 1024:
+ return JSONResponse({"ok": False, "message": "audio too large (100 MB max)"}, status_code=413)
+ try:
+ from backend.audio_denoise import denoise_audio, resolve_strength
+
+ # The STT tab's preset picker sends 'gentle' / 'medium' / 'aggressive'
+ # (or a raw 0β1 number); resolve_strength never raises, so a garbage
+ # pick degrades to the default instead of a 500.
+ strength = resolve_strength(form.get("strength") or "")
+
+ tmp_in = Path(tempfile.gettempdir()) / f"lal_denoise_{uuid.uuid4().hex}.wav"
+ tmp_out = Path(tempfile.gettempdir()) / f"lal_denoise_{uuid.uuid4().hex}_clean.wav"
+ tmp_in.write_bytes(data)
+ try:
+ denoise_audio(str(tmp_in), str(tmp_out), strength=strength)
+ cleaned = tmp_out.read_bytes()
+ finally:
+ # Both temp files are cleaned up on every exit path β a denoiser
+ # failure mid-write must not leak lal_denoise_* in the temp dir.
+ tmp_in.unlink(missing_ok=True)
+ tmp_out.unlink(missing_ok=True)
+ if not cleaned:
+ return JSONResponse({"ok": False, "message": "denoise produced no audio"}, status_code=500)
+ return Response(content=cleaned, media_type="audio/wav")
+ except Exception as e: # pragma: no cover β defensive
+ return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
+
+
+@app.post("/api/stt/open-outputs")
+async def stt_open_outputs():
+ """Open user_data/outputs/ (where Save Audio lands) in the OS file
+ explorer β created on first use so Explorer never opens a missing path."""
+ from backend.paths import user_data_dir
+ from backend.report_tools import _open_folder_in_explorer # Gradio-free
+
+ out_dir = user_data_dir() / "outputs"
+ ok, message = _open_folder_in_explorer(str(out_dir))
+ return {"ok": ok, "message": message, "path": str(out_dir)}
+
+
+@app.post("/api/stt/load")
+async def stt_load(payload: dict):
+ from backend import models
+
+ mid = mr.resolve_stt_model_id(payload.get("model_label") or "") or mr.DEFAULT_STT_MODEL or ""
+ try:
+ models.force_reload_stt(mid)
+ l = _lang(payload.get("lang", "kh"))
+ return {"ok": True, "message": l["msg_loaded"].format(model=mid)}
+ except Exception as e: # pragma: no cover β defensive
+ return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
+
+
+@app.post("/api/stt/unload")
+async def stt_unload(payload: dict):
+ from backend import models
+
+ return {"ok": True, "message": models.unload_stt_fn(payload.get("lang", "kh"))}
+
+
+# ββ Data Analysis βββββββββββββββββββββββββββββββββββββββββββββββββββββ
+@app.get("/api/data/chart/{name}")
+def data_chart(name: str):
+ """Serve a chart PNG produced by data-analysis runs. Checks the active report
+ folder, DATA_OUTPUT_DIR, and data_analysis report subdirectories. Only
+ basenames are served (no traversal)."""
+ safe = Path(name or "").name
+ if not safe:
+ return JSONResponse({"ok": False, "message": "chart not found"}, status_code=404)
+
+ # 1. Check active report directory from current/latest data analysis run
+ try:
+ from agents import data_analysis as da
+ active_dir = da.get_active_report_dir()
+ if active_dir and (Path(active_dir) / safe).is_file():
+ return FileResponse(str(Path(active_dir) / safe), media_type="image/png")
+ except Exception:
+ pass
+
+ # 2. Check DATA_OUTPUT_DIR
+ path = Path(mr.DATA_OUTPUT_DIR) / safe
+ if path.is_file():
+ return FileResponse(str(path), media_type="image/png")
+
+ # 3. Check reports/data_analysis subdirectories (newest first)
+ try:
+ data_reports = Path(mr.REPORT_DIRS.get("data", ""))
+ if data_reports.is_dir():
+ for sub in sorted(data_reports.iterdir(), key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True):
+ if sub.is_dir() and (sub / safe).is_file():
+ return FileResponse(str(sub / safe), media_type="image/png")
+ except Exception:
+ pass
+
+ return JSONResponse({"ok": False, "message": "chart not found"}, status_code=404)
+
+
+@app.get("/api/data/output-dir")
+def data_output_dir():
+ """The FULL path of the folder where the Data Analysis agent saves its
+ charts (mr.DATA_OUTPUT_DIR) β so the UI can display it. Read-only, no
+ side effects (the folder may not exist until the first run)."""
+ return {
+ "ok": True,
+ "path": str(Path(mr.DATA_OUTPUT_DIR)),
+ "exists": Path(mr.DATA_OUTPUT_DIR).is_dir(),
+ }
+
+
+@app.post("/api/data/open-outputs")
+async def data_open_outputs():
+ """Create (on first use) + open the Data Analysis charts folder in the
+ OS file explorer β mirrors the STT open-outputs endpoint."""
+ from backend.report_tools import _open_folder_in_explorer # Gradio-free
+
+ out_dir = Path(mr.DATA_OUTPUT_DIR)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ ok, message = _open_folder_in_explorer(str(out_dir))
+ return {"ok": ok, "message": message, "path": str(out_dir)}
+
+
+def _run_data_analysis(paths, question, model_label, history, use_memory, lang_key, max_steps, worker_max_steps, execution_timeout):
+ """Run the EDA agent generator in a thread; return the FINAL yield's
+ values (history, real chart list, report β the report slot is always
+ None: the agent returns the report as its final answer, never a saved
+ file). Intermediate yields carry placeholder values β only yields
+ whose gallery is a real list are kept."""
+ from agents import data_analysis
+
+ final = (history, [], "")
+ try:
+ for h, gallery, report_file in data_analysis.run_data_analysis(
+ paths,
+ question,
+ model_label,
+ history or [],
+ use_memory=use_memory,
+ lang_key=lang_key,
+ max_steps=max_steps or None,
+ worker_max_steps=worker_max_steps or None,
+ execution_timeout=execution_timeout or None,
+ ):
+ if isinstance(gallery, list):
+ final = (h, gallery, report_file)
+ except Exception as e: # pragma: no cover β defensive
+ final = (history, [], f"β {e}")
+ return final
+
+
+@app.post("/api/data/upload")
+async def data_upload(request: Request):
+ """Accept CSV/XLSX files (the Data tab's upload chip) and stash them in
+ temp files. Returns {paths}; the WS chat handler feeds those paths to
+ chat.chat_data() and deletes them after the run β the same lifecycle as
+ the Vision tab's /api/upload image."""
+ form = await request.form()
+ files = form.getlist("files")
+ paths = _save_uploads(files, "data")
+ if not paths:
+ return JSONResponse({"ok": False, "message": "no data file uploaded"}, status_code=400)
+ return {"ok": True, "paths": paths}
+
+
+@app.post("/api/data/analyze")
+async def data_analyze(request: Request):
+ """Upload CSV/XLSX files + question + analysis options β the EDA agent
+ runs (in a worker thread) and the final history, chart list and report
+ markdown are returned."""
+ import asyncio
+
+ form = await request.form()
+ files = form.getlist("files")
+ question = str(form.get("question") or "").strip()
+ model_label = str(form.get("model_label") or "").strip()
+ use_memory = str(form.get("use_memory") or "true").lower() not in ("0", "false", "no")
+ lang_key = str(form.get("lang") or "kh")
+ try:
+ max_steps = int(form.get("max_steps") or 0) or None
+ except ValueError:
+ max_steps = None
+ try:
+ worker_max_steps = int(form.get("worker_max_steps") or 0) or None
+ except ValueError:
+ worker_max_steps = None
+ try:
+ execution_timeout = int(form.get("execution_timeout") or 0) or None
+ except ValueError:
+ execution_timeout = None
+
+ paths = _save_uploads(files, "data")
+ if not paths:
+ return JSONResponse({"ok": False, "message": "no data file uploaded"}, status_code=400)
+
+ try:
+ history, gallery, report_file = await asyncio.to_thread(
+ _run_data_analysis, paths, question, model_label, [], use_memory, lang_key, max_steps, worker_max_steps, execution_timeout
+ )
+ finally:
+ # save_data_files() copied the uploads into the data-output dir during
+ # the run β the temp copies are now redundant (STT/KB clean up too).
+ for p in paths:
+ try:
+ Path(p).unlink(missing_ok=True)
+ except OSError:
+ pass
+ report_text = ""
+ if isinstance(report_file, str) and report_file and Path(report_file).is_file():
+ try:
+ report_text = Path(report_file).read_text(encoding="utf-8", errors="replace")
+ except Exception:
+ report_text = ""
+ charts = [Path(p).name for p in (gallery or []) if Path(str(p)).suffix.lower() == ".png"]
+ return {
+ "ok": True,
+ "history": history or [],
+ "charts": charts,
+ "report": report_text,
+ }
+
+
+@app.post("/api/data/reset")
+async def data_reset():
+ from agents import data_analysis
+
+ data_analysis.reset_agent()
+ data_analysis._last_data_context["key"] = None
+ return {"ok": True}
+
+
+# ββ Knowledge Base ββββββββββββββββββββββββββββββββββββββββββββββββββββ
+@app.post("/api/kb/index")
+async def kb_index(request: Request):
+ """Upload files (+ theme/subtheme/visual retriever) and index them into
+ the ChromaDB knowledge base.
+
+ Streams live progress as Server-Sent Events (``text/event-stream``): each
+ ``log`` event carries one of the app's OWN terminal status prints
+ (``[RAG]`` embedding load, ``[transformers]`` model-load warnings, β¦) so
+ the KB tab can render AND copy them as they happen, and the final ``done``
+ event carries the result message. Mirrors the chat WS log-streaming
+ pattern (ThreadStdoutTee) so the KB tab's "Copy All" can capture exactly
+ what the terminal showed β including the ColPali weight-report warnings that
+ previously only appeared in the console."""
+ import json as _json
+
+ from backend import knowledge_base as kb
+ from backend.stdio_hardening import ThreadStdoutTee
+
+ form = await request.form()
+ files = form.getlist("files")
+ # theme/subtheme may be a single value OR repeated form fields (the
+ # multi-select tag dropdowns) β collect them all.
+ theme = [str(v).strip() for v in form.getlist("theme") if str(v).strip()]
+ subtheme = [str(v).strip() for v in form.getlist("subtheme") if str(v).strip()]
+ lang_key = str(form.get("lang") or "kh").strip() or "kh"
+ visual_retriever = str(form.get("visual_retriever") or "").strip()
+ if not visual_retriever and mr.VISUAL_RETRIEVER_OPTIONS:
+ visual_retriever = next(iter(mr.VISUAL_RETRIEVER_OPTIONS))
+ embed_model_label = str(form.get("embed_model") or "").strip()
+ embed_provider_label = str(form.get("embed_provider") or "").strip()
+ if embed_provider_label:
+ sentinel = mr.EMBED_PROVIDER_OPTIONS.get(embed_provider_label)
+ if sentinel:
+ mr.set_saved_provider("embed", sentinel)
+ if embed_model_label:
+ mr.set_saved_model("embed", embed_model_label)
+ mr.set_embed_model(embed_model_label)
+ saved = _save_uploads(files, "kb", with_names=True)
+ paths = [it["path"] for it in saved]
+ source_names = {it["path"]: it["name"] for it in saved}
+ if not paths:
+ return JSONResponse({"ok": False, "message": "no files uploaded"}, status_code=400)
+
+ loop = asyncio.get_running_loop()
+ # Surfaced even when untagged: the ColPali UNEXPECTED/MISSING weight report
+ # and any other model-load warnings/errors the terminal prints.
+ _warn_re = re.compile(r"(UNEXPECTED|MISSING|Load Report|WARNING|ERROR|β|β οΈ)", re.IGNORECASE)
+
+ def _warn_predicate(line):
+ return bool(_warn_re.search(line))
+
+ q: "asyncio.Queue" = asyncio.Queue()
+
+ # The tee is created on the event-loop thread but must CAPTURE on the
+ # worker thread (where the blocking index actually prints) β attach() is
+ # therefore called inside _run, not here.
+ tee = ThreadStdoutTee(sys.stdout, warn_predicate=_warn_predicate)
+ sys.stdout = tee
+
+ def _run():
+ try:
+ tee.attach()
+ try:
+ message = kb.index_uploaded_files(
+ paths, visual_retriever, theme, subtheme,
+ lang_key=lang_key, source_names=source_names,
+ )
+ loop.call_soon_threadsafe(q.put_nowait, ("done", message or "Nothing indexed.", None))
+ except Exception as e: # surface the failure as a done event too
+ loop.call_soon_threadsafe(q.put_nowait, ("done", f"β {e}", str(e)))
+ finally:
+ for p in paths:
+ try:
+ Path(p).unlink(missing_ok=True)
+ except OSError:
+ pass
+ tee.detach()
+ except Exception:
+ loop.call_soon_threadsafe(q.put_nowait, ("done", "β Indexing crashed.", None))
+
+ async def event_gen():
+ worker = threading.Thread(target=_run, daemon=True)
+ worker.start()
+ try:
+ while worker.is_alive():
+ lines = tee.drain()
+ for ln in lines:
+ yield f"data: {_json.dumps({'type': 'log', 'line': ln}, ensure_ascii=False)}\n\n"
+ await asyncio.sleep(0.3)
+ # Flush any trailing (unfinished) line so the final warning isn't lost.
+ for ln in tee.drain(flush_partial=True):
+ yield f"data: {_json.dumps({'type': 'log', 'line': ln}, ensure_ascii=False)}\n\n"
+ finally:
+ tee.restore()
+ # Emit the terminal result line carried by the done event.
+ kind, msg, err = await q.get()
+ yield f"data: {_json.dumps({'type': 'done', 'message': msg, 'error': err}, ensure_ascii=False)}\n\n"
+
+ return StreamingResponse(
+ event_gen(),
+ media_type="text/event-stream",
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
+ )
+
+
+@app.get("/api/kb/docs")
+async def kb_docs(refresh: int = 0):
+ from backend import knowledge_base as kb
+
+ rows = await asyncio.to_thread(kb.get_doc_table, bool(refresh))
+ return {"ok": True, "rows": rows or []}
+
+
+@app.post("/api/kb/delete")
+async def kb_delete(payload: dict):
+ import asyncio
+
+ from backend import knowledge_base as kb
+
+ table, message = await asyncio.to_thread(
+ kb.delete_selected_sources,
+ payload.get("selected") or [], payload.get("rows") or [],
+ payload.get("lang", "kh"),
+ )
+ return {"ok": True, "message": message, "rows": table or []}
+
+
+@app.post("/api/kb/clear")
+async def kb_clear(payload: dict = None):
+ import asyncio
+
+ from backend import knowledge_base as kb
+
+ lang_key = (payload or {}).get("lang", "kh")
+ table, message = await asyncio.to_thread(kb.clear_index, lang_key)
+ return {"ok": True, "message": message, "rows": table or []}
+
+
+@app.get("/api/kb/visual-thumb")
+def kb_visual_thumb(doc_id: int = 0, page: int = 1):
+ """A stored page image from the visual index as a PNG β read from the
+ persisted collection (base64 per embed id), NO retriever model load.
+ Served via
in the KB tab's Visual Index table, so the session
+ token must ride the `?token=` query param (an
can't send headers)."""
+ from backend import knowledge_base as kb
+
+ data = kb.get_visual_thumb_bytes(doc_id, page)
+ if not data:
+ return JSONResponse({"ok": False, "message": "visual page not found"}, status_code=404)
+ return Response(content=data, media_type="image/png")
+
+
+@app.get("/api/kb/themes")
+async def kb_themes(theme: str = ""):
+ import asyncio
+
+ from backend import knowledge_base as kb
+
+ themes, subthemes = await asyncio.to_thread(kb.get_existing_themes_and_subthemes, theme)
+ return {"ok": True, "themes": themes or [], "subthemes": subthemes or []}
+
+
+@app.get("/api/kb/visual-docs")
+async def kb_visual_docs():
+ """List the visual index documents (source file, doc id, page/image
+ count) WITHOUT loading the retriever model β pure file read."""
+ import asyncio
+
+ from backend import knowledge_base as kb
+
+ rows = await asyncio.to_thread(kb.get_visual_index_table)
+ return {"ok": True, "rows": rows or []}
+
+
+@app.post("/api/kb/visual-delete")
+async def kb_visual_delete(payload: dict):
+ """Delete selected rows from the visual index (file surgery β no model
+ reload needed). Returns the refreshed visual table + message."""
+ import asyncio
+
+ from backend import knowledge_base as kb
+
+ table, message = await asyncio.to_thread(
+ kb.delete_visual_docs,
+ payload.get("selected") or [], payload.get("rows") or [],
+ payload.get("lang", "kh"),
+ )
+ return {"ok": True, "message": message, "rows": table or []}
+
+
+@app.post("/api/kb/visual-clear")
+async def kb_visual_clear(payload: dict = None):
+ """Delete the ENTIRE visual index."""
+ import asyncio
+
+ from backend import knowledge_base as kb
+
+ lang_key = (payload or {}).get("lang", "kh")
+ table, message = await asyncio.to_thread(kb.clear_visual_index, lang_key)
+ return {"ok": True, "message": message, "rows": table or []}
+
+
+# ββ Settings ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+def _llama_cpp_status_text(lang_key: str) -> str:
+ from backend import llama_backend
+
+ kh = lang_key == "kh"
+ if not llama_backend.LLAMA_CPP_AVAILABLE:
+ if getattr(llama_backend, "LLAMA_CPP_IMPORT_ERROR", ""):
+ return ("β Installed but Broken β GGUF won't load (ααα‘αΎααα½α
ααα»ααααααΌα
β GGUF ααΉααα·αααααΎαααΆα)" if kh
+ else "β Installed but Broken β GGUF won't load")
+ return "β Not Installed (αα·αααΆααααΆαααα‘αΎα)" if kh else "β Not Installed"
+ if llama_backend.LLAMA_CPP_GPU_AVAILABLE:
+ return "β
Installed (GPU CUDA Accelerated β ααΆαααα‘αΎαααΎ GPU)" if kh else "β
Installed (GPU CUDA Accelerated)"
+ return "β
Installed (CPU Mode β ααΆαααα‘αΎαααΎ CPU)" if kh else "β
Installed (CPU Mode)"
+
+
+def _hw_status_text(lang_key: str) -> str:
+ """HARDWARE detection block for the Settings tab β the physical machine
+ story only: device, GPU brand, driver CUDA version, the GPU list with
+ VRAM, and compute capability. No software-detection info here β the
+ llama.cpp engine state / runtime DLL / torch / index story lives in the
+ software block below."""
+ from backend import hardware
+ from backend.llama_health import _gpu_compute_capability
+
+ kh = lang_key == "kh"
+ info = hardware.HardwareManager.get_system_status()
+ device = (info.get("current_device") or "cpu").upper()
+ brand = (info.get("gpu_brand") or "none").upper()
+ cuda_ver = info.get("cuda_version") or "β"
+ cc = _gpu_compute_capability() or "β"
+ gpu_parts = []
+ for g in info.get("gpus") or []:
+ name = g.get("name") or "?"
+ try:
+ ram_gb = hardware.HardwareManager._adapter_ram_gb(g)
+ ram_text = f" Β· {ram_gb:.1f} GB" if ram_gb is not None else ""
+ except Exception:
+ ram_text = ""
+ gpu_parts.append(f"{name}{ram_text}")
+ gpu_line = " | ".join(gpu_parts) or ("ααααΆα" if kh else "none")
+ if kh:
+ return (
+ f"α§ααααα: {device} | GPU: {brand} | CUDA: {cuda_ver}\n"
+ f"GPU: {gpu_line}\n"
+ f"Compute Capability: {cc}"
+ )
+ return (
+ f"Device: {device} | GPU: {brand} | CUDA: {cuda_ver}\n"
+ f"GPU: {gpu_line}\n"
+ f"Compute Capability: {cc}"
+ )
+
+
+def _llama_server_path_status_text(lang_key: str) -> str:
+ """The llama-server binary PATH health line β 'the path has been set to
+ ...' / 'not set yet', shown in the Software Detection block so the user
+ sees at a glance whether the llama-server backend is configured (and to
+ which exact path)."""
+ from backend import llama_backend
+
+ kh = lang_key == "kh"
+ path = (getattr(llama_backend, "LLAMA_SERVER_EXE_PATH", "") or "").strip()
+ if not path:
+ return (
+ "llama-server: β " + (
+ "αα·αααΆαααααααααααΌααα β ααααααααα»α Settings (βοΈ)"
+ if kh else "path not set β set it in Settings (βοΈ)"
+ )
+ )
+ if os.path.exists(path):
+ return (
+ "llama-server: β
" + (
+ f"ααααΌαααααΌαααΆαααααααα
: {path}"
+ if kh else f"path has been set to: {path}"
+ )
+ )
+ return (
+ "llama-server: β οΈ " + (
+ f"ααααΌαααΆαααααα ααα»ααααααα―αααΆααα·αααΎα: {path}"
+ if kh else f"path set but file not found: {path}"
+ )
+ )
+
+
+def _cuda_status_text(lang_key: str) -> str:
+ """SOFTWARE detection block for the Settings tab β the installed-runtime
+ story the hardware console above does NOT carry: the llama.cpp python
+ engine state, the llama-server binary path health, the installed CUDA
+ runtime DLL family, and the live torch CUDA state. The RECOMMENDATIONS
+ are dynamic β each appears ONLY while it is not already done: the
+ PyTorch index is hidden once CUDA torch works, the llama.cpp build
+ recommendation hides once the engine is installed as recommended, and
+ the install hint shows only when at least one recommendation is still
+ pending. Hardware facts (device / GPU brand / VRAM / compute capability)
+ live in the hardware console β never duplicated here."""
+ from backend import hardware
+ from backend import llama_backend
+
+ kh = lang_key == "kh"
+ info = hardware.HardwareManager.get_system_status()
+ runtime_major = hardware.HardwareManager.detect_installed_cuda_runtime_major()
+ runtime_dll = f"cublas64_{runtime_major}.dll" if runtime_major else "β"
+ torch_ok = bool(info.get("torch_cuda_available"))
+ index = info.get("recommended_index") or ""
+ recs = info.get("recommendations") or {}
+ ll = (recs.get("llama_cpp") or {}).get("choice", "cpu").upper()
+
+ lines = [
+ f"llama-cpp-python: {_llama_cpp_status_text(lang_key)}",
+ _llama_server_path_status_text(lang_key),
+ ("CUDA Runtime DLL" if kh else "Installed CUDA Runtime DLL") + f": {runtime_dll}",
+ "PyTorch CUDA: " + ("β
ααΆα" if kh and torch_ok else "β
Yes" if torch_ok else "β αα" if kh else "β No"),
+ ]
+
+ # Dynamic recommendations β each shows ONLY while it is not done yet.
+ recommends = []
+ # PyTorch GPU: recommended only when CUDA torch is NOT working.
+ if not torch_ok:
+ recommends.append(
+ ("PyTorch Index αααααΆαααααΆα" if kh else "Recommended PyTorch Index") + f": {index}"
+ )
+ # llama.cpp build: recommended only while the engine is NOT installed in
+ # the recommended mode (CPU-only builds still recommend the GPU build on
+ # a CUDA machine; an absent engine always recommends).
+ llama_cpp_done = bool(
+ getattr(llama_backend, "LLAMA_CPP_AVAILABLE", False)
+ and (ll == "CPU" or getattr(llama_backend, "LLAMA_CPP_GPU_AVAILABLE", False))
+ )
+ if not llama_cpp_done:
+ recommends.append(
+ ("ααΆαααααΆα llama.cpp" if kh else "Recommended llama.cpp") + f": {ll}"
+ )
+ # The install hint appears only while something is still pending.
+ if recommends:
+ lines.append("")
+ lines.extend(recommends)
+ lines.append("")
+ lines.append(
+ "ααα‘αΎα GPU ααααααααΈαααα»α Settings αααααΆααααΈααΎααααααα·ααΈα"
+ if kh else "Install GPU packages from Settings after launch."
+ )
+ return "\n".join(lines)
+
+
+def _env_status_text(lang_key: str) -> str:
+ """Python-environment block for the Settings tab β the 'does the app
+ recognize its packages?' diagnostic. Reports the runtime MODE (frozen
+ standalone bundle vs a .venv vs system Python), the interpreter path,
+ and a LIVE import check of every core package with its version.
+
+ A frozen (MSIX / PyInstaller standalone) build bundles the packages
+ INSIDE the app β no .venv exists or is needed; a venv-based install
+ (SETUP.ps1) shows the venv path instead. On a machine that 'does not
+ recognize any packages', this block shows exactly which imports fail.
+ """
+ import importlib.metadata as _md
+ import importlib.util as _iu
+ import sys as _sys
+
+ kh = lang_key == "kh"
+ frozen = bool(getattr(_sys, "frozen", False))
+ venv = bool(getattr(_sys, "base_prefix", None) and _sys.base_prefix != _sys.prefix)
+
+ lines = []
+ if frozen:
+ lines.append(
+ "π¦ " + (
+ "αααααα·ααΈ Standalone (ααΆαααα
αα) β αααα
ααααΆααα’αααααα·ααααα»ααααααα·ααΈ αα·αααααΌαααΆα .venv αα"
+ if kh else
+ "Standalone (frozen bundle) β all packages are bundled inside the app; no .venv needed"
+ )
+ )
+ elif venv:
+ lines.append(
+ "π " + ("ααα·ααΆααΆααα·αααα·α (.venv)" if kh else "Virtual environment (.venv)")
+ )
+ else:
+ lines.append(
+ "π " + ("Python αααααααα (System)" if kh else "System Python")
+ )
+ lines.append(f"Python: {_sys.version.split()[0]} | {_sys.executable}")
+
+ # Core packages the app needs at runtime β each with a live import
+ # check + version, so a machine that 'does not recognize any packages'
+ # shows exactly which imports fail (and which are just on-demand).
+ core = [
+ ("torch", "torch"),
+ ("torchaudio", "torchaudio"),
+ ("torchvision", "torchvision"),
+ ("transformers", "transformers"),
+ ("accelerate", "accelerate"),
+ ("sentence_transformers", "sentence-transformers"),
+ ("chromadb", "chromadb"),
+ ("docx", "python-docx"),
+ ("pandas", "pandas"),
+ ("numpy", "numpy"),
+ ("matplotlib", "matplotlib"),
+ ("PIL", "Pillow"),
+ ("soundfile", "soundfile"),
+ ("librosa", "librosa"),
+ ("smolagents", "smolagents"),
+ ("requests", "requests"),
+ ]
+ failed = []
+ for mod, dist in core:
+ try:
+ spec = _iu.find_spec(mod)
+ except Exception:
+ spec = None
+ if spec is None:
+ lines.append(f"β {mod}")
+ failed.append(mod)
+ continue
+ # Metadata (dist-info) is NOT shipped for every bundled package β
+ # PyInstaller only collects it for packages that query it at runtime
+ # (e.g. torch, chromadb). A missing version must NEVER flip a
+ # present-and-importable package to β: try the canonical dist name
+ # plus the PEP-503-normalized variants, and fall back to a blank
+ # version (still β
β the import check is what matters).
+ ver = ""
+ for name in {dist, dist.replace("-", "_"), dist.replace("_", "-")}:
+ try:
+ got = _md.version(name)
+ if got:
+ ver = got
+ break
+ except Exception:
+ continue
+ lines.append(f"β
{mod} {ver}".rstrip())
+ # llama-cpp-python is OPTIONAL β installed on demand from Settings, so
+ # 'missing' here is expected until the user installs it (never a red β).
+ try:
+ if _iu.find_spec("llama_cpp") is not None:
+ lines.append(f"β
llama_cpp {_md.version('llama-cpp-python') or ''}".rstrip())
+ else:
+ lines.append(
+ "βΉοΈ llama_cpp β " + (
+ "ααα‘αΎαααΆααααααΌαααΆαααΈ Settings (αααααΎα)"
+ if kh else "optional β install from Settings"
+ )
+ )
+ except Exception:
+ lines.append("βΉοΈ llama_cpp β " + ("αα·αα’αΆα
αα·αα·αααααΆα" if kh else "unavailable"))
+ # One-line summary when ANY core package import fails β the at-a-glance
+ # takeaway for a machine that 'does not recognize any packages', with a
+ # hint pointing at the reinstall path (the Settings download buttons /
+ # GPU PyTorch install, or the MSIX/venv reinstall). Kept in BOTH
+ # languages, following the inline-bilingual pattern of this block.
+ if failed:
+ names = ", ".join(failed)
+ if kh:
+ lines.append(
+ f"β οΈ αααα
ααααααα·αα’αΆα
αααα»αααΆα ({len(failed)}): {names} β "
+ "ααΌαααα‘αΎαα‘αΎααα·αααΆα Settings (βοΈ)"
+ )
+ else:
+ lines.append(
+ f"β οΈ {len(failed)} package(s) failed to import: {names} β "
+ "reinstall via Settings (βοΈ)"
+ )
+ return "\n".join(lines)
+
+
+def _llama_timeout_seconds() -> int:
+ """The saved llama-server timeout as SECONDS (the Settings number input
+ contract) β maps the persisted label back through LLAMA_SERVER_TIMEOUT_OPTIONS."""
+ try:
+ return mr.LLAMA_SERVER_TIMEOUT_OPTIONS.get(mr.get_saved_llm_server_timeout_label())\
+ or mr.DEFAULT_LLAMA_SERVER_TIMEOUT
+ except Exception: # pragma: no cover β defensive
+ return 300
+
+
+@app.get("/api/settings")
+async def settings_status(lang: str = "kh"):
+ from backend import component_downloader, llama_backend, whisper_cpp_backend
+ from backend.report_tools import _list_report_files # Gradio-free
+
+ lang_key = lang or "kh"
+ l = _lang(lang_key)
+ comp = component_downloader.get_component_statuses()
+
+ def _status(ready: bool) -> str:
+ return l["web_comp_ready"] if ready else l["web_comp_missing"]
+
+ comp_text = (
+ f"llama-server.exe: {_status(comp['llama_server'])}"
+ f" | whisper-server.exe: {_status(comp['whisper_server'])}"
+ f" | Poppler: {_status(comp['poppler'])}"
+ f" | Playwright Chromium: {_status(comp['playwright'])}"
+ )
+ return {
+ "ok": True,
+ "hw": _hw_status_text(lang_key),
+ # The venv/packages diagnostic β shown right under the hardware
+ # card: runtime mode (frozen standalone vs .venv), interpreter, and
+ # a live import check of every core package.
+ "env": _env_status_text(lang_key),
+ "components": comp_text,
+ "componentStatuses": comp,
+ "device": _device_label(),
+ "cuda": _cuda_status_text(lang_key),
+ "reportBaseDir": mr.REPORT_BASE_DIR,
+ "reportFiles": _list_report_files(),
+ "fields": {
+ "hf_token": mr.get_saved_hf_token(),
+ # NOTE: no "hf_model_id" field β the HF API model is chosen
+ # ONLY in each tab's header model picker (the curated
+ # hf_api_models.csv list); there is no Settings-level model id.
+ "hf_provider": mr.get_saved_hf_provider(),
+ "litellm_model_id": mr.get_saved_litellm_model_id(),
+ "litellm_api_key": mr.get_saved_litellm_api_key(),
+ "litellm_api_base": mr.get_saved_litellm_api_base(),
+ "llama_server_path": llama_backend.LLAMA_SERVER_EXE_PATH or "",
+ "llama_server_args": llama_backend.LLAMA_SERVER_EXTRA_ARGS or "",
+ # SECONDS, not the display label β the Settings tab renders this in
+ # a number input and POSTs it straight back to set_llm_server_timeout.
+ "llama_server_timeout": _llama_timeout_seconds(),
+ "whisper_server_path": whisper_cpp_backend.WHISPER_CPP_SERVER_EXE_PATH or "",
+ "whisper_server_args": whisper_cpp_backend.WHISPER_CPP_SERVER_EXTRA_ARGS or "",
+ "gguf_dir": llama_backend.LLAMA_CPP_MODEL_DIR or "",
+ "flash_attn_pytorch": mr.get_saved_flash_attn_pytorch(),
+ "flash_attn_llama": mr.get_saved_flash_attn_llama(),
+ "torch_compile": mr.get_saved_torch_compile(),
+ "torch_compile_mode": mr.get_saved_torch_compile_mode(),
+ "torch_bf16": mr.get_saved_torch_bf16(),
+ "llama_kv_cache_quant": mr.get_saved_llama_kv_cache_quant(),
+ "llama_mlock": mr.get_saved_llama_mlock(),
+ "llama_mmap": mr.get_saved_llama_mmap(),
+ "llama_threads": mr.get_saved_llama_threads(),
+ "llama_tensor_split": mr.get_saved_llama_tensor_split(),
+ "llama_draft_model": mr.get_saved_llama_draft_model(),
+ "llama_draft_max": mr.get_saved_llama_draft_max(),
+ "visual_retrieval": mr.get_rag_visual_retrieval(),
+ "clear_confirm_min": mr.get_saved_clear_confirm_min() or mr.CLEAR_CONFIRM_MIN_DEFAULT,
+ "denoise_strength": mr.get_saved_denoise_strength(),
+ "stt_lang": mr.get_saved_stt_lang(),
+ "stt_mic_device": mr.get_saved_stt_mic(),
+ },
+ # The llama-server per-request timeout presets (label + seconds) β
+ # the Settings tab's timeout dropdown (this GLOBAL setting lives
+ # only here; see test_llama_server_timeout_lives_in_settings_not_meta).
+ "llama_server_timeout_options": [
+ {"label": label, "seconds": seconds}
+ for label, seconds in mr.LLAMA_SERVER_TIMEOUT_OPTIONS.items()
+ ],
+ # Per-tab context window (n_ctx) β same shared contract as /api/meta
+ # (see _ctx_window_payload).
+ **_ctx_window_payload(),
+ }
+
+
+@app.post("/api/settings/save")
+async def settings_save(payload: dict):
+ """Persist one Settings field ({key, value}) β mirrors the Gradio save
+ handlers (set_* in model_registry / llama_backend / whisper_cpp_backend)."""
+ key = payload.get("key") or ""
+ value = payload.get("value")
+ try:
+ if key == "lang":
+ user_config.set_saved_lang(str(value or ""))
+ elif key == "hf_token":
+ mr.set_hf_token(str(value or ""))
+ # NOTE: no "hf_model_id" save branch β the HF API model is chosen
+ # per-tab in the header pickers; a stale save request is ignored so
+ # a custom Settings-level model id can never silently reappear.
+ elif key == "hf_provider":
+ mr.set_hf_provider(str(value or ""))
+ elif key == "litellm_model_id":
+ mr.set_litellm_model_id(str(value or ""))
+ elif key == "litellm_api_key":
+ mr.set_litellm_api_key(str(value or ""))
+ elif key == "litellm_api_base":
+ mr.set_litellm_api_base(str(value or ""))
+ elif key == "llama_server_path":
+ from backend import llama_backend
+
+ llama_backend.set_llama_server_exe_path(str(value or ""))
+ elif key == "llama_server_args":
+ from backend import llama_backend
+
+ llama_backend.set_llama_server_extra_args(str(value or ""))
+ elif key == "llama_server_timeout":
+ seconds = int(value or 0)
+ if seconds > 0:
+ mr.set_llm_server_timeout(seconds)
+ try:
+ import backend.models as models
+
+ if getattr(models, "_llm", None) is not None and hasattr(models._llm, "timeout"):
+ models._llm.timeout = seconds
+ except Exception:
+ pass
+ elif key == "whisper_server_path":
+ from backend import whisper_cpp_backend
+
+ whisper_cpp_backend.set_whisper_server_exe_path(str(value or ""))
+ elif key == "whisper_server_args":
+ from backend import whisper_cpp_backend
+
+ whisper_cpp_backend.set_whisper_server_extra_args(str(value or ""))
+ elif key == "gguf_dir":
+ from backend import llama_backend
+
+ llama_backend.set_model_dir(str(value or ""))
+ elif key == "flash_attn_pytorch":
+ mr.set_flash_attn_pytorch(bool(value))
+ elif key == "flash_attn_llama":
+ mr.set_flash_attn_llama(bool(value))
+ elif key == "torch_compile":
+ mr.set_torch_compile(bool(value))
+ elif key == "torch_compile_mode":
+ mr.set_torch_compile_mode(str(value or ""))
+ elif key == "torch_bf16":
+ mr.set_torch_bf16(bool(value))
+ elif key == "llama_kv_cache_quant":
+ mr.set_llama_kv_cache_quant(str(value or ""))
+ elif key == "llama_mlock":
+ mr.set_llama_mlock(bool(value))
+ elif key == "llama_mmap":
+ mr.set_llama_mmap(bool(value))
+ elif key == "llama_threads":
+ mr.set_llama_threads(value)
+ elif key == "llama_tensor_split":
+ mr.set_llama_tensor_split(str(value or ""))
+ elif key == "llama_draft_model":
+ mr.set_llama_draft_model(str(value or ""))
+ elif key == "llama_draft_max":
+ mr.set_llama_draft_max(value)
+ elif key == "stt_provider":
+ sentinel = mr.STT_PROVIDER_OPTIONS.get(str(value or ""))
+ if sentinel:
+ mr.set_saved_provider("stt", sentinel)
+ elif key == "stt_report_provider":
+ # The STT tab's transcriptβreport analysis LLM provider β its
+ # own slot (stt_report), separate from the transcription
+ # provider above. chat.py reads this to build the analyser.
+ sentinel = mr.LLM_PROVIDER_OPTIONS.get(str(value or ""))
+ if sentinel:
+ mr.set_saved_provider("stt_report", sentinel)
+ elif key == "stt_report_model":
+ mr.set_saved_model("stt_report", str(value or ""))
+ elif key == "embed_provider":
+ sentinel = mr.EMBED_PROVIDER_OPTIONS.get(str(value or ""))
+ if sentinel:
+ mr.set_saved_provider("embed", sentinel)
+ models.unload_embed_model_fn()
+ elif key == "ctx_window":
+ # Per-tab context window β the UI posts the dropdown LABEL (the
+ # label IS the value); map it back to the token count. Defensive:
+ # a raw int is accepted too, so a future UI posting numbers keeps
+ # working. Unknown labels/tabs are refused, never silently saved.
+ tab = _CTX_WINDOW_TABS.get(payload.get("tab") or "general")
+ # type() is int rather than isinstance() so a JSON `true` (bool) can
+ # never slip through as n_ctx=1.
+ n_ctx = value if type(value) is int else mr.CONTEXT_WINDOW_OPTIONS.get(str(value or ""))
+ if tab not in _CTX_WINDOW_TABS.values() or type(n_ctx) is not int or n_ctx <= 0:
+ return JSONResponse(
+ {"ok": False, "message": f"unknown context window: {value}"},
+ status_code=400,
+ )
+ mr.set_context_window(n_ctx, tab)
+ elif key in ("agent_max_steps", "searcher_max_steps"):
+ # Per-tab step budgets β the UI's "Max Steps" / "Search steps"
+ # controls. value: a positive int, or null to clear back to
+ # AUTO (model-scaled default). type() is int (not isinstance)
+ # so a JSON `true` (bool) can never persist as a budget of 1.
+ tab = _provider_tab(payload.get("tab") or "general")
+ slots = mr._AGENT_STEPS_KEYS if key == "agent_max_steps" else mr._SUB_AGENT_STEPS_KEYS
+ if tab not in slots:
+ return JSONResponse(
+ {"ok": False, "message": f"unknown tab: {payload.get('tab')}"},
+ status_code=400,
+ )
+ if value is not None and type(value) is not int:
+ return JSONResponse(
+ {"ok": False, "message": f"invalid step budget: {value}"},
+ status_code=400,
+ )
+ if key == "agent_max_steps":
+ mr.set_agent_steps(tab, value)
+ else:
+ mr.set_sub_agent_steps(tab, value)
+ elif key == "execution_timeout":
+ # Per-tab agentic execution timeout (General's "Exec timeout"
+ # control). value: a positive int (seconds), or null to clear
+ # back to AUTO (factory default). Same guards as the step
+ # budgets β type() is int so a JSON `true` can never persist
+ # as a 1-second timeout.
+ tab = _provider_tab(payload.get("tab") or "general")
+ if tab not in mr._AGENT_EXEC_TIMEOUT_KEYS:
+ return JSONResponse(
+ {"ok": False, "message": f"unknown tab: {payload.get('tab')}"},
+ status_code=400,
+ )
+ if value is not None and type(value) is not int:
+ return JSONResponse(
+ {"ok": False, "message": f"invalid execution timeout: {value}"},
+ status_code=400,
+ )
+ mr.set_execution_timeout(tab, value)
+ elif key == "run_timeout":
+ # Per-tab generation RUN timeout (the Generation Settings
+ # "Timeout" control β General / RAG / Vision, plus Deep
+ # Research's legacy `deep_research_timeout` key which lands in
+ # the same slot). value: a positive int (seconds), or null to
+ # clear back to no explicit deadline. Same guards as the step
+ # budgets β type() is int so a JSON `true` can never persist
+ # as a 1-second timeout.
+ tab = _provider_tab(payload.get("tab") or "general")
+ if tab not in mr._AGENT_RUN_TIMEOUT_KEYS:
+ return JSONResponse(
+ {"ok": False, "message": f"unknown tab: {payload.get('tab')}"},
+ status_code=400,
+ )
+ if value is not None and type(value) is not int:
+ return JSONResponse(
+ {"ok": False, "message": f"invalid run timeout: {value}"},
+ status_code=400,
+ )
+ mr.set_agent_run_timeout(tab, value)
+ elif key == "visual_retrieval":
+ # The RAG tab's resource-intensive visual path toggle (the
+ # agentic `visual_retriever` page-image tool + the VLM grounding
+ # pass). Only the RAG tab exposes it; DEFAULT OFF (pure
+ # text-retrieval + text-LLM pipeline).
+ tab = _provider_tab(payload.get("tab") or "general")
+ if tab != "rag":
+ return JSONResponse(
+ {"ok": False, "message": f"unknown tab: {payload.get('tab')}"},
+ status_code=400,
+ )
+ mr.set_rag_visual_retrieval(bool(value))
+ elif key == "clear_confirm_min":
+ # App-wide Alt+Delete clear-confirmation threshold (messages) β
+ # the Settings tab's "Confirm-clear threshold" field. value: a
+ # positive int, or null/'' to reset to the default (8). Same
+ # guards as the budgets β type() is int so a JSON `true` can
+ # never persist as a 1-message threshold.
+ if value is not None and type(value) is not int:
+ return JSONResponse(
+ {"ok": False, "message": f"invalid clear threshold: {value}"},
+ status_code=400,
+ )
+ if value is not None and value < 1:
+ return JSONResponse(
+ {"ok": False, "message": f"invalid clear threshold: {value}"},
+ status_code=400,
+ )
+ mr.set_clear_confirm_min(value)
+ elif key == "denoise_strength":
+ # STT tab's π§ Reduce Noise strength preset (gentle / medium /
+ # aggressive). value: the preset name, or null/'' to reset to the
+ # default ('' normalized to None like the other handlers).
+ # Unknown names are refused with a 400 β never silently persisted.
+ if value is not None and value != "":
+ from backend.audio_denoise import DENOISE_STRENGTH_PRESETS
+
+ if not isinstance(value, str) or value.strip().lower() not in DENOISE_STRENGTH_PRESETS:
+ return JSONResponse(
+ {"ok": False, "message": f"invalid denoise strength: {value}"},
+ status_code=400,
+ )
+ mr.set_denoise_strength(value if value != "" else None)
+ elif key == "stt_lang":
+ # STT tab's transcription language (auto / english / khmer /
+ # french / chinese / japanese). value: the language value, or
+ # null/'' to reset to the default ('auto'). Unknown values are
+ # refused with a 400 β never silently persisted.
+ if value is not None and value != "":
+ if not isinstance(value, str) or value.strip().lower() not in mr.STT_LANG_OPTIONS:
+ return JSONResponse(
+ {"ok": False, "message": f"invalid stt language: {value}"},
+ status_code=400,
+ )
+ mr.set_stt_lang(value if value != "" else None)
+ elif key == "stt_mic_device":
+ # STT tab's microphone device id β an opaque browser-assigned
+ # string (or '' for system default). No validation needed;
+ # the frontend silently clears stale ids on its own.
+ mr.set_stt_mic(value if isinstance(value, str) else "")
+ elif key == "deep_research_timeout":
+ # Deep Research's whole-run timeout (DrControls "Timeout"
+ # field). value: a positive int (seconds), or null to clear
+ # back to the agent's default. Same guards as the step budgets
+ # β type() is int so a JSON `true` can never persist as a
+ # 1-second run timeout.
+ tab = _provider_tab(payload.get("tab") or "general")
+ if tab not in mr._AGENT_RUN_TIMEOUT_KEYS:
+ return JSONResponse(
+ {"ok": False, "message": f"unknown tab: {payload.get('tab')}"},
+ status_code=400,
+ )
+ if value is not None and type(value) is not int:
+ return JSONResponse(
+ {"ok": False, "message": f"invalid deep research timeout: {value}"},
+ status_code=400,
+ )
+ mr.set_agent_run_timeout(tab, value)
+ else:
+ return JSONResponse({"ok": False, "message": f"unknown setting: {key}"}, status_code=400)
+ return {"ok": True}
+ except Exception as e: # pragma: no cover β defensive
+ return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
+
+
+@app.get("/api/settings/memory")
+def settings_memory():
+ """Live CPU + RAM + VRAM usage β polled by the Settings tab and the
+ sidebar Free-VRAM chip so users see how much of the machine is in use
+ next to the buttons (and how much freeing VRAM actually recovered)."""
+ from backend import hardware
+
+ try:
+ usage = hardware.HardwareManager.get_memory_usage()
+ except Exception: # pragma: no cover β defensive
+ usage = {"cpu": {}, "ram": {}, "vram": {}}
+ return {"ok": True, "usage": usage}
+
+
+def _reset_app_state(lang_key: str = "kh") -> list:
+ """Shared full-reset teardown used by Free-All-VRAM AND the header
+ Restart button: reset cached agents, unload every model, stop the
+ managed llama-server/whisper-server subprocesses, then run a full
+ multi-generation garbage collection + GPU cache reclaim.
+
+ Returns the list of bilingual status lines (unload summaries + server-
+ stop claims) the caller renders. Safe to call when nothing is loaded
+ (every step is idempotent/cheap).
+
+ The managed servers are stopped UNCONDITIONALLY, not only when a model
+ wrapper happens to be cached: a GGUF model can be resident in VRAM
+ inside llama-server.exe while every Python wrapper is already None (e.g.
+ an earlier Free All VRAM dropped the wrapper, then a late/stale chat
+ turn restarted the server; or a start succeeded but crashed before the
+ wrapper was cached; or an old build that released EmbeddingServerModel's
+ wrapper without stopping the shared server). The per-model unload fns
+ early-return "nothing loaded" in that state, so the server would survive
+ and keep the GPU occupied β exactly the "VRAM still ~50% after Free All
+ VRAM" report. Stopping is idempotent and cheap when nothing runs.
+ """
+ from agents import data_analysis, deep_research_agent, general_agent, rag_agent
+ from backend import knowledge_base as kb
+ from backend import llama_backend, models, whisper_cpp_backend
+ from ui.i18n import LANGUAGES # dicts only β lightweight, no UI framework
+
+ msgs = []
+ # 1. Reset all cached agents FIRST so they release any references to
+ # the shared _llm, tools, and sub-agents.
+ for mod in (general_agent, rag_agent, data_analysis, deep_research_agent):
+ try:
+ mod.reset_agent()
+ except Exception:
+ pass
+
+ # 2. Unload all models and visual retrievers
+ msgs.append(models.unload_llm_fn(lang_key))
+ msgs.append(models.unload_vlm_fn(lang_key))
+ msgs.append(models.unload_stt_fn(lang_key))
+ msgs.append(models.unload_embed_model_fn(lang_key))
+ msgs.append(kb.unload_visual_retriever_fn(lang_key))
+
+ # 3. Unconditional server stop β see the docstring. stop_*_server() also
+ # reaps ORPHANED servers a previous app instance left behind (same exe /
+ # model-dir signature β see local_server.kill_stray_app_servers) and
+ # reports how many processes they actually stopped, so the summary only
+ # claims a stop when one really happened.
+ l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
+ stopped = llama_backend.stop_llama_server()
+ if stopped:
+ msgs.append(l["msg_server_stopped"].format(server="llama-server"))
+ # The dedicated EMBEDDING llama-server is a separate slot β stopped
+ # here too (idempotent when idle), never by stop_llama_server().
+ stopped = llama_backend.stop_embed_server()
+ if stopped:
+ msgs.append(l["msg_server_stopped"].format(server="llama-server-embed"))
+ stopped = whisper_cpp_backend.stop_whisper_server()
+ if stopped:
+ msgs.append(l["msg_server_stopped"].format(server="whisper-server"))
+
+ # 4. Reset agents again defensively
+ for mod in (general_agent, rag_agent, data_analysis, deep_research_agent):
+ try:
+ mod.reset_agent()
+ except Exception:
+ pass
+
+ # 5. Full multi-generation garbage collection & GPU cache reclaim
+ import gc
+ gc.collect()
+ gc.collect()
+ try:
+ import torch
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ torch.cuda.ipc_collect()
+ elif hasattr(torch, "xpu") and torch.xpu.is_available():
+ torch.xpu.empty_cache()
+ torch.xpu.synchronize()
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
+ torch.mps.empty_cache()
+ except Exception:
+ pass
+ return msgs
+
+
+@app.post("/api/settings/free-vram")
+async def settings_free_vram(payload: dict):
+ """Unload every loaded model + drop cached agents β the web port of the
+ Gradio do_free_vram handler."""
+ try:
+ msgs = _reset_app_state(str(payload.get("lang", "kh")))
+ except Exception as e: # pragma: no cover β defensive
+ return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
+ return {"ok": True, "notice": "\n".join(str(m) for m in msgs if m)}
+
+
+@app.post("/api/restart")
+async def api_restart(payload: dict):
+ """Full in-process app restart β the header β» Restart button (after π
+ Refresh). Unlike the refresh button (which only re-boots the SPA and
+ re-fetches /api/meta), this ALSO fully resets the backend state: cached
+ agents, every loaded model (VRAM), and the managed llama-server /
+ whisper-server subprocesses β then rebuilds the model registry from disk
+ (re-scanning the saved GGUF folder) so newly installed / downloaded
+ components and models are picked up, exactly like a cold app start.
+
+ The FastAPI server runs IN the same process as the launcher (dev
+ `_launch_web.py`, webview `run_webview.py`, frozen MSIX exe), so a hard
+ process kill + relaunch would risk a dead app if the respawn failed.
+ `_reset_app_state()` gives the same observable outcome β the SPA re-boot
+ re-fetches everything fresh β with zero death risk."""
+ lang_key = str(payload.get("lang", "kh"))
+ l = _lang(lang_key)
+ try:
+ msgs = _reset_app_state(lang_key)
+ # Rebuild the model registry from disk (GGUF folder + registered
+ # presets) so newly-installed components / models are discovered.
+ from backend import llama_backend
+ from backend import model_registry as mr
+
+ mr.rescan_gguf_models(llama_backend.LLAMA_CPP_MODEL_DIR or "", lang_key)
+ except Exception as e: # pragma: no cover β defensive
+ return JSONResponse(
+ {"ok": False, "message": l["err_restart_app"].format(error=str(e))},
+ status_code=500,
+ )
+ return {
+ "ok": True,
+ "message": l["msg_restart_app"],
+ "notice": "\n".join(str(m) for m in msgs if m),
+ }
+
+
+@app.post("/api/settings/clear-reports")
+async def settings_clear_reports(payload: dict):
+ from backend.report_tools import _clear_old_reports # Gradio-free
+
+ deleted, days = _clear_old_reports(payload.get("days"))
+ return {"ok": True, "deleted": deleted, "days": days}
+
+
+@app.post("/api/settings/open-reports")
+async def settings_open_reports(payload: dict):
+ from backend.report_tools import open_reports_folder_for # Gradio-free
+
+ # A per-tab "Open Reports Folder" button sends its tab key (stt / gen /
+ # rag / dr / vis / data) and opens THAT tab's own folder; or passes an
+ # exact folder path if a report was recently saved. No/unknown
+ # tab falls back to the reports base dir (Settings / About / KB).
+ tab = str(payload.get("tab") or "").strip() or None
+ target_path = str(payload.get("path") or "").strip() or None
+ ok, message, path = open_reports_folder_for(tab_key=tab, specific_path=target_path)
+ return {"ok": ok, "message": message, "path": path}
+
+
+@app.post("/api/settings/refresh-reports")
+async def settings_refresh_reports():
+ from backend.report_tools import _list_report_files # Gradio-free
+
+ return {"ok": True, "files": _list_report_files()}
+
+
+@app.post("/api/settings/delete-report")
+async def settings_delete_report(payload: dict):
+ from backend.report_tools import _delete_report_file, _list_report_files # Gradio-free
+
+ ok, message = _delete_report_file(payload.get("rel") or "")
+ return {"ok": ok, "message": message, "files": _list_report_files()}
+
+
+# Background component downloads / installs β one job at a time; the frontend
+# polls GET /api/settings/download for the streaming log tail. The lock makes
+# the check-and-start atomic so two near-simultaneous POSTs can't spawn two
+# workers (the TOCTOU the bare flag allowed).
+_DL_STATE = {"running": False, "component": "", "lines": [], "progress": None, "label": ""}
+_DL_LOCK = threading.Lock()
+
+# Regex to extract "(42%)" from download progress lines.
+_RE_DL_PCT = re.compile(r"\((\d{1,3})%\)")
+_RE_DL_MB = re.compile(r"([\d.]+)\s*/\s*([\d.]+)\s*MB")
+_RE_DL_LABEL = re.compile(r"Downloading\s+(.+?)\.\.\.")
+
+
+def _track_dl_progress(line: str) -> None:
+ """Parse a download progress line and update _DL_STATE progress/label."""
+ m_pct = _RE_DL_PCT.search(line)
+ if m_pct:
+ _DL_STATE["progress"] = int(m_pct.group(1))
+ m_label = _RE_DL_LABEL.search(line)
+ if m_label:
+ _DL_STATE["label"] = m_label.group(1).strip()
+ # Track downloaded/total MB for the progress bar subtitle.
+ m_mb = _RE_DL_MB.search(line)
+ if m_mb:
+ _DL_STATE["dl_mb"] = m_mb.group(1)
+ _DL_STATE["total_mb"] = m_mb.group(2)
+
+
+def _download_worker(component: str, choice: str | None = None):
+ try:
+ if component in ("llama_cpp", "llm_cpp_install"):
+ from backend import hardware
+
+ gen = hardware.HardwareManager.install_llama_cpp_python_gen(choice=choice)
+ for line in gen:
+ sline = str(line)
+ _DL_STATE["lines"].append(sline)
+ _track_dl_progress(sline)
+ if len(_DL_STATE["lines"]) > 800:
+ _DL_STATE["lines"] = _DL_STATE["lines"][-800:]
+ elif component == "fix_env":
+ from backend import hardware
+
+ for msg, dev, log in hardware.HardwareManager.fix_environment_gen(choice=choice):
+ sline = str(log or msg)
+ _DL_STATE["lines"].append(sline)
+ _track_dl_progress(sline)
+ if len(_DL_STATE["lines"]) > 800:
+ _DL_STATE["lines"] = _DL_STATE["lines"][-800:]
+ else:
+ from backend import component_downloader
+
+ for line in component_downloader.download_component_gen(component, choice=choice):
+ sline = str(line)
+ _DL_STATE["lines"].append(sline)
+ _track_dl_progress(sline)
+ if len(_DL_STATE["lines"]) > 800:
+ _DL_STATE["lines"] = _DL_STATE["lines"][-800:]
+ except Exception as e: # pragma: no cover β defensive
+ _DL_STATE["lines"].append(f"β {e}")
+ finally:
+ _DL_STATE["running"] = False
+
+
+@app.post("/api/settings/download")
+async def settings_download(payload: dict):
+ component = payload.get("component") or ""
+ if component not in ("llama_server", "whisper_server", "poppler", "playwright", "llama_cpp", "fix_env"):
+ return JSONResponse({"ok": False, "message": f"unknown component: {component}"}, status_code=400)
+ with _DL_LOCK:
+ if _DL_STATE["running"]:
+ return JSONResponse({"ok": False, "message": "a download is already running"}, status_code=409)
+ _DL_STATE["running"] = True
+ _DL_STATE["component"] = component
+ _DL_STATE["lines"] = []
+ _DL_STATE["progress"] = None
+ _DL_STATE["label"] = ""
+ _DL_STATE.pop("dl_mb", None)
+ _DL_STATE.pop("total_mb", None)
+ threading.Thread(target=_download_worker, args=(component,), daemon=True).start()
+ return {"ok": True, "running": True}
+
+
+@app.get("/api/settings/download")
+async def settings_download_status():
+ from backend import component_downloader
+
+ return {
+ "ok": True,
+ "running": _DL_STATE["running"],
+ "component": _DL_STATE["component"],
+ "log": "\n".join(_DL_STATE["lines"][-200:]),
+ "progress": _DL_STATE.get("progress"),
+ "label": _DL_STATE.get("label", ""),
+ "dl_mb": _DL_STATE.get("dl_mb"),
+ "total_mb": _DL_STATE.get("total_mb"),
+ "statuses": component_downloader.get_component_statuses(),
+ }
+
+
+@app.get("/api/settings/llm-cpp-info")
+async def settings_llm_cpp_info():
+ from backend import hardware
+
+ return {"ok": True, **hardware.HardwareManager.get_llama_cpp_install_plan()}
+
+
+@app.post("/api/settings/llm-cpp-install")
+async def settings_llm_cpp_install(payload: dict):
+ choice = (payload.get("choice") or "auto").lower()
+ if choice not in ("auto", "cpu", "cuda", "vulkan"):
+ return JSONResponse(
+ {"ok": False, "message": f"unknown choice: {choice}"}, status_code=400
+ )
+ with _DL_LOCK:
+ if _DL_STATE["running"]:
+ return JSONResponse({"ok": False, "message": "a download is already running"}, status_code=409)
+ _DL_STATE["running"] = True
+ _DL_STATE["component"] = "llm_cpp_install"
+ _DL_STATE["lines"] = []
+ _DL_STATE["progress"] = None
+ _DL_STATE["label"] = ""
+ _DL_STATE.pop("dl_mb", None)
+ _DL_STATE.pop("total_mb", None)
+ threading.Thread(target=_download_worker, args=("llm_cpp_install", choice), daemon=True).start()
+ return {"ok": True, "running": True}
+
+
+@app.get("/api/settings/llama-server-info")
+async def settings_llama_server_info():
+ """GET /api/settings/llama-server-info β the llama-server download
+ popup's data source. Mirrors the llama-cpp-python detection report: the
+ detected hardware facts plus every build that CAN run on this PC
+ (auto / cpu / cuda12 / cuda13), each with a bilingual reason key."""
+ from backend import component_downloader
+
+ return {"ok": True, **component_downloader.get_llama_server_download_plan()}
+
+
+@app.post("/api/settings/llama-server-install")
+async def settings_llama_server_install(payload: dict):
+ """POST /api/settings/llama-server-install {choice} β download the
+ user-chosen llama-server build (auto / cpu / cuda12 / cuda13) in the
+ SAME shared download thread as /api/settings/download. A garbage choice
+ is refused (400) before any worker spawns."""
+ choice = (payload.get("choice") or "auto").lower()
+ if choice not in ("auto", "cpu", "cuda12", "cuda13"):
+ return JSONResponse(
+ {"ok": False, "message": f"unknown choice: {choice}"}, status_code=400
+ )
+ with _DL_LOCK:
+ if _DL_STATE["running"]:
+ return JSONResponse({"ok": False, "message": "a download is already running"}, status_code=409)
+ _DL_STATE["running"] = True
+ _DL_STATE["component"] = "llama_server_install"
+ _DL_STATE["lines"] = []
+ _DL_STATE["progress"] = None
+ _DL_STATE["label"] = ""
+ _DL_STATE.pop("dl_mb", None)
+ _DL_STATE.pop("total_mb", None)
+ threading.Thread(target=_download_worker, args=("llama_server", choice), daemon=True).start()
+ return {"ok": True, "running": True}
+
+
+@app.get("/api/settings/whisper-server-info")
+async def settings_whisper_server_info():
+ """GET /api/settings/whisper-server-info β the whisper-server download
+ popup's data source. Mirrors the llama-server / llama-cpp-python
+ detection reports: the detected hardware facts plus every build that CAN
+ run on this PC (auto / cpu / cuda11 / cuda12), each with a bilingual
+ reason key."""
+ from backend import component_downloader
+
+ return {"ok": True, **component_downloader.get_whisper_server_download_plan()}
+
+
+@app.post("/api/settings/whisper-server-install")
+async def settings_whisper_server_install(payload: dict):
+ """POST /api/settings/whisper-server-install {choice} β download the
+ user-chosen whisper-server build (auto / cpu / cuda11 / cuda12) in the
+ SAME shared download thread as /api/settings/download. A garbage choice
+ is refused (400) before any worker spawns."""
+ choice = (payload.get("choice") or "auto").lower()
+ if choice not in ("auto", "cpu", "cuda11", "cuda12"):
+ return JSONResponse(
+ {"ok": False, "message": f"unknown choice: {choice}"}, status_code=400
+ )
+ with _DL_LOCK:
+ if _DL_STATE["running"]:
+ return JSONResponse({"ok": False, "message": "a download is already running"}, status_code=409)
+ _DL_STATE["running"] = True
+ _DL_STATE["component"] = "whisper_server_install"
+ _DL_STATE["lines"] = []
+ _DL_STATE["progress"] = None
+ _DL_STATE["label"] = ""
+ _DL_STATE.pop("dl_mb", None)
+ _DL_STATE.pop("total_mb", None)
+ threading.Thread(target=_download_worker, args=("whisper_server", choice), daemon=True).start()
+ return {"ok": True, "running": True}
+
+
+@app.get("/api/settings/pytorch-info")
+async def settings_pytorch_info():
+ """GET /api/settings/pytorch-info β the PyTorch install popup's data
+ source. Mirrors the llama-server / whisper-server / llama-cpp-python
+ detection reports: the detected hardware facts plus every build that CAN
+ run on this PC (auto / cpu / cuda / xpu / rocm), each with a bilingual
+ reason key."""
+ from backend import hardware
+
+ return {"ok": True, **hardware.HardwareManager.get_pytorch_install_plan()}
+
+
+@app.post("/api/settings/pytorch-install")
+async def settings_pytorch_install(payload: dict):
+ """POST /api/settings/pytorch-install {choice} β install the user-chosen
+ PyTorch build (auto / cpu / cuda / xpu / rocm) in the SAME shared
+ download thread as /api/settings/download. A garbage choice is refused
+ (400) before any worker spawns."""
+ choice = (payload.get("choice") or "auto").lower()
+ if choice not in ("auto", "cpu", "cuda", "xpu", "rocm"):
+ return JSONResponse(
+ {"ok": False, "message": f"unknown choice: {choice}"}, status_code=400
+ )
+ with _DL_LOCK:
+ if _DL_STATE["running"]:
+ return JSONResponse({"ok": False, "message": "a download is already running"}, status_code=409)
+ _DL_STATE["running"] = True
+ _DL_STATE["component"] = "fix_env"
+ _DL_STATE["lines"] = []
+ _DL_STATE["progress"] = None
+ _DL_STATE["label"] = ""
+ _DL_STATE.pop("dl_mb", None)
+ _DL_STATE.pop("total_mb", None)
+ threading.Thread(target=_download_worker, args=("fix_env", choice), daemon=True).start()
+ return {"ok": True, "running": True}
+
+
+# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+# Chat WebSocket
+# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+def _clean_unicode_surrogates(obj):
+ """Recursively sanitize invalid Unicode surrogate code points (U+D800 - U+DFFF)
+ from strings, dicts, lists, and tuples so that JSON serialization and WebSocket
+ UTF-8 transmission can never raise UnicodeEncodeError."""
+ if isinstance(obj, str):
+ try:
+ return obj.encode("utf-8", errors="replace").decode("utf-8")
+ except Exception:
+ return "".join(c for c in obj if not (0xD800 <= ord(c) <= 0xDFFF))
+ elif isinstance(obj, dict):
+ return {_clean_unicode_surrogates(k): _clean_unicode_surrogates(v) for k, v in obj.items()}
+ elif isinstance(obj, list):
+ return [_clean_unicode_surrogates(x) for x in obj]
+ elif isinstance(obj, tuple):
+ return tuple(_clean_unicode_surrogates(x) for x in obj)
+ return obj
+
+
+async def _send_ws_json(ws: WebSocket, payload: dict) -> None:
+ """Send a JSON payload over WebSocket with guaranteed surrogate-safe UTF-8
+ encoding. Starlette's ws.send_json leaves lone surrogates in the text string,
+ causing uvicorn's .encode('utf-8') to fail with UnicodeEncodeError.
+ This helper cleans all surrogates and uses ws.send_text."""
+ import json
+
+ clean_payload = _clean_unicode_surrogates(payload)
+ try:
+ text = json.dumps(clean_payload, ensure_ascii=False)
+ safe_text = text.encode("utf-8", errors="replace").decode("utf-8")
+ await ws.send_text(safe_text)
+ except Exception:
+ safe_ascii = json.dumps(clean_payload, ensure_ascii=True)
+ await ws.send_text(safe_ascii)
+
+
+@app.websocket("/ws/chat")
+async def chat_ws(ws: WebSocket):
+ token = ws.query_params.get("token") or ws.headers.get("x-session-token")
+ if not token or token != _SESSION_TOKEN:
+ await ws.close(code=1008)
+ return
+ await ws.accept()
+ try:
+ payload = await ws.receive_json()
+ except Exception:
+ await ws.close()
+ return
+
+ if payload.get("type") != "chat":
+ await ws.close()
+ return
+
+ tab = payload.get("tab", "general")
+ message = payload.get("message", "")
+ history = payload.get("history") or []
+ model_label = payload.get("model_label") or ""
+ lang_key = payload.get("lang", "kh")
+
+ try:
+ if tab == "general":
+ await _stream_general(ws, payload, message, history, model_label, lang_key)
+ elif tab == "rag":
+ await _stream_rag(ws, payload, message, history, model_label, lang_key)
+ elif tab == "deep_research":
+ await _stream_deep_research(ws, payload, message, history, model_label, lang_key)
+ elif tab == "vision":
+ await _stream_vision(ws, payload, message, history, model_label, lang_key)
+ elif tab == "data":
+ await _stream_data(ws, payload, message, history, model_label, lang_key)
+ else:
+ await _send_ws_json(
+ ws, {"type": "error", "message": f"no chat stream for tab '{tab}'"}
+ )
+ except WebSocketDisconnect:
+ pass
+ except Exception:
+ try:
+ await _send_ws_json(ws, {"type": "error", "message": traceback.format_exc()})
+ except Exception:
+ pass
+ finally:
+ try:
+ await ws.close()
+ except Exception:
+ pass
+
+
+async def _run_stream(ws, build_gen, timeout=None, lang_key: str = "kh"):
+ """Run a chat generator in a daemon thread and stream its (history, export)
+ yields to the client as JSON events (update β final, or error). Shared by
+ the general, RAG, Deep Research and Vision WS handlers.
+
+ The generator thread's stdout is teed (ThreadStdoutTee): the app's own
+ `[Tag]`-prefixed status prints β llama-server launch/ready, model load,
+ agent build, β¦ β are drained between yields and streamed to the client
+ as `log` events BEFORE the corresponding update/final event, so the chat
+ answer shows what the terminal shows. All output still reaches the real
+ stdout too.
+
+ While a run is active the live-streaming bus is also owned by this
+ stream: the model wrappers push the incremental text they generate there
+ (see live_stream.py), and the SAME 0.5s live timer forwards it to the
+ client as `live` events ({"type": "live", "reset": bool, "text": str})
+ so the answer bubble grows from the model's ACTUAL output in real time.
+
+ `timeout` (optional seconds): the per-tab generation RUN timeout β a
+ whole-run wall-clock deadline. When a run exceeds it, the client gets a
+ "timeout" event instead (the generator is abandoned mid-run; the daemon
+ thread then exits and any finally-blocks β e.g. the Vision image
+ deletion β still run through the generator's close()). None = no
+ deadline, the run finishes naturally."""
+ import copy
+
+ queue: asyncio.Queue = asyncio.Queue()
+ loop = asyncio.get_running_loop()
+ deadline = (time.monotonic() + timeout) if (timeout and timeout > 0) else None
+
+ from backend.stdio_hardening import ThreadStdoutTee
+
+ def run():
+ # Capture the app's own `[Tag]`-prefixed status prints (llama-server
+ # launch, model load, agent build, β¦) from THIS thread and stream
+ # them to the UI as `log` events β the terminal output shown inside
+ # the chat answer. All output still reaches the real stdout too.
+ from backend.live_stream import get_bus
+
+ bus = get_bus()
+ bus.begin_run() # enable the model wrappers' live token streaming
+
+ tee = ThreadStdoutTee(sys.stdout)
+ sys.stdout = tee
+ tee.attach()
+ # LIVE draining: agent construction + model load block the generator
+ # for a long time with NO yields (the tee is otherwise drained only
+ # between yields), so the construction sequence would only appear in
+ # one lump together with the first step β and stay on screen the
+ # whole run. A timer polls the tee AND the live-streaming bus and
+ # streams them in real time: `log` events carry [Tag] status prints,
+ # `live` events carry the raw generated text tokens (the model's
+ # ACTUAL output growing in the answer bubble).
+ stop_drainer = threading.Event()
+
+ def _live_drain():
+ # 0.2 s polling: fast enough that streamed tokens appear fluid in
+ # the answer bubble (a 0.5 s drain felt stuttery β half-second
+ # text lumps), cheap enough that a long idle run costs nothing.
+ while not stop_drainer.wait(0.2):
+ lines = tee.drain()
+ if lines:
+ loop.call_soon_threadsafe(
+ queue.put_nowait, ("log", None, None, lines)
+ )
+ reset, live_text = bus.drain()
+ if live_text or reset:
+ loop.call_soon_threadsafe(
+ queue.put_nowait,
+ ("live", reset, live_text, ""),
+ )
+
+ drainer = threading.Thread(target=_live_drain, daemon=True)
+ drainer.start()
+ try:
+ gen = build_gen()
+ last = None
+ while True:
+ if deadline is not None and time.monotonic() > deadline:
+ try:
+ gen.close()
+ except Exception:
+ pass
+ loop.call_soon_threadsafe(
+ queue.put_nowait,
+ ("timeout", None, None, tee.drain(flush_partial=True)),
+ )
+ return
+ try:
+ h, ex = next(gen)
+ except StopIteration:
+ break
+ last = (h, ex)
+ # Deep-copy the snapshot: the generator thread keeps mutating
+ # `history` in place while the event loop serializes it.
+ loop.call_soon_threadsafe(
+ queue.put_nowait, ("update", copy.deepcopy(h), None, tee.drain())
+ )
+ if last is not None:
+ loop.call_soon_threadsafe(
+ queue.put_nowait,
+ ("final", copy.deepcopy(last[0]), last[1] or "",
+ tee.drain(flush_partial=True)),
+ )
+ except Exception:
+ loop.call_soon_threadsafe(
+ queue.put_nowait,
+ ("error", None, traceback.format_exc(), tee.drain(flush_partial=True)),
+ )
+ finally:
+ stop_drainer.set()
+ tee.restore()
+ bus.end_run()
+
+ threading.Thread(target=run, daemon=True).start()
+
+ while True:
+ kind, h, ex, lines = await queue.get()
+ if kind == "live":
+ # h = reset flag (bool), ex = accumulated live text.
+ if ex or h:
+ await _send_ws_json(ws, {"type": "live", "reset": bool(h), "text": ex or ""})
+ continue
+ if lines:
+ await _send_ws_json(ws, {"type": "log", "lines": lines})
+ if kind == "update":
+ await _send_ws_json(ws, {"type": "update", "history": h})
+ elif kind == "final":
+ await _send_ws_json(ws, {"type": "final", "history": h, "export": ex or ""})
+ break
+ elif kind == "error":
+ await _send_ws_json(ws, {"type": "error", "message": ex})
+ break
+ elif kind == "timeout":
+ from backend import chat as chat_module
+
+ await _send_ws_json(
+ ws, {"type": "timeout", "message": chat_module.run_timeout_message(lang_key)}
+ )
+ break
+
+
+async def _stream_general(ws, payload, message, history, model_label, lang_key):
+ """Stream chat.chat_general(). The agentic path already chunk-streams the
+ final answer server-side; the direct path's single final yield is
+ revealed client-side. The Generation Settings "Timeout" (whole-run
+ wall-clock deadline, seconds) is enforced at the stream layer β the
+ chat generators themselves have no deadline of their own."""
+ import backend.chat as chat
+
+ await _run_stream(
+ ws,
+ lambda: chat.chat_general(
+ message,
+ history,
+ model_label,
+ use_agentic=bool(payload.get("use_agentic")),
+ use_memory=bool(payload.get("use_memory", True)),
+ lang_key=lang_key,
+ max_steps=payload.get("max_steps"),
+ execution_timeout=payload.get("execution_timeout"),
+ use_tool_calling=bool(payload.get("use_tool_calling", True)),
+ ),
+ # Explicit payload wins; None falls back to the saved per-tab value
+ # (the control on "auto"), else no deadline. Mirrors the step-budget
+ # fallback pattern in chat.chat_general_agentic().
+ timeout=payload.get("timeout") or mr.get_saved_agent_run_timeout("gen"),
+ lang_key=lang_key,
+ )
+
+
+async def _stream_rag(ws, payload, message, history, model_label, lang_key):
+ """Stream chat.chat_rag() with the multi-select retrieval-topic inputs:
+ `themes` / `subthemes` are LISTS (each chunk must match ANY selected
+ value; empty = no filter) and `files` is the list of source filenames
+ to restrict retrieval to. The legacy single-value `theme` / `subtheme`
+ keys are still accepted (backward compat). use_tool_calling defaults
+ True. The "Timeout" whole-run deadline is enforced at the stream layer
+ like General's."""
+ import backend.chat as chat
+
+ theme = payload.get("themes") or payload.get("theme") or ""
+ subtheme = payload.get("subthemes") or payload.get("subtheme") or ""
+
+ await _run_stream(
+ ws,
+ lambda: chat.chat_rag(
+ message,
+ history,
+ model_label,
+ use_agentic=bool(payload.get("use_agentic", True)),
+ use_memory=bool(payload.get("use_memory", True)),
+ theme=theme,
+ subtheme=subtheme,
+ sources=payload.get("files") or [],
+ max_steps=payload.get("max_steps"),
+ searcher_max_steps=payload.get("searcher_max_steps"),
+ execution_timeout=payload.get("execution_timeout"),
+ lang_key=lang_key,
+ use_tool_calling=bool(payload.get("use_tool_calling", True)),
+ visual_retrieval=bool(payload.get("visual_retrieval", False)),
+ ),
+ timeout=payload.get("timeout") or mr.get_saved_agent_run_timeout("rag"),
+ lang_key=lang_key,
+ )
+
+
+async def _stream_deep_research(ws, payload, message, history, model_label, lang_key):
+ """Stream chat.chat_deep_research() β manager planning + delegated
+ web_search_agent calls β with the Playwright browser-tools toggle,
+ headless flag and step/timeout budgets."""
+ import backend.chat as chat
+
+ # Whole-run timeout: explicit payload wins; None falls back to the
+ # saved value (chat.chat_deep_research() resolves the same way for the
+ # agent's own per-step budget).
+ run_timeout = payload.get("timeout") or mr.get_saved_agent_run_timeout("dr")
+
+ await _run_stream(
+ ws,
+ lambda: chat.chat_deep_research(
+ message,
+ history,
+ model_label,
+ use_memory=bool(payload.get("use_memory", True)),
+ use_playwright=bool(payload.get("use_playwright", False)),
+ headless=bool(payload.get("headless", True)),
+ manager_max_steps=payload.get("manager_max_steps") or None,
+ search_max_steps=payload.get("search_max_steps") or None,
+ # The saved-value fallbacks live in chat.chat_deep_research()
+ # (same 'payload None β saved' pattern as the step budgets).
+ timeout=payload.get("timeout") or None,
+ execution_timeout=payload.get("execution_timeout") or None,
+ lang_key=lang_key,
+ use_tool_calling=bool(payload.get("use_tool_calling", True)),
+ ),
+ timeout=run_timeout,
+ lang_key=lang_key,
+ )
+
+
+async def _stream_vision(ws, payload, message, history, model_label, lang_key):
+ """Stream chat.chat_vision(), which yields (history, image_reset, export)
+ β the image_reset slot is always None (keep the uploaded image) and is
+ dropped here. The uploaded image arrives as a temp-file path from
+ /api/upload; it is deleted after the run completes. The "Timeout"
+ whole-run deadline is enforced at the stream layer."""
+ import backend.chat as chat
+
+ image_path = payload.get("image") or None
+ mmproj_label = payload.get("mmproj_label") or ""
+
+ def build():
+ try:
+ for h, _img_reset, ex in chat.chat_vision(
+ message,
+ image_path,
+ history,
+ model_label,
+ bool(payload.get("use_memory", True)),
+ lang_key=lang_key,
+ mmproj_label=mmproj_label,
+ ):
+ yield h, ex
+ finally:
+ if image_path:
+ try:
+ Path(image_path).unlink(missing_ok=True)
+ except OSError:
+ pass
+
+ await _run_stream(
+ ws,
+ build,
+ timeout=payload.get("timeout") or mr.get_saved_agent_run_timeout("vlm"),
+ lang_key=lang_key,
+ )
+
+
+async def _stream_data(ws, payload, message, history, model_label, lang_key):
+ """Stream chat.chat_data() β the Data Analysis tab's chat turn. The
+ uploaded files arrive as temp paths from /api/data/upload; they are
+ deleted after the run completes (same lifecycle as the Vision image)."""
+ import backend.chat as chat
+
+ files = [str(p) for p in (payload.get("files") or []) if p]
+
+ def build():
+ try:
+ yield from chat.chat_data(
+ message,
+ history,
+ model_label,
+ files=files,
+ use_memory=bool(payload.get("use_memory", True)),
+ lang_key=lang_key,
+ max_steps=payload.get("max_steps") or None,
+ worker_max_steps=payload.get("worker_max_steps") or None,
+ execution_timeout=payload.get("execution_timeout") or None,
+ )
+ finally:
+ for p in files:
+ try:
+ Path(p).unlink(missing_ok=True)
+ except OSError:
+ pass
+
+ await _run_stream(
+ ws,
+ build,
+ timeout=payload.get("timeout") or mr.get_saved_agent_run_timeout("data"),
+ lang_key=lang_key,
+ )
+
+
+@app.websocket("/ws/stt/analyse")
+async def stt_analyse_ws(ws: WebSocket):
+ """Stream the STT transcript β Markdown report analysis live, like the
+ chat tabs: the model's generated tokens flow to the client as `live`
+ events (backend.live_stream bus drained by _run_stream) so the report
+ grows in real time, then a final `final` event carries the complete
+ report (in the export slot). Same token/session guard as /ws/chat."""
+ token = ws.query_params.get("token") or ws.headers.get("x-session-token")
+ if not token or token != _SESSION_TOKEN:
+ await ws.close(code=1008)
+ return
+ await ws.accept()
+ try:
+ payload = await ws.receive_json()
+ except Exception:
+ await ws.close()
+ return
+
+ transcript = payload.get("transcript") or ""
+ model_label = payload.get("model_label") or ""
+ lang_key = payload.get("lang", "kh")
+
+ import backend.chat as chat
+
+ if not (transcript or "").strip():
+ l = _lang(lang_key)
+ await _send_ws_json(
+ ws, {"type": "error", "message": l.get("err_stt_no_transcript", "no transcript")}
+ )
+ await ws.close()
+ return
+
+ def build():
+ # chat.analyse_transcript_to_report yields (status, report) tuples β
+ # adapt to the (history, export) contract _run_stream expects: the
+ # report lands in the export slot (the client reads it as the final
+ # answer), and the intermediate status yields pass through as
+ # history-less updates while the model's live tokens stream via the
+ # bus (same as every chat tab).
+ for _status, report in chat.analyse_transcript_to_report(
+ transcript, model_label, lang_key=lang_key
+ ):
+ yield [], report or ""
+
+ try:
+ await _run_stream(ws, build, lang_key=lang_key)
+ except WebSocketDisconnect:
+ pass
+ except Exception:
+ try:
+ await _send_ws_json(ws, {"type": "error", "message": traceback.format_exc()})
+ except Exception:
+ pass
+ finally:
+ try:
+ await ws.close()
+ except Exception:
+ pass
+
+
+@app.websocket("/ws/stt/transcribe")
+async def stt_transcribe_ws(ws: WebSocket):
+ """Stream STT transcription progress live β status messages flow as
+ `log` events and the growing transcript as `update` events, mirroring
+ the chat tabs' streaming pattern. A final `final` event carries the
+ complete transcript.
+
+ The client sends: {audio_file_url?, audio_blob?, stt_label, language}
+ Because WebSocket cannot carry binary multipart, the audio must be
+ uploaded first via POST /api/stt/upload (or the existing POST
+ /api/stt/transcribe endpoint) and the temp path passed, OR the client
+ posts the form data separately and sends the resulting temp path.
+ For simplicity, the client first uploads via a hidden form post, then
+ opens this socket with the returned temp path.
+ """
+ token = ws.query_params.get("token") or ws.headers.get("x-session-token")
+ if not token or token != _SESSION_TOKEN:
+ await ws.close(code=1008)
+ return
+ await ws.accept()
+ try:
+ payload = await ws.receive_json()
+ except Exception:
+ await ws.close()
+ return
+
+ audio_path = payload.get("audio_path") or ""
+ stt_label = payload.get("stt_label") or ""
+ language = payload.get("language") or "auto"
+ lang_key = payload.get("lang") or "kh"
+
+ if not audio_path or not Path(audio_path).is_file():
+ await _send_ws_json(ws, {"type": "error", "message": "no audio file"})
+ await ws.close()
+ return
+
+ from backend import models
+
+ mid = mr.resolve_stt_model_id(stt_label) or mr.DEFAULT_STT_MODEL or None
+
+ try:
+ queue: asyncio.Queue = asyncio.Queue()
+ loop = asyncio.get_running_loop()
+ import threading
+
+ last_text = ""
+
+ def _run():
+ nonlocal last_text
+ try:
+ for chunk in models.transcribe_audio_stream(
+ audio_path, language=language or None, model_id=mid
+ ):
+ text = str(chunk or "").strip()
+ if text.startswith(("β³", "π", "π‘", "π΅", "ποΈ")):
+ loop.call_soon_threadsafe(
+ queue.put_nowait, ("log", text)
+ )
+ else:
+ last_text = text
+ loop.call_soon_threadsafe(
+ queue.put_nowait, ("update", text)
+ )
+ except Exception as e:
+ loop.call_soon_threadsafe(
+ queue.put_nowait, ("error", str(e))
+ )
+ finally:
+ loop.call_soon_threadsafe(
+ queue.put_nowait, ("done", last_text)
+ )
+
+ t = threading.Thread(target=_run, daemon=True)
+ t.start()
+
+ while True:
+ kind, text = await queue.get()
+ if kind == "log":
+ await _send_ws_json(ws, {"type": "log", "message": text})
+ elif kind == "update":
+ await _send_ws_json(ws, {"type": "update", "text": text})
+ elif kind == "error":
+ await _send_ws_json(ws, {"type": "error", "message": text})
+ break
+ elif kind == "done":
+ # Send the final transcript
+ await _send_ws_json(ws, {"type": "final", "text": text})
+ break
+ except WebSocketDisconnect:
+ pass
+ except Exception:
+ try:
+ await _send_ws_json(ws, {"type": "error", "message": traceback.format_exc()})
+ except Exception:
+ pass
+ finally:
+ try:
+ await ws.close()
+ except Exception:
+ pass
+
+
+@app.post("/api/stt/upload")
+async def stt_upload(request: Request):
+ """Upload an audio file for WebSocket-based STT β returns a temp path
+ that the client passes to /ws/stt/transcribe."""
+ form = await request.form()
+ files = form.getlist("audio")
+ paths = _save_uploads(files, "stt")
+ if not paths:
+ return JSONResponse({"ok": False, "message": "no audio uploaded"}, status_code=400)
+ return {"ok": True, "path": paths[0]}
+
+
+
+# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+# Static SPA (must come last so /api/* routes win)
+# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+if (DIST / "assets").is_dir():
+ app.mount("/assets", StaticFiles(directory=str(DIST / "assets")), name="assets")
+
+ if APP_ICON.is_file():
+
+ @app.get("/favicon.png", include_in_schema=False)
+ def favicon():
+ return FileResponse(str(APP_ICON))
+
+ @app.get("/{path:path}", include_in_schema=False)
+ def spa(path: str):
+ f = DIST / path
+ if path and f.is_file():
+ return FileResponse(str(f))
+ index_file = DIST / "index.html"
+ if index_file.is_file():
+ content = index_file.read_text(encoding="utf-8")
+ token_script = f''
+ if "" in content:
+ content = content.replace("", f"{token_script}", 1)
+ else:
+ content = token_script + content
+ return HTMLResponse(content)
+ return JSONResponse({"ok": False, "message": "SPA not built"}, status_code=404)
+
+
+def _reconfigure_stdio():
+ """Harden sys.stdout / sys.stderr for the server process.
+
+ Delegates to the shared backend.stdio_hardening.harden_stdio() β the
+ SINGLE source of truth used by every entry point (app.py, run_webview.py,
+ the frozen runtime hook). Besides forcing UTF-8 + errors=replace (the
+ old emoji/Khmer UnicodeEncodeError fix), it now also REPLACES streams
+ whose OS handle is closed/invalid β the Windows GUI-launch case where
+ `print()` raises `OSError: [WinError 6] The handle is invalid` and
+ kills a whole chat turn (e.g. the `[Model] Starting/reusing llama-server`
+ line in get_llm).
+ """
+ from backend.stdio_hardening import harden_stdio, harden_subprocesses
+ from backend.metadata_hardening import harden_metadata
+
+ harden_stdio()
+ harden_subprocesses()
+ harden_metadata()
+
+
+def run(host: str = "127.0.0.1", port: int = 7862, log_level: str = "warning",
+ progress=None):
+ """Blocking uvicorn entry β call from a background thread inside pywebview.
+
+ `progress` is an optional callable(msg: str) invoked as the server reaches
+ startup milestones (loading model registry, binding the port, β¦). The
+ desktop launcher (run_webview.py) uses it to drive the splash window's
+ live status line; other callers (tools/_launch_web.py, tools/_dev_web.py,
+ tests) leave it None and nothing changes.
+ """
+ _reconfigure_stdio()
+
+ def _report(msg: str):
+ if progress is not None:
+ try:
+ progress(msg)
+ except Exception:
+ pass # a broken status reporter must never kill startup
+
+ _report("Loading model registryβ¦")
+ import uvicorn
+ # The splash says 'Starting the appβ¦' β there is no user-facing server
+ # to announce; uvicorn binds the port behind the scenes.
+ _report("Starting the appβ¦")
+
+ uvicorn.run(app, host=host, port=port, log_level=log_level)