from __future__ import annotations import ast import os import subprocess import sys import tempfile import textwrap import time from dataclasses import dataclass from pathlib import Path ALLOWED_IMPORTS = { "math", "re", "json", "typing", "collections", "itertools", "statistics", "functools", "datetime", "decimal", "fractions", "string", "enum", "dataclasses", "unittest", "solution" } BLOCKED_CALLS = { "open", "eval", "exec", "compile", "input", "globals", "locals", "vars", "getattr", "setattr", "delattr", "__import__", "breakpoint", "help", "memoryview" } MAX_CODE_CHARS = 60_000 MAX_TEST_CHARS = 30_000 @dataclass class Evaluation: passed: bool score: float syntax_ok: bool policy_ok: bool output: str elapsed_seconds: float def report(self) -> str: status = "ناجح" if self.passed else "فشل" return ( f"النتيجة: {status}\n" f"الدرجة الإرشادية: {self.score:.1f}/100\n" f"الصياغة: {'صحيحة' if self.syntax_ok else 'خطأ'} | " f"فحص السياسة: {'اجتاز' if self.policy_ok else 'مرفوض'} | " f"الاختبارات: {'اجتازت' if self.passed else 'لم تجتز'}\n" f"زمن الاختبار: {self.elapsed_seconds:.2f} ثانية\n\n{self.output[:5000]}" ) def _check_ast(code: str, *, tests: bool = False) -> tuple[bool, str]: if not code.strip(): return False, "الكود فارغ." if len(code) > (MAX_TEST_CHARS if tests else MAX_CODE_CHARS): return False, "الكود أكبر من الحد المسموح." try: tree = ast.parse(code) except SyntaxError as exc: return False, f"SyntaxError في السطر {exc.lineno}: {exc.msg}" for node in ast.walk(tree): if isinstance(node, (ast.Import, ast.ImportFrom)): names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else [node.module or ""] for name in names: if name not in ALLOWED_IMPORTS: return False, f"استيراد غير مسموح في مختبر الاختبارات: {name}" if isinstance(node, ast.ImportFrom) and node.module == "unittest": safe_unittest_names = {"TestCase", "TestSuite", "TestLoader", "TextTestRunner", "skip", "skipIf", "skipUnless", "expectedFailure"} if any(alias.name not in safe_unittest_names for alias in node.names): return False, "تم رفض استيراد فرعي غير مسموح من unittest." if isinstance(node, ast.Call): if isinstance(node.func, ast.Name) and node.func.id in BLOCKED_CALLS: return False, f"استدعاء غير مسموح في مختبر الاختبارات: {node.func.id}" if isinstance(node.func, ast.Attribute) and node.func.attr.startswith("__"): return False, "الوصول إلى خصائص Python الداخلية غير مسموح في مختبر الاختبارات." if isinstance(node, ast.Attribute) and node.attr.startswith("__"): return False, "الوصول إلى خصائص Python الداخلية غير مسموح في مختبر الاختبارات." if isinstance(node, ast.Name) and node.id in {"__builtins__", "__loader__", "__spec__", "__import__"}: return False, f"اسم غير مسموح في مختبر الاختبارات: {node.id}" return True, "فحص الصياغة والسياسة اجتاز." def _resource_limits(): """Best-effort Linux limits; this is not a security-grade sandbox.""" try: import resource resource.setrlimit(resource.RLIMIT_CPU, (4, 4)) resource.setrlimit(resource.RLIMIT_FSIZE, (2_000_000, 2_000_000)) resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 512 * 1024 * 1024)) if hasattr(resource, "RLIMIT_CORE"): resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) except Exception: pass def evaluate_python(code: str, tests: str, timeout_seconds: int = 6) -> Evaluation: """Run small, pure-Python unit tests in a restricted subprocess for the MVP. AST allow-list, scrubbed environment, isolated mode and resource limits reduce risk, but Python subprocesses are NOT a hardened sandbox. Only run code you trust. """ started = time.monotonic() if not tests.strip(): return Evaluation(False, 0, False, False, "اكتب اختبارات unittest قبل اعتماد أي تحسين.", time.monotonic() - started) code_ok, code_note = _check_ast(code, tests=False) if not code_ok: return Evaluation(False, 0, False, False, f"رفض الكود: {code_note}", time.monotonic() - started) tests_ok, tests_note = _check_ast(tests, tests=True) if not tests_ok: return Evaluation(False, 0, True, False, f"رفض الاختبارات: {tests_note}", time.monotonic() - started) with tempfile.TemporaryDirectory(prefix="amo_test_") as temp: root = Path(temp) (root / "solution.py").write_text(code, encoding="utf-8") (root / "test_solution.py").write_text(tests, encoding="utf-8") runner = textwrap.dedent(""" import sys, unittest sys.path.insert(0, '.') import test_solution suite = unittest.defaultTestLoader.loadTestsFromModule(test_solution) result = unittest.TextTestRunner(verbosity=2).run(suite) raise SystemExit(0 if result.wasSuccessful() and result.testsRun > 0 else 1) """) env = {"PATH": os.environ.get("PATH", ""), "HOME": temp, "PYTHONIOENCODING": "utf-8", "PYTHONHASHSEED": "0"} try: proc = subprocess.run( [sys.executable, "-I", "-S", "-c", runner], cwd=temp, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=max(2, min(timeout_seconds, 10)), check=False, preexec_fn=_resource_limits if os.name == "posix" else None, ) output = (proc.stdout + "\n" + proc.stderr).strip() if proc.returncode == 0: quality = _readability_score(code) score = round(80 + quality * 1.5, 1) return Evaluation(True, score, True, True, output or "اجتازت الاختبارات.", time.monotonic() - started) return Evaluation(False, round(15 + _readability_score(code) * 0.1, 1), True, True, output or f"انتهى الاختبار برمز {proc.returncode}.", time.monotonic() - started) except subprocess.TimeoutExpired: return Evaluation(False, 5, True, True, "تجاوز التنفيذ الوقت المحدد وتم إيقافه.", time.monotonic() - started) except Exception as exc: return Evaluation(False, 0, True, True, f"تعذّر تشغيل الاختبارات: {type(exc).__name__}: {exc}", time.monotonic() - started) def _readability_score(code: str) -> float: """A deliberately modest heuristic, not a measure of intelligence or correctness.""" lines = code.splitlines() score = 10.0 if not lines: return 0.0 long_lines = sum(1 for line in lines if len(line) > 110) blank = sum(1 for line in lines if not line.strip()) if len(lines) > 100: score -= min(3, (len(lines) - 100) / 100) score -= min(3.0, long_lines * 0.25) if len(lines) > 8 and blank == 0: score -= 0.8 try: tree = ast.parse(code) branches = sum(isinstance(n, (ast.If, ast.For, ast.AsyncFor, ast.While, ast.Try, ast.ExceptHandler, ast.IfExp)) for n in ast.walk(tree)) score -= min(2.0, branches * 0.12) except SyntaxError: score -= 8 return max(0.0, min(10.0, score))