feat(M7.5): 非题库题本地评测——AI 出的题不提交 Hydro,走服务器本地编译+运行比对(支持 stdin/fileio)或 LLM 代码分析;前端按题目来源/语言自动路由,结果插入发起判题之后
这个提交包含在:
@@ -10,8 +10,10 @@ from app.adapters.base import JudgeEngineError
|
||||
from app.core.db import get_session
|
||||
from app.core.session_pool import pool
|
||||
from app.repositories.message_repo import MessageRepo
|
||||
from app.services.ai_service import AIService
|
||||
from app.services.auth_service import AuthService
|
||||
from app.services.judge_service import JudgeService
|
||||
from app.services.local_judge import LocalJudgeError, local_judge
|
||||
from app.services.progress_service import ProgressService
|
||||
|
||||
router = APIRouter(prefix="/judge", tags=["judge"])
|
||||
@@ -27,6 +29,17 @@ class SubmitBody(BaseModel):
|
||||
conversation_id: int = 0 # 会话(学科窗口)
|
||||
|
||||
|
||||
class LocalSubmitBody(BaseModel):
|
||||
"""本地评测:AI 出的非题库题(无 Hydro 测试点)→ 服务器本地编译运行比对 / LLM 分析。"""
|
||||
lang: str
|
||||
code: str
|
||||
tests: list[dict] = [] # [{input, expected}](stdin 模式)
|
||||
file_in: str | None = None # 文件 IO 模式输入文件名(如 add.in)
|
||||
file_out: str | None = None # 文件 IO 模式输出文件名(如 add.out)
|
||||
context_md: str = "" # 题目上下文(AI 出的题面),供 LLM 分析
|
||||
conversation_id: int = 0
|
||||
|
||||
|
||||
def _current(authorization: str | None, session: Session) -> tuple[str, int | None, dict | None]:
|
||||
"""从 JWT 取当前用户:返回 (uid 标识, 本地 user_id, hydro session cookies)。未登录 → (guest, None, None)。"""
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
@@ -57,6 +70,61 @@ async def submit(body: SubmitBody, authorization: str | None = Header(None), ses
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/local")
|
||||
async def submit_local(body: LocalSubmitBody, authorization: str | None = Header(None), session: Session = Depends(get_session)):
|
||||
"""本地评测:非题库题(AI 出的题,无 Hydro 测试点)。
|
||||
有测试用例 → 本地编译运行比对(stdin/fileio 两种模式);
|
||||
无测试用例 → 编译检查 + LLM 代码分析(判逻辑正确性/输入方式)。
|
||||
"""
|
||||
uid, user_id, _sid = _current(authorization, session)
|
||||
try:
|
||||
result = await local_judge(body.lang, body.code, body.tests, body.file_in, body.file_out)
|
||||
except LocalJudgeError as e:
|
||||
raise HTTPException(400, str(e))
|
||||
|
||||
# 无测试用例 → LLM 分析兜底(代码走读:语法/逻辑/输入方式/边界)
|
||||
if result.get("no_tests"):
|
||||
try:
|
||||
ai = AIService()
|
||||
ctx = body.context_md.strip() or "(无题面上下文)"
|
||||
from app.adapters.ai_provider import ChatMessage
|
||||
sys_prompt = (
|
||||
"你是竞赛编程代码评审助手。学生提交了一段代码,用于解决一道 AI 随出的练习题(可能不是标准题库题)。"
|
||||
"请逐项检查并给出结论:\n"
|
||||
"1) 语法/编译层面是否有问题;\n"
|
||||
"2) 逻辑是否正确(读入、计算、输出);\n"
|
||||
"3) 输入方式是否匹配题目要求:题面要求文件 IO(如 add.in/add.out)还是标准输入输出;"
|
||||
" 若代码用 ifstream 读文件而题面/评测环境不支持,要明确指出;\n"
|
||||
"4) 边界情况(0、负数、大数、空输入等)。\n"
|
||||
"输出格式:先给结论(代码可运行且逻辑正确 / 有问题需修改),再分条列出问题与修改建议。"
|
||||
"用中文,Markdown 组织,不要直接给完整改写代码除非逻辑有硬伤。"
|
||||
)
|
||||
reply = await ai.provider.chat(
|
||||
[ChatMessage("user", f"题目上下文:\n{ctx}\n\n学生代码({body.lang}):\n```{body.lang}\n{body.code}\n```")],
|
||||
system=sys_prompt,
|
||||
)
|
||||
result["verdict"] = "AI 分析"
|
||||
result["status"] = 10
|
||||
result["score"] = 0
|
||||
result["analysis"] = reply
|
||||
result["compile_ok"] = True
|
||||
except Exception as e:
|
||||
import traceback
|
||||
logging.getLogger("fluent.judge").exception("LLM 代码分析失败")
|
||||
result["analysis"] = f"(LLM 分析暂不可用:{type(e).__name__},本地编译已通过)"
|
||||
result["status"] = 10
|
||||
result["verdict"] = "AI 分析"
|
||||
|
||||
# 本地评测结果入库(judge 消息,便于复盘)
|
||||
MessageRepo(session).add(
|
||||
user_id, "judge", body.code, kind="judge_local",
|
||||
meta={"verdict": result.get("verdict", ""), "score": result.get("score", 0),
|
||||
"status": result.get("status"), "lang": body.lang, "local": True},
|
||||
conversation_id=body.conversation_id if user_id else 0,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/{rid}")
|
||||
async def fetch(rid: str, uid: str = "guest", session: Session = Depends(get_session)):
|
||||
svc = JudgeService(session)
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""本地评测:非题库题(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)
|
||||
在新工单中引用
屏蔽一个用户