text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
"""Feature registry: per-feature metadata for the search pipeline (T2-01).
Every vocabulary feature carries declarative metadata: its **PIT tier**
(the weakest data source it consumes: local daily bars, PIT fundamentals,
capital-flow feeds, current-snapshot extrapolations, or neutral), its
empirical **coverage** on th... | fanxxxks/N | ashare_model/feature_registry.py | .py | dacc0decf3527354 | 7.15 | 1 |
"""DEAP strongly-typed genetic-programming baseline (T2-02).
The baseline reuses DEAP's official typed-tree machinery (primitive set,
half-and-half generation, one-point crossover, uniform mutation,
tournament selection) instead of reimplementing a GP engine. What this
module adds is the mapping between DEAP trees an... | fanxxxks/N | ashare_model/gp_search.py | .py | df2aeec6a6a66100 | 7.15 | 1 |
"""Pareto-front selection (T1-04).
Eligibility (the hard constraints) filters candidates first; among the
eligible, selection prefers non-dominated candidates on the primary
portfolio objectives — active IR (maximize), risk exposure (minimize),
turnover (minimize), capacity utilization (minimize) — instead of
stuffing... | fanxxxks/N | ashare_model/pareto.py | .py | 956f56e05e7252e1 | 7.15 | 1 |
"""Robust signal-quality statistics and hard quality gates (T1-03).
The daily rank-IC series is the raw measurement; everything here makes
that measurement trustworthy:
* ``hac_variance`` / ``effective_n`` / ``robust_icir`` — the ICIR is
shrunk by the effective sample size under autocorrelation
(Newey-West-style ... | fanxxxks/N | ashare_model/signal_quality.py | .py | 6d16999d797340e5 | 7.15 | 1 |
"""Optuna TPE baseline (T2-02).
The baseline searches the policy's exact search space with Optuna's
TPESampler — a mature, maintained implementation of tree-structured
Parzen-estimator search — instead of a hand-rolled surrogate.
Parameterization: a trial is a full ``max_formula_len`` token sequence,
suggested positi... | fanxxxks/N | ashare_model/tpe_search.py | .py | 437aebf2eff37cab | 7.15 | 1 |
"""StackVM interpreter for A-share factor formulas.
Output contract: every executed formula returns its signal **cross-sectionally
z-scored per date** (:func:`ashare_model.ops.cross_sectional_zscore`), applied
as the final step of :meth:`StackVM.execute`. Stacked arithmetic (MUL/DIV/ADD
chains) can drift the raw scal... | fanxxxks/N | ashare_model/vm.py | .py | 3c8c3c331d7582c1 | 7.15 | 1 |
"""A-share factor/operator vocabulary.
The vocabulary is versioned: :attr:`FormulaVocab.feature_version` is a hash
of the feature/operator name lists *and* the grammar generation, recorded
in every training artifact. Saved formulas are resolved against the
current vocabulary *by name* (see :func:`resolve_formula_toke... | fanxxxks/N | ashare_model/vocab.py | .py | 53fe401297273aab | 7.15 | 1 |
"""Portfolio layer: constrained portfolio optimization (T3-01).
The factor layer outputs expected alpha / rank; this layer owns the
portfolio constraints — single-name and industry caps, Beta/size exposure
ranges, ADV participation, turnover budget, min cash, position count and
min trade amount — and produces target w... | fanxxxks/N | ashare_portfolio/optimizer.py | .py | 840d489ed2fe3de5 | 7.15 | 1 |
"""BlueSight — Home Assistant custom integration.
Makes the connection layer of Home Assistant's Bluetooth stack visible:
GATT slot allocations per ESPHome proxy, deadlocks (core issue #176516),
ghost slots, and pairing storms.
The config flow and platforms arrive in later tasks; setup here only
constructs the coordi... | dasimon135/ha-bluesight | custom_components/bluesight/__init__.py | .py | 3858efbec25b93e0 | 7 | 0 |
"""Isolated habluetooth slot-allocation surface for BlueSight.
This is the ONLY module coupled to the habluetooth manager API. Everything
else depends on the stable interface exposed here, so a future
HA/habluetooth API change touches only this file.
Confirmed against habluetooth as bundled in Home Assistant 2026.7.4... | dasimon135/ha-bluesight | custom_components/bluesight/adapter.py | .py | f22799d5becae8e0 | 7 | 0 |
"""Global incident binary sensor for BlueSight.
A single ``binary_sensor.bluesight_incident`` that reports a PROBLEM whenever
the coordinator has any open incidents, whether slot-layer (deadlock, ghost
slot, storm) or proxy-health (offline, stalled, reboot storm). The full
incident list is exposed as state attributes ... | dasimon135/ha-bluesight | custom_components/bluesight/binary_sensor.py | .py | 5560e2f7a04ab9d8 | 7 | 0 |
"""Config and options flow for BlueSight.
Single-instance integration: there is exactly one BLE stack per Home
Assistant, so only one config entry may exist. The user step needs no input
to start (sensible defaults cover everything); all tunables live in the
options flow.
"""
from __future__ import annotations
from t... | dasimon135/ha-bluesight | custom_components/bluesight/config_flow.py | .py | 153c4a538af27d26 | 7 | 0 |
"""Pure snapshot container + assembly for BlueSight.
No Home Assistant dependency: the whole correlation/assembly step lives here
so it is fully unit-testable with plain pytest. The ``DataUpdateCoordinator``
subclass stays a thin shell that only feeds this function a snapshot.
"""
from __future__ import annotations
f... | dasimon135/ha-bluesight | custom_components/bluesight/coordinator_data.py | .py | 034f049fc6f5901d | 7 | 0 |
"""Pure detectors for BLE connection-layer incidents.
No Home Assistant dependency; fully unit-testable with plain pytest.
"""
from __future__ import annotations
from collections import defaultdict
from .model import Incident, IncidentKind, ProxyHealth, ProxySlots, normalize_address
from .telemetry import ProxyTelem... | dasimon135/ha-bluesight | custom_components/bluesight/detector.py | .py | 6a66e999dd946e4f | 7 | 0 |
"""Pure MAC -> device_id indexing over the Home Assistant device registry.
No Home Assistant dependency: the registry entries are read duck-typed
(``.id``, ``.connections``, ``.identifiers``) and the connection-type strings
are injected by the caller, exactly as :mod:`.telemetry_reader` takes its two
lookups as callab... | dasimon135/ha-bluesight | custom_components/bluesight/device_index.py | .py | 1ed99608458cd2df | 7 | 0 |
"""Diagnostics dump for BlueSight.
For a triage integration this is the single most useful thing to attach to a
bug report: the exact slot allocations, the scanner health, the rolling failure
windows, every incident the detectors currently raise, and what -- if anything
-- each proxy's ESPHome telemetry reported (see ... | dasimon135/ha-bluesight | custom_components/bluesight/diagnostics.py | .py | f0e4b3f65ad3c1f5 | 7 | 0 |
"""Pure shaping of the ESPHome telemetry for the diagnostics dump.
The twin of :mod:`.diagnostics` in the same way :mod:`.coordinator_data` is the
twin of :mod:`.coordinator`: no Home Assistant import lives here, so this is
testable with plain pytest on a machine that has no Home Assistant, which is
where the shape de... | dasimon135/ha-bluesight | custom_components/bluesight/diagnostics_data.py | .py | 8fd1391012de2649 | 7 | 0 |
"""Serve and register the BlueSight Lovelace card from the integration.
HACS installs BlueSight as an *integration*, so it copies
``custom_components/bluesight/`` and nothing else. Shipping the card inside
that directory is therefore what makes HACS deliver it: the two manual steps
the docs used to require (copy into ... | dasimon135/ha-bluesight | custom_components/bluesight/frontend/__init__.py | .py | 127d3d6b0f5873cf | 7 | 0 |
"""Pure notification policy for BlueSight.
No Home Assistant dependency: incident de-duplication/precedence, create /
dismiss reconciliation, the parameters each notification interpolates, and the
notification-id sanitizer all live here so they are fully unit-testable under
plain pytest on any platform. The wording it... | dasimon135/ha-bluesight | custom_components/bluesight/incident_policy.py | .py | 9cf344400d0cae98 | 7 | 0 |
"""Pure data model for BlueSight.
This module has no Home Assistant dependency and is fully unit-testable with
plain pytest.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import StrEnum
def normalize_address(addr: str) -> str:
"""Canonicalize a BLE MAC address for cor... | dasimon135/ha-bluesight | custom_components/bluesight/model.py | .py | f23d29717a17a569 | 7 | 0 |
"""Thin Home Assistant glue for BlueSight persistent notifications.
All of the decision logic (dedup/precedence, create/dismiss reconciliation,
notification parameters, id sanitizing) lives in the HA-free
:mod:`.incident_policy` module, and the wording itself in the string
catalogue. This manager only turns those deci... | dasimon135/ha-bluesight | custom_components/bluesight/notify.py | .py | 18fbbde8ffeeb8c2 | 7 | 0 |
"""Pure rendering of catalogued, parameterised strings.
No Home Assistant dependency; unit-testable with plain pytest.
Detectors emit a key and parameters instead of prose so the same incident can
be rendered in Home Assistant's language on the backend and in the viewer's
language in the card, from one catalogue.
No... | dasimon135/ha-bluesight | custom_components/bluesight/rendering.py | .py | a3a905d8b325dbaf | 7 | 0 |
"""Per-proxy GATT slot sensors for BlueSight.
Each ESPHome/Bluetooth proxy gets its own HA device carrying two sensors:
``Slots Used`` and ``Slots Free``. Proxies can appear after startup, so the
platform registers a coordinator listener that adds entities for newly-seen
proxy sources without ever creating duplicates.... | dasimon135/ha-bluesight | custom_components/bluesight/sensor.py | .py | 9e094beff06179d2 | 7 | 0 |
"""Pure connection-failure signal for the pairing-storm detector.
No Home Assistant dependency; fully unit-testable with plain pytest.
Why this exists
---------------
The storm detector needs "this device failed to connect" events. Home Assistant
exposes no SMP/bond failure counter (that lands with the v1.5 ESPHome
c... | dasimon135/ha-bluesight | custom_components/bluesight/storm_signal.py | .py | ec82bc89cedf1340 | 7 | 0 |
"""Pure parser for the telemetry the BlueSight ESPHome component publishes.
No Home Assistant dependency; fully unit-testable with plain pytest. (The
stdlib ``logging`` import is not a Home Assistant dependency: HA configures the
root logger, and a module-level logger costs this module none of its purity.)
The firmwa... | dasimon135/ha-bluesight | custom_components/bluesight/telemetry.py | .py | 989ef4f91917198c | 7 | 0 |
"""Isolated Home Assistant surface for the BlueSight ESPHome telemetry.
The twin of :mod:`.adapter`: this is the ONLY module that knows how the
telemetry reaches Home Assistant, so a change in that surface touches one file.
Discovery matches on the entity registry's ``original_name``. Not
``entity_id`` -- users renam... | dasimon135/ha-bluesight | custom_components/bluesight/telemetry_reader.py | .py | a6120d1c865d3dee | 7 | 0 |
"""Rolling time-window bookkeeping for connection failures.
Pure logic with an injected clock for deterministic testing; no Home
Assistant or wall-clock dependency.
"""
from __future__ import annotations
from collections import defaultdict, deque
from collections.abc import Callable
class FailureWindow:
def __i... | dasimon135/ha-bluesight | custom_components/bluesight/window.py | .py | 51101ddb44b3b978 | 7 | 0 |
"""Codegen for the BlueSight ESPHome telemetry component.
BlueSight's read-only invariant holds all the way into the firmware: this
component registers as a passive observer on the BLE event stream and opens no
connection, writes no bond and never calls into ``bluetooth_proxy``.
It publishes facts, never verdicts. Th... | dasimon135/ha-bluesight | esphome/components/bluesight/__init__.py | .py | f1172eb5aa845b29 | 7 | 0 |
"""Generate the BlueSight brand icon (an original connection-slot motif).
Home Assistant (>= 2026.3) loads a custom integration's brand images from the
``custom_components/<domain>/brand/`` directory, taking priority over the
``home-assistant/brands`` CDN -- no PR to that repository is needed:
- ``icon.png`` (256x256... | dasimon135/ha-bluesight | scripts/make_icon.py | .py | 2e69a06eaeccfde4 | 7 | 0 |
"""Unit tests for the pure ghost-slot availability decision helper.
Pure logic, no Home Assistant import, so this runs on the default Windows
``python -m pytest`` suite.
"""
from custom_components.bluesight.availability import is_device_alive
def test_none_is_alive():
# Device not found in the registry -> conser... | dasimon135/ha-bluesight | tests/test_availability.py | .py | b436ba0e31b2b339 | 7.5 | 0 |
"""Drift guards for the shipped incident string catalogues.
The catalogues live under the directory the integration already serves over
HTTP, so the backend reads the same files the card will fetch: one source of
truth for both sides. That only holds if the languages stay in step, which is
what these tests pin.
The l... | dasimon135/ha-bluesight | tests/test_catalogue_files.py | .py | 52ead03e6f61e29d | 7.5 | 0 |
"""Singular agreement for every counted string we ship.
A count of one is the case the catalogue got wrong for a whole release: the
templates were authored with the plural noun baked in, so a proxy that saw
exactly one device read "1 devices seen" and a threshold of one failure read
"1 failures". That is invisible in ... | dasimon135/ha-bluesight | tests/test_catalogue_plurals.py | .py | 109598f0f3dbc79b | 7.5 | 0 |
"""Config and options flow tests for BlueSight.
These require the ``hass`` fixture from
``pytest-homeassistant-custom-component``, whose pytest plugin does not load
on Windows (it imports the Unix-only ``fcntl`` via the HA test runner). The
whole module is skipped when that plugin is unavailable, so the default
Window... | dasimon135/ha-bluesight | tests/test_config_flow.py | .py | 8c5eb84cee27eae8 | 7.5 | 0 |
"""Bond-lost detection: pairing attempted, failing, and no bond exists.
This is the one diagnosis that is impossible without the ESPHome telemetry
component: Home Assistant can see neither SMP failures nor a proxy's NVS bond
store, so every assertion here is about evidence only the firmware supplies.
"""
from __future... | dasimon135/ha-bluesight | tests/test_detector_bond_lost.py | .py | 11a6e43d68fcce45 | 7.5 | 0 |
"""The joint between the detectors and the shipped string catalogues.
Every other test covers one side of it. The per-detector tests pin the key and
the parameters each detector emits; test_catalogue_files pins that the language
files agree with each other; test_rendering pins the renderer. Nothing pins that
a detecto... | dasimon135/ha-bluesight | tests/test_detector_catalogue_keys.py | .py | 4e21caedd21ff847 | 7.5 | 0 |
import torch
class AvePool(torch.nn.Module):
def __init__(self):
super(AvePool, self).__init__()
def forward(self, in_tensor):
return torch.sum(in_tensor,1)
class GcnPool(torch.nn.Module):
"""
This layer apply a chain of mlp on each node of tthe graph.
thr input is a matric ma... | MirzaeiSfu/GraphVAE-REQ | Aggregation.py | .py | ad751d061f3b3421 | 7 | 0 |
import torch
class kernel(torch.nn.Module):
"""
this class return a list of kernel ordered by keywords in kernel_type
"""
def __init__(self, **ker):
"""
:param ker:
kernel_type; a list of string which determine needed kernels
"""
self.device = ker.get("device")
... | MirzaeiSfu/GraphVAE-REQ | GlobalProperties.py | .py | fc883162c487e6f8 | 7 | 0 |
import networkx as nx
import scipy
import numpy as np
from plotter import plotG
import numpy
from operator import itemgetter
import random
def Synthetic_data(type= "grid", rand = False):
if rand==True:
if type == "grid":
G = grid(random.randint(10,15), random.randint(10,15))
elif ... | MirzaeiSfu/GraphVAE-REQ | Synthatic_graph_generator.py | .py | d6c721a70740d2a2 | 7 | 0 |
from __future__ import annotations
STRUCT_TYPE_TO_ID = {
"Corner": 1,
"Edge": 2,
"Interior": 3,
}
DISTANCE_TO_BOUNDARY_TO_ID = {
"Boundary": 1,
"Near-Boundary": 2,
"Near-Center": 3,
"Center": 4,
"Deep-Center": 5,
}
EDGE_ORBIT_TO_ID = {
"Boundary": 1,
"Interior": 2,
}
STRUCT_... | MirzaeiSfu/GraphVAE-REQ | dataset_feature_utils/grid_features.py | .py | 30a38e06ae910d66 | 7 | 0 |
from __future__ import annotations
import networkx as nx
NODE_DEGREE_TO_ID = {
"Leaf": 1,
"Branch": 2,
"Hub": 3,
"SuperHub": 4,
}
DISTANCE_TO_SPINE_TO_ID = {
"On-Spine": 1,
"Near-Spine": 2,
"Mid-Spine": 3,
"Far-Spine": 4,
}
SUBTREE_SIZE_BUCKET_TO_ID = {
"1-5": 1,
"6-20": 2,
... | MirzaeiSfu/GraphVAE-REQ | dataset_feature_utils/lobster_features.py | .py | 0ad60265e3daa699 | 7 | 0 |
from __future__ import annotations
from collections import Counter
from math import sqrt
STRUCT_TYPE_TO_ID = {
"Vertex": 1,
"Boundary": 2,
"Edge-Corner": 3,
"Edge-Transition": 4,
"Interior": 5,
}
DISTANCE_TO_BOUNDARY_TO_ID = {
"Boundary": 1,
"Near-Boundary": 2,
"Near-Center": 3,
... | MirzaeiSfu/GraphVAE-REQ | dataset_feature_utils/triangular_grid_features.py | .py | 2abb341342052263 | 7 | 0 |
"""Strict PyTorch Geometric interchange contract.
The public boundary is a collection of individual, homogeneous
``torch_geometric.data.Data`` objects. The evaluator intentionally accepts a
small subset of PyG:
* ``x`` is a finite floating-point matrix of shape ``[N, D_node]``;
* ``edge_index`` is an ``int64`` matri... | MirzaeiSfu/GraphVAE-REQ | graph_evaluation/src/ggm_eval/contract.py | .py | 5022c6223a52c481 | 7 | 0 |
"""Per-task LLM call seam over pf-core's router, tracked calls, and recording.
Every LLM-calling site goes through `invoke_agent(slug, …)`: it resolves
backend + model via `pf_core.llm.router`, acquires the backend client, and
runs the call through `tracked_messages_call` (which writes the `llm_runs`
row when tracking... | phierceweb/pagespeak | src/pagespeak/_agent_runtime.py | .py | eae18a43e642517a | 7.24 | 2 |
"""Pagespeak DB configuration — thin wrapper over pf-core's connection helpers.
All LLM call tracking writes to whatever DB the standard `DATABASE_URL`
env var points at — SQLite by default (file in `~/.pagespeak/`),
Postgres or MySQL by setting `DATABASE_URL=postgresql://...` or
`mysql+pymysql://...`. pf-core's SQLAl... | phierceweb/pagespeak | src/pagespeak/_db.py | .py | 97b7f103ec253af4 | 7.24 | 2 |
"""Docling heading-hierarchy inference: option construction + level fixups.
Docling's PDF pipeline labels every section header at the same level unless
`HeadingHierarchyOptions.enabled` is set, which infers levels from PDF
bookmarks, then section numbering, then font style (in that precedence).
Two Docling behaviours... | phierceweb/pagespeak | src/pagespeak/backends/_docling_headings.py | .py | a902ddbc03ff79bb | 7.24 | 2 |
from __future__ import annotations
import re
import tempfile
import zipfile
from pathlib import Path
from typing import Any
from pf_core.log import get_logger
from ..models._models import IngestResult
from ..services._image_refs import ImageRef, replace_image_refs
from ..utils._mathml import prepare_mathml_for_markd... | phierceweb/pagespeak | src/pagespeak/backends/_docx.py | .py | cdb902e376b05b5f | 7.24 | 2 |
"""DOCX backend selection — mirrors `backends/_pdf_dispatch.py`.
`markitdown` (default) = the legacy MarkItDown path (also the only
path for non-.docx office formats). `python-docx` = the structure-
faithful backend. python-docx is an optional extra; the ImportError
names the exact pip extra, mirroring the docling pat... | phierceweb/pagespeak | src/pagespeak/backends/_docx_dispatch.py | .py | d189e9541e2455a8 | 7.24 | 2 |
"""Structural heading hygiene for the python-docx reader.
Post-processing on the structure the reader derives from Word's file
format (`numId`/`ilvl`, `Heading N` styles). Structural only — it never
inspects heading wording; a structure-faithful reader transfers the
author's structure, it doesn't edit their prose.
* ... | phierceweb/pagespeak | src/pagespeak/backends/_docx_quality.py | .py | 6bfe1acfafc114f1 | 7.24 | 2 |
"""One paragraph's inline content -> markdown (python-docx backend).
Word nests visible text inside container elements — tracked insertions,
fields, content controls, smart tags, math — not only in bare ``w:r`` runs.
A reader that dispatches on ``w:r`` alone drops every one of them silently,
which is content loss disg... | phierceweb/pagespeak | src/pagespeak/backends/_docx_runs.py | .py | 131ef2f2fd90acad | 7.24 | 2 |
"""Structure-faithful DOCX -> markdown emitter (python-docx backend).
Renders Word's explicit element types: Heading styles -> ATX headings,
numbered lists -> nested ordered lists (running numbers), bulleted
lists -> nested unordered lists, runs -> bold/italic, hyperlinks ->
links, tables -> a visible deferred placeho... | phierceweb/pagespeak | src/pagespeak/backends/_docx_structured.py | .py | 252261e45d5fb5c9 | 7.24 | 2 |
"""GFM table rendering for the structure-faithful DOCX backend.
python-docx flattens vMerge/gridSpan into a repeated-value rectangular
grid (a vMerge origin's text recurs in every spanned row). GFM has no
rowspan/colspan, so the grid is rendered AS-IS; the repetition is
intentional and RAG-friendly (each row self-cont... | phierceweb/pagespeak | src/pagespeak/backends/_docx_table.py | .py | 3855e4a68ace732f | 7.24 | 2 |
"""Body-order traversal + Word numbering resolution for the
structure-faithful DOCX backend.
Two concerns, both isolated here for unit testing:
- `build_numfmt_map`: resolve every (numId, ilvl) to its w:numFmt
("bullet" vs an ordered format like "decimal") by walking
word/numbering.xml. Missing/odd entries default... | phierceweb/pagespeak | src/pagespeak/backends/_docx_walk.py | .py | 59995601af059b1e | 7.24 | 2 |
"""Copy local sibling image refs into the output dir.
An HTML bundle (saved webpage, doc-site export) ships ``doc.html`` plus a
sibling ``images/`` dir with relative refs. MarkItDown keeps the refs but
nothing copies the files, so the vision pass — which only globs
``<output_dir>/images/`` — sees nothing. This closes ... | phierceweb/pagespeak | src/pagespeak/backends/_local_images.py | .py | 63bacc23527b4843 | 7.24 | 2 |
from __future__ import annotations
import os
from pathlib import Path
from pf_core.log import get_logger
from ..models._models import IngestResult
from ..services._image_refs import ImageRef, replace_image_refs
logger = get_logger(__name__)
# Tracks the device the marker model cache was first loaded on so we can ... | phierceweb/pagespeak | src/pagespeak/backends/_pdf.py | .py | 2dde60232431f5ed | 7.24 | 2 |
"""PDF-backend selection: pick `marker`, `docling`, or `tophat` per call.
Pagespeak's PDF backends:
- **Marker** (`_pdf.convert_pdf`) — fast, the default. Heading
hierarchy and tables flatten on academic PDFs; surya can crash on MPS.
- **Docling** (`_pdf_docling.convert_pdf_docling`) — accuracy-first
alternative.... | phierceweb/pagespeak | src/pagespeak/backends/_pdf_dispatch.py | .py | 12067833c39877c2 | 7.24 | 2 |
"""Docling PDF backend.
Wraps `docling.DocumentConverter` to match the Marker backend's
contract: same signature, same `IngestResult` return shape, same
`` ref convention in the markdown output.
Three things Docling needs translated to fit our pipeline:
1. **Image refs.** Docling emits `<!-- image ... | phierceweb/pagespeak | src/pagespeak/backends/_pdf_docling.py | .py | a02d1fd30bb5dadd | 7.24 | 2 |
"""Canvas QTI XML → normalized quiz model.
Parses the two XML files Canvas emits per quiz:
- `assessment_meta.xml` (Canvas `cccv1p0`) → title, points, instructions.
- `<hash>.xml` (IMS QTI 1.2 `questestinterop`) → the questions.
Namespace handling uses the `{*}` ElementPath wildcard so the parser is
not pinned to an... | phierceweb/pagespeak | src/pagespeak/backends/_qti_parse.py | .py | 26ffd3b577ea130b | 7.24 | 2 |
"""Normalized quiz model → LLM-friendly markdown.
One quiz renders as an H1 title + a metadata line + instructions, then the
questions as **`## Question N` headings**. The exam title is the only `#`
H1, so the per-exam splitter cuts one document per quiz; the `##` question
headings let the markdown be re-split per que... | phierceweb/pagespeak | src/pagespeak/backends/_qti_render.py | .py | c106fed4682881d1 | 7.24 | 2 |
"""QTI per-question split + output frontmatter.
Splits one exam's rendered markdown into one self-contained `Question NNN.md`
per question (each with rich provenance frontmatter for RAG linkage), and
builds the whole-exam master doc's frontmatter. Kept separate from
`backends/_qti` (discovery + per-exam ingest) to sta... | phierceweb/pagespeak | src/pagespeak/backends/_qti_split.py | .py | f0ddd4f120ae129c | 7.24 | 2 |
"""Download remote image refs in HTML-derived markdown to local files.
MarkItDown converts an HTML document by preserving its ``<img src="http…">``
tags as remote markdown image refs — it never downloads the binaries. The
pagespeak vision pass only processes images that live locally under
``<output_dir>/images/``, so ... | phierceweb/pagespeak | src/pagespeak/backends/_remote_images.py | .py | b32379b130475152 | 7.24 | 2 |
"""Top Hat quiz-export PDF → per-question markdown.
Top Hat's "Export" produces a print-to-PDF of its web quiz page. Marker and
Docling both *damage* it: Marker shreds every answer option into a
one-word-per-line table; Docling de-shreds but drops whole questions and
triple-duplicates the rest. The cause is the same —... | phierceweb/pagespeak | src/pagespeak/backends/_tophat.py | .py | 0f4ca72ebc999ec1 | 7.24 | 2 |
"""Read the correct answer(s) from a Top Hat *answers-populated* export.
When an instructor exports a Top Hat quiz after the due date, the correct
option is revealed — but **only visually**: the correct option's letter glyph
is rendered light grey (`#ABABAB` → RGB 171,171,171) with a green check, while
every other opt... | phierceweb/pagespeak | src/pagespeak/backends/_tophat_answers.py | .py | a7954fa234fa540a | 7.24 | 2 |
"""Extract embedded figures from a Top Hat quiz PDF and bind them to questions.
Some Top Hat questions ARE a figure — a diagram is the whole question (e.g. a
multi-stage process cascade), with no text stem and no answer toggle. The
text-only path drops these entirely. This module pulls the embedded image
bitmaps out o... | phierceweb/pagespeak | src/pagespeak/backends/_tophat_images.py | .py | fc6f44bd1fd9b84e | 7.24 | 2 |
"""Parsed Top Hat quiz model → LLM-friendly markdown.
One quiz renders as a `#` H1 title + a metadata line + optional subtitle, then
each question as a `## Question N` heading. The title is the only H1, so the
section splitter cuts one file per question — the same shape as the Canvas QTI
render (`backends/_qti_render`... | phierceweb/pagespeak | src/pagespeak/backends/_tophat_render.py | .py | 3a442847ace8cd53 | 7.24 | 2 |
"""Typer subcommand registration for `pagespeak ingest`."""
from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
from typing import Any, cast
import typer
from ..backends._docx_dispatch import DocxBackendName
from ..orchestrators._chunk import resolve_cli_workers
from ..o... | phierceweb/pagespeak | src/pagespeak/cli/_ingest.py | .py | 4327a7e7c6c30ed5 | 7.24 | 2 |
"""Run-record flag inheritance for `pagespeak convert`.
When convert targets an existing output dir holding a
`.pagespeak-run.json`, flags the user didn't pass explicitly default to
the record's `resolved_flags` — so a bare `--rerun-from` rebuilds
`sections/` with the original shape instead of silently dropping it.
Ex... | phierceweb/pagespeak | src/pagespeak/cli/_inherit.py | .py | f44acd3ea4271617 | 7.24 | 2 |
"""Public result types returned by `to_markdown()` and the diagram pass.
These are intentionally plain frozen dataclasses so consumers can pickle them,
diff them, or feed them to downstream pipelines without depending on pagespeak
internals.
"""
from __future__ import annotations
from dataclasses import dataclass, f... | phierceweb/pagespeak | src/pagespeak/models/_models.py | .py | bec20a4913fc3d36 | 7.24 | 2 |
"""Pipeline manifest: shared state across ingest chunked-worker phases.
The manifest is the single source of truth for what work is done.
Each worker reads it on entry, skips completed work, and updates it
incrementally so an interrupted ingest run can resume from the next call.
File layout under OUTDIR (chunked path... | phierceweb/pagespeak | src/pagespeak/models/_pipeline.py | .py | 922e1b9931f7a353 | 7.24 | 2 |
"""Normalized quiz model — the intermediate representation between the QTI
parser and the markdown renderer.
Parse-then-render: `backends/_qti_parse` produces these frozen value
objects from Canvas QTI XML; `backends/_qti_render` turns them into
markdown. Keeping a clean model in the middle is what lets the same engin... | phierceweb/pagespeak | src/pagespeak/models/_quiz.py | .py | b28e2b5d68d945d2 | 7.24 | 2 |
"""Chunk phase: parallel Marker conversion of page-range slices.
Splits a PDF into N-page chunks, runs each through Marker in a separate
process (Marker isn't thread-safe and the torch+surya model load is per-
process), and records each chunk's output in the manifest. Resume on
re-invocation: chunks marked `completed`... | phierceweb/pagespeak | src/pagespeak/orchestrators/_chunk.py | .py | be7a214efd60e667 | 7.24 | 2 |
"""`to_markdown` setup helpers: preset/flag resolution + dir-mode input.
The preset/default resolution, the dir-mode stem/input resolution, and
the run-timestamp helper. `_dispatch` re-exports `resolve_dir_mode_stem`
(the CLI imports it) and uses the rest internally. Self-contained: no
dependency back on `_dispatch`.
... | phierceweb/pagespeak | src/pagespeak/orchestrators/_dispatch_setup.py | .py | 00abaeca724cdbee | 7.24 | 2 |
"""Unified backend phase: produce `<stem>.raw.md` + `images/` for one document.
Single entry point for "convert source → raw markdown." Dispatches on
`workers`:
- `workers == 1` (default): backend runs in-process. For PDFs this is
Marker / docling; for other formats this is MarkItDown. Output goes
directly to `<o... | phierceweb/pagespeak | src/pagespeak/orchestrators/_ingest.py | .py | f0e6f37e93bda499 | 7.24 | 2 |
"""The Phase contract — one pipeline stage as an independently runnable
unit whose on-disk checkpoint is its sole interface to its neighbours.
A `Phase` reads its input checkpoint, does its work, and writes its
output checkpoint. Phases never hand an in-memory markdown string to
each other; the checkpoint file IS the ... | phierceweb/pagespeak | src/pagespeak/orchestrators/_phase.py | .py | 86920fe4e8cdba6d | 7.24 | 2 |
"""Shared, deterministic ADR catalog and relationship graph helpers.
Markdown ADR files remain authoritative. This module projects their invariant
frontmatter and format-aware semantic sections into records consumed by
``adr-index``, ``adr-context``, and ``adr-related``.
"""
from __future__ import annotations
impor... | rvdbreemen/adr-kit | bin/adr_catalog.py | .py | 4dd91e92a55ff494 | 7.39 | 5 |
"""Shared, stdlib-only validation for adr-kit project configuration."""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any, Dict, List
class ConfigValidationError(ValueError):
"""Raised when .adr-kit.json is malformed or violates its schema."""
# Keys the ... | rvdbreemen/adr-kit | bin/adr_config.py | .py | f44d04b10e6759b8 | 7.39 | 5 |
"""Bounded native and MCP-extension doctor probes."""
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
from adr_doctor_models import benchmark_extension, check
from clients.installer.detection import detect_clients
from clients.installer.bounded import run_bounded
... | rvdbreemen/adr-kit | bin/adr_doctor_probes.py | .py | ae21ce35a56bb814 | 7.39 | 5 |
"""Deterministic Proposed-ADR work queue and disposable cache helpers."""
from __future__ import annotations
import json
import os
import re
import threading
import time
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
QUEUE_SCHEMA_VERSION = 1
QUEUE_CACHE_NAME = ".adr-kit-readiness.... | rvdbreemen/adr-kit | bin/adr_guardian_queue.py | .py | aad043b0b55e20fa | 7.39 | 5 |
"""Read the git history for decision-shaped evidence (spec R1, TASK-80).
The bootstrap scanners walk the working tree, which shows what the project is.
The history shows how it got that way -- and the *why* of an existing codebase
lives there, in the commit that says "switch to X because Y", in the merge that
introduc... | rvdbreemen/adr-kit | bin/adr_history_scan.py | .py | 59cd603941199e45 | 7.39 | 5 |
"""adr_index_core: the ADR index generator, separated from its CLI.
`bin/adr-index` was both the renderer and the command. That was fine while the
only caller was the command line, and it stopped being fine when the guardian
needed to answer one question at SessionStart -- *is the committed index still
what the genera... | rvdbreemen/adr-kit | bin/adr_index_core.py | .py | 46e81280fe8436eb | 7.39 | 5 |
"""Shared LLM backend registry for adr-kit's model-calling entry points.
ADR-017 replaced a pinned vendor CLI with a named enum resolving to a code-side
command table. `bin/adr-judge` shipped that table under TASK-59; `bin/adr-suggest`
kept its own default command vector naming one vendor and one pinned model tag,
and... | rvdbreemen/adr-kit | bin/adr_llm.py | .py | fa4d8e2902184d13 | 7.39 | 5 |
"""Enable the LLM judge on existing ADRs, opt-out style.
`llm_judge` defaults to TRUE as of TASK-74, so an Enforcement block that says
nothing about it opts in. Existing ADRs are the problem this module solves:
they were authored under the old default and carry an explicit
``"llm_judge": false`` that is indistinguisha... | rvdbreemen/adr-kit | bin/adr_llm_judge_migration.py | .py | d523af420aa1d9c8 | 7.39 | 5 |
"""Deterministic, read-only ADR readiness and implementation-link analysis."""
from __future__ import annotations
import fnmatch
import re
from datetime import date
from pathlib import Path
from typing import Dict, List, Optional, Sequence
from adr_catalog import build_relationships, load_adr_records, normalize_adr_... | rvdbreemen/adr-kit | bin/adr_readiness.py | .py | 73c235080f96f740 | 7.39 | 5 |
"""Killable, bounded regex evaluation for repository-authored policy."""
from __future__ import annotations
import atexit
import json
import queue
import subprocess
import sys
import threading
from pathlib import Path
from typing import Optional
DEFAULT_REGEX_TIMEOUT_SECONDS = 1.0
DEFAULT_REGEX_INPUT_BYTES = 2 * 10... | rvdbreemen/adr-kit | bin/adr_regex.py | .py | 36cb9f931abeac29 | 7.39 | 5 |
"""Shared ADR frontmatter schema helpers.
This module intentionally stays stdlib-only and YAML-subset-only. adr-kit
frontmatter is rendered in a simple shape that this parser can round-trip:
scalar fields plus string lists.
"""
from __future__ import annotations
import importlib.machinery
import importlib.util
impor... | rvdbreemen/adr-kit | bin/adr_schema.py | .py | 6147fafeb1764f86 | 7.39 | 5 |
"""A timeout that actually bounds, even behind a shim.
`subprocess.run(..., timeout=N)` does not bound anything once a descendant
outlives the direct child. CPython's own handler is:
except TimeoutExpired as exc:
process.kill()
if _mswindows:
exc.stdout, exc.stderr = process.communicat... | rvdbreemen/adr-kit | clients/installer/bounded.py | .py | 06e917fd0915ebb9 | 7.39 | 5 |
"""Read-only, registry-driven ADR Kit client detection."""
from __future__ import annotations
import hashlib
import json
import os
import shutil
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Mapping, Sequence
from .contracts import CLIENT_IDS, SPECS, Detect... | rvdbreemen/adr-kit | clients/installer/detection.py | .py | d06333f5b24a2cc1 | 7.39 | 5 |
"""Record the machine-local judge host client at install time.
ADR-036 keeps ADR-017's resolution rule: ``judge.backend`` resolves to the host
client's CLI *recorded at install time*. The client is knowable here and only
here - a ``git commit`` is client-agnostic, it happens whether or not any agent
is running - so an... | rvdbreemen/adr-kit | clients/installer/judge_backend.py | .py | afe01d54c2ab2943 | 7.39 | 5 |
"""Read what each client's OWN registration says is installed.
Detection cannot do this itself. It is mirrored into the generated codex/ and
copilot/ trees, where it must stay stdlib-only and free of per-client quirks,
and it promises in its own docstring not to invoke plugin managers. So the
quirks live here and the ... | rvdbreemen/adr-kit | clients/installer/registrations.py | .py | 6441e3f9cf898b1f | 7.39 | 5 |
"""Activation-independent smoke probes for a prepared payload.
Split from ``payload.py`` along the seam its own docstring already named:
preparing a payload is one job, proving the prepared runtimes actually answer
is another. ADR-010 caps a support module at 400 lines and ``payload.py`` had
reached it exactly.
"""
f... | rvdbreemen/adr-kit | clients/installer/smoke.py | .py | 8ec717aa8535661f | 7.39 | 5 |
"""Per-client lock, evidence, and rollback primitives."""
from __future__ import annotations
import json
import os
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Callable, Iterator
from .contracts import ClientResult
STALE_LOCK_SECONDS = 15 * 60
def _atomic_json(pat... | rvdbreemen/adr-kit | clients/installer/transaction.py | .py | fdf98efb35265c66 | 7.39 | 5 |
import torch
class KVCache:
"""A fixed-capacity inference key/value cache."""
def __init__(
self,
batch_size: int,
max_length: int,
num_kv_heads: int,
head_dim: int,
*,
dtype: torch.dtype,
device: torch.device | str,
) -> None:
raise... | ComistryMo/llm_interview_lab | curriculum/problems/ATT-009-kv-cache/starter.py | .py | a83b7da458d54e92 | 7.15 | 1 |
# -*- coding: utf-8 -*-
# @Time : 6/19/21 12:23 AM
# @Author : Yuan Gong
# @Affiliation : Massachusetts Institute of Technology
# @Email : yuangong@mit.edu
# @File : dataloader.py
# modified from:
# Author: David Harwath
# with some functions borrowed from https://github.com/SeanNaren/deepspeech.pytorch
imp... | oosuhada/multimodal-context-engine | a_cls/dataloader.py | .py | da347c045bf0dd11 | 7 | 0 |
import numpy as np
from scipy import stats
from sklearn import metrics
import torch
def d_prime(auc):
standard_normal = stats.norm()
d_prime = standard_normal.ppf(auc) * np.sqrt(2.0)
return d_prime
def calculate_stats(output, target):
"""Calculate statistics including mAP, AUC, etc.
Args:
o... | oosuhada/multimodal-context-engine | a_cls/stats.py | .py | 114e638de2a51d02 | 7 | 0 |
import math
import pickle
import numpy as np
import torch
import torch.nn as nn
import random
from collections import namedtuple
def calc_recalls(S):
"""
Computes recall at 1, 5, and 10 given a similarity matrix S.
By convention, rows of S are assumed to correspond to images and columns are captions.
"... | oosuhada/multimodal-context-engine | a_cls/util.py | .py | b65269cfad2c4c7b | 7 | 0 |
from functools import partial
from itertools import islice
from typing import Callable, List, Optional, Sequence, Union
import torch
import torch.nn.functional as F
def batched(iterable, n):
"""Batch data into lists of length *n*. The last batch may be shorter.
NOTE based on more-itertools impl, to be replac... | oosuhada/multimodal-context-engine | a_cls/zero_shot_classifier.py | .py | 96881e63cfb52c28 | 7 | 0 |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import os
import torchaudio
from torch.utils.data import Dataset
import numpy as np
import pandas as pd
from collections import defaultdict
import json
import random
fr... | oosuhada/multimodal-context-engine | al_ret/dataloader_msrvtt_retrieval.py | .py | 0e3d5e2380e8fd2e | 7 | 0 |
"""Manifest 기반 multimodal context index/search 명령행 인터페이스입니다."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from .encoder import LanguageBindContextEncoder
from .index import ContextIndex, MediaItem
def load_manifest(path: Path) -> list[MediaItem]:
"""JSON manifest를 ... | oosuhada/multimodal-context-engine | context_engine/cli.py | .py | fe46139ee570699d | 7 | 0 |
"""LanguageBind 원본 model/processor/tokenizer를 직접 사용하는 runtime encoder입니다."""
from __future__ import annotations
from collections import defaultdict
from pathlib import Path
import numpy as np
import torch
from languagebind import (
LanguageBind,
LanguageBindImageTokenizer,
to_device,
transform_dict,... | oosuhada/multimodal-context-engine | context_engine/encoder.py | .py | edc145a6ef8708b9 | 7 | 0 |
"""LAVIS registry를 직접 재사용해 context embedding fusion 전략을 관리합니다."""
from __future__ import annotations
from collections.abc import Callable
import numpy as np
from third_party.lavis.lavis.common.registry import registry
FusionFunction = Callable[[np.ndarray, list[str]], np.ndarray]
def _normalize(vector: np.ndarr... | oosuhada/multimodal-context-engine | context_engine/fusion.py | .py | b7ae74a058480596 | 7 | 0 |
"""멀티모달 item과 group-level context embedding을 보관하고 검색합니다."""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from pathlib import Path
import numpy as np
import torch
from .fusion import get_fusion
@dataclass(frozen=True)
class MediaItem:
"""한 개의 image/audio/video 입력과 그 c... | oosuhada/multimodal-context-engine | context_engine/index.py | .py | cc578504f177d577 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.