jkos9 commited on
Commit
21cb6e0
·
1 Parent(s): 83094e7

Deploy a06f0d9: Bar charts from screenshots/JPEGs: merge split bars, drop outline colours, join split colours and segments

Browse files
EVAL_LOG.md CHANGED
@@ -293,3 +293,27 @@ Fixes:
293
  | perturbed: silent / series count / recall / type | 0.5% / 88.5% / 84% / 91% | 0.5% / 90.5% / 85.5% / 92% |
294
  | PlotQA test / held-out RNSS | 99.5 / 97.1 | 99.6 / 97.1 |
295
  | user figures t_1..t_4 | all wrong | all correct (t_2 low_confidence: 3 y labels covered) |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  | perturbed: silent / series count / recall / type | 0.5% / 88.5% / 84% / 91% | 0.5% / 90.5% / 85.5% / 92% |
294
  | PlotQA test / held-out RNSS | 99.5 / 97.1 | 99.6 / 97.1 |
295
  | user figures t_1..t_4 | all wrong | all correct (t_2 low_confidence: 3 y labels covered) |
296
+
297
+ ## Stage 12 — bar charts as screenshots / JPEGs
298
+
299
+ The user figures t_3/t_4 passed as the original PNGs (also inside the Space's Docker
300
+ image) but failed when uploaded as screenshots: rescaled 0.5-2x or saved as JPEG,
301
+ 11 of 20 variants were wrong, most with status `ok`.
302
+
303
+ Fixes:
304
+ 1. Bar pieces: overlapping same-series pieces, edge slivers with the same top, and
305
+ bottoms blurred by compression are merged into one bar.
306
+ 2. Unnamed colours whose every bar lies on (or just outside) another series' bar are
307
+ outlines/fringes, not series.
308
+ 3. Two unnamed similar colours whose bars fill different groups at the same slot are
309
+ one series split by compression.
310
+ 4. Small clusters next to a much heavier colour merge with a looser blend tolerance
311
+ (JPEG fringes); legend swatches washed out by JPEG match the nearest free colour.
312
+ 5. Collinear line segments split by a one-pixel step (rescaled images) are joined;
313
+ this had cut the plot area at mid-width.
314
+ 6. Status: a legend of line swatches on a chart read as scatter is `low_confidence`.
315
+
316
+ t_3/t_4 at scales 0.5/0.75/1/1.5/2, PNG and JPEG q75: 9 -> 19 of 20 correct (the
317
+ remaining 240x188 JPEG is `low_confidence`); checked in `tests/test_tricky.py`.
318
+ Synthetic and PlotQA results unchanged (clean 0% silent, 0.10% median error;
319
+ perturbed 0.5% silent; PlotQA RNSS 99.6 / 97.1).
plotscribe/axes.py CHANGED
@@ -166,7 +166,23 @@ def find_segments(ink: np.ndarray, lab: np.ndarray, orient: str, min_len: int,
166
  else:
167
  pos, start, end = x + xs.mean() + 0.5, float(y), float(y + bh)
168
  segs.append(Segment(orient, float(pos), start, end, float(area) / length, tuple(float(c) for c in col)))
169
- return segs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
 
172
  def _mode_cluster(vals: list[float], tol: float, prefer: str = "low") -> tuple[float | None, int]:
 
166
  else:
167
  pos, start, end = x + xs.mean() + 0.5, float(y), float(y + bh)
168
  segs.append(Segment(orient, float(pos), start, end, float(area) / length, tuple(float(c) for c in col)))
169
+ return _join_collinear(segs)
170
+
171
+
172
+ def _join_collinear(segs: list[Segment]) -> list[Segment]:
173
+ """Join pieces of one line split where it steps by a pixel (resampled images)."""
174
+ out: list[Segment] = []
175
+ for sg in sorted(segs, key=lambda q: (q.start, q.pos)):
176
+ for k, o in enumerate(out):
177
+ if abs(o.pos - sg.pos) <= 1.5 and -2.0 <= sg.start - o.end <= 3.0:
178
+ la, lb = o.length, sg.length
179
+ out[k] = Segment(o.orient, (o.pos * la + sg.pos * lb) / (la + lb), o.start, max(o.end, sg.end),
180
+ (o.thickness * la + sg.thickness * lb) / (la + lb),
181
+ tuple((a * la + b * lb) / (la + lb) for a, b in zip(o.lab, sg.lab)))
182
+ break
183
+ else:
184
+ out.append(sg)
185
+ return out
186
 
187
 
188
  def _mode_cluster(vals: list[float], tol: float, prefer: str = "low") -> tuple[float | None, int]:
plotscribe/extract_bar.py CHANGED
@@ -101,8 +101,12 @@ def merge_split(bars: list[Bar], gap: float) -> list[Bar]:
101
  ov = min(b.x1, o.x1) - max(b.x0, o.x0)
102
  vgap = max(b.top - o.bottom, o.top - b.bottom)
103
  hgap = max(b.x0 - o.x1, o.x0 - b.x1)
104
- same_rows = abs(b.top - o.top) <= 2 and abs(b.bottom - o.bottom) <= 2
105
- if (ov > 0.8 * min(b.width, o.width) and -1.0 <= vgap <= gap) or (same_rows and -1.0 <= hgap <= gap):
 
 
 
 
106
  o.bottom, o.top = max(o.bottom, b.bottom), min(o.top, b.top)
107
  o.x0, o.x1 = min(o.x0, b.x0), max(o.x1, b.x1)
108
  break
 
101
  ov = min(b.x1, o.x1) - max(b.x0, o.x0)
102
  vgap = max(b.top - o.bottom, o.top - b.bottom)
103
  hgap = max(b.x0 - o.x1, o.x0 - b.x1)
104
+ # Same rows - or a narrow edge sliver with the same top (its lower part lost
105
+ # to compression where it touches a neighbouring bar).
106
+ sliver = min(b.width, o.width) < 0.4 * max(b.width, o.width)
107
+ bot_tol = 2 + 0.01 * max(b.bottom - b.top, o.bottom - o.top) # compression blurs ends
108
+ same_rows = abs(b.top - o.top) <= 2 and (abs(b.bottom - o.bottom) <= bot_tol or sliver)
109
+ if (ov > 0.8 * min(b.width, o.width) and vgap <= gap) or (same_rows and -min(b.width, o.width) <= hgap <= gap):
110
  o.bottom, o.top = max(o.bottom, b.bottom), min(o.top, b.top)
111
  o.x0, o.x1 = min(o.x0, b.x0), max(o.x1, b.x1)
112
  break
plotscribe/pipeline.py CHANGED
@@ -514,7 +514,13 @@ def separate_series(res: PipelineResult, ink: np.ndarray, leg: legend_mod.Legend
514
  for k, e in enumerate(leg.entries):
515
  d = [np.linalg.norm(c.lab - e.lab) for c in clusters]
516
  j = int(np.argmin(d)) if d else -1
517
- if j >= 0 and d[j] < 25 and j not in used:
 
 
 
 
 
 
518
  used.add(j)
519
  colours.append(clusters[j].lab)
520
  else:
@@ -824,6 +830,62 @@ def zero_line_px(res: PipelineResult) -> float:
824
  return ax.plot_box.y1
825
 
826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
827
  def extract_bars(res: PipelineResult, series: list[Series], alpha: np.ndarray, labels: np.ndarray) -> None:
828
  ax = res.axes
829
  assert ax is not None
@@ -836,6 +898,8 @@ def extract_bars(res: PipelineResult, series: list[Series], alpha: np.ndarray, l
836
  bars += bar_mod.bars_from_mask(s.mask, soft, i, min_w)
837
  bars = bar_mod.merge_split(bars, gap=2 * ax.line_thickness + 4)
838
  bars = bar_mod.drop_fragments(bars, min_h=1.5 * ax.line_thickness + 1)
 
 
839
  joint_tol = 4.0 + 2 * ax.line_thickness + res.pre.noise_sigma
840
  zero = zero_line_px(res)
841
  bar_mod.snap_baseline(bars, zero, ax.line_thickness + 3)
@@ -992,6 +1056,10 @@ def status_from_calibration(res: PipelineResult) -> None:
992
  or (unmatched and res.extra.get("not_in_legend", 0))):
993
  status = "low_confidence"
994
  res.warn("series", "legend colours and plot colours do not match up; series may be mixed up")
 
 
 
 
995
  if x is not None and x.kind == "categorical" and x.categories:
996
  junk = sum(misread_name(c) for c in x.categories)
997
  if junk >= max(2.0, len(x.categories) / 3):
 
514
  for k, e in enumerate(leg.entries):
515
  d = [np.linalg.norm(c.lab - e.lab) for c in clusters]
516
  j = int(np.argmin(d)) if d else -1
517
+ if j >= 0 and 25 <= d[j] < 45 and j not in used:
518
+ # Small swatches lose saturation in JPEGs: accept the nearest colour when
519
+ # no other legend entry is closer to it.
520
+ others = [np.linalg.norm(clusters[j].lab - o.lab) for o in leg.entries if o is not e]
521
+ if others and min(others) < d[j]:
522
+ j = -1
523
+ if j >= 0 and d[j] < 45 and j not in used:
524
  used.add(j)
525
  colours.append(clusters[j].lab)
526
  else:
 
830
  return ax.plot_box.y1
831
 
832
 
833
+ def drop_shadow_series(res: PipelineResult, series: list[Series], bars: list) -> list:
834
+ """Drop an unnamed colour whose every bar lies on another series' bar (dark bar
835
+ outlines, compression fringes): it repeats those bars, it is not data."""
836
+ pad = 2 * (res.axes.line_thickness if res.axes else 1.0) + 3 # outline strokes sit just outside
837
+
838
+ def covered(b, o) -> bool:
839
+ ox = min(b.x1, o.x1 + pad) - max(b.x0, o.x0 - pad)
840
+ oy = min(b.bottom, o.bottom + pad) - max(b.top, o.top - pad)
841
+ return ox >= 0.5 * min(b.width, o.width) and oy >= 0.5 * (b.bottom - b.top)
842
+
843
+ out = bars
844
+ for i, s in enumerate(series):
845
+ mine = [b for b in out if b.series == i]
846
+ if s.from_legend or not mine:
847
+ continue
848
+ others = [o for o in out if o.series != i]
849
+ if all(any(covered(b, o) for o in others) for b in mine):
850
+ out = [b for b in out if b.series != i]
851
+ res.warn("series", f"colour {s.rgb} only repeats other series' bars (outlines?); ignored")
852
+ return out
853
+
854
+
855
+ def merge_complementary_colours(res: PipelineResult, series: list[Series], bars: list) -> None:
856
+ """Join two unnamed, similar colours whose bars fill different groups: one series
857
+ whose colour compression split in two (e.g. red bars at 16 and 32 vs at 64)."""
858
+ if res.chart_type == "stacked_bar":
859
+ return
860
+ centres = np.asarray(bar_mod.category_clusters(bars))
861
+ if len(centres) < 2:
862
+ return
863
+
864
+ def groups(i: int) -> set[int]:
865
+ return {int(np.argmin(np.abs(centres - b.cx))) for b in bars if b.series == i}
866
+
867
+ n_groups = len(centres)
868
+ for i, a in enumerate(series):
869
+ for j, b in enumerate(series):
870
+ if j <= i or a.from_legend or b.from_legend:
871
+ continue
872
+ ga, gb = groups(i), groups(j)
873
+ if not ga or not gb or ga & gb or len(ga) + len(gb) > n_groups:
874
+ continue
875
+ if np.linalg.norm(np.asarray(a.lab) - np.asarray(b.lab)) >= 30:
876
+ continue
877
+ # Same position within each group (the series' slot), so the same series.
878
+ off_a = [b_.cx - centres[int(np.argmin(np.abs(centres - b_.cx)))] for b_ in bars if b_.series == i]
879
+ off_b = [b_.cx - centres[int(np.argmin(np.abs(centres - b_.cx)))] for b_ in bars if b_.series == j]
880
+ width = float(np.median([b_.width for b_ in bars]))
881
+ if abs(np.median(off_a) - np.median(off_b)) > 0.5 * width:
882
+ continue
883
+ for b_ in bars:
884
+ if b_.series == j:
885
+ b_.series = i
886
+ res.warn("series", f"colours {a.rgb} and {b.rgb} treated as one series (bars in different groups)")
887
+
888
+
889
  def extract_bars(res: PipelineResult, series: list[Series], alpha: np.ndarray, labels: np.ndarray) -> None:
890
  ax = res.axes
891
  assert ax is not None
 
898
  bars += bar_mod.bars_from_mask(s.mask, soft, i, min_w)
899
  bars = bar_mod.merge_split(bars, gap=2 * ax.line_thickness + 4)
900
  bars = bar_mod.drop_fragments(bars, min_h=1.5 * ax.line_thickness + 1)
901
+ bars = drop_shadow_series(res, series, bars)
902
+ merge_complementary_colours(res, series, bars)
903
  joint_tol = 4.0 + 2 * ax.line_thickness + res.pre.noise_sigma
904
  zero = zero_line_px(res)
905
  bar_mod.snap_baseline(bars, zero, ax.line_thickness + 3)
 
1056
  or (unmatched and res.extra.get("not_in_legend", 0))):
1057
  status = "low_confidence"
1058
  res.warn("series", "legend colours and plot colours do not match up; series may be mixed up")
1059
+ kinds = [e.get("swatch_kind") for e in res.extra.get("legend_info", {}).get("entries", [])]
1060
+ if status == "ok" and kinds and kinds.count("line") > len(kinds) / 2 and res.chart_type == "scatter":
1061
+ status = "low_confidence"
1062
+ res.warn("chart_type", f"legend shows lines but the chart was read as {res.chart_type}")
1063
  if x is not None and x.kind == "categorical" and x.categories:
1064
  junk = sum(misread_name(c) for c in x.categories)
1065
  if junk >= max(2.0, len(x.categories) / 3):
plotscribe/series.py CHANGED
@@ -193,8 +193,11 @@ def find_colors(pixels: np.ndarray, bg: np.ndarray, min_frac: float = 0.02, max_
193
  merged: list[ColorCluster] = []
194
  for cl in sorted(out, key=lambda c: -float(np.linalg.norm(c.lab - bg))):
195
  for m in merged:
 
 
 
196
  if np.linalg.norm(m.lab - cl.lab) < merge_de or (
197
- is_blend_of(cl.lab, m.lab, bg) and not (is_solid is not None and is_solid(cl.lab))):
198
  m.weight += cl.weight
199
  break
200
  else:
 
193
  merged: list[ColorCluster] = []
194
  for cl in sorted(out, key=lambda c: -float(np.linalg.norm(c.lab - bg))):
195
  for m in merged:
196
+ # A small cluster beside a much heavier colour is usually its fringe;
197
+ # JPEG chroma shifts move fringes further off the exact blend line.
198
+ tol = 20.0 if cl.weight < 0.15 * m.weight else 10.0
199
  if np.linalg.norm(m.lab - cl.lab) < merge_de or (
200
+ is_blend_of(cl.lab, m.lab, bg, tol) and not (is_solid is not None and is_solid(cl.lab))):
201
  m.weight += cl.weight
202
  break
203
  else:
tests/test_tricky.py CHANGED
@@ -74,3 +74,33 @@ def test_t4_tinted_bars_against_spine():
74
  assert t.shape[1] == 6
75
  np.testing.assert_allclose(t.iloc[0, 1:].to_numpy(float), [12.7, 11.75, 12.1, 10.9, 10.8], atol=0.2)
76
  np.testing.assert_allclose(t.iloc[2, 1:].to_numpy(float), [10.0, 7.6, 8.15, 7.05, 6.5], atol=0.2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  assert t.shape[1] == 6
75
  np.testing.assert_allclose(t.iloc[0, 1:].to_numpy(float), [12.7, 11.75, 12.1, 10.9, 10.8], atol=0.2)
76
  np.testing.assert_allclose(t.iloc[2, 1:].to_numpy(float), [10.0, 7.6, 8.15, 7.05, 6.5], atol=0.2)
77
+
78
+
79
+ BAR_EXPECTED = {
80
+ "t_3.png": ([10, 11, 12, 13, 14, 15], [[0.646, 0.70, 0.729, 0.756, 0.788, 0.797],
81
+ [0.966, 0.968, 0.971, 0.972, 0.975, 0.977]], 0.012),
82
+ "t_4.png": ([16, 32, 64], [[12.7, 12.7, 10.0], [11.75, 9.6, 7.6], [12.1, 10.7, 8.15], [10.9, 9.1, 7.05],
83
+ [10.8, 8.75, 6.5]], 0.25),
84
+ }
85
+
86
+
87
+ @pytest.mark.parametrize("name", sorted(BAR_EXPECTED))
88
+ @pytest.mark.parametrize("scale,jpeg", [(0.5, None), (0.75, None), (0.75, 75), (1.0, 75), (1.5, None),
89
+ (1.5, 75), (2.0, None), (2.0, 75)])
90
+ def test_bar_figures_survive_rescaling_and_jpeg(tmp_path, name, scale, jpeg):
91
+ # Uploads are often screenshots or JPEGs of the figure, not the original file.
92
+ import cv2
93
+
94
+ src = DIR / name
95
+ if not src.exists():
96
+ pytest.skip(f"{src} not available")
97
+ img = cv2.imread(str(src))
98
+ img = cv2.resize(img, None, fx=scale, fy=scale,
99
+ interpolation=cv2.INTER_AREA if scale < 1 else cv2.INTER_CUBIC)
100
+ out = tmp_path / ("v.jpg" if jpeg else "v.png")
101
+ cv2.imwrite(str(out), img, [cv2.IMWRITE_JPEG_QUALITY, jpeg] if jpeg else [])
102
+ t = pipeline.run(str(out)).table
103
+ xs, cols, tol = BAR_EXPECTED[name]
104
+ assert t.shape == (len(xs), len(cols) + 1)
105
+ np.testing.assert_allclose(t.iloc[:, 0].to_numpy(float), xs, atol=0.3)
106
+ np.testing.assert_allclose(t.iloc[:, 1:].to_numpy(float).T, cols, atol=tol)