""" Flask backend server for Arabic text summarization. Provides API endpoints for the Bayan web application. """ import os import logging import time from flask import Flask, request, jsonify, Response from flask_cors import CORS from pathlib import Path import traceback import difflib import re # Quran search import sys _quran_root = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, _quran_root) try: from quran import search_bayan logger_quran_ok = True except Exception as _quran_err: logger_quran_ok = False import logging as _ql _ql.getLogger('app').warning(f'[QURAN] Failed to import quran module: {_quran_err}') _ql.getLogger('app').warning(f'[QURAN] Searched path: {_quran_root}') _ql.getLogger('app').warning(f'[QURAN] Files in root: {os.listdir(_quran_root) if os.path.isdir(_quran_root) else "DIR NOT FOUND"}') # Pipeline hardening modules from nlp.pipeline_context import PipelineContext from nlp.punctuation.punctuation_rules import validate_punctuation_diff # Load .env file from project root (one level up from src/) try: from dotenv import load_dotenv _env_path = Path(__file__).parent.parent / '.env' load_dotenv(dotenv_path=_env_path) except ImportError: pass # python-dotenv not installed; rely on environment variables directly SUPABASE_URL = os.environ.get('SUPABASE_URL', '') SUPABASE_ANON_KEY = os.environ.get('SUPABASE_ANON_KEY', '') from model_loader import ( SummarizationModel, SpellingModel, AutocompleteModel, GrammarModel, PunctuationModel, SUMMARIZATION_PATH, SPELLING_PATH, AUTOCOMPLETE_PATH, GRAMMAR_PATH, PUNCTUATION_PATH ) # HuggingFace Inference API — used in production to avoid RAM limits from hf_inference import ( hf_summarize, hf_correct_spelling, hf_add_punctuation, hf_autocomplete, check_hf_api_available, ) HUGGINGFACE_SUMMARIZATION_REPO = os.environ.get( "SUMMARIZATION_REPO_ID", "bayan10/summarization-model", ) # When HF_API_TOKEN is set, use remote HF Inference API instead of local models. # This avoids loading 500MB+ models into RAM on the free tier. HF_API_TOKEN = os.environ.get('HF_API_TOKEN', '') USE_HF_API = bool(HF_API_TOKEN) # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) # Initialize Flask app app = Flask(__name__, static_folder='.', static_url_path='') CORS(app, resources={r"/api/*": {"origins": "*"}}) # CORS for API routes only # Configuration MAX_TEXT_LENGTH = 5000 # Maximum characters for input text MAX_SUMMARY_LENGTH = 512 # Maximum tokens for summary MIN_TEXT_LENGTH = 10 # Minimum characters for summarization # Global model instances summarization_model = None spelling_model = None autocomplete_model = None grammar_model = None punctuation_model = None # ── Directional Blocks: prevent meaning-changing substitutions ── # Used by both spelling confidence filter and grammar diff filter. _DIRECTIONAL_BLOCKS = { # Demonstratives: هذه (correct feminine) → هذة (misspelling) = ALWAYS wrong 'هذه': {'هذة'}, 'هذا': {'هذة', 'هذه'}, # masculine → don't flip to feminine forms # Verb/particle confusion: كان (was) ↔ كأن (as if) = ALWAYS wrong 'كان': {'كأن'}, 'كأن': {'كان'}, 'كانت': {'كأنت'}, # H016: كانت → كأنت = ALWAYS wrong 'كانوا': {'كأنوا'}, # also block plural form # Preposition confusion: different meanings, both valid 'إلى': {'على', 'علي'}, 'على': {'إلى', 'علي'}, 'علي': {'على'}, # proper name vs preposition # Conjunction: لكن (correct) ↔ لاكن (misspelling of لكن, never valid) 'لكن': {'لاكن'}, # correct → misspelling = ALWAYS wrong # Demonstrative: ذلك (correct) ↔ ذالك (common misspelling) 'ذلك': {'ذالك'}, # correct → misspelling = ALWAYS wrong # Pronoun suffix: ه→ة corruption (G037: عمله→عملة) 'عمله': {'عملة'}, # عمله (his work) → عملة (currency) = WRONG 'لسانه': {'لسانة'}, # his tongue 'بيته': {'بيتة'}, # his house 'كتابه': {'كتابة'}, # his book → writing } def load_models(): """Load models. In HF API mode, load summarization locally; other models gracefully degrade.""" global summarization_model, spelling_model, autocomplete_model, grammar_model, punctuation_model if USE_HF_API: logger.info("HF_API_TOKEN is set — HF API mode enabled") logger.info("NOTE: HF Spaces free tier has NO outbound DNS. Loading summarization model locally.") logger.info("Spelling, punctuation, autocomplete will gracefully degrade (return input unchanged).") # Fall through to load summarization model locally loaded = [] failed = [] # Store startup errors for diagnostics global _startup_errors _startup_errors = [] # Load only the Summarization model locally. try: logger.info(f"Loading summarization model from Hugging Face: {HUGGINGFACE_SUMMARIZATION_REPO}") try: summarization_model = SummarizationModel(HUGGINGFACE_SUMMARIZATION_REPO) except Exception as remote_error: logger.warning(f"Remote load failed, falling back to local model: {remote_error}") _startup_errors.append(f"remote_load: {str(remote_error)[:200]}") logger.info(f"Loading summarization model from local path: {SUMMARIZATION_PATH}") summarization_model = SummarizationModel(SUMMARIZATION_PATH) loaded.append("summarization") logger.info("Summarization model loaded successfully") except Exception as e: import traceback err_detail = traceback.format_exc() failed.append(("summarization", str(e))) _startup_errors.append(f"summarization_load_failed: {err_detail[-500:]}") logger.error(f"Failed to load summarization model: {str(e)}") logger.info(f"Models loaded: {loaded}") if failed: logger.warning(f"Models failed to load: {[f[0] for f in failed]}") return len(loaded) > 0 _startup_errors = [] @app.route('/') def index(): """Serve the main HTML file with Supabase credentials injected.""" html_path = Path(__file__).parent / 'index.html' html = html_path.read_text(encoding='utf-8') # Inject Supabase credentials into the meta tags html = html.replace( '', f'' ) html = html.replace( '', f'' ) return Response(html, mimetype='text/html') @app.route('/api/health', methods=['GET']) def health_check(): """Health check endpoint for production monitoring.""" if USE_HF_API: health = { 'status': 'healthy', 'mode': 'hf_spaces_local', 'models': { 'summarization': summarization_model is not None, 'spelling': _spelling_available(), 'autocomplete': _autocomplete_available(), 'grammar': _grammar_available(), 'punctuation': _punctuation_available(), 'dialect': _dialect_available() }, 'note': 'Free tier: summarization local, other models return input unchanged', 'supabase': { 'configured': bool(SUPABASE_URL and SUPABASE_ANON_KEY), }, 'environment': 'huggingface_spaces', } status_code = 200 if summarization_model is not None else 503 return jsonify(health), status_code health = { 'status': 'healthy', 'mode': 'local_models', 'models': { 'summarization': summarization_model is not None, 'spelling': spelling_model is not None, 'autocomplete': autocomplete_model is not None, 'grammar': grammar_model is not None, 'punctuation': punctuation_model is not None, 'dialect': _dialect_available() }, 'supabase': { 'configured': bool(SUPABASE_URL and SUPABASE_ANON_KEY), }, 'environment': 'render' if os.environ.get('RENDER') else 'local', } status_code = 200 if health['models']['summarization'] else 503 return jsonify(health), status_code @app.route('/api/debug-models', methods=['GET']) def debug_models(): """Debug endpoint: report model status and startup errors.""" from hf_inference import debug_test_all_models results = debug_test_all_models() # Memory info import os try: import resource mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss mem_info = f"{mem} KB" except Exception: mem_info = "N/A" # /proc/meminfo on Linux proc_mem = {} try: with open('/proc/meminfo', 'r') as f: for line in f: if any(k in line for k in ['MemTotal', 'MemFree', 'MemAvailable', 'SwapTotal']): parts = line.split() proc_mem[parts[0].rstrip(':')] = parts[1] + ' ' + (parts[2] if len(parts) > 2 else '') except Exception: proc_mem = {"error": "cannot read /proc/meminfo"} return jsonify({ 'status': 'debug', 'hf_api_token_set': bool(HF_API_TOKEN), 'summarization_model_loaded': summarization_model is not None, 'startup_errors': _startup_errors, 'memory': mem_info, 'proc_meminfo': proc_mem, 'models': results, }), 200 def _spelling_available(): """Check if spelling model is loaded (without triggering lazy load).""" try: from nlp.spelling.araspell_service import is_loaded return is_loaded() except Exception: return False def _grammar_available(): """Check if grammar model is loaded (without triggering lazy load).""" try: from nlp.grammar.grammar_service import is_loaded return is_loaded() except Exception: return False def _punctuation_available(): """Check if punctuation model is loaded (without triggering lazy load).""" try: from nlp.punctuation.punctuation_service import is_loaded return is_loaded() except Exception: return False def _autocomplete_available(): """Check if autocomplete model is loaded (without triggering lazy load).""" try: from nlp.autocomplete.autocomplete_service import _instance return _instance is not None and _instance.is_ready() except Exception: return False def _dialect_available(): """Check if dialect model is loaded (without triggering lazy load).""" try: from nlp.dialect.dialect_service import is_loaded return is_loaded() except Exception: return False @app.route('/api/spelling', methods=['POST']) def spelling_correction(): """ Correct spelling in Arabic text. Request JSON: { "text": "Arabic text with spelling errors" } Response JSON: { "original_text": "...", "corrected_text": "...", "status": "success" } """ try: if not request.is_json: return jsonify({'error': 'Request must be JSON', 'status': 'error'}), 400 data = request.get_json() text = data.get('text', '').strip() if not text: return jsonify({'error': 'Text is required', 'status': 'error'}), 400 if len(text) > MAX_TEXT_LENGTH: return jsonify({ 'error': f'Text too long. Maximum {MAX_TEXT_LENGTH} characters.', 'status': 'error' }), 400 logger.info(f"Spelling correction request: text_length={len(text)}") from nlp.spelling.araspell_service import get_spelling_model checker = get_spelling_model() corrected = checker.correct(text) return jsonify({ 'original_text': text, 'corrected_text': corrected, 'status': 'success' }), 200 except RuntimeError as e: logger.error(f"Spelling model error: {e}") return jsonify({ 'error': f'Spelling model unavailable: {str(e)[:200]}', 'status': 'error' }), 503 except Exception as e: logger.error(f"Spelling correction error: {e}") return jsonify({ 'error': f'Spelling correction failed: {str(e)[:200]}', 'status': 'error' }), 500 @app.route('/api/summarize', methods=['POST']) def summarize(): """ Summarize Arabic text. Expected JSON payload: { "text": "Arabic text to summarize", "length": 1-3 (1=short, 2=medium, 3=long), "full_text": true/false (whether to summarize full text or just first paragraph) } """ if summarization_model is None: return jsonify({ 'error': 'Summarization model not loaded. Please check server logs.', 'status': 'error' }), 503 try: # Validate request if not request.is_json: return jsonify({ 'error': 'Request must be JSON', 'status': 'error' }), 400 data = request.get_json() # Validate input text text = data.get('text', '').strip() if not text: return jsonify({ 'error': 'Text is required', 'status': 'error' }), 400 if len(text) < MIN_TEXT_LENGTH: return jsonify({ 'error': f'Text must be at least {MIN_TEXT_LENGTH} characters', 'status': 'error' }), 400 if len(text) > MAX_TEXT_LENGTH: return jsonify({ 'error': f'Text must be at most {MAX_TEXT_LENGTH} characters', 'status': 'error' }), 400 # Get parameters length = int(data.get('length', 2)) # Default to medium length = max(1, min(3, length)) # Clamp between 1 and 3 full_text = data.get('full_text', True) # Calculate max_length based on length parameter # Short: ~30% of input, Medium: ~50%, Long: ~70% input_length = len(text.split()) length_multipliers = {1: 0.3, 2: 0.5, 3: 0.7} max_length = max(20, int(input_length * length_multipliers[length])) max_length = min(max_length, MAX_SUMMARY_LENGTH) # Generate summary logger.info(f"Generating summary: length={length}, max_length={max_length}, text_length={len(text)}") # Always use local model (HF Spaces free tier has no outbound DNS for API calls) summary = summarization_model.summarize(text, max_length=max_length, min_length=max(10, max_length // 3)) return jsonify({ 'summary': summary, 'status': 'success', 'original_length': len(text), 'summary_length': len(summary) }) except ValueError as e: logger.error(f"Validation error: {str(e)}") return jsonify({ 'error': f'Invalid input: {str(e)}', 'status': 'error' }), 400 except Exception as e: logger.error(f"Error during summarization: {str(e)}") logger.error(traceback.format_exc()) return jsonify({ 'error': 'An error occurred during summarization. Please try again.', 'status': 'error', 'details': str(e) if app.debug else None }), 500 @app.route('/api/autocomplete', methods=['POST']) def autocomplete(): """ Get autocomplete suggestions for Arabic text. COMPLETELY INDEPENDENT — has zero interaction with /api/analyze. Request JSON: { "context": "", "n": 5 (optional) } Response JSON: { "status": "success", "suggestions": ["word1", "word2", ...] } """ try: if not request.is_json: return jsonify({'error': 'Request must be JSON', 'status': 'error'}), 400 data = request.get_json() context = data.get('context', '').strip() n = int(data.get('n', 3)) if not context or len(context) < 3: return jsonify({'suggestions': [], 'status': 'success'}) # Extract last ~200 chars (trimmed to word boundary) from nlp.autocomplete.autocomplete_rules import extract_context context = extract_context(context, max_chars=200) # Lazy-load the model on first request from nlp.autocomplete.autocomplete_service import get_autocomplete_model ac_model = get_autocomplete_model() if not ac_model.is_ready(): return jsonify({'suggestions': [], 'status': 'success'}) t0 = time.time() suggestions = ac_model.predict(context, n=n) elapsed = int((time.time() - t0) * 1000) logger.info(f"[AUTOCOMPLETE] {elapsed}ms | mode={ac_model.get_mode()} | context='{context[:80]}' | suggestions={suggestions}") return jsonify({ 'suggestions': suggestions, 'status': 'success' }) except Exception as e: logger.error(f"Error during autocomplete: {str(e)}") logger.error(traceback.format_exc()) return jsonify({ 'suggestions': [], 'status': 'success' # Graceful degradation — never fail the UI }) @app.route('/api/grammar', methods=['POST']) def grammar_correction(): """ Correct grammar in Arabic text. Request JSON: { "text": "Arabic text with grammar errors" } Response JSON: { "original_text": "...", "corrected_text": "...", "status": "success" } """ try: if not request.is_json: return jsonify({'error': 'Request must be JSON', 'status': 'error'}), 400 data = request.get_json() text = data.get('text', '').strip() if not text: return jsonify({'error': 'Text is required', 'status': 'error'}), 400 if len(text) > MAX_TEXT_LENGTH: return jsonify({ 'error': f'Text too long. Maximum {MAX_TEXT_LENGTH} characters.', 'status': 'error' }), 400 logger.info(f"Grammar correction request: text_length={len(text)}") from nlp.grammar.grammar_service import get_grammar_model checker = get_grammar_model() corrected = checker.correct(text) return jsonify({ 'original_text': text, 'corrected_text': corrected, 'status': 'success' }), 200 except RuntimeError as e: logger.error(f"Grammar model error: {e}") return jsonify({ 'error': f'Grammar model unavailable: {str(e)[:200]}', 'status': 'error' }), 503 except Exception as e: logger.error(f"Error during grammar correction: {str(e)}") logger.error(traceback.format_exc()) return jsonify({ 'error': 'An error occurred during grammar correction.', 'status': 'error', 'details': str(e) if app.debug else None }), 500 @app.route('/api/punctuation', methods=['POST']) def add_punctuation(): """ Add punctuation to Arabic text using PuncAra-v1. Request JSON: { "text": "Arabic text without punctuation" } Response JSON: { "status": "success", "original_text": "...", "corrected_text": "..." } """ try: if not request.is_json: return jsonify({'error': 'Request must be JSON', 'status': 'error'}), 400 data = request.get_json() text = data.get('text', '').strip() if not text: return jsonify({'error': 'Text is required', 'status': 'error'}), 400 logger.info(f"Adding punctuation for text of length: {len(text)}") from nlp.punctuation.punctuation_service import get_punctuation_model punc_checker = get_punctuation_model() punctuated = punc_checker.correct(text) return jsonify({ 'original_text': text, 'corrected_text': punctuated, 'status': 'success' }) except RuntimeError as e: logger.error(f"Punctuation model error: {e}") return jsonify({ 'error': f'Punctuation model unavailable: {str(e)[:200]}', 'status': 'error' }), 503 except Exception as e: logger.error(f"Error during punctuation: {str(e)}") logger.error(traceback.format_exc()) return jsonify({ 'error': 'An error occurred during punctuation.', 'status': 'error', 'details': str(e) if app.debug else None }), 500 def get_word_positions(text): """ Returns a list of tuples (word, start_char_index, end_char_index) for all whitespace-separated words in the text. """ positions = [] for m in re.finditer(r'\S+', text): positions.append((m.group(), m.start(), m.end())) return positions class OffsetMapper: """ Single source of truth for coordinate transformations between two consecutive versions of CURRENT_TEXT. CONTRACT: Input: text_before (str), text_after (str) — two consecutive states of CURRENT_TEXT Stores: Internal diff operations (PRIVATE) API: reverse_map_offset(pos) → text_after pos → text_before pos forward_map_range(start, end) → text_before range → text_after range TERMINOLOGY: text_before = CURRENT_TEXT before this stage's mutation text_after = CURRENT_TEXT after this stage's mutation forward = text_before → text_after reverse = text_after → text_before RULES: All external code uses reverse_map_offset() or forward_map_range(). ._opcodes is PRIVATE — no external access. """ def __init__(self, text_before, text_after): self._text_before = text_before self._text_after = text_after self._opcodes = [] # PRIVATE — (i1, i2, j1, j2) tuples self._build() def _build(self): s = difflib.SequenceMatcher(None, self._text_before, self._text_after) for tag, i1, i2, j1, j2 in s.get_opcodes(): self._opcodes.append((i1, i2, j1, j2)) def reverse_map_offset(self, pos_in_after): """ Map a single position from text_after → text_before. (CURRENT_TEXT after mutation → CURRENT_TEXT before mutation) Used by PipelineContext.map_to_original() to walk the mapper chain in reverse, ultimately reaching ORIGINAL_TEXT coordinates. """ for i1, i2, j1, j2 in self._opcodes: if j1 <= pos_in_after <= j2: if j2 == j1: # insertion point return i1 ratio = (pos_in_after - j1) / (j2 - j1) return round(i1 + ratio * (i2 - i1)) # FIX-12: round() instead of int() truncation return len(self._text_before) def forward_map_range(self, start_in_before, end_in_before): """ Map a range from text_before → text_after. (CURRENT_TEXT before mutation → CURRENT_TEXT after mutation) Used ONLY by StageLocker.update_via_mapper() to shift locked spans after a text mutation. MONOTONICITY GUARD: If independent point mapping produces an inverted range (start > end) due to non-monotonic edits, the end is clamped to max(new_start, new_end). """ new_start = self._forward_map_pos(start_in_before) new_end = self._forward_map_pos(end_in_before) # Monotonicity guard: prevent inverted ranges new_end = max(new_start, new_end) return new_start, new_end def _forward_map_pos(self, pos): """Map a single position text_before → text_after. PRIVATE.""" for i1, i2, j1, j2 in self._opcodes: if i1 <= pos <= i2: if i2 == i1: return j1 ratio = (pos - i1) / (i2 - i1) return int(j1 + ratio * (j2 - j1)) if self._opcodes: last = self._opcodes[-1] return last[3] + (pos - last[1]) return pos def get_word_diffs(original, corrected): """ Identify differences between original and corrected text at the word level. Returns a list of suggestions with start and end character offsets. """ orig_words = get_word_positions(original) corr_words = get_word_positions(corrected) s = difflib.SequenceMatcher(None, [w[0] for w in orig_words], [w[0] for w in corr_words]) suggestions = [] for tag, i1, i2, j1, j2 in s.get_opcodes(): if tag == 'replace': if i1 < len(orig_words) and i2 - 1 < len(orig_words): start_char = orig_words[i1][1] end_char = orig_words[i2-1][2] suggestions.append({ 'start': start_char, 'end': end_char, 'original': original[start_char:end_char], 'correction': " ".join([w[0] for w in corr_words[j1:j2]]), 'type': 'generic' }) elif tag == 'delete': if i1 < len(orig_words) and i2 - 1 < len(orig_words): start_char = orig_words[i1][1] end_char = orig_words[i2-1][2] suggestions.append({ 'start': start_char, 'end': end_char, 'original': original[start_char:end_char], 'correction': '', 'type': 'generic' }) elif tag == 'insert': pos = orig_words[i1][1] if i1 < len(orig_words) else len(original) suggestions.append({ 'start': pos, 'end': pos, 'original': '', 'correction': " ".join([w[0] for w in corr_words[j1:j2]]), 'type': 'generic' }) return suggestions def _levenshtein(a, b): """Damerau-Levenshtein distance — transpositions count as 1 edit. Better for Arabic typos like اقصتاديا→اقتصاديا (swap صت→تص): Standard Levenshtein says edit=2, Damerau says edit=1. FIX-45: Upgraded from standard Levenshtein. """ m, n = len(a), len(b) if m == 0: return n if n == 0: return m # Use (m+2)x(n+2) matrix to handle transpositions safely dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): dp[i][0] = i for j in range(n + 1): dp[0][j] = j for i in range(1, m + 1): for j in range(1, n + 1): cost = 0 if a[i - 1] == b[j - 1] else 1 dp[i][j] = min( dp[i - 1][j] + 1, # deletion dp[i][j - 1] + 1, # insertion dp[i - 1][j - 1] + cost, # substitution ) # Transposition: swap adjacent characters (counts as 1 edit) if (i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]): dp[i][j] = min(dp[i][j], dp[i - 2][j - 2] + 1) return dp[m][n] def _is_small_spelling_change(orig_word, corr_word, vocab_manager=None): """ Heuristic: only accept small spelling edits and ignore aggressive changes (to avoid over-editing). CRITICAL: If both words are in-vocabulary (both are valid Arabic words), only accept known orthographic fixes (ه→ة, hamza whitelist). This prevents the model from corrupting correct words (e.g. وكان→وكأن). Returns: float: 0.0 = reject, 0.5 = dampened confidence (rare word risk), 0.9 = normal confidence. Phase 2 (BUG-034/035/036/037/E8). """ if not orig_word or not corr_word: return 0.0 if orig_word == corr_word: return 0.0 # ── FIX-39: Edit distance hallucination guard (from legacy AraSpell OutputValidator) ── # Block corrections where the edit distance is too high relative to word length. # This catches model hallucinations like والممرضات→والرضا, شجعتهم→يجعلهم, طبخ→طبي. _ed_dist = _levenshtein(orig_word, corr_word) _max_len = max(len(orig_word), len(corr_word)) if _max_len >= 3 and _ed_dist > max(2, _max_len * 0.4): logger.info( f"[SPELLING] Blocked hallucination: '{orig_word}'→'{corr_word}' " f"(edit_dist={_ed_dist}, max_allowed={max(2, int(_max_len * 0.4))})" ) return 0.0 # ── FIX-42a: Length ratio guard ── # Block corrections that shrink the word significantly (>30% shorter). # Catches: والممرضات(9)→والرضا(6), للطالبه(7)→للطالب(6), شجعتهم(6)→يجعلهم(6) # These often indicate the model hallucinated a different word. _orig_len = len(orig_word) _corr_len = len(corr_word) if _orig_len >= 5 and _corr_len < _orig_len * 0.7: logger.info( f"[SPELLING] Blocked length shrink: '{orig_word}'→'{corr_word}' " f"(len {_orig_len}→{_corr_len}, ratio={_corr_len/_orig_len:.2f})" ) return 0.0 # ── FIX-42b: First-letter change guard ── # Block corrections that change the first character (after stripping common prefixes). # Catches: افهمه→تفهمة (أ→ت), واحتاج→وتحتاج (ا→ت). # The first root letter almost never changes in a typo — it's a hallucination. if _orig_len >= 3 and _corr_len >= 3: # Strip common prefixes (ال, و, ف, ب, ل, ك) to compare root starts _PREFIXES = ('وال', 'فال', 'بال', 'كال', 'لل', 'ال', 'و', 'ف', 'ب', 'ل', 'ك') _o_root = orig_word _c_root = corr_word for _pfx in _PREFIXES: if _o_root.startswith(_pfx) and len(_o_root) > len(_pfx) + 1: _o_root = _o_root[len(_pfx):] break for _pfx in _PREFIXES: if _c_root.startswith(_pfx) and len(_c_root) > len(_pfx) + 1: _c_root = _c_root[len(_pfx):] break # If roots start with different letters AND this isn't an orthographic pair # AND roots have same length (true consonant swap, not a character addition) # Exception: الولاد→الأولاد has roots ولاد(4)→أولاد(5) — different length = allow _HAMZA_CHARS = set('أإآاء') if (_o_root and _c_root and _o_root[0] != _c_root[0] and len(_o_root) == len(_c_root) # same-length roots only and not (_o_root[0] in _HAMZA_CHARS and _c_root[0] in _HAMZA_CHARS)): logger.info( f"[SPELLING] Blocked first-letter change: '{orig_word}'→'{corr_word}' " f"(root '{_o_root[0]}'→'{_c_root[0]}')" ) return 0.0 # ── GUARD 1: Numeral protection (Phase 1, BUG-011/012/E1) ── # Reject corrections that remove/change/introduce digits. # Numeral hallucination is a complete-replacement failure mode. _DIGITS = set('0123456789٠١٢٣٤٥٦٧٨٩') if any(c in _DIGITS for c in orig_word): return 0.0 # Never "correct" text containing numerals if any(c in _DIGITS for c in corr_word): return 0.0 # Never introduce digits that weren't in original # ── GUARD 2: Directional confusable-word rules (Phase 1, BUG-004/005/E4) ── # For known function words, only allow corrections TOWARD the valid form. # This prevents meaning-changing substitutions that pass orthographic checks. # # ── B5 KNOWN LIMITATION (BUG-025/026): Shadda Duplication ── # AraSpell duplicates shadda-bearing words in ISOLATION: إنّ→إن إن, أنّ→أن أن. # In sentence context (e.g., "إنّ العلم نور"), the model handles shadda correctly. # This is an isolation-only AraSpell quirk — no pipeline filter needed. # _DIRECTIONAL_BLOCKS is defined at module level (line ~100) if corr_word in _DIRECTIONAL_BLOCKS.get(orig_word, set()): return 0.0 # Check with common prefixes stripped (و+كان→و+كأن etc.) _CLITIC_PREFIXES = ('و', 'ف', 'ب', 'ل', 'ك') for _pfx in _CLITIC_PREFIXES: if (orig_word.startswith(_pfx) and corr_word.startswith(_pfx) and len(orig_word) > len(_pfx) + 1): _orig_stem = orig_word[len(_pfx):] _corr_stem = corr_word[len(_pfx):] if _corr_stem in _DIRECTIONAL_BLOCKS.get(_orig_stem, set()): return 0.0 # ── FIX-30: Prefix-stripping protection ── # Block corrections that strip a clitic prefix from a valid compound: # وبالمستشفيات → والمستشفيات (stripped ب from وب prefix chain) # فبالتالي → وبالتالي (swapped ف→و) # These destroy the meaning of the prefix (بال = by the, و = and, ف = so/then) _COMPOUND_PREFIXES = ['وبال', 'فبال', 'وال', 'فال', 'بال', 'كال', 'ول', 'فل', 'وب', 'فب', 'وك', 'فك'] for _cpfx in _COMPOUND_PREFIXES: if orig_word.startswith(_cpfx) and len(orig_word) > len(_cpfx) + 2: if not corr_word.startswith(_cpfx): # Original has compound prefix but correction doesn't — check if # the stem is the same (meaning only the prefix was stripped) _stem = orig_word[len(_cpfx):] for _alt_pfx in _COMPOUND_PREFIXES + list(_CLITIC_PREFIXES) + ['ال', '']: if corr_word.startswith(_alt_pfx): _corr_stem2 = corr_word[len(_alt_pfx):] if _stem == _corr_stem2 or _levenshtein(_stem, _corr_stem2) <= 1: return 0.0 break # Only check the longest matching prefix # Ignore tokens that contain non-letters (numbers / punctuation) # Arabic letters range plus basic Latin letters. if re.search(r'[^ء-يآأإىa-zA-Z]', orig_word): return 0.0 if re.search(r'[^ء-يآأإىa-zA-Z]', corr_word): return 0.0 # Fix S2: Reject corrections that drop feminine marker (ه/ة) # e.g. بارده→بارد, منخفظه→منخفض — these are WORSE than no correction feminine_endings = ('ه', 'ة') if orig_word.endswith(feminine_endings) and not corr_word.endswith(feminine_endings): # Only reject if the correction is just the word minus the ending if corr_word == orig_word[:-1] or len(corr_word) < len(orig_word): return 0.0 # ── FIX-41: Block corrections that ADD trailing ا/ي to IV words ── # Model sometimes adds accusative markers: واجب→واجبا, معطف→معطفا. # If the original word is IV and the correction just appends a letter, reject. if vocab_manager and len(corr_word) == len(orig_word) + 1 and corr_word.startswith(orig_word): _appended_char = corr_word[-1] if _appended_char in ('ا', 'ي', 'و') and vocab_manager.is_iv(orig_word): logger.info( f"[SPELLING] Blocked trailing '{_appended_char}' addition: " f"'{orig_word}'→'{corr_word}' (original is IV)" ) return 0.0 # CRITICAL: If both words are valid Arabic words, only accept known fixes. # This prevents the spelling model from changing one correct word to another # (e.g. وكان→وكأن, which changes "and was" to "as if" — a meaning change). if vocab_manager: orig_iv = vocab_manager.is_iv(orig_word) corr_iv = vocab_manager.is_iv(corr_word) if orig_iv and corr_iv: # Both are valid words — only accept known orthographic fixes: # 1. ه→ة at word end (feminine marker fix) # B3 (BUG-014/015): EXCEPT when ه is a pronoun suffix (preceded by ت). # Pattern: verb+ته = "verb + him/it", NOT ta marbuta. # E.g., فتأملته (fataamaltahu) → فتأملتة is WRONG. if (orig_word.endswith('ه') and corr_word.endswith('ة') and orig_word[:-1] == corr_word[:-1]): # FIX-38: Expanded pronoun suffix guard. # ه at end can be: (a) ta marbuta (should be ة) OR (b) pronoun "him/it". # The old guard only blocked ته. But كله (كل+ه), احبه (احب+ه), # عنده (عند+ه) are ALL pronoun suffixes — the ه is NOT ta marbuta. # Strategy (from legacy AraSpell WordAligner): if the STEM (word without ه) # is itself IV, then ه is likely a pronoun suffix → block the change. # If the stem is NOT IV, ه is likely a misspelled ة → allow. stem = orig_word[:-1] if len(stem) >= 2 and vocab_manager.is_iv(stem): logger.info( f"[SPELLING] Blocked ه→ة (pronoun suffix): " f"'{orig_word}'→'{corr_word}' (stem '{stem}' is IV → ه is pronoun)" ) return 0.0 return 0.9 # 2. ة→ه at word end (less common but valid) if (orig_word.endswith('ة') and corr_word.endswith('ه') and orig_word[:-1] == corr_word[:-1]): return 0.9 # 3. Word is in the hamza whitelist (known common errors) # CRITICAL (Phase 5 fix, BUG-016/027): only accept if the correction # MATCHES the whitelist target — not any arbitrary correction. # FIX-02: This check now ALWAYS accepts whitelist matches, bypassing IV-IV guard. from nlp.spelling.araspell_rules import AraSpellPostProcessor if orig_word in AraSpellPostProcessor.HAMZA_WHITELIST: expected = AraSpellPostProcessor.HAMZA_WHITELIST[orig_word] if corr_word == expected: return 0.9 else: logger.info( f"[SPELLING] Whitelist mismatch: '{orig_word}'→'{corr_word}' " f"(expected '{expected}') — rejected" ) return 0.0 # 4. Check prefixed hamza (و+whitelist word, etc.) for prefix in AraSpellPostProcessor.HAMZA_PREFIXES: if orig_word.startswith(prefix) and len(orig_word) > len(prefix) + 1: remainder = orig_word[len(prefix):] if remainder in AraSpellPostProcessor.HAMZA_WHITELIST: expected = prefix + AraSpellPostProcessor.HAMZA_WHITELIST[remainder] if corr_word == expected: return 0.9 else: logger.info( f"[SPELLING] Prefixed whitelist mismatch: '{orig_word}'→'{corr_word}' " f"(expected '{expected}') — rejected" ) return 0.0 # 5. FIX-02: Alif maqsura fix (ي↔ى at end) — both IV but correction is valid if (orig_word.endswith('ي') and corr_word.endswith('ى') and orig_word[:-1] == corr_word[:-1]): return 0.85 if (orig_word.endswith('ى') and corr_word.endswith('ي') and orig_word[:-1] == corr_word[:-1]): return 0.85 # ── Phase 12 (A7): Vocab-aware IV-IV override ── # Allow keyboard-adjacent single edits when correction is significantly # more common. Prevents blocking genuine typos where both happen to be IV. if len(orig_word) == len(corr_word): from nlp.spelling.araspell_rules import RulesBasedCorrector edit_dist = _levenshtein(orig_word, corr_word) if edit_dist == 1: orig_rank = vocab_manager.get_frequency_rank(orig_word) corr_rank = vocab_manager.get_frequency_rank(corr_word) if corr_rank < orig_rank and corr_rank < 5000: # Check keyboard proximity for extra safety for a, b in zip(orig_word, corr_word): if a != b: if RulesBasedCorrector.is_keyboard_neighbor(a, b): logger.info( f"[SPELLING] Vocab-override (IV-IV): " f"'{orig_word}'(rank={orig_rank})→" f"'{corr_word}'(rank={corr_rank}) " f"keyboard-adjacent '{a}'→'{b}'" ) return 0.5 break # 6. FIX-49: Trailing و removal (المصنعو→المصنع) # Common model artifact — original has trailing و that should be removed if (orig_word.endswith('و') and corr_word == orig_word[:-1] and len(corr_word) >= 3): return 0.8 # 7. FIX-49b: Trailing و→وا (حضرو→حضروا) # Missing alif after waw al-jama'a if (orig_word.endswith('و') and corr_word == orig_word + 'ا' and len(orig_word) >= 3): return 0.8 # Both are valid words and change is NOT a known fix — REJECT # This prevents وكان→وكأن, etc. return 0.0 dist = _levenshtein(orig_word, corr_word) max_len = max(len(orig_word), len(corr_word)) # Tighter filter for OOV words: reject edits that change word roots # Allow max 2 edits at max 50% of word length if dist > 2 or (dist / max_len) > 0.5: return 0.0 # CRITICAL: Only allow ORTHOGRAPHIC fixes (ه↔ة, ا↔أ↔إ↔آ, ي↔ى). # Any other letter change means the word's ROOT is different # (e.g. عضلية→عملية ض→م = completely different word!) ORTHO_PAIRS = { ('ه', 'ة'), ('ة', 'ه'), ('ا', 'أ'), ('أ', 'ا'), ('ا', 'إ'), ('إ', 'ا'), ('ا', 'آ'), ('آ', 'ا'), ('ي', 'ى'), ('ى', 'ي'), ('ؤ', 'و'), ('و', 'ؤ'), # hamza on waw ('ئ', 'ي'), ('ي', 'ئ'), # hamza on ya ('ء', 'أ'), ('أ', 'ء'), # standalone hamza ↔ hamza on alef ('ء', 'ؤ'), ('ؤ', 'ء'), # standalone hamza ↔ hamza on waw ('ء', 'ئ'), ('ئ', 'ء'), # standalone hamza ↔ hamza on ya } # ── Phase 12 (A2): Phonetically confusable pairs ── # Arabic letters commonly confused due to similar pronunciation. # From AraSpell.py ContextualCorrector.CONFUSION_PAIRS. PHONETIC_PAIRS = { ('ض', 'ظ'), ('ظ', 'ض'), # emphatic d/z ('ذ', 'ز'), ('ز', 'ذ'), # z variants ('ص', 'س'), ('س', 'ص'), # s variants ('ط', 'ت'), ('ت', 'ط'), # t variants ('ق', 'ك'), ('ك', 'ق'), # k/q variants ('د', 'ض'), ('ض', 'د'), # d/emphatic-d ('غ', 'ق'), ('ق', 'غ'), # gh/q } from nlp.spelling.araspell_rules import RulesBasedCorrector # ── Phase 13: Adjacent character transposition detection ── # Transpositions (e.g., العصوبات→الصعوبات) have Levenshtein=2 but are a # single adjacent swap. Detect and accept when OOV→IV. if len(orig_word) == len(corr_word) and dist == 2: _transposition_found = False for _ti in range(len(orig_word) - 1): if (orig_word[_ti] == corr_word[_ti + 1] and orig_word[_ti + 1] == corr_word[_ti] and orig_word[:_ti] == corr_word[:_ti] and orig_word[_ti + 2:] == corr_word[_ti + 2:]): _transposition_found = True break if _transposition_found: if vocab_manager: _orig_oov = not vocab_manager.is_iv(orig_word) _corr_iv = vocab_manager.is_iv(corr_word) if _orig_oov and _corr_iv: logger.info( f"[SPELLING] Transposition accepted (OOV→IV): " f"'{orig_word}'→'{corr_word}'" ) return 0.6 # Dampened confidence for transpositions elif _orig_oov and not _corr_iv: # Both OOV — still accept transposition with lower confidence logger.info( f"[SPELLING] Transposition accepted (OOV→OOV): " f"'{orig_word}'→'{corr_word}' (low confidence)" ) return 0.5 else: return 0.6 # No vocab manager — accept with dampened confidence # ── Phase 13: Single character insertion detection ── # When the original has one extra character (user typed an extra letter), # e.g., الكتتاب→الكتاب (extra ت). Levenshtein=1, lengths differ by 1. if len(orig_word) == len(corr_word) + 1 and dist == 1: # Find where the extra character is in orig_word _insertion_valid = False for _di in range(len(orig_word)): # Try removing character at position _di from orig_word _candidate = orig_word[:_di] + orig_word[_di + 1:] if _candidate == corr_word: _insertion_valid = True break if _insertion_valid: if vocab_manager: _orig_oov = not vocab_manager.is_iv(orig_word) _corr_iv = vocab_manager.is_iv(corr_word) if _orig_oov and _corr_iv: # FIX-35: Don't strip verb conjugation suffixes. # Only block ن (feminine plural: ذهبن→ذهب) and # ت (feminine past: كتبت→كتب) — these are the # suffixes grammar commonly adds that spelling # would try to strip. Other endings (ة,ا,ي,و,ه) # are more likely genuine typos than grammar fixes. _CONJUGATION_SUFFIXES = {'ن', 'ت'} _removed_char = None for _di2 in range(len(orig_word)): if orig_word[:_di2] + orig_word[_di2 + 1:] == corr_word: _removed_char = orig_word[_di2] _removed_pos = _di2 break if (_removed_char in _CONJUGATION_SUFFIXES and _removed_pos == len(orig_word) - 1 and len(corr_word) >= 3): logger.info( f"[SPELLING] Rejected suffix strip: " f"'{orig_word}'→'{corr_word}' " f"(removing suffix '{_removed_char}' likely strips conjugation)" ) return 0.0 logger.info( f"[SPELLING] Insertion fix accepted (OOV→IV): " f"'{orig_word}'→'{corr_word}' (extra char removed)" ) return 0.7 else: return 0.6 # ── Phase 13: Single character deletion detection ── # When the original is missing one character (user missed a key), # e.g., الكتب→الكتاب (missing ا). Levenshtein=1, lengths differ by 1. if len(corr_word) == len(orig_word) + 1 and dist == 1: # Find where the missing character should be in corr_word _deletion_valid = False for _di in range(len(corr_word)): # Try removing character at position _di from corr_word _candidate = corr_word[:_di] + corr_word[_di + 1:] if _candidate == orig_word: _deletion_valid = True break if _deletion_valid: if vocab_manager: _orig_oov = not vocab_manager.is_iv(orig_word) _corr_iv = vocab_manager.is_iv(corr_word) if _orig_oov and _corr_iv: logger.info( f"[SPELLING] Deletion fix accepted (OOV→IV): " f"'{orig_word}'→'{corr_word}' (missing char added)" ) return 0.7 else: return 0.6 # Check every character pair — reject if ANY non-orthographic change if len(orig_word) != len(corr_word): # Length change = structural change, not just orthographic # Exception: if diff is just adding/removing ا at start (hamza) if abs(len(orig_word) - len(corr_word)) > 1: return 0.0 # ── FIX: Block Grammar Changes masked as Spelling Typos (Dual → Plural) ── if orig_word.endswith('ان') and corr_word.endswith('ات') and orig_word[:-2] == corr_word[:-2]: logger.info( f"[SPELLING] Blocked grammatical change (Dual→Plural): " f"'{orig_word}'→'{corr_word}'" ) return 0.0 # ── Phase 12 (A1): Keyboard-neighbor and phonetic acceptance ── # Check each differing character: ortho → full accept, keyboard/phonetic → dampened _has_keyboard_or_phonetic = False for a, b in zip(orig_word, corr_word): if a != b: if (a, b) in ORTHO_PAIRS: continue # Orthographic — fully accepted elif RulesBasedCorrector.is_keyboard_neighbor(a, b) or (a, b) in PHONETIC_PAIRS: _has_keyboard_or_phonetic = True # Mark for dampened confidence else: return 0.0 # Not ortho, not keyboard, not phonetic → reject # If we reached here, all diffs are ortho or keyboard/phonetic if _has_keyboard_or_phonetic: logger.info( f"[SPELLING] Keyboard/phonetic typo accepted: " f"'{orig_word}'→'{corr_word}' (dampened to 0.6)" ) return 0.6 # Dampened confidence for keyboard/phonetic typos # ── B3 (BUG-014/015): Pronoun suffix guard (OOV path) ── # Same guard as IV-IV path: block ه→ة when preceded by ت if (orig_word.endswith('ه') and corr_word.endswith('ة') and len(orig_word) >= 3 and orig_word[-2] == 'ت' and orig_word[:-1] == corr_word[:-1]): logger.info( f"[SPELLING] Blocked ه→ة at pronoun suffix (OOV path): " f"'{orig_word}'→'{corr_word}'" ) return 0.0 # ── Phase 2 (BUG-034/035/036/037/E8): Confidence dampening ── # If the original word might be a valid rare word (OOV in model but # potentially real Arabic), dampen confidence so users can reject easily. if vocab_manager: orig_iv = vocab_manager.is_iv(orig_word) corr_iv = vocab_manager.is_iv(corr_word) # Phase 2.2: Use frequency rank if available. # If the original word is a known word (even rare), require a # meaningfully higher confidence bar before replacing it. orig_rank = vocab_manager.get_frequency_rank(orig_word) # 999999 if unknown corr_rank = vocab_manager.get_frequency_rank(corr_word) # 999999 if unknown if orig_iv and corr_iv and orig_rank < 999999: # Original is a known ranked word — correction should be more common # If correction is rarer or similarly ranked, dampen confidence if corr_rank >= orig_rank: logger.info( f"[SPELLING] Dampened (freq): '{orig_word}'(rank={orig_rank})" f"→'{corr_word}'(rank={corr_rank}) — corr not more common" ) return 0.5 if not orig_iv and corr_iv: # OOV→IV: original might be a rare word being "corrected" to common # Dampen confidence to 0.5 (lower than normal 0.9) logger.info( f"[SPELLING] Dampened confidence: '{orig_word}'→'{corr_word}' " f"(OOV→IV, possible rare word)" ) return 0.5 # ── B2 (BUG-006/009/010/013): Hamza-removal dampening ── # Hamza changes (أ→ا, إ→ا, ء→ا, etc.) between same-length words are # ambiguous — could be a valid fix OR a corruption. Always dampen these # to 0.5 regardless of vocab_manager status. This prevents BUG-009 # (قرأ→قرا) and BUG-013 (خطأ→خطا) from leaking at full confidence. _HAMZA_CHARS = set('أإآؤئء') if len(orig_word) == len(corr_word): has_hamza_diff = False for a, b in zip(orig_word, corr_word): if a != b: if a in _HAMZA_CHARS or b in _HAMZA_CHARS: has_hamza_diff = True else: has_hamza_diff = False break # Non-hamza difference, don't apply this guard if has_hamza_diff: logger.info( f"[SPELLING] Dampened (hamza-only): '{orig_word}'→'{corr_word}'" ) return 0.5 return 0.9 def _is_spelling_only_change(original: str, correction: str) -> bool: """ Detect if a grammar model's correction is actually a spelling/orthographic fix (hamza, ه→ة, ا→أ, etc.) rather than a true grammar change. Used to re-label grammar patches as 'spelling' for correct UI icons. """ if not original or not correction: return False # Normalize: strip diacritics for comparison import re as _re strip_diacritics = lambda t: _re.sub(r'[\u064B-\u065F\u0670]', '', t) o = strip_diacritics(original) c = strip_diacritics(correction) if o == c: return True # Only diacritical difference # Check word-by-word for single-word changes o_words = o.split() c_words = c.split() if len(o_words) != len(c_words): return False # Word count changed = grammar (word split/merge) all_spelling = True for ow, cw in zip(o_words, c_words): if ow == cw: continue if _is_orthographic_variant(ow, cw): continue all_spelling = False break return all_spelling def _is_orthographic_variant(word1: str, word2: str) -> bool: """ Check if two words differ only by common Arabic orthographic variations: - Hamza placement: ا↔أ↔إ↔آ, ى↔ي, ه↔ة - These are spelling differences, not grammar. """ if len(word1) != len(word2): # Allow ه→ة at end (same length since both are 1 char) # But also allow small length diffs for hamza additions if abs(len(word1) - len(word2)) > 1: return False # Check if only difference is a trailing ة↔ه if (word1[:-1] == word2[:-1] and {word1[-1], word2[-1]} <= {'ه', 'ة'}): return True return False # Same length: check char-by-char SPELLING_EQUIVALENCES = { frozenset({'ا', 'أ'}), frozenset({'ا', 'إ'}), frozenset({'ا', 'آ'}), frozenset({'أ', 'إ'}), frozenset({'أ', 'آ'}), frozenset({'إ', 'آ'}), frozenset({'ى', 'ي'}), frozenset({'ه', 'ة'}), frozenset({'ؤ', 'و'}), frozenset({'ئ', 'ي'}), frozenset({'ئ', 'ء'}), } diff_count = 0 for c1, c2 in zip(word1, word2): if c1 == c2: continue if frozenset({c1, c2}) in SPELLING_EQUIVALENCES: diff_count += 1 else: return False # Non-orthographic difference = grammar return diff_count > 0 # At least one orthographic difference @app.route('/api/dialect', methods=['POST']) def convert_dialect(): """ Convert dialect Arabic text to Modern Standard Arabic (MSA). Request JSON: { "text": "عايز اشتكي من موظف في فرعكم" } Response JSON: { "status": "success", "original_text": "...", "converted_text": "..." } """ try: if not request.is_json: return jsonify({'error': 'Request must be JSON', 'status': 'error'}), 400 data = request.get_json() text = data.get('text', '').strip() if not text: return jsonify({'error': 'Text is required', 'status': 'error'}), 400 if len(text) > MAX_TEXT_LENGTH: return jsonify({ 'error': f'Text too long. Maximum {MAX_TEXT_LENGTH} characters.', 'status': 'error' }), 400 logger.info(f"[DIALECT] Conversion request: text_length={len(text)}") from nlp.dialect.dialect_service import get_dialect_model converter = get_dialect_model() t0 = time.time() result = converter.convert(text) elapsed = int((time.time() - t0) * 1000) logger.info(f"[DIALECT] {elapsed}ms | input='{text[:80]}' | output='{result[:80]}'") return jsonify({ 'original_text': text, 'converted_text': result, 'status': 'success' }), 200 except RuntimeError as e: logger.error(f"Dialect model error: {e}") return jsonify({ 'error': f'Dialect model unavailable: {str(e)[:200]}', 'status': 'error' }), 503 except Exception as e: logger.error(f"Error during dialect conversion: {e}") logger.error(traceback.format_exc()) return jsonify({ 'error': 'An error occurred during dialect conversion.', 'status': 'error', 'details': str(e) if app.debug else None }), 500 @app.route('/api/quran', methods=['POST']) def quran_verify(): """ Quran text verification and translation. Accepts: {text: str, language: str (optional, default='تدقيق الايات')} Returns: {matched_segment, full_verse} or {error} """ try: if not logger_quran_ok: return jsonify({'error': 'Quran search module not available'}), 503 data = request.get_json(force=True) text = data.get('text', '').strip() language = data.get('language', 'تدقيق الايات').strip() if not text: return jsonify({'error': 'النص المُدخل فارغ'}), 400 if len(text) > 2000: return jsonify({'error': 'النص طويل جداً (الحد الأقصى 2000 حرف)'}), 400 app.logger.info(f'[QURAN] Query: "{text[:60]}..." lang={language}') start_time = time.time() result = search_bayan(text, target_type=language) elapsed = int((time.time() - start_time) * 1000) app.logger.info(f'[QURAN] Done in {elapsed}ms') if 'error' in result: return jsonify(result), 404 return jsonify(result) except Exception as e: app.logger.error(f'[QURAN] Error: {e}') app.logger.error(traceback.format_exc()) return jsonify({'error': 'حدث خطأ أثناء البحث في القرآن الكريم'}), 500 @app.route('/api/analyze', methods=['POST']) def analyze_text(): """ Perform sequential analysis (Spelling -> Grammar -> Punctuation) and return word-level suggestions with offsets. """ try: if not request.is_json: return jsonify({'error': 'Request must be JSON', 'status': 'error'}), 400 data = request.get_json() text = data.get('text', '').strip() if not text: return jsonify({'error': 'Text is required', 'status': 'error'}), 400 # ── Input Sanitization (Fix 3: prevent pathological model inputs) ── # Strip HTML tags — prevents AraSpell from doing exhaustive edit-distance # on tag characters like