ziffir commited on
Commit
1010f17
·
verified ·
1 Parent(s): 6c0ffed

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -0
app.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import torch
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from huggingface_hub import login
6
+
7
+ # Hugging Face token (Private Space için)
8
+ # HF_TOKEN = os.getenv("HF_TOKEN") # Spaces secrets'tan alınacak
9
+
10
+ # Model seçimi - daha kontrol edilebilir bir model
11
+ MODEL_ID = "codellama/CodeLlama-7b-Instruct-hf" # veya sizin tercihiniz
12
+
13
+ class SecureCodeAnalyzer:
14
+ def __init__(self):
15
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
16
+ print(f"Using device: {self.device}")
17
+
18
+ # Tokenizer
19
+ self.tokenizer = AutoTokenizer.from_pretrained(
20
+ MODEL_ID,
21
+ use_fast=True
22
+ )
23
+ self.tokenizer.pad_token = self.tokenizer.eos_token
24
+
25
+ # Model - daha optimize yükleme
26
+ self.model = AutoModelForCausalLM.from_pretrained(
27
+ MODEL_ID,
28
+ torch_dtype=torch.float16,
29
+ device_map="auto" if self.device == "cuda" else None,
30
+ low_cpu_mem_usage=True
31
+ )
32
+
33
+ if self.device == "cpu":
34
+ self.model = self.model.to(self.device)
35
+
36
+ self.model.eval()
37
+
38
+ def analyze(self, code, language, detail_level, custom_prompt=""):
39
+ try:
40
+ # Özel prompt kullan veya varsayılanı
41
+ if custom_prompt.strip():
42
+ base_prompt = custom_prompt
43
+ else:
44
+ base_prompt = f"""Analyze this {language} code for security vulnerabilities.
45
+ Provide detailed technical analysis including:
46
+ 1. Vulnerability type
47
+ 2. Risk level
48
+ 3. Exploitation method
49
+ 4. Fix recommendation
50
+
51
+ Code to analyze:
52
+ {code}
53
+
54
+ Analysis ({detail_level} level):
55
+ """
56
+
57
+ inputs = self.tokenizer(
58
+ base_prompt,
59
+ return_tensors="pt",
60
+ truncation=True,
61
+ max_length=2048
62
+ ).to(self.device)
63
+
64
+ with torch.no_grad():
65
+ outputs = self.model.generate(
66
+ **inputs,
67
+ max_new_tokens=500,
68
+ temperature=0.3,
69
+ do_sample=True,
70
+ top_p=0.95,
71
+ repetition_penalty=1.1
72
+ )
73
+
74
+ response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
75
+
76
+ # Sadece yeni oluşturulan kısmı al
77
+ if base_prompt in response:
78
+ response = response.split(base_prompt)[-1].strip()
79
+
80
+ return response
81
+
82
+ except Exception as e:
83
+ return f"Error: {str(e)}"
84
+
85
+ # Initialize analyzer
86
+ analyzer = SecureCodeAnalyzer()
87
+
88
+ # Gradio arayüzü
89
+ def create_interface():
90
+ with gr.Blocks(theme=gr.themes.Soft(), title="Private Code Auditor") as demo:
91
+ gr.Markdown("# 🔐 Private Code Security Auditor")
92
+ gr.Markdown("*For internal security analysis purposes*")
93
+
94
+ with gr.Row():
95
+ with gr.Column(scale=1):
96
+ language = gr.Dropdown(
97
+ ["Python", "C/C++", "JavaScript", "Java", "Go", "PHP", "Other"],
98
+ value="Python",
99
+ label="Code Language"
100
+ )
101
+
102
+ detail = gr.Dropdown(
103
+ ["Quick Scan", "Standard", "Deep Analysis"],
104
+ value="Standard",
105
+ label="Analysis Depth"
106
+ )
107
+
108
+ custom_prompt = gr.Textbox(
109
+ label="Custom Prompt (Optional)",
110
+ placeholder="Enter custom analysis instructions...",
111
+ lines=3
112
+ )
113
+
114
+ gr.Markdown("### Instructions:")
115
+ gr.Markdown("""
116
+ - Paste code in the code editor
117
+ - Select language and depth
118
+ - Optional: Add custom prompt
119
+ - Click Analyze
120
+ """)
121
+
122
+ with gr.Column(scale=2):
123
+ code_input = gr.Code(
124
+ label="Source Code",
125
+ language="python",
126
+ lines=20,
127
+ value="// Paste your code here"
128
+ )
129
+
130
+ analyze_btn = gr.Button(
131
+ "🔍 Analyze Code",
132
+ variant="primary",
133
+ size="lg"
134
+ )
135
+
136
+ output = gr.Textbox(
137
+ label="Security Analysis Report",
138
+ lines=15,
139
+ interactive=False
140
+ )
141
+
142
+ # Event handler
143
+ analyze_btn.click(
144
+ fn=lambda code, lang, detail, custom: analyzer.analyze(code, lang, detail, custom),
145
+ inputs=[code_input, language, detail, custom_prompt],
146
+ outputs=output
147
+ )
148
+
149
+ # Clear button
150
+ clear_btn = gr.Button("Clear")
151
+ clear_btn.click(
152
+ fn=lambda: ("", "", "Standard", "", ""),
153
+ outputs=[code_input, output, detail, custom_prompt, language]
154
+ )
155
+
156
+ return demo
157
+
158
+ # Uygulamayı başlat
159
+ if __name__ == "__main__":
160
+ demo = create_interface()
161
+ demo.launch(
162
+ server_name="0.0.0.0",
163
+ server_port=7860,
164
+ share=False, # Private için share kapalı
165
+ debug=False
166
+ )