File size: 15,829 Bytes
92c67c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
"""Turn document items into extracted-text rows.

A document is a list of items: ``("line", text)``, ``("kv", label, value)`` or
``("table", header, rows)``. A layout decides how the items become text, the
way different PDF extractors (PyMuPDF, pdftotext -raw, Docling markdown, a
CSV export) print the same page. Title lines are tagged so a row can be
rendered with the title on top, at the bottom (footer-only form IDs), or not
at all (cropped scans), which forces the content to carry the label.
"""

from __future__ import annotations

import random
import re

from specs import COINS, EXTRA_POOLS, FIRST, LAST, MAKES, SECURITIES, STREETS, CITIES
import specs

FORM_LAYOUTS = ["stacked", "inline", "columns", "boxed", "flat", "markdown"]
STATEMENT_LAYOUTS = ["stacked", "inline", "columns", "csv", "flat", "markdown"]
TITLE = "title"


# ── Values ──────────────────────────────────────────────────────────────────

def money(rng: random.Random, low: float, high: float, dollar: float = 0.5) -> str:
    """Return a formatted amount, sometimes with a dollar sign."""
    value = rng.uniform(low, high)
    text = f"{value:,.2f}"
    return ("$" + text) if rng.random() < dollar else text


def date(rng: random.Random, year: int) -> str:
    """Return a date in one of the formats statements print."""
    m, d = rng.randint(1, 12), rng.randint(1, 28)
    style = rng.randrange(4)
    if style == 0:
        return f"{m:02d}/{d:02d}/{year}"
    if style == 1:
        return f"{year}-{m:02d}-{d:02d}"
    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September",
              "October", "November", "December"]
    if style == 2:
        return f"{months[m - 1]} {d}, {year}"
    return f"{m}/{d}/{str(year)[2:]}"


def person(rng: random.Random) -> str:
    """Return an invented full name."""
    middle = f" {rng.choice('ABCDEJKLMRS')}." if rng.random() < 0.3 else ""
    return f"{rng.choice(FIRST)}{middle} {rng.choice(LAST)}"


def address(rng: random.Random) -> tuple[str, str]:
    """Return an invented street line and city line."""
    city, state = rng.choice(CITIES)
    return f"{rng.randint(10, 9899)} {rng.choice(STREETS)}", f"{city}, {state} {rng.randint(10000, 99999)}"


def masked(rng: random.Random, digits: int = 4) -> str:
    """Return a masked account or TIN tail."""
    return rng.choice(["XXX-XX-", "***-**-", "XXXXX", "****", "ending in "]) + "".join(
        rng.choice("0123456789") for _ in range(digits))


def ein(rng: random.Random) -> str:
    """Return an invented EIN."""
    return f"{rng.randint(10, 98)}-{rng.randint(1000000, 9999999)}"


def pool(name: str) -> list[str]:
    """Return a named organization pool from specs."""
    return EXTRA_POOLS.get(name) or getattr(specs, name)


def box_value(rng: random.Random, kind: str, year: int) -> str | None:
    """Return a value for one IRS box kind; None leaves the box blank."""
    if kind == "money":
        return money(rng, 800, 140000)
    if kind == "small_money":
        return money(rng, 3, 9500)
    if kind == "big_money":
        return money(rng, 80000, 650000)
    if kind == "zero":
        return rng.choice(["0.00", "$0.00", "", "", None])
    if kind == "signed":
        v = rng.uniform(-9000, 30000)
        return f"({abs(v):,.2f})" if v < 0 and rng.random() < 0.5 else f"{v:,.2f}"
    if kind == "date":
        return date(rng, year - rng.choice([0, 0, 1, 3]))
    if kind == "text_year":
        return str(year)
    if kind == "code":
        return f"{rng.choice(['D', 'DD', 'W', 'C', 'AA', 'V'])} {money(rng, 50, 9000, 0)}"
    if kind == "check":
        return rng.choice(["X", "☒", "[X]", "", "☐"])
    if kind == "count":
        return str(rng.randint(1, 999))
    if kind == "state":
        return f"{rng.choice(['IL', 'WI', 'OH', 'CO', 'MN', 'TX', 'GA', 'PA'])} {rng.randint(1000000, 9999999)}"
    if kind == "percent":
        return f"{rng.uniform(1, 100):.4f} %"
    if kind == "wager":
        return rng.choice(["Slots", "Keno", "Poker tournament", "Horse race", "Lottery"])
    if kind == "dist_code":
        return rng.choice(["7", "1", "G", "2", "4", "7D"])
    if kind == "term":
        return rng.choice(["Short-term", "Long-term", "X Short-term", "X Long-term"])
    if kind == "security":
        return rng.choice(SECURITIES)
    if kind == "address":
        return " ".join(address(rng))
    if kind == "one":
        return "1"
    if kind == "code1":
        return rng.choice(["1", "2", "A", "F", "G"])
    if kind == "hsa":
        return "HSA ☒"
    if kind == "debt":
        return rng.choice(["Credit card", "Personal loan", "Auto loan deficiency"])
    if kind == "coin":
        return rng.choice(COINS)
    if kind == "units":
        return f"{rng.uniform(0.01, 40):.6f}"
    if kind == "make":
        return rng.choice(MAKES)[0]
    if kind == "model":
        return rng.choice(MAKES)[1]
    if kind == "vin":
        return "".join(rng.choice("ABCDEFGHJKLMNPRSTUVWXYZ0123456789") for _ in range(17))
    if kind == "yesno":
        return rng.choice(["Yes ☐  No ☒", "No"])
    if kind == "ira":
        return rng.choice(["IRA ☒", "Roth IRA ☒", "SEP ☒"])
    if kind == "origin":
        return rng.choice(["A", "B", "C", "D"])
    if kind == "person":
        return person(rng)
    if kind == "offer":
        return rng.choice(["1A", "1E", "1H"])
    if kind == "safe":
        return rng.choice(["2C", "2D", "2H"])
    if kind == "month":
        return f"{rng.randint(1, 12):02d}"
    if kind == "voucher":
        return str(rng.randint(1, 4))
    if kind == "due":
        return rng.choice([f"April 15, {year}", f"June 15, {year}", f"Sept. 15, {year}", f"Jan. 15, {year + 1}"])
    if kind == "explain":
        return rng.choice(["Received a corrected Form 1099-DIV after filing.", "Claimed a missed education credit.",
                           "Reported omitted interest income."])
    if kind == "classification":
        return rng.choice(["☒ Individual/sole proprietor", "☒ C corporation", "☒ Limited liability company  P",
                           "☒ S corporation"])
    if kind == "goods":
        return rng.choice(["Household furniture, good condition", "Clothing, 6 bags, good used", "Laptop computer, fair"])
    if kind == "how":
        return rng.choice(["Purchase", "Gift", "Inheritance"])
    if kind == "fmv":
        return rng.choice(["Thrift shop value", "Comparable sales", "Appraisal"])
    return None


# ── Forms → items ───────────────────────────────────────────────────────────

def compact_form_items(rng: random.Random, spec: dict, year: int) -> list[tuple]:
    """A short snippet of a form: one title line, short party lines, a few boxes.

    Matches cropped photos, one-box summaries and preparer notes, where only a
    handful of boxes survive extraction.
    """
    form = spec["form"]
    form_id = form if form.startswith(("SCHEDULE", "Schedule")) else f"Form {form}"
    items: list[tuple] = [("title", f"{form_id} {spec['titles'][0]} {year}" if rng.random() < 0.6 else f"{form_id} {spec['titles'][0]}")]
    if spec["payer_pool"]:
        short = spec["parties"][0].split(" name")[0].split(",")[0].split("'")[0].strip() or "PAYER"
        items.append(("kv", rng.choice([f"{short}:", f"{short}'S name:", "From:"]), rng.choice(pool(spec["payer_pool"]))))
        items.append(("kv", rng.choice(["RECIPIENT:", "Recipient's name:", "To:"]), person(rng)))
    else:
        items.append(("kv", "Name:", person(rng)))
    boxes = [b for b in spec["boxes"] if b[2] not in ("none", "zero")] or spec["boxes"]
    for number, label, kind in rng.sample(boxes, k=min(len(boxes), rng.randint(1, 4))):
        value = box_value(rng, kind, year) or "0.00"
        items.append(("kv", f"{number} {label}".strip(), value))
    return items


def form_items(rng: random.Random, spec: dict, year: int) -> list[tuple]:
    """Build the items of one IRS form copy; a quarter of rows are compact snippets."""
    if rng.random() < 0.25:
        return compact_form_items(rng, spec, year)
    form = spec["form"]
    form_id = form if form.startswith(("SCHEDULE", "Schedule")) else f"Form {form}"
    items: list[tuple] = []
    if rng.random() < 0.35:
        items.append(("line", rng.choice(["CORRECTED (if checked)", "VOID  CORRECTED", "☐ CORRECTED"])))
    items.append(("title", form_id))
    for title in spec["titles"]:
        items.append(("title", title))
    if rng.random() < 0.8:
        items.append(("line", str(year) if rng.random() < 0.5 else f"For calendar year {year}"))
    if spec["omb"] and rng.random() < 0.7:
        items.append(("line", f"OMB No. {spec['omb']}"))
    for copy in spec["copies"]:
        if rng.random() < 0.6:
            items.append(("line", copy))
    payer_label, recipient_label, payer_tin, recipient_tin = spec["parties"]
    payer = rng.choice(pool(spec["payer_pool"])) if spec["payer_pool"] else None
    street, city = address(rng)
    if payer:
        p_street, p_city = address(rng)
        items.append(("kv", payer_label, f"{payer} {p_street} {p_city}"))
        items.append(("kv", payer_tin, ein(rng)))
        items.append(("kv", recipient_label, person(rng)))
        items.append(("kv", recipient_tin, masked(rng)))
        if rng.random() < 0.7:
            items.append(("kv", "Street address (including apt. no.)", street))
            items.append(("kv", "City or town, state or province, country, and ZIP or foreign postal code", city))
        if rng.random() < 0.4:
            items.append(("kv", "Account number (see instructions)", masked(rng, 6)))
    else:
        items.append(("kv", payer_label, person(rng)))
        items.append(("kv", recipient_label, f"{street} {city}"))
        items.append(("kv", payer_tin, masked(rng)))
        items.append(("line", recipient_tin))
    for number, label, kind in spec["boxes"]:
        if rng.random() < 0.15:
            continue
        value = box_value(rng, kind, year)
        text = f"{number} {label}".strip()
        items.append(("kv", text, value or ""))
    if rng.random() < 0.6:
        tail = f"Form {form.replace('Schedule ', '').replace('SCHEDULE ', '')}"
        items.append(("title", f"{tail} (keep for your records)  www.irs.gov/Form{re.sub('[^0-9A-Za-z]', '', spec['form'])}"))
        items.append(("line", "Department of the Treasury - Internal Revenue Service"))
    return items


# ── Layouts ─────────────────────────────────────────────────────────────────

def _gap(rng: random.Random) -> str:
    return " " * rng.choice([1, 1, 2, 3, 6])


def _runs(items: list[tuple]) -> list[tuple[str, list]]:
    """Group consecutive items of the same type."""
    runs: list[tuple[str, list]] = []
    for item in items:
        kind = "kv" if item[0] == "kv" else item[0]
        if runs and runs[-1][0] == kind and kind == "kv":
            runs[-1][1].append(item)
        else:
            runs.append((kind, [item]))
    return runs


def render(rng: random.Random, items: list[tuple], layout: str, title_mode: str) -> str:
    """Render items with a layout; title_mode is top, bottom or none."""
    titles = [i for i in items if i[0] == TITLE]
    body = [i for i in items if i[0] != TITLE]
    if title_mode == "top":
        items = [("line", t[1]) for t in titles if "www.irs.gov" not in t[1]] + \
                [i for i in body] + [("line", t[1]) for t in titles if "www.irs.gov" in t[1]]
        items = _keep_order(items, titles, body)
    elif title_mode == "bottom":
        items = body + [("line", t[1]) for t in titles]
    else:
        items = body
    lines: list[str] = []
    for kind, run in _runs(items):
        if kind == "line":
            text = run[0][1]
            lines.append(("## " + text) if layout == "markdown" and rng.random() < 0.3 else text)
        elif kind == "table":
            _, header, rows = run[0]
            lines.extend(_table(rng, header, rows, layout))
        else:
            lines.extend(_kv(rng, [(r[1], r[2]) for r in run], layout))
    if layout == "flat":
        words = " ".join(l for l in lines if l).split()
        cut = sorted(rng.sample(range(1, max(2, len(words))), k=min(2, max(0, len(words) - 2))))
        parts, start = [], 0
        for c in cut + [len(words)]:
            parts.append(" ".join(words[start:c]))
            start = c
        return "\n".join(p for p in parts if p)
    return "\n".join(lines).strip()


def _keep_order(items: list[tuple], titles: list[tuple], body: list[tuple]) -> list[tuple]:
    """Keep a CORRECTED marker above the title, as printed forms do."""
    if body and body[0][0] == "line" and "CORRECTED" in body[0][1]:
        return [body[0]] + [i for i in items if i is not body[0]]
    return items


def _kv(rng: random.Random, pairs: list[tuple[str, str]], layout: str) -> list[str]:
    if layout == "stacked":
        out = []
        for label, value in pairs:
            out.append(label)
            if value:
                out.append(value)
        return out
    if layout in ("inline", "flat"):
        return [f"{label}{_gap(rng)}{value}".rstrip() for label, value in pairs]
    if layout == "columns":
        return [p[0] for p in pairs] + [p[1] for p in pairs if p[1]]
    if layout == "boxed":
        prefix = rng.choice(["Box ", "", "Line "])
        return [f"{prefix}{label}: {value}".rstrip(": ") if re.match(r"^[0-9]", label) else f"{label}: {value}"
                for label, value in pairs]
    if layout == "csv":
        return [f"{_csv(label)},{_csv(value)}" for label, value in pairs]
    out = ["| Field | Value |", "| --- | --- |"]
    out += [f"| {label} | {value} |" for label, value in pairs]
    return out


def _table(rng: random.Random, header: list[str], rows: list[list[str]], layout: str) -> list[str]:
    if layout == "csv":
        return [",".join(_csv(h) for h in header)] + [",".join(_csv(c) for c in r) for r in rows]
    if layout == "markdown":
        return ["| " + " | ".join(header) + " |", "|" + " --- |" * len(header)] + \
               ["| " + " | ".join(r) + " |" for r in rows]
    if layout == "columns":
        return header + [c for r in rows for c in r]
    if layout == "stacked":
        return ["  ".join(header)] + [c for r in rows for c in r]
    return [_gap(rng).join(header)] + [_gap(rng).join(r) for r in rows]


def _csv(value: str) -> str:
    return f'"{value}"' if ("," in value or '"' in value) else value


# ── OCR noise ───────────────────────────────────────────────────────────────

SWAPS = [("0", "O"), ("1", "l"), ("rn", "m"), ("l", "1"), ("O", "0"), ("S", "5"), ("cl", "d"), ("e", "c"), ("i", "í")]


def ocr_noise(rng: random.Random, text: str) -> str:
    """Apply scan-like damage: swapped glyphs, lost spaces, split words."""
    chars = list(text)
    out = "".join(chars)
    for _ in range(max(1, len(out) // 60)):
        a, b = rng.choice(SWAPS)
        idx = out.find(a, rng.randrange(max(1, len(out))))
        if idx >= 0:
            out = out[:idx] + b + out[idx + len(a):]
    words = out.split(" ")
    for _ in range(max(1, len(words) // 25)):
        if len(words) > 3:
            k = rng.randrange(len(words) - 1)
            words[k] = words[k] + words.pop(k + 1)
    out = " ".join(words)
    if rng.random() < 0.3:
        out = out.replace("$", "S", 1)
    return out