import os import subprocess import sys # ========================================== # 自动安装依赖模块 (确保在 Hugging Face 运行) # ========================================== def install_requirements(): try: import gradio from PIL import Image except ImportError: print("正在安装必要依赖,请稍候...") subprocess.check_call([sys.executable, "-m", "pip", "install", "gradio", "Pillow"]) print("依赖安装完成!") install_requirements() # ========================================== # 核心逻辑:图片切割与打包程序 # ========================================== import zipfile import shutil import gradio as gr from PIL import Image from datetime import datetime from pathlib import Path def split_and_zip(files): if not files: return None, "❌ 错误:请先上传图片!" # 1. 建立临时工作目录 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") work_dir = Path(f"process_{timestamp}") output_dir = work_dir / "panels" output_dir.mkdir(parents=True, exist_ok=True) all_output_paths = [] processed_count = 0 # 2. 遍历处理上传的所有图片 for file_obj in files: # file_obj 是一个文件路径字符串或具有 .name 属性的对象 file_path = file_obj.name if hasattr(file_obj, 'name') else file_obj original_name = Path(file_path).stem try: with Image.open(file_path) as img: # 转换为 RGB 模式防止 GIF/RGBA 报错 img = img.convert("RGB") width, height = img.size # 计算 3x3 九宫格的单元尺寸 panel_w = width // 3 panel_h = height // 3 # 3. 执行切割 (按行扫描:左上->中上->右上...) count = 1 for row in range(3): for col in range(3): left = col * panel_w upper = row * panel_h right = left + panel_w lower = upper + panel_h # 切割并保存 panel = img.crop((left, upper, right, lower)) save_filename = f"{original_name}_{count:02d}.jpg" save_path = output_dir / save_filename panel.save(save_path, quality=95) all_output_paths.append(save_path) count += 1 processed_count += 1 except Exception as e: print(f"处理 {original_name} 时出错: {str(e)}") # 4. 打包为 ZIP 文件 zip_name = f"split_images_{timestamp}.zip" zip_path = work_dir / zip_name with zipfile.ZipFile(zip_path, 'w') as zipf: for file in all_output_paths: zipf.write(file, arcname=file.name) status_msg = f"✅ 成功!已处理 {processed_count} 张原图,共生成 {len(all_output_paths)} 张分镜。" return str(zip_path), status_msg # ========================================== # Gradio 界面 UI 部分 # ========================================== with gr.Blocks(title="9宫格分镜切割器", theme=gr.themes.Soft()) as demo: gr.Markdown(""" # 🎬 9宫格分镜图自动切割工具 **使用方法:** 1. 在下方上传 Midjourney 生成的 **3x3 无缝拼贴图**(支持多图)。 2. 点击 **[开始切割并打包]**。 3. 在右侧下载生成的 **ZIP 压缩包**。 """) with gr.Row(): with gr.Column(scale=1): input_files = gr.File( label="上传九宫格原图", file_count="multiple", file_types=["image"] ) run_btn = gr.Button("🚀 开始切割并打包", variant="primary") with gr.Column(scale=1): status_output = gr.Textbox(label="状态反馈", placeholder="等待任务开始...") download_file = gr.File(label="📦 点击此处下载 ZIP") run_btn.click( fn=split_and_zip, inputs=input_files, outputs=[download_file, status_output] ) gr.Markdown("---") gr.HTML("

适合 9:16 分镜工作流 | 支持 Python 自动化批处理

") # 启动服务 if __name__ == "__main__": demo.launch()