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
from abc import ABC, abstractmethod from typing import ClassVar from ragbits.chat.history import compressors from ragbits.core.prompt.base import ChatFormat from ragbits.core.utils.config_handling import WithConstructionConfig class ConversationHistoryCompressor(WithConstructionConfig, ABC): """ An abstract ...
rajath-raman/ragbits
packages/ragbits-chat/src/ragbits/chat/history/compressors/base.py
.py
e631a9f7f40fec33
7
0
from pydantic import BaseModel from ragbits.chat.history.compressors import ConversationHistoryCompressor from ragbits.core.llms.base import LLM from ragbits.core.prompt import ChatFormat, Prompt class LastMessageAndHistory(BaseModel): """ A class representing the last message and the history of messages. ...
rajath-raman/ragbits
packages/ragbits-chat/src/ragbits/chat/history/compressors/llm.py
.py
5d64869d49de79ba
7
0
import base64 import functools import hmac import json import logging import time import uuid from abc import ABC, abstractmethod from collections.abc import AsyncGenerator, Callable from typing import Any, Literal from ragbits.core.prompt.base import ChatFormat from ragbits.core.utils import get_secret_key from ..pe...
rajath-raman/ragbits
packages/ragbits-chat/src/ragbits/chat/interface/_interface.py
.py
bb396aefdf9cefee
7
0
from pydantic import BaseModel, Field class FormField(BaseModel): """Field in a feedback form.""" name: str = Field(description="Name of the field") type: str = Field(description="Type of the field (text, select, etc.)") required: bool = Field(description="Whether the field is required") label: s...
rajath-raman/ragbits
packages/ragbits-chat/src/ragbits/chat/interface/forms.py
.py
e5ce2be5286c7db3
7
0
from enum import Enum from typing import Any, cast from pydantic import BaseModel, ConfigDict, Field class MessageRole(str, Enum): """Defines the role of the message sender in a conversation.""" USER = "user" ASSISTANT = "assistant" SYSTEM = "system" class Message(BaseModel): """Represents a s...
rajath-raman/ragbits
packages/ragbits-chat/src/ragbits/chat/interface/types.py
.py
dc7ea49b19521d4b
7
0
from abc import ABC, abstractmethod from ragbits.chat.interface.types import ChatContext, ChatResponse class HistoryPersistenceStrategy(ABC): """Base class for history persistence strategies.""" @abstractmethod async def save_interaction( self, message: str, response: str, ...
rajath-raman/ragbits
packages/ragbits-chat/src/ragbits/chat/persistence/base.py
.py
bf6576917412c73a
7
0
import json from pathlib import Path from ..interface.types import ChatContext, ChatResponse from .base import HistoryPersistenceStrategy class FileHistoryPersistence(HistoryPersistenceStrategy): """Strategy that saves chat history to dated files in a directory.""" def __init__(self, base_path: str | Path):...
rajath-raman/ragbits
packages/ragbits-chat/src/ragbits/chat/persistence/file.py
.py
1c7c7bf05710273b
7
0
import uuid from typing import Any, Protocol, TypeVar import sqlalchemy from sqlalchemy import JSON, TIMESTAMP, Column, Float, ForeignKey, Integer, String, Text, func from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, create_async_engine from sqlalchemy.orm import DeclarativeBase from typing_extensions impo...
rajath-raman/ragbits
packages/ragbits-chat/src/ragbits/chat/persistence/sql.py
.py
2b75a40b3c20e83b
7
0
import json from collections.abc import AsyncGenerator from typing import Any from unittest.mock import MagicMock, mock_open, patch import pytest from fastapi.testclient import TestClient from ragbits.chat.api import RagbitsAPI from ragbits.chat.interface import ChatInterface from ragbits.chat.interface.forms import ...
rajath-raman/ragbits
packages/ragbits-chat/tests/unit/test_api.py
.py
be0b84e0781fecb2
7.5
0
import importlib.util import os import pkgutil from pathlib import Path from typing import Annotated # litellm downloads cost map on import, which creates extra latency in CLI. # This config disables it. os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" import click import typer from typer.main import get_command ...
rajath-raman/ragbits
packages/ragbits-cli/src/ragbits/cli/__init__.py
.py
d8552f6a7177a04b
7
0
from pathlib import Path from typing import Protocol, TypeVar import typer from pydantic.alias_generators import to_snake from rich.console import Console from ragbits.core.config import CoreConfig, core_config from ragbits.core.utils.config_handling import InvalidConfigError, NoPreferredConfigError, WithConstruction...
rajath-raman/ragbits
packages/ragbits-cli/src/ragbits/cli/_utils.py
.py
3d6f2fd57e1b9478
7
0
"""Add local auth support Revision ID: 0002 Revises: 0001 Create Date: 2026-03-09 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op revision: str = "0002" down_revision: Union[str, None] = "0001" branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence...
Cenkay1/s3BEAR
backend/alembic/versions/0002_local_auth.py
.py
697a5b7de520d159
7.3
3
"""Add audit log table Revision ID: 0003 Revises: 0002 Create Date: 2026-03-12 """ from typing import Sequence, Union import sqlalchemy as sa from sqlalchemy.dialects import postgresql from alembic import op revision: str = "0003" down_revision: Union[str, None] = "0002" branch_labels: Union[str, Sequence[str], None...
Cenkay1/s3BEAR
backend/alembic/versions/0003_audit_log.py
.py
222b418f715bb179
7.3
3
"""Add api_tokens table Revision ID: 0005 Revises: 0004 Create Date: 2026-08-19 """ from typing import Sequence, Union import sqlalchemy as sa from sqlalchemy.dialects import postgresql from alembic import op revision: str = "0005" down_revision: Union[str, None] = "0004" branch_labels: Union[str, Sequence[str], Non...
Cenkay1/s3BEAR
backend/alembic/versions/0005_api_tokens.py
.py
79f1a514dbcdc43d
7.3
3
"""Add storage_providers and managed_buckets tables (multi-provider support) Migrates the legacy single S3 connection (stored under the s3_* app_settings keys) into a default StorageProvider row so existing deployments keep working. Revision ID: 0007 Revises: 0006 Create Date: 2026-08-23 """ import uuid from typing ...
Cenkay1/s3BEAR
backend/alembic/versions/0007_storage_providers.py
.py
3ed971cb57c450a6
7.3
3
"""Add bucket_tags table Stores key/value tags for managed buckets in s3BEAR's own database, powering tag-based filtering and key/value autocomplete in the console. Revision ID: 0008 Revises: 0007 Create Date: 2026-08-24 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op revision...
Cenkay1/s3BEAR
backend/alembic/versions/0008_bucket_tags.py
.py
52322d8a802e75a4
7.3
3
"""Add tag-based targeting to cleanup policies A policy targets buckets either by name pattern (existing bucket_patterns) or by a single tag (tag_key + optional tag_value). The target_type column records which. Revision ID: 0009 Revises: 0008 Create Date: 2026-08-25 """ from typing import Sequence, Union import sql...
Cenkay1/s3BEAR
backend/alembic/versions/0009_policy_tag_targeting.py
.py
97d8b108e352a962
7.3
3
"""Shared helper for endpoints that can transform an image on the fly. Keeps the streaming fast-path untouched when no transform is requested, and returns a fully-buffered transformed Response otherwise. """ from fastapi import HTTPException, status from fastapi.responses import Response from app.core.config import s...
Cenkay1/s3BEAR
backend/app/api/v1/image_utils.py
.py
aa436f406aa44c5c
7.3
3
import uuid from datetime import datetime from typing import Optional from sqlalchemy import Boolean, DateTime, String, Text, ForeignKey, func from sqlalchemy.orm import Mapped, mapped_column, relationship from sqlalchemy.dialects.postgresql import UUID from app.core.database import Base class StorageProvider(Base): ...
Cenkay1/s3BEAR
backend/app/models/provider.py
.py
78fddf6416b15408
7.3
3
# backend/core/chat_engine.py — VIA Phase 5: Conversational Chat Engine # Uses Gemini first, falls back to Groq if Gemini hits rate limits import logging import os import re import httpx from backend.core.llm_provider import llm from backend.database.db import get_history_by_id from backend.core.memory_store import ge...
Gollavinaykumar1/via
backend/core/chat_engine.py
.py
1871d826c609a5dd
7
0
# backend/core/code_writer.py — Phase 3 # Handles LLM code block extraction and project file saving import os import re import logging from datetime import datetime logger = logging.getLogger("AI-Digital-Company") # Base directory where all generated projects are saved PROJECTS_BASE_DIR = os.path.join(os.path.dirnam...
Gollavinaykumar1/via
backend/core/code_writer.py
.py
557844d3b50617b0
7
0
# backend/core/inter_agent_bus.py # Phase 2: Inter-Agent Communication Bus # # Enables departments to share context with each other BEFORE final output. # Example flow: # - backend finishes → shares API design summary → security reads it # - security finishes → shares threat model → devops reads it # - architectu...
Gollavinaykumar1/via
backend/core/inter_agent_bus.py
.py
4a53bc99ba490e6e
7
0
# backend/core/memory_store.py — Phase 3: Agent Memory (DB-mode agnostic) import json import logging from backend.database.db import ( save_agent_mem, get_agent_mem, get_all_mem, save_meeting_db, get_meeting_db, get_recent_meetings_db ) logger = logging.getLogger("AI-Digital-Company") async def save_agent_m...
Gollavinaykumar1/via
backend/core/memory_store.py
.py
025818fa8a6d4afc
7
0
# backend/core/render_deployer.py # # FIX 1: live_url comes from Render API response, not constructed from svc_name. # FIX 2: _redeploy() sends full env var set so nothing gets wiped. # FIX 3: Uses RENDER_DATABASE_URL from .env — never auto-provisions a DB. # Table isolation handled per-app by fullstack_builder...
Gollavinaykumar1/via
backend/core/render_deployer.py
.py
1c3a6176aecb96d1
7
0
# backend/core/ws_manager.py # Phase 2: WebSocket Manager # Manages all active WebSocket connections per job_id # Broadcasts real-time streaming events to connected clients import asyncio import json from datetime import datetime from fastapi import WebSocket from .logger import logger class ConnectionManager: "...
Gollavinaykumar1/via
backend/core/ws_manager.py
.py
f07ca250d7cef40e
7
0
# backend/routers/filebrowser_router.py — VIA Phase 3: Project File Browser import os import json import zipfile import io from pathlib import Path from fastapi import APIRouter, Depends, HTTPException from fastapi.responses import Response, JSONResponse from backend.auth.auth import get_current_active_user router = ...
Gollavinaykumar1/via
backend/routers/filebrowser_router.py
.py
95ef69955d214c4e
7
0
# backend/tasks/orchestration_task.py # Phase 2: Background orchestration via Celery # Runs the full CEO → agents pipeline asynchronously # Job status tracked in DB; results retrievable via GET /jobs/{job_id} # Gracefully handles missing Celery/Redis import asyncio, json, time, logging from backend.tasks.celery_app im...
Gollavinaykumar1/via
backend/tasks/orchestration_task.py
.py
db8a072347ed9989
7
0
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = ["pillow>=10"] # /// """Render display copies of wallpapers into .display/. Two treatments: - Photos: the image full-bleed with a minimal shadowed caption (title + credit) in the bottom-right, placed inside the region that s...
arnavw/awe-some-wallpapers
rotator/compose.py
.py
792ebc97404b65cb
7
0
#!/usr/bin/python3 """Wallpaper fetcher for the WorldWallpapers rotation. Downloads high-resolution, landscape-oriented photos of architecture, buildings, and landscapes into ~/Pictures/WorldWallpapers. Sources, in order of preference: 1. Unsplash official API (only if `unsplash_access_key` is set in config.json) ...
arnavw/awe-some-wallpapers
rotator/fetch.py
.py
db485ccb391fbe65
7
0
#!/usr/bin/python3 """Legacy wallpaper setter for macOS 15 (Sequoia) and earlier — stamps every Space/display entry of the wallpaper store (~/Library/Application Support/ com.apple.wallpaper/Store/Index.plist) and restarts WallpaperAgent, which is the only path that covers all Spaces plus the lock screen on those syste...
arnavw/awe-some-wallpapers
rotator/set_wallpaper.py
.py
6003483a7391596d
7
0
"""Fail closed when two package directories are not byte-identical.""" from __future__ import annotations import argparse import hashlib from pathlib import Path import sys def _package_entries(directory: Path, label: str) -> tuple[str, str]: """Return the ZIP and manifest names after validating *directory*."""...
mtchuang1981/clin-data-nav
scripts/compare_packages.py
.py
0a44b6de937d38f1
7
0
#!/usr/bin/env python3 """Bounded read-only SARIF structural observer; not a validator or triage tool.""" import json,sys def band(n): return 'none' if n==0 else 'one' if n==1 else 'few' if n<5 else 'many' def summarize(text): d=json.loads(text) if not isinstance(d,dict): return {'top_level':'non-object'} runs=d.get...
ranaaryan-testing-a/sarif-related-location-cue
sarif_related_location_cue.py
.py
00cd20f7e3b3d4cf
7
0
# Name: Rabbi Ahmed # Student Number: 10698964 # admin.py — CLI to manage board games in data.txt (JSON list). import json def inputInt(prompt): """Read a positive integer (> 0) from the user; re-prompt on bad input.""" while True: raw = input(prompt) try: value = int(raw) ...
Judiciousmurich/board-game-catalogue
admin.py
.py
d3b1c5b1467c8ca1
7
0
import os import torch import logging from pathlib import Path from pyannote.audio import Pipeline from huggingface_hub import snapshot_download from pyannote.audio.core.task import Problem, Resolution, Specifications from transformers import ( AutoModelForSpeechSeq2Seq, AutoProcessor, WhisperFeatureExtract...
ma14ch/Avano
src/models.py
.py
ae03ee3d992c09ae
7.35
4
import os import tempfile import uuid import librosa import numpy as np import torch import logging from pydub import AudioSegment, effects from pathlib import Path from models import get_asr_model, get_diarization_pipeline # Configure logging logger = logging.getLogger(__name__) # Target loudness (dBFS) that quiet/...
ma14ch/Avano
src/processor.py
.py
18dd5c0a41e37307
7.35
4
"""v0.5.0 任务持久化:队列/历史落 SQLite,服务重启恢复未完成任务。 设计(任务 2-3): - 单表 jobs,一行一个任务的最新快照(与 Job.snapshot() 字段对齐, progress 以 JSON 存储) - 终态任务(done/cancelled/error)保留为历史,非终态(queued/running/ paused)在 JobManager 启动时按 seq 顺序恢复重跑——配合翻译缓存, 重跑只剩增量段(已完成段的译文直接命中缓存零调用) - 运行配置文件(.ui_run_config_*.yaml)由 app.py 落盘、任务终态才清理, 服务被杀时文件仍在,重启恢复...
ShZbz/pdf-translator
server/store.py
.py
6f319102b1c233ce
7.15
1
"""P2 验收单测(SCHEME §6 P2): - batch 协议 roundtrip(LLM 返回 JSON → 译文落位) - 缓存二次运行 0 调用 - max_llm_calls 触顶行为(不崩、保留原文、stderr 警告) - [FORMULA_n] 计数守恒 - 坏响应重试一次后降级保留原文 """ from __future__ import annotations import json import threading import time import sys from pathlib import Path from types import SimpleNamespace sys.path.in...
ShZbz/pdf-translator
tests/test_smoke.py
.py
5e87a73751b106b9
7.65
1
"""v0.4.2 单测:多语言注册表 / 跨平台字体 / 语言化排版 / Unicode 断行 / 修复回归。 全部零网络零 API key;字体目录相关用 tmp_path + monkeypatch 隔离, 不依赖本机是否装了对应字体。 """ from __future__ import annotations import sys from pathlib import Path from types import SimpleNamespace import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import tr...
ShZbz/pdf-translator
tests/test_v042.py
.py
e7c3966c31066139
7.65
1
"""SQLite 翻译缓存。key = MD5(engine|model|lang_pair|text)。 SCHEME: 二次运行 0 调用(验收清单 #2)。 """ from __future__ import annotations import hashlib import sqlite3 from pathlib import Path class TranslationCache: def __init__(self, db_path: str | Path, max_entries: int = 0): """max_entries: v0.4.3 容量上限(0=不限制)。 ...
ShZbz/pdf-translator
translator/cache.py
.py
63e06a2554de1d82
7.15
1
"""YAML 配置 → dataclass 校验 + provider presets(SCHEME §5)。""" from __future__ import annotations from dataclasses import dataclass, field from pathlib import Path import yaml PRESETS: dict[str, dict] = { "deepseek": {"base_url": "https://api.deepseek.com/v1", "env": "DEEPSEEK_API_KEY"}, "openai": {"bas...
ShZbz/pdf-translator
translator/config.py
.py
b11f38ee77586dc9
7.15
1
"""文字层提取:page → 结构化块列表(BBox/size/flags/font)。 <50 字符的扫描页候选走 OCR 降级(D7),OCR 引擎为可选依赖, 未安装时该页保留空文本并计入警告。 """ from __future__ import annotations import pymupdf def page_has_text_layer(page, min_chars: int = 50) -> bool: """D7: 文字层字符数 < min_chars 视为扫描页候选。""" return len(page.get_text().strip()) >= min_chars def...
ShZbz/pdf-translator
translator/extract.py
.py
2253c6147c70bcc8
7.15
1
"""v0.4.3 惰性 OCR 接入:扫描页文字提取(paddleocr 可选依赖)。 设计(任务 2-3 落地): - OCR 引擎完全惰性:只有文档里检出扫描页且 engine 可用时才 import。 未安装 paddleocr 时给出明确警告并保持旧行为(扫描页原样保留), 绝不因缺依赖崩溃。 - 引擎单例按 (engine, lang) 缓存——paddleocr 初始化(模型加载)很重, 每页重建会把 8 页文档的 OCR 时间放大 8 倍。 - 输出仅取文本行(按 y 排序拼接)。bbox 不用:扫描页的"翻译回贴" 需要覆盖原图再排版(PDFMathTranslate 式),风险高;v0.4.3 ...
ShZbz/pdf-translator
translator/ocr.py
.py
c972106c5902f963
7.15
1
"""修复 _wrap_cjk: Latin 词不拆行(词边界断行), CJK 保持逐字断行。 v0.2.2 任务1/5 排版包:英文保留段/双语原文层被逐字拆碎的根因是 贪心逐字断行对 Latin 文本无词边界概念。改为混合策略: - 连续 Latin/digit 串视为不可分 token - 行首放不下整个 token 时整词压到下一行;超长 token(>行宽)硬切兜底 - CJK 字符维持逐字+避头尾 """ from __future__ import annotations import re import pymupdf # 行首禁则标点(不可出现在行首,悬挂到上一行行尾) _NO_LINE_START = s...
ShZbz/pdf-translator
translator/wrap_mixed.py
.py
127c65f86c37a73f
7.15
1
""" Distributed dataloaders for pretraining. BOS-aligned bestfit: - Every row starts with BOS token - Documents packed using best-fit algorithm to minimize cropping - When no document fits remaining space, crops a document to fill exactly - 100% utilization (no padding), ~35% tokens cropped at T=2048 Comp...
askerlee/kappa-swiglu
nanochat/dataloader.py
.py
2fbb50ff7d7981aa
7
0
#!/usr/bin/env python3 import subprocess import time import sys def get_gpu_utilizations(): """Get current GPU utilization percentages for all visible GPUs.""" result = subprocess.run( ['nvidia-smi', '--query-gpu=utilization.gpu', '--format=csv,noheader,nounits'], capture_output=True, t...
askerlee/kappa-swiglu
scripts/auto-shutdown.py
.py
c4e4c17eb9e7e552
7
0
""" Base class for all Tasks. A Task is basically a dataset of conversations, together with some metadata and often also evaluation criteria. Example tasks: MMLU, ARC-Easy, ARC-Challenge, GSM8K, HumanEval, SmolTalk. """ import random class Task: """ Base class of a Task. Allows for lightweight slicing of the ...
askerlee/kappa-swiglu
tasks/common.py
.py
182aee93d56f9870
7
0
"""Tool adapters.""" from __future__ import annotations __all__ = ("CellProfilerAdapter", "OpenHCSAdapter") _EXPORT_NAMES = frozenset(__all__) _MISSING_EXPORT = object() def _adapter_export_modules(): import benchmark.adapters.openhcs as openhcs_adapter yield openhcs_adapter import benchmark.adapters...
OpenHCSDev/openhcs
benchmark/adapters/__init__.py
.py
aa93075a5770d135
7.35
4
"""Shared .cppipe source resolution for benchmark adapters.""" from __future__ import annotations from collections.abc import Callable, Mapping from dataclasses import dataclass from pathlib import Path from typing import Any from urllib.parse import urlparse from urllib.request import urlopen from benchmark.contrac...
OpenHCSDev/openhcs
benchmark/adapters/cppipe_source.py
.py
92dbff9de92e77e1
7.35
4
"""Dataset contracts for benchmark platform.""" from __future__ import annotations from pathlib import Path from dataclasses import dataclass from enum import Enum class ArchiveFormat(Enum): """Supported dataset archive formats.""" ZIP = "zip" class DatasetValidationRule(Enum): """Dataset acquisition...
OpenHCSDev/openhcs
benchmark/contracts/dataset.py
.py
2d35266b1dac6c3f
7.35
4
"""Self-materializing benchmark manifest root contracts.""" from __future__ import annotations import os import shutil import subprocess from abc import ABC, abstractmethod from collections.abc import Mapping, Sequence from dataclasses import dataclass from enum import Enum from pathlib import Path from typing import...
OpenHCSDev/openhcs
benchmark/contracts/manifest_acquisition.py
.py
8a09c47497c234fa
7.35
4
"""Pipeline contracts for benchmark platform.""" from __future__ import annotations from dataclasses import dataclass, field from types import MappingProxyType from benchmark.contracts.values import BenchmarkParameterMap def immutable_benchmark_parameters( values: BenchmarkParameterMap | None = None, ) -> Benc...
OpenHCSDev/openhcs
benchmark/contracts/pipeline.py
.py
54857ee11404bdc5
7.35
4
"""Tool adapter abstract base class for benchmark platform.""" from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Sequence from pathlib import Path from dataclasses import dataclass from typing import ClassVar from benchmark.contracts.metric import MetricCollector from...
OpenHCSDev/openhcs
benchmark/contracts/tool_adapter.py
.py
6ff5923c8f7ba171
7.35
4
"""Typed expectations for in-tree CellProfiler .cppipe fixtures.""" from __future__ import annotations from collections.abc import Mapping, Sequence from dataclasses import dataclass from enum import Enum import os from pathlib import Path from benchmark.contracts.comparison_manifest import ComparisonManifest from b...
OpenHCSDev/openhcs
benchmark/converter/cppipe_corpus.py
.py
b533f62e8366f3b7
7.35
4
"""Dataset acquisition utilities.""" from __future__ import annotations import subprocess import shutil import zipfile from abc import ABC, abstractmethod from dataclasses import dataclass from pathlib import Path from urllib.parse import unquote, urlparse from metaclass_registry import AutoRegisterMeta import reque...
OpenHCSDev/openhcs
benchmark/datasets/acquire.py
.py
d1d7f66bd78a0a5b
7.35
4
"""Benchmark dataset filesystem path authorities.""" from __future__ import annotations import os from enum import Enum from pathlib import Path OPENHCS_BENCHMARK_DATASET_CACHE_ROOT_ENV = "OPENHCS_BENCHMARK_DATASET_CACHE_ROOT" CELLPROFILER_EXAMPLES_ROOT_ENV = "CELLPROFILER_EXAMPLES_ROOT" class BenchmarkPathRootKi...
OpenHCSDev/openhcs
benchmark/datasets/cache.py
.py
df88ef97ca44ec11
7.35
4
"""Materialize acquired datasets into benchmark manifests.""" from __future__ import annotations import json from collections.abc import Iterable from pathlib import Path from benchmark.contracts.dataset import AcquiredDataset, DatasetSpec from benchmark.datasets.cache import default_benchmark_dataset_cache_root d...
OpenHCSDev/openhcs
benchmark/datasets/manifest.py
.py
f3ab9ca4152d54bb
7.35
4
"""Registry of benchmark datasets.""" from __future__ import annotations from abc import ABC from typing import ClassVar from pathlib import Path from metaclass_registry import AutoRegisterMeta from openhcs.constants.constants import Microscope from benchmark.contracts.dataset import ( ArchiveFormat, Benchm...
OpenHCSDev/openhcs
benchmark/datasets/registry.py
.py
10a2fa46fbe4c56b
7.35
4
"""Wall-clock timing metric.""" import time from benchmark.contracts.metric import MetricCollector class TimeMetric(MetricCollector): """Measures execution time using perf_counter.""" name = "execution_time_seconds" def __init__(self): self.start_time: float | None = None self.end_time...
OpenHCSDev/openhcs
benchmark/metrics/time.py
.py
fb1a4facd5f7a93c
7.35
4
#!/usr/bin/env python3 """ CellProfiler IdentifyPrimaryObjects - Exact Replication in OpenHCS This module provides an exact reimplementation of CellProfiler's IdentifyPrimaryObjects algorithm for nuclei segmentation, using the same algorithmic steps: 1. Smoothing (Gaussian blur with auto-calculated sigma) 2. Threshol...
OpenHCSDev/openhcs
benchmark/pipelines/cellprofiler_nuclei.py
.py
0213e71025d67399
7.35
4
#!/usr/bin/env python3 """ CellProfiler IdentifyPrimaryObjects - GPU-Accelerated (pyclesperanto) Same algorithm as cellprofiler_nuclei.py but running on GPU. This demonstrates OpenHCS's backend polymorphism - same algorithm, different backend. Performance comparison: - CellProfiler (CPU, single-threaded): 195 AWS mac...
OpenHCSDev/openhcs
benchmark/pipelines/cellprofiler_nuclei_gpu.py
.py
47a851b41c383bc0
7.35
4
"""Registry of benchmark pipelines.""" from __future__ import annotations from abc import ABC from typing import ClassVar from metaclass_registry import AutoRegisterMeta from benchmark.contracts.pipeline import PipelineSpec from benchmark.contracts.values import BenchmarkParameterMap class BenchmarkPipelineDeclar...
OpenHCSDev/openhcs
benchmark/pipelines/registry.py
.py
22db38a979d30a52
7.35
4
"""Benchmark runner.""" from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Any, Iterable, Mapping from benchmark.adapters.cellprofiler import ( CellProfilerAdapter, native_cellprofiler_reference_provenance, ) from benchmark.adapters.openhcs import...
OpenHCSDev/openhcs
benchmark/runner.py
.py
089f0c3a31496dcf
7.35
4
"""Shared runtime environment setup for benchmark entrypoints.""" from __future__ import annotations import logging import os from openhcs.core.native_threading import configure_native_thread_count def configure_headless_cpu_benchmark_runtime(log_level: str) -> None: """Configure deterministic CPU-only benchma...
OpenHCSDev/openhcs
benchmark/runtime_env.py
.py
c5661239230be69e
7.35
4
"""[GTX]-prefixed logging shim for bt-hosted processes. Exports `gtx_log` with the same surface as `bt.logging` (`.info` / `.warning` / `.error` / `.debug` / `.success`). Records are routed through `bt.logging` with `prefix="[GTX]"` so they pick up bt's formatter + level config — grep-friendly for operators, no f-stri...
ronaldo-porto/orthoxplus_gold
GenTRX/src/bt_log.py
.py
6260a608ae604825
7
0
# SPDX-FileCopyrightText: 2025 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """DataLoader for order stream parquets — per-field inputs and labels. Lazy chunk-indexed loading: only parquet metadata is read at init time. File contents are loaded, tokenized, and cached on demand via LRU. Uses ChunkS...
ronaldo-porto/orthoxplus_gold
GenTRX/src/dataloader.py
.py
ecbf9c76de5f958d
7
0
# SPDX-FileCopyrightText: 2025 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """Window-based distributed training primitives. Wraps the existing training infrastructure to support the distributed protocol: 1. train_window() — train for N steps, return a GradientDelta 2. apply_gradient() — appl...
ronaldo-porto/orthoxplus_gold
GenTRX/src/distributed.py
.py
4517b29f2f999937
7
0
# SPDX-FileCopyrightText: 2025 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """Training and evaluation metrics for GenTRX order model. Provides human-interpretable metrics beyond raw CE loss: - Per-field top-k accuracy (especially order_type direction accuracy) - Mid-price direction accuracy (...
ronaldo-porto/orthoxplus_gold
GenTRX/src/metrics.py
.py
445f6a7c6d07beb6
7
0
# SPDX-FileCopyrightText: 2025 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """Minimal LOB matching engine for inference. Adapted from mlib/core/orderbook.py (Microsoft MarS). Stripped to continuous auction only — no call auction, no agent framework, no event loop. Used at inference time to compu...
ronaldo-porto/orthoxplus_gold
GenTRX/src/orderbook.py
.py
bf733f7691e6a058
7
0
# SPDX-FileCopyrightText: 2025 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """State extractor for the validator/proxy. Walks a `MarketSimulationStateUpdate` (or compatible dict) and produces a serialization-friendly tick packet that the gradient server can ingest. State packet format: { ...
ronaldo-porto/orthoxplus_gold
GenTRX/src/state_packager.py
.py
ee5afc3dae7bd19d
7
0
# SPDX-FileCopyrightText: 2025 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """Order tokenizer — per-field binning, no composite tokens. Each order field is binned independently. No flat vocabulary. Fields: order_type, price, vol_int, vol_dec, interval. Conditioning (not tokenized): lob_volumes, t...
ronaldo-porto/orthoxplus_gold
GenTRX/src/tokenizer.py
.py
e2e9bfb7f9692271
7
0
# SPDX-FileCopyrightText: 2025 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """Wandb integration for GenTRX gradient server. Mirrors every aggregation event (already written to aggregation.jsonl) to a Weights & Biases run. Soft dependency — import failure or missing project config means the module...
ronaldo-porto/orthoxplus_gold
GenTRX/src/wandb_ops.py
.py
949e11ad5fb92aa0
7
0
"""Tests for GradientAggregator assignment lifecycle. Verifies the event-driven assignment state machine: PENDING -> DATA_READY -> DELIVERED -> GRADIENT_IN -> SCORED These tests use a mocked store so they run without S3. """ from unittest.mock import MagicMock import pytest @pytest.fixture def aggregator(tmp_path...
ronaldo-porto/orthoxplus_gold
GenTRX/tests/test_assignment_lifecycle.py
.py
404ae1f61bee264a
7.5
0
# SPDX-FileCopyrightText: 2026 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """ Miner training pipeline — pool-shutdown must not deadlock on stuck downloads. Regression for the observed live bug (2026-07-02): benchmark miner on a remote R2-backed deployment received 27 assignments over ~2 hours bu...
ronaldo-porto/orthoxplus_gold
GenTRX/tests/test_miner_training_no_pool_deadlock.py
.py
a107265eebf862f9
7.5
0
"""network_from_subtensor: bucket-prefix network resolution. Regression for the aggregator/validator prefix split — a netuid-2 localnet resolved to `localnet` for the validator (which passed netuid) but `mainnet` for the gradient server (which didn't), so their S3 prefixes diverged and the aggregator never saw miner g...
ronaldo-porto/orthoxplus_gold
GenTRX/tests/test_network_resolution.py
.py
87f298651f61b628
7.5
0
# SPDX-FileCopyrightText: 2026 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """ PR-2 — concurrency hardening tests. Black-box assertions on the locks introduced this round: * ``GradientServer._assignments_lock`` exists and is an RLock so the API path can re-enter through ``_create_assignmen...
ronaldo-porto/orthoxplus_gold
GenTRX/tests/test_pr2_concurrency.py
.py
6f437a223fbf9cc3
7.5
0
# SPDX-FileCopyrightText: 2026 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """ PR-3 — scoring fairness + observability. Covers the validator-side reward changes (EMA bootstrap-at-0, per-round idempotency) and the gradient_server scores-payload additions (rejection_reason + held_unavailable). `sc...
ronaldo-porto/orthoxplus_gold
GenTRX/tests/test_pr3_scoring_fairness.py
.py
e666de1ec71ccd30
7.5
0
# SPDX-FileCopyrightText: 2026 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """ PR-4 — performance micro-fixes. Tests: 1. The decompress→compress round-trip on the aggregated dense gradient is gone — we build the GradientDelta directly. Verified by checking that the new code path produ...
ronaldo-porto/orthoxplus_gold
GenTRX/tests/test_pr4_performance.py
.py
fa0ada217726f9f4
7.5
0
# SPDX-FileCopyrightText: 2026 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """ PR-5 — defensive guards + circuit-breaker observability. Tests: 1. `_prune_dedup_keys` drops `miner_X/round_Y` entries whose round_id is older than `_DEDUP_RETENTION_ROUNDS` rounds behind `_agg_round`. 2. The ...
ronaldo-porto/orthoxplus_gold
GenTRX/tests/test_pr5_defensive.py
.py
edee8435de9926df
7.5
0
# SPDX-FileCopyrightText: 2026 Rayleigh Research <to@rayleigh.re> # SPDX-License-Identifier: MIT """GenTRX startup isolation — `_restore_written_parquets` wall-clock budget. Background: on sim-local-dev with a stale 12 GB minio data-dir, boto3's paginated `ListObjectsV2` against the validator's bucket hangs in `socket...
ronaldo-porto/orthoxplus_gold
GenTRX/tests/test_pr_isolation_restore_timeout.py
.py
f0c11fe47cb5028a
7.5
0
"""Tests for price/volume scale binding in the gradient server. Pin the rule: the live sim's priceDecimals/volumeDecimals bind the scale when present; a tick that reaches the server with no decimals falls back to the canonical simulation_0.xml values (pd=2, vd=4) and logs a warning, never a silently-wrong scale. Run:...
ronaldo-porto/orthoxplus_gold
GenTRX/tests/test_scale_binding.py
.py
4744e2f125f81377
7.5
0
"""Plumbing tests for the plain-text adapter (DESIGN.md section 6.1). Why the adapter is worth real tests even though it is barely 60 lines: silent chunking bugs (dropping the last paragraph, swallowing a chunk, reading files in a different order each run) produce a subtly wrong corpus rather than an error. Nothing do...
willnordnet/tiny-gpt-trainer
tests/test_adapters.py
.py
069d52890544ef5d
7.5
0
"""Plumbing tests for the data-prep stage (DESIGN.md section 6.1). This stage is where a mistake becomes hardest to trace. An out-of-range token id or a wrong dtype does not fail here, it fails inside the model as an opaque indexing error, a long way from the code that caused it. And a leaky train/val split does not f...
willnordnet/tiny-gpt-trainer
tests/test_data_prepare.py
.py
873a3887696c7e84
7.5
0
"""Plumbing tests for the byte-level BPE tokenizer (DESIGN.md section 6.1). A silently broken round trip is the worst bug class in this project: it does not raise, it poisons every downstream stage, and the symptom (a model emitting nonsense) is indistinguishable from a small model behaving exactly as expected. So the...
willnordnet/tiny-gpt-trainer
tests/test_tokenizer.py
.py
89b5c5d6a598d463
7.5
0
"""The adapter interface: the one abstraction in this project that matters. Everything downstream of an adapter (tokenizer, token shards, model, training loop, sampler) works on text and knows nothing about where that text came from. That is the entire point: an adapter is the *only* place domain-specific logic is all...
willnordnet/tiny-gpt-trainer
tinygpt/adapters/base.py
.py
092a2bd56e3d2ac5
7
0
"""Plain-text adapter: reads .txt file(s) and yields paragraph-ish chunks. This is the only adapter in the project, deliberately (DESIGN.md section 7): a general-purpose interface is easiest to get right once it has been proven against one real, working case rather than several imagined ones. Run directly to see the ...
willnordnet/tiny-gpt-trainer
tinygpt/adapters/plain_text.py
.py
a4a7c8ae77d31ccb
7
0
"""Model and training size presets. Why a config module at all, rather than constants scattered across model.py and train.py: the same handful of numbers (how wide, how deep, how long a context) determine the shape of nearly every tensor in the project. Naming them in one place means `model.py` can talk about `cfg.d_m...
willnordnet/tiny-gpt-trainer
tinygpt/config.py
.py
3c847aed117ebf86
7
0
"""Turn a text source into token shards ready for training. This is the last stage that knows anything about text. Everything after it (model.py, train.py) sees only integer arrays. Each split is written as one flat uint16 stream, not as pre-cut fixed-length windows. Training windows are sliced out of that stream at ...
willnordnet/tiny-gpt-trainer
tinygpt/data/prepare.py
.py
3efaaa60abf7550a
7
0
"""Byte-level BPE tokenizer: load, encode, decode. This file is the *runtime* side of the tokenizer. Training lives in train_tokenizer.py, because training happens once and encoding happens constantly, and separating them keeps this file short enough to read in one sitting. Why byte-level, starting from the 256 singl...
willnordnet/tiny-gpt-trainer
tinygpt/tokenizer/tokenizer.py
.py
87be09174d974faf
7
0
"""Train a byte-level BPE vocabulary from whatever an adapter yields. Why train a tokenizer instead of importing a pretrained one (tiktoken, GPT-2's vocab): doing it yourself is a large part of what this project is for, and a tiny model genuinely wants a tiny vocabulary. At 4096 tokens the embedding table is ~18% of t...
willnordnet/tiny-gpt-trainer
tinygpt/tokenizer/train_tokenizer.py
.py
2e0f52fd9d74acb9
7
0
"""Look inside a saved checkpoint: next-token distributions and attention. Everything here loads a checkpoint from disk rather than reaching into the running trainer. That is a consequence of running training as a subprocess (see web/runner.py): the weights being optimised live in another process, and the only thing t...
willnordnet/tiny-gpt-trainer
web/introspect.py
.py
45891433ae43c692
7.5
0
"""anyon.py —— 任意子统计类型判定(10.43/10.44) δ = Cl(8) Majorana 8-循环置换:8-循环 = 7 个相邻对换; 单次对换携带 Ising(Majorana)交换相位 e^{±iπ/4}; δ 净相位 = 7π/4 = -π/4;δ⁸ 净相位 = 14π ≡ 0 (mod 2π), 与 Berry 相位 2π 一致 → 回路闭合无剩余相位。 判定:δ⁸ 回路携带 Ising 型(Majorana 型)任意子统计, 非 Fibonacci 型(Fibonacci 型要求非 Abelian 相位结构)。 """ import numpy as np # Cl(8) Majorana 8...
sdoygb/qec-geometry
qecgeo/anyon.py
.py
22f224ea51920b61
7.15
1
"""qecgeo/closedform.py —— AG 完备码族闭式参数(几何论 10.27–10.36) 零电路、零模拟:由组合闭式直接给出码参数、失败率、损失标度、零损失边界。 定理引用: - 码参数 [[2^m, k, 2^{r+1}]]: 10.30 - fail(w0) 引理 10.35.2.07 - kappa 引理 10.35.2.10 - loss(θ) 定理 10.35.1.07 - 零损失 定理 10.31.1.01 """ from __future__ import annotations import math from math import comb from...
sdoygb/qec-geometry
qecgeo/closedform.py
.py
badf5a7f2f751c8f
7.15
1
"""pauli.py —— n 比特 Pauli 算符(qecgeo 几何码工具包) 表示:每比特类型 t_i ∈ {0=I, 1=X, 2=Z, 3=Y},整体相位 ∈ {±1, ±i}。 单比特乘法表由 2×2 矩阵自动生成,避免手写错误。 """ import numpy as np # ---------- 单比特乘法表(自动生成) ---------- _I = np.eye(2, dtype=complex) _X = np.array([[0, 1], [1, 0]], dtype=complex) _Z = np.array([[1, 0], [0, -1]], dtype=complex) _Y = 1j *...
sdoygb/qec-geometry
qecgeo/pauli.py
.py
8ea5f61920650179
7.15
1
"""rm_decoder.py —— Reed-Muller 快速解码器(矩恢复,O(n·poly),非查表) 量子 CSS(RM(r,m)) 的 X 错误解码 ≡ 经典码 RM(m-r-1,m) 的 syndrome 解码: - syndrome = 错误支撑 A 与次数 ≤ r 单项式的点积("矩") - 解码目标:从矩恢复最小权重错误 A(= syndrome 类的最小权重代表) - 矩唯一性(260827 复核):权重 ≤ (d−1)/2 = 2^r − ½ 的错误矩唯一(可纠 范围,理论保证);更大权重在 m 小时碰撞(r=1 的 w=2 对所有 m 大量 碰撞——线性矩不足;r=2 且 m...
sdoygb/qec-geometry
qecgeo/rm_decoder.py
.py
e1b7b35cd7763635
7.15
1
"""rm_general_decoder.py —— 通用 Reed-Muller 矩解码器(r≥1,非查表) 理论: 量子 CSS(RM(r,m)) X 错误 A 的 syndrome = 次数 ≤ r 矩 m_I = Σ_{a∈A} x_I(a)。 矩唯一性(260827 复核修正):权重 ≤ (d−1)/2 = 2^r − ½(整数 ≤ 2^r−1)的 错误矩唯一(可纠范围,理论保证);更大权重在 m 小时出现碰撞 (如 (5,2) w=4 有 ~1% 碰撞,(4..8,1) w=2 大量碰撞)——超出码的纠错能力, 解码器对可纠范围内错误返回唯一解,超出后可能返回最小权重代表 (非真实 A)。10...
sdoygb/qec-geometry
qecgeo/rm_general_decoder.py
.py
a685a442dbcbc226
7.15
1
"""stabilizer.py —— 稳定子码框架(qecgeo 几何码工具包) 编码 |ψ_L⟩、syndrome 测量、解码(查表)、纠错、保真度、距离验证。 对应:10.27 命题 3.13–3.15(几何码构造,O5 程序复核)。 """ import numpy as np from itertools import product, combinations from .pauli import Pauli class StabilizerCode: def __init__(self, name, gens, lx, lz): self.name = name self....
sdoygb/qec-geometry
qecgeo/stabilizer.py
.py
75586d46c2b6201c
7.15
1
"""threshold.py —— 容错阈值闭式(10.44) 理论:单轮最优纠错下,逻辑错误率 p_L(p) ≈ A·p²(A = η·C(n,2)), 其中 η = 权重 2 错误被误恢复为逻辑算符的比例(全枚举精确计算)。 理想拼接阈值 p_th = 1/A(拼接不动点 p_{L+1} = A·p_L² = p_L ⟺ p = 1/A; p_L = 1 的渐近点在 1/√A——括注 260827 修正)。 模块内容: - weight2_errors(code) 全部非平凡权重 2 Pauli 错误 - analyze_eta(code) 精确枚举 η、A、p_th - mo...
sdoygb/qec-geometry
qecgeo/threshold.py
.py
8abd7af33ad21695
7.15
1
#!/usr/bin/env python3 """ag_pL_sim.py —— AG 完备码 depolarizing 噪声 p_L 模拟(10.84 桥接验证) 零简并理论(10.30 定理 10.30.2.02/10.30.2.03)的物理噪声验证: - r≥2 的 AG 完备码零简并 ⟹ 权重 ≤ d−1 = 2^r 的错误全部可恢复(查表无歧义) - depolarizing 噪声下 p_L ≈ P(权重 ≥ d)(w<d 无逻辑、无简并、查表全恢复) - 对照 r=1 AG(部分简并)与 r≥2 AG(零简并) 发现:AG(6,2) [[64,20,8]] / AG(8,3) [[256,70,16]] 零简并 +...
sdoygb/qec-geometry
scripts/ag_pL_sim.py
.py
a633696822ba5ca4
7.15
1
#!/usr/bin/env python3 """ag_stim_memory.py —— AG 码 stim 多轮记忆电路 + 差分探测器 + 查表解码 stim 多轮电路(rounds=2 参考轮 + 差分探测器)基础设施: - 数据 depolarize(轮间)+ 测量噪声(MR flip)标准模型 - 差分探测器正确(无噪声 dets 全零,已验证) - 从 stim 差分提取稳定子(X_ERROR/Y_ERROR 注入)= 标准 RM 生成元(已验证) - LookupDecoder 查表解码管线(p_L 输出) 已打通(验证): 1. 多轮电路语义正确:rounds=2 差分,无噪声 dets 全零、obs 全 F...
sdoygb/qec-geometry
scripts/ag_stim_memory.py
.py
a6070a628eca2470
7.15
1
"""跨码多噪声扫描:surface code vs color code 的 A0/A1 几何诊断区分度 用法(在装有 stim+pymatching+chromobius 的环境): python scripts/benchmark_scan.py [--shots 10000] [--seed 42] 输出 benchmark 表:pL, cross_lift, total_dist_ratio, exc_ratio, cluster_ratio """ import argparse import sys import time import numpy as np sys.path.insert(0, "....
sdoygb/qec-geometry
scripts/benchmark_scan.py
.py
52d97811367b0e0f
7.15
1