text stringlengths 302 37k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 5
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
"""Окружение Alembic.
Метаданных ORM нет: миграции - это явный SQL, поэтому автогенерация нарочно не
подключена (docs/adr/0001-no-orm.md). Адрес соединения приходит из POSTGRES_DSN и
переписывается на диалект asyncpg, чтобы один и тот же адрес работал и для
приложения, и для миграций.
"""
from __future__ import annot... | pitpamyati-netizen/Vellar | migrations/env.py | .py | 352230ce280f659a | 7 | 0 |
"""Первая схема: пользователи, персонажи, сумка.
В PostgreSQL живёт только долговечное состояние. Всё производное (итоги
характеристик, карты локаций, прилавки лавок) считается заново, а всё
короткоживущее (состояние автомата, начатые бои, изменения в локациях) живёт в
Redis со сроком - см. docs/architecture.md, «Что ... | pitpamyati-netizen/Vellar | migrations/versions/0001_initial_schema.py | .py | 658e1dbe53efb798 | 7 | 0 |
"""Сделки: эскроу, держащий стоящее предложение, и журнал закрытых.
До сих пор предложение жило только в Redis и не двигало ничего, пока на него не
ответят. Теперь оно держит вещь или золото автора с той минуты, как объявлено, а
ценность, с которой игрок расстался, не вправе зависеть от кэша, истекающего
самого по себ... | pitpamyati-netizen/Vellar | migrations/versions/0002_trades.py | .py | cd9cdb55635021c8 | 7 | 0 |
"""Приватность: карточка, которую игрок вправе закрыть, и те, с кем он не имеет дела.
И то и другое принадлежит аккаунту, а не персонажу. Чёрный список, который
обходится заведением второго персонажа, списком не является, как не является
закрытой и карточка, открывающаяся на следующем персонаже (Roadmap 2.5).
``block... | pitpamyati-netizen/Vellar | migrations/versions/0003_privacy.py | .py | c5f9f26c9bcb5d8f | 7 | 0 |
"""Раны, переживающие бой, сундук и журнал заданий.
Три вещи, которые персонаж теперь носит между заходами в игру (Roadmap 1.3, 1.5):
``health`` - что осталось после последнего боя. Ноль значит «как новенький»,
а именно таким был каждый персонаж, созданный до этой миграции,
поэтому ... | pitpamyati-netizen/Vellar | migrations/versions/0004_wounds_bank_quests.py | .py | c5a218450de58f46 | 7 | 0 |
"""Работа, сделанная персонажем в ремёслах.
Одна колонка, один документ (Roadmap 1.7). ``crafts`` сопоставляет ремеслу уже
вложенную в него работу и стражу, в которую случился последний сбор::
{"mining": {"experience": 240, "cycle": 12}}
Ранг не хранится никогда: его отсчитывает обратно от опыта
``mmorpg.domain.... | pitpamyati-netizen/Vellar | migrations/versions/0005_crafts.py | .py | fd44834359b4be11 | 7 | 0 |
"""Кто держит игру.
``is_admin`` отражает настройку ``ADMIN_IDS`` на персонаже, чтобы экраны
спрашивали персонажа, а не объект настроек. Источником истины остаётся
окружение: колонка переписывается из него на каждом ``/start``, и выдать её себе
изнутри игры не может никто. Каждый персонаж, созданный до этой миграции, ... | pitpamyati-netizen/Vellar | migrations/versions/0006_admin.py | .py | e4a1e02da74a756c | 7 | 0 |
"""Как далеко персонаж зашёл во вступлении.
Одно целое число, которое ``mmorpg.domain.rules.tutorial`` читает битовой
маской. Персонажи, созданные до этой миграции, начинают вступление сначала - об
этом и говорит значение по умолчанию; ничто из уже сделанного не теряется,
потому что каждое дело отмечается в ту минуту,... | pitpamyati-netizen/Vellar | migrations/versions/0007_tutorial.py | .py | 5ce98c55d8e91ca0 | 7 | 0 |
"""Круг долгов: что персонаж в нём выиграл и проиграл.
Два счётчика, и больше ничего. Арена платит золотом в минуту боя, поэтому нести
через время нечего; эти колонки существуют ради таблицы сезона и ради той
строки, которую экран арены показывает игроку о нём самом.
Revision ID: 0008
Revises: 0007
Create Date: 2026-... | pitpamyati-netizen/Vellar | migrations/versions/0008_arena.py | .py | ebc30719b9cec6a0 | 7 | 0 |
"""Панель смотрителя: правки поверх содержимого и учёт заблокировавших бота.
Две вещи, и обе - про то, чтобы игра жила без выкатки.
``content_overlay`` - единственное содержимое, которое хранится в базе. Файлы в
``content/`` остаются источником мира; правка ложится сверху и снимается целиком,
поэтому исходная строка ... | pitpamyati-netizen/Vellar | migrations/versions/0009_keeper_panel.py | .py | 28a13fe35e7aa274 | 7 | 0 |
"""Что Круг долгов держит с персонажа.
Победа когда-то платила вдвое из ниоткуда, и это делало Круг единственным местом
в игре, где золото появлялось без того, чтобы кто-то кого-то победил. Теперь
добавка сверх возвращённой ставки идёт из ставок, которые Круг уже взял с этого
персонажа, и эта колонка и есть тот залог.... | pitpamyati-netizen/Vellar | migrations/versions/0010_arena_credit.py | .py | 412a6144797a7556 | 7 | 0 |
"""Право смотрителя, выданное изнутри игры.
``ADMIN_IDS`` остаётся тем, откуда право берётся: id оттуда — смотритель всегда, и
только он раздаёт право другим. Само раздаваемое право лежит здесь, на аккаунте, а
не на персонаже: право, от которого можно уйти, заведя второго персонажа, правом
не было бы (та же причина, п... | pitpamyati-netizen/Vellar | migrations/versions/0011_keeper_grants.py | .py | d9b85872e8a7934b | 7 | 0 |
"""Перерождение, Печать Палаты и голос в голосовании.
Четыре колонки на персонаже и ни одной новой таблицы: голос — это не событие, а
состояние, и считать его надо одним запросом по тем, кто сейчас в игре
(``docs/endgame.md``). Кто ответил на прошлый вопрос, видно по ``turning_cycle``:
голос за прошлый цикл в этом не ... | pitpamyati-netizen/Vellar | migrations/versions/0012_turning.py | .py | 8355155045c2486e | 7 | 0 |
"""Временная блокировка аккаунта и журнал смотрителя.
Блокировка лежит на аккаунте, а не на персонаже: наказание, от которого уходят,
заведя второго персонажа, наказанием не было бы (та же причина, что у чёрного
списка в 0003 и у права смотрителя в 0011). Ничего не стирается — персонаж,
вещи и золото остаются на месте... | pitpamyati-netizen/Vellar | migrations/versions/0013_moderation.py | .py | 42e95915f06dd02f | 7 | 0 |
"""Расчёт, который смотритель откатил.
Откат — не возврат сделки в ожидание, а её собственное состояние: то, что
произошло, произошло, и журнал обязан говорить об этом дальше. Поэтому у
``status`` появляется пятое значение, а не исчезает четвёртое.
Момент расчёта при этом не переписывается. Когда сделку откатили и кт... | pitpamyati-netizen/Vellar | migrations/versions/0014_trade_rollback.py | .py | f4260cfc8476d1d6 | 7 | 0 |
"""Снаряжение сменило имена: сорок написанных вещей стали собранными.
Вещи в игре больше не пишут руками — их собирают из вида, ступени и редкости
(ADR 0015), и вместе с этим у каждой сменилось имя: ``rusty_sword`` стал
``sword@1#common``. В базе имена лежат в двух местах: строками в ``inventory`` и
ключами слотов в `... | pitpamyati-netizen/Vellar | migrations/versions/0015_gear_ids.py | .py | 2ef7abe2aa74694c | 7 | 0 |
"""Сутки экономики одной таблицей.
Каждое движение золота, кроме передачи из рук в руки, пишет строку ``gold_flow``
(``mmorpg.economy_log``). Строк этих за сутки игры тысячи, и по одной они не
говорят ничего; сложенные по видам — говорят всё: сколько мир выплатил, сколько
города забрали, сколько убрала пошлина и не пе... | pitpamyati-netizen/Vellar | scripts/economy.py | .py | f4f8ed857f497af8 | 7 | 0 |
"""Сто игроков сразу — и что при этом происходит с задержкой.
Обещание игры — сто миллисекунд на нажатие (``docs/architecture.md``). Проверено
оно было на одном игроке, и это не проверка: узкое место у такой игры не в
правилах, а в том, сколько одновременных запросов держит пул PostgreSQL. Здесь
это и меряется — тем ж... | pitpamyati-netizen/Vellar | scripts/loadtest.py | .py | 553f6f0e0f03943b | 7.5 | 0 |
"""Кто скажет, что игра встала, если она встала молча.
Сердцебиение (``mmorpg.health``) видно снаружи процесса: живой цикл событий
трогает файл, вставший — перестаёт. В контейнере это читает проба Docker и
перезапускает бота. Без контейнеров (ADR 0010) читать некому: процесс держит
консоль и выглядит живым, а игроки в... | pitpamyati-netizen/Vellar | scripts/watchdog.py | .py | 166420b01d30a8f1 | 7 | 0 |
"""Черновик персонажа: что игрок выбрал к этой минуте.
Черновик неизменен и несёт выбор каждого шага, и это то, что делает «назад»
дешёвым: шаг назад ничего не отменяет, он лишь меняет, какой экран показан
(спецификация, раздел 12).
"""
from __future__ import annotations
import re
from dataclasses import dataclass, ... | pitpamyati-netizen/Vellar | src/mmorpg/application/dto/creation.py | .py | 9f4ea95c8f093fbb | 7 | 0 |
"""Содержимое, которое можно перечитать, не останавливая игру.
Раньше ``GameContent`` собирался один раз в композиционном корне и раздавался
хендлерам как значение. Так и осталось — с одной поправкой: значение теперь
берётся отсюда на каждом обновлении, а не запоминается при старте. Реестр держит
две сборки: ту, что п... | pitpamyati-netizen/Vellar | src/mmorpg/application/services/content.py | .py | 43dd1a0c46de38da | 7 | 0 |
"""Что панель смотрителя делает с хранилищами.
Экран решает, что должно случиться; здесь это случается. Разделение то же, что у
всей игры (``Claude.md``, правило 5), и здесь оно важнее обычного: каждая функция
ниже что-нибудь необратимо стирает, и такое должно лежать в одном месте, где это
видно целиком, а не растекат... | pitpamyati-netizen/Vellar | src/mmorpg/application/services/keeper_panel.py | .py | 477ef057eca3b016 | 7 | 0 |
"""Отряд: как он собирается и где лежит.
Правила отряда - в ``domain/rules/party.py``; здесь только хранение и те
действия, из которых оно состоит: завести, позвать, согласиться, уйти,
расформировать.
Всё со сроком. Отряд, о котором забыли, распадается сам через пару часов, а зов,
на который не ответили, - через неск... | pitpamyati-netizen/Vellar | src/mmorpg/application/services/party.py | .py | b67f57c6bb2586f3 | 7 | 0 |
"""Настройки приложения.
Настройки читаются один раз на старте из окружения (и из локального файла
``.env``, если он есть), после чего считаются неизменными. Ничто в коде не
читает ``os.environ`` напрямую: всё идёт через :class:`Settings`.
"""
from __future__ import annotations
import tempfile
from enum import StrEn... | pitpamyati-netizen/Vellar | src/mmorpg/config.py | .py | 059bd0a19a70de47 | 7 | 0 |
"""Персонаж и то, что у него действительно хранится.
Здесь живут только *сырые* значения: розданные очки характеристик, уровень,
опыт, выбранные черты, набор умений и снаряжение. Итоги - здоровье, броня, урон
- не хранятся никогда: их пересчитывает из этих сырых значений
``mmorpg.domain.rules.stats``.
"""
from __futu... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/character.py | .py | 42ff83a36bbefe72 | 7 | 0 |
"""Бой: стороны, бойцы, очередь.
Бой в Велларе один на все случаи: узел локации, спуск, арена, поединок на
вольной земле, отряд против стаи и отряд против отряда - это одна и та же
сущность с разным составом сторон. Раньше их было две - «игрок» и «враги», - и
всё, что не укладывалось в одного игрока, укладывалось в по... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/combat.py | .py | 2c7a141963eefbd9 | 7 | 0 |
"""Ремёсла: сбор сырья в дороге и работа из него руками.
Ремесло - это работа, а не то, кто ты такой: приключенец выбирает класс один
раз, а ремёсла может выучить все (``Narrative.md``, раздел 2). Описания
приходят из ``content/crafts.toml``; на персонаже лежит только уже сделанная
работа, потому что ранг зарабатывают... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/craft.py | .py | 08e29688ab5b8cde | 7 | 0 |
"""Чем бьют: род урона.
До этого у удара было два состояния - «физический» и «магический», - а между
ними стоял тег ``elemental``, который не значил ни того, ни другого: «стихийный
урон» был словом без стихии. Убран. Следом убран и ``chaos``: «хаотический
урон» - такое же слово ни о чём, у него нет ни источника, ни ор... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/damage.py | .py | 2fec6242a9d5b21f | 7 | 0 |
"""Кости: чем в Vellar считается урон.
Урон в игре — не процент от чего-то, а число в границах: «2d6» это два броска
шестигранной кости, от 2 до 12. Так его пишут в содержимом, так его и слышит
игрок — только словами: **«урон от 2 до 12»**, потому что «2d6» экранный диктор
читает как «два дэ шесть», и это не речь (`do... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/dice.py | .py | 921463df53b82976 | 7 | 0 |
"""Собранные строения локации.
Ничто в этом модуле не хранится. Локация - чистая функция от своего сида,
поэтому один и тот же сид всегда собирает тот же граф, те же узлы и тех же
противников. См. ``docs/procgen.md``.
"""
from __future__ import annotations
from collections import deque
from collections.abc import Ma... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/location.py | .py | 1335ab47032034e7 | 7 | 0 |
"""Наказание и запись о том, кто его наложил.
Две вещи, и обе про людей, а не про мир. :class:`Ban` — временное отлучение от
игры: персонаж цел, вещи целы, но бот с этим аккаунтом не разговаривает, пока
срок не вышел. :class:`KeeperEntry` — строка журнала: что смотритель сделал, с
кем и когда.
Журнал существует потом... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/moderation.py | .py | 443b08a58572d887 | 7 | 0 |
"""Правки смотрителя: то, что положено поверх содержимого из TOML.
Файлы в ``content/`` остаются источником мира. Смотритель ничего в них не пишет:
он кладёт сверху записи, и игра читает содержимое как «TOML плюс правки». Отсюда
два свойства, ради которых это и сделано: правку видно сразу, без перезапуска, и
её всегда... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/overlay.py | .py | 835329e02fb864c2 | 7 | 0 |
"""Задания: чего просит город и как далеко зашёл персонаж.
Задание в Vellar - оплаченная работа, а не призвание: кто-то называет цену, а
игрок берётся или нет (``Narrative.md``, раздел 4). Описание приходит из
``content/quests.toml``; ход дела лежит на персонаже, потому что два персонажа
одного игрока ведут свои счета... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/quest.py | .py | 99b551406b2d09d9 | 7 | 0 |
"""Основные характеристики персонажа.
Семь основных характеристик кормят собой каждое производное число. Модуль -
чистые данные: он знает, как характеристики складываются, а не откуда они
берутся.
"""
from __future__ import annotations
from collections.abc import Iterator, Mapping
from dataclasses import dataclass, ... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/stats.py | .py | 4e910fbfbd64e768 | 7 | 0 |
"""Состояния: то, что висит на бойце и что-то с ним делает.
Раньше половина этого была признаком «правда или ложь», спрятанным в самом
бойце: ``stunned`` считал ходы, ``free_cast`` помнил одно нажатие, а горение и
кровотечение отличались друг от друга только названием умения, которое их
повесило. Ни спросить «что на м... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/statuses.py | .py | 862850255d4e6086 | 7 | 0 |
"""Сделка между двумя игроками: кто что предложил и чем это кончилось.
Это существительные групповой экономики. Глаголы - кто вправе ответить, что
вправе закрыться - живут в ``domain/rules/group_offers.py``; тамошние проверки
читают эти объекты и никогда их не меняют.
:class:`Offer` - то, что предлагает один игрок. :... | pitpamyati-netizen/Vellar | src/mmorpg/domain/entities/trade.py | .py | 7907008e47ebbd47 | 7 | 0 |
#!/usr/bin/env python3
"""PreToolUse guard: Edit/Write to a CODEMAP-frozen file asks first.
Reads the tool-call JSON on stdin, looks the target path up in
docs/CODEMAP.md, and for class results-cited or reproduce-pinned emits
a permissionDecision=ask so the edit needs an explicit user OK.
Everything else (library, spe... | 39hops/llmopt | .claude/hooks/codemap_guard.py | .py | caae9c4d0cd09771 | 7.15 | 1 |
#!/usr/bin/env python3
"""Regenerate whatever a ledger edit just invalidated.
The ledger has four generated surfaces, each derived from a file a
session edits by hand:
docs/RESULTS.md -> docs/results-index.jsonl (gen_results_index.py)
+ the FINDINGS ratchet headroom line
docs/FINDINGS.md ... | 39hops/llmopt | .claude/hooks/ledger_regen.py | .py | e4547f12479d22c8 | 7.15 | 1 |
#!/usr/bin/env python3
"""PreToolUse guard: a driver that has a SMOKE mode must isolate its paths.
House rule (CLAUDE.md, earned twice on 2026-08-15): SMOKE mode writes
receipts AND checkpoints to its own paths, and refuse-if-exists guards
stay unconditional. A smoke artifact on a real path cost a manual
delete and an... | 39hops/llmopt | .claude/hooks/smoke_guard.py | .py | b782245b4048ee57 | 7.15 | 1 |
"""llmopt.backends — decode backends behind one interface.
Symbols resolve lazily: importing this package costs nothing, and torch
or sympy load only when a name is actually used. `llmopt.backends.<module>`
still works for anything not re-exported here.
"""
from __future__ import annotations
import importlib
from typ... | 39hops/llmopt | llmopt/backends/__init__.py | .py | 3b775a9e355e2295 | 7.15 | 1 |
"""Backend protocol for greedy block-verify decoding.
The decode loop (llmopt.decoding.lookup_generic) is framework-agnostic:
only plain Python ints cross this boundary. A backend owns the model,
its KV cache, and any compilation strategy (CUDA graphs, mx.compile).
Contract mirrors the StaticCache block-verify scheme... | 39hops/llmopt | llmopt/backends/base.py | .py | 2c3ea0b7b98768ce | 7.15 | 1 |
"""MLX backend: mlx-lm model + trimmable KV cache (Apple silicon).
Implements the DecodeBackend protocol (see base.py) so the generic
prompt-lookup loop (llmopt.decoding.lookup_generic) runs on MLX.
Unlike the torch StaticCache path, mlx-lm caches track their write
position implicitly (``cache[0].offset``); there is ... | 39hops/llmopt | llmopt/backends/mlx_backend.py | .py | bc12f6bdca63c5bd | 7.15 | 1 |
"""Torch/HF backend: StaticCache + optional torch.compile CUDA-graph step.
Implements the DecodeBackend protocol (see base.py). Same mechanics as
llmopt.decoding.lookup_static, factored so the decode loop can also run
on non-torch backends (e.g. MLX).
"""
from __future__ import annotations
from typing import Sequenc... | 39hops/llmopt | llmopt/backends/torch_static.py | .py | 2a2af52a21d48ba0 | 7.15 | 1 |
"""KV eviction policies: which cached positions survive a budget cut.
Policies are pure functions from (attention evidence, budget) to kept
position indices, sorted ascending — storage-agnostic, like the rest of
cache/. apply_eviction compacts an HF cache down to the kept indices.
- sliding_window: keep the most rece... | 39hops/llmopt | llmopt/cache/eviction.py | .py | b7a84a1297720936 | 7.15 | 1 |
"""KV cache quantization: int8/int4 with per-token-per-head scales.
KV activations have outlier channels but per-(token, head) max-abs
scaling keeps error contained enough for int8 to be near-lossless in
attention; int4 is the aggressive setting. Storage is a symmetric
integer code + one fp scale per (token, head) row... | 39hops/llmopt | llmopt/cache/kv_quant.py | .py | 083d4602721aa00a | 7.15 | 1 |
"""Paged KV cache blocks (vLLM-style, pure-Python manager).
KV memory is a fixed pool of fixed-size blocks; each sequence maps
logical positions to physical blocks through a block table. Sharing is
by reference count: ``fork`` copies the table and bumps refcounts (e.g.
parallel sampling from a shared prompt), and writ... | 39hops/llmopt | llmopt/cache/paged.py | .py | 5cac91c07ee6a70f | 7.15 | 1 |
"""Glue between RadixCache and HF KV caches: prefix reuse for prefill.
The radix tree stores opaque payloads; here the payload is a per-layer
list of (k, v) tensors [1, H, t, D] covering the edge's tokens. Three
operations make the tree usable as a prompt-prefix cache:
- slice_payload: cut [start, end) out of a finis... | 39hops/llmopt | llmopt/cache/prefix_reuse.py | .py | 1d6930f1a7f07c39 | 7.15 | 1 |
"""Radix-tree prefix KV cache (SGLang-style, pure Python structure).
The tree stores token-id sequences on edges; each node owns the KV payload
for its edge's tokens (opaque to the tree -- tensors, tuples, whatever the
caller slices out of an HF `past_key_values`). Lookup returns the longest
cached prefix so prefill c... | 39hops/llmopt | llmopt/cache/radix.py | .py | 4dc4a9f6784225a1 | 7.15 | 1 |
"""LLVM toolchain oracle: clang / llvm-mc / objdump.
Faster sibling of oracle.py (no vcvars shell), plus the two tools MSVC
lacks: llvm-mc gives per-instruction byte encodings both directions, so
a model's *predicted* assembly can be scored by assembling it — the
toolchain judges semantics, not string distance.
Tool ... | 39hops/llmopt | llmopt/codegen/llvm.py | .py | 8397d949170b932b | 7.15 | 1 |
"""LLMLingua-style prompt compression: shrink the prompt itself.
Prefill is compute-bound at length (see eval/roofline), so dropping
tokens is a direct cost cut — and attention is robust to losing
low-information tokens. A small scorer LM measures each token's
self-information -log2 p(token | prefix); tokens the LM fi... | 39hops/llmopt | llmopt/context/compression.py | .py | e592f9f402759df2 | 7.15 | 1 |
"""Gist tokens: learned prompt compression (Mu et al. 2023).
Instead of dropping tokens (compression.py), teach the model to *summarize
a prefix into k slots*: append k gist tokens after the instruction and
train with a mask where everything after the gists cannot see the
instruction — only the gists. The model is for... | 39hops/llmopt | llmopt/context/gist.py | .py | 8c91e73b112c5dc0 | 7.15 | 1 |
"""RoPE scaling: run a model past its trained context window.
RoPE encodes position as rotations at frequencies inv_freq[j] =
base^(-2j/dim). Extending context means slowing rotations so unseen
absolute positions land inside the trained rotation range:
- Position interpolation (PI): divide all frequencies by the scal... | 39hops/llmopt | llmopt/context/rope_scaling.py | .py | 40916fb386ba250e | 7.15 | 1 |
"""RULER-style synthetic long-context eval.
Claimed context length != usable context length. RULER's trick: generate
retrieval tasks at any target length from templates, so degradation can be
measured along the length axis with exact-match scoring — no dataset
needed, no judge model.
Tasks (the core RULER families, m... | 39hops/llmopt | llmopt/context/ruler.py | .py | 093eabcf10c605f2 | 7.15 | 1 |
"""REST-style datastore drafting (He et al. 2023, "REST: Retrieval-Based
Speculative Decoding").
Prompt-lookup can only draft text that already appears in the current
context. A retrieval datastore generalizes it: index every sequence the
model has produced (or any corpus), and draft by longest-suffix match
against th... | 39hops/llmopt | llmopt/decoding/datastore.py | .py | 2cdc08714985ffc3 | 7.15 | 1 |
"""KV-cache helpers for draft/verify decode loops.
Supports both the modern HF `Cache` API (DynamicCache: get_seq_length /
crop) and the legacy tuple-of-(k, v) format with shapes [B, H, T, D].
`crop` drops rejected draft positions after a verify pass; `valid_len`
reports cached sequence length.
"""
from __future__ im... | 39hops/llmopt | llmopt/decoding/kv.py | .py | 34921879809ec9c3 | 7.15 | 1 |
"""Prompt-lookup (n-gram) decoding: draft tokens by copying from the prompt.
Pure-Python matcher (no torch) plus a generate loop that verifies drafts
with a single target-model forward pass per step.
"""
from __future__ import annotations
from typing import Sequence
def find_ngram_continuation(
context: Sequen... | 39hops/llmopt | llmopt/decoding/prompt_lookup.py | .py | 1b0b4d773f3e857b | 7.15 | 1 |
"""Quality-verified decoding: accept drafts by score, not bit-exactness.
Exact speculative decoding rejects a draft token the moment it differs
from the target argmax — even when the target thinks it's a perfectly
good token. Quality verification relaxes the criterion:
- "top_k": accept if the draft token is within t... | 39hops/llmopt | llmopt/decoding/quality_verify.py | .py | 5cf1a5d59afc47ca | 7.15 | 1 |
"""Composable sampling pipeline: logits processors + terminal sampler.
A processor maps ``(logits, ctx) -> logits`` for one next-token
distribution (1-D tensor over vocab); ``ctx`` is the full token list so
far (prompt + generated). Filtering processors mask excluded tokens to
-inf; the pipeline ends with a softmax + ... | 39hops/llmopt | llmopt/decoding/samplers.py | .py | 09bc07529aef7785 | 7.15 | 1 |
"""CLI for Bug Bounty Platform."""
import typer
import uvicorn
from bug_bounty.api import app
cli = typer.Typer(name="bug-bounty", help="Bug Bounty Platform")
server_cli = typer.Typer(name="server", help="API Server")
@server_cli.command()
def run(
host: str = typer.Option("0.0.0.0", help="Host to b... | OpKnock/bug-bounty-platform | src/bug_bounty/cli.py | .py | 93f6e432c77f34c3 | 7 | 0 |
"""Bug Bounty Platform core models."""
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Dict, List, Optional
import uuid
class Severity(Enum):
"""Vulnerability severity levels."""
CRITICAL = "critical"
HIGH = "high"
MEDIUM = ... | OpKnock/bug-bounty-platform | src/bug_bounty/models.py | .py | 8dcc7d9a15cf5c6a | 7 | 0 |
"""Filename matching rules for RAW Photo Cleaner."""
from pathlib import Path
RAW_EXTENSIONS = frozenset(
{
".nef",
".cr2",
".cr3",
".arw",
".dng",
".raf",
".rw2",
".orf",
}
)
EXPORT_EXTENSIONS = frozenset(
{
".jpg",
".jpeg",... | Anthony-2549/raw-photo-cleaner | src/raw_photo_cleaner/matcher.py | .py | 46e0b6ea18f7373b | 7 | 0 |
from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator, Awaitable
from typing import Annotated, Any, Literal, Protocol, TypeVar
import anyio
from fastapi import APIRouter, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidatio... | oktykrk/dwell | src/dwell/api/openai.py | .py | 10cc2fcb8e82563b | 7 | 0 |
from __future__ import annotations
import json
import sqlite3
import threading
import uuid
from collections.abc import Iterable, Iterator
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Any
from dwell.domain import (
TERMINAL_JOB_STATUSES,
JobErr... | oktykrk/dwell | src/dwell/jobs/store.py | .py | 9b4d76cf713d51d6 | 7 | 0 |
from __future__ import annotations
import asyncio
from abc import ABC, abstractmethod
from collections.abc import AsyncIterator, Awaitable, Callable
from pathlib import Path
from typing import Any
from pydantic import BaseModel, ConfigDict
from dwell.domain import (
GenerationResult,
ModelDefinition,
Run... | oktykrk/dwell | src/dwell/runtimes/base.py | .py | c58d14a6201b8735 | 7 | 0 |
# hetsi/core/diskinfo.py
"""Tailles de dossiers, espace disque et liste des lecteurs."""
import ctypes
import os
import shutil
import stat
import string
DRIVE_FIXED = 3
def _est_point_reparse(chemin):
"""Vrai si `chemin` est un point de reparse (jonction ou lien symbolique)."""
try:
infos = os.stat(c... | ardani37/hetsi | hetsi/core/diskinfo.py | .py | 16cea80a12e4a0a5 | 7 | 0 |
"""Élévation administrateur et chemin des données applicatives."""
import ctypes
import os
import sys
def est_admin():
try:
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception:
return False
def relancer_en_admin():
"""Relance le processus courant élevé. Renvoie True si re... | ardani37/hetsi | hetsi/core/elevate.py | .py | 811ac61305ecfeba | 7 | 0 |
# hetsi/core/history.py
"""Persistance JSON de l'historique des déplacements + annulation."""
import json
import os
from hetsi.core import mover
class Historique:
def __init__(self, chemin_json):
self.chemin = chemin_json
def _lire(self):
if not os.path.exists(self.chemin):
retur... | ardani37/hetsi | hetsi/core/history.py | .py | 5264bcd8ba9054ca | 7 | 0 |
"""Journal fichier de hetsi (diagnostic)."""
import logging
def configurer(chemin_log):
log = logging.getLogger("hetsi")
log.setLevel(logging.INFO)
# éviter d'empiler les handlers si rappelé (et fermer pour libérer le fd)
for h in [h for h in log.handlers if isinstance(h, logging.FileHandler)]:
... | ardani37/hetsi | hetsi/core/journal.py | .py | d902ccc3a0b270c1 | 7 | 0 |
# hetsi/core/mover.py
"""Cœur : détection de jonction et copie robocopy."""
import os
import shutil
import stat
import subprocess
from dataclasses import dataclass
from hetsi.core import diskinfo
@dataclass
class ResultatCopie:
succes: bool
code: int
message: str
def est_jonction(chemin):
"""True s... | ardani37/hetsi | hetsi/core/mover.py | .py | 173ad429a213afb3 | 7 | 0 |
"""Détection et fermeture des programmes lancés depuis un dossier.
Tout passe par des appels Windows directs (ctypes). Aucun processus externe
n'est lancé : c'est à la fois plus rapide (attente native au lieu de sondage)
et moins suspect pour les antivirus, qui signalent les applications lançant des
scripts pour termi... | ardani37/hetsi | hetsi/core/processus.py | .py | e9a70a8a2ff7eaa4 | 7 | 0 |
# hetsi/core/risques.py
"""Analyse de risque avant un déplacement."""
import ctypes
import os
import winreg
from dataclasses import dataclass
from hetsi.core import diskinfo
DRIVE_REMOVABLE = 2
DRIVE_REMOTE = 4
def _racines_programmes():
"""Racines Program Files (minuscules), d'après l'environnement Windows."""... | ardani37/hetsi | hetsi/core/risques.py | .py | 9aa21564d95a08dd | 7 | 0 |
import os
import shutil
import subprocess
import time
from hetsi.core import processus
def _lancer_programme_depuis(dossier):
"""Copie cmd.exe dans `dossier` et le lance sur une longue attente.
cmd.exe est utilisé plutôt que python.exe : ses dépendances vivent dans
System32, donc une copie isolée démarr... | ardani37/hetsi | hetsi/tests/test_processus.py | .py | a5db8a6214ff7247 | 7.5 | 0 |
"""Génère le fichier de ressources de version lu par PyInstaller (--version-file).
Un exécutable correctement identifié (nom, description, éditeur) est nettement
moins suspect pour les heuristiques antivirus qu'un binaire anonyme.
"""
import itertools
import sys
MODELE = """VSVersionInfo(
ffi=FixedFileInfo(
fil... | ardani37/hetsi | outils/generer_version.py | .py | d3878f472278c29d | 7 | 0 |
import os
from typing import List
from google import genai
from rag_cli.processing.chunker import DocumentChunk
class GeminiEmbedder:
"""Generates vector embeddings for text using the Gemini API."""
# Using gemini-embedding-2 as standard for Gemini embeddings
DEFAULT_MODEL = "gemini-embedding-2"
... | Muhammed-Sahal717/Retrieval-Augmented-Generation-RAG- | src/rag_cli/embeddings/gemini_embedder.py | .py | 50f92d611b9b0972 | 7 | 0 |
import os
from typing import List, Dict, Any
from google import genai
class Generator:
"""Handles the generation of answers using Gemini based on retrieved context."""
DEFAULT_MODEL = "gemini-3.6-flash"
def __init__(self, api_key: str | None = None, model: str = DEFAULT_MODEL):
"""
I... | Muhammed-Sahal717/Retrieval-Augmented-Generation-RAG- | src/rag_cli/generation/generator.py | .py | 10a0048e98eff29f | 7 | 0 |
from pathlib import Path
class TextLoader:
"""Loads and extracts text from local .txt and .md files."""
SUPPORTED_EXTENSIONS = {".txt", ".md"}
@classmethod
def load(cls, file_path: str | Path) -> str:
"""
Validates and loads text from the given file path.
Args:
... | Muhammed-Sahal717/Retrieval-Augmented-Generation-RAG- | src/rag_cli/loaders/text_loader.py | .py | 8597f634f14a2415 | 7 | 0 |
import hashlib
from dataclasses import dataclass
from typing import List
@dataclass
class DocumentChunk:
chunk_id: str
text: str
source_document: str
chunk_index: int
class TextChunker:
"""Splits text into smaller chunks with configurable size and overlap."""
def __init__(self, chunk_siz... | Muhammed-Sahal717/Retrieval-Augmented-Generation-RAG- | src/rag_cli/processing/chunker.py | .py | bc56e74188956208 | 7 | 0 |
from typing import List, Dict, Any
from rag_cli.embeddings.gemini_embedder import GeminiEmbedder
from rag_cli.vector_store.chroma_store import ChromaStore
class Retriever:
"""Handles the semantic retrieval of relevant document chunks for a given query."""
def __init__(self, embedder: GeminiEmbedder, vect... | Muhammed-Sahal717/Retrieval-Augmented-Generation-RAG- | src/rag_cli/retrieval/retriever.py | .py | bdb66f11ec7b308b | 7 | 0 |
import os
from typing import Dict, Any
from rag_cli.loaders.text_loader import TextLoader
from rag_cli.processing.chunker import TextChunker
from rag_cli.embeddings.gemini_embedder import GeminiEmbedder
from rag_cli.vector_store.chroma_store import ChromaStore
from rag_cli.retrieval.retriever import Retriever
from rag... | Muhammed-Sahal717/Retrieval-Augmented-Generation-RAG- | src/rag_cli/services/rag_service.py | .py | 2cb93248198974ba | 7 | 0 |
import os
import chromadb
from typing import List, Dict, Any
from rag_cli.processing.chunker import DocumentChunk
class ChromaStore:
"""Manages local storage and retrieval of vector embeddings using ChromaDB."""
def __init__(self, persist_directory: str = "./chroma_db", collection_name: str = "rag_docum... | Muhammed-Sahal717/Retrieval-Augmented-Generation-RAG- | src/rag_cli/vector_store/chroma_store.py | .py | 110ae3fc67ee5db8 | 7 | 0 |
"""
MCP stdio adapter over AgentService.
This module is a protocol translation layer and nothing else: it maps tool
calls onto AgentService, converts snapshots into a compact response model, and
forwards progress. All business logic lives in src/service/.
Two rules this file must never break:
1. stdout belongs to th... | Yi-luo-hua/BilibiliCrawler | backend/mcp_server.py | .py | 0f8183de3ad24f47 | 7.75 | 31 |
"""
数据处理和清洗模块
"""
import logging
from typing import List, Dict, Optional
logger = logging.getLogger(__name__)
class DataProcessor:
"""数据处理器类"""
@staticmethod
def clean_comments(comments: List[Dict]) -> List[Dict]:
"""
清洗评论数据
Args:
comments: 原始评论列表
Returns:
... | Yi-luo-hua/BilibiliCrawler | src/processor/data_processor.py | .py | d05dc5d5ee349645 | 7.75 | 31 |
"""
LLM credential resolution for headless runs.
The desktop app already stores the user's key via the Rust command
``write_llm_api_key`` at ``<user_data_dir>/config/credentials.json``
(desktop/src-tauri/src/main.rs). Reading that file back means a user who
configured the GUI does not have to copy a plaintext key into... | Yi-luo-hua/BilibiliCrawler | src/service/credentials.py | .py | c2729536be999720 | 7.75 | 31 |
"""
Output directory resolution, shared by the desktop sidecar and the agent service.
One policy, in one place: prefer the project root so users can find their files,
and fall back to %LOCALAPPDATA% for installed layouts where the project root is
not writable. Both front ends resolve through here, so the desktop app's... | Yi-luo-hua/BilibiliCrawler | src/service/paths.py | .py | b8c275d0d40444ff | 7.75 | 31 |
import io
import json
import tempfile
import threading
import time
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from src.service.agent_service import AgentService
from src.service.credentials import LLMCredentials
from src.service.models import MAX_PAGES_CEILING, ErrorCode, RunStatus... | Yi-luo-hua/BilibiliCrawler | tests/test_agent_service.py | .py | a03041bde148c6e0 | 7.25 | 31 |
"""Filesystem layout for SRTForge's persistent state.
Settings live in a per-user config directory. On Windows that's
``%APPDATA%/srtforge``. We try ``QStandardPaths`` first (most idiomatic)
and fall back to ``%APPDATA%`` so this module is importable *before*
``QApplication`` exists.
"""
from __future__ import annota... | Asgh24/srtforge | src/srtforge/config/paths.py | .py | 97916f3fbbafd7a0 | 7.15 | 1 |
"""APIProfile — a single OpenAI/Anthropic-compatible endpoint + key."""
from __future__ import annotations
import uuid
from dataclasses import asdict, dataclass, field
from typing import Any
def _new_id() -> str:
return uuid.uuid4().hex
@dataclass
class APIProfile:
"""A named LLM endpoint configuration.
... | Asgh24/srtforge | src/srtforge/config/profiles.py | .py | d4e735a2bcca6ccf | 7.15 | 1 |
"""Settings persistence — JSON file under the user config directory."""
from __future__ import annotations
import json
import logging
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
from srtforge.config.paths import settings_file
from srtforge.config.profiles import A... | Asgh24/srtforge | src/srtforge/config/settings.py | .py | 170d9178e6715cd6 | 7.15 | 1 |
"""Subtitle file I/O built on pysubs2.
We only *write* SRT today, but ``load`` accepts anything pysubs2 can
read (srt, ass/ssa, vtt, sub, ...) so a future feature can widen the
output formats with a one-line change.
"""
from __future__ import annotations
import re
from pathlib import Path
import pysubs2
from srtfo... | Asgh24/srtforge | src/srtforge/srt/io.py | .py | 9a669ee32fc82478 | 7.15 | 1 |
"""Pure data model for one subtitle cue."""
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class SubtitleEntry:
"""A single subtitle cue.
``text`` is plain text with ``\n`` separators. Styling (``<i>``,
``{\\an8}`` etc.) is stripped before translation and re-appl... | Asgh24/srtforge | src/srtforge/srt/model.py | .py | 364d849377190440 | 7.15 | 1 |
"""Greedy subtitle-by-subtitle chunker.
The unit of a chunk is a *whole subtitle cue* — they're authored as
natural sentence boundaries, so we never split mid-sentence. We just
accumulate cues until adding the next one would exceed the model's
input budget.
Budget = floor(model.context_length × safety_margin) − outpu... | Asgh24/srtforge | src/srtforge/translate/chunker.py | .py | 621028f7a780a844 | 7.15 | 1 |
"""Token estimation.
We support two backends:
1. ``tiktoken`` — accurate for OpenAI-family models. Optional dep.
2. Heuristic ``len / 3.5`` — covers CJK (~1.5 char/token) and Latin
(~4 char/token) reasonably well.
The backend is picked at call time so missing ``tiktoken`` is silent.
"""
from __future__ import an... | Asgh24/srtforge | src/srtforge/translate/estimator.py | .py | c5f8dcc682175eba | 7.15 | 1 |
"""Languages we ship in the dropdown.
The list is intentionally short — these are the most common
target languages for English-speaking learners of other languages.
The dropdown is editable: users can type any language they want.
"""
from __future__ import annotations
COMMON_LANGUAGES: list[str] = [
"English",
... | Asgh24/srtforge | src/srtforge/translate/languages.py | .py | c9fd1c22a09477d4 | 7.15 | 1 |
"""OpenRouter-style model metadata.
We only need three things per model:
- id (used as the API ``model`` field)
- context_length (max input+output tokens)
- max_output_tokens (soft cap, from ``top_provider.max_completion_tokens``)
The OpenRouter ``/models`` endpoint returns a JSON array of objects with
a lot mo... | Asgh24/srtforge | src/srtforge/translate/models.py | .py | e305b1b1b44cb34b | 7.15 | 1 |
"""Prompt templates.
The default prompt is deliberately *behavioural* — it tells the model
exactly what shape of JSON to return and warns against common failure
modes (echoing indices, adding commentary, splitting cues). The
``custom_prompt`` field in settings lets power users override.
"""
from __future__ import ann... | Asgh24/srtforge | src/srtforge/translate/prompt.py | .py | 1c49d7442dd51a24 | 7.15 | 1 |
"""Settings dialog — concurrency, safety margin, custom prompt, theme."""
from __future__ import annotations
from PySide6.QtCore import Signal
from PySide6.QtWidgets import (
QComboBox,
QDialog,
QDialogButtonBox,
QDoubleSpinBox,
QFormLayout,
QHBoxLayout,
QLineEdit,
QPushButton,
QSp... | Asgh24/srtforge | src/srtforge/ui/dialogs/settings_dialog.py | .py | 4559ed253c90f988 | 7.15 | 1 |
"""Chunker tests — every entry appears once, no chunk overflows."""
from __future__ import annotations
import pytest
from srtforge.srt.model import SubtitleEntry
from srtforge.translate.chunker import chunk
from srtforge.translate.models import ModelInfo
def _entry(i: int, text: str = "x") -> SubtitleEntry:
re... | Asgh24/srtforge | tests/test_chunker.py | .py | 7d1e9721bb8723ca | 7.65 | 1 |
"""Token estimator tests."""
from __future__ import annotations
from srtforge.translate.estimator import estimate_tokens
def test_empty_string() -> None:
assert estimate_tokens("") == 0
def test_known_short_text_has_positive_count() -> None:
assert estimate_tokens("Hello world") >= 1
def test_longer_tex... | Asgh24/srtforge | tests/test_estimator.py | .py | 33ffd6d4d0f202ef | 7.65 | 1 |
"""Shared HTTP + parsing helpers used by provider implementations.
Kept in a private module so provider modules (``openrouter``, ``vercel``, …)
don't re-implement the same auth/rate-limit/JSON dance and don't reach into
each other's private functions.
* :func:`_f` — lenient ``float`` parse for pricing/score string... | gi-dellav/anypick | anypick-python/anypick/_http.py | .py | 56c35f6840716177 | 7.24 | 2 |
"""anypick errors."""
from __future__ import annotations
class AnypickError(Exception):
"""Base class for anypick errors."""
class NoModelsFound(AnypickError):
"""Raised when filtering empties the candidate set.
Attributes:
survivors_by_clause: ordered mapping of clause name -> count of models... | gi-dellav/anypick | anypick-python/anypick/errors.py | .py | c64d577186224af3 | 7.24 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.