"""Read Japanese text from a game or visual novel screenshot, without furigana. Free to use, no warranty.
Brasspage, Nov 2026.

Usage: python vn_ocr.py shot.png [x y w h]
Needs: pip install meikiocr  (tested with 0.3.5; the first run downloads its models, LGPL-3.0)
x y w h: an optional dialog area, in pixels (left, top, width, height). Without it the whole screenshot is read.

How it works: meikiocr (rtr46/meikiocr, Apache-2.0) finds each text line and reads it. Furigana comes back as
lines of its own, about half as tall as the text under it, so this script drops any line whose letters are
under 0.6 of the tallest line's letter height. A small name tag stays. Not tested on vertical text.
"""

import statistics
import sys

import cv2
from meikiocr import MeikiOCR

img = cv2.imread(sys.argv[1])
if img is None:
    sys.exit(f"Can not read {sys.argv[1]}")
if len(sys.argv) == 6:
    x, y, w, h = map(int, sys.argv[2:])
    img = img[y : y + h, x : x + w]

# punct_conf_factor 0.5: where a 「 and the letter after it overlap, keep the letter. With the default 1.0,
# meikiocr dropped the first letter on 18 of our 100 test screens; with 0.5 it dropped none (it drops more 「 instead).
lines = [
    line for line in MeikiOCR().run_ocr(img, punct_conf_factor=0.5) if line["chars"]
]


def height(line):
    return statistics.median(c["bbox"][3] - c["bbox"][1] for c in line["chars"])


tallest = max(map(height, lines), default=0)
for line in lines:
    if height(line) >= 0.6 * tallest:
        print(line["text"])
