#!/usr/bin/env python3
"""card2csv.py: business card scans or photos to one CSV file, a row a card.
Free and offline: OpenCV finds the card in a photo and flattens it, Tesseract
reads it, then plain rules sort the lines into fields.

Usage:  python3 card2csv.py cards/*.jpg > cards.csv
        python3 card2csv.py --rapid cards/*.jpg > cards.csv   (RapidOCR: slower,
        better on phone photos; pip install rapidocr onnxruntime first)
Needs:  Tesseract 5 (macOS: brew install tesseract,
        Ubuntu: sudo apt install tesseract-ocr), Python 3.10+, and
        pip install opencv-python-headless numpy
Fields: name, title, company, phone, phone2, email, website, address.
        A field it can not find stays empty.
The CSV is UTF-8 with a byte order mark, so Excel keeps accents (Renée, Tomás).
Brasspage, Nov 2026. MIT license.
"""

import csv
import re
import subprocess
import sys
import unicodedata

import cv2
import numpy as np

FIELDS = [
    "file",
    "name",
    "title",
    "company",
    "phone",
    "phone2",
    "email",
    "website",
    "address",
]
EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
URL = re.compile(
    r"(?:https?:/\s?/)?(?:www\.)?([a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,})\b/?", re.I
)
PHONE = re.compile(r"\+?\(?\d[\d ().-]{6,}\d")
LABEL = re.compile(  # a label at the start of a line
    r"^(?:"
    r"tel|phone|mobile|mob|cell|office|direct|fax|email|e-mail|web|t|p|m|c|f|"
    r"e|w"
    r")(?![a-z])[:.]?\s*",
    re.I,
)
INLABEL = re.compile(
    r"\b(?:tel|phone|mobile|cell|office|fax|t|p|m|c|f)[:.]?\s*(?=[+(]?\d)", re.I
)  # a label inside a line
ZIP = re.compile(r"\b[A-Z]{2}\s+\d{5}(?:-\d{4})?\b")  # US: state and ZIP
POSTCODE = re.compile(r"\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b")  # UK postcode
STREET = re.compile(r"^\d+[A-Za-z]?\s+[A-Za-z]")
COMPANY = re.compile(
    r"\b(?:"
    r"inc|llc|ltd|co|corp|company|group|studio|services|partners|agency|"
    r"associates|gmbh|plc|llp"
    r")\b\.?",
    re.I,
)
JOB = re.compile(
    r"\b(?:"
    r"owner|founder|co-founder|president|ceo|cfo|coo|cto|chief|director|"
    r"manager|head|lead|officer|agent|broker|executive|designer|engineer|"
    r"developer|architect|consultant|advisor|specialist|coordinator|"
    r"assistant|associate|analyst|accountant|bookkeeper|attorney|lawyer|"
    r"partner|principal|chef|therapist|contractor|electrician|plumber|"
    r"technician|planner|realtor|representative|sales|marketing|operations|"
    r"editor|producer|photographer|nurse|doctor|dentist|teacher"
    r")\b",
    re.I,
)


def flatten(img):
    """BGR image -> the card, cropped and flat.

    The whole image when no outline of card size and shape shows (a scan)."""
    h, w = img.shape[:2]
    k = 1000 / max(h, w)
    s = cv2.GaussianBlur(
        cv2.resize(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), None, fx=k, fy=k), (5, 5), 0
    )
    e = cv2.dilate(cv2.Canny(s, 30, 90), np.ones((3, 3), np.uint8))
    cs, _ = cv2.findContours(e, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if not cs:
        return img
    c = cv2.convexHull(max(cs, key=cv2.contourArea))
    if cv2.contourArea(c) < 0.15 * s.size or cv2.contourArea(c) > 0.95 * s.size:
        return img
    q = cv2.approxPolyDP(c, 0.02 * cv2.arcLength(c, True), True).reshape(-1, 2)
    if len(q) != 4:
        q = cv2.boxPoints(cv2.minAreaRect(c))
    q = q.astype(np.float32) / k
    o = q.sum(1).argmin()  # top-left first, then clockwise
    q = np.roll(q, -o, axis=0)
    a, b = q[1] - q[0], q[3] - q[0]
    if a[0] * b[1] - a[1] * b[0] < 0:  # counterclockwise (y points down): flip
        q = q[[0, 3, 2, 1]]
    W = int(max(np.linalg.norm(q[1] - q[0]), np.linalg.norm(q[2] - q[3])))
    H = int(max(np.linalg.norm(q[3] - q[0]), np.linalg.norm(q[2] - q[1])))
    if (
        not 1.3 <= max(W, H) / max(1, min(W, H)) <= 2.2
    ):  # not card shaped (a color band, a logo): keep it all
        return img
    M = cv2.getPerspectiveTransform(q, np.float32([[0, 0], [W, 0], [W, H], [0, H]]))
    return cv2.warpPerspective(img, M, (W, H))


def ocr(path):
    """The flat card to Tesseract on stdin, in sparse text mode (short lines)."""
    png = cv2.imencode(".png", flatten(cv2.imread(path)))[1].tobytes()
    out = subprocess.run(
        ["tesseract", "stdin", "stdout", "--psm", "11"],
        input=png,
        capture_output=True,
        check=True,
    )
    return out.stdout.decode("utf-8", "replace").splitlines()


_rapid = None


def ocr_rapid(path):
    """RapidOCR on the image as it is, its text lines in reading order."""
    global _rapid
    if _rapid is None:
        from rapidocr import RapidOCR

        _rapid = RapidOCR(params={"Global.log_level": "error"})
    r = _rapid(path)
    if r.txts is None:
        return []
    boxes = [(t, *b.min(0), *b.max(0)) for t, b in zip(r.txts, r.boxes, strict=True)]
    return ordered([(t, *map(float, b)) for t, *b in boxes])


def ordered(items):
    """[(text, x0, y0, x1, y1)] -> texts top to bottom, then left to right.
    Boxes whose centers sit within half a box height share a row."""
    items = sorted(items, key=lambda b: (b[2] + b[4]) / 2)
    rows = []
    for b in items:
        mid = (b[2] + b[4]) / 2
        if rows and abs(mid - rows[-1][0]) < (b[4] - b[2]) / 2:
            rows[-1][1].append(b)
        else:
            rows.append([mid, [b]])
    return [b[0] for _, row in rows for b in sorted(row, key=lambda b: b[1])]


def plain(s):
    return unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode().lower()


def wordy(line):
    """A line of real words: most characters are letters."""
    letters = sum(ch.isalpha() for ch in line)
    return len(line) >= 3 and letters >= 0.6 * len(line.replace(" ", ""))


def parse(lines):
    """Text lines of one card, in reading order -> dict of fields."""
    f = dict.fromkeys(FIELDS[1:], "")
    rest, phones, addr = [], [], []
    # a line can hold more than one item: "T 555 0100   M 555 0101", "phone   email"
    for raw in lines:
        line = re.sub(r"\s*@\s*", "@", " ".join(raw.split()))
        for m in EMAIL.finditer(line):
            f["email"] = f["email"] or m.group(0).lower().strip(".")
        line = EMAIL.sub(" ", line)
        u = URL.search(line)
        if u:
            f["website"] = f["website"] or re.sub(r"^www\.", "", u.group(1).lower())
            line = line.replace(u.group(0), " ")
        body = " ".join(INLABEL.sub(" ", LABEL.sub("", line.strip())).split())
        if not (STREET.match(body) or ZIP.search(body)):
            # a label inside the line splits two numbers: "T (614) 555-0103 M (720) ..."
            split = " ".join(INLABEL.sub(" ; ", LABEL.sub("", line.strip())).split())
            for p in PHONE.finditer(split):
                if 7 <= sum(ch.isdigit() for ch in p.group(0)) <= 13:
                    phones.append(p.group(0).strip())
                    body = body.replace(p.group(0), " ")
            body = " ".join(body.split())
        if not body:
            continue
        if STREET.match(body) or ZIP.search(body) or POSTCODE.search(body):
            addr.append(body)
            continue
        if wordy(line):
            rest.append(line)
    f["phone"], f["phone2"] = (phones + ["", ""])[:2]
    f["address"] = ", ".join(addr)
    domain = (f["email"].split("@")[1] if f["email"] else f["website"]).split(".")[0]
    local = f["email"].split("@")[0] if f["email"] else ""
    # company: the line that spells the web domain, else a line with Inc, LLC, ...
    for line in rest:
        key = re.sub(r"[^a-z]", "", plain(line))
        if (domain and len(domain) >= 4 and domain[:6] in key) or COMPANY.search(line):
            f["company"] = line
            break
    rest = [x for x in rest if x != f["company"]]
    # name: the line that matches the email name (maria.lopez, mlopez, maria),
    # else the first line of 2 to 3 capitalized words
    toks = [t for t in re.split(r"[._-]", local) if t]
    for line in rest:
        words = re.sub(r"[^a-z ]", "", plain(line)).split()
        if not 2 <= len(words) <= 4 or JOB.search(line):
            continue
        if toks and (
            set(toks) & set(words)
            or (len(toks) == 1 and toks[0] == words[0][0] + words[-1])
        ):
            f["name"] = line
            break
    if not f["name"]:
        for line in rest:
            words = line.split()
            if (
                2 <= len(words) <= 3
                and all(w[0].isupper() for w in words)
                and not JOB.search(line)
            ):
                if not any(ch.isdigit() for ch in line):
                    f["name"] = line
                    break
    rest = [x for x in rest if x != f["name"]]
    # title: the first line left with a job word (owner, manager, agent and the like)
    for line in rest:
        if JOB.search(line):
            f["title"] = line
            break
    return f


def main():
    w = csv.DictWriter(sys.stdout, FIELDS)
    sys.stdout.reconfigure(encoding="utf-8-sig", newline="")  # no blank rows on Windows
    w.writeheader()
    paths = sys.argv[1:]
    read = ocr
    if paths and paths[0] == "--rapid":
        paths, read = paths[1:], ocr_rapid
    for path in paths:
        w.writerow({"file": path, **parse(read(path))})


if __name__ == "__main__":
    main()
