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 |
|---|---|---|---|---|---|---|
"""Local Spotify client using D-Bus MPRIS (no credentials needed)."""
import time
from dataclasses import dataclass
@dataclass
class LocalTrack:
"""Represents a track detected via local D-Bus."""
name: str
artist: str
album: str
duration_ms: int
position_ms: int
is_playing: bool
trac... | SamuzDev/ethereal-lyrics | src/local_spotify.py | .py | c8f0d81eeb3b59bb | 7 | 0 |
"""Lyrics fetcher using LRCLib (free, no auth required)."""
import time
import httpx
from dataclasses import dataclass, field
from difflib import SequenceMatcher
from abc import ABC, abstractmethod
def parse_synced_lyrics(synced: str) -> list["LyricLine"]:
"""Parse LRC format synced lyrics into LyricLine objects... | SamuzDev/ethereal-lyrics | src/lyrics_fetcher.py | .py | cab58340f3bf49be | 7 | 0 |
"""Ethereal Lyrics - Display Spotify lyrics in your terminal."""
import sys
import os
import time
import signal
import atexit
import tty
import termios
import threading
from dataclasses import dataclass
from dotenv import load_dotenv
from .config import get_settings
from .spotify_client import SpotifyClient, Track
fr... | SamuzDev/ethereal-lyrics | src/main.py | .py | 7c9dc7e6923d72c1 | 7 | 0 |
"""Spotify client for fetching currently playing track."""
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from dataclasses import dataclass
from typing import Optional
@dataclass
class Track:
"""Represents a currently playing track."""
name: str
artists: str
album: str
duration_ms: int
... | SamuzDev/ethereal-lyrics | src/spotify_client.py | .py | ca6cfcfb5ce6868c | 7 | 0 |
"""Minimal terminal UI that displays synced lyrics one word at a time,
centered on screen, using block character art."""
from __future__ import annotations
import time
from typing import Any
from rich.console import Console
from rich.live import Live
from rich.text import Text
from .font import FONT
def _make_t... | SamuzDev/ethereal-lyrics | src/terminal_ui.py | .py | 065a859f480ce2ec | 7 | 0 |
"""Auto-update mechanism for ethereal-lyrics binary."""
import os
import sys
import urllib.request
import json
from pathlib import Path
VERSION = "0.5.29"
REPO = "SamuzDev/ethereal-lyrics"
GITHUB_API = f"https://api.github.com/repos/{REPO}/releases"
def get_current_version() -> str:
"""Return the current versio... | SamuzDev/ethereal-lyrics | src/updater.py | .py | 9970d44ede857b3f | 7 | 0 |
"""Tests for Japanese text processing module."""
import pytest
from src.japanese_text import (
is_hiragana,
is_katakana,
is_kanji,
is_japanese,
normalize_japanese,
has_japanese,
count_japanese_chars,
to_hiragana,
to_katakana,
normalize_japanese,
JapaneseMode,
convert_jap... | SamuzDev/ethereal-lyrics | tests/test_japanese_text.py | .py | f366f6ffc0859642 | 7.5 | 0 |
"""Tests for terminal_ui module."""
import pytest
from src.terminal_ui import (
_split_words,
_count_real_words,
render_big,
_make_text_glyph,
_TYPOGRAPHIC_MAP,
)
class TestSplitWords:
"""Tests for _split_words function."""
def test_simple_words(self):
words = _split_words("Rise ... | SamuzDev/ethereal-lyrics | tests/test_terminal_ui.py | .py | d48e0bb4b5632c48 | 7.5 | 0 |
"""ttn_alias_check tests: verdict classes on real corpus strings + synthetic DB."""
import os
import sqlite3
import tempfile
import pytest
import ttn_alias_check as AC
@pytest.fixture
def db(tmp_path):
"""Minimal raw-tables DB: enough rows for grounding and effect counts."""
p = tmp_path / "t.sqlite"
co... | nicksweeney/notturnometer | test_ttn_alias_check.py | .py | 9cbf3d5ab983000a | 7.65 | 1 |
"""Tests for ttn_credits — the credit/unit primitive (extracted from the
retired ttn_rebroadcast). Run: uv run --with pytest pytest test_ttn_credits.py -v"""
from ttn_credits import (parse_credit, CreditSig, credit_key, Unit,
build_units, cluster_length, representative_title)
def test_parse_c... | nicksweeney/notturnometer | test_ttn_credits.py | .py | eb5cf139cbc38881 | 7.65 | 1 |
import pytest
import ttn_curate as C
def test_each_subcommand_routes_with_passthrough_argv(monkeypatch):
"""Every subcommand calls its module's main() with argv[1:] verbatim."""
import ttn_duplicates, ttn_composer_duplicates, ttn_audit
import ttn_audit_composer, ttn_mbid_audit
cases = {
"dupli... | nicksweeney/notturnometer | test_ttn_curate.py | .py | 8b629dc8ab414ba9 | 7.65 | 1 |
"""Tests for the shared missing-DB CLI guard (ttn_db) and its wiring: every
tool that operates on an already-scraped DB must refuse a missing path up
front, instead of letting sqlite3.connect() create a 0-byte file that later
fails with "no such table"."""
import importlib
import os
import sqlite3
import pytest
impor... | nicksweeney/notturnometer | test_ttn_db.py | .py | 4df90643bbaa1445 | 7.65 | 1 |
"""ttn_fragmentation --projected mode tests (synthetic DB + stubbed projection)."""
import sqlite3
import pytest
import ttn_fragmentation as F
@pytest.fixture
def db(tmp_path):
p = tmp_path / "t.sqlite"
conn = sqlite3.connect(p)
conn.execute("CREATE TABLE episodes (pid TEXT PRIMARY KEY, broadcast_date T... | nicksweeney/notturnometer | test_ttn_fragmentation.py | .py | a0e72e306a24e566 | 7.65 | 1 |
"""Kitchen/back-of-house data dispatcher: one door to the ingestion + cache tools.
Thin pass-through: `uv run ttn_data.py <subcommand> [args...]` calls the matching
tool's main(args...) verbatim. Plus three metatasks: `update` (= scrape -> segments
-> warm), the DATA-REFRESH recipe so the segments-backfill and re-warm... | nicksweeney/notturnometer | ttn_data.py | .py | 4918d694f2371db8 | 7.15 | 1 |
"""Shared CLI guard for opening an existing SQLite database.
sqlite3.connect() silently CREATES an empty file for a missing path, which
then surfaces as a confusing "no such table: tracks" — so every tool that
operates on an already-scraped DB errors cleanly up front instead.
(ttn_scrape is the deliberate exception: c... | nicksweeney/notturnometer | ttn_db.py | .py | 9796bf247fd1667d | 7.15 | 1 |
#!/usr/bin/env python3
"""Post-alias duplicate-work detector — an independent cross-check that
flags same-composer work-groups likely to be one work keyed apart (the
straggler-scan that was being done by eye over `ttn_analyze --by work`).
"""
import argparse
import re
import sqlite3
from collections import Counter, def... | nicksweeney/notturnometer | ttn_duplicates.py | .py | 25c5ce0c610ba294 | 7.15 | 1 |
#!/usr/bin/env python3
"""EBU source-broadcaster codes -> (broadcaster_name, country_code, country_name).
The `record_label` on segment_events is the EBU source-identifier of the
broadcaster that supplied the recording. The first two letters are an ISO-3166
country code; the remainder identifies the broadcaster. This ... | nicksweeney/notturnometer | ttn_ebu_codes.py | .py | f1f4c50c1b98f933 | 7.15 | 1 |
#!/usr/bin/env python3
"""Recording-pid evidence for identity-aware registry sync (option b).
The evidence cache answers one question during sync_registry's orphan pass:
WHICH recordings backed a slug historically? Keyed by SLUG -- an orphan is a
slug whose stored identity vanished from derivation; what must persist a... | nicksweeney/notturnometer | ttn_evidence.py | .py | feb130b8a0911e04 | 7.15 | 1 |
"""Fragmentation scan: rank composers by FOLDABLE AIRINGS -- which curation
pass moves the most airings. Graduated from scratch/fragmentation_scan.py
(2026-07-19) after proving out over the Milhaud/Hildegard/Durufle/Handel/
Debussy/Brahms passes and finding the number-leak gate.
Score per composer = airings that would... | nicksweeney/notturnometer | ttn_fragmentation.py | .py | a621dfa8a2ce3825 | 7.15 | 1 |
from __future__ import annotations
import statistics
from typing import Any, Callable, Iterable
SHORT_TRANCHE = "IMMEDIATE"
LONG_TRANCHE = "EXTENDED"
# The scales are fixed by the protocol, rather than by a model's chosen ETA.
# They cover the latest target allowed in each tranche plus the three-hour
# settlement w... | fh-eval/foxhole-forecast | src/foxhole_forecast/score_metrics.py | .py | 933ec42f5d095701 | 7 | 0 |
import os
import json
import yaml
import re
import subprocess
from datetime import datetime
CONFIG_DIR = ".amosclaud"
POLICY_FILE = os.path.join(CONFIG_DIR, "repair-policy.json")
LOG_DIR = os.path.join(CONFIG_DIR, "logs")
os.makedirs(LOG_DIR, exist_ok=True)
def load_exact_policy() -> dict:
"""Reads your exact 25... | wamakologeorge-dev/amosclaude-clean | .amosclaud/amosclaud_policy_engine.py | .py | cab2d2794cbb16c8 | 7.15 | 1 |
import os
import sys
import shutil
import subprocess
from datetime import datetime
CONFIG_DIR = ".amosclaud"
SHELL_LOG = os.path.join(CONFIG_DIR, "logs", "shell_execution_bridge.md")
os.makedirs(os.path.dirname(SHELL_LOG), exist_ok=True)
def log_shell_event(command: str, exit_code: int, output: str, status: str):
... | wamakologeorge-dev/amosclaude-clean | .amosclaud/amosclaud_shell_bridge.py | .py | e3fe0d600454850f | 7.15 | 1 |
import json
import os
import sys
import re
import py_compile
import subprocess
from datetime import datetime
CONFIG_DIR = ".amosclaud"
POLICY_FILE = os.path.join(CONFIG_DIR, "repair-policy.json")
def load_policy_rules() -> list:
if os.path.exists(POLICY_FILE):
try:
with open(POLICY_FILE, "r", ... | wamakologeorge-dev/amosclaude-clean | .amosclaud/local_ci_healer.py | .py | 82f7fd7c08d2cf8f | 7.15 | 1 |
#!/usr/bin/env python3
"""Compatibility guard for the retired external Claude patch executor.
Amosclaud patch requests now run through the native Repair Control Plane, which
selects the configured Ollama service first. This module intentionally has no
model-network client, no repository-context reader, and no commit/p... | wamakologeorge-dev/amosclaude-clean | .github/scripts/ai_patch_executor.py | .py | 749d3b8f94d037d3 | 7.15 | 1 |
#!/usr/bin/env python3
"""Generate a bounded feature/build candidate from an Amosclaud issue request.
This reuses the guarded repair candidate engine, but changes the model contract
from "repair a reproduced failure" to "implement the requested product or
feature". Publication remains the responsibility of the trusted... | wamakologeorge-dev/amosclaude-clean | .github/scripts/amosclaud_build_candidate.py | .py | 92014c176f256995 | 7.15 | 1 |
#!/usr/bin/env python3
"""Deterministic failure classification for Amosclaud repair routing."""
from __future__ import annotations
from enum import Enum
class FailureClass(str, Enum):
CODE_FAILURE = "CODE_FAILURE"
TEST_FAILURE = "TEST_FAILURE"
LINT_FAILURE = "LINT_FAILURE"
SECURITY_FAILURE = "SECURI... | wamakologeorge-dev/amosclaude-clean | .github/scripts/amosclaud_failure_classifier.py | .py | 42eeb190ecc348cc | 7.15 | 1 |
#!/usr/bin/env python3
"""Expose prior approval while the candidate validator checks the proposed repair."""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
ROOT = SCRIPT_DIR.parents[1]
for value in (str(SCRIPT_DIR), str(RO... | wamakologeorge-dev/amosclaude-clean | .github/scripts/amosclaud_pr_sensitive_approval.py | .py | a312c41be742abbe | 7.15 | 1 |
#!/usr/bin/env python3
"""Run the repair candidate with the sensitive-data-only approval policy."""
from __future__ import annotations
import copy
import os
import sys
from pathlib import Path
from typing import Any
SCRIPT_DIR = Path(__file__).resolve().parent
ROOT = SCRIPT_DIR.parents[1]
for value in (str(SCRIPT_DI... | wamakologeorge-dev/amosclaude-clean | .github/scripts/amosclaud_repair_candidate_v2.py | .py | 917e961ec0566a04 | 7.15 | 1 |
#!/usr/bin/env python3
"""Fallback beat: the spine outlives any single machine.
The primary beat runs on dedicated hardware. This script (run by the fallback-beat
workflow on a schedule) mints a tick ONLY when the newest anchor is stale — so if the
primary's machine dies, the repo itself keeps the heartbeat going, and... | kody-w/dogg | tools/fallback_beat.py | .py | 13b47828d1c51b04 | 7 | 0 |
#!/usr/bin/env python3
"""orient.json — full orientation in ONE fetch.
A cold agent GETs /orient.json and holds: the current tick anchor, the newest world
frame, every registered dimension, and the chant table. Regenerated by every beat.
"""
import json, sys, pathlib, datetime, hashlib
sys.path.insert(0, str(pathlib.... | kody-w/dogg | tools/orient.py | .py | 599b09c7aed6e3ec | 7 | 0 |
#!/usr/bin/env python3
"""A WITNESS dimension — a second, independent machine re-observes the world.
One machine's reading of a public API is a claim; two unrelated machines recording the
same fact at the same tick corroborate each other. A witness runs on its own hardware,
re-fetches a core subset of the world source... | kody-w/dogg | tools/witness.py | .py | ee38133f13097bb5 | 7 | 0 |
"""ASR model configuration and resolution for docling integration."""
from pydantic import BaseModel, ConfigDict
from researcher.enums import AudioAsrModel
from researcher.platform import is_apple_silicon
class AsrModelSpec(BaseModel):
"""Single source of truth for one ASR model's identifiers across every consu... | svetzal/researcher-cli | researcher/asr_config.py | .py | e6aed9cce54ecfa5 | 7 | 0 |
from researcher.models import SearchResult
def parse_query_results(results: dict) -> list[SearchResult]:
"""Transform raw ChromaDB query results into domain models.
Args:
results: The dict returned by ChromaDB's ``collection.query()``,
containing keys ``ids``, ``documents``, ``metadatas``... | svetzal/researcher-cli | researcher/chroma_parsing.py | .py | 54227dea584b7bde | 7 | 0 |
import contextlib
import json
from collections.abc import Callable
import typer
from rich.console import Console
from researcher.config import RepositoryConfig
from researcher.error_boundary import handle_boundary_errors
from researcher.exceptions import ResearcherError
from researcher.service_factory import ServiceF... | svetzal/researcher-cli | researcher/cli/output.py | .py | 0dba6dfa82f94d14 | 7 | 0 |
"""Docling converter configuration resolution for DoclingGateway."""
from typing import Any
from pydantic import BaseModel, ConfigDict
from researcher.asr_config import resolve_asr_spec_name
from researcher.enums import AudioAsrModel, ImagePipeline
from researcher.model_registry import resolve_vlm_preset
class Vlm... | svetzal/researcher-cli | researcher/docling_config.py | .py | f599678e66638ddf | 7 | 0 |
"""Embedding provider configuration resolution for EmbeddingGateway."""
from pydantic import BaseModel, ConfigDict
from researcher.enums import EmbeddingProvider
# Default embedding model for each provider
_DEFAULT_MODELS: dict[EmbeddingProvider, str] = {
EmbeddingProvider.CHROMADB: "default",
EmbeddingProvi... | svetzal/researcher-cli | researcher/embedding_providers.py | .py | 48bc56bfc6bd6572 | 7 | 0 |
from importlib.metadata import version as pkg_version
from importlib.resources import files
from researcher.gateways.error_wrapper import wrap_storage_error
class BundledSkillsGateway:
"""Gateway for accessing bundled skill files and package metadata."""
@wrap_storage_error("Failed to read bundled skill '{s... | svetzal/researcher-cli | researcher/gateways/bundled_skills_gateway.py | .py | 7457d796eebb4276 | 7 | 0 |
import json
import os
from datetime import UTC, datetime
from pathlib import Path
from researcher.gateways.error_wrapper import wrap_storage_error
class ChecksumGateway:
def __init__(self, checksums_path: Path):
self._path = checksums_path
@wrap_storage_error("Failed to load checksum file '{self._pa... | svetzal/researcher-cli | researcher/gateways/checksum_gateway.py | .py | 44fe3062523bfe24 | 7 | 0 |
import os
import tempfile
# Must happen before any `app.*` import: app/database.py reads DATABASE_URL
# at module import time, so tests get their own throwaway SQLite file
# instead of touching the real Postgres database.
_test_db_fd, _test_db_path = tempfile.mkstemp(suffix=".db")
os.environ["DATABASE_URL"] = f"sqlite... | NairbN/SortFlow | backend/tests/conftest.py | .py | aadd26bd2b8da926 | 7.65 | 1 |
"""RSS 抓取器:读取 sources.yaml,抓取全部信息源,产出统一格式的候选条目。
设计要点:
- 单个源失败只打警告、不中断(有些 RSS 源就是偶尔抽风)
- 每条带 priority / category / 时间戳,供 LLM 筛选和兜底排序使用
"""
import calendar
import concurrent.futures
import logging
import ssl
import time
from dataclasses import asdict, dataclass
from urllib.request import Request, urlopen
import certifi... | zhanghuaiwei/ai-daily | src/fetcher.py | .py | 19a49e8267a0bc71 | 7 | 0 |
"""Untrusted-content normalization shared by fetching, curation and rendering."""
from __future__ import annotations
import html
import re
import unicodedata
from collections.abc import Mapping
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\... | zhanghuaiwei/ai-daily | src/safety.py | .py | 160ff0eb443c7e57 | 7 | 0 |
"""Immutable boundary for activating matched capability descriptors."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from capability.descriptor import CapabilityDescriptor
from capability.matching import CapabilityMatchCollection
@dataclass(frozen=True, slots=True)
class ActiveCapabilityCol... | nolanjaycee2qve0a8-boop/EOS | capability/activation.py | .py | 8786713ed861f866 | 7 | 0 |
"""Abstract boundary for EMS business capabilities."""
from abc import ABC, abstractmethod
from kernel.decision import DecisionContext, DecisionIntent
class EMSCapabilityBoundary(ABC):
"""Define a stateless extension point from decision facts to intent.
A capability expresses what a business objective want... | nolanjaycee2qve0a8-boop/EOS | capability/base.py | .py | 2e7933cc9c8fc2bc | 7 | 0 |
"""Abstract boundary for deterministic EMS capability composition."""
from abc import ABC, abstractmethod
from capability.base import EMSCapabilityBoundary
from kernel.decision import DecisionContext, DecisionIntent
class CapabilityCompositionBoundary(ABC):
"""Define ordered, exactly-once capability evaluation.... | nolanjaycee2qve0a8-boop/EOS | capability/composition.py | .py | 67ac4a4b77a61728 | 7 | 0 |
"""Immutable descriptor contract for an EMS capability."""
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class CapabilityDescriptor:
"""Describe a capability without referencing its implementation."""
name: str
description: str
def __post_init__(self) -> None:
if not... | nolanjaycee2qve0a8-boop/EOS | capability/descriptor.py | .py | 580b5607767037c9 | 7 | 0 |
"""Deterministic caller-parameterized intent resolution."""
from dataclasses import dataclass
from capability.resolution import IntentResolutionBoundary
from kernel.decision import DecisionIntent
@dataclass(frozen=True, slots=True)
class DeterministicIntentResolutionParameters:
"""Select one candidate by an exp... | nolanjaycee2qve0a8-boop/EOS | capability/deterministic_resolution.py | .py | 8edfb0b474f9b65a | 7 | 0 |
"""Immutable boundary for discovering available capability descriptors."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from capability.descriptor import CapabilityDescriptor
@dataclass(frozen=True, slots=True)
class AvailableCapabilityCollection:
"""Hold exact descriptors reported as a... | nolanjaycee2qve0a8-boop/EOS | capability/discovery.py | .py | 7fe4dcef7b7033e9 | 7 | 0 |
"""Immutable boundary for required-to-available capability matching facts."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from capability.descriptor import CapabilityDescriptor
from capability.discovery import AvailableCapabilityCollection
@dataclass(frozen=True, slots=True)
class Required... | nolanjaycee2qve0a8-boop/EOS | capability/matching.py | .py | 4b1d5e81087361eb | 7 | 0 |
"""Abstract boundary for resolving candidate EMS decision intents."""
from abc import ABC, abstractmethod
from kernel.decision import DecisionIntent
class IntentResolutionBoundary(ABC):
"""Define the extension point from candidate intents to one intent.
The boundary declares only the input and output contr... | nolanjaycee2qve0a8-boop/EOS | capability/resolution.py | .py | 5d72de751ce21972 | 7 | 0 |
"""Stateless photovoltaic self-consumption EMS capability."""
from capability.base import EMSCapabilityBoundary
from kernel.decision import DecisionContext, DecisionIntent
class SelfConsumptionCapability(EMSCapabilityBoundary):
"""Generate battery intent from instantaneous PV-load imbalance."""
__slots__ = ... | nolanjaycee2qve0a8-boop/EOS | capability/self_consumption.py | .py | d3451c996ddabe50 | 7 | 0 |
"""Immutable semantic intent contract for Phase 5 decision formation."""
from dataclasses import dataclass
from typing import Literal
@dataclass(frozen=True, slots=True)
class DecisionIntent:
"""Describe one semantic EMS action without execution meaning.
``action`` is exactly ``"charge"``, ``"discharge"``, ... | nolanjaycee2qve0a8-boop/EOS | decision_formation/intent.py | .py | a7a7cbb8eb5e89e6 | 7 | 0 |
"""Small, transport-neutral validation primitives for Edge contracts."""
from collections.abc import Iterable
from dataclasses import fields, is_dataclass
from datetime import UTC, datetime, timedelta
from enum import Enum
from math import isfinite
from types import UnionType
from typing import Any, ClassVar, Union, g... | nolanjaycee2qve0a8-boop/EOS | edge_runtime/validation.py | .py | ec8e4225415aab69 | 7 | 0 |
"""Concrete deterministic Load profile model for the EMS Simulator demo."""
from simulator import (
LoadSimulationInput,
LoadSimulationModelBoundary,
LoadSimulationResult,
)
class LoadProfileSimulationModel(LoadSimulationModelBoundary):
"""Expose one caller-supplied Load profile value as consumed pow... | nolanjaycee2qve0a8-boop/EOS | ems_simulator/load.py | .py | b447c01fc826ac37 | 7 | 0 |
"""Concrete deterministic PV profile model for the EMS Simulator demo."""
from simulator import (
PVSimulationInput,
PVSimulationModelBoundary,
PVSimulationResult,
)
class PVProfileSimulationModel(PVSimulationModelBoundary):
"""Expose one caller-supplied PV profile value as generated PV power.
T... | nolanjaycee2qve0a8-boop/EOS | ems_simulator/pv.py | .py | 0a7a5237fa88831f | 7 | 0 |
import sys
import shutil
import tempfile
import subprocess
import urllib.request
import gzip
from pathlib import Path
from datetime import datetime
import pytz
# 日志函数(带北京时间)
def log(msg: str):
beijing_time = datetime.now(pytz.timezone('Asia/Shanghai')).strftime("%Y-%m-%d %H:%M:%S")
print(f"[{beijing_time}] INF... | qq5460168/EasyAds | data/python/rules_generator/mihomo.py | .py | 73a017adff94ff51 | 7.24 | 2 |
# EasyAds/data/python/utils/common.py
import logging
from pathlib import Path
from typing import List, Union
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)
def read_file_safely(file_path: Union[Path, str], encoding: str = "utf-8") -> str:
"""安全读取文... | qq5460168/EasyAds | data/python/utils/common.py | .py | 0d4cfd069f4029c0 | 7.24 | 2 |
import os
import re
import subprocess
import time
import shutil
from pathlib import Path
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed, Future
# 配置常量
MAX_WORKERS = 5 # 并发下载数量
TIMEOUT = 60 # 超时时间(秒)
RETRY = 5 # 重试次数
RETRY_DELAY = 2 # 重试间隔(秒)
ENCODING = "ut... | qq5460168/EasyAds | data/python/utils/dl.py | .py | deccb54772e2bf62 | 7.24 | 2 |
import sys
from pathlib import Path
class AdGuardProcessor:
def __init__(self):
# 初始化计数器用于生成报告
self.total_black = 0
self.total_white = 0
self.filtered_count = 0
def process_blacklist(self, black_path, white_path, output_path):
"""处理黑名单并应用白名单过滤"""
# 读取白名单规则
... | qq5460168/EasyAds | data/python/utils/filter-ad.py | .py | 44aca488a3797af7 | 7.24 | 2 |
import re
import os
import shutil
from pathlib import Path
from datetime import datetime
# 路径计算(与dl.py保持一致,确保文件能被找到)
SCRIPT_DIR = Path(__file__).resolve().parent # 脚本所在目录:data/python/utils
ROOT_DIR = SCRIPT_DIR.parent.parent.parent # 项目根目录:EasyAds/
TMP_DIR = ROOT_DIR / "tmp" # 临时目录(与dl.py的输出目录一致... | qq5460168/EasyAds | data/python/utils/merge.py | .py | 538026b57db5518d | 7.24 | 2 |
import re
import logging
from pathlib import Path
from typing import List, Optional
# 配置日志系统
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
logger = logging.getLogger(__name__)
def merge_files(pattern: str, output_file: Path, enco... | qq5460168/EasyAds | data/python/utils/merge_files.py | .py | f153193a34962395 | 7.24 | 2 |
"""规则文件头部处理工具"""
import shutil
from pathlib import Path
from datetime import datetime, timedelta
# 北京时区偏移(UTC+8)
BEIJING_TZ = timedelta(hours=8)
HEADER_TEMPLATE = """[Adblock Plus 2.0]
! 规则更新时间: {timestamp}
! 有效规则数量: {line_count} 条
! 项目地址: https://github.com/qq5460168/EasyAds
! 请不要删除此头部,用于规则识别和更新
\n"""
def get_beijin... | qq5460168/EasyAds | data/python/utils/title.py | .py | 918462d72e6834dc | 7.24 | 2 |
import re
import logging
from pathlib import Path
from typing import Dict, List, Tuple, Set, Optional
from datetime import datetime
import pytz
# 配置日志系统
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
logger = logging.getLogger(__na... | qq5460168/EasyAds | data/python/utils/validate_rules.py | .py | a96376e716316c60 | 7.24 | 2 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@file: data_pusher.py
@desc: Push trending data and reports to a separate GitHub repository
"""
import json
import base64
from datetime import datetime
from typing import Dict, List, Optional
from github import Github, GithubException
from tenacity import retry, stop_a... | wayyoungboy/github-trending-reporter | data_pusher.py | .py | a8d3674adb378d86 | 7.3 | 3 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@file: main.py
@desc: Main entry point for GitHub Trending Reporter
"""
import argparse
import sys
from datetime import datetime
from typing import Optional
from trending_scraper import fetch_trending
from llm_analyzer import LLMAnalyzer
from data_pusher import DataPu... | wayyoungboy/github-trending-reporter | main.py | .py | 6a81c7fe5bb03d23 | 7.3 | 3 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@file: trending_scraper.py
@desc: Scrape GitHub Trending repositories
"""
import requests
from bs4 import BeautifulSoup
from typing import List, Dict, Optional
from tenacity import retry, stop_after_attempt, wait_exponential
import config
class TrendingScraper:
"... | wayyoungboy/github-trending-reporter | trending_scraper.py | .py | de4377588dfa3c53 | 7.3 | 3 |
import argparse
import os
import torch
import torchvision
import tqdm
import re
from PIL import Image
import json
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import smart_resize
def parse_args():
parser = argparse.ArgumentParser(description='GroundingSuite with B... | Lemoncpu/CycleGRPO-OPSD | evaluation/bbox/qwen25vl_groundingsuite_infer_bbox.py | .py | 046882f7bd4ab121 | 7 | 0 |
import argparse
import os
import torch
import torchvision
import tqdm
import re
from PIL import Image
import json
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5ForConditionalGeneration
from transformers import AutoProcessor
NO_THINK_PREFIX = "<think>\n\n</think>\n\n"
def parse_args():
parser ... | Lemoncpu/CycleGRPO-OPSD | evaluation/bbox/qwen35_groundingsuite_infer_bbox.py | .py | b8ff1174da2be786 | 7 | 0 |
import argparse
import copy
import os
import torch
import torchvision
import tqdm
from pycocotools import mask as mask_utils
import numpy as np
import re
from PIL import Image
import json
import base64
from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
def parse_args():
parser = argparse.Arg... | Lemoncpu/CycleGRPO-OPSD | evaluation/bbox/qwen3vl_gar_vqa_infer_bbox.py | .py | 35a8c8c1f8062284 | 7 | 0 |
import argparse
import os
import torch
import torchvision
import tqdm
import re
from PIL import Image
import json
from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
def parse_args():
parser = argparse.ArgumentParser(description='GroundingSuite with BBox')
parser.add_argument(
'--... | Lemoncpu/CycleGRPO-OPSD | evaluation/bbox/qwen3vl_groundingsuite_infer_bbox.py | .py | a1017ddadb276d43 | 7 | 0 |
import argparse
import copy
import math
import os
import torch
import torchvision
import tqdm
from pycocotools import mask as mask_utils
import numpy as np
import random
import re
from PIL import Image
import json
import uuid
import hydra
import base64
import io
from transformers import Qwen3VLForConditionalGeneration... | Lemoncpu/CycleGRPO-OPSD | evaluation/gar/qwen3vl_gar_detail_infer.py | .py | 48162cac73c7e3a0 | 7 | 0 |
import argparse
import copy
import math
import os
import torch
import torchvision
import tqdm
from pycocotools import mask as mask_utils
import numpy as np
import random
import re
from PIL import Image
import json
import uuid
import hydra
import base64
import io
from transformers import Qwen3VLForConditionalGeneration... | Lemoncpu/CycleGRPO-OPSD | evaluation/gar/qwen3vl_gar_vqa_infer.py | .py | ab737a9fd6162b72 | 7 | 0 |
import argparse
import math
import os
import time
import torch
import tqdm
from pycocotools import mask as mask_utils
import numpy as np
import copy
import hydra
from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
from PIL import Image
import re
import json
from qwen_vl_utils import process_visio... | Lemoncpu/CycleGRPO-OPSD | evaluation/gcg/qwen3vl_gcg_eval.py | .py | 17ff17dbc1d746d6 | 7 | 0 |
"""Shared mask metrics for offline gRefCOCO/GRES aggregate reports."""
from __future__ import annotations
from dataclasses import dataclass, field
import numpy as np
@dataclass
class GresMetricAccumulator:
"""Accumulate the official GRES empty-target and mask-IoU semantics."""
intersection: int = 0
un... | Lemoncpu/CycleGRPO-OPSD | evaluation/gres/subset_metrics.py | .py | cd68a232e426bb82 | 7 | 0 |
import argparse
import copy
import math
import os
import time
import torch
import torchvision
import tqdm
from pycocotools import mask as mask_utils
import numpy as np
import random
import re
from PIL import Image
import json
import uuid
import hydra
from transformers import Qwen3VLForConditionalGeneration, AutoProces... | Lemoncpu/CycleGRPO-OPSD | evaluation/groundingsuite/qwen3vl_groundingsuite_infer.py | .py | 2db3c78a938d3b3d | 7 | 0 |
"""Shared SAMTok mask-generation protocols for offline segmentation evaluation."""
import re
MASK_PROTOCOLS = ("legacy_union", "first_mask")
_MASK_GROUP_PATTERN = re.compile(
r"<\|mt_start\|><\|mt_(\d{4})\|><\|mt_(\d{4})\|><\|mt_end\|>"
)
def validate_mask_protocol(protocol: str) -> str:
if protocol not in... | Lemoncpu/CycleGRPO-OPSD | evaluation/mask_protocol.py | .py | d93ec4f2679774c9 | 7 | 0 |
#!/usr/bin/env python3
"""Convert mask tokens in a JSON file to bbox strings using VQ-SAM2.
Input JSON format: a list of samples where each sample contains at least:
- 'image': list of image paths (first image used to get size)
- 'conversations': list of dicts with 'from' and 'value' fields
This script preserves ... | Lemoncpu/CycleGRPO-OPSD | projects/rl/datasets/convert_json_mask_tokens_to_bbox.py | .py | 8519fbf52dc5deb8 | 7 | 0 |
import argparse
import os
import re
from typing import Dict, List, Any, Tuple
from PIL import Image
import numpy as np
import torch
import torchvision
import json
import tqdm
import hydra
from tqdm import tqdm
from datasets import Dataset, load_dataset
from concurrent.futures import ThreadPoolExecutor, as_completed
fr... | Lemoncpu/CycleGRPO-OPSD | projects/rl/datasets/convert_mask_token_to_bbox.py | .py | 0bf2e466a3f632b4 | 7 | 0 |
"""Canonical template queries for label-supervised text-to-mask samples.
These templates intentionally encode only labels supplied by the source
dataset. They are not synthetic referring expressions and do not add spatial
relations or unannotated attributes.
"""
from __future__ import annotations
# COCO-Stuff ``st... | Lemoncpu/CycleGRPO-OPSD | projects/rl/datasets/grounding_queries.py | .py | 26c196ac35a03f8d | 7 | 0 |
import os
import json
import tqdm
import random
import re
import argparse
from datasets import Dataset, Sequence
from datasets import Image as ImageData
def extract_answer_content(text):
"""
Extract answer content from response text.
Handles multiple formats:
1. <answer>...</answer> tags -> extract ... | Lemoncpu/CycleGRPO-OPSD | projects/rl/datasets/prepare_gcg_rl_dataset.py | .py | 2b32e75da63f7dbd | 7 | 0 |
import os
import json
import tqdm
import time
from openai import OpenAI
import base64
import re
import random
def split_list_random(lst, k=4000, seed=None):
"""
从 lst 中随机选取 k 个元素作为子集A,剩余作为子集B。
不放回抽样,A 与 B 不重叠。
"""
if seed is not None:
random.seed(seed) # 可复现实验
n = len(lst)
if k > n... | Lemoncpu/CycleGRPO-OPSD | projects/rl/datasets/prepare_gres_cold_start_data.py | .py | 54ad0a736a596432 | 7 | 0 |
import os
import re
import json
import argparse
from typing import List
from PIL import Image
import tqdm
from datasets import Dataset, Sequence
from datasets import Image as ImageData
def extract_mt_token_ids(text):
"""Extract mask token ids from text."""
pattern = r"<\|mt_(\d{4})\|>"
return [int(x) for... | Lemoncpu/CycleGRPO-OPSD | projects/rl/datasets/prepare_gres_no_target_rl_dataset.py | .py | 705de2649c194d57 | 7 | 0 |
#!/usr/bin/env python3
"""Convert PACO-LVIS object-part masks into CycleGRPO training records.
PACO annotations identify an object annotation by ``id == obj_ann_id``. This
tool only accepts the complementary annotations, so the output contains true
part masks rather than parent-object masks.
"""
import argparse
impo... | Lemoncpu/CycleGRPO-OPSD | projects/rl/datasets/prepare_paco_lvis_part_cycle_dataset.py | .py | 918f012c8c9ff5f9 | 7 | 0 |
#!/usr/bin/env python3
"""
Logging helpers that tee stdout/stderr into the consolidated workflow log file.
"""
from __future__ import annotations
import contextlib
import sys
from pathlib import Path
from typing import Iterator, TextIO
class TeeStream:
def __init__(self, original: TextIO, mirror: TextIO) -> Non... | devMuniz02/btc-hourly-tournament | pipelines/consolidated/logging_utils.py | .py | 6d7575a263a6b974 | 7 | 0 |
"""Margin-balance and Shenwan-industry auxiliary factors.
Sources (all free via AkShare):
* Margin financing: the SSE/SZSE per-date cross-section feeds
(``stock_margin_detail_sse`` / ``stock_margin_detail_szse``) publish the
full market for a given trading date, so a backfill costs one request
per exchange per t... | fanxxxks/N | ashare_data/capital_flow.py | .py | 066c07f11dc1bbb2 | 7.15 | 1 |
"""Point-in-time fundamental pipeline (quarterly, disclosure-season aligned).
Sources (all free via AkShare):
* Eastmoney 业绩报表 (``stock_yjbb_em``, whole market per quarter): the
primary source -- cumulative year-to-date EPS/BVPS/ROE/gross margin/
revenue/profit/YoY growth. The endpoint's own announcement column
... | fanxxxks/N | ashare_data/fundamentals.py | .py | d2ac1f63779fb2c2 | 7.15 | 1 |
"""Centralized production gate runner (T0-03).
Every formal entry — training, the evaluation protocol, backtest,
simulation, archiving and the web API — is gated on the same
:class:`ProductionGateRunner`. The runner merges the historical G6/G7
gates with the strict PIT universe contract into one auditable check list:... | fanxxxks/N | ashare_data/gates.py | .py | 9f6474ad706cf869 | 7.15 | 1 |
"""Defensive JSON file I/O shared across the project.
Single implementation for two recurring concerns (previously duplicated
in portfolio/manager/run_sim/webapi/dashboard):
* :func:`read_json_safe` — a missing or corrupt file degrades to ``None``
with a logged warning instead of crashing a read-only consumer (the
... | fanxxxks/N | ashare_data/io_utils.py | .py | e1ae7fcd4071ec3e | 7.15 | 1 |
"""Pure helpers for the point-in-time universe import.
The network/DB orchestration lives in ``scripts/import_pit_universe.py``;
everything here is side-effect-free and unit-tested (the script itself
had zero test coverage before this split).
"""
from __future__ import annotations
import pandas as pd
def merge_lis... | fanxxxks/N | ashare_data/pit_import.py | .py | 8d2bd743c23bdc42 | 7.15 | 1 |
"""Data cleaning, universe filtering, and cross-sectional preprocessing."""
from __future__ import annotations
import numpy as np
import pandas as pd
def has_cross_sectional_dispersion(
values: np.ndarray, min_distinct: int = 2
) -> bool:
"""Whether a signal cross-section carries enough dispersion to trade ... | fanxxxks/N | ashare_data/processor.py | .py | e07b1a33ccd641f7 | 7.15 | 1 |
"""Shared dataclasses used across the A-share modules."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
import numpy as np
@dataclass
class BacktestResult:
equity_curve: list[float]
dates: list[str]
daily_returns: list[float]
turnover: list[float... | fanxxxks/N | ashare_data/schemas.py | .py | 7d83eb9d3028b1c1 | 7.15 | 1 |
"""AkShare data synchronisation entry point.
Usage:
python -m ashare_data.sync [--config config/ashare_config.yaml]
[--offline] [--limit N]
"""
from __future__ import annotations
import argparse
import shutil
from pathlib import Path
from typing import Any
import pandas as pd
from ... | fanxxxks/N | ashare_data/sync.py | .py | 6d1f90a4e4c27ec5 | 7.15 | 1 |
"""Shared A-share execution costs and deployment-config validation.
This module is deliberately outside the model and trading packages: reward
scoring, continuous-weight backtests and whole-lot paper matching all depend
on the same domain rules and must not grow private fee implementations.
"""
from __future__ import... | fanxxxks/N | ashare_execution.py | .py | cac13d8850e5f40b | 7.15 | 1 |
"""Run logging helpers for AlphaGPT.
The project already uses :mod:`loguru` for console logging. This module adds
two conveniences needed for reproducible runs and test sessions:
* an in-memory sink that keeps the latest formatted records;
* :func:`export_log_txt` which writes those records to a plain ``.txt`` file.
... | fanxxxks/N | ashare_logging.py | .py | f8d506fd015e6f64 | 7.15 | 1 |
"""RL admission experiment logic (T2-03).
The admission question: does RL (REINFORCE policy) beat the search
baselines — uniform random and strongly-typed GP — under **identical
unique-semantic-evaluation budgets**, across at least five independent
initializations? The pre-registered rule (recorded in the Phase-2
mea... | fanxxxks/N | ashare_model/admission.py | .py | 482c4726816fd831 | 7.15 | 1 |
"""LoopedTransformer policy model for A-share factor discovery.
The model is a single-task policy: one linear head over the formula
vocabulary plus a scalar critic. The former multi-task head (MTPHead)
was removed in MODEL_VERSION 2 — it had no multi-task supervision and
the trainer discarded its router probabilities... | fanxxxks/N | ashare_model/alphagpt.py | .py | 09ccddf5ae5763b4 | 7.15 | 1 |
"""Legacy-artifact classification and stamping (P0-04).
Pre-Phase-0 artifacts — the reward-v10 strategy
(``data/best_ashare_strategy.json``) and the protocol-v12 result
(``data/protocol_result.json``) — are older than the current code
generation and must never be mistaken for the current champion. This
module is the ... | fanxxxks/N | ashare_model/artifact_versions.py | .py | fffb3244294d345f | 7.15 | 1 |
"""AST complexity billing (T1-03).
Complexity is billed from the formula AST — the single source of truth for
formula semantics — along four auditable axes:
* ``node_count`` — every operator/feature node;
* ``max_depth`` — the deepest nesting;
* ``longest_window`` — the longest trailing window any operator looks back... | fanxxxks/N | ashare_model/complexity.py | .py | afe931eeaece8b2b | 7.15 | 1 |
"""Load A-share data from DuckDB into model-ready tensors."""
from __future__ import annotations
from pathlib import Path
import pandas as pd
import numpy as np
import torch
from ashare_data.capital_flow import build_capital_frames, build_industry_member_frame
from ashare_data.config import DataConfig, ModelConfig,... | fanxxxks/N | ashare_model/data_loader.py | .py | 932232d5991f0ee3 | 7.15 | 1 |
"""Factor diagnostics: coverage, rank-IC against the forward target and
cross-sectional correlations.
These are the objective, cheap checks that decide whether a factor family
earns its place in the vocabulary before any training budget is spent on
it. The report is written as JSON and printed as tables; the family-l... | fanxxxks/N | ashare_model/diagnostics.py | .py | 8317ee39065bd51c | 7.15 | 1 |
"""Optional MLflow tracking bridge (T1-01).
The experiment archive (``scripts/archive_run.py``, domain JSON under
``experiments/``) remains the primary, offline-first experiment record.
MLflow is an **additive, opt-in** channel: when ``mlflow`` is installed
and a tracking URI is configured (``MLFLOW_TRACKING_URI`` or ... | fanxxxks/N | ashare_model/experiment_tracking.py | .py | 9d56611768436424 | 7.15 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.