File size: 12,184 Bytes
b9c7f6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"""온라인 ν•„κΈ° strokeλ₯Ό λͺ¨λΈ 독립적인 2차원 μˆ˜μ‹ μ…€λ‘œ λ¬ΆλŠ”λ‹€."""

from __future__ import annotations

from dataclasses import dataclass
from statistics import median
from typing import Any, Sequence

from PIL import Image, ImageDraw


@dataclass(frozen=True, slots=True)
class GridConfig:
    """ν•„μš” λ³€μˆ˜: κΈ°ν•˜ μž„κ³„κ°’κ³Ό μž…λ ₯ μƒν•œμ΄λ‹€.
    μž‘λ™ 원리: κ³ μ • μ΅œμ†Œκ°’κ³Ό λŒ€ν‘œ 획 높이 λΉ„μœ¨μ„ ν•¨κ»˜ μ‚¬μš©ν•΄ κΈ°κΈ° μ’Œν‘œκ³„ 변화에 λŒ€μ‘ν•œλ‹€.
    """

    baseline_tolerance: float = 24.0
    expression_gap: float = 72.0
    structure_gap: float = 52.0
    padding: float = 12.0
    max_strokes: int = 2_000
    max_points_per_stroke: int = 4_096
    max_total_points: int = 200_000
    coordinate_limit: float = 20_000.0


@dataclass(frozen=True, slots=True)
class StrokeBox:
    """ν•„μš” λ³€μˆ˜: μ’ŒΒ·μƒΒ·μš°Β·ν•˜ 경계닀.
    μž‘λ™ 원리: 획과 μˆ˜μ‹ μ…€μ˜ μΆ• μ •λ ¬ 경계 및 병합 연산을 μ œκ³΅ν•œλ‹€.
    """

    left: float
    top: float
    right: float
    bottom: float

    @property
    def width(self) -> float:
        """ν•„μš” λ³€μˆ˜: 쒌우 μ’Œν‘œ. μž‘λ™ 원리: μŒμˆ˜κ°€ μ•„λ‹Œ 폭을 λ°˜ν™˜ν•œλ‹€."""
        return max(0.0, self.right - self.left)

    @property
    def height(self) -> float:
        """ν•„μš” λ³€μˆ˜: μƒν•˜ μ’Œν‘œ. μž‘λ™ 원리: μŒμˆ˜κ°€ μ•„λ‹Œ 높이λ₯Ό λ°˜ν™˜ν•œλ‹€."""
        return max(0.0, self.bottom - self.top)

    @property
    def center_y(self) -> float:
        """ν•„μš” λ³€μˆ˜: μƒν•˜ μ’Œν‘œ. μž‘λ™ 원리: 같은 κΈ°μ€€μ„  νŒμ •μš© 쀑심을 λ°˜ν™˜ν•œλ‹€."""
        return (self.top + self.bottom) / 2.0

    def union(self, other: "StrokeBox") -> "StrokeBox":
        """ν•„μš” λ³€μˆ˜: λ‹€λ₯Έ 경계. μž‘λ™ 원리: 두 경계λ₯Ό ν¬ν•¨ν•˜λŠ” μ΅œμ†Œ 경계λ₯Ό λ§Œλ“ λ‹€."""
        return StrokeBox(
            min(self.left, other.left),
            min(self.top, other.top),
            max(self.right, other.right),
            max(self.bottom, other.bottom),
        )


@dataclass(frozen=True, slots=True)
class Stroke:
    """ν•„μš” λ³€μˆ˜: μ•ˆμ •μ μΈ 획 IDΒ·μˆœμ„œ μžˆλŠ” 점·선 κ΅΅κΈ°λ‹€.
    μž‘λ™ 원리: μ„  λ°˜μ§€λ¦„μ„ ν¬ν•¨ν•œ 경계λ₯Ό 계산해 ν•„κΈ° 폭을 λ³΄μ‘΄ν•œλ‹€.
    """

    stroke_id: int
    points: tuple[tuple[float, float], ...]
    width: float = 3.0

    @property
    def box(self) -> StrokeBox:
        """ν•„μš” λ³€μˆ˜: 필기점·ꡡ기. μž‘λ™ 원리: μ„  λ°˜μ§€λ¦„κΉŒμ§€ ν¬ν•¨ν•œ 경계λ₯Ό κ³„μ‚°ν•œλ‹€."""
        radius = self.width / 2.0
        return StrokeBox(
            min(point[0] for point in self.points) - radius,
            min(point[1] for point in self.points) - radius,
            max(point[0] for point in self.points) + radius,
            max(point[1] for point in self.points) + radius,
        )


@dataclass(frozen=True, slots=True)
class FormulaGrid:
    """ν•„μš” λ³€μˆ˜: μ…€ μˆœλ²ˆΒ·κ²½κ³„Β·μ†Œμ† 획 IDλ‹€.
    μž‘λ™ 원리: 인식기와 λ¬΄κ΄€ν•œ 결정적 μˆ˜μ‹ μ…€ 계약을 ν‘œν˜„ν•œλ‹€.
    """

    index: int
    box: StrokeBox
    stroke_ids: tuple[int, ...]


class _DisjointSet:
    """ν•„μš” λ³€μˆ˜: 획 개수. μž‘λ™ 원리: 경둜 μ••μΆ•κ³Ό 크기 κΈ°μ€€ λ³‘ν•©μœΌλ‘œ μ—°κ²° 성뢄을 κ΄€λ¦¬ν•œλ‹€."""

    def __init__(self, size: int) -> None:
        """ν•„μš” λ³€μˆ˜: μ›μ†Œ 수. μž‘λ™ 원리: 각 νšμ„ 독립 μ§‘ν•©μœΌλ‘œ μ΄ˆκΈ°ν™”ν•œλ‹€."""
        self.parent = list(range(size))
        self.size = [1] * size

    def find(self, value: int) -> int:
        """ν•„μš” λ³€μˆ˜: 획 인덱슀. μž‘λ™ 원리: λŒ€ν‘œλ₯Ό μ°ΎλŠ” λ™μ•ˆ 경둜λ₯Ό μ••μΆ•ν•œλ‹€."""
        while self.parent[value] != value:
            self.parent[value] = self.parent[self.parent[value]]
            value = self.parent[value]
        return value

    def union(self, first: int, second: int) -> None:
        """ν•„μš” λ³€μˆ˜: 두 획 인덱슀. μž‘λ™ 원리: μž‘μ€ 트리λ₯Ό 큰 트리 μ•„λž˜μ— κ²°ν•©ν•œλ‹€."""
        root_first = self.find(first)
        root_second = self.find(second)
        if root_first == root_second:
            return
        if self.size[root_first] < self.size[root_second]:
            root_first, root_second = root_second, root_first
        self.parent[root_second] = root_first
        self.size[root_first] += self.size[root_second]


def parse_writing_events(value: Any, config: GridConfig | None = None) -> list[Stroke]:
    """ν•„μš” λ³€μˆ˜: JSON μœ μ‚¬ writing events와 선택 섀정이닀.
    μž‘λ™ 원리: μœ ν•œν•œ μ’Œν‘œΒ·μ Β·νšλ§Œ μƒν•œ μ•ˆμ—μ„œ λ°›μ•„ μ•ˆμ „ν•œ λΆˆλ³€ Stroke둜 μ •κ·œν™”ν•œλ‹€.
    """
    settings = config or GridConfig()
    if not isinstance(value, list):
        return []
    total_points = 0
    strokes: list[Stroke] = []
    for fallback_id, item in enumerate(value[: settings.max_strokes]):
        if not isinstance(item, dict) or not isinstance(item.get("points"), list):
            continue
        points: list[tuple[float, float]] = []
        for point in item["points"][: settings.max_points_per_stroke]:
            if not isinstance(point, dict):
                continue
            try:
                x = float(point["x"])
                y = float(point["y"])
            except (KeyError, TypeError, ValueError):
                continue
            if abs(x) <= settings.coordinate_limit and abs(y) <= settings.coordinate_limit:
                points.append((x, y))
        if len(points) < 2:
            continue
        if total_points + len(points) > settings.max_total_points:
            break
        try:
            stroke_id = int(item.get("stroke_id", fallback_id))
            width = min(32.0, max(0.5, float(item.get("width", 3.0))))
        except (TypeError, ValueError):
            continue
        strokes.append(Stroke(stroke_id, tuple(points), width))
        total_points += len(points)
    return strokes


def build_formula_grids(
    strokes: Sequence[Stroke],
    config: GridConfig | None = None,
) -> list[FormulaGrid]:
    """ν•„μš” λ³€μˆ˜: μ •κ·œν™”λœ 획과 선택 섀정이닀.
    μž‘λ™ 원리: κΈ°μ€€μ„ Β·κ·Όμ ‘ 뢀착·ꡬ쑰선 관계 κ·Έλž˜ν”„μ˜ μ—°κ²° 성뢄을 2차원 μˆ˜μ‹ μ…€λ‘œ λ§Œλ“ λ‹€.
    """
    if not strokes:
        return []
    settings = config or GridConfig()
    boxes = [stroke.box for stroke in strokes]
    typical_height = median(box.height for box in boxes)
    baseline = max(settings.baseline_tolerance, typical_height * 0.50)
    expression_gap = max(settings.expression_gap, typical_height * 1.25)
    structure_gap = max(settings.structure_gap, typical_height * 0.80)
    attachment_gap = max(18.0, typical_height * 0.18)
    groups = _DisjointSet(len(strokes))

    for first in range(len(strokes)):
        for second in range(first + 1, len(strokes)):
            horizontal_gap = _axis_gap(
                boxes[first].left,
                boxes[first].right,
                boxes[second].left,
                boxes[second].right,
            )
            vertical_gap = _axis_gap(
                boxes[first].top,
                boxes[first].bottom,
                boxes[second].top,
                boxes[second].bottom,
            )
            center_gap = abs(boxes[first].center_y - boxes[second].center_y)
            same_line = center_gap <= baseline and horizontal_gap <= expression_gap
            attachment = (
                horizontal_gap <= attachment_gap
                and vertical_gap <= attachment_gap
                and center_gap
                <= max(boxes[first].height, boxes[second].height) * 1.35 + attachment_gap
            )
            if same_line or attachment:
                groups.union(first, second)

    _join_structural_bridges(boxes, groups, structure_gap)
    members: dict[int, list[int]] = {}
    for index in range(len(strokes)):
        members.setdefault(groups.find(index), []).append(index)

    raw: list[tuple[StrokeBox, tuple[int, ...]]] = []
    for indices in members.values():
        box = boxes[indices[0]]
        for index in indices[1:]:
            box = box.union(boxes[index])
        padded = StrokeBox(
            box.left - settings.padding,
            box.top - settings.padding,
            box.right + settings.padding,
            box.bottom + settings.padding,
        )
        raw.append((padded, tuple(sorted(strokes[index].stroke_id for index in indices))))

    raw.sort(key=lambda item: (round(item[0].top / max(1.0, baseline)), item[0].left))
    return [
        FormulaGrid(index=index, box=box, stroke_ids=stroke_ids)
        for index, (box, stroke_ids) in enumerate(raw)
    ]


def render_grid_images(
    image: Image.Image,
    strokes: Sequence[Stroke],
    grids: Sequence[FormulaGrid],
) -> list[Image.Image]:
    """ν•„μš” λ³€μˆ˜: κΈ°μ€€ μΊ”λ²„μŠ€Β·μ›λ³Έ νšΒ·μˆ˜μ‹ 셀이닀.
    μž‘λ™ 원리: 각 μ…€μ˜ μ†Œμ† 획만 흰 배경에 μž¬λ Œλ”λ§ν•˜κ³  μ…€ κ²½κ³„λ‘œ 잘라 RGB μ΄λ―Έμ§€λ‘œ λ°˜ν™˜ν•œλ‹€.
    """
    stroke_by_id = {stroke.stroke_id: stroke for stroke in strokes}
    results: list[Image.Image] = []
    for grid in grids:
        canvas = Image.new("RGB", image.size, "white")
        draw = ImageDraw.Draw(canvas)
        for stroke_id in grid.stroke_ids:
            stroke = stroke_by_id.get(stroke_id)
            if stroke is not None:
                draw.line(
                    stroke.points,
                    fill="black",
                    width=max(1, round(stroke.width)),
                    joint="curve",
                )
        results.append(_crop(canvas, grid.box))
    return results


def _join_structural_bridges(
    boxes: Sequence[StrokeBox],
    groups: _DisjointSet,
    structure_gap: float,
) -> None:
    """ν•„μš” λ³€μˆ˜: 획 경계·집합 ꡬ쑰·ꡬ쑰 거리닀.
    μž‘λ™ 원리: κΈ΄ κ°€λ‘œμ„ μ€ λΆ„μˆ˜μ„ , κΈ΄ μ„Έλ‘œμ„ μ€ κ΄„ν˜ΈΒ·ν–‰λ ¬ 경계 ν›„λ³΄λ‘œ 보고 인접 νšμ„ μ—°κ²°ν•œλ‹€.
    """
    for bridge_index, bridge in enumerate(boxes):
        horizontal_bridge = bridge.width >= 30 and bridge.width >= bridge.height * 4
        vertical_bridge = bridge.height >= 45 and bridge.height >= bridge.width * 2.5
        if not horizontal_bridge and not vertical_bridge:
            continue
        for other_index, other in enumerate(boxes):
            if other_index == bridge_index:
                continue
            if horizontal_bridge:
                overlap = _overlap(bridge.left, bridge.right, other.left, other.right)
                denominator = max(1.0, min(bridge.width, other.width))
                if (
                    overlap / denominator >= 0.20
                    and _axis_gap(bridge.top, bridge.bottom, other.top, other.bottom)
                    <= structure_gap
                ):
                    groups.union(bridge_index, other_index)
            elif (
                bridge.top - 18 <= other.center_y <= bridge.bottom + 18
                and _axis_gap(bridge.left, bridge.right, other.left, other.right)
                <= structure_gap
            ):
                groups.union(bridge_index, other_index)


def _crop(image: Image.Image, box: StrokeBox) -> Image.Image:
    """ν•„μš” λ³€μˆ˜: 이미지와 μ…€ 경계. μž‘λ™ 원리: 경계λ₯Ό 이미지 μ•ˆ μ •μˆ˜ μ’Œν‘œλ‘œ μ œν•œν•΄ μ•ˆμ „ν•˜κ²Œ 자λ₯Έλ‹€."""
    left = max(0, min(image.width - 1, int(box.left)))
    top = max(0, min(image.height - 1, int(box.top)))
    right = max(left + 1, min(image.width, int(box.right + 0.999)))
    bottom = max(top + 1, min(image.height, int(box.bottom + 0.999)))
    return image.crop((left, top, right, bottom))


def _axis_gap(
    first_start: float,
    first_end: float,
    second_start: float,
    second_end: float,
) -> float:
    """ν•„μš” λ³€μˆ˜: ν•œ μΆ•μ˜ 두 ꡬ간. μž‘λ™ 원리: 겹치면 0, μ•„λ‹ˆλ©΄ μ΅œκ·Όμ ‘ 끝점 거리λ₯Ό λ°˜ν™˜ν•œλ‹€."""
    return max(0.0, max(first_start, second_start) - min(first_end, second_end))


def _overlap(
    first_start: float,
    first_end: float,
    second_start: float,
    second_end: float,
) -> float:
    """ν•„μš” λ³€μˆ˜: ν•œ μΆ•μ˜ 두 ꡬ간. μž‘λ™ 원리: 두 κ΅¬κ°„μ˜ ꡐ집합 길이λ₯Ό λ°˜ν™˜ν•œλ‹€."""
    return max(0.0, min(first_end, second_end) - max(first_start, second_start))