quran-text-tools 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- quran_text_tools-0.1.0/LICENSE +16 -0
- quran_text_tools-0.1.0/PKG-INFO +88 -0
- quran_text_tools-0.1.0/README.md +69 -0
- quran_text_tools-0.1.0/pyproject.toml +27 -0
- quran_text_tools-0.1.0/setup.cfg +4 -0
- quran_text_tools-0.1.0/src/quran_text_tools/__init__.py +10 -0
- quran_text_tools-0.1.0/src/quran_text_tools/__main__.py +27 -0
- quran_text_tools-0.1.0/src/quran_text_tools/normalize.py +73 -0
- quran_text_tools-0.1.0/src/quran_text_tools/verses.py +340 -0
- quran_text_tools-0.1.0/src/quran_text_tools.egg-info/PKG-INFO +88 -0
- quran_text_tools-0.1.0/src/quran_text_tools.egg-info/SOURCES.txt +12 -0
- quran_text_tools-0.1.0/src/quran_text_tools.egg-info/dependency_links.txt +1 -0
- quran_text_tools-0.1.0/src/quran_text_tools.egg-info/top_level.txt +1 -0
- quran_text_tools-0.1.0/tests/test_tools.py +59 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nasser Ba Break
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
|
6
|
+
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
|
|
7
|
+
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
|
|
8
|
+
persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
|
11
|
+
Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
|
14
|
+
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
15
|
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
16
|
+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: quran-text-tools
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Match Uthmani Quran text with typed Arabic, and find and check quoted verses against the Mushaf
|
|
5
|
+
Author: Nasser Ba Break
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://quranicatlas.com
|
|
8
|
+
Project-URL: Source, https://github.com/NasserWasfiBaBreak/quran-text-tools
|
|
9
|
+
Project-URL: Issues, https://github.com/NasserWasfiBaBreak/quran-text-tools/issues
|
|
10
|
+
Keywords: quran,arabic,uthmani,nlp,text-matching
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Natural Language :: Arabic
|
|
14
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# quran-text-tools
|
|
21
|
+
|
|
22
|
+
Match the Uthmani (Mushaf) text of the Quran with ordinary typed Arabic, and find every verse quoted in a text and
|
|
23
|
+
check it word by word against the Mushaf.
|
|
24
|
+
|
|
25
|
+
From the makers of [Quranic Atlas](https://quranicatlas.com) (أطلس علاقات الكلمات القرآنية), where the same method
|
|
26
|
+
powers the verse checker (مدقق الآيات).
|
|
27
|
+
|
|
28
|
+
## Why
|
|
29
|
+
|
|
30
|
+
People type «الصلاة», «الرحمن», «يا أيها»; the Mushaf writes «ٱلصَّلَوٰةَ», «ٱلرَّحۡمَٰنِ», «يَٰٓأَيُّهَا». Plain string
|
|
31
|
+
matching fails on almost every word. Quotations in sermons, articles and posts often carry a changed word («ربي» for
|
|
32
|
+
«رب»), a missing one, or «أن» where the Mushaf has «إن». This library handles both.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install quran-text-tools
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Or the latest code: `pip install git+https://github.com/NasserWasfiBaBreak/quran-text-tools`
|
|
41
|
+
|
|
42
|
+
Python 3.9+, no dependencies.
|
|
43
|
+
|
|
44
|
+
## The Quran text
|
|
45
|
+
|
|
46
|
+
The text is **not bundled**. Use the official text of the King Fahd Complex for the Printing of the Holy Quran
|
|
47
|
+
(مجمع الملك فهد لطباعة المصحف الشريف), Hafs from ʿĀṣim, and respect its terms. Load it from a CSV with columns `surah`,
|
|
48
|
+
`ayah`, `text`, or a JSON list:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from quran_text_tools import Quran
|
|
52
|
+
quran = Quran.from_csv('quran_hafs.csv')
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Use
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from quran_text_tools import find_quotations, skeleton
|
|
59
|
+
|
|
60
|
+
skeleton('ٱلصَّلَوٰةَ') == skeleton('الصلاة') # True
|
|
61
|
+
|
|
62
|
+
for q in find_quotations('قال تعالى: ﴿وقل ربي زدني علما﴾', quran):
|
|
63
|
+
print(q.ref, q.correct) # 20:114 False
|
|
64
|
+
print(q.differences) # [{'kind': 'changed', 'written': 'ربي', 'mushaf': 'رَّبِّ'}]
|
|
65
|
+
print(q.suggestion) # وَقُل رَّبِّ زِدۡنِي عِلۡمٗا
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
From the command line:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
echo 'قال تعالى: ﴿وقل ربي زدني علما﴾' | python -m quran_text_tools quran_hafs.csv
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## What counts as a difference
|
|
75
|
+
|
|
76
|
+
- **Not a difference (spelling):** diacritics and Quranic marks; ٱ أ إ آ (= ا); ى (= ي); ة (= ه); hamza seats; the
|
|
77
|
+
small alif and و with a small alif (الرحمن / الرحمان, الصلاة); the small و/ي heard after a final pronoun (بِهِۦ);
|
|
78
|
+
«يا أيها» written as two words.
|
|
79
|
+
- **A difference:** a word changed, left out or added, and «أ» where the Mushaf has «إ» (or the reverse) at the start
|
|
80
|
+
of a word.
|
|
81
|
+
|
|
82
|
+
A quotation needs at least four matching words (three inside quotation marks), with at most one edit for every three
|
|
83
|
+
matching words. Text inside quotation marks («…» ﴿…﴾ "…") is compared as a whole, and a quotation never runs across a
|
|
84
|
+
quotation mark. When the same wording occurs in several places, `also_at` lists them.
|
|
85
|
+
|
|
86
|
+
## License
|
|
87
|
+
|
|
88
|
+
MIT. The Quran text you load is under its own terms.
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# quran-text-tools
|
|
2
|
+
|
|
3
|
+
Match the Uthmani (Mushaf) text of the Quran with ordinary typed Arabic, and find every verse quoted in a text and
|
|
4
|
+
check it word by word against the Mushaf.
|
|
5
|
+
|
|
6
|
+
From the makers of [Quranic Atlas](https://quranicatlas.com) (أطلس علاقات الكلمات القرآنية), where the same method
|
|
7
|
+
powers the verse checker (مدقق الآيات).
|
|
8
|
+
|
|
9
|
+
## Why
|
|
10
|
+
|
|
11
|
+
People type «الصلاة», «الرحمن», «يا أيها»; the Mushaf writes «ٱلصَّلَوٰةَ», «ٱلرَّحۡمَٰنِ», «يَٰٓأَيُّهَا». Plain string
|
|
12
|
+
matching fails on almost every word. Quotations in sermons, articles and posts often carry a changed word («ربي» for
|
|
13
|
+
«رب»), a missing one, or «أن» where the Mushaf has «إن». This library handles both.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install quran-text-tools
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Or the latest code: `pip install git+https://github.com/NasserWasfiBaBreak/quran-text-tools`
|
|
22
|
+
|
|
23
|
+
Python 3.9+, no dependencies.
|
|
24
|
+
|
|
25
|
+
## The Quran text
|
|
26
|
+
|
|
27
|
+
The text is **not bundled**. Use the official text of the King Fahd Complex for the Printing of the Holy Quran
|
|
28
|
+
(مجمع الملك فهد لطباعة المصحف الشريف), Hafs from ʿĀṣim, and respect its terms. Load it from a CSV with columns `surah`,
|
|
29
|
+
`ayah`, `text`, or a JSON list:
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from quran_text_tools import Quran
|
|
33
|
+
quran = Quran.from_csv('quran_hafs.csv')
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Use
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from quran_text_tools import find_quotations, skeleton
|
|
40
|
+
|
|
41
|
+
skeleton('ٱلصَّلَوٰةَ') == skeleton('الصلاة') # True
|
|
42
|
+
|
|
43
|
+
for q in find_quotations('قال تعالى: ﴿وقل ربي زدني علما﴾', quran):
|
|
44
|
+
print(q.ref, q.correct) # 20:114 False
|
|
45
|
+
print(q.differences) # [{'kind': 'changed', 'written': 'ربي', 'mushaf': 'رَّبِّ'}]
|
|
46
|
+
print(q.suggestion) # وَقُل رَّبِّ زِدۡنِي عِلۡمٗا
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
From the command line:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
echo 'قال تعالى: ﴿وقل ربي زدني علما﴾' | python -m quran_text_tools quran_hafs.csv
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## What counts as a difference
|
|
56
|
+
|
|
57
|
+
- **Not a difference (spelling):** diacritics and Quranic marks; ٱ أ إ آ (= ا); ى (= ي); ة (= ه); hamza seats; the
|
|
58
|
+
small alif and و with a small alif (الرحمن / الرحمان, الصلاة); the small و/ي heard after a final pronoun (بِهِۦ);
|
|
59
|
+
«يا أيها» written as two words.
|
|
60
|
+
- **A difference:** a word changed, left out or added, and «أ» where the Mushaf has «إ» (or the reverse) at the start
|
|
61
|
+
of a word.
|
|
62
|
+
|
|
63
|
+
A quotation needs at least four matching words (three inside quotation marks), with at most one edit for every three
|
|
64
|
+
matching words. Text inside quotation marks («…» ﴿…﴾ "…") is compared as a whole, and a quotation never runs across a
|
|
65
|
+
quotation mark. When the same wording occurs in several places, `also_at` lists them.
|
|
66
|
+
|
|
67
|
+
## License
|
|
68
|
+
|
|
69
|
+
MIT. The Quran text you load is under its own terms.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "quran-text-tools"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Match Uthmani Quran text with typed Arabic, and find and check quoted verses against the Mushaf"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
authors = [{ name = "Nasser Ba Break" }]
|
|
13
|
+
keywords = ["quran", "arabic", "uthmani", "nlp", "text-matching"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Natural Language :: Arabic",
|
|
18
|
+
"Topic :: Text Processing :: Linguistic",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://quranicatlas.com"
|
|
23
|
+
Source = "https://github.com/NasserWasfiBaBreak/quran-text-tools"
|
|
24
|
+
Issues = "https://github.com/NasserWasfiBaBreak/quran-text-tools/issues"
|
|
25
|
+
|
|
26
|
+
[tool.setuptools.packages.find]
|
|
27
|
+
where = ["src"]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Tools for working with the text of the Quran in Uthmani (Mushaf) script.
|
|
2
|
+
|
|
3
|
+
- ``skeleton``: fold Mushaf spelling and typed Arabic to the same key, so «ٱلصَّلَوٰةَ» matches «الصلاة».
|
|
4
|
+
- ``find_quotations``: find every verse quoted in a text and check it word by word against the Mushaf.
|
|
5
|
+
"""
|
|
6
|
+
from .normalize import fold, initial_hamza, near_one, skeleton, strip_marks
|
|
7
|
+
from .verses import Quotation, Quran, diff, find_quotations
|
|
8
|
+
|
|
9
|
+
__all__ = ['fold', 'strip_marks', 'skeleton', 'initial_hamza', 'near_one', 'Quran', 'Quotation', 'find_quotations', 'diff']
|
|
10
|
+
__version__ = '0.1.0'
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""python -m quran_text_tools QURAN.csv [FILE] — check the verses quoted in FILE (or standard input)."""
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
from . import Quran, find_quotations
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def main(argv=None):
|
|
8
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
9
|
+
if not argv:
|
|
10
|
+
print(__doc__.strip()); return 2
|
|
11
|
+
src = argv[0]
|
|
12
|
+
quran = Quran.from_json(src) if src.endswith('.json') else Quran.from_csv(src)
|
|
13
|
+
text = open(argv[1], encoding='utf-8').read() if len(argv) > 1 else sys.stdin.read()
|
|
14
|
+
bad = 0
|
|
15
|
+
for q in find_quotations(text, quran):
|
|
16
|
+
mark = 'OK ' if q.correct else 'FIX'
|
|
17
|
+
print(f'{mark} {q.ref}: {q.quoted}')
|
|
18
|
+
if not q.correct:
|
|
19
|
+
bad += 1
|
|
20
|
+
for d in q.differences:
|
|
21
|
+
print(f" {d['kind']}: {d['written'] or '—'} → {d['mushaf'] or '—'}")
|
|
22
|
+
print(f' Mushaf: {q.suggestion}')
|
|
23
|
+
return 1 if bad else 0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
if __name__ == '__main__':
|
|
27
|
+
sys.exit(main())
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Fold Uthmani (Mushaf) spelling and ordinary typed Arabic to the same letters.
|
|
2
|
+
|
|
3
|
+
The Mushaf's spelling differs from what people type: diacritics and Quranic marks, the wasla alif (ٱ), the seats of
|
|
4
|
+
the hamza (أ إ آ ؤ ئ), alif maqsura (ى), ta marbuta (ة), the small alif (ٰ) that stands where modern spelling writes ا
|
|
5
|
+
or nothing (ٱلرَّحۡمَٰنِ: الرحمن / الرحمان), و with a small alif read as ا (ٱلصَّلَوٰةَ: الصلاة), and the small و and ي that
|
|
6
|
+
are only heard after a final pronoun (بِهِۦ). All of these fold away, so a word becomes its *skeleton*.
|
|
7
|
+
"""
|
|
8
|
+
import re
|
|
9
|
+
|
|
10
|
+
_SKIP = re.compile('[ً-ٟۖ-ۭـء]') # marks, tatweel, bare hamza
|
|
11
|
+
_TO = {'ٱ': 'ا', 'أ': 'ا', 'إ': 'ا', 'آ': 'ا', 'ى': 'ي', 'ة': 'ه', 'ؤ': 'و', 'ئ': 'ي', 'ٰ': '~'}
|
|
12
|
+
_MARKS = re.compile('[ً-ٰٟۖ-ۭـ]')
|
|
13
|
+
|
|
14
|
+
ARABIC_WORD = re.compile('[ء-ٰٟٱۖ-ۭـ]+')
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def fold(text: str) -> str:
|
|
18
|
+
"""Letters only: marks dropped, hamza seats and ٱ to ا, ى to ي, ة to ه; the small alif kept as «~»."""
|
|
19
|
+
out = []
|
|
20
|
+
for c in text:
|
|
21
|
+
if c != 'ٰ' and _SKIP.match(c):
|
|
22
|
+
continue
|
|
23
|
+
out.append(_TO.get(c, c))
|
|
24
|
+
return ''.join(out)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def strip_marks(text: str) -> str:
|
|
28
|
+
"""The text without diacritics and Quranic marks (letters unchanged)."""
|
|
29
|
+
return _MARKS.sub('', text)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def skeleton(word: str) -> str:
|
|
33
|
+
"""A spelling-free key for one word: equal skeletons mean the same written word, however it is spelled.
|
|
34
|
+
|
|
35
|
+
>>> skeleton('ٱلصَّلَوٰةَ') == skeleton('الصلاة')
|
|
36
|
+
True
|
|
37
|
+
"""
|
|
38
|
+
w = re.sub('[ۥۦ](?=[^ء-ي]*$)', '', word) # small و/ي after a final pronoun: heard, not written
|
|
39
|
+
w = re.sub('[ۦۧ]', 'ي', w).replace('ۥ', 'و')
|
|
40
|
+
s = fold(w).replace('و~', '')
|
|
41
|
+
s = re.sub('[ا~]', '', s)
|
|
42
|
+
s = re.sub('و+', 'و', s)
|
|
43
|
+
s = re.sub('ي+', 'ي', s)
|
|
44
|
+
return re.sub(r'\s+', '', s)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def initial_hamza(word: str) -> str:
|
|
48
|
+
"""The hamza a word starts with (after و ف ب ك ل): «أ», «إ» or ''. Skeletons fold them together; this tells them apart."""
|
|
49
|
+
m = re.match('^[وف]?[بكل]?([أإ])', _MARKS.sub('', word))
|
|
50
|
+
return m.group(1) if m else ''
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def near_one(a: str, b: str) -> bool:
|
|
54
|
+
"""True when two strings differ by at most one letter added, dropped or changed."""
|
|
55
|
+
if a == b:
|
|
56
|
+
return True
|
|
57
|
+
la, lb = len(a), len(b)
|
|
58
|
+
if abs(la - lb) > 1:
|
|
59
|
+
return False
|
|
60
|
+
i = j = d = 0
|
|
61
|
+
while i < la and j < lb:
|
|
62
|
+
if a[i] == b[j]:
|
|
63
|
+
i += 1; j += 1; continue
|
|
64
|
+
d += 1
|
|
65
|
+
if d > 1:
|
|
66
|
+
return False
|
|
67
|
+
if la > lb:
|
|
68
|
+
i += 1
|
|
69
|
+
elif lb > la:
|
|
70
|
+
j += 1
|
|
71
|
+
else:
|
|
72
|
+
i += 1; j += 1
|
|
73
|
+
return d + (la - i) + (lb - j) <= 1
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""Find the Quran quoted in any text, and check each quotation word by word against the Mushaf.
|
|
2
|
+
|
|
3
|
+
A pasted text (a sermon, an article, a post) is read word by word. Every run of words that is in the Quran is found
|
|
4
|
+
with its place, and compared with the Mushaf: a word changed, left out or added. Spelling is never a difference (see
|
|
5
|
+
``normalize.skeleton``), but «أ» written where the Mushaf has «إ» at the start of a word is.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import csv
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Iterable
|
|
14
|
+
|
|
15
|
+
from .normalize import ARABIC_WORD, initial_hamza, skeleton
|
|
16
|
+
|
|
17
|
+
QUOTE = re.compile('[«»"“”﴿﴾]') # a quotation never runs over one of these
|
|
18
|
+
STOP = re.compile(r'[.،؛:!?؟\n«»"“”﴿﴾()\[\]]') # a mark that ends a quotation
|
|
19
|
+
PAUSE_END = re.compile('[ۖ-ۜ]$') # a Quranic pause mark at the end of a word
|
|
20
|
+
MAX_WORDS = 8000
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Verse:
|
|
25
|
+
surah: int
|
|
26
|
+
ayah: int
|
|
27
|
+
text: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Quran:
|
|
31
|
+
"""The Quran as a list of verses, in Mushaf order. Load it from the official text (not bundled with this package).
|
|
32
|
+
|
|
33
|
+
Accepted sources: an iterable of (surah, ayah, text); a CSV with columns ``surah``, ``ayah``, ``text``; or a JSON
|
|
34
|
+
list of objects with those keys (or of [surah, ayah, text] lists).
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, verses: Iterable[tuple[int, int, str]]):
|
|
38
|
+
self.verses = [Verse(int(s), int(a), t) for s, a, t in verses]
|
|
39
|
+
if not self.verses:
|
|
40
|
+
raise ValueError('no verses')
|
|
41
|
+
self.words = [v.text.split() for v in self.verses]
|
|
42
|
+
self._stream = None
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def from_csv(cls, path: str) -> 'Quran':
|
|
46
|
+
with open(path, encoding='utf-8-sig', newline='') as f:
|
|
47
|
+
return cls((r['surah'], r['ayah'], r['text']) for r in csv.DictReader(f))
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_json(cls, path: str) -> 'Quran':
|
|
51
|
+
with open(path, encoding='utf-8') as f:
|
|
52
|
+
data = json.load(f)
|
|
53
|
+
return cls((r['surah'], r['ayah'], r['text']) if isinstance(r, dict) else tuple(r[:3]) for r in data)
|
|
54
|
+
|
|
55
|
+
# the whole text as one stream of skeleton words, each with its verse and its first and last word in that verse
|
|
56
|
+
def stream(self):
|
|
57
|
+
if self._stream is None:
|
|
58
|
+
raw = []
|
|
59
|
+
for v, ws in enumerate(self.words):
|
|
60
|
+
for p, x in enumerate(ws):
|
|
61
|
+
s = skeleton(x)
|
|
62
|
+
if s:
|
|
63
|
+
raw.append({'s': s, 'h': initial_hamza(x), 'v': v, 'p': p, 'e': p})
|
|
64
|
+
w = _join_ya(raw, lambda t, n: t['v'] == n['v'])
|
|
65
|
+
idx3, idx2 = {}, {}
|
|
66
|
+
for k in range(len(w) - 2):
|
|
67
|
+
idx3.setdefault(w[k]['s'] + ' ' + w[k + 1]['s'] + ' ' + w[k + 2]['s'], []).append(k)
|
|
68
|
+
for k in range(len(w) - 1):
|
|
69
|
+
idx2.setdefault(w[k]['s'] + ' ' + w[k + 1]['s'], []).append(k)
|
|
70
|
+
self._stream = (w, idx3, idx2)
|
|
71
|
+
return self._stream
|
|
72
|
+
|
|
73
|
+
def wording(self, fq: int, tq: int) -> str:
|
|
74
|
+
"""The Mushaf's own words for a run of the stream, with the verse numbers between verses."""
|
|
75
|
+
W = self.stream()[0]
|
|
76
|
+
out, v, p = [], W[fq]['v'], W[fq]['p']
|
|
77
|
+
end_v, end_p = W[tq]['v'], W[tq]['e']
|
|
78
|
+
while v < end_v or (v == end_v and p <= end_p):
|
|
79
|
+
if p >= len(self.words[v]):
|
|
80
|
+
out.append(f'({self.verses[v].ayah})')
|
|
81
|
+
v += 1; p = 0
|
|
82
|
+
continue
|
|
83
|
+
out.append(self.words[v][p])
|
|
84
|
+
p += 1
|
|
85
|
+
return ' '.join(out)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _join_ya(ts, apart):
|
|
89
|
+
"""يا and ها written apart (يا أيها، ها أنتم) are one word in the Mushaf (يَٰٓأَيُّهَا): joined on both sides."""
|
|
90
|
+
out, k = [], 0
|
|
91
|
+
while k < len(ts):
|
|
92
|
+
t = ts[k]
|
|
93
|
+
n = ts[k + 1] if k + 1 < len(ts) else None
|
|
94
|
+
if t['s'] in ('ي', 'ه') and n and apart(t, n):
|
|
95
|
+
m = dict(n); m['s'] = re.sub('ي+', 'ي', t['s'] + n['s']) # يا+أيها folds like يَٰٓأَيُّهَا
|
|
96
|
+
for key in ('a', 'p'):
|
|
97
|
+
if key in t:
|
|
98
|
+
m[key] = t[key]
|
|
99
|
+
out.append(m); k += 2
|
|
100
|
+
else:
|
|
101
|
+
out.append(t); k += 1
|
|
102
|
+
return out
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _tokens(text: str):
|
|
106
|
+
out = []
|
|
107
|
+
for m in ARABIC_WORD.finditer(text):
|
|
108
|
+
s = skeleton(m.group())
|
|
109
|
+
if s:
|
|
110
|
+
out.append({'s': s, 'h': initial_hamza(m.group()), 'a': m.start(), 'b': m.end()})
|
|
111
|
+
return _join_ya(out, lambda t, n: text[t['b']:n['a']].strip() == '')
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _marked(text: str, T):
|
|
115
|
+
"""Token ranges inside quotation marks: ﴿…﴾ «…» "…" “…”."""
|
|
116
|
+
segs, k = [], 0
|
|
117
|
+
for m in re.finditer(r'[﴿﴾]([^﴿﴾]*)[﴿﴾]|«([^»]*)»|"([^"\n]*)"|“([^”]*)”', text):
|
|
118
|
+
a, b = m.start(), m.end()
|
|
119
|
+
while k < len(T) and T[k]['b'] <= a:
|
|
120
|
+
k += 1
|
|
121
|
+
e = k
|
|
122
|
+
while e < len(T) and T[e]['b'] <= b:
|
|
123
|
+
e += 1
|
|
124
|
+
if e > k:
|
|
125
|
+
segs.append((k, e - 1))
|
|
126
|
+
return segs
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def diff(a: list[str], b: list[str]) -> list[dict]:
|
|
130
|
+
"""Word-by-word differences of two runs (longest common subsequence).
|
|
131
|
+
|
|
132
|
+
``eq`` the same word; ``sub`` a word changed; ``ins`` a word added in ``a``; ``del`` a word of ``b`` left out.
|
|
133
|
+
``i`` indexes ``a`` and ``q`` indexes ``b``.
|
|
134
|
+
"""
|
|
135
|
+
n, m = len(a), len(b)
|
|
136
|
+
L = [[0] * (m + 1) for _ in range(n + 1)]
|
|
137
|
+
for x in range(n - 1, -1, -1):
|
|
138
|
+
for y in range(m - 1, -1, -1):
|
|
139
|
+
L[x][y] = L[x + 1][y + 1] + 1 if a[x] == b[y] else max(L[x + 1][y], L[x][y + 1])
|
|
140
|
+
ops, ins, dele = [], [], []
|
|
141
|
+
|
|
142
|
+
def flush():
|
|
143
|
+
k = min(len(ins), len(dele))
|
|
144
|
+
for j in range(k):
|
|
145
|
+
ops.append({'t': 'sub', 'i': ins[j], 'q': dele[j]})
|
|
146
|
+
ops.extend({'t': 'ins', 'i': i} for i in ins[k:])
|
|
147
|
+
ops.extend({'t': 'del', 'q': q} for q in dele[k:])
|
|
148
|
+
ins.clear(); dele.clear()
|
|
149
|
+
|
|
150
|
+
x = y = 0
|
|
151
|
+
while x < n and y < m:
|
|
152
|
+
if a[x] == b[y]:
|
|
153
|
+
flush(); ops.append({'t': 'eq', 'i': x, 'q': y}); x += 1; y += 1
|
|
154
|
+
elif L[x + 1][y] >= L[x][y + 1]:
|
|
155
|
+
ins.append(x); x += 1
|
|
156
|
+
else:
|
|
157
|
+
dele.append(y); y += 1
|
|
158
|
+
ins.extend(range(x, n)); dele.extend(range(y, m))
|
|
159
|
+
flush()
|
|
160
|
+
return ops
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@dataclass
|
|
164
|
+
class Quotation:
|
|
165
|
+
"""One run of the text found in the Quran."""
|
|
166
|
+
start: int # character offsets of the quotation in the text
|
|
167
|
+
end: int
|
|
168
|
+
quoted: str # the text as written
|
|
169
|
+
surah: int # where it starts and ends in the Mushaf
|
|
170
|
+
ayah: int
|
|
171
|
+
to_surah: int
|
|
172
|
+
to_ayah: int
|
|
173
|
+
mushaf: str # the Mushaf's own wording for that place
|
|
174
|
+
correct: bool # no word changed, left out or added
|
|
175
|
+
differences: list[dict] = field(default_factory=list) # {'kind': 'changed'|'missing'|'added', 'written', 'mushaf'}
|
|
176
|
+
also_at: list[tuple[int, int]] = field(default_factory=list) # other places with the same wording
|
|
177
|
+
suggestion: str = '' # the Mushaf's wording to use instead, when not correct
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def ref(self) -> str:
|
|
181
|
+
if (self.surah, self.ayah) == (self.to_surah, self.to_ayah):
|
|
182
|
+
return f'{self.surah}:{self.ayah}'
|
|
183
|
+
if self.surah == self.to_surah:
|
|
184
|
+
return f'{self.surah}:{self.ayah}-{self.to_ayah}'
|
|
185
|
+
return f'{self.surah}:{self.ayah}-{self.to_surah}:{self.to_ayah}'
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def find_quotations(text: str, quran: Quran) -> list[Quotation]:
|
|
189
|
+
"""Every run of ``text`` that is in the Quran, compared word by word with the Mushaf, in the order of the text."""
|
|
190
|
+
W, idx3, idx2 = quran.stream()
|
|
191
|
+
T = _tokens(text)[:MAX_WORDS]
|
|
192
|
+
n = len(T)
|
|
193
|
+
|
|
194
|
+
def apart(i, j):
|
|
195
|
+
if not (0 <= i < n and 0 <= j < n):
|
|
196
|
+
return False
|
|
197
|
+
lo, hi = min(i, j), max(i, j)
|
|
198
|
+
return bool(QUOTE.search(text[T[lo]['b']:T[hi]['a']]))
|
|
199
|
+
|
|
200
|
+
def eq(i, q):
|
|
201
|
+
return 0 <= i < n and 0 <= q < len(W) and T[i]['s'] == W[q]['s']
|
|
202
|
+
|
|
203
|
+
def stop_after(k):
|
|
204
|
+
return k >= n - 1 or bool(STOP.search(text[T[k]['b']:T[k + 1]['a']]))
|
|
205
|
+
|
|
206
|
+
# 1. three words in a row found in the Mushaf (seeds), chained along the same alignment
|
|
207
|
+
chains, live = [], {}
|
|
208
|
+
for i in range(n - 2):
|
|
209
|
+
for d in [d for d, c in live.items() if i - c['li'] > 6]:
|
|
210
|
+
del live[d]
|
|
211
|
+
ps = idx3.get(T[i]['s'] + ' ' + T[i + 1]['s'] + ' ' + T[i + 2]['s'])
|
|
212
|
+
if not ps or len(ps) > 1500:
|
|
213
|
+
continue
|
|
214
|
+
for q in ps:
|
|
215
|
+
d = q - i
|
|
216
|
+
c = live.get(d)
|
|
217
|
+
x = 1
|
|
218
|
+
while x <= 3 and not c:
|
|
219
|
+
c = live.get(d - x) or live.get(d + x); x += 1
|
|
220
|
+
if c and q > c['lq'] and i > c['li'] and not apart(c['li'], i + 2):
|
|
221
|
+
if c['d'] != d:
|
|
222
|
+
live.pop(c['d'], None); c['d'] = d; live[d] = c
|
|
223
|
+
c['li'], c['lq'] = i, q
|
|
224
|
+
else:
|
|
225
|
+
c = {'fi': i, 'fq': q, 'li': i, 'lq': q, 'd': d}
|
|
226
|
+
live[d] = c; chains.append(c)
|
|
227
|
+
# inside quotation marks two words in a row are a start too
|
|
228
|
+
marked = _marked(text, T)
|
|
229
|
+
for s, e in marked:
|
|
230
|
+
for i in range(s, e):
|
|
231
|
+
ps = idx2.get(T[i]['s'] + ' ' + T[i + 1]['s'])
|
|
232
|
+
if ps and len(ps) <= 300:
|
|
233
|
+
chains.extend({'fi': i, 'fq': q, 'li': i - 1, 'lq': q - 1} for q in ps)
|
|
234
|
+
|
|
235
|
+
# 2. each chain grown at both ends, over at most two changed, missing or added words
|
|
236
|
+
def grow(i, q, dr):
|
|
237
|
+
ed = 0
|
|
238
|
+
while True:
|
|
239
|
+
if apart(i, i + dr):
|
|
240
|
+
break
|
|
241
|
+
if eq(i + dr, q + dr):
|
|
242
|
+
i += dr; q += dr; continue
|
|
243
|
+
if ed >= 2:
|
|
244
|
+
break
|
|
245
|
+
if not apart(i, i + 2 * dr) and eq(i + dr, q + 2 * dr) and eq(i + 2 * dr, q + 3 * dr):
|
|
246
|
+
i += dr; q += 2 * dr; ed += 1; continue # a word left out
|
|
247
|
+
if not apart(i, i + 3 * dr) and eq(i + 2 * dr, q + dr) and eq(i + 3 * dr, q + 2 * dr):
|
|
248
|
+
i += 2 * dr; q += dr; ed += 1; continue # a word added
|
|
249
|
+
if not apart(i, i + 3 * dr) and eq(i + 2 * dr, q + 2 * dr) and eq(i + 3 * dr, q + 3 * dr):
|
|
250
|
+
i += 2 * dr; q += 2 * dr; ed += 1; continue # a word changed
|
|
251
|
+
break
|
|
252
|
+
return i, q
|
|
253
|
+
|
|
254
|
+
found = {}
|
|
255
|
+
for c in chains:
|
|
256
|
+
fi, fq = grow(c['fi'], c['fq'], -1)
|
|
257
|
+
ti, tq = grow(c['li'] + 2, c['lq'] + 2, 1)
|
|
258
|
+
sg = next(((s, e) for s, e in marked if s <= ti and e >= fi), None)
|
|
259
|
+
if sg and fi - sg[0] <= 4 and sg[1] - ti <= 4: # inside quotation marks: the whole marked text
|
|
260
|
+
if sg[0] < fi:
|
|
261
|
+
fq = max(0, fq - (fi - sg[0])); fi = sg[0]
|
|
262
|
+
if sg[1] > ti:
|
|
263
|
+
tq = min(len(W) - 1, tq + (sg[1] - ti)); ti = sg[1]
|
|
264
|
+
elif (not sg and not stop_after(ti) and stop_after(ti + 1) and tq + 1 < len(W) and W[tq + 1]['v'] == W[tq]['v']
|
|
265
|
+
and (tq + 2 >= len(W) or W[tq + 2]['v'] != W[tq]['v'])):
|
|
266
|
+
ti += 1; tq += 1 # the last word of a verse, changed, before a full stop
|
|
267
|
+
key = (fi, ti, fq)
|
|
268
|
+
if key in found:
|
|
269
|
+
continue
|
|
270
|
+
ops = diff([t['s'] for t in T[fi:ti + 1]], [w['s'] for w in W[fq:tq + 1]])
|
|
271
|
+
eq_n = sum(o['t'] == 'eq' for o in ops)
|
|
272
|
+
hz = 0
|
|
273
|
+
for o in ops: # أ against إ
|
|
274
|
+
if o['t'] == 'eq':
|
|
275
|
+
a_, b_ = T[fi + o['i']]['h'], W[fq + o['q']]['h']
|
|
276
|
+
if a_ and b_ and a_ != b_:
|
|
277
|
+
o['t'] = 'sub'; hz += 1
|
|
278
|
+
edits = sum(o['t'] != 'eq' for o in ops)
|
|
279
|
+
if eq_n < (3 if sg else 4) or (edits - hz) * 3 > eq_n + 1:
|
|
280
|
+
continue
|
|
281
|
+
found[key] = {'fi': fi, 'ti': ti, 'fq': fq, 'tq': tq, 'ops': ops, 'eq': eq_n, 'edits': edits}
|
|
282
|
+
|
|
283
|
+
# 3. the best reading of each part of the text; places as good as it are kept with it
|
|
284
|
+
R = sorted(found.values(), key=lambda r: (-r['eq'], r['edits'], r['fi'], r['ops'][0]['t'] != 'eq', r['fq']))
|
|
285
|
+
res = []
|
|
286
|
+
for r in R:
|
|
287
|
+
hit = next((o for o in res if r['fi'] <= o['ti'] and r['ti'] >= o['fi']), None)
|
|
288
|
+
if not hit:
|
|
289
|
+
r['alts'] = []; res.append(r)
|
|
290
|
+
elif (r['eq'] == hit['eq'] and r['edits'] == hit['edits'] and abs(r['fi'] - hit['fi']) <= 1
|
|
291
|
+
and abs(r['ti'] - hit['ti']) <= 1 and W[hit['fq']]['v'] != W[r['fq']]['v']
|
|
292
|
+
and not any(W[x['fq']]['v'] == W[r['fq']]['v'] for x in hit['alts'])):
|
|
293
|
+
hit['alts'].append(r)
|
|
294
|
+
res.sort(key=lambda r: r['fi'])
|
|
295
|
+
return [_quotation(r, text, T, W, quran) for r in res]
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _right(r, W, quran):
|
|
299
|
+
"""The Mushaf's wording to suggest: its place, less an edge word that a pause mark sets apart from the rest."""
|
|
300
|
+
def ends(q):
|
|
301
|
+
w = W[q]
|
|
302
|
+
return bool(PAUSE_END.search(' '.join(quran.words[w['v']][w['p']:w['e'] + 1])))
|
|
303
|
+
a, b = r['fq'], r['tq']
|
|
304
|
+
for o in r['ops']:
|
|
305
|
+
if o['t'] == 'eq':
|
|
306
|
+
break
|
|
307
|
+
if o.get('q') is not None and ends(r['fq'] + o['q']):
|
|
308
|
+
a = r['fq'] + o['q'] + 1
|
|
309
|
+
else:
|
|
310
|
+
break
|
|
311
|
+
for o in reversed(r['ops']):
|
|
312
|
+
if o['t'] == 'eq':
|
|
313
|
+
break
|
|
314
|
+
if o.get('q') is not None and o['q'] > 0 and ends(r['fq'] + o['q'] - 1):
|
|
315
|
+
b = r['fq'] + o['q'] - 1
|
|
316
|
+
else:
|
|
317
|
+
break
|
|
318
|
+
return a, b
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _quotation(r, text, T, W, quran) -> Quotation:
|
|
322
|
+
def where(q):
|
|
323
|
+
v = quran.verses[W[q]['v']]
|
|
324
|
+
return v.surah, v.ayah
|
|
325
|
+
s1, a1 = where(r['fq'])
|
|
326
|
+
s2, a2 = where(r['tq'])
|
|
327
|
+
kinds = {'sub': 'changed', 'del': 'missing', 'ins': 'added'}
|
|
328
|
+
diffs = []
|
|
329
|
+
for o in r['ops']:
|
|
330
|
+
if o['t'] == 'eq':
|
|
331
|
+
continue
|
|
332
|
+
written = text[T[r['fi'] + o['i']]['a']:T[r['fi'] + o['i']]['b']] if 'i' in o else ''
|
|
333
|
+
mushaf = quran.wording(r['fq'] + o['q'], r['fq'] + o['q']) if 'q' in o else ''
|
|
334
|
+
diffs.append({'kind': kinds[o['t']], 'written': written, 'mushaf': mushaf})
|
|
335
|
+
correct = r['edits'] == 0
|
|
336
|
+
return Quotation(
|
|
337
|
+
start=T[r['fi']]['a'], end=T[r['ti']]['b'], quoted=text[T[r['fi']]['a']:T[r['ti']]['b']],
|
|
338
|
+
surah=s1, ayah=a1, to_surah=s2, to_ayah=a2, mushaf=quran.wording(r['fq'], r['tq']), correct=correct,
|
|
339
|
+
differences=diffs, also_at=[where(x['fq']) for x in r['alts']],
|
|
340
|
+
suggestion='' if correct else quran.wording(*_right(r, W, quran)))
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: quran-text-tools
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Match Uthmani Quran text with typed Arabic, and find and check quoted verses against the Mushaf
|
|
5
|
+
Author: Nasser Ba Break
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://quranicatlas.com
|
|
8
|
+
Project-URL: Source, https://github.com/NasserWasfiBaBreak/quran-text-tools
|
|
9
|
+
Project-URL: Issues, https://github.com/NasserWasfiBaBreak/quran-text-tools/issues
|
|
10
|
+
Keywords: quran,arabic,uthmani,nlp,text-matching
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Natural Language :: Arabic
|
|
14
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# quran-text-tools
|
|
21
|
+
|
|
22
|
+
Match the Uthmani (Mushaf) text of the Quran with ordinary typed Arabic, and find every verse quoted in a text and
|
|
23
|
+
check it word by word against the Mushaf.
|
|
24
|
+
|
|
25
|
+
From the makers of [Quranic Atlas](https://quranicatlas.com) (أطلس علاقات الكلمات القرآنية), where the same method
|
|
26
|
+
powers the verse checker (مدقق الآيات).
|
|
27
|
+
|
|
28
|
+
## Why
|
|
29
|
+
|
|
30
|
+
People type «الصلاة», «الرحمن», «يا أيها»; the Mushaf writes «ٱلصَّلَوٰةَ», «ٱلرَّحۡمَٰنِ», «يَٰٓأَيُّهَا». Plain string
|
|
31
|
+
matching fails on almost every word. Quotations in sermons, articles and posts often carry a changed word («ربي» for
|
|
32
|
+
«رب»), a missing one, or «أن» where the Mushaf has «إن». This library handles both.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install quran-text-tools
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Or the latest code: `pip install git+https://github.com/NasserWasfiBaBreak/quran-text-tools`
|
|
41
|
+
|
|
42
|
+
Python 3.9+, no dependencies.
|
|
43
|
+
|
|
44
|
+
## The Quran text
|
|
45
|
+
|
|
46
|
+
The text is **not bundled**. Use the official text of the King Fahd Complex for the Printing of the Holy Quran
|
|
47
|
+
(مجمع الملك فهد لطباعة المصحف الشريف), Hafs from ʿĀṣim, and respect its terms. Load it from a CSV with columns `surah`,
|
|
48
|
+
`ayah`, `text`, or a JSON list:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from quran_text_tools import Quran
|
|
52
|
+
quran = Quran.from_csv('quran_hafs.csv')
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Use
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from quran_text_tools import find_quotations, skeleton
|
|
59
|
+
|
|
60
|
+
skeleton('ٱلصَّلَوٰةَ') == skeleton('الصلاة') # True
|
|
61
|
+
|
|
62
|
+
for q in find_quotations('قال تعالى: ﴿وقل ربي زدني علما﴾', quran):
|
|
63
|
+
print(q.ref, q.correct) # 20:114 False
|
|
64
|
+
print(q.differences) # [{'kind': 'changed', 'written': 'ربي', 'mushaf': 'رَّبِّ'}]
|
|
65
|
+
print(q.suggestion) # وَقُل رَّبِّ زِدۡنِي عِلۡمٗا
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
From the command line:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
echo 'قال تعالى: ﴿وقل ربي زدني علما﴾' | python -m quran_text_tools quran_hafs.csv
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## What counts as a difference
|
|
75
|
+
|
|
76
|
+
- **Not a difference (spelling):** diacritics and Quranic marks; ٱ أ إ آ (= ا); ى (= ي); ة (= ه); hamza seats; the
|
|
77
|
+
small alif and و with a small alif (الرحمن / الرحمان, الصلاة); the small و/ي heard after a final pronoun (بِهِۦ);
|
|
78
|
+
«يا أيها» written as two words.
|
|
79
|
+
- **A difference:** a word changed, left out or added, and «أ» where the Mushaf has «إ» (or the reverse) at the start
|
|
80
|
+
of a word.
|
|
81
|
+
|
|
82
|
+
A quotation needs at least four matching words (three inside quotation marks), with at most one edit for every three
|
|
83
|
+
matching words. Text inside quotation marks («…» ﴿…﴾ "…") is compared as a whole, and a quotation never runs across a
|
|
84
|
+
quotation mark. When the same wording occurs in several places, `also_at` lists them.
|
|
85
|
+
|
|
86
|
+
## License
|
|
87
|
+
|
|
88
|
+
MIT. The Quran text you load is under its own terms.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/quran_text_tools/__init__.py
|
|
5
|
+
src/quran_text_tools/__main__.py
|
|
6
|
+
src/quran_text_tools/normalize.py
|
|
7
|
+
src/quran_text_tools/verses.py
|
|
8
|
+
src/quran_text_tools.egg-info/PKG-INFO
|
|
9
|
+
src/quran_text_tools.egg-info/SOURCES.txt
|
|
10
|
+
src/quran_text_tools.egg-info/dependency_links.txt
|
|
11
|
+
src/quran_text_tools.egg-info/top_level.txt
|
|
12
|
+
tests/test_tools.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
quran_text_tools
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from quran_text_tools import Quran, find_quotations, near_one, skeleton
|
|
6
|
+
|
|
7
|
+
HERE = os.path.dirname(__file__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.fixture(scope='module')
|
|
11
|
+
def quran():
|
|
12
|
+
return Quran.from_csv(os.path.join(HERE, 'fixture.csv'))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pytest.mark.parametrize('mushaf, typed', [
|
|
16
|
+
('ٱلصَّلَوٰةَ', 'الصلاة'), ('ٱلرَّحۡمَٰنِ', 'الرحمن'), ('ٱلرَّحۡمَٰنِ', 'الرحمان'),
|
|
17
|
+
('بِهِۦ', 'به'), ('إِنَّهُۥ', 'انه'), ('ٱلصَّٰبِرِينَ', 'الصابرين'),
|
|
18
|
+
])
|
|
19
|
+
def test_skeleton_folds_spelling(mushaf, typed):
|
|
20
|
+
assert skeleton(mushaf) == skeleton(typed)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_skeleton_keeps_different_words_apart():
|
|
24
|
+
assert skeleton('صبر') != skeleton('صبروا')
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_near_one():
|
|
28
|
+
assert near_one('كتاب', 'كتب') and not near_one('كتاب', 'قلم')
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_correct_quotation(quran):
|
|
32
|
+
(q,) = find_quotations('قال تعالى: ﴿وقل رب زدني علما﴾ صدق الله', quran)
|
|
33
|
+
assert (q.surah, q.ayah) == (20, 114) and q.correct
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_changed_word_is_found_and_corrected(quran):
|
|
37
|
+
(q,) = find_quotations('قال تعالى: «وقل ربي زدني علما»', quran)
|
|
38
|
+
assert not q.correct and q.ref == '20:114'
|
|
39
|
+
assert [d['kind'] for d in q.differences] == ['changed']
|
|
40
|
+
assert skeleton(q.differences[0]['mushaf']) == skeleton('رب')
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_hamza_is_a_difference(quran):
|
|
44
|
+
(q,) = find_quotations('واعلموا «أن الله مع الصابرين»', quran)
|
|
45
|
+
assert not q.correct and any(d['kind'] == 'changed' for d in q.differences)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_two_quotations_are_kept_apart(quran):
|
|
49
|
+
qs = find_quotations('«بسم الله الرحمن الرحيم» و«الحمد لله رب العالمين»', quran)
|
|
50
|
+
assert [q.ref for q in qs] == ['1:1', '1:2'] and all(q.correct for q in qs)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_ya_written_apart(quran):
|
|
54
|
+
(q,) = find_quotations('يا أيها الذين آمنوا استعينوا بالصبر والصلاة إن الله مع الصابرين', quran)
|
|
55
|
+
assert q.ref == '2:153' and q.correct and q.quoted.startswith('يا أيها')
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_plain_text_finds_nothing(quran):
|
|
59
|
+
assert find_quotations('هذا نص عادي لا آيات فيه', quran) == []
|