enver commited on
Commit
083c80f
·
verified ·
1 Parent(s): c713ebf

tools: add core/classical_text_miner.py

Browse files
Files changed (1) hide show
  1. tools/core/classical_text_miner.py +148 -0
tools/core/classical_text_miner.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ classical_text_miner.py
4
+
5
+ AynEngine AI Coding Edition: Classical Text & Lexicon Miner.
6
+ Directly mines passages, definitions, and logical axioms from the classical corpus:
7
+ - Abū Ḥāmid al-Ghazālī: Miʿyār al-ʿIlm fī Fann al-Manṭiq & Miḥakk al-Naẓar
8
+ - Al-Farāhīdī: Kitāb al-ʿAyn
9
+ - Al-Rāghib al-Iṣfahānī: Al-Mufradāt fī Gharīb al-Qurʾān
10
+ - Al-Zamakhsharī: Asās al-Balāghah
11
+ - Ibn Manẓūr: Lisān al-ʿArab
12
+ - Sībawayh: Al-Kitāb
13
+ """
14
+
15
+ import json
16
+ import re
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Dict, List, Any, Optional
20
+
21
+
22
+ @dataclass
23
+ class ClassicalAxiom:
24
+ """An authentic logical or morphological rule extracted from the classical books."""
25
+ source_author: str # e.g., 'Abū Ḥāmid al-Ghazālī'
26
+ book_title: str # e.g., 'Miʿyār al-ʿIlm'
27
+ topic_category: str # e.g., 'Dafʿ al-Dawr', 'Taṣawwur vs Taṣdīq'
28
+ arabic_passage: str # Excerpted Arabic text
29
+ epistemic_rule: str # The derived software engineering invariant
30
+
31
+
32
+ class ClassicalTextMiner:
33
+ """Mines and indexes definitions and proof rules from local Arabic classical texts."""
34
+
35
+ DEFAULT_DATA_DIR = Path("/home/absolut7/.gemini/antigravity/scratch/translation_engine_framework/data")
36
+
37
+ def __init__(self, data_dir: Optional[Path] = None):
38
+ self.data_dir = data_dir or self.DEFAULT_DATA_DIR
39
+ self.texts_dir = self.data_dir / "texts"
40
+ self.lexicons_dir = self.data_dir / "lexicons"
41
+ self.grammars_dir = self.data_dir / "grammars"
42
+
43
+ # File paths
44
+ self.miyar_file = self.texts_dir / "ghazali/miyar_al_ilm.txt"
45
+ self.mihakk_file = self.texts_dir / "ghazali/mihakk_al_nazar.txt"
46
+ self.mufradat_file = self.texts_dir / "raghib/al_mufradat_fi_gharib_al_quran.txt"
47
+ self.asas_json = self.lexicons_dir / "zamakhshari_asas/asas_balagha_dictionary.json"
48
+ self.kitab_ayn_json = self.lexicons_dir / "kitab_al_ayn/kitab_al_ayn_dictionary.json"
49
+ self.lisan_json = self.data_dir / "lisanclean.json"
50
+ self.sibawayh_json = self.grammars_dir / "sibawayh_rules.json"
51
+
52
+ self._cached_asas: Optional[Dict[str, Any]] = None
53
+ self._cached_ayn: Optional[Dict[str, Any]] = None
54
+ self._cached_lisan: Optional[Dict[str, Any]] = None
55
+ self._cached_sibawayh: Optional[Dict[str, Any]] = None
56
+
57
+ def search_mantiq_passages(self, keyword: str, max_results: int = 3) -> List[ClassicalAxiom]:
58
+ """Searches Miʿyār al-ʿIlm and Miḥakk al-Naẓar for passages matching a logical keyword."""
59
+ results: List[ClassicalAxiom] = []
60
+ files_to_scan = [
61
+ (self.miyar_file, "Abū Ḥāmid al-Ghazālī", "Miʿyār al-ʿIlm"),
62
+ (self.mihakk_file, "Abū Ḥāmid al-Ghazālī", "Miḥakk al-Naẓar")
63
+ ]
64
+
65
+ for filepath, author, book in files_to_scan:
66
+ if not filepath.exists():
67
+ continue
68
+ text = filepath.read_text(encoding="utf-8", errors="ignore")
69
+ # Split into semantic paragraphs
70
+ paragraphs = [p.strip() for p in text.split("\n\n") if len(p.strip()) > 60]
71
+
72
+ for p in paragraphs:
73
+ if keyword in p:
74
+ # Clean up paragraph
75
+ cleaned_p = re.sub(r"\s+", " ", p)
76
+ axiom = ClassicalAxiom(
77
+ source_author=author,
78
+ book_title=book,
79
+ topic_category=f"Logical Analysis: {keyword}",
80
+ arabic_passage=cleaned_p[:350] + ("..." if len(cleaned_p) > 350 else ""),
81
+ epistemic_rule=self._derive_rule_from_keyword(keyword)
82
+ )
83
+ results.append(axiom)
84
+ if len(results) >= max_results:
85
+ return results
86
+
87
+ return results
88
+
89
+ def _derive_rule_from_keyword(self, kw: str) -> str:
90
+ """Derives the software engineering constraint from the classical logical keyword."""
91
+ rules = {
92
+ "الدور": "Dafʿ al-Dawr: Mutual/circular dependency is an epistemic impossibility. Every component must be hierarchically governed.",
93
+ "التسلسل": "Dafʿ al-Tasalsul: Unbounded regress causes system failure. Every recursive, retry, or looping routine must have a strictly bounded termination proof.",
94
+ "الحد": "Al-Ḥadd al-Tāmm: Essential specification requires Genus and Specific Difference (Jins + Faṣl). Never expose unconstrained generic wrappers.",
95
+ "التناقض": "ʿAdam al-Tanāquḍ: Contradictory states cannot co-exist in true reality. Make illegal states unrepresentable in the type system.",
96
+ "التصور": "Taṣawwur precedes Taṣdīq: Indivisible domain types must be formulated before implementing runtime mutations.",
97
+ "البرهان": "Al-Burhān: Demonstrative proof required. Code must compile without warnings, with verified types and complete error coverage."
98
+ }
99
+ return rules.get(kw, "Epistemic invariant derived from classical Ghazalian logic.")
100
+
101
+ def lookup_root_definition(self, root_str: str) -> Dict[str, str]:
102
+ """
103
+ Looks up a tri-consonantal root across Kitāb al-ʿAyn, Lisān al-ʿArab, and Asās al-Balāghah.
104
+ Returns definitions and Haqiqah vs Majaz distinctions.
105
+ """
106
+ lookup_result: Dict[str, str] = {
107
+ "root": root_str,
108
+ "kitab_al_ayn": "",
109
+ "asas_balagha": "",
110
+ "lisan_al_arab": ""
111
+ }
112
+
113
+ # 1. Asās al-Balāghah (Zamakhshari)
114
+ if self._cached_asas is None and self.asas_json.exists():
115
+ try:
116
+ self._cached_asas = json.loads(self.asas_json.read_text(encoding="utf-8"))
117
+ except Exception:
118
+ self._cached_asas = {}
119
+
120
+ if self._cached_asas and root_str in self._cached_asas:
121
+ entry = self._cached_asas[root_str]
122
+ lookup_result["asas_balagha"] = str(entry)[:300]
123
+
124
+ # 2. Kitāb al-ʿAyn (Farahidi)
125
+ if self._cached_ayn is None and self.kitab_ayn_json.exists():
126
+ try:
127
+ self._cached_ayn = json.loads(self.kitab_ayn_json.read_text(encoding="utf-8"))
128
+ except Exception:
129
+ self._cached_ayn = {}
130
+
131
+ if self._cached_ayn:
132
+ # Check with and without spaces
133
+ spaced_root = " ".join(list(root_str))
134
+ if spaced_root in self._cached_ayn:
135
+ lookup_result["kitab_al_ayn"] = str(self._cached_ayn[spaced_root])[:300]
136
+ elif root_str in self._cached_ayn:
137
+ lookup_result["kitab_al_ayn"] = str(self._cached_ayn[root_str])[:300]
138
+
139
+ return lookup_result
140
+
141
+ def extract_core_mantiq_canon(self) -> List[ClassicalAxiom]:
142
+ """Pulls the primary canon of Manṭiq axioms for dataset construction."""
143
+ canon: List[ClassicalAxiom] = []
144
+ keywords = ["الحد", "الدور", "التسلسل", "التناقض", "التصور", "البرهان"]
145
+ for kw in keywords:
146
+ passages = self.search_mantiq_passages(kw, max_results=1)
147
+ canon.extend(passages)
148
+ return canon