repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
cs249r_book | interviews/vault-cli/scripts/regenerate_format_markers.py | .py | #!/usr/bin/env python3
"""Regenerate marker-compliant common_mistake / napkin_math via Gemini.
Phase 6 pre-flight (2026-05-04): after apply_format_skip_level.py drained
the 41 entangled holdouts, 36 published YAMLs still have malformed
markers. The audit either had no proposal for these or the proposal
itself didn't f... | 252 | 9,729 |
cs249r_book | interviews/vault-cli/scripts/diagnose_chain_coverage.py | .py | #!/usr/bin/env python3
"""Diagnose chain coverage by (track, topic) bucket.
For each (track, topic) bucket of published questions, reports how many
questions live in the bucket and how many chains currently cover any of
them. Surfaces two lists worth a second-pass Gemini sweep:
- ``uncovered_buckets``: β₯3 published... | 213 | 7,404 |
cs249r_book | interviews/vault-cli/scripts/check_chain_decay.py | .py | #!/usr/bin/env python3
"""Detect chain decay β questions that have drifted semantically away from
their chain mates after an edit.
Phase 4.7 of CHAIN_ROADMAP.md. **Advisory, not blocking** on first ship.
Run as a manual gut-check after editing chain-member questions, or wire
into pre-commit if you want it on every cha... | 259 | 9,478 |
cs249r_book | interviews/vault-cli/scripts/pre_commit_corpus_guard.py | .py | #!/usr/bin/env python3
"""Pre-commit hook guarding vault/corpus.json from direct edits.
Per ARCHITECTURE.md Β§11.1 (fixes C-2): YAML is the sole authoring surface from
Day 1 of Phase 1. ``corpus.json`` is generated-only; this hook refuses any
commit that touches it unless the commit carries the override trailer.
Insta... | 76 | 2,443 |
cs249r_book | interviews/vault-cli/scripts/audit_math.py | .py | #!/usr/bin/env python3
"""Independent math verifier for question napkin_math blocks.
Standalone tool β runs ONE focused Gemini call per question to re-derive
the napkin_math arithmetic from scratch, then compares against what's
written. Catches calculation errors, unit-conversion mistakes, and
conclusions that don't f... | 317 | 11,429 |
cs249r_book | interviews/vault-cli/scripts/_batching.py | .py | """Shared batching helper for Gemini-CLI prompts.
Generalized from audit_chains_with_gemini.py:batch_chains and
build_chains_with_gemini.py:plan_batches. Pack a list of items into
batches whose serialized JSON payload stays under MAX_PROMPT_CHARS,
leaving wrapper room for the prompt scaffolding.
Used by:
- audit_co... | 109 | 3,835 |
cs249r_book | interviews/vault-cli/scripts/mass_apply_corrections.py | .py | #!/usr/bin/env python3
"""Mass-apply low-risk Gemini-proposed corrections without prompting.
Reads a 01_audit.json from a --propose-fixes run, walks rows with
suggested_corrections, classifies each by risk, and auto-applies the
LOW-risk ones. HIGH-risk corrections (anything that rewrites
realistic_solution β i.e., mat... | 407 | 15,883 |
cs249r_book | interviews/vault-cli/scripts/verify_math_corrections.py | .py | #!/usr/bin/env python3
"""Verify Gemini-proposed math corrections via an independent Gemini pass.
The original audit run flagged ~376 questions with math errors and
proposed napkin_math + realistic_solution rewrites. Auto-applying
those without verification is risky β we'd be trusting Gemini's
fix without a second eye... | 408 | 15,769 |
cs249r_book | interviews/vault-cli/scripts/check_reviewer_identity.py | .py | #!/usr/bin/env python3
"""CI check: `vault promote --reviewed-by` cannot be spoofed.
Closes Gemini R5-H-3. ARCHITECTURE.md Β§13 requires the reviewer identity in
a promotion PR to match the committer email; without this check, any
contributor can promote drafts claiming to be someone else.
Runs in CI on every PR touch... | 131 | 4,776 |
cs249r_book | interviews/vault-cli/scripts/summarize_audit.py | .py | #!/usr/bin/env python3
"""Summarize an audit_corpus_batched run into an AUDIT_FINDINGS markdown.
Reads a 01_audit.json file produced by audit_corpus_batched.py and
emits a human-readable triage doc with:
- per-gate pass/fail/error counts
- per-track per-gate failure rate matrix
- top failure categories (level_f... | 410 | 16,427 |
cs249r_book | interviews/vault-cli/scripts/check_registry_append_only.py | .py | #!/usr/bin/env python3
"""CI check: ``id-registry.yaml`` is append-only.
Rejects PRs that remove or reorder lines from ``interviews/vault/id-registry.yaml``
β the registry is the C-5 load-bearing structure. Compares the file's lines
between the PR base and HEAD; ensures every base-line is still present and
in the same... | 66 | 2,049 |
cs249r_book | interviews/vault-cli/src/vault_cli/yaml_io.py | .py | """Hardened YAML I/O.
Wraps ``yaml.safe_load`` with limits that defeat billion-laughs, unbounded
string allocation, and deeply nested payloads. Every vault YAML load goes
through this module β never call ``yaml.load`` directly.
Implements REVIEWS.md H-7 (YAML DoS defenses).
"""
from __future__ import annotations
im... | 92 | 3,023 |
cs249r_book | interviews/vault-cli/src/vault_cli/main.py | .py | """Top-level Typer entry point for the ``vault`` CLI.
Subcommands are added incrementally as phases land. At Phase 0 the app surfaces
only ``--version`` and a help panel β subcommands become real starting Phase 1.
"""
from __future__ import annotations
import typer
from rich.console import Console
from vault_cli._v... | 119 | 2,780 |
cs249r_book | interviews/vault-cli/src/vault_cli/models.py | .py | """Pydantic models for vault questions (schema v1.0).
Enum values are imported from the vault's single source of truth at
``interviews/vault/schema/enums.py``. See also the LinkML schema at
``interviews/vault/schema/question_schema.yaml``.
v1.0 (2026-04-21): classification is now encoded in YAML fields rather than
th... | 443 | 15,100 |
cs249r_book | interviews/vault-cli/src/vault_cli/policy.py | .py | """Release-policy filter predicate β SINGLE source of truth.
No consumer (paper exporter, site, D1 migration emitter) may re-implement this
logic. The import-graph CI check enforces that. See ARCHITECTURE.md Β§11.3 and
REVIEWS.md H-21.
"""
from __future__ import annotations
from collections.abc import Iterable, Mappi... | 56 | 1,902 |
cs249r_book | interviews/vault-cli/src/vault_cli/_version.py | .py | """Canonical version string.
Keep in sync with ``pyproject.toml``. The CLI reports this via ``vault --version``.
"""
__version__ = "0.1.0"
| 7 | 141 |
cs249r_book | interviews/vault-cli/src/vault_cli/__init__.py | .py | """StaffML vault CLI.
Authoring, building, and releasing the StaffML question vault.
See ARCHITECTURE.md (interviews/vault/ARCHITECTURE.md) for design intent.
"""
from vault_cli._version import __version__
__all__ = ["__version__"]
| 11 | 236 |
cs249r_book | interviews/vault-cli/src/vault_cli/legacy_export.py | .py | """Legacy-JSON exporter (v1.1: chains as sidecar metadata).
Regenerates the ``corpus.json`` artifact in the shape the Next.js frontend
expects (field set + array-of-items). Driven from the v1.0 YAML source
plus the ``chains.json`` sidecar (authoritative chain registry), producing
a deterministic, byte-stable JSON.
v1... | 408 | 14,817 |
cs249r_book | interviews/vault-cli/src/vault_cli/validator.py | .py | """Invariant checker.
Implements the tiered checks in ARCHITECTURE.md Β§5. Fast-tier checks run in
the pre-commit hook; structural-tier checks run in CI; slow-tier checks run
nightly.
This module is the engine; tier selection and reporting are in
``commands/check.py``.
"""
from __future__ import annotations
import r... | 605 | 22,687 |
cs249r_book | interviews/vault-cli/src/vault_cli/release.py | .py | """Release artifact management.
Implements ARCHITECTURE.md Β§4.2 primitives (snapshot, migrations emit,
export paper, tag) and Β§4.3 composed `publish`. Staging uses
``releases/.pending-<v>/`` with atomic ``rename(2)`` as the final step
(fixes C-7 non-atomic publish).
"""
from __future__ import annotations
import json... | 277 | 10,041 |
cs249r_book | interviews/vault-cli/src/vault_cli/paths.py | .py | """Path utilities for the vault layout.
Classification lives in the YAML body, never in the path. The path mirrors
two body fields for navigability:
``vault/questions/<track>/<competency_area>/<id>.yaml``
A fast-tier invariant in the loader verifies that the YAML's ``track`` and
``competency_area`` fields match th... | 130 | 4,102 |
cs249r_book | interviews/vault-cli/src/vault_cli/hashing.py | .py | """Canonical hashing for content_hash and release_hash.
Implements ARCHITECTURE.md Β§3.5. The hashes are over *inputs* (canonicalized
JSON of whitelisted semantic fields), never over SQLite binary. This is what
makes the corpus academically citable and reproducible.
Canonicalization version ``CANON_VERSION`` is pinned... | 115 | 4,530 |
cs249r_book | interviews/vault-cli/src/vault_cli/loader.py | .py | """Walk ``vault/questions/`` -> in-memory Question records (schema v1.1).
Classification comes from the YAML body, not the path. The loader enforces
one cheap structural invariant: filename prefix must match yaml.track.
v1.1: chains.json is the authoritative chain registry. The loader joins
sidecar chain data onto ea... | 135 | 4,440 |
cs249r_book | interviews/vault-cli/src/vault_cli/compiler.py | .py | """YAML β SQLite compiler.
Produces ``vault.db`` as a build artifact. Consumed by:
- ``vault export paper`` (SQL β LaTeX macros),
- D1 migration emitter (SQL β UPSERT deltas),
- ``vault serve`` via Datasette for ad-hoc exploration.
The SQLite file is never hashed directly (ARCHITECTURE.md Β§3.5 β not
byte-reproducible... | 388 | 13,748 |
cs249r_book | interviews/vault-cli/src/vault_cli/ship.py | .py | """Coordinator for ``vault ship`` β atomic release across D1 + Next.js + paper.
Implements ARCHITECTURE.md Β§6.1.1 commit protocol and closes Dean R3-NH-1.
Ordering (load-bearing, Β§6.1.1):
1. D1 deploy (rollback: R2 snapshot restore; always works)
2. Next.js deploy (rollback: wrangler pa... | 234 | 8,223 |
cs249r_book | interviews/vault-cli/src/vault_cli/exit_codes.py | .py | """Stable exit-code taxonomy for the ``vault`` CLI.
Documented in ``vault-cli/docs/EXIT_CODES.md`` and referenced from
ARCHITECTURE.md Β§4.6. Never renumber an existing code β scripts pin to these.
"""
from enum import IntEnum
class ExitCode(IntEnum):
"""Process exit codes emitted by ``vault`` subcommands.
... | 31 | 950 |
cs249r_book | interviews/vault-cli/src/vault_cli/book_refs.py | .py | """Topic β textbook chapter resolution for the StaffML "Learn more" funnel.
Every question carries a ``topic`` (one of the 87 curated taxonomy ids). The
``schema/topic_chapter_map.yaml`` file maps each topic to the book chapter(s)
that develop it. This module joins the two so the build can emit a ``book_refs``
list on... | 165 | 6,403 |
cs249r_book | interviews/vault-cli/src/vault_cli/chains/rescue.py | .py | """Rescue suggestions for orphan singleton chains.
For each orphan, find ranked candidate questions in the same (track, topic)
bucket that could plausibly extend the chain. Honors structural constraints:
single-topic, Bloom-monotonic level adjacency, candidate not already chained.
Pure embedding-based ranking β no LL... | 200 | 6,993 |
cs249r_book | interviews/vault-cli/src/vault_cli/chains/audit.py | .py | """Chain audit: orphans, position drift, stale registry, similarity drift.
Reads the YAML corpus + chains.json, computes a current snapshot of chain
health, and emits a report. Read-only β no mutations.
"""
from __future__ import annotations
import json
from collections import defaultdict
from dataclasses import asd... | 216 | 7,752 |
cs249r_book | interviews/vault-cli/src/vault_cli/chains/__init__.py | .py | """Chain audit and rescue suggestions.
Three layers:
- embeddings: cached sentence-transformer embeddings per question
- audit: orphans, position drift, stale-registry detection
- rescue: ranked merge candidates for orphan singletons
Embedding-only by design β no LLM in the hot path. The structural
constraints ... | 12 | 464 |
cs249r_book | interviews/vault-cli/src/vault_cli/chains/embeddings.py | .py | """Sentence embeddings for chain similarity.
Embeds (scenario + question + realistic_solution) with BGE-small. Caches
to a content-hashed sidecar so re-runs only re-embed changed questions.
The sidecar is gitignored (large, reproducible). A small manifest is
committed (interviews/vault/embeddings-manifest.json) recor... | 163 | 5,232 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/serve_api.py | .py | """``vault api`` and ``vault serve`` β local dev surfaces.
``vault api`` mirrors the production Worker endpoint surface from a local
vault.db so contributors can run the site without a Cloudflare account
(REVIEWS.md H-17 resolution).
``vault serve`` launches Datasette for ad-hoc exploration of vault.db.
"""
from __f... | 129 | 5,472 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/dup.py | .py | """``vault dup`` β acknowledge scenario-dedup false positives.
The LSH scenario-dedup invariant (nightly tier) flags pairs of questions
whose Jaro-Winkler similarity exceeds 0.95. Some of those are legitimate
templates (e.g., "How do you diagnose KV-cache saturation on A100/H100/H200?")
that share a common prefix. Thi... | 124 | 4,369 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/generate.py | .py | """``vault generate`` β LLM-assisted question generation (ARCHITECTURE.md Β§12).
Draws exemplars ONLY from ``vault/exemplars/`` (never from the general corpus).
Outputs to ``vault/drafts/`` with ``status: draft``, ``provenance: llm-draft``.
Use ``vault promote`` to move drafts into the published corpus after human revi... | 478 | 18,861 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/audit.py | .py | """``vault audit`` β Gemini-driven corpus audit + correction workflow.
Subcommands:
vault audit run [--all|--tracks|--qids] [--propose-fixes] ...
Wraps audit_corpus_batched.py. Audits the corpus (or a subset)
against the four Gemini-judge gates (level_fit, coherence,
math_correct, plus the... | 223 | 7,911 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/codegen.py | .py | """``vault codegen`` β regenerate shared artifacts from the LinkML schema (B.7).
Codegen contract (ARCHITECTURE.md Β§13, Soumith H-NEW-3): PR authors run
``vault codegen`` locally and commit the regenerated files; CI runs
``vault codegen --check`` which re-runs in a tempdir and diffs. CI never
auto-pushes follow-up com... | 115 | 4,536 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/stats.py | .py | """``vault stats`` β scorecard over vault.db (B.8).
Also wires the ``--exemplar-coverage`` audit from scripts/exemplar_coverage_audit.py
into the CLI surface (ARCHITECTURE.md Β§14 Phase 0 milestone; Chip R3-H3).
"""
from __future__ import annotations
import json
import sqlite3
import subprocess
import sys
from pathli... | 111 | 4,466 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/promote.py | .py | """``vault promote`` β move drafts to published (B.12 / Β§4.4).
Sets ``status: published`` and bumps ``provenance: llm-draft`` β
``llm-then-human-edited`` (since promoting implies human review). Records
the reviewer via ``--reviewed-by`` (must match the committer email per
Soumith L-NEW-1; CI enforces).
"""
from __fut... | 120 | 4,525 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/chain.py | .py | """``vault chain`` β browse and inspect question chains.
Subcommands:
vault chain ls [--track --topic] list chains with counts + spans
vault chain show <chain-id> walk a chain end-to-end
A chain links questions on a single topic into a progression, usually
across Bloom's levels. β32% o... | 190 | 7,366 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/lint.py | .py | """``vault lint`` β author-facing linter for question YAMLs.
Usage:
vault lint path/to/file.yaml
vault lint interviews/vault/questions/cloud/
vault lint --all
Emits three severities:
ERROR β schema violation; question cannot be loaded
WARNING β likely misclassification (zone-level affinity mis... | 237 | 8,214 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/authoring.py | .py | """Authoring primitives: new, edit, rm, restore, move.
Phase-1 minimal implementations. Each command performs the core operation with
validation and typed-confirmation safety; advanced flags (batch mode, editor
multi-file) are Phase-1.x follow-ups.
"""
from __future__ import annotations
import hashlib
import os
impo... | 572 | 24,655 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/diff_cmd.py | .py | """``vault diff <from> <to> [--classify]`` β compare two release artifacts (B.10).
Classifies each modification as cosmetic / semantic / structural per Β§4 of
ARCHITECTURE.md so maintainers can spot breaking changes before ship.
"""
from __future__ import annotations
import json
import sqlite3
from dataclasses import... | 136 | 5,280 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/check.py | .py | """``vault check`` β run invariant checks against vault/questions/."""
from __future__ import annotations
import json
from pathlib import Path
import typer
from rich.console import Console
from vault_cli.exit_codes import ExitCode
from vault_cli.loader import load_all
from vault_cli.validator import fast_tier, run_... | 88 | 3,443 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/show.py | .py | """``vault show`` β inspect one question with its chain context.
Usage:
vault show cloud-0185
Output:
- full classification (track/level/zone/topic/competency_area/bloom_level/phase)
- title + scenario preview
- validation + human-review lineage
- every chain the question belongs to, with prev/nex... | 122 | 4,950 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/release.py | .py | """Release commands: snapshot, migrations emit, export paper, tag, publish, verify."""
from __future__ import annotations
import json
import re
import sqlite3
import subprocess
from datetime import UTC, datetime
from pathlib import Path
import typer
from rich.console import Console
from vault_cli.compiler import bu... | 930 | 42,730 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/ls.py | .py | """``vault ls`` β browse questions with axis filters.
One-line-per-question output, aligned columns, filterable on every
first-class classification axis. Powers the "I want to see level at a
glance" workflow without opening individual YAMLs.
Usage:
vault ls # every question in the vaul... | 96 | 3,882 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/build.py | .py | """``vault build`` β compile vault/questions/ β vault.db."""
from __future__ import annotations
import json
from pathlib import Path
import typer
from rich.console import Console
from rich.table import Table
from vault_cli.compiler import build as compile_build
from vault_cli.exit_codes import ExitCode
from vault_c... | 198 | 8,539 |
cs249r_book | interviews/vault-cli/src/vault_cli/commands/doctor.py | .py | """``vault doctor`` β diagnostic subchecks (B.11).
Each subcheck is independently runnable via ``--check <name>``. Machine-readable
output via ``--json`` emits one ``{check, status, detail}`` object per row.
Exit 0 if all green; 1 if any red.
"""
from __future__ import annotations
import json
import os
import re
imp... | 306 | 11,551 |
cs249r_book | interviews/paper/scripts/analyze_corpus.py | .py | #!/usr/bin/env python3
"""Build corpus_stats.json for paper figures from the **served-question** lineage.
**Preferred:** ``interviews/vault/vault.db`` β the same SQLite file that
``interviews/vault-cli/scripts/ship_d1.py`` serializes to Cloudflare D1 (``SELECT β¦ FROM
questions`` / ``chains`` / ``chain_questions``). Th... | 573 | 23,997 |
cs249r_book | interviews/paper/scripts/validate_refs.py | .py | #!/usr/bin/env python3
"""Validate bibliography entries in paper.bbl against CrossRef.
Reads paper.bbl from the paper directory, extracts each \\bibitem's rough
title, queries CrossRef, and reports whether a match was found. Useful as a
spot-check after large bibliography edits to catch typos, wrong years, or
silently... | 70 | 2,231 |
cs249r_book | interviews/paper/scripts/generate_macros.py | .py | #!/usr/bin/env python3
"""Generate LaTeX macros β Phase-2 thin wrapper over ``vault export-paper``.
The figures pipeline (unchanged) still uses a **generated** monolithic JSON from
``vault build --local-json`` (see ``analyze_corpus.py``) for
``corpus_stats.json``. This entry point is **not** the stats sidecar.
The Ph... | 86 | 3,255 |
cs249r_book | interviews/paper/scripts/generate_figures.py | .py | #!/usr/bin/env python3
"""Generate publication-quality data figures for the StaffML paper.
Pipeline: generated corpus.json (``vault build --local-json``) + chains
β analyze_corpus.py β corpus_stats.json β THIS β PDFs
Run: python3 generate_figures.py
(or: make figures)
Reads: corpus_stats.json (structured stats f... | 421 | 15,285 |
cs249r_book | interviews/staffml/scripts/parse_glossary.py | .py | #!/usr/bin/env python3
"""Parse MLSysBook glossary QMD files and produce a JSON glossary
for the StaffML interview platform's acronym hover tooltip feature.
Source files:
- vol1: book/quarto/contents/vol1/backmatter/glossary/glossary.qmd
- vol2: book/quarto/contents/vol2/backmatter/glossary/glossary.qmd
Output:
... | 396 | 13,422 |
cs249r_book | interviews/staffml/scripts/validate-vault.py | .py | #!/usr/bin/env python3
"""Sparse vault sanity check for the StaffML deploy.
Validates the small committed metadata files that ship in the repo:
``taxonomy.json`` and ``vault-manifest.json``. Confirms taxonomy has
concepts, manifest has a question count, and track distributions add up.
Per-question deep validation (sc... | 126 | 3,929 |
cs249r_book | interviews/staffml/scripts/e2e-smoke.py | .py | #!/usr/bin/env python3
"""Headless-Chromium smoke test for the built Next.js export.
Runs in CI after `npm run build`. Starts a static file server from
`interviews/staffml/out/`, loads a handful of critical routes in
Playwright, and fails the job if any of these invariants break:
1. HTTP 200 on every page
2. No u... | 183 | 6,600 |
ChatGPT | setup.py | .py | from pathlib import Path
from setuptools import find_namespace_packages
from setuptools import setup
DOCS_PATH = Path(__file__).parents[0] / "docs/README.md"
PATH = Path("README.md")
if not PATH.exists():
with open(DOCS_PATH, encoding="utf-8") as f1:
with open(PATH, "w+", encoding="utf-8") as f2:
... | 56 | 2,097 |
ChatGPT | tests/test_recipient.py | .py | import asyncio
import json
from revChatGPT.V1 import AsyncChatbot
from revChatGPT.V1 import Chatbot
config = json.load(open("/home/acheong/.config/revChatGPT/config.json"))
async def main() -> None:
chatbot = AsyncChatbot(config)
async for message in chatbot.ask("Hello, how are you?"):
print(message... | 25 | 548 |
ChatGPT | src/revChatGPT/utils.py | .py | import re
from typing import Set
from prompt_toolkit import prompt
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.key_binding import KeyBin... | 93 | 2,667 |
ChatGPT | src/revChatGPT/__main__.py | .py | """
Main CLI
"""
import argparse
import sys
from . import __version__
from . import typings as t
from . import V1
from . import V3
__all__ = ()
def main() -> None:
"""
main function for CLI
"""
parser = argparse.ArgumentParser(
description="ChatGPT - A command-line interface to OpenAI's Chat... | 66 | 1,724 |
ChatGPT | src/revChatGPT/__init__.py | .py | """
The __init__ file does not a main file
You can import the following module to use:
revChatGPT.V1
revChatGPT.V3
"""
from .version import version
__version__ = version
__all__ = ()
def verify() -> None:
# Available Python Version Verify
from . import typings as t
if int(__import__("platform").python_... | 38 | 991 |
ChatGPT | src/revChatGPT/V1.py | .py | """
Standard ChatGPT
"""
from __future__ import annotations
import base64
import binascii
import contextlib
import json
import logging
import secrets
import subprocess
import sys
import time
import uuid
from functools import wraps
from os import environ
from os import getenv
try:
from os import startfile
except I... | 1,752 | 63,458 |
ChatGPT | src/revChatGPT/typings.py | .py | """
A module that contains all the types used in this project
"""
import os
import platform
from enum import Enum
from typing import Union
python_version = list(platform.python_version_tuple())
SUPPORT_ADD_NOTES = int(python_version[0]) >= 3 and int(python_version[1]) >= 11
class ChatbotError(Exception):
"""
... | 199 | 4,805 |
ChatGPT | src/revChatGPT/V3.py | .py | """
A simple wrapper for the official ChatGPT API
"""
import argparse
import json
import os
import sys
from importlib.resources import path
from pathlib import Path
from typing import AsyncGenerator
from typing import NoReturn
import httpx
import requests
import tiktoken
from . import __version__
from . import typing... | 766 | 25,069 |
InvokeAI | invokeai/invocation_api/__init__.py | .py | """
This file re-exports all the public API for invocations. This is the only file that should be imported by custom nodes.
TODO(psyche): Do we want to dogfood this?
"""
from invokeai.app.invocations.baseinvocation import (
BaseInvocation,
BaseInvocationOutput,
Bottleneck,
Classification,
invocati... | 302 | 8,191 |
InvokeAI | invokeai/version/__init__.py | .py | """
initialization file for invokeai
"""
from invokeai.version.invokeai_version import __version__ # noqa: F401
__app_id__ = "invoke-ai/InvokeAI"
__app_name__ = "InvokeAI"
def _ignore_xformers_triton_message_on_windows():
import logging
logging.getLogger("xformers").addFilter(
lambda record: "A ma... | 21 | 529 |
InvokeAI | invokeai/frontend/__init__.py | .py | """
Initialization file for invokeai.frontend
"""
| 4 | 50 |
InvokeAI | invokeai/frontend/install/__init__.py | .py | """
Initialization file for invokeai.frontend.config
"""
| 4 | 57 |
InvokeAI | invokeai/frontend/install/import_images.py | .py | # Copyright (c) 2023 - The InvokeAI Team
# Primary Author: David Lovell (github @f412design, discord @techjedi)
# co-author, minor tweaks - Lincoln Stein
# pylint: disable=line-too-long
# pylint: disable=broad-exception-caught
"""Script to import images into the new database system for 3.0.0"""
import datetime
import... | 787 | 34,417 |
InvokeAI | invokeai/frontend/cli/arg_parser.py | .py | from argparse import ArgumentParser, Namespace, RawTextHelpFormatter
from typing import Optional
from invokeai.version import __version__
_root_help = r"""Path to the runtime root directory. If omitted, the app will search for the root directory in the following order:
- The `$INVOKEAI_ROOT` environment variable
- Th... | 47 | 1,833 |
InvokeAI | invokeai/frontend/web/__init__.py | .py | """
Initialization file for invokeai.frontend.web
"""
| 4 | 54 |
InvokeAI | invokeai/frontend/web/scripts/clean_translations.py | .py | # Cleans translations by removing unused keys
# Usage: python clean_translations.py
# Note: Must be run from invokeai/frontend/web/scripts directory
#
# After running the script, open `en.json` and check for empty objects (`{}`) and remove them manually.
# Also, the script does not handle keys with underscores. They ne... | 90 | 3,107 |
InvokeAI | invokeai/backend/text_llm_pipeline.py | .py | import queue
import threading
import time
from typing import Callable
import torch
from transformers import PreTrainedModel, PreTrainedTokenizerBase, TextIteratorStreamer
from transformers.generation.logits_process import LogitsProcessor
DEFAULT_SYSTEM_PROMPT = (
"You are an expert prompt writer for AI image gene... | 258 | 11,569 |
InvokeAI | invokeai/backend/llava_onevision_pipeline.py | .py | import queue
import threading
import time
from typing import Callable
import torch
from PIL.Image import Image
from transformers import LlavaOnevisionForConditionalGeneration, LlavaOnevisionProcessor, TextIteratorStreamer
ProgressCallback = Callable[[int, int], None]
# Backstop timeout (seconds) for the streamer's b... | 120 | 4,939 |
InvokeAI | invokeai/backend/__init__.py | .py | """
Initialization file for invokeai.backend
"""
| 4 | 49 |
InvokeAI | invokeai/backend/spandrel_image_to_image_model.py | .py | from pathlib import Path
from typing import Any, Optional
import numpy as np
import torch
from PIL import Image
from spandrel import ImageModelDescriptor, ModelLoader
from invokeai.backend.raw_model import RawModel
class SpandrelImageToImageModel(RawModel):
"""A wrapper for a Spandrel Image-to-Image model.
... | 140 | 5,237 |
InvokeAI | invokeai/backend/model_patcher.py | .py | # Copyright (c) 2024 Ryan Dick, Lincoln D. Stein, and the InvokeAI Development Team
"""These classes implement model patching with LoRAs and Textual Inversions."""
from __future__ import annotations
import pickle
from contextlib import contextmanager
from typing import Any, Generator, Iterator, List, Optional, Tuple,... | 181 | 8,020 |
InvokeAI | invokeai/backend/textual_inversion.py | .py | """Textual Inversion wrapper class."""
from pathlib import Path
from typing import Optional, Union
import torch
from compel.embeddings_provider import BaseTextualInversionManager
from safetensors.torch import load_file
from transformers import CLIPTokenizer
from typing_extensions import Self
from invokeai.backend.ra... | 130 | 5,338 |
InvokeAI | invokeai/backend/raw_model.py | .py | from abc import ABC, abstractmethod
from typing import Optional
import torch
class RawModel(ABC):
"""Base class for 'Raw' models.
The RawModel class is the base class of LoRAModelRaw, TextualInversionModelRaw, etc.
and is used for type checking of calls to the model patcher. Its main purpose
is to a... | 23 | 778 |
InvokeAI | invokeai/backend/flux2/ref_image_extension.py | .py | """FLUX.2 Klein Reference Image Extension for multi-reference image editing.
This module provides the Flux2RefImageExtension for FLUX.2 Klein models,
which handles encoding reference images using the FLUX.2 VAE and
generating the appropriate position IDs for multi-reference image editing.
FLUX.2 Klein has built-in su... | 311 | 13,569 |
InvokeAI | invokeai/backend/flux2/denoise.py | .py | """Flux2 Klein Denoising Function.
This module provides the denoising function for FLUX.2 Klein models,
which use Qwen3 as the text encoder instead of CLIP+T5.
"""
import inspect
import math
from typing import Any, Callable
import numpy as np
import torch
from tqdm import tqdm
from invokeai.backend.rectified_flow.r... | 316 | 14,806 |
InvokeAI | invokeai/backend/flux2/__init__.py | .py | """FLUX.2 backend modules.
This package contains modules specific to FLUX.2 models (e.g., Klein).
"""
| 5 | 103 |
InvokeAI | invokeai/backend/flux2/sampling_utils.py | .py | """FLUX.2 Klein Sampling Utilities.
FLUX.2 Klein uses a 32-channel VAE (AutoencoderKLFlux2) instead of the 16-channel VAE
used by FLUX.1. This module provides sampling utilities adapted for FLUX.2.
"""
import math
import torch
from einops import rearrange
def get_noise_flux2(
num_samples: int,
height: int,... | 207 | 6,972 |
InvokeAI | invokeai/backend/flux2/text_conditioning.py | .py | from dataclasses import dataclass
import torch
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import Range
@dataclass
class Flux2TextConditioning:
"""Single FLUX.2 Klein text conditioning entry (Qwen3 embeddings) with optional regional mask."""
txt_embeddings: torch.Tensor
mask: tor... | 28 | 742 |
InvokeAI | invokeai/backend/flux2/extensions/regional_prompting_extension.py | .py | from typing import Optional
import torch
import torchvision
from invokeai.backend.flux2.text_conditioning import Flux2RegionalTextConditioning, Flux2TextConditioning
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import Range
from invokeai.backend.util.devices import TorchDevice
from invokeai.back... | 176 | 7,679 |
InvokeAI | invokeai/backend/pid/state_dict_utils.py | .py | # SPDX-License-Identifier: Apache-2.0
"""The key-space normalisation shared by PiD identification and PiD loading.
NVIDIA's official `.pth` checkpoints serialise `PidDistillModel`, which keeps the student network
under a `net.` prefix and carries the other distill submodules (the EMA copy, the fake-score net,
the disc... | 87 | 4,539 |
InvokeAI | invokeai/backend/pid/decode.py | .py | # SPDX-License-Identifier: Apache-2.0
"""Decode pipeline for the vendored PiD (Pixel Diffusion Decoder).
This module bridges between InvokeAI's model-manager-loaded PiD checkpoints
(state dicts produced by `model_loaders/pid_decoder.py`) and the underlying
`PidNet` super-resolution network. It deliberately reimplement... | 664 | 31,930 |
InvokeAI | invokeai/backend/pid/_src/networks/pixeldit_official.py | .py | # PixelDiT T2I β consolidated network architecture.
# Verbatim copy from the original PixelDiT repo, merged into a single file.
# Sources:
# pixdit_core/modules.py β building blocks (RMSNorm, RoPE, attention, etc.)
# pixdit_core/pixeldit_c2i.py β PatchTokenEmbedder, PixelTokenEmbedder, PiTBlock
# pixdit_... | 1,534 | 68,682 |
InvokeAI | invokeai/backend/pid/_src/networks/pid_net.py | .py | # PidNet β Super-resolution variant of PixDiT_T2I.
#
# Extends the text-to-image PixDiT model with LQ (low-quality) image/latent
# conditioning for image super-resolution. The base T2I architecture is unchanged;
# LQ information is injected via per-block gated injection between transformer
# blocks ("controlnet" mode β... | 479 | 21,011 |
InvokeAI | invokeai/backend/pid/_src/networks/lq_projection_2d.py | .py | # 2D LQ projection for pixel-space image super-resolution.
#
# Takes LQ image [B, 3, H_lq, W_lq] at original low resolution and/or
# LQ VAE latent [B, z_dim, zH, zW], projects them to patch-aligned tokens
# for injection into the PixDiT_T2I transformer.
#
# Spatial alignment (lossless):
# Image branch: PixelUnshuffl... | 414 | 18,765 |
InvokeAI | invokeai/backend/pid/_src/utils/context_parallel.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht... | 195 | 7,468 |
InvokeAI | invokeai/backend/pid/_src/inference/pipeline_registry.py | .py | """
Registry of diffusers pipelines for FPD-vs-VAE evaluation on generated images.
Each DiffusionPipelineConfig describes how to load a diffusers pipeline, extract
latents in (B, C, H, W) format, denormalize them, and decode with the pipeline's VAE.
Supported backbones: flux, sdxl, sd3, flux2, qwenimage, zimage, zima... | 365 | 16,002 |
InvokeAI | invokeai/backend/pid/_src/inference/checkpoint_registry.py | .py | # Shared official PID checkpoint registry.
#
# Single source of truth for the (experiment_name, checkpoint_path) pair used by
# every pixel-decoder demo in `pid/_src/inference/`. The registry is keyed by
# (backbone, ckpt_type):
#
# ckpt_type = "2k" Original 2048px-trained decoders, used as
# ... | 123 | 5,645 |
InvokeAI | invokeai/backend/pid/_src/modules/conditioner.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht... | 564 | 22,743 |
InvokeAI | invokeai/backend/pid/_src/models/pid_distill_model.py | .py | # PID distillation model β inference subset of the DMD2-distilled student.
#
# The training-time teacher / fake_score / discriminator / DMD-loss machinery has been
# stripped; what remains is the student net (`self.net`) plus the few-step sampler
# (`_get_t_list`, `_student_sample_loop`, `_velocity_to_x0`) consumed by
... | 316 | 13,391 |
InvokeAI | invokeai/backend/pid/_src/models/pixeldit_model.py | .py | # PixelDiT T2I model β inference subset.
#
# Provides the bare minimum needed by PidDistillModel: net + frozen text
# encoder + caption embedding helper + a flow-matching `timescale` field.
# Training-time machinery (EMA, REPA, flow-matching trainer, training/validation
# steps) has been removed.
from __future__ impor... | 270 | 10,557 |
InvokeAI | invokeai/backend/pid/_src/models/pid_model.py | .py | # PID (PixelDiT SR) model β inference subset.
#
# At inference the only thing this class adds on top of PixelDiTModel is the
# frozen VAE (`vae_encoder`) used by `encode_lq_latent`. The training-time
# degradation pipeline, LoRA injection, LPIPS loss, and training/validation
# steps have all been removed.
from __futur... | 76 | 2,595 |
InvokeAI | invokeai/backend/pid/_ext/imaginaire/model.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht... | 130 | 5,128 |
InvokeAI | invokeai/backend/pid/_ext/imaginaire/lazy_config/file_io.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Minimal stdlib-based stand-in for the upstream iopath PathManager.
# Only `open()` on local paths and trivial helpers are supported; the upstream
# HTTPURLHandler / OneDrivePathHa... | 59 | 1,540 |
InvokeAI | invokeai/backend/pid/_ext/imaginaire/lazy_config/registry.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht... | 118 | 3,809 |
InvokeAI | invokeai/backend/pid/_ext/imaginaire/lazy_config/lazy.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Minimal LazyCall / LazyConfig stub. The upstream module supports file-based
# config save/load via yaml + cloudpickle + dill + detectron2 helpers; the
# vendored decoder-inference... | 53 | 1,950 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.