File size: 14,333 Bytes
1f7d355
 
 
eb887b5
 
6d9a769
 
 
af59de2
63d2006
2b46bb5
 
a47b847
6d9a769
 
 
63d2006
 
6d9a769
 
 
 
2b46bb5
6d9a769
2b46bb5
 
6d9a769
 
 
 
63d2006
 
 
 
 
 
 
 
 
 
6d9a769
63d2006
 
 
d6ceac1
63d2006
 
 
d6ceac1
63d2006
 
 
 
 
 
 
 
 
 
 
d6ceac1
63d2006
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6ceac1
2b46bb5
eb887b5
63d2006
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af59de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb887b5
 
 
af59de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb887b5
 
 
af59de2
 
 
 
 
 
 
 
eb887b5
 
af59de2
 
 
 
 
 
 
 
 
 
 
 
eb887b5
 
 
af59de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c622495
 
 
 
 
 
af59de2
 
 
 
c622495
 
 
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import gradio as gr
import qrcode
import random
import os
from datetime import datetime
from PIL import Image, ImageDraw
from math import cos, sin, radians

# ν…Œλ‘λ¦¬ μž₯식 ν•¨μˆ˜
def create_border_decoration(qr_image, decoration_prompt="🌸"):
    # Convert QR image to RGB mode first
    qr_image = qr_image.convert('RGB')
    
    # Get the size of the QR code image
    width, height = qr_image.size
    
    # Create a new image with smaller padding for decoration
    padding = 30  # νŒ¨λ”©μ„ μ€„μ—¬μ„œ QR μ½”λ“œ 크기λ₯Ό 더 크게
    new_width = width + (padding * 2)
    new_height = height + (padding * 2)
    
    # Create new image with white background
    decorated_image = Image.new('RGB', (new_width, new_height), 'white')
    
    # Paste QR code in center (with RGB mode)
    decorated_image.paste(qr_image, (padding, padding))
    
    # Get draw object
    draw = ImageDraw.Draw(decorated_image)
    
    # 이λͺ¨μ§€μ— λ”°λ₯Έ μž₯식 μ„€μ •
    emoji_size = 12
    gap = emoji_size * 2  # 이λͺ¨μ§€ μ‚¬μ΄μ˜ 간격
    
    # ν…Œλ‘λ¦¬λ₯Ό 따라 μ λ“€μ˜ μœ„μΉ˜ 계산
    border_points = []
    
    # 상단 ν…Œλ‘λ¦¬
    for x in range(padding//2, new_width - padding//2, gap):
        border_points.append((x, padding//2))
        
    # 우츑 ν…Œλ‘λ¦¬
    for y in range(padding//2, new_height - padding//2, gap):
        border_points.append((new_width - padding//2, y))
        
    # ν•˜λ‹¨ ν…Œλ‘λ¦¬
    for x in range(new_width - padding//2, padding//2, -gap):
        border_points.append((x, new_height - padding//2))
        
    # 쒌츑 ν…Œλ‘λ¦¬
    for y in range(new_height - padding//2, padding//2, -gap):
        border_points.append((padding//2, y))
    
    # 각 μœ„μΉ˜μ— 이λͺ¨μ§€ 그리기
    for x, y in border_points:
        if "🌸" in decoration_prompt:  # λ²šκ½ƒ
            for angle in range(0, 360, 45):
                x1 = x + emoji_size * cos(radians(angle))
                y1 = y + emoji_size * sin(radians(angle))
                draw.ellipse([x1-4, y1-4, x1+4, y1+4], fill='pink')
            draw.ellipse([x-3, y-3, x+3, y+3], fill='yellow')
        
        elif "πŸ€" in decoration_prompt:  # λ„€μžŽν΄λ‘œλ²„
            for angle in range(0, 360, 90):
                x1 = x + emoji_size * cos(radians(angle))
                y1 = y + emoji_size * sin(radians(angle))
                draw.ellipse([x1-4, y1-4, x1+4, y1+4], fill='lightgreen')
            draw.ellipse([x-2, y-2, x+2, y+2], fill='darkgreen')
        
        elif "⭐" in decoration_prompt:  # 별
            for angle in range(0, 360, 72):
                x1 = x + emoji_size * cos(radians(angle))
                y1 = y + emoji_size * sin(radians(angle))
                draw.polygon([(x1, y1), (x1+4, y1+4), (x1-4, y1+4)], fill='gold')
        
        elif "❀️" in decoration_prompt:  # ν•˜νŠΈ
            draw.ellipse([x-6, y-6, x+6, y], fill='red')
            draw.polygon([(x-6, y), (x+6, y), (x, y+8)], fill='red')
        
        elif "🌟" in decoration_prompt:  # λ°˜μ§μ΄λŠ” 별
            for angle in range(0, 360, 45):
                x1 = x + emoji_size * cos(radians(angle))
                y1 = y + emoji_size * sin(radians(angle))
                draw.line([(x, y), (x1, y1)], fill='yellow', width=2)
            draw.ellipse([x-3, y-3, x+3, y+3], fill='white')
        
        elif "πŸƒ" in decoration_prompt:  # 잎
            draw.ellipse([x-8, y-4, x+8, y+4], fill='lightgreen')
            draw.ellipse([x-4, y-8, x+4, y+8], fill='green')
        
        elif "πŸ’«" in decoration_prompt:  # μ†Œμš©λŒμ΄
            for i in range(5):
                size = emoji_size - (i * 2)
                angle = i * 45
                x1 = x + size * cos(radians(angle))
                y1 = y + size * sin(radians(angle))
                draw.ellipse([x1-3, y1-3, x1+3, y1+3], fill='lightyellow')
        
        elif "✨" in decoration_prompt:  # λ°˜μ§μž„
            for angle in range(0, 360, 60):
                x1 = x + emoji_size * cos(radians(angle))
                y1 = y + emoji_size * sin(radians(angle))
                draw.line([(x, y), (x1, y1)], fill='gold', width=1)
        
        elif "🌊" in decoration_prompt:  # νŒŒλ„
            draw.arc([x-8, y-4, x+8, y+4], 0, 180, fill='lightblue')
            draw.arc([x-8, y, x+8, y+8], 0, 180, fill='blue')
        
        elif "🎨" in decoration_prompt:  # λ¬΄μ§€κ°œ
            colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
            for i, color in enumerate(colors):
                size = emoji_size - (i * 2)
                draw.arc([x-size, y-size, x+size, y+size], 0, 180, fill=color)
    
    return decorated_image

# create_interface() ν•¨μˆ˜ λ‚΄μ˜ border_decoration λΆ€λΆ„ μˆ˜μ •
border_decoration = gr.Dropdown(
    choices=[
        "🌸 Cherry Blossoms",
        "πŸ€ Four Leaf Clover",
        "⭐ Stars",
        "❀️ Hearts",
        "🌟 Sparkles",
        "πŸƒ Leaves",
        "πŸ’« Swirls",
        "✨ Twinkles",
        "🌊 Waves",
        "🎨 Rainbow"
    ],
    value="🌸 Cherry Blossoms",
    label="Border Decoration Style"
)

# create_qr ν•¨μˆ˜μ—μ„œ border_decoration 처리 μˆ˜μ •
def create_qr(..., border_decoration="🌸 Cherry Blossoms"):
    ...
    if border_decoration.strip():
        emoji = border_decoration.split()[0]  # Get only the emoji part
        qr_img = create_border_decoration(qr_img, emoji)
    ...

# QR μ½”λ“œ 생성 ν•¨μˆ˜
def create_qr(content, qr_type, fill_color, back_color, box_size, border_size, error_correction, border_decoration="flowers"):
    # QR μ½”λ“œ 데이터 ν¬λ§·νŒ…
    formatted_data = format_data(content, qr_type)
    
    # μ—λŸ¬ μˆ˜μ • 레벨 μ„€μ •
    error_levels = {
        "Low (7%)": qrcode.constants.ERROR_CORRECT_L,
        "Medium (15%)": qrcode.constants.ERROR_CORRECT_M,
        "Quartile (25%)": qrcode.constants.ERROR_CORRECT_Q,
        "High (30%)": qrcode.constants.ERROR_CORRECT_H
    }
    
    # QR μ½”λ“œ 생성
    qr = qrcode.QRCode(
        version=1,
        error_correction=error_levels[error_correction],
        box_size=box_size,
        border=border_size,
    )
    
    qr.add_data(formatted_data)
    qr.make(fit=True)
    
    # QR 이미지 생성
    qr_img = qr.make_image(fill_color=fill_color, back_color=back_color)
    
    # Add border decoration if specified
    if border_decoration.strip():  # Only if decoration prompt is not empty
        qr_img = create_border_decoration(qr_img, border_decoration)
    
    # 파일 μ €μž₯
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    random_id = random.randint(1000, 9999)
    filename = f"qrfile/qr_{timestamp}_{random_id}.png"
    
    # 디렉토리 확인 및 생성
    os.makedirs("qrfile", exist_ok=True)
    
    # 이미지 μ €μž₯
    qr_img.save(filename)
    cleanup_old_files("qrfile/", max_files=100)
    
    return filename, formatted_data

# 데이터 ν¬λ§·νŒ… ν•¨μˆ˜
def format_data(content, qr_type):
    if not content:
        return ""
        
    format_rules = {
        "URL": lambda x: f"https://{x}" if not x.startswith(('http://', 'https://')) else x,
        "Email": lambda x: f"mailto:{x}",
        "Phone": lambda x: f"tel:{x}",
        "SMS": lambda x: f"sms:{x}",
        "WhatsApp": lambda x: f"whatsapp://send?text={x}",
        "Location": lambda x: f"geo:{x}",
        "Wi-Fi": lambda x: f"WIFI:S:{x};;",
        "Text": lambda x: x,
        "vCard": lambda x: f"BEGIN:VCARD\nVERSION:3.0\n{x}\nEND:VCARD"
    }
    
    return format_rules[qr_type](content.strip())

# 파일 정리 ν•¨μˆ˜
def cleanup_old_files(directory, max_files):
    files = [f for f in os.listdir(directory) if f.endswith('.png')]
    if len(files) > max_files:
        files.sort(key=lambda x: os.path.getctime(os.path.join(directory, x)))
        for f in files[:-max_files]:
            try:
                os.remove(os.path.join(directory, f))
            except:
                continue

def format_example_text(qr_type):
    examples = {
        "URL": "β€’ Direct URL: https://example.com\nβ€’ Without https: example.com",
        "Email": "β€’ Basic: [email protected]\nβ€’ With subject: [email protected]?subject=Hello",
        "Phone": "β€’ International: +1234567890\nβ€’ Local: 01012345678",
        "SMS": "β€’ Basic: +1234567890\nβ€’ With message: +1234567890?body=Hello",
        "WhatsApp": "β€’ Message: Hello World!\nβ€’ With number: +1234567890:Hello",
        "Location": "β€’ Coordinates: 37.7749,-122.4194\nβ€’ With zoom: 37.7749,-122.4194,15z",
        "Wi-Fi": "β€’ Network name only: MyWiFiNetwork\nβ€’ With password: WIFI:S:MyNetwork;P:password;;",
        "Text": "β€’ Simple text: Hello World!\nβ€’ Multiple lines: Line 1\\nLine 2",
        "vCard": "β€’ Basic:\nFN:John Doe\nTEL:+1234567890\nEMAIL:[email protected]\nβ€’ Extended:\nFN:John Doe\nTEL:+1234567890\nEMAIL:[email protected]\nADR:;;123 Street;City;State;12345;Country"
    }
    return examples.get(qr_type, "Enter your content here...")

# Gradio μΈν„°νŽ˜μ΄μŠ€ 생성
def create_interface():
    theme = gr.themes.Soft(
        primary_hue="blue",
        secondary_hue="indigo",
    ).set(
        body_background_fill="*neutral_50",
        block_background_fill="*neutral_100",
        button_primary_background_fill="*primary_500",
    )
    
    with gr.Blocks(theme=theme, title="QR Canvas") as demo:
        gr.Markdown(
            """
            # 🎯 QR CANVAS
            Create customized QR codes for various purposes with professional styling options.
            """
        )
        
        gr.HTML("""<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fginipick-QR-Canvas.hf.space">
                <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fginipick-QR-Canvas.hf.space&countColor=%23263759" />
                </a>""")
        
        with gr.Row():
            with gr.Column(scale=2):
                qr_type = gr.Dropdown(
                    choices=["URL", "Email", "Phone", "SMS", "WhatsApp", "Location", "Wi-Fi", "Text", "vCard"],
                    value="URL",
                    label="QR Code Type"
                )
                
                content = gr.Textbox(
                    label="Content",
                    placeholder="Enter your content here...",
                    lines=3
                )
                
                example_format = gr.Textbox(
                    value=format_example_text("URL"),
                    label="Format Examples",
                    interactive=False,
                    lines=6
                )
                
                with gr.Row():
                    fill_color = gr.ColorPicker(
                        label="QR Code Color",
                        value="#000000"
                    )
                    back_color = gr.ColorPicker(
                        label="Background Color",
                        value="#FFFFFF"
                    )
                
                with gr.Row():
                    box_size = gr.Slider(
                        minimum=1,
                        maximum=20,
                        value=10,
                        step=1,
                        label="QR Code Size"
                    )
                    border_size = gr.Slider(
                        minimum=0,
                        maximum=10,
                        value=4,
                        step=1,
                        label="Border Size"
                    )
                
                error_correction = gr.Dropdown(
                    choices=[
                        "Low (7%)",
                        "Medium (15%)",
                        "Quartile (25%)",
                        "High (30%)"
                    ],
                    value="Medium (15%)",
                    label="Error Correction Level"
                )
                
                border_decoration = gr.Textbox(
                    label="Border Decoration Prompt",
                    placeholder="Enter decoration style (e.g., flowers, simple, modern)",
                    value="flowers"
                )
                
                generate_btn = gr.Button(
                    "Generate QR Code",
                    variant="primary"
                )
            
            with gr.Column(scale=1):
                output_image = gr.Image(
                    label="Generated QR Code",
                    type="filepath"
                )
                output_data = gr.Textbox(
                    label="Formatted Data",
                    interactive=False
                )
        
        def update_example(qr_type):
            return format_example_text(qr_type)
        
        qr_type.change(
            fn=update_example,
            inputs=[qr_type],
            outputs=example_format
        )
        
        generate_btn.click(
            fn=create_qr,
            inputs=[
                content,
                qr_type,
                fill_color,
                back_color,
                box_size,
                border_size,
                error_correction,
                border_decoration
            ],
            outputs=[output_image, output_data]
        )
        
        gr.Markdown(
            """
            ### πŸ“ Instructions
            1. Select the QR code type from the dropdown menu
            2. Enter your content following the format examples shown
            3. Customize the appearance using the color pickers and sliders
            4. Click 'Generate QR Code' to create your custom QR code
            
            ### πŸ’‘ Tips
            - Use higher error correction levels for better scan reliability
            - Ensure sufficient contrast between QR code and background colors
            - Keep the content concise for better readability
            - Follow the format examples for best results
            """
        )
    
    return demo

if __name__ == "__main__":
    try:
        os.makedirs("qrfile", exist_ok=True)
        demo = create_interface()
        demo.launch(
            server_name="0.0.0.0",
            server_port=7860,
            share=True,
            debug=True
        )
    except Exception as e:
        print(f"Error starting the application: {e}")