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

Сравнивает частоту окончаний слов в туркменском (кириллица) образце
против русских образцов - чтобы найти окончания, которые действительно
характерны для туркменского текста ПОСЛЕ распознавания его через
русскую OCR-модель (а не "настоящие" туркменские буквы, которых там
быть не может).
"""

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 языках"

TURKMEN_FILE = "Ata Atajanow - Teke gyzy Tatýana-1987 Türkmenistan.pdf"
RUSSIAN_FILES = [
    "Аннанепесов М. - Туркмены в экспедициях А. Бековича-Черкасского 1715-1717 гг (1979).pdf",
    "Жуковский В. А. - Развалины древнего Мерва (1894).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="rus"):
    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="rus")
    doc.close()
    return [w for w in words if WORD_RE.fullmatch(w) and len(w) >= 4]


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


def main():
    print("Распознаю туркменский образец...")
    tk_words = get_words(TURKMEN_FILE)
    print(f"  слов: {len(tk_words)}")

    print("Распознаю русские образцы...")
    ru_words = []
    for f in RUSSIAN_FILES:
        ru_words.extend(get_words(f))
    print(f"  слов: {len(ru_words)}")

    for length in (2, 3, 4):
        print(f"\n===== Окончания длиной {length} буквы =====")
        tk_c, tk_total = ending_freq(tk_words, length)
        ru_c, ru_total = ending_freq(ru_words, length)

        candidates = []
        for ending, count in tk_c.most_common(40):
            tk_ratio = count / tk_total
            ru_count = ru_c.get(ending, 0)
            ru_ratio = ru_count / ru_total
            # интересуют окончания, частые у туркменского и минимум втрое реже у русского
            if tk_ratio >= 0.008 and ru_ratio < tk_ratio / 3:
                candidates.append((ending, tk_ratio, ru_ratio))

        candidates.sort(key=lambda x: -x[1])
        for ending, tk_r, ru_r in candidates[:15]:
            print(f"  -{ending:<6} туркм.={tk_r:.3f} ({int(tk_r*tk_total)} слов)   русск.={ru_r:.3f} ({int(ru_r*ru_total)} слов)")


if __name__ == "__main__":
    main()
