MUHAMMADSAADAMIN commited on
Commit
2883685
·
verified ·
1 Parent(s): 4b1a242

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -0
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ from fastapi import FastAPI
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ from pydantic import BaseModel
6
+
7
+ MODEL_NAME = "MUHAMMADSAADAMIN/polyguard-model"
8
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
9
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
10
+ model.eval()
11
+
12
+ suggestions = {
13
+ "sqli": "Use parameterized queries instead of building SQL strings manually.",
14
+ "xss": "Sanitize all user inputs before rendering them to the page.",
15
+ "secrets": "Never hardcode API keys or passwords. Use environment variables instead.",
16
+ "crypto": "Avoid MD5 and SHA1. Use SHA256 or bcrypt for hashing.",
17
+ "memory": "Always check buffer sizes before copying data in C/C++.",
18
+ "auth": "Always verify user permissions before returning sensitive data.",
19
+ }
20
+
21
+ language_tips = {
22
+ "python": [
23
+ "Use list comprehensions instead of for loops where possible.",
24
+ "Use f-strings for string formatting instead of .format() or %.",
25
+ "Use 'with open()' for file handling instead of open/close.",
26
+ ],
27
+ "javascript": [
28
+ "Use const and let instead of var.",
29
+ "Use async/await instead of nested callbacks.",
30
+ "Always use === instead of == for comparisons.",
31
+ ],
32
+ "java": [
33
+ "Use try-with-resources for handling streams and connections.",
34
+ "Use StringBuilder instead of String concatenation in loops.",
35
+ ],
36
+ "go": [
37
+ "Always handle errors explicitly.",
38
+ "Use goroutines for concurrency instead of threads.",
39
+ ],
40
+ }
41
+
42
+ app = FastAPI(title="PolyGuard API")
43
+
44
+ app.add_middleware(
45
+ CORSMiddleware,
46
+ allow_origins=["*"],
47
+ allow_methods=["*"],
48
+ allow_headers=["*"],
49
+ )
50
+
51
+ class CodeRequest(BaseModel):
52
+ code: str
53
+ language: str = "python"
54
+
55
+ @app.get("/")
56
+ def home():
57
+ return {"status": "PolyGuard API is running!"}
58
+
59
+ @app.post("/analyze")
60
+ def analyze(request: CodeRequest):
61
+ inputs = tokenizer(
62
+ request.code,
63
+ return_tensors="pt",
64
+ truncation=True,
65
+ max_length=256,
66
+ padding=True
67
+ )
68
+ with torch.no_grad():
69
+ outputs = model(**inputs)
70
+
71
+ probs = torch.softmax(outputs.logits, dim=1)
72
+ clean_conf = probs[0][0].item()
73
+ vuln_conf = probs[0][1].item()
74
+ score = round(clean_conf * 10, 1)
75
+
76
+ if score >= 8:
77
+ risk = "low"
78
+ elif score >= 5:
79
+ risk = "medium"
80
+ else:
81
+ risk = "high"
82
+
83
+ findings = []
84
+ if vuln_conf > 0.4:
85
+ findings.append(suggestions["sqli"])
86
+ if vuln_conf > 0.6:
87
+ findings.append(suggestions["xss"])
88
+
89
+ tips = language_tips.get(request.language.lower(), ["Keep learning!"])
90
+
91
+ return {
92
+ "score": score,
93
+ "risk": risk,
94
+ "verdict": "CLEAN" if score >= 7 else "VULNERABLE",
95
+ "clean_confidence": round(clean_conf * 100, 1),
96
+ "vuln_confidence": round(vuln_conf * 100, 1),
97
+ "findings": findings,
98
+ "tips": tips,
99
+ }