devorah-ai-2016 commited on
Commit
0f40e38
·
verified ·
1 Parent(s): 2d0eb6f

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -373
app.py DELETED
@@ -1,373 +0,0 @@
1
- import os
2
- import tempfile
3
- import re
4
- from datetime import date
5
- import gradio as gr
6
- from PIL import Image, ImageDraw, ImageFont
7
-
8
- # Define directory paths
9
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
10
- FONTS_DIR = os.path.join(BASE_DIR, "assets", "fonts")
11
- AWARD_IMAGES_DIR = os.path.join(BASE_DIR, "assets", "award images")
12
-
13
- # Helper to find fonts
14
- def get_font_path(font_name):
15
- paths = [
16
- os.path.join(FONTS_DIR, font_name),
17
- os.path.join(BASE_DIR, "font", font_name)
18
- ]
19
- for p in paths:
20
- if os.path.exists(p):
21
- return p
22
- return None
23
-
24
- # Helper to load font
25
- def load_font(font_choice, size, bold=False):
26
- if font_choice == "고딕체":
27
- file_name = "NotoSansKR-Bold.ttf" if bold else "NotoSansKR-Regular.ttf"
28
- else:
29
- file_name = "NotoSerifKR-Bold.ttf" if bold else "NotoSerifKR-Regular.ttf"
30
-
31
- font_path = get_font_path(file_name)
32
- if font_path:
33
- return ImageFont.truetype(font_path, size)
34
- return ImageFont.load_default()
35
-
36
- # Wrap text function for Korean char-by-char wrapping
37
- def wrap_text(text, font, max_width, draw):
38
- lines = []
39
- for paragraph in text.split("\n"):
40
- paragraph = paragraph.strip()
41
- if not paragraph:
42
- lines.append("")
43
- continue
44
-
45
- current_line = ""
46
- for char in paragraph:
47
- test_line = current_line + char
48
- bbox = draw.textbbox((0, 0), test_line, font=font)
49
- w = bbox[2] - bbox[0]
50
- if w <= max_width:
51
- current_line = test_line
52
- else:
53
- if current_line:
54
- lines.append(current_line)
55
- current_line = char
56
- if current_line:
57
- lines.append(current_line)
58
- return lines
59
-
60
- # Format date string into Korean format (e.g., YYYY-MM-DD -> YYYY년 MM월 DD일)
61
- def format_date_korean(date_str):
62
- date_str = date_str.strip()
63
- match = re.match(r"^(\d{4})-(\d{1,2})-(\d{1,2})$", date_str)
64
- if match:
65
- y, m, d = match.groups()
66
- return f"{y}년 {int(m)}월 {int(d)}일"
67
- return date_str
68
-
69
- # Render certificate PIL Image matching the user's uploaded image style
70
- def render_certificate_img(design, award_name, recipient_name, recipient_role, content, institution_name, director_name, issue_date, seal_file, font_choice):
71
- # A4 dimensions at 150 DPI
72
- width, height = 1240, 1754
73
-
74
- # Load background image
75
- img_path = os.path.join(AWARD_IMAGES_DIR, f"{design}.jpg")
76
- if os.path.exists(img_path):
77
- img = Image.open(img_path).convert("RGBA")
78
- img = img.resize((width, height), Image.Resampling.LANCZOS)
79
- else:
80
- # Fallback white background
81
- img = Image.new("RGBA", (width, height), (255, 255, 255, 255))
82
-
83
- draw = ImageDraw.Draw(img)
84
-
85
- # 1. Main fixed Title "상 장" at top center (100px Bold)
86
- title_font = load_font(font_choice, 100, bold=True)
87
- draw.text((620, 300), "상 장", font=title_font, fill=(28, 28, 28, 255), anchor="mm")
88
-
89
- # 2. Winner Name & Role (성명 송영국 어르신) right-aligned at X = 1020, Y = 480
90
- label_font = load_font(font_choice, 30, bold=False)
91
- name_font = load_font(font_choice, 46, bold=True)
92
-
93
- label_text_name = "성명 "
94
- bbox_label_name = draw.textbbox((0, 0), label_text_name, font=label_font)
95
- label_w_name = bbox_label_name[2] - bbox_label_name[0]
96
-
97
- bbox_name = draw.textbbox((0, 0), recipient_name, font=name_font)
98
- name_w = bbox_name[2] - bbox_name[0]
99
-
100
- role_w = 0
101
- role_text = ""
102
- if recipient_role:
103
- role_text = f" {recipient_role}"
104
- bbox_role = draw.textbbox((0, 0), role_text, font=label_font)
105
- role_w = bbox_role[2] - bbox_role[0]
106
-
107
- total_w = label_w_name + name_w + role_w
108
- start_x = 1020 - total_w
109
-
110
- draw.text((start_x, 480), label_text_name, font=label_font, fill=(28, 28, 28, 255), anchor="lm")
111
- draw.text((start_x + label_w_name, 480), recipient_name, font=name_font, fill=(28, 28, 28, 255), anchor="lm")
112
- if recipient_role:
113
- draw.text((start_x + label_w_name + name_w, 480), role_text, font=label_font, fill=(28, 28, 28, 255), anchor="lm")
114
-
115
- # 4. Custom Award Name (상장명, e.g. "최고 웹디자인상") left-aligned at X = 220, Y = 600 (76px Bold)
116
- award_font = load_font(font_choice, 76, bold=True)
117
- draw.text((220, 600), award_name, font=award_font, fill=(28, 28, 28, 255), anchor="lm")
118
-
119
- # 5. Content (공적내용) - 32px Regular, auto wrap, centered
120
- content_font = load_font(font_choice, 32, bold=False)
121
- # Wrapping width: 840 px (margins of 200 px on each side)
122
- wrapped_lines = wrap_text(content, content_font, 840, draw)
123
- line_spacing = 22
124
-
125
- # Calculate vertical heights to center the block at Y = 920
126
- line_heights = []
127
- total_height = 0
128
- for line in wrapped_lines:
129
- if not line:
130
- h = 32
131
- else:
132
- bbox = draw.textbbox((0, 0), line, font=content_font)
133
- h = bbox[3] - bbox[1]
134
- line_heights.append(h)
135
- total_height += h
136
- total_height += line_spacing * (len(wrapped_lines) - 1)
137
-
138
- start_y = 920 - total_height / 2
139
- for line, h in zip(wrapped_lines, line_heights):
140
- if line:
141
- draw.text((620, start_y + h / 2), line, font=content_font, fill=(28, 28, 28, 255), anchor="mm")
142
- start_y += h + line_spacing
143
-
144
- # 6. Award Date (수여일) - 30px Regular, centered at Y = 1280
145
- formatted_date = format_date_korean(issue_date)
146
- date_font = load_font(font_choice, 30, bold=False)
147
- draw.text((620, 1280), formatted_date, font=date_font, fill=(28, 28, 28, 255), anchor="mm")
148
-
149
- # 7. Organization Name (기관명) & Representative Name (대표자명) right-aligned at X = 920
150
- inst_font = load_font(font_choice, 38, bold=True)
151
- dir_font = load_font(font_choice, 46, bold=True)
152
-
153
- if director_name:
154
- # Draw institution_name at Y = 1420
155
- draw.text((920, 1420), institution_name, font=inst_font, fill=(28, 28, 28, 255), anchor="rm")
156
- # Draw director_name at Y = 1480
157
- draw.text((920, 1480), director_name, font=dir_font, fill=(28, 28, 28, 255), anchor="rm")
158
- else:
159
- # If no director name, draw institution_name at Y = 1480
160
- draw.text((920, 1480), institution_name, font=inst_font, fill=(28, 28, 28, 255), anchor="rm")
161
-
162
- # 8. Seal Upload (직인) - Placed immediately to the right of the Representative Name
163
- if seal_file:
164
- try:
165
- seal_img = Image.open(seal_file).convert("RGBA")
166
- seal_img.thumbnail((120, 120), Image.Resampling.LANCZOS)
167
- seal_w, seal_h = seal_img.size
168
- seal_x = 940
169
- seal_y = int(1480 - seal_h / 2)
170
- img.paste(seal_img, (seal_x, seal_y), seal_img)
171
- except Exception as e:
172
- print(f"Error rendering seal image: {e}")
173
-
174
- return img.convert("RGB")
175
-
176
- # Generate and save formats callback
177
- def generate_and_save(design, award_name, recipient_name, recipient_role, content, institution_name, director_name, issue_date, seal_file, font_choice):
178
- img = render_certificate_img(
179
- design, award_name, recipient_name, recipient_role, content, institution_name, director_name, issue_date, seal_file, font_choice
180
- )
181
-
182
- temp_dir = tempfile.mkdtemp(prefix="beecare_award_")
183
- safe_recipient = re.sub(r"[^\w가-힣-_]", "", recipient_name).strip() or "수상자"
184
- safe_award = re.sub(r"[^\w가-힣-_]", "", award_name).strip() or "상장"
185
- filename_base = f"{safe_recipient}_{safe_award}"
186
-
187
- png_path = os.path.join(temp_dir, f"{filename_base}.png")
188
- jpg_path = os.path.join(temp_dir, f"{filename_base}.jpg")
189
- pdf_path = os.path.join(temp_dir, f"{filename_base}.pdf")
190
-
191
- img.save(png_path, "PNG")
192
- img.save(jpg_path, "JPEG", quality=95)
193
- img.save(pdf_path, "PDF", resolution=150.0)
194
-
195
- return img, png_path, jpg_path, pdf_path
196
-
197
- # Modern styling CSS
198
- THEME_CSS = """
199
- :root {
200
- --primary-color: #4f46e5;
201
- --primary-hover: #4338ca;
202
- --bg-color: #f9fafb;
203
- --panel-bg: #ffffff;
204
- --text-color: #1f2937;
205
- --border-color: #e5e7eb;
206
- }
207
- .gradio-container {
208
- font-family: 'Inter', 'Noto Sans KR', sans-serif;
209
- background-color: var(--bg-color);
210
- color: var(--text-color);
211
- }
212
- .title-header {
213
- text-align: center;
214
- margin-bottom: 24px;
215
- padding: 20px;
216
- background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
217
- color: white;
218
- border-radius: 12px;
219
- box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
220
- }
221
- .title-header h1 {
222
- font-size: 28px;
223
- margin: 0;
224
- font-weight: 700;
225
- }
226
- .title-header p {
227
- font-size: 14px;
228
- margin: 8px 0 0 0;
229
- opacity: 0.9;
230
- }
231
- .control-panel {
232
- background-color: var(--panel-bg);
233
- border: 1px solid var(--border-color);
234
- border-radius: 12px;
235
- padding: 20px;
236
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05);
237
- }
238
- .preview-panel {
239
- background-color: var(--panel-bg);
240
- border: 1px solid var(--border-color);
241
- border-radius: 12px;
242
- padding: 20px;
243
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05);
244
- }
245
- """
246
-
247
- # Available award background choices
248
- AWARD_DESIGN_CHOICES = [f"award{i}" for i in range(1, 15)]
249
-
250
- # Gradio Interface builder
251
- with gr.Blocks(title="실무형 상장생성기") as demo:
252
- gr.HTML(
253
- """
254
- <div class="title-header">
255
- <h1>실무형 상장생성기</h1>
256
- <p>주간보호센터, 방문요양센터, 요양원에서 바로 사용할 수 있는 간편하고 직관적인 상장 제작 도구입니다.</p>
257
- </div>
258
- """
259
- )
260
-
261
- with gr.Row():
262
- # Left Panel - Inputs
263
- with gr.Column(scale=1, elem_classes=["control-panel"]):
264
- gr.Markdown("### 🛠️ 상장 설정 및 입력")
265
-
266
- design = gr.Dropdown(
267
- choices=AWARD_DESIGN_CHOICES,
268
- value="award1",
269
- label="1. 상장 디자인 선택"
270
- )
271
-
272
- award_name = gr.Textbox(
273
- value="최고 웹디자인상",
274
- label="2. 상장명 직접 입력",
275
- placeholder="예: 최고 웹디자인상, 미소상, 한결같은 사랑상"
276
- )
277
-
278
- recipient_name = gr.Textbox(
279
- value="송영진",
280
- label="3. 수상자명 입력",
281
- placeholder="예: 송영진"
282
- )
283
-
284
- recipient_role = gr.Dropdown(
285
- choices=["어르신", "보호자", "요양보호사", "사회복지사", "간호조무사", "직원", "자원봉사자"],
286
- value="직원",
287
- allow_custom_value=True,
288
- label="4. 직책/관계 선택 (직접 입력도 가능)"
289
- )
290
-
291
- content = gr.Textbox(
292
- value="귀하는 미리캔버스 직원으로서 모든 고객들께\n저작권 걱정없이 사용하는 완전 무료 디자인툴인\n미리캔버스의 눈부신 성장과 발전에 기여한 공이\n크고 늘 팀원들에게 활기찬 에너지를 주어\n이에 감사의 마음을 담아 이 상장을 드립니다",
293
- label="5. 공적내용 직접 입력",
294
- lines=5,
295
- placeholder="상장에 들어갈 문구를 입력하세요. (자동 줄바꿈)"
296
- )
297
-
298
- institution_name = gr.Textbox(
299
- value="(주) 미리캔버스 대표",
300
- label="6. 기관명 직접 입력",
301
- placeholder="예: (주) 미리캔버스 대표, 행복주간보호센터"
302
- )
303
-
304
- director_name = gr.Textbox(
305
- value="강미리",
306
- label="6-2. 대표자명 직접 입력",
307
- placeholder="예: 강미리, 센터장 홍길동"
308
- )
309
-
310
- issue_date = gr.Textbox(
311
- value="2030-10-28",
312
- label="7. 수여일 선택/입력",
313
- placeholder="예: YYYY-MM-DD"
314
- )
315
-
316
- seal_file = gr.File(
317
- label="8. 기관 직인 업로드 (PNG 권장)",
318
- file_types=["image"],
319
- type="filepath"
320
- )
321
-
322
- font_choice = gr.Radio(
323
- choices=["고딕체", "명조체"],
324
- value="명조체",
325
- label="9. 글씨체 선택"
326
- )
327
-
328
- # Right Panel - Preview & Saves
329
- with gr.Column(scale=1, elem_classes=["preview-panel"]):
330
- gr.Markdown("### 🔍 상장 실시간 미리보기")
331
- preview = gr.Image(
332
- label="상장 미리보기",
333
- type="pil",
334
- interactive=False
335
- )
336
-
337
- gr.Markdown("### 💾 상장 파일 다운로드")
338
- with gr.Row():
339
- png_download = gr.File(label="PNG 저장")
340
- jpg_download = gr.File(label="JPG 저장")
341
- pdf_download = gr.File(label="PDF 저장")
342
-
343
- # Define inputs array (must match render_certificate_img and generate_and_save arguments)
344
- inputs = [
345
- design,
346
- award_name,
347
- recipient_name,
348
- recipient_role,
349
- content,
350
- institution_name,
351
- director_name,
352
- issue_date,
353
- seal_file,
354
- font_choice
355
- ]
356
-
357
- # Define outputs array
358
- outputs = [
359
- preview,
360
- png_download,
361
- jpg_download,
362
- pdf_download
363
- ]
364
-
365
- # Event bindings
366
- for inp in inputs:
367
- inp.change(fn=generate_and_save, inputs=inputs, outputs=outputs)
368
-
369
- # Trigger load preview initially
370
- demo.load(fn=generate_and_save, inputs=inputs, outputs=outputs)
371
-
372
- if __name__ == "__main__":
373
- demo.launch(css=THEME_CSS)