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 |
|---|---|---|---|---|---|---|
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2026 finevals.ai and contributors.
"""Honest rolling-statistics baseline for the payment-behaviours late-payment task.
The FM fine-tune answers "will a currently-current customer exceed 30 dpd within the next 3
invoices?" from the raw days-past-due sequence. The ob... | Algoritmica-ai/deeploans | credit-foundation-model/scripts/baseline_payment_behaviours.py | .py | 3988f38e105432a0 | 7.6 | 15 |
import logging
import subprocess
import requests
from pygeoweaver.constants import *
from pygeoweaver.server import ensure_geoweaver_started
from pygeoweaver.utils import (
download_geoweaver_jar,
get_geoweaver_jar_path,
get_java_bin_path,
get_root_dir,
get_spinner,
check_os,
)
from pygeoweaver... | ESIPFed/pygeoweaver | pygeoweaver/commands/pgw_detail.py | .py | 265dcd9c6fe2c7bb | 7.63 | 17 |
import http
import json
import logging
import subprocess
import traceback
from urllib.parse import urlencode, urlparse
import click
import pandas as pd
import requests
from tabulate import tabulate
from pygeoweaver.constants import *
from pygeoweaver.server import check_geoweaver_status, start
from pygeoweaver.utils ... | ESIPFed/pygeoweaver | pygeoweaver/commands/pgw_history.py | .py | 738e21d43c5da4f0 | 7.63 | 17 |
import subprocess
from pygeoweaver.utils import (
download_geoweaver_jar,
get_geoweaver_jar_path,
get_java_bin_path,
get_root_dir,
)
def import_workflow(workflow_zip_file_path):
"""
Usage: <main class> import workflow <workflow_zip_file_path>
import a workflow from file
<workflow... | ESIPFed/pygeoweaver | pygeoweaver/commands/pgw_import.py | .py | f5bea8a881319054 | 7.63 | 17 |
import os
import json
import shutil
import zipfile
import requests
import typing
from pygeoweaver.constants import *
from pygeoweaver.utils import (
download_geoweaver_jar,
copy_files,
get_spinner,
safe_exit,
)
from halo import Halo
def overwrite_files(source_dir, destination_dir):
"""
Overw... | ESIPFed/pygeoweaver | pygeoweaver/commands/pgw_sync.py | .py | b06bf655a2d9f4b4 | 7.63 | 17 |
"""Utility functions for handling configuration files in Geoweaver."""
import os
import logging
from configparser import ConfigParser
logger = logging.getLogger(__name__)
def read_properties_file(file_path):
"""
Read a Java-style properties file and return a dictionary of key-value pairs.
Args:
... | ESIPFed/pygeoweaver | pygeoweaver/config_utils.py | .py | efcb464475bff986 | 7.63 | 17 |
import logging
import os
import tempfile
def setup_logging(log_dir=None, force_new=False):
"""
Set up logging for pygeoweaver. If log_dir is not provided, use home directory (old behavior).
Args:
log_dir (str, optional): Directory to store log files. Defaults to home directory.
force_n... | ESIPFed/pygeoweaver | pygeoweaver/pgw_log_config.py | .py | ff09784e2c80b176 | 7.63 | 17 |
import os
import socket
import subprocess
import sys
import webbrowser
import time
from typing import Optional
import psutil
import requests
from halo import Halo
from pygeoweaver.constants import GEOWEAVER_DEFAULT_ENDPOINT_URL
from pygeoweaver.h2_utils import (
get_safe_datasource_url_for_start,
maintain_h2_... | ESIPFed/pygeoweaver | pygeoweaver/server.py | .py | 5138e7079ad37a91 | 7.63 | 17 |
import os
import sys
import shutil
import logging
import subprocess
import requests
import platform
from IPython import get_ipython
from halo import Halo
from pygeoweaver.constants import GEOWEAVER_URL
from pygeoweaver.pgw_log_config import get_logger
from pygeoweaver.pgw_spinner import Spinner
logger = get_logger(__... | ESIPFed/pygeoweaver | pygeoweaver/utils.py | .py | 9e022cc05620bca7 | 7.63 | 17 |
"""The explicit null sentinel used by request params.
Python has a single absence value, ``None``, but the Seam API distinguishes
an omitted param from a param explicitly set to null. For example, in an
update request, an omitted param leaves the current value unchanged,
while a null param unsets the current value.
S... | seamapi/python | seam/null.py | .py | 41bb8d2f4b647605 | 7.65 | 19 |
"""Mapping compatibility for generated nested resource dataclasses."""
from typing import Any, ClassVar, Iterator
class ResourceMapping:
"""Provide legacy dictionary-style reads for a nested resource object."""
def __getitem__(self, key: str) -> Any:
return getattr(self, key)
def get(self, key:... | seamapi/python | seam/resource_mapping.py | .py | c554175bbebc3ee6 | 7.65 | 19 |
from typing import Any, Dict, List, Literal, Optional, Union
from dataclasses import dataclass
from ..deep_attr_dict import DeepAttrDict
from ..resource_mapping import ResourceMapping
@dataclass
class AcsEncoder:
"""Represents a hardware device that encodes `credential <https://docs.seam.co/low-level-apis/access-... | seamapi/python | seam/resources/acs_encoder.py | .py | 3c41b41d3fc04265 | 7.65 | 19 |
from typing import Any, Dict, List, Literal, Optional, Union
from dataclasses import dataclass
from ..deep_attr_dict import DeepAttrDict
from ..resource_mapping import ResourceMapping
@dataclass
class Phone:
"""Represents an app user's mobile phone.
:ivar created_at: Date and time at which the phone was crea... | seamapi/python | seam/resources/phone.py | .py | cf1dc1b616cc9459 | 7.65 | 19 |
# delete_me_discord/api.py
import os
import time
import random
from datetime import datetime
from typing import Any, Dict, Generator, List, Optional, Tuple, Union
import logging
import requests
import urllib.parse
from .models import DiscordChannel, DiscordEmoji, DiscordMessage
from .type_enums import MessageType
from... | janthmueller/delete-me-discord | delete_me_discord/api.py | .py | 337ea5491620aae3 | 7.5 | 9 |
# delete_me_discord/discovery.py
from typing import Dict, Any, List
from rich.console import Console
from .api import DiscordAPI
from .scope_inventory import ScopeInventory
from .utils import should_include_channel
from .discovery_renderers import (
render_guilds_json,
render_guilds_rich,
render_channels_j... | janthmueller/delete-me-discord | delete_me_discord/discovery.py | .py | 190e6425ffbbe3a8 | 7.5 | 9 |
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Any, Optional, Tuple, TypedDict
class DiscordEmoji(TypedDict, total=False):
"""Subset of Discord's emoji payload used for reaction deletion."""
id: Optional[str]
name: Optional[str]
class Dis... | janthmueller/delete-me-discord | delete_me_discord/models.py | .py | ca9dfa2ff31c8357 | 7.5 | 9 |
# delete_me_discord/preserve_cache.py
import json
import logging
import os
from typing import Dict, List, Any
from .privacy import sensitive
DEFAULT_PRESERVE_CACHE_PATH = os.path.join(
os.path.expanduser("~"),
".config",
"delete-me-discord",
"preserve_cache.json",
)
class PreserveCache:
"""
... | janthmueller/delete-me-discord | delete_me_discord/preserve_cache.py | .py | 60ff1db5a859de6d | 7.5 | 9 |
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class RedactionConfig:
"""Runtime redaction configuration for log-facing sensitive values.
``redact_names`` controls human-readable Discord display names only:
usernames, guild names, category names, channel names, and ... | janthmueller/delete-me-discord | delete_me_discord/privacy.py | .py | e5264a9703245feb | 7.5 | 9 |
import logging
from enum import IntEnum
logger = logging.getLogger("MessageType")
# Added from https://docs.discord.food/resources/message
# https://discordhttp.alexflipnote.dev/api/enums.html#discord_http.enums.MessageType.custom_gift
class MessageType(IntEnum):
DEFAULT = 0, True
RECIPIENT_ADD = 1, False
... | janthmueller/delete-me-discord | delete_me_discord/type_enums.py | .py | 9eaae5e274384d11 | 7.5 | 9 |
# delete_me_discord/utils.py
import argparse
import json
import logging
import re
import sys
from datetime import datetime, timedelta, timezone
from typing import List, Dict, Any, Tuple, Set, Optional, Generator
from rich.console import Console
from rich.logging import RichHandler
from rich.padding import Padding
from... | janthmueller/delete-me-discord | delete_me_discord/utils.py | .py | 9b544f9c3f0df18c | 7.5 | 9 |
from abc import ABC, abstractmethod
from numpy import ndarray
from midas import Parameters, Fields, FieldRequest
class DiagnosticModel(ABC):
"""
An abstract base-class for diagnostic models.
"""
parameters: Parameters
fields: Fields
@abstractmethod
def predictions(self, **parameters_and_f... | C-bowman/midas | midas/models/diagnostics.py | .py | e4a6d80d20ec7a97 | 7.42 | 6 |
from dataclasses import dataclass
from numpy import ndarray
Coordinates = dict[str, ndarray]
@dataclass
class ParameterVector:
"""
A class used for specifying the parameters required to evaluate a
diagnostic model, field model or prior distribution.
:param name: \
The name of the parameter(s... | C-bowman/midas | midas/parameters.py | .py | 06b005ea9c37d1e8 | 7.42 | 6 |
from numpy import ndarray, atleast_1d, zeros
from midas.parameters import ParameterVector, FieldRequest
from midas.parameters import Parameters, Fields
from midas.state import BasePrior
class ExponentialPrior(BasePrior):
"""
Specify an exponential prior over either a series of field values, or a
set of pa... | C-bowman/midas | midas/priors/exponential.py | .py | 006640dbd16139e5 | 7.42 | 6 |
from numpy import array, diagonal, eye, log, ndarray, atleast_1d
from numpy.linalg import cholesky, LinAlgError
from scipy.linalg import solve_triangular
from warnings import warn
from inference.gp.covariance import CovarianceFunction, SquaredExponential
from inference.gp.mean import MeanFunction, ConstantMean
from mi... | C-bowman/midas | midas/priors/gp.py | .py | d57d34a410caa290 | 7.42 | 6 |
from numpy import ndarray, sqrt, arctan2
from scipy.interpolate import RectBivariateSpline
from abc import ABC, abstractmethod
from midas.parameters import Coordinates
class CoordinateTransform(ABC):
"""
An abstract base class for transformations between coordinate systems.
Subclasses declare the require... | C-bowman/midas | midas/transforms.py | .py | 2e43852f779e54db | 7.42 | 6 |
"""Save and load .midas session files (JSON format)."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import numpy as np
from midas_gui.session import GraphModel, NodeModel, Edge, NODE_TYPES
_VERSION = "1.0"
# Property keys that should not be serialized
_SKIP_PROPS ... | C-bowman/midas | midas_gui/session_io.py | .py | fbfc5281e68b576a | 7.42 | 6 |
from __future__ import annotations
from PySide6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QPlainTextEdit,
QPushButton, QCheckBox, QFileDialog, QLabel,
)
from PySide6.QtCore import Qt
from PySide6.QtGui import QFont, QColor, QSyntaxHighlighter, QTextCharFormat
from midas_gui.session import GraphMod... | C-bowman/midas | midas_gui/widgets/code_preview.py | .py | fd344e42a6b8cd10 | 7.42 | 6 |
"""
Quantum ML Feature Processing Script
Reads the 9 normalized Iceberg tables produced by quantum_incremental_processing.py
and joins them into two ML-ready feature tables:
- ml_iteration_features (one row per iteration per experiment)
- ml_run_summary (one row per VQE run, aggregated from iterations)
... | straightchlorine/quantum-pipeline | docker/airflow/scripts/quantum_ml_feature_processing.py | .py | e126086eb7a1c2fe | 7.54 | 11 |
"""
initial_states.py
Hartree-Fock initial state preparation for VQE ansatz.
Provides a HartreeFock circuit (from qiskit-nature) to be used as the
initial_state parameter of EfficientSU2. This correctly encodes the HF
ground state under the given qubit mapping with blocked spin-orbital ordering.
"""
from __future__ ... | straightchlorine/quantum-pipeline | quantum_pipeline/circuits/initial_states.py | .py | fba3025867019ad3 | 7.54 | 11 |
from collections.abc import Callable
from dataclasses import asdict, dataclass
from typing import Any
from qiskit_ibm_runtime import IBMBackend
from quantum_pipeline.configs.defaults import DEFAULTS
@dataclass
class BackendConfig:
"""Dataclass for storing backend filter."""
local: bool | None
gpu: bool... | straightchlorine/quantum-pipeline | quantum_pipeline/configs/module/backend.py | .py | 9b7605251f954991 | 7.54 | 11 |
from dataclasses import asdict, dataclass
from typing import Any
from quantum_pipeline.configs.defaults import DEFAULTS
from quantum_pipeline.configs.module.security import SecurityConfig
@dataclass
class ProducerConfig:
"""Configuration for Kafka Producer object"""
servers: str
topic: str
security:... | straightchlorine/quantum-pipeline | quantum_pipeline/configs/module/producer.py | .py | fc836f42f101a73e | 7.54 | 11 |
import argparse
import json
from copy import deepcopy
from datetime import datetime
from pathlib import Path
from typing import Any
from quantum_pipeline.configs import settings
from quantum_pipeline.configs.defaults import DEFAULTS
from quantum_pipeline.configs.module.backend import BackendConfig
from quantum_pipelin... | straightchlorine/quantum-pipeline | quantum_pipeline/configs/parsing/configuration_manager.py | .py | 22e2712b47316934 | 7.54 | 11 |
"""
molecule_loader.py
This module contains utilities to load and validate molecular information
used in quantum simulations.
"""
import json
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
from qiskit_nature.units import DistanceUnit
def validate_molecule_data(data: list):
"""Validate da... | straightchlorine/quantum-pipeline | quantum_pipeline/drivers/molecule_loader.py | .py | 24c87c3e22196829 | 7.54 | 11 |
from collections import Counter
from qiskit import QuantumCircuit
class CircuitFeatures:
@staticmethod
def extract_features(circuit: QuantumCircuit):
"""
Extract features from a quantum circuit, including depth, gate counts,
and entanglement.
Args:
circuit (Quantu... | straightchlorine/quantum-pipeline | quantum_pipeline/features/circuit.py | .py | e9424ec2226d3b16 | 7.54 | 11 |
"""
jordan_wigner_mapper.py
This module defines a class for mapping fermionic operators to qubit operators
using the Jordan-Wigner transformation. This transformation is used to represent
fermionic systems on quantum computers.
"""
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.second_q.mappers impo... | straightchlorine/quantum-pipeline | quantum_pipeline/mappers/jordan_winger_mapper.py | .py | 898b6c95eeb1a267 | 7.54 | 11 |
from abc import ABC, abstractmethod
class Mapper(ABC):
"""Base class for operator mappers."""
@abstractmethod
def map(self, operator):
"""Map a fermionic operator to qubit operator."""
...
@abstractmethod
def get_qiskit_mapper(self):
"""Return the underlying Qiskit mapper... | straightchlorine/quantum-pipeline | quantum_pipeline/mappers/mapper.py | .py | a359376e58fbf6d3 | 7.04 | 11 |
import os
from pathlib import Path
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
from reportlab.lib import colors
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import cm
from reportlab.platypus import Paragraph, Spacer, Table, TableStyle
from qua... | straightchlorine/quantum-pipeline | quantum_pipeline/report/content_builder.py | .py | d6fca512a04482aa | 7.54 | 11 |
"""
report_generator.py
Generates PDF reports with improved modularity and flexibility.
"""
from pathlib import Path
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
from quantum_pipeline.configs import settings
from quantum_pipeline.report.configuration import ReportConfiguration
from quantum_... | straightchlorine/quantum-pipeline | quantum_pipeline/report/report_generator.py | .py | f47be8eb99e3e881 | 7.54 | 11 |
from abc import ABC, abstractmethod
from quantum_pipeline.utils.logger import get_logger
class Runner(ABC):
def __init__(self):
self.logger = get_logger(self.__class__.__name__)
@abstractmethod
def run(self):
"""Execute the quantum algorithm. Subclasses must implement this."""
..... | straightchlorine/quantum-pipeline | quantum_pipeline/runners/runner.py | .py | 06e28721c94baf5b | 7.04 | 11 |
"""
optimizer_config.py
This module provides a factory for creating optimizer-specific configurations
for scipy.optimize.minimize. It handles the proper parameter mapping and
validation for different optimizers used in VQE optimization.
"""
import logging
from abc import ABC, abstractmethod
from typing import Any, Cl... | straightchlorine/quantum-pipeline | quantum_pipeline/solvers/optimizer_config.py | .py | 4ee27a6a6cf70545 | 7.54 | 11 |
from time import sleep
from kafka import KafkaProducer
from kafka.errors import KafkaError, NoBrokersAvailable
from quantum_pipeline.configs.module.producer import ProducerConfig
from quantum_pipeline.stream.kafka_security import KafkaSecurity
from quantum_pipeline.stream.serialization.interfaces.vqe import (
VQE... | straightchlorine/quantum-pipeline | quantum_pipeline/stream/kafka_interface.py | .py | 53daa140db9924f0 | 7.54 | 11 |
from pathlib import Path
from typing import Any
from quantum_pipeline.configs.module.producer import ProducerConfig
class KafkaSecurity:
def __init__(self, config: ProducerConfig):
"""Initialize the Kafka security configuration.
Args:
config: Configuration for the Kafka connection.
... | straightchlorine/quantum-pipeline | quantum_pipeline/stream/kafka_security.py | .py | 302e9cddaa1ef6d4 | 7.54 | 11 |
"""Config flow for Ring Keypad integration."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
import voluptuous as vol
from homeassistant.const import CONF_DEVICE_ID
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers import selector
from ... | allenporter/home-assistant-ring-keypad | custom_components/ring_keypad/config_flow.py | .py | 1a4ec163c248f6f0 | 7.5 | 9 |
"""Event entity platform for Ring Keypad."""
import logging
from typing import Any
from homeassistant.components.event import EventDeviceClass, EventEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE_ID
from homeassistant.core import Event, HomeAssistant, callback
... | allenporter/home-assistant-ring-keypad | custom_components/ring_keypad/event.py | .py | aff6c8c43b8a788b | 7.5 | 9 |
"""Data model related to the Ring Keypad.
The details for the events and commands are described here:
https://github.com/ImSorryButWho/HomeAssistantNotes/blob/main/RingKeypadV2.md
"""
import enum
from homeassistant.components.alarm_control_panel import AlarmControlPanelState
from .const import DEFAULT_DELAY
EVENT_... | allenporter/home-assistant-ring-keypad | custom_components/ring_keypad/model.py | .py | 41f2edf9da285e83 | 7.5 | 9 |
"""Fixtures for the custom component."""
import logging
from collections.abc import AsyncGenerator, Generator
from unittest.mock import patch
import pytest
from homeassistant.const import CONF_DEVICE_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from... | allenporter/home-assistant-ring-keypad | tests/conftest.py | .py | 1d3577b1ce51a01a | 8 | 9 |
"""Tests for a Ring Keypad blueprint."""
import logging
import pathlib
from collections.abc import Mapping
from typing import Any
from unittest.mock import patch
import pytest
import yaml
from homeassistant.core import Event, HomeAssistant
from homeassistant.setup import async_setup_component
from pytest_homeassistan... | allenporter/home-assistant-ring-keypad | tests/test_blueprint.py | .py | e2e98ebbbe2aba1f | 7 | 9 |
"""Tests for the Ring Keypad component."""
import attr
import pytest
from homeassistant import config_entries
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from pytest_homeassistant_custom_component.common import (
MockConfigEntry,
async_mock_service,
)
f... | allenporter/home-assistant-ring-keypad | tests/test_init.py | .py | 61cb6dd85bea8f97 | 7 | 9 |
"""
test_code_execution.py
======================
A comprehensive example demonstrating how to use LollmsDiscussion to allow an LLM
to build, execute, and interpret the output of a Python script.
This script relies on a .env file for configuration.
Copy 'test_code_execution.env.example' to '.env' and modify the valu... | ParisNeo/lollms_client | examples/test_code_execution.py | .py | 8f7f6a778ca15262 | 8.07 | 13 |
"""
Diagnostic Example: Sovereign Tool Seeding Verification
This script verifies that a LollmsPersonality only seeds context-relevant tools
(data tools, document tools) based on the workspace contents and the `enable_data_tools`
flag, strictly excluding irrelevant tools (system_shell, execute_python_code, etc.).
It u... | ParisNeo/lollms_client | lollms_client/examples/test_tool_seeding.py | .py | fe3230e34aee287b | 8.07 | 13 |
"""
gui_prefs.py — lollms_code-GUI-specific preferences (agent behavior, paths,
appearance). NOT the LLM/TTI/TTS/etc. connection config — that's owned by
env_config.py and lives in ~/.lollms-client/.env, matching the real wizard
(lollms_config_cli_env.py) so the CLI and GUI share one source of truth.
"""
from __future_... | ParisNeo/lollms_client | src/lollms_client/apps/lollms_code/gui/gui_prefs.py | .py | cee03461d21faa47 | 7.57 | 13 |
#!/usr/bin/env python3
"""
lollms_code GUI — NiceGUI native-window front end for the lollms_code agent.
Run:
pip install nicegui pywebview
python main.py
Packaging into a standalone executable, once this works against your real
lollms_client install:
pip install pyinstaller
pyinstaller --onefile --win... | ParisNeo/lollms_client | src/lollms_client/apps/lollms_code/gui/main.py | .py | 5cc735fb62667d00 | 7.57 | 13 |
import base64
import os
from io import BytesIO
from pathlib import Path
from typing import Optional, Callable, List, Union, Dict
from lollms_client.lollms_discussion import LollmsDiscussion, LollmsMessage
from lollms_client.lollms_llm_binding import LollmsLLMBinding
from lollms_client.lollms_types import MSG_TYPE
from... | ParisNeo/lollms_client | src/lollms_client/llm_bindings/groq/__init__.py | .py | c9f701e7d87d4984 | 7.57 | 13 |
import os
from typing import Optional, Callable, List, Union, Dict
from lollms_client.lollms_discussion import LollmsDiscussion, LollmsMessage
from lollms_client.lollms_llm_binding import LollmsLLMBinding
from lollms_client.lollms_types import MSG_TYPE
from ascii_colors import ASCIIColors, trace_exception
import pipm... | ParisNeo/lollms_client | src/lollms_client/llm_bindings/hugging_face_inference_api/__init__.py | .py | 2802c58b4fd92af7 | 7.57 | 13 |
import json
import os
import traceback
import util
from util import logger
from v2ex import V2ex
def generateArchiveMd(items):
"""生成归档readme
"""
def topic(item):
title = item['title']
url = item['url']
return '1. [{}]({})'.format(title, url)
topicMd = '暂无数据'
if items:
... | cxyfreedom/v2ex-hot-hub | main.py | .py | f13d4da7d208a4c8 | 7.42 | 6 |
import numpy as np
from keras import ops
def qwen_vl_input(
batch_size=2, grid=(1, 4, 4), patch_dim=1176, image_token_id=4, merge=2
):
"""Multimodal input for the Qwen-VL models: pre-patchified image patches +
input_ids with the right number of image-placeholder tokens per row."""
t, gh, gw = grid
... | IMvision12/ZeroModels | tests/fixtures/dummy_inputs.py | .py | f112783ab26d8d4c | 7.1 | 15 |
"""Golden-file (snapshot) helpers for the processor suites.
A snapshot pins what a component *currently* produces for a fixed input, so an
unintended change to preprocessing shows up as a diff instead of silently
altering everyone's pixels or token ids. This complements the vs-HF parity
tests: parity says "we match th... | IMvision12/ZeroModels | tests/fixtures/snapshot_util.py | .py | cc53674dbaeb6422 | 8.1 | 15 |
import json
import keras
import numpy as np
import pytest
from keras import layers, ops
from zeromodels.base import BaseModel
from zeromodels.conversion import converted_cache
from zeromodels.conversion.hf_download_utils import LazyStateDict
@keras.saving.register_keras_serializable(package="zeromodels_tests")
clas... | IMvision12/ZeroModels | tests/integration/test_loading_optimizations.py | .py | 55b5a4717d546ebc | 8.1 | 15 |
"""Make the repo-root ``assets/`` directory part of the MkDocs build.
The model pages carry their figures and audio as raw HTML pointing at
``../assets/...``, but that directory lives next to ``docs/`` rather than inside
it, so MkDocs has no idea it exists and every image and audio player 404s.
Registering the files ... | IMvision12/ZeroModels | website/hooks/copy_assets.py | .py | d7490536e0a8748b | 7.6 | 15 |
import keras
from keras import ops
VALID_ATTN_IMPL = ("sdpa", "flash")
ATTN_IMPLEMENTATION = "sdpa"
def _fused_op_available():
backend = keras.config.backend()
if backend == "jax":
try:
from jax.nn import dot_product_attention # noqa: F401
return True
except ImportEr... | IMvision12/ZeroModels | zeromodels/base/base_attention.py | .py | d2298e8523dd269f | 7.6 | 15 |
import inspect
from collections import OrderedDict
import keras
import numpy as np
from keras import ops
from zeromodels.base.base_mixin import inference_scope
from zeromodels.samplers import GreedySampler
class BaseGeneration:
"""Backend-agnostic autoregressive generation for decoder-only LMs (mirrors HF's ``G... | IMvision12/ZeroModels | zeromodels/base/base_generation.py | .py | 021a9e31b9d38ae7 | 7.6 | 15 |
import keras
from keras import layers, ops
MASK_NEG = -1e9
@keras.saving.register_keras_serializable(package="zeromodels")
class CausalMask(layers.Layer):
"""Additive causal (+ padding, + optional sliding-window) attention mask.
Produces ``(batch, 1, seq, seq)`` holding ``0`` where a query may attend and
... | IMvision12/ZeroModels | zeromodels/base/base_generation_layers.py | .py | faafba363b8ea517 | 7.6 | 15 |
import keras
from zeromodels.base.base_config import BaseConfig
from zeromodels.base.base_mixin import WeightLoadingMixin
_KerasModelMeta = type(keras.Model)
class _ConfigModelMeta(_KerasModelMeta):
"""Metaclass giving config-carrying models the transformers ``Model(config)`` API.
Transforms a :class:`Base... | IMvision12/ZeroModels | zeromodels/base/base_model.py | .py | fd652789cdd641ce | 7.6 | 15 |
import keras
from zeromodels.base.base_mixin import PreprocessorMixin
class BaseProcessor(PreprocessorMixin):
"""Base class for zeromodels multi-modal processors.
A processor **composes** (has-a) a :class:`BaseTokenizer` and a
:class:`BaseImageProcessor` / :class:`BaseAudioFeatureExtractor`; it is not a... | IMvision12/ZeroModels | zeromodels/base/base_processor.py | .py | 63231531196182bb | 7.6 | 15 |
def normalize_axes(axis, ndim):
"""Normalize an int or tuple ``axis`` to a sorted tuple of positive axes."""
if isinstance(axis, int):
axis = (axis,)
return tuple(sorted(a % ndim for a in axis))
def single_axis(axis, ndim):
"""Resolve ``axis`` to one positive axis; error if it names more than ... | IMvision12/ZeroModels | zeromodels/base/base_quantization.py | .py | 7e64c415dfeef294 | 7.6 | 15 |
import os
import numpy as np
from keras import ops
from zeromodels.base.base_mixin import PreprocessorMixin
class BaseTokenizer(PreprocessorMixin):
"""Abstract base for zeromodels tokenizers.
Subclasses implement ``call`` (text -> ids) and ``decode`` (ids -> text);
``batch_decode`` is a pure-Python loo... | IMvision12/ZeroModels | zeromodels/base/base_tokenizer.py | .py | aae51b471f7d9f9b | 7.6 | 15 |
import hashlib
import json
import os
import re
import warnings
import keras
import numpy as np
from zeromodels.conversion.hf_download_utils import LazyStateDict
# Cache files are intentionally much smaller than the maximum safetensors shard
# size. ``save_file`` needs one complete shard in memory, so a 5 GB shard w... | IMvision12/ZeroModels | zeromodels/conversion/converted_cache.py | .py | 29aba2bde1151deb | 7.6 | 15 |
class WeightTransferError(Exception):
"""Base exception class for weight transfer errors."""
pass
class WeightMappingError(WeightTransferError):
"""
Exception raised when a corresponding torch weight cannot be found for a given Keras weight.
This error typically occurs during weight transfer bet... | IMvision12/ZeroModels | zeromodels/conversion/exceptions.py | .py | 7beb6613b41c522f | 7.6 | 15 |
import hashlib
import json
import os
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
def validate_url(url: str) -> bool:
"""Validate if the provided URL is well-formed.
Args:
url: URL string to validate
Returns:
bool: True if URL is valid, False oth... | IMvision12/ZeroModels | zeromodels/conversion/file_downloader.py | .py | 3cb95735e24f4e86 | 7.6 | 15 |
"""Self-describing Hub repos: zm_config.json (model) and zm_preprocessor.json.
Each zeromodels weight repo can carry two small namespaced json files at its
root, next to model.weights.h5:
zm_config.json the model: class + flat hyperparameters + weights filename.
zm_preprocessor.json the image processor / ... | IMvision12/ZeroModels | zeromodels/conversion/zm_config.py | .py | 971c4f837c6fb7a8 | 7.6 | 15 |
import numpy as np
import matplotlib
matplotlib.use('TkAgg') # Use TkAgg backend for better display
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
from scipy.linalg import eigh
import sys
import os
# Add ... | microprediction/randomcov | create_geodesic_video_simple.py | .py | 213ad81aae13d662 | 7.5 | 9 |
from sklearn.covariance import LedoitWolf, MinCovDet
import numpy as np
import warnings
from collections import defaultdict
from randomcov.randomcovariancematrix import random_covariance_matrix
from randomcov.covutil.geodesicinterpolation import geodesic_interpolation_towards_perfect
from randomcov.covutil.nearestposd... | microprediction/randomcov | randomcov/benchmarkingutil/minvarleaderboard.py | .py | a8d6f4a2e4ac44f2 | 7.5 | 9 |
import numpy as np
def lkj_corr(n, eta=1.0, rng=None):
"""
Generates a random correlation matrix using the LKJ prior.
https://en.wikipedia.org/wiki/Lewandowski-Kurowicka-Joe_distribution
Args:
n (int): Dimension of the correlation matrix.
eta (float): Shape parameter controlling the c... | microprediction/randomcov | randomcov/corrgens/lkj.py | .py | 668f31384b4c627c | 7.5 | 9 |
import numpy as np
from scipy.linalg import sqrtm, inv, fractional_matrix_power
from randomcov.covutil.nearestposdef import nearest_positive_def
from scipy.linalg import eigh
def geodesic_interpolation(start_cov, end_cov, gamma):
"""
Interpolate between two SPD matrices along the geodesic under the affine-inv... | microprediction/randomcov | randomcov/covutil/geodesicinterpolation.py | .py | 18e024ede6fa3a50 | 7.5 | 9 |
from statsmodels.stats.correlation_tools import cov_nearest
import numpy as np
def remove_negative_eigenvalues(cov_matrix, eps=1e-6):
"""
Adjusts a covariance matrix to make it positive definite by removing negative eigenvalues.
Parameters:
- cov_matrix: The original covariance matrix (must be squar... | microprediction/randomcov | randomcov/covutil/nearestposdef.py | .py | cc97bff2c737d37a | 7.5 | 9 |
"""Mid-size 6-layer GPT-style decoder for causal LM, ~35M params. Balanced speed/quality for moderate datasets."""
import torch
import torch.nn as nn
framework = "pytorch"
main_class = "MediumCausalLM"
category = "causal_language_modeling"
model_type = ""
batch_size = 32
sequence_length = 256
vocab_size = 30522
licens... | tracebloc/model-zoo | model_zoo/causal_language_modeling/pytorch/medium_causal_lm.py | .py | 0bc2feff34ca0b9a | 7.48 | 8 |
"""GPT-2-small-scale decoder for causal LM, ~109M params. Train from scratch on domain corpora (next-token pretraining)."""
import torch
import torch.nn as nn
framework = "pytorch"
main_class = "NanoGPTScratch"
category = "causal_language_modeling"
model_type = ""
batch_size = 16
sequence_length = 256
vocab_size = 305... | tracebloc/model-zoo | model_zoo/causal_language_modeling/pytorch/nanogpt_style_scratch.py | .py | 8a64bc3347313342 | 7.48 | 8 |
"""Minimal GPT-style decoder for causal LM, ~19M params. Smoke-test model for quick iteration and pipeline validation."""
import torch
import torch.nn as nn
framework = "pytorch"
main_class = "SimpleCausalLM"
category = "causal_language_modeling"
model_type = ""
batch_size = 32
sequence_length = 128
vocab_size = 30522... | tracebloc/model-zoo | model_zoo/causal_language_modeling/pytorch/simple_causal_lm.py | .py | 582d04ee83301d4c | 7.48 | 8 |
"""Minimal transformer text encoder for contrastive embeddings, ~10M params. From-scratch model for smoke-training the embeddings pipeline."""
import torch
import torch.nn as nn
from transformers.modeling_outputs import BaseModelOutput
framework = "pytorch"
main_class = "SimpleTextEncoder"
category = "embeddings"
mode... | tracebloc/model-zoo | model_zoo/embeddings/pytorch/simple_text_encoder.py | .py | e2cdd225745ee0e3 | 7.48 | 8 |
"""AIMv2 (Apple, Nov 2024). Autoregressive image pretraining with multimodal targets; strong DINOv3 alternative on classification + retrieval. Backbone frozen → federated averaging only syncs the head.
Offline variant: the architecture is built from the inlined config below —
no hub model id, no config fetch, no downl... | tracebloc/model-zoo | model_zoo/image_classification/pytorch/aimv2.py | .py | a07887e01e93bcfb | 7.48 | 8 |
"""DINOv3 backbone (Meta, Aug 2025) with a trainable linear head. Self-supervised ViT trained on 1.7B images; backbone is frozen so federated averaging only sees the small head — BN-free by construction.
Offline variant: the architecture is built from the inlined config below —
no hub model id, no config fetch, no dow... | tracebloc/model-zoo | model_zoo/image_classification/pytorch/dinov3.py | .py | 319295d4d6ce5f9f | 7.48 | 8 |
"""Hiera (Meta, ICML 2023). Hierarchical ViT that strips per-stage tricks (relative position, conv stem, etc.) while matching Swin/MViTv2 accuracy. Simpler architecture, MAE-pretrained, available via transformers.
Offline variant: the architecture is built from the inlined config below —
no hub model id, no config fet... | tracebloc/model-zoo | model_zoo/image_classification/pytorch/hiera.py | .py | d25364ca62988c5c | 7.48 | 8 |
"""SigLIP 2 (Google, Feb 2025). Sigmoid-loss vision-language pretraining successor to SigLIP; now the default frozen backbone for many 2025 multimodal stacks. Backbone frozen → federated averaging only syncs the linear head.
Offline variant: the architecture is built from the inlined config below —
no hub model id, no... | tracebloc/model-zoo | model_zoo/image_classification/pytorch/siglip2.py | .py | a3bed8578e669a73 | 7.48 | 8 |
"""ViT-B/16 backbone from HuggingFace transformers + custom classification head. Pick when you want to swap the head or extract features.
Offline variant: the architecture is built from the inlined config below —
no hub model id, no config fetch, no download at build time, so the template
constructs anywhere, network ... | tracebloc/model-zoo | model_zoo/image_classification/pytorch/vit.py | .py | 027ce7b5123a940e | 7.48 | 8 |
"""ViT-B/16 via HuggingFace ViTForImageClassification, google/vit-base-patch16-224 weights. Pretrained classifier; fine-tune the head for your classes.
Offline variant: the architecture is built from the inlined config below —
no hub model id, no config fetch, no download at build time, so the template
constructs anyw... | tracebloc/model-zoo | model_zoo/image_classification/pytorch/vit_google.py | .py | 5545a2c17b0081a5 | 7.48 | 8 |
"""Cascaded Pyramid Network (direct regression) on a ResNet-50 backbone. Two-stage refinement improves hard-keypoint accuracy.
Offline variant: built with ``weights=None`` — no checkpoint download at
construction, so the template constructs anywhere, network or not. A plain
classification ResNet builds the identical a... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/cpn.py | .py | bafd08e8ef02c6a3 | 7.48 | 8 |
"""Cascaded Pyramid Network, heatmap-based output. Usually the stronger CPN variant.
Offline variant: built with ``weights=None`` — no checkpoint download at
construction, so the template constructs anywhere, network or not. A plain
classification ResNet builds the identical architecture (same state_dict
keys and shap... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/cpn_heatmap.py | .py | 8d8cdab43701c8b9 | 7.48 | 8 |
"""DeepPose (Toshev & Szegedy, 2014). Direct coordinate regression; historical baseline for deep pose estimation."""
import torch
import torch.nn as nn
import torch.nn.functional as F
# Configuration
framework = "pytorch"
model_type = ""
main_class = "DeepPoseModel"
image_size = 64
batch_size = 128
output_classes = 1
... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/deeppose.py | .py | 37c5cc70d07f21ec | 7.48 | 8 |
"""Differentiable Spatial-to-Numerical Transform. End-to-end coordinate regression with heatmap inductive bias."""
import torch
import torch.nn as nn
import torch.nn.functional as F
# Configuration
framework = "pytorch"
model_type = ""
main_class = "KeypointDetectionModel"
image_size = 64
batch_size = 128
output_clas... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/dsnt.py | .py | 3aadb0e779fd7d62 | 7.48 | 8 |
"""Single-Person Pose Estimator on a Faster R-CNN ResNet-50 backbone. Reuses a strong detection backbone for keypoints.
Offline variant: the architecture is built without any checkpoint download,
so the template constructs anywhere, network or not. The pretrained backbone
tensors are delivered from the tracebloc model... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/faster_rcnn_sppe.py | .py | a0efa955129bb022 | 7.48 | 8 |
"""High-Resolution Network (direct regression). Maintains high-res representations throughout; state-of-the-art keypoint accuracy."""
import torch
import torch.nn as nn
# Configuration
framework = "pytorch"
model_type = ""
main_class = "HRNetKeypointDetection"
image_size = 64
batch_size = 128
output_classes = 1
catego... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/hrnet.py | .py | a291e7d0753200cd | 7.48 | 8 |
"""HRNet with heatmap output. Usually the strongest choice in this directory."""
import torch
import torch.nn as nn
# Configuration
framework = "pytorch"
model_type = "heatmap"
main_class = "HRNetKeypointDetection"
image_size = 64
batch_size = 128
output_classes = 1
category = "keypoint_detection"
num_feature_points =... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/hrnet_heatmap.py | .py | e02562bbfbb8bd1a | 7.48 | 8 |
"""OpenPose-style multi-stage CNN for keypoint detection. Well-known architecture; moderate accuracy, interpretable outputs."""
import torch
import torch.nn as nn
framework = "pytorch"
model_type = ""
main_class = "OpenPoseKeypointDetector"
image_size = 64
batch_size = 128
output_classes = 1
category = "keypoint_detec... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/openpose.py | .py | dcee3cacde324bc7 | 7.48 | 8 |
"""SimpleBaseline keypoint detector on a ResNet-50 backbone. Minimal architecture; good starting point.
Offline variant: built with ``weights=None`` — no checkpoint download at
construction, so the template constructs anywhere, network or not. A plain
classification ResNet builds the identical architecture (same state... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/resnet_50.py | .py | 8664afb77e414093 | 7.48 | 8 |
"""Single-Person Pose Estimator on a ResNet-50 backbone. Simpler than FasterRCNNSPPE; good default when you don't need detection.
Offline variant: built with ``weights=None`` — no checkpoint download at
construction, so the template constructs anywhere, network or not. A plain
classification ResNet builds the identica... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/resnet_sppe.py | .py | eba54b564870d983 | 7.48 | 8 |
"""RTMPose (OpenMMLab, 2023). Production-grade real-time pose with SimCC (coordinate classification) head; widely deployed in industry. CSPNeXt backbone uses GroupNorm-style normalization where possible — federated-friendly compared to BN-heavy alternatives."""
import torch
import torch.nn as nn
import torch.nn.functio... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/rtmpose.py | .py | 129c1a7017771fb4 | 7.48 | 8 |
"""Sapiens (Meta, ECCV 2024). Human-centric foundation model — pose, depth,
normals, segmentation in one family.
Backbone note
-------------
The official ``facebook/sapiens-pose-*`` Hub repos ship as TorchScript
artifacts (not loadable as HF transformers models), and the MAE-pretrained
``facebook/sapiens-pretrain-0.3b... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/sapiens.py | .py | 5e0e6cc1b0b56a9c | 7.48 | 8 |
"""ViTPose (NeurIPS 2022). First transformer pose model in the zoo — ViT backbone + simple decoder; 81+ AP COCO whole-body at Huge scale, fine-tunes well at Base.
Offline variant: the architecture is built from the inlined config below
(ViTPose backbone sub-config included) — no hub model id, no config fetch,
no downl... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/vitpose.py | .py | 1c4366f8856ea9c6 | 7.48 | 8 |
"""ViTPose++ (NeurIPS 2023). MoE-style task-shared / task-specific experts on top of ViTPose; current top of the COCO whole-body leaderboard at Huge scale. Base variant is the practical fine-tune default.
Offline variant: the architecture is built from the inlined config below
(ViTPose backbone sub-config with 6 exper... | tracebloc/model-zoo | model_zoo/keypoint_detection/pytorch/vitpose_plus.py | .py | 80f63edf4e956eec | 7.48 | 8 |
"""Convolutional encoder for MLM, ~25M params. No attention — pure CNN baseline for fast training."""
import torch
import torch.nn as nn
framework = "pytorch"
main_class = "ConvMLM"
category = "masked_language_modeling"
model_type = ""
batch_size = 64
sequence_length = 128
vocab_size = 30522
class ConvMLM(nn.Module)... | tracebloc/model-zoo | model_zoo/masked_language_modeling/pytorch/conv_mlm.py | .py | bb9780413b592246 | 7.48 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.