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 |
|---|---|---|---|---|---|---|
"""Configuration management with pydantic-settings."""
from pathlib import Path
from typing import Any, Literal
from pydantic import Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
from graftpunk import paths
class GraftpunkSettings(BaseSettings):
"""graftpunk application settin... | stavxyz/graftpunk | src/graftpunk/config.py | .py | 5b0fe71fa3ffe679 | 7.48 | 8 |
"""Centralized terminal output for graftpunk.
All user-facing output should go through this module. Plugins should prefer
these helpers over importing Rich directly.
Key principle: stderr for status/progress, stdout for data.
"""
from __future__ import annotations
from pathlib import Path
from rich.console import ... | stavxyz/graftpunk | src/graftpunk/console.py | .py | d4f040792948f768 | 7.48 | 8 |
"""Session encryption using Fernet symmetric encryption.
This module provides encryption/decryption for session data using
Fernet (AES-128-CBC with HMAC authentication). Keys are sourced based
on the storage backend configuration:
- GRAFTPUNK_STORAGE_BACKEND=local: Local file (~/.config/graftpunk/.session_key)
- GRAF... | stavxyz/graftpunk | src/graftpunk/encryption.py | .py | f3c58b7a98d3c95b | 7.48 | 8 |
"""Custom exceptions for graftpunk package."""
class GraftpunkError(Exception):
"""Base exception class for all graftpunk errors."""
class BrowserError(GraftpunkError):
"""Raised when browser automation or interaction fails."""
class ChromeDriverError(BrowserError):
"""Raised when ChromeDriver initial... | stavxyz/graftpunk | src/graftpunk/exceptions.py | .py | 2ad4bbc87e07c9b7 | 7.48 | 8 |
"""HAR analysis for auth flow detection and API discovery.
Analyzes HAR entries to identify:
- Authentication flows (login forms, OAuth, etc.)
- Session cookies that indicate logged-in state
- API endpoints suitable for plugin commands
"""
from __future__ import annotations
import re
from collections import Counter
... | stavxyz/graftpunk | src/graftpunk/har/analyzer.py | .py | da394edd54ac9880 | 7.48 | 8 |
"""Python plugin code generator from HAR analysis.
Generates SitePlugin subclasses from detected auth flows and API endpoints.
"""
from __future__ import annotations
import re
from textwrap import dedent
from graftpunk.har.analyzer import APIEndpoint, AuthFlow
from graftpunk.logging import get_logger
LOG = get_log... | stavxyz/graftpunk | src/graftpunk/har/generator.py | .py | 53d51f12267f0cc9 | 7.48 | 8 |
"""HAR file parser.
Parses HAR (HTTP Archive) format files into structured Python objects
for analysis.
HAR format specification: http://www.softwareishard.com/blog/har-12-spec/
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathli... | stavxyz/graftpunk | src/graftpunk/har/parser.py | .py | 0004dac5e2e6f39e | 7.48 | 8 |
"""Keepalive daemon state management.
This module provides types and functions for managing keepalive daemon state.
It is intentionally separated from CLI code to avoid circular imports.
"""
import json
import os
import tempfile
from dataclasses import asdict, dataclass, replace
from enum import StrEnum
from pathlib ... | stavxyz/graftpunk | src/graftpunk/keepalive/state.py | .py | 27677649dafcf2a3 | 7.48 | 8 |
"""Structured logging configuration using structlog."""
import os
import sys
from contextlib import contextmanager
from typing import Any
import structlog
from structlog.typing import EventDict, WrappedLogger
def add_log_level(logger: WrappedLogger, method_name: str, event_dict: EventDict) -> EventDict:
"""Add ... | stavxyz/graftpunk | src/graftpunk/logging.py | .py | 5fb754413fa548aa | 7.48 | 8 |
"""Magic link detection and extraction utilities.
Magic links are passwordless authentication URLs sent via email.
This module provides utilities for detecting and extracting tokens
from magic link URLs.
"""
import re
import time
from collections.abc import Callable
from dataclasses import dataclass, field
from typin... | stavxyz/graftpunk | src/graftpunk/mfa/magiclink.py | .py | c0394187c62cc20d | 7.48 | 8 |
"""reCAPTCHA detection and handling utilities.
This module provides utilities for detecting and handling reCAPTCHA
challenges on web pages. It supports both reCAPTCHA v2 and v3.
"""
import time
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from selenium.webdriver.remote.web... | stavxyz/graftpunk | src/graftpunk/mfa/recaptcha.py | .py | 22d4ae5b58bbd534 | 7.48 | 8 |
"""Plugin-facing observability context."""
from __future__ import annotations
import os
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
from graftpunk.logging import get_logger
if TYPE_CHECKING:
from graftpunk.observe.capture import CaptureBackend
from graftpunk.observe.s... | stavxyz/graftpunk | src/graftpunk/observe/context.py | .py | 1fb543aaa3edb675 | 7.48 | 8 |
"""Header role classification and extraction from CDP request data."""
from __future__ import annotations
from typing import Any
# Headers excluded from roles: request-specific (cookie, host, referer, origin,
# content-length, content-type), ephemeral security tokens (x-csrf-token),
# or HTTP/2 pseudo-headers (manag... | stavxyz/graftpunk | src/graftpunk/observe/headers.py | .py | b5cfa4cd10b926b0 | 7.48 | 8 |
"""Observe run lifecycle helpers shared by the CLI, BrowserSession and the login engine."""
from __future__ import annotations
import base64
import datetime
import json
import os
import urllib.parse
from collections.abc import Iterable
from typing import Any
from graftpunk.logging import get_logger
from graftpunk.ob... | stavxyz/graftpunk | src/graftpunk/observe/run.py | .py | f8fb5a95c09985c8 | 7.48 | 8 |
"""Observability data storage."""
from __future__ import annotations
import json
import re
import time
from pathlib import Path
from typing import Any
from graftpunk.logging import get_logger
LOG = get_logger(__name__)
_SAFE_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$")
class ObserveStorage:
"""File-... | stavxyz/graftpunk | src/graftpunk/observe/storage.py | .py | 19ca0c0288daea1b | 7.48 | 8 |
"""Settings-free path resolution shared by config and workstation_env.
This module is the single owner of "where is the config dir". It must stay
import-light and side-effect-free: no get_settings(), no directory creation
(GraftpunkSettings.__init__ creates directories; this module must not).
Note: pydantic-settings ... | stavxyz/graftpunk | src/graftpunk/paths.py | .py | 464a2e95ccb4fd27 | 7.48 | 8 |
"""Plugin system for graftpunk using entry points.
This module provides discovery and loading of plugins registered via
Python entry points. Plugins can provide:
- Storage backends (graftpunk.storage)
- Keepalive handlers (graftpunk.keepalive_handlers)
- Site plugins (graftpunk.plugins)
Example plugin registration i... | stavxyz/graftpunk | src/graftpunk/plugins/__init__.py | .py | 87c3d80866dc5354 | 7.48 | 8 |
"""Generic data-to-file export utilities.
Provides ``flatten_dict``, ``ordered_keys``, ``json_to_csv``,
``json_to_pdf``, and ``get_downloads_dir`` for converting lists of
flat or nested dicts into CSV and PDF files respectively, and
resolving the download directory for file-based output. Intended
for use by plugin do... | stavxyz/graftpunk | src/graftpunk/plugins/export.py | .py | 0c47e3b7fa091510 | 7.48 | 8 |
"""Merge immutable model ``locations`` with review overlay for processed items.
See ``docs/api/processed-item-review.md`` → *Entity review domains* for the JSON contract.
"""
from __future__ import annotations
import copy
from typing import Any
from api.processed_item.mention_occurrences import (
build_mention_... | localangle/backfield | apps/agate-api/src/api/processed_item/entities/location/locations_merge.py | .py | 697c2efd820e3848 | 7.52 | 10 |
"""Deterministic identity helpers for processed-item entity enrichment."""
from __future__ import annotations
import re
from typing import Any, TypeVar
EntityT = TypeVar("EntityT")
_POSITIONAL_RAW_ENTRY_ID_RE = re.compile(r"^stylebook_output:\d+$")
def source_raw_entry_id(
source_details: Any,
*,
run_... | localangle/backfield | apps/agate-api/src/api/processed_item/entities/review_identity.py | .py | 9a38e7fddc196dcc | 7.52 | 10 |
"""Node metadata for Agate UI (sync script also reads filesystem)."""
from __future__ import annotations
import json
from pathlib import Path
from fastapi import APIRouter
router = APIRouter(prefix="/nodes", tags=["nodes"])
def _metadata_dir() -> Path:
import agate_nodes
return Path(agate_nodes.__file__)... | localangle/backfield | apps/agate-api/src/api/routers/nodes.py | .py | c03a000a0f6e6321 | 7.52 | 10 |
"""会话级 VRChat 自主操作护栏。
本模块刻意仅负责授权与时效检查,不涉及感知或高频运动控制。规划器可依据此状态决定执行何种操作,而身体调度器仍是唯一负责写入 AnyaDance 动画帧的组件。
"""
from __future__ import annotations
from dataclasses import dataclass
import math
import threading
import time
from typing import Any, Callable, Mapping
from .world_state import blocking_uncertainties
ALLOWED_... | ggg233m/n.e.k.o_plugin_vrc_body | backend/autonomy.py | .py | aa6ee0ac7a9ae530 | 7.56 | 12 |
"""方向性死路记忆:只记「最近朝哪个方向试过、结果如何」。
这不是地图,也不是里程计。VRChat 不回传绝对朝向(``AngularY`` 只在移动期间产生
新样本,量级不确定且停止后不再更新),所以任何全局坐标积分都会旋转漂移且无法闭
环校正。这里刻意退一步:不建坐标系,只在方向扇区上记账,并给每条记录一个短
TTL,超时就忘。
**扇区锚在调度器虚拟 HMD 的 yaw 上,不是「相对当前朝向」。** 存的是 yaw 加请求
转角得到的记忆系角度;对外汇报时再换算回相对当前朝向。两者混用是个真实的 bug:
撞墙时记下 ``+45°``,绕行或转身之后同一个 ``+45°`` 已经指向另一堵墙,拿旧记录去
拒绝会把可走的... | ggg233m/n.e.k.o_plugin_vrc_body | backend/direction_memory.py | .py | 4fe001bcc485d300 | 7.56 | 12 |
"""Subscribe to AnyaDance's driver telemetry multicast group.
The driver multicasts one JSON datagram per event on a loopback-only group with
TTL 0, whether or not anyone is listening. Subscribing is the only way to learn
what the driver actually did with a pose command: the pose protocol itself has
no response, so a... | ggg233m/n.e.k.o_plugin_vrc_body | driver_log.py | .py | 49812b3076710aff | 7.56 | 12 |
"""拉图的滑动窗口预算。
单独成模块有两个理由。一是它必须能被测到:窗口边界的 off-by-one 是这类计数器
的经典 bug,而 ``__init__.py`` 需要 SDK 才能导入,测试里进不去。二是它要挡的
东西很具体——agent 每回合都拉一张图。一张 960 px 的 JPEG 进上下文大约十万字符
量级的 base64,循环里拉几轮就能把会话挤爆,成本也跟着走。
刻意不做令牌桶:桶允许攒额度,于是「安静十分钟」之后能一口气连拉十张,恰好是
最该拦住的那种突发。滑动窗口在任何一分钟内都只放行固定张数。
"""
from __future__ import annotations
from collecti... | ggg233m/n.e.k.o_plugin_vrc_body | frame_budget.py | .py | 1bda737fae6b6778 | 7.56 | 12 |
"""直接测试 LocalNavigator 的撞墙检测,跳过 service/autonomy 层。"""
import sys
import time
import json
from pathlib import Path
# 模拟最小的依赖环境
class FakeVrchatOscBridge:
def __init__(self):
self.packets = []
def locomotion(self, vertical, horizontal, duration_ms):
self.packets.append({
"t": time.t... | ggg233m/n.e.k.o_plugin_vrc_body | test_navigator_direct.py | .py | 4bb91dabc917eb73 | 8.06 | 12 |
#!/usr/bin/env python
"""直接测试 wander 撞墙行为,绕过 HTTP 和工具层配对检查。"""
import json
import time
from pathlib import Path
# 需要先启动后端进程,这个脚本只是客户端
import requests
BASE = "http://127.0.0.1:14670"
TOKEN = "O6say2hTx5H_-EXrH_7W-N7UQq-eeCKZ"
HEADERS = {"X-Neko-Backend-Token": TOKEN}
def snapshot():
return requests.get(f"{BASE}/s... | ggg233m/n.e.k.o_plugin_vrc_body | test_wander_collision.py | .py | 90f2eb167039f15b | 8.06 | 12 |
"""方向性死路记忆的离线验证。
这里刻意不接后端:``DirectionMemory`` 是纯逻辑,喂进实测采样就能验证。用到的数字
全部来自实机采集(tmp/px_open2、tmp/px_approach 等),不是构造的理想值。
"""
from __future__ import annotations
import unittest
from tests import _bootstrap # noqa: F401
from neko_anyadance_body.backend.direction_memory import (
DirectionMemory,
SegmentOutcome,
... | ggg233m/n.e.k.o_plugin_vrc_body | tests/test_direction_memory.py | .py | 791517b3b6222bad | 8.06 | 12 |
from __future__ import annotations
import unittest
from tests import _bootstrap # noqa: F401
from neko_anyadance_body.frame_budget import FrameBudget
class FrameBudgetTests(unittest.TestCase):
def test_calls_under_the_limit_are_allowed(self) -> None:
budget = FrameBudget(3)
for index in range(3... | ggg233m/n.e.k.o_plugin_vrc_body | tests/test_frame_budget.py | .py | b9259e64fb66ab80 | 8.06 | 12 |
"""chain._log — timestamped log + error-prefixed die helpers.
CLAUDE.md "Code style" forbids ``print(...)`` and ``sys.exit(...)``
outside of two documented exceptions in ``orchestrator/leerie.py``,
plus a third exception for this module: the chain subpackage cannot
import from the orchestrator (the package-isolation i... | enricai/leerie | chain/_log.py | .py | d172c816fba65fbc | 7.52 | 10 |
#!/usr/bin/env python3
"""Derive the per-worker-type duration distribution from a leerie state root.
N25's work order was explicit that the per-worker timeout *values* must come
from the observed distribution in the run corpus' `calls.ndjson`, not from a
guess: "a timeout set below a legitimate p99 converts a slow wor... | enricai/leerie | scripts/measure/worker_durations.py | .py | d8e43c27c7d86868 | 7.52 | 10 |
#!/usr/bin/env python3
"""scripts/remote/seed_dirty_filter.py — shared dirty-file transfer filter.
Single-owner implementation of the filter both seed-repo.sh (Fly) and
ec2-seed-repo.sh (EC2) apply to the NUL/newline-delimited candidate file
list before handing it to rsync's --files-from. Invoked from
seed-common.sh's... | enricai/leerie | scripts/remote/seed_dirty_filter.py | .py | 043b5e6d581bd26b | 7.52 | 10 |
#!/usr/bin/env python3
"""Check every schema in `SCHEMAS` against the real API's strict mode.
Run this after editing any entry in `SCHEMAS`, or after touching
`_strictify_schema`, when `--dangerously-force-strict-output` matters. It sends
each hardened schema to `api.anthropic.com` and reports which ones grammar
compi... | enricai/leerie | scripts/verify-strict-schemas.py | .py | 83d9efed82c45d60 | 7.52 | 10 |
"""The single derivation of the launcher's detect_bedrock_mode()/bedrock_preflight()
functions, extracted verbatim for test harnesses that need real implementations
rather than stubs.
Previously duplicated byte-for-byte in tests/test_bedrock_bearer_token.py and
tests/test_bedrock_mode.py — same single-owner discipline... | enricai/leerie | tests/bedrock_extract.py | .py | f0fec550ec581c5c | 7.02 | 10 |
"""The single derivation of the launcher's real `config)` case arm.
`test_config_verb.py` and `test_config_recapture.py` both extract this arm
verbatim from the shipped launcher (rather than hand-reproducing its logic,
which would be body-blind by construction — see `test_config_verb.py`'s
module docstring for the fal... | enricai/leerie | tests/config_arm_extract.py | .py | cc632a5fe5beb288 | 7.02 | 10 |
"""Shared pytest fixtures for the leerie test suite.
leerie.py is a single script (no package), so we load it once as a
module via importlib and expose it to every test via the `leerie`
fixture.
"""
from __future__ import annotations
import asyncio
import contextlib
import ctypes
import importlib.util
import os
impor... | enricai/leerie | tests/conftest.py | .py | 5279b90e9de184fb | 8.02 | 10 |
"""Shared extraction of the per-repo derived-image block from the launcher.
Single owner for `_extract_autogen_block`, previously duplicated
byte-identically in tests/test_dockerfile_autogen.py and
tests/test_dockerfile_bake_from_capture.py.
"""
def extract_autogen_block(text: str) -> str:
"""Extract the per-rep... | enricai/leerie | tests/dockerfile_autogen_extract.py | .py | d9b39c307d474fb1 | 7.02 | 10 |
"""Rebuilds the 2026-07-19 incident's payload shape from shape.json.
The real task file (an internal product audit, 51,142 bytes) is
deliberately not committed here. This module reconstructs a synthetic,
shape-matched stand-in from the measured per-field byte distribution in
`shape.json` — same total sizes, same subta... | enricai/leerie | tests/fixtures/incident_2026_07_19/generate.py | .py | 8327c9ccd549451c | 8.02 | 10 |
"""Shared fake-`flyctl` test double for Fly.io remote-script tests.
Mirrors tests/ec2_stub.py's precedent on the EC2 side: rather than five
independently reimplemented `_make_fake_flyctl` bash builders each
re-parsing the same `-C`/`auth`/`machine`/`ssh` flags, callers supply only
the routing logic that differs for th... | enricai/leerie | tests/fly_stub.py | .py | bd3f20939cb5fa08 | 7.02 | 10 |
"""Single owner of `_run_argv` extraction from the launcher.
`tests/test_launcher_state_mount.py` and `tests/test_launcher_env_forwarding.py`
both need the real `nerdctl run` argv array construction, extracted verbatim
from `leerie` rather than reproduced — the exact hazard
`tests/test_no_duplicate_launcher_blocks.py`... | enricai/leerie | tests/launcher_argv_extract.py | .py | 2c1221754b24aa1d | 7.02 | 10 |
"""The single derivation of the launcher's orchestrator launch blocks.
Each remote runtime builds its own `child_env = dict(os.environ)` inside its own
unquoted `<<PY` launch heredoc. Several guards need that set — the
`LEERIE_COMMIT` forwarding check in `test_leerie_commit.py`, and the
stray-`${...}` and backtick sca... | enricai/leerie | tests/launcher_blocks.py | .py | 8bcef385870dcb57 | 7.02 | 10 |
"""Shared launcher-text extraction helpers for the --log-file wiring tests
(test_log_file_wiring.py, test_log_file_persistence.py). Both files
independently defined byte-identical `_extract_setup_block`,
`_extract_invocation`, and `_extract_reap_tail` -- this module is their
single owner, following the `launcher_blocks... | enricai/leerie | tests/log_file_extract_helpers.py | .py | 8549acc4dc825091 | 8.02 | 10 |
"""Behavioural probe for `prompts/planner.md`'s `extent` decision rules.
**Not a test module.** `pytest.ini` sets `python_files = test_*.py`, so this is
never collected — same arrangement as
`tests/fixtures/incident_2026_07_19/generate.py`. It spawns real `claude -p`
workers and costs money; run it by hand.
## Why th... | enricai/leerie | tests/manual/planner_fence_probe.py | .py | d0eac40cb6fc0d5e | 8.02 | 10 |
"""Shared _extract_block helper for the per-repo image test harnesses.
Used by test_launcher_per_repo_image.py, test_fly_per_repo_image.py, and
test_build_repo_image.py, whose own copies were verified byte-identical
(AST-diff, body minus docstring). test_no_verify_push_env_seed.py and
test_resolve_log_file.py define t... | enricai/leerie | tests/repo_image_block_extract.py | .py | 00e7463fa7a80468 | 7.02 | 10 |
"""Shared test helpers reused across tests/*.py.
Single-owner discipline (see CLAUDE.md's `launcher_blocks.py`/`ec2_stub.py`
precedent): each helper here previously existed as byte-identical copies in
every consuming test file, which is the drift risk this module exists to
remove.
"""
from __future__ import annotation... | enricai/leerie | tests/stub_helpers.py | .py | e66f6b37350ff932 | 8.02 | 10 |
"""Tests for _read_toml_key().
The hand-rolled leerie.toml line parser used by both
resolve_source_of_truth() and resolve_models(). Both resolvers depend
on its quoting/comment/whitespace behavior, so it gets dedicated
coverage.
"""
from __future__ import annotations
import pytest
def test_missing_file_returns_none... | enricai/leerie | tests/test__read_toml_key.py | .py | 70befdb14f78293c | 8.02 | 10 |
"""A waiver must not delete the finding it waives.
Both accept verbs are reached from a `die()` that tells the operator to consult
`state.json`. `accept-blocked` then set `subtask_status[sid] = "complete"`,
popped the `blocked` registry and wrote nothing else — so afterwards a waived
subtask was byte-indistinguishable... | enricai/leerie | tests/test_accept_verbs_keep_their_evidence.py | .py | 63e91b7580a26c65 | 8.02 | 10 |
"""Tests for the artifact-passing contract between subtasks.
Covers DESIGN §5 *Artifact passing between subtasks*: a producer
subtask returns structured deliverables on its result's `artifacts`
field; the orchestrator persists them under
`.leerie/runs/<id>/artifacts/<sid>.json`; consumer subtasks whose
predecessor gra... | enricai/leerie | tests/test_artifact_passing.py | .py | 2e96c7f14e0d5d82 | 8.02 | 10 |
""""Could not measure" is a third state, distinct from RED, and it is not clean.
An exit code cannot distinguish "the command ran and failed" from "the command
never produced a verdict". Both causes of the latter are authored by leerie's own
environment rather than by the diff — the runner is absent from this tree, or... | enricai/leerie | tests/test_axis_unmeasurable.py | .py | 1c192502387859bd | 8.02 | 10 |
"""Regression guard for the base image's Chromium provisioning.
feedback #64 (shipped in #23 / f31d650) bakes Chromium + chromedriver and
the rootless-container Chrome flags into the base ./Dockerfile so browser
tests (Selenium/Capybara/etc.) work without runtime setup — see
docs/IMPLEMENTATION.md "Browser-based testi... | enricai/leerie | tests/test_base_dockerfile_chromium.py | .py | 317882a72ab868fb | 8.02 | 10 |
"""Tests for Fix 2: clear stale blocked[sid] when a subtask completes.
The `_settle_subtask` function must pop the sid from `st.data["blocked"]`
when the final written status is "complete", so a resume-that-completes
doesn't leave a contradictory blocked record in state.json.
"""
from __future__ import annotations
im... | enricai/leerie | tests/test_blocked_clear_on_complete.py | .py | a6c63fac4087cf26 | 8.02 | 10 |
"""Configuració de l'aplicació, llegida de variables d'entorn o del fitxer .env."""
from functools import lru_cache
from pathlib import Path
from typing import Literal
from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy import URL
# El .env viu a l'arrel del repositori (un nivell per sobre... | Softcatala/arena-cat | backend/app/config.py | .py | 8f00359609db53fd | 7.66 | 20 |
"""Infraestructura de SQLAlchemy: classe base declarativa i fàbriques de motor i sessions.
El motor fa servir el rol d'aplicació amb permisos limitats (database_url) i només
es crea quan algú demana get_engine().
"""
from collections.abc import Generator
from functools import lru_cache
from sqlalchemy import Engine,... | Softcatala/arena-cat | backend/app/db.py | .py | 2ffd8c26696cadb5 | 7.66 | 20 |
"""Dependències d'autenticació reutilitzables per als endpoints de FastAPI.
Exposa àlies `Annotated` per injectar la sessió de base de dades i l'usuari
autenticat (verificat o no) directament a la signatura dels handlers.
"""
from typing import Annotated
from fastapi import Cookie, Depends, HTTPException
from sqlalc... | Softcatala/arena-cat | backend/app/deps.py | .py | bb2116c36d8698fe | 7.66 | 20 |
from fastapi import HTTPException
# Codi que el frontend fa servir per distingir aquest cas d'una sessió caducada:
# el 401 és del token de tasca (curt i d'un sol ús), no de la cookie de sessió,
# així que no ha de forçar cap desconnexió.
TASK_TOKEN_INVALID = "task_token_invalid"
class TaskTokenError(HTTPException):... | Softcatala/arena-cat | backend/app/exceptions.py | .py | 69408d69b6a2d1c5 | 7.66 | 20 |
"""Tria la propera tasca a mostrar a un avaluador.
`select_next_task` retorna un diccionari amb el prompt, les dues respostes
i la informació necessària perquè la microservei la mostri a l'usuari.
Estratègia per defecte: **quota-balanced randomization**.
- Considera cada combinació (prompt, parella ordenada de model... | Softcatala/arena-cat | backend/app/ranking/sampler.py | .py | b8674e6f18c14545 | 7.66 | 20 |
from fastapi import APIRouter, Cookie, Response
from app.config import get_settings
from app.deps import CurrentUser, DbSession, OptionalUser
from app.schemas import (
DeleteAccountRequest,
DeleteAccountResponse,
ExportDataResponse,
LoginRequest,
LoginResponse,
LogoutRequest,
LogoutResponse... | Softcatala/arena-cat | backend/app/routes/auth.py | .py | 9a19d782034ca490 | 7.66 | 20 |
from fastapi import APIRouter
from app.deps import CurrentVerifiedUser, DbSession
from app.schemas import SkipTaskRequest, SkipTaskResponse, TaskProgressResponse, TaskResponse
from app.services import task_service
router = APIRouter()
@router.get("/task")
def get_task(
current_user: CurrentVerifiedUser,
db:... | Softcatala/arena-cat | backend/app/routes/task.py | .py | ae9178fa01ea0035 | 7.66 | 20 |
import base64
import hmac
import json
import secrets
from datetime import UTC, datetime, timedelta
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from app.config import get_settings
_password_hasher = PasswordHasher()
TASK_VOTE_WAIT_SECONDS = 10
def _sign_payload(payload: dict,... | Softcatala/arena-cat | backend/app/security.py | .py | 82d086c9bcc640b6 | 7.66 | 20 |
import logging
from datetime import UTC, datetime, timedelta
from fastapi import HTTPException
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session as OrmSession
from app.config import get_settings
from app.models import Session, User, Vote
from app.schemas import... | Softcatala/arena-cat | backend/app/services/auth_service.py | .py | 2a79f0a0d6e059b8 | 7.66 | 20 |
from fastapi import HTTPException
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.models import Category
from app.ranking.confidence import assess_confidence
from app.ranking.ranking import compute_ranking
def _confidence_response(confidence: dict) -> dict:
"""Adapta les mètriques inter... | Softcatala/arena-cat | backend/app/services/ranking_service.py | .py | 6657784a5a8e4517 | 7.66 | 20 |
from collections import defaultdict
from itertools import combinations
from fastapi import HTTPException
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.exceptions import TaskTokenError
from app.models import Category, Response, TaskSkip, User, Vote
... | Softcatala/arena-cat | backend/app/services/task_service.py | .py | c6cb4e53e7e42e21 | 7.66 | 20 |
"""add users and sessions
Revision ID: 5bcc14a623b7
Revises: 94019e30371a
Create Date: 2026-07-17 21:32:18.987135
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "5bcc14a623b7"
down_revision: str | Sequence[str] | None = "94019e30371a"
branch_labels: str | Se... | Softcatala/arena-cat | backend/migrations/versions/5bcc14a623b7_add_users_and_sessions.py | .py | ac4cf52c3c1d942f | 7.66 | 20 |
"""Càrrega de tasques fictícies (mock) a la base de dades.
Insereix prompts i respostes sintètiques perquè el flux de `GET /api/task` i
`POST /api/vote` es pugui provar sense dependre de la càrrega d'inferències
reals. Cada prompt rep almenys dues respostes de models diferents, de manera
que el sampler pot formar pare... | Softcatala/arena-cat | backend/scripts/seed_mock_tasks.py | .py | 2a024922369cdf4c | 7.66 | 20 |
"""Configuració dels tests: motor cap a la base de dades de tests i sessió aïllada per test.
Cada test s'executa dins d'una transacció que es desfà al final (rollback),
de manera que queden aïllats entre si.
"""
from datetime import UTC, datetime
import pytest
from fastapi.testclient import TestClient
from sqlalchem... | Softcatala/arena-cat | backend/tests/conftest.py | .py | 6ff0aeafef8c5e90 | 8.16 | 20 |
"""Tests de la càrrega idempotent de prompts i inferències (contra PostgreSQL real)."""
import sys
from pathlib import Path
import pytest
import yaml
from sqlalchemy import func, select
from app.models import Prompt, Response
# L'script viu a scripts/ (projecte arrel), fora del paquet backend.
sys.path.insert(0, st... | Softcatala/arena-cat | backend/tests/test_carrega_inferencies.py | .py | a45e8813709a2cf2 | 7.16 | 20 |
"""Tests de `app.ranking.confidence.assess_confidence`.
Comprovem que el bootstrap clusteritzat amb etiquetes fixes és calibrat:
declara estable un rànquing realment estable i rebutja un cas de coin-flip.
"""
from __future__ import annotations
from sqlalchemy import select
from app.models import Category, Prompt, R... | Softcatala/arena-cat | backend/tests/test_confidence.py | .py | 331d1f27941aeee4 | 8.16 | 20 |
"""Tests de `app.ranking.sampler.select_next_task`."""
from __future__ import annotations
from collections import Counter
from datetime import UTC, datetime
from sqlalchemy import select
from app.models import Category, Prompt, Response, TaskSkip, User, Vote, Winner
from app.ranking.sampler import select_next_task
... | Softcatala/arena-cat | backend/tests/test_sampler.py | .py | bcce862bd42ff823 | 8.16 | 20 |
import base64
import json
from app.security import (
create_email_verification_token,
create_task_token,
verify_task_token,
)
def test_verify_task_token():
"""Prova de verificar un token vàlid."""
token = create_task_token(prompt_id=1, response_a_id=2, response_b_id=3, user_id=7)
payload = ve... | Softcatala/arena-cat | backend/tests/test_security.py | .py | b02c28a49e6b1f8f | 8.16 | 20 |
"""Càrrega idempotent de prompts i inferències a la base de dades.
Llegeix els prompts versionats a ``data/prompts/<version>/*.txt`` (text pla, on
el nom del fitxer és el codi) i les inferències a
``data/inferencies/<version>/<model_id>/*.yaml``, i en fa *upsert* a les taules
``prompts`` i ``responses``. La clau natur... | Softcatala/arena-cat | scripts/carrega_inferencies.py | .py | 75309f86ffc17393 | 7.66 | 20 |
"""
Shared layout helpers for RedForge workspace pages.
"""
from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
QFrame,
QHBoxLayout,
QLabel,
QPushButton,
QSplitter,
QVBoxLayout,
QWidget,
)
def make_page_header(title: str) -> tuple[QLabel, QVBoxLayout, QWidget]:
"""
Retur... | arpittoppo/RedForge | src/redforge/ui/pages/_page_utils.py | .py | d69416dd3635405b | 7.54 | 11 |
"""Mental Omega APWorld options."""
from dataclasses import dataclass
from Options import FreeText, OptionDict, PerGameCommonOptions
class LauncherSettings(OptionDict):
"""Readable launcher options mirrored by the signed run manifest."""
display_name = "Launcher Settings"
default = {}
class RunManife... | Heinki/Mental-Omega-Randomizer | Archipelago/APWorld/mental_omega/options.py | .py | febe98c0d3066aac | 7.42 | 6 |
"""Portable launcher-settings documents for sharing identical setups."""
from pathlib import Path
from randomizer.core.storage import atomic_write_json, read_json_object
from .player import (
DEFAULT_CONFIG,
deep_copy,
deep_merge,
migrate_loaded_config,
)
PORTABLE_SETTINGS_FORMAT = 'mental-omega-ra... | Heinki/Mental-Omega-Randomizer | randomizer/config/portable.py | .py | ee035a2519ec4102 | 7.42 | 6 |
"""Load editable static configuration from source or packaged data."""
import hashlib
import json
import shutil
from copy import deepcopy
from functools import lru_cache
from pathlib import Path
from randomizer.config.schema import (
REQUIRED_SECTIONS,
StaticConfigError,
validate_sections,
)
from randomiz... | Heinki/Mental-Omega-Randomizer | randomizer/config/static.py | .py | 1bde5a0f78f1f91b | 7.42 | 6 |
"""Typed access to editable reward, clone, and assistance tuning."""
from functools import lru_cache
from randomizer.config.static import load_static_config
_CONFIG = load_static_config('rewards/tuning.json')
BUFF_EFFECTS = _CONFIG['buff_effects']
CLONE_POLICY = _CONFIG['clone_policy']
CLONE_UI_DESCRIPTION = str(
... | Heinki/Mental-Omega-Randomizer | randomizer/config/tuning.py | .py | 3483ecda4447fef8 | 7.42 | 6 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/compose.py | .py | 95116dc7623e17da | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/conditions.py | .py | 9f73ba1536debd5a | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/container.py | .py | 521cea85802b81b8 | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/context.py | .py | f4ca04b319bf5009 | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/exceptions.py | .py | 0685648371e40167 | 7.52 | 10 |
# api_ref_gen::ignore
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | tandemdude/linkd | linkd/ext/_common.py | .py | 03e23653e8acc8b2 | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/ext/connectrpc.py | .py | 17f29540b0ae526b | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/ext/fastapi.py | .py | 223be387b6efc428 | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/ext/grpc.py | .py | da926c5fab95f7bf | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/ext/quart.py | .py | 4fdd33b59e1ee9ac | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/ext/starlette.py | .py | ee71199169043a06 | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/graph.py | .py | 76f84c2e25e2ac2f | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/registry.py | .py | ff38c973321ee957 | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | linkd/utils.py | .py | 5e37a0fb5293224c | 7.52 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | tests/test_conditions.py | .py | 89e78d8198647bcb | 7.02 | 10 |
# -*- coding: utf-8 -*-
# Copyright (c) 2025-present tandemdude
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | tandemdude/linkd | tests/test_graph.py | .py | a178afd81376df05 | 7.02 | 10 |
import sys
from itertools import count
from typing import List
import os.path as osp
import yaml
from ament_index_python.packages import get_package_share_directory
counter = count(0)
def get_unique_name(name: str) -> str:
"""Returns a unique name
Parameters:
----------
`name`: Base name
Return... | Sophia-AI-formula-team/aiformula_sophia | aiformula/common/common_python/common_python/launch_util.py | .py | 672dbaaf388d2006 | 7.48 | 8 |
import os
from typing import List, Tuple
def add_directory(package_name: str, target_directory: str, data_files: List[Tuple[str, List[str]]]) -> None:
"""Add `target_directory` to `data_files`
Parameters:
----------
`package_name`: Package name to build
`target_directory`: Directory to copy to in... | Sophia-AI-formula-team/aiformula_sophia | aiformula/common/common_python/common_python/setup_util.py | .py | 6015be69442f3503 | 7.48 | 8 |
import rclpy
from rclpy.node import Node
import numpy as np
from geometry_msgs.msg import Pose2D
TARGET_SPEED_MPS = 2.0
PATH_SPACING_EPSILON_M = 1.0e-6
class KalmanFilterNode(Node):
def __init__(self):
super().__init__('kalman_filter_node')
# === 1) 订阅和发布 Pose2D 数据 ===
self.pose_subscrip... | Sophia-AI-formula-team/aiformula_sophia | aiformula/perception/kalman_filter/kalman_filter/kalman0225.py | .py | 4310eb5b97124e44 | 7.48 | 8 |
import rclpy
from rclpy.node import Node
import numpy as np
from geometry_msgs.msg import Pose2D
TARGET_SPEED_MPS = 2.0
PATH_SPACING_EPSILON_M = 1.0e-6
class DataProcessingNode(Node):
def __init__(self):
super().__init__('data_processing_node')
# === 1) 订阅和发布 Pose2D 数据 ===
self.pose_subs... | Sophia-AI-formula-team/aiformula_sophia | aiformula/perception/kalman_filter/kalman_filter/withoutkalman.py | .py | b0a278d172e9f2ef | 7.48 | 8 |
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
import numpy as np
from geometry_msgs.msg import Pose2D
from std_msgs.msg import Bool
TARGET_SPEED_MPS = 2.0
PATH_SPACING_EPSILON_M = 1.0e-6
class DataProcessingNode(Node):
def __init__(self):
super().__init__('data_processing_node')
... | Sophia-AI-formula-team/aiformula_sophia | aiformula/perception/kalman_filter/kalman_filter/withoutkalman_0312.py | .py | 303f76a12e011004 | 7.48 | 8 |
"""Shared conservative identity rules for title/year deduplication."""
from __future__ import annotations
import re
import unicodedata
from collections.abc import Iterable, Mapping
def normalize_edition_identity(value: object) -> str:
text = str(value or "").strip()
if not text:
return ""
folded... | helmerzNL/DiscVault | app/backend/dedup_identity.py | .py | e1e29c01ee600897 | 7.48 | 8 |
"""API access token helpers for the DiscVault Next backend.
This module owns the API token permission catalogs and the token payload
helpers used by the profile API access surface. The helpers are extracted from
``next_app.py`` so that domain modules can reuse them without importing the
oversized application module. `... | helmerzNL/DiscVault | app/backend/next_api_token.py | .py | 85cdf1ab6cd146e4 | 7.48 | 8 |
"""Permanent removal of artwork that has sat in the trash long enough.
Hiding a poster or backdrop marks its `entity_media` link `deleted_at` and sets
a `purge_after` from the configured retention window; this module is what
finally deletes the link, the `media_assets` row nothing points at any more, and
the local fil... | helmerzNL/DiscVault | app/backend/next_artwork_trash.py | .py | 2274e2bc8a284e0a | 7.48 | 8 |
"""Audit activity helpers for the DiscVault Next backend.
This module owns audit-event persistence, request-IP resolution, API/MCP audit
metadata, and the profile-facing API audit filters. The helpers are extracted
from ``next_app.py`` so that domain modules can reuse them without importing the
oversized application m... | helmerzNL/DiscVault | app/backend/next_audit.py | .py | a08f1273413dc447 | 7.48 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.