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
"""Normalized, provider-agnostic types. These two structs are the *currency* of anypick: every obtainer translates its raw payload into them, and the filter/pick layers operate on them and nothing else. See docs/architecture.md. """ from __future__ import annotations from dataclasses import dataclass, field from typ...
gi-dellav/anypick
anypick-python/anypick/model.py
.py
6ffad9dcc7ab7fb7
7.24
2
"""Vercel AI Gateway provider implementation (models only). See docs/providers/vercel.md for the endpoint contract, response shape, and mapping rules. * :class:`VercelModelObtainer` — ``GET /v1/models`` (public; Bearer key optional). The Vercel AI Gateway exposes **no benchmark feed**, so there is no ``VercelBenchma...
gi-dellav/anypick
anypick-python/anypick/vercel.py
.py
4f21fa15ac591be4
7.24
2
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Agent Troubleshooter - 诊断工具 使用方法: python diagnose.py "Codex 报 401 错误" python diagnose.py "Claude 429 rate limit" """ import json import sys from pathlib import Path # 确保以任意工作目录运行时都能找到同目录下的 utils 包 sys.path.insert(0, str(Path(__file__).resolve().parent)) # 导入...
XCZ-Huazhou/agent-troubleshoot-skill
diagnose.py
.py
92ebabbba03bfbe7
7
0
""" Agent Troubleshooter - 语义匹配和去重工具 功能: 1. 症状关键词提取和标准化 2. Jaccard 相似度计算 3. 框架名识别 4. 案例去重判断 """ import json import re import sys from datetime import date from typing import List, Dict, Any, Tuple, Optional from pathlib import Path # 错误码标准化映射 ERROR_CODE_NORMALIZATION = { # 认证错误 "401": "AUTH_ERROR", "403"...
XCZ-Huazhou/agent-troubleshoot-skill
utils/matcher.py
.py
051b2223814ebb77
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ batch-generate and tag wavetables, destination paths are hard-coded """ import os import shutil import wtcurve import wtfile import wttag # destination paths for tagged files wav_path = '/home/ftp/audio/Wavetables/WT1/My' wt_path = os.path.expanduser('~/Music/Bitwig/...
porzione/wtcurve
gen_n_tag.py
.py
18cd366e6ee06703
7.45
7
#!/usr/bin/env python # -*- coding: utf-8 -*- """ process wavetable files """ import sys import os import struct import numpy as np import soundfile as sf WAV_SAMPLE_RATE = 44100 H2P_HEADER = """\ #defaults=no #cm=OSC Wave=2 <? float Wave[%d]; """ H2P_FMULT = 0.999969 # u-he Zebra 2 OSC format is fixed H2P_NUM_WAV...
porzione/wtcurve
wtfile.py
.py
ef4e3f32b9a3fb38
7.45
7
""" Agent 2 — Clause Miner Uses Gemini (google-genai) to read raw contract text and extract every AI-likeness / voice-clone / digital-double consent clause into a structured, citable form. This is the first point where the Google Cloud AI SDK is imported and called at runtime, per the hackathon's technical requirement...
asmita-ai/consent-continuity-agent
agents/clause_miner.py
.py
4627bd4db7e5977e
7
0
""" Agent 1 — Ingestor Normalizes heterogeneous inputs (contract PDFs, call sheets, dubbing scripts, promo/campaign plans, game tie-in briefs) into plain text ready for the Clause Miner. In production this would use Vertex AI Document AI for PDFs; for the hackathon build we support .txt/.pdf and a pluggable extractor....
asmita-ai/consent-continuity-agent
agents/ingestor.py
.py
7c7ed4adabe30157
7
0
""" Core data models for the Continuity rights ledger. These are the machine-checkable structures that Agent 3 (Policy Compiler) produces from Agent 2's (Clause Miner) raw extraction, and that Agent 4 (Usage Monitor) queries against every planned-use event. """ from __future__ import annotations from datetime import...
asmita-ai/consent-continuity-agent
models/schema.py
.py
7d4277dbca21b760
7
0
"""Configuration management for Transcript Generator.""" import json import os import re from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Any, Dict, List, Optional, Union # Valid export format options VALID_FORMATS = {"text", "timestamped", "srt", "vtt", "json", "csv", "mar...
advaitpr/transcript-generator
src/transcript_generator/config.py
.py
64ccb096ccfdaa6f
7
0
"""URL parser and video ID extractor for video URLs.""" import re from urllib.parse import parse_qs, urlparse # Regular expression for a valid 11-character YouTube video ID VIDEO_ID_REGEX = re.compile(r"^[a-zA-Z0-9_-]{11}$") # Patterns for extracting video ID from various URL formats URL_PATTERNS = [ # Standard ...
advaitpr/transcript-generator
src/transcript_generator/url_parser.py
.py
84d7ff799ac49813
7
0
"""audio conversion helpers. ffmpeg does the heavy lifting: anything it can decode gets turned into Ogg Vorbis at the pen's native settings (mono 22050 Hz). ffmpeg is found via the RAV_FFMPEG env var, then PATH, then the static binary that ships with imageio-ffmpeg (if installed). """ import os import re import shut...
Markthegamer108/RAVage
rav_tool/convert.py
.py
5fd40ffd60d0c63c
7.24
2
"""任务管理器:子进程隔离跑翻译,UI 崩了不影响翻译。 每个任务 = 独立子进程(python -m translator.cli 变体),通过 JSONL 事件流文件 + 控制管道与父进程通信。单任务模型: 同一时刻只允许一个翻译在跑(LLM 并发/缓存 DB 都是单写者设计)。 """ from __future__ import annotations import json import os import subprocess import sys import threading import time import uuid from pathlib import Path from translator.c...
ShZbz/pdf-translator
server/jobs.py
.py
9fee7d77dd6a8395
7.15
1
"""P2 验收单测(SCHEME §6 P2): - batch 协议 roundtrip(LLM 返回 JSON → 译文落位) - 缓存二次运行 0 调用 - max_llm_calls 触顶行为(不崩、保留原文、stderr 警告) - [FORMULA_n] 计数守恒 - 坏响应重试一次后降级保留原文 """ from __future__ import annotations import json import threading import time import sys from pathlib import Path from types import SimpleNamespace sys.path.in...
ShZbz/pdf-translator
tests/test_smoke.py
.py
cab2744f7a301985
7.65
1
"""v0.4.0 UI 集成单测:事件流 / 暂停恢复 / 取消 / 锁安全。 全部零网络零 API key(FakeLLM 复用 test_smoke 的模式)。 """ from __future__ import annotations import json import sys import threading import time from pathlib import Path from types import SimpleNamespace sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from translator.contr...
ShZbz/pdf-translator
tests/test_v040.py
.py
dc8c767f28102b6d
7.65
1
"""协作式任务控制:暂停/恢复/取消(v0.4.0 UI 支持)。 语义(批间暂停): - 检查点粒度 = 页级(布局/渲染循环)+ 批级(LLM 调用前)。 - pause 后正在飞行中的那一次 LLM 请求会跑完才停,不半路掐断 (省 token、防半截缓存)。实际延迟几秒内。 - cancel 在下一个检查点立即生效,抛 JobCancelled 向上传播; 调用方负责收尾(管线内已保证不落半成品 PDF:先写 .tmp 再 rename)。 并发纪律:所有公开方法遵循「锁内改状态、锁外发通知」—— notify 必须在释放 self._lock 之后执行(非重入锁,锁内 notify = 死锁)。 """ fr...
ShZbz/pdf-translator
translator/control.py
.py
a598c914a7ab3b74
7.15
1
"""进度事件流(v0.4.0 UI 支持)。 设计: - 事件是纯 dict(JSON 可序列化),经回调推给消费者(server 端转 JSONL/轮询快照)。 - 回调永远不抛异常出去——UI 故障不能拖死翻译管线。 - CLI 不装回调时零开销(一次 None 判断)。 """ from __future__ import annotations import threading import time from typing import Callable class EventSink: """线程安全的事件收集器。 on_event: callable(dict) -> None,在调用者线程...
ShZbz/pdf-translator
translator/events.py
.py
fe236ae250150db7
7.15
1
"""文字层提取:page → 结构化块列表(BBox/size/flags/font)。 <50 字符的扫描页候选走 OCR 降级(D7),OCR 引擎为可选依赖, 未安装时该页保留空文本并计入警告。 """ from __future__ import annotations import pymupdf def page_has_text_layer(page, min_chars: int = 50) -> bool: """D7: 文字层字符数 < min_chars 视为扫描页候选。""" return len(page.get_text().strip()) >= min_chars def...
ShZbz/pdf-translator
translator/extract.py
.py
dbc336a63e62687d
7.15
1
"""D4 术语表:外部 YAML {src: dst},注入 system prompt + 译后校验。""" from __future__ import annotations from pathlib import Path import yaml class Glossary: def __init__(self, mapping: dict[str, str] | None = None): self.mapping: dict[str, str] = dict(mapping or {}) @classmethod def load(cls, path: str | P...
ShZbz/pdf-translator
translator/glossary.py
.py
08f4da0e360bf6f7
7.15
1
"""P4: preprocess.py — D5 水印两层策略(文字层 wmremover 式清理)。 三层递进(SCHEME D5,复用 wmremover.py 逻辑 + P4 实测修复): 1. 独立短流(<500B)含水印关键词 → 清空 2. 长流/Form XObject 中斜切/旋转矩阵 Tm + 水印关键词的 BT..ET 块 → 移除块 (P4 实测:水印常藏在 Form XObject 里;斜切矩阵形如 "1 0 0.21256 1", 原"四小数"正则漏检 → 放宽为允许 b/c 为 0) 3. Watermark/Stamp 注释 → 删除 cv2.inpaint 仅用于...
ShZbz/pdf-translator
translator/preprocess.py
.py
e5df1e87b4cb0dd3
7.15
1
"""修复 _wrap_cjk: Latin 词不拆行(词边界断行), CJK 保持逐字断行。 v0.2.2 任务1/5 排版包:英文保留段/双语原文层被逐字拆碎的根因是 贪心逐字断行对 Latin 文本无词边界概念。改为混合策略: - 连续 Latin/digit 串视为不可分 token - 行首放不下整个 token 时整词压到下一行;超长 token(>行宽)硬切兜底 - CJK 字符维持逐字+避头尾 """ from __future__ import annotations import re import pymupdf # 行首禁则标点(不可出现在行首,悬挂到上一行行尾) _NO_LINE_START = s...
ShZbz/pdf-translator
translator/wrap_mixed.py
.py
ef26f1640ee9f16f
7.15
1
#!/usr/bin/env python3 """activity-emitter — async Claude Code hook that journals the core's activity as AWP activity objects (Activity outbox Phase 2, step 1 — owner's pick 2026-07-24, delivered via the human-action bridge's first live card). The AWP roadmap's Phase 2 is a durable Agent Activity outbox: the owner (an...
sonichi/sutando
hooks/activity-emitter.py
.py
8a417efc6dd3f13b
8
387
#!/usr/bin/env python3 """gmail-write-guard — PreToolUse hook that denies the claude.ai Gmail MCP connector's WRITE-scoped tools and routes writes to the IMAP/SMTP path. Why (field report 05cb849a, michael@actoneventures.com, 2026-07-13): every Gmail WRITE operation through the claude.ai connector is unreliable or bro...
sonichi/sutando
hooks/gmail-write-guard.py
.py
a0dc70dc7b2c00e9
8
387
#!/usr/bin/env python3 """result-file-marker-guard — PreToolUse hook that DENIES writing a result body whose ``[file:|send:|attach:]`` marker points outside the send allowlist **for the adapter that will actually deliver it**. Why (owner incident 2026-08-04, #susan): the agent finished a 6-minute video, wrote ``[file:...
sonichi/sutando
hooks/result-file-marker-guard.py
.py
e81bd69f743cea53
8
387
#!/usr/bin/env python3 """Skill-usage telemetry — PostToolUse[Skill] hook. Emits ONE anonymous ``feature_used {feature: "skill:<name>"}`` product-telemetry event every time the core invokes a skill (the `Skill` tool). This is the chokepoint that broadens feature-usage coverage from the two hand-instrumented scripts (m...
sonichi/sutando
hooks/skill-usage-telemetry.py
.py
e1ea01ff51c2b587
8
387
#!/usr/bin/env python3 """skip-ask-user-question — PreToolUse hook that blocks the interactive `AskUserQuestion` tool in Sutando's headless core session. Why: the core agent runs NON-INTERACTIVELY — src/agent/claude/cli/start-cli.sh launches it with `--dangerously-skip-permissions` inside a tmux pane, driven over `--r...
sonichi/sutando
hooks/skip-ask-user-question.py
.py
13665d1dfc5f5fa1
7
387
"""Fail-closed secret redaction for persisted inbound chat content. The explicit ``vault set KEY VALUE`` path stores named values in Keychain. This module covers the other common case: somebody pastes a token into ordinary Discord/Slack prose. Known values are replaced before task files, owner-activity state, prompt s...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/chat_secret_filter.py
.py
cc059b9c06981d84
8
387
#!/usr/bin/env python3 """Recovery for a `[deduped: <holder>]` result whose holder never answered. `result_markers.dedup_decision` decides; this binds that decision to a workspace and performs the filesystem half, so every adapter keeps only its own routing and notification. Returns a `(action, payload)` plan rather ...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/dedup_recovery.py
.py
194467cbc6f30ee2
8
387
"""Delivery Core contract: the channel-neutral seam between local ownership (ClaimBackend), the external side effect (DeliveryProvider), and the drain loop (DeliveryCore in core.py). Identity model (three types, never conflated): - item_id: stable logical message identity, assigned at publish. - ClaimToken: one local-...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/delivery_core/contract.py
.py
f7b11971da558165
8
387
"""DeliveryCore: the drain loop. The ONLY component that reads DeliveryOutcome semantics and ProviderCapabilities — channel code never decides retry/UNKNOWN rules (acceptance criterion 2). Retry policy (normative): - only a confirmed NOT_DELIVERED auto-retries; - OUTCOME_UNKNOWN parks unless capabilities license recon...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/delivery_core/core.py
.py
68f79fc9a6ad800a
8
387
"""Migration fencing: single-protocol-per-epoch (seam doc §4). One logical item is interpreted by exactly ONE claim protocol within an epoch. Migration = lock out drainers -> one-shot convert (each item individually atomic) -> write the version fence -> start only the new drainer. The fence is written LAST: a crash an...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/delivery_core/migration.py
.py
7ab8f786712bf36a
8
387
"""event_channel — Sparrow's persistent Workspace-Event delivery channel (#AWP P0). An ADDITIVE, ISOLATED channel that runs ALONGSIDE task delivery and never touches it. It keeps an outbound SSE connection to `/v1/events/stream`, writes every authorized event durably to the local EventInbox (at-least-once), and resume...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/event_channel.py
.py
fc8dc90164dee131
8
387
"""Restart recovery for proactively delivered result files. Bridges claim ``proactive-*.txt`` as ``.sending``; this restores claims a crash stranded so every adapter applies one collision and failure policy at startup. """ from __future__ import annotations import os import re from pathlib import Path from typing im...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/proactive_recovery.py
.py
c489835ce1ef1c47
8
387
#!/usr/bin/env python3 """Readiness of a `results/<task-id>.txt` file, for every delivery consumer. The single owner of "is this result file ready to send?". Adapters bind their own resolved results directory and keep only provider-specific delivery; they must not re-implement the check. A result path can exist befor...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/result_ready.py
.py
dc48c98ae0747325
8
387
"""Shared file-attachment allowlist for `[file:|send:|attach:]` markers. Single source of truth for the policy that decides whether an agent- emitted file marker can be delivered to the owner's Discord DM / channel. Used by: - ``src/discord-bridge.py`` — live WS-connected bridge (``discord.File(path)``). - ``...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/send_allowlist.py
.py
b416718b64facbfb
8
387
"""Classify an outbound-send failure as transient (retry) or permanent (park). Parking is the safe default: only a KNOWN transient retries. """ from __future__ import annotations from pathlib import Path # 4xx timing cases only. 5xx is handled as a RANGE below, because enumerating it # silently parked the Cloudflar...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/send_failure_policy.py
.py
944eb3c5610d186e
8
387
#!/usr/bin/env python3 """The Team-tier guardrail prose, shared by every surface that admits Team work. Two consumers interpret the same policy — the workstream session worker (which used to wrap it around a spawned Team session) and the AG2 Space gateway (which must now emit it in-band, because closing the Team sessi...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/team_guardrail.py
.py
9837295d360c2b03
8
387
"""Pure, dependency-free `vault set KEY VALUE` grammar — regex + redact-only. Canonical source for `vault_intercept.py` and the vendored ag2-sparrow copy; no imports beyond `re`. """ from __future__ import annotations import re # Separator is whitespace or `=`; KEY stops at the first space/`=` so `=` isn't swallowed...
sonichi/sutando
packages/ag2-sparrow/ag2_sparrow/vault_set_grammar.py
.py
c3aa73e81c0e0f5c
7
387
"""_post_task_ack — self-healing retry when the gateway lacks /v1/tasks/<id>/ack. The worker acks each pulled task so the broker can surface a "received" state. When the broker lacks the endpoint it 404s; the worker must back off — but NOT permanently, or a broker that later *deploys* the endpoint is never picked up u...
sonichi/sutando
packages/ag2-sparrow/tests/test_ack_retry.py
.py
d46f085c12c4ed1f
8.5
387
"""Bounded DNS resolution — a hung resolver must raise (so the poll loop can emit "reconnecting" and retry) instead of wedging the process forever. Regression guard for the 2026-07-25 tester incident: the gateway sat in a "reconnecting" state indefinitely because getaddrinfo (which has no native timeout) blocked the l...
sonichi/sutando
packages/ag2-sparrow/tests/test_dns_timeout.py
.py
a1727d41b910257f
8.5
387
"""The env tier must strip quotes, like the three file tiers already do. A user who writes the credential quoted — REMOTE_TASK_TOKEN='https://gw.example/relay|<secret>' — gets a working bridge when the value is read from the FILE (three readers call `.strip().strip("'\\"")`) and a permanently unauthorized one wh...
sonichi/sutando
packages/ag2-sparrow/tests/test_env_token_quotes.py
.py
f66449501964d261
8.5
387
"""Tests for event_consumer (AWP P1) — inbox → taskify → tasks/. Covers ambient trust boundary, held-events-not-consumed (no loss), idempotent re-drain, and skip-settles-immediately. Self-contained; exit 0/1.""" import os import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve...
sonichi/sutando
packages/ag2-sparrow/tests/test_event_consumer.py
.py
1ce87de2d8e59f8a
8.5
387
"""Tests for the P0 event delivery channel — durable inbox + persistent SSE consumer. Covers the friend's fault-recovery acceptance criteria: at-least-once dedup, cursor recovery, crash-before-durable safety, channel isolation, fatal auth stop. Self-contained (stdlib + a mocked urlopen). Exit 0/1.""" import io import o...
sonichi/sutando
packages/ag2-sparrow/tests/test_event_inbox_channel.py
.py
0778635d970427c3
8.5
387
"""_emit_gateway_status — connection-liveness sidecar (state/gateway-status.json). Covers the shape a local supervisor reads and the last_ok_ts preservation that lets it show "last connected N s ago" while reconnecting. """ import json import os import tempfile import importlib import sys import pathlib def _load(tmp)...
sonichi/sutando
packages/ag2-sparrow/tests/test_gateway_status.py
.py
2edc623ac0cda31c
8.5
387
"""in-flight ledger — crash-before-ack recovery (v1 freeze gate #142 item 6). A task pulled from the broker but not yet completed (`POST /v1/results`) lives in the persisted in-flight set. If the worker restarts between pull and result-POST, the set must survive so the result drain re-acks it — otherwise the reply is ...
sonichi/sutando
packages/ag2-sparrow/tests/test_inflight_recovery.py
.py
f3f78aa4e0eff8ee
8.5
387
"""FastAPI backend entry point for the Insurance Hybrid RAG application.""" from __future__ import annotations import logging from contextlib import asynccontextmanager from typing import Annotated import uvicorn from fastapi import FastAPI, Header, HTTPException from fastapi.middleware.cors import CORSMiddleware fro...
Rabilkhan786/health-agentic-rag
app.py
.py
a5e31c9f89faf894
7
0
"""Single validated configuration entry point for the application.""" from __future__ import annotations import os from dataclasses import dataclass from pathlib import Path from typing import Any import yaml from dotenv import load_dotenv REQUIRED_SECTIONS = ( "project", "models", "pinecone", "retr...
Rabilkhan786/health-agentic-rag
config/settings.py
.py
3ce0f10030d92125
7
0
"""Run the RAGAS evaluation suite against evaluation/rag_dataset.json. Usage: uv run python evaluation/run_ragas.py uv run python evaluation/run_ragas.py --smoke (1 per topic) WHAT THIS MEASURES, AND WHAT IT DOES NOT: this scores the retrieval half of the copilot -- can it find the clause that answers a qu...
Rabilkhan786/health-agentic-rag
evaluation/run_ragas.py
.py
ba95af709e17392c
7
0
"""Root entry point for the PDF-to-Pinecone indexing workflow. Runs the section-aware pipeline (src/ingestion/pipeline.py) over every PDF in Data/insurance_documents/ and upserts the result into Pinecone. Upserts are idempotent -- document IDs hash the chunk's own content -- so re-running overwrites the same vectors r...
Rabilkhan786/health-agentic-rag
main.py
.py
cf7379820c5a80ab
7
0
"""Layer 1 — the tool-calling agent, built by LangChain's create_agent. create_agent owns the whole reason/act loop, parallel tool execution, and session memory. Nothing in this file hand-rolls any of that. Context.customer_id is the fix for the old "please give me your policy ID" bug: it is passed at invoke time and...
Rabilkhan786/health-agentic-rag
src/agent/agent.py
.py
5a0f4856cbb356de
7
0
"""The typed recommendation an employee reviews. WHY the numbers are assembled here rather than asked of the model: the deterministic engine has already decided the status and computed the payable amount. Handing those to the LLM and asking for them back is a round trip that can only lose -- it once returned a payable...
Rabilkhan786/health-agentic-rag
src/agent/recommendation.py
.py
056803903b04bbe5
7
0
"""Layer 2 — the outer workflow: a claim goes in, a reviewed decision comes out. claim submitted -> eligibility -> agent -> review (pauses) -> persist -> END chat question -> agent -> END The compiled create_agent graph from Layer 1 is added here as an ordinary node (subgraph-as-node), so the claim path end...
Rabilkhan786/health-agentic-rag
src/agent/workflow.py
.py
8d3891ca6b466b3c
7
0
"""In-process TTL cache for hybrid retrieval results. WHY: a full retrieval is dense search + sparse search + RRF + cross-encoder rerank, which costs roughly 4 seconds. Demo users ask the same handful of questions repeatedly, and the eligibility engine re-queries the same treatment for coverage and exclusions, so the ...
Rabilkhan786/health-agentic-rag
src/cache/rag_cache.py
.py
720c6861bcd42901
7
0
"""SQLite-backed audit trail: what the AI recommended vs what the employee did.""" from __future__ import annotations import json import logging import sqlite3 from uuid import uuid4 from src.utils.sqlite_store import SqliteStore from .models import SCHEMA logger = logging.getLogger(__name__) # The three calls the...
Rabilkhan786/health-agentic-rag
src/decisions/store.py
.py
3c42134ebf8b9257
7
0
"""How the engine represents a policy fact it may or may not actually know. WHY this exists: the engine used to return plain numbers, so "this policy states no co-payment" and "nobody could find out whether this policy states a co-payment" arrived at the calculator as the same value -- None, read as 0%. The claim was ...
Rabilkhan786/health-agentic-rag
src/eligibility/facts.py
.py
e21792ee7eff6398
7
0
"""Pull numbers out of policy clause text. WHY this exists: structured facts (sub-limits, waiting periods, co-pays, deductibles) are only in SQL for policies someone has already curated. A customer arriving with any of the other indexed policies has no rows at all, and the engine used to treat that as "no limit applie...
Rabilkhan786/health-agentic-rag
src/eligibility/parsing.py
.py
4c5c12436807945a
7
0
"""Separate a PDF page's prose from its tables. WHY this file exists: PyMuPDF's ``page.get_text()`` dumps table cell content straight into the text stream. That means a sliding-window chunker happily produces chunks like "Cataract 25000 Hernia 30000 waiting period 24" -- cell values glued to unrelated prose, which ret...
Rabilkhan786/health-agentic-rag
src/ingestion/page_parser.py
.py
38a1dd364684e79e
7
0
"""Re-index every policy PDF: clean text to chunks, tables to their homes. WHY: this replaces the single-path Unstructured loader for the policy corpus. Each page is split into prose and tables first, so a chunk never contains stray table cells and a table never gets chopped into chunks. """ from __future__ import ann...
Rabilkhan786/health-agentic-rag
src/ingestion/pipeline.py
.py
75f2a64ff87431ae
7
0
"""Turn classified table rows into natural-language sentences for Pinecone. WHY: an embedding model cannot make sense of a bare row like ``["Cataract", "Rs 25,000"]``. Rewritten as a full sentence that names the insurer, the UIN and the page, the same row becomes a retrievable fact with a citation baked in. """ from _...
Rabilkhan786/health-agentic-rag
src/ingestion/table_converter.py
.py
333310a8bae4b983
7
0
"""Hybrid retrieval, composed from LangChain retrievers instead of by hand. The shape is the one the reference book describes -- run a dense and a sparse retriever in parallel, fuse their rankings, then rerank the survivors with a cross-encoder -- but built with the current LangChain 1.x classes: EnsembleRetrieve...
Rabilkhan786/health-agentic-rag
src/retrieval/retrievers.py
.py
e84cc071d69bbde9
7
0
"""Agent-facing tools over the CRM store: customers, policies, claims. WHY these tools take no customer_id: it is injected at invoke time via ToolRuntime.context, so it never appears in the schema the LLM sees. The model therefore cannot reach another customer's records, and cannot ask for an ID the employee already e...
Rabilkhan786/health-agentic-rag
src/tools/crm_tools.py
.py
2760bc61be3e0867
7
0
"""Agent-facing tools over the hybrid RAG pipeline. Every function narrows retrieval with a Pinecone metadata filter (topic and/or policy UIN) instead of searching the whole index — a question about waiting periods should only compete against waiting_period chunks. The filter matches on `topics`, the list of every to...
Rabilkhan786/health-agentic-rag
src/tools/rag_tools.py
.py
17f9fe547d50f7e8
7
0
"""Shared SQLite plumbing for the three stores in this project. CRMStore, PolicyDataStore and DecisionStore each opened their own connection, set the same row factory, and ran their own schema on first use -- the same fifteen lines written three times. They differ only in which schema they create and what they log, so...
Rabilkhan786/health-agentic-rag
src/utils/sqlite_store.py
.py
b8148af89e694cd0
7
0
"""Adapters for the existing dense and hosted sparse Pinecone indexes. WHY this is not langchain-pinecone's PineconeVectorStore: that class covers one dense index, and this project runs two indexes of different kinds. The sparse half is a Pinecone *hosted* sparse index -- created with create_index_for_model() and quer...
Rabilkhan786/health-agentic-rag
src/vectorstores/pinecone_store.py
.py
da697b67b52ff402
7
0
"""Claims Copilot - the employee-facing frontend. Run with: uv run streamlit run streamlit_app.py This is an INTERNAL tool. The person using it is a claims employee, not a customer. The screen shows a recommendation and the employee decides: the Approve / Edit / Reject actions at the bottom are the point of the whol...
Rabilkhan786/health-agentic-rag
streamlit_app.py
.py
2c6df0b2c09496e7
7
0
"""Deterministic cache-key derivation. ``pickle.dumps`` is not a safe basis for cache keys: the byte stream for a ``set`` (or any object reducing to one) depends on string hash randomisation, so the same logical key hashes differently in every process. This module walks the value instead and emits a canonical encoding...
farfarfun/farcache
src/farcache/_keys.py
.py
1d92937d7399dab7
7
0
"""Internal utilities shared across farcache modules.""" from __future__ import annotations import inspect from collections.abc import Callable from typing import Any __all__ = ["bind_args", "namespace_of"] def bind_args( signature: inspect.Signature, args: tuple[Any, ...], kwargs: dict[str, Any], ) ->...
farfarfun/farcache
src/farcache/_utils.py
.py
99e9f7e4000c1f61
7
0
"""In-memory caches, backed by :mod:`cachebox` eviction policies. Every decorator here works both bare and called:: @lru_cache def f(x): ... @lru_cache(maxsize=500) def g(x): ... The wrapper exposes the underlying policy as ``f.cache``, so ``f.cache.clear()`` empties it and ``len(f.cache)`` reports ...
farfarfun/farcache
src/farcache/box.py
.py
dc4e4eedbb09bde7
7
0
"""SQLite-backed function cache, built on :mod:`diskcache`.""" from __future__ import annotations import os from collections.abc import Callable, Iterable from hashlib import sha256 from typing import Any from diskcache import Cache from ._base import MISSING, CacheStore, FunctionCache from ._utils import namespace...
farfarfun/farcache
src/farcache/disk.py
.py
7d41cfdbec03e2f4
7
0
#!/usr/bin/env python3 """Two promises of install.py that failed silently once, so they get a check each. ⛔ WHY THESE TWO AND NOTHING ELSE HERE. Both were the same shape of bug: the script SAID the right thing and did the wrong thing. 1. `--check` was honoured by the statusline half only, so `--all --check` printed ...
Dino9021/dispatch-guard
test_install.py
.py
dd7ef68050b75369
7.5
0
"""AWS client wrapper for the AWS Infrastructure integration.""" from __future__ import annotations import logging import boto3 from botocore.config import Config _LOGGER = logging.getLogger(__name__) # Apply a connect and read timeout to all boto3 clients. # Without this, a hung or slow AWS endpoint can block a co...
ianpleasance/home-assistant-aws-infrastructure
custom_components/aws_infrastructure/aws_client.py
.py
b80a77f21df7cc36
7
0
"""Config flow for AWS Infrastructure integration.""" from __future__ import annotations import json import logging from typing import Any import voluptuous as vol from homeassistant import config_entries from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from .const import...
ianpleasance/home-assistant-aws-infrastructure
custom_components/aws_infrastructure/config_flow.py
.py
22abcc694222cfa4
7
0
import logging from datetime import timedelta from django.db.models import Count, OuterRef, Subquery from django.utils import timezone from rest_framework import generics, permissions, serializers from rest_framework.response import Response from rest_framework.views import APIView from drf_spectacular.utils import ex...
coneshare/coneshare
backend/analytics/views.py
.py
952a36892c43e463
7.78
35
from collections import defaultdict from datetime import timedelta import logging from zoneinfo import ZoneInfo from django.utils.dateparse import parse_datetime from django.utils import timezone from django.utils.translation import gettext as _, override as translation_override from django.core.mail import send_mail ...
coneshare/coneshare
backend/automations/emails.py
.py
1bb5e1e706fc5c0a
7.78
35
import logging import uuid from core.models import Organization, User from .models import AutomationDelivery, AutomationRule, AutomationDestination from .constants import EMAIL_COALESCE_DEBOUNCE_SECONDS logger = logging.getLogger(__name__) def _rule_matches_scope(rule, payload): share_link_id = payload.get('sh...
coneshare/coneshare
backend/automations/services.py
.py
78692ad66830b017
7.78
35
''' pip install flask export CONESHARE_SIGNING_SECRET='supersecret' # optional for local testing python coneshare_webhook_receiver.py ''' import hashlib import hmac import json import os from flask import Flask, request, jsonify app = Flask(__name__) # Set this to the same value as AutomationDestination.signing_s...
coneshare/coneshare
backend/automations/webhook_receiver.example.py
.py
9bf2dc1530b17d4b
7.78
35
import os import re def get_client_ip(request): """ Gets the real client IP address from a request, prioritizing a trusted X-Real-IP header set by a proxy. If not present, it falls back to X-Forwarded-For and then REMOTE_ADDR. """ real_ip = request.META.get('HTTP_X_REAL_IP') if real_ip: ...
coneshare/coneshare
backend/backend/utils.py
.py
dfc53ad8a86d8f15
7.78
35
import os import pytest from django.contrib.auth import get_user_model from rest_framework.test import APIClient from compile_po import BASE_LOCALE, make_mo from core.models import Organization User = get_user_model() DEFAULT_TEST_PASSWORD = "StrongPassword123!" @pytest.fixture(autouse=True, scope="session") def e...
coneshare/coneshare
backend/bdd/conftest.py
.py
cc047b51a3b0a02d
8.28
35
from pytest_bdd import given from rest_framework import status @given("I am an authenticated user", target_fixture="user_context") def user_context(user, api_client): """The user and api_client fixtures handle authentication.""" return {"user": user, "api_client": api_client} @given("my document list is emp...
coneshare/coneshare
backend/bdd/step_definitions/common_steps.py
.py
f69675d0c057a5cc
7.78
35
import pytest from unittest.mock import patch, MagicMock from django.core.files.uploadedfile import SimpleUploadedFile from pytest_bdd import parsers, scenario, then, when from rest_framework import status pytest_plugins = "bdd.step_definitions.common_steps" @pytest.mark.django_db @scenario('../features/document_upl...
coneshare/coneshare
backend/bdd/step_definitions/test_document_upload.py
.py
92c3cac713055dab
8.28
35
import pytest from unittest.mock import patch, MagicMock from django.core.files.uploadedfile import SimpleUploadedFile from pytest_bdd import parsers, scenario, given, when, then from rest_framework import status from documents.models import Document, DocumentVersion # Make common steps available pytest_plugins = "bd...
coneshare/coneshare
backend/bdd/step_definitions/test_document_version_upload.py
.py
f658ff52fc154784
8.28
35
import pytest from pytest_bdd import given, parsers, scenario, then, when from rest_framework import status from documents.models import Document from sharelinks.models import ShareLink, ViewSession, Viewer pytest_plugins = "bdd.step_definitions.common_steps" @pytest.mark.django_db @scenario('../features/share_link...
coneshare/coneshare
backend/bdd/step_definitions/test_share_link_analytics.py
.py
8140b7795332003d
8.28
35
import pytest from pytest_bdd import parsers, scenario, given, when, then from rest_framework import status from documents.models import Document from sharelinks.models import ShareLink # Make common steps available pytest_plugins = "bdd.step_definitions.common_steps" @pytest.mark.django_db @scenario( '../featu...
coneshare/coneshare
backend/bdd/step_definitions/test_share_link_view.py
.py
6e9a9cb105297ff7
8.28
35
import re from urllib.parse import urlparse, parse_qs import pytest from django.contrib.auth import get_user_model from django.core.cache import cache from django.urls import reverse from pytest_bdd import scenario, given, when, then, parsers from rest_framework import status from core.models import AppConfiguration ...
coneshare/coneshare
backend/bdd/step_definitions/test_user_authentication.py
.py
ce9f9445b21a8c66
8.28
35
import pytest from unittest.mock import patch from pytest_bdd import scenario, given, when, then, parsers from documents.models import Document from sharelinks.models import ShareLink, ViewSession, PageView pytest_plugins = "bdd.step_definitions.common_steps" @pytest.mark.django_db @scenario('../features/view_track...
coneshare/coneshare
backend/bdd/step_definitions/test_view_tracking.py
.py
940ce9304e709d66
8.28
35
"""CLI for Encrypted P2P Chat.""" import typer import base64 from p2pchat.crypto import IdentityKeys from p2pchat.protocol import ChatSession cli = typer.Typer(name="p2pchat", help="Educational Encrypted P2P Chat") @cli.command() def generate_identity(): """Generate a new identity key pair.""" ...
OpKnock/encrypted-p2p-chat
src/p2pchat/cli.py
.py
09ca71ef42a14101
7
0
"""Educational cryptographic primitives for P2P chat.""" import os import base64 import json from typing import Tuple, Dict, Optional from dataclasses import dataclass from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey from cryptography.hazmat.primitives.asymmetric...
OpKnock/encrypted-p2p-chat
src/p2pchat/crypto.py
.py
28cc641699791182
7
0
# config.py import logging from llama_index.core import Settings logger = logging.getLogger("campus_rag") Settings.llm = None Settings.embed_model = None Settings.chunk_size = 1024 Settings.chunk_overlap = 50 _llm_initialized = False _embed_initialized = False def init_llm() -> bool: """Initialize LLM. Returns...
allowan/USTC-107-let-ai-think-of-one
campus_rag/config.py
.py
4b85bc2945b8cbb0
7
0
#data_loader.py from llama_index.core import Document from llama_index.core.node_parser import SentenceSplitter import os def load_documents_from_files(directory: str) -> list: """读取目录下所有 .txt 文件,每个文件为一个 Document""" documents = [] if not os.path.isdir(directory): return documents for filename i...
allowan/USTC-107-let-ai-think-of-one
campus_rag/data_loader.py
.py
49c34c7006b85912
7
0
import logging from pathlib import Path from llama_index.core import Document _base = Path(__file__).resolve().parent from .index_manager import RAGSystem logger = logging.getLogger("campus_rag.query") _rag = None _public_retriever = None _user_retrievers: dict[str, object] = {} def _reset(): """重置所有缓存状态,下次调用...
allowan/USTC-107-let-ai-think-of-one
campus_rag/query.py
.py
3157d16554fc349f
7
0
import json import os from pathlib import Path from langchain.chat_models import init_chat_model _SETTINGS_PATH = Path(__file__).resolve().parent.parent / "settings.json" def read_json() -> dict: """读取 settings.json 中的 env 配置(文件不存在时返回空字典)。""" try: with open(_SETTINGS_PATH, encoding="utf-8") as f: ...
allowan/USTC-107-let-ai-think-of-one
model/config.py
.py
e55a76fc1b1ab37a
7
0
""" Auth service: topic CRUD. Delegates to campus_rag.auth. """ import logging logger = logging.getLogger("server") class AuthService: """Thin wrapper around campus_rag.auth for topic management.""" @staticmethod def list_topics(username: str) -> list: from campus_rag import list_topics ...
allowan/USTC-107-let-ai-think-of-one
server/services/auth_service.py
.py
0c8f31e7db0abb2f
7
0
""" RAG service: search, personal data CRUD. Delegates to campus_rag.query and campus_rag.index_manager. """ import logging from llama_index.core import Document logger = logging.getLogger("server") class RAGService: """Encapsulates RAG operations: search and personal data management.""" @staticmethod ...
allowan/USTC-107-let-ai-think-of-one
server/services/rag_service.py
.py
c1fb76ca2040c16f
7
0
"""Local structured schedule storage.""" from __future__ import annotations import json import sqlite3 from datetime import datetime, timezone from pathlib import Path DB_PATH = Path(__file__).resolve().parents[2] / "schedule.db" # USTC's standard period ranges. Imported files can provide exact times; these # rang...
allowan/USTC-107-let-ai-think-of-one
server/services/schedule_service.py
.py
381302af4cba4feb
7
0
""" Sync service: pulls public notices from sync_server, updates local ChromaDB. """ import json import logging from pathlib import Path import httpx logger = logging.getLogger("server") ROOT = Path(__file__).resolve().parent.parent.parent SYNC_STATE_PATH = ROOT / "data" / "sync_state.json" # Default sync_server U...
allowan/USTC-107-let-ai-think-of-one
server/services/sync_service.py
.py
9b15840dfeb16226
7
0
""" Database: document storage + change log for versioned sync. """ import os import sqlite3 import json from pathlib import Path from datetime import datetime ROOT = Path(__file__).resolve().parent DB_PATH = ROOT / "data" / "sync_server.db" def _get_conn() -> sqlite3.Connection: DB_PATH.parent.mkdir(parents=Tr...
allowan/USTC-107-let-ai-think-of-one
sync_server/database.py
.py
cc40ceeb57a7fc7e
7
0
""" Sync Server — 公共通知数据库同步服务端。 纯文档存储 + 版本管理,不依赖 LLM / ChromaDB / Ollama。 启动: python main.py (默认端口 8001) """ import sys from pathlib import Path # Allow running as python main.py from within sync_server/ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import logging from fastapi import FastAPI fro...
allowan/USTC-107-let-ai-think-of-one
sync_server/main.py
.py
d5992812d646ae26
7
0
""" Refresh the free-proxy-list mirror from the ProxyScrape v4 public API. Writes: proxies/all/data.{txt,json,csv} proxies/protocols/{http,https,socks4,socks5}/data.{txt,json,csv} proxies/countries/{ISO}/data.{txt,json,csv} (ISO-3166 alpha-2, lowercased) proxies/countries/{ISO}/{protocol}/data....
ProxyScrape/free-proxy-list
scripts/update.py
.py
84326d2fc5f52b51
8
120
"""Command-line interface for ofplang.schedule. Thin presentation layer over the library. Subcommands: ofp-schedule validate [--kind ...] [--format ...] <file>... ofp-schedule schedule <workflow> --env <env> [--document <doc>] [-o <file>] [--format yaml|json] ofp-schedule visualize <plan> [--view device|w...
ofplang/schedule
ofplang/schedule/cli.py
.py
f23a1dc20189a0ed
7
0
"""Diagnostics and validation result. Shared by both schema validators. A diagnostic pins a stable error code (SPECIFICATIONS.md §10) to a source position; `severity` distinguishes hard errors from warnings. Warnings never make a document invalid (§9), so `ValidationResult.ok` looks only at errors. """ from __future_...
ofplang/schedule
ofplang/schedule/core/diagnostics.py
.py
0205c42512428e53
7
0