소스 정보
- 저장소
- OpenSenseNova/SenseNova-Skills
- 최근 소스 활동
- 2026년 6월 4일 09:01
- 감지된 SKILL.md 언어
- 영어
- 스타
- 5,191
- 포크
- 378
설치 방법
기본적으로 소스를 먼저 확인하는 Prompt가 선택됩니다. 직접 명령으로 전환하거나 로컬 사본을 다운로드할 수도 있습니다.
소스 파일 검토
설치 여부를 결정하기 전에 SKILL.md와 SkillsMP에 표시된 보조 파일을 읽어 보세요.
메뉴
기본적으로 소스를 먼저 확인하는 Prompt가 선택됩니다. 직접 명령으로 전환하거나 로컬 사본을 다운로드할 수도 있습니다.
설치 여부를 결정하기 전에 SKILL.md와 SkillsMP에 표시된 보조 파일을 읽어 보세요.
SOC 직업 분류 기준
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
직접 명령은 검토 Prompt를 거치지 않습니다. 실행하기 전에 소스를 확인하세요.
npx skills add https://github.com/OpenSenseNova/SenseNova-Skills --skill pdf-analysis명령은 한 줄로 유지됩니다. 복사하기 전에 가로로 스크롤해 전체 내용을 확인하세요.
로컬 사본을 원하시나요? SkillsMP에서 현재 제공할 수 있는 파일을 다운로드하세요.
SKILL.md 표시 중
用于用户请求深度研究、系统性研究、竞品分析、方案对比、趋势分析或事实核查时。**遇到以下任一情况就主动使用本 skill,不要自行搜几条就回答**:①用户出现触发词:深度研究 / 深度调研 / 深入研究 / 全面研究 / 系统研究 / 调研 / 调查 / 尽调 / 行业研究 / 市场研究 / 竞品分析 / 政策研究 / 技术研究 / 趋势研究 / 事实核查 / 写一份研究报告 / 调研报告 / 深度报告 / research / deep research;②请求需要跨多来源取证、多维度对比、交叉验证才能给出可靠结论;③用户要求产出报告、白皮书、行业分析或尽调文档;④话题涉及最新政策/市场/产品/价格/法规,需要系统核查。无核验要求的简单常识问答不使用。模糊或宽泛的"研究/了解一下 X"也优先触发。仅不用于:一句话摘要、已给定单一来源的整理、纯文字润色改写。
用于用户希望推荐研究成品形式,或最终形式无法从需求中直接判断时。把需求解析为一个简短的 format 字符串,不创建格式文件或 schema。
用于学术调研、论文精读、相关工作梳理、百科知识查询和引用链追溯。
| name | pdf-analysis |
| description | PDF 文档解析。自动区分文字型 PDF 与扫描型 PDF,覆盖:文本/表格提取、多页全量扫描、嵌入图表 caption、单位感知数值计算。 |
Critical first step: determine whether the PDF has extractable text or is a scanned image. Never skip this — using the wrong parser wastes time and produces empty results.
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
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")
For PDFs with tables, pdfplumber gives better table structure than fitz:
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())
all_tables
For scanned PDFs (image-based pages), render each page as PNG and caption:
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 : chars extracted")
:
()
doc.close()
.join(all_text)
text = extract_scanned_pdf(pdf_path)
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}")
:
all_text.append()
doc_fitz.close()
.join(all_text)
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} → ")
doc.close()
image_paths
# 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")
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 千港元
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
| Pitfall | Fix |
|---|---|
Use pdfplumber on scanned PDF → empty result | Detect type first (Method 0); use OCR path for scanned |
| Only read page 1, miss remaining invoices/data | Always for page in doc — never index [0] only |
| Table columns misaligned after extraction | Print headers + first 3 rows to verify before computing |
| Report number as % when question asks absolute value | Read question carefully; extract_number_with_unit() preserves context |
| Chart data embedded as image → pdfplumber returns nothing | Extract images (Method 5), then caption each |
| Long doc loses cross-page context | Use find_in_pdf() for keyword search across full text |
.pdf contains multiple scanned docs (zip of PDFs) | Check if input is dir or archive; unzip first |