tarfandoon commited on
Commit
cef09da
·
verified ·
1 Parent(s): 4ba278b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -40
app.py CHANGED
@@ -292,6 +292,35 @@ def polish_continuous_sketch(sketch_rgb: np.ndarray) -> np.ndarray:
292
  return np.ascontiguousarray(out)
293
 
294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  def draw_cm_ruler_grid(img_rgb: np.ndarray, width_cm: float, grid_n: int = 4) -> Tuple[np.ndarray, float, float, float]:
296
  """
297
  Draws a clean real-world centimeter ruler border + 4x4 grid on the sketch
@@ -680,13 +709,17 @@ def _gpu_decorator(fn):
680
  @torch.no_grad()
681
  def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int):
682
  if input_img is None or MODEL is None:
683
- return None, "", None, None, None, "لطفاً ابتدا یک نقاشی آپلود کن.", 1, [], None, None, None, "", gr.update(), None, None
684
 
685
  dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
686
  MODEL.to(dev)
687
 
688
  clean = auto_crop_borders(input_img)
689
  h, w = clean.shape[:2]
 
 
 
 
690
  scale = 512.0 / max(h, w)
691
  nw = max(64, (int(round(w * scale)) // 32) * 32)
692
  nh = max(64, (int(round(h * scale)) // 32) * 32)
@@ -717,53 +750,65 @@ def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int
717
  m_shadow = stages_v2[4]
718
  m_detail = stages_v2[5]
719
 
720
- # Add real-world centimeter ruler & 4x4 grid to Stage 1 & Stage 2!
721
- st1_cm, height_cm, cell_w, cell_h = draw_cm_ruler_grid(m_rough, float(width_cm), grid_n=4)
722
- st2_cm, _, _, _ = draw_cm_ruler_grid(m_sketch, float(width_cm), grid_n=4)
 
 
 
 
 
 
 
 
 
 
 
 
 
723
 
724
  guides = build_step_guides(float(width_cm), height_cm, cell_w, cell_h)
725
  score_html = render_aesthetic_score_html(aes_val, float(width_cm), height_cm, cell_w, cell_h)
726
 
727
- # Smooth animations (both continuous pencil reveal & 7-stage timelapse)
728
- sketch_gif = make_smooth_sketch_animation(m_rough, m_sketch, float(width_cm))
729
- timelapse_gif = make_timelapse_gif([m_rough, m_sketch, m_sepia, m_block, m_shadow, m_detail, resized])
730
-
731
- step_imgs = {1: st1_cm, 2: st2_cm, 3: m_sepia, 4: m_block, 5: m_shadow, 6: m_detail, 7: resized}
732
- blank = np.full_like(resized, 248)
733
  paint_zones = {
734
  1: st1_cm,
735
  2: st2_cm,
736
- 3: make_clear_paint_zones(blank, m_sepia),
737
- 4: make_clear_paint_zones(m_sepia, m_block),
738
- 5: make_clear_paint_zones(m_block, m_shadow),
739
- 6: make_clear_paint_zones(m_shadow, m_detail),
740
- 7: make_clear_paint_zones(m_detail, resized),
741
  }
742
 
743
  gallery_items = [
744
  (st1_cm, "۱. کادر و خطوط اصلی (cm)"),
745
  (st2_cm, "۲. اسکچ کامل مدادی"),
746
- (m_sepia, "۳. زیررنگ سپیا"),
747
- (m_block, "۴. رنگ‌گذاری پایه"),
748
- (m_shadow, "۵. سایه‌ها و حجم"),
749
- (m_detail, "۶. جزئیات میانی"),
750
- (resized, "۷. نقاشی نهایی"),
751
  ]
752
 
753
  palette = extract_physical_palette(resized, k=int(num_colors))
754
  pal_card = render_palette_card(palette)
755
- loc_img, loc_html = highlight_target_rgb_on_canvas(resized, palette[0].rgb)
756
  color_choices = [f"رنگ #{c.index + 1} ({c.hex}) — {c.proportion * 100:.1f}%" for c in palette]
757
 
758
- attention_img = make_attention_overlay(resized, focal_01)
759
- value_study = make_value_study_3tone(resized)
 
760
 
761
  state = {
762
- "resized": resized,
763
  "step_imgs": step_imgs,
764
  "paint_zones": paint_zones,
765
  "guides": guides,
766
  "palette": palette,
 
 
767
  }
768
 
769
  return (
@@ -774,8 +819,9 @@ def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int
774
  step_imgs[1],
775
  guides[1],
776
  1,
 
777
  gallery_items,
778
- resized,
779
  pal_card,
780
  loc_img,
781
  loc_html,
@@ -785,20 +831,36 @@ def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int
785
  )
786
 
787
 
788
- def render_slide(step_num: int, show_zones: bool, state: Optional[dict]):
789
  if not state:
790
  return None, "ابتدا یک نقاشی آپلود کن.", 1
791
  s = max(1, min(7, int(step_num)))
792
- img = state["paint_zones"][s] if show_zones else state["step_imgs"][s]
793
- return img, state["guides"][s], s
 
794
 
795
 
796
- def prev_slide(step_num: int, show_zones: bool, state: Optional[dict]):
797
- return render_slide(max(1, int(step_num) - 1), show_zones, state)
798
 
799
 
800
- def next_slide(step_num: int, show_zones: bool, state: Optional[dict]):
801
- return render_slide(min(7, int(step_num) + 1), show_zones, state)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
802
 
803
 
804
  def on_color_dropdown(color_label: str, state: Optional[dict]):
@@ -925,15 +987,17 @@ def build_ui():
925
  # TAB 1: Interactive 7-Stage Slides + Smooth Animations
926
  with gr.Tab("🎬 ۱. آموزش ۷ مرحله‌ای + انیمیشن اسکچ و فیلم"):
927
  with gr.Row():
928
- with gr.Column(scale=1):
929
- gr.Markdown("### 🖼️ اسلاید تعاملی ۷ مرحله‌ای (با ابعاد سانتی‌متر)")
930
- slide_img = gr.Image(label="بوم هدف در مرحله فعلی", interactive=False)
931
  with gr.Row():
932
  prev_btn = gr.Button("⬅️ مرحله قبل")
933
  next_btn = gr.Button("مرحله بعد ➡️", variant="primary")
 
934
  with gr.Row():
935
  step_slider = gr.Slider(1, 7, value=1, step=1, label="شماره مرحله (۱ تا ۷)")
936
- zone_chk = gr.Checkbox(value=False, label="📍 نشان بده در این مرحله کجا را رنگ کنم!")
 
937
  slide_guide = gr.Markdown("پس از آپلود نقاشی، اینجا راهنمای دقیق هر مرحله (با سایز قلم‌مو و ابعاد بوم به سانتی‌متر) نمایش داده می‌شود.")
938
 
939
  with gr.Column(scale=1):
@@ -999,6 +1063,7 @@ def build_ui():
999
  slide_img,
1000
  slide_guide,
1001
  step_slider,
 
1002
  gallery_out,
1003
  clickable_img,
1004
  pal_out,
@@ -1010,10 +1075,13 @@ def build_ui():
1010
  ],
1011
  )
1012
 
1013
- step_slider.change(render_slide, [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider])
1014
- zone_chk.change(render_slide, [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider])
1015
- prev_btn.click(prev_slide, [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider])
1016
- next_btn.click(next_slide, [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider])
 
 
 
1017
  color_dropdown.change(on_color_dropdown, [color_dropdown, studio_state], [color_loc_img, color_recipe_html])
1018
  clickable_img.select(on_canvas_click, [studio_state], [color_loc_img, color_recipe_html])
1019
  check_btn.click(evaluate_amateur_painting, [in_img, user_canvas_in], [feedback_img_out, feedback_md_out])
 
292
  return np.ascontiguousarray(out)
293
 
294
 
295
+ def upscale_hi_res(img_rgb: np.ndarray, target_max: int = 1024, sharpen: bool = True) -> np.ndarray:
296
+ """Crisp Lanczos upscale to ~1024px so Maximize/Fullscreen & Zoom show rich detail."""
297
+ h, w = img_rgb.shape[:2]
298
+ if max(h, w) >= target_max:
299
+ return np.ascontiguousarray(img_rgb)
300
+ scale = target_max / max(h, w)
301
+ nw, nh = int(round(w * scale)), int(round(h * scale))
302
+ up = cv2.resize(img_rgb, (nw, nh), interpolation=cv2.INTER_LANCZOS4)
303
+ if sharpen:
304
+ blur = cv2.GaussianBlur(up, (0, 0), 1.2)
305
+ up = cv2.addWeighted(up, 1.25, blur, -0.25, 0)
306
+ return np.ascontiguousarray(up)
307
+
308
+
309
+ def render_zoom_crop(img_rgb: np.ndarray, zoom_level: float, cx_norm: float = 0.5, cy_norm: float = 0.5) -> np.ndarray:
310
+ """Return a crisp zoomed-in detail view around (cx_norm, cy_norm) at `zoom_level` (1.0 - 4.0x)."""
311
+ if zoom_level <= 1.05:
312
+ return img_rgb
313
+ h, w = img_rgb.shape[:2]
314
+ cw = max(64, int(round(w / zoom_level)))
315
+ ch = max(64, int(round(h / zoom_level)))
316
+ cx = int(round(cx_norm * w))
317
+ cy = int(round(cy_norm * h))
318
+ x0 = max(0, min(w - cw, cx - cw // 2))
319
+ y0 = max(0, min(h - ch, cy - ch // 2))
320
+ crop = img_rgb[y0 : y0 + ch, x0 : x0 + cw]
321
+ return np.ascontiguousarray(cv2.resize(crop, (w, h), interpolation=cv2.INTER_LANCZOS4))
322
+
323
+
324
  def draw_cm_ruler_grid(img_rgb: np.ndarray, width_cm: float, grid_n: int = 4) -> Tuple[np.ndarray, float, float, float]:
325
  """
326
  Draws a clean real-world centimeter ruler border + 4x4 grid on the sketch
 
709
  @torch.no_grad()
710
  def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int):
711
  if input_img is None or MODEL is None:
712
+ return None, "", None, None, None, "لطفاً ابتدا یک نقاشی آپلود کن.", 1, 1.0, [], None, None, None, "", gr.update(), None, None
713
 
714
  dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
715
  MODEL.to(dev)
716
 
717
  clean = auto_crop_borders(input_img)
718
  h, w = clean.shape[:2]
719
+ # Keep true high-res ~1024px original for crisp fullscreen & zooming
720
+ hi_scale = min(1.0, 1024.0 / max(h, w))
721
+ orig_hi = cv2.resize(clean, (int(round(w * hi_scale)), int(round(h * hi_scale))), interpolation=cv2.INTER_AREA)
722
+
723
  scale = 512.0 / max(h, w)
724
  nw = max(64, (int(round(w * scale)) // 32) * 32)
725
  nh = max(64, (int(round(h * scale)) // 32) * 32)
 
750
  m_shadow = stages_v2[4]
751
  m_detail = stages_v2[5]
752
 
753
+ # Smooth animations at fast 512px
754
+ sketch_gif = make_smooth_sketch_animation(m_rough, m_sketch, float(width_cm))
755
+ timelapse_gif = make_timelapse_gif([m_rough, m_sketch, m_sepia, m_block, m_shadow, m_detail, resized])
756
+
757
+ # Upscale ALL interactive display stages to crisp 1024px so Maximize & Zoom are razor-sharp!
758
+ hi_rough = upscale_hi_res(m_rough, 1024, sharpen=True)
759
+ hi_sketch = upscale_hi_res(m_sketch, 1024, sharpen=True)
760
+ hi_sepia = upscale_hi_res(m_sepia, 1024, sharpen=False)
761
+ hi_block = upscale_hi_res(m_block, 1024, sharpen=False)
762
+ hi_shadow = upscale_hi_res(m_shadow, 1024, sharpen=True)
763
+ hi_detail = upscale_hi_res(m_detail, 1024, sharpen=True)
764
+ hi_final = cv2.resize(orig_hi, (hi_detail.shape[1], hi_detail.shape[0]), interpolation=cv2.INTER_LANCZOS4)
765
+
766
+ # Render centimeter ruler & 4x4 grid AT 1024px for ultra-sharp readable numbers!
767
+ st1_cm, height_cm, cell_w, cell_h = draw_cm_ruler_grid(hi_rough, float(width_cm), grid_n=4)
768
+ st2_cm, _, _, _ = draw_cm_ruler_grid(hi_sketch, float(width_cm), grid_n=4)
769
 
770
  guides = build_step_guides(float(width_cm), height_cm, cell_w, cell_h)
771
  score_html = render_aesthetic_score_html(aes_val, float(width_cm), height_cm, cell_w, cell_h)
772
 
773
+ step_imgs = {1: st1_cm, 2: st2_cm, 3: hi_sepia, 4: hi_block, 5: hi_shadow, 6: hi_detail, 7: hi_final}
774
+ blank_hi = np.full_like(hi_final, 248)
 
 
 
 
775
  paint_zones = {
776
  1: st1_cm,
777
  2: st2_cm,
778
+ 3: make_clear_paint_zones(blank_hi, hi_sepia),
779
+ 4: make_clear_paint_zones(hi_sepia, hi_block),
780
+ 5: make_clear_paint_zones(hi_block, hi_shadow),
781
+ 6: make_clear_paint_zones(hi_shadow, hi_detail),
782
+ 7: make_clear_paint_zones(hi_detail, hi_final),
783
  }
784
 
785
  gallery_items = [
786
  (st1_cm, "۱. کادر و خطوط اصلی (cm)"),
787
  (st2_cm, "۲. اسکچ کامل مدادی"),
788
+ (hi_sepia, "۳. زیررنگ سپیا"),
789
+ (hi_block, "۴. رنگ‌گذاری پایه"),
790
+ (hi_shadow, "۵. سایه‌ها و حجم"),
791
+ (hi_detail, "۶. جزئیات میانی"),
792
+ (hi_final, "۷. نقاشی نهایی"),
793
  ]
794
 
795
  palette = extract_physical_palette(resized, k=int(num_colors))
796
  pal_card = render_palette_card(palette)
797
+ loc_img, loc_html = highlight_target_rgb_on_canvas(hi_final, palette[0].rgb)
798
  color_choices = [f"رنگ #{c.index + 1} ({c.hex}) — {c.proportion * 100:.1f}%" for c in palette]
799
 
800
+ focal_hi = cv2.resize(focal_01, (hi_final.shape[1], hi_final.shape[0]), interpolation=cv2.INTER_LINEAR)
801
+ attention_img = make_attention_overlay(hi_final, focal_hi)
802
+ value_study = make_value_study_3tone(hi_final)
803
 
804
  state = {
805
+ "resized": hi_final,
806
  "step_imgs": step_imgs,
807
  "paint_zones": paint_zones,
808
  "guides": guides,
809
  "palette": palette,
810
+ "zoom_cx": 0.5,
811
+ "zoom_cy": 0.5,
812
  }
813
 
814
  return (
 
819
  step_imgs[1],
820
  guides[1],
821
  1,
822
+ 1.0,
823
  gallery_items,
824
+ hi_final,
825
  pal_card,
826
  loc_img,
827
  loc_html,
 
831
  )
832
 
833
 
834
+ def render_slide(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict]):
835
  if not state:
836
  return None, "ابتدا یک نقاشی آپلود کن.", 1
837
  s = max(1, min(7, int(step_num)))
838
+ base = state["paint_zones"][s] if show_zones else state["step_imgs"][s]
839
+ zoomed = render_zoom_crop(base, float(zoom_level), state.get("zoom_cx", 0.5), state.get("zoom_cy", 0.5))
840
+ return zoomed, state["guides"][s], s
841
 
842
 
843
+ def prev_slide(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict]):
844
+ return render_slide(max(1, int(step_num) - 1), show_zones, zoom_level, state)
845
 
846
 
847
+ def next_slide(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict]):
848
+ return render_slide(min(7, int(step_num) + 1), show_zones, zoom_level, state)
849
+
850
+
851
+ def on_slide_click_zoom(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict], evt: gr.SelectData):
852
+ """Click anywhere on the slide to center the zoom lens right on that detail!"""
853
+ if not state:
854
+ return None, "ابتدا یک نقاشی آپلود کن.", 1, 1.0
855
+ s = max(1, min(7, int(step_num)))
856
+ base = state["paint_zones"][s] if show_zones else state["step_imgs"][s]
857
+ h, w = base.shape[:2]
858
+ # If currently at 1x, clicking auto-zooms to 2.5x right where clicked; otherwise re-centers zoom
859
+ new_zoom = 2.5 if float(zoom_level) <= 1.05 else float(zoom_level)
860
+ state["zoom_cx"] = float(np.clip(evt.index[0] / max(w, 1), 0.0, 1.0))
861
+ state["zoom_cy"] = float(np.clip(evt.index[1] / max(h, 1), 0.0, 1.0))
862
+ zoomed = render_zoom_crop(base, new_zoom, state["zoom_cx"], state["zoom_cy"])
863
+ return zoomed, state["guides"][s], s, new_zoom
864
 
865
 
866
  def on_color_dropdown(color_label: str, state: Optional[dict]):
 
987
  # TAB 1: Interactive 7-Stage Slides + Smooth Animations
988
  with gr.Tab("🎬 ۱. آموزش ۷ مرحله‌ای + انیمیشن اسکچ و فیلم"):
989
  with gr.Row():
990
+ with gr.Column(scale=2):
991
+ gr.Markdown("### 🖼️ اسلاید تعاملی ۷ مرحله‌ای (کیفیت بالا 1024px — برای زوم روی هر نقطه کلیک کن!)")
992
+ slide_img = gr.Image(label="بوم هدف (کلیک روی تصویر = زوم روی جزئیات | آیکون فول‌اسکرین = تمام‌صفحه HD)", height=540, interactive=False)
993
  with gr.Row():
994
  prev_btn = gr.Button("⬅️ مرحله قبل")
995
  next_btn = gr.Button("مرحله بعد ➡️", variant="primary")
996
+ reset_zoom_btn = gr.Button("🔍 ریست زوم (1×)")
997
  with gr.Row():
998
  step_slider = gr.Slider(1, 7, value=1, step=1, label="شماره مرحله (۱ تا ۷)")
999
+ zoom_slider = gr.Slider(1.0, 4.0, value=1.0, step=0.25, label="🔍 بزرگ‌نمایی / زوم (1× تا 4×)")
1000
+ zone_chk = gr.Checkbox(value=False, label="📍 نشان بده در این مرحله کجا را رنگ کنم!")
1001
  slide_guide = gr.Markdown("پس از آپلود نقاشی، اینجا راهنمای دقیق هر مرحله (با سایز قلم‌مو و ابعاد بوم به سانتی‌متر) نمایش داده می‌شود.")
1002
 
1003
  with gr.Column(scale=1):
 
1063
  slide_img,
1064
  slide_guide,
1065
  step_slider,
1066
+ zoom_slider,
1067
  gallery_out,
1068
  clickable_img,
1069
  pal_out,
 
1075
  ],
1076
  )
1077
 
1078
+ step_slider.change(render_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider])
1079
+ zone_chk.change(render_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider])
1080
+ zoom_slider.change(render_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider])
1081
+ prev_btn.click(prev_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider])
1082
+ next_btn.click(next_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider])
1083
+ slide_img.select(on_slide_click_zoom, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider, zoom_slider])
1084
+ reset_zoom_btn.click(lambda s, z, st: (*render_slide(s, z, 1.0, st), 1.0), [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider, zoom_slider])
1085
  color_dropdown.change(on_color_dropdown, [color_dropdown, studio_state], [color_loc_img, color_recipe_html])
1086
  clickable_img.select(on_canvas_click, [studio_state], [color_loc_img, color_recipe_html])
1087
  check_btn.click(evaluate_amateur_painting, [in_img, user_canvas_in], [feedback_img_out, feedback_md_out])