seifreed/MarkDownIngress

GitHub: seifreed/MarkDownIngress

MarkDownIngress 是一个面向 LLM 管道的安全优先网页内容摄取引擎,在将不可信网页内容喂给大模型之前完成提取、清洗、注入检测和 token 优化。

Stars: 1 | Forks: 0

MarkDownIngress

MarkDownIngress

面向 LLM 管道的确定性、防注入 Web → Markdown 引擎

PyPI Version Python Versions License CI Status Deterministic

GitHub Stars GitHub Issues Buy Me a Coffee

## 概述 **MarkDownIngress** 是一个面向 LLM 管道的安全优先的网页内容摄取引擎。它通过 Mozilla Readability 获取网页、清理 HTML、检测提示注入模式、转换为 token 优化的 Markdown,并生成确定性输出。它以 Python 库、FastAPI 服务器和 CLI 的形式提供。 它**不是**递归爬虫、完整的 RAG 框架或通用的 HTML→Markdown 转换器。它**是**一个摄取安全边界,在不可信内容到达模型之前对其进行标记。 ### 核心特性 | 特性 | 描述 | |---------|-------------| | **注入检测** | 10+ 种模式检测器,风险评分范围 0.0–1.0;可选 Nova / LLM 层级 | | **Token 优化** | 通过 Readability + 清理实现 70–80% 的平均 token 减少 | | **确定性输出** | `fast` 模式下稳定的 Markdown 及 SHA256 内容/结构哈希 | | **Fast / Render / Auto** | 仅 HTTP、Playwright SPA 渲染或自动回退 | | **结构化块与分块** | 标题/表格/代码/列表提取,生成稳定的 RAG 分块 | | **域名策略** | 针对各主机的模式、阈值、选择器、允许/阻止标签覆盖 | | **输出配置文件** | `llm_safe`、`rag_chunkable`、`for_search`、`for_archive`、`default` | | **批量与异步** | 并发摄取,支持飞行中去重和按模式统计 | | **库 + CLI + API** | `ingest()` / `markdown-ingress` / FastAPI `/api/v1/*` | ### 支持的输出 ``` Document SafeDocument (markdown + metadata + hashes + score + flags) Serialization Markdown, JSON Security Injection score 0.0–1.0, risk level, JSON security report Structure Structured blocks, native chunks, structural hash API FastAPI /api/v1 with persistent batch jobs + webhooks ``` ## 安装 ### 从 PyPI 安装(推荐) ``` pip install markdown-ingress ``` ### 从源码安装 ``` git clone https://github.com/seifreed/MarkDownIngress.git cd MarkDownIngress python3 -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install -e . ``` ### 可选扩展 ``` pip install "markdown-ingress[all]" # everything pip install "markdown-ingress[render]" # Playwright SPA rendering pip install "markdown-ingress[security]" # Nova advanced injection detection pip install "markdown-ingress[api]" # FastAPI server # 渲染模式还需要一个浏览器二进制文件: playwright install chromium ``` ## 快速开始 ``` # 摄取单个 URL 并打印报告 markdown-ingress ingest https://example.com # 将清理后的 Markdown 保存到文件 markdown-ingress ingest https://example.com --save example.md # 包含元数据、哈希值和注入分数的 JSON 输出 markdown-ingress ingest https://example.com --json --save example.json ``` 报告输出示例: ``` ============================================================ MarkDownIngress v1.0.0 - Ingestion Report ============================================================ 📄 Title: Example Domain 🔗 URL: http://example.com ✔ Tokens: 33 ↳ Saved: 119 tokens (78.29% reduction) 🔒 Injection Score: 0.000 (SAFE) 🔑 Hash: sha256:d6ac852cf2392c04d2cf3e3e4156f786cfbc4f46308ebe756ebd72cf9ffef4ef ⏱️ Fetch time: 116ms ``` ## 使用方法 ### 命令行界面 ``` # 使用 Playwright 渲染 JavaScript 重度 SPA markdown-ingress ingest https://spa-app.example.com --render --timeout 60 # 带有基于标题分块的 RAG 就绪结构化输出 markdown-ingress ingest https://docs.example.com \ --output-profile rag_chunkable \ --extract-blocks \ --chunking-strategy heading \ --show-chunks # 将 URL 列表批量转换为 Markdown 文件目录 markdown-ingress batch urls.txt --output results/ # 在本地 HTML 文件上比较提取器(离线运行) markdown-ingress compare tests/fixtures/technical_doc.html --json # 跨 URL 列表对 token 缩减进行基准测试 markdown-ingress benchmark urls.txt --iterations 5 --compare-extractors ``` ### 命令 | 命令 | 描述 | |---------|-------------| | `markdown-ingress ingest ` | 摄取单个 URL(`text`、`--json`、`--save`) | | `markdown-ingress batch ` | 并发处理换行分隔的 URL 文件 | | `markdown-ingress compare ` | 在本地 HTML 上比较 Readability 与 Trafilatura | | `markdown-ingress benchmark ` | 在 URL 列表上测量延迟和 token 减少情况 | ### 关键标志(`ingest`) | 选项 | 描述 | |--------|-------------| | `--render` / `--fast` | 强制使用 Playwright 渲染模式或仅 HTTP 快速模式 | | `--strict` / `--permissive` | 切换严格安全阈值(默认严格) | | `--config FILE` | 从 YAML/JSON 配置文件加载运行时设置 | | `--model MODEL` | Token 估算模型(`gpt-4`、`claude`、`gpt-3.5-turbo`) | | `--output-profile PROFILE` | 应用 `llm_safe`、`rag_chunkable`、`for_search`、`for_archive` | | `--extract-blocks` | 输出结构化块(标题、表格、代码、列表) | | `--chunking-strategy {none,heading,size}` | 构建稳定的原生分块 | | `--domain-policy-file FILE` | 从 JSON 加载每主机策略覆盖 | | `--json` / `--save FILE` | 输出 JSON / 将主要输出写入文件 | | `--show-observability` | 打印阶段计时和策略/成本遥测数据 | ## Python 库 ### 基本用法 ``` from markdown_ingress import ingest doc = ingest("https://example.com", mode="fast", strict=True) print(doc.markdown) # Sanitized Markdown print(doc.token_estimate) # Token count for the chosen model print(doc.injection_score) # 0.0 (safe) → 1.0 (critical) print(doc.content_hash) # "sha256:..." for dedup/versioning print(doc.flags) # Security warning flags ``` ### 批量与异步 ``` import asyncio from markdown_ingress import ingest_many, ingest_async # 并发批量摄取与飞行中去重 result = ingest_many( ["https://example.com/a", "https://example.com/b"], mode="auto", max_concurrent=4, ) print(f"safe: {result.successful}/{result.total}") # 异步单次摄取 async def main(): doc = await ingest_async("https://example.com", mode="auto") print(doc.metadata["title"]) asyncio.run(main()) ``` ### RAG 就绪的结构化输出 ``` from markdown_ingress import ingest doc = ingest( "https://docs.example.com/guide", mode="fast", output_profile="rag_chunkable", extract_blocks=True, chunking_strategy="heading", ) print(doc.structured_blocks[0]["block_type"]) print(doc.chunks[0]["chunk_id"]) ``` ### 安全报告 API ``` from markdown_ingress import generate_security_report report = generate_security_report("https://suspicious-site.example.com") report.save("security_report.json") print(report.injection_score) # numeric risk score print(report.risk_level) # SAFE / LOW / MEDIUM / HIGH / CRITICAL print(report.token_reduction_percent) # token savings % print(report.pattern_matches) # matched injection patterns ``` ### 特定域名加固 ``` from markdown_ingress import DomainPolicy, ingest doc = ingest( "https://forum.example.com/thread", mode="auto", domain_policies=[ DomainPolicy( domain="forum.example.com", output_profile="llm_safe", policy_name="strict", blocked_selectors=[".reply-box", ".promo"], blocked_tags=["form"], ) ], ) print(doc.metadata["domain_policy"]) ``` 更多可运行脚本位于 [`examples/`](examples/) — 参见 [`library_usage.py`](examples/library_usage.py) 和 [`library_batch_async.py`](examples/library_batch_async.py)。 ## 安全模型 ### 注入检测模式 | 模式 | 权重 | 示例 | |---------|--------|---------| | 指令覆盖 | 0.8 | "ignore previous instructions" | | 密钥提取 | 0.9 | "reveal secret keys" | | 模式切换 | 0.7 | "enable developer mode" | | 系统提示访问 | 0.6 | "reveal system prompt" | | 策略覆盖 | 0.8 | "override policy settings" | | 模型操纵 | 0.5 | "you are ChatGPT" | ### 风险等级 | 分数 | 等级 | 操作 | |-------|-------|--------| | 0.0 – 0.2 | **安全** | 内容看起来安全 | | 0.2 – 0.4 | **低** | 建议审查 | | 0.4 – 0.6 | **中** | 需要人工审查 | | 0.6 – 0.8 | **高** | 谨慎使用 | | 0.8 – 1.0 | **严重** | 建议阻止 | 基础安装使用确定性启发式方法。安装 `[security]` 以添加 Nova 语义检测,并设置 `ANTHROPIC_API_KEY` 配合 `--use-llm` 以启用 可选的 LLM 辅助层级。 ## FastAPI 服务器 ``` pip install "markdown-ingress[api]" uvicorn markdown_ingress.api_server:app --port 8000 ``` `/api/v1` 下的版本化端点: ``` POST /api/v1/ingest Single URL ingestion POST /api/v1/ingest/batch Synchronous batch POST /api/v1/jobs/batch Persistent batch job (TTL + optional webhook) GET /api/v1/jobs/{job_id} Job status / result POST /api/v1/security/report Security report for a URL GET /api/v1/stats Process-level ingest stats GET /api/v1/health Health check ``` ``` curl -X POST http://localhost:8000/api/v1/ingest \ -H "Content-Type: application/json" \ -d '{"url":"https://example.com","mode":"fast","strict":true}' ``` ## 要求 - Python 3.13 或 3.14 - 核心依赖:`httpx`、`selectolax`、`readability-lxml`、`markdownify`、`tiktoken` - 可选:`playwright`(渲染)、`nova-hunting`(安全)、`fastapi`(API) - 完整依赖列表参见 [pyproject.toml](pyproject.toml) ## 开发 ``` git clone https://github.com/seifreed/MarkDownIngress.git cd MarkDownIngress python3 -m venv venv && source venv/bin/activate pip install -e ".[dev]" playwright install chromium make test # full local suite (campaign/baseline excluded) make test-fast # suite excluding opt-in live dataset tests ruff check markdown_ingress tests black --check markdown_ingress tests mypy markdown_ingress bandit -r markdown_ingress ``` 每个 bug 修复必须包含一个回归测试,该测试在修复前失败、修复后通过。`ruff`、`black --check`、`mypy` 和 `bandit` 必须在代码被视为完成之前通过。 ## 发布 发布由标签驱动。更新 `pyproject.toml` 和 `markdown_ingress/__init__.py` 中的包版本,提交更改,然后创建并推送 `v*` 标签: ``` git tag v1.0.0 git push origin v1.0.0 ``` 发布工作流构建 wheel 和源码分发包,使用 `twine` 检查,创建或更新匹配的 GitHub Release,将 `dist/*` 上传为发布资产,并通过 Trusted Publishing/OIDC 发布到 PyPI。不使用长期有效的 PyPI API token。 在推送发布标签之前配置 PyPI 可信发布者: - 所有者:`seifreed` - 仓库:`MarkDownIngress` - 工作流:`publish.yml` - 环境:`pypi` ## 许可证 本项目基于 MIT 许可证授权。参见 [LICENSE](LICENSE)。 **致谢** - 作者:**Marc Rivero López** | [@seifreed](https://github.com/seifreed) - 仓库:[github.com/seifreed/MarkDownIngress](https://github.com/seifreed/MarkDownIngress)

为 LLM 时代而构建。默认安全。设计确定性。

标签:LLM, Markdown, MarkdownIngress, pip, prompt injection, PyPI, Python, Token效率, Unmanaged PE, Web内容提取, Web爬虫, 二进制发布, 云安全监控, 内容净化, 内容审计, 内容管道, 安全引擎, 开源, 开源工具, 提示注入, 数字安全, 数据清洗, 无后门, 特征检测, 确定性, 结构化输出, 网络安全, 运行时操纵, 逆向工具, 防注入, 隐私保护, 集群管理, 零日漏洞检测, 静态分析