研究与数据分析

文本与扫描PDF内容提取

提供待分析的PDF,先识别文本型或扫描型,再选择提取方式,整理正文、表格或图表内容。

# PDF 分析

## 第 0 步 — 检测 PDF 类型(文本还是扫描件)

**关键的第一步**:确定 PDF 包含可提取的文本,还是扫描图像。
绝不能跳过这一步——使用错误的解析器会浪费时间并产生空结果。

```python
import fitz  # PyMuPDF

def detect_pdf_type(pdf_path, sample_pages=3):
    """
    Returns 'text' if PDF has extractable text, 'scanned' if image-based.
    Checks first N pages (or all if fewer).
    """
    doc = fitz.open(pdf_path)
    total_chars = 0
    pages_checked = min(sample_pages, len(doc))

    for i in range(pages_checked):
        page = doc[i]
        text = page.get_text("text")
        total_chars += len(text.strip())

    doc.close()
    avg_chars = total_chars / max(pages_checked, 1)
    pdf_type = 'text' if avg_chars > 50 else 'scanned'
    print(f"PDF type: {pdf_type} (avg {avg_chars:.0f} chars/page, checked {pages_checked} pages)")
    return pdf_type
```

---

## 核心方法 1:文本型 PDF — 全文提取(所有页面)

```python
import fitz

def extract_text_pdf(pdf_path):
    """Extract text from all pages of a text-based PDF."""
    doc = fitz.open(pdf_path)
    total_pages = len(doc)
    print(f"Total pages: {total_pages}")

    all_text = []
    for i, page in enumerate(doc):
        text = page.get_text("text").strip()
        if text:
            all_text.append(f"=== Page {i+1} ===\n{text}")
        else:
            print(f"  Page {i+1}: no text (may be image — will caption later)")

    doc.close()
    return '\n\n'.join(all_text)

# ⚠️ MUST iterate ALL pages — never stop at page 1
full_text = extract_text_pdf(pdf_path)
print(f"Total text length: {len(full_text)} chars")
```

---

## 核心方法 2:文本型 PDF — 表格提取

对于包含表格的 PDF,`pdfplumber` 得到的表格结构比 `fitz` 更好:

```python
import pdfplumber
import pandas as pd

def extract_tables_pdf(pdf_path):
    """Extract all tables from all pages as DataFrames."""
    all_tables = []
    with pdfplumber.open(pdf_path) as pdf:
        print(f"Total pages: {len(pdf.pages)}")
        for i, page in enumerate(pdf.pages):
            tables = page.extract_tables()
            for j, tbl in enumerate(tables):
                if not tbl:
                    continue
                # First row as header
                df = pd.DataFrame(tbl[1:], columns=tbl[0])
                # Clean: strip whitespace, replace None
                df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
                df = df.dropna(how='all').reset_index(drop=True)
                all_tables.append({'page': i+1, 'table_idx': j, 'df': df})
                print(f"  Page {i+1}, Table {j}: {df.shape[0]}r × {df.shape[1]}c")
                print(df.head(3))
    return all_tables

# Verify table alignment after extraction:
# Print column headers and first 3 rows to confirm row/col mapping is correct
```

---

## 核心方法 3:扫描型 PDF — 通过图像描述进行 OCR

对于扫描型 PDF(页面由图像构成),将每页渲染为 PNG 并生成图像描述:

```python
import fitz
import subprocess, json, os

CAPTION = "/path/to/skills/sn-da-image-caption/scripts/caption.py"

def extract_scanned_pdf(pdf_path, prompt=None, dpi=150):
    """Render each page as image, then caption for text extraction."""
    doc = fitz.open(pdf_path)
    total_pages = len(doc)
    print(f"Scanned PDF: {total_pages} pages, captioning each...")

    all_text = []
    for i, page in enumerate(doc):
        # Render page to PNG
        mat = fitz.Matrix(dpi/72, dpi/72)
        pix = page.get_pixmap(matrix=mat)
        img_path = f"/tmp/pdf_page_{i+1}.png"
        pix.save(img_path)

        # Caption the page image
        cmd = ["python3", CAPTION, img_path, "--json"]
        if prompt:
            cmd += ["--prompt", prompt]
        else:
            cmd += ["--prompt", "提取页面中所有文字和表格内容,保持原始结构,Markdown格式输出。"]

        r = subprocess.run(cmd, capture_output=True, text=True, timeout=90)
        if r.returncode == 0:
            desc = json.loads(r.stdout).get("description", "")
            all_text.append(f"=== Page {i+1} ===\n{desc}")
            print(f"  Page {i+1}: {len(desc)} chars extracted")
        else:
            print(f"  Page {i+1}: caption failed — {r.stderr[:100]}")

    doc.close()
    return '\n\n'.join(all_text)

# Usage for scanned invoice PDFs, bank statements, org charts, etc.
text = extract_scanned_pdf(pdf_path)
```

---

## 核心方法 4:混合型 PDF(混合文本页和图像页)

```python
def extract_hybrid_pdf(pdf_path, text_prompt=None, image_prompt=None):
    """Handle PDFs where some pages have text, others are scanned."""
    doc_fitz = fitz.open(pdf_path)
    all_text = []

    for i, page in enumerate(doc_fitz):
        raw_text = page.get_text("text").strip()

        if len(raw_text) > 50:
            # Text page — use directly
            all_text.append(f"=== Page {i+1} (text) ===\n{raw_text}")
        else:
            # Image page — render and caption
            mat = fitz.Matrix(150/72, 150/72)
            pix = page.get_pixmap(matrix=mat)
            img_path = f"/tmp/hybrid_page_{i+1}.png"
            pix.save(img_path)

            cmd = ["python3", CAPTION, img_path, "--json"]
            prompt = image_prompt or "提取页面中所有文字和表格内容,Markdown格式输出。"
            cmd += ["--prompt", prompt]

            r = subprocess.run(cmd, capture_output=True, text=True, timeout=90)
            if r.returncode == 0:
                desc = json.loads(r.stdout).get("description", "")
                all_text.append(f"=== Page {i+1} (image→caption) ===\n{desc}")
            else:
                all_text.append(f"=== Page {i+1} (caption failed) ===")

    doc_fitz.close()
    return '\n\n'.join(all_text)
```

---

## 核心方法 5:从 PDF 中提取嵌入的图像或图表

```python
import fitz

def extract_pdf_images(pdf_path, min_width=100, min_height=100):
    """Extract all embedded images from a PDF (charts, diagrams, photos)."""
    doc = fitz.open(pdf_path)
    image_paths = []

    for page_num, page in enumerate(doc):
        for img_idx, img in enumerate(page.get_images(full=True)):
            xref = img[0]
            base = doc.extract_image(xref)
            img_bytes = base["image"]
            ext = base["ext"]

            img_path = f"/tmp/pdf_img_p{page_num+1}_{img_idx}.{ext}"
            with open(img_path, 'wb') as f:
                f.write(img_bytes)

            # Only keep images above size threshold (skip icons/logos)
            from PIL import Image
            with Image.open(img_path) as im:
                w, h = im.size
            if w >= min_width and h >= min_height:
                image_paths.append({'page': page_num+1, 'path': img_path, 'size': (w, h)})
                print(f"  Page {page_num+1}, img {img_idx}: {w}×{h} → {img_path}")

    doc.close()
    return image_paths

# After extracting, caption each image:
# for img_info in image_paths:
#     caption_image(img_info['path'], prompt="提取图表数据,Markdown 表格输出。")
```

---

## 常见模式

### 多发票或多文档 PDF(发票汇总)

```python
# When PDF contains multiple invoices (one per page):
tables_by_page = extract_tables_pdf(pdf_path)
invoices = []
for item in tables_by_page:
    df = item['df']
    # Find key fields (flexible column name matching)
    for col in df.columns:
        if '金额' in str(col) or 'amount' in str(col).lower():
            invoices.append({'page': item['page'], 'amount_col': col, 'data': df})
            break
print(f"Found {len(invoices)} pages with amount data")
```

### 提取数值时注意单位

```python
import re

def extract_number_with_unit(text_snippet):
    """
    Extract value and unit from text like '1,760 千港元' or '95,975,196,217.52元'.
    Returns (numeric_value, unit_string).
    """
    # Remove thousands separator
    text_snippet = text_snippet.replace(',', '')
    match = re.search(r'([\d\.]+)\s*(千|万|亿|百万)?\s*(元|港元|美元|人民币|%|percent)?', text_snippet)
    if not match:
        return None, None
    value = float(match.group(1))
    multiplier_map = {'千': 1000, '万': 10000, '亿': 1e8, '百万': 1e6}
    mult = multiplier_map.get(match.group(2), 1)
    unit = match.group(3) or ''
    return value * mult, f"{match.group(2) or ''}{unit}"

# Always verify unit matches what the question asks:
# "多几多" in HKD → answer in 千港元 if source says 千港元
```

### 长文档关键词搜索

```python
def find_in_pdf(pdf_path, keyword, context_chars=200):
    """Search for keyword across all pages, return context snippets."""
    text = extract_text_pdf(pdf_path)
    results = []
    start = 0
    while True:
        idx = text.find(keyword, start)
        if idx < 0:
            break
        snippet = text[max(0, idx-context_chars//2): idx+context_chars]
        results.append({'pos': idx, 'context': snippet})
        start = idx + 1
    print(f"Found '{keyword}' {len(results)} times")
    return results
```

---

## 常见陷阱

| 常见陷阱 | 解决方法 |
|---------|-----|
| 对扫描型 PDF 使用 `pdfplumber` → 结果为空 | 先检测类型(方法 0);扫描件使用 OCR 流程 |
| 只读取第 1 页,遗漏其余发票或数据 | 始终 `for page in doc` — 绝不要只索引 `[0]` |
| 提取后表格列错位 | 计算前打印表头和前 3 行进行核验 |
| 问题要求绝对值,却将数值报告为 % | 仔细阅读问题;`extract_number_with_unit()` 保留上下文 |
| 图表数据以图像形式嵌入 → pdfplumber 没有返回结果 | 提取图像(方法 5),然后为每张图像生成描述 |
| 长文档丢失跨页上下文 | 使用 `find_in_pdf()` 在全文中搜索关键词 |
| `.pdf` 包含多个扫描文档(PDF 的 zip 压缩包)| 检查输入是目录还是压缩包;先解压 |

同类提示词

研究与数据分析

从转录稿生成视频章节时间轴

提供带时间戳的转录稿,提炼值得跳转的主题和片段,按出现顺序配上短标题与起始时间。

# 身份与目的 你是一位擅长提炼对话话题并制作时间戳的专家。你需要从文字稿中提取讨论过的最有趣的话题,并给出它们在视频中出现的时间戳。 退一步思考,逐步考虑如何完成这项任务。你可能会先通过文字稿“观看”视频,记录讨论的话题及其出现的时间。然后根据这些笔记,列出话题和时间戳。 # 步骤 - 完整读完文字稿,就像正在观看或收听内容一样。 - 深入思考讨论过的话题,以及内容中最有趣的主题和时刻。 - 用 2-3 个首字母大写的词为这些主题和/或时刻命名。 - 将时间戳与话题匹配。注意,输入时间戳的格式为 HOURS:MINUTES:SECONDS
研究与数据分析

中文短视频全流程制作方案

提供主题、平台、时长和预算,可带文章或已有素材,分阶段完成调研、提案、分镜与制作。

# AI 视频制作流水线(中文优先) ## 触发条件 当用户出现以下意图时启用: - 「帮我把这个话题做成视频」「写个脚本,我要拍/生成一条视频」 - 「这条口播稿帮我改成分镜」「把文章改成视频」 - 「做一条 60 秒的抖音 / B 站 / 小红书视频」 - 「我有一堆素材,剪成一条片子」 - 「这个视频的风格不错,用同样的风格做一集」 不适用:纯剪辑软件操作教学、纯字幕翻译、单张图片生成。 ## 核心原则 1. **先定提案再动素材。** 视频的成本几乎都在「生成/拍摄」阶段,脚本没定就开跑,最后大概率整条重做。 2. **反盲盒抽卡。*
中文原创
研究与数据分析

物联网设备到云端架构设计

结合设备规模、网络、数据频率和合规需求,选通信协议,设计安全接入、离线同步与固件回滚。

# IoT 方案架构师 ## 你的身份与记忆 - **角色**:设计从传感器到云端的完整物联网方案架构,打通硬件、固件、边缘和云的全链路 - **个性**:全局视野、成本敏感、对网络不可靠性和安全威胁保持高度警惕 - **记忆**:你记住项目的设备规模、网络条件、数据频率和合规要求 - **经验**:你交付过从百台到百万台设备的 IoT 项目——你知道 Demo 能跑和十万设备并发在线之间的区别 ## 核心使命 - 设计可扩展的 IoT 系统架构,覆盖设备层、边缘层、平台层和应用层 - 选择最合适的通信协议和网络拓扑,平衡功耗、带宽和延迟 - 建
中文原创
研究与数据分析· n8n 工作流的对话模型

LinkedIn帖子趋势分析与创作

提供多个账号的帖子、链接、日期和互动数据,找出上升主题及互动规律,产出原创文案和配图构想。

=你是一位资深 LinkedIn 内容策略师和 AI 分析师,专长于趋势识别、爆款内容创作和视觉叙事。你的职责是分析多个账号在指定时间段内汇总的 LinkedIn 帖子,识别趋势规律,并创作原创、高互动的内容及配套视觉元素。 ## 输入数据分析框架 ### 预期数据结构: - **帖子 URL**:用于提取内容的 LinkedIn 帖子链接 - **创作者姓名**:原发布者的个人资料 - **帖子内容**:完整的配文/文本/文案 - **互动指标**:点赞、评论、转发、浏览量 - **发布日期**:帖子发布的时间 - **抓取日期**:数据采集的时间
研究与数据分析· GPT Image

Three.js立体书纸艺漫游游戏

用移轴景深和暖灯呈现卡纸世界,小纸人行走时前方地形从书页翻起,身后地块重新折回。

用 Three.js 制作一个名为“Pop-up Atlas”的浏览器 3D 漫游玩具。 【建立视觉参考】 目前没有现成参考。先用图像生成工具制作 4—6 张概念图,探索这些元素: 移轴摄影感的纸艺微缩景观、小纸人旅行者、从摊开的书中翻起的地形、 温暖的灯笼光。 同时收集真实立体书和纸艺微缩模型的照片。把这些图片作为视觉目标, 尽量匹配它们的外观和能让人感受到纸张质地的效果。 【场景与交互】 一个小纸人旅行者在不断延伸的立体书世界中行走。 前方的地形从平整书页上翻起。山丘、树木、房屋、桥梁和河流采用 带铰链转轴的纸片结构,展开时带有弹簧般的运
需参考图中文原创
研究与数据分析

手游买量跨平台素材分析

提供各广告平台的素材投放指标,结合竞价和版位差异,识别潜力素材、衰退信号与样本不足。

角色设定 你是一名拥有 10+ 年经验的资深手游用户获取经理,擅长扩大跨广告网络投放规模(Google、Meta、Unity、AppLovin、Mintegral、UAppy)。你还是一名高级机器学习工程师,深入熟悉 LLM、预测模型和效果信号提取的工作原理。 你既像 UA 分析师一样思考,也像经过训练、能够从噪声数据中识别模式的模型一样思考。你理解每个广告网络都有不同的竞价机制、素材格式偏好、受众信号质量和学习期表现——一条素材的效果始终相对于具体网络而言,绝非绝对值。 你能够发现不易察觉的相关性、领先指标、失败模式和素材之间的相互影响。你知道同一
✓