# Generates src/papers/layout.rs from the official forms in forms/: every # blank (measured by scripts/form_blanks.py, or for TM.47 from the gaps # between its labels), the boxes to tick and the titles to circle, each with # the key of the value that goes there. import importlib.util import pathlib import subprocess import sys import pymupdf # the repository, from scripts/ REPO = pathlib.Path(__file__).resolve().parent.parent spec = importlib.util.spec_from_file_location("fb", REPO / "scripts" / "form_blanks.py") fb = importlib.util.module_from_spec(spec) spec.loader.exec_module(fb) # blank number (as form_blanks.py prints it) -> key; SKIP lists the blanks # left empty on purpose (signatures, lines for the officer). A key used on # several blanks repeats its value (the Thai and the English half of a form); # "key+" continues the text of the blank before it on the next line. MAP = { "tm7": { 1: "written_at", 2: "date_day", 3: "date_month", 4: "date_year", 5: "family_name", 6: "first_name", 7: "middle_name", 8: "age", 9: "birth_day", 10: "birth_month", 11: "birth_year", 12: "birth_place", 13: "nationality", 14: "passport_no", 15: "passport_issue_day", 16: "passport_issue_month", 17: "passport_issue_year", 18: "passport_issued_at", 19: "passport_expiry_day", 20: "passport_expiry_month", 21: "passport_expiry_year", 22: "visa_type", 23: "arrived_by", 24: "arrived_from", 25: "arrival_port", 26: "arrival_day", 27: "arrival_month", 28: "arrival_year", 29: "tdac_no", 30: "days", 31: "days", 32: "reason", 33: "reason+", 34: "reason+", 35: "reason+", 37: "address", 38: "full_name", 39: "house_no", 40: "road", 41: "subdistrict", 42: "district", 43: "province", }, "tm8": { 1: "written_at", 2: "date_day", 3: "date_month", 4: "date_year", 5: "family_name", 6: "first_name", 7: "middle_name", 8: "nationality", 9: "age", 10: "birth_day", 11: "birth_month", 12: "birth_year", 13: "birth_place", 14: "birth_country", 15: "occupation", 16: "house_no", 17: "road", 18: "subdistrict", 19: "district", 20: "province", 21: "trip_to", 22: "leave_day", 23: "leave_month", 24: "leave_year", 25: "trip_by", 26: "trip_for", 28: "return_day", 29: "return_month", 30: "return_year", 31: "passport_country", 32: "passport_issued_at", 33: "passport_no", 34: "passport_issue_day", 35: "passport_issue_month", 36: "passport_issue_year", 37: "passport_expiry_day", 38: "passport_expiry_month", 39: "passport_expiry_year", 40: "visa_issued_at", 41: "visa_issue_day", 42: "visa_issue_month", 43: "visa_issue_year", 44: "arrival_day", 45: "arrival_month", 46: "arrival_year", 47: "permitted_day", 48: "permitted_month", 49: "permitted_year", }, "stm2": { 1: "date", 2: "full_name", 3: "age", 4: "nationality", 5: "reason", 7: "date", 8: "full_name", 9: "age", 10: "nationality", 11: "reason_short", }, "stm9": { 1: "written_at", 2: "date_day", 3: "date_month", 4: "date_year", 5: "family_name", 6: "first_name", 7: "middle_name", 8: "age", 9: "nationality", 10: "passport_no", }, "stm11": { 1: "date_day", 2: "date_month", 3: "date_year", 4: "full_name", 5: "age", 6: "nationality", 7: "passport_no", 8: "phone", 9: "extension_nth", 10: "reason_short", 11: "position", 12: "company_name", 13: "coordinator", 14: "coordinator_phone", 16: "date", 17: "full_name", 18: "age", 19: "nationality", 20: "passport_no", 21: "phone", 22: "extension_years", 23: "reason_short", 24: "position", 25: "company_name", 26: "coordinator", 27: "coordinator_phone", }, "stm1": { 1: "company_written_at", 2: "date", 3: "company_name_th", 4: "company_registered_at", 5: "company_house_no", 6: "company_road", 7: "company_subdistrict", 8: "company_district", 9: "company_province", 10: "company_signatory", 11: "company_registered_at", 12: "company_name", 13: "company_certificate_short", 14: "full_name", 15: "age", 16: "nationality", 17: "position", 18: "salary", 19: "contract_from", 20: "contract_until", 21: "company_business", 22: "company_capital", 23: "company_paid_up", 24: "figures_year", 25: "revenue", 26: "foreign_costs", 27: "figures_year", 28: "equity", 29: "thai_staff", 30: "foreign_staff", 31: "company_signatory", }, } SKIP = { "tm7": {36, 44}, # the applicant's and the writer's signatures "tm8": {27, 50}, # the end of "and shall return" (the date follows), the signature "stm2": {6, 12}, "stm9": {11}, "stm11": {15, 28}, "stm1": set(), } # TM.47 draws its dotted lines dot by dot: its blanks run from a label's end # to the next label (or the right margin at 521), on the Thai baselines. TM47 = [ # key, baseline, from x, to x ("written_at", 131.2, 356.0, 521.0), ("date_day", 164.1, 318.6, 340.6), ("date_month", 164.1, 368.2, 448.6), ("date_year", 164.1, 470.5, 521.0), ("full_name", 230.1, 165.8, 521.0), ("nationality", 263.1, 106.9, 233.0), ("arrival_day", 297.8, None, None), # measured below ("arrival_month", 297.8, None, None), ("arrival_year", 297.8, 292.7, 322.6), ("arrived_by", 297.8, 373.8, 521.0), ("passport_no", 330.8, 156.0, 286.6), ("tdac_no", 330.8, 367.6, 521.0), ("house_no", 363.8, 382.2, 521.0), ("road", 396.8, 115.6, 223.5), ("subdistrict", 396.8, 252.6, 376.6), ("district", 396.8, 407.3, 521.0), ("province", 429.9, 104.6, 223.5), ("phone", 429.9, 265.2, 377.0), ] # boxes: form -> [(key, value, page, x0, x1, y0, y1)] TICKS = { "tm8": [ ("entries", "single", 1, 115.2, 133.2, 484.2, 510.8), ("entries", "multiple", 1, 259.9, 277.9, 484.4, 510.8), ("visa_kind", "non-immigrant", 2, 115.9, 133.9, 119.4, 146.4), ("visa_kind", "tourist", 2, 294.8, 312.8, 118.4, 146.4), ("visa_kind", "transit", 2, 439.9, 457.9, 117.5, 146.4), ("visa_kind", "other", 2, 115.9, 133.9, 154.3, 181.3), ], "stm11": [ ("applying_for", "extension", 1, 109.8, 126.3, 240.0, 253.7), ("applying_for", "extension", 1, 84.8, 101.3, 581.8, 595.5), ], "tm47": [ ("visa_kind", "tourist", 1, 325.1, 332.4, 257.6, 264.8), ("visa_kind", "non-immigrant", 1, 325.1, 332.4, 270.2, 277.4), ], } # the printed titles to circle: (form, page, English line's words with their # key value, the Thai span) TITLE_WORDS = { "tm7": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Miss": "Miss"}, 275.0, 295.0, "นาย/นาง/นางสาว", 255.0, 278.0), "tm8": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Miss": "Miss"}, 286.0, 305.0, "นาย/นาง/นางสาว", 266.0, 289.0), "stm2": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Miss": "Miss"}, 497.0, 519.0, "นาย/นาง/นางสาว", 130.0, 155.0), "stm9": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Ms": "Ms."}, 300.0, 322.0, "นาย/นาง/นางสาว", 280.0, 304.0), "stm11": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Miss": "Miss"}, 499.0, 520.0, "นาย/นาง/นางสาว", 155.0, 178.0), "stm1": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Miss": "Miss"}, 366.0, 386.0, "นาย,นาง,นางสาว", 350.0, 372.0), } THAI_TITLES = [("Mr", "นาย"), ("Mrs", "นาง"), ("Miss", "นางสาว")] def rings(form, doc): page_no, words, ey0, ey1, thai, ty0, ty1 = TITLE_WORDS[form] page = doc[page_no - 1] out = [] mr = [r for r in page.search_for("Mr.") if ey0 <= r.y0 <= ey1] assert len(mr) == 1, (form, mr) for value, word in words.items(): # "Miss" also matches inside "Commissioner" and "permission": the # title is a short word on the line of "Mr." hits = [ r for r in page.search_for(word) if abs(r.y0 - mr[0].y0) < 2 and r.width < 25 ] assert len(hits) == 1, (form, word, hits) r = hits[0] out.append(("title", value, page_no, r.x0, r.x1, r.y0, r.y1)) # the Thai titles: the characters of the span "นาย/นาง/นางสาว" raw = page.get_text("rawdict") for block in raw["blocks"]: for line in block.get("lines", []): chars = [c for s in line["spans"] for c in s["chars"]] text = "".join(c["c"] for c in chars) i = text.find(thai) if i < 0 or not (ty0 <= chars[i]["bbox"][1] <= ty1): continue sep = thai[3] parts = thai.split(sep) pos = i for (value, _), part in zip(THAI_TITLES, parts): cs = chars[pos : pos + len(part)] x0 = min(c["bbox"][0] for c in cs) x1 = max(c["bbox"][2] for c in cs) y0 = min(c["bbox"][1] for c in cs) y1 = max(c["bbox"][3] for c in cs) out.append(("title", value, page_no, x0, x1, y0, y1)) pos += len(part) + 1 return out raise SystemExit(f"{form}: no Thai title span {thai!r}") def tm47_entered(doc): """The day and month blanks of 'เดินทางเข้ามาเมื่อวันที่ ... เดือน ...'.""" page = doc[0] raw = page.get_text("rawdict") for block in raw["blocks"]: for line in block.get("lines", []): chars = [c for s in line["spans"] for c in s["chars"]] text = "".join(c["c"] for c in chars) if text.startswith("เดินทางเข้ามาเมื่อวันที่"): day_from = chars[len("เดินทางเข้ามาเมื่อวันที่") - 1]["bbox"][2] + 1.5 j = text.index("เดือน") day_to = chars[j]["bbox"][0] - 1.5 month_from = chars[j + len("เดือน") - 1]["bbox"][2] + 1.5 return (day_from, day_to), (month_from, 268.6) raise SystemExit("tm47: no entry line") def rust_blanks(form): path = REPO / "forms" / f"{form}.pdf" if form == "tm47": doc = pymupdf.open(path) (d0, d1), (m0, m1) = tm47_entered(doc) out = [] for key, y, x0, x1 in TM47: if key == "arrival_day": x0, x1 = d0, d1 elif key == "arrival_month": x0, x1 = m0, m1 out.append((1, x0, y, x1 - x0, key)) return out rows = sorted(fb.blanks(str(path)), key=lambda r: (r[0], r[3], r[1])) mapping, skip = MAP[form], SKIP[form] numbers = set(range(1, len(rows) + 1)) assert set(mapping) | skip == numbers, (form, sorted(numbers - set(mapping) - skip), sorted(set(mapping) - numbers)) assert not set(mapping) & skip, form out = [] for n, (page, x0, x1, y, _label) in enumerate(rows, 1): if n in mapping: out.append((page, x0, y, x1 - x0, mapping[n])) return out FORMS = ["tm7", "stm2", "stm9", "stm11", "stm1", "tm47", "tm8"] def main(): lines = [ "//! Where the values go on the official forms: generated by", "//! scripts/gen_layout.py from the blank forms in forms/ (positions in PDF", "//! points from the top left of the page, the baseline of each blank's", "//! dotted line). Do not edit by hand; measure again when the Immigration", "//! Bureau publishes a new version of a form.", "", "use super::{Blank, Layout, Mark, b, m};", "", ] for form in FORMS: doc = pymupdf.open(REPO / "forms" / f"{form}.pdf") blanks = rust_blanks(form) marks = [("tick",) + t for t in TICKS.get(form, [])] if form in TITLE_WORDS: marks += [("ring",) + r for r in rings(form, doc)] name = form.upper() lines.append(f"pub const {name}: Layout = Layout {{") lines.append(f" blanks: &{name}_BLANKS,") lines.append(f" marks: &{name}_MARKS,") lines.append("};") lines.append("") lines.append(f"const {name}_BLANKS: [Blank; {len(blanks)}] = [") for page, x, y, w, key in blanks: lines.append(f" b({page}, {x:.1f}, {y:.1f}, {w:.1f}, \"{key}\"),") lines.append("];") lines.append("") lines.append(f"const {name}_MARKS: [Mark; {len(marks)}] = [") for kind, key, value, page, x0, x1, y0, y1 in marks: ring = "true" if kind == "ring" else "false" lines.append( f" m({page}, {x0:.1f}, {y0:.1f}, {x1 - x0:.1f}, {y1 - y0:.1f}, \"{key}\", \"{value}\", {ring})," ) lines.append("];") lines.append("") out = REPO / "src" / "papers" / "layout.rs" out.parent.mkdir(exist_ok=True) out.write_text("\n".join(lines), encoding="utf-8", newline="\n") # formatted as cargo fmt would, so a rerun gives the committed file subprocess.run(["rustfmt", "--edition", "2024", str(out)], check=True) print("wrote", out, sum(1 for l in lines if l.startswith(" b(")), "blanks", sum(1 for l in lines if l.startswith(" m(")), "marks") if __name__ == "__main__": main()