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 """ What a category asks of an event, and the shift times it produces. Below both callers. Collection works these out from a calendar item, and an edit works them out again whenever the answer could change -- a different category, a different time. Written twice, the two would ...
rcrderby/star-pass
app/star_pass/_shift_timing.py
.py
9086a9e26b433fbc
7
0
#!/usr/local/bin/python3 """ Google Calendar shift management classes and methods. """ # Imports - Python Standard Library from copy import copy from dataclasses import dataclass from os import getenv from typing import Any, Dict, List, Optional, Sequence, Tuple # Imports - Local from . import _defaults from ._except...
rcrderby/star-pass
app/star_pass/gcal_data.py
.py
568fa0ae9d8faa61
7
0
#!/usr/bin/env python3 """ The service, assembled. A factory rather than a module level application object, so that a test builds one per test and configuration is read when a server starts rather than when something imports this module. Importing a module should not open sockets or read the environme...
rcrderby/star-pass
app/star_pass_api/_app.py
.py
88e671a0a37f8133
7
0
"""initial multi-user schema Revision ID: 0001 Revises: Create Date: 2026-07-08 12:12:34.835989 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op revision: str = '0001' down_revision: str | None = None branch_labels: str | Sequence[str] | None = None depends_on: str | Sequenc...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0001_initial_multi_user_schema.py
.py
4a3f805de2c5a2ae
7.24
2
"""users.password_changed_at for token revocation on password change Revision ID: 0002 Revises: 0001 Create Date: 2026-07-11 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op revision: str = '0002' down_revision: str | None = '0001' branch_labels: str | Sequence[str] | None = ...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0002_users_password_changed_at.py
.py
ad65be23e47664db
7.24
2
"""ai_analyses.kind so transcriptions share the quota counter Revision ID: 0003 Revises: 0002 Create Date: 2026-07-26 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op revision: str = '0003' down_revision: str | None = '0002' branch_labels: str | Sequence[str] | None = None de...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0003_ai_analyses_kind.py
.py
dd705c684885893c
7.24
2
"""weights table and settings.weight_unit Revision ID: 0004 Revises: 0003 Create Date: 2026-07-28 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op revision: str = '0004' down_revision: str | None = '0003' branch_labels: str | Sequence[str] | None = None depends_on: str | Sequ...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0004_weight_entries_and_weight_unit.py
.py
259626bfed63d466
7.24
2
"""password_resets table Revision ID: 0005 Revises: 0004 Create Date: 2026-08-04 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op revision: str = '0005' down_revision: str | None = '0004' branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None ...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0005_password_resets.py
.py
fbf26cd58808e043
7.24
2
"""meals.created_at — when the row was written, not when the food was eaten Revision ID: 0006 Revises: 0005 Create Date: 2026-08-14 `meals.date` is user-chosen and freely backdated, so it cannot answer "when was the app used". This column can. It is nullable rather than backfilled: rows written before it existed have...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0006_meals_created_at.py
.py
050a543862a67abb
7.24
2
"""meal_templates table Revision ID: 0007 Revises: 0006 Create Date: 2026-08-15 A saved meal the user can re-log in one tap. `items_json` holds the ingredient rows as serialized JSON rather than a child table: nothing queries by ingredient, so the rows are read whole or not at all, which is the same reason ai_analyse...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0007_meal_templates.py
.py
b72ca55fa4f96658
7.24
2
"""settings body profile and targets_auto Revision ID: 0008 Revises: 0007 Create Date: 2026-08-20 The body profile behind the calorie/BMI calculator. Five nullable columns plus one boolean flag, all on the existing `settings` row rather than a new table: there is exactly one profile per account, `settings` is already...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0008_settings_body_profile.py
.py
96b2f465cf1af252
7.24
2
"""water_logs table and the two water settings columns Revision ID: 0009 Revises: 0008 Create Date: 2026-08-21 The water tracker. One new user-owned table plus two nullable columns on `settings`. `water_logs` is event rows, not a per-day total, and the index is deliberately NOT unique on (user_id, date) -- see the m...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0009_water_tracker.py
.py
f254ffcaf93cd4f8
7.24
2
"""steps tracker: steps table + settings.steps_goal Revision ID: 0010 Revises: 0009 Create Date: 2026-08-21 The index here IS unique on (user_id, date), which is the opposite of 0009's and the one thing about this schema easiest to "tidy up" into a bug. Water is event rows, so several a day is the point; a step count...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0010_steps_tracker.py
.py
02cc487a2c736ded
7.24
2
"""supplement tracker: supplements + supplement_logs Revision ID: 0011 Revises: 0010 Create Date: 2026-08-21 Two tables and no settings column, which is what makes this phase different from 0009 and 0010. Water and steps each hung a goal off `settings`; a supplement's schedule belongs to the supplement, so there is n...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0011_supplement_tracker.py
.py
f3946adbf6378c03
7.24
2
"""meals.updated_at — when the row was last rewritten, null until it is Revision ID: 0012 Revises: 0011 Create Date: 2026-08-25 A companion to 0006's `created_at`, and nullable for a different reason. 0006 left `created_at` nullable because pre-0006 rows genuinely had no record of when they were written. This column...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0012_meals_updated_at.py
.py
54a5e3ba876acec0
7.24
2
"""calorie banking: calorie_plan_days Revision ID: 0013 Revises: 0012 Create Date: 2026-08-25 One table and no settings column, for the reason 0011 gives: an adjustment belongs to a day, not to the account, so there is nothing to hang off the settings row and nothing to backfill on it. The unique index is the one to...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0013_calorie_plan_days.py
.py
23f18c14bc50df83
7.24
2
"""weigh-in reminder: settings.weigh_in_reminder_time + _days Revision ID: 0014 Revises: 0013 Create Date: 2026-08-27 Two columns on an existing table and no new table, so the eleven-item checklist does not apply -- the six-item settings-column one does. The two columns are deliberately not the same shape, and the a...
Abdulla1x/Macros-Calculator
backend/alembic/versions/0014_settings_weigh_in_reminder.py
.py
30e1535c4b34e5e8
7.24
2
import os import jwt from fastapi import Depends, HTTPException from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from sqlalchemy.orm import Session from ..db import get_db from ..models import User from .security import decode_token _bearer = HTTPBearer(auto_error=False) # Admins are named in a...
Abdulla1x/Macros-Calculator
backend/app/auth/deps.py
.py
41bc3db2bed2a25e
7.24
2
import hashlib import logging import os import secrets from datetime import datetime, time, timedelta, timezone from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request from sqlalchemy import delete, func, select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from ...
Abdulla1x/Macros-Calculator
backend/app/auth/router.py
.py
9c05e4dc9d46aa04
7.24
2
"""Password hashing (Argon2) and JWT access tokens.""" import logging import os from datetime import datetime, timedelta, timezone import jwt from pwdlib import PasswordHash from ..db import get_database_url from ..env import env_float logger = logging.getLogger(__name__) ALGORITHM = "HS256" TOKEN_DAYS_ENV = "ACCES...
Abdulla1x/Macros-Calculator
backend/app/auth/security.py
.py
a2585a816c910850
7.24
2
"""Calorie banking: moving calories between days without moving the week. The arithmetic only. No database, no request, no `today` of its own -- every function takes what it needs, so all of it is testable without a fixture, the way `calculations.py` is. Two things happen here, and they are not the same thing: * *...
Abdulla1x/Macros-Calculator
backend/app/banking.py
.py
571ada35e889f4e2
7.24
2
"""Calibration: how the AI's estimates compare to what you actually saved. The arithmetic only. No database, no request, no `now` of its own -- every function takes what it needs, so all of it is testable without a fixture, the way `calculations.py` is. Every meal analysis is shown to the user as a point estimate ins...
Abdulla1x/Macros-Calculator
backend/app/calibration.py
.py
1bffed0a5c93a16a
7.24
2
import os import sqlite3 from collections.abc import Iterator from pathlib import Path from sqlalchemy import create_engine, event from sqlalchemy.engine import Engine from sqlalchemy.orm import Session # Default to a repo-root SQLite file for zero-config local development. DEFAULT_SQLITE_URL = f"sqlite:///{Path(__fi...
Abdulla1x/Macros-Calculator
backend/app/db.py
.py
54f2c6626e162968
7.24
2
"""Numeric settings read from the environment, parsed so a typo cannot 500. Every one of these is set in the Render dashboard, and `render.yaml` is not synced to it -- the dashboard is the only source of truth, which makes it exactly where a typo lives. These readers run inside request handlers, so an unparseable valu...
Abdulla1x/Macros-Calculator
backend/app/env.py
.py
9194d5cc1446c0b7
7.24
2
import logging import math import os from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from slo...
Abdulla1x/Macros-Calculator
backend/app/main.py
.py
b40b324f36f560d3
7.24
2
"""Operator metrics: how many people use this app, and how much. PRIVACY BOUNDARY — read this before adding a field. Every other router here is scoped to the authenticated user. This one deliberately is not, which is exactly why it is the only router behind `require_admin`. What it may expose is **counts, dates and a...
Abdulla1x/Macros-Calculator
backend/app/routers/admin.py
.py
7188c1638a73d805
7.24
2
"""CSV export/import of the meals table, plus a full JSON export of all data.""" import csv import io import json import math from datetime import date as date_type from datetime import datetime, timedelta, timezone from fastapi import APIRouter, Depends, HTTPException, UploadFile from fastapi.responses import Streami...
Abdulla1x/Macros-Calculator
backend/app/routers/data.py
.py
065049a391774bc4
7.24
2
from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy import case, func, select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from ..auth.deps import get_current_user from ..db import get_db from ..models import Food as FoodRow from ..models import User from ..sche...
Abdulla1x/Macros-Calculator
backend/app/routers/foods.py
.py
733850dd59d84b15
7.24
2
"""Saved meals the user can re-log in one tap. A template is a meal plus its ingredient rows. Meals themselves are flat -- the rows someone types are discarded on save -- so this is the only place those rows survive, which is what makes re-logging editable rather than all-or- nothing. No rate limiting here, per rate_...
Abdulla1x/Macros-Calculator
backend/app/routers/meal_templates.py
.py
fbc883f688b4851d
7.24
2
"""Calorie banking: moving a day's target without moving the week's. Five verbs over `calorie_plan_days`. The arithmetic and every refusal live in `app/banking.py`; this file is the database and HTTP around them. **Nothing here may write the four goal columns.** That is the invariant, and it is a different one from t...
Abdulla1x/Macros-Calculator
backend/app/routers/plan.py
.py
ee807d1070fa2542
7.24
2
import json from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from ..auth.deps import get_current_user from ..db import get_db from ..models import Setting, User from ..schemas import BodyTargets, Settings from ..targets import apply_auto_targets, compute_targets router = APIRouter(prefix="/a...
Abdulla1x/Macros-Calculator
backend/app/routers/settings.py
.py
de36539de1d1a794
7.24
2
"""Meal share codes: turn one of your meals into a string, and read one back. A code is the meal itself, not a link to it. Nothing is stored, so there is no table here, nothing to expire and nothing to revoke -- see app/share.py for the format and for why it carries no signature. **This router owns no rows, and that ...
Abdulla1x/Macros-Calculator
backend/app/routers/share.py
.py
6ce531ca34846b00
7.24
2
"""Daily step logging. Three verbs over one row per day. The shape is water's, deliberately -- that router says `/api/steps` is expected to mirror it -- with one difference that comes from the data rather than from taste: a step count is a *day*, so POST upserts the way `routers/weights.py` does instead of inserting t...
Abdulla1x/Macros-Calculator
backend/app/routers/steps.py
.py
e46cfd81aa155e3e
7.24
2
"""Daily water logging. Three verbs over event rows. `/api/steps` in a later phase is expected to mirror this shape exactly, which is the point of keeping it plain. **Nothing here may recompute calorie targets.** `routers/weights.py` and `routers/settings.py` both call `apply_auto_targets`, so copying one of them int...
Abdulla1x/Macros-Calculator
backend/app/routers/water.py
.py
ee1370ab8d1765ea
7.24
2
from datetime import date as date_type from datetime import timedelta from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy import select from sqlalchemy.orm import Session from ..auth.deps import get_current_user from ..calculations import weekly_rate, weight_trend from ..db import get_db from...
Abdulla1x/Macros-Calculator
backend/app/routers/weights.py
.py
43914d76da437789
7.24
2
"""Transactional email via Brevo. This is the ONLY Brevo-aware module: callers depend on the provider-neutral EmailError hierarchy below, so switching providers later means rewriting this file and changing env vars, nothing else. Brevo was chosen over Resend because it is the only free tier that will mail *arbitrary*...
Abdulla1x/Macros-Calculator
backend/app/services/email.py
.py
2084c75c90070cc9
7.24
2
def get_size_format(b, factor=1024, suffix="B"): """ Scale bytes to its proper byte format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' Parameters ---------- b : int size in bytes factor : int, optional conversion factor, by default 1024 suffix : str, ...
tyleracorn/avic_repo
avic/utils/file_utils.py
.py
77e2639c38637a76
7
0
import logging from pathlib import Path class ClassWithLogger: def __init__(self, name, log_file=False, logger=None, level=logging.INFO): """class for initializing a subclass with a logger Parameters ---------- name : str name of the class log_file : str ...
tyleracorn/avic_repo
avic/utils/logger.py
.py
ef0a9929d9ad3bc8
7
0
import datetime def get_date(): return datetime.datetime.now().strftime("%Y-%m-%d") def get_date_12hr_min(): return datetime.datetime.now().strftime("%Y-%m-%d: %I:%M%p") def get_date_24hr_min(): return datetime.datetime.now().strftime("%Y-%m-%d: %H:%M") def listify(variable): """ Convert a give...
tyleracorn/avic_repo
avic/utils/utils.py
.py
602608c9da48c7df
7
0
import ffmpeg _video_suffixes = ['.mp4', '.m4v', '.mpg', '.mpeg', '.avi', '.mkv', '.mov', '.wmv', '.mts', '.ts'] def _get_video_codec(fl): """Determine the video codec of a file Parameters ---------- fl : Path path to video file Returns ------- str : video codec video c...
tyleracorn/avic_repo
avic/utils/video_utils.py
.py
5a77f9a72de807c1
7
0
"""Configuration loaders for model registry.""" import copy from importlib import resources from pathlib import Path from typing import Any import yaml from platformdirs import user_config_dir from oi.constants import DEFAULT_FALLBACK_MODEL from oi.exceptions import ConfigurationError def _ensure_user_config() -> ...
dansclearov/oi
src/oi/config/loaders.py
.py
3c205c861dcba1c5
7.24
2
"""Configuration for LLM CLI.""" import json import os import tempfile from dataclasses import dataclass, field from pathlib import Path from typing import Any from dotenv import load_dotenv from platformdirs import user_config_dir, user_data_dir def get_env_file_path() -> Path: """Get the path to oi's own env ...
dansclearov/oi
src/oi/config/settings.py
.py
e278f7ba0ec88b40
7.24
2
"""Chat management with auto-save and smart title generation.""" from functools import partial from typing import Optional from rich.console import Console from oi.config.settings import Config from oi.core.chat_repository import ChatRepository from oi.core.smart_title import SmartTitleGenerator from oi.core.session...
dansclearov/oi
src/oi/core/chat_manager.py
.py
e09b92e57cb1c040
7.24
2
"""Persistence layer for chat sessions.""" import json import shutil from datetime import datetime from pathlib import Path from typing import Callable, Optional from oi.config.settings import Config from oi.core.message_utils import ( convert_legacy_messages, count_non_system_messages, deserialize_model_m...
dansclearov/oi
src/oi/core/chat_repository.py
.py
7743ccb30451cc72
7.24
2
"""Aggregate statistics over the chat history. `StatsCollector.collect()` runs a cheap pass over chat metadata. With `deep=True` it also loads each transcript to count words said. """ from __future__ import annotations from dataclasses import dataclass, field from datetime import date, datetime, timedelta from typin...
dansclearov/oi
src/oi/core/stats.py
.py
6823c8fcf3dc3c89
7.24
2
"""Shared LLM-related data structures.""" from dataclasses import dataclass, field from typing import Any, Callable @dataclass class ModelCapabilities: """Capabilities of a specific model.""" supports_search: bool = False supports_thinking: bool = False supports_vision: bool = False supports_sub...
dansclearov/oi
src/oi/llm_types.py
.py
d2cfb6791f4f5dae
7.24
2
"""Helpers for local in-chat slash commands.""" from dataclasses import dataclass from difflib import get_close_matches from prompt_toolkit.completion import Completer, Completion @dataclass(frozen=True) class LocalCommandSpec: name: str description: str LOCAL_COMMAND_SPECS = ( LocalCommandSpec("/btw"...
dansclearov/oi
src/oi/local_commands.py
.py
4a1e4ece90f9e363
7.24
2
import re from importlib import resources from pathlib import Path from platformdirs import user_config_dir from oi.exceptions import PromptNotFoundError def read_system_message_from_file(file_name: str) -> str: """Read system message from a prompt file, checking user config first then package.""" # First t...
dansclearov/oi
src/oi/prompts.py
.py
c9c1f5edc20796d8
7.24
2
from typing import Any from oi.config.loaders import load_merged_model_config, parse_models_and_aliases from oi.exceptions import ModelNotFoundError from oi.llm_types import ModelCapabilities from oi.ui.labels import WARNING_LABEL, ansi_message # Aliases to exclude from display models EXCLUDED_ALIASES = {"default"} ...
dansclearov/oi
src/oi/registry.py
.py
182d0b6306fb9c2e
7.24
2
"""Output renderers for streaming LLM responses.""" from abc import ABC, abstractmethod from typing import Optional from rich.console import Console from rich.markup import escape from oi.llm_types import ChatOptions, ModelCapabilities from oi.ui.labels import AI_LABEL, rich_label class ResponseRenderer(ABC): ...
dansclearov/oi
src/oi/renderers.py
.py
da4eb19a36601a29
7.24
2
from __future__ import annotations import json from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Optional, Sequence # pydantic_ai imports are function-local: its package __init__ costs ~600ms, # which would otherwise land on every startup before the first prompt paints. if TYPE_CHECKING:...
dansclearov/oi
src/oi/response_handler.py
.py
3abd87549278ffc8
7.24
2
"""Formatting for server-side (native) tool call lines in the TUI. One line per call, Claude-Code-style: a green marker plus a calling-a-function description — `Web Search("query")`, `Fetch(url)`, `Code(command)`. Providers differ in arg shapes (Anthropic/xAI send `query`, Google `queries`, OpenAI Responses one `web_s...
dansclearov/oi
src/oi/tui/tool_lines.py
.py
68f4c1a4c73ebdc1
7.24
2
"""Paste support: clipboard images and large text pastes rendered as pills. Both paste kinds occupy a single Unicode Private-Use codepoint in the input buffer so backspace/vim motions treat the pill atomically. A prompt_toolkit Processor expands each sentinel into a styled pill at display time. """ from __future__ im...
dansclearov/oi
src/oi/ui/image_paste.py
.py
ed363d12df8febe9
7.24
2
from __future__ import annotations from typing import TYPE_CHECKING from prompt_toolkit.cursor_shapes import ModalCursorShapeConfig from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.keys import Keys from prompt_toolkit.shortcuts import CompleteStyle, PromptSession if TYPE_CHECKING: from pyda...
dansclearov/oi
src/oi/ui/input_handler.py
.py
07c2f71934ee5f6d
7.24
2
"""Shared label definitions and formatting helpers.""" from dataclasses import dataclass from colored import attr, fg from prompt_toolkit.formatted_text import HTML from rich.text import Text @dataclass(frozen=True) class LabelStyle: text: str ansi_style: str rich_style: str prompt_html_color: str |...
dansclearov/oi
src/oi/ui/labels.py
.py
4ba342933e2b6325
7.24
2
"""Rich rendering for `oi stats`.""" from __future__ import annotations from datetime import date, datetime, timedelta from typing import Optional from rich.console import Console from rich.markup import escape from rich.text import Text from oi.core.stats import Stats, current_streak, longest_streak from oi.text i...
dansclearov/oi
src/oi/ui/stats_view.py
.py
f1dd2efc9f54105c
7.24
2
"""Plaintext + styled transcript views shared by the chat selector. All three consumers (preview pane, $EDITOR export, body search) build on `flatten_history` so they see the same role+text view the main app renders. """ from rich.text import Text from oi.core.message_utils import flatten_history from oi.core.sessio...
dansclearov/oi
src/oi/ui/transcript.py
.py
e7767f64f03cee34
7.24
2
"""Background pre-import of pydantic_ai. pydantic_ai's package `__init__` costs ~600ms, so the startup path keeps it to function-local imports and the interactive frontends call `warm()` once their UI is up, hiding the import behind the user's first pause. Python resolves import cycles that span threads by exposing p...
dansclearov/oi
src/oi/warmup.py
.py
c1d8481be35cb8bf
7.24
2
"""Pytest configuration and fixtures.""" import tempfile import pytest @pytest.fixture(autouse=True) def isolated_user_config(tmp_path_factory, monkeypatch): """Point the user config at a temp file for every test. `Config()` reads it and `/vim` writes it, so without this the suite reads and rewrites th...
dansclearov/oi
tests/conftest.py
.py
fbd6c6d8f43ccaef
7.74
2
"""Simple plugin maker script.""" import os import sys # Config possible_paths = [ "./src/jerry_bot/plugins", "./plugins", ] base_plugin="""\"\"\"Main Module for {class_name}\"\"\" # squid_core imports from squid_core.plugin_base import Plugin, PluginCog from squid_core.framework import Framework class {cl...
squid1127/jerry-bot
scripts/make_plugin.py
.py
0a79e0ae213bc3c7
7.24
2
"""Activity tracking for Activity Roles plugin.""" from redis.asyncio import Redis import squid_core from datetime import datetime, timedelta, timezone import asyncio from .models.db import ActivityRoleEntry, ActivityRoleConfig from .models.dataclasses import ActivityRoleUpdate class ActivityTracker: """Class to...
squid1127/jerry-bot
src/jerry_bot/plugins/activity_roles/activity.py
.py
a76da8ed833188dd
7.24
2
"""Database models for Activity Roles Plugin.""" from tortoise import fields from tortoise.models import Model class ActivityRoleConfig(Model): """ Database model for activity roles configuration. Attributes: guild_id (int): The ID of the guild. Primary key. active_role_id (int): The I...
squid1127/jerry-bot
src/jerry_bot/plugins/activity_roles/models/db.py
.py
0d22b3dd93ce2326
7.24
2
"""Discord UIs, etc for AutoEmbed plugin.""" import discord def build_embed(content: dict) -> discord.Embed | None: """Build a Discord embed from a dictionary.""" try: embed = discord.Embed.from_dict(content) except Exception: return None return embed def parse_color(color_input: st...
squid1127/jerry-bot
src/jerry_bot/plugins/auto_embed/interactions.py
.py
124b8bb4a221cb3a
7.24
2
"""Main plugin file for AutoEmbed plugin.""" from squid_core import Plugin as PluginBase, PluginCog from squid_core.framework import Framework import discord from discord import app_commands from .interactions import AutoEmbedInputForm class AutoEmbedPlugin(PluginBase): """Plugin class for AutoEmbed.""" de...
squid1127/jerry-bot
src/jerry_bot/plugins/auto_embed/plugin.py
.py
3a19dcabb93e045d
7.24
2
"""Auto Reply Component for AR Plugin""" import discord from squid_core import Framework, Plugin from .jinja_manager import JinjaManager from .models.db import ( AutoReplyIgnore, AutoReplyRule, AutoReplyIgnoreData, AutoReplyRuleData, ) from .models.enums import IgnoreType from .response_handler import...
squid1127/jerry-bot
src/jerry_bot/plugins/auto_reply/ar.py
.py
ea23fd9c5fa122f9
7.24
2
"""Jinja2 manager for auto-reply rendering.""" import datetime import math import random import re import json import yaml from typing import Any import asteval import jinja2 from squid_core import Plugin from .globals import GLOBALS, GLOBALS_ASTEVAL, global_method class JinjaManager: """Manages Jinja2 environ...
squid1127/jerry-bot
src/jerry_bot/plugins/auto_reply/jinja_manager.py
.py
ded7af7ebbeb4fb4
7.24
2
"""Database Models and Types for AutoReply Plugin""" from collections.abc import Sequence from tortoise import fields from tortoise.models import Model from tortoise.expressions import Q from dataclasses import dataclass, field import regex as re from functools import cached_property from math import ceil from .enums...
squid1127/jerry-bot
src/jerry_bot/plugins/auto_reply/models/db.py
.py
990d8888dd50ab3e
7.24
2
"""Enumeration types for AutoReply Plugin""" from enum import IntEnum, auto class ResponseType(IntEnum): """Enumeration for different types of auto-reply responses.""" PLAIN = auto() RANDOM_YAML = auto() TEMPLATE = auto() ASTEVAL = auto() class ResponseMethod(IntEnum): """Enumeration for d...
squid1127/jerry-bot
src/jerry_bot/plugins/auto_reply/models/enums.py
.py
aba82a0b62eda8d9
7.24
2
"""Main Module for AutoReply""" # squid_core imports from squid_core.plugin_base import Plugin from squid_core.framework import Framework from squid_core.decorators import DiscordEventListener, CLICommandDec, RedisSubscribe from squid_core.components.cli import CLIContext, EmbedLevel # other imports import discord fr...
squid1127/jerry-bot
src/jerry_bot/plugins/auto_reply/plugin.py
.py
8f9b2329bf0595bf
7.24
2
"""At everyone command logic""" from enum import Enum import discord from discord import app_commands from squid_core import PluginCog, Plugin import regex as re MENTION_TOKENIZER = re.compile(r"\(|\)|[^\s()]+") IS_DISCORD_MENTION = re.compile(r"<@(\d+)>|<@&(\d+)>") class MentionMode(Enum): Interaction = "Intera...
squid1127/jerry-bot
src/jerry_bot/plugins/commands/at_everyone.py
.py
7d3f250696d40e78
7.24
2
"""Main plugin file for Commands plugin.""" from squid_core import Plugin, PluginCog from squid_core.framework import Framework from enum import Enum import aiohttp, bs4 import asyncio import discord from discord import app_commands from .constants import * from .at_everyone import StaticCommandAtEveryoneCog clas...
squid1127/jerry-bot
src/jerry_bot/plugins/commands/plugin.py
.py
080c9a378e0f7f8c
7.24
2
"""Configuration manager for Gemini plugin.""" import logging from pathlib import Path from typing import Optional import aiofiles from aiofiles import os as aiofiles_os from yaml import safe_load, safe_dump from .global_config import GlobalConfig class ConfigManager: """Manages configuration loading, validatio...
squid1127/jerry-bot
src/jerry_bot/plugins/gemini/config/manager.py
.py
8f756b51a25602e8
7.24
2
"""Provider and model configuration models for Gemini plugin.""" from typing import Optional, Dict, Any from pydantic import BaseModel, Field, model_validator from ..models.enums import ProviderType class LLMProfileConfig(BaseModel): """Pydantic model for individual model configuration within a provider.""" ...
squid1127/jerry-bot
src/jerry_bot/plugins/gemini/config/provider_config.py
.py
f50741f719176fc2
7.24
2
"""Conversation session-scoped context object""" from dataclasses import dataclass, field from typing import Optional from ..dc_chat.input_processor import OutputContext from ..models import Channel, LLMProfile, GuildRecord from ..provider import Provider from ..config import GlobalConfig @dataclass(slots=True, fr...
squid1127/jerry-bot
src/jerry_bot/plugins/gemini/core/context.py
.py
11330baf8556e9b3
7.24
2
"""Unified conversation processing engine for all message types.""" import time from ..models import ( Message, UserMessage, ModelMessage, SystemMessage, ExceptionMessage, ToolResponseMessage, ) from ..models.exceptions import ConversationInactivityTimeoutError from ..dc_chat import LLMContext...
squid1127/jerry-bot
src/jerry_bot/plugins/gemini/core/conversation_engine.py
.py
fc969282d467a3ae
7.24
2
"""Conversation factory and context builder for the Gemini plugin.""" from uuid import uuid4 from discord import TextChannel from discord.ext.commands import Bot from logging import Logger from ..dc_chat import OutputContext from .context import SessionContext from .session import ConversationSession from ..models ...
squid1127/jerry-bot
src/jerry_bot/plugins/gemini/core/factory.py
.py
1e9945fe0d87b087
7.24
2
"""Conversation session manager for Gemini plugin.""" from ..repo import Repositories from ..models import ConfigurationError, Message from ..dc_chat import OutputContext from .factory import ConversationFactory from .session import ConversationSession from discord.ext.commands import Bot from logging import Logger ...
squid1127/jerry-bot
src/jerry_bot/plugins/gemini/core/manager.py
.py
f40190f9cfec6f62
7.24
2
"""Message queue implementation for message processing within Gemini conversations.""" import asyncio import logging from typing import ClassVar, Protocol from ..models import Message from ..models.exceptions import ( FatalError, ProviderError, ConversationInactivityTimeoutError, ) import time class Turn...
squid1127/jerry-bot
src/jerry_bot/plugins/gemini/core/message_queue.py
.py
f4c3874de720877d
7.24
2
"""Individual, channel-scoped conversations within the Gemini plugin.""" from logging import Logger from typing import TYPE_CHECKING, Optional from ..dc_chat import OutputContext from .context import SessionContext from ..models import ChannelRecord, GuildRecord, Message, LLMProfile from .message_queue import Messag...
squid1127/jerry-bot
src/jerry_bot/plugins/gemini/core/session.py
.py
e9487002a6e4d833
7.24
2
"""Turn engine for orchestrating one conversation turn at a time.""" import asyncio from dataclasses import dataclass import logging import traceback from typing import TYPE_CHECKING, AsyncIterator from .context import SessionContext from ..dc_chat import LLMContextGenerator, OutputContext from ..models import ( ...
squid1127/jerry-bot
src/jerry_bot/plugins/gemini/core/turn_engine.py
.py
b841c56e4aa8d09e
7.24
2
"""Abstraction layer for configuration UI, allowing for Discord UI to interface with core logic""" from ..repo import Repositories from .manager import ConversationManager from ..models import ChannelRecord, Channel, GuildRecord, LLMProfile, LLMProfileRecord from ..provider import Provider class UIService: """Se...
squid1127/jerry-bot
src/jerry_bot/plugins/gemini/core/ui_service.py
.py
f2cfafe196e2e04b
7.24
2
""" Download the geojson files from the Mobile libraries API and save to data directory. """ import json import os import requests GEOJSON_STOPS_URL = 'https://api.mobilelibraries.org/api/stops?limit=20000' GEOJSON_TRIPS_URL = 'https://api.mobilelibraries.org/api/trips' def download_geojson(url): """Download th...
LibrariesHacked/mobilelibraries-tiles
download.py
.py
8c28f6379a7d2f8f
7.15
1
import json import os from functools import cached_property # OpenCode's ACP mode runs bash/edit UNSUPERVISED by default -- verified against # opencode 1.18.16: a `uname -a` and a file write both executed while emitting # ZERO session/request_permission requests. KiroCrew's governance gate is *fed # by* those requests...
layertwo/homelab
containers/kirocrew-opencode/src/kirocrew_shim/environment.py
.py
923507404bd055b5
7
0
"""The stdio plumbing: two pump threads moving ndjson between client and agent. Why a proxy and not a wrapper: a wrapper that `exec`s vanishes from the pipe and can only influence argv. One that stays alive owns both directions of the stream and can rewrite every message -- which is what makes zero KiroCrew patches po...
layertwo/homelab
containers/kirocrew-opencode/src/kirocrew_shim/proxy.py
.py
783a1841b7bc6220
7
0
"""Pure translation between KiroCrew's ACP dialect and standard ACP. No I/O happens here: every function takes decoded values and returns decoded values, so the whole dialect gap is unit-testable without spawning an agent. The four verified incompatibilities, all absorbed here rather than by patching KiroCrew (see do...
layertwo/homelab
containers/kirocrew-opencode/src/kirocrew_shim/translate.py
.py
461b3fdc720becfd
7
0
import io import pytest @pytest.fixture def model() -> str: return "ollama-cloud/gpt-oss:120b" @pytest.fixture(autouse=True) def clean_env(monkeypatch): """Keep a developer's real OpenCode config out of the tests.""" for key in ("OPENCODE_MODEL", "OPENCODE_BIN", "OPENCODE_PERMISSION"): monkeypa...
layertwo/homelab
containers/kirocrew-opencode/tests/conftest.py
.py
187435149a2cf624
7.5
0
"""Flask application for the OIDC to SAML bridge.""" import logging import secrets from typing import Any, Optional import requests from flask import Flask, redirect, request, session from markupsafe import escape from oidc_saml_bridge.environment import ServiceProvider from oidc_saml_bridge.saml import parse_authn_...
layertwo/homelab
containers/oidc-saml-bridge/src/oidc_saml_bridge/app.py
.py
c1bda71a6d5de2a4
7
0
"""OIDC client for authenticating with pocket-id.""" from functools import cached_property from typing import Any from urllib.parse import urlencode import jwt import requests class OIDCClient: """OpenID Connect client for pocket-id.""" def __init__( self, issuer: str, client_id: st...
layertwo/homelab
containers/oidc-saml-bridge/src/oidc_saml_bridge/oidc.py
.py
5c54fa4c215ba119
7
0
""" autoregressive.py - Trains a Byte-Level BPE tokenizer on linearized constituency parses. - Builds a GPT-2 style causal LM from scratch (random init). - Fine-tunes / trains on the parse corpus. - Evaluates average cross-entropy (bits per token equivalent can be derived). Usage: python autoregressive.py --parses da...
Aatlantise/prosody-syntax-interface
constituency/autoregressive.py
.py
2d07445371b19752
7
0
""" getting surprisal values for words in convo-ados dataset """ import pandas as pd import numpy as np from tqdm import tqdm import argparse import warnings from typing import Iterable from dataclasses import dataclass import torch from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM from glob im...
Aatlantise/prosody-syntax-interface
constituency/candor/get_surprisals_candor.py
.py
e8fc27a0fc41544b
7
0
import os import pandas as pd from pathlib import Path import string from glob import glob from tqdm.contrib.concurrent import process_map import traceback import re def clean_words_vectorized(series): """Vectorized cleaning: Lowercases, strips whitespace, and removes punctuation.""" # Create a regex pattern ...
Aatlantise/prosody-syntax-interface
constituency/candor/merge_mfa_durations_candor.py
.py
6d845e75d76d3843
7
0
import pandas as pd import re def load_data(filepath): """ Tabular prosody data to df :param filepath: :return: dataframe """ df = pd.read_csv(filepath, sep='\t', names=["start", "end", "token"], keep_default_na=False) return df def load_celex_syllables(celex_path="/home/jm3743/prosody-sy...
Aatlantise/prosody-syntax-interface
constituency/data.py
.py
2736e5049f1069aa
7
0
import pandas as pd import numpy as np from pathlib import Path def load_and_align(path_dict): """ Loads multiple CSVs and merges them into a single DataFrame aligned by 'original_index'. """ merged_df = None dfs = [] for name, path in path_dict.items(): if not Path(path).exists(): ...
Aatlantise/prosody-syntax-interface
constituency/significance.py
.py
588b9c1d41c7d225
7
0
"""Parser for AI conference deadlines. Source: the Hugging Face ``ai-deadlines`` project, the actively maintained successor to the now-dead aideadlin.es. The data lives as one YAML file per conference under ``src/data/conferences/`` in the GitHub repo, each file holding a list of per-year entries. We list the directo...
luarss/awesome-conference-dates
parsers/ai_deadlines.py
.py
018c2dafe084e3ed
7.35
4
"""Parser for the ccf-deadlines dataset (github.com/ccfddl/ccf-deadlines). ccf-deadlines keeps one hand-maintained YAML file per conference series, which is far more reliable than scraping individual conference sites. We download the whole repository as a single gzipped tarball (one HTTP request), parse every ``confer...
luarss/awesome-conference-dates
parsers/ccf_deadlines.py
.py
fbec9f6a87e4ac0c
7.35
4
"""Parser for the IEEE CAS (Circuits and Systems Society) event feed. The public page https://ieee-cas.org/conference-events/full-conference-list is a Drupal view with a "Load More" button. The old implementation drove that button with Selenium, which was flaky (it returned 0, 18 or 36 duplicated events on different r...
luarss/awesome-conference-dates
parsers/ieee_cas.py
.py
401b857459728f99
7.35
4
import re TYPE_ID_MP3_IDS_MAP = { "2": ["A", "B", "C"], "4": ["A", "B", "C"], "5": ["A", "B", "C"], "6": ["A", "B", "C", "D", "E"], "8": ["A", "B", "C", "D", "E"], "9": ["A", "B", "C", "D", "E"], } TYPE_ID_TYPE_NAME_MAP = { "1": "word", "2": "sentence", "3": "recognize", "4": "...
FormoSpeech/klokah_crawler
klokah_crawler/utils/parse_sp.py
.py
dceb14108bae48b0
7.3
3
""" Row-ordering helpers via hierarchical clustering. Inputs are plain numpy arrays. No file I/O, no AnnData dependency. Factored out of what were three independent copies of the same Ward-linkage block-ordering logic across project driver scripts. """ from __future__ import annotations import numpy as np from scipy...
jkmckenna/smftools
src/smftools/analysis/compute/clustering.py
.py
89c692a20b717c8b
7.3
3
""" metrics_store.py — Per-run Zarr store for computed per-read analysis metrics. Keeps raw signal caches pristine by storing derived metrics separately. Row ordering matches the companion <run>.zarr barcode-sorted obs. Structure:: <run>_metrics.zarr/ obs/ ls_nrl_bp_<mask> float (n_obs...
jkmckenna/smftools
src/smftools/analysis/compute/metrics_store.py
.py
6d0e10fedc05bd23
7.3
3
""" Matrix-level helpers for binary classifier fitting and evaluation. Inputs are feature matrices, labels, and metadata-derived parameters. No AnnData access or file I/O occurs here. """ from __future__ import annotations import numpy as np from sklearn.metrics import ( accuracy_score, auc, balanced_acc...
jkmckenna/smftools
src/smftools/analysis/compute/ml_metrics.py
.py
41431b0cae62b6f1
7.3
3