Saturday, November 21, 2026

NLP Test with Four Languages (NLP-01)

အောက်ပါပရိုဂရမ်သည် ဘာသာစကားအမျိုးမျိုးဖြင့် ရေးသားထားသော ဂန္ထဝင်စာအုပ်များ (Project Gutenberg Corpus) ထဲမှ စကားလုံးအရေအတွက် စုစုပေါင်း (Book Length) နှင့် မတူညီသော စကားလုံးအသစ် အရေအတွက် (Unique Vocabulary Size) တို့ကြား ဆက်နွှယ်မှုကို Natural Language Processing (NLP) နည်းလမ်းဖြင့် ခွဲခြမ်းစိတ်ဖြာပြီး Log-Log ဂရပ်ဖ် ရေးဆွဲသည့် ပရိုဂရမ် ဖြစ်ပါသည်။

ပရိုဂရမ်၏ လုပ်ဆောင်ပုံ အဆင့်ဆင့် ရှင်းလင်းချက်

  1. အဆင့် (၁) — စာသားသန့်စင်ခြင်းနှင့် စကားလုံးအကြိမ်ရေ ရေတွက်ခြင်း (count_words & count_words_fast)

    • စာသားအားလုံးကို စာလုံးအသေး (.lower()) ပြောင်းလဲ၍ စာလုံးအကြီး/အသေး ကွဲပြားမှုကြောင့် စကားလုံးတစ်လုံးတည်းကို နှစ်မျိုးမရေတွက်မိစေရန် ပြုလုပ်ပါသည် (Case Folding)။

    • ပုဒ်ဖြတ်ပုဒ်ရပ် သင်္ကေတများ (., ,, ;, :, ', ") ကို ဖယ်ရှားပြီး စကားလုံးတစ်လုံးချင်းစီ မည်မျှပါဝင်ကြောင်း Dictionary ({word: count}) အဖြစ် ရေတွက်ပါသည်။

  2. အဆင့် (၂) — စာအုပ်ဖိုင် ဖတ်ယူခြင်း (read_book)

    • encoding="utf8" ဖြင့် ဖိုင်ကို ဖွင့်ဖတ်ခြင်းကြောင့် ပြင်သစ်၊ ဂျာမန်၊ ပေါ်တူဂီ စသည့် ဘာသာစကားများရှိ အထူးအက္ခရာများ (Accented characters ဥပမာ — é, ü, ç) မပျက်စီးဘဲ အပြည့်အဝ ဖတ်ယူနိုင်ပါသည်။

  3. အဆင့် (၃) — ဝေါဟာရ စာရင်းအင်း တွက်ချက်ခြင်း (word_stats)

    • စကားလုံးအကြိမ်ရေ Dictionary ထဲမှ မတူညီသော စကားလုံးအရေအတွက် (num_unique = len(word_counts)) နှင့် စကားလုံးတစ်လုံးချင်းစီ၏ ပါဝင်မှုအကြိမ်ရေ (counts = word_counts.values()) ကို ထုတ်ပေးပါသည်။

  4. အဆင့် (၄) — ဖိုင်တွဲအဆင့်ဆင့် ဝင်ရောက်ဖတ်ရှုပြီး ဇယားတည်ဆောက်ခြင်း (stats DataFrame)

    • Books -> language -> author -> title.txt ဟူသော အဆင့် ၃ ဆင့်ပါ Folder Structure ထဲသို့ Nested for loop ဖြင့် ဝင်ရောက်ကာ စာအုပ်တစ်အုပ်ချင်းစီ၏ ဘာသာစကား၊ စာရေးဆရာ၊ စာအုပ်အမည်၊ စကားလုံးစုစုပေါင်း (sum(counts)) နှင့် စကားလုံးအသစ်အရေအတွက် (num_unique) တို့ကို Pandas DataFrame stats ထဲသို့ စုစည်းထည့်သွင်းပါသည်။

  5. အဆင့် (၅) — Log-Log ဂရပ်ဖ် ရေးဆွဲခြင်း (plt.loglog)

    • X-ဝင်ရိုးတွင် စာအုပ်အရှည် (length) နှင့် Y-ဝင်ရိုးတွင် မတူညီသော စကားလုံးအရေအတွက် (unique) တို့ကို Logarithmic Scale ဖြင့် ပုံဖော်ပြီး lang_plot.pdf အဖြစ် သိမ်းဆည်းပါသည်။


ဖန်ရှင်များ၏ အဆက်အစပ်နှင့် ပရိုဂရမ်တစ်ပုဒ်လုံး၏ ရည်ရွယ်ချက်

ပရိုဂရမ်တစ်ပုဒ်လုံး၏ ရည်ရွယ်ချက်

  • လက်တွေ့ ရည်ရွယ်ချက် စာအုပ်တစ်အုပ်၏ စကားလုံးအရေအတွက် ရှည်လျားလာသည်နှင့်အမျှ စာရေးဆရာ အသုံးပြုသော ဝေါဟာရအသစ် (unique words) အရေအတွက် မည်သို့ တိုးပွားလာသလဲ ဆိုသည်ကို ဘာသာစကားအလိုက် နှိုင်းယှဉ်လေ့လာရန် ဖြစ်ပါသည်။

  • AIMA NLP သီအိုရီ ရည်ရွယ်ချက် (Chapter 23 — Natural Language Processing) သဘာဝဘာသာစကားများ၏ အခြေခံသင်္ချာနိယာမ နှစ်ခုဖြစ်သော Heaps' Law ($V(N) = K \cdot N^\beta$ — စကားလုံးစုစုပေါင်း $N$ တိုးလာတိုင်း ဝေါဟာရအသစ် $V$ သည် မျဉ်းဖြောင့်အတိုင်း မတိုးဘဲ Power-Law အချိုးအစားအတိုင်း နှေးကွေးစွာ တိုးပွားလာခြင်း) နှင့် Zipf's Law ($f(r) \propto 1/r^\alpha$) တို့ကို လက်တွေ့စာအုပ်ဒေတာများဖြင့် သက်သေပြရန် ဖြစ်ပါသည်။


ဖန်ရှင် ၄ ခု၏ အပြန်အလှန် အဆက်အစပ် (NLP Processing Pipeline)

Plaintext
[Books / language / author / title.txt]  (Nested Directory Traversal)
                   │
                   ▼
        1. read_book(title_path) ────────► စာအုပ်တစ်အုပ်လုံး၏ Raw Text (UTF-8 String)
                   │
                   ▼
        2. count_words_fast(text) ───────► စကားလုံးအကြိမ်ရေ Dictionary {word: freq}
                   │
                   ▼
        3. word_stats(word_counts) ──────► (num_unique, counts) -> စုစုပေါင်း = sum(counts)
                   │
                   ▼
        4. Pandas DataFrame ('stats') ───► (language, author, title, length, unique)
                   │
                   ▼
        5. plt.loglog(length, unique) ───► Heaps' Law Power-Law Graph (lang_plot.pdf)


Python Code


Python
# -*- coding: utf-8 -*-
"""
Computational Linguistics & Natural Language Processing (NLP):
Multilingual Book Corpus Analysis, Heaps' Law & Zipf's Law
Connected with AIMA (4th Ed.) Chapter 23 (Natural Language Processing)
"""

import os
import re
import time
from collections import Counter
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.style.use('ggplot')


# ==============================================================================
# ဖန်ရှင် (၁) - စာသားသန့်စင်ခြင်းနှင့် စကားလုံးအကြိမ်ရေ ရေတွက်ခြင်း (Baseline Dictionary)
# AIMA (4th Ed.) Ch. 23, Sec. 23.1 (Language Models: Tokenization & Bag-of-Words)
# သီအိုရီ -
#   1. Tokenization & Normalization: စာသားတစ်ခုကို စက်က နားလည်နိုင်ရန် အခြေခံယူနစ်များ
#      (Tokens / Words) အဖြစ် ပိုင်းဖြတ်ရသည်။ စာလုံးအသေးပြောင်းခြင်း (Case Folding: .lower())
#      နှင့် ပုဒ်ဖြတ်ပုဒ်ရပ်များ ဖယ်ရှားခြင်းသည် တူညီသော စကားလုံးများကို တစ်ခုတည်းအဖြစ်
#      ပေါင်းစည်းပေးသဖြင့် ဝေါဟာရအရွယ်အစား (Vocabulary Size |V|) မဖောင်းပွစေရန် ထိန်းသိမ်းပေးသည်။
#   2. Unigram Bag-of-Words Model: စကားလုံးအစီအစဉ်ကို ဖယ်ထားပြီး စကားလုံးတစ်လုံးချင်းစီ၏
#      ပါဝင်မှုကြိမ်နှုန်း P(w_i) = count(w_i) / N ကို တွက်ချက်ခြင်း ဖြစ်သည်။
# ==============================================================================
def count_words(text):
    """Count the number of words in given text (str) using a standard dictionary."""
    text = text.lower()
    skips = [".", ",", ";", ":", "'", '"', "!", "?", "(", ")", "-", "—", "_"]
    for ch in skips:
        text = text.replace(ch, " ")

    word_counts = {}
    # text.split() (argument မပါ) ကို သုံးခြင်းဖြင့် Space အပိုများကြောင့် "" (Empty Token) မဖြစ်စေပါ
    for word in text.split():
        if word in word_counts:
            word_counts[word] += 1
        else:
            word_counts[word] = 1
    return word_counts


# ==============================================================================
# ဖန်ရှင် (၂) - အမြန်နှုန်းမြင့် စကားလုံးရေတွက်ခြင်း (Optimized C-Backed Counter)
# AIMA (4th Ed.) Appendix A & Ch. 23.1 (Scalable Corpus Processing)
# သီအိုရီ - နှစ်ခုလုံးသည် Time Complexity O(N) ဖြစ်သော်လည်း collections.Counter သည်
# Python ၏ C-level hash table ကို တိုက်ရိုက်အသုံးပြုသောကြောင့် စာအုပ်ကြီးများစွာကို
# ဖတ်ရှုရာတွင် သာမန် Python loop ထက် ၂ ဆမှ ၃ ဆခန့် ပိုမိုမြန်ဆန်သည်။
# ==============================================================================
def count_words_fast(text):
    """Count the number of words in given text (str) using collections.Counter."""
    text = text.lower()
    skips = [".", ",", ";", ":", "'", '"', "!", "?", "(", ")", "-", "—", "_"]
    for ch in skips:
        text = text.replace(ch, " ")

    return Counter(text.split())


# ==============================================================================
# ဖန်ရှင် (၃) - စာအုပ်ဖိုင် ဖတ်ယူခြင်း (UTF-8 Corpus Ingestion)
# AIMA (4th Ed.) Ch. 23, Sec. 23.1 (Multilingual Character Encoding)
# သီအိုရီ - ဘာသာစကားအမျိုးမျိုး (English, French, German, Portuguese) ၏ အထူးအက္ခရာများ
# မပျက်စီးစေရန် UTF-8 ဖြင့် ဖတ်ယူရမည်။ ထို့အပြင် စာကြောင်းအဆုံး (\n, \r) များကို "" အစား
# " " (Space) ဖြင့် အစားထိုးမှသာ စာကြောင်းတစ်ခုအဆုံးနှင့် နောက်တစ်ခုအစ စကားလုံးများ ပူးကပ်မသွားမည်။
# ==============================================================================
def read_book(title_path):
    """Read the book in UTF-8 encoding and normalize line breaks into spaces."""
    with open(title_path, "r", encoding="utf-8", errors="replace") as current_file:
        text = current_file.read()
        text = text.replace("\n", " ").replace("\r", " ")
    return text


# ==============================================================================
# ဖန်ရှင် (၄) - ဝေါဟာရ စာရင်းအင်း တွက်ချက်ခြင်း (Types vs. Tokens)
# AIMA (4th Ed.) Ch. 23, Sec. 23.1 (Type-Token Ratio & Vocabulary Growth)
# သီအိုရီ - ဘာသာဗေဒနှင့် NLP တွင် စကားလုံးစုစုပေါင်း (sum(counts)) ကို "Tokens (N)" ဟုခေါ်ပြီး၊
# မတူညီသော စကားလုံးအသစ် အရေအတွက် (len(word_counts)) ကို "Types / Vocabulary (V)" ဟုခေါ်သည်။
# ==============================================================================
def word_stats(word_counts):
    """Return number of unique words (types) and word frequencies (token counts)."""
    num_unique = len(word_counts)
    counts = word_counts.values()
    return (num_unique, counts)


# ==============================================================================
# အပိုင်း (၅) - ဖိုင်တွဲအဆင့်ဆင့် ဝင်ရောက်ဖတ်ရှုပြီး Corpus Statistics တည်ဆောက်ခြင်း
# ==============================================================================
# Windows ဖိုင်လမ်းကြောင်းတွင် \U Unicode Error မတက်စေရန် Raw String (r"...") ကို သုံးရမည်
book_dir = r"C:\Users\kks\OneDrive\Desktop\MyPyTest\Module4\Datasets\Books"

rows = []
global_counters_by_lang = {}  # ဘာသာစကားအလိုက် Zipf's Law တွက်ချက်ရန် စုစည်းထားမည်
t0 = time.time()

for language in sorted(os.listdir(book_dir)):
    lang_path = os.path.join(book_dir, language)
    if not os.path.isdir(lang_path):
        continue

    global_counters_by_lang[language] = Counter()

    for author in sorted(os.listdir(lang_path)):
        author_path = os.path.join(lang_path, author)
        if not os.path.isdir(author_path):
            continue

        for title in sorted(os.listdir(author_path)):
            if not title.lower().endswith(".txt"):
                continue

            inputfile = os.path.join(author_path, title)
            text = read_book(inputfile)
            wc = count_words_fast(text)
            global_counters_by_lang[language].update(wc)

            (num_unique, counts) = word_stats(wc)
            total_tokens = sum(counts)
            ttr = num_unique / total_tokens if total_tokens > 0 else 0.0

            rows.append({
                "language": language,
                "author": author.capitalize(),
                "title": os.path.splitext(title)[0],
                "length": total_tokens,
                "unique": num_unique,
                "type_token_ratio": round(ttr, 4)
            })

stats = pd.DataFrame(rows)
stats.index = np.arange(1, len(stats) + 1)

print(f"Processed {len(stats)} books across {stats['language'].nunique()} languages in {time.time() - t0:.2f}s.\n")
print("First 5 Books (stats.head()):")
print(stats.head())
print("\nLast 5 Books (stats.tail()):")
print(stats.tail())

print("\nSummary Statistics by Language (Mean Book Length & Unique Vocabulary):")
print(stats.groupby("language")[["length", "unique", "type_token_ratio"]].mean().round(2))


# ==============================================================================
# အပိုင်း (၆) - Heaps' Law နှင့် Zipf's Law ဂရပ်ဖ် ၂ ခု ရေးဆွဲခြင်း
# AIMA (4th Ed.) Ch. 23, Sec. 23.1 (Empirical Laws of Natural Language: Heaps' & Zipf's Laws)
# သီအိုရီ -
#   1. Heaps' Law: V(N) = K * N^beta  =>  log(V) = log(K) + beta * log(N)
#      Log-Log ဂရပ်ဖ်ပေါ်တွင် စာအုပ်အရှည် (N) နှင့် မတူညီသော စကားလုံးအရေအတွက် (V) တို့သည်
#      လျှောစောက် beta (0.45 မှ 0.65 ဝန်းကျင်) ရှိသော မျဉ်းဖြောင့်တစ်ကြောင်းအတိုင်း ရှိနေသည်။
#      ဝိဘတ်နှင့် ကြိယာပြောင်းလဲပုံ ကြွယ်ဝသော ဘာသာစကားများ (French, German, Portuguese) သည်
#      English ထက် Unique Words ပိုမိုများပြားသည်ကို ဂရပ်ဖ်ပေါ်တွင် အထင်အရှား တွေ့နိုင်သည်။
#   2. Zipf's Law: f(r) ∝ 1 / r^alpha
#      စကားလုံးများကို အကြိမ်ရေအများဆုံးမှ အနည်းဆုံးသို့ အဆင့်စီ (Rank r = 1, 2, 3, ...) လိုက်ပါက
#      အဆင့် r မြောက် စကားလုံး၏ အကြိမ်ရေသည် 1/r နှင့် ပြောင်းပြန်အချိုးကျသဖြင့် Log-Log ဂရပ်ဖ်တွင်
#      လျှောစောက် -1 နီးပါးရှိသော မျဉ်းဖြောင့်အဖြစ် ပေါ်ထွက်လာသည်။
# ==============================================================================
lang_colors = {
    "English": "crimson",
    "French": "forestgreen",
    "German": "royalblue",
    "Portuguese": "darkorange"
}

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15.5, 6.2))

# --- ဘယ်ဘက်ဂရပ်ဖ်: Heaps' Law (Book Length vs. Unique Words on Log-Log Scale) ---
for lang in sorted(stats["language"].unique()):
    subset = stats[stats["language"] == lang]
    c = lang_colors.get(lang, None)

    # Power-law regression fit: log10(V) = beta * log10(N) + log10(K)
    if len(subset) >= 2:
        beta, log_k = np.polyfit(np.log10(subset["length"]), np.log10(subset["unique"]), 1)
        x_fit = np.logspace(np.log10(subset["length"].min()), np.log10(subset["length"].max()), 50)
        y_fit = (10**log_k) * (x_fit**beta)
        ax1.loglog(x_fit, y_fit, linestyle="--", alpha=0.55, color=c)
        lbl = f"{lang} (n={len(subset)}, β={beta:.2f})"
    else:
        lbl = f"{lang} (n={len(subset)})"

    ax1.loglog(subset["length"], subset["unique"], "o", markersize=7, alpha=0.85, label=lbl, color=c)

ax1.legend(fontsize=9.5)
ax1.set_xlabel("Book Length: Total Word Tokens (N) [Log Scale]", fontsize=11)
ax1.set_ylabel("Number of Unique Words: Vocabulary Size (V) [Log Scale]", fontsize=11)
ax1.set_title("1. Heaps' Law Across Languages (V = K · N^β)\nSub-Linear Vocabulary Growth on Log-Log Plot",
              fontsize=11.5, fontweight="bold")
ax1.grid(True, which="both", linestyle=":", alpha=0.6)

# --- ညာဘက်ဂရပ်ဖ်: Zipf's Law (Word Frequency vs. Rank on Log-Log Scale) ---
for lang, total_counter in sorted(global_counters_by_lang.items()):
    if len(total_counter) == 0:
        continue
    freqs = np.array(sorted(total_counter.values(), reverse=True), dtype=np.float64)
    ranks = np.arange(1, len(freqs) + 1)
    c = lang_colors.get(lang, None)
    ax2.loglog(ranks, freqs, linewidth=2.0, alpha=0.85, label=f"{lang} (|V|={len(freqs):,})", color=c)

ax2.legend(fontsize=9.5)
ax2.set_xlabel("Word Frequency Rank (r) [Log Scale]", fontsize=11)
ax2.set_ylabel("Word Frequency f(r) [Log Scale]", fontsize=11)
ax2.set_title("2. Zipf's Law Verification (f(r) ∝ 1 / r^α)\nHeavy-Tailed Word Distribution Across Gutenberg Corpus",
              fontsize=11.5, fontweight="bold")
ax2.grid(True, which="both", linestyle=":", alpha=0.6)

plt.tight_layout()

# PDF ဖိုင်အဖြစ် သိမ်းဆည်းခြင်း (မူလကုဒ်ပါ lang_plot.pdf အတိုင်း)
output_pdf = os.path.join(os.path.dirname(book_dir), "lang_plot.pdf")
plt.savefig(output_pdf)
print(f"\nSaved Log-Log NLP plot to: {output_pdf}")
plt.show()


ထွက်ပေါ်လာမည့် ရလဒ်များမှ တွေ့ရှိရမည့် NLP သီအိုရီ အနှစ်ချုပ်

ပရိုဂရမ်ကို Run လိုက်သောအခါ ထွက်ပေါ်လာမည့် ဂရပ်ဖ် ၂ ခုတွင် အောက်ပါ ဘာသာဗေဒဆိုင်ရာ အချက်အလက်များကို မျက်မြင်တွေ့ရှိနိုင်ပါသည်—
  1. ဘယ်ဘက်ဂရပ်ဖ် (Heaps' Law — V = K · N^β)

    • ဘာသာစကားတိုင်း၏ စာအုပ်အမှတ်များသည် Log-Log ဂရပ်ဖ်ပေါ်တွင် လျှောစောက် $\beta \approx 0.50 \text{ မှ } 0.65$ ဝန်းကျင်ရှိသော မျဉ်းဖြောင့်များအတိုင်း စီတန်းနေပါသည် (ဆိုလိုသည်မှာ စာအုပ်အရှည် 4 ဆ ပိုရှည်လာသော်လည်း စကားလုံးအသစ် အရေအတွက်မှာ 2 ဆခန့်သာ တိုးလာပါသည်)။

    • ထို့အပြင် စာအုပ်အရှည် တူညီသည့်တိုင် French, German နှင့် Portuguese စာအုပ်များ၏ အမှတ်များသည် English စာအုပ်များထက် ပိုမိုမြင့်မားသော နေရာတွင် ရှိနေပါသည်။ အကြောင်းမှာ ပြင်သစ်နှင့် ဂျာမန်ဘာသာစကားများတွင် ကျား/မ လိင်နှင့် ကြိယာကာလအလိုက် စကားလုံးပုံစံ ပြောင်းလဲမှု (Morphological Inflection) ပိုမိုများပြားသောကြောင့် ဖြစ်ပါသည်။

  2. ညာဘက်ဂရပ်ဖ် (Zipf's Law — f(r) ∝ 1 / r^α)

    • ဘာသာစကား ၄ မျိုးလုံး၏ စကားလုံးအကြိမ်ရေ မျဉ်းကွေးများသည် Log-Log ဂရပ်ဖ်ပေါ်တွင် တစ်ထပ်တည်းနီးပါး တူညီသော လျှောစောက် -1 မျဉ်းဖြောင့် အဖြစ် ဆင်းသွားသည်ကို တွေ့ရပါမည်— ၎င်းက အင်္ဂလိပ် (the, of, and) ဖြစ်စေ၊ ပြင်သစ် (de, la, et) ဖြစ်စေ လူသားဘာသာစကားတိုင်းတွင် ထိပ်ဆုံးစကားလုံး အနည်းငယ်က စာအုပ်တစ်ခုလုံး၏ ၅၀% ခန့်ကို နေရာယူထားပြီး ကျန်စကားလုံးအများစုမှာ ၁ ကြိမ် သို့မဟုတ် ၂ ကြိမ်သာ ပါဝင်သည့် Heavy-Tailed Distribution ရှိကြောင်း သက်သေပြနေပါသည်။