Spaces:
Runtime error
Runtime error
Update app.py
Browse files1123450 unmodified lines5556575858596061616263646566676869701 unmodified line727374757677787980738182837584858687888990789192939495969784859899from fastapi import FastAPIfrom fastapi import FastAPI, Bodyfrom fastapi.middleware.cors import CORSMiddlewarefrom transformers import AutoTokenizer, AutoModelForSequenceClassificationimport torch50 unmodified lines
# === 核心检测接口 ===@app.post("/detect")async def detect_vulnerability(code: str):async def detect_vulnerability(payload: dict = Body(...)): """代码安全检测主接口""" try: # 输入处理 # 获取 JSON 输入数据 code = payload.get("code", "").strip()
if not code: return {"error": "代码内容为空", "tip": "请提供有效的代码字符串"}
# 限制代码长度 code = code[:2000] # 截断超长输入 # 模型推理1 unmodified line code, return_tensors="pt", truncation=True, padding=True, # 自动选择填充策略 max_length=512 )
with torch.no_grad(): outputs = model(**inputs)
# 结果解析 logits = outputs.logits label_id = outputs.logits.argmax().item() label_id = logits.argmax().item() confidence = logits.softmax(dim=-1)[0][label_id].item()
logger.info(f"Code analyzed. Logits: {logits.tolist()}, Prediction: {label_id}, Confidence: {confidence:.4f}")
return { "label": label_id, # 0:安全 1:不安全 "confidence": outputs.logits.softmax(dim=-1)[0][label_id].item() "confidence": round(confidence, 4) } except Exception as e: logger.error("Error during model inference: %s", str(e)) return { "error": str(e), "tip": "请检查输入代码是否包含非ASCII字符" } "tip": "请检查输入代码是否包含非ASCII字符或格式错误" }app.py+22-8