-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinal.py
More file actions
415 lines (352 loc) · 17.4 KB
/
final.py
File metadata and controls
415 lines (352 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
from flask import Flask, request, jsonify, render_template, send_from_directory, redirect, url_for
import torch
from PIL import Image
import io
from ultralytics import YOLO
import os
import cv2
import numpy as np
import requests
import mimetypes
import json
import time
domainUrl = "https://bananacv.pablonara.com"
app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024
model_path = "content1/datasets/runs/obb/train4/weights/best.pt"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = YOLO(model_path)
model.to(device)
#def awaitVTresponse(sleepTime):
# try:
# responseData = response.json()
# idValue = responseData['data']['attributes']['stats']['malicious']
# if idValue > 0:
# print("detect!")
# trueOrFalse.append(True)
# guiUrlBase = "https://www.virustotal.com/gui/file-analysis/"
# md5sum = responseData['data']['meta']['file_info']['md5']
# urlsToReturn.append(guiUrlBase + md5)
# else:
# guiUrlBase = "https://www.virustotal.com/gui/file-analysis/"
# md5sum = responseData['data']['meta']['file_info']['md5']
# trueOrFalse.append(False)
# urlsToReturn.append()
# except Exception as e:
# print("processing")
# time.sleep(sleepTime)
def readIndex():
try:
f = open("filesIndex.txt", "r")
return(f.read())
except:
f = open("filesIndex.txt", "x")
f = open("filesIndex.txt", "r")
return(f.read())
def writeIndex(text):
f = open("filesIndex.txt", "a")
f.write(text)
f.close()
#def saveToDevice(path, image):
def process_video(filepath):
cap = cv2.VideoCapture(filepath)
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Choose the codec suitable for your needs
output_filepath = os.path.splitext(filepath)[0] + '_processed.mp4'
out = cv2.VideoWriter(output_filepath, fourcc, 20.0, (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))
while True:
ret, frame = cap.read()
if not ret:
break
results = model(frame, stream=True)
framenum = 0
for result in results:
boxes = result.boxes # Boxes object for bounding box outputs
masks = result.masks # Masks object for segmentation masks outputs
keypoints = result.keypoints # Keypoints object for pose outputs
probs = result.probs # Probs object for classification outputs
#obb = result.obb # Oriented boxes object for OBB outputs
# result.show() # display to screen
result.save(filename="concatonate.png")
writeOutFrame = cv2.imread("concatonate.png") # cv2 doesn't work direct importing yolov8, need convert first
out.write(writeOutFrame)
framenum += 1
print(framenum)
break # no need to continue after first frame because no more
cap.release()
out.release()
return send_from_directory(app.config['UPLOAD_FOLDER'], os.path.basename(output_filepath), as_attachment=True)
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
if 'file1' not in request.files:
return 'There is no file1 in the form!'
file1 = request.files['file1']
filename = file1.filename
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file1.save(filepath)
filename, fileExtension = os.path.splitext(filepath)
#results = model([filepath]) # return a list of Results objects, image only
fileExtension = set(['.png', '.jpg', '.jpeg'])
if fileExtension in imageExtensions:
results = model(filepath, stream=False, conf=0.5)
# Process results list
for result in results:
boxes = result.boxes # Boxes object for bounding box outputs
masks = result.masks # Masks object for segmentation masks outputs
keypoints = result.keypoints # Keypoints object for pose outputs
probs = result.probs # Probs object for classification outputs
obb = result.obb # Oriented boxes object for OBB outputs
# result.show() # display to screen
result.save(filename=filepath) # save to disk
file_name = os.path.basename(filepath)
return send_from_directory(app.config['UPLOAD_FOLDER'], file_name)
else:
#return(process_video(filepath))
cap = cv2.VideoCapture(filepath)
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Choose the codec suitable for your needs
output_filepath = os.path.splitext(filepath)[0] + '_processed.mp4'
out = cv2.VideoWriter(output_filepath, fourcc, 20.0, (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))
while True:
ret, frame = cap.read()
if not ret:
break
results = model(frame, stream=False, conf=0.5)
framenum = 0
for result in results:
boxes = result.boxes # Boxes object for bounding box outputs
masks = result.masks # Masks object for segmentation masks outputs
keypoints = result.keypoints # Keypoints object for pose outputs
probs = result.probs # Probs object for classification outputs
obb = result.obb # Oriented boxes object for OBB outputs
# result.show() # display to screen
result.save(filename="concatonate.png")
writeOutFrame = cv2.imread("concatonate.png") # cv2 doesn't work direct importing yolov8, need convert first
out.write(writeOutFrame)
framenum += 1
print(framenum)
break # no need to continue after first frame because no more
cap.release()
out.release()
return send_from_directory(app.config['UPLOAD_FOLDER'], os.path.basename(output_filepath), as_attachment=False)
elif request.method == 'GET':
return render_template('index.html')
def deployProduction():
return Flask(__name__)
# API
@app.route('/process_urls', methods=['POST'])
def process_urls():
# Extract the JSON data from the request
data = request.get_json()
print(data)
# Extract the list of links from the dictionary
links_list = data['files']
# Iterate over each link and print them
trueOrFalse = []
urlsToReturn = []
extension = ''
for link in links_list:
headerType=''
if link.startswith(('http://', 'https://')):
# Handle URL
response = requests.get(link)
# Get the original filename from the URL
filename = link.split('/')[-1].split('?')[0] # Remove query parameters
# Get the content type from the response headers
content_type = response.headers.get('Content-Type')
print(extension)
# Map content type to file extension
extension = mimetypes.guess_extension(content_type)
#print('mimetypes: ' + extension)
if not filename.lower().endswith(extension):
filename += extension
print(extension)
# print(extension)
if extension == None:
trueOrFalse.append(None)
urlsToReturn.append(link)
continue
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
filepath = os.path.join(UPLOAD_FOLDER, filename)
print(filepath)
with open(filepath, 'wb') as f:
f.write(response.content)
if extension == '.zip': # VT proof of concept check
print(link)
url = "https://www.virustotal.com/api/v3/files"
files = { "file": ("payload.zip", open("./"+filepath, "rb"), "application/zip") }
payload = { "password": "123" }
headers = {
"accept": "application/json",
#"content-type": "multipart/form-data",
"x-apikey": "YOUR_API_KEY"
}
response = requests.post(url, data=payload, files=files, headers=headers)
print (response.text)
print (response.text)
data = response.json()
#data_dict = json.loads(data)
# Access the 'id' value
urlGet = "https://www.virustotal.com/api/v3/urls/"
id_value = data['data']['links']['self']
print(id_value)
headers = {
"accept": "application/json",
"x-apikey": "YOUR_API_KEY"
}
print(id_value)
response = requests.get(id_value, headers=headers)
print(response.text)
try:
responseData = response.json()
idValue = responseData['data']['attributes']['stats']['malicious']
if idValue > 0:
print("detect!")
trueOrFalse.append(True)
guiUrlBase = "https://www.virustotal.com/gui/file-analysis/"
md5sum = responseData['meta']['file_info']['md5']
urlsToReturn.append(guiUrlBase + md5sum)
print("test")
else:
guiUrlBase = "https://www.virustotal.com/gui/file-analysis/"
md5sum = responseData['meta']['file_info']['md5']
trueOrFalse.append(False)
urlsToReturn.append(guiUrlBase + md5sum)
print('reached here.')
except Exception as e:
print(e)
print("processing")
time.sleep(25)
try:
responseData = response.json()
idValue = responseData['data']['attributes']['stats']['malicious']
if idValue > 0:
print("detect!")
trueOrFalse.append(True)
guiUrlBase = "https://www.virustotal.com/gui/file-analysis/"
md5sum = responseData['meta']['file_info']['md5']
urlsToReturn.append(guiUrlBase + md5sum)
else:
guiUrlBase = "https://www.virustotal.com/gui/file-analysis/"
md5sum = responseData['meta']['file_info']['md5']
trueOrFalse.append(False)
urlsToReturn.append(guiUrlBase + md5sum)
except Exception as e:
print("processing")
time.sleep(25)
try:
responseData = response.json()
idValue = responseData['data']['attributes']['stats']['malicious']
if idValue > 0:
print("detect!")
trueOrFalse.append(True)
guiUrlBase = "https://www.virustotal.com/gui/file-analysis/"
md5sum = responseData['meta']['file_info']['md5']
urlsToReturn.append(guiUrlBase + md5sum)
else:
guiUrlBase = "https://www.virustotal.com/gui/file-analysis/"
md5sum = responseData['meta']['file_info']['md5']
trueOrFalse.append(False)
urlsToReturn.append(guiUrlBase + md5sum)
except Exception as e:
print("VirusTotal timed out, assuming false")
trueOrFalse.append(False)
urlsToReturn.append(guiUrlBase + md5sum)
print(e)
# If there's no extension in the filename, append the correct one
#if not filename.lower().endswith(extension):
#filename += extension
#print(extension)
# Save the file with the correct extension
#filepath = os.path.join(UPLOAD_FOLDER, filename)
#with open(filepath, 'wb') as f:
#f.write(response.content)
else:
file1 = request.files.get(link)
#file1 = request.files[link]
filename = file1.filename
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file1.save(filepath)
filename, fileExtension = os.path.splitext(filepath)
#results = model([filepath]) # return a list of Results objects, image only
imageExtensions = set(['.png', '.jpg', '.jpeg', 'image/png', 'image/jpg', 'image/jpeg', 'image/webp'])
if extension in imageExtensions:
results = model(filepath, stream=False, conf=0.5, save_txt=True)
# Process results list
for result in results:
boxes = result.boxes # Boxes object for bounding box outputs
masks = result.masks # Masks object for segmentation masks outputs
keypoints = result.keypoints # Keypoints object for pose outputs
probs = result.probs # Probs object for classification outputs
obb = result.obb # Oriented boxes object for OBB outputs
# result.show() # display to screen
result.save(filename=filepath) # save to disk
file_name = os.path.basename(filepath)
print(result.obb)
count = len(results[0].obb)
print("count", count)
#print(boxes.conf)
#classes: Dict[int, str] = results.names
#resultsWithProbs: List[Tuple[Results, str]] = [(result, classes[result.boxes.cls.numpy()[0]]) for result in results]
try:
if count == 0:
trueOrFalse.append(False)
print("false")
else:
trueOrFalse.append(True)
print("true")
except Exception as e:
trueOrFalse.append(False)
print("Frue")
print(e)
urlsToReturn.append(domainUrl + url_for('static', filename="uploads/"+file_name))
else:
#return(process_video(filepath))
cap = cv2.VideoCapture(filepath)
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Choose the codec suitable for your needs
output_filepath = os.path.splitext(filepath)[0] + '_processed.mp4'
out = cv2.VideoWriter(output_filepath, fourcc, 20.0, (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))
framenum = 0
while True:
detected = False
ret, frame = cap.read()
if not ret:
break
results = model(frame, stream=True, conf=0.5)
for result in results:
boxes = result.boxes # Boxes object for bounding box outputs
masks = result.masks # Masks object for segmentation masks outputs
keypoints = result.keypoints # Keypoints object for pose outputs
probs = result.probs # Probs object for classification outputs
obb = result.obb # Oriented boxes object for OBB outputs
# result.show() # display to screen
result.save(filename="concatonate.png")
writeOutFrame = cv2.imread("concatonate.png") # cv2 doesn't work direct importing yolov8, need convert first
out.write(writeOutFrame)
framenum += 1
print(framenum)
count = len(results[0].obb)
#count = len(results[0].obb)
if count == 0:
trueOrFalse.append(False)
else:
trueOrFalse.append(True)
break # no need to continue after first frame because no more
cap.release()
out.release()
#count = len(results[0].obb)
#if boxes.conf == 'None':
#trueOrFalse.append(False)
#else:
#trueOrFalse.append(True)
urlsToReturn.append(domainUrl + url_for('static', filename='uploads/'+output_filepath))
data = {
'results': trueOrFalse,
'urls': urlsToReturn
}
return jsonify(data)
if __name__ == '__main__':
#app.run(debug=True, port=8082)
from waitress import serve # production
serve(app, host="0.0.0.0", port=8082, threads=4)