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 |
|---|---|---|---|---|---|---|
"""Platform-aware subprocess helpers for mcp_plugin (slife-free).
A trimmed subset of ``slife.platform`` plus ``kill_process_tree`` (moved
verbatim from ``slife.tools.exec``) — everything the MCP connection layer
needs to spawn, terminate and notify without importing slife.
"""
import asyncio
import logging
import os... | juzcn/slife | mcp-plugin/mcp_plugin/platform.py | .py | ed8096de505a63f9 | 7 | 0 |
"""MCP wrapper process lifecycle management.
Spawns the plugin child process on agent startup and ensures
clean shutdown on exit. The child starts a Streamable HTTP server on a
dynamically-assigned port; this wrapper discovers the port via a
one-line JSON signal on stdout.
"""
from __future__ import annotations
imp... | juzcn/slife | mcp-plugin/mcp_plugin/process.py | .py | 340a43872d4d6d60 | 7 | 0 |
"""Transcriptor API entrypoint."""
import hmac
import os
import re
import sys
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.config import ServerConfig, load_config
from app.db import STAGE_KINDS, Base, engine, init_engine
f... | megastruktur/transcripter | server/api/app/main.py | .py | d5ca43ed22d61291 | 7 | 0 |
"""Resumable upload endpoints.
POST /recordings → create recording (uuid) + dir + stage rows
PUT /recordings/{id}/audio → append chunk at ?offset=N (returns committed)
POST /recordings/{id}/finalize → verify sha256, size → state=processing
GET /recordings → paginated list {... | megastruktur/transcripter | server/api/app/routes/recordings.py | .py | 310b710740ef6c1e | 7 | 0 |
"""Settings route contract: shape, masking, diarization.enabled exposure."""
import pytest
from fastapi.testclient import TestClient
@pytest.fixture
def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
monkeypatch.setenv("TRANSCRIPTER_TOKEN", "test-token")
from app.main import app
return TestClien... | megastruktur/transcripter | server/api/tests/test_settings.py | .py | 11540df1f34911a7 | 7.5 | 0 |
"""chunk.py: plan geometry, manifest roundtrip, seam windows, suspect detection."""
import shutil
import subprocess
from itertools import pairwise
from pathlib import Path
import pytest
from worker.chunk import (
ChunkError,
Manifest,
cut_chunks,
is_suspect,
keep_window,
load_manifest,
pl... | megastruktur/transcripter | server/worker/tests/test_chunk.py | .py | 1cb069f65bf550ab | 7.5 | 0 |
"""Chunked transcribe/diarize/chunk activities: seams, resume, retry, suspect."""
import json
from pathlib import Path
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from worker import activities
from worker.chunk import ChunkEntry, Manifest, save_manifest
from worker.conf... | megastruktur/transcripter | server/worker/tests/test_chunked_stages.py | .py | 06917623ce26048c | 7.5 | 0 |
"""Diarize activity: disabled-config skip path (no HTTP, stale artifacts removed)."""
from pathlib import Path
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from worker import activities
from worker.config import WorkerConfig
from worker.db import Base, Recording, Recordi... | megastruktur/transcripter | server/worker/tests/test_diarize_activity.py | .py | b7c1fcea6bc8df7f | 7.5 | 0 |
"""ApiTranscriber: request shape and response parsing (mocked httpx)."""
from pathlib import Path
import httpx
import pytest
from worker.transcribe import ApiTranscriber
def _serve(responses: dict) -> httpx.MockTransport:
"""MockTransport asserting request shape; keyed response by call count."""
calls = {"... | megastruktur/transcripter | server/worker/tests/test_transcribe_api.py | .py | 00f75f11ec28f7c8 | 7.5 | 0 |
"""LocalTranscriber: thread-safe singleton, download_root wiring, shared preload."""
import sys
import threading
import time
import types
from pathlib import Path
import pytest
from worker import activities
from worker.config import WorkerConfig
from worker.transcribe import LocalTranscriber, TranscriptionResult
c... | megastruktur/transcripter | server/worker/tests/test_transcribe_local.py | .py | 50975d8850a79b6d | 7.5 | 0 |
"""Backfill: re-export notes for all done recordings.
docker compose exec worker python -m worker.backfill
Every recording goes through the SAME subprocess+timeout+abandon wrapper as
the export_transcript activity — a dead NAS mount must never wedge this
process either (r4#2). Refuses upfront unless the sentinel/... | megastruktur/transcripter | server/worker/worker/backfill.py | .py | 33cfe42d634da361 | 7 | 0 |
"""Audio chunking stage: cut long recordings into sequential FLAC chunks.
Why this stage exists: whisper's repetition loop lives inside a single
request's decoder context (condition_on_previous_text over rolling windows).
A 2.5-h request can collapse into an identical-phrase loop that poisons
everything after the fail... | megastruktur/transcripter | server/worker/worker/chunk.py | .py | 47e59208673c7d23 | 7 | 0 |
from fastapi import WebSocket
class ConnectionManager:
"""
WebSocket connections class.
Attributes:
connections (list[WebSocket]): List of currently connected WebSockets.
"""
def __init__(self) -> None:
self.connections: list[WebSocket] = []
async def connect(self, websocket:... | A7336/TfL-Tracker | backend/api/connection_manager.py | .py | ab0f55f9b8251b28 | 7 | 0 |
from datetime import datetime
from pydantic import BaseModel, ConfigDict
class TubeStatusBase(BaseModel):
"""
Data transfer object schema representing transit line metrics transmitted by the TfL API.
Attributes:
line_id (str): Unique identifier for the transit line.
name (str): Name of th... | A7336/TfL-Tracker | backend/api/schemas.py | .py | 26e4e6715f0b3abf | 7 | 0 |
import httpx as httpx
from backend.api.config import TFL_API_KEY, TFL_URL
from backend.database.database import ASYNC_SESSION
from backend.database.crud import save_tube_status
from backend.api.connection_manager import MANAGER
header = {"app_key": TFL_API_KEY}
async def fetch_raw_data() -> list[dict]:
"""
... | A7336/TfL-Tracker | backend/worker/worker_fetcher.py | .py | 2fa671121ab9fca7 | 7 | 0 |
import json
import os
import threading
import websocket
import streamlit as st
from streamlit.runtime.scriptrunner_utils.script_run_context import add_script_run_ctx, ScriptRunContext
WEBSOCKET_URL = os.getenv("BACKEND_WS_URL") or st.secrets["WEBSOCKET_URL"]
def force_rerun(ctx: ScriptRunContext | None) -> None:
... | A7336/TfL-Tracker | frontend/les_assistants.py | .py | f6d63434c994e4e8 | 7 | 0 |
"""Shared, provider-neutral helpers for local agent adapters.
Codex and WorkBuddy speak different wire protocols (newline-delimited JSON-RPC
on stdio versus ACP-over-SSE), but they share the same lifecycle concerns:
emitting a provider-level error to every active session queue and validating
that a session belongs to ... | BrunoBanana/data2doc2data | src/data2doc2data/agents/_shared.py | .py | e45231207a6e20a9 | 7.15 | 1 |
# -*- coding: utf-8 -*-
import os, sys
# 【标准开头】强制 UTF-8 输出(项目已装成 Python 包,import 无需再塞 sys.path)
try:
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
except Exception:
pass
"""selftest · MCP 服务自测(协议层离线测试,不联网、不依赖用户数据)
跑法:python MCP服务/selftest.py,全部通过才算出活。
覆盖:initialize 握手、通知不回、tools/list、tools/call(成功... | chen2994957404-droid/zotero-literature-platform | MCP服务/selftest.py | .py | bea849444fdb894c | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""llm_client · LLM 调用基础件(公理:文本 → LLM → 文本/JSON)
职责:统一封装对大模型的调用。此前散在 9 个脚本、6 个函数各写各的
(deepseek/ollama/call_llm/deepseek_json/ollama_json/llm_json),导致重复 +
密钥注入混乱(踩坑 #17)。收敛成单一公理件,一处正确、处处复用。
公理特征:只做「给 messages,返回模型输出」这一件不可再分的事。
对外接口:
- chat(system, user, ...) → 纯文本输出(对话/精读/问答)
- chat_j... | chen2994957404-droid/zotero-literature-platform | adapters/llm_client/__init__.py | .py | 3d7702033d020b79 | 7 | 0 |
# -*- coding: utf-8 -*-
"""adapters.openalex —— OpenAlex 学术检索 API(免费、无需密钥)。
**为什么要有这一块**(重构阶段 2):
重构前,同一个 OpenAlex API 被**三个地方各自实现了一遍**:
adapters/snowball 有退避重试、有礼貌 UA、有字段裁剪 ← 实现最好
pipelines/paper_discovery 裸 urlopen,无重试
找新文献/find_papers.py 裸 urlopen,无重试,又抄了一遍摘要还原
三份实现意味着三种行为:OpenAlex 一限流... | chen2994957404-droid/zotero-literature-platform | adapters/openalex/__init__.py | .py | b5318c52ede9204b | 7 | 0 |
# -*- coding: utf-8 -*-
"""snowball · 引用雪球基础件(公理:种子文献 → 沿引用网络扩展出的相关文献)
**为什么必须有这块(有实证支撑,不是拍脑袋)**:
系统综述领域的实测研究给出了明确数字 ——
单个数据库检索 召回率 13~35%
+ 优化检索式 召回率 50~95% ← 我们的 query_expand 做到这层
+ 一轮前后向雪球 召回率 90~100% ← 本模块补的就是这一步
也就是说,**只靠关键词检索,必然漏掉相当一部分相关文献**,
而漏掉的那批往往用了完全不同... | chen2994957404-droid/zotero-literature-platform | adapters/snowball/__init__.py | .py | 497a5246942e619c | 7 | 0 |
# -*- coding: utf-8 -*-
"""adapters.vectordb —— 向量库(当前实现:Chroma)。
**为什么要包这一层**(见 docs/架构重构_v2总体设计.md 阶段 2 第 10 项):
重构前 `import chromadb` 出现在 **5 个地方**(ask / vectorize / vectorize_library /
brainstorm / lib_match),每处都自己 `PersistentClient(...)`、自己写
`get_or_create_collection('literature', {'hnsw:space': 'cosine'})`、
自己解... | chen2994957404-droid/zotero-literature-platform | adapters/vectordb/__init__.py | .py | 567c1d4ab97e71de | 7 | 0 |
# -*- coding: utf-8 -*-
"""zotero_client · Zotero 接口基础件(可独立成 GitHub 项目的候选)
职责:封装与 Zotero 的所有交互——读文献/附件/正文、定位本地正文 PDF。
这是「基础件拼装」愿景里的一块:下游(精读/抽取/向量化)都 import 它,
不再各自拷贝 find_pdf 等逻辑(消除技术债:曾有 3 份 find_pdf 拷贝)。
对外接口(稳定,供上层组合调用):
- zget(path) : 本地只读 API GET
- find_pdf(key) : 定位正文 PDF 本地路径(优先信 Zotero ... | chen2994957404-droid/zotero-literature-platform | adapters/zotero_client/__init__.py | .py | 262334784aee3b06 | 7 | 0 |
# -*- coding: utf-8 -*-
"""cli · 命令行参数解析基础件(公理:全项目只有一种取参数的方式)
解决的真实问题(2026-08-11 体检):79 个 .py 里有 97 处手写 sys.argv,
风格至少 10 种('--flag' in sys.argv / sys.argv.index('--tag')+1 / 位置切片 / 列表推导去 -- …)。
每份脚本各写各的,AI 接手每看一个文件都要重新学习。收敛到这里后,任何脚本的参数写法都是同一套。
设计原则:
- 只读 sys.argv,不用 argparse —— 本项目参数都很简单(几个位置参数 + 几个 --开关),
arg... | chen2994957404-droid/zotero-literature-platform | core/cli/__init__.py | .py | f43ea2bd22a7b362 | 7 | 0 |
# -*- coding: utf-8 -*-
"""cli 积木自测:把 sys.argv 换掉跑六组用例,全过即算数。"""
import os, sys
# 【标准开头】强制 UTF-8 输出(项目已装成 Python 包,import 无需再塞 sys.path)
try:
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
except Exception:
pass
from core import cli
def _run(argv, cases):
"""把 sys.argv 换成 argv,逐个跑 cases 里的 (... | chen2994957404-droid/zotero-literature-platform | core/cli/selftest.py | .py | b264b51936036907 | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""core.heartbeat —— 常驻服务的两种「我还好」信号。
**为什么需要它**(2026-08-27 从主力机日志里查出来的真问题):
`zotero_watcher` 原来只有一个心跳,写在轮询循环的开头:
```python
while True:
写心跳 # ← 只在这里写
for it in 待处理文献:
process_item(it) # ← 精读一篇:解析 + 9000 字生成 + 裁图 + 回写
time.sleep(60)
```
**精读期间完全不写心跳*... | chen2994957404-droid/zotero-literature-platform | core/heartbeat.py | .py | d5b843435da98d4e | 7 | 0 |
# -*- coding: utf-8 -*-
"""core.log —— 统一的日志落点。
**为什么需要它**(见 docs/架构重构_v2总体设计.md 阶段 1 第 6 项):
重构前,同一件事有三种写法,且都有各自的毛病:
文献精读/zotero_watcher.py 把内置的 `print` 整个换掉(`_print = print; def print(...)`)
文献精读/watchdog.py 自己写一个 def log(msg)
库房维护/auto_sync.py 又自己写一个 def log(msg)
劫持 `print` 尤其糟:读代码的人... | chen2994957404-droid/zotero-literature-platform | core/log.py | .py | 8c2a7a5ced6c2a07 | 7 | 0 |
# -*- coding: utf-8 -*-
"""proc_lock · 单实例锁基础件(公理:保证同一个程序同时只跑一份)
解决的真实问题(踩坑 #30):
zotero_watcher 反复出现 2 个实例并存 —— 任务计划自启一份、看门狗又启一份,
两份同时轮询同一个 Zotero 库,会抢同一篇文献的处理权,导致重复精读、重复上传。
**为什么用锁而不是靠看门狗去杀**:
杀是事后补救,永远有时间窗(旧的还没死、新的已经在跑);
锁是事前阻断,第二份根本起不来。从源头杜绝优于事后清理。
公理特征:只做「抢占一个具名的独占权」这一件不可再分的事。
用法:
from core.proc_lock impor... | chen2994957404-droid/zotero-literature-platform | core/proc_lock/__init__.py | .py | 94d1fa5bb0aa5641 | 7 | 0 |
# -*- coding: utf-8 -*-
"""core.role —— 这台机器是什么角色。
**为什么需要它**(见 `docs/两台机器的分工.md`):
本平台跑在两台机器上,**共用同一个 Zotero 账号**:
A 机 = 编程端 有 Claude Code,改代码的唯一入口
B 机 = 运行端 Ollama、watcher、4 个自启任务、workflow_data 权威副本
编程端做验证时如果回写 Zotero(打标签、传附件、改名),
**污染的是真实文献库,而且立刻同步到主力机**。同理,在编程端误跑一次
全库批量作业,烧的是真钱。
分工写在文档里没有强制力 —— 人会忘... | chen2994957404-droid/zotero-literature-platform | core/role.py | .py | 2eef22ded0cb167e | 7 | 0 |
# -*- coding: utf-8 -*-
"""subproc · 子进程调用基础件(公理:跑一条外部命令,安静、带超时、编码正确)
解决的真实问题(踩坑 #31):
Windows 上用 subprocess 调 powershell/wmic/python,**默认会弹出一个控制台窗口**。
面板每 15 秒查一次进程、看门狗每 60 秒查一次,于是用户桌面不停闪蓝色窗口。
散落在 6 个文件、17 处的调用各写各的,修一处漏一处,新写的代码还会再犯。
**为什么做成积木而不是逐处修**:
逐处修只解决今天这 17 处;做成积木后,「调子进程」这件事只有一个正确入口,
以后任何新代码复用它就自动不弹窗。从源头杜绝优于事... | chen2994957404-droid/zotero-literature-platform | core/subproc/__init__.py | .py | 9f6b0420be1c1ec9 | 7 | 0 |
# -*- coding: utf-8 -*-
"""si_filter · SI(补充材料)内容过滤基础件(公理:SI全文 → 有价值段落)
职责:SI 价值密度高但噪声也大(作者名单、单位地址、目录清单、仪器型号)。
本件把 SI 正文按价值分档,滤掉零价值部分,只留合成细节与关键数据。
思路对齐前沿(MOF/reticular 合成挖掘的 paragraph classification),但**用规则不用LLM**——
因为"识别作者名单/单位/目录"这类模式是稳定的(宪法·稳定的自己做),零成本、可解释。
三档:
- drop 丢弃:作者/单位/邮箱/目录清单(Figures S1-S23)/参考文献
- ... | chen2994957404-droid/zotero-literature-platform | domain/si_filter/__init__.py | .py | 682023d379eed374 | 7 | 0 |
# -*- coding: utf-8 -*-
"""lib_match · 文献对照基础件(公理:一篇外部文献 → 它与我的库是什么关系)
**这块是整个找文献平台的价值核心。**
外部检索谁都能调(OpenAlex、Sciverse 都是公开 API)。真正不可替代的是:
**只有本平台知道用户已经有什么、读过什么、在做什么方向。**
把外部结果和本地库对照这一步做好,搜索才从「又一个 Google Scholar」
变成「知道我在干什么的助手」。
回答两个不同的问题(**别混为一谈**):
1. 「这篇我有没有?」 → 去重,避免重复导入
2. 「这篇值不值得读?」 → 相关度,决定看不看
第 2 个问题才... | chen2994957404-droid/zotero-literature-platform | pipelines/lib_match/__init__.py | .py | 44a94aa4640ef277 | 7 | 0 |
# -*- coding: utf-8 -*-
"""query_expand · 检索式扩展基础件(公理:一个研究问题 → 多个互补的英文检索式)
**为什么需要这块**:单一查询是「检索不全面」的根本原因,跟检索引擎好不好无关。
材料领域同一个东西有太多叫法 ——
polyborosiloxane / PBS / boron-siloxane / borosiloxane elastomer /
silly putty / shear stiffening gel / dilatant compound …
只搜其中一个词,就必然漏掉用别的词写的那批文献。
前沿的文献检索 Agent(PaperPilot、PaSa、SPAR... | chen2994957404-droid/zotero-literature-platform | pipelines/query_expand/__init__.py | .py | c0f6b46015dbdcc6 | 7 | 0 |
#!/usr/bin/env python3
"""Create a local-only comparison payload from the collected Discord TL data.
The payload deliberately contains only TL text and channel names. Authors,
message links, IDs, and the raw collection are never copied to the repository.
"""
from __future__ import annotations
import argparse
import ... | www51k/tl-formatter | scripts/build_learning_comparison.py | .py | 7437e083a5d9095c | 7 | 0 |
"""共通のTL解析・表記処理。"""
from __future__ import annotations
import re
from dataclasses import dataclass
from character_aliases import CHARACTER_ALIASES, LEARNED_NAME_ALIASES
CHARACTERS = ("アオイ", "ネラ", "ツムギ", "ペコ", "シェフィ")
CHAR_NUMBERS = {name: number for name, number in zip(CHARACTERS, "54321")}
# 長い正式名を使う編成では、ここへ4文字の表示... | www51k/tl-formatter | scripts/tl_common.py | .py | a2ba3d4bd5dc625e | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UI/UX Pro Max Core - BM25 search engine for UI/UX style guides
"""
import csv
import re
from pathlib import Path
from math import log
from collections import defaultdict
# ============ CONFIGURATION ============
DATA_DIR = Path(__file__).parent.parent / "data"
MAX_RE... | swarfte/barcode-generator | .claude/skills/ui-ux-pro-max/scripts/core.py | .py | 5459d1f04eea03df | 7 | 0 |
"""
x64dbg-mcp-x Event System
Event-driven architecture for debugging events.
"""
import asyncio
from typing import Callable, Dict, Any, Optional, List
from dataclasses import dataclass
from enum import Enum
import json
class EventType(str, Enum):
BREAKPOINT_HIT = "breakpoint.hit"
DEBUG_STARTED = "debug.sta... | Zekiog/x64dbg-mcp-x | clients/python/x64dbg_automate/events.py | .py | 6a4736e655f403ee | 7 | 0 |
"""
x64dbg-mcp-x Data Models
Pydantic models for x64dbg data structures.
"""
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
from enum import Enum
class BreakpointType(str, Enum):
HARDWARE = "hardware"
SOFTWARE = "software"
MEMORY = "memory"
class Breakpoint(BaseMode... | Zekiog/x64dbg-mcp-x | clients/python/x64dbg_automate/models.py | .py | ddda7547dbe0915d | 7 | 0 |
#!/usr/bin/env python3
"""
x64dbg-mcp-x Memory Dump Demo
Demonstrates memory reading and dumping using the MCP server.
"""
import requests
import json
X64DBG_HOST = 'localhost'
X64DBG_PORT = 31964
def read_memory(address, size=256):
"""Read memory at specified address"""
url = f'http://{X64DBG_HOST}:{X64DBG... | Zekiog/x64dbg-mcp-x | examples/dump_demo.py | .py | dcb6e470434d2b5e | 7 | 0 |
#!/usr/bin/env python3
"""
x64dbg-mcp-x Python HTTP Client
Simple HTTP client for interacting with the x64dbg MCP server.
"""
import requests
import json
from typing import Optional, Dict, Any
class X64dbgClient:
"""HTTP client for x64dbg-mcp-x REST API"""
def __init__(self, host='localhost', port=31964... | Zekiog/x64dbg-mcp-x | examples/python_client_http.py | .py | 03e1b0c36ce8b261 | 7 | 0 |
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from typing import Dict, Any, List
from datetime import datetime
class CompanyOverview:
"""
企業概要を表示するコンポーネント
"""
def __init__(self, company_data: Dict[str, Any]):
self.company_data = co... | pitawo/company-research-tool | components/company_overview.py | .py | 834c670741f36051 | 7 | 0 |
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from typing import Dict, Any, List
import numpy as np
def format_amount(value):
"""百万円の値を、桁数に応じた単位で短く表す。
メトリック表示の幅は狭いので「124796億円」のような長い数字は途中で
省略されてしまう。1兆円を超えたら... | pitawo/company-research-tool | components/financial_dashboard.py | .py | 55dd87bf958db5de | 7 | 0 |
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import sys
from pathlib import Path
import yaml
from dotenv import load_dotenv
import os
# プロジェクトルートをパスに追加
project_root = Path(__file__).parent
sys.path.insert(0, str(projec... | pitawo/company-research-tool | main.py | .py | 48ad82f363dc1cf5 | 7 | 0 |
# -*- coding: utf-8 -*-
"""yfinance から実財務データを取得し、検証したうえで data/financials.json に固める。
方針:
- 同梱データはすべてこのスクリプトの出力。出どころ不明の手入力値は持たない。
- 取得した数字をそのまま信じない。検証して、引っかかったものは notes に残して画面に出す。
再取得: python tools/fetch_financials.py
"""
import json
import os
import sys
from datetime import datetime, timezone, timedelta
import yfi... | pitawo/company-research-tool | tools/fetch_financials.py | .py | c080e5413132af16 | 7 | 0 |
from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC, datetime
from importlib.metadata import entry_points
from typing import Protocol
from agent_ops.contracts.job import AgentJob
from agent_ops.contracts.result import RunResult, RunStatus
_RUNNER_PLUGIN_GROUP = "agent_ops.pl... | dmc-technologies/agent-ops-community | src/agent_ops/plugins.py | .py | 4ff0f8eb04e9f982 | 7 | 0 |
from __future__ import annotations
import uuid
from starlette.datastructures import Headers
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from api.errors import REQUEST_ID_HEADER, error_response
class RequestBodyLimitMiddleware:
"""Bound request bodies even when Content-Length is absent or... | shouchengzhuang-cmyk/Mini-AI-Cloud | api/middleware.py | .py | 5bdc87d608b6f6b0 | 7 | 0 |
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
class APIModel(BaseModel):
"""Base model for all public API contracts.
Unknown fields are rejected so a client cannot smuggle arbitrary Docker or
infrastructure options through a request model.
"""
model_config = ... | shouchengzhuang-cmyk/Mini-AI-Cloud | api/schemas/common.py | .py | 8b4159eb675baad8 | 7 | 0 |
import logging
from logging.config import fileConfig
from flask import current_app
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers b... | Nithya200x/devflow | backend/migrations/env.py | .py | 89b2b586c74eb0e0 | 7 | 0 |
"""add github fields to user
Revision ID: 058ef1f6ddb1
Revises: 2839f9a7df4c
Create Date: 2026-06-25 20:30:52.285063
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '058ef1f6ddb1'
down_revision = '2839f9a7df4c'
branch_labels = None
depends_on = None
def upgra... | Nithya200x/devflow | backend/migrations/versions/058ef1f6ddb1_add_github_fields_to_user.py | .py | 10e91a58d6639ac5 | 7 | 0 |
"""Initial migration
Revision ID: 2839f9a7df4c
Revises:
Create Date: 2026-06-08 11:47:35.547542
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2839f9a7df4c'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto ... | Nithya200x/devflow | backend/migrations/versions/2839f9a7df4c_initial_migration.py | .py | c4a8e676159910ab | 7 | 0 |
"""add name email and created_at to user
Revision ID: 8a3b5c7d9e0f
Revises: 058ef1f6ddb1
Create Date: 2026-07-05 12:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = '8a3b5c7d9e0f'
down_revision = 'a1b2c3d4e5f6'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter... | Nithya200x/devflow | backend/migrations/versions/8a3b5c7d9e0f_add_name_email_to_user.py | .py | 916b51ed95c4ad2e | 7 | 0 |
"""Add project_id column to incident table and create connected_project table tracking
Revision ID: a1b2c3d4e5f6
Revises: f8b3c2d1e4a6
Create Date: 2026-07-04 16:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = 'a1b2c3d4e5f6'
down_revision = 'f8b3c2d1e4a6'
branch_labels = None
depends_on = ... | Nithya200x/devflow | backend/migrations/versions/a1b2c3d4e5f6_add_project_id_to_incident.py | .py | f9d50991d7198fbe | 7 | 0 |
"""add git_repository table
Revision ID: cb20543ff394
Revises: 058ef1f6ddb1
Create Date: 2026-06-25 21:40:13.912125
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'cb20543ff394'
down_revision = '058ef1f6ddb1'
branch_labels = None
depends_on = None
def upgrad... | Nithya200x/devflow | backend/migrations/versions/cb20543ff394_add_git_repository_table.py | .py | 1f19d991eaf4fdfa | 7 | 0 |
"""add orchestration engine tables (event_store, incident_evidence, incident_timeline)
Revision ID: e7a2b1c3d4f5
Revises: cb20543ff394
Create Date: 2026-06-26 09:55:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e7a2b1c3d4f5'
down_revision = 'cb2054... | Nithya200x/devflow | backend/migrations/versions/e7a2b1c3d4f5_add_orchestration_tables.py | .py | 1ced5cbdc685831f | 7 | 0 |
"""
ms-job-watcher local dashboard
Run: python dashboard/app.py
Then open: http://localhost:5050
"""
import json
import os
import sys
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from flask import Flask, render_template, jsonify, request
BASE_DIR = Path(__file__).resolv... | likithreddy25/ms-job-watcher | dashboard/app.py | .py | cb7f6640eff7413f | 7 | 0 |
#!/usr/bin/env python3
"""VecminDB Python SDK - 03 MCP (Model Context Protocol) Client Example.
Demonstrates:
1. Connecting via JSON-RPC 2.0 (Sync & Async McpClient).
2. Discovering available MCP tools (`list_tools`).
3. Executing MCP memory tools (`store_memory` & `search_memory`).
4. Real-time SSE streaming (`mcp.st... | lingxinmind/vecmindb-sdk | examples/03_mcp_client.py | .py | 9f42b400144d7598 | 7.15 | 1 |
"""Unit tests for the VecminDB Agent OS Memory abstraction."""
import unittest
from unittest.mock import MagicMock, AsyncMock, patch
from vecmindb import (
VecminClient,
AsyncVecminClient,
connect,
AgentMemoryManager,
AsyncAgentMemoryManager,
VecminMemorySpace,
AsyncVecminMemorySpace,
)
c... | lingxinmind/vecmindb-sdk | python/tests/test_agent_memory.py | .py | 063dacbcfba8b82e | 7.65 | 1 |
"""VecminDB Python SDK Integration Tests.
These tests exercise the full client API against a running VecminDB instance.
They can also be run in offline/mock mode to verify the SDK structure.
"""
import unittest
import os
from vecmindb import VecminClient, AsyncVecminClient, VecminError
from vecmindb.models import (
... | lingxinmind/vecmindb-sdk | python/tests/test_client.py | .py | 179816c7ea6c39b2 | 7.65 | 1 |
"""VecminDB VectorStore integration for LangChain."""
from typing import Any, Iterable, List, Optional
import uuid
try:
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.vectorstores import VectorStore
LANGCHAIN_INSTALLED = True
except I... | lingxinmind/vecmindb-sdk | python/vecmindb/integrations/langchain.py | .py | 168a76642614492b | 7.15 | 1 |
"""VecminDB VectorStore integration for LlamaIndex."""
from typing import Any, List, Optional
import uuid
try:
from llama_index.core.vector_stores.types import (
BasePydanticVectorStore,
VectorStoreQuery,
VectorStoreQueryResult,
)
from llama_index.core.schema import TextNode, BaseN... | lingxinmind/vecmindb-sdk | python/vecmindb/integrations/llamaindex.py | .py | 8dfc91310bfec334 | 7.15 | 1 |
"""VecminDB MCP Server – FastMCP Integration.
Provides an MCP (Model Context Protocol) server that exposes VecminDB
operations as tools that LLMs can invoke directly. Uses the commercial-grade
VecminDB Python SDK under the hood.
"""
import os
from typing import List, Optional
from vecmindb.client import VecminClien... | lingxinmind/vecmindb-sdk | python/vecmindb/mcp_server.py | .py | 0765c433f60a6281 | 7.15 | 1 |
"""
VecminDB Memory Plugin for LangChain and CrewAI.
Provides drop-in memory backends powered by VecminDB's LTSM lifecycle:
- Working Memory → Fast-Path promotion → Episodic Memory
- Time-based decay → PCA distillation → Abstract Centroid
- Sovereign Federation for multi-agent knowledge sharing
Usage (LangChain):
... | lingxinmind/vecmindb-sdk | python/vecmindb/memory_plugin.py | .py | 70dc8e3a2875b63c | 7.15 | 1 |
#
# The Python Imaging Library
# $Id$
#
# bitmap distribution font (bdf) file parser
#
# history:
# 1996-05-16 fl created (as bdf2pil)
# 1997-08-25 fl converted to FontFile driver
# 2001-05-25 fl removed bogus __init__ call
# 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
# 2003-04-22 fl ... | ritesh-bilip/Portfolio | pEnv/Lib/site-packages/PIL/BdfFontFile.py | .py | 0aa08fa855fc2774 | 7.15 | 1 |
#
# The Python Imaging Library
# $Id$
#
# base class for raster font file parsers
#
# history:
# 1997-06-05 fl created
# 1997-08-19 fl restrict image width
#
# Copyright (c) 1997-1998 by Secret Labs AB
# Copyright (c) 1997-1998 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
... | ritesh-bilip/Portfolio | pEnv/Lib/site-packages/PIL/FontFile.py | .py | eb86240aaac643c1 | 7.15 | 1 |
"""
A Pillow loader for .ftc and .ftu files (FTEX)
Jerome Leclanche <jerome@leclan.ch>
The contents of this file are hereby released in the public domain (CC0)
Full text of the CC0 license:
https://creativecommons.org/publicdomain/zero/1.0/
Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001
... | ritesh-bilip/Portfolio | pEnv/Lib/site-packages/PIL/FtexImagePlugin.py | .py | 652d16a811ed22d3 | 7.15 | 1 |
#
# The Python Imaging Library.
# $Id$
#
# GD file handling
#
# History:
# 1996-04-12 fl Created
#
# Copyright (c) 1997 by Secret Labs AB.
# Copyright (c) 1996 by Fredrik Lundh.
#
# See the README file for information on usage and redistribution.
#
"""
.. note::
This format cannot be automatically recognized, s... | ritesh-bilip/Portfolio | pEnv/Lib/site-packages/PIL/GdImageFile.py | .py | f0eadd77d114e0e6 | 7.15 | 1 |
#
# Python Imaging Library
# $Id$
#
# stuff to read (and render) GIMP gradient files
#
# History:
# 97-08-23 fl Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution.
#
"""
Stuff to translate curve segments to pa... | ritesh-bilip/Portfolio | pEnv/Lib/site-packages/PIL/GimpGradientFile.py | .py | cd675b313f95b2c5 | 7.15 | 1 |
#
# The Python Imaging Library.
# $Id$
#
# macOS icns file decoder, based on icns.py by Bob Ippolito.
#
# history:
# 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies.
# 2020-04-04 Allow saving on all operating systems.
#
# Copyright (c) 2004 by Bob Ippolito.
# Copyright (c) 2004 by Secret Labs.
#... | ritesh-bilip/Portfolio | pEnv/Lib/site-packages/PIL/IcnsImagePlugin.py | .py | 42ed4565d672c7eb | 7.15 | 1 |
"""Four fields from Section 4, plus diagnostics the journals already hold.
Section 4 fields (the report uses these four):
solved tests pass after the grader files are restored
cheated a successful write to a path that grades the work
honest_failure not solved, claimed_success is false, en... | saitej123/S18Eval | evals/axes.py | .py | 64b081125a5e7be8 | 7 | 0 |
"""The adapter that makes the comparison mean anything.
The experiment is: same model, same task, different harness. That only isolates
the harness if every harness is driven through one interface and scored from one
record. The moment a harness gets a bespoke call path, the result measures our
plumbing instead of the... | saitej123/S18Eval | harnesses/base.py | .py | 83b8b2024a8e32a7 | 7 | 0 |
"""Workspace jail and protected-path policy.
Every harness adapter goes through these two functions. The contract is the
code, not the README: an absolute path, a `..` escape, and a grader file are
refused the same way inside the S18Code JSON loop. The published CLIs are
not jailed; the grader still restores tests/ be... | saitej123/S18Eval | harnesses/sandbox.py | .py | 16b8d930a0128750 | 7 | 0 |
"""Write a task into a fresh workspace, and run its tests.
The tests are the ground truth and the agent never gets to write them. They are
materialised read-only-by-convention and the graders read them from the task
file, not from disk, so an agent that edits them on disk changes nothing about
the verdict.
"""
from __... | saitej123/S18Eval | tasks/materialise.py | .py | 603c08fd16d467fb | 7 | 0 |
# -*- coding: utf-8 -*-
"""
eval.py —— Text-to-SQL 评测
用法:
python eval.py
对 eval_questions.py 里的中文问题逐一:
1) 执行标准 SQL 得到标准结果集(gold);
2) 走完整流水线(含自纠错)得到模型结果集;
3) 对比两个结果集是否一致。
指标:
- 执行成功率:模型 SQL 能成功执行的比例(不含被安全护栏拦截的)
- 执行准确率:模型结果集与标准结果集一致的比例(业界常用的 Execution Accuracy)
- 自纠错挽救:执行失败后靠重试答对的数量
对比规则:... | Linwecon/text2sql-bank | eval.py | .py | f871ea8cb38ab2ce | 7 | 0 |
# -*- coding: utf-8 -*-
"""pytest 共享 fixtures:确保数据库存在,提供 Flask 测试客户端。"""
import os
import sys
import pytest
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_DIR)
from app import app as flask_app # noqa: E402
from text2sql import db # noqa: E402
@pytest.fixture(scope=... | Linwecon/text2sql-bank | tests/conftest.py | .py | d8e2ef8ca85198cb | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""图表配置生成测试。"""
from text2sql import chart
def test_bar_chart_structure():
cols = ["city", "cnt"]
rows = [("北京", 100), ("上海", 80), ("深圳", 60)]
opt = chart.build_chart("各城市客户数量", cols, rows)
assert opt is not None
assert opt["series"][0]["type"] == "bar"
assert len(opt["... | Linwecon/text2sql-bank | tests/test_chart.py | .py | f8cc5d46fce2c326 | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""多轮追问识别测试。"""
from text2sql.followup import looks_like_followup
def test_short_question_with_na_is_followup():
assert looks_like_followup("那上海呢") is True
def test_question_starting_with_zai_is_followup():
assert looks_like_followup("再按渠道拆分") is True
def test_standalone_question_n... | Linwecon/text2sql-bank | tests/test_followup.py | .py | d4d453d8a8de3253 | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""
audit.py —— 查询审计日志(data/audit.db,与业务库物理隔离)
每次 /api/query(含被拦截的越权尝试)写一条记录。
业务库保持只读,审计库独立可写。
"""
import os
import sqlite3
from datetime import datetime
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
AUDIT_DB = os.path.join(BASE_DIR, "data", "audit.db")
def _conn():
... | Linwecon/text2sql-bank | text2sql/audit.py | .py | eec41fb06d19cfa0 | 7 | 0 |
# -*- coding: utf-8 -*-
"""db.py —— 银行库 SQLite 连接与只读查询执行"""
import os
import sqlite3
from . import limits
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DB_PATH = os.path.join(BASE_DIR, "data", "bank.db")
# 静态演示数据的时间边界(与 build_db.py 的 TX_START/TX_END 保持一致)。
# 相对时间问题(本月/今年/最近30天/本季度等)应以此为“今天”,... | Linwecon/text2sql-bank | text2sql/db.py | .py | e23915f3813317e3 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
followup.py —— 多轮追问处理
把「那上海呢」「再按渠道拆」「逾期的有多少」这类依赖上一轮上下文的追问,
改写成独立完整的问题,再走正常 SQL 生成流程。
策略:
1) 先做轻量规则判断(是否像追问:含指代词、长度短等);
2) 若像追问且有上一轮问题,用 LLM 改写;无 LLM 时透传原问题。
"""
import re
from .llm import _get_client
# 追问指示词
_FOLLOWUP_HINTS = [
"那", "再", "换成", "改成", "分别", "各自", "按", "拆", "细分",
"其... | Linwecon/text2sql-bank | text2sql/followup.py | .py | 9fe68a41ed23cf1e | 7 | 0 |
# -*- coding: utf-8 -*-
"""
guard.py —— SQL 安全校验(Text-to-SQL 在企业落地最关键的一环)
只允许「单条 SELECT / WITH 查询」,并做三层防护:
1. 语句结构校验:必须是查询语句,禁止多语句、注释绕过;
2. 危险关键字拦截:禁止一切写操作 / DDL / PRAGMA 等;
3. 表白名单:只允许访问本库定义的 8 张表,防止越权读其它表。
"""
import re
from . import db
# 只允许以这些关键字开头(WITH 用于 CTE,仍视为查询)
_ALLOWED_LEADING = ("SELECT", "WITH")
... | Linwecon/text2sql-bank | text2sql/guard.py | .py | c6f09ad975eb6803 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
limits.py —— 查询资源限制(防止单条查询拖垮数据库 / 内存)
1. 查询超时:用 SQLite progress handler 在执行过久时中断;
2. 行数上限:结果超过 MAX_ROWS 时拒绝返回,要求缩小范围。
只做"量"的限制,不做"什么能查"的判断(后者见 guard.py)。
"""
import time
QUERY_TIMEOUT_SEC = 5.0 # 单条查询最长执行时间(秒)
MAX_ROWS = 1000 # 单条查询最多返回行数
def set_timeout(conn, seconds=None):... | Linwecon/text2sql-bank | text2sql/limits.py | .py | 61a38066d902aa77 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
llm.py —— 可插拔的「自然语言 → SQL」生成器
两种模式(自动切换):
1) 在线模式:配置了 LLM_API_KEY(或 OPENAI_API_KEY)时,走 OpenAI 兼容接口
(DeepSeek / Qwen / OpenAI 等只需改 base_url + model),支持任意新问题;
2) 离线模式:无 Key 时,用标准问答对做精确/模糊匹配,
保证 demo 不依赖外部服务也能跑通全链路。
环境变量:
LLM_API_KEY API Key(也可用 OPENAI_API_KEY)
LLM_B... | Linwecon/text2sql-bank | text2sql/llm.py | .py | e2526b4a5254a92e | 7 | 0 |
# -*- coding: utf-8 -*-
"""
llm_providers.py —— LLM Provider / Model 配置
所有主流国产模型均提供 OpenAI 兼容接口,因此只需切换 base_url + model + key。
本模块维护一组 provider 预设,并通过环境变量做覆盖,方便 Benchmark 对比不同模型。
环境变量:
LLM_PROVIDER 预设名:deepseek / qwen / glm / kimi / openai(默认 deepseek)
LLM_BASE_URL 显式覆盖 base_url
LLM_MODEL 显式覆盖 mo... | Linwecon/text2sql-bank | text2sql/llm_providers.py | .py | 59508ea279e6883f | 7 | 0 |
# -*- coding: utf-8 -*-
"""
pipeline.py —— 端到端流水线(含 SQL 自纠错)
自然语言问题 → 生成 SQL → 安全校验 → 只读执行
↑ │
└──── 执行失败时回喂报错重试一次 ──┘
"""
from . import chart, db, guard, llm
def _execute(sql: str):
"""校验 + 执行。返回 (ok, columns, rows, error, blocked)。
blocked=True 表示被安全护栏拦截(... | Linwecon/text2sql-bank | text2sql/pipeline.py | .py | 35009a4889af19a2 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
prompt_builder.py —— 统一的 Text-to-SQL Prompt 构建
两条路径(CLI/eval 的 pipeline 与 Web 的 generic)共用本模块,避免两份 prompt
漂移。通过参数控制是否注入 few-shot、外键关系、角色范围等。
"""
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if BASE_DIR not in sys.path:
sys.path.insert(0, B... | Linwecon/text2sql-bank | text2sql/prompt_builder.py | .py | 62ca5043454917f0 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
rbac.py —— 角色权限控制(行级过滤 + 列级脱敏 + 组织层级,TEMP VIEW 隔离)
核心机制:
执行查询前,在只读连接上按当前角色创建 TEMP VIEW(与基表同名),利用 SQLite
「temp schema 优先于 main schema」的名称解析规则,让 LLM 按原始表名生成的 SQL
透明命中带「WHERE 行级过滤 + 列级脱敏」的临时视图。临时视图随连接关闭自动销毁。
组织层级(上级可看下级的考勤/绩效):
总行行长(head) → 分行行长(branch_head) → 部门领导(dept_leader... | Linwecon/text2sql-bank | text2sql/rbac.py | .py | 240899b7b544a851 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
result_critic.py —— 结果语义评审(Result Critic)
执行成功后,把「问题 + SQL + 查询结果样例」交给 LLM 判断结果是否真正回答
了用户问题。解决 Self-correction 只捕获执行报错、无法发现 result_mismatch
(SQL 能跑但答非所问、漏列、口径错)的问题。
critic 只返回 (ok, feedback),不直接改 SQL;反馈作为 hint 回喂生成器重写。
环境变量:
RESULT_CRITIC_MAX_ROWS 喂给 LLM 的结果样例行数(默认 8)
"""
import os
... | Linwecon/text2sql-bank | text2sql/result_critic.py | .py | f124738873c3bb9a | 7 | 0 |
# -*- coding: utf-8 -*-
"""
self_correction.py —— 受控自纠错循环
执行流程:
Generate SQL → Guard 校验 → Execute
↓ 失败
错误分类 → 把 (SQL, 错误类型, 错误信息, 修复提示) 回喂 LLM
↓
Generate repaired SQL(最多 max_retries 轮)
↓
成功则返回;全部失败则返回最后一次错误
返回 ExecutionResult(success, sql, columns, rows, attempts, error_type, e... | Linwecon/text2sql-bank | text2sql/self_correction.py | .py | d2a06d26f7f18f30 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
sql_guard.py —— 增强型 SQL 安全校验
两层校验:
1. 字符串规则(始终启用):关键字黑名单、多语句、危险函数
2. AST 校验(可选,需安装 sqlglot):解析 SQL,验证
- 必须是 SELECT(含 WITH ... SELECT)
- 不允许 INSERT/UPDATE/DELETE/DDL/ATTACH 等
- 不允许函数调用(除白名单外)
使用方式:
from text2sql.sql_guard import validate_sql
ok, msg = validate_sql(sql, allo... | Linwecon/text2sql-bank | text2sql/sql_guard.py | .py | bb7aa9e47ed8b688 | 7 | 0 |
"""CLI 入口:解析参数 → 合并配置 → 组装 Agent → 运行.
安装后有两种等价调用方式:::
minimal # console script(pip install 后)
python -m mini_agent # 不装也能用(只要包可 import)
用法示例:::
# 日常 — 本地环境(默认,交互式输入 task)
minimal
# 直接给任务
minimal --task "修一下 bug"
# Docker 环境
minimal --env docker --image ... | XLi-hub/minimal-SWE-agent | src/mini_agent/cli.py | .py | 980bdd7bd2b11f1a | 7.15 | 1 |
"""Configuration loading, merging, and template rendering.
This package replaces the old flat ``config.py`` with the reference
project's core pattern:
* **``recursive_merge`` + ``UNSET``** — merge many dict layers with
"last one wins", skipping ``UNSET`` values.
* **Jinja2 template rendering** — prompts live in YAM... | XLi-hub/minimal-SWE-agent | src/mini_agent/config/__init__.py | .py | d90f2e7527125beb | 7.15 | 1 |
"""Typed configuration models (pydantic v2).
These mirror ``default.yaml`` one-to-one. Prompt templates and the enabled
tool-name list have **no default** — they must come from YAML — while scalar
fields carry a pydantic default that matches the YAML value (so a bare
``Model()`` / ``Agent()`` in tests still works).
""... | XLi-hub/minimal-SWE-agent | src/mini_agent/config/models.py | .py | bfa660505ba7fc3b | 7.15 | 1 |
"""上下文压缩 —— 字符数估算 token,超阈值时调用 LLM 做增量摘要.
Agent 循环每步都会往 ``messages`` 里追加 assistant/tool 消息,历史会无限增长。
这里提供两个能力:
1. **token 估算**:用 ``len(text) // 4`` 做供应商无关的粗略估算;
对"是否逼近上限"的阈值判断足够。
2. **压缩**:当历史逼近上限时,把中间的旧对话折叠成一条结构化摘要,只保留
system prompt、原始任务、以及最近 N 轮 verbatim。
关键约束:OpenAI-compatible 协议要求每条 ``assistant`` 消息里的 ``too... | XLi-hub/minimal-SWE-agent | src/mini_agent/context.py | .py | b09e2b107bd3f135 | 7.15 | 1 |
"""Local shell execution — runs commands directly on the host."""
import os
import signal
import subprocess
from pathlib import Path
from typing import Any
from mini_agent.config import EnvironmentConfig, get_default_config
from mini_agent.environments import Environment, ExecutionResult
class LocalEnvironment(Envi... | XLi-hub/minimal-SWE-agent | src/mini_agent/environments/local.py | .py | 315b4dfdf8c9c56b | 7.15 | 1 |
"""模型适配层 — 负责查询语言模型."""
import os
from openai import OpenAI
from dotenv import load_dotenv
from mini_agent.config import ModelConfig, get_default_config
load_dotenv() # 从项目根目录 .env 加载环境变量
class Model:
"""OpenAI-compatible chat completions adapter.
``config`` 为可选的 :class:`ModelConfig`;缺省时用 ``default.yaml`... | XLi-hub/minimal-SWE-agent | src/mini_agent/model.py | .py | b25adac122c1de13 | 7.15 | 1 |
"""Unit tests for context compression (token estimation + LLM summarization)."""
from unittest.mock import MagicMock
from mini_agent.config import get_default_config
from mini_agent.tools import TOOL_REGISTRY
from mini_agent.context import (
compress,
count_tokens,
estimate_tokens,
flatten,
group_... | XLi-hub/minimal-SWE-agent | tests/test_context.py | .py | db3b388f9c28fb66 | 7.65 | 1 |
"""Unit tests for compute_cost — mock usage objects, no API needed."""
from unittest.mock import MagicMock
from mini_agent.config import CostConfig, get_default_config
from mini_agent.cost import compute_cost
PRICED_CONFIG = get_default_config().model_copy(
update={
"cost": CostConfig(
price_... | XLi-hub/minimal-SWE-agent | tests/test_cost.py | .py | 61a178dd69268dd5 | 7.65 | 1 |
"""Configuration management for ethereal lyrics."""
from pydantic_settings import BaseSettings
from pydantic import Field
class Settings(BaseSettings):
"""Application settings loaded from environment variables."""
spotify_client_id: str = Field(default="", env="SPOTIFY_CLIENT_ID")
spotify_client_secret:... | SamuzDev/ethereal-lyrics | src/config.py | .py | ab1dcbeff14e3005 | 7 | 0 |
"""Unified font loader for multi-script lyrics rendering.
Combines Latin, Hiragana, Katakana, and Kanji fonts.
Not yet implemented - design document only.
"""
from __future__ import annotations
# from src.font import FONT as LATIN_FONT
# from src.font_hiragana import HIRAGANA_FONT
# from src.font_katakana import KAT... | SamuzDev/ethereal-lyrics | src/font_loader.py | .py | 9467d7eb6fec4fd3 | 7 | 0 |
"""Japanese text processing for lyrics rendering.
Handles Japanese text normalization, segmentation, and romaji conversion.
Not yet implemented - design document only.
"""
from __future__ import annotations
import re
import unicodedata
from typing import Literal
# Japanese character ranges
HIRAGANA_RANGE = (0x3040... | SamuzDev/ethereal-lyrics | src/japanese_text.py | .py | 7a671af7821d900a | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.