-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
249 lines (208 loc) · 7.91 KB
/
Copy pathapp.py
File metadata and controls
249 lines (208 loc) · 7.91 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
from flask import Flask, request, render_template, send_file
from PIL import Image, ImageOps
from io import BytesIO
from dotenv import load_dotenv
import requests
import cloudinary
import cloudinary.exceptions
import cloudinary.uploader
import cloudinary.utils
import os
app = Flask(__name__)
load_dotenv()
REMOVE_BG_API_KEY = os.getenv("REMOVE_BG_API_KEY")
CLOUDINARY_CLOUD_NAME = os.getenv("CLOUDINARY_CLOUD_NAME")
CLOUDINARY_API_KEY = os.getenv("CLOUDINARY_API_KEY")
CLOUDINARY_API_SECRET = os.getenv("CLOUDINARY_API_SECRET")
REQUIRED_CONFIG = {
"REMOVE_BG_API_KEY": REMOVE_BG_API_KEY,
"CLOUDINARY_CLOUD_NAME": CLOUDINARY_CLOUD_NAME,
"CLOUDINARY_API_KEY": CLOUDINARY_API_KEY,
"CLOUDINARY_API_SECRET": CLOUDINARY_API_SECRET,
}
cloudinary.config(
cloud_name=CLOUDINARY_CLOUD_NAME,
api_key=CLOUDINARY_API_KEY,
api_secret=CLOUDINARY_API_SECRET,
)
@app.route("/")
def index():
return render_template("index.html")
def process_single_image(input_image_bytes):
"""Remove background, enhance, and return a ready-to-paste passport PIL image."""
# Step 1: Background removal
try:
response = requests.post(
"https://api.remove.bg/v1.0/removebg",
files={"image_file": input_image_bytes},
data={"size": "auto"},
headers={"X-Api-Key": REMOVE_BG_API_KEY},
timeout=60,
)
except requests.RequestException as exc:
raise ValueError("remove_bg_network_error") from exc
if response.status_code != 200:
try:
error_info = response.json()
if error_info.get("errors"):
error_code = error_info["errors"][0].get("code", "unknown_error")
raise ValueError(f"bg_removal_failed:{error_code}:{response.status_code}")
except ValueError:
raise
except Exception:
pass
raise ValueError(f"bg_removal_failed:unknown:{response.status_code}")
bg_removed = BytesIO(response.content)
img = Image.open(bg_removed)
if img.mode in ("RGBA", "LA"):
background = Image.new("RGB", img.size, (255, 255, 255))
background.paste(img, mask=img.split()[-1])
processed_img = background
else:
processed_img = img.convert("RGB")
# Step 2: Upload to Cloudinary
buffer = BytesIO()
processed_img.save(buffer, format="PNG")
buffer.seek(0)
try:
upload_result = cloudinary.uploader.upload(buffer, resource_type="image")
except cloudinary.exceptions.AuthorizationRequired as exc:
raise ValueError("cloudinary_auth_failed") from exc
except cloudinary.exceptions.Error as exc:
raise ValueError("cloudinary_upload_failed") from exc
image_url = upload_result.get("secure_url")
public_id = upload_result.get("public_id")
if not image_url:
raise ValueError("cloudinary_upload_failed")
# Step 3: Enhance via Cloudinary AI
enhanced_url = cloudinary.utils.cloudinary_url(
public_id,
transformation=[
{"effect": "gen_restore"},
{"quality": "auto"},
{"fetch_format": "auto"},
],
)[0]
try:
enhanced_response = requests.get(enhanced_url, timeout=60)
enhanced_response.raise_for_status()
except requests.RequestException as exc:
raise ValueError("cloudinary_enhance_failed") from exc
enhanced_img_data = enhanced_response.content
img = Image.open(BytesIO(enhanced_img_data))
if img.mode in ("RGBA", "LA"):
background = Image.new("RGB", img.size, (255, 255, 255))
background.paste(img, mask=img.split()[-1])
passport_img = background
else:
passport_img = img.convert("RGB")
return passport_img
@app.route("/process", methods=["POST"])
def process():
print("==== /process endpoint hit ====")
# Layout settings
passport_width = int(request.form.get("width", 390))
passport_height = int(request.form.get("height", 480))
border = int(request.form.get("border", 2))
spacing = int(request.form.get("spacing", 10))
margin_x = 10
margin_y = 10
horizontal_gap = 10
a4_w, a4_h = 2480, 3508
# Collect images and their copy counts
# Supports: image_0, image_1, ... and copies_0, copies_1, ...
# Also supports legacy single: image + copies
images_data = []
# Multi-image mode
i = 0
while f"image_{i}" in request.files:
file = request.files[f"image_{i}"]
copies = int(request.form.get(f"copies_{i}", 6))
images_data.append((file.read(), copies))
i += 1
# Fallback to single image mode
if not images_data and "image" in request.files:
file = request.files["image"]
copies = int(request.form.get("copies", 6))
images_data.append((file.read(), copies))
if not images_data:
return "No image uploaded", 400
missing_config = [name for name, value in REQUIRED_CONFIG.items() if not value]
if missing_config:
return {
"error": "missing_config",
"missing": missing_config,
"message": "Add the missing values to a .env file in the project root.",
}, 500
print(f"DEBUG: Processing {len(images_data)} image(s)")
# Process all images
passport_images = []
for idx, (img_bytes, copies) in enumerate(images_data):
print(f"DEBUG: Processing image {idx + 1} with {copies} copies")
try:
img = process_single_image(img_bytes)
img = img.resize((passport_width, passport_height), Image.LANCZOS)
img = ImageOps.expand(img, border=border, fill="black")
passport_images.append((img, copies))
except ValueError as e:
err_str = str(e)
if "410" in err_str or "face" in err_str.lower():
return {"error": "face_detection_failed"}, 410
elif "429" in err_str or "quota" in err_str.lower():
return {"error": "quota_exceeded"}, 429
elif err_str == "remove_bg_network_error":
return {"error": "remove_bg_network_error"}, 502
elif err_str == "cloudinary_auth_failed":
return {"error": "cloudinary_auth_failed"}, 502
elif err_str in {"cloudinary_upload_failed", "cloudinary_enhance_failed"}:
return {"error": err_str}, 502
else:
print(err_str)
return {"error": err_str}, 500
paste_w = passport_width + 2 * border
paste_h = passport_height + 2 * border
# Build all pages
pages = []
current_page = Image.new("RGB", (a4_w, a4_h), "white")
x, y = margin_x, margin_y
def new_page():
nonlocal current_page, x, y
pages.append(current_page)
current_page = Image.new("RGB", (a4_w, a4_h), "white")
x, y = margin_x, margin_y
for passport_img, copies in passport_images:
for _ in range(copies):
# Move to next row if needed
if x + paste_w > a4_w - margin_x:
x = margin_x
y += paste_h + spacing
# Move to next page if needed
if y + paste_h > a4_h - margin_y:
new_page()
current_page.paste(passport_img, (x, y))
print(f"DEBUG: Placed at x={x}, y={y}")
x += paste_w + horizontal_gap
pages.append(current_page)
print(f"DEBUG: Total pages = {len(pages)}")
# Export multi-page PDF
output = BytesIO()
if len(pages) == 1:
pages[0].save(output, format="PDF", dpi=(300, 300))
else:
pages[0].save(
output,
format="PDF",
dpi=(300, 300),
save_all=True,
append_images=pages[1:],
)
output.seek(0)
print("DEBUG: Returning PDF to client")
return send_file(
output,
mimetype="application/pdf",
as_attachment=True,
download_name="passport-sheet.pdf",
)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)