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 |
|---|---|---|---|---|---|---|
"""高德充电 Provider —— 用高德 POI 搜**真实**充电站 + 真实路线距离/时长,替代 mock 假数据。
复用导航 agent 的 `AmapPOIProvider`(monorepo:容器 `COPY agents` 已含 navigation 代码);
凭证经 env(AMAP_KEY) 注入,绝不进代码/日志。调用失败抛 ProviderError,Agent 据此降级 mock。
注:高德基础 POI 不返回充电桩实时空闲枪数/电价,故只给真实**站点名/地址/距离/评分**,
不编造空闲数(available/total 置 0,由 Agent 话术按"是否已知"自适应展示)。
"""
from ... | SuperdeMan/cockpit-agent | agents/charging_planner/src/providers/amap.py | .py | 0c722296ef7d6bbf | 7.56 | 12 |
"""充电 Provider 接口定义。"""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
@dataclass
class GeoPoint:
"""地理位置。"""
address: str = ""
lat: float = 0.0
lng: float = 0.0
@dataclass
class ChargingStation:
"""充电站信息。"""
id: str = ""
n... | SuperdeMan/cockpit-agent | agents/charging_planner/src/providers/base.py | .py | 5fbeb6acf6f71fff | 7.56 | 12 |
"""充电 Provider Mock 实现。"""
from __future__ import annotations
import random
from .base import ChargingProvider, ChargingStation, ChargingPlan, GeoPoint
class MockChargingProvider(ChargingProvider):
"""Mock 充电 Provider,生成模拟数据。"""
_OPERATORS = ["特来电", "星星充电", "国家电网", "小桔充电"]
_CHARGER_TYPES = [["快充"], ["慢充"... | SuperdeMan/cockpit-agent | agents/charging_planner/src/providers/mock.py | .py | a3ed3567815971f7 | 7.56 | 12 |
"""充电 Provider 工厂契约:无 key mock;key 即意图,构造失败 fail-fast(治理 P0)。"""
import pytest
from agents._sdk.provenance import ProviderConfigError
from agents.charging_planner.src.providers import build_charging_provider
from agents.charging_planner.src.providers.mock import MockChargingProvider
class _Boom:
def __init__(sel... | SuperdeMan/cockpit-agent | agents/charging_planner/tests/test_provider_factory.py | .py | 62622fb17b65f64f | 8.06 | 12 |
"""充电编织纯函数单测。"""
from agents.charging_planner.src.weave import weave_charging_targets
def _route(distance_km: float, step_km: float = 10.0) -> list[dict]:
"""构造一条沿东向的等距路线点(cum_km 递增)。"""
pts, cum = [], 0.0
lat, lng = 30.0, 120.0
while cum <= distance_km:
pts.append({"lat": lat, "lng": lng + cu... | SuperdeMan/cockpit-agent | agents/charging_planner/tests/test_weave.py | .py | 0c2c96bd0bb34d50 | 8.06 | 12 |
"""记忆驱动的回答要说出出处——**确定性后处理,零 LLM**(Q5 残余,2026-08-16)。
## 病不是幻觉,是「真记忆没有出处」
QA 轮把「您女儿在南山实验小学上学」记成幻觉(I-044/I-028)。psql 取证推翻了那个
定性——**库里逐字有这条记忆**。真正的病是:真记忆在用户眼里与幻觉不可区分。
清洗后复跑把它从「方差」改硬成 **0/3 稳定红**。
## 直接成因是系统自己下的指令
`_memory_context` 注入 prompt 时写着「…**勿暴露这是系统记忆**」
——**不是模型忘了说出处,是我们让它别说**。
## 为什么是确定性后处理而不是改提示词
卡上写的是「要的是机... | SuperdeMan/cockpit-agent | agents/chitchat/src/mem_source.py | .py | 4613b7779d867e4d | 7.56 | 12 |
"""Location resolution and exact-radius calculations for theatre searches."""
import re
import threading
from functools import lru_cache
import requests
from geopy.distance import geodesic
USER_AGENT = "MovieSeatFinder/1.0 (location lookup)"
_LOCAL = threading.local()
class ZipNotFoundError(ValueError):
"""The... | ivan-grebe/movieseatfinder | src/backend/location.py | .py | 7e07d0c75a4034d3 | 7.52 | 10 |
#!/usr/bin/env python3
"""Build the frozen eval query set from the robotics downstream task map.
The quality standard forbids inventing task names: the task layer of the
narration hierarchy has one controlled vocabulary, and it is the robotics
downstream task map. So the eval queries are not written — they are *drawn*... | Memories-ai-labs/Internet2EgoExo | eval/build_query_set.py | .py | fbd8a16d7768922d | 7.6 | 15 |
"""Clarification flow management for ambiguous queries per PRD."""
from typing import Any
from video_searching_agent.models.query import ParsedQuery, QueryType, TimeFrame
class ClarificationManager:
"""Manages clarification flow when queries are ambiguous.
Per PRD, clarification is triggered when:
- In... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/agent/clarification.py | .py | 7040c1de0b6a0d46 | 7.6 | 15 |
"""Frames from an indexed video, so an agent can look instead of inferring.
Every judgement in this pipeline used to be read off caption *wording*: whether
hands are in frame, whether the camera is worn, whether a span is one action.
Caption text is a real signal and it is also a lossy one, and the failures were
the k... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/agent/eyes.py | .py | 400132ad673957b7 | 7.6 | 15 |
"""Shared ReAct plumbing for the specialized agents.
Every agent in this package works the same way: it thinks, it calls one
Datalake tool, it records what came back, and it repeats. Keeping that
machinery here means the cleaning agent and the annotation agent produce the
*same* auditable trace shape, so a label can a... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/agent/react.py | .py | 81922f9ab2fa6c46 | 7.6 | 15 |
"""A small ReAct runtime: think, act, observe, until there is an answer.
The agents in this repo started as single-shot calls — build a prompt, read one
JSON answer back — and that shape has a specific weakness. It forces the caller
to decide in advance what evidence the model gets. If a span's captions are
ambiguous,... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/agent/react_loop.py | .py | 9bcc8ce60122eed3 | 7.6 | 15 |
"""Deterministic tool-call policy helpers for the video searching agent."""
from __future__ import annotations
from typing import Any
from video_searching_agent.models.query import MetricType, ParsedQuery, QueryType
# Tools that index or read one video's own content. Indexing is billed per
# minute of video, so the... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/agent/tool_policy.py | .py | 6d1b2ccf2bdf5213 | 7.6 | 15 |
"""Pick the model provider once, so nothing downstream has to care.
Two providers are supported and they present the same interface:
* **Gemini** (`GOOGLE_API_KEY`) — the original path, using the google-genai SDK.
* **OpenRouter** (`OPENROUTER_API_KEY`) — one key in front of hundreds of
models, including multimodal... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/api/llm.py | .py | 71c6c927376641e1 | 7.6 | 15 |
"""Pricing configuration for API and tool costs.
This module defines the cost rates for:
- Gemini API token pricing
- External tool/API costs (Apify, Exa, YouTube quota)
"""
from pydantic import BaseModel, Field
class GeminiPricing(BaseModel):
"""Pricing for Gemini API per 1M tokens."""
# Gemini 3 Flash Pr... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/config/pricing.py | .py | 9850d43f04dd6df2 | 7.6 | 15 |
"""Application settings and configuration."""
from functools import lru_cache
from typing import Any
from pydantic import Field, model_validator
try:
from pydantic_settings import BaseSettings
except ImportError:
from pydantic import BaseSettings # type: ignore
class Settings(BaseSettings):
"""Applica... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/config/settings.py | .py | 5a74360fb35fa9e4 | 7.6 | 15 |
"""What an hour of collected footage actually costs.
A collection run spends money in four places:
1. **Discovery** — Gemini tokens plus per-call search/scrape fees while finding
candidates. Already measured per run by `UsageMetrics`, so it is passed in
rather than estimated.
2. **Download** — pulling the files... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/curation/cost.py | .py | 7b49f4f6a7c9886c | 7.6 | 15 |
"""Ask the raw video's own index, not the words written about it.
Every judgement in the cleaning, clipping and annotating path has read *caption
text*: a clip-level description, several seconds wide, written about the footage.
`frame_check` says so in its own docstring — "a text judgement about a visual
description".... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/curation/embedding_search.py | .py | b8129e06f9cdd505 | 7.6 | 15 |
"""Turn anchors into footage somebody can actually train on.
The dataset is a set of time anchors on whole videos, never cut files, and that
is deliberate — `G2-TREE-5`. Cutting loses the context either side of a boundary,
and a boundary that turns out to be wrong cannot be moved once the file exists.
But an anchor i... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/curation/export.py | .py | c3632b1843fd83f8 | 7.6 | 15 |
"""Turn a run's candidate references into a dataset manifest.
Shared by the streaming and non-streaming agents so both produce the same
deliverable: clips annotated with viewpoint, duration and licence, ranked by
usability, with the totals that say whether the collection goal was met.
"""
from __future__ import annot... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/curation/manifest.py | .py | dddb5d405e2d10f7 | 7.6 | 15 |
"""Search the words uploaders use, not the words the requester used.
A training-data request arrives as a task: *someone doing the laundry, loading a
machine and folding clothes*. Sent to YouTube verbatim, that returns exactly what
those words select for — beginner guides, appliance reviews, a presenter talking
to a t... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/curation/query_rewrite.py | .py | fa6ad052148c5fcb | 7.6 | 15 |
"""Score anchors against what was actually asked for.
Anchor discovery is exhaustive by design: the cleaning agent walks every caption
segment of a video and marks every run where work is happening. That is the
right way to build a *complete* set of anchors, and it is the wrong way to
answer "which of these is what I ... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/curation/relevance.py | .py | abafe2bc74b135ba | 7.6 | 15 |
"""Camera-viewpoint classification for training-data collection.
Egocentric footage is shot from the actor's own head/body — the camera moves
with them and their hands enter frame. Exocentric footage observes the actor
from outside — fixed cameras, tripods, multi-view rigs, spectator angles.
Classification is determi... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/curation/viewpoint.py | .py | 2f871ad41f47008d | 7.6 | 15 |
"""Render an eval run as something a person will actually read.
The JSON the metrics module produces is the record; this is the page somebody
looks at. Two rules shape it:
* **Every ratio is printed next to its denominator.** "44% accepted" out of nine
clips and out of nine hundred are different claims, and a perce... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/evaluation/scorecard.py | .py | 9990abe5172bed3b | 7.6 | 15 |
"""Cost and usage tracking models."""
from pydantic import BaseModel, Field
class TokenUsage(BaseModel):
"""Token usage for a Gemini API call or aggregated session."""
input_tokens: int = Field(0, description="Number of input/prompt tokens")
output_tokens: int = Field(0, description="Number of output/co... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/models/cost.py | .py | c09b7959f4807595 | 7.6 | 15 |
"""Dataset manifest models — the deliverable of a collection run.
A run's output is not prose: it is a list of clips with the metadata a
training pipeline needs to fetch and filter them, plus the totals that say
whether the collection goal was met.
"""
from __future__ import annotations
from pydantic import BaseMode... | Memories-ai-labs/Internet2EgoExo | src/video_searching_agent/models/dataset.py | .py | 73da9973d29d467e | 7.6 | 15 |
"""Optional API key authentication for the pandoc service.
Authentication is disabled by default. It activates when the ``API_KEY``
environment variable holds at least one non-empty key. Several keys can be
configured as a comma-separated list, which allows key rotation without
downtime.
Clients send the key in one o... | SchweizerischeBundesbahnen/pandoc-service | app/auth.py | .py | dff6fddd029773d3 | 7.42 | 6 |
"""Rewrite direct run-level color formatting in a DOCX as character styles.
Pandoc's DOCX reader drops direct character formatting (``<w:color>``,
``<w:shd>``, ``<w:highlight>``) before producing the AST, so no Lua filter
can recover those properties for the LaTeX/PDF writer. This preprocessor
runs *before* pandoc rea... | SchweizerischeBundesbahnen/pandoc-service | app/docx_color_pre_process.py | .py | ff0d892692f32ad9 | 7.42 | 6 |
"""Single-pass docx→latex preprocessing.
For LaTeX/PDF targets five independent rewrites run on the source DOCX before
pandoc reads it: colour/size runs (:mod:`app.docx_color_pre_process`), paragraph
alignment/indent (:mod:`app.docx_paragraph_pre_process`), list-level tagging
(:mod:`app.docx_list_level_pre_process`), ... | SchweizerischeBundesbahnen/pandoc-service | app/docx_latex_pre_process.py | .py | e41e5219276e310c | 7.42 | 6 |
"""Tag list-paragraph indent levels in a DOCX so they survive into LaTeX/PDF.
Polarion allows malformed lists where a deeper level is nested directly inside
a shallower one with no intermediate item (e.g. a level-3 ``<ol>`` straight
inside a level-1 list). The DOCX is fine — each paragraph carries its absolute
``<w:nu... | SchweizerischeBundesbahnen/pandoc-service | app/docx_list_level_pre_process.py | .py | 84936fb75e57d9ee | 7.42 | 6 |
r"""Decode math color markers into real OMML color (companion to html_math_color_pre_process).
``html_math_color_pre_process`` rewrites ``\color``/``\textcolor`` inside math scripts
into ``\text{@@PMC:RRGGBB@@}...\text{@@PMCEND@@}`` markers before pandoc runs,
because ``texmath`` cannot carry color through to OMML. Pa... | SchweizerischeBundesbahnen/pandoc-service | app/docx_math_color_post_process.py | .py | b6de0deaa8616d5c | 7.42 | 6 |
r"""Preserve OMML math-run color across the DOCX -> LaTeX/PDF path.
Pandoc reads Office math (``<m:oMath>``) through the ``texmath`` library
(``readOMML`` -> ``[Exp]`` -> ``writeTeX``). ``texmath``'s expression AST has no
color constructor and its OMML reader ignores ``<w:color>`` on math runs
entirely, so a colored e... | SchweizerischeBundesbahnen/pandoc-service | app/docx_math_color_pre_process.py | .py | 13f2971f694e6e9c | 7.42 | 6 |
"""Shared OOXML/zip plumbing for the DOCX preprocessors.
``docx_color_pre_process``, ``docx_paragraph_pre_process`` and
``docx_list_level_pre_process`` all rewrite body parts of a DOCX package before
pandoc reads it. This module factors out the boilerplate they share: the
WordprocessingML namespace, the canonical-pref... | SchweizerischeBundesbahnen/pandoc-service | app/docx_ooxml.py | .py | 78418845de0f51d6 | 7.42 | 6 |
"""Rewrite paragraph alignment / indentation in a DOCX as paragraph styles.
Pandoc's DOCX reader drops paragraph alignment (``<w:jc>``) entirely and
coerces left indentation (``<w:ind w:left>``) into a single ``BlockQuote``
(merging distinct indent levels) before producing the AST, so no Lua filter
can recover those p... | SchweizerischeBundesbahnen/pandoc-service | app/docx_paragraph_pre_process.py | .py | 3dcedca584ab9f02 | 7.42 | 6 |
"""Rewrite table properties in a DOCX so tables survive into LaTeX/PDF.
Pandoc's DOCX reader has three table-related problems this preprocessor fixes:
1. **Missing grid-column widths**: ``<w:gridCol/>`` elements without a
``w:w`` attribute cause pandoc to produce an empty ``ColSpec`` list,
which in turn drops e... | SchweizerischeBundesbahnen/pandoc-service | app/docx_table_pre_process.py | .py | 7cf65febac37cbab | 7.42 | 6 |
"""Give un-sized ``<img>`` elements an explicit pixel width/height at 96 dpi.
Pandoc's DOCX writer sizes an image with no explicit ``width``/``height`` from
the image's pixel dimensions divided by its embedded density (``pHYs`` for PNG,
JFIF for JPEG). Screenshots and Polarion attachments usually carry *no* density,
s... | SchweizerischeBundesbahnen/pandoc-service | app/html_image_pre_process.py | .py | 3f08c03ebbfa5923 | 7.42 | 6 |
"""Wrap orphan ``<ol>`` / ``<ul>`` nested directly inside another list.
Some HTML emitters (notably Polarion) produce non-standard list markup where
an ``<ol>`` or ``<ul>`` appears as a *direct* child of another list, with no
wrapping ``<li>``. Browsers and CSS-counter renderers (e.g. WeasyPrint when
producing PDF) ha... | SchweizerischeBundesbahnen/pandoc-service | app/html_lists_pre_process.py | .py | dd687aafaa0260ca | 7.42 | 6 |
r"""Preserve LaTeX math color (``\color`` / ``\textcolor``) across pandoc.
Pandoc converts the LaTeX inside ``<script type="math/tex">`` to native Word
equations (OMML) through its ``texmath`` library. ``texmath`` discards ``\color``
(it parses the formula but drops the color), cannot parse ``\textcolor`` at all
(the ... | SchweizerischeBundesbahnen/pandoc-service | app/html_math_color_pre_process.py | .py | 3167669aee80eda3 | 7.42 | 6 |
"""Preserve paragraph-level ``<p style="...">`` formatting for DOCX conversion.
Pandoc's HTML reader drops the ``style`` attribute from ``<p>`` entirely, so
any paragraph-level CSS applied inline is lost before any Lua filter can read
it. This preprocessor finds each such ``<p>``, extracts the formatting we
support — ... | SchweizerischeBundesbahnen/pandoc-service | app/html_paragraph_pre_process.py | .py | c9a1d418b45e3d23 | 7.42 | 6 |
"""Extract table width and alignment from HTML source for DOCX post-processing.
Pandoc's HTML reader keeps the ``<table style="...">`` declaration in the
Table node's ``Attr`` key-value list, but the DOCX writer discards it: every
table comes out with ``<w:tblW w:type="auto"/>`` and no alignment. On top of
that, :mod:... | SchweizerischeBundesbahnen/pandoc-service | app/html_table_layout.py | .py | 5c31dad6b0eeec32 | 7.42 | 6 |
"""
Dedicated metrics server for Prometheus metrics endpoint.
This module provides a separate FastAPI application serving only the /metrics
endpoint on a dedicated port for security purposes. This allows network-level
isolation between the main application API and the metrics endpoint.
"""
from __future__ import anno... | SchweizerischeBundesbahnen/pandoc-service | app/metrics_server.py | .py | d0c3497269be6b84 | 7.42 | 6 |
"""
Internal metrics tracking for pandoc-service.
This module provides a PandocMetrics class that tracks conversion statistics
and performance metrics internally. These metrics are then exposed via
Prometheus through the prometheus_metrics module.
"""
from __future__ import annotations
import os
import threading
imp... | SchweizerischeBundesbahnen/pandoc-service | app/pandoc_metrics.py | .py | 3c6739595a788914 | 7.42 | 6 |
import argparse
import logging
import os
from datetime import UTC, datetime
from pathlib import Path
from app import pandoc_controller
logger = logging.getLogger(__name__)
def setup_logging() -> Path:
"""
Configure logging for the Pandoc service with both file and console output.
The function:
- Se... | SchweizerischeBundesbahnen/pandoc-service | app/pandoc_service_application.py | .py | f0b6955d74f20b6e | 7.42 | 6 |
import logging
from io import BytesIO
from typing import TypedDict
from zipfile import ZIP_DEFLATED, ZipFile
from defusedxml import ElementTree
# Standard slide sizes (width x height in inches)
class Dimensions(TypedDict):
width: float
height: float
SLIDE_SIZES: dict[str, Dimensions] = {
"16:9": {"widt... | SchweizerischeBundesbahnen/pandoc-service | app/pptx_post_process.py | .py | 257850b7dafc1888 | 7.42 | 6 |
"""
Prometheus metrics collectors for pandoc-service.
This module defines custom Prometheus metrics that expose conversion
and application-level metrics for monitoring and observability.
Note: Counters are incremented when events occur (not synced from external state).
Gauges are updated periodically to reflect... | SchweizerischeBundesbahnen/pandoc-service | app/prometheus_metrics.py | .py | 7cadbf11a7990538 | 7.42 | 6 |
"""
SVG processing utilities.
Features:
- Convert SVG <svg> to <img src="data:image/svg+xml;base64,...">
- Replace base64 SVG <img> with base64 PNG using Chromium via CDP (Chrome DevTools Protocol)
- Handle SVG dimensions, including vw/vh/% via viewBox
This is a port of the SvgProcessor from weasyprint-service, kept ... | SchweizerischeBundesbahnen/pandoc-service | app/svg_processor.py | .py | 32facb05628ae9bb | 7.42 | 6 |
"""Optional TLS for the servers of this service.
Both servers speak plain HTTP by default, which is what a deployment behind a
reverse proxy or an ingress expects. Where the service is reached directly, each
server can serve TLS instead.
The API server reads ``TLS_*`` and the metrics server reads ``METRICS_TLS_*``.
T... | SchweizerischeBundesbahnen/pandoc-service | app/tls.py | .py | cd58d75a33e7d676 | 7.42 | 6 |
"""Shared pytest fixtures for all tests."""
import logging
import os
import subprocess
from unittest.mock import patch
import pytest
import requests
from tests.test_container import (
TEST_CONTAINER_NAME,
TEST_IMAGE_FULL,
TestParameters,
cleanup_docker_resources,
wait_for_container_ready,
)
logg... | SchweizerischeBundesbahnen/pandoc-service | tests/conftest.py | .py | 619a32958ac4317e | 7.92 | 6 |
"""End-to-end integration tests for the caption pipeline with a localized
caption sequence.
Polarion caption sequences are arbitrary names — a German instance emits
``<span data-sequence="Tabelle" ...>`` and the paragraph label reads
"Tabelle 1 ...", which does NOT start with "Table". The old text-prefix
heuristic sil... | SchweizerischeBundesbahnen/pandoc-service | tests/test_caption_references_integration.py | .py | 792b87ddf1d9aa98 | 7.92 | 6 |
"""Unit tests for ``app.docx_latex_pre_process`` (the single-pass orchestrator).
It must produce the same package as chaining the three standalone docx→latex
preprocessors, but in one unzip/re-zip so an image-heavy document's media is
recompressed once rather than three times.
"""
from __future__ import annotations
... | SchweizerischeBundesbahnen/pandoc-service | tests/test_docx_latex_preprocess.py | .py | fb77b49ca2103fab | 7.92 | 6 |
"""Integration tests for ``filters/docx_lists_to_latex.lua``.
Runs the real ``pandoc`` binary inside the pandoc-service container with the
filter on a native AST that mimics what the docx reader produces for a Polarion
"irregular" list once ``docx_list_level_pre_process`` has tagged each item with its
true ``<w:ilvl>`... | SchweizerischeBundesbahnen/pandoc-service | tests/test_docx_lists_to_latex_filter.py | .py | 5b5952178694d2cb | 7.92 | 6 |
"""Unit tests for ``app.docx_math_color_post_process.apply_math_colors``.
These verify the *decode* half of the math-color shim: given a ``Document`` whose OMML
carries ``@@PMC:RRGGBB@@`` / ``@@PMCEND@@`` marker runs (as pandoc emits them from the
``\\text{}`` markers ``html_math_color_pre_process`` injects), ``apply_... | SchweizerischeBundesbahnen/pandoc-service | tests/test_docx_math_color_postprocess.py | .py | b9d978d6d564cc73 | 7.92 | 6 |
"""Unit tests for ``app.docx_math_color_pre_process``.
These verify the *encode* half of the DOCX -> LaTeX/PDF math-color shim: given a DOCX
whose OMML carries direct ``<w:color>`` on math runs (as ``docx_math_color_post_process``
writes on the HTML -> DOCX path, and as Word renders), the preprocessor wraps each
color... | SchweizerischeBundesbahnen/pandoc-service | tests/test_docx_math_color_preprocess.py | .py | ca9444f1acc56702 | 7.92 | 6 |
"""Integration tests for ``filters/docx_paragraphs_to_latex.lua``.
Runs pandoc inside the pandoc-service container with the filter loaded and
asserts the LaTeX output for a ``Div`` carrying the synthetic
``custom-style="PandocPara__..."`` attribute the ``docx_paragraph_pre_process``
preprocessor produces. The AST shap... | SchweizerischeBundesbahnen/pandoc-service | tests/test_docx_paragraphs_to_latex_filter.py | .py | 7e96e3f4ee5446c5 | 7.92 | 6 |
"""End-to-end test for DOCX table width/alignment surviving into LaTeX.
Builds a real DOCX with a table carrying ``<w:tblW>`` / ``<w:jc>`` (what the
HTML->DOCX post-processing writes), runs it through the docx->latex
preprocessing + ``filters/docx_tables_to_latex.lua``, and checks that:
* pandoc's DOCX reader would n... | SchweizerischeBundesbahnen/pandoc-service | tests/test_docx_table_layout_to_latex.py | .py | b90ee190dfd83287 | 7.92 | 6 |
"""Integration tests for ``filters/docx_text_decorations.lua``.
Runs the real ``pandoc`` binary inside the pandoc-service container on a
native AST (what the docx reader produces) and checks how Underline/Strikeout
are rendered to LaTeX. Pandoc-only — no DOCX fixture or tectonic needed.
The contract: plain-text under... | SchweizerischeBundesbahnen/pandoc-service | tests/test_docx_text_decorations_filter.py | .py | 7791c1dbdefa7509 | 7.92 | 6 |
"""Tests for the container healthcheck script."""
from __future__ import annotations
import subprocess
from pathlib import Path
import pytest
HEALTHCHECK = Path(__file__).parent.parent / "healthcheck.sh"
FAKE_CURL = """#!/bin/sh
printf '%s\\n' "$@" > "${CURL_ARGS_FILE}"
"""
@pytest.fixture
def run_healthcheck(tm... | SchweizerischeBundesbahnen/pandoc-service | tests/test_healthcheck.py | .py | 18e079edbbfe0797 | 7.92 | 6 |
import subprocess
import sumolib
import os
import sys
from typing import Optional, List
from utils.sumo import build_sumo_diagnostics, find_sumo_tool_script
from utils.output import truncate_text
from utils.timeout import subprocess_run_with_timeout
def netconvert(osm_file: str, output_file: str, options: Optional[Li... | HypaSMarty/SUMO-MCP-Server | src/mcp_tools/network.py | .py | 02e8c030b68ad1cc | 7.48 | 8 |
import subprocess
import sumolib
import os
import sys
from typing import Optional, List
from utils.sumo import build_sumo_diagnostics, find_sumo_tool_script
from utils.output import truncate_text
from utils.timeout import subprocess_run_with_timeout
def random_trips(net_file: str, output_file: str, end_time: int = 36... | HypaSMarty/SUMO-MCP-Server | src/mcp_tools/route.py | .py | a77916e298d5a193 | 7.48 | 8 |
import os
import logging
import subprocess
import traci
from utils.sumo import build_sumo_diagnostics, find_sumo_binary
from utils.timeout import run_with_adaptive_timeout
from utils.traci import traci_close_best_effort
logger = logging.getLogger(__name__)
def run_simple_simulation(config_path: str, steps: int = 100... | HypaSMarty/SUMO-MCP-Server | src/mcp_tools/simulation.py | .py | 580696d7772c765a | 7.48 | 8 |
import traci
from typing import List, Tuple
from utils.connection import connection_manager
def get_vehicles() -> List[str]:
"""Get the list of all active vehicle IDs."""
if not connection_manager.is_connected():
return []
return list(traci.vehicle.getIDList())
def get_vehicle_speed(vehicle_id: st... | HypaSMarty/SUMO-MCP-Server | src/mcp_tools/vehicle.py | .py | ee0c9a60852f7619 | 7.48 | 8 |
import logging
import subprocess
from typing import Any, Dict, Optional
from mcp.server.fastmcp import FastMCP
from utils.traci import ensure_traci_start_stdout_suppressed
from mcp_tools.simulation import run_simple_simulation
from mcp_tools.network import netconvert, netgenerate, osm_get
from mcp_tools.route import ... | HypaSMarty/SUMO-MCP-Server | src/server.py | .py | 89dac250c1f13364 | 7.48 | 8 |
import logging
import os
import subprocess
import threading
from typing import Callable, Optional, TypeVar
import traci
from utils.sumo import find_sumo_binary
logger = logging.getLogger(__name__)
DEFAULT_TRACI_TIMEOUT_S = float(os.environ.get("SUMO_MCP_TRACI_TIMEOUT_S", "10"))
T = TypeVar("T")
def _run_with_tim... | HypaSMarty/SUMO-MCP-Server | src/utils/connection.py | .py | b2ed66fb74a68521 | 7.48 | 8 |
import glob
import logging
import os
import shutil
import sys
from pathlib import Path
from typing import Optional
import sumolib
logger = logging.getLogger(__name__)
def find_sumo_binary(name: str) -> Optional[str]:
"""
Find a SUMO binary by name.
Resolution order:
1) `sumolib.checkBinary()` (resp... | HypaSMarty/SUMO-MCP-Server | src/utils/sumo.py | .py | 9ef89fd35906adfb | 7.48 | 8 |
"""
智能超时控制器
提供三层超时策略:
1. 静态超时 - 用于快速、可预测的操作
2. 参数自适应超时 - 根据输入参数估算合理超时
3. 心跳+指数退避 - 用于长时间运行的操作(如 RL 训练)
"""
import os
import logging
import inspect
import subprocess
import sys
import threading
import time
from dataclasses import dataclass
from typing import Any, Callable, Optional, TypeVar
logger = logging.getLogger... | HypaSMarty/SUMO-MCP-Server | src/utils/timeout.py | .py | 4b654ce02acb8395 | 7.48 | 8 |
from __future__ import annotations
import inspect
import subprocess
import threading
from typing import Any, Callable, Optional
def ensure_traci_start_stdout_suppressed() -> None:
"""
Ensure `traci.start()` defaults to `stdout=subprocess.DEVNULL`.
Why:
MCP uses JSON-RPC over stdio; any SUMO/TraCI ... | HypaSMarty/SUMO-MCP-Server | src/utils/traci.py | .py | 7a97a30f19258c70 | 7.48 | 8 |
import os
import shutil
import warnings
import logging
from filecmp import cmp
from typing import List, Optional
from mcp_tools.simulation import run_simple_simulation
from mcp_tools.signal import tls_cycle_adaptation, tls_coordinator
from mcp_tools.analysis import analyze_fcd
logger = logging.getLogger(__name__)
d... | HypaSMarty/SUMO-MCP-Server | src/workflows/signal_opt.py | .py | 4725c6b04f4c6c05 | 7.48 | 8 |
import os
from pymilvus import Collection, connections, utility
def get_collection_info(collection_name, alias):
"""Safely gets a collection object and its number of entities."""
try:
collection = Collection(collection_name, using=alias)
collection.load()
return collection, collection... | wilson0523/Yuxi-Know | scripts/rename_milvus_collections.py | .py | 48e6d396999f8995 | 7.45 | 7 |
"""访问日志中间件 - 记录请求处理时间"""
import time
import logging
from collections.abc import Callable
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
# 创建专用的访问日志记录器
access_logger = logging.getLogger("access_logger")
# 设置访问日志记录器
if not access_logger.handlers:
handler = logging.S... | wilson0523/Yuxi-Know | server/utils/access_log_middleware.py | .py | f254d9e3a73d3161 | 7.45 | 7 |
import hashlib
import os
from datetime import timedelta
from typing import Any
import jwt
from src.utils.datetime_utils import utc_now
# JWT配置
JWT_SECRET_KEY = os.environ.get("JWT_SECRET_KEY", "yuxi_know_secure_key")
JWT_ALGORITHM = "HS256"
JWT_EXPIRATION = 7 * 24 * 60 * 60 # 7天过期
class AuthUtils:
"""认证工具类"""... | wilson0523/Yuxi-Know | server/utils/auth_utils.py | .py | f9ca27722693d091 | 7.45 | 7 |
"""通用工具函数"""
import logging
from fastapi import Request
from sqlalchemy.orm import Session
from src.storage.db.models import OperationLog, User
def setup_logging():
"""配置应用程序日志格式"""
# 配置日志格式
logging.basicConfig(
level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s", datefmt="%Y-%m... | wilson0523/Yuxi-Know | server/utils/common_utils.py | .py | 3a5c3522fe43269b | 7.45 | 7 |
import asyncio
import importlib
import inspect
from pathlib import Path
from server.utils.singleton import SingletonMeta
from src.agents.common import BaseAgent
from src.utils import logger
class AgentManager(metaclass=SingletonMeta):
def __init__(self):
self._classes = {}
self._instances = {} #... | wilson0523/Yuxi-Know | src/agents/__init__.py | .py | 89b9c9665d7438cb | 7.45 | 7 |
import os
import uuid
from typing import Any
import requests
from langchain.tools import tool
from src.agents.common import get_buildin_tools
from src.agents.common.subagents import calc_agent_tool
from src.storage.minio import aupload_file_to_minio
from src.utils import logger
@tool
async def text_to_img_demo(text... | wilson0523/Yuxi-Know | src/agents/chatbot/tools.py | .py | ebaa8acecd701c20 | 7.45 | 7 |
from __future__ import annotations
import importlib.util
import os
import tomllib as tomli
from abc import abstractmethod
from pathlib import Path
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver, aiosqlite
from langgraph.graph.state import CompiledSta... | wilson0523/Yuxi-Know | src/agents/common/base.py | .py | e278bdea0dae478a | 7.45 | 7 |
"""Define the configurable parameters for the agent."""
import os
import uuid
from dataclasses import MISSING, dataclass, field, fields
from pathlib import Path
from typing import Annotated, get_args, get_origin
import yaml
from src import config as sys_config
from src.utils import logger
@dataclass(kw_only=True)
... | wilson0523/Yuxi-Know | src/agents/common/context.py | .py | f66822b9bbb91e44 | 7.45 | 7 |
"""MCP Client setup and management for LangGraph ReAct Agent."""
import traceback
from collections.abc import Callable
from typing import Any, cast
from langchain_mcp_adapters.client import MultiServerMCPClient
from src.utils import logger
# Global MCP tools cache
_mcp_tools_cache: dict[str, list[Callable[..., Any]... | wilson0523/Yuxi-Know | src/agents/common/mcp.py | .py | 688e8ae879f21b89 | 7.45 | 7 |
"""附件注入中间件 - 使用 LangChain 标准中间件实现"""
from __future__ import annotations
from collections.abc import Callable, Sequence
from typing import NotRequired
from langchain.agents import AgentState
from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse
from src.utils import logger
class Atta... | wilson0523/Yuxi-Know | src/agents/common/middlewares/attachment_middleware.py | .py | 61698246f884a767 | 7.45 | 7 |
"""通用的 Context 相关中间件"""
from collections.abc import Callable
from langchain.agents.middleware import ModelRequest, ModelResponse, dynamic_prompt, wrap_model_call
from src.agents.common import load_chat_model
from src.utils import logger
@dynamic_prompt
def context_aware_prompt(request: ModelRequest) -> str:
""... | wilson0523/Yuxi-Know | src/agents/common/middlewares/context_middlewares.py | .py | 6a35d2dec16d3b21 | 7.45 | 7 |
from collections.abc import Callable
from typing import Any
from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse
from src.agents.common import get_mcp_tools
from src.utils import logger
class DynamicToolMiddleware(AgentMiddleware):
"""动态工具选择中间件 - 支持 MCP 工具的动态加载和注册
注意:所有可能用到的... | wilson0523/Yuxi-Know | src/agents/common/middlewares/dynamic_tool_middleware.py | .py | 795a2e2b45ace300 | 7.45 | 7 |
import concurrent.futures
import threading
import time
from contextlib import contextmanager
from typing import Any
import pymysql
from pymysql import MySQLError
from pymysql.cursors import DictCursor
from src.utils import logger
class MySQLConnectionManager:
"""MySQL 数据库连接管理器"""
def __init__(self, config:... | wilson0523/Yuxi-Know | src/agents/common/toolkits/mysql/connection.py | .py | 89f35cdb46dba433 | 7.45 | 7 |
"""agent implementations for familiar."""
from __future__ import annotations
import subprocess
import warnings
from abc import ABC, abstractmethod
from pathlib import Path
from ._plugins import load_plugins
class Agent(ABC):
"""base class for AI coding agents."""
name: str
output_file: str
skill_d... | cyberwitchery/familiar | src/familiar/agents.py | .py | ece483661fe794f5 | 7.42 | 6 |
"""linting for familiar conjurings and invocations."""
from __future__ import annotations
import re
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Literal
from ._plugins import load_plugins
from .render import (
_SNIPPET_INCLUDE,
N... | cyberwitchery/familiar | src/familiar/lint.py | .py | 6c52b0961eaf826c | 7.42 | 6 |
"""render system and user prompts from conjurings and invocations."""
from __future__ import annotations
import re
import sys
from importlib import resources
try:
from importlib.resources.abc import Traversable # type: ignore[import-not-found]
except ImportError:
from importlib.abc import Traversable
from p... | cyberwitchery/familiar | src/familiar/render.py | .py | fbc05df5dc41ed1f | 7.42 | 6 |
"""Nox sessions for matrix testing across Python versions and dependency pins.
Run all default sessions:
uv run nox
Run tests against a single Python version:
uv run nox -s tests-3.14
Run the textual matrix:
uv run nox -s tests_textual
"""
from __future__ import annotations
import nox
nox.options.defa... | jongracecox/fujimoto | noxfile.py | .py | 4d61fafaa4f24839 | 7.48 | 8 |
"""Full-text search across Claude Code transcript logs.
The home screen's `/` filter matches session *names*; this module matches
session *contents* — the JSONL transcripts Claude Code writes under
`~/.claude/projects/`. That means touching every byte of every log, which is
far too slow to do synchronously between key... | jongracecox/fujimoto | src/fujimoto/claude/search.py | .py | e1b1c6313b77ed73 | 7.48 | 8 |
from __future__ import annotations
import json
import os
import re
from datetime import date
from pathlib import Path
from fujimoto import debug
class ConfigError(Exception):
pass
def get_git_projects_root() -> Path | None:
"""Read FUJIMOTO_GIT_ROOT env var. Returns None if unset."""
raw = os.environ.... | jongracecox/fujimoto | src/fujimoto/config.py | .py | c201eedbfb6b0a36 | 7.48 | 8 |
from __future__ import annotations
import subprocess
from pathlib import Path
from fujimoto import debug
class GitError(Exception):
pass
def _run(args: list[str], cwd: Path | str | None = None) -> str:
try:
result = subprocess.run(
["git", *args],
cwd=cwd,
captu... | jongracecox/fujimoto | src/fujimoto/git.py | .py | 8c2df129946e5170 | 7.48 | 8 |
"""Per-project `.fujimoto.yaml` configuration.
An optional, committed config file at the project root describing files to copy
or link into a new worktree and commands to run inside it. Parsed and validated
with pydantic; applied at worktree creation and on session launch/resume.
"""
from __future__ import annotation... | jongracecox/fujimoto | src/fujimoto/project_config.py | .py | 33bbbf41588b88f2 | 7.48 | 8 |
"""Which sessions the user still considers open.
Fujimoto is the only thing that ever changes a session's *intent*. A session
the user terminated through fujimoto is forgotten; a session that disappeared
any other way — an out-of-band ``tmux kill-session``, a closed terminal window,
an ``exit`` in the pane, a tmux cra... | jongracecox/fujimoto | src/fujimoto/session_state.py | .py | fdadeb5efc9510cf | 7.48 | 8 |
"""Open a new terminal window in a given directory.
Cross-platform: macOS uses iTerm2 (or Terminal.app fallback). Linux uses the
``FUJIMOTO_TERMINAL`` env var if set, otherwise auto-detects a common terminal
emulator on PATH.
The ``FUJIMOTO_TERMINAL`` env var is shell-quoted and may contain ``{dir}`` as
a placeholder... | jongracecox/fujimoto | src/fujimoto/terminal.py | .py | a2a1ee23edea0c9c | 7.48 | 8 |
"""Open a directory in Visual Studio Code."""
from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
from fujimoto import debug
def _has_vscode() -> bool:
"""Check if the ``code`` CLI is available on PATH."""
return shutil.which("code") is not None
def open_vscode(dir... | jongracecox/fujimoto | src/fujimoto/vscode.py | .py | dc225c320620cbe1 | 7.48 | 8 |
from __future__ import annotations
import json
from pathlib import Path
import pytest
from fujimoto.claude.search import (
MAX_SNIPPETS,
ContentMode,
SearchError,
_collapse,
_message_text,
_snippet,
compile_matcher,
iter_hits,
list_session_logs,
search_log,
)
# -- Helpers --... | jongracecox/fujimoto | tests/test_claude_search.py | .py | 8945061c3f77b059 | 7.98 | 8 |
"""
Module: fetch_pepy_downloads.py
This module fetches download statistics for a specific Python package
hosted on pepy.tech using the Pro API (which requires authentication),
and generates a badge (as an SVG file) representing the total number of downloads.
Features:
- Secure API access using a GitHub Actions secr... | MichaelHallik/robotframework-xmlvalidator | fetch_pepy_downloads.py | .py | 25404bc267a67835 | 7.42 | 6 |
# Copyright 2024-2026 Michael Hallik
#
# 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 or agreed to in... | MichaelHallik/robotframework-xmlvalidator | src/xmlvalidator/files.py | .py | 4cd9ac979a8e24aa | 7.42 | 6 |
# Copyright 2024-2026 Michael Hallik
#
# 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 or agreed to in... | MichaelHallik/robotframework-xmlvalidator | src/xmlvalidator/namespaces.py | .py | 045af2f766672284 | 7.42 | 6 |
# Copyright 2024-2026 Michael Hallik
#
# 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 or agreed to in... | MichaelHallik/robotframework-xmlvalidator | src/xmlvalidator/results.py | .py | 2e0096269db0a8d4 | 7.42 | 6 |
# Copyright 2024-2026 Michael Hallik
#
# 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 or agreed to in... | MichaelHallik/robotframework-xmlvalidator | src/xmlvalidator/schema/manager.py | .py | 57a87ad1ec1a137f | 7.42 | 6 |
# Copyright 2024-2026 Michael Hallik
#
# 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 or agreed to in... | MichaelHallik/robotframework-xmlvalidator | src/xmlvalidator/schema/resolver.py | .py | 0a6b28f2e8283dd2 | 7.42 | 6 |
# Copyright 2024-2026 Michael Hallik
#
# 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 or agreed to in... | MichaelHallik/robotframework-xmlvalidator | src/xmlvalidator/validation.py | .py | ac83c6dfca5abbca | 7.42 | 6 |
"""
conftest.py - Shared pytest fixtures for XML Validator tests.
This module defines reusable pytest fixtures for setting up test files
and other common test utilities used across multiple test modules.
Pytest automatically discovers fixtures defined in `conftest.py`, making
them available in all test modules with... | MichaelHallik/robotframework-xmlvalidator | test/conftest.py | .py | 7e3445d118e30c24 | 7.92 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.