tarfandoon commited on
Commit
3d984fa
·
verified ·
1 Parent(s): cef09da

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -3
app.py CHANGED
@@ -9,6 +9,9 @@ Telegram: https://t.me/tarfandoonchannel
9
  """
10
 
11
  import argparse
 
 
 
12
  import os
13
  import tempfile
14
  from dataclasses import dataclass
@@ -643,6 +646,186 @@ ON_SPACES = bool(os.environ.get("SPACE_ID"))
643
  MODEL = None
644
 
645
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
646
  def build_step_guides(width_cm: float, height_cm: float, cell_w: float, cell_h: float) -> Dict[int, str]:
647
  return {
648
  1: (
@@ -709,7 +892,7 @@ def _gpu_decorator(fn):
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)
@@ -800,6 +983,7 @@ def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int
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,
@@ -828,6 +1012,7 @@ def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int
828
  gr.update(choices=color_choices, value=color_choices[0]),
829
  attention_img,
830
  value_study,
 
831
  )
832
 
833
 
@@ -1032,8 +1217,18 @@ def build_ui():
1032
  attn_out = gr.Image(label="🔥 نقشه کانون توجه چشم (ConvNeXt Deep Focal Map)")
1033
  val_out = gr.Image(label="🌗 مطالعه ارزش نوری ۳ سطحی (تیره / میانی / روشن)")
1034
 
1035
- # TAB 4: Check My Hand-Painted Canvas
1036
- with gr.Tab("🏆 ۴. ارزیابی نقاشیِ دستِ تو"):
 
 
 
 
 
 
 
 
 
 
1037
  gr.Markdown("از نقاشی‌ای که خودت با دست روی بوم یا کاغذ کشیدی عکس بگیر و اینجا آپلود کن تا **امتیاز ۰ تا ۱۰۰ و نقشه اصلاح** بگیری!")
1038
  with gr.Row():
1039
  user_canvas_in = gr.Image(type="numpy", label="📸 عکس نقاشیِ دستِ خودت")
@@ -1072,6 +1267,7 @@ def build_ui():
1072
  color_dropdown,
1073
  attn_out,
1074
  val_out,
 
1075
  ],
1076
  )
1077
 
 
9
  """
10
 
11
  import argparse
12
+ import base64
13
+ import html as html_lib
14
+ import io
15
  import os
16
  import tempfile
17
  from dataclasses import dataclass
 
646
  MODEL = None
647
 
648
 
649
+ def _img_to_b64_jpeg(img_rgb: np.ndarray, max_side: int = 768, quality: int = 85) -> str:
650
+ h, w = img_rgb.shape[:2]
651
+ scale = min(1.0, max_side / max(h, w))
652
+ if scale < 1.0:
653
+ img_rgb = cv2.resize(img_rgb, (int(round(w * scale)), int(round(h * scale))), interpolation=cv2.INTER_AREA)
654
+ buf = io.BytesIO()
655
+ Image.fromarray(img_rgb).save(buf, format="JPEG", quality=quality)
656
+ return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii")
657
+
658
+
659
+ def build_ar_camera_html(rough_rgb: np.ndarray, sketch_rgb: np.ndarray, block_rgb: np.ndarray, final_rgb: np.ndarray) -> str:
660
+ """
661
+ 60-FPS Browser-Native AR Canvas Tracing Studio (Phone Back Camera & Laptop Webcam)!
662
+ Uses CSS `mix-blend-mode: multiply` so white paper becomes 100% transparent and
663
+ ONLY the crisp pencil lines float directly over the user's real paper/canvas.
664
+ """
665
+ b64_rough = _img_to_b64_jpeg(rough_rgb)
666
+ b64_sketch = _img_to_b64_jpeg(sketch_rgb)
667
+ b64_block = _img_to_b64_jpeg(block_rgb)
668
+ b64_final = _img_to_b64_jpeg(final_rgb)
669
+
670
+ inner_doc = f"""<!DOCTYPE html>
671
+ <html lang="fa" dir="rtl">
672
+ <head>
673
+ <meta charset="utf-8" />
674
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
675
+ <style>
676
+ * {{ box-sizing: border-box; font-family: system-ui, -apple-system, sans-serif; }}
677
+ body {{ margin: 0; padding: 12px; background: #fffdf9; color: #111827; }}
678
+ .controls {{
679
+ display: flex; flex-wrap: wrap; gap: 8px; align-items: center;
680
+ background: #fef6e8; border: 1px solid #e5d1b3; border-radius: 14px;
681
+ padding: 12px; margin-bottom: 12px;
682
+ }}
683
+ button, select {{
684
+ padding: 8px 14px; border-radius: 10px; border: 1px solid #d1d5db;
685
+ background: #1f2937; color: #fff; font-weight: 700; font-size: 13px; cursor: pointer;
686
+ }}
687
+ button.primary {{ background: #d97706; border-color: #b45309; }}
688
+ button.secondary {{ background: #ffffff; color: #1f2937; }}
689
+ select {{ background: #ffffff; color: #111827; }}
690
+ label.rng {{
691
+ display: inline-flex; align-items: center; gap: 6px; font-size: 12px;
692
+ font-weight: 700; color: #374151; background: #fff; padding: 6px 10px;
693
+ border-radius: 10px; border: 1px solid #e5e7eb;
694
+ }}
695
+ .stage-wrap {{
696
+ position: relative; width: 100%; height: 540px; background: #111827;
697
+ border-radius: 16px; overflow: hidden; border: 2px solid #e5d1b3;
698
+ touch-action: none; user-select: none;
699
+ }}
700
+ video#cam {{
701
+ position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;
702
+ }}
703
+ img#overlay {{
704
+ position: absolute; top: 50%; left: 50%;
705
+ max-width: 92%; max-height: 92%;
706
+ transform: translate(-50%, -50%) scale(1);
707
+ opacity: 0.72; pointer-events: none;
708
+ mix-blend-mode: multiply;
709
+ filter: contrast(1.25);
710
+ }}
711
+ .hint {{
712
+ position: absolute; bottom: 10px; right: 12px; left: 12px;
713
+ background: rgba(17, 24, 39, 0.75); color: #fff;
714
+ padding: 8px 12px; border-radius: 10px; font-size: 12px; text-align: center;
715
+ }}
716
+ </style>
717
+ </head>
718
+ <body>
719
+ <div class="controls">
720
+ <button class="primary" onclick="startCam()">📷 روشن کردن دوربین</button>
721
+ <button class="secondary" onclick="flipCam()">🔄 تعویض دوربین (پشت/جلو)</button>
722
+ <select id="layerSel" onchange="changeLayer()">
723
+ <option value="rough">لایه ۱: خطوط اصلی (شفاف روی کاغذ)</option>
724
+ <option value="sketch" selected>لایه ۲: اسکچ کامل مدادی (پیشنهادی)</option>
725
+ <option value="block">لایه ۳: لکه‌های رنگی پایه</option>
726
+ <option value="final">لایه ۴: نقاشی نهایی</option>
727
+ </select>
728
+ <label class="rng">شفافیت <input id="opRng" type="range" min="10" max="100" value="75" oninput="updateTransform()"></label>
729
+ <label class="rng">اندازه <input id="scRng" type="range" min="40" max="180" value="100" oninput="updateTransform()"></label>
730
+ <button class="secondary" onclick="toggleBlend()" id="blendBtn">✨ حذف پس‌زمینه سفید: روشن</button>
731
+ <button class="secondary" onclick="toggleMirror()">🪞 آینه‌ای</button>
732
+ <button class="secondary" onclick="goFullscreen()">⛶ تمام‌صفحه</button>
733
+ </div>
734
+
735
+ <div class="stage-wrap" id="arBox">
736
+ <video id="cam" autoplay playsinline muted></video>
737
+ <img id="overlay" src="{b64_sketch}" alt="AR Sketch Overlay" />
738
+ <div class="hint" id="statusMsg">دکمه «📷 روشن کردن دوربین» را بزن، گوشی را روی پایه بگذار و با انگشت یا ماوس طرح را روی کاغذ واقعی تنظیم کن!</div>
739
+ </div>
740
+
741
+ <script>
742
+ const LAYERS = {{
743
+ rough: "{b64_rough}",
744
+ sketch: "{b64_sketch}",
745
+ block: "{b64_block}",
746
+ final: "{b64_final}"
747
+ }};
748
+ let stream = null;
749
+ let facing = "environment";
750
+ let multiplyOn = true;
751
+ let mirrored = false;
752
+ let dx = 0, dy = 0, dragging = false, sx = 0, sy = 0;
753
+
754
+ async function startCam() {{
755
+ const msg = document.getElementById("statusMsg");
756
+ try {{
757
+ if (stream) stream.getTracks().forEach(t => t.stop());
758
+ stream = await navigator.mediaDevices.getUserMedia({{
759
+ video: {{ facingMode: {{ ideal: facing }}, width: {{ ideal: 1280 }}, height: {{ ideal: 720 }} }},
760
+ audio: false
761
+ }});
762
+ document.getElementById("cam").srcObject = stream;
763
+ msg.textContent = "✅ دوربین فعال شد! طرح را با کشیدن (Drag) و اسلایدر اندازه دقیقاً روی کاغذت تنظیم کن و با مداد بکش.";
764
+ }} catch (e) {{
765
+ msg.textContent = "⚠️ دسترسی به دوربین داده نشد یا دوربین پیدا نشد: " + e.message;
766
+ }}
767
+ }}
768
+
769
+ function flipCam() {{
770
+ facing = (facing === "environment") ? "user" : "environment";
771
+ startCam();
772
+ }}
773
+
774
+ function changeLayer() {{
775
+ const v = document.getElementById("layerSel").value;
776
+ const ov = document.getElementById("overlay");
777
+ ov.src = LAYERS[v];
778
+ // For sketch layers, multiply mode makes white paper 100% invisible!
779
+ multiplyOn = (v === "rough" || v === "sketch");
780
+ ov.style.mixBlendMode = multiplyOn ? "multiply" : "normal";
781
+ document.getElementById("blendBtn").textContent = "✨ حذف پس‌زمینه سفید: " + (multiplyOn ? "روشن" : "خاموش");
782
+ }}
783
+
784
+ function toggleBlend() {{
785
+ multiplyOn = !multiplyOn;
786
+ document.getElementById("overlay").style.mixBlendMode = multiplyOn ? "multiply" : "normal";
787
+ document.getElementById("blendBtn").textContent = "✨ حذف پس‌زمینه سفید: " + (multiplyOn ? "روشن" : "خاموش");
788
+ }}
789
+
790
+ function toggleMirror() {{
791
+ mirrored = !mirrored;
792
+ updateTransform();
793
+ }}
794
+
795
+ function updateTransform() {{
796
+ const ov = document.getElementById("overlay");
797
+ const op = document.getElementById("opRng").value / 100.0;
798
+ const sc = document.getElementById("scRng").value / 100.0;
799
+ const fx = mirrored ? -sc : sc;
800
+ ov.style.opacity = op;
801
+ ov.style.transform = `translate(calc(-50% + ${{dx}}px), calc(-50% + ${{dy}}px)) scale(${{fx}}, ${{sc}})`;
802
+ }}
803
+
804
+ function goFullscreen() {{
805
+ const box = document.getElementById("arBox");
806
+ if (box.requestFullscreen) box.requestFullscreen();
807
+ }}
808
+
809
+ // Drag overlay smoothly with mouse or touch to align on real paper
810
+ const box = document.getElementById("arBox");
811
+ box.addEventListener("pointerdown", e => {{ dragging = true; sx = e.clientX - dx; sy = e.clientY - dy; }});
812
+ window.addEventListener("pointermove", e => {{
813
+ if (!dragging) return;
814
+ dx = e.clientX - sx; dy = e.clientY - sy;
815
+ updateTransform();
816
+ }});
817
+ window.addEventListener("pointerup", () => {{ dragging = false; }});
818
+ </script>
819
+ </body>
820
+ </html>"""
821
+
822
+ escaped = html_lib.escape(inner_doc, quote=True)
823
+ return (
824
+ f'<iframe srcdoc="{escaped}" allow="camera; fullscreen" '
825
+ f'style="width:100%; height:670px; border:none; border-radius:16px; background:#fffdf9;"></iframe>'
826
+ )
827
+
828
+
829
  def build_step_guides(width_cm: float, height_cm: float, cell_w: float, cell_h: float) -> Dict[int, str]:
830
  return {
831
  1: (
 
892
  @torch.no_grad()
893
  def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int):
894
  if input_img is None or MODEL is None:
895
+ return None, "", None, None, None, "لطفاً ابتدا یک نقاشی آپلود کن.", 1, 1.0, [], None, None, None, "", gr.update(), None, None, ""
896
 
897
  dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
898
  MODEL.to(dev)
 
983
  focal_hi = cv2.resize(focal_01, (hi_final.shape[1], hi_final.shape[0]), interpolation=cv2.INTER_LINEAR)
984
  attention_img = make_attention_overlay(hi_final, focal_hi)
985
  value_study = make_value_study_3tone(hi_final)
986
+ ar_html = build_ar_camera_html(m_rough, m_sketch, m_block, resized)
987
 
988
  state = {
989
  "resized": hi_final,
 
1012
  gr.update(choices=color_choices, value=color_choices[0]),
1013
  attention_img,
1014
  value_study,
1015
+ ar_html,
1016
  )
1017
 
1018
 
 
1217
  attn_out = gr.Image(label="🔥 نقشه کانون توجه چشم (ConvNeXt Deep Focal Map)")
1218
  val_out = gr.Image(label="🌗 مطالعه ارزش نوری ۳ سطحی (تیره / میانی / روشن)")
1219
 
1220
+ # TAB 4: AR Live Camera Tracing (Phone Back Camera & Laptop Webcam!)
1221
+ with gr.Tab("📱 ۴. دوربین AR (کشیدن مستقیم روی کاغذ واقعی!)"):
1222
+ gr.Markdown(
1223
+ "### 📷 حالت واقعیت افزوده (AR Canvas Tracing) — بدون نیاز به اپلیکیشن!\n"
1224
+ "دوربین گوشی (یا وبکم) را روشن کن، پس‌زمینه سفید اسکچ **خودکار حذف می‌شود** و فقط خطوط مدادی روی تصویر زنده کاغذت می‌افتند — گوشی را روی پایه بگذار و مستقیم با مداد روی کاغذ واقعی بکش!"
1225
+ )
1226
+ ar_camera_out = gr.HTML(
1227
+ "<div style='padding:24px; text-align:center; background:#fff9ef; border:1px solid #e5d1b3; border-radius:14px; color:#374151;'>ابتدا در بالای صفحه یک نقاشی آپلود کن و دکمه «✨ ساخت نقشه ۷ مرحله‌ای» را بزن تا دوربین AR فعال شود!</div>"
1228
+ )
1229
+
1230
+ # TAB 5: Check My Hand-Painted Canvas
1231
+ with gr.Tab("🏆 ۵. ارزیابی نقاشیِ دستِ تو"):
1232
  gr.Markdown("از نقاشی‌ای که خودت با دست روی بوم یا کاغذ کشیدی عکس بگیر و اینجا آپلود کن تا **امتیاز ۰ تا ۱۰۰ و نقشه اصلاح** بگیری!")
1233
  with gr.Row():
1234
  user_canvas_in = gr.Image(type="numpy", label="📸 عکس نقاشیِ دستِ خودت")
 
1267
  color_dropdown,
1268
  attn_out,
1269
  val_out,
1270
+ ar_camera_out,
1271
  ],
1272
  )
1273