Download backend/report_tools.py from localailb/assistant: direct link, hf CLI and curl.
- Browser
- Download file 22.4 kB
-
https://huggingface.co/spaces/localailb/assistant/resolve/main/backend/report_tools.py
- Command line
-
hf download hf://spaces/localailb/assistant/backend/report_tools.py
-
curl -L -o report_tools.py https://huggingface.co/spaces/localailb/assistant/resolve/main/backend/report_tools.py
22.4 kB
| """report_tools.py β Gradio-free report/model-notice helpers. | |
| These pure functions used to live in `ui/ui.py` (the Gradio UI, now | |
| removed). They are shared by the web API (backend/web_api.py), the | |
| in-process tests, and any consumer that needs report saving / clearing / | |
| deleting / opening without importing a UI framework. This module imports | |
| NOTHING Gradio-related. | |
| Single source of truth for: | |
| - report path resolution + .docx / .txt writers (_answer_docx_path, | |
| _transcript_txt_path), | |
| - filename sanitization + dedupe (_sanitize_report_filename, | |
| _dedupe_report_path), | |
| - the reports tree sweep + per-file delete (_clear_old_reports, | |
| _list_report_files, _delete_report_file), | |
| - the OS "open folder" launcher (_open_folder_in_explorer, | |
| _open_reports_folder, _open_tab_reports_folder), | |
| - the "already downloaded?" model status notice | |
| (get_model_download_notice). | |
| """ | |
| import os | |
| import re | |
| import subprocess as _subprocess | |
| import sys as _sys | |
| from datetime import datetime | |
| from pathlib import Path | |
| from typing import Optional | |
| from backend import model_registry as mr | |
| from backend import models | |
| from backend.docx_export import markdown_text_to_docx | |
| def _sanitize_report_filename(name, ext: str = ".docx") -> str: | |
| """Turn a user-typed report filename into a safe file STEM (no | |
| extension). Returns "" when the name is unusable (empty, or nothing | |
| survives sanitization) β the caller then falls back to the auto | |
| timestamped name. | |
| Sanitization: strips Windows-forbidden filename characters | |
| (<>:"/\\|?* and control chars), trims leading/trailing dots and | |
| whitespace, caps the length (so the full path stays well under | |
| MAX_PATH), and drops a trailing `ext` (the caller's own extension β | |
| ".docx" for reports, ".txt" for transcripts β typed by the user, since | |
| the writer appends it itself). Path separators are removed, so a name | |
| can never escape the report folder. Windows reserved device names | |
| (CON/PRN/AUX/NUL/COM*/LPT*) are refused β creating them would fail on | |
| Windows, so falling back to the timestamp name is friendlier than a | |
| confusing "save failed". Unicode/Khmer filenames survive untouched. | |
| Never raises.""" | |
| try: | |
| if not name: | |
| return "" | |
| name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "", str(name)).strip() | |
| # Leading AND trailing dots/whitespace are stripped β Windows treats | |
| # a trailing dot as a directory marker and a leading dot as hidden. | |
| name = name.strip(". ").strip() | |
| if ext and name.lower().endswith(ext): | |
| name = name[:-len(ext)].strip(". ").strip() | |
| if name.upper() in {"CON", "PRN", "AUX", "NUL"} or ( | |
| name.upper().startswith("COM") and name[3:].isdigit() | |
| ) or (name.upper().startswith("LPT") and name[3:].isdigit()): | |
| return "" | |
| return name[:100] | |
| except Exception: | |
| return "" | |
| def _dedupe_report_path(out_dir: Path, stem: str, ext: str = ".docx") -> Path: | |
| """Return `stem{ext}` β or `stem-2{ext}`, `stem-3{ext}`, β¦ when that | |
| exact file already exists β so a custom filename save never silently | |
| overwrites a previous report/transcript (the auto timestamp names | |
| never collide; the dedupe only matters for user-typed names).""" | |
| candidate = out_dir / f"{stem}{ext}" | |
| if not candidate.exists(): | |
| return candidate | |
| i = 2 | |
| while (out_dir / f"{stem}-{i}{ext}").exists(): | |
| i += 1 | |
| return out_dir / f"{stem}-{i}{ext}" | |
| def _answer_docx_path(markdown_text, tab_key: str, filename: str = "") -> Optional[str]: | |
| """Write report markdown to a .docx inside the tab's per-tab report | |
| folder (user_data/reports/<tab_folder>/ β see model_registry.REPORT_DIRS) | |
| via the shared backend.docx_export converter and return its path. Only | |
| ever called by the "πΎ Save Report" buttons β reports are NEVER | |
| auto-saved. | |
| The filename is optional: a non-empty `filename` (sanitized via | |
| _sanitize_report_filename, deduped against existing files) becomes the | |
| file's stem; an empty/unusable one falls back to the microsecond | |
| timestamped name. Returns None β never raises β when the source is | |
| empty/unusable, the tab key is unknown, or the converter can't produce | |
| a file (e.g. python-docx not installed), so a failed save can never | |
| crash the UI.""" | |
| try: | |
| if not markdown_text: | |
| return None | |
| out_dir = Path(mr.REPORT_DIRS[tab_key]) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| stem = _sanitize_report_filename(filename) | |
| if stem: | |
| out_path = str(_dedupe_report_path(out_dir, stem)) | |
| else: | |
| # datetime (not time.strftime): %f microseconds isn't supported | |
| # by time.strftime on Windows and would raise. | |
| ts = datetime.now().strftime("%Y%m%d-%H%M%S-%f") | |
| out_path = str(out_dir / f"{tab_key}-{ts}.docx") | |
| return markdown_text_to_docx(markdown_text, out_path) | |
| except Exception: | |
| return None | |
| def _transcript_txt_path(transcript, filename: str = "") -> Optional[str]: | |
| """Write a transcript to a .txt inside the STT report folder | |
| (user_data/reports/stt/) and return its path. Only ever called by the | |
| STT tab's "Save Transcript (.txt)" button β transcripts are NEVER | |
| auto-saved. | |
| The optional `filename` (the STT tab's filename Textbox, shared with | |
| the Save Report button) becomes the file's stem when non-empty; an | |
| empty one falls back to the timestamped name. The file is saved as | |
| UTF-8 WITH BOM so Windows Notepad renders Khmer correctly on every | |
| Windows version (plain UTF-8 without BOM can show as mojibake on | |
| older Notepad). Returns None β never raises β when the transcript is | |
| empty/unusable, so the download stays hidden.""" | |
| try: | |
| if not transcript or not transcript.strip(): | |
| return None | |
| out_dir = Path(mr.REPORT_DIRS["stt"]) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| stem = _sanitize_report_filename(filename, ".txt") | |
| if stem: | |
| out_path = _dedupe_report_path(out_dir, stem, ".txt") | |
| else: | |
| # datetime (not time.strftime): %f microseconds isn't supported | |
| # by time.strftime on Windows and would raise. | |
| ts = datetime.now().strftime("%Y%m%d-%H%M%S-%f") | |
| out_path = out_dir / f"stt-transcript-{ts}.txt" | |
| out_path.write_text(transcript, encoding="utf-8-sig") | |
| return str(out_path) | |
| except Exception: | |
| return None | |
| def _clear_old_reports(days) -> tuple: | |
| """Delete report files older than `days` days from every per-tab folder | |
| under user_data/reports/ (model_registry.REPORT_DIRS β general_chat, | |
| rag, deep_research, vision, stt, data_analysis) and return | |
| (deleted_count, days_used). | |
| Per-report ATTACHED FOLDERS (the data tab's user_data/reports/ | |
| data_analysis/<stem>/ folders holding the .docx + its charts) are swept | |
| too β their old report files are deleted and a subfolder emptied by the | |
| sweep is removed. The tab folders themselves are never deleted; missing | |
| dirs are skipped; a file that can't be inspected/unlinked is skipped | |
| (OSError swallowed) so a locked file never aborts the sweep. `days` is | |
| coerced (non-numeric β 30, < 1 β 1) and returned so the caller can echo | |
| the real threshold used in the confirmation message.""" | |
| try: | |
| days = int(days) | |
| except (TypeError, ValueError): | |
| days = 30 | |
| days = max(1, days) | |
| cutoff = datetime.now().timestamp() - days * 86400 | |
| total = 0 | |
| for folder in mr.REPORT_DIRS.values(): | |
| d = Path(folder) | |
| if not d.exists(): | |
| continue | |
| for f in d.iterdir(): | |
| try: | |
| if f.is_file() and f.stat().st_mtime < cutoff: | |
| f.unlink() | |
| total += 1 | |
| elif f.is_dir(): | |
| # A per-report attached folder: sweep its old report | |
| # artifacts too, then drop the folder once emptied. | |
| for g in f.iterdir(): | |
| try: | |
| if g.is_file() and g.stat().st_mtime < cutoff: | |
| g.unlink() | |
| total += 1 | |
| except OSError: | |
| pass | |
| try: | |
| if not any(f.iterdir()): | |
| f.rmdir() | |
| except OSError: | |
| pass | |
| except OSError: | |
| pass | |
| return total, days | |
| def _open_folder_in_explorer(folder: str) -> tuple: | |
| """Ensure `folder` exists and open it in the OS file explorer. | |
| Returns (ok: bool, error_message: str). The folder is created (parents | |
| included) so Explorer never opens a missing path. Uses os.startfile on | |
| Windows, `open` on macOS, and xdg-open elsewhere β the opener is the | |
| only place a platform difference is allowed.""" | |
| base = Path(folder) | |
| try: | |
| base.mkdir(parents=True, exist_ok=True) | |
| except OSError as e: | |
| return False, str(e) | |
| try: | |
| if _sys.platform == "win32": | |
| os.startfile(str(base)) | |
| elif _sys.platform == "darwin": | |
| _subprocess.Popen(["open", str(base)]) | |
| else: | |
| _subprocess.Popen(["xdg-open", str(base)]) | |
| except Exception as e: | |
| return False, str(e) | |
| return True, "" | |
| def _open_reports_dir(base_dir=None): | |
| """Resolve β creating it if needed β the reports base directory. | |
| Pure path resolution (no Explorer β use _open_reports_folder to open | |
| it). `base_dir` overrides the default user_data/reports root so | |
| callers/tests can point at an arbitrary root. Returns a Path (never | |
| raises, never None).""" | |
| base = Path(base_dir) if base_dir is not None else Path(mr.REPORT_BASE_DIR) | |
| try: | |
| base.mkdir(parents=True, exist_ok=True) | |
| except OSError: | |
| pass | |
| return base | |
| _TAB_KEY_ALIASES = { | |
| "gen": "gen", "general": "gen", "general_chat": "gen", | |
| "rag": "rag", | |
| "dr": "dr", "deep_research": "dr", | |
| "vis": "vis", "vision": "vis", | |
| "stt": "stt", | |
| "data": "data", "data_analysis": "data", | |
| } | |
| def _normalize_tab_key(tab_key: Optional[str]) -> Optional[str]: | |
| if not tab_key: | |
| return None | |
| k = str(tab_key).strip().lower() | |
| return _TAB_KEY_ALIASES.get(k, k if k in mr.REPORT_DIRS else None) | |
| def _open_tab_reports_dir(tab_key: str, reports_dir=None): | |
| """Resolve β creating it if needed β ONE tab's own report folder | |
| (user_data/reports/<tab_folder>/) under the reports root. | |
| Pure path resolution (no Explorer β use _open_tab_reports_folder to | |
| open it). The subfolder name comes from model_registry.REPORT_DIRS | |
| ('general_chat' for 'gen', 'deep_research' for 'dr', β¦); the folder is | |
| created on first use so Explorer never opens a missing path. Returns a | |
| Path β never raises. An unknown tab key degrades to a named subfolder | |
| under the reports root.""" | |
| norm_tab = _normalize_tab_key(tab_key) or tab_key | |
| reports = _open_reports_dir(reports_dir) | |
| configured = mr.REPORT_DIRS.get(norm_tab) | |
| if configured: | |
| folder = reports / Path(configured).name | |
| else: | |
| folder = reports / norm_tab | |
| try: | |
| folder.mkdir(parents=True, exist_ok=True) | |
| except OSError: | |
| pass | |
| return folder | |
| def _open_reports_folder() -> tuple: | |
| """Open the reports BASE dir (user_data/reports) in the OS file explorer. | |
| Thin wrapper over the shared _open_folder_in_explorer β see there for | |
| the (ok, error_message) contract. Used by the Settings / About | |
| 'π Open Reports Folder' buttons.""" | |
| return _open_folder_in_explorer(str(_open_reports_dir())) | |
| def _open_tab_reports_folder(tab_key: str) -> tuple: | |
| """Open ONE tab's own report folder (user_data/reports/<tab_folder>/ β | |
| see model_registry.REPORT_DIRS) in the OS file explorer. | |
| Returns (ok: bool, error_message: str) β never raises. An unknown tab | |
| key degrades to (False, message) instead of crashing, and the folder | |
| is created on first use so Explorer never opens a missing path.""" | |
| norm_tab = _normalize_tab_key(tab_key) or tab_key | |
| if norm_tab not in mr.REPORT_DIRS: | |
| return False, f"unknown tab key: {tab_key}" | |
| return _open_folder_in_explorer(str(_open_tab_reports_dir(norm_tab))) | |
| def open_reports_folder_for(tab_key: Optional[str] = None, | |
| specific_path: Optional[str] = None) -> tuple: | |
| """Open a specific report folder, or ONE tab's own report folder when | |
| `tab_key` is a known model_registry.REPORT_DIRS key (the per-tab "Open | |
| Reports Folder" buttons in the Svelte UI), otherwise the reports BASE dir | |
| (Settings / About / KB β tabs without a per-tab report folder). | |
| Returns (ok, message, path) where `path` is the exact folder that was | |
| opened (or attempted). Never raises; an unknown/empty tab key falls | |
| back to the base dir so the button always opens something sensible.""" | |
| if specific_path: | |
| p = Path(specific_path) | |
| if p.is_file(): | |
| p = p.parent | |
| if p.is_dir(): | |
| ok, message = _open_folder_in_explorer(str(p)) | |
| return ok, message, str(p) | |
| norm_tab = _normalize_tab_key(tab_key) | |
| if norm_tab and norm_tab in mr.REPORT_DIRS: | |
| folder_path = str(_open_tab_reports_dir(norm_tab)) | |
| ok, message = _open_tab_reports_folder(norm_tab) | |
| return ok, message, folder_path | |
| ok, message = _open_reports_folder() | |
| return ok, message, str(_open_reports_dir()) | |
| def _list_report_files() -> list: | |
| """Return the saved report files (relative posix paths under | |
| user_data/reports/, e.g. 'general_chat/chat-2026-08-09.docx' or the | |
| data tab's 'data_analysis/report-2026-08-09/report-2026-08-09.docx'), | |
| sorted by file modification time, NEWEST FIRST. | |
| Missing per-tab folders are skipped; only regular files are listed | |
| (per-report attached folders β the data tab's <stem>/ subfolders β are | |
| descended one level so their .docx reports still show in the dropdown); | |
| a file that can't be inspected (OSError) is skipped. The mtime ordering | |
| puts the most recently saved report at the top of the delete dropdown | |
| (alphabetical order put e.g. 'rag-report.docx' above 'chat-β¦' no | |
| matter how old it was). The relative paths double as the dropdown's | |
| display labels AND values, and are the only thing the per-file delete | |
| handler ever touches β it resolves them back against REPORT_BASE_DIR | |
| with a traversal guard.""" | |
| base = Path(mr.REPORT_BASE_DIR) | |
| out = [] | |
| for folder in mr.REPORT_DIRS.values(): | |
| d = Path(folder) | |
| if not d.exists(): | |
| continue | |
| for f in d.iterdir(): | |
| try: | |
| if f.is_file(): | |
| out.append((f.stat().st_mtime, f.relative_to(base).as_posix())) | |
| elif f.is_dir(): | |
| for g in f.iterdir(): | |
| try: | |
| if g.is_file(): | |
| out.append((g.stat().st_mtime, g.relative_to(base).as_posix())) | |
| except (OSError, ValueError): | |
| pass | |
| except (OSError, ValueError): | |
| pass | |
| out.sort(key=lambda item: item[0], reverse=True) | |
| return [rel for _, rel in out] | |
| def _delete_report_file(rel_path) -> tuple: | |
| """Delete a single saved report file given its path relative to | |
| user_data/reports/ and return (ok, error_message). | |
| The relative path is resolved against REPORT_BASE_DIR and MUST stay | |
| inside it β a traversal attempt ("../", absolute path) is rejected and | |
| never touches anything outside the reports folder. A missing/locked file | |
| degrades to (False, message) instead of raising.""" | |
| if not rel_path: | |
| return False, "no file selected" | |
| base = Path(mr.REPORT_BASE_DIR).resolve() | |
| target = (base / rel_path).resolve() | |
| # base not in target.parents also rejects target == base ("."), which | |
| # the relative_to check alone would let through. | |
| if base not in target.parents: | |
| return False, "path escapes the reports folder" | |
| try: | |
| target.unlink() | |
| except OSError as e: | |
| return False, str(e) | |
| # Tidy: deleting a report inside a per-report attached folder (the data | |
| # tab's <stem>/ subfolder) removes the folder once it's emptied β never | |
| # the tab folder itself. | |
| parent = target.parent | |
| if parent != base and parent.is_dir(): | |
| try: | |
| if not any(parent.iterdir()): | |
| parent.rmdir() | |
| except OSError: | |
| pass | |
| return True, "" | |
| def get_model_download_notice(provider_label: str, model_label: str, option_type: str = "llm", lang_key: str = "kh") -> str: | |
| """Returns a dynamic Markdown notice telling the user if the selected model is | |
| already downloaded/cached, local GGUF file, or remote API model.""" | |
| if not model_label: | |
| return "" | |
| if option_type == "llm": | |
| options = mr.MODEL_OPTIONS | |
| provider_map = mr.LLM_PROVIDER_OPTIONS | |
| elif option_type == "vlm": | |
| options = mr.VLM_OPTIONS | |
| provider_map = mr.VLM_PROVIDER_OPTIONS | |
| elif option_type == "stt": | |
| options = mr.STT_OPTIONS | |
| provider_map = mr.STT_PROVIDER_OPTIONS | |
| elif option_type == "embed": | |
| options = mr.EMBED_OPTIONS | |
| provider_map = mr.EMBED_PROVIDER_OPTIONS | |
| else: | |
| options = mr.MODEL_OPTIONS | |
| provider_map = mr.LLM_PROVIDER_OPTIONS | |
| model_id = options.get(model_label, model_label) | |
| provider_id = provider_map.get(provider_label, provider_label) | |
| if option_type == "stt" and provider_id in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON): | |
| # The whisper.cpp providers list DISCOVERED local files + GGUF STT | |
| # presets β NOT STT_OPTIONS (the local-HuggingFace list this | |
| # function defaulted to). A preset label therefore never resolved, | |
| # fell back to the raw label as id, and every downloaded whisper | |
| # model showed the generic "Server Backend Model" text instead of | |
| # its real ready/missing state. | |
| options = mr.get_model_options_for_provider(provider_id, "stt") | |
| model_id = options.get(model_label, model_label) | |
| # A GGUF STT preset id ('repo#ggml-base.bin') must become its | |
| # CONCRETE local path when the file is already downloaded β the β | |
| # branch below stats the path directly, and the multi-root search | |
| # also covers models living in the downloader's fallback folder. | |
| local = mr._find_local_stt_file(model_id) | |
| if local: | |
| model_id = local | |
| is_khmer = (lang_key == "kh") | |
| if provider_id == mr.PROVIDER_HF_API: | |
| if is_khmer: | |
| return f"βοΈ **αααΌααα HF Inference API** (`{model_id}`): ααααΎαααΆαααΎ Hugging Face Cloud (αα·αααΆα αααΆααααα αααΆαααΈααα)" | |
| return f"βοΈ **HF Inference API Model** (`{model_id}`): Runs on Hugging Face Cloud (No local download required)." | |
| elif provider_id == mr.PROVIDER_LITELLM: | |
| if is_khmer: | |
| return f"π **αααΌααα LiteLLM Provider** (`{model_id}`): αααααΆαααα ααΆαα Remote API Endpoint" | |
| return f"π **LiteLLM Provider Model** (`{model_id}`): Routes to remote API endpoint." | |
| elif provider_id == mr.PROVIDER_SERVER: | |
| if os.path.isfile(model_id): | |
| try: | |
| size_gb = os.path.getsize(model_id) / (1024 ** 3) | |
| if is_khmer: | |
| return f"β **α―αααΆα GGUF αααα»ααααΆαααΈα αα½α ααΆαα** (`{os.path.basename(model_id)}`, {size_gb:.2f} GB ααΎααΆα)" | |
| return f"β **Local GGUF File Ready** (`{os.path.basename(model_id)}`, {size_gb:.2f} GB on disk)." | |
| except Exception: | |
| if is_khmer: | |
| return f"β **α―αααΆα GGUF αααα»ααααΆαααΈα αα½α ααΆαα**: `{model_id}`" | |
| return f"β **Local GGUF File Ready**: `{model_id}`" | |
| elif str(model_id).lower().endswith((".gguf", ".ggml", ".bin")): | |
| if is_khmer: | |
| return f"β οΈ **αααα·αααΎαα―αααΆα GGUF αααα»ααααΆαααΈααα**: `{model_id}`" | |
| return f"β οΈ **Local GGUF File Missing**: `{model_id}`" | |
| else: | |
| if is_khmer: | |
| return f"π₯οΈ **αααΌααα Server Backend**: `{model_id}`" | |
| return f"π₯οΈ **Server Backend Model**: `{model_id}`" | |
| # Local HuggingFace / GGUF local file check | |
| if models.is_model_cached(model_id): | |
| if is_khmer: | |
| return f"β **ααΆαααΆααα αα·ααααααΆαα»ααααα»ααααΆαααΈααα½α ααΆαα**: `{model_id}`" | |
| return f"β **Already Downloaded & Cached Locally**: `{model_id}`" | |
| else: | |
| size_gb = models.get_download_size_gb(model_id) | |
| if is_khmer: | |
| size_str = f"αααα αα ~{size_gb:.1f} GB" if size_gb else "αα·αααΉαααα α" | |
| if size_gb is not None and size_gb >= 20: | |
| return ( | |
| f"π¨ **αααΌαααααα ααα ({size_str})**: `{model_id}` ααΉαααΆααα ({size_str}) αααααααΎααΎαααααΌα β " | |
| f"ααΆαααΆαααα’αΆα α αααΆααααααΌαα ααΌαααααΆααααΆα’αααααΆαααΆααααααΆααα’ααΈαααΊαα·αα" | |
| ) | |
| return f"π₯ **αα·αααΆααααΆαααΆααααα**: `{model_id}` ααΉαααΆααα ({size_str}) αααααααΎααΎαααααΌα" | |
| size_str = f"~{size_gb:.1f} GB" if size_gb else "unknown size" | |
| if size_gb is not None and size_gb >= 20: | |
| return ( | |
| f"π¨ **Large Model ({size_str})**: `{model_id}` will download ({size_str}) on first use β " | |
| f"this may take a long time depending on your internet speed." | |
| ) | |
| return f"π₯ **Not Downloaded Yet**: `{model_id}` will download ({size_str}) on first load." | |