STLooo commited on
Commit
94182ca
·
verified ·
1 Parent(s): ea494fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -28
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"❌ 無法寫入資料夾:{path}")
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("❌ 找不到 background.jpg")
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"✅ 合成完成,共 {len(results)} 張圖片"
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((".jpg", ".jpeg", ".png")):
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
- iface = gr.Interface(
93
- fn=process_inputs,
94
- inputs=[
95
- gr.inputs.File(label="📎 上傳 PDF 或圖片", type="file", multiple=True),
96
- gr.inputs.Textbox(label="檔名前綴(可選)", default="result_"),
97
- ],
98
- outputs=[
99
- gr.outputs.Gallery(label="🖼️ 合成結果"),
100
- gr.outputs.File(label="⬇️ 下載 ZIP"),
101
- gr.outputs.Textbox(label="📄 處理日誌")
102
- ],
103
- title="PDF 圖像合成工具",
104
- description="📄🖼️ 支援上傳 PDF 或圖像,合成到固定背景圖中"
105
- )
106
 
107
  if __name__ == "__main__":
108
- iface.launch()
 
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()