Spaces:
Running
Running
Upload 34 files
Browse filesFiles changed (3)
- README.md+100-7
- _utils/_shared_logic.py+6
- app.py+47-14
245 unmodified lines24624724824925025125225325425561 unmodified lines31731831932032132232362 unmodified lines386387388389390391392301 unmodified lines69469569669769869970070110 unmodified lines712713714715716717718245 unmodified lines## ConfigurationConfigure values in **Space β Settings** using the correct surface:- **Secrets** β credentials such as HF/GitHub/GitLab/Bitbucket tokens.- **Variables** β non-sensitive configuration such as repository IDs, token-type labels, booleans, and `RECORD_STORAGE_TARGETS`.See [DATASET_COLLECTION_GUIDANCE.md](./DATASET_COLLECTION_GUIDANCE.md) for the beginner-to-operator storage guide, including exact HF-only, GitHub-only, Primary+Mirror, migration, testing, and deduplication recipes.61 unmodified lines| `BACKEND_URL` | No | `""` | **Path 1** β Explicit upstream URL. All requests forwarded here when set. Use for Docker Model Runner, Ollama, or any custom backend. || `HF_SPACES_MODEL_URL` | No | β | **Path 2** β Custom ZeroGPU Space URL (e.g. `https://scikit-plots-ai-model.hf.space/v1/chat/completions`). Receives requests whose `model` matches `HF_SPACES_MODEL_NAMESPACES`. || `HF_SPACES_MODEL_NAMESPACES` | No | `scikit-plots` | Comma-separated model owner prefixes routed to Path 2 (e.g. `scikit-plots,my-org`). || `ALLOWED_MODELS` | No | bundled public model set | Exact Path-3 provider model IDs accepted by the strict chat contract. The default matches the public models shown by `_example_conf.py`: `Qwen/Qwen2.5-Coder-7B-Instruct`, `Qwen/Qwen2.5-Coder-32B-Instruct`, and `openai/gpt-oss-20b`. || `HF_BASE` | No | `https://router.huggingface.co` | **Path 3** β HF Serverless API base URL. Only used when Path 1 and Path 2 do not match. || `DEFAULT_MODEL` | No | `scikit-plots/Qwen2.5-Coder-7B-Instruct` | Fallback model when the request body omits `"model"`. |62 unmodified lines| Variable | Default | Description ||---|---|---|| `ALLOWED_ORIGINS` | empty | Comma-separated **additional** exact browser origins. The official `https://scikit-plots.github.io` origin is always retained so an environment override cannot accidentally break the shipped documentation. Missing `Origin` remains valid for server-to-server clients. `*` is an explicit insecure compatibility escape hatch and is not authentication. || `DEPLOYMENT_PROFILE` | `compat` | `compat` preserves explicit legacy deployment choices. The hardened Dockerfile sets `strict`, which fails startup as root, rejects wildcard origins and opaque-origin **writes**, and requires verified TLS for all configured Redis authorities. Read-only opaque Share compatibility remains a separate explicit opt-in because local `file://` viewers may need it. || `REDIS_REQUIRE_TLS` | `false` (`true` in strict) | Requires `rediss://`; URL query parameters are rejected so callers cannot disable certificate verification through redis-py URL options. || `REQUIRE_NON_ROOT` | `false` (`true` in strict) | Fails application startup when the process is UID 0 on POSIX. |301 unmodified lines# For Primary + Mirrors, use RECORD_STORAGE_TARGETS instead; see DATASET_COLLECTION_GUIDANCE.md.# Security# Optional extra origins; official https://scikit-plots.github.io is built in.ALLOWED_ORIGINS =# Optional read-only local-file (Origin:null) Share compatibility.# Keep false unless you explicitly need Global Share viewing from file:// pages.SHARE_ALLOW_OPAQUE_ORIGIN = false10 unmodified lines# 1. Liveness probecurl $BASE/health# {"status":"ok","version":"6.8.0"}# Optional deterministic stub rig statuscurl -s $BASE/health | python3 -m json.tool245 unmodified lines24624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934061 unmodified lines40240340440540640740862 unmodified lines471472473474475476477478301 unmodified lines78078178278378478578678778878979079179279379410 unmodified lines805806807808809810811245 unmodified lines## ConfigurationConfigure the Space from **Settings β Variables and secrets**. Hugging Face exposesVariables as non-sensitive deployment configuration and keeps Secrets private. See[Managing Spaces variables and secrets](https://huggingface.co/docs/hub/spaces-overview#managing-secrets).### Variables and secretsUse one simple rule: **configuration goes in Variables; credentials and capabilities go in Secrets**.Both surfaces become environment variables inside the container, so putting a non-secret valuein Secrets still works technically, but it makes maintenance harder and hides which settings areactually sensitive.#### Variables β public / non-sensitive| Name | Required? | Typical value | Notes ||---|---:|---|---|| `RECORD_STORAGE_TARGETS` | Multi-store deployments | JSON array | Provider-neutral Primary + Mirrors topology. May contain repo IDs and `token_env` **names**, never token values. If repository topology itself is confidential, it is acceptable to store this JSON as a Secret instead. || `TRAINING_DATASET_REPO` | Legacy HF-only mode | `scikit-plots/ai-assistant-contributions` | Repository identifier, not a credential. If this is currently stored as a Secret, it can be moved to Variables unless you intentionally treat the repo identity as confidential. Ignored as the active topology when `RECORD_STORAGE_TARGETS` is set. || `ALLOWED_MODELS` | No | comma-separated model IDs | Exact Path-3 model allow-list. Do not use `*`; an explicit model list prevents the proxy from becoming a general-purpose inference relay. || `HF_SPACES_MODEL_NAMESPACES` | No | `scikit-plots` | Model owner prefixes routed through the configured Path-2 model Space. || `ALLOWED_ORIGINS` | Custom sites only | comma-separated origins | Exact browser origins such as `https://docs.example.org`. Origins contain only scheme + host (+ optional port): no path, query, fragment, or trailing page URL. || `ALLOWED_ORIGINS_MODE` | No | `additive` | `additive` keeps the bundled Scikit-plots origins and adds `ALLOWED_ORIGINS`; `replace` trusts only `ALLOWED_ORIGINS` and is the recommended mode for forks/downstream sites that want their own CORS boundary. || `CONTRIBUTION_REVIEW_MODE` | No | `provider-pr` or `ledger` | Native provider PR/MR review or historical ledger review. || `HF_TOKEN_TYPE` | Recommended | `fine-grained` / `read` / `write` | Non-secret classification label for `HF_TOKEN`; avoids `unknown` startup diagnostics. || `HF_DATASET_TOKEN_TYPE` | Legacy HF persistence | `fine-grained` | Non-secret classification label for the dataset-persistence token. |The proxy has two built-in browser origins because this extension is currently deployed on bothScikit-plots documentation sites:```texthttps://scikit-plots.github.iohttps://scikit-plots-learn.readthedocs.io```With the default `ALLOWED_ORIGINS_MODE=additive`, both remain trusted and any`ALLOWED_ORIGINS` entries are appended. A downstream/open-source deployment can take completecontrol without editing `app.py`:```text# Custom/fork deployment: trust only these sitesALLOWED_ORIGINS=https://docs.example.org,https://learn.example.orgALLOWED_ORIGINS_MODE=replace```To add a site while retaining the two Scikit-plots defaults:```textALLOWED_ORIGINS=https://preview.example.orgALLOWED_ORIGINS_MODE=additive```Never use `ALLOWED_ORIGINS=*` in production. CORS is a browser abuse boundary, not authentication;server-to-server clients without an `Origin` header still rely on their own token/capability controls.#### Secrets β private / server-only| Name | Required? | Purpose ||---|---:|---|| `HF_TOKEN` | Path 3 inference | Hugging Face inference credential. Prefer least privilege; it should not also be your broad repository-write token. || `AI_RECORD_STORAGE_TOKEN_HF_PRIMARY` | When referenced by `RECORD_STORAGE_TARGETS` | Example HF Primary write credential. The exact name is configurable through each target's `token_env`. || `AI_RECORD_STORAGE_TOKEN_GITHUB_MIRROR` | When referenced by `RECORD_STORAGE_TARGETS` | Example GitHub Mirror write credential. Use an independent least-privilege token. || `AI_RECORD_STORAGE_TOKEN_*` | Per configured target | Provider-specific HF/GitHub/GitLab/Bitbucket write credential. Only names with this prefix are accepted by storage target configuration. || `HF_DATASET_TOKEN` | Legacy HF-only persistence | Preferred legacy dataset token; fine-grained to the target dataset repository. || `CONTRIBUTION_REVIEW_TOKEN` | Optional | API-driven review/promotion capability. Not required when maintainers review entirely through provider-native PR/MR UI. || `RATE_LIMIT_IDENTITY_SECRET` | Redis rate limiting | HMAC key used to pseudonymize shared rate-limit identities. || `CONTRIBUTION_LEDGER_KEY_SECRET` | Redis contribution ledger | HMAC key used to pseudonymize receipt identifiers. || Redis URLs containing credentials | When Redis is used | Keep `RATE_LIMIT_REDIS_URL`, `SHARE_STORE_REDIS_URL`, and `CONTRIBUTION_LEDGER_REDIS_URL` private when they contain usernames/passwords/tokens. |A practical Scikit-plots Space layout is therefore:```text# VariablesRECORD_STORAGE_TARGETS=<provider-neutral JSON topology>ALLOWED_MODELS=openai/gpt-oss-20b,Qwen/Qwen2.5-Coder-7B-Instruct,Qwen/Qwen2.5-Coder-32B-Instruct,scikit-plots/gpt-oss-20b,scikit-plots/Qwen2.5-Coder-7B-Instruct,scikit-plots/Qwen2.5-Coder-32B-InstructHF_SPACES_MODEL_NAMESPACES=scikit-plotsALLOWED_ORIGINS_MODE=additive# ALLOWED_ORIGINS may remain empty because both current Scikit-plots sites are built in.# Legacy-only variable (not needed as the active topology when RECORD_STORAGE_TARGETS is used)TRAINING_DATASET_REPO=scikit-plots/ai-assistant-contributions# SecretsHF_TOKEN=<inference-token>AI_RECORD_STORAGE_TOKEN_HF_PRIMARY=<repo-scoped-write-token>AI_RECORD_STORAGE_TOKEN_GITHUB_MIRROR=<repo-scoped-write-token>```The proxy never reads provider token values from `RECORD_STORAGE_TARGETS`; it reads only theconfigured `token_env` name and then resolves that environment variable server-side. Keep tokenvalues out of `conf.py`, generated Sphinx HTML, JavaScript, logs, repository URLs, and commit metadata.See [DATASET_COLLECTION_GUIDANCE.md](./DATASET_COLLECTION_GUIDANCE.md) for the beginner-to-operator storage guide, including exact HF-only, GitHub-only, Primary+Mirror, migration, testing, and deduplication recipes.61 unmodified lines| `BACKEND_URL` | No | `""` | **Path 1** β Explicit upstream URL. All requests forwarded here when set. Use for Docker Model Runner, Ollama, or any custom backend. || `HF_SPACES_MODEL_URL` | No | β | **Path 2** β Custom ZeroGPU Space URL (e.g. `https://scikit-plots-ai-model.hf.space/v1/chat/completions`). Receives requests whose `model` matches `HF_SPACES_MODEL_NAMESPACES`. || `HF_SPACES_MODEL_NAMESPACES` | No | `scikit-plots` | Comma-separated model owner prefixes routed to Path 2 (e.g. `scikit-plots,my-org`). || `ALLOWED_MODELS` | No | `DEFAULT_MODEL` + bundled provider models | Exact model IDs accepted by the strict chat contract before routing. The bundled defaults include the configured `DEFAULT_MODEL` plus `Qwen/Qwen2.5-Coder-7B-Instruct`, `Qwen/Qwen2.5-Coder-32B-Instruct`, and `openai/gpt-oss-20b`; Path-2 namespaces remain an additional explicit admission rule. || `HF_BASE` | No | `https://router.huggingface.co` | **Path 3** β HF Serverless API base URL. Only used when Path 1 and Path 2 do not match. || `DEFAULT_MODEL` | No | `scikit-plots/Qwen2.5-Coder-7B-Instruct` | Fallback model when the request body omits `"model"`. |62 unmodified lines| Variable | Default | Description ||---|---|---|| `ALLOWED_ORIGINS` | empty | Comma-separated exact browser origins. In `additive` mode they are appended to the two bundled defaults (`https://scikit-plots.github.io`, `https://scikit-plots-learn.readthedocs.io`). In `replace` mode they are the complete browser allow-list. Missing `Origin` remains valid for server-to-server clients. `*` is an explicit insecure compatibility escape hatch and is not authentication. || `ALLOWED_ORIGINS_MODE` | `additive` | `additive` retains the bundled project origins; `replace` starts from an empty allow-list and trusts only valid entries from `ALLOWED_ORIGINS`. Invalid values fail safely back to `additive`. || `DEPLOYMENT_PROFILE` | `compat` | `compat` preserves explicit legacy deployment choices. The hardened Dockerfile sets `strict`, which fails startup as root, rejects wildcard origins and opaque-origin **writes**, and requires verified TLS for all configured Redis authorities. Read-only opaque Share compatibility remains a separate explicit opt-in because local `file://` viewers may need it. || `REDIS_REQUIRE_TLS` | `false` (`true` in strict) | Requires `rediss://`; URL query parameters are rejected so callers cannot disable certificate verification through redis-py URL options. || `REQUIRE_NON_ROOT` | `false` (`true` in strict) | Fails application startup when the process is UID 0 on POSIX. |301 unmodified lines# For Primary + Mirrors, use RECORD_STORAGE_TARGETS instead; see DATASET_COLLECTION_GUIDANCE.md.# Security# Both current Scikit-plots origins are built in:# https://scikit-plots.github.io# https://scikit-plots-learn.readthedocs.io# Leave empty to use only those defaults, or add exact custom origins.ALLOWED_ORIGINS =ALLOWED_ORIGINS_MODE = additive# Fork/downstream alternative:# ALLOWED_ORIGINS=https://docs.example.org,https://learn.example.org# ALLOWED_ORIGINS_MODE=replace# Optional read-only local-file (Origin:null) Share compatibility.# Keep false unless you explicitly need Global Share viewing from file:// pages.SHARE_ALLOW_OPAQUE_ORIGIN = false10 unmodified lines# 1. Liveness probecurl $BASE/health# {"status":"ok","version":"7.3.0"}# Optional deterministic stub rig statuscurl -s $BASE/health | python3 -m json.tool
1412 unmodified lines14131414141514161417141885 unmodified lines15041505150615071412 unmodified linesPath 3 read timeout (env ``PATH3_TIMEOUT``).``max_body_bytes`` : int``allowed_origins`` : str``hf_token_type`` : strClassified token type for *hf_token* (env ``HF_TOKEN_TYPE``).One of ``"fine-grained"``, ``"read"``, ``"write"``, ``"unknown"``.85 unmodified linesDEFAULT_MAX_BODY_BYTES,),"allowed_origins": os.environ.get("ALLOWED_ORIGINS", "").strip(),}1412 unmodified lines1413141414151416141714181419142085 unmodified lines150615071508150915101511151215131412 unmodified linesPath 3 read timeout (env ``PATH3_TIMEOUT``).``max_body_bytes`` : int``allowed_origins`` : str``allowed_origins_mode`` : strRaw deployment composition mode (``additive`` or ``replace``).``hf_token_type`` : strClassified token type for *hf_token* (env ``HF_TOKEN_TYPE``).One of ``"fine-grained"``, ``"read"``, ``"write"``, ``"unknown"``.85 unmodified linesDEFAULT_MAX_BODY_BYTES,),"allowed_origins": os.environ.get("ALLOWED_ORIGINS", "").strip(),"allowed_origins_mode": (os.environ.get("ALLOWED_ORIGINS_MODE", "additive").strip().lower()or "additive"),}
86 unmodified lines87888990919293899 unmodified lines993994995996997998999100016 unmodified lines10171018101910201021102210231024102510261027102810291030103110321033103410 unmodified lines104510461047104810491050105124 unmodified lines1076107710781079108010811082108310841621 unmodified lines2706270727082709271027112712271327142715271627172718271986 unmodified lines# persistence; fine-grained repo-write is preferred.# HF_WRITE_TOKEN_TYPE Legacy type declaration for HF_WRITE_TOKEN.# Accepted values: fine-grained | read | write.# ALLOWED_ORIGINS Comma-separated additional exact CORS origins. The official docs origin is always included; set * only as an explicit insecure compatibility escape hatch.# RECORD_STORAGE_TARGETS Optional JSON array defining one primary record# store plus mirrors (huggingface/github/gitlab/bitbucket).# Credentials are referenced only through env names with899 unmodified lines# CORS# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ_DEFAULT_ALLOWED_ORIGINS = "https://scikit-plots.github.io"_OFFICIAL_ALLOWED_ORIGINS: tuple[str, ...] = (_DEFAULT_ALLOWED_ORIGINS,)def _normalise_browser_origin(value: str) -> str:16 unmodified linesreturn f"{parsed.scheme.lower()}://{parsed.netloc.lower()}"def _build_allowed_origins(raw: str) -> list[str]:"""Build the exact browser-origin allowlist.The official Scikit-Plots documentation origin is a package-owned trustanchor and cannot be accidentally removed by an ``ALLOWED_ORIGINS``deployment override. The environment variable adds exact origins. Onlyan explicit ``*`` selects wildcard compatibility mode."""text = str(raw or "").strip()if text == "*":return ["*"]merged: list[str] = list(_OFFICIAL_ALLOWED_ORIGINS)for item in text.split(","):item = item.strip() # ruff: ignore[redefined-loop-name]if not item:10 unmodified lines_raw_origins: str = os.environ.get("ALLOWED_ORIGINS", "").strip()_allowed_origins: list[str] = _build_allowed_origins(_raw_origins)#: Optional Share-only compatibility for browser opaque origins such as#: ``file://`` documents, which browsers serialize as ``Origin: null``. This is24 unmodified lines"AI proxy [CORS_WILDCARD]: ALLOWED_ORIGINS=* explicitly enables every browser origin; ""use an exact comma-separated origin list in production.")elif _raw_origins:logger.info("AI proxy CORS: official docs origin retained; ALLOWED_ORIGINS contributes additional exact origins.")#: Trust ``X-Forwarded-For`` only when a known ingress proxy strips/overwrites1621 unmodified linesdef _cors_public_status() -> dict[str, Any]:"""Return public CORS diagnostics without exposing custom/private origins."""wildcard = _allowed_origins == ["*"]return {"official_docs_origin": _DEFAULT_ALLOWED_ORIGINS,"official_docs_origin_allowed": (wildcard or _DEFAULT_ALLOWED_ORIGINS in _allowed_origins),"wildcard": wildcard,"allowed_origin_count": None if wildcard else len(_allowed_origins),"env_semantics": "additive","share_opaque_origin_allowed": SHARE_ALLOW_OPAQUE_ORIGIN,"share_opaque_origin_write_allowed": bool(SHARE_ALLOW_OPAQUE_ORIGIN and SHARE_ALLOW_OPAQUE_ORIGIN_WRITE86 unmodified lines8788899091929394899 unmodified lines9949959969979989991000100110021003100416 unmodified lines1021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210 unmodified lines10631064106510661067106810691070107110721073107424 unmodified lines10991100110111021103110411051106110711081109111011111621 unmodified lines2733273427352736273727382739274027412742274327442745274627472748274927502751275286 unmodified lines# persistence; fine-grained repo-write is preferred.# HF_WRITE_TOKEN_TYPE Legacy type declaration for HF_WRITE_TOKEN.# Accepted values: fine-grained | read | write.# ALLOWED_ORIGINS Comma-separated exact CORS origins. Additive by default; use ALLOWED_ORIGINS_MODE=replace for downstream sites.# ALLOWED_ORIGINS_MODE additive (default) keeps built-in Scikit-plots origins; replace trusts only ALLOWED_ORIGINS.# RECORD_STORAGE_TARGETS Optional JSON array defining one primary record# store plus mirrors (huggingface/github/gitlab/bitbucket).# Credentials are referenced only through env names with899 unmodified lines# CORS# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ_DEFAULT_ALLOWED_ORIGINS: tuple[str, ...] = ("https://scikit-plots.github.io","https://scikit-plots-learn.readthedocs.io",)_ALLOWED_ORIGIN_MODES: frozenset[str] = frozenset({"additive", "replace"})def _normalise_browser_origin(value: str) -> str:16 unmodified linesreturn f"{parsed.scheme.lower()}://{parsed.netloc.lower()}"def _normalise_allowed_origins_mode(value: str) -> str:"""Return the supported CORS composition mode without echoing bad input."""mode = str(value or "additive").strip().lower() or "additive"if mode not in _ALLOWED_ORIGIN_MODES:logger.warning("AI proxy [CORS_MODE_INVALID]: invalid ALLOWED_ORIGINS_MODE; using additive defaults.")return "additive"return modedef _build_allowed_origins(raw: str, *, mode: str = "additive") -> list[str]:"""Build the exact browser-origin allowlist.``additive`` retains the package defaults and appends deployment-specificexact origins. ``replace`` starts empty so downstream/open-source deploymentscan own their complete browser-origin trust boundary without editing source.Only an explicit ``*`` selects wildcard compatibility mode."""text = str(raw or "").strip()if text == "*":return ["*"]selected_mode = _normalise_allowed_origins_mode(mode)merged: list[str] = (list(_DEFAULT_ALLOWED_ORIGINS) if selected_mode == "additive" else [])for item in text.split(","):item = item.strip() # ruff: ignore[redefined-loop-name]if not item:10 unmodified lines_raw_origins: str = os.environ.get("ALLOWED_ORIGINS", "").strip()ALLOWED_ORIGINS_MODE: str = _normalise_allowed_origins_mode(os.environ.get("ALLOWED_ORIGINS_MODE", "additive"))_allowed_origins: list[str] = _build_allowed_origins(_raw_origins, mode=ALLOWED_ORIGINS_MODE)#: Optional Share-only compatibility for browser opaque origins such as#: ``file://`` documents, which browsers serialize as ``Origin: null``. This is24 unmodified lines"AI proxy [CORS_WILDCARD]: ALLOWED_ORIGINS=* explicitly enables every browser origin; ""use an exact comma-separated origin list in production.")elif ALLOWED_ORIGINS_MODE == "replace":logger.info("AI proxy CORS: replacement mode active; only exact ALLOWED_ORIGINS entries are trusted.")elif _raw_origins:logger.info("AI proxy CORS: built-in documentation origins retained; ALLOWED_ORIGINS contributes additional exact origins.")#: Trust ``X-Forwarded-For`` only when a known ingress proxy strips/overwrites1621 unmodified linesdef _cors_public_status() -> dict[str, Any]:"""Return public CORS diagnostics without exposing custom/private origins."""wildcard = _allowed_origins == ["*"]primary_default = _DEFAULT_ALLOWED_ORIGINS[0]return {# Backward-compatible singular fields refer to the primary project origin."official_docs_origin": primary_default,"official_docs_origin_allowed": (wildcard or primary_default in _allowed_origins),"default_allowed_origin_count": len(_DEFAULT_ALLOWED_ORIGINS),"default_allowed_origins_allowed": (wildcard or all(origin in _allowed_origins for origin in _DEFAULT_ALLOWED_ORIGINS)),"wildcard": wildcard,"allowed_origin_count": None if wildcard else len(_allowed_origins),"env_semantics": ALLOWED_ORIGINS_MODE,"share_opaque_origin_allowed": SHARE_ALLOW_OPAQUE_ORIGIN,"share_opaque_origin_write_allowed": bool(SHARE_ALLOW_OPAQUE_ORIGIN and SHARE_ALLOW_OPAQUE_ORIGIN_WRITE
README.md+100-7
_utils/_shared_logic.py+6
app.py+47-14