File size: 2,675 Bytes
4da5949
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, sys, shutil, subprocess, tempfile, uuid
from pathlib import Path
import gradio as gr

# 导入字体安装函数
from install_fonts import install_fonts_from_repository

BASE_DIR = Path(__file__).parent.resolve()
BINARY_PATH = BASE_DIR / "PptxToJpgZip"
os.chmod(BINARY_PATH, 0o755)  # 忽略异常

def _safe_name() -> str:
    """生成仅 ASCII 的临时文件名"""
    return f"input_{uuid.uuid4().hex}.pptx"

def convert_pptx_to_zip(pptx_file) -> str:
    """调用 PptxToJpgZip,把 PPTX 转成图片 ZIP;若仅有文件夹则自动 zip。"""
    tmpdir = Path(tempfile.mkdtemp())
    src = tmpdir / _safe_name()
    shutil.copy(pptx_file.name, src)

    # 调用外部可执行文件
    proc = subprocess.run(
        [str(BINARY_PATH), str(src)],
        cwd=tmpdir,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    if proc.returncode != 0:
        raise RuntimeError(
            f"PptxToJpgZip 失败,退出码 {proc.returncode}\n"
            f"stderr:\n{proc.stderr.decode(errors='ignore')}"
        )

    # ---- ① 优先找 *_images.zip ----
    zips = list(tmpdir.glob("*_images.zip"))
    if zips:
        return str(zips[0])

    # ---- ② 若无 ZIP,再找 *_images 目录,自动打包 ----
    img_dirs = [p for p in tmpdir.glob("*_images") if p.is_dir()]
    if img_dirs:
        folder = img_dirs[0]
        zip_path = folder.with_suffix(".zip")      # <name>_images.zip
        shutil.make_archive(zip_path.with_suffix(""), "zip", folder)
        return str(zip_path)

    # ---- ③ 仍没找到:列出 tmpdir 内容方便调试 ----
    contents = "\n".join(["  • " + p.name for p in tmpdir.iterdir()])
    raise FileNotFoundError(
        "未找到输出 ZIP,也未发现 *_images 文件夹。\n"
        f"临时目录内容:\n{contents}"
    )

# ----------------- Gradio UI 保持不变 ----------------- #
with gr.Blocks(title="PPTX→JPG→ZIP 转换器") as demo:
    gr.Markdown(
        """

# PPTX→JPG→ZIP  

上传 `.pptx`,后台调用 **PptxToJpgZip**,将每页导出为 JPG 并打包 ZIP。"""
    )
    with gr.Row():
        pptx_in = gr.File(label="上传 PPTX (.pptx)", file_types=[".pptx"])
        btn = gr.Button("开始转换")
    zip_out = gr.File(label="下载 ZIP 文件")
    btn.click(fn=convert_pptx_to_zip, inputs=pptx_in, outputs=zip_out)

if __name__ == "__main__":
    # 启动应用前安装字体(通过引用方式调用)
    install_fonts_from_repository()
    demo.launch(server_name="0.0.0.0", server_port=7860, share=False)