LiangLabUMB commited on
Commit
e03bc05
Β·
verified Β·
1 Parent(s): 60a26e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -108
app.py CHANGED
@@ -678,14 +678,12 @@ def compute_summary(r1, r2, r3, r4):
678
  # ---------------------------------------------------------------------------
679
  def make_crop_canvas_html(tab_idx):
680
  """
681
- Return an HTML string containing a canvas-based polygon selector.
682
- The user clicks/taps up to 4 points; JS writes pixel coords (mapped
683
- back to original image space) into a hidden textbox with id
684
- f'crop_pts_{tab_idx}'. A 'Clear' button resets the polygon.
685
- The canvas listens for the Gradio img_input change event by watching
686
- a sibling img element (Gradio renders <img> inside the component).
687
  """
688
- uid = f"cropcanvas_{tab_idx}"
689
  pts_id = f"crop_pts_{tab_idx}"
690
  return f"""
691
  <div style="position:relative;width:100%;user-select:none;">
@@ -700,8 +698,7 @@ def make_crop_canvas_html(tab_idx):
700
  background:#e05;color:#fff;font-size:14px;cursor:pointer;">
701
  βœ• Clear points
702
  </button>
703
- <span id="{uid}_label"
704
- style="font-size:13px;color:#aaa;">
705
  Upload an image, then tap up to 4 vertices
706
  </span>
707
  </div>
@@ -709,24 +706,20 @@ def make_crop_canvas_html(tab_idx):
709
 
710
  <script>
711
  (function(){{
712
- const CANVAS_ID = "{uid}";
713
- const PTS_ID = "{pts_id}";
714
- const TAB_IDX = {tab_idx};
715
- const MAX_PTS = 4;
716
 
717
  let imgNaturalW = 0, imgNaturalH = 0;
718
- let points = []; // {{cx, cy}} in canvas CSS pixels
719
- let imgSrc = null;
720
  let imgObj = new Image();
721
 
722
- const canvas = document.getElementById(CANVAS_ID);
723
- const ctx = canvas.getContext("2d");
724
- const clearBtn= document.getElementById(CANVAS_ID + "_clear");
725
- const label = document.getElementById(CANVAS_ID + "_label");
726
 
727
- // ── helpers ──────────────────────────────────────────────────────────────
728
  function getPtsTextbox() {{
729
- // Gradio hides the real <textarea> inside a wrapper. Find by elem id.
730
  return document.getElementById(PTS_ID)?.querySelector("textarea")
731
  || document.querySelector(`#${{PTS_ID}} textarea`);
732
  }}
@@ -735,145 +728,113 @@ def make_crop_canvas_html(tab_idx):
735
  const ta = getPtsTextbox();
736
  if (!ta) return;
737
  ta.value = JSON.stringify(pts_orig);
738
- ta.dispatchEvent(new Event("input", {{bubbles:true}}));
739
  ta.dispatchEvent(new Event("change", {{bubbles:true}}));
740
  }}
741
 
742
  function canvasToOriginal(cx, cy) {{
743
- // canvas.width / height are the backing-store pixel dimensions
744
- const scaleX = imgNaturalW / canvas.width;
745
- const scaleY = imgNaturalH / canvas.height;
746
- return [Math.round(cx * scaleX), Math.round(cy * scaleY)];
747
  }}
748
 
749
  function draw() {{
750
  ctx.clearRect(0, 0, canvas.width, canvas.height);
751
- if (imgObj.complete && imgObj.naturalWidth) {{
752
  ctx.drawImage(imgObj, 0, 0, canvas.width, canvas.height);
753
- }}
754
- if (points.length === 0) return;
755
 
756
- // polygon fill
757
  ctx.beginPath();
758
  ctx.moveTo(points[0].cx, points[0].cy);
759
  for (let i = 1; i < points.length; i++) ctx.lineTo(points[i].cx, points[i].cy);
760
  if (points.length === MAX_PTS) ctx.closePath();
761
- ctx.strokeStyle = "#4af";
762
- ctx.lineWidth = 2;
763
- ctx.stroke();
764
  if (points.length === MAX_PTS) {{
765
- ctx.fillStyle = "rgba(74,170,255,0.18)";
766
- ctx.fill();
767
  }}
768
-
769
- // vertex dots + numbers
770
  points.forEach((p, i) => {{
771
- ctx.beginPath();
772
- ctx.arc(p.cx, p.cy, 7, 0, Math.PI*2);
773
- ctx.fillStyle = "#4af";
774
- ctx.fill();
775
- ctx.strokeStyle = "#fff";
776
- ctx.lineWidth = 1.5;
777
- ctx.stroke();
778
- ctx.fillStyle = "#fff";
779
- ctx.font = "bold 11px sans-serif";
780
- ctx.textAlign = "center";
781
- ctx.textBaseline = "middle";
782
  ctx.fillText(i+1, p.cx, p.cy);
783
  }});
784
  }}
785
 
786
- function loadImage(src) {{
787
- imgSrc = src;
788
  imgObj = new Image();
789
  imgObj.onload = function() {{
790
  imgNaturalW = imgObj.naturalWidth;
791
  imgNaturalH = imgObj.naturalHeight;
792
- // size canvas backing store to match natural image (capped for memory)
793
  const maxSide = 1024;
794
  let cw = imgNaturalW, ch = imgNaturalH;
795
  if (Math.max(cw,ch) > maxSide) {{
796
  const s = maxSide / Math.max(cw,ch);
797
  cw = Math.round(cw*s); ch = Math.round(ch*s);
798
  }}
799
- canvas.width = cw;
800
- canvas.height = ch;
801
- points = [];
802
- writePts([]);
803
  label.textContent = "Tap up to 4 vertices to define your crop region";
804
  draw();
805
  }};
806
- imgObj.src = src;
807
  }}
808
 
809
- // ── pointer events (works for mouse + touch) ──────────────────────────
 
 
 
810
  canvas.addEventListener("pointerdown", function(e) {{
811
  e.preventDefault();
812
- if (!imgNaturalW) return;
813
- if (points.length >= MAX_PTS) return;
814
-
815
  const rect = canvas.getBoundingClientRect();
816
- const cssX = e.clientX - rect.left;
817
- const cssY = e.clientY - rect.top;
818
- // map CSS pixels β†’ backing-store pixels
819
- const bx = cssX * (canvas.width / rect.width);
820
- const by = cssY * (canvas.height / rect.height);
821
-
822
  points.push({{cx: bx, cy: by}});
823
  draw();
824
-
825
- // write original-image coords to the hidden textbox
826
- const orig = points.map(p => canvasToOriginal(p.cx, p.cy));
827
- writePts(orig);
828
-
829
- if (points.length === MAX_PTS) {{
830
- label.textContent = "4 points set β€” clear to redraw";
831
- }} else {{
832
- label.textContent = `${{points.length}} / ${{MAX_PTS}} points`;
833
- }}
834
  }});
835
 
836
  clearBtn.addEventListener("click", function() {{
837
- points = [];
838
- writePts([]);
839
  label.textContent = "Points cleared β€” tap to add new vertices";
840
  draw();
841
  }});
842
-
843
- // ── watch for Gradio image uploads ────────────────────────────────────
844
- // Gradio renders the uploaded image as an <img> inside the component.
845
- // We poll for it until found, then watch src changes with MutationObserver.
846
- function findGradioImg() {{
847
- // Gradio wraps img_input in a div whose data-testid = "image"
848
- // Walk up from our canvas to find the nearest Gradio Blocks row,
849
- // then find the image component in the same Tab.
850
- const allImgs = document.querySelectorAll(".gradio-image img, [data-testid='image'] img");
851
- // pick the one closest to our canvas in the DOM
852
- if (allImgs.length === 0) return null;
853
- // heuristic: find closest ancestor shared with canvas
854
- for (const img of allImgs) {{
855
- if (img.src && img.src !== imgSrc) return img;
856
- }}
857
- return allImgs[0];
858
- }}
859
-
860
- let observer = null;
861
- function startWatching() {{
862
- const img = findGradioImg();
863
- if (!img) {{ setTimeout(startWatching, 500); return; }}
864
- if (img.src && img.src !== imgSrc) loadImage(img.src);
865
- if (observer) observer.disconnect();
866
- observer = new MutationObserver(() => {{
867
- if (img.src && img.src !== imgSrc) loadImage(img.src);
868
- }});
869
- observer.observe(img, {{attributes: true, attributeFilter: ["src"]}});
870
- }}
871
- setTimeout(startWatching, 800);
872
  }})();
873
  </script>
874
  """
875
 
876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
877
  def build_tab(tab_index, masks_state, image_state, result_state):
878
  with gr.Tab(f"Tab {tab_index}"):
879
  gr.Markdown("Run segmentation")
@@ -890,6 +851,10 @@ def build_tab(tab_index, masks_state, image_state, result_state):
890
  # Lightweight polygon crop selector (no ImageEditor)
891
  gr.HTML(make_crop_canvas_html(tab_index))
892
 
 
 
 
 
893
  # Hidden textbox that receives [[x,y],...] from JS
894
  crop_points = gr.Textbox(
895
  value="",
@@ -1005,6 +970,11 @@ def build_tab(tab_index, masks_state, image_state, result_state):
1005
  inputs=[img_input, left_excl, top_excl],
1006
  outputs=[excl_preview]
1007
  )
 
 
 
 
 
1008
  left_excl.change(
1009
  fn=update_exclusion_preview,
1010
  inputs=[img_input, left_excl, top_excl],
 
678
  # ---------------------------------------------------------------------------
679
  def make_crop_canvas_html(tab_idx):
680
  """
681
+ Static HTML+JS for the polygon crop canvas.
682
+ Image data is pushed from Python via push_image_to_canvas().
683
+ A global function window.loadCropCanvas_{uid}(dataURL) is registered
684
+ so the gr.HTML update triggered by img_input.change can load the image.
 
 
685
  """
686
+ uid = f"cropcanvas_{tab_idx}"
687
  pts_id = f"crop_pts_{tab_idx}"
688
  return f"""
689
  <div style="position:relative;width:100%;user-select:none;">
 
698
  background:#e05;color:#fff;font-size:14px;cursor:pointer;">
699
  βœ• Clear points
700
  </button>
701
+ <span id="{uid}_label" style="font-size:13px;color:#aaa;">
 
702
  Upload an image, then tap up to 4 vertices
703
  </span>
704
  </div>
 
706
 
707
  <script>
708
  (function(){{
709
+ const CANVAS_ID = "{uid}";
710
+ const PTS_ID = "{pts_id}";
711
+ const MAX_PTS = 4;
 
712
 
713
  let imgNaturalW = 0, imgNaturalH = 0;
714
+ let points = [];
 
715
  let imgObj = new Image();
716
 
717
+ const canvas = document.getElementById(CANVAS_ID);
718
+ const ctx = canvas.getContext("2d");
719
+ const clearBtn = document.getElementById(CANVAS_ID + "_clear");
720
+ const label = document.getElementById(CANVAS_ID + "_label");
721
 
 
722
  function getPtsTextbox() {{
 
723
  return document.getElementById(PTS_ID)?.querySelector("textarea")
724
  || document.querySelector(`#${{PTS_ID}} textarea`);
725
  }}
 
728
  const ta = getPtsTextbox();
729
  if (!ta) return;
730
  ta.value = JSON.stringify(pts_orig);
731
+ ta.dispatchEvent(new Event("input", {{bubbles:true}}));
732
  ta.dispatchEvent(new Event("change", {{bubbles:true}}));
733
  }}
734
 
735
  function canvasToOriginal(cx, cy) {{
736
+ return [Math.round(cx * imgNaturalW / canvas.width),
737
+ Math.round(cy * imgNaturalH / canvas.height)];
 
 
738
  }}
739
 
740
  function draw() {{
741
  ctx.clearRect(0, 0, canvas.width, canvas.height);
742
+ if (imgObj.complete && imgObj.naturalWidth)
743
  ctx.drawImage(imgObj, 0, 0, canvas.width, canvas.height);
744
+ if (!points.length) return;
 
745
 
 
746
  ctx.beginPath();
747
  ctx.moveTo(points[0].cx, points[0].cy);
748
  for (let i = 1; i < points.length; i++) ctx.lineTo(points[i].cx, points[i].cy);
749
  if (points.length === MAX_PTS) ctx.closePath();
750
+ ctx.strokeStyle = "#4af"; ctx.lineWidth = 2; ctx.stroke();
 
 
751
  if (points.length === MAX_PTS) {{
752
+ ctx.fillStyle = "rgba(74,170,255,0.18)"; ctx.fill();
 
753
  }}
 
 
754
  points.forEach((p, i) => {{
755
+ ctx.beginPath(); ctx.arc(p.cx, p.cy, 7, 0, Math.PI*2);
756
+ ctx.fillStyle = "#4af"; ctx.fill();
757
+ ctx.strokeStyle = "#fff"; ctx.lineWidth = 1.5; ctx.stroke();
758
+ ctx.fillStyle = "#fff"; ctx.font = "bold 11px sans-serif";
759
+ ctx.textAlign = "center"; ctx.textBaseline = "middle";
 
 
 
 
 
 
760
  ctx.fillText(i+1, p.cx, p.cy);
761
  }});
762
  }}
763
 
764
+ // ── called by Python push via gr.HTML update ──────────────────────────
765
+ function loadFromDataURL(dataURL) {{
766
  imgObj = new Image();
767
  imgObj.onload = function() {{
768
  imgNaturalW = imgObj.naturalWidth;
769
  imgNaturalH = imgObj.naturalHeight;
 
770
  const maxSide = 1024;
771
  let cw = imgNaturalW, ch = imgNaturalH;
772
  if (Math.max(cw,ch) > maxSide) {{
773
  const s = maxSide / Math.max(cw,ch);
774
  cw = Math.round(cw*s); ch = Math.round(ch*s);
775
  }}
776
+ canvas.width = cw; canvas.height = ch;
777
+ points = []; writePts([]);
 
 
778
  label.textContent = "Tap up to 4 vertices to define your crop region";
779
  draw();
780
  }};
781
+ imgObj.src = dataURL;
782
  }}
783
 
784
+ // Register globally so the injected <script> snippet can call it
785
+ window["loadCropCanvas_{uid}"] = loadFromDataURL;
786
+
787
+ // ── pointer / touch events ────────────────────────────────────────────
788
  canvas.addEventListener("pointerdown", function(e) {{
789
  e.preventDefault();
790
+ if (!imgNaturalW || points.length >= MAX_PTS) return;
 
 
791
  const rect = canvas.getBoundingClientRect();
792
+ const bx = (e.clientX - rect.left) * (canvas.width / rect.width);
793
+ const by = (e.clientY - rect.top) * (canvas.height / rect.height);
 
 
 
 
794
  points.push({{cx: bx, cy: by}});
795
  draw();
796
+ writePts(points.map(p => canvasToOriginal(p.cx, p.cy)));
797
+ label.textContent = points.length === MAX_PTS
798
+ ? "4 points set β€” clear to redraw"
799
+ : `${{points.length}} / ${{MAX_PTS}} points`;
 
 
 
 
 
 
800
  }});
801
 
802
  clearBtn.addEventListener("click", function() {{
803
+ points = []; writePts([]);
 
804
  label.textContent = "Points cleared β€” tap to add new vertices";
805
  draw();
806
  }});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
807
  }})();
808
  </script>
809
  """
810
 
811
 
812
+ def push_image_to_canvas(image_pil, tab_idx):
813
+ """
814
+ Convert the uploaded PIL image to a base64 data URL and return a
815
+ gr.HTML snippet that calls the canvas loader function registered by
816
+ make_crop_canvas_html. Returned value is set on a hidden gr.HTML
817
+ component whose change fires the JS.
818
+ """
819
+ if image_pil is None:
820
+ return ""
821
+ uid = f"cropcanvas_{tab_idx}"
822
+ buf = io.BytesIO()
823
+ # Downscale for the preview only β€” keep it lightweight
824
+ thumb = image_pil.copy()
825
+ thumb.thumbnail((1024, 1024), Image.LANCZOS)
826
+ thumb.save(buf, format="JPEG", quality=85)
827
+ b64 = base64.b64encode(buf.getvalue()).decode()
828
+ data_url = f"data:image/jpeg;base64,{b64}"
829
+ return f"""<script>
830
+ (function(){{
831
+ const fn = window["loadCropCanvas_{uid}"];
832
+ if (fn) {{ fn("{data_url}"); }}
833
+ else {{ setTimeout(()=>{{ const f=window["loadCropCanvas_{uid}"]; if(f) f("{data_url}"); }}, 400); }}
834
+ }})();
835
+ </script>"""
836
+
837
+
838
  def build_tab(tab_index, masks_state, image_state, result_state):
839
  with gr.Tab(f"Tab {tab_index}"):
840
  gr.Markdown("Run segmentation")
 
851
  # Lightweight polygon crop selector (no ImageEditor)
852
  gr.HTML(make_crop_canvas_html(tab_index))
853
 
854
+ # Hidden HTML component β€” Python pushes a <script> snippet here
855
+ # on every img_input change to load the image into the canvas
856
+ canvas_pusher = gr.HTML(value="", visible=False)
857
+
858
  # Hidden textbox that receives [[x,y],...] from JS
859
  crop_points = gr.Textbox(
860
  value="",
 
970
  inputs=[img_input, left_excl, top_excl],
971
  outputs=[excl_preview]
972
  )
973
+ img_input.change(
974
+ fn=lambda img: push_image_to_canvas(img, tab_index),
975
+ inputs=[img_input],
976
+ outputs=[canvas_pusher]
977
+ )
978
  left_excl.change(
979
  fn=update_exclusion_preview,
980
  inputs=[img_input, left_excl, top_excl],