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 |
|---|---|---|---|---|---|---|
import collections
import csv
import datetime
import random
import time
from django.core.management.base import BaseCommand
from randomizer.data.bosses import StarLocation
from randomizer.data.keys import get_default_key_item_locations
from randomizer.data.items import Item
from randomizer.logic.flags import CATEGORI... | Super-Mario-RPG-Randomizer/smrpg_web_randomizer | randomizer/management/commands/generatesample.py | .py | 2f6301a28d76e0ab | 7.63 | 17 |
#!/usr/bin/env python3
"""Download a pinned Lexxy bundle (JS + CSS) and save it to the
vendored JS/CSS directories shipped with newly-created Proper apps.
Run when bumping the pinned version:
```bash
uv run python bin/vendor-lexxy.py
# or
make vendor-lexxy
```
The JS output is the *bundled* ESM build from esm.sh - a... | jpsca/proper | bin/vendor-lexxy.py | .py | 0f510c2057980a01 | 7.48 | 8 |
from proper.emails import EmailMessage
from ..tasks import send_email_task
class BaseEmail(EmailMessage):
def send_later(self, *, via=None, **options):
"""Queue the email to be sent by a worker.
Pass `via` to route the message through a specific mailer from
`MAILERS` (by name). Defaults ... | jpsca/proper | blueprint/[[app_name]]/emails/base_email.py | .py | d4816f770887b12f | 7.48 | 8 |
import peewee as pw
from ..base import BaseModel
class RussianDollCached(BaseModel):
"""A Rails-like russian doll caching mechanism for Peewee models.
When a model declares `touches`, saving or deleting an instance
automatically bumps the `updated_at` of related parent records.
This invalidates the ... | jpsca/proper | blueprint/[[app_name]]/models/concerns/russian_doll_cached.py | .py | cea702a292590e73 | 7.48 | 8 |
import os
import pandas as pd
import numpy as np
from loguru import logger
import fangraphs
# Edit these two lines once a year. They are named rather than inlined so the
# error messages below can tell you which season a failed fetch was for.
CURRENT_SEASON = 2026
PRIOR_SEASON = 2025
PLAYER_ID_MAP_FILE = "SFBB Play... | JamesYouL2/FantasyBaseball | createrankings.py | .py | 05ea8c913a41b513 | 7.42 | 6 |
# -*- coding: utf-8 -*-
"""The Yahoo session every run uses. Never prompts, never opens a browser.
Authorization is a one-time event and lives in auth.py. This module only
spends what auth.py produced: it trades the refresh token for an access token
whenever the current one is close to expiring, and hands back an ordi... | JamesYouL2/FantasyBaseball | league_authorization.py | .py | 35f6b363ee76ed2e | 7.42 | 6 |
#!/usr/bin/env python3
"""Strip outputs and machine-specific metadata from Jupyter notebooks.
Used two ways:
git clean filter cat notebook.ipynb | python3 scripts/nbstrip.py
manual cleanup python3 scripts/nbstrip.py --inplace draft/draft.ipynb
Notebook outputs are the easiest way to leak something from thi... | JamesYouL2/FantasyBaseball | scripts/nbstrip.py | .py | 91d7aa9e0fdd6b92 | 7.42 | 6 |
import os
import asyncio
import pytest
import aiohttp
from smarttub import SmartTub, Spa
pytestmark = pytest.mark.integration
USERNAME = os.environ.get("SMARTTUB_USER")
PASSWORD = os.environ.get("SMARTTUB_PASS")
SPA_INDEX = int(os.environ.get("SMARTTUB_SPA_INDEX", "0"))
POLL_INTERVAL = 2
TIMEOUT = 60
@pytest.mark.a... | mdz/python-smarttub | tests/integration/test_real_api.py | .py | cb7070a65240dbd8 | 7.06 | 12 |
import pytest
from smarttub import SpaReminder
pytestmark = pytest.mark.asyncio
@pytest.fixture
def reminders(mock_spa):
reminders = [
SpaReminder(
mock_spa,
**{
"id": "WATER",
"lastUpdated": "2021-03-04T08:00:45.330Z",
"name": "Ref... | mdz/python-smarttub | tests/test_reminder.py | .py | f5951458326c7ea7 | 7.06 | 12 |
from dataclasses import dataclass
from typing import Optional
from git import Commit
from github.Issue import Issue
@dataclass
class Cherry:
commit: Optional[Commit]
pr: Issue
is_applied: bool
@dataclass
class CommitSummary:
"""
This dataclass is needed to speed up processing
"""
pr_num... | apache-superset/cherrytree | cherrytree/classes.py | .py | d2c0653e4282d0da | 7.09 | 14 |
import os
import re
from collections import OrderedDict
from typing import Generator, List, Optional, Reversible
import delegator
from git import Commit
from git.exc import InvalidGitRepositoryError
from git.repo import Repo
from github import Github
from github.Label import Label
from github.Issue import Issue
from g... | apache-superset/cherrytree | cherrytree/github_utils.py | .py | 4bdad73e3f8d0027 | 7.59 | 14 |
import logging
from contextlib import suppress
from datetime import timezone, datetime
from enum import Enum
from itertools import chain
from pathlib import Path
import rich_click as click
from pydantic import BaseModel
from rich.prompt import Confirm
from .console.default import console
from .console.output import p... | iago1460/cataloguer | cataloguer/cli.py | .py | 103e5e5ee6cf8b8a | 7.5 | 9 |
import json
import logging
import os
from contextlib import suppress
from datetime import datetime, timezone
from itertools import chain
from pathlib import Path
from typing import List, Dict, Optional
from rich.progress import (
Progress,
TextColumn,
BarColumn,
TaskProgressColumn,
MofNCompleteColu... | iago1460/cataloguer | cataloguer/filesystem/directory.py | .py | 1f1089abc1153ffe | 7.5 | 9 |
#!/usr/bin/env python3
import os
from functools import partial
import geopandas as gp
import pandas as pd
import polars as pl
import quackosm as qosm
from shapely.ops import transform
WGS84 = "EPSG:4326"
# CRS = "EPSG:4087"
CRS = "EPSG:27700"
OUTPATH = "output/ine-rail.gpkg"
pd.set_option("display.max_columns", No... | anisotropi4/magpie | quackosmget.py | .py | 3fb01e0907f53051 | 7.5 | 9 |
#!/usr/bin/env python3
"""quackplanetosmget: combine split OSM planet file to extract rail related tags"""
import os
import geopandas as gp
import pandas as pd
import polars as pl
import quackosm as qosm
WGS84 = "EPSG:4326"
# CRS = "EPSG:4087"
CRS = "EPSG:3857"
OUTPATH = "output/planet-rail.gpkg"
pd.set_option("di... | anisotropi4/magpie | quackplanetosmget.py | .py | 8a409c37fa96cc36 | 7.5 | 9 |
"""Stage 4 - sort renamed files into per-season folders.
Reads the ``S01E02`` token that the renamer writes into every file name and
moves the file into a ``Season 1`` folder (created on demand). Falls back to
parsing the legacy ``Ep-N S-E`` layout for files produced by older runs.
Cross-platform path handling and a... | kud04rk/anime-renamer | anime_renamer/organiser.py | .py | b2ebfe6f5fee8abb | 7.62 | 16 |
"""Interactive pipeline that ties every stage together.
Both entry points (``python -m anime_renamer`` and the standalone
``main.py``) delegate here so the flow is defined once. Every stage is
invoked as a direct function call - never via ``os.system`` - which makes the
tool work identically on Windows, Linux and mac... | kud04rk/anime-renamer | anime_renamer/pipeline.py | .py | 43c2ee4a9e090c0b | 7.62 | 16 |
"""Stage 2 - strip unwanted text from file names.
Lets the user remove one or more substrings (or a regular expression) from
the names of every media file in the current folder. Common release-group
noise (``[Group]``, ``(720p)``, resolution / codec tags) can be removed in a
single pass with the built-in ``--tags`` s... | kud04rk/anime-renamer | anime_renamer/remover.py | .py | 697b474a4904738c | 7.62 | 16 |
import asyncio
import difflib
import discord
from discord.ext.commands import Bot, Cog
from config import CONFIG
def locate(channel_id, channel_list):
"""Find the channel from id, and create location string ("between #abc and #def")"""
for i, c in enumerate(channel_list):
if c.id == channel_id:
... | UWCS/apollo | cogs/channel_checker.py | .py | ebedd3a639da218f | 7.52 | 10 |
import datetime
import time
from discord.ext import commands
from discord.ext.commands import Bot, Context, check
from utils.utils import is_compsoc_exec_in_guild
LONG_HELP_TEXT = """
Place a bid on an Exec position!
"""
SHORT_HELP_TEXT = """Make the bot repeat after you."""
class Bid:
def __i... | UWCS/apollo | cogs/commands/auction.py | .py | 76da9780df499d5b | 7.52 | 10 |
import logging
from enum import Enum
import discord
import openai
from discord.ext import commands
from discord.ext.commands import Bot, Context, check, clean_content
import utils
from cogs.commands.openaiadmin import is_author_banned_openai
from config import CONFIG
LONG_HELP_TEXT = """
Apollo is more creative than... | UWCS/apollo | cogs/commands/dalle.py | .py | da34295b525503ac | 7.52 | 10 |
from datetime import datetime, timedelta
import discord
from discord.ext import commands
from discord.ext.commands import Bot, Context
from pytz import timezone
from models import db_session
from models.event_sync import EventLink
from utils.utils import get_json_from_url, is_compsoc_exec_in_guild
LONG_HELP_TEXT = "... | UWCS/apollo | cogs/commands/event_sync.py | .py | 133dc99d87b8c114 | 7.52 | 10 |
import logging
from enum import Enum, unique
from discord import TextChannel
from discord.ext import commands
from discord.ext.commands import Bot, Context, check
from sqlalchemy.exc import SQLAlchemyError
from models import db_session
from models.channel_settings import IgnoredChannel, MiniKarmaChannel
from utils im... | UWCS/apollo | cogs/commands/karma_admin.py | .py | f2d5112be4655315 | 7.52 | 10 |
from discord import Interaction, User
from discord.ext import commands
from discord.ext.commands import Bot, Context, check
from psycopg import OperationalError
from sqlalchemy.exc import SQLAlchemyError
from models import db_session
from models.openai import OpenAIBans
from models.user import User as db_user
from uti... | UWCS/apollo | cogs/commands/openaiadmin.py | .py | 34f33252a6c1e164 | 7.52 | 10 |
import asyncio
import json
import logging
from datetime import date, datetime, time, timedelta
from pathlib import Path
from urllib.parse import quote
import discord
import humanize
from discord.ext import commands
from discord.ext.commands import Bot, Context
import utils
# from cogs.commands.karma_admin import Min... | UWCS/apollo | cogs/commands/roomsearch.py | .py | 4d28efbd3457c87e | 7.52 | 10 |
import configparser
import logging
import os
import re
import shutil
from pathlib import Path
import requests
from discord import Color, Embed
from discord.ext import commands
from discord.ext.commands import Bot, Context, check, clean_content
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy_utils import Sca... | UWCS/apollo | cogs/commands/unused/print_tools.py | .py | 37720584b0713bfc | 7.52 | 10 |
from dataclasses import dataclass
from itertools import groupby
from typing import Iterable, List
from discord import Message
from sqlalchemy.orm import Session
from karma.parser import KarmaItem
from models.karma import BlockedKarma
from utils.utils import user_is_irc_bot
def is_self_karma(karma_item: KarmaItem, m... | UWCS/apollo | karma/transaction.py | .py | a72157029652e39f | 7.52 | 10 |
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from config import CONFIG
from models import Base
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config f... | UWCS/apollo | migrations/env.py | .py | 21d2dd26937eeec9 | 7.52 | 10 |
"""Added unique column to role menu
Revision ID: 0963d3f2727b
Revises: 42510fc13e04
Create Date: 2022-09-23 16:01:03.363118
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "0963d3f2727b"
down_revision = "42510fc13e04"
branch_labels = None
depends_on = None
def... | UWCS/apollo | migrations/versions/0963d3f2727b_added_unique_column_to_role_menu.py | .py | 116a462b6e2e0233 | 7.52 | 10 |
"""Create table reminders
Revision ID: 1cb55d4fff97
Revises: 3e497f4c9795
Create Date: 2019-02-05 23:15:12.150452
"""
from datetime import datetime
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "1cb55d4fff97"
down_revision = "3e497f4c9795"
branch_labels = None
de... | UWCS/apollo | migrations/versions/1cb55d4fff97_create_table_reminders.py | .py | b78e5b646426a181 | 7.52 | 10 |
document.getElementById("mcq").addEventListener("click", function () {
// document.getElementById("enterquestion").innerHTML = `
// `;
document.getElementById("mcqform").style.display = "block";
document.getElementById("subform").style.display = "none";
document.getElementById("displayques").style.display... | SuyashMore/AI-Proctored-Examination-System | src/BackendServer/public/createTest.js | .js | 4156e6097ba89b4d | 7.02 | 10 |
filepath = "audio_wav/"
output_filepath = "Transcripts/"
#bucketname='speech2textaudio'
from pydub import AudioSegment
import io
import os
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
import wave
from google.cloud import storage
def mp3_to_wav(audio_file_... | prateekralhan/Speech2Text-for-Long-Audio-Files | Google_Longaudio_API.py | .py | ee7a23a431f48a4d | 7.59 | 14 |
from flask.globals import current_app
from flask_httpauth import HTTPBasicAuth
from redis import RedisError
from redisConnections.redis_users_connection import RedisUsersConnection
from utility.util import hash_pw
auth = HTTPBasicAuth()
users: RedisUsersConnection
@auth.hash_password
def hash_pw_bytes(password: str... | YangCatalog/backend | api/authentication/auth.py | .py | 1716d23097fa0bd5 | 7.42 | 6 |
# Copyright The IETF Trust 2020, All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | YangCatalog/backend | api/views/comparisons.py | .py | 6158b621827b1e76 | 7.42 | 6 |
# Copyright The IETF Trust 2020, All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | YangCatalog/backend | api/views/error_handler.py | .py | ef96af243accded1 | 7.42 | 6 |
# Copyright The IETF Trust 2022, All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | YangCatalog/backend | api/views/yang_search/response_row.py | .py | a16c0351cf4da7a5 | 7.42 | 6 |
# Copyright The IETF Trust 2019, All Rights Reserved
# Copyright 2018 Cisco and its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | YangCatalog/backend | api/yangcatalog_api.py | .py | 68167ae155b340f9 | 7.42 | 6 |
# Copyright The IETF Trust 2023, All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | YangCatalog/backend | automatic_push/iana_push.py | .py | 01d5096c13363316 | 7.42 | 6 |
# Copyright The IETF Trust 2023, All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | YangCatalog/backend | automatic_push/ietf_push.py | .py | 0958944fc2cf5770 | 7.42 | 6 |
# Copyright The IETF Trust 2023, All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | YangCatalog/backend | automatic_push/utils.py | .py | 35a6ff14ddf81141 | 7.42 | 6 |
# Copyright The IETF Trust 2019, All Rights Reserved
# Copyright 2018 Cisco and its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | YangCatalog/backend | ietfYangDraftPull/pull_local.py | .py | cf5810a291cfaf1e | 7.42 | 6 |
"""
Support for Airnut 1S plant sensor.
Developer by billhu
192.168.123.4 apn.airnut.com
"""
import logging
import datetime
from homeassistant.components.sensor import SensorEntity
from homeassistant.helpers.device_registry import DeviceInfo
from .const import (
DOMAIN,
CONF_IP,
ATTR_TEMPERATURE,
ATTR... | billhu1996/Airnut | custom_components/airnut/sensor.py | .py | f72bc765ac62e6ab | 7.56 | 12 |
#!/usr/bin/env python3
"""STM32 DfuSe 只读读取工具(基于 ST AN3156 协议)
只执行 UPLOAD(读取)操作,绝不执行擦除/下载/解锁,安全无损。
用法:
python3 dfu_read.py ob # 读 Option Bytes(检查读保护 RDP)
python3 dfu_read.py info # 读 Unique ID + Flash 容量
python3 dfu_read.py flash <addr> <size> <outfile> # 读指定 Flash 区域
例:... | billhu1996/Airnut | firmware/dfu_read.py | .py | c5fdcf7f99cec20d | 7.56 | 12 |
"""Base classes for audio feature extraction models."""
from abc import ABC, abstractmethod
from pathlib import Path
import numpy as np
import torch
from exordium.audio.io import load_audio
from exordium.utils.device import get_torch_device
class AudioModelWrapper(ABC):
"""Abstract base class for audio feature... | fodorad/exordium | exordium/audio/base.py | .py | d9afb68ca99eb02a | 7.42 | 6 |
"""CLAP audio embedding model wrapper."""
from pathlib import Path
import numpy as np
import torch
import torchaudio
from transformers import ClapModel, ClapProcessor
from exordium.audio.base import AudioModelWrapper
from exordium.utils.ckpt import build_hf_model
CLAP_MODEL_ID = "laion/larger_clap_music_and_speech"... | fodorad/exordium | exordium/audio/clap.py | .py | 0c6a1a8187a718d1 | 7.42 | 6 |
"""Audio input/output utilities."""
import logging
import math
from pathlib import Path
import torch
import torchaudio
logger = logging.getLogger(__name__)
"""Module-level logger."""
def save_audio(audio: torch.Tensor, output_path: Path | str, sr: int = 16000) -> None:
"""Save audio waveform to file using torc... | fodorad/exordium | exordium/audio/io.py | .py | 0cd8315bb79a24a6 | 7.42 | 6 |
"""OpenSmile feature extractor wrapper."""
from pathlib import Path
from typing import cast
import numpy as np
import opensmile
import torch
from exordium.utils.decorator import load_or_create
class OpensmileWrapper:
"""Extract acoustic features using OpenSmile.
Wrapper for OpenSmile feature extraction wi... | fodorad/exordium | exordium/audio/smile.py | .py | fcf386fe67d73afd | 7.42 | 6 |
"""Audio spectrogram generation utilities."""
from pathlib import Path
from typing import Any
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchaudio
def preprocess_audio(
waveform: torch.Tensor, waveform_sample_rate: int, target_sample_rate: int
) -> tuple[torch.Tensor, int]:
"""C... | fodorad/exordium | exordium/audio/spectrogram.py | .py | 7f0f8f5ea064831b | 7.92 | 6 |
"""Wav2Vec2 speech encoding model wrapper.
Supports multiple pretrained weight configurations:
- ``"base-960h"`` — Facebook's wav2vec2-base-960h (ASR-finetuned).
- ``"emotion-iemocap"`` — SpeechBrain's emotion-recognition-wav2vec2-IEMOCAP
(emotion-finetuned on IEMOCAP: neutral, anger, happy, sad).
Both variants pr... | fodorad/exordium | exordium/audio/wav2vec2.py | .py | 6b05be2249de8448 | 7.42 | 6 |
"""WavLM speech encoding model wrapper."""
from pathlib import Path
import numpy as np
import torch
from transformers import WavLMModel
from exordium.audio.base import AudioModelWrapper
from exordium.utils.ckpt import build_hf_model
from exordium.utils.decorator import load_or_create
WAVLM_SAMPLE_RATE = 16000 # al... | fodorad/exordium | exordium/audio/wavlm.py | .py | f97eb77e5f7f3012 | 7.42 | 6 |
"""Word-level forced alignment and open-vocabulary word timestamps.
Two public classes:
* :class:`TorchaudioForcedAligner` — aligns a **known** transcript to audio
using ``torchaudio``'s multilingual ``MMS_FA`` bundle. No extra dependencies
beyond the pinned ``torchaudio``.
* :class:`WhisperWordTimestamper` — tr... | fodorad/exordium | exordium/text/alignment.py | .py | 5d68c679fdcfc77d | 7.42 | 6 |
"""BERT text encoding model wrapper."""
import torch
from exordium.text.base import TextModelWrapper
class BertWrapper(TextModelWrapper):
"""BERT (bert-base-uncased) token-level encoder. Hidden size: 768.
Returns all token hidden states of shape ``(B, T, 768)``. BERT is not a
sentence-transformer — it... | fodorad/exordium | exordium/text/bert.py | .py | fa95ad8ef0497a11 | 7.42 | 6 |
"""EuroBERT multilingual text encoder wrapper (token-level or pooled).
EuroBERT is a **EuroBERT-architecture** encoder (Llama-style: rotary embeddings,
grouped-query attention) — not XLM-RoBERTa. It is kept in its own module so the
naming stays architecture-honest; it shares the ``pooling`` API of
:class:`~exordium.te... | fodorad/exordium | exordium/text/eurobert.py | .py | 1a538044b27cdb66 | 7.42 | 6 |
"""Structured transcript-quality metrics and segment-annotation validation.
Pure logic (no models): turns a word stream and known annotations into
structured, serialisable results that downstream code (e.g. an audio cutter in
another project) can act on directly.
* :func:`evaluate_transcript` → :class:`TranscriptMetr... | fodorad/exordium | exordium/text/evaluation.py | .py | 31ffc60b6d2f8f4b | 7.42 | 6 |
"""mmBERT multilingual text encoder wrapper (token-level or pooled).
mmBERT is a **ModernBERT-architecture** massively multilingual encoder — not
XLM-RoBERTa. It is kept in its own module so the naming stays architecture-honest;
it shares the ``pooling`` API of :class:`~exordium.text.base.PooledTokenTextWrapper`
with ... | fodorad/exordium | exordium/text/mmbert.py | .py | 7cff21de825c2ff5 | 7.42 | 6 |
"""High-level speech transcription & alignment facade.
:class:`SpeechAlignmentPipeline` hides the choice of forced-alignment backend
(``torchaudio`` ``MMS_FA`` or whisperX) and the fuzzy-matching mechanics behind a
small set of methods that return **structured** results. Downstream projects
consume those results (tra... | fodorad/exordium | exordium/text/pipeline.py | .py | cb25551e206870b6 | 7.42 | 6 |
"""RoBERTa text encoding model wrapper."""
import torch
from exordium.text.base import TextModelWrapper
class RobertaWrapper(TextModelWrapper):
"""RoBERTa-large token-level encoder. Hidden size: 1024.
Returns all token hidden states of shape ``(B, T, 1024)``. RoBERTa is not
a sentence-transformer — it... | fodorad/exordium | exordium/text/roberta.py | .py | 06fb0a545d9a7a35 | 7.42 | 6 |
"""Dataset-agnostic fuzzy re-alignment of a known transcript to a word stream.
Given a word stream with timestamps (``list[Word]`` from any backend in
:mod:`exordium.text.alignment` / :mod:`exordium.text.whisperx_align`) and a
**known** segment transcript from any dataset, :func:`find_segment` locates where
that text ... | fodorad/exordium | exordium/text/transcript_align.py | .py | afe0ef6156f202f2 | 7.42 | 6 |
"""Whisper speech-to-text model wrapper."""
import logging
import re
from collections.abc import Iterator
from pathlib import Path
from threading import Thread
from typing import cast
import numpy as np
import torch
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, TextIteratorStreamer
from exordium... | fodorad/exordium | exordium/text/whisper.py | .py | 20cb1793e1fc5eed | 7.42 | 6 |
"""whisperX wav2vec2 forced alignment (ships with the ``text`` extra).
Wraps whisperX's per-language wav2vec2 CTC alignment so a **known** transcript
can be aligned to audio, returning the same ``list[Word]`` as the built-in
:class:`~exordium.text.alignment.TorchaudioForcedAligner`. Having both lets you
cross-check w... | fodorad/exordium | exordium/text/whisperx_align.py | .py | 96c17e21ff793fdc | 7.42 | 6 |
"""Checkpoint utility functions."""
import logging
import urllib.request
from pathlib import Path
from typing import Any
import torch
logger = logging.getLogger(__name__)
"""Module-level logger."""
_HF_REPO_ID = "fodorad/exordium-weights"
"""HuggingFace Hub repository ID for exordium model weights."""
def build_h... | fodorad/exordium | exordium/utils/ckpt.py | .py | 19cee6ed6cf68505 | 7.42 | 6 |
"""Concurrent execution utilities."""
import multiprocessing
import threading
from collections.abc import Callable, Iterable, Sequence
from typing import Any
import torch
from tqdm import tqdm
def _split_evenly(data: Sequence, n: int) -> list:
"""Split a sequence into n roughly equal chunks."""
k, m = divmo... | fodorad/exordium | exordium/utils/concurrent.py | .py | 37d529736f0ca2ac | 7.42 | 6 |
"""Loss function utilities."""
import torch
def bell_l2_l1_loss(y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
"""Bell + L2 + L1 loss.
Args:
y_pred (torch.Tensor): prediction of shape (N, M).
y_true (torch.Tensor): ground truth of shape (N, M).
Returns:
torch.Tenso... | fodorad/exordium | exordium/utils/loss.py | .py | 3e68e2e9def201eb | 7.42 | 6 |
"""Normalization computation utilities."""
import json
import os
from pathlib import Path
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
def get_mean_std(
dataloader: DataLoader, ndim: int, verbose: bool = False
) -> tuple[torch.Tensor, torch.Tensor]:
"""Calculates mean and std v... | fodorad/exordium | exordium/utils/normalize.py | .py | 49baf763a4217a67 | 7.42 | 6 |
"""Padding and cropping utilities."""
import torch
import torch.nn.functional as F
def pad_or_crop_time_dim(
tensor: torch.Tensor, target_size: int, pad_value: int | float = 0
) -> tuple[torch.Tensor, torch.Tensor]:
"""Adjust the time dimension (T) of a tensor to a given size and generate a mask.
Handle... | fodorad/exordium | exordium/utils/padding.py | .py | 680ef2c16f396457 | 7.42 | 6 |
"""Video transformation and face manipulation utilities."""
import math
from collections.abc import Sequence
from typing import cast
import cv2
import numpy as np
import torch
import torchvision.transforms.functional as TF
from exordium.video.core.bb import xyxy2full
from exordium.video.face.landmark.constants impor... | fodorad/exordium | exordium/video/core/transform.py | .py | 2213197a52a94112 | 7.42 | 6 |
"""Abstract base class for frame-wise visual feature extractors."""
from abc import ABC, abstractmethod
from collections.abc import Sequence
from pathlib import Path
from typing import cast
import torch
from tqdm import tqdm
from exordium.utils.decorator import load_or_create
from exordium.utils.device import get_to... | fodorad/exordium | exordium/video/deep/base.py | .py | 94da90180169c0d3 | 7.42 | 6 |
"""CLIP vision-language model wrapper using HuggingFace Transformers."""
import torch
import torchvision.transforms.functional as TF
from transformers import CLIPVisionConfig, CLIPVisionModelWithProjection
from exordium.utils.ckpt import build_hf_model
from exordium.video.deep.base import VisualModelWrapper
_CLIP_ME... | fodorad/exordium | exordium/video/deep/clip.py | .py | c0b395be585816d0 | 7.42 | 6 |
"""DINOv2 vision encoder wrapper using HuggingFace Transformers."""
import torch
import torchvision.transforms.functional as TF
from transformers import Dinov2Model
from exordium.utils.ckpt import build_hf_model
from exordium.video.deep.base import _IMAGENET_MEAN, _IMAGENET_STD, VisualModelWrapper
_MODEL_IDS: dict[s... | fodorad/exordium | exordium/video/deep/dinov2.py | .py | ee017758e786bfd2 | 7.42 | 6 |
"""EmotiEffNet facial expression feature extractor wrapper.
Wraps the EmotiEffNet models from the EmotiEffLib project for penultimate-layer
feature extraction. Models are EfficientNet backbones (B0 or B2) pre-trained on
VGGFace2 and fine-tuned on AffectNet for facial expression recognition.
Weights are downloaded on... | fodorad/exordium | exordium/video/deep/emotieffnet.py | .py | 68bf8cd7132af806 | 7.42 | 6 |
"""FabNet facial feature extractor wrapper."""
import logging
import torch
import torch.nn as nn
import torchvision.transforms.functional as TF
from exordium import WEIGHT_DIR
from exordium.utils.ckpt import download_weight
from exordium.video.deep.base import VisualModelWrapper
logger = logging.getLogger(__name__)... | fodorad/exordium | exordium/video/deep/fabnet.py | .py | 939dc71307f42f12 | 7.42 | 6 |
"""FaRL universal facial representation wrapper.
Wraps the FaRL (Facial Representation Learning) vision encoder for frame-wise
feature extraction. FaRL is a CLIP ViT-B/16 further pre-trained on LAION-Face
(20M face image-text pairs) with combined image-text contrastive learning and
masked image modelling, yielding a ... | fodorad/exordium | exordium/video/deep/farl.py | .py | 2b4c0fd028e9289f | 7.42 | 6 |
#!/usr/bin/env python3
"""
The module contains the Dash application with which the user will interact.
The workflow consists of:
1. Build the HTML page using dash_html_components.
2. Update the Symbols DataTable using a callback.
* The callback runs whenever data from the Financials or the ... | andreiraduta11/bet-etf | docker-compose/dash_application.py | .py | 9e3db81b04a4a942 | 7.54 | 11 |
#!/usr/bin/env python3
from concurrent.futures import ThreadPoolExecutor
from json import dumps, loads
from math import floor
from multiprocessing import cpu_count
from socket import AF_INET, SOCK_STREAM, socket
from time import sleep
from traceback import print_exc
from typing import Dict, List
from mysql.connector... | andreiraduta11/bet-etf | docker-swarm/application/application.py | .py | 571aaafcc11527da | 7.54 | 11 |
#!/usr/bin/env python3
from sys import exit
from time import sleep
from typing import Dict, List
from lxml.html import HtmlElement, fromstring
from requests import get
from mysql.connector import connect
LOOP_INTERVAL = 1 * 60
MYSQL_TIMEOUT = 3
MYSQL_RETRIES = 10
MYSQL_CONFIG = {
'user': 'mysql_user',
'pa... | andreiraduta11/bet-etf | docker-swarm/collector/collector.py | .py | c23d132ef93fd45c | 7.54 | 11 |
"""
The module contains methods to collect data about the symbols of the BET
Index from the BVB and Tradeville websites.
Andrei Răduță andrei.raduta11@gmail.com
"""
from datetime import datetime
from json import dump
from typing import Dict, List
from zoneinfo import ZoneInfo
from lxml.html import fromstring... | andreiraduta11/bet-etf | pythonanywhere/collector.py | .py | 164b7be4707fee7e | 7.54 | 11 |
"""
The module contains the Dash application with which the user will interact.
The workflow consists of:
1. Build the HTML page using dash_html_components.
2. Update the Symbols DataTable using a callback.
* The callback runs whenever data from the Financials or the Symbols DataTables has ch... | andreiraduta11/bet-etf | pythonanywhere/dash_application.py | .py | d5dcaf0406d52f7e | 7.54 | 11 |
#!/usr/bin/python
# Author: @BlankGodd_
from search import Search_Genius
from interact import Interact
from save import Save
from web import Webpage
from tool import Tool
class ResponseError(Exception):
"""Response error class"""
pass
class Package:
"""class for using blyrics as a module"""
def __... | AgbaD/BLyrics | blyrics/blyrics.py | .py | f794f2bf722e0723 | 7.45 | 7 |
#!/usr/bin/python
# Author: @BlankGodd_
import json
import ast
import requests
class DupError(Exception):
"""Duplication Error"""
pass
class Interact:
"""For getting referents"""
def __init__(self):
"""Interact class constructor
Method:
- get_referents: for gett... | AgbaD/BLyrics | blyrics/interact.py | .py | a30ce11a80cd4985 | 7.45 | 7 |
#!/usr/bin/python
# Author: @BlankGodd_
import os
import json
class Save:
"""For saving information to files"""
def __init__(self):
"""Constructor for saving files
Methods:
- save_artist: saving artist information
- save_song: saving song information
"""
... | AgbaD/BLyrics | blyrics/save.py | .py | deab4ad00bb50753 | 7.45 | 7 |
#!/usr/bin/python
# Author: @BlankGodd_
import requests
import ast, json
from bs4 import BeautifulSoup
import re
class Search_Genius:
"""Songs, Artists and Search"""
def __init__(self):
"""Constructor for search genius
Methods
- search: to make a general search
- s... | AgbaD/BLyrics | blyrics/search.py | .py | abb2697a332580c3 | 7.45 | 7 |
#!/usr/bin/python
# Author: @BlankGodd_
import requests
from bs4 import BeautifulSoup
import re, ast
class Webpage:
"""For getting articles from www.genius.com"""
def __init__(self):
"""Constructor for Webpage class
Methods:
- get_page: get the genius home page
... | AgbaD/BLyrics | blyrics/web.py | .py | 67f823bf75680ff4 | 7.45 | 7 |
"""Pure functions implementing the BRB inference pipeline.
Each function corresponds to one step in the BRB evidential reasoning process:
input transformation, activation weight computation, belief combination, and
output aggregation. All functions are vectorized over samples.
"""
from collections.abc import Callable... | gialmisi/desdeo-brb | src/desdeo_brb/inference.py | .py | 37cb2577500f8fd4 | 7.57 | 13 |
"""JAX backend for the BRB inference pipeline.
Provides JIT-compiled versions of the inference functions and a
differentiable end-to-end inference function for gradient-based training.
Because ``jax.jit`` traces code and requires static array shapes, the
varying-length referential value arrays are padded into fixed-s... | gialmisi/desdeo-brb | src/desdeo_brb/jax_backend.py | .py | f47e6db67ef1a3b0 | 7.57 | 13 |
"""Pydantic models for BRB data structures.
Defines the core data containers used throughout the BRB system:
rule bases, inference results, and trainable parameter containers.
"""
import numpy as np
from pydantic import BaseModel, ConfigDict, model_validator
class RuleBase(BaseModel):
"""Holds the complete spec... | gialmisi/desdeo-brb | src/desdeo_brb/models.py | .py | 53bc394b1894b279 | 7.57 | 13 |
"""Pyomo backend for symbolic BRB optimization with IPOPT.
Builds a Pyomo ``ConcreteModel`` that encodes the entire BRB inference
pipeline as symbolic expressions, suitable for solving with interior-point
solvers like IPOPT. The MSE objective is built from the predictions on
training data.
Two modes for handling the ... | gialmisi/desdeo-brb | src/desdeo_brb/pyomo_backend.py | .py | 2b2fd5a4c1c3f5fb | 7.57 | 13 |
"""Utility and helper functions for the BRB system.
Provides common operations such as generating referential value grids
and computing Cartesian products of arrays with varying lengths.
"""
import numpy as np
def cartesian_product(list_of_arrays: list[np.ndarray]) -> np.ndarray:
"""Compute the Cartesian produc... | gialmisi/desdeo-brb | src/desdeo_brb/utils.py | .py | f35688f484dd3b79 | 7.57 | 13 |
"""Integration tests reproducing numerical examples from the source papers.
References:
- Chen et al. (2011): "A generalized RIMER method for rule-based
classification with varying rule lengths"
- Thesis: Section 3.5 (simple additive example), Section 5.1 (Himmelblau)
"""
import numpy as np
import pytest
from numpy... | gialmisi/desdeo-brb | tests/integration/test_article_examples.py | .py | 1ac1febd74318ae2 | 8.07 | 13 |
"""Integration tests for the BRB fit-predict pipeline."""
import numpy as np
import pytest
from numpy.testing import assert_allclose
from desdeo_brb.brb import BRBModel
from desdeo_brb.models import InferenceResult
from desdeo_brb.utils import generate_uniform_referential_values
def test_predict_untrained_identity(... | gialmisi/desdeo-brb | tests/integration/test_brb_fit_predict.py | .py | bd1c0e6569eba8f8 | 7.07 | 13 |
"""Integration tests for JAX-based training."""
import time
import numpy as np
import pytest
from numpy.testing import assert_allclose
from desdeo_brb.brb import BRBModel
from desdeo_brb.jax_backend import JAX_AVAILABLE
from desdeo_brb.utils import generate_uniform_referential_values
pytestmark = pytest.mark.skipif... | gialmisi/desdeo-brb | tests/integration/test_jax_training.py | .py | 55b665a74b3da281 | 8.07 | 13 |
"""Integration tests based on published BRB application examples.
References:
- Chen et al. (2011), Appendix D / Table D.1 — pipeline leak detection
- Xu et al. (2007) — original pipeline leak detection expert system
- Yang et al. (2007) — expert-then-train BRB workflow
- Thesis Section 3.7 — cos(sqrt(x)) / (2 + cos(x... | gialmisi/desdeo-brb | tests/integration/test_literature_examples.py | .py | 7262f9172ab0402a | 8.07 | 13 |
"""Integration tests for the Pyomo backend."""
import numpy as np
import pytest
try:
import pyomo.environ as pyo
from desdeo_brb.pyomo_backend import PYOMO_AVAILABLE, build_pyomo_brb_model
_solver = pyo.SolverFactory("ipopt")
IPOPT_AVAILABLE = bool(_solver.available())
except Exception: # pragma: n... | gialmisi/desdeo-brb | tests/integration/test_pyomo_backend.py | .py | 2f376004df38fda8 | 7.07 | 13 |
"""Tests for desdeo_brb.inference."""
import numpy as np
from numpy.testing import assert_allclose
from desdeo_brb.inference import (
compute_activation_weights,
compute_combined_belief_degrees,
compute_output,
input_transform,
)
# input_transform tests
def test_input_transform_at_referential_value... | gialmisi/desdeo-brb | tests/unit/test_inference.py | .py | e4a78315fefba8ca | 8.07 | 13 |
"""Tests for desdeo_brb.jax_backend."""
import numpy as np
import pytest
from numpy.testing import assert_allclose
from desdeo_brb.inference import (
compute_activation_weights,
compute_combined_belief_degrees,
compute_output,
input_transform,
)
from desdeo_brb.jax_backend import JAX_AVAILABLE
from de... | gialmisi/desdeo-brb | tests/unit/test_jax_backend.py | .py | e9283ff46dbd81c9 | 8.07 | 13 |
"""Tests for desdeo_brb.models."""
import json
import numpy as np
import pytest
from numpy.testing import assert_array_equal
from pydantic import ValidationError
from desdeo_brb.models import InferenceResult, RuleBase
def _make_valid_rule_base() -> RuleBase:
"""Create a minimal valid RuleBase for testing."""
... | gialmisi/desdeo-brb | tests/unit/test_models.py | .py | 33c369f8f09f6c0a | 8.07 | 13 |
"""Tests for desdeo_brb.utils."""
import numpy as np
from numpy.testing import assert_array_equal
from desdeo_brb.utils import (
build_rule_antecedent_indices,
cartesian_product,
generate_uniform_referential_values,
)
def test_cartesian_product_basic():
"""Two arrays of length 2 produce 4 rows."""
... | gialmisi/desdeo-brb | tests/unit/test_utils.py | .py | 2ecaba7ee38a90d5 | 8.07 | 13 |
""" synchronous addoutput example """
import datetime
import json
from typing import Any, Dict
from pvoutput import PVOutput
def get_apikey_systemid_sync() -> Dict[str, Any]:
"""non-asyncio config loader"""
with open("pvoutput.json", "r", encoding="utf8") as config_file:
config_data: Dict[str, Any] = ... | yaleman/pvoutput | examples/sync_addoutput.py | .py | 93a4eb3c4734f048 | 7.54 | 11 |
""" addstatus example """
import json
from typing import Any, Dict
from pvoutput import PVOutput
def get_apikey_systemid_sync() -> Dict[str, Any]:
"""non-asyncio config loader"""
with open("pvoutput.json", encoding="utf8") as config_file:
config_data: Dict[str, Any] = json.load(config_file)
return... | yaleman/pvoutput | examples/sync_addstatus.py | .py | 100b2e7b8617c56f | 7.54 | 11 |
""" rate limit check example """
import datetime
import json
from typing import Any, Dict
from pvoutput import PVOutput
def get_apikey_systemid_sync() -> Dict[str, Any]:
"""non-asyncio config loader"""
with open("pvoutput.json", "r", encoding="utf8") as config_file:
config_data: Dict[str, Any] = json.... | yaleman/pvoutput | examples/sync_check_rate_limit.py | .py | 84530f7f50dfb64e | 7.54 | 11 |
""" delete status example """
import datetime
import json
from typing import Any, Dict
from pvoutput import PVOutput
def get_apikey_systemid_sync() -> Dict[str, Any]:
"""non-asyncio config loader"""
with open("pvoutput.json", "r", encoding="utf8") as config_file:
config_data: Dict[str, Any] = json.loa... | yaleman/pvoutput | examples/sync_deletestatus.py | .py | 5651db5f07d0e70b | 8.04 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.