475 lines
16 KiB
Python
475 lines
16 KiB
Python
from __future__ import annotations
|
||
|
||
import base64
|
||
import hashlib
|
||
import io
|
||
import re
|
||
from pathlib import Path
|
||
|
||
from edkb_system.contracts import Block, Context
|
||
from edkb_system.skills.soffice_util import convert_with_soffice
|
||
|
||
|
||
def _to_data_uri(blob: bytes, content_type: str) -> str:
|
||
return f"data:{content_type};base64,{base64.b64encode(blob).decode('ascii')}"
|
||
|
||
|
||
def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path:
|
||
"""将 .ppt 转为 .pptx;soffice 超时由 soffice_util 控制。"""
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
proc = convert_with_soffice(
|
||
"soffice",
|
||
convert_to="pptx",
|
||
source_path=path,
|
||
out_dir=out_dir,
|
||
)
|
||
if proc.returncode != 0:
|
||
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
|
||
output = out_dir / f"{path.stem}.pptx"
|
||
if not output.exists():
|
||
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
|
||
return output
|
||
|
||
|
||
def _convert_presentation_to_pdf(path: Path, out_dir: Path) -> Path | None:
|
||
"""将演示文稿转为 PDF;失败或超时返回 None,由上层选择其它解析路径。"""
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
try:
|
||
proc = convert_with_soffice(
|
||
"soffice",
|
||
convert_to="pdf",
|
||
source_path=path,
|
||
out_dir=out_dir,
|
||
)
|
||
except FileNotFoundError:
|
||
return None
|
||
except RuntimeError:
|
||
return None
|
||
if proc.returncode != 0:
|
||
return None
|
||
output = out_dir / f"{path.stem}.pdf"
|
||
return output if output.exists() else None
|
||
|
||
|
||
def _export_slide_pngs(path: Path, out_dir: Path) -> dict[int, bytes]:
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
app = None
|
||
pres = None
|
||
output: dict[int, bytes] = {}
|
||
try:
|
||
from win32com.client import DispatchEx
|
||
|
||
app = DispatchEx("PowerPoint.Application")
|
||
pres = app.Presentations.Open(str(path), WithWindow=False)
|
||
for idx, slide in enumerate(pres.Slides, start=1):
|
||
target = out_dir / f"slide_{idx:03d}.png"
|
||
slide.Export(str(target), "PNG")
|
||
if target.exists():
|
||
output[idx] = target.read_bytes()
|
||
except Exception:
|
||
return {}
|
||
finally:
|
||
if pres is not None:
|
||
try:
|
||
pres.Close()
|
||
except Exception:
|
||
pass
|
||
if app is not None:
|
||
try:
|
||
app.Quit()
|
||
except Exception:
|
||
pass
|
||
return output
|
||
|
||
|
||
def _norm_text(text: str) -> str:
|
||
return "\n".join(x.strip() for x in (text or "").splitlines() if x.strip()).strip()
|
||
|
||
|
||
def _shape_bbox(shape) -> tuple[float, float, float, float]:
|
||
left = float(getattr(shape, "left", 0))
|
||
top = float(getattr(shape, "top", 0))
|
||
width = float(getattr(shape, "width", 0))
|
||
height = float(getattr(shape, "height", 0))
|
||
return (left, top, left + width, top + height)
|
||
|
||
|
||
def _image_pixel_size(blob: bytes) -> tuple[int, int]:
|
||
try:
|
||
from PIL import Image
|
||
|
||
with Image.open(io.BytesIO(blob)) as im:
|
||
return int(im.width), int(im.height)
|
||
except Exception:
|
||
return (0, 0)
|
||
|
||
|
||
def _is_small_decorative_image(
|
||
blob: bytes, bbox: tuple[float, float, float, float], slide_area: float
|
||
) -> bool:
|
||
width_px, height_px = _image_pixel_size(blob)
|
||
pixel_area = max(width_px, 0) * max(height_px, 0)
|
||
box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0)
|
||
if (
|
||
width_px
|
||
and height_px
|
||
and (width_px <= 48 or height_px <= 48 or pixel_area <= 6400)
|
||
):
|
||
return True
|
||
if slide_area > 0 and box_area / slide_area <= 0.015 and pixel_area <= 20000:
|
||
return True
|
||
return False
|
||
|
||
|
||
def _is_dominant_picture(
|
||
bbox: tuple[float, float, float, float], slide_area: float
|
||
) -> bool:
|
||
box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0)
|
||
if slide_area <= 0:
|
||
return False
|
||
return box_area / slide_area >= 0.45
|
||
|
||
|
||
def _table_to_markdown(table) -> str:
|
||
rows: list[list[str]] = []
|
||
for row in table.rows:
|
||
vals = [
|
||
" ".join(
|
||
p.text.strip() for p in cell.text_frame.paragraphs if p.text.strip()
|
||
)
|
||
for cell in row.cells
|
||
]
|
||
vals = [v.strip() for v in vals]
|
||
if any(vals):
|
||
rows.append(vals)
|
||
if not rows:
|
||
return ""
|
||
width = max(len(r) for r in rows)
|
||
norm = [r + [""] * (width - len(r)) for r in rows]
|
||
header = norm[0]
|
||
body = norm[1:]
|
||
lines = [
|
||
"| " + " | ".join(header) + " |",
|
||
"| " + " | ".join(["---"] * width) + " |",
|
||
]
|
||
lines.extend("| " + " | ".join(r) + " |" for r in body)
|
||
return "\n".join(lines)
|
||
|
||
|
||
def _render_pdf_page_png(
|
||
pdf_path: Path, page_number: int, scale: float = 2.0
|
||
) -> bytes | None:
|
||
try:
|
||
import pypdfium2 as pdfium
|
||
except Exception:
|
||
return None
|
||
|
||
doc = None
|
||
try:
|
||
doc = pdfium.PdfDocument(str(pdf_path))
|
||
page = doc[page_number - 1]
|
||
bitmap = page.render(scale=scale)
|
||
pil_image = bitmap.to_pil()
|
||
buf = io.BytesIO()
|
||
pil_image.save(buf, format="PNG")
|
||
return buf.getvalue()
|
||
except Exception:
|
||
return None
|
||
finally:
|
||
try:
|
||
if doc is not None:
|
||
doc.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _crop_rendered_region(
|
||
rendered: bytes,
|
||
*,
|
||
crop_bbox: tuple[float, float, float, float],
|
||
slide_width: float,
|
||
slide_height: float,
|
||
padding: float = 0.03,
|
||
) -> bytes | None:
|
||
try:
|
||
from PIL import Image
|
||
|
||
with Image.open(io.BytesIO(rendered)) as im:
|
||
x0, y0, x1, y1 = crop_bbox
|
||
pad_x = slide_width * padding
|
||
pad_y = slide_height * padding
|
||
x0 = max(0.0, x0 - pad_x)
|
||
y0 = max(0.0, y0 - pad_y)
|
||
x1 = min(slide_width, x1 + pad_x)
|
||
y1 = min(slide_height, y1 + pad_y)
|
||
if x1 <= x0 or y1 <= y0:
|
||
return None
|
||
scale_x = im.width / max(slide_width, 1.0)
|
||
scale_y = im.height / max(slide_height, 1.0)
|
||
box = (
|
||
int(x0 * scale_x),
|
||
int(y0 * scale_y),
|
||
int(x1 * scale_x),
|
||
int(y1 * scale_y),
|
||
)
|
||
cropped = im.crop(box)
|
||
buf = io.BytesIO()
|
||
cropped.save(buf, format="PNG")
|
||
return buf.getvalue()
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def _union_bboxes(
|
||
boxes: list[tuple[float, float, float, float]],
|
||
) -> tuple[float, float, float, float] | None:
|
||
if not boxes:
|
||
return None
|
||
x0 = min(b[0] for b in boxes)
|
||
y0 = min(b[1] for b in boxes)
|
||
x1 = max(b[2] for b in boxes)
|
||
y1 = max(b[3] for b in boxes)
|
||
return (x0, y0, x1, y1)
|
||
|
||
|
||
def _bbox_overlap_ratio(
|
||
a: tuple[float, float, float, float], b: tuple[float, float, float, float]
|
||
) -> float:
|
||
ax0, ay0, ax1, ay1 = a
|
||
bx0, by0, bx1, by1 = b
|
||
ix0 = max(ax0, bx0)
|
||
iy0 = max(ay0, by0)
|
||
ix1 = min(ax1, bx1)
|
||
iy1 = min(ay1, by1)
|
||
if ix1 <= ix0 or iy1 <= iy0:
|
||
return 0.0
|
||
inter = (ix1 - ix0) * (iy1 - iy0)
|
||
area = max((ax1 - ax0) * (ay1 - ay0), 1.0)
|
||
return inter / area
|
||
|
||
|
||
def _pick_slide_title(flat_shapes) -> str:
|
||
candidates: list[tuple[float, float, str]] = []
|
||
for shape in flat_shapes:
|
||
if not getattr(shape, "has_text_frame", False):
|
||
continue
|
||
txt = _norm_text(getattr(shape, "text", ""))
|
||
if not txt:
|
||
continue
|
||
top = float(getattr(shape, "top", 0))
|
||
left = float(getattr(shape, "left", 0))
|
||
candidates.append((top, left, txt))
|
||
if not candidates:
|
||
return ""
|
||
candidates.sort(key=lambda x: (x[0], x[1]))
|
||
preferred_pat = re.compile(r"^(?:[一二三四五六七八九十]+、|\d+(?:\.\d+){0,2})")
|
||
for top, left, txt in candidates[:6]:
|
||
first_line = txt.splitlines()[0].strip()
|
||
if preferred_pat.match(first_line) and top <= 1200000:
|
||
return first_line
|
||
for top, left, txt in candidates[:6]:
|
||
first_line = txt.splitlines()[0].strip()
|
||
if 2 <= len(first_line) <= 30 and top <= 1800000:
|
||
return first_line
|
||
return candidates[0][2].splitlines()[0].strip()
|
||
|
||
|
||
def _iter_shapes(shapes):
|
||
from pptx.enum.shapes import MSO_SHAPE_TYPE
|
||
|
||
for shape in shapes:
|
||
yield shape
|
||
if getattr(shape, "shape_type", None) == MSO_SHAPE_TYPE.GROUP:
|
||
for child in _iter_shapes(shape.shapes):
|
||
yield child
|
||
|
||
|
||
def run(input_data: dict, context: Context) -> list[Block]:
|
||
file_path = Path(input_data["file_path"])
|
||
work_dir = Path(input_data["work_dir"])
|
||
if file_path.suffix.lower() == ".ppt":
|
||
file_path = _convert_ppt_to_pptx(file_path, work_dir)
|
||
|
||
from pptx import Presentation
|
||
from pptx.enum.shapes import MSO_SHAPE_TYPE
|
||
|
||
prs = Presentation(str(file_path))
|
||
slide_pngs = _export_slide_pngs(file_path, work_dir / f"{file_path.stem}_slides")
|
||
pdf_path = None if slide_pngs else _convert_presentation_to_pdf(file_path, work_dir)
|
||
context.pages = len(prs.slides)
|
||
blocks: list[Block] = []
|
||
img_idx = 0
|
||
blk_idx = 0
|
||
slide_area = float(prs.slide_width) * float(prs.slide_height)
|
||
|
||
for slide_no, slide in enumerate(prs.slides, start=1):
|
||
flat_shapes = list(_iter_shapes(slide.shapes))
|
||
title_text = _norm_text(
|
||
getattr(getattr(slide.shapes, "title", None), "text", "")
|
||
)
|
||
if not title_text:
|
||
title_text = _pick_slide_title(flat_shapes)
|
||
heading_text = f"第{slide_no}页"
|
||
if title_text:
|
||
heading_text = f"第{slide_no}页 {title_text}"
|
||
blk_idx += 1
|
||
blocks.append(
|
||
Block(
|
||
id=f"pptx-{slide_no}-heading-{blk_idx}",
|
||
page=slide_no,
|
||
type="heading",
|
||
text=heading_text,
|
||
bbox=(0.0, 0.0, 0.0, 0.0),
|
||
)
|
||
)
|
||
|
||
seen_image_hashes: set[str] = set()
|
||
dominant_pictures = 0
|
||
shape_heavy = 0
|
||
flow_boxes: list[tuple[float, float, float, float]] = []
|
||
suppress_all_images = title_text == "目录"
|
||
|
||
for shape in flat_shapes:
|
||
try:
|
||
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
|
||
image = shape.image
|
||
bbox = _shape_bbox(shape)
|
||
blob_hash = hashlib.sha1(image.blob).hexdigest()
|
||
if blob_hash in seen_image_hashes:
|
||
continue
|
||
seen_image_hashes.add(blob_hash)
|
||
if _is_small_decorative_image(image.blob, bbox, slide_area):
|
||
continue
|
||
if _is_dominant_picture(bbox, slide_area):
|
||
dominant_pictures += 1
|
||
elif shape.shape_type in {
|
||
MSO_SHAPE_TYPE.AUTO_SHAPE,
|
||
MSO_SHAPE_TYPE.LINE,
|
||
MSO_SHAPE_TYPE.FREEFORM,
|
||
}:
|
||
shape_heavy += 1
|
||
bbox = _shape_bbox(shape)
|
||
mid_x = (bbox[0] + bbox[2]) / 2.0
|
||
if (
|
||
bbox[2] > bbox[0]
|
||
and bbox[3] > bbox[1]
|
||
and mid_x >= float(prs.slide_width) * 0.18
|
||
):
|
||
flow_boxes.append(bbox)
|
||
except Exception as exc:
|
||
context.warnings.append(f"pptx picture skipped: {exc}")
|
||
|
||
seen_image_hashes.clear()
|
||
render_flow_focus = (
|
||
(not suppress_all_images)
|
||
and bool(slide_pngs or pdf_path)
|
||
and shape_heavy >= 8
|
||
and dominant_pictures == 0
|
||
)
|
||
flow_crop: tuple[float, float, float, float] | None = None
|
||
if render_flow_focus:
|
||
rendered = slide_pngs.get(slide_no)
|
||
if rendered is None and pdf_path is not None:
|
||
rendered = _render_pdf_page_png(pdf_path, slide_no)
|
||
if rendered:
|
||
flow_crop = (0.0, 0.0, float(prs.slide_width), float(prs.slide_height))
|
||
img_idx += 1
|
||
blocks.append(
|
||
Block(
|
||
id=f"pptx-flow-{slide_no}-{img_idx}",
|
||
page=slide_no,
|
||
type="image",
|
||
text="",
|
||
bbox=flow_crop,
|
||
meta={
|
||
"data_uri": _to_data_uri(rendered, "image/png"),
|
||
"flow_focus": True,
|
||
"flow_focus_source": "pptx",
|
||
"rendered_slide": True,
|
||
},
|
||
)
|
||
)
|
||
|
||
for shape in flat_shapes:
|
||
try:
|
||
if getattr(shape, "has_table", False):
|
||
table_md = _table_to_markdown(shape.table)
|
||
if table_md:
|
||
blk_idx += 1
|
||
blocks.append(
|
||
Block(
|
||
id=f"pptx-{slide_no}-table-{blk_idx}",
|
||
page=slide_no,
|
||
type="table",
|
||
text=table_md,
|
||
bbox=_shape_bbox(shape),
|
||
)
|
||
)
|
||
continue
|
||
|
||
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
|
||
if render_flow_focus or suppress_all_images:
|
||
continue
|
||
is_dominant = False
|
||
image = shape.image
|
||
bbox = _shape_bbox(shape)
|
||
blob_hash = hashlib.sha1(image.blob).hexdigest()
|
||
if blob_hash in seen_image_hashes:
|
||
continue
|
||
seen_image_hashes.add(blob_hash)
|
||
if _is_small_decorative_image(image.blob, bbox, slide_area):
|
||
continue
|
||
is_dominant = _is_dominant_picture(bbox, slide_area)
|
||
img_idx += 1
|
||
ext = (getattr(image, "ext", "png") or "png").lower()
|
||
ct = f"image/{'jpeg' if ext == 'jpg' else ext}"
|
||
meta: dict[str, object] = {
|
||
"data_uri": _to_data_uri(image.blob, ct),
|
||
"blob_sha1": blob_hash,
|
||
}
|
||
if is_dominant:
|
||
meta["page_image"] = True
|
||
meta["page_image_source"] = "pptx"
|
||
blocks.append(
|
||
Block(
|
||
id=f"pptx-img-{slide_no}-{img_idx}",
|
||
page=slide_no,
|
||
type="image",
|
||
text="",
|
||
bbox=bbox,
|
||
meta=meta,
|
||
)
|
||
)
|
||
continue
|
||
|
||
if getattr(shape, "has_text_frame", False):
|
||
txt = _norm_text(shape.text)
|
||
bbox = _shape_bbox(shape)
|
||
if not txt or txt == title_text:
|
||
continue
|
||
if title_text and txt.startswith(title_text):
|
||
txt = txt[len(title_text) :].lstrip("\n ::;;,,")
|
||
txt = _norm_text(txt)
|
||
if not txt:
|
||
continue
|
||
if re.fullmatch(r"\d+", txt):
|
||
continue
|
||
if flow_crop is not None and len(txt) <= 28:
|
||
continue
|
||
if txt and txt != title_text:
|
||
blk_idx += 1
|
||
blocks.append(
|
||
Block(
|
||
id=f"pptx-{slide_no}-text-{blk_idx}",
|
||
page=slide_no,
|
||
type="paragraph",
|
||
text=txt,
|
||
bbox=bbox,
|
||
)
|
||
)
|
||
except Exception as exc:
|
||
context.warnings.append(f"pptx shape skipped: {exc}")
|
||
|
||
context.extras["slides_count"] = len(prs.slides)
|
||
return blocks
|