Spaces:
Runtime error
Runtime error
Update app.py
Browse files123450 unmodified lines555657585960616263641 unmodified line6667686970717273747576777879808182838485from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom transformers import AutoTokenizer, AutoModelForSequenceClassificationimport torch50 unmodified lines# === 核心检测接口 ===@app.post("/detect")async def detect_vulnerability(code: str):"""代码安全检测主接口"""try:# 输入处理code = code[:2000] # 截断超长输入# 模型推理1 unmodified linecode,return_tensors="pt",truncation=True,max_length=512)with torch.no_grad():outputs = model(**inputs)# 结果解析label_id = outputs.logits.argmax().item()return {"label": label_id, # 0:安全 1:不安全"confidence": outputs.logits.softmax(dim=-1)[0][label_id].item()}except Exception as e:return {"error": str(e),"tip": "请检查输入代码是否包含非ASCII字符"}123450 unmodified lines555657585960616263646566676869701 unmodified line72737475767778798081828384858687888990919293949596979899from fastapi import FastAPI, Bodyfrom fastapi.middleware.cors import CORSMiddlewarefrom transformers import AutoTokenizer, AutoModelForSequenceClassificationimport torch50 unmodified lines# === 核心检测接口 ===@app.post("/detect")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 linecode,return_tensors="pt",truncation=True,padding=True, # 自动选择填充策略max_length=512)with torch.no_grad():outputs = model(**inputs)# 结果解析logits = outputs.logitslabel_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": round(confidence, 4)}except Exception as e:logger.error("Error during model inference: %s", str(e))return {"error": str(e),"tip": "请检查输入代码是否包含非ASCII字符或格式错误"}
app.py+22-8