PDF 转 PPT

Model: qwen-plus | ¥0.15/call
PDFPPT转换演示文稿AI论文报告加密 PDF智能提炼按页转换

PDF 转 PPT pdf-to-ppt:按页生成 PPTX 演示文稿,每页一张幻灯片;可选 AI 总结每页要点(更专业)。支持加密 PDF(需密码)。适合论文转 PPT、报告转 PPT、长 PDF 转演示文稿。

Skill Documentation

---

name: pdf-to-ppt

description: PDF 转 PPT pdf-to-ppt:按页生成 PPTX 演示文稿,每页一张幻灯片;可选 AI 总结每页要点(更专业、更适合演讲)。支持加密 PDF(需密码)。适合论文转 PPT、产品手册转 PPT、白皮书转 PPT、长 PDF 转演示文稿、合同转汇报材料、学生作业转 PPT。

---

⚠️ chat 模式使用须知(重要)

本 skill 的真实能力依赖平台后端工具。在网页 / chat 端点下,这些工具可能不可用:

此时**请勿轻信**,请改用 **agent / CLI 路径**运行本 skill 以获取真实结果。任何路径下都**严禁谎称「已调用 / 已搜索完成」而实际未执行**。

PDF 转 PPT(pdf-to-ppt)

把 PDF 文档按页转成 PPTX 演示文稿:每页生成一张幻灯片(标题 + 要点列表)。支持两种模式:①确定性按行提取 ②AI 总结每页要点(更专业)。本地执行,不上传文档。

典型使用场景

**场景 1:研究生答辩准备** —— 导师给的 30 页 PDF 论文直接转 PPT,加 `--ai-summary` 让 AI 自动提炼每页要点 + 起个更专业的标题,1 小时手动活压缩到 3 分钟。

**场景 2:销售做产品介绍** —— 产品白皮书 PDF 转 PPTX,加公司 logo + 演讲备注后直接给客户演示。

**场景 3:咨询师月度汇报** —— 行业研究报告 PDF 转 PPT,按章节自动总结要点,免去复制粘贴。

适用人群

| 角色 | 典型用途 |

|------|----------|

| 研究生 / 大学生 | 论文转答辩 PPT、课件转 PPT |

| 研究员 / 学者 | 学术论文转汇报、白皮书转 PPT |

| 销售 / 商务 | 产品手册转 PPT、白皮书转 PPT |

| 咨询师 / 分析师 | 行业报告转汇报材料 |

| 培训师 / 教师 | 教材 PDF 转课件 |

| 法务 / HR | 合同 / 制度文件转汇报材料 |

完整数据示例(实测)

# 基础模式(确定性按行提取)
python scripts/pdf2ppt.py --input 论文.pdf --output 论文.pptx --max-bullets 6

# AI 总结模式(每页调用 qwen-flash 提炼要点 + 标题)
python scripts/pdf2ppt.py --input 产品白皮书.pdf --output 产品白皮书.pptx --ai-summary

# 加密 PDF 转 PPT
python scripts/pdf2ppt.py --input 保密文档.pdf --output 保密文档.pptx --password xxx

输出示例:

{"ok": true, "output": "论文.pptx", "pdf_pages": 30, "ppt_slides": 28,
 "ai_calls": 28, "bytes": 234567, "note": "AI 总结每页要点"}

为什么选 pdf-to-ppt

| 对比项 | 手动做 PPT | pdf-to-ppt |

|--------|-----------|------------|

| 30 页论文转 PPT | 4-8 小时 | 3-5 分钟 |

| 排版一致性 | 容易前后不一致 | 自动统一标题 + 要点样式 |

| AI 提炼要点 | 没有(手动读 + 写)| `--ai-summary` 一键 |

| 加密 PDF | 不能用 | 支持(密码) |

| 成本 | 人工时间 | ¥0.15/次,AI 模式仅多花 ¥0.3-1 |

触发条件

用户要求"PDF 转 PPT / PDF 转 PPTX / 把论文做成 PPT / PDF 生成演示文稿 / 帮我把这份 PDF 做成能演讲的 PPT"时触发。

触发条件

用户要求"PDF 转 PPT / PDF 转 PPTX / 把论文做成 PPT / PDF 生成演示文稿 / 帮我把这份 PDF 做成能演讲的 PPT"时触发。

执行步骤

1. 安装依赖

pip install pypdf python-pptx
# AI 总结(--ai-summary):依赖 AIMS_API_KEY

2. 执行转换

# 默认(确定性按行提取)
python scripts/pdf2ppt.py --input 论文.pdf --output 论文.pptx [--max-bullets 6] [--password xxx]

# AI 总结模式(每页调用 qwen-flash 提炼要点 + 标题,更专业)
python scripts/pdf2ppt.py --input 论文.pdf --output 论文.pptx --ai-summary

参数说明:

3. 输出

成功返回 JSON:

{"ok": true, "output": "论文.pptx", "pdf_pages": 12, "ppt_slides": 12, "ai_calls": 12, "bytes": 45678,
 "note": "AI 总结每页要点"}

处理规则

1. 每页 PDF → 一张幻灯片,标题为"第 N 页 · 页面首行"

2. 无文本的空白页自动跳过(不计入 slide)

3. 生成后可建议用户用 pptx 读取工具检查内容完整性

失败处理

| 情况 | 处理 |

|---|---|

| PDF 加密无密码 | 报错并提示提供密码(先确认文档归属) |

| 扫描版 PDF(无文本层) | 报错"请先 OCR 识别出文本再转换",引导用 OCR 工具 |

| 依赖缺失 | 提示安装命令后重试 |

合规与安全

<!-- ===== 以下为内嵌脚本代码(agent 安装时按需落盘为 scripts/<name> 并 chmod +x) ===== -->

文件:scripts/pdf2ppt.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""PDF 转 PPTX:按页提取 PDF 文本,每页生成一张 PPT(标题+要点)。

用法示例:
  python pdf2ppt.py --input 论文.pdf --output 论文.pptx [--max-bullets 6] [--password xxx]
  python pdf2ppt.py --input 论文.pdf --output 论文.pptx --ai-summary                    # AI 总结每页要点
  python pdf2ppt.py --input 论文.pdf --output 论文.pptx --ai-summary --api-key aims_sk_xxx

依赖:pip install pypdf python-pptx
说明:纯文本转换,确定性输出;扫描版 PDF(无文本层)请先用 ocr.py 识别出文本再转换。
AI 增强(--ai-summary):依赖 AIMS_APIKEY,按页调用 qwen-flash 总结,更智能
"""
import argparse
import json
import re
import sys
from pathlib import Path

try:
    from pypdf import PdfReader
    from pptx import Presentation
    from pptx.util import Inches, Pt
except ImportError:  # pragma: no cover
    sys.stderr.write("缺少依赖 pypdf/python-pptx,请先执行: pip install pypdf python-pptx\n")
    sys.exit(2)

_HERE = Path(__file__).resolve().parent
_ROOT = _HERE.parent.parent
# _lib 查找(2026-09-22 修复):优先包内 _lib/(发布包已随附),
# 退回开发布局 office-skills/_lib —— 否则装到用户侧会 ModuleNotFoundError。
for _lib_cand in (Path(__file__).resolve().parent.parent / "_lib",
                  Path(__file__).resolve().parent.parent.parent / "_lib"):
    if _lib_cand.is_dir():
        sys.path.insert(0, str(_lib_cand))
        break
else:
    raise RuntimeError(
        "找不到 _lib/(需要 aims_functional_api.py)。"
        "发布包应自带 _lib/;开发环境下请确认 office-skills/_lib 存在。"
    )
try:
    from aims_chat import chat_text_json
    _AIMS_OK = True
except Exception:  # pragma: no cover
    _AIMS_OK = False


def _clean(text: str) -> list[str]:
    """按行清理,返回非空行。"""
    lines = []
    for line in text.splitlines():
        line = line.strip()
        if line:
            lines.append(line)
    return lines


def _pick_title(lines: list[str]) -> tuple[str, list[str]]:
    """取第一行作为标题(截断 40 字),其余为要点。"""
    if not lines:
        return "", []
    title = lines[0]
    if len(title) > 40:
        title = title[:40] + "…"
    return title, lines[1:]


def _ai_summarize_page(text: str, max_bullets: int, api_key: str | None) -> tuple[str, list[str]]:
    """让 AI 提炼:标题 + 要点。"""
    if not text.strip():
        return "", []
    body = text[:4000]
    prompt = (
        "你是一个 PPT 提炼助手。请把下面这段 PDF 页面正文整理成 PPT 一页的内容。\n"
        "严格返回 JSON(不要解释、不要 Markdown 代码块),格式:\n"
        f"{{\"title\": \"本页标题(≤30字)\", \"bullets\": [\"要点1\", \"要点2\", ...]}}(bullets ≤ {max_bullets} 条,每条 ≤ 30 字)\n"
        f"--- 正文 ---\n{body}"
    )
    try:
        obj = chat_text_json(prompt, api_key=api_key, max_tokens=2000)
        title = (obj.get("title") or "").strip()
        bullets = [str(b).strip() for b in (obj.get("bullets") or [])][:max_bullets]
        return title, bullets
    except Exception:
        return _pick_title(_clean(text))


def cmd_convert(args) -> dict:
    reader = PdfReader(args.input)
    if reader.is_encrypted:
        if not args.password:
            raise ValueError("PDF 已加密,请提供 --password(仅限您有权处理的文档)")
        if not reader.decrypt(args.password):
            raise ValueError("密码错误")
    prs = Presentation()
    max_bullets = args.max_bullets
    use_ai = bool(getattr(args, "ai_summary", False))
    if use_ai and not _AIMS_OK:
        raise RuntimeError("--ai-summary 需要 AIMS helper(_lib/aims_chat.py)")

    slide_total = 0
    ai_calls = 0
    for i, page in enumerate(reader.pages, 1):
        raw = page.extract_text() or ""
        lines = _clean(raw)
        if not lines:
            continue  # 无文本页跳过
        if use_ai:
            title, bullets = _ai_summarize_page(raw, max_bullets, args.api_key)
            ai_calls += 1
        else:
            title, rest = _pick_title(lines)
            bullets = rest[:max_bullets]

        slide = prs.slides.add_slide(prs.slide_layouts[1])
        slide.shapes.title.text = f"第 {i} 页" + (f" · {title}" if title else "")
        body = None
        for ph in slide.placeholders:
            if ph.placeholder_format.idx == 1:
                body = ph
                break
        if body is not None:
            tf = body.text_frame
            tf.clear()
            for j, b in enumerate(bullets):
                para = tf.paragraphs[0] if j == 0 else tf.add_paragraph()
                para.text = b
        elif bullets:
            tb = slide.shapes.add_textbox(Inches(0.6), Inches(1.6), Inches(9), Inches(5))
            tf = tb.text_frame
            for j, b in enumerate(bullets):
                para = tf.paragraphs[0] if j == 0 else tf.add_paragraph()
                para.text = b
        slide_total += 1

    if slide_total == 0:
        raise ValueError("PDF 无可提取文本(可能是扫描件)。请先 OCR 识别出文本再转换。")

    out = Path(args.output)
    out.parent.mkdir(parents=True, exist_ok=True)
    prs.save(str(out))
    note = "AI 总结每页要点" if use_ai else f"每页提取前 {max_bullets} 个要点;扫描版请先 OCR"
    return {
        "ok": True,
        "output": str(out),
        "pdf_pages": len(reader.pages),
        "ppt_slides": slide_total,
        "ai_calls": ai_calls,
        "bytes": out.stat().st_size,
        "note": note,
    }


def build_parser() -> argparse.ArgumentParser:
    ap = argparse.ArgumentParser(description="PDF 转 PPTX(文本/AI 总结)")
    ap.add_argument("--input", required=True, help="源 PDF")
    ap.add_argument("--output", required=True, help="输出 PPTX")
    ap.add_argument("--max-bullets", type=int, default=6, help="每页最多要点数,默认 6")
    ap.add_argument("--password", default=None, help="加密 PDF 的密码(仅限本人文档)")
    ap.add_argument("--ai-summary", action="store_true", help="用 AI 提炼每页要点(依赖 AIMS_API_KEY)")
    ap.add_argument("--api-key", default=None)
    return ap


def main():
    args = build_parser().parse_args()
    try:
        result = cmd_convert(args)
    except Exception as e:
        print(json.dumps({"ok": False, "error": str(e)}, ensure_ascii=False))
        sys.exit(1)
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()

<!-- ===== 以下为共享依赖 _lib(落盘为 _lib/<name>,与 scripts/ 同级上层) ===== -->

文件:_lib/aims_chat.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AIMS 平台 AI 调用公共 helper(6 个 skill 复用)。

能力:
  - chat_text(prompt, model="qwen-flash")          纯文本对话
  - chat_vision(image_path_or_url, prompt, ...)    图片+文本多模态
  - chat_pdf_pages(pdf_path, prompt, zoom=2.0)     扫描版 PDF OCR
  - chat_with_usage(...)                           返回文本+用量

环境:依赖 AIMS_API_KEY 环境变量或 --api-key
"""
import argparse
import base64
import json
import os
import sys
import time
import urllib.request
from pathlib import Path

AIMS_URL = "https://aimsgateway.cn/mcp/"
TEXT_MODEL = "qwen-flash"           # 通用文本(最便宜)
VISION_MODEL = "qwen-vl-ocr-latest" # 视觉/OCR


# ---------- 鉴权 & 协议 ----------
def _get_key(api_key=None):
    key = api_key or os.environ.get("AIMS_API_KEY")
    if not key:
        raise RuntimeError(
            "缺少 AIMS API Key:请设置环境变量 AIMS_API_KEY,或调用方传 --api-key"
        )
    return key


def _rpc(url, key, method, params, mid, tries=3, timeout=180):
    body = json.dumps({"jsonrpc": "2.0", "id": mid, "method": method, "params": params}).encode()
    headers = {"Content-Type": "application/json", "Authorization": f"Bearer {key}"}
    last = None
    for _ in range(tries):
        try:
            req = urllib.request.Request(url, data=body, method="POST", headers=headers)
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read().decode())
        except Exception as e:  # noqa: BLE001
            last = e
            time.sleep(2)
    raise RuntimeError(f"MCP 调用失败: {last}")


def _handshake(key):
    _rpc(AIMS_URL, key, "initialize",
         {"protocolVersion": "2025-03-26", "capabilities": {},
          "clientInfo": {"name": "office-skills", "version": "1.0"}}, 1)
    try:
        _rpc(AIMS_URL, key, "notifications/initialized", {}, 2)
    except Exception:
        pass


# ---------- 图片编码 ----------
def _file_to_data_url(path):
    p = Path(path)
    if not p.exists():
        raise FileNotFoundError(path)
    b64 = base64.b64encode(p.read_bytes()).decode()
    ext = p.suffix.lower()
    mime = {
        "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg",
        "gif": "image/gif", "webp": "image/webp", "bmp": "image/bmp",
    }.get(ext, "image/png")
    return f"data:{mime};base64,{b64}"


def _pdf_page_to_data_url(pdf_path, page_index=0, zoom=2.0):
    try:
        import fitz  # PyMuPDF
    except ImportError:
        raise RuntimeError("PDF 多模态需要 PyMuPDF:pip install pymupdf")
    doc = fitz.open(pdf_path)
    if page_index < 0 or page_index >= doc.page_count:
        raise IndexError(f"页码 {page_index} 越界,共 {doc.page_count} 页")
    pix = doc[page_index].get_pixmap(matrix=fitz.Matrix(zoom, zoom))
    raw = pix.tobytes("png")
    b64 = base64.b64encode(raw).decode()
    return f"data:image/png;base64,{b64}"


# ---------- 聊天封装 ----------
def _chat_call(key, model, content, max_tokens=4000, temperature=0, mid=7, no_rag=True):
    """调 aims.chat。

    关键参数 `no_rag` 默认 True(2026-09-16 平台确认):
    - 平台默认给 chat 注入知识库(KB)内容,视觉模型/OCR 收到 RAG 文本会跑偏
    - 加上 `no_rag: True` 后,模型纯粹根据 prompt + 图片回答
    - 纯文本调用也建议加,避免被 KB 干扰
    """
    arguments = {
        "model": model,
        "messages": [{"role": "user", "content": content}],
        "max_tokens": max_tokens, "temperature": temperature,
        "no_rag": no_rag,
    }
    resp = _rpc(AIMS_URL, key, "tools/call",
                {"name": "aims.chat", "arguments": arguments}, mid)
    txt = resp.get("result", {}).get("content", [{}])[0].get("text", "")
    if not txt:
        raise RuntimeError("平台返回为空: " + json.dumps(resp, ensure_ascii=False)[:300])
    try:
        obj = json.loads(txt)
        return obj["choices"][0]["message"]["content"], obj.get("usage", {})
    except Exception:
        return txt, {}


def chat_text(prompt, model=None, max_tokens=4000, temperature=0, api_key=None, no_rag=True):
    """纯文本对话:返回文本。"""
    key = _get_key(api_key)
    _handshake(key)
    model = model or TEXT_MODEL
    text, _ = _chat_call(key, model, prompt, max_tokens, temperature, no_rag=no_rag)
    return text.strip()


def chat_text_with_usage(prompt, model=None, max_tokens=4000, temperature=0, api_key=None, no_rag=True):
    key = _get_key(api_key)
    _handshake(key)
    model = model or TEXT_MODEL
    text, usage = _chat_call(key, model, prompt, max_tokens, temperature, no_rag=no_rag)
    return text.strip(), usage


def chat_vision(image_input, prompt, model=None, max_tokens=4000, api_key=None, no_rag=True):
    """图片对话:image_input 可为本地路径或 data: URI。"""
    key = _get_key(api_key)
    _handshake(key)
    model = model or VISION_MODEL
    if image_input.startswith("data:"):
        data_url = image_input
    else:
        data_url = _file_to_data_url(image_input)
    content = [
        {"type": "image_url", "image_url": {"url": data_url}},
        {"type": "text", "text": prompt},
    ]
    text, _ = _chat_call(key, model, content, max_tokens, 0, no_rag=no_rag)
    return text.strip()


def chat_pdf_page(pdf_path, page_index, prompt, model=None, zoom=2.0, max_tokens=4000, api_key=None, no_rag=True):
    """扫描版 PDF 单页:先渲染成图,再视觉 OCR。"""
    data_url = _pdf_page_to_data_url(pdf_path, page_index, zoom)
    return chat_vision(data_url, prompt, model=model, max_tokens=max_tokens, api_key=api_key, no_rag=no_rag)


# ---------- JSON 输出辅助 ----------
def _strip_code_fence(s):
    s = s.strip()
    if s.startswith("```"):
        lines = s.splitlines()
        if lines and lines[0].startswith("```"):
            lines = lines[1:]
        if lines and lines[-1].strip().startswith("```"):
            lines = lines[:-1]
        s = "\n".join(lines)
    return s.strip()


def chat_text_json(prompt, model=None, max_tokens=4000, api_key=None, no_rag=True):
    """纯文本对话 → 强制 JSON 输出(解析失败抛错)。"""
    text = chat_text(prompt, model=model, max_tokens=max_tokens, api_key=api_key, no_rag=no_rag)
    return json.loads(_strip_code_fence(text))


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description="AIMS 平台 AI 调用 helper 自检")
    ap.add_argument("--api-key", default=None)
    ap.add_argument("--text", default="用一句话介绍 Python。")
    args = ap.parse_args()
    print("=== chat_text ===")
    print(chat_text(args.text, api_key=args.api_key))

文件:_lib/aims_functional_api.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AIMS 平台功能型 API 公共调用 helper(付费 skill 共用)。

能力:
  - call_functional_api(resource_id, arguments)  统一调用平台托管功能型 API
  - needs_confirm → 抛出 NeedsConfirmation(结构化,带真实报价)
  - estimate_cost(resource_id, units)            免费报价(不调上游,0 花费)

协议(2026-09-22 platform-paid-confirm-protocol):
  付费工具默认 **confirm=False**(安全默认)。平台返回 -32006 时不扣费,
  本模块把它翻译成 NeedsConfirmation 异常(带 estimated_cost_yuan),
  而不是笼统的 RuntimeError——这样 agent 能把真实报价展示给用户,
  用户确认后加 --approved 重试。

环境:依赖 AIMS_API_KEY 环境变量或 --api-key
"""
import argparse
import json
import os
import time
import urllib.request

AIMS_URL = "https://aimsgateway.cn/mcp/"

# 内部源名 → 对外目录名(与平台 application/services/public_naming.py 的
# PUBLIC_SOURCES 对齐;未登记的源原样透出)。estimate 用它把内部 resource_id
# 映射成 list_functional_apis 返回的对外 id。
_EXTERNALIZE = {"serpapi": "web", "hunter": "email", "jev": "decision", "apis": "public-api"}


class NeedsConfirmation(RuntimeError):
    """付费工具未确认 —— 平台返回 -32006 / requires_confirmation。

    仍未扣费。调用方应把 estimated_cost_yuan 展示给用户,
    用户同意后带 confirm=True 重试。

    继承 RuntimeError 是为了向后兼容既有 ``except RuntimeError`` 调用方。
    """

    def __init__(self, resource_id, estimated_cost_yuan=0.0, basis="", raw=None, hint=""):
        self.resource_id = resource_id
        self.estimated_cost_yuan = float(estimated_cost_yuan or 0.0)
        self.basis = basis or ""
        self.raw = raw if isinstance(raw, dict) else {}
        self.hint = hint or ""
        super().__init__(
            f"付费工具需确认: {resource_id} 约 ¥{self.estimated_cost_yuan:.2f} "
            f"(价格依据: {self.basis or 'unknown'})。"
            f"请把该报价展示给用户;确认后加 --approved 重试。未确认不会扣费。"
        )

    def to_dict(self):
        """给 CLI 输出的结构化载荷(agent 可直接机读)。"""
        return {
            "ok": False,
            "needs_confirmation": True,
            "resource_id": self.resource_id,
            "estimated_cost_yuan": self.estimated_cost_yuan,
            "cost_basis": self.basis or "unknown",
            "hint": self.hint or "把费用展示给用户;用户确认后加 --approved 重试",
        }


def _external_rid(resource_id):
    """内部 resource_id → 对外目录 id。serpapi/google → web/google"""
    src, _, rest = (resource_id or "").strip().partition("/")
    ext = _EXTERNALIZE.get(src, src)
    return f"{ext}/{rest}" if rest else ext


def _maybe_needs_confirmation(resource_id, parsed):
    """把平台的 -32006 载荷翻译成 NeedsConfirmation;不是则返回 None。

    兼容三种形态:
      A {"error": {"code": -32006, "data": {...}}}   平台 JSON-RPC 包装
      B {"code": -32006, "data": {...}}              已解包的 error 对象
      C {"requires_confirmation": true, ...}         直接是 data
    """
    if not isinstance(parsed, dict):
        return None

    err = parsed.get("error")
    if isinstance(err, dict) and err.get("code") == -32006:
        d = err.get("data") if isinstance(err.get("data"), dict) else {}
        return NeedsConfirmation(resource_id, d.get("estimated_cost_yuan"),
                                 d.get("cost_basis", ""), err, d.get("hint", ""))

    if parsed.get("code") == -32006:
        d = parsed.get("data") if isinstance(parsed.get("data"), dict) else {}
        return NeedsConfirmation(resource_id, d.get("estimated_cost_yuan"),
                                 d.get("cost_basis", ""), parsed, d.get("hint", ""))

    if parsed.get("requires_confirmation") is True:
        return NeedsConfirmation(resource_id, parsed.get("estimated_cost_yuan"),
                                 parsed.get("cost_basis", ""), parsed, parsed.get("hint", ""))

    return None


def raise_if_needs_confirmation(resource_id, parsed):
    """载荷是 -32006 时抛 NeedsConfirmation,否则原样返回 parsed。

    给自建 _rpc_call 的 skill 复用(它们拿到 isError 载荷后调这个,
    就能和走本模块的 skill 有同一套结构化确认语义)。
    """
    nc = _maybe_needs_confirmation(resource_id, parsed)
    if nc is not None:
        raise nc
    return parsed


# ---------- 鉴权 & 协议 ----------
def _get_key(api_key=None):
    key = api_key or os.environ.get("AIMS_API_KEY")
    if not key:
        raise RuntimeError(
            "缺少 AIMS API Key:请设置环境变量 AIMS_API_KEY,或调用方传 --api-key"
        )
    return key


def _rpc(url, key, method, params, mid, tries=3, timeout=120):
    body = json.dumps({"jsonrpc": "2.0", "id": mid, "method": method, "params": params}).encode()
    headers = {"Content-Type": "application/json", "Authorization": f"Bearer {key}"}
    last = None
    for _ in range(tries):
        try:
            req = urllib.request.Request(url, data=body, method="POST", headers=headers)
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read().decode())
        except Exception as e:  # noqa: BLE001
            last = e
            time.sleep(2)
    raise RuntimeError(f"MCP 调用失败: {last}")


def _handshake(key):
    _rpc(AIMS_URL, key, "initialize",
         {"protocolVersion": "2025-03-26", "capabilities": {},
          "clientInfo": {"name": "office-skills-func-api", "version": "1.0"}}, 1)
    try:
        _rpc(AIMS_URL, key, "notifications/initialized", {}, 2)
    except Exception:
        pass


# ---------- 功能型 API 调用 ----------
def call_functional_api(resource_id, arguments=None, api_key=None, mid=3, confirm=False):
    """调 AIMS 平台的功能型 API。

    Args:
        resource_id: 资源 ID,9 个可选值:
            - hunter/account
            - hunter/domain-search
            - hunter/email-finder
            - hunter/email-verifier
            - serpapi/account
            - serpapi/{engine}
            - apis/catalog
            - apis/{slug}
            - apis/{slug}/{path}
        arguments: dict,参数键值对(按上游 API 的 params 字段说明)
        api_key: 可选 Bearer Token(默认读 env)
        confirm: True 时附 confirm:true,平台放行付费工具;False 时平台返回
            -32006 / requires_confirmation,未付费不扣费(默认 False,安全默认)

    返回 dict(平台直接返回上游响应 + 末尾 `_aimschina` 元数据)
    抛出 RuntimeError 当 isError=True
    """
    key = _get_key(api_key)
    _handshake(key)
    args = dict(arguments or {})
    if confirm:
        args["confirm"] = True
    resp = _rpc(AIMS_URL, key, "tools/call",
                {"name": "aims.call_functional_api",
                 "arguments": {"resource_id": resource_id, "arguments": args}}, mid)
    is_err = resp.get("result", {}).get("isError")
    text = resp.get("result", {}).get("content", [{}])[0].get("text", "{}")
    parsed = json.loads(text)
    if is_err:
        _nc = _maybe_needs_confirmation(resource_id, parsed)
        if _nc is not None:
            raise _nc
        raise RuntimeError(f"{resource_id} 错误: {parsed}")
    return parsed


# ---------- 9 个快捷封装 ----------
def hunter_account(api_key=None, confirm=False):
    """hunter 账户与配额(免费)。"""
    return call_functional_api("hunter/account", {}, api_key=api_key, confirm=confirm)


def hunter_domain_search(domain, limit=10, offset=0, type=None,
                         seniority=None, department=None, api_key=None, confirm=False):
    """按域名搜邮箱。返回 {"domain":..., "emails":[{value,type,confidence,position,...}], "_aimschina":{cost_yuan,...}}"""
    args = {"domain": domain, "limit": str(limit)}
    if offset:
        args["offset"] = str(offset)
    if type:
        args["type"] = type
    if seniority:
        args["seniority"] = seniority
    if department:
        args["department"] = department
    return call_functional_api("hunter/domain-search", args, api_key=api_key, confirm=confirm)


def hunter_email_finder(domain, full_name=None, first_name=None, last_name=None,
                        max_duration=10, api_key=None, confirm=False):
    """按人名 + 域名推断邮箱。"""
    args = {"domain": domain, "max_duration": str(max_duration)}
    if full_name:
        args["full_name"] = full_name
    elif first_name and last_name:
        args["first_name"] = first_name
        args["last_name"] = last_name
    return call_functional_api("hunter/email-finder", args, api_key=api_key, confirm=confirm)


def hunter_email_verifier(email, api_key=None, confirm=False):
    """验证邮箱是否可投递。返回 {"status": "valid"|"invalid"|"accept_all"|"webmail"|"disposable"|"unknown", ...}"""
    return call_functional_api("hunter/email-verifier", {"email": email}, api_key=api_key, confirm=confirm)


def serpapi_account(api_key=None, confirm=False):
    """serpapi 账户与配额(免费)。"""
    return call_functional_api("serpapi/account", {}, api_key=api_key, confirm=confirm)


def serpapi_search(engine, q=None, num=10, page=1, gl=None, hl=None,
                   location=None, api_key=None, confirm=False):
    """透传到任意 serpapi 引擎(google / google_maps / google_shopping 等)。

    engine 必填,例如 "google_maps" 拿 POI、"google" 拿网页搜索结果、"google_shopping" 拿商品。
    实际调 serpapi.engine 工具(不是走 functional_api 路由)。

    confirm=True 时附 confirm:true 放行付费工具;默认 False 平台返回 -32006 不扣费。
    """
    args = {"engine": engine, "num": str(num), "page": str(page)}
    if q:
        args["q"] = q
    if gl:
        args["gl"] = gl
    if hl:
        args["hl"] = hl
    if location:
        args["location"] = location
    if confirm:
        args["confirm"] = True
    key = _get_key(api_key)
    _handshake(key)
    resp = _rpc(AIMS_URL, key, "tools/call",
                {"name": "serpapi.engine", "arguments": args}, 3)
    is_err = resp.get("result", {}).get("isError")
    text = resp.get("result", {}).get("content", [{}])[0].get("text", "{}")
    parsed = json.loads(text)
    if is_err:
        _nc = _maybe_needs_confirmation("serpapi/" + str(engine or ""), parsed)
        if _nc is not None:
            raise _nc
        raise RuntimeError(f"serpapi.engine({engine}) 错误: {parsed}")
    return parsed


def apis_catalog(api_key=None):
    """列出所有 apis 目录(450+ 免密钥公共 API)。"""
    return call_functional_api("apis/catalog", {}, api_key=api_key)


def apis_slug(slug, api_key=None):
    """调 apis/{slug} 顶层端点(GET)。"""
    return call_functional_api(f"apis/{slug}", {}, api_key=api_key)


def apis_slug_path(slug, path, method="GET", body=None, params=None, api_key=None):
    """调 apis/{slug}/{path} 任意端点。

    Args:
        slug: 例如 "openweather"
        path: 例如 "data/2.5/weather"
        method: GET / POST / PUT / DELETE
        body: POST/PUT body
        params: query 参数
    """
    args = {"method": method}
    if body is not None:
        args["body"] = body
    if params is not None:
        args["params"] = params
    return call_functional_api(f"apis/{slug}/{path}", args, api_key=api_key)


# ---------- 免费报价 estimate(0 上游花费) ----------
# 本地兜底价:**只登记实测过的资源**(来源:lead-miner install.md §17.4,
# 实测日期 2026-09-17)。平台实时价取不到时才用它,且 cost_basis 会明确标
# local_fallback + price_note 提示可能有偏差——绝不拿它冒充权威报价。
# 没实测过的资源**一律不给兜底价**(宁可 ok=False,也不猜)。
LOCAL_FALLBACK_PRICE_YUAN = {
    "serpapi/google_maps": 0.21,
    "hunter/domain-search": 0.204,
    "hunter/email-verifier": 0.10,
}


def estimate_cost(resource_id, units=1, api_key=None):
    """纯报价:走**免费**的 aims.list_functional_apis 读实时单价,不调上游。

    这是唯一可靠的报价途径——catalog 声明价与实收价实测差 ~18%,
    而 list_functional_apis 返回的是平台已折算的 effective 单价
    (observed 实测价优先,缺失才回落 declared)。

    Args:
        resource_id: 内部 resource_id,如 "serpapi/google" / "hunter/domain-search"
        units: 预计调用次数
        api_key: 可选 Bearer Token(默认读 env)

    Returns:
        dict: {ok, resource_id, external_resource_id, units, unit_cost_yuan,
               cost_basis, total_yuan, upstream_called: False, note}
        查不到价时返回 ok=False(不抛异常——报价失败不该让调用方崩)
    """
    ext = _external_rid(resource_id)
    base = {
        "resource_id": resource_id,
        "external_resource_id": ext,
        "units": int(units or 1),
        "upstream_called": False,
    }

    def _fallback(note):
        """平台价拿不到时用本地实测兜底;没登记的资源保持 ok=False(不猜价)。"""
        unit = LOCAL_FALLBACK_PRICE_YUAN.get(resource_id)
        if unit is None:
            return False
        base.update({
            "ok": True,
            "unit_cost_yuan": round(unit, 4),
            "cost_basis": "local_fallback",
            "billing_unit": "per_call",
            "total_yuan": round(unit * base["units"], 4),
            "price_note": ("本地登记的【实测兜底价】(2026-09-17),非平台实时价,"
                           "实收可能偏差约 ±18%;要准数请配好 AIMS_API_KEY 重跑 estimate。"),
            "note": note,
        })
        return True

    try:
        key = _get_key(api_key)
    except RuntimeError as e:
        if not _fallback("用本地实测兜底价(未触达平台)"):
            base.update({"ok": False, "error": str(e),
                         "note": "estimate 需要 AIMS_API_KEY 才能读到平台实时单价"})
        return base
    try:
        _handshake(key)
        resp = _rpc(AIMS_URL, key, "tools/call",
                    {"name": "aims.list_functional_apis",
                     "arguments": {"limit": 200}}, 7)
        text = resp.get("result", {}).get("content", [{}])[0].get("text", "{}")
        payload = json.loads(text)
    except Exception as e:  # noqa: BLE001
        if not _fallback("用本地实测兜底价(平台单价查询失败)"):
            base.update({"ok": False, "error": f"读取平台单价失败: {e}"})
        return base

    items = payload.get("apis") or []
    hit = None
    for it in items:
        if isinstance(it, dict) and it.get("resource_id") in (ext, resource_id):
            hit = it
            break
    if hit is None:
        if _fallback("平台目录里没有该资源,改用本地实测兜底价"):
            base["not_in_catalog"] = True
            return base
        base.update({
            "ok": False,
            "error": f"平台目录里没找到 {ext}(内部 id: {resource_id})",
            "note": "单价未知——不要凭猜测报给用户;请确认该资源是否已上架/被 chat 策略隐藏",
            "available_count": len(items),
        })
        return base

    unit = float(hit.get("unit_cost_yuan") or 0.0)
    base.update({
        "ok": True,
        "name": hit.get("name") or "",
        "unit_cost_yuan": round(unit, 4),
        "cost_basis": hit.get("price_basis") or "declared",
        "billing_unit": hit.get("billing_unit") or "per_call",
        "total_yuan": round(unit * base["units"], 4),
        "note": "本报价未调用上游、未扣费;用户确认后加 --approved 真实执行",
    })
    return base


def emit_estimate(resource_id, units=1, api_key=None):
    """CLI 用:打印报价 JSON 并以退出码结束(0=有报价 / 1=查不到)。

    在 skill 里这样用(parse_args 之后、真调付费接口之前):
        if args.estimate:
            emit_estimate("serpapi/google")
    """
    est = estimate_cost(resource_id, units=units, api_key=api_key)
    print(json.dumps(est, ensure_ascii=False, indent=2))
    raise SystemExit(0 if est.get("ok") else 1)


def add_estimate_flag(parser):
    """给 skill 的 argparse 统一加 --estimate(免费报价,不调上游)。"""
    parser.add_argument(
        "--estimate", action="store_true",
        help="只报预估费用,不调用上游、不扣费(免费)",
    )
    return parser


# ---------- 列出当前所有可用 resource_id ----------
KNOWN_RESOURCES = [
    "hunter/account",
    "hunter/domain-search",
    "hunter/email-finder",
    "hunter/email-verifier",
    "serpapi/account",
    "serpapi/{engine}",
    "apis/catalog",
    "apis/{slug}",
    "apis/{slug}/{path}",
]


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(description="AIMS 功能型 API helper 自检")
    ap.add_argument("--api-key", default=None)
    ap.add_argument("--resource", default="hunter/account", help=f"资源 ID,已知: {KNOWN_RESOURCES}")
    ap.add_argument("--args", default="{}", help="JSON 字符串参数")
    args = ap.parse_args()

    print(f"=== call_functional_api({args.resource}) ===")
    parsed_args = json.loads(args.args)
    result = call_functional_api(args.resource, parsed_args, api_key=args.api_key)
    print(json.dumps(result, ensure_ascii=False, indent=2)[:2000])