junjiro1129 commited on
Commit
2aac19e
·
verified ·
1 Parent(s): 444b4e3

Add Streamlit app

Browse files
Files changed (4) hide show
  1. app.py +174 -0
  2. apt.txt +2 -0
  3. hf.yml +2 -0
  4. requirements.txt +0 -0
app.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import zipfile
3
+ import tempfile
4
+ import shutil
5
+ import os
6
+ import json
7
+ from PIL import Image
8
+ import numpy as np
9
+ import cv2
10
+ from io import BytesIO
11
+
12
+ st.set_page_config(page_title="MOCKJET – 100+ Mockups in Seconds", layout="wide")
13
+ st.title("🚀 MOCKJET - 100+ Mockups in Seconds")
14
+ st.write("Upload your base mockups and design images to generate product mockups in seconds!")
15
+
16
+ # --- ファイル保存用ディレクトリ
17
+ TMP_ROOT = tempfile.mkdtemp()
18
+ BASES_DIR = os.path.join(TMP_ROOT, "bases")
19
+ DESIGNS_DIR = os.path.join(TMP_ROOT, "designs")
20
+ OUT_DIR = os.path.join(TMP_ROOT, "out")
21
+ os.makedirs(BASES_DIR, exist_ok=True)
22
+ os.makedirs(DESIGNS_DIR, exist_ok=True)
23
+ os.makedirs(OUT_DIR, exist_ok=True)
24
+
25
+ # --- Helper: 画像ファイル保存
26
+ def save_uploaded_files(files, save_dir):
27
+ valid_ext = [".png", ".jpg", ".jpeg"]
28
+ saved_paths = []
29
+ for uploaded_file in files:
30
+ fname = uploaded_file.name
31
+ ext = os.path.splitext(fname)[1].lower()
32
+ if ext in valid_ext:
33
+ out_path = os.path.join(save_dir, fname)
34
+ with open(out_path, "wb") as f:
35
+ f.write(uploaded_file.getbuffer())
36
+ saved_paths.append(out_path)
37
+ elif ext == ".zip":
38
+ # ZIP解凍
39
+ with zipfile.ZipFile(uploaded_file, "r") as zip_ref:
40
+ for zipinfo in zip_ref.infolist():
41
+ ext2 = os.path.splitext(zipinfo.filename)[1].lower()
42
+ if ext2 in valid_ext:
43
+ zip_ref.extract(zipinfo, save_dir)
44
+ saved_paths.append(os.path.join(save_dir, zipinfo.filename))
45
+ return saved_paths
46
+
47
+ # --- ファイルアップロードUI
48
+ st.header("Upload Mockup Bases (ZIP or PNG/JPG/JPEG files)")
49
+ bases_files = st.file_uploader("Upload base files", type=["png", "jpg", "jpeg", "zip"], accept_multiple_files=True)
50
+
51
+ st.header("Upload Design Images (.png, .jpg, .jpeg)")
52
+ design_files = st.file_uploader("Upload design files", type=["png", "jpg", "jpeg"], accept_multiple_files=True)
53
+
54
+ st.header("Upload templates.json (coordinates of print area)")
55
+ templates_file = st.file_uploader("Upload templates.json", type=["json"])
56
+
57
+ # --- ファイル保存
58
+ bases_paths, designs_paths = [], []
59
+ if bases_files:
60
+ bases_paths = save_uploaded_files(bases_files, BASES_DIR)
61
+ if design_files:
62
+ designs_paths = save_uploaded_files(design_files, DESIGNS_DIR)
63
+
64
+ # --- templates.jsonロード
65
+ templates = None
66
+ if templates_file is not None:
67
+ templates = json.load(templates_file)
68
+
69
+ # --- 画像表示
70
+ if bases_paths:
71
+ st.subheader("Mockup Bases")
72
+ num_cols = 6
73
+ cols = st.columns(num_cols)
74
+ for idx, img_path in enumerate(bases_paths):
75
+ with cols[idx % num_cols]:
76
+ st.image(img_path, caption=os.path.basename(img_path), width=180)
77
+
78
+ if designs_paths:
79
+ st.subheader("Design Images")
80
+ num_cols2 = 6
81
+ cols2 = st.columns(num_cols2)
82
+ for idx, img_path in enumerate(designs_paths):
83
+ with cols2[idx % num_cols2]:
84
+ st.image(img_path, caption=os.path.basename(img_path), width=180)
85
+
86
+ # --- 縦横比維持でワープ貼付
87
+ def warp_design_onto_mockup_fit(base_img, design_img, coords):
88
+ base_cv = np.array(base_img.convert("RGBA"))
89
+ design_cv = np.array(design_img.convert("RGBA"))
90
+ h_des, w_des = design_cv.shape[:2]
91
+
92
+ pts_dst = np.array(coords, dtype=np.float32)
93
+
94
+ # 外接長方形
95
+ widthA = np.linalg.norm(pts_dst[0] - pts_dst[1])
96
+ widthB = np.linalg.norm(pts_dst[3] - pts_dst[2])
97
+ maxWidth = int(max(widthA, widthB))
98
+
99
+ heightA = np.linalg.norm(pts_dst[0] - pts_dst[3])
100
+ heightB = np.linalg.norm(pts_dst[1] - pts_dst[2])
101
+ maxHeight = int(max(heightA, heightB))
102
+
103
+ # デザイン画像をアスペクト比維持でフィット
104
+ scale = min(maxWidth / w_des, maxHeight / h_des)
105
+ new_w = int(w_des * scale)
106
+ new_h = int(h_des * scale)
107
+ design_resized = cv2.resize(design_cv, (new_w, new_h), interpolation=cv2.INTER_AREA)
108
+
109
+ # 背景透明画像を中央配置
110
+ design_bg = np.zeros((maxHeight, maxWidth, 4), dtype=np.uint8)
111
+ x_offset = (maxWidth - new_w) // 2
112
+ y_offset = (maxHeight - new_h) // 2
113
+ design_bg[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = design_resized
114
+
115
+ pts_src = np.array([[0,0],[maxWidth-1,0],[maxWidth-1,maxHeight-1],[0,maxHeight-1]], dtype=np.float32)
116
+
117
+ M = cv2.getPerspectiveTransform(pts_src, pts_dst)
118
+ warped = cv2.warpPerspective(design_bg, M, (base_cv.shape[1], base_cv.shape[0]), borderMode=cv2.BORDER_TRANSPARENT)
119
+
120
+ mask = warped[:,:,3] > 0
121
+ base_cv[mask] = warped[mask]
122
+ return Image.fromarray(base_cv)
123
+
124
+ # --- モックアップ生成
125
+ output_images = []
126
+ if st.button("Generate Mockups") and bases_paths and designs_paths and templates:
127
+ st.info("Generating mockups... Please wait.")
128
+
129
+ for base_path in bases_paths:
130
+ base_name = os.path.basename(base_path)
131
+ if base_name not in templates:
132
+ st.warning(f"{base_name} is not found in templates.json, skipping.")
133
+ continue
134
+ coords = templates[base_name]['print_area']
135
+ # [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]
136
+ if isinstance(coords[0], dict):
137
+ # もしdict形式なら変換
138
+ coords = [[p[0], p[1]] for p in coords.values()]
139
+ elif isinstance(coords[0], list):
140
+ coords = coords
141
+ else:
142
+ st.warning("Invalid coords format.")
143
+ continue
144
+
145
+ for design_path in designs_paths:
146
+ base_img = Image.open(base_path).convert("RGBA")
147
+ design_img = Image.open(design_path).convert("RGBA")
148
+ result_img = warp_design_onto_mockup_fit(base_img, design_img, coords)
149
+ result_name = f"{os.path.splitext(base_name)[0]}_{os.path.splitext(os.path.basename(design_path))[0]}.png"
150
+ result_path = os.path.join(OUT_DIR, result_name)
151
+ result_img.save(result_path)
152
+ output_images.append(result_path)
153
+
154
+ st.success(f"Generated {len(output_images)} mockup images!")
155
+
156
+ # --- 生成画像表示&ZIPダウンロード
157
+ if output_images:
158
+ st.subheader("Generated Mockups")
159
+ cols3 = st.columns(min(len(output_images), 4))
160
+ for idx, out_img in enumerate(output_images):
161
+ with cols3[idx % 4]:
162
+ st.image(out_img, caption=os.path.basename(out_img), width=180)
163
+
164
+ zip_buf = BytesIO()
165
+ with zipfile.ZipFile(zip_buf, "w") as zipf:
166
+ for img_path in output_images:
167
+ zipf.write(img_path, os.path.basename(img_path))
168
+ st.download_button("Download All as ZIP", zip_buf.getvalue(), file_name="mockups.zip", mime="application/zip")
169
+
170
+ # --- 後始末
171
+ def cleanup_tmp():
172
+ shutil.rmtree(TMP_ROOT, ignore_errors=True)
173
+ import atexit
174
+ atexit.register(cleanup_tmp)
apt.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ libgl1
2
+ libglib2.0-0
hf.yml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ sdk: streamlit
2
+ app_file: app.py
requirements.txt ADDED
Binary file (126 Bytes). View file