#!/usr/bin/env python3.11
# -*- coding: utf-8 -*-
"""
analyze_persian_script.py

Сравнивает частоту (а) окончаний слов и (б) частых коротких слов
в белуджском, туркменском-на-фарси и урду образцах против
подтверждённого фарси-образца - чтобы найти маркеры, которые
переживают OCR через модель 'fas' и реально отличают эти языки
друг от друга.
"""

import os
import re
from collections import Counter

import fitz
import pytesseract
from PIL import Image

INPUT_DIR = "/home/dayhanbiz/public_html/3-damja.science/ТЕСТ_образцы_языков/Тексты на 11 языках"

FARSI_BASELINE = "ketab3392.pdf"
TARGETS = {
    "белуджский": "Zuban Zanthi - Balochi Academy E-BOOKS.pdf",
    "туркменский_фарси": "Magtymguly,1926 Türkmen döwlet neşirýat gullugy.pdf",
    "урду": "aab-e-hayat.pdf",
}

WORD_RE = re.compile(r"\w+", re.UNICODE)


def render_pages(doc, start=4, end=9, dpi=200):
    indices = [i - 1 for i in range(start, end + 1) if 0 <= i - 1 < doc.page_count]
    if not indices:
        indices = list(range(min(doc.page_count, 6)))
    images = []
    zoom = dpi / 72
    mat = fitz.Matrix(zoom, zoom)
    for idx in indices:
        page = doc.load_page(idx)
        pix = page.get_pixmap(matrix=mat)
        images.append(Image.frombytes("RGB", [pix.width, pix.height], pix.samples))
    return images


def ocr_words(images, lang="fas"):
    words = []
    for img in images:
        data = pytesseract.image_to_data(img, lang=lang, output_type=pytesseract.Output.DICT)
        for t in data.get("text", []):
            t = t.strip()
            if t:
                words.append(t)
    return words


def get_words(filename):
    path = os.path.join(INPUT_DIR, filename)
    doc = fitz.open(path)
    images = render_pages(doc)
    words = ocr_words(images, lang="fas")
    doc.close()
    return [w for w in words if WORD_RE.fullmatch(w)]


def ending_freq(words, length):
    c = Counter(w[-length:] for w in words if len(w) > length)
    total = len(words) if words else 1
    return c, total


def whole_word_freq(words, max_len=4):
    c = Counter(w for w in words if len(w) <= max_len)
    total = len(words) if words else 1
    return c, total


def print_candidates(title, target_c, target_total, base_c, base_total, top_n=15):
    candidates = []
    for token, count in target_c.most_common(50):
        t_ratio = count / target_total
        b_ratio = base_c.get(token, 0) / base_total
        if t_ratio >= 0.006 and b_ratio < t_ratio / 3:
            candidates.append((token, t_ratio, b_ratio))
    candidates.sort(key=lambda x: -x[1])
    print(f"  {title}:")
    if not candidates:
        print("    (значимых кандидатов не найдено)")
    for token, t_r, b_r in candidates[:top_n]:
        print(f"    {token!r:<10} цель={t_r:.3f}   фарси={b_r:.3f}")


def main():
    print("Распознаю фарси-образец (базовый)...")
    farsi_words = get_words(FARSI_BASELINE)
    print(f"  слов: {len(farsi_words)}")
    farsi_end2, farsi_end2_total = ending_freq(farsi_words, 2)
    farsi_end3, farsi_end3_total = ending_freq(farsi_words, 3)
    farsi_short, farsi_short_total = whole_word_freq(farsi_words)

    for name, filename in TARGETS.items():
        print(f"\n========== {name} ({filename}) ==========")
        words = get_words(filename)
        print(f"  слов распознано: {len(words)}")

        end2, end2_total = ending_freq(words, 2)
        end3, end3_total = ending_freq(words, 3)
        short, short_total = whole_word_freq(words)

        print("\n Окончания (2 буквы):")
        print_candidates("окончания-2", end2, end2_total, farsi_end2, farsi_end2_total)
        print("\n Окончания (3 буквы):")
        print_candidates("окончания-3", end3, end3_total, farsi_end3, farsi_end3_total)
        print("\n Частые короткие слова (до 4 букв, вероятные служебные слова):")
        print_candidates("короткие_слова", short, short_total, farsi_short, farsi_short_total)


if __name__ == "__main__":
    main()
