File size: 8,824 Bytes
51d43b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""
text_utils.py — Arabic text normalization, isnad filtering, negation detection,
Qattan evidence extraction, and relevance scoring.

Extracted from Searcher to isolate stateless text processing logic.
"""

import re


def normalize_arabic(text: str) -> str:
    """Remove diacritics, normalize alef/ya/ta-marbuta."""
    text = re.sub(r"[\u064B-\u065F\u0670]", "", text or "")
    text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا")
    text = text.replace("ى", "ي").replace("ة", "ه")
    text = re.sub(r"\s+", " ", text)
    return text.strip()


def is_isnad_only(text: str, search_term: str = "") -> bool:
    """
    Return True if text is a pure isnad chain with no critical opinion.
    Re-designed: a result is rejected ONLY if it's an isolated isnad.
    """
    if not text:
        return True

    stripped = text.strip()
    if len(stripped) < 40:
        return True

    normalized = normalize_arabic(stripped)

    # Opinion verbs → not pure isnad
    opinion_verbs = [
        "سمعت",
        "سألت",
        "سألته",
        "ذكر",
        "وذكر",
        "نعت",
        "وصف",
        "حكى",
        "روى عنه",
        "حكم",
    ]
    for verb in opinion_verbs:
        if normalize_arabic(verb) in normalized:
            return False

    # Imam names → not pure isnad
    imams = [
        "ابن معين",
        "يحيى بن معين",
        "أحمد بن حنبل",
        "أبو حاتم",
        "أبو حاتم الرازي",
        "البخاري",
        "أبو زرعة",
        "الدارقطني",
        "ابن عدي",
        "ابن حبان",
        "يعقوب بن شيبة",
        "النسائي",
        "ابن سعد",
        "العقيلي",
        "الذهبي",
        "ابن حجر",
        "شعبة",
        "سفيان الثوري",
        "مالك بن أنس",
    ]
    for imam in imams:
        if normalize_arabic(imam) in normalized:
            return False

    # Pure isnad chain patterns
    pure_isnad_patterns = [
        r"(?:حدثنا|اخبرنا|حدثني|اخبرني).*?عن.*?عن",
        r"عن.*?عن.*?عن.*?عن",
        r"(?:حدثنا|اخبرنا).*?قال\s+(?:حدثنا|اخبرنا).*?عن",
        r"اسناده?\s+(?:صحيح|حسن|ضعيف|واه)",
        r"هذا\s+(?:الاسناد|اسناد)\s+(?:صحيح|حسن|ضعيف)",
    ]
    isnad_hits = sum(1 for p in pure_isnad_patterns if re.search(p, normalized))
    if isnad_hits >= 2:
        return True

    return False


def check_negation(text: str, term: str) -> bool:
    """
    Detect if a term is negated in the text.
    Uses a 50-char window before the term to capture Arabic negation constructions.
    """
    normalized_text = normalize_arabic(text)
    normalized_term = normalize_arabic(term)

    # Special negation for مستقيم/يستقيم/استقام
    if any(x in normalized_term for x in ["مستقيم", "يستقيم", "استقام"]):
        for neg_phrase in [
            "لا يستقيم",
            "لم يستقيم",
            "ليس بمستقيم",
            "غير مستقيم",
            "لا يصح حديثه",
        ]:
            if normalize_arabic(neg_phrase) in normalized_text:
                return True

    idx = normalized_text.find(normalized_term)
    if idx == -1:
        # Try partial match on individual words
        words = [w for w in normalized_term.split() if len(w) >= 3]
        for w in words:
            idx = normalized_text.find(w)
            if idx != -1:
                break
        if idx == -1:
            return False

    # 50-char window before the term
    window_start = max(0, idx - 50)
    before_term = normalized_text[window_start:idx].strip()

    negations = [
        "ليس",
        "غير",
        "لا",
        "ما هو",
        "لم يكن",
        "ما كان",
        "ليس بقوي",
        "ليس بذاك",
        "ضعيف",
        "متروك",
        "لا يستحق",
        "لا يصح",
        "ليس ممن",
        "لا ممن",
    ]

    for neg in negations:
        norm_neg = normalize_arabic(neg)
        pattern = r"\b" + re.escape(norm_neg) + r"\b"
        if re.search(pattern, before_term):
            return True

    return False


def has_excluded_qattan(text: str, exclude_patterns: list[str]) -> bool:
    """Check if text contains excluded Qattan variants (Ibn al-Qattan al-Fasi, etc.)."""
    normalized = normalize_arabic(text)
    return any(normalize_arabic(p) in normalized for p in exclude_patterns)


def extract_qattan_evidence(
    text: str,
    exclude_patterns: list[str],
    attribution_patterns: list[str],
    strong_patterns: list[str],
) -> str:
    """
    Extract Qattan attribution evidence from text.
    Returns the matched attribution string, or empty string if none found.
    """
    if not text or has_excluded_qattan(text, exclude_patterns):
        return ""

    normalized = normalize_arabic(text)

    for pattern in attribution_patterns:
        normalized_pattern = normalize_arabic(pattern)
        match = re.search(normalized_pattern, normalized)
        if match:
            return match.group(0)

    for phrase in strong_patterns:
        normalized_phrase = normalize_arabic(phrase)
        if normalized_phrase in normalized:
            return phrase

    return ""


def compute_relevance_score(
    text: str,
    qattan_evidence: str,
    narrator: str,
    book: str,
    section_book_keywords: dict,
    strong_patterns: list[str],
) -> float:
    """
    Compute a relevance score (0-10) for a search result.
    Higher score = more likely to contain direct Qattan judgment.
    """
    score = 0.0

    # ── Qattan evidence (highest weight) ──────────────────────────
    if qattan_evidence:
        if any(
            p in qattan_evidence
            for p in ["قال يحيى", "وقال يحيى", "فقال يحيى", "يحيى بن سعيد القطان"]
        ):
            score += 4.0  # Direct quote from al-Qattan
        elif any(p in qattan_evidence for p in strong_patterns):
            score += 3.0  # Strong attribution
        else:
            score += 2.0  # Weak attribution

    # ── Narrator identified ──────────────────────────────────────
    if narrator and narrator != "أقوال عامة ونصوص متفرقة":
        score += 2.0
    else:
        score += 0.5

    # ── Book priority (core rijal books get highest weight) ────────
    # Tier 1: Direct Jarh wa Ta'dil books (highest priority)
    tier1_keywords = [
        "الجرح والتعديل",
        "الضعفاء",
        "الكامل",
        "المغني",
        "الميزان",
        "لسان الميزان",
        "الكاشف",
        "الثقات",
        "تقريب",
        "تهذيب",
        "الشجرة",
        "ديوان الضعفاء",
        "المجروحين",
        "الإصابة",
        "الاستيعاب",
        "بحر الدم",
        "مشاهير",
        "سؤالات",
    ]
    # Tier 2: Hadith sciences + comparative
    tier2_keywords = [
        "علوم الحديث",
        "الكفاية",
        "تدريب",
        "فتح المغيث",
        "الموقظة",
        "الاقتراح",
        "نزهة النظر",
        "ألفية",
        "الباعث الحثيث",
        "حلية",
        "تاريخ الإسلام",
        "سير",
        "تاريخ بغداد",
        "تاريخ دمشق",
        "الطبقات",
    ]

    if any(kw in book for kw in tier1_keywords):
        score += 2.5  # Core rijal book
    elif any(kw in book for kw in tier2_keywords):
        score += 1.5  # Supporting book
    else:
        score += 0.5  # Other books

    # ── Text length (longer = more context) ──────────────────────
    if len(text) > 1000:
        score += 1.0
    elif len(text) > 500:
        score += 0.5

    # ── Text contains term variation ──────────────────────────────
    if "قال" in text and "يحيى" in text:
        score += 0.5  # Has attribution format

    return min(score, 10.0)


def extract_context(text: str, term: str) -> str:
    """Extract a window of text around the search term for context."""
    if not text or not term:
        return ""
    idx = text.find(term)
    if idx == -1:
        return text[:300]
    start = max(0, idx - 200)
    end = min(len(text), idx + len(term) + 200)
    return text[start:end]