Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,7 @@ import numpy as np
|
|
| 3 |
import fitz # PyMuPDF
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
-
#
|
| 7 |
OUTPUT_DIR = "output"
|
| 8 |
ZIP_PATH = os.path.join(OUTPUT_DIR, "results.zip")
|
| 9 |
BG_PATH = "background.jpg"
|
|
@@ -11,14 +11,14 @@ TARGET_WIDTH, TARGET_HEIGHT = 2133, 1200
|
|
| 11 |
POS1 = (1032, 0)
|
| 12 |
POS2 = (4666, 0)
|
| 13 |
|
| 14 |
-
#
|
| 15 |
def ensure_dir(path):
|
| 16 |
os.makedirs(path, exist_ok=True)
|
| 17 |
if not os.access(path, os.W_OK):
|
| 18 |
-
raise RuntimeError(f"❌ 無法寫入
|
| 19 |
ensure_dir(OUTPUT_DIR)
|
| 20 |
|
| 21 |
-
# PDF轉圖片
|
| 22 |
def pdf_to_images(file):
|
| 23 |
images = []
|
| 24 |
doc = fitz.open(file.name)
|
|
@@ -28,7 +28,7 @@ def pdf_to_images(file):
|
|
| 28 |
images.append(img)
|
| 29 |
return images
|
| 30 |
|
| 31 |
-
# 合成
|
| 32 |
def overlay_image(bg, fg_img, x, y):
|
| 33 |
fg = cv2.resize(np.array(fg_img), (TARGET_WIDTH, TARGET_HEIGHT), interpolation=cv2.INTER_AREA)
|
| 34 |
if fg.shape[2] == 4:
|
|
@@ -41,11 +41,11 @@ def overlay_image(bg, fg_img, x, y):
|
|
| 41 |
bg[y:y+TARGET_HEIGHT, x:x+TARGET_WIDTH] = fg
|
| 42 |
return bg
|
| 43 |
|
| 44 |
-
#
|
| 45 |
def process_and_combine(images, prefix):
|
| 46 |
bg = cv2.imread(BG_PATH)
|
| 47 |
if bg is None:
|
| 48 |
-
raise gr.Error("❌
|
| 49 |
|
| 50 |
for f in os.listdir(OUTPUT_DIR):
|
| 51 |
if f.endswith(".jpg"):
|
|
@@ -63,46 +63,45 @@ def process_and_combine(images, prefix):
|
|
| 63 |
gc.collect()
|
| 64 |
|
| 65 |
if not results:
|
| 66 |
-
raise gr.Error("⚠️ 沒有生
|
| 67 |
|
| 68 |
with zipfile.ZipFile(ZIP_PATH, "w", zipfile.ZIP_DEFLATED) as zipf:
|
| 69 |
for f in sorted(os.listdir(OUTPUT_DIR)):
|
| 70 |
if f.endswith(".jpg"):
|
| 71 |
zipf.write(os.path.join(OUTPUT_DIR, f), arcname=f)
|
| 72 |
|
| 73 |
-
return results, ZIP_PATH, f"✅ 合成
|
| 74 |
|
| 75 |
-
#
|
| 76 |
def process_inputs(files, prefix):
|
| 77 |
prefix = prefix.strip() or "result_"
|
| 78 |
images = []
|
| 79 |
-
|
| 80 |
for file in files:
|
| 81 |
name = file.name.lower()
|
| 82 |
if name.endswith(".pdf"):
|
| 83 |
images.extend(pdf_to_images(file))
|
| 84 |
-
elif name.endswith((".
|
| 85 |
img = Image.open(file).convert("RGBA")
|
| 86 |
images.append(img)
|
| 87 |
else:
|
| 88 |
raise gr.Error(f"不支援的檔案格式:{name}")
|
| 89 |
return process_and_combine(images, prefix)
|
| 90 |
|
| 91 |
-
# Gradio
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
gr.
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
gr.
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
)
|
| 106 |
|
| 107 |
if __name__ == "__main__":
|
| 108 |
-
|
|
|
|
| 3 |
import fitz # PyMuPDF
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
+
# 設定常數
|
| 7 |
OUTPUT_DIR = "output"
|
| 8 |
ZIP_PATH = os.path.join(OUTPUT_DIR, "results.zip")
|
| 9 |
BG_PATH = "background.jpg"
|
|
|
|
| 11 |
POS1 = (1032, 0)
|
| 12 |
POS2 = (4666, 0)
|
| 13 |
|
| 14 |
+
# 檢查並建立資料夾
|
| 15 |
def ensure_dir(path):
|
| 16 |
os.makedirs(path, exist_ok=True)
|
| 17 |
if not os.access(path, os.W_OK):
|
| 18 |
+
raise RuntimeError(f"❌ 無法寫入:{path}")
|
| 19 |
ensure_dir(OUTPUT_DIR)
|
| 20 |
|
| 21 |
+
# PDF 轉圖片(PyMuPDF)
|
| 22 |
def pdf_to_images(file):
|
| 23 |
images = []
|
| 24 |
doc = fitz.open(file.name)
|
|
|
|
| 28 |
images.append(img)
|
| 29 |
return images
|
| 30 |
|
| 31 |
+
# 圖像合成功能
|
| 32 |
def overlay_image(bg, fg_img, x, y):
|
| 33 |
fg = cv2.resize(np.array(fg_img), (TARGET_WIDTH, TARGET_HEIGHT), interpolation=cv2.INTER_AREA)
|
| 34 |
if fg.shape[2] == 4:
|
|
|
|
| 41 |
bg[y:y+TARGET_HEIGHT, x:x+TARGET_WIDTH] = fg
|
| 42 |
return bg
|
| 43 |
|
| 44 |
+
# 主處理邏輯
|
| 45 |
def process_and_combine(images, prefix):
|
| 46 |
bg = cv2.imread(BG_PATH)
|
| 47 |
if bg is None:
|
| 48 |
+
raise gr.Error("❌ 無法讀取 background.jpg")
|
| 49 |
|
| 50 |
for f in os.listdir(OUTPUT_DIR):
|
| 51 |
if f.endswith(".jpg"):
|
|
|
|
| 63 |
gc.collect()
|
| 64 |
|
| 65 |
if not results:
|
| 66 |
+
raise gr.Error("⚠️ 沒有產生圖片")
|
| 67 |
|
| 68 |
with zipfile.ZipFile(ZIP_PATH, "w", zipfile.ZIP_DEFLATED) as zipf:
|
| 69 |
for f in sorted(os.listdir(OUTPUT_DIR)):
|
| 70 |
if f.endswith(".jpg"):
|
| 71 |
zipf.write(os.path.join(OUTPUT_DIR, f), arcname=f)
|
| 72 |
|
| 73 |
+
return results, ZIP_PATH, f"✅ 共合成 {len(results)} 張圖片,已打包 ZIP"
|
| 74 |
|
| 75 |
+
# 處理輸入
|
| 76 |
def process_inputs(files, prefix):
|
| 77 |
prefix = prefix.strip() or "result_"
|
| 78 |
images = []
|
|
|
|
| 79 |
for file in files:
|
| 80 |
name = file.name.lower()
|
| 81 |
if name.endswith(".pdf"):
|
| 82 |
images.extend(pdf_to_images(file))
|
| 83 |
+
elif name.endswith((".png", ".jpg", ".jpeg")):
|
| 84 |
img = Image.open(file).convert("RGBA")
|
| 85 |
images.append(img)
|
| 86 |
else:
|
| 87 |
raise gr.Error(f"不支援的檔案格式:{name}")
|
| 88 |
return process_and_combine(images, prefix)
|
| 89 |
|
| 90 |
+
# Gradio Blocks UI
|
| 91 |
+
with gr.Blocks(title="PDF與圖片合成工具") as demo:
|
| 92 |
+
gr.Markdown("### 📄🖼️ PDF / 圖片 雙輸入合成工具(背景為 7872x1200)")
|
| 93 |
+
|
| 94 |
+
with gr.Row():
|
| 95 |
+
files = gr.Files(label="📎 上傳 PDF 或圖片", file_types=[".pdf", ".jpg", ".jpeg", ".png"])
|
| 96 |
+
prefix = gr.Textbox(label="輸出檔名前綴", placeholder="例如:poster_", value="result_")
|
| 97 |
+
run_btn = gr.Button("🚀 開始合成", variant="primary")
|
| 98 |
+
|
| 99 |
+
with gr.Row():
|
| 100 |
+
gallery = gr.Gallery(label="🖼️ 預覽", columns=3, height="auto")
|
| 101 |
+
zip_file = gr.File(label="⬇️ 下載 ZIP")
|
| 102 |
+
log = gr.Textbox(label="📄 日誌", interactive=False)
|
| 103 |
+
|
| 104 |
+
run_btn.click(fn=process_inputs, inputs=[files, prefix], outputs=[gallery, zip_file, log])
|
| 105 |
|
| 106 |
if __name__ == "__main__":
|
| 107 |
+
demo.launch()
|