hongyu12321 commited on
Commit
165f68d
Β·
verified Β·
1 Parent(s): 18d7038

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -84
app.py CHANGED
@@ -1,6 +1,5 @@
1
- # app.py β€” One-page Age + Cartoon app (no extra modules needed)
2
 
3
- # Quiet TF/Flax logs (PyTorch-only)
4
  import os
5
  os.environ["TRANSFORMERS_NO_TF"] = "1"
6
  os.environ["TRANSFORMERS_NO_FLAX"] = "1"
@@ -11,9 +10,7 @@ from PIL import Image, ImageDraw
11
  import numpy as np
12
  import torch
13
 
14
- # ---------------------------
15
- # 1) Pretrained Age Estimator
16
- # ---------------------------
17
  from transformers import AutoImageProcessor, AutoModelForImageClassification
18
 
19
  HF_MODEL_ID = "nateraw/vit-age-classifier"
@@ -44,23 +41,24 @@ class PretrainedAgeEstimator:
44
  for i, p in enumerate(probs))
45
  return expected, top
46
 
47
- # ---------------------------
48
- # 2) Face detector / cropper (MTCNN)
49
- # ---------------------------
50
  from facenet_pytorch import MTCNN
 
51
  class FaceCropper:
52
- """Detect faces and return (cropped_face, annotated_image)."""
53
- def __init__(self, device: str | None = None):
54
  self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
55
  self.mtcnn = MTCNN(keep_all=True, device=self.device)
 
56
 
57
  def _ensure_pil(self, img):
58
  if isinstance(img, Image.Image):
59
  return img.convert("RGB")
60
  return Image.fromarray(img).convert("RGB")
61
 
62
- def detect_and_crop(self, img, select="largest"):
63
  pil = self._ensure_pil(img)
 
64
  boxes, probs = self.mtcnn.detect(pil)
65
 
66
  annotated = pil.copy()
@@ -69,124 +67,165 @@ class FaceCropper:
69
  if boxes is None or len(boxes) == 0:
70
  return None, annotated
71
 
72
- # draw boxes
73
- for b, p in zip(boxes, probs):
74
- x1, y1, x2, y2 = map(float, b)
75
- draw.rectangle([x1, y1, x2, y2], outline=(255, 0, 0), width=3)
76
- draw.text((x1, max(0, y1-12)), f"{p:.2f}", fill=(255, 0, 0))
77
-
78
- # choose largest by area
79
  idx = int(np.argmax([(b[2]-b[0])*(b[3]-b[1]) for b in boxes]))
80
  if isinstance(select, int) and 0 <= select < len(boxes):
81
  idx = select
82
- x1, y1, x2, y2 = boxes[idx].astype(int)
83
- face = pil.crop((x1, y1, x2, y2))
84
- return face, annotated
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
- # ---------------------------
87
- # 3) Cartoonizer (Stable Diffusion img2img)
88
- # ---------------------------
89
- from diffusers import StableDiffusionImg2ImgPipeline
90
 
91
- SD15_ID = "runwayml/stable-diffusion-v1-5"
92
- def load_sd_pipe(device):
 
 
 
 
 
 
 
 
93
  dtype = torch.float16 if (device == "cuda") else torch.float32
94
- pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
95
- SD15_ID,
96
  torch_dtype=dtype,
97
- safety_checker=None, # rely on prompts; HF has global content filters
98
  )
99
- return pipe.to(device)
100
-
101
- # ---------------------------
102
- # 4) Initialize models once
103
- # ---------------------------
 
 
 
104
  age_est = PretrainedAgeEstimator()
105
- cropper = FaceCropper(device=age_est.device)
106
- sd_pipe = load_sd_pipe(age_est.device)
107
-
108
- # ---------------------------
109
- # 5) App logic (one click does both)
110
- # ---------------------------
111
- DEFAULT_PROMPT = (
112
- "cartoon, cel-shaded, clean lineart, smooth shading, vibrant colors, "
113
- "studio ghibli style, pixar style, 2D illustration, high quality"
 
 
 
114
  )
115
 
 
116
  def _ensure_pil(img):
117
  return img if isinstance(img, Image.Image) else Image.fromarray(img)
118
 
 
 
 
 
 
 
 
 
 
119
  @torch.inference_mode()
120
- def run_all(img, prompt, auto_crop=True, strength=0.6, guidance=7.5, steps=25, seed=-1):
121
  if img is None:
122
  return {}, "Please upload an image.", None
123
-
124
  img = _ensure_pil(img).convert("RGB")
125
 
126
- # ---- choose region for both age + cartoon ----
127
- face = None
128
  annotated = None
129
  if auto_crop:
130
- face, annotated = cropper.detect_and_crop(img, select="largest")
 
131
 
132
- target_for_age = face if face is not None else img
133
- # Age prediction
134
- age, top = age_est.predict(target_for_age, topk=5)
135
  probs = {lbl: float(p) for lbl, p in top}
136
  summary = f"**Estimated age:** {age:.1f} years"
 
 
 
 
 
 
 
137
 
138
- # Cartoon generation
139
- txt = (prompt or "").strip()
140
- if not txt:
141
- txt = DEFAULT_PROMPT
142
- else:
143
- txt = f"{DEFAULT_PROMPT}, {txt}"
 
 
 
 
 
 
 
144
 
145
  generator = None
146
  if isinstance(seed, (int, float)) and int(seed) >= 0:
147
  generator = torch.Generator(device=age_est.device).manual_seed(int(seed))
148
 
149
- base_img = face if face is not None else img
150
  out = sd_pipe(
151
- prompt=txt,
152
- image=base_img,
153
- strength=float(strength), # 0.3 subtle β†’ 0.8 strong
154
- guidance_scale=float(guidance), # 5–12 typical
155
- num_inference_steps=int(steps),
 
156
  generator=generator,
157
  )
158
- cartoon = out.images[0]
159
- return probs, summary, cartoon
160
 
161
- # ---------------------------
162
- # 6) Gradio UI (single page)
163
- # ---------------------------
164
- with gr.Blocks(title="Age + Cartoon (One Page)") as demo:
165
- gr.Markdown("# Age Estimator + Cartoonizer")
166
- gr.Markdown("Upload or capture once β€” get **age prediction** and a **cartoon** of the same image.")
167
 
168
  with gr.Row():
169
  with gr.Column(scale=1):
170
- img_in = gr.Image(sources=["upload", "webcam"], type="pil",
171
- label="Upload / Webcam")
172
- prompt = gr.Textbox(label="(Optional) Extra cartoon style",
173
- placeholder="e.g., comic-book halftone, bold lines, neon palette")
174
- auto = gr.Checkbox(True, label="Auto face crop (recommended)")
 
175
  with gr.Row():
176
- strength = gr.Slider(0.2, 0.95, value=0.6, step=0.05, label="Cartoon strength")
177
- guidance = gr.Slider(3, 15, value=7.5, step=0.5, label="Guidance")
178
- steps = gr.Slider(10, 50, value=25, step=1, label="Steps")
179
  seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")
180
- go = gr.Button("Predict Age + Generate Cartoon", variant="primary", size="lg")
 
 
181
 
182
  with gr.Column(scale=1):
183
  probs_out = gr.Label(num_top_classes=5, label="Age Prediction (probabilities)")
184
  age_md = gr.Markdown(label="Age Summary")
 
185
  cartoon_out = gr.Image(label="Cartoon Result")
186
 
187
- go.click(fn=run_all,
188
- inputs=[img_in, prompt, auto, strength, guidance, steps, seed],
189
- outputs=[probs_out, age_md, cartoon_out])
190
 
191
  if __name__ == "__main__":
192
  demo.launch()
 
1
+ # app.py β€” Age-first + FAST cartoon (Turbo), nicer framing & magical background
2
 
 
3
  import os
4
  os.environ["TRANSFORMERS_NO_TF"] = "1"
5
  os.environ["TRANSFORMERS_NO_FLAX"] = "1"
 
10
  import numpy as np
11
  import torch
12
 
13
+ # ------------------ Age estimator (Hugging Face) ------------------
 
 
14
  from transformers import AutoImageProcessor, AutoModelForImageClassification
15
 
16
  HF_MODEL_ID = "nateraw/vit-age-classifier"
 
41
  for i, p in enumerate(probs))
42
  return expected, top
43
 
44
+ # ------------------ Face detection with WIDER crop ------------------
 
 
45
  from facenet_pytorch import MTCNN
46
+
47
  class FaceCropper:
48
+ """Detect faces; return (cropped_wide, annotated). Adds margin so face isn't full screen."""
49
+ def __init__(self, device: str | None = None, margin_scale: float = 1.8):
50
  self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
51
  self.mtcnn = MTCNN(keep_all=True, device=self.device)
52
+ self.margin_scale = margin_scale
53
 
54
  def _ensure_pil(self, img):
55
  if isinstance(img, Image.Image):
56
  return img.convert("RGB")
57
  return Image.fromarray(img).convert("RGB")
58
 
59
+ def detect_and_crop_wide(self, img, select="largest"):
60
  pil = self._ensure_pil(img)
61
+ W, H = pil.size
62
  boxes, probs = self.mtcnn.detect(pil)
63
 
64
  annotated = pil.copy()
 
67
  if boxes is None or len(boxes) == 0:
68
  return None, annotated
69
 
70
+ # choose largest face
 
 
 
 
 
 
71
  idx = int(np.argmax([(b[2]-b[0])*(b[3]-b[1]) for b in boxes]))
72
  if isinstance(select, int) and 0 <= select < len(boxes):
73
  idx = select
74
+ x1, y1, x2, y2 = boxes[idx]
75
+
76
+ # draw all boxes
77
+ for b, p in zip(boxes, probs):
78
+ bx1, by1, bx2, by2 = map(float, b)
79
+ draw.rectangle([bx1, by1, bx2, by2], outline=(255, 0, 0), width=3)
80
+ draw.text((bx1, max(0, by1-12)), f"{p:.2f}", fill=(255, 0, 0))
81
+
82
+ # expand with margin
83
+ cx, cy = (x1 + x2) / 2.0, (y1 + y2) / 2.0
84
+ w, h = (x2 - x1), (y2 - y1)
85
+ side = max(w, h) * self.margin_scale # wider frame to include background/shoulders
86
+ # keep a pleasant portrait aspect (4:5)
87
+ target_w = side
88
+ target_h = side * 1.25
89
 
90
+ nx1 = int(max(0, cx - target_w/2))
91
+ nx2 = int(min(W, cx + target_w/2))
92
+ ny1 = int(max(0, cy - target_h/2))
93
+ ny2 = int(min(H, cy + target_h/2))
94
 
95
+ crop = pil.crop((nx1, ny1, nx2, ny2))
96
+ return crop, annotated
97
+
98
+ # ------------------ FAST Cartoonizer (SD-Turbo) ------------------
99
+ from diffusers import AutoPipelineForImage2Image
100
+
101
+ # Turbo is very fast (1–4 steps). Great for stylization on CPU/GPU.
102
+ TURBO_ID = "stabilityai/sd-turbo"
103
+
104
+ def load_turbo_pipe(device):
105
  dtype = torch.float16 if (device == "cuda") else torch.float32
106
+ pipe = AutoPipelineForImage2Image.from_pretrained(
107
+ TURBO_ID,
108
  torch_dtype=dtype,
109
+ safety_checker=None,
110
  )
111
+ pipe = pipe.to(device)
112
+ try:
113
+ pipe.enable_attention_slicing()
114
+ except Exception:
115
+ pass
116
+ return pipe
117
+
118
+ # ------------------ Init models once ------------------
119
  age_est = PretrainedAgeEstimator()
120
+ cropper = FaceCropper(device=age_est.device, margin_scale=1.8) # 1.6–2.0 feels good
121
+ sd_pipe = load_turbo_pipe(age_est.device)
122
+
123
+ # ------------------ Prompts ------------------
124
+ DEFAULT_POSITIVE = (
125
+ "beautiful princess portrait, elegant gown, tiara, soft magical lighting, "
126
+ "sparkles, dreamy castle background, painterly, clean lineart, vibrant but natural colors, "
127
+ "storybook illustration, high quality"
128
+ )
129
+ DEFAULT_NEGATIVE = (
130
+ "deformed, disfigured, ugly, extra limbs, extra fingers, bad anatomy, low quality, "
131
+ "blurry, watermark, text, logo"
132
  )
133
 
134
+ # ------------------ Helpers ------------------
135
  def _ensure_pil(img):
136
  return img if isinstance(img, Image.Image) else Image.fromarray(img)
137
 
138
+ def _resize_512(im: Image.Image):
139
+ # keep aspect, fit longest side to 512 (faster, fewer artifacts)
140
+ w, h = im.size
141
+ scale = 512 / max(w, h)
142
+ if scale < 1.0:
143
+ im = im.resize((int(w*scale), int(h*scale)), Image.LANCZOS)
144
+ return im
145
+
146
+ # ------------------ 1) Predict Age (fast) ------------------
147
  @torch.inference_mode()
148
+ def predict_age_only(img, auto_crop=True):
149
  if img is None:
150
  return {}, "Please upload an image.", None
 
151
  img = _ensure_pil(img).convert("RGB")
152
 
153
+ face_wide = None
 
154
  annotated = None
155
  if auto_crop:
156
+ face_wide, annotated = cropper.detect_and_crop_wide(img)
157
+ target = face_wide if face_wide is not None else img
158
 
159
+ age, top = age_est.predict(target, topk=5)
 
 
160
  probs = {lbl: float(p) for lbl, p in top}
161
  summary = f"**Estimated age:** {age:.1f} years"
162
+ return probs, summary, (annotated if annotated is not None else img)
163
+
164
+ # ------------------ 2) Generate Cartoon (fast) ------------------
165
+ @torch.inference_mode()
166
+ def generate_cartoon(img, prompt="", auto_crop=True, strength=0.5, steps=2, seed=-1):
167
+ if img is None:
168
+ return None
169
 
170
+ img = _ensure_pil(img).convert("RGB")
171
+ # use wide face crop to include background/shoulders
172
+ if auto_crop:
173
+ face_wide, _ = cropper.detect_and_crop_wide(img)
174
+ if face_wide is not None:
175
+ img = face_wide
176
+
177
+ img = _resize_512(img)
178
+
179
+ # prompt assembly
180
+ user = (prompt or "").strip()
181
+ pos = DEFAULT_POSITIVE if not user else f"{DEFAULT_POSITIVE}, {user}"
182
+ neg = DEFAULT_NEGATIVE
183
 
184
  generator = None
185
  if isinstance(seed, (int, float)) and int(seed) >= 0:
186
  generator = torch.Generator(device=age_est.device).manual_seed(int(seed))
187
 
188
+ # Turbo likes low steps and guidance ~0
189
  out = sd_pipe(
190
+ prompt=pos,
191
+ negative_prompt=neg,
192
+ image=img,
193
+ strength=float(strength), # 0.4–0.6 keeps identity & adds dress/background
194
+ guidance_scale=0.0, # Turbo typically uses 0
195
+ num_inference_steps=int(steps), # 1–4 steps β†’ very fast
196
  generator=generator,
197
  )
198
+ return out.images[0]
 
199
 
200
+ # ------------------ UI ------------------
201
+ with gr.Blocks(title="Age First + Fast Cartoon") as demo:
202
+ gr.Markdown("# Upload or capture once β€” get age prediction first, then a faster cartoon ✨")
 
 
 
203
 
204
  with gr.Row():
205
  with gr.Column(scale=1):
206
+ img_in = gr.Image(sources=["upload", "webcam"], type="pil", label="Upload / Webcam")
207
+ auto = gr.Checkbox(True, label="Auto face crop (wide, recommended)")
208
+ prompt = gr.Textbox(
209
+ label="(Optional) Extra cartoon style",
210
+ placeholder="e.g., studio ghibli watercolor, soft bokeh, pastel palette"
211
+ )
212
  with gr.Row():
213
+ strength = gr.Slider(0.3, 0.8, value=0.5, step=0.05, label="Cartoon strength")
214
+ steps = gr.Slider(1, 4, value=2, step=1, label="Turbo steps (1–4)")
 
215
  seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")
216
+
217
+ btn_age = gr.Button("Predict Age (fast)", variant="primary")
218
+ btn_cartoon = gr.Button("Make Cartoon (fast)", variant="secondary")
219
 
220
  with gr.Column(scale=1):
221
  probs_out = gr.Label(num_top_classes=5, label="Age Prediction (probabilities)")
222
  age_md = gr.Markdown(label="Age Summary")
223
+ preview = gr.Image(label="Detection Preview")
224
  cartoon_out = gr.Image(label="Cartoon Result")
225
 
226
+ # Wire the buttons
227
+ btn_age.click(fn=predict_age_only, inputs=[img_in, auto], outputs=[probs_out, age_md, preview])
228
+ btn_cartoon.click(fn=generate_cartoon, inputs=[img_in, prompt, auto, strength, steps, seed], outputs=cartoon_out)
229
 
230
  if __name__ == "__main__":
231
  demo.launch()