"""本地评测:非题库题(AI 对话中出的题,无 Hydro 测试点)→ 服务器本地编译+运行+比对。 - 有测试用例:逐用例本地运行比对(支持 stdin 与 fileio 两种模式) - 无测试用例:仅编译检查(CE),配合前端走 LLM 代码分析 安全:临时工作目录 + 超时 kill + 输出截断,不设网络。 """ from __future__ import annotations import asyncio import logging import os import shutil import uuid logger = logging.getLogger("fluent.services.local_judge") LANGS: dict[str, dict] = { "cpp": {"ext": ".cpp", "compile": ["g++", "-std=c++17", "-O2"], "run": ["./a.out"]}, "java": {"ext": ".java", "compile": ["javac"], "run": ["java", "Main"], "main_file": "Main.java"}, "python": {"ext": ".py", "compile": None, "run": ["python3"]}, } RUN_TIMEOUT = 3.0 # 单用例运行超时(秒) MAX_OUTPUT = 2000 # 输出截断字符 def _norm(s: str) -> str: return "\n".join(line.rstrip() for line in (s or "").splitlines()).strip() async def _run(cmd: list[str], cwd: str, stdin_data: str | None = None, timeout: float = RUN_TIMEOUT) -> tuple[int, str, str]: try: proc = await asyncio.create_subprocess_exec( *cmd, cwd=cwd, stdin=asyncio.subprocess.PIPE if stdin_data is not None else asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) try: out, err = await asyncio.wait_for( proc.communicate(stdin_data.encode() if stdin_data is not None else None), timeout=timeout) except asyncio.TimeoutError: try: proc.kill() except Exception: pass await proc.wait() return -9, "", "timeout" return proc.returncode or 0, out.decode(errors="replace"), err.decode(errors="replace") except FileNotFoundError: raise LocalJudgeError(f"本地评测缺少运行环境: {' '.join(cmd[:1])}") class LocalJudgeError(Exception): pass async def local_judge(lang: str, code: str, tests: list[dict] | None = None, file_in: str | None = None, file_out: str | None = None) -> dict: """本地编译+运行+比对。 - 无 file_in/file_out:stdin 模式,tests=[{input, expected}] - 有 file_in/file_out:文件 IO 模式,每用例写 file_in → 运行 → 读 file_out 比对 - tests 为空:仅编译检查 返回对齐 /api/judge 结果:{status, verdict, score, test_cases, done, compile_error?} """ lang_cfg = LANGS.get(lang) if not lang_cfg: return {"status": 7, "verdict": "Compile Error", "score": 0, "test_cases": [], "done": True, "compile_error": f"暂不支持本地评测语言: {lang}(支持 cpp/java/python)"} workdir = f"/tmp/fl_local_{uuid.uuid4().hex[:10]}" os.makedirs(workdir, exist_ok=True) try: src = os.path.join(workdir, lang_cfg.get("main_file", "main" + lang_cfg["ext"])) with open(src, "w", encoding="utf-8") as f: f.write(code) # ---- 编译 ---- if lang_cfg.get("compile"): if lang == "cpp": cmd = ["g++", "-std=c++17", "-O2", src, "-o", "a.out"] elif lang == "java": cmd = ["javac", src] else: cmd = lang_cfg["compile"] + [src] rc, out, err = await _run(cmd, workdir, timeout=20) if rc != 0: return {"status": 7, "verdict": "Compile Error", "score": 0, "test_cases": [], "done": True, "compile_error": (err or out)[:800]} tests = tests or [] results: list[dict] = [] fileio = bool(file_in and file_out) for t in tests: t_input = str(t.get("input", "")) expected = str(t.get("expected", "")) stdin_data = None if fileio else t_input if fileio: with open(os.path.join(workdir, file_in), "w", encoding="utf-8") as f: f.write(t_input) rc, out, err = await _run(lang_cfg["run"], workdir, stdin_data=stdin_data, timeout=RUN_TIMEOUT) if rc == -9: results.append({"input": t_input, "expected": expected, "output": "", "status": 3, "ok": False, "reason": "运行超时"}) continue actual = "" if fileio: try: with open(os.path.join(workdir, file_out), encoding="utf-8", errors="replace") as f: actual = f.read()[:MAX_OUTPUT] except OSError: actual = "" else: actual = (out or "")[:MAX_OUTPUT] if rc != 0: results.append({"input": t_input, "expected": expected, "output": actual, "status": 6, "ok": False, "reason": (err or "Runtime Error")[:200]}) continue ok = _norm(actual) == _norm(expected) results.append({"input": t_input, "expected": expected, "output": actual, "status": 1 if ok else 2, "ok": ok}) if results: passed = sum(1 for r in results if r["ok"]) status = 1 if passed == len(results) else 2 return {"status": status, "verdict": "Accepted" if status == 1 else "Wrong Answer", "score": round(100 * passed / len(results)), "test_cases": results, "done": True, "compile_error": ""} # 无测试用例:仅编译通过(前端可走 LLM 分析) return {"status": 0, "verdict": "Compile OK", "score": 0, "test_cases": [], "done": True, "compile_error": "", "no_tests": True} finally: shutil.rmtree(workdir, ignore_errors=True)