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 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python3
"""Утренний бриф: готовый контекст дня в графе — ДО первого вопроса.
Sleep-time-подход: ночью (после Tier3-ревизии) собрать из ГОТОВЫХ строк
графа файл `_Сегодня.md` — что решили на последних встречах, какие
поручения и открытые вопросы висят, какие ядра живые, что Tier3 пометил
на сведение. Утр... | charoiteai/Charoite_audio | scripts/morning_brief.py | .py | 0c2c3b6a76dc33fc | 7.48 | 8 |
"""Ночной облачный проход по ядрам: Opus смотрит то, что локальной модели не по зубам.
Запускается из nightly.sh ПОСЛЕ tier3 (читает уже причёсанные ядра).
Ничего НЕ правит — пишет отчёт-рекомендации в граф:
`Служебное_ночная_ревизия_YYYY-MM-DD.md` (противоречия между ядрами,
протухшие факты, кандидаты на слияние, пот... | charoiteai/Charoite_audio | scripts/nightly_claude_cores.py | .py | c56296b369f5e666 | 7.48 | 8 |
#!/usr/bin/env python3
"""Протокол встречи одной командой: решения, поручения, открытые вопросы.
После встречи в папке архива лежат Саммари и Минутки. Отдать их участникам
было нечем: человек открывал Obsidian, выделял текст руками, вычищал
вики-ссылки и вставлял в письмо — после каждой встречи. Здесь то же самое
дела... | charoiteai/Charoite_audio | scripts/protocol.py | .py | 5fc31f03acba8e53 | 7.48 | 8 |
#!/usr/bin/env python3
"""Подписать манифест релиза ключом владельца и приложить подпись к релизу.
Якорь подлинности обновлений, НЕЗАВИСИМЫЙ от GitHub (карточка №24):
контрольная сумма лежит рядом с архивом, и кто дотянулся до релиза
(утёкший токен CI, компрометация аккаунта), тот подписал бы и её. Этот
ключ в CI не б... | charoiteai/Charoite_audio | scripts/sign_release_manifest.py | .py | 89265abcf54294d2 | 7.48 | 8 |
#!/usr/bin/env python3
"""CLI ревизии ядер (ядро — src/tier3.py, там же вся логика и пороги).
.venv/bin/python scripts/tier3_cores.py # текущий граф, только отчёт
.venv/bin/python scripts/tier3_cores.py --mark # обратимые пометки в графе
.venv/bin/python scripts/tier3_cores.py --appl... | charoiteai/Charoite_audio | scripts/tier3_cores.py | .py | 92a9f6a3ebe086d6 | 7.48 | 8 |
#!/usr/bin/env python3
"""Ждём, пока машина освободится от разбора встреч.
Ночной цикл и разбор встречи делают одно и то же — гоняют локальную модель, —
и на одной машине не помещаются. 12.08 они совпали: транскрипция, ревизия
ядер и сборка досье одновременно, свободной памяти 14 ГБ из 64 при 17 ГБ уже
в компрессоре. ... | charoiteai/Charoite_audio | scripts/wait_for_idle.py | .py | ea9731573bde3719 | 7.48 | 8 |
"""Поручения из минуток — в формат, который видит приложение.
Промпт просит модель писать поручение чекбоксом («- [ ] **Имя** — что — срок»),
и модель честно выдаёт имя, суть и срок. Но оборачивает всё в свой markdown:
* **- **Дмитрий** — подготовить демонстрацию. — **Срок: завтра**.**
Скобок `[ ]` здесь уже н... | charoiteai/Charoite_audio | src/action_items.py | .py | 38bdf09c039209a9 | 7.48 | 8 |
"""Кто занимает машину: общие сигналы для ночи, мутатора и прочих тяжеловесов.
Ночь 23→24.08: мутатор делил локальную модель со встречей и ночным циклом —
досье поймали 35 ReadTimeout по 300 с, прогон оборвали руками. Здесь общий
словарь занятости: живая запись, разбор встреч, мутация тестов, ночной цикл.
Лок мутации... | charoiteai/Charoite_audio | src/busy_signals.py | .py | f3372d5be153f6f9 | 7.48 | 8 |
"""Где лежат рабочие данные Чароита.
Раньше каждый модуль выводил корень из собственного положения:
ROOT = pathlib.Path(__file__).resolve().parent.parent
Пока код и данные жили в одной папке (склонированный репозиторий), это
работало. С вложенным в приложение python-контуром код переехал внутрь
бандла — а бандл ... | charoiteai/Charoite_audio | src/charoite_paths.py | .py | c7f9d995178b1090 | 7.48 | 8 |
"""Какая облачная модель работает на каком шаге. Одно место вместо литералов.
Разрешение на облако выдаёт src/privacy.py, здесь — только выбор модели, когда
разрешение уже есть. Разделение не косметическое: у тумблера цена — приватность,
у модели — качество и время ответа, и путать их не стоит.
Дефолты были разбросан... | charoiteai/Charoite_audio | src/cloud.py | .py | 8ad4f1360841a7dd | 7.48 | 8 |
"""Рецепт вместо трейсбека, когда скрипт запущен не тем интерпретатором.
Зависимости живут в `.venv` — так велит README. Но набрать `python3 scripts/…`
человек будет всё равно: по привычке, по копипасту из статьи, из старой версии
документации. Ответом на это была стена трассировки:
Traceback (most recent call la... | charoiteai/Charoite_audio | src/deps.py | .py | 39f60b2c9f50e11b | 7.48 | 8 |
"""Диаризация записи встречи: кто из НЕСКОЛЬКИХ голосов что сказал, с именами.
Запуск: .venv/bin/python src/diarize.py <запись.wav|m4a> [--channel right] [ЧЧММ]
Конвейер: sherpa-onnx (pyannote-сегментация + eres2net-эмбеддинги, чистый ONNX,
всё локально) → сегменты Speaker N → GigaAM по сегментам → qwen сопоставляет
... | charoiteai/Charoite_audio | src/diarize.py | .py | 9901d04e8a8b5e08 | 7.48 | 8 |
"""Голосовая заметка и дневник: запись до EOF stdin → GigaAM STT → qwen
причёсывает → .md в граф → remember в Чароит.
Режимы:
(без флагов) заметка → Заметки/<дата>_<слаг>.md (заголовок, задачи)
--diary дневник → <diary_dir>/YYYY-MM-DD.md, дозапись секцией
«## HH:MM»: голос от первого лица, и... | charoiteai/Charoite_audio | src/dictate_note.py | .py | a1b5405ec8f65105 | 7.48 | 8 |
"""Сверка фактических якорей документа со стенограммой.
Замер 22.07 на реальной встрече: из четырёх прогонов минуток один приписал
задачу TASK 3242, которой в стенограмме нет ни разу. Внешне такой пункт
неотличим от настоящего — та же формулировка, тот же тон.
Номера задач и даты — вещи буквальные: если они прозвучал... | charoiteai/Charoite_audio | src/fact_check.py | .py | 77afb6f55704b3bf | 7.48 | 8 |
"""Файловые локи: два общих приёма — проба и захват (партия D-П6).
Пять контуров держат flock по-своему, и это НЕ дубль: проба ночного
фона, отказ мутатора, очередь пересборок (блокирующий EX), deadline
замка графа и одиночность демона — разные политики. Дословно
дублировались только два приёма, они и сведены сюда. Вс... | charoiteai/Charoite_audio | src/file_locks.py | .py | c62cac602a365dd5 | 7.48 | 8 |
"""Где лежат графы — одно место решения для скриптов ночного контура.
Vault — это папка НАД графом: `sufler.graph_dir` указывает на ~/Vault/Работа,
а ночью надо обойти и ~/Vault/Личное. Смотрим туда и в стандартный
iCloud-Obsidian: одного захардкоженного пути мало для машины, где Obsidian
живёт не в iCloud, — а раньше... | charoiteai/Charoite_audio | src/graphs.py | .py | e126ff76e3cab0a4 | 7.48 | 8 |
"""Профиль установки: что эта машина тянет, а что на ней выключено.
Модели выбираются по объёму памяти (`ModelPresetPolicy` в приложении), но
одних моделей мало: на восьмигигабайтной машине рядом с STT и системой не
живут все контуры сразу. Раньше об этом была только фраза в описании
пресета — «Граф знаний выключен», ... | charoiteai/Charoite_audio | src/install_profile.py | .py | c4323609b92dd367 | 7.48 | 8 |
"""Живая встреча важнее фона: один общий признак «суфлёр сейчас слушает».
Факт 18.08: пересборка 18-часовой записи держала тяжёлую модель промптами по
12-13 тыс. токенов, а Ollama с MLX-раннером на занятой модели отвечает
503 за четверть секунды вместо очереди — подсказки живой встречи 45 минут
подряд падали с `[LLM: ... | charoiteai/Charoite_audio | src/live_gate.py | .py | 2756afd04e0a0954 | 7.48 | 8 |
"""内置告警引擎 — 无需外部 Prometheus + AlertManager。
为独立部署提供轻量告警能力:规则评估 + 冷却抑制 + 日志触达。
"""
import logging
import time
from typing import Callable
log = logging.getLogger("imagefree_api.alerting")
class AlertRule:
"""一条告警规则。
参数:
name: 规则名(唯一标识)
severity: 严重级别(warning / critical)
message: 告警描述... | lza6/Image-to-2api | api/alerting.py | .py | c96c4719f2fe331e | 7.66 | 20 |
"""不可变审计日志(仅追加),记录管理操作、鉴权失败、provider 状态变更等。"""
import json
import logging
from datetime import datetime, timezone
from pathlib import Path
log = logging.getLogger("imagefree_api.audit")
class AuditLog:
"""不可变审计日志。仅追加写入,永不修改已有记录。"""
def __init__(self, path: str = "data/audit.log"):
self._path = path
... | lza6/Image-to-2api | api/audit.py | .py | 63e6b135bfb81ae7 | 7.66 | 20 |
"""v4.4: 全局 API Key 鉴权(防滥用)。
设计:
- 固定静态 Key 池由环境变量 IF_API_KEYS 注入(逗号分隔);空 = 开放模式。
- 支持三种传递方式(按优先级):Authorization: Bearer <key> / X-API-Key: <key> / ?api_key=<key>。
- v4.4.2:全站写操作(生图 /v1/generate*、图生图 /v1/edit、聊天 /v1/chat/*、/v1/messages)统一强制 Key。
- 只读端点(/v1/stats、/v1/providers、/v1/models、/v1/meta、/v1/healthz 等)与运维端点保持公... | lza6/Image-to-2api | api/auth.py | .py | ce41fdf07181631b | 7.66 | 20 |
"""config 子模块公共辅助:环境变量布尔/字符串/整数解析。"""
from __future__ import annotations
import os
def _env_bool(name: str, default: str = "0") -> bool:
"""环境变量布尔解析:'1'/'true'/'yes'/'on' → True;空字符串视为 False。"""
return os.getenv(name, default).strip().lower() in {"1", "true", "yes", "on"}
def _env_str(name: str, default: s... | lza6/Image-to-2api | api/config/base.py | .py | 27a064e0c3b18813 | 7.66 | 20 |
"""SolverSettings 子配置。"""
from __future__ import annotations
from typing import Any
from pydantic import BaseModel, field_validator
class SolverSettings(BaseModel):
"""CF solver / Turnstile 求解配置组。"""
base_url: str = "https://imagefree.net"
sitekey: str = "0x4AAAAAACE-XLGoQUckKKm_"
cf_solver_url: str... | lza6/Image-to-2api | api/config/solver.py | .py | 87fe6a64e74fb01a | 7.66 | 20 |
"""SQLite 动态 IP 封禁与风控规则存储(ISSUE-02)。
字段契约:
- ip: 主键 IP 地址
- block_type: 'block' (全量 403 拦截) | 'daily_limit' (每日调用上限拦截)
- daily_limit: 每日最大允许调用次数(当 block_type='daily_limit' 时生效,默认 1)
- reason: 封禁或限流原因
- expire_at: 过期时间戳(0 或 NULL 表示永久有效)
- created_at: 创建时间戳
- updated_at: 更新时间戳
"""
from __future__ import annotations
imp... | lza6/Image-to-2api | api/db/ip_blocklist_store.py | .py | 75ade465d23b6855 | 7.66 | 20 |
"""SQLite 行级原子租约锁存储(替代文件系统 PID 锁)。
设计:edit_leases 表,key 为 PRIMARY KEY。
- acquire:单条 SQL 内原子完成「检查过期 + 覆盖写入」,SQLite 写事务串行保证排他。
- renew:持锁者按 token 续租(延长 expires_at)。
- release:持锁者按 token 释放(DELETE WHERE key=? AND token=?)。
- 异常宕机:无续租 → expires_at 过期 → 新 acquire 自动覆盖,杜绝僵尸死锁。
"""
from __future__ import annotations
import ... | lza6/Image-to-2api | api/db/lease_store.py | .py | 73159c37943417b4 | 7.66 | 20 |
"""QueueDB 类(已废弃,请使用 QueueStore)+ task_to_public 函数。"""
from __future__ import annotations
import logging
import threading
import time
log = logging.getLogger("db")
class QueueDB:
"""持久化队列 DB(同步实现,**已废弃**)。
⚠️ 此实现使用同步 sqlite3,会阻塞事件循环。
请使用 `api.db.queue_store.QueueStore`(异步 aiosqlite)替代。
保留仅为兼容已有引用... | lza6/Image-to-2api | api/db/queries.py | .py | f2e89d25af67dc66 | 7.66 | 20 |
"""持久化任务队列存储(WAL 模式,task_queue 表)。
设计在 api/db/__init__.py 的 QueueDB 之上或替代之,独立于 imagefree.db。
"""
from __future__ import annotations
import asyncio
import logging
import os
import time
import aiosqlite
log = logging.getLogger("db.queue_store")
_SCHEMA = """
CREATE TABLE IF NOT EXISTS task_queue (
task_id TEXT P... | lza6/Image-to-2api | api/db/queue_store.py | .py | 0cb986c1e6373427 | 7.66 | 20 |
"""磁盘日志落盘(P13):按天滚动文件日志,保留 N 天。
/v1/logs 仍从内存环形缓冲读取(log_buffer.py),本模块只做持久化补充:
root logger 追加 TimedRotatingFileHandler,跨重启可查。
"""
from __future__ import annotations
import logging
import os
from logging.handlers import TimedRotatingFileHandler
_LOG_FORMAT = "%(asctime)s %(levelname)s %(name)s %(message)s"
def setu... | lza6/Image-to-2api | api/disk_logger.py | .py | 5a3ac2f8a10ae564 | 7.66 | 20 |
"""统一错误响应格式和分层错误码体系。
分层格式:CATEGORY.NNN(如 AUTH.001、SYS.002)
支持多语言错误消息(zh/en)和动态参数插值。
兼容旧版字符串错误码(如 "QUEUE_FULL" → "SYS.002")。
用法:
raise AppError(ErrorCodes.QUEUE_FULL, "队列已满,请稍后重试", status_code=429)
return error_response(ErrorCodes.QUEUE_FULL, "队列已满", status_code=429)
msg = get_error_message(ErrorCodes.QUEU... | lza6/Image-to-2api | api/errors.py | .py | 4f0869a2b41bd5d9 | 7.66 | 20 |
"""IP 地理位置解析与多协议代理链接生成工具库。
功能:
1. 本地轻量离线 IP 段/前缀 + 内置中文国家映射(极速、无外部网络阻塞依赖)
2. 生成 V2Ray / Clash / Shadowsocks / Socks5 / HTTP 订阅链接与标准格式
"""
from __future__ import annotations
import base64
import json
import urllib.parse
# 常见国家代码及其中文对照与国旗 Emoji
COUNTRY_NAMES: dict[str, tuple[str, str]] = {
"CN": ("中国", "🇨🇳"),
... | lza6/Image-to-2api | api/geo_ip.py | .py | ca9ef78a585905db | 7.66 | 20 |
"""全局异常处理器(v4.2 拆分:main.py 迁移)。"""
from __future__ import annotations
import logging
from starlette.exceptions import HTTPException as StarletteHTTPException
from .errors import AppError, ErrorCodes, error_response, STATUS_CODE_ERROR_MAP
log = logging.getLogger("imagefree_api")
async def app_error_handler(request... | lza6/Image-to-2api | api/handlers.py | .py | 8a25f2006ccb24a5 | 7.66 | 20 |
"""统一健康状态机(A-04)。
HealthRegistry 整合 solver_guard、provider_health、DB 连接等散落的健康状态,
提供统一视图供 /v1/healthz 消费。
"""
from __future__ import annotations
import logging
import time
from dataclasses import dataclass, field
from typing import Awaitable, Callable, Literal
log = logging.getLogger("health")
@dataclass
class Healt... | lza6/Image-to-2api | api/health.py | .py | 102525d0285f6752 | 7.66 | 20 |
"""内存环形缓冲区日志处理器,供 /v1/logs 端点查询最近日志。"""
from __future__ import annotations
import logging
import time
from collections import deque
class LogBufferHandler(logging.Handler):
"""内存环形缓冲区日志处理器。maxlen=1000,保留最近 1000 条日志。"""
def __init__(self, maxlen: int = 1000) -> None:
super().__init__()
self.b... | lza6/Image-to-2api | api/log_buffer.py | .py | 544c8702ac74f7b6 | 7.66 | 20 |
"""WebSocket 实时日志推送 + 日志缓冲区。
通过 WebSocket 向客户端推送实时日志,支持 LogBuffer 收集最近日志。
日志处理器(WsLogHandler)注入 root logger,任何模块的日志自动广播到
所有已连接的 WebSocket 客户端,实现实时日志观测。
U-02: 实时日志推送 — 前端可 WebSocket 连接 /v1/logs/ws 接收实时日志流。
O-04: 深度可观测性 — 日志 + 指标 + 追踪联动。
"""
from __future__ import annotations
import asyncio
import logging
from collect... | lza6/Image-to-2api | api/log_ws.py | .py | 2805343140fc4314 | 7.66 | 20 |
"""邮件验证码 / 验证链接提取:正则快路径 + 可选 LLM 兜底。
设计(借鉴 cloudflare_temp_email 的 AI 邮件识别思路,但严格适配主项目约束):
- **默认仅用正则快路径**,行为与历史完全一致、零回归风险。
- 仅当启用 ``IF_MAIL_AI_EXTRACT=1`` 且正则未命中时,才降级调用 LLM 兜底,
用于从难以用正则覆盖的邮件中提取验证码 / 验证链接。
- LLM 通道复用 TryingOpen 聊天提供商(``chat_collect``),不新增第三方依赖。
- LLM 调用失败或返回非法结构时**严格返回 None**,绝不阻塞注册主流程。
调用方:``api/re... | lza6/Image-to-2api | api/mail_extract.py | .py | e783a754faf4a83f | 7.66 | 20 |
"""imagefree_api 主服务:应用组装入口(v4.2 拆分后 <300 行)。
挂载路由(api.routes)、中间件、全局异常处理器、前端管理面板、生命周期。
业务逻辑已迁移至:routes/、dispatch.py、dispatch_edit.py、lifespan.py、
handlers.py、bg_tasks.py、models.py、meta.py、sse_events.py。
"""
from __future__ import annotations
import logging
from pathlib import Path
from fastapi import FastAPI
from f... | lza6/Image-to-2api | api/main.py | .py | 6be480dcdd19fb89 | 7.66 | 20 |
"""prometheus_client 指标系统(替代手动拼接 /metrics)。
测试安全:pytest 会话可能多次 import 本模块(conftest 清 sys.modules 后重建),
而 prometheus 全局 REGISTRY 不会清——重复注册会抛 Duplicated timeseries。
统一走 _metric 工厂:已注册同名指标时复用既有 collector。
"""
from prometheus_client import Counter, Histogram, Gauge, generate_latest, REGISTRY
def _metric(factory, name, d... | lza6/Image-to-2api | api/metrics_ext.py | .py | 81eb1e20c39b6d9a | 7.66 | 20 |
"""SPA smoke tests (B3.0).
These pin the behaviours a weak future change is most likely to break: the app
shell, hash-route navigation, and the accessibility landmarks. They run against
the real single-file SPA with no data fixtures (its data fetches degrade
gracefully), so they are fast and deterministic.
"""
def t... | OpenVoiceOS/ovos-localize | e2e/test_spa_smoke.py | .py | a5a4eca7e985046a | 7.95 | 7 |
"""Context card builder — generates translator-facing context from AST analysis.
Produces structured context cards that explain what a locale file does,
how it's used in skill code, and translation tips per file type.
"""
from dataclasses import dataclass, field
from typing import Any
from ovos_localize.analyzers.as... | OpenVoiceOS/ovos-localize | ovos_localize/analyzers/context_builder.py | .py | 4e622a069e0359f2 | 7.45 | 7 |
"""Bracket/parentheses expansion for OVOS locale templates.
Expands ``(a|b)`` alternative groups and ``[optional]`` groups into
all possible sentence combinations. Pure stdlib implementation
compatible with ``ovos_utils.bracket_expansion.expand_template``.
Examples:
>>> expand_template("(hello|hi) world")
['h... | OpenVoiceOS/ovos-localize | ovos_localize/bracket_expansion.py | .py | ffaf840d24ad4b62 | 7.45 | 7 |
"""Standalone CLI validation tool for OVOS locale files.
Usable in CI pipelines and locally without the web server.
"""
import argparse
import json
import sys
from pathlib import Path
from ovos_localize.sync.github import scan_locale_directory
from ovos_localize.validators.rules import validate_file
def validate_r... | OpenVoiceOS/ovos-localize | ovos_localize/cli/validate.py | .py | 93fd7aa596a03e68 | 7.45 | 7 |
"""Dataset generator for slot-filling / NER training data.
Each record pairs an utterance template with its slot names and any known
entity values from the corresponding .entity file.
"""
import re
from collections.abc import Iterator
from typing import Any
_SLOT_RE = re.compile(r"\{(\w+)\}")
def _slot_names(text:... | OpenVoiceOS/ovos-localize | ovos_localize/datasets/slot_filling.py | .py | fbe01193bd942190 | 7.45 | 7 |
"""Dataset generator for parallel corpora (machine translation)."""
from collections.abc import Iterator
from typing import Any
from ovos_localize.bracket_expansion import clean_text, expand_template
def generate_parallel_corpora(skill_id: str, skill_data: dict, base_lang: str = "en-US") -> Iterator[dict[str, Any]]... | OpenVoiceOS/ovos-localize | ovos_localize/datasets/translation.py | .py | d032fc32adc55d9c | 7.45 | 7 |
"""Shared enums for OVOS locale file types and intent systems.
Extracted from models/locale_file.py to avoid SQLAlchemy dependency
for pure-Python consumers (CLI, scripts, GitHub Actions).
"""
import enum
class FileType(str, enum.Enum):
"""OVOS locale file types."""
INTENT = "intent"
VOCAB = "voc"
... | OpenVoiceOS/ovos-localize | ovos_localize/enums.py | .py | e7a58e01c1b4ff9c | 7.45 | 7 |
"""Language code normalization using the ``langcodes`` library.
Normalizes inconsistent casing and merges equivalent tags using BCP-47
tag distance. Provides display names for the SPA frontend.
"""
from collections.abc import Iterable
import langcodes
# Explicit normalization for OVOS specific usage
# needed for sk... | OpenVoiceOS/ovos-localize | ovos_localize/lang_utils.py | .py | 379a3994a7c9d802 | 7.45 | 7 |
"""Parser for .dialog files.
Format: one response variant per line, with {variable} placeholders.
"""
from ovos_localize.parsers.base import BaseParser, ParsedFile, ParsedLine
class DialogParser(BaseParser):
"""Parser for .dialog locale files.
Each line is a response variant that may contain ``{variable}`... | OpenVoiceOS/ovos-localize | ovos_localize/parsers/dialog.py | .py | 49e4995581b42221 | 7.45 | 7 |
"""Parser for .entity files.
Format: one example value per line.
"""
from ovos_localize.parsers.base import BaseParser, ParsedFile, ParsedLine
class EntityParser(BaseParser):
"""Parser for .entity locale files.
Each line is an example value for a Padatious entity slot.
"""
file_type = "entity"
... | OpenVoiceOS/ovos-localize | ovos_localize/parsers/entity.py | .py | f15e83d50a16ff75 | 7.45 | 7 |
"""Parser for Padatious .intent files.
Format: one training utterance per line, with {slot} placeholders and (alt|alt) groups.
"""
from ovos_localize.parsers.base import BaseParser, ParsedFile, ParsedLine
class IntentParser(BaseParser):
"""Parser for .intent (Padatious) locale files.
Each line is a traini... | OpenVoiceOS/ovos-localize | ovos_localize/parsers/intent.py | .py | bc2e7a3efa1d4486 | 7.45 | 7 |
"""Parser for .rx (regex) files.
Format: one regex pattern per line, with (?P<Name>...) named groups.
"""
import re
from ovos_localize.parsers.base import BaseParser, ParsedFile, ParsedLine
class RegexParser(BaseParser):
"""Parser for .rx (regex) locale files.
Each line is a regex pattern. Named groups ``... | OpenVoiceOS/ovos-localize | ovos_localize/parsers/regex.py | .py | efecd8606bfc7746 | 7.45 | 7 |
"""Parser for generic JSON resource/data files in locale directories.
Handles key-value JSON files where values are translatable strings or
lists of strings (e.g., color names, yes/no synonyms).
"""
import json
from ovos_localize.parsers.base import BaseParser, ParsedFile, ParsedLine
class ResourceJsonParser(BaseP... | OpenVoiceOS/ovos-localize | ovos_localize/parsers/resource_json.py | .py | a3d132c2a84dba89 | 7.45 | 7 |
"""Parser for settingsmeta.json / settingsmeta.yml files."""
import json
from ovos_localize.parsers.base import BaseParser, ParsedFile, ParsedLine
# Keys in settingsmeta that contain translatable text
TRANSLATABLE_FIELDS = {"label", "name", "title", "placeholder", "value"}
class SettingsMetaParser(BaseParser):
... | OpenVoiceOS/ovos-localize | ovos_localize/parsers/settings_meta.py | .py | 9278c0b48e25114b | 7.45 | 7 |
"""Parser for skill.json metadata files."""
import json
from ovos_localize.parsers.base import BaseParser, ParsedFile, ParsedLine
# Keys in skill.json that are translatable
TRANSLATABLE_KEYS = {"name", "description", "examples", "tags"}
class SkillJsonParser(BaseParser):
"""Parser for skill.json locale files.
... | OpenVoiceOS/ovos-localize | ovos_localize/parsers/skill_json.py | .py | 0c868a9dc19dd2e8 | 7.45 | 7 |
"""Parser for .value files.
Format: CSV with ``display_name,system_value`` per line.
The right column (system_value) is immutable during translation.
"""
from ovos_localize.parsers.base import BaseParser, ParsedFile, ParsedLine
class ValueParser(BaseParser):
"""Parser for .value (named value) locale files.
... | OpenVoiceOS/ovos-localize | ovos_localize/parsers/value.py | .py | 729207299f9d83a2 | 7.45 | 7 |
"""Parser for Adapt .voc files.
Format: one keyword per line, with optional (alt|alt) expansion.
"""
from ovos_localize.parsers.base import BaseParser, ParsedFile, ParsedLine
class VocabParser(BaseParser):
"""Parser for .voc (Adapt keyword) locale files.
Each line is a keyword or keyword phrase. Supports ... | OpenVoiceOS/ovos-localize | ovos_localize/parsers/vocab.py | .py | 9ba88d53127e3235 | 7.45 | 7 |
"""Repository scanning and GitHub integration.
Handles:
- Cloning/pulling repos
- Discovering locale directories and skill Python files
- Building the file type inventory
- Generating code context via AST analysis
"""
import re
import subprocess
from dataclasses import dataclass, field
from pathlib import Path
from ... | OpenVoiceOS/ovos-localize | ovos_localize/sync/github.py | .py | c3cf1ad51f61ff7a | 7.45 | 7 |
"""Translation submission payload contract (B3.1 — session/batch editing).
An issue created by the SPA carries either:
* **v1** — a single ``<!-- TRANSLATION_META … -->`` block plus one
``<content>…</content>`` (base64), i.e. one file; or
* **v2** — a ``<!-- SESSION_META … -->`` block whose JSON body is
``{"meta_... | OpenVoiceOS/ovos-localize | ovos_localize/sync/submission.py | .py | 554b5a2297be3c90 | 7.45 | 7 |
#!/usr/bin/env python3
"""Generate ML datasets from parsed OVOS skill JSON files.
Reads from ``data/skills/`` and outputs JSONL datasets to ``data/datasets/``.
Datasets generated
------------------
classification/
One JSONL per language: intent/voc utterances with skill+intent label.
translation/
One JSONL pe... | OpenVoiceOS/ovos-localize | scripts/generate_datasets.py | .py | 4c26b8aa96b2be48 | 7.45 | 7 |
"""Unit tests for bracket expansion."""
from ovos_localize.bracket_expansion import count_expanded_lines, expand_template
class TestExpandTemplate:
"""Tests for expand_template()."""
def test_no_expansion(self) -> None:
"""Plain text returns unchanged."""
assert expand_template("hello world"... | OpenVoiceOS/ovos-localize | test/unittests/test_bracket_expansion.py | .py | 1422010c36e5a109 | 7.95 | 7 |
"""Property-based tests for template expansion (B4.1 — validation soundness).
These assert structural invariants of ``expand_template`` that must hold for
*any* well-formed template, not just hand-picked examples: slot preservation,
full bracket elimination, idempotence, and correct alternation cardinality.
"""
impor... | OpenVoiceOS/ovos-localize | test/unittests/test_bracket_expansion_properties.py | .py | 528162cf259c7b82 | 7.95 | 7 |
"""Unit tests for the CLI validation tool."""
from pathlib import Path
from ovos_localize.cli.validate import validate_repo
class TestValidateRepo:
"""Tests for validate_repo()."""
def test_no_locale_dir(self, tmp_path: Path) -> None:
"""Return 0 when no locale directory exists."""
assert v... | OpenVoiceOS/ovos-localize | test/unittests/test_cli.py | .py | 99108678884d9caf | 7.95 | 7 |
"""Unit tests for the context card builder."""
from ovos_localize.analyzers.ast_analyzer import SkillAnalyzer
from ovos_localize.analyzers.context_builder import build_context_card
from ovos_localize.enums import FileType
from ovos_localize.sync.github import ScannedFile
def _make_scanned(
base_name: str, file_... | OpenVoiceOS/ovos-localize | test/unittests/test_context_builder.py | .py | 96f32b27ac2e7df9 | 7.95 | 7 |
"""Unit tests for language utilities."""
import pytest
from ovos_localize.lang_utils import (
is_rtl,
lang_display_name,
lang_display_name_native,
merge_equivalent_langs,
normalize_lang_code,
)
class TestIsRtl:
"""Tests for is_rtl()."""
@pytest.mark.parametrize("code", [
"ar", "... | OpenVoiceOS/ovos-localize | test/unittests/test_lang_utils.py | .py | 022ce75f520e6180 | 7.95 | 7 |
"""Extra parser tests for serialization and edge cases."""
import json
from ovos_localize.parsers.dialog import DialogParser
from ovos_localize.parsers.entity import EntityParser
from ovos_localize.parsers.regex import RegexParser
from ovos_localize.parsers.settings_meta import SettingsMetaParser
from ovos_localize.p... | OpenVoiceOS/ovos-localize | test/unittests/test_parsers_extra.py | .py | 00033815a924b1c8 | 7.95 | 7 |
"""Unit tests for the repo scanner / locale directory scanner."""
import os
from pathlib import Path
from ovos_localize.enums import FileType
from ovos_localize.sync.github import RepoScanner, scan_locale_directory
class TestScanLocaleDirectory:
"""Tests for scan_locale_directory()."""
def test_scan_simple... | OpenVoiceOS/ovos-localize | test/unittests/test_scanner.py | .py | b628eaba41013ea5 | 7.95 | 7 |
#!/usr/bin/env python3
"""Writing a validation receipt, in one place.
Six validators each had their own copy of "hash the text, write
`.ddw-sessions/<prefix>-validated-<digest>`, print the path". Six copies of one
rule is how the rule drifts, and it is the shape this project keeps finding.
What is new here is the sec... | soydiloreto/dilux-development-workflow | ddw/scripts/ddw_receipt.py | .py | 260184f938f5db25 | 7.56 | 12 |
#!/usr/bin/env python3
"""ddw-create-adr's mechanical half — the only artifact that had no checker.
Every other document in DDW has a validator pinning what it is: a PRD that is
not a PRD fails eight checks before anyone reads it. The ADR had none, so the
one thing that makes it an ADR — that it EXPLAINS a decision al... | soydiloreto/dilux-development-workflow | ddw/scripts/validate_adr.py | .py | 8ec295ed0e0473f0 | 7.56 | 12 |
#!/usr/bin/env python3
"""Keep every fact this repo states twice honest.
Mostly that means versions, of which there are three kinds, and conflating them
is how they rot:
**The product's.** One number, in `.claude-plugin/plugin.json` and at the top of
the CHANGELOG. It is what someone installs and what the changelog t... | soydiloreto/dilux-development-workflow | scripts/check_versions.py | .py | 8128ba2d8f618256 | 7.56 | 12 |
"""The one-approve index: the leash, and `done` that no word can write.
family_index_pr.py collapses the index ceremony to one approval per
direction. What these tests pin is not the convenience — it is the two
safety properties that make the convenience acceptable:
* the LEASH: `merge` refuses any PR touching a fi... | soydiloreto/dilux-development-workflow | tests/test_family_index_pr.py | .py | bf2fee792bf3dc72 | 8.06 | 12 |
"""
Clean DKIM Output Formatter
Produces actionable, security-focused DKIM summaries
Shows:
- Found selectors with key strength
- Security warnings (weak keys, missing signatures)
- Actionable recommendations
"""
from typing import List, Dict
import re
from dkim_tag_analyzer import _decode_rsa_key_bits
def analyze_... | marmot7775/dns-security-auditor | dkim_formatter.py | .py | 9c0a7a6ff3aebad1 | 7.5 | 9 |
"""
DNS Snapshot Storage
====================
Lightweight SQLite-based storage for tracking changes to public DNS records
over time. Only stores a new snapshot when a record actually changes.
All data stored is publicly available DNS records.
No personal data, IP addresses, or user tracking.
"""
import hashlib
import... | marmot7775/dns-security-auditor | dns_snapshots.py | .py | b9f7a9e7b4309fcd | 7.5 | 9 |
"""
Intelligent DKIM Selector Discovery via SPF Analysis
Uses SPF includes to detect vendors, then prioritizes appropriate DKIM selectors.
This is 10x smarter than blind looping through all selectors.
Based on real-world consulting experience with 100+ enterprise deployments.
"""
import re
import time
import dns.reso... | marmot7775/dns-security-auditor | spf_intelligence.py | .py | f18ce160184be3b1 | 7.5 | 9 |
"""
Recursive SPF Lookup Counter
=============================
Follows every include:, redirect=, a, mx, exists, and ptr mechanism
through the full SPF chain to return the TRUE DNS lookup count.
RFC 7208 Section 4.6.4: SPF implementations MUST limit the number
of mechanisms and modifiers that cause DNS lookups to at m... | marmot7775/dns-security-auditor | spf_recursive.py | .py | bef3363ac8725ef8 | 7.5 | 9 |
"""
Load test for bug 28: audit_domain/audit_pdf must not block the event loop.
Runs a real uvicorn server (not TestClient, which doesn't exercise true
concurrency) with run_full_audit patched to a slow synchronous call, then
fires concurrent requests to prove /api/health stays responsive while
audits are running, and... | marmot7775/dns-security-auditor | tests/test_audit_endpoint_offload_load.py | .py | f28c84962f8913da | 8 | 9 |
"""Regression test for the two spellings of a BIMI declination record
getting different verdicts.
Bug: "l" and "a" are both optional with an empty default, so
`v=BIMI1; l=; a=;` and `v=BIMI1;` assert the same thing -- the domain
declines to publish a logo indicator. The bare form ("l" absent) hit
the "warning" branch,... | marmot7775/dns-security-auditor | tests/test_bimi_declination_spelling_consistency.py | .py | 7020701a71b72461 | 8 | 9 |
"""Regression tests for the BIMI DMARC prerequisite check.
Bug 1: check_bimi's guard was `if dmarc_enforcing_override is not None:
dmarc_found = True`. The audit orchestrator (audit_engine.py) always
passes a bool for dmarc_enforcing_override, never None, so dmarc_found was
forced True even when there was no DMARC rec... | marmot7775/dns-security-auditor | tests/test_bimi_dmarc_prerequisite.py | .py | e78d6da6282d7248 | 8 | 9 |
"""Tests for business_risk callout attachment in SPF/DMARC/DKIM checks.
The audit engine attaches a plain-English business-impact sentence to
selected top-level findings via issue["business_risk"]. These tests pin:
- Top-level findings (no record, p=none, no rua, no SPF) carry
business_risk that matches the BUS... | marmot7775/dns-security-auditor | tests/test_business_risk_callouts.py | .py | 02769b42e10f53d4 | 8 | 9 |
"""Regression test for weak DKIM keys never reaching the remediation plan.
Bug 17: _has_weak_dkim_keys (remediation_planner.py) looks for key_size,
key_bits or key_analysis.key_bits on each found selector. The default
discovery path is smart_dkim_check (spf_intelligence.py), whose selector
dicts carried only a key_typ... | marmot7775/dns-security-auditor | tests/test_dkim_discovered_key_size_normalization.py | .py | 4d6ff2a495846796 | 8 | 9 |
"""Regression test for Ed25519 DKIM keys being called weak by the planner.
Bug 18: _has_weak_dkim_keys compared every key against `bits <= 1024`, an RSA
modulus threshold. An Ed25519 key is 256 bits, so it matched, and the plan
told the user "your selectors use 1024-bit RSA keys, rotate to 2048-bit"
while the DKIM car... | marmot7775/dns-security-auditor | tests/test_dkim_ed25519_not_weak.py | .py | b3aa34b8efcdb7db | 8 | 9 |
"""Regression test for overdue DKIM keys being listed last in the report.
Bug 38: generate_rotation_report sorted with
key=lambda x: (urgency_order.get(x['urgency'], 3),
x['rotation_status'] == 'OVERDUE')
The second element is a bare equality test, so it is False (0) for a key that
is fine and... | marmot7775/dns-security-auditor | tests/test_dkim_key_age_overdue_first.py | .py | 4ec86ca2c7ff573c | 8 | 9 |
"""Regression test for the rotation schedule being an exact-match lookup.
Bug 36: analyze_key picked its rotation advice with
`ROTATION_SCHEDULE.get(key_size, ROTATION_SCHEDULE[2048])`. ROTATION_SCHEDULE
is keyed by 1024, 2048 and 4096, so any other size fell through to the 2048
default. A 512-bit or 768-bit key, weak... | marmot7775/dns-security-auditor | tests/test_dkim_key_age_rotation_bands.py | .py | e29d4a0c4af3978e | 8 | 9 |
"""Regression test for YYYYMMDD selectors being unreadable, and UNKNOWN
scoring better than OVERDUE.
Bug 37: SELECTOR_PATTERNS['date_based'] covered YYYYMM, YYYY-MM and YYMM but
not YYYYMMDD, which is Google Workspace's own rotating selector format. A
selector like 20230601 fell through every pattern and came back "Un... | marmot7775/dns-security-auditor | tests/test_dkim_key_age_yyyymmdd_selectors.py | .py | d2e19fab6ea96800 | 8 | 9 |
"""Regression test for the k=ed25519 / RSA key data mismatch never firing.
Bug 20: the algorithm mismatch check sat below the RSA branch of _check_key,
but every key_type == "ed25519" path returned before reaching it, so no
k=ed25519 record ever got there. The classic key type migration mistake,
`v=DKIM1; k=ed25519; p... | marmot7775/dns-security-auditor | tests/test_dkim_key_type_data_mismatch.py | .py | 1e10619b393fd72b | 8 | 9 |
"""Regression test for a revoked DKIM key (empty p=) passing as valid.
Bug: per RFC 6376 §3.6.1, an empty p= tag means the key is revoked. Three
things conspired to hide this:
- dkim_formatter's Ed25519 shortcut returned "strong" before ever
checking whether p= was empty.
- For RSA, analyze_dkim_key_strength's... | marmot7775/dns-security-auditor | tests/test_dkim_revoked_key.py | .py | 3a63e12247fddc5d | 8 | 9 |
"""
Tests for RFC 7489 S6.3 case-sensitive validation of the DMARC version tag.
The version tag value 'DMARC1' is case-sensitive. A record published as
v=dmarc1 is NOT a valid DMARC record and must not be honored. The audit
engine must:
- exclude lowercase v=dmarc1 records from the valid-record count
- emit a synt... | marmot7775/dns-security-auditor | tests/test_dmarc_case_sensitivity.py | .py | b6fe68890b6ede06 | 8 | 9 |
"""Regression test for the DMARC-check crash on read-only filesystem.
Bug: tldextract's default cache lives under ~/.cache, which is read-only
on the prod systemd unit (ProtectHome=read-only). Running the DMARC
check on a domain that exists but lacks DMARC triggered a tldextract
cache write, the OSError bubbled up, an... | marmot7775/dns-security-auditor | tests/test_dmarc_no_record.py | .py | 0a7f2740b954ad46 | 8 | 9 |
"""Running-state binary sensors from the AC's extended report.
Present only on units that report the extended figures; on the rest they stay unavailable rather
than showing a made-up "off". Names live in strings.json via `translation_key`.
"""
from __future__ import annotations
from collections.abc import Callable
fr... | enapt/haismart-local | custom_components/haismart/binary_sensor.py | .py | 32acb9d0d67b873c | 7.5 | 9 |
"""Button to start the AC's self-clean cycle.
Self-clean is a one-shot *trigger*, not a toggle: the cycle runs to completion and there is no OFF
command — the device model declares a start and no stop, and pressing it again while it runs is
ignored. So it is a Button, not a switch. Pressing it sends ``selfCleaningStat... | enapt/haismart-local | custom_components/haismart/button.py | .py | 270099455b171209 | 7.5 | 9 |
"""Base entity wiring device info + coordinator for Haismart entities."""
from __future__ import annotations
import re
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo, format_mac
from homeassistant.helpers.update_coordina... | enapt/haismart-local | custom_components/haismart/entity.py | .py | 45fe060c880a3a2b | 7.5 | 9 |
"""Select entities: the multi-level ECO control, and where each vane points.
ECO is off / L1 / L2 / L3, matching the remote's "ECO L1/L2/L3". It is NOT the digital model's
energySavingStatus bool. The levels are a compressor current limit — a higher level caps harder, so
the unit draws less and cools more slowly, whic... | enapt/haismart-local | custom_components/haismart/select.py | .py | 39dabd7e21a1f101 | 7.5 | 9 |
"""Switch entities for the AC's boolean features (all confirmed).
Each switch flips one grSetDAC bit via the coordinator's group-set control path; the library refuses
any field that wasn't confirmed, so only these fire. App labels: strong=rapidMode,
quiet=muteStatus, health=healthMode, sleep=silentSleepStatus, lamp=sc... | enapt/haismart-local | custom_components/haismart/switch.py | .py | 5a3ce5df6243d516 | 7.5 | 9 |
#!/usr/bin/env python3
"""Standalone proof-of-concept: read and control a Haismart Haier AC WITHOUT Home Assistant.
``haismart-hrdp`` has no Home Assistant dependency, so the same local protocol the integration uses can
drive an AC from any Python program — a CLI, a cron job, a Node-RED ``exec`` node, an MQTT bridge, ... | enapt/haismart-local | examples/standalone_control.py | .py | 405467f990670d75 | 7.5 | 9 |
"""
Thin wrappers around the existing prompt-building library for use in skill_runner.
These functions accept plain dicts and primitive types so callers need not
instantiate internal dataclasses directly.
"""
from __future__ import annotations
import sys
import tempfile
import dataclasses
from collections.abc import... | wwind123/coding-review-agent-loop | helpers/prompt_builders.py | .py | 2762d9257f979a2a | 7.54 | 11 |
"""Agent backend protocol and shared types."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import tempfile
import uuid
from typing import TYPE_CHECKING, Literal, Protocol, cast
from ..runner import CommandResult, Runner
from ..usage import UsageMetadata
if TYPE_CHEC... | wwind123/coding-review-agent-loop | src/coding_review_agent_loop/agents/base.py | .py | 15749eb607a25473 | 7.54 | 11 |
"""Claude Code backend."""
from __future__ import annotations
import json
import os
import re
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
from .base import (
AgentName,
AgentResult,
STDIN_PROMPT_THRESHOLD_BYTES,
public_response_path,
read_public_res... | wwind123/coding-review-agent-loop | src/coding_review_agent_loop/agents/claude.py | .py | c10c01b9251b45c4 | 7.54 | 11 |
"""OpenAI Codex CLI backend."""
from __future__ import annotations
import json
import os
import re
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING
from .base import (
AgentName,
AgentResult,
STDIN_PROMPT_THRESHOLD_BYTES,
public_response_path,
read_public_response_file,
... | wwind123/coding-review-agent-loop | src/coding_review_agent_loop/agents/codex.py | .py | 76185c6fcab7ee49 | 7.54 | 11 |
"""Gemini CLI backend."""
from __future__ import annotations
import json
import re
from datetime import date, timedelta
from pathlib import Path
from typing import TYPE_CHECKING
from .base import (
AgentName,
AgentResult,
AgentTextSource,
STDIN_PROMPT_THRESHOLD_BYTES,
public_response_path,
re... | wwind123/coding-review-agent-loop | src/coding_review_agent_loop/agents/gemini.py | .py | 68fe25cdf4da03d6 | 7.54 | 11 |
"""Registry for supported agent backends."""
from __future__ import annotations
from typing import TYPE_CHECKING
from .base import AgentBackend, AgentName, AgentResult
from .antigravity import BACKEND as ANTIGRAVITY_BACKEND
from .claude import BACKEND as CLAUDE_BACKEND
from .codex import BACKEND as CODEX_BACKEND
fro... | wwind123/coding-review-agent-loop | src/coding_review_agent_loop/agents/registry.py | .py | 2e462ab3a7003b80 | 7.54 | 11 |
"""Shared executable-replacement evidence gates for text-based backends."""
from __future__ import annotations
import json
import re
from ..protocol import PUBLIC_RESPONSE_MARKER
from ..runner import CommandResult, executable_identity_changed, strip_ansi
from ..workdir_guard import WorkdirReplayEvidence, WorkdirSnap... | wwind123/coding-review-agent-loop | src/coding_review_agent_loop/agents/replacement.py | .py | 941d14c3928f1679 | 7.54 | 11 |
"""Shared exceptions for the agent loop."""
from __future__ import annotations
class AgentLoopError(RuntimeError):
"""Raised for expected orchestration failures."""
class UnknownPriorItemDispositionError(AgentLoopError):
"""Raised when an agent dispositions a non-carried prior item ID."""
def __init__... | wwind123/coding-review-agent-loop | src/coding_review_agent_loop/errors.py | .py | a3e518ba25aeecd1 | 7.54 | 11 |
"""Construction and reconciliation of the expected issue-closing contract."""
from __future__ import annotations
import hashlib
import json
from dataclasses import dataclass
from collections.abc import Iterable
from .errors import AgentLoopError
def normalize_issue_ids(
value: Iterable[object] | None,
*,
... | wwind123/coding-review-agent-loop | src/coding_review_agent_loop/expected_closure.py | .py | 3daaf64fbf5d4581 | 7.54 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.