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 |
|---|---|---|---|---|---|---|
"""LLM 제공자 공통 인터페이스.
Gemini로 먼저 만들지만 나중에 Claude와 GPT를 같은 자리에 끼울 수 있도록,
화면은 이 인터페이스만 알고 구체 제공자는 모르게 둔다.
"""
from __future__ import annotations
import json
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Iterator
from utils.parsing import article_jo_label
class Llm... | hgkang17/law_info_search | llm/base.py | .py | 940189ac31cca927 | 7 | 0 |
"""Claude Code CLI 제공자.
이 컴퓨터에 설치된 claude CLI(Claude Code)를 별도 프로세스로 불러
대화한다. API 키가 없다 — claude CLI가 이미 로그인해 둔 Claude 구독
(Pro/Max)의 사용량으로 그대로 돈다. 대신 다음 두 가지가 미리 되어
있어야 한다.
1. claude CLI 설치와 로그인 (`claude auth login` 또는 터미널에서 한 번
`claude`를 실행해 로그인).
2. 프로그램 위쪽 "API 인증키" 칸에 국가법령정보 OC 인증키 입력.
법령검색 MCP 설정은 매 요청에 프로그램... | hgkang17/law_info_search | llm/claude_code.py | .py | 44b6bfd3adbbc385 | 7 | 0 |
"""Claude CodeㆍCodex CLI가 남긴 영문 오류를 한글 설명으로 바꾼다.
두 CLI 모두 실패하면 종료 코드와 영문 stderr만 남긴다. 화면에 그대로
띄우면 무엇이 잘못됐는지, 무엇을 하면 되는지 알 수 없어서 여기서 한 번
사람 말로 풀어 준다.
두 CLI 다 성공은 0, 실패는 0이 아닌 값만 쓰고 값마다 뜻을 정해 두지
않았다. 그래서 종료 코드로는 운영체제가 정한 것(신호로 죽음, 명령 없음)
만 알아보고, 나머지는 stderr 문구로 가린다.
"""
from __future__ import annotations
import re
... | hgkang17/law_info_search | llm/cli_errors.py | .py | 811c469a441eb28c | 7 | 0 |
"""Claude/Codex가 이 프로그램의 법령 MCP 서버를 띄우는 방법.
소스 실행 중에는 현재 파이썬으로 ``mcp_server.server`` 모듈을 실행한다.
PyInstaller onefile 배포본에서는 같은 실행 파일을 ``--mcp-server`` 모드로
다시 띄운다. 이 한 곳에서 명령을 만들면 Claude Code와 Codex app-server가
항상 같은 법령 도구를 사용한다.
"""
from __future__ import annotations
import json
import os
import shutil
import subproce... | hgkang17/law_info_search | llm/desktop_mcp.py | .py | 63057a37c95495c1 | 7 | 0 |
"""검색으로 알게 된 법령 id → 이름.
도구 호출 인자에는 법령 id만 있고 이름이 없다. 진행줄에 숫자 id를 그리지
않도록, 검색 결과가 나올 때마다 여기 적어 두고 화면이 약칭을 찾는다.
"""
from __future__ import annotations
import json
from storage.paths import AI_TOOL_SEARCH_CACHE_DIR
_NAME_INDEX_PATH = AI_TOOL_SEARCH_CACHE_DIR / "id_names.json"
def _load_index() -> dict[str, dict[st... | hgkang17/law_info_search | llm/document_labels.py | .py | b3cc5837e60cd9a5 | 7 | 0 |
"""중앙부처 질의회신 기관을 고른다."""
from __future__ import annotations
import re
from molit_cgm_expc_api import AGENCIES, AGENCY_BY_TARGET, AgencyConfig
_ALL_KEYS = {"", "all", "전체", "전체기관"}
def is_inquiry_target(value: str) -> bool:
"""법제처 중앙부처 질의회신 기관 target인지."""
return str(value or "").strip() in AGENCY_BY_TARGE... | hgkang17/law_info_search | llm/inquiries.py | .py | ff8b4636f7010728 | 7 | 0 |
"""법령 약칭을 정식 명칭으로 풀어 검색한다.
법제처 목록 검색은 정식 제명에 강하고 `국토계획법` 같은 실무 약칭에는
약하다. 약칭표를 두고 재검색하되, 풀네임으로 물어봤는데 쿼리와 무관한
법령만 잔뜩 오면 그 결과는 버린다. 없는 법을 있는 것처럼 보여 주는
편이 더 나쁘다.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
# 가운뎃점 표기 차이. 법제처 제명은 ㆍ, 실무·모델 출력은 · 가 흔하다.
_INTERPUNCT = str.maketrans(
... | hgkang17/law_info_search | llm/law_aliases.py | .py | d61b16e51e6aaaa4 | 7 | 0 |
"""AI 검색 도구의 응답을 파일로 담아 두는 얇은 캐시.
같은 답 하나를 만드는 동안 모델은 법령을 대여섯 번씩 오간다. 게다가
Claude는 질문마다 MCP 서버를 새 프로세스로 띄우므로 메모리에 들고
있어 봐야 다음 질문에서는 사라진다. 그래서 파일로만 이어 붙인다.
storage/cache.py를 쓰지 않는 이유는 그쪽이 PySide6를 끌어오기 때문이다.
MCP 서버는 질문마다 새로 뜨는데 Qt까지 얹으면 그만큼 늦어진다. 여기서
필요한 것은 "문자열 하나를 정해진 시간 동안 들고 있기"뿐이라 따로 둔다.
"""
from __future__ impor... | hgkang17/law_info_search | llm/tool_cache.py | .py | aa2ea1a453567b5e | 7 | 0 |
"""AI 답에 적힌 조문 인용이 법제처에 실존하는지 확인한다.
화면의 조항호목 팝업과 같은 API(eflawjosub)로 그 조만 읽는다.
조 하나 확인하려고 법령 전문을 받지 않는다.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from html import escape
from urllib.parse import quote
import molit_cgm_expc_api as api
from llm.document_labels import lookup_c... | hgkang17/law_info_search | llm/verify_citations.py | .py | 8d2226a3f68b287c | 7 | 0 |
"""국가법령정보 통합검색 실행 진입점."""
from __future__ import annotations
from pathlib import Path
import sys
def main() -> int:
# 내려받은 새 onefile EXE가 기존 EXE의 종료를 기다렸다 교체하는 모드다.
# Qt를 불러오기 전에 처리해야 도우미가 작고 빠르게 끝난다.
if "--apply-update" in sys.argv[1:]:
from utils.updater import apply_update_mode
index... | hgkang17/law_info_search | main.py | .py | 09cb1a0ec07deb1c | 7 | 0 |
"""프로그램이 파일을 저장하는 위치.
이 폴더에 들어가는 것은 캐시만이 아니다. 저장한 본문에 사용자가 직접
붙인 메모와 즐겨찾기 구성(폴더ㆍ순서)이 같은 json에 함께 들어간다. 이
둘은 API로 다시 받아 올 수 없으므로, 폴더를 지우거나 옮기는 코드를 쓸
때는 캐시가 아니라 사용자 자료로 다룬다.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
# storage/paths.py 기준으로 한 단계 위가 프로그램 폴더다.
APP_DIR = Path(__... | hgkang17/law_info_search | storage/paths.py | .py | 758c9d5df2a81fce | 7 | 0 |
"""테스트 공통 준비."""
from __future__ import annotations
import os
import shutil
import tempfile
from pathlib import Path
# UI 시험이 실제 창을 띄우면 작업 화면에 에이전트 창이 깜빡인다.
# 각 테스트 파일이 PySide6를 가져오기 전에 여기서 먼저 막는다.
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
@pytest.fixture(autouse=True)
def isolate_ai_too... | hgkang17/law_info_search | tests/conftest.py | .py | 6d823da7bb999725 | 7.5 | 0 |
"""문장 중간에서 끊긴 ``다.)`` 꼬리가 목으로 잘못 그려지지 않는지 검증."""
import os
import re
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
from utils.formatting import body_to_html
from utils.parsing import merge_sentence_tail_item_lines
def _plain(html: str) -> list[str]:
"""렌더된 HT... | hgkang17/law_info_search | tests/test_admin_rule_sentence_tail.py | .py | 93a9baac78338de5 | 7.5 | 0 |
"""ui/tabs/ai_chat_panel.py의 순수 변환 로직 검증.
화면 없이도 확인할 수 있는 부분만 다룬다 — 실제 위젯 렌더링ㆍ네트워크
호출은 이 파일이 아니라 수동 검증으로 이미 확인했다.
"""
import os
import re
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from ui.tabs.ai_chat_panel import AiChatPanel
def test_to_html_converts_citation_link() -> None:
"""모델 인용은 본문 화면과 같은 조... | hgkang17/law_info_search | tests/test_ai_chat_panel.py | .py | eddb38935485b370 | 7.5 | 0 |
"""Fake installed library; xylophone_marker_token identifies dep-only text."""
def clamp(value, low, high):
return max(low, min(high, value))
class Widget:
def __init__(self, size):
self.size = size
def grow(self, amount):
self.size = clamp(self.size + amount, 0, 100)
| thefilesareinthecomputer/dotagents | skills/code-kg/tests/fixture-deps/.venv/lib/python3.12/site-packages/helperlib/core.py | .py | 8bbcdbc0e5f720b6 | 7 | 0 |
"""Seed the database with a demo org and user."""
from django.core.management.base import BaseCommand
from core.models import Org, User
class Command(BaseCommand):
help = "Create demo records."
def handle(self, *args, **options):
org, _ = Org.objects.get_or_create(name="Demo", slug="demo")
U... | thefilesareinthecomputer/dotagents | skills/code-kg/tests/fixture-django/core/management/commands/seed.py | .py | 83d1b8db391b2ef3 | 7 | 0 |
"""Request middleware, wired via the MIDDLEWARE settings string."""
class TenantMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.tenant = getattr(request.user, "org", None)
return self.get_response(request)
| thefilesareinthecomputer/dotagents | skills/code-kg/tests/fixture-django/core/middleware.py | .py | 49bba66a68849296 | 7 | 0 |
"""DRF permission classes enforcing org isolation and billing-admin gates."""
from rest_framework.permissions import BasePermission, SAFE_METHODS
class IsOrgMember(BasePermission):
"""Only authenticated users may touch org-scoped resources."""
def has_permission(self, request, view):
return bool(requ... | thefilesareinthecomputer/dotagents | skills/code-kg/tests/fixture-django/core/permissions.py | .py | 13aafe3da8ac9659 | 7.5 | 0 |
"""Reporting service: aggregate figures for dashboards and the revenue API."""
from decimal import Decimal
from core.models import Invoice
from core.selectors import outstanding_invoices, overdue_invoices, revenue_by_customer
from core.utils import money, percent, summarize_amounts
def collection_summary(org):
"... | thefilesareinthecomputer/dotagents | skills/code-kg/tests/fixture-django/core/services/reports.py | .py | d18b03a4467b888e | 7.5 | 0 |
#!/usr/bin/env python3
"""系列廣告 Short 一站式產線(固化流程)。在系列資料夾根目錄執行:
python3 tools/build_short.py # 配音 → 渲染 → BGM 混音
python3 tools/build_short.py --upload # 上一步全做 + 上傳 unlisted
步驟:
1. 配音合成 tools/build_short_intro_voice.py(MiniMax 克隆聲,NARRATION 在此檔改)
2. BGM 生成 本機 MiniMax Music 3(tools/music3.py),up... | odafeng/series-studio | claude/series-studio/template/tools/build_short.py | .py | 033213815257bd47 | 7 | 0 |
#!/usr/bin/env python3
"""系列廣告 Short《你早就在用機器學習》配音合成(垂直 1080x1920)。
沿用 build_voice.py 的 MiniMax 克隆聲與內容雜湊,只產出 shortIntro 專用 manifest
+ 音檔 + srt。在系列資料夾根目錄執行:
python3 tools/build_short_intro_voice.py
"""
import json
import sys
from pathlib import Path
ROOT = Path.cwd()
sys.path.insert(0, str(ROOT / "tools"))
# build_... | odafeng/series-studio | claude/series-studio/template/tools/build_short_intro_voice.py | .py | 5eccc9fa3a09dfbf | 7 | 0 |
#!/usr/bin/env python3
"""生成純樂器 BGM 種子 → remotion/public/audio/bgm_{preset}_seed.mp3。
後端是**本機的 MiniMax Music 3 開源權重**(`tools/music3.py`),不是 MiniMax 雲端 API。
`POST /v1/music_generation` 在 2026-08 對新用戶關閉(HTTP 410 / 2153),
官方在錯誤訊息裡指向開源權重,所以改走那條。安裝步驟見 music3.py 的 docstring。
CLI 與舊版相容(`--preset` / `--out` 照舊),另外多了:
--s... | odafeng/series-studio | claude/series-studio/template/tools/generate_bgm.py | .py | 71cd032f96d27d11 | 7 | 0 |
#!/usr/bin/env python3
"""腳本 lint — 交稿前自動掃過,取代「編劇要記得自己掃」。
規則的單一真相是 `voice-style.md`:破音字對照表直接從那份文件解析,
所以改文件就等於改規則,兩邊不會漂移。句構規則(破折號、28 字斷點…)
邏輯性太強,寫在本檔。
用法:
python3 tools/lint_script.py --ep 1
python3 tools/lint_script.py --selftest
exit 0 = 沒有 ERROR(WARN 不擋);exit 1 = 有 ERROR。
"""
import argparse
import re
impo... | odafeng/series-studio | claude/series-studio/template/tools/lint_script.py | .py | cd8f3b4075a9629b | 7 | 0 |
#!/usr/bin/env python3
"""MiniMax Music 3 的本機推論後端(Apple Silicon / MLX)。
**為什麼不再打 API**:MiniMax 的 `POST /v1/music_generation` 在 2026-08 對新用戶關閉,
所有 model 一律回 `HTTP 410 / status_code 2153`(本專案兩把金鑰都試過,含付費那把)。
官方在錯誤訊息裡指向開源權重 `MiniMaxAI/MiniMax-Music3`,這支就是接那條路。
用的是社群量化的 `mlx-community/MiniMax-Music3-4bit`(9.2 GB,M4 Pro / ... | odafeng/series-studio | claude/series-studio/template/tools/music3.py | .py | eee0ca78c82cdf18 | 7 | 0 |
from __future__ import annotations
import json
from datetime import UTC, datetime
from pathlib import Path
from limbus_librarian.sources import RawPage
class DumpSourceConnector:
"""Load a local JSONL dump of wiki pages (one RawPage per line)."""
source_id = "limbuscompany_wiki"
def __init__(self, dum... | CantBush/LimbusLibrarian | src/limbus_librarian/sources/dump.py | .py | c867e9e11c79d2c8 | 7 | 0 |
"""Deterministic placeholder Dreamer for development and end-to-end testing.
The MockDreamer lets the full AIVE loop (Checker -> Planner -> *Dreamer* ->
Re-check -> Answerer) run without a trained generative world model. It does not
learn anything; it simply returns a view for the next step:
* ``identity`` — returns ... | zmwu-ai/AIVE-2026 | dreamer/mock.py | .py | 5f55396ffba084e1 | 7 | 0 |
"""A scripted VLM adapter for offline pipeline testing.
Returns canned responses based on the active system prompt, so the full AIVE
loop can be exercised without any API access.
"""
from typing import Any
from utils.ModelAdapter import BaseModelAdapter
class DummyVLMAdapter(BaseModelAdapter):
"""Deterministic... | zmwu-ai/AIVE-2026 | tests/dummy_vlm.py | .py | 578aa0864355f408 | 7.5 | 0 |
"""Unit tests for CLI argument parsing and paper-aligned defaults."""
from utils.args import build_parser
def test_defaults_match_paper():
args = build_parser().parse_args([])
# exploration budget T = 3 (paper §5.1)
assert args.max_steps_per_question == 3
# action space: forward up to 3 m in 0.25 m s... | zmwu-ai/AIVE-2026 | tests/test_args.py | .py | 22fd0bcbfac3a0b5 | 7.5 | 0 |
"""SAT dataset preparation for AIVE evaluation.
Downloads the SAT (Spatial Aptitude Training) benchmark from HuggingFace
(``array/SAT``), persists the RGB views as PNG files, and writes a
``{split}.json`` file with one normalised record per question.
The output layout is consumed directly by :class:`pipelines.AIVE_ba... | zmwu-ai/AIVE-2026 | utils/data_process.py | .py | 987de167f723e2fb | 7 | 0 |
"""
Thread-safe caching utilities for the RUBLI API.
Replaces ad-hoc _cache = {} patterns with bounded, thread-safe TTLCache.
All caches are size-bounded (maxsize) and time-bounded (ttl seconds).
"""
import threading
from cachetools import TTLCache
class AppCache:
"""Application-wide cache registry. Thread-safe ... | rodanaya/yangwenli | backend/api/cache.py | .py | e1201bf4c76a2062 | 7.39 | 5 |
"""Database connection and common dependencies for the API."""
import sqlite3
import os
from pathlib import Path
from contextlib import contextmanager
from typing import Generator
from fastapi import Header, HTTPException, status
# Write-key auth — set RUBLI_WRITE_KEY env var to enable.
# In production (RUBLI_ENV != ... | rodanaya/yangwenli | backend/api/dependencies.py | .py | 4f97e138704de987 | 7.39 | 5 |
"""
Helper functions for analysis endpoints.
Extracts common patterns to reduce code duplication.
"""
import json
import sqlite3
from typing import Optional, List, Tuple, Any, Dict
def build_where_clause(
conditions: List[str],
params: List[Any],
sector_id: Optional[int] = None,
institution_id: Opti... | rodanaya/yangwenli | backend/api/helpers/analysis_helpers.py | .py | 8c5e69934c82b6c6 | 7.39 | 5 |
"""JWT authentication middleware for RUBLI API."""
import os
from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from jose import jwt, JWTError
JWT_SECRET = os.environ.get("RUBLI_JWT_SECRET", "rubli-dev-secret-change-in-p... | rodanaya/yangwenli | backend/api/middleware/auth_jwt.py | .py | 2af0b55e711d7b52 | 7.39 | 5 |
"""
Global error handlers for the RUBLI API.
Translates exceptions into consistent JSON error responses.
Never exposes internal details to clients.
"""
import sqlite3
import structlog
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
logger = structlog.get_logger("rubli.api.errors")
c... | rodanaya/yangwenli | backend/api/middleware/error_handler.py | .py | e73b188ab52372c6 | 7.39 | 5 |
"""
Request logging middleware with structured JSON output.
Logs every request with method, path, status, duration.
Warns on slow queries (>2000ms).
Adds X-Request-ID header for tracing.
"""
import time
import uuid
import structlog
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests impor... | rodanaya/yangwenli | backend/api/middleware/logging_middleware.py | .py | 58f8c88e51c37534 | 7.39 | 5 |
"""Common Pydantic models for pagination and responses."""
from pydantic import BaseModel, Field
from typing import TypeVar, Generic, List
from datetime import datetime
T = TypeVar("T")
class PaginationMeta(BaseModel):
"""Pagination metadata for list responses."""
page: int = Field(..., description="Current... | rodanaya/yangwenli | backend/api/models/common.py | .py | 8dd59c397f798562 | 7.39 | 5 |
"""
Pydantic models for contract endpoints.
"""
from datetime import date
from typing import Optional, List
from pydantic import BaseModel, Field, model_validator
class ContractBase(BaseModel):
"""Base contract model with common fields."""
id: int
contract_number: Optional[str] = None
title: Optional[... | rodanaya/yangwenli | backend/api/models/contract.py | .py | b85b73dbefac280e | 7.39 | 5 |
"""Pydantic models for industry taxonomy endpoints."""
from pydantic import BaseModel, ConfigDict, Field
from typing import List, Optional
from datetime import datetime
class IndustryResponse(BaseModel):
"""Single industry in the taxonomy."""
id: int = Field(..., description="Industry ID (1001-1035)")
co... | rodanaya/yangwenli | backend/api/models/industry.py | .py | 58dadb522690239f | 7.39 | 5 |
"""
Pydantic models for procurement scandals (Case Library).
"""
from __future__ import annotations
from typing import Any, List, Optional, Union
from pydantic import BaseModel
class KeyActor(BaseModel):
name: str
role: str # vendor | official | institution | journalist
title: Optional[str] = None
n... | rodanaya/yangwenli | backend/api/models/scandal.py | .py | aeb4f9e27a0c1617 | 7.39 | 5 |
"""
Pydantic models for sector endpoints.
"""
from typing import Optional, List
from pydantic import BaseModel, Field
class SectorBase(BaseModel):
"""Base sector model."""
id: int
code: str
name: str
color: str
class SectorStatistics(BaseModel):
"""Statistics for a single sector."""
sect... | rodanaya/yangwenli | backend/api/models/sector.py | .py | 334e54d32ffc7e49 | 7.39 | 5 |
"""Pydantic models for classification statistics endpoints."""
from pydantic import BaseModel, Field
from typing import List, Dict, Optional
from datetime import datetime
class IndustryCoverage(BaseModel):
"""Coverage statistics for a single industry."""
industry_id: int
industry_code: str
industry_n... | rodanaya/yangwenli | backend/api/models/stats.py | .py | b9f7ce72ffd3092f | 7.39 | 5 |
"""
Alert feed endpoint.
GET /api/v1/alerts/feed
Returns recent critical-risk contracts as an investigation alert feed.
"""
import logging
import sqlite3
from typing import Optional, List
from fastapi import APIRouter, Query
from pydantic import BaseModel
from ..dependencies import get_db
logger = logging.getLogger(... | rodanaya/yangwenli | backend/api/routers/alerts.py | .py | 667d17b0d52b95ad | 7.39 | 5 |
"""
Case Library router — documented procurement scandals.
Endpoints:
GET /cases List all cases with optional filters
GET /cases/stats Aggregate statistics
GET /cases/{slug} Full detail for one case
GET /cases/by-sector/{sector_id} Cases for a sector
"""
from __future__ import annota... | rodanaya/yangwenli | backend/api/routers/cases.py | .py | b755a76ab2419060 | 7.39 | 5 |
"""API router for industry taxonomy endpoints."""
import threading
import time
from fastapi import APIRouter, HTTPException
from typing import Optional
from ..dependencies import get_db
from ..models.industry import IndustryResponse, IndustryListResponse
router = APIRouter(prefix="/industries", tags=["industries"])
... | rodanaya/yangwenli | backend/api/routers/industries.py | .py | 4a22d490c6d53d84 | 7.39 | 5 |
from __future__ import annotations
import json
import logging
import logging.handlers
import os
from datetime import datetime, timezone
# Mirrors Hugging Face's LOG_LEVEL convention; use BEACON_ prefix to avoid collisions.
_LOG_LEVEL = os.getenv("BEACON_LOG_LEVEL", "WARNING").upper()
_LOG_DIR = os.getenv("BEACON_LOG_... | arno49/observability-agentic-harness | corpus/beacon/beacon_logging.py | .py | 46e30baadb760484 | 7 | 0 |
from __future__ import annotations
import json
from pathlib import Path
_DISEASES_DIR = Path(__file__).parent / "data" / "diseases"
_ALL_DISEASES: list[dict] = [
json.loads(p.read_text())
for p in sorted(_DISEASES_DIR.glob("*.json"))
]
def lookup_disease_profile(standardized_name: str) -> dict | None:
... | arno49/observability-agentic-harness | corpus/beacon/prompts.py | .py | eda02978fe92c453 | 7 | 0 |
"""Celery tasks for AI explanation generation."""
import logging
import anthropic
from celery import shared_task
from django.conf import settings
from apps.questions.models import Answer, Question
from .models import Explanation, PersonalizedExplanation
from .prompts import (
EXPLANATION_SYSTEM,
EXPLANATION_... | arno49/observability-agentic-harness | corpus/examcopilot/backend/apps/ai_service/tasks.py | .py | e8b072d7406c56dc | 7 | 0 |
"""AI explanation views.
POST /api/v1/ai/explain/ — synchronous endpoint with caching and rate limiting.
GET /api/v1/ai/explain/{question_id}/ — legacy async endpoint (Celery).
"""
import logging
import anthropic
from django.conf import settings
from django.utils import timezone
from rest_framework import permission... | arno49/observability-agentic-harness | corpus/examcopilot/backend/apps/ai_service/views.py | .py | 00a5d8fd8902c5ef | 7 | 0 |
"""E9 — backend target config generation. Entirely deterministic: no
LLM, no agent, nothing to mock in this module's own tests -- the
content is fully known once a backend is chosen, so there's no
judgment call to delegate to a model.
architecture.md's S7 lists backend selection as "justified against
context.yaml cons... | arno49/observability-agentic-harness | oah/backend_targets.py | .py | 7c27a3d34be16aaa | 7 | 0 |
"""S8 DTO generation — real LiteLLM call for the parts that need judgment
(anchor selection, preconditions, change type), deterministic post-
processing for the part that doesn't: rollout_step, assigned by
architecture.md S7's real ordering rule ("first workflow = most critical
one, tracing + generation capture first, ... | arno49/observability-agentic-harness | oah/design/dto_generator.py | .py | 5ae7bb7320e54ce4 | 7 | 0 |
"""S7 (partial): event_schema.json emission, deterministic.
architecture.md lists S7 as *(skill: synthesizer)* — architecture.md
(prose) and rollout_plan.md genuinely need an LLM to write; event_schema.json
does not. Every attribute in it already exists, fully specified, in the S4
design_fragments that fed it (name, m... | arno49/observability-agentic-harness | oah/design/event_schema.py | .py | b149f5ed6257485d | 7 | 0 |
"""S4 lens invocation — real LiteLLM calls against a lens skill's own
SKILL.md + io/ schemas, generalized once so each S4 lens reuses the same
wiring instead of duplicating oah/discovery/disambiguate.py's pattern per
lens as more of them get built. Same design as that module: frontier tier
by default (SP8), instruction... | arno49/observability-agentic-harness | oah/design/lens.py | .py | 6527e49fdd89e672 | 7 | 0 |
"""S1 LLM disambiguation pass — the real thing, not a spike stand-in.
SP1's and SP8's spikes used Claude Code's own agent mechanism to exercise
the s1-surface-mapper skill (a reasonable stand-in for testing, stated as
such in both decision records). This module is what `oah`'s own standalone
process actually calls at ... | arno49/observability-agentic-harness | oah/discovery/disambiguate.py | .py | 758f3ce90537c36f | 7 | 0 |
"""S3: join S1 x S2, classify every surface point dark/partial/covered,
weight priority by context.yaml's workflow criticality when a point's
workflow_hint matches an interviewed workflow, emit gap_model.json.
context.yaml (oah/interview.py) is optional here on purpose: this module
must produce a useful, honest gap li... | arno49/observability-agentic-harness | oah/discovery/gap_model.py | .py | 993cffbc2336beff | 7 | 0 |
"""S2 manifest-based vendor/telemetry-package detection: package.json
dependencies, not source imports. A declared dependency is real evidence a
target repo has *some* telemetry vendor wired up, but -- unlike
existing_otel_usage's source-level import scan (Python-only today) -- it
doesn't confirm the package is actuall... | arno49/observability-agentic-harness | oah/discovery/manifest_scanner.py | .py | 68185417f22573e7 | 7 | 0 |
"""Derives S1's deterministic-pass lookup structures from a loaded domain
pack's `registries[]`, instead of holding them as literal dicts (E13,
docs/decisions/011). Two detector shapes exist:
- **receiver_method_suffix** (and `module_function_call`,
`imported_namespace_method_call`) — a resolved receiver (tracked vi... | arno49/observability-agentic-harness | oah/discovery/registry.py | .py | 889f624e394edf4b | 7 | 0 |
"""Loads a domain pack manifest: domains/<name>/pack.json, validated against
schemas/domain_pack.schema.json the same way every other stage boundary in
this codebase is validated (oah/schemas.py). Pure and deterministic -- no LLM
call, no network -- so pipeline core can call this unconditionally on every
command that u... | arno49/observability-agentic-harness | oah/domains/loader.py | .py | 10496aed7b16cbfb | 7 | 0 |
"""Runtime pack-membership checks for the fields whose schema once carried a
closed JSON Schema `enum` (kind, dimension, lens, maps_to.kind, event_type --
see docs/decisions/011). Those schemas now accept any well-formed identifier
string, so a value's real validity -- "is this one of THIS pack's declared
values" -- is... | arno49/observability-agentic-harness | oah/domains/validate.py | .py | c02d22a0e7687312 | 7 | 0 |
"""`oah estimate` — two-phase cost prediction per docs/decisions/002-sp5-cost-model.md.
Phase 1: a free, deterministic pre-scan (S1's own detector, in scan-only
mode) yields the real driver counts (C, A) instead of guessing them from
LOC. Phase 2: a per-stage formula over those counts, using constants from
estimate_co... | arno49/observability-agentic-harness | oah/estimate.py | .py | dbeb9a583f438adc | 7 | 0 |
"""
Telegram Bot Commands
/start, /subscribe, /help, /heatmap, /myid, /language, and the button menu that mirrors them
"""
import logging
from datetime import datetime, timedelta
import stripe
from telegram import Update, ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup, LabeledPrice
from telegram.ext i... | printezy247/macro-trader-bot | bot/commands.py | .py | 4f86dd826d1043e5 | 7 | 0 |
"""
Database Connection and Initialization
SQLAlchemy setup for SQLite or PostgreSQL
"""
import logging
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from config import DATABASE_URL, DEBUG
from database.models import Base
logger = logging.getLogger(__name__)
# Create database eng... | printezy247/macro-trader-bot | database/db.py | .py | e470cf1da8707e0a | 7 | 0 |
"""
Database Models
User, Subscription, Alert tracking
"""
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Float
from sqlalchemy.orm import declarative_base
from datetime import datetime
from i18n import DEFAULT_LANGUAGE
Base = declarative_base()
class User(Base):
"""User model for Telegram u... | printezy247/macro-trader-bot | database/models.py | .py | 9ce52e6660b7190d | 7 | 0 |
"""
Asset Correlation Heatmap (Premium)
Shows how strongly pairs of major assets are currently moving together (or
opposite each other), which matters for hedging and avoiding over-exposure
to the same underlying risk.
NOTE: `_get_correlation_data()` currently returns sample placeholder data.
Swap it for a live source... | printezy247/macro-trader-bot | heatmaps/asset_correlation.py | .py | 2770081f6ef73d7f | 7 | 0 |
"""
Central Bank Policy Divergence Heatmap (Premium)
Shows where major central banks stand on rates and stance, since the gap
between two banks' stances is what drives currency pair trends.
NOTE: `_get_central_bank_data()` currently returns sample placeholder data.
Swap it for a live source (e.g. central bank websites... | printezy247/macro-trader-bot | heatmaps/central_bank_divergence.py | .py | 25b48356d51158a2 | 7 | 0 |
"""
Economic Calendar Heatmap
Formats upcoming macro economic events into a color-coded Telegram message.
Pulls live data from the Financial Modeling Prep economic calendar endpoint
when FMP_API_KEY is configured (see config.py). If the key is missing, or
the request fails for any reason, this falls back to placeholde... | printezy247/macro-trader-bot | heatmaps/economic_calendar.py | .py | cfe2c7eb537cc057 | 7 | 0 |
"""
Crypto Fear & Greed Index
Pulls the daily index from the free, keyless alternative.me API and renders
it as a compact gauge line for the economic calendar heatmap.
Returns None on any failure (network error, bad response) so the caller can
simply omit the section rather than crash the heatmap or the daily schedule... | printezy247/macro-trader-bot | heatmaps/fear_greed.py | .py | 49a0bf75d07c7428 | 7 | 0 |
"""
Shared text-based gauge rendering for heatmap messages.
Two gauge shapes, matching two different kinds of data:
- Fill gauge: a 0-100 magnitude (e.g. recession probability, risk level).
Fills left-to-right as the value increases.
- Slider gauge: a position on a two-sided spectrum (e.g. dovish<->hawkish,
negati... | printezy247/macro-trader-bot | heatmaps/gauge.py | .py | ff4415ab86678f19 | 7 | 0 |
"""
Geopolitical Risk Heatmap (Premium)
Shows current geopolitical hotspots and which markets they tend to move.
NOTE: `_get_geopolitical_data()` currently returns sample placeholder data.
Swap it for a live source (e.g. a geopolitical risk index API or news
sentiment feed) when you wire one up.
"""
from heatmaps.gau... | printezy247/macro-trader-bot | heatmaps/geopolitical_risk.py | .py | a1be6511fb9063ab | 7 | 0 |
"""
Gold Futures Roll Calendar & Alerts
Tracks COMEX Gold (GC) futures contract expirations and roll dates,
computed directly from CME's published contract rules - no external
market-data API involved, so unlike the other heatmaps this one can't
go down because a third-party feed changes its terms or goes offline.
Ru... | printezy247/macro-trader-bot | heatmaps/gold_futures_calendar.py | .py | d100eafa84a61379 | 7 | 0 |
"""
Price-Momentum Gauge for Gold and Oil
There is no established, publicly-available "Fear & Greed Index" for gold
or oil the way alternative.me provides one for crypto. Rather than
inventing a proprietary index and presenting it as if it were a
recognized standard, this computes a real, widely-used technical
indicat... | printezy247/macro-trader-bot | heatmaps/momentum.py | .py | f2bcbdee07320664 | 7 | 0 |
"""
News article links for heatmap items.
Powered by NewsAPI.org for all topics, including crypto ones (their
free-tier CryptoPanic alternative was removed after CryptoPanic dropped
free API access entirely - their cheapest plan is now $50/week).
NewsAPI's free Developer plan: 100 requests/day, dev/testing use only p... | printezy247/macro-trader-bot | heatmaps/news.py | .py | 66e6890ca8471bcc | 7 | 0 |
"""
Recession Probability Heatmap (Premium)
Shows an estimated recession probability per major economy, based on
leading indicators (yield curve, PMI, retail sales, etc).
NOTE: `_get_recession_data()` currently returns sample placeholder data.
Swap it for a live source (e.g. FRED, OECD leading indicators) when you
wir... | printezy247/macro-trader-bot | heatmaps/recession_probability.py | .py | b18c2e9cfd7e456c | 7 | 0 |
"""
MacroTrader Telegram Bot - Main Entry Point
Handles bot initialization and startup
"""
import asyncio
import logging
import os
import sys
import threading
from dotenv import load_dotenv
from telegram.ext import (
Application, CommandHandler, MessageHandler, CallbackQueryHandler,
PreCheckoutQueryHandler, fi... | printezy247/macro-trader-bot | main.py | .py | 76dbe3e590f3d534 | 7 | 0 |
"""
NOWPayments crypto checkout (USDT and other cryptocurrencies).
Telegram's bot payment policy requires Telegram Stars for the native
in-chat payment UI on digital goods, so - same as Stripe - this goes
through an external hosted checkout page (NOWPayments' "Invoice") that
the customer is linked out to, rather than ... | printezy247/macro-trader-bot | nowpayments.py | .py | bc12de69acb56a35 | 7 | 0 |
"""
Product catalog for MacroTrader Bot's paid tiers.
This is a code-level catalog, not a database table: prices and product
definitions are business decisions made by the operator, versioned in git
like everything else, not user-generated data. Adding a new product means
adding an entry here (plus wiring its content/... | printezy247/macro-trader-bot | products.py | .py | 65bdaf88267d092f | 7 | 0 |
"""
Scheduler for Daily Alerts
Sends the economic calendar heatmap to every registered user at a set time each day
"""
import logging
import pytz
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from config import ALERT_TIME_HOUR, ALERT_TIME_MINUTE
from dat... | printezy247/macro-trader-bot | scheduler/tasks.py | .py | 27603ee7e795406b | 7 | 0 |
"""
Payment webhook receiver: Stripe and NOWPayments.
Runs as a background thread inside the same process as the bot's Telegram
polling loop (see main.py's post_init), so Railway only needs one service
instead of two. Binds to $PORT - Railway must have "Public Networking"
enabled on this service, and the resulting pub... | printezy247/macro-trader-bot | webhook_server.py | .py | a0cc225d0702faa4 | 7 | 0 |
#!/usr/bin/env python3
"""
AGI Auto-Executor – Connects AGI Brain to contracts
"""
import json
import time
import random
from web3 import Web3
from web3.middleware import geth_poa_middleware
# Configuration
RPC_URL = "https://mainnet.base.org"
PRIVATE_KEY = os.getenv("PRIVATE_KEY") # Your wallet private key
GRID_CON... | jvoidial/spirit-guide-token | agi_executor.py | .py | aa0e324fe626e780 | 7.15 | 1 |
#!/usr/bin/env python3
"""
AGI Auto‑Claim Executor – Automatically processes Base claim link
"""
import time
import json
import os
from web3 import Web3
from web3.middleware import geth_poa_middleware
# Configuration
RPC_URL = "https://mainnet.base.org"
PRIVATE_KEY = os.getenv("PRIVATE_KEY") # Your wallet private ke... | jvoidial/spirit-guide-token | auto_claim_executor.py | .py | 6106d1c07718b323 | 7.15 | 1 |
#!/usr/bin/env python3
"""
🧠 Voxel Resonance – 3rd Brain Module
Storage, Liquidity Tracking, Market Data, AGI Memory
Runs as a background daemon with Pinata integration
"""
import os
import sys
import json
import time
import requests
import subprocess
from datetime import datetime, timezone
from threading import Thre... | jvoidial/spirit-guide-token | voxel_3rd_brain.py | .py | be1305f161ecb814 | 7.15 | 1 |
"""
Incremental Indexing Benchmark Runner.
Evaluates >= 100 edit scenarios to measure:
- stale fact removal precision
- fresh fact discovery recall
- re-anchor retention rate
- chunks reprocessed ratio
"""
from typing import Any
from narrative_copilot.anchors.reanchoring import ReanchoringEngine
from narrative_copilo... | waalwalker1/narrative-continuity-copilot | evals/runners/incremental_runner.py | .py | 0fb456a8e0b7cc7f | 7 | 0 |
"""
Long Manuscript Stress Benchmark Runner.
Generates book-length synthetic fiction (60k-100k words) to measure latency and long-distance evidence recall.
"""
import time
from typing import Any
from narrative_copilot.ingestion.importer import ManuscriptImporter
from narrative_copilot.llm.embeddings import SentenceTr... | waalwalker1/narrative-continuity-copilot | evals/runners/long_manuscript_runner.py | .py | ebb55d4975d0d0ad | 7 | 0 |
"""
Master Evaluation Suite Runner.
Executes all benchmarks and generates synchronized markdown reports and summary.json under artifacts/evals/latest/.
"""
import asyncio
import json
from pathlib import Path
from typing import Any
from evals.runners.ablations_runner import AblationRunner
from evals.runners.anchors_ru... | waalwalker1/narrative-continuity-copilot | evals/runners/run_all.py | .py | fc0e633091cdf953 | 7 | 0 |
#!/usr/bin/env python3
"""
Full transactional Docker smoke test.
Validates the entire end-to-end containerized system against a live running Docker Compose stack.
"""
import json
import subprocess
import sys
import time
import urllib.error
import urllib.request
def http_get(url: str) -> dict:
req = urllib.reques... | waalwalker1/narrative-continuity-copilot | scripts/docker_smoke.py | .py | daf9475e68dc47cd | 7 | 0 |
#!/usr/bin/env python3
"""
Synchronizes measured synthetic benchmark results from artifacts/evals/latest/summary.json
into the public README.md between canonical markers.
Supports --write and --check modes for CI gate enforcement.
"""
import argparse
import json
import re
import sys
from pathlib import Path
BASE_DIR ... | waalwalker1/narrative-continuity-copilot | scripts/sync_public_metrics.py | .py | a048d04bc723983e | 7 | 0 |
"""
Stable provenance and re-anchoring engine.
Preserves citation fidelity and re-aligns anchors across manuscript edits and revisions.
"""
import difflib
import hashlib
from typing import Literal
from pydantic import BaseModel
from narrative_copilot.schemas import SourceAnchor, StructuralUnit, UnitType
class Rean... | waalwalker1/narrative-continuity-copilot | src/narrative_copilot/anchors/reanchoring.py | .py | 50d301d505f86d97 | 7 | 0 |
"""
Evidence Critic module.
Rigorously checks candidate pairs and adjudication results against evidence anchors and narrative epistemic constraints.
"""
from narrative_copilot.schemas import SourceAnchor
from narrative_copilot.schemas.continuity import AdjudicationResult, CandidatePair
class EvidenceCriticResult:
... | waalwalker1/narrative-continuity-copilot | src/narrative_copilot/continuity/critic.py | .py | aae5f9c050d5db96 | 7 | 0 |
"""
Continuity Reasoning Engine orchestrator.
Executes the candidate -> precondition -> LLM adjudication -> critic -> validator pipeline.
"""
from narrative_copilot.continuity.candidate_generator import CandidateGenerator
from narrative_copilot.continuity.critic import EvidenceCritic
from narrative_copilot.continuity.... | waalwalker1/narrative-continuity-copilot | src/narrative_copilot/continuity/engine.py | .py | 6d0199d7aec244d4 | 7 | 0 |
"""
Deterministic precondition engine for candidate continuity pairs.
Filters out incompatible, superseded, or author-suppressed pairs before AI adjudication.
"""
from narrative_copilot.schemas.continuity import CandidatePair, DeterministicPreconditionResult
class PreconditionChecker:
"""
Evaluates determini... | waalwalker1/narrative-continuity-copilot | src/narrative_copilot/continuity/preconditions.py | .py | 9d50be9f585c627c | 7 | 0 |
"""
Deterministic final validator for continuity alerts.
Rejects any output with unknown citations, missing anchors, or invalid classification.
"""
from narrative_copilot.schemas import (
CanonicalStatus,
ContinuityAlert,
EvidenceSnippet,
SourceAnchor,
)
from narrative_copilot.schemas.continuity import... | waalwalker1/narrative-continuity-copilot | src/narrative_copilot/continuity/validator.py | .py | 4cfe12e6f1efde7b | 7 | 0 |
"""
Entity and alias resolution engine.
Handles character name variants, nicknames, titles, and author-controlled entity splits and merges.
"""
import difflib
from pydantic import BaseModel
from narrative_copilot.schemas import CanonicalStatus, Entity
NICKNAME_MAP: dict[str, set[str]] = {
"elizabeth": {"lizzy",... | waalwalker1/narrative-continuity-copilot | src/narrative_copilot/entities/resolver.py | .py | 0ebef11fd5c0e6d9 | 7 | 0 |
"""
Hallucination detection and provenance grounding verifier.
"""
from narrative_copilot.schemas import ContinuityAlert, SourceAnchor
class HallucinationDetector:
"""
Verifies that model generated explanations and alerts contain no unsupported assertions or citations.
"""
def verify_alert_grounding... | waalwalker1/narrative-continuity-copilot | src/narrative_copilot/grounding/hallucination_detector.py | .py | e3c762ab398cffaa | 7 | 0 |
"""
Prompt-injection defense and untrusted text boundary management.
Ensures manuscript prose (even containing adversarial text) is safely treated as data.
"""
import re
class PromptInjectionDefense:
"""
Guards the system boundary against adversarial prompt injections embedded in creative manuscripts.
""... | waalwalker1/narrative-continuity-copilot | src/narrative_copilot/grounding/injection_defense.py | .py | 696419ac0c81d11f | 7 | 0 |
"""
DOCX importer using python-docx.
Extracts headings, paragraphs, and scene separators into normalized manuscript structures.
"""
import io
from pathlib import Path
class DocxImporter:
"""
Extracts text from DOCX documents and normalizes them into Markdown for structural parsing.
"""
def import_fr... | waalwalker1/narrative-continuity-copilot | src/narrative_copilot/ingestion/docx_importer.py | .py | b769ef5ba64c36a1 | 7 | 0 |
"""
Unified manuscript ingestion module.
Supports Markdown, Plaintext, and DOCX imports with size limits and security validation.
"""
from pathlib import Path
from narrative_copilot.ingestion.docx_importer import DocxImporter
from narrative_copilot.schemas import SourceAnchor, StructuralUnit
from narrative_copilot.sc... | waalwalker1/narrative-continuity-copilot | src/narrative_copilot/ingestion/importer.py | .py | 4d2bf4e2ed795db9 | 7 | 0 |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
# Copyright 2023-2024 SGLang Team
# Copyright 2025 ModelBest Inc. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#... | chendy25/iclr-tb-opd | examples/data_preprocess/aime2024_multiturn_w_tool.py | .py | 700505becc21f305 | 7 | 0 |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
# Copyright 2023-2024 SGLang Team
# Copyright 2025 ModelBest Inc. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#... | chendy25/iclr-tb-opd | examples/data_preprocess/dapo_multiturn_w_tool.py | .py | 5b10900b9569e52d | 7 | 0 |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | chendy25/iclr-tb-opd | examples/data_preprocess/full_hh_rlhf.py | .py | bbbf0ef47e89b75b | 7 | 0 |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | chendy25/iclr-tb-opd | examples/data_preprocess/geo3k.py | .py | 3b670ca0a39c97b3 | 7 | 0 |
# Copyright 2023-2025 SGLang Team
# Copyright Amazon.com, Inc. or its affiliates.
# Copyright 2025 Reallm Labs Ltd. or its affiliates
# Copyright 2025 ModelBest Inc. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... | chendy25/iclr-tb-opd | examples/data_preprocess/geo3k_multiturn_w_tool.py | .py | 78b8e95a87edbccd | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.