vivaceailab commited on
Commit
bcf15d5
·
verified ·
1 Parent(s): 926a84f

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +107 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+ import torch
4
+ from transformers import BlipProcessor, BlipForConditionalGeneration
5
+ from diffusers import StableDiffusionPipeline
6
+ import traceback
7
+
8
+ # 모델 로딩 (최대한 빠른 처리: BLIP + SD-Turbo)
9
+ device = "cuda" if torch.cuda.is_available() else "cpu"
10
+
11
+ blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
12
+ blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(device)
13
+
14
+ pipe = StableDiffusionPipeline.from_pretrained(
15
+ "stabilityai/stable-diffusion-turbo",
16
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
17
+ ).to(device)
18
+ pipe.safety_checker = None # 안전필터 off (실습/학습 목적)
19
+
20
+ def caricature_from_photo(image):
21
+ try:
22
+ raw_image = image.convert('RGB')
23
+ inputs = blip_processor(raw_image, return_tensors="pt").to(device)
24
+ out = blip_model.generate(**inputs, max_new_tokens=30)
25
+ description = blip_processor.decode(out[0], skip_special_tokens=True)
26
+
27
+ # 캐리커쳐 스타일 프롬프트 (이모티콘과 직관적 키워드로 꾸밈)
28
+ caricature_prompt = (
29
+ f"{description}, cute cartoon, gentle lines, charming and lovely, sweet expression, lovely mood, digital illustration, "
30
+ "cheerful, simple background, joy, cartoon-style, 😄✨"
31
+ )
32
+
33
+ # turbo SD: 매우 빠른 생성!
34
+ result = pipe(
35
+ caricature_prompt,
36
+ num_inference_steps=4, # turbo 권장값: 4
37
+ guidance_scale=0.0 # turbo 권장값: 0.0 (텍스트 프롬프트 반영)
38
+ ).images[0]
39
+
40
+ info_text = (
41
+ f"**이미지 설명**: {description}\n\n"
42
+ f"**캐리커쳐 프롬프트**: `{caricature_prompt}`"
43
+ )
44
+ return result, info_text
45
+ except Exception as e:
46
+ err = f"❗️ 오류가 발생했어요!\n\n{e}\n\n{traceback.format_exc()}"
47
+ empty = Image.new("RGB", (512,512), "#FFFDE7")
48
+ return empty, err
49
+
50
+ custom_css = """
51
+ body { background: linear-gradient(135deg, #a7ffeb 0%, #fce4ec 100%);}
52
+ .gradio-container { background-color: #fafcff !important;}
53
+ .gr-button { background: #ffd600; color: #252525; border-radius:18px; font-size:1.2em;}
54
+ .gr-button:hover { background:#ffd54f;}
55
+ #caricature-preview img {
56
+ border-radius: 30px; border: 4px solid #ffff8d;
57
+ box-shadow: 0px 8px 56px #ffd60044;
58
+ margin-top: 1em;
59
+ }
60
+ #main-view .block {
61
+ background: #ffffffb8; border-radius: 22px;
62
+ box-shadow: 0 4px 32px #b3afec33; margin:18px;
63
+ }
64
+ """
65
+
66
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
67
+ gr.Markdown("""
68
+ <div style="text-align:center; padding-top:.5em;">
69
+ <span style="font-size:2.3em;">🎨 <b style="color:#1ec69d">캐리커쳐 매직</b> <span style="font-size:1em;">앱</span> ✨</span>
70
+ <p style="font-size:1.11em; color:#575d76;">
71
+ 어떤 사진이든 <b>1초 만에 캐리커쳐</b>로!<br>
72
+ <span style="color:#2196f3">카메라 📷</span> 또는 <span style="color:#ff1696">앨범</span>에서 이미지를 올려보세요!
73
+ </p>
74
+ </div>
75
+ """)
76
+ with gr.Row(elem_id="main-view"):
77
+ with gr.Column():
78
+ photo = gr.Image(
79
+ label="📷 사진 찍기 또는 선택(앨범)",
80
+ type="pil",
81
+ height=300,
82
+ elem_id="user-photo",
83
+ )
84
+ btn = gr.Button("👉 캐리커쳐 만들기!", elem_id="do_caricature")
85
+ with gr.Column():
86
+ caricature_img = gr.Image(
87
+ label="🖼️ 캐리커쳐 미리보기",
88
+ elem_id="caricature-preview",
89
+ height=350,
90
+ show_label=True
91
+ )
92
+ info = gr.Markdown(label="생성 내역 및 설명", value="", elem_id="summary-field")
93
+ btn.click(caricature_from_photo, inputs=photo, outputs=[caricature_img, info])
94
+
95
+ # 안내 메시지
96
+ gr.Markdown("""
97
+ <div style="background:#fffde7; border-radius:18px; border:1.5px dashed #ffe082; padding:1em; text-align:center; margin-top:18px;">
98
+ <b>💡 사용법 & 인쇄 안내</b><br/>
99
+ <ul style="text-align:left; margin-left:1.8em;">
100
+ <li>휴대폰은 [사진찍기] 선택 시, 카메라와 앨범 둘 다 사용 가능</li>
101
+ <li>[👉 캐리커쳐 만들기!] 버튼을 누르면 캐리커쳐가 빠르게 생성됩니다.</li>
102
+ <li>결과 이미지를 길게 누르거나 우클릭하여 저장/공유/인쇄 할 수 있습니다.</li>
103
+ </ul>
104
+ </div>
105
+ """)
106
+
107
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ torch
3
+ transformers
4
+ diffusers
5
+ Pillow
6
+ accelerate
7
+ safetensors
8
+