code
stringlengths
17
6.64M
class NodeDegree(object): def __call__(self, data): (row, col) = data.edge_index N = data.num_nodes data.x = degree(row, N, dtype=torch.float) data.x = data.x.view((- 1), 1) return data def __repr__(self): return '{}()'.format(self.__class__.__name__)
def save_model(args, model): torch.save(model.state_dict(), (args['log_dir'] + 'best_model.pt'))
def log_info(args, epoch, y_true, y_pred, y_scores, param_count, run_time, data_type='val'): macro_f1 = round(f1_score(y_true, y_pred, average='macro'), 3) report = classification_report(y_true, y_pred, labels=args['class_indexes'], target_names=args['class_labels'], output_dict=True) with open((args['log_dir'] + 'best_{}_info.txt'.format(data_type)), 'w') as f: pprint('Parameters', stream=f) pprint(args, stream=f) pprint('Epoch: {}'.format(epoch), stream=f) pprint('Number of model parameters: {}'.format(param_count), stream=f) pprint('Classification report', stream=f) pprint(report, stream=f) pprint('Macro-f1: {}'.format(macro_f1), stream=f) pprint('Malware group: {}'.format(args['group']), stream=f) pprint('Train ratio: {}'.format(args['train_ratio']), stream=f) pprint('Embedding took {} seconds w/ {} cpu cores'.format(round(run_time, 2), args['n_cores']), stream=f) pprint('Label dictionary:', stream=f) pprint(args['class_labels'], stream=f) if (args['group'] != 'family'): pprint('Confusion matrix', stream=f) cm = confusion_matrix(y_true, y_pred, labels=args['class_indexes']) pprint(cm, stream=f) if (args['group'] == 'binary'): pprint('FPR/TPR Info', stream=f) (fpr, tpr, thresholds) = roc_curve(y_true, y_scores, pos_label=[1]) pprint('tpr: {}'.format(tpr.tolist()), stream=f) pprint('fpr: {}'.format(fpr.tolist()), stream=f) pprint('thresholds: {}'.format(thresholds.tolist()), stream=f) auc_macro_score = roc_auc_score(y_true, y_scores, average='macro') auc_class_scores = roc_auc_score(y_true, y_scores, average=None) pprint('AUC macro score: {}'.format(auc_macro_score), stream=f) pprint('AUC class scores: {}'.format(auc_class_scores), stream=f)
def get_split_info(args): if args['malnet_tiny']: args['group'] = 'type' split_dir = ('split-info-tiny' if args['malnet_tiny'] else 'split-info') data_dir = (args['malnet_tiny_dir'] if args['malnet_tiny'] else args['malnet_dir']) with open((os.getcwd() + '/../{}/{}/{}/train.txt'.format(split_dir, args['group'], args['train_ratio'])), 'r') as f: lines_train = f.readlines() with open((os.getcwd() + '/../{}/{}/{}/val.txt'.format(split_dir, args['group'], args['train_ratio'])), 'r') as f: lines_val = f.readlines() with open((os.getcwd() + '/../{}/{}/{}/test.txt'.format(split_dir, args['group'], args['train_ratio'])), 'r') as f: lines_test = f.readlines() files_train = [((data_dir + file.strip()) + '.edgelist') for file in lines_train] files_val = [((data_dir + file.strip()) + '.edgelist') for file in lines_val] files_test = [((data_dir + file.strip()) + '.edgelist') for file in lines_test] if (args['group'] == 'type'): graph_labels = sorted(list(set([file.split(data_dir)[1].split('/')[0] for file in files_train]))) label_dict = {t: idx for (idx, t) in enumerate(graph_labels)} train_labels = [label_dict[file.split(data_dir)[1].split('/')[0]] for file in files_train] val_labels = [label_dict[file.split(data_dir)[1].split('/')[0]] for file in files_val] test_labels = [label_dict[file.split(data_dir)[1].split('/')[0]] for file in files_test] elif (args['group'] == 'family'): graph_labels = sorted(list(set([file.split(data_dir)[1].split('/')[1] for file in files_train]))) label_dict = {t: idx for (idx, t) in enumerate(graph_labels)} train_labels = [label_dict[file.split(data_dir)[1].split('/')[1]] for file in files_train] val_labels = [label_dict[file.split(data_dir)[1].split('/')[1]] for file in files_val] test_labels = [label_dict[file.split(data_dir)[1].split('/')[1]] for file in files_test] elif (args['group'] == 'binary'): graph_labels = ['benign', 'malicious'] label_dict = {t: idx for (idx, t) in enumerate(graph_labels)} train_labels = [(0 if ('benign' in file.split(data_dir)[1].split('/')[0]) else 1) for file in files_train] val_labels = [(0 if ('benign' in file.split(data_dir)[1].split('/')[0]) else 1) for file in files_val] test_labels = [(0 if ('benign' in file.split(data_dir)[1].split('/')[0]) else 1) for file in files_test] else: print('Group does not exist') exit(1) print('Number of train samples: {}, val samples: {}, test samples: {}'.format(len(files_train), len(files_val), len(files_test))) return (files_train, files_val, files_test, train_labels, val_labels, test_labels, label_dict)
def match_ann(fileName): js = json.loads(open(fileName).read()) for items in js['people']: handRight = items['hand_right_keypoints_2d'] confPoints = helper.confidencePoints(handRight) confidence = helper.confidence(confPoints) if (confidence > 10.2): handPoints = helper.removePoints(handRight) '\n experimenting with scaling \n ' p1 = [handPoints[0], handPoints[1]] p2 = [handPoints[18], handPoints[19]] distance = math.sqrt((((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))) (Result, Points) = scale.scalePoints(handPoints, distance) (handRightResults, handRightPoints) = move.centerPoints(handPoints) '\n extracting data from db\n ' connection = sqlite3.connect('data\\db\\main_dataset.db') crsr = connection.cursor() sql = 'SELECT x1,y1' for x in range(2, 22): sql = ((((sql + ',x') + str(x)) + ',y') + str(x)) sql = (sql + ' FROM rightHandDataset WHERE 1') crsr.execute(sql) feature_res = crsr.fetchall() feature_res = np.asarray(feature_res) features = [] for x in feature_res: features.append(x) crsr.execute('SELECT label FROM rightHandDataset WHERE 1') label_res = crsr.fetchall() labels = [] for x in label_res: labels.append(x) le = preprocessing.LabelEncoder() label_encoded = le.fit_transform(labels) label_encoded = to_categorical(label_encoded) (X_train, X_test, y_train, y_test) = train_test_split(features, label_encoded, test_size=0.2) scaler = StandardScaler().fit(X_train) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) y_pred = model.predict(scaler.transform(np.array([handRightResults]))) C = np.argmax(y_pred) result = le.inverse_transform([C]) return result[0] else: return 'no confidence'
def signal_handler(signal, frame): shutil.rmtree('Keypoints', ignore_errors=True, onerror=handleRemoveReadonly) shutil.rmtree('gui\\captured_images', ignore_errors=True, onerror=handleRemoveReadonly) shutil.rmtree('gui\\temp_images', ignore_errors=True, onerror=handleRemoveReadonly) print('All done') sys.exit(0)
def handleRemoveReadonly(func, path, exc): excvalue = exc[1] if ((func in (os.rmdir, os.remove)) and (excvalue.errno == errno.EACCES)): os.chmod(path, ((stat.S_IRWXU | stat.S_IRWXG) | stat.S_IRWXO)) func(path) else: raise Exception
def plotPose(posePoints, handRightPoints, handLeftPoints): POSE_PAIRS = [[1, 0], [1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [0, 15], [15, 17], [0, 16], [16, 18]] HAND_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]] colors = [[0, 0, 130], [0, 0, 175], [0, 0, 210], [0, 0, 250], [0, 200, 160], [0, 180, 150], [0, 230, 186], [0, 255, 255], [82, 201, 8], [82, 204, 0], [92, 230, 0], [102, 252, 6], [197, 88, 17], [204, 82, 0], [179, 71, 0], [227, 94, 5], [204, 0, 163], [200, 0, 163], [196, 0, 163], [230, 0, 184]] background = 'PSL\\BLACK_background.jpg' frame = cv2.imread(background) count = 0 for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (posePoints[partA] and posePoints[partB] and (posePoints[partA][0] != 0) and (posePoints[partA][1] != 0) and (posePoints[partB][0] != 0) and (posePoints[partB][1] != 0)): cv2.line(frame, posePoints[partA], posePoints[partB], colors[count], 10) cv2.circle(frame, posePoints[partA], 5, (0, 0, 255), thickness=10, lineType=cv2.FILLED) cv2.circle(frame, posePoints[partB], 5, (255, 255, 255), thickness=15, lineType=cv2.FILLED) count += 1 count = 0 for pair in HAND_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=3, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 5, (255, 255, 255), thickness=4, lineType=cv2.FILLED) count += 1 count = 0 for pair in HAND_PAIRS: partA = pair[0] partB = pair[1] if (handLeftPoints[partA] and handLeftPoints[partB]): cv2.line(frame, handLeftPoints[partA], handLeftPoints[partB], colors[count], 10) cv2.circle(frame, handLeftPoints[partA], 5, (0, 0, 255), thickness=3, lineType=cv2.FILLED) cv2.circle(frame, handLeftPoints[partB], 5, (255, 255, 255), thickness=4, lineType=cv2.FILLED) count += 1 return frame
@eel.expose def capture_alphabet_dataset(sec): global remfileNames '\n ----------------------Start OpenPoseDemo.exe----------------------\n --render_pose 0 --display 0\n ' os.chdir('bin\\openpose') print('Starting OpenPose') subprocess.Popen('bin\\OpenPoseDemo.exe --hand --write_json ..\\..\\Keypoints --number_people_max 1', shell=True) os.chdir('..\\..') '\n ----------------------Creating temp folder----------------------\n ' dirName = 'Keypoints' init_file = 'PSL\\000000000000_keypoints.json' try: os.mkdir(dirName) os.mkdir('gui\\captured_images') os.mkdir('gui\\temp_images') shutil.copy(init_file, dirName) print('Directory ', dirName, ' Created ') except FileExistsError: print('Directory ', dirName, ' already exists') '\n ----------------------Live View----------------------\n ' t = (time.time() + sec) while (time.time() <= t): eel.sleep(0.05) os.system('taskkill /f /im OpenPoseDemo.exe') '\n ---------------------- Auto Remove files----------------------\n ' conf_thershold = 10 fileNames = [] for entry in os.scandir('Keypoints'): if entry.is_file(): if (os.path.splitext(entry)[1] == '.json'): fileNames.append(entry.name) for x in range(len(fileNames)): js = json.loads(open(('Keypoints\\' + fileNames[x])).read()) for items in js['people']: handRight = items['hand_right_keypoints_2d'] confPoints = helper.confidencePoints(handRight) confidence = helper.confidence(confPoints) print(confidence) if (confidence < conf_thershold): os.remove(('Keypoints\\' + fileNames[x])) '\n ----------------------plot and save----------------------\n ' background = 'big_background.png' fileNames = [] for entry in os.scandir('Keypoints'): if entry.is_file(): if (os.path.splitext(entry)[1] == '.json'): fileNames.append(entry.name) frame = cv2.imread(background) i = 1 for x in range(len(fileNames)): js = json.loads(open(('Keypoints\\' + fileNames[x])).read()) for items in js['people']: handRight = items['hand_right_keypoints_2d'] handPoints = helper.removePoints(handRight) p1 = [handPoints[0], handPoints[1]] p2 = [handPoints[18], handPoints[19]] distance = math.sqrt((((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))) (Result, Points) = scale.dummy_scalePoints(handPoints, distance) (handRightResults, handRightPoints) = move.dummy_centerPoints(Result) frame = plot.plot_dataset(handRightPoints, 'black') cv2.imwrite((('gui\\captured_images\\' + str(i)) + '.jpg'), frame) i += 1 '\n ----------------------get ref to delete files----------------------\n ' for entry in os.scandir('Keypoints'): if entry.is_file(): if (os.path.splitext(entry)[1] == '.json'): remfileNames.append(entry.name) '\n ----------------------end capture_alphabet_dataset(sec)----------------------\n '
@eel.expose def getFileCount(): Names = [] for entry in os.scandir('gui\\captured_images'): Names.append(entry.name) return str(len(Names))
@eel.expose def delete_Image(i): global remfileNames print(remfileNames) try: os.remove(('Keypoints\\' + remfileNames[(i - 1)])) os.remove((('gui\\captured_images\\' + str(i)) + '.jpg')) except: print('file not found') pass
@eel.expose def getlabel(a): label = a.strip() print(label) "\n traverse 'dataset' folder ,\n find subfolder matching 'label' ,\n create folder with timestamp in matched folder , \n and copy everything from 'Keypoints_temp' to created folder\n " for entry in os.scandir('data\\datasets\\alphabets_dataset'): if (entry.name == label): now = datetime.now() timestamp = str(datetime.timestamp(now)) dir_name = ((('data\\datasets\\alphabets_dataset\\' + entry.name) + '\\') + timestamp) try: os.mkdir(dir_name) print('Directory ', dir_name, ' Created ') except FileExistsError: print('Directory ', dir_name, ' already exists') copy_tree('Keypoints', ((('data\\datasets\\alphabets_dataset\\' + entry.name) + '\\') + timestamp)) ' \n Remove temp folders \n ' try: shutil.rmtree('Keypoints', ignore_errors=True, onerror=handleRemoveReadonly) shutil.rmtree('gui\\captured_images', ignore_errors=True, onerror=handleRemoveReadonly) shutil.rmtree('gui\\temp_images', ignore_errors=True, onerror=handleRemoveReadonly) print('Keypoints_temp folder removed') except: print('not removed') pass
@eel.expose def db_train(): retrain.re_train(1)
def signal_handler(signal, frame): shutil.rmtree('Keypoints', ignore_errors=True, onerror=handleRemoveReadonly) print('All done') sys.exit(0)
def handleRemoveReadonly(func, path, exc): excvalue = exc[1] if ((func in (os.rmdir, os.remove)) and (excvalue.errno == errno.EACCES)): os.chmod(path, ((stat.S_IRWXU | stat.S_IRWXG) | stat.S_IRWXO)) func(path) else: raise Exception
def json_files(Dir): folders = [] files = [] fileNames = [] for entry in os.scandir(Dir): if entry.is_dir(): folders.append(entry.path) for entry1 in os.scandir(entry.path): if entry1.is_dir(): folders.append(entry1.path) for entry2 in os.scandir(entry1.path): if entry2.is_dir(): folders.append(entry2.path) elif entry2.is_file(): if (os.path.splitext(entry2)[1] == '.json'): files.append(entry2.path) fileNames.append(entry2.name) elif entry1.is_file(): if (os.path.splitext(entry1)[1] == '.json'): files.append(entry1.path) fileNames.append(entry1.name) elif entry.is_file(): if (os.path.splitext(entry)[1] == '.json'): files.append(entry.path) fileNames.append(entry.name) return (files, fileNames, folders)
def removePoints(handRight): handRightResults = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 3): handRightX.append(handRight[x]) for x in range(1, len(handRight), 3): handRightY.append(handRight[x]) for x in range(len(handRightX)): handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return handRightResults
def getCoordPoints(handRight): handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 3): handRightX.append(handRight[x]) for x in range(1, len(handRight), 3): handRightY.append(handRight[x]) for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) return handRightPoints
def confidencePoints(handRight): handRightC = [] for x in range(2, len(handRight), 3): handRightC.append(handRight[x]) return handRightC
def confidence(handRight): sum = handRight[0] for x in range(1, len(handRight)): sum += handRight[x] return sum
def seperate_points(handRight): handRightResults = [] handRightX = [] handRightY = [] for x in range(len(handRight)): handRightX.append(handRight[x][0]) handRightY.append(handRight[x][1]) for x in range(len(handRight)): handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return handRightResults
def join_points(handRight): handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) return handRightPoints
def isolatePoints(handRight): handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) minX = min(handRightX, key=float) minX -= 10 for x in range(len(handRightX)): handRightX[x] -= minX minY = min(handRightY, key=float) minY -= 10 for x in range(len(handRightY)): handRightY[x] -= minY for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def centerPoints(handRight): refX = 150 refY = 150 handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) p1 = [handRightX[0], handRightY[0]] p2 = [refX, refY] distanceX = (p1[0] - p2[0]) distanceY = (p1[1] - p2[1]) for x in range(len(handRightX)): handRightX[x] -= distanceX for x in range(len(handRightY)): handRightY[x] -= distanceY for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def dummy_centerPoints(handRight): refX = 600 refY = 600 handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) p1 = [handRightX[0], handRightY[0]] p2 = [refX, refY] distanceX = (p1[0] - p2[0]) distanceY = (p1[1] - p2[1]) for x in range(len(handRightX)): handRightX[x] -= distanceX for x in range(len(handRightY)): handRightY[x] -= distanceY for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def movePoints(handRight, addX, addY): refX = (handRight[0] + addX) refY = (handRight[1] + addY) handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) p1 = [handRightX[0], handRightY[0]] p2 = [refX, refY] distanceX = (p1[0] - p2[0]) distanceY = (p1[1] - p2[1]) for x in range(len(handRightX)): handRightX[x] -= distanceX for x in range(len(handRightY)): handRightY[x] -= distanceY for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def moveBothHands(handRight, handLeft, addX, addY): refX = (handRight[0] + addX) refY = (handRight[1] + addY) handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) p1 = [handRightX[0], handRightY[0]] p2 = [refX, refY] distanceX = (p1[0] - p2[0]) distanceY = (p1[1] - p2[1]) for x in range(len(handRightX)): handRightX[x] -= distanceX for x in range(len(handRightY)): handRightY[x] -= distanceY for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) refX = (handLeft[0] + addX) refY = (handLeft[1] + addY) handLeftResults = [] handLeftPoints = [] handLeftX = [] handLeftY = [] for x in range(0, len(handLeft), 2): handLeftX.append(handLeft[x]) for x in range(1, len(handLeft), 2): handLeftY.append(handLeft[x]) p1 = [handLeftX[0], handLeftY[0]] p2 = [refX, refY] distanceX = (p1[0] - p2[0]) distanceY = (p1[1] - p2[1]) for x in range(len(handLeftX)): if (handLeftX[x] != 0): handLeftX[x] -= distanceX for x in range(len(handLeftY)): if (handLeftX[x] != 0): handLeftY[x] -= distanceY for x in range(len(handLeftX)): handLeftPoints.append((int(handLeftX[x]), int(handLeftY[x]))) handLeftResults.append(handLeftX[x]) handLeftResults.append(handLeftY[x]) return (handRightResults, handRightPoints, handLeftResults, handLeftPoints)
def move_to_wrist(handRight, wristX, wristY): refX = wristX refY = wristY handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) p1 = [handRightX[0], handRightY[0]] p2 = [refX, refY] distanceX = (p1[0] - p2[0]) distanceY = (p1[1] - p2[1]) for x in range(len(handRightX)): handRightX[x] -= distanceX for x in range(len(handRightY)): handRightY[x] -= distanceY for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def scaleBody(handRight, distance): ref = 200 handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) scale = (ref / distance) for x in range(len(handRightX)): handRightX[x] *= scale for x in range(len(handRightY)): handRightY[x] *= scale for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def moveBody(handRight): refX = 1000 refY = 400 handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) p1 = [handRightX[1], handRightY[1]] p2 = [refX, refY] distanceX = (p1[0] - p2[0]) distanceY = (p1[1] - p2[1]) for x in range(len(handRightX)): if (handRightX[x] != 0): handRightX[x] -= distanceX for x in range(len(handRightY)): if (handRightY[x] != 0): handRightY[x] -= distanceY for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def dummyMoveBody(handRight): refX = 400 refY = 200 handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) p1 = [handRightX[1], handRightY[1]] p2 = [refX, refY] distanceX = (p1[0] - p2[0]) distanceY = (p1[1] - p2[1]) for x in range(len(handRightX)): if (handRightX[x] != 0): handRightX[x] -= distanceX for x in range(len(handRightY)): if (handRightY[x] != 0): handRightY[x] -= distanceY for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def dummyScaleBody(handRight, distance): ref = 500 handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) scale = (ref / distance) for x in range(len(handRightX)): handRightX[x] *= scale for x in range(len(handRightY)): handRightY[x] *= scale for x in range(len(handRightY)): handRightX[x] *= 2 handRightY[x] *= 2 for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def plot_skeleton(fileName, background, isMove, isScale): js = json.loads(open(fileName).read()) for items in js['people']: handRight = items['hand_right_keypoints_2d'] handCoord = helper.getCoordPoints(handRight) handPoints = helper.removePoints(handRight) p1 = [handPoints[0], handPoints[1]] p2 = [handPoints[18], handPoints[19]] distance = math.sqrt((((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))) if isScale: (handRightResult, handRightPoints) = scale.scalePoints(handPoints, distance) else: handRightResult = handPoints handRightPoints = handCoord if isMove: (handRightResult, handRightPoints) = move.centerPoints(handRightResult) p1 = [handRightResult[0], handRightResult[1]] p2 = [handRightResult[18], handRightResult[19]] distance = math.sqrt((((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))) frame = cv2.imread(('C:\\123Drive\\Python\\Sign_Language_Interpreter\\' + background)) for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], (0, 255, 255), 2) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=(- 1), lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 5, (0, 0, 255), thickness=(- 1), lineType=cv2.FILLED) return frame
def plot_points(points, background): handRight = points handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) frame = cv2.imread(('' + background)) for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], (0, 255, 255), 2) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=(- 1), lineType=cv2.FILLED) return frame
def plot_db(): ret_frame = [] POSE_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]] background = 'big_background.png' connection = sqlite3.connect('db\\main_dataset.db') crsr = connection.cursor() sql = 'SELECT x1,y1' for x in range(2, 22): sql = ((((sql + ',x') + str(x)) + ',y') + str(x)) sql = (sql + ' FROM rightHandDataset WHERE 1') crsr.execute(sql) feature_res = crsr.fetchall() for x in range(len(feature_res)): points = feature_res[x] handRight = points handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) frame = cv2.imread(background) for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], (0, 255, 255), 2) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=(- 1), lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 5, (0, 0, 255), thickness=(- 1), lineType=cv2.FILLED) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) ret_frame.append(frame) frame = cv2.imread(background) return ret_frame
def plot_db_label(label): ret_frame = [] POSE_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]] background = 'big_background.png' connection = sqlite3.connect('db\\main_dataset.db') crsr = connection.cursor() label = label.strip() label = (("'" + label) + "'") sql = 'SELECT x1,y1' for x in range(2, 22): sql = ((((sql + ',x') + str(x)) + ',y') + str(x)) sql = ((sql + ' FROM rightHandDataset WHERE label = ') + label) crsr.execute(sql) feature_res = crsr.fetchall() for x in range(len(feature_res)): points = feature_res[x] handRight = points handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) frame = cv2.imread(background) for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], (0, 255, 255), 2) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=(- 1), lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 5, (0, 0, 255), thickness=(- 1), lineType=cv2.FILLED) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) ret_frame.append(frame) frame = cv2.imread(background) return ret_frame
def plot_dataset(handRightPoints, color): ret_frame = [] POSE_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]] colors = [[0, 0, 130], [0, 0, 175], [0, 0, 210], [0, 0, 250], [0, 200, 160], [0, 180, 150], [0, 230, 186], [0, 255, 255], [82, 201, 8], [82, 204, 0], [92, 230, 0], [102, 252, 6], [197, 88, 17], [204, 82, 0], [179, 71, 0], [227, 94, 5], [204, 0, 163], [200, 0, 163], [196, 0, 163], [230, 0, 184]] color = color.capitalize() background = (color + '_background.jpg') frame = cv2.imread(('PSL\\' + background)) count = 0 for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): if (color == 'White'): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, colors[count], thickness=10, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 15, (0, 0, 0), thickness=5, lineType=(- 1)) else: cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=10, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 5, (255, 255, 255), thickness=15, lineType=cv2.FILLED) count += 1 ret_frame.append(frame) return frame
def save_old_dataset(handRightPoints, color, name): POSE_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]] colors = [[0, 0, 130], [0, 0, 175], [0, 0, 210], [0, 0, 250], [0, 200, 160], [0, 180, 150], [0, 230, 186], [0, 255, 255], [82, 201, 8], [82, 204, 0], [92, 230, 0], [102, 252, 6], [197, 88, 17], [204, 82, 0], [179, 71, 0], [227, 94, 5], [204, 0, 163], [200, 0, 163], [196, 0, 163], [230, 0, 184]] color = color.capitalize() background = (color + '_background.jpg') frame = cv2.imread(background) count = 0 for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): if (color == 'White'): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, colors[count], thickness=10, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 15, (0, 0, 0), thickness=5, lineType=(- 1)) else: cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=10, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 5, (255, 255, 255), thickness=15, lineType=cv2.FILLED) count += 1 os.chdir('temp_old_dataset_processing') cv2.imwrite((name + '.png'), frame) os.chdir('..')
def plotPose(posePoints, handRightPoints, handLeftPoints): POSE_PAIRS = [[1, 0], [1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [0, 15], [15, 17], [0, 16], [16, 18]] HAND_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]] colors = [[0, 0, 130], [0, 0, 175], [0, 0, 210], [0, 0, 250], [0, 200, 160], [0, 180, 150], [0, 230, 186], [0, 255, 255], [82, 201, 8], [82, 204, 0], [92, 230, 0], [102, 252, 6], [197, 88, 17], [204, 82, 0], [179, 71, 0], [227, 94, 5], [204, 0, 163], [200, 0, 163], [196, 0, 163], [230, 0, 184]] color = 'black' color = color.capitalize() background = (color + '_background.jpg') frame = cv2.imread(background) count = 0 for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (posePoints[partA] and posePoints[partB] and (posePoints[partA][0] != 0) and (posePoints[partA][1] != 0) and (posePoints[partB][0] != 0) and (posePoints[partB][1] != 0)): if (color == 'White'): cv2.line(frame, posePoints[partA], posePoints[partB], colors[count], 10) cv2.circle(frame, posePoints[partA], 5, colors[count], thickness=10, lineType=cv2.FILLED) cv2.circle(frame, posePoints[partB], 15, (0, 0, 0), thickness=5, lineType=(- 1)) else: cv2.line(frame, posePoints[partA], posePoints[partB], colors[count], 10) cv2.circle(frame, posePoints[partA], 5, (0, 0, 255), thickness=10, lineType=cv2.FILLED) cv2.circle(frame, posePoints[partB], 5, (255, 255, 255), thickness=15, lineType=cv2.FILLED) count += 1 count = 0 for pair in HAND_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): if (color == 'White'): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, colors[count], thickness=10, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 15, (0, 0, 0), thickness=5, lineType=(- 1)) else: cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=3, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 5, (255, 255, 255), thickness=4, lineType=cv2.FILLED) count += 1 count = 0 for pair in HAND_PAIRS: partA = pair[0] partB = pair[1] if (handLeftPoints[partA] and handLeftPoints[partB]): if (color == 'White'): cv2.line(frame, handLeftPoints[partA], handLeftPoints[partB], colors[count], 10) cv2.circle(frame, handLeftPoints[partA], 5, colors[count], thickness=10, lineType=cv2.FILLED) cv2.circle(frame, handLeftPoints[partB], 15, (0, 0, 0), thickness=5, lineType=(- 1)) else: cv2.line(frame, handLeftPoints[partA], handLeftPoints[partB], colors[count], 10) cv2.circle(frame, handLeftPoints[partA], 5, (0, 0, 255), thickness=3, lineType=cv2.FILLED) cv2.circle(frame, handLeftPoints[partB], 5, (255, 255, 255), thickness=4, lineType=cv2.FILLED) count += 1 frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) return frame
def plotPoseDataset(): POSE_PAIRS = [[1, 0], [1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [0, 9], [9, 11], [0, 10], [10, 12]] HAND_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]] colors = [[0, 0, 130], [0, 0, 175], [0, 0, 210], [0, 0, 250], [0, 200, 160], [0, 180, 150], [0, 230, 186], [0, 255, 255], [82, 201, 8], [82, 204, 0], [92, 230, 0], [102, 252, 6], [197, 88, 17], [204, 82, 0], [179, 71, 0], [227, 94, 5], [204, 0, 163], [200, 0, 163], [196, 0, 163], [230, 0, 184]] '\n extracting data from db\n ' connection = sqlite3.connect('..\\data\\db\\main_dataset.db') crsr = connection.cursor() sql = 'SELECT Rx1,Ry1' for x in range(2, 22): sql = ((((sql + ',Rx') + str(x)) + ',Ry') + str(x)) for x in range(1, 22): sql = ((((sql + ',Lx') + str(x)) + ',Ly') + str(x)) for x in range(1, 14): sql = ((((sql + ',Px') + str(x)) + ',Py') + str(x)) sql = (sql + ' FROM poseDataset WHERE 1') crsr.execute(sql) feature_res = crsr.fetchall() feature_res = np.asarray(feature_res) features = [] for x in feature_res: features.append(x) print(features[0][22]) for i in range(len(features)): posePoints = [] for x in range(84, 110, 2): posePoints.append((int(features[i][x]), int(features[i][(x + 1)]))) handRightPoints = [] for x in range(0, 42, 2): handRightPoints.append((int(features[i][x]), int(features[i][(x + 1)]))) handLeftPoints = [] for x in range(0, 42, 2): handLeftPoints.append((int(features[i][x]), int(features[i][(x + 1)]))) color = 'black' color = color.capitalize() background = (color + '_background.jpg') frame = cv2.imread(background) count = 0 for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (posePoints[partA] and posePoints[partB] and (posePoints[partA][0] != 0) and (posePoints[partA][1] != 0) and (posePoints[partB][0] != 0) and (posePoints[partB][1] != 0)): if (color == 'White'): cv2.line(frame, posePoints[partA], posePoints[partB], colors[count], 10) cv2.circle(frame, posePoints[partA], 5, colors[count], thickness=10, lineType=cv2.FILLED) cv2.circle(frame, posePoints[partB], 15, (0, 0, 0), thickness=5, lineType=(- 1)) else: cv2.line(frame, posePoints[partA], posePoints[partB], colors[count], 10) cv2.circle(frame, posePoints[partA], 5, (0, 0, 255), thickness=10, lineType=cv2.FILLED) cv2.circle(frame, posePoints[partB], 5, (255, 255, 255), thickness=15, lineType=cv2.FILLED) count += 1 count = 0 for pair in HAND_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): if (color == 'White'): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, colors[count], thickness=10, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 15, (0, 0, 0), thickness=5, lineType=(- 1)) else: cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=3, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 5, (255, 255, 255), thickness=4, lineType=cv2.FILLED) count += 1 count = 0 for pair in HAND_PAIRS: partA = pair[0] partB = pair[1] if (handLeftPoints[partA] and handLeftPoints[partB]): if (color == 'White'): cv2.line(frame, handLeftPoints[partA], handLeftPoints[partB], colors[count], 10) cv2.circle(frame, handLeftPoints[partA], 5, colors[count], thickness=10, lineType=cv2.FILLED) cv2.circle(frame, handLeftPoints[partB], 15, (0, 0, 0), thickness=5, lineType=(- 1)) else: cv2.line(frame, handLeftPoints[partA], handLeftPoints[partB], colors[count], 10) cv2.circle(frame, handLeftPoints[partA], 5, (0, 0, 255), thickness=3, lineType=cv2.FILLED) cv2.circle(frame, handLeftPoints[partB], 5, (255, 255, 255), thickness=4, lineType=cv2.FILLED) count += 1 frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) fig2 = plt.figure(figsize=(10, 10)) ax3 = fig2.add_subplot(111) ax3.imshow(frame, interpolation='none') plt.imshow(frame) plt.show()
def rotate(point, angle, center_point=(0, 0)): 'Rotates a point around center_point(origin by default)\n Angle is in degrees.\n Rotation is counter-clockwise\n ' angle_rad = radians((angle % 360)) new_point = ((point[0] - center_point[0]), (point[1] - center_point[1])) new_point = (((new_point[0] * cos(angle_rad)) - (new_point[1] * sin(angle_rad))), ((new_point[0] * sin(angle_rad)) + (new_point[1] * cos(angle_rad)))) new_point = (int((new_point[0] + center_point[0])), int((new_point[1] + center_point[1]))) return new_point
def rotate_file(fileName): js = json.loads(open(fileName).read()) for items in js['people']: handRight = items['hand_right_keypoints_2d'] handPoints = helper.removePoints(handRight) p1 = [handPoints[0], handPoints[1]] p2 = [handPoints[18], handPoints[19]] distance = math.sqrt((((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))) (Result, Points) = scale.scalePoints(handPoints, distance) (handRightResults, handRightPoints) = move.centerPoints(Result) newPoints = [handRightPoints[0]] for x in range(1, len(handRightPoints)): newPoints.append(rotate(handRightPoints[x], (- 60), handRightPoints[0])) newPoints = helper.seperate_points(newPoints) return newPoints
def rotate_points(points, angle): coordPoints = helper.join_points(points) newPoints = [coordPoints[0]] for x in range(1, len(coordPoints)): newPoints.append(rotate(coordPoints[x], angle, coordPoints[0])) return newPoints
def rotate_line(origin, point, angle): '\n Rotate a point counterclockwise by a given angle around a given origin.\n\n The angle should be given in radians.\n ' (ox, oy) = origin (px, py) = point qx = ((ox + (math.cos(angle) * (px - ox))) - (math.sin(angle) * (py - oy))) qy = ((oy + (math.sin(angle) * (px - ox))) + (math.cos(angle) * (py - oy))) return (qx, qy)
def scalePoints(handRight, distance): ref = 50 handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) scale = (ref / distance) for x in range(len(handRightX)): handRightX[x] *= scale for x in range(len(handRightY)): handRightY[x] *= scale for x in range(len(handRightY)): handRightX[x] *= 2 handRightY[x] *= 2 for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def dummy_scalePoints(handRight, distance): ref = 200 handRightResults = [] handRightPoints = [] handRightX = [] handRightY = [] for x in range(0, len(handRight), 2): handRightX.append(handRight[x]) for x in range(1, len(handRight), 2): handRightY.append(handRight[x]) scale = (ref / distance) for x in range(len(handRightX)): handRightX[x] *= scale for x in range(len(handRightY)): handRightY[x] *= scale for x in range(len(handRightY)): handRightX[x] *= 2 handRightY[x] *= 2 for x in range(len(handRightX)): handRightPoints.append((int(handRightX[x]), int(handRightY[x]))) handRightResults.append(handRightX[x]) handRightResults.append(handRightY[x]) return (handRightResults, handRightPoints)
def synthesize(angle): '\n extracting data from db\n ' connection = sqlite3.connect('data\\db\\main_dataset.db') crsr = connection.cursor() sql = 'SELECT x1,y1' for x in range(2, 22): sql = ((((sql + ',x') + str(x)) + ',y') + str(x)) sql = (sql + ' FROM rightHandDataset WHERE 1') crsr.execute(sql) feature_res = crsr.fetchall() features = [] for x in feature_res: features.append(x) crsr.execute('SELECT label FROM rightHandDataset WHERE 1') label_res = crsr.fetchall() labels = [] for x in label_res: labels.append(x) connection = sqlite3.connect('data\\db\\main_dataset.db') crsr = connection.cursor() for x in range(len(features)): rotated = rotate.rotate_points(features[x], (- angle)) handRightResults = helper.seperate_points(rotated) parentName = (("'" + str(labels[x][0])) + "'") sql_command = (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((('INSERT INTO rightHandDataset VALUES (NULL, ' + str(handRightResults[0])) + ', ') + str(handRightResults[1])) + ',') + str(handRightResults[2])) + ',') + str(handRightResults[3])) + ',') + str(handRightResults[4])) + ',') + str(handRightResults[5])) + ',') + str(handRightResults[6])) + ',') + str(handRightResults[7])) + ',') + str(handRightResults[8])) + ',') + str(handRightResults[9])) + ',') + str(handRightResults[10])) + ',') + str(handRightResults[11])) + ',') + str(handRightResults[12])) + ',') + str(handRightResults[13])) + ',') + str(handRightResults[14])) + ',') + str(handRightResults[15])) + ',') + str(handRightResults[16])) + ',') + str(handRightResults[17])) + ',') + str(handRightResults[18])) + ',') + str(handRightResults[19])) + ',') + str(handRightResults[20])) + ',') + str(handRightResults[21])) + ',') + str(handRightResults[22])) + ',') + str(handRightResults[23])) + ',') + str(handRightResults[24])) + ',') + str(handRightResults[25])) + ',') + str(handRightResults[26])) + ',') + str(handRightResults[27])) + ',') + str(handRightResults[28])) + ',') + str(handRightResults[29])) + ',') + str(handRightResults[30])) + ',') + str(handRightResults[31])) + ',') + str(handRightResults[32])) + ',') + str(handRightResults[33])) + ',') + str(handRightResults[34])) + ',') + str(handRightResults[35])) + ',') + str(handRightResults[36])) + ',') + str(handRightResults[37])) + ',') + str(handRightResults[38])) + ',') + str(handRightResults[39])) + ',') + str(handRightResults[40])) + ',') + str(handRightResults[41])) + ',') + parentName) + ');') crsr.execute(sql_command) rotated = rotate.rotate_points(features[x], angle) handRightResults = helper.seperate_points(rotated) sql_command = (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((('INSERT INTO rightHandDataset VALUES (NULL, ' + str(handRightResults[0])) + ', ') + str(handRightResults[1])) + ',') + str(handRightResults[2])) + ',') + str(handRightResults[3])) + ',') + str(handRightResults[4])) + ',') + str(handRightResults[5])) + ',') + str(handRightResults[6])) + ',') + str(handRightResults[7])) + ',') + str(handRightResults[8])) + ',') + str(handRightResults[9])) + ',') + str(handRightResults[10])) + ',') + str(handRightResults[11])) + ',') + str(handRightResults[12])) + ',') + str(handRightResults[13])) + ',') + str(handRightResults[14])) + ',') + str(handRightResults[15])) + ',') + str(handRightResults[16])) + ',') + str(handRightResults[17])) + ',') + str(handRightResults[18])) + ',') + str(handRightResults[19])) + ',') + str(handRightResults[20])) + ',') + str(handRightResults[21])) + ',') + str(handRightResults[22])) + ',') + str(handRightResults[23])) + ',') + str(handRightResults[24])) + ',') + str(handRightResults[25])) + ',') + str(handRightResults[26])) + ',') + str(handRightResults[27])) + ',') + str(handRightResults[28])) + ',') + str(handRightResults[29])) + ',') + str(handRightResults[30])) + ',') + str(handRightResults[31])) + ',') + str(handRightResults[32])) + ',') + str(handRightResults[33])) + ',') + str(handRightResults[34])) + ',') + str(handRightResults[35])) + ',') + str(handRightResults[36])) + ',') + str(handRightResults[37])) + ',') + str(handRightResults[38])) + ',') + str(handRightResults[39])) + ',') + str(handRightResults[40])) + ',') + str(handRightResults[41])) + ',') + parentName) + ');') crsr.execute(sql_command) connection.commit() connection.close()
def synthesize_multiple(angle1, angle2): '\n extracting data from db\n ' connection = sqlite3.connect('..\\..\\data\\db\\main_dataset.db') crsr = connection.cursor() sql = 'SELECT x1,y1' for x in range(2, 22): sql = ((((sql + ',x') + str(x)) + ',y') + str(x)) sql = (sql + ' FROM rightHandDataset WHERE 1') crsr.execute(sql) feature_res = crsr.fetchall() features = [] for x in feature_res: features.append(x) crsr.execute('SELECT label FROM rightHandDataset WHERE 1') label_res = crsr.fetchall() labels = [] for x in label_res: labels.append(x) connection = sqlite3.connect('..\\..\\data\\db\\main_dataset.db') crsr = connection.cursor() for x in range(len(features)): '\n sythesizing at angle 1\n ' rotated = rotate.rotate_points(features[x], (- angle1)) handRightResults = helper.seperate_points(rotated) parentName = (("'" + str(labels[x][0])) + "'") sql_command = (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((('INSERT INTO rightHandDataset VALUES (NULL, ' + str(handRightResults[0])) + ', ') + str(handRightResults[1])) + ',') + str(handRightResults[2])) + ',') + str(handRightResults[3])) + ',') + str(handRightResults[4])) + ',') + str(handRightResults[5])) + ',') + str(handRightResults[6])) + ',') + str(handRightResults[7])) + ',') + str(handRightResults[8])) + ',') + str(handRightResults[9])) + ',') + str(handRightResults[10])) + ',') + str(handRightResults[11])) + ',') + str(handRightResults[12])) + ',') + str(handRightResults[13])) + ',') + str(handRightResults[14])) + ',') + str(handRightResults[15])) + ',') + str(handRightResults[16])) + ',') + str(handRightResults[17])) + ',') + str(handRightResults[18])) + ',') + str(handRightResults[19])) + ',') + str(handRightResults[20])) + ',') + str(handRightResults[21])) + ',') + str(handRightResults[22])) + ',') + str(handRightResults[23])) + ',') + str(handRightResults[24])) + ',') + str(handRightResults[25])) + ',') + str(handRightResults[26])) + ',') + str(handRightResults[27])) + ',') + str(handRightResults[28])) + ',') + str(handRightResults[29])) + ',') + str(handRightResults[30])) + ',') + str(handRightResults[31])) + ',') + str(handRightResults[32])) + ',') + str(handRightResults[33])) + ',') + str(handRightResults[34])) + ',') + str(handRightResults[35])) + ',') + str(handRightResults[36])) + ',') + str(handRightResults[37])) + ',') + str(handRightResults[38])) + ',') + str(handRightResults[39])) + ',') + str(handRightResults[40])) + ',') + str(handRightResults[41])) + ',') + parentName) + ');') crsr.execute(sql_command) rotated = rotate.rotate_points(features[x], angle1) handRightResults = helper.seperate_points(rotated) sql_command = (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((('INSERT INTO rightHandDataset VALUES (NULL, ' + str(handRightResults[0])) + ', ') + str(handRightResults[1])) + ',') + str(handRightResults[2])) + ',') + str(handRightResults[3])) + ',') + str(handRightResults[4])) + ',') + str(handRightResults[5])) + ',') + str(handRightResults[6])) + ',') + str(handRightResults[7])) + ',') + str(handRightResults[8])) + ',') + str(handRightResults[9])) + ',') + str(handRightResults[10])) + ',') + str(handRightResults[11])) + ',') + str(handRightResults[12])) + ',') + str(handRightResults[13])) + ',') + str(handRightResults[14])) + ',') + str(handRightResults[15])) + ',') + str(handRightResults[16])) + ',') + str(handRightResults[17])) + ',') + str(handRightResults[18])) + ',') + str(handRightResults[19])) + ',') + str(handRightResults[20])) + ',') + str(handRightResults[21])) + ',') + str(handRightResults[22])) + ',') + str(handRightResults[23])) + ',') + str(handRightResults[24])) + ',') + str(handRightResults[25])) + ',') + str(handRightResults[26])) + ',') + str(handRightResults[27])) + ',') + str(handRightResults[28])) + ',') + str(handRightResults[29])) + ',') + str(handRightResults[30])) + ',') + str(handRightResults[31])) + ',') + str(handRightResults[32])) + ',') + str(handRightResults[33])) + ',') + str(handRightResults[34])) + ',') + str(handRightResults[35])) + ',') + str(handRightResults[36])) + ',') + str(handRightResults[37])) + ',') + str(handRightResults[38])) + ',') + str(handRightResults[39])) + ',') + str(handRightResults[40])) + ',') + str(handRightResults[41])) + ',') + parentName) + ');') crsr.execute(sql_command) '\n sythesizing at angle 2\n ' rotated = rotate.rotate_points(features[x], (- angle2)) handRightResults = helper.seperate_points(rotated) parentName = (("'" + str(labels[x][0])) + "'") sql_command = (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((('INSERT INTO rightHandDataset VALUES (NULL, ' + str(handRightResults[0])) + ', ') + str(handRightResults[1])) + ',') + str(handRightResults[2])) + ',') + str(handRightResults[3])) + ',') + str(handRightResults[4])) + ',') + str(handRightResults[5])) + ',') + str(handRightResults[6])) + ',') + str(handRightResults[7])) + ',') + str(handRightResults[8])) + ',') + str(handRightResults[9])) + ',') + str(handRightResults[10])) + ',') + str(handRightResults[11])) + ',') + str(handRightResults[12])) + ',') + str(handRightResults[13])) + ',') + str(handRightResults[14])) + ',') + str(handRightResults[15])) + ',') + str(handRightResults[16])) + ',') + str(handRightResults[17])) + ',') + str(handRightResults[18])) + ',') + str(handRightResults[19])) + ',') + str(handRightResults[20])) + ',') + str(handRightResults[21])) + ',') + str(handRightResults[22])) + ',') + str(handRightResults[23])) + ',') + str(handRightResults[24])) + ',') + str(handRightResults[25])) + ',') + str(handRightResults[26])) + ',') + str(handRightResults[27])) + ',') + str(handRightResults[28])) + ',') + str(handRightResults[29])) + ',') + str(handRightResults[30])) + ',') + str(handRightResults[31])) + ',') + str(handRightResults[32])) + ',') + str(handRightResults[33])) + ',') + str(handRightResults[34])) + ',') + str(handRightResults[35])) + ',') + str(handRightResults[36])) + ',') + str(handRightResults[37])) + ',') + str(handRightResults[38])) + ',') + str(handRightResults[39])) + ',') + str(handRightResults[40])) + ',') + str(handRightResults[41])) + ',') + parentName) + ');') crsr.execute(sql_command) rotated = rotate.rotate_points(features[x], angle2) handRightResults = helper.seperate_points(rotated) sql_command = (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((('INSERT INTO rightHandDataset VALUES (NULL, ' + str(handRightResults[0])) + ', ') + str(handRightResults[1])) + ',') + str(handRightResults[2])) + ',') + str(handRightResults[3])) + ',') + str(handRightResults[4])) + ',') + str(handRightResults[5])) + ',') + str(handRightResults[6])) + ',') + str(handRightResults[7])) + ',') + str(handRightResults[8])) + ',') + str(handRightResults[9])) + ',') + str(handRightResults[10])) + ',') + str(handRightResults[11])) + ',') + str(handRightResults[12])) + ',') + str(handRightResults[13])) + ',') + str(handRightResults[14])) + ',') + str(handRightResults[15])) + ',') + str(handRightResults[16])) + ',') + str(handRightResults[17])) + ',') + str(handRightResults[18])) + ',') + str(handRightResults[19])) + ',') + str(handRightResults[20])) + ',') + str(handRightResults[21])) + ',') + str(handRightResults[22])) + ',') + str(handRightResults[23])) + ',') + str(handRightResults[24])) + ',') + str(handRightResults[25])) + ',') + str(handRightResults[26])) + ',') + str(handRightResults[27])) + ',') + str(handRightResults[28])) + ',') + str(handRightResults[29])) + ',') + str(handRightResults[30])) + ',') + str(handRightResults[31])) + ',') + str(handRightResults[32])) + ',') + str(handRightResults[33])) + ',') + str(handRightResults[34])) + ',') + str(handRightResults[35])) + ',') + str(handRightResults[36])) + ',') + str(handRightResults[37])) + ',') + str(handRightResults[38])) + ',') + str(handRightResults[39])) + ',') + str(handRightResults[40])) + ',') + str(handRightResults[41])) + ',') + parentName) + ');') crsr.execute(sql_command) connection.commit() connection.close()
def re_train(mode): if (mode == 0): dbh.create_table() dbh.populate_db() synth.synthesize(20) alphabet_model.train_alphabets() if (mode == 1): dbh.create_pose_table() dbh.populate_words() word_model.train_words()
def match_ann(fileName): js = json.loads(open(fileName).read()) for items in js['people']: pose = items['pose_keypoints_2d'] handRight = items['hand_right_keypoints_2d'] handLeft = items['hand_left_keypoints_2d'] RightConfPoints = helper.confidencePoints(handRight) LeftConfPoints = helper.confidencePoints(handLeft) RightConfidence = helper.confidence(RightConfPoints) LeftConfidence = helper.confidence(LeftConfPoints) if (RightConfidence > 12): if ((LeftConfidence > 12) or (LeftConfidence < 2)): pose_points = helper.removePoints(pose) p1 = [pose_points[0], pose_points[1]] p2 = [pose_points[2], pose_points[3]] distance = math.sqrt((((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))) (scaled_results, scaled_points) = norm.scaleBody(pose_points, distance) (poseResults, posePoints) = norm.moveBody(scaled_results) hand_right_points = helper.removePoints(handRight) p1 = [hand_right_points[0], hand_right_points[1]] p2 = [hand_right_points[18], hand_right_points[19]] distance = math.sqrt((((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))) (RightResult, Points) = scale.scalePoints(hand_right_points, distance) (handRightResults, handRightPoints) = norm.move_to_wrist(RightResult, poseResults[8], poseResults[9]) if (LeftConfidence > 3): hand_left_points = helper.removePoints(handLeft) p1 = [hand_left_points[0], hand_left_points[1]] p2 = [hand_left_points[18], hand_left_points[19]] distance = math.sqrt((((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))) if (distance != 0): (LeftResult, Points) = scale.scalePoints(hand_left_points, distance) (handLeftResults, handLeftPoints) = norm.move_to_wrist(LeftResult, poseResults[14], poseResults[15]) else: (handLeftResults, handLeftPoints) = norm.move_to_wrist(hand_left_points, poseResults[14], poseResults[15]) else: handLeftResults = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] posePoints = [] for x in range(18): posePoints.append(poseResults[x]) for x in range(30, 38): posePoints.append(poseResults[x]) results = ((handRightResults + handLeftResults) + posePoints) connection = sqlite3.connect('data\\db\\main_dataset.db') crsr = connection.cursor() sql = 'SELECT Rx1,Ry1' for x in range(2, 22): sql = ((((sql + ',Rx') + str(x)) + ',Ry') + str(x)) for x in range(1, 22): sql = ((((sql + ',Lx') + str(x)) + ',Ly') + str(x)) for x in range(1, 14): sql = ((((sql + ',Px') + str(x)) + ',Py') + str(x)) sql = (sql + ' FROM poseDataset WHERE 1') crsr.execute(sql) feature_res = crsr.fetchall() feature_res = np.asarray(feature_res) features = [] for x in feature_res: features.append(x) crsr.execute('SELECT label FROM poseDataset WHERE 1') label_res = crsr.fetchall() labels = [] for x in label_res: labels.append(x) le = preprocessing.LabelEncoder() label_encoded = le.fit_transform(labels) label_encoded = to_categorical(label_encoded) (X_train, X_test, y_train, y_test) = train_test_split(features, label_encoded, test_size=0.2) scaler = StandardScaler().fit(X_train) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) y_pred = model.predict(scaler.transform(np.array([results]))) C = np.argmax(y_pred) result = le.inverse_transform([C]) return result[0] else: return 'no confidence' else: return 'no confidence'
def signal_handler(signal, frame): shutil.rmtree('Keypoints', ignore_errors=True, onerror=handleRemoveReadonly) shutil.rmtree('gui\\Learn_images', ignore_errors=True, onerror=handleRemoveReadonly) os.system('taskkill /f /im OpenPoseDemo.exe') print('All done') sys.exit(0)
def handleRemoveReadonly(func, path, exc): excvalue = exc[1] if ((func in (os.rmdir, os.remove)) and (excvalue.errno == errno.EACCES)): os.chmod(path, ((stat.S_IRWXU | stat.S_IRWXG) | stat.S_IRWXO)) func(path) else: raise Exception
@eel.expose def skip_Sign(): global skip_sign skip_sign = True print('skip_sign')
@eel.expose def openposelearn(): '\n Starting OpenPoseDemo.exe\n and storing json files to temporary folder [Keypoints]\n ' print('Starting OpenPose') os.chdir('bin\\openpose') subprocess.Popen('bin\\OpenPoseDemo.exe --hand --write_json ..\\..\\Keypoints --net_resolution 128x128 --number_people_max 1', shell=True) os.chdir('..\\..')
def plotPose(posePoints, handRightPoints, handLeftPoints): POSE_PAIRS = [[1, 0], [1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [0, 15], [15, 17], [0, 16], [16, 18]] HAND_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]] colors = [[0, 0, 130], [0, 0, 175], [0, 0, 210], [0, 0, 250], [0, 200, 160], [0, 180, 150], [0, 230, 186], [0, 255, 255], [82, 201, 8], [82, 204, 0], [92, 230, 0], [102, 252, 6], [197, 88, 17], [204, 82, 0], [179, 71, 0], [227, 94, 5], [204, 0, 163], [200, 0, 163], [196, 0, 163], [230, 0, 184]] background = 'PSL\\BLACK_background.jpg' frame = cv2.imread(background) count = 0 for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (posePoints[partA] and posePoints[partB] and (posePoints[partA][0] != 0) and (posePoints[partA][1] != 0) and (posePoints[partB][0] != 0) and (posePoints[partB][1] != 0)): cv2.line(frame, posePoints[partA], posePoints[partB], colors[count], 10) cv2.circle(frame, posePoints[partA], 5, (0, 0, 255), thickness=10, lineType=cv2.FILLED) cv2.circle(frame, posePoints[partB], 5, (255, 255, 255), thickness=15, lineType=cv2.FILLED) count += 1 count = 0 for pair in HAND_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=3, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 5, (255, 255, 255), thickness=4, lineType=cv2.FILLED) count += 1 count = 0 for pair in HAND_PAIRS: partA = pair[0] partB = pair[1] if (handLeftPoints[partA] and handLeftPoints[partB]): cv2.line(frame, handLeftPoints[partA], handLeftPoints[partB], colors[count], 10) cv2.circle(frame, handLeftPoints[partA], 5, (0, 0, 255), thickness=3, lineType=cv2.FILLED) cv2.circle(frame, handLeftPoints[partB], 5, (255, 255, 255), thickness=4, lineType=cv2.FILLED) count += 1 return frame
@eel.expose def learning(): global skip_sign '\n storing json files to temporary folder [Keypoints]\n Creating temp folder and initializing with zero padded json file\n ' dirName = 'Keypoints' fileName = 'PSL\\000000000000_keypoints.json' try: os.mkdir(dirName) shutil.copy(fileName, dirName) print('Directory ', dirName, ' Created ') except FileExistsError: print('Directory ', dirName, ' already exists') label = '' for x in range(len(fileNames)): skip_sign = False eel.get_Alphabet((x + 1)) while (label != labels[x]): for entry in os.scandir('Keypoints'): if entry.is_file(): if (os.path.splitext(entry)[1] == '.json'): filePlotName = entry.name try: js = json.loads(open(('Keypoints\\' + filePlotName)).read()) except ValueError: print('Decoding JSON has failed') pass for items in js['people']: pose = items['pose_keypoints_2d'] handRight = items['hand_right_keypoints_2d'] handLeft = items['hand_left_keypoints_2d'] pose_points = helper.removePoints(pose) posePoints = helper.join_points(pose_points) hand_right_Points = helper.removePoints(handRight) handRightPoints = helper.join_points(hand_right_Points) hand_left_points = helper.removePoints(handLeft) handLeftPoints = helper.join_points(hand_left_points) frame = plotPose(posePoints, handRightPoints, handLeftPoints) if (hand_right_Points[0] != 0): cv2.imwrite((('gui\\Learn_images\\' + filePlotName) + '.jpg'), frame) frame = cv2.imread('PSL\\BLACK_background.jpg') eel.get_fileName(filePlotName) eel.sleep(0.05) if (skip_sign == True): break try: for entry in os.scandir('Keypoints'): if entry.is_file(): if (os.path.splitext(entry)[1] == '.json'): fileName = entry.name try: label = alphabet.match_ann(('Keypoints\\' + fileName)) except: pass except UnboundLocalError: print('UnboundLocalError') eel.get_status() print('end while') return True
def on_close(page, sockets): print(page, 'closed') print('Still have sockets open to', sockets)
def signal_handler(signal, frame): shutil.rmtree('Keypoints', ignore_errors=True, onerror=handleRemoveReadonly) os.system('taskkill /f /im OpenPoseDemo.exe') print('All done') sys.exit(0)
def handleRemoveReadonly(func, path, exc): excvalue = exc[1] if ((func in (os.rmdir, os.remove)) and (excvalue.errno == errno.EACCES)): os.chmod(path, ((stat.S_IRWXU | stat.S_IRWXG) | stat.S_IRWXO)) func(path) else: raise Exception
def plotPose(posePoints, handRightPoints, handLeftPoints): POSE_PAIRS = [[1, 0], [1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [0, 15], [15, 17], [0, 16], [16, 18]] HAND_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]] colors = [[0, 0, 130], [0, 0, 175], [0, 0, 210], [0, 0, 250], [0, 200, 160], [0, 180, 150], [0, 230, 186], [0, 255, 255], [82, 201, 8], [82, 204, 0], [92, 230, 0], [102, 252, 6], [197, 88, 17], [204, 82, 0], [179, 71, 0], [227, 94, 5], [204, 0, 163], [200, 0, 163], [196, 0, 163], [230, 0, 184]] background = 'PSL\\BLACK_background.jpg' frame = cv2.imread(background) count = 0 for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if (posePoints[partA] and posePoints[partB] and (posePoints[partA][0] != 0) and (posePoints[partA][1] != 0) and (posePoints[partB][0] != 0) and (posePoints[partB][1] != 0)): cv2.line(frame, posePoints[partA], posePoints[partB], colors[count], 10) cv2.circle(frame, posePoints[partA], 5, (0, 0, 255), thickness=10, lineType=cv2.FILLED) cv2.circle(frame, posePoints[partB], 5, (255, 255, 255), thickness=15, lineType=cv2.FILLED) count += 1 count = 0 for pair in HAND_PAIRS: partA = pair[0] partB = pair[1] if (handRightPoints[partA] and handRightPoints[partB]): cv2.line(frame, handRightPoints[partA], handRightPoints[partB], colors[count], 10) cv2.circle(frame, handRightPoints[partA], 5, (0, 0, 255), thickness=3, lineType=cv2.FILLED) cv2.circle(frame, handRightPoints[partB], 5, (255, 255, 255), thickness=4, lineType=cv2.FILLED) count += 1 count = 0 for pair in HAND_PAIRS: partA = pair[0] partB = pair[1] if (handLeftPoints[partA] and handLeftPoints[partB]): cv2.line(frame, handLeftPoints[partA], handLeftPoints[partB], colors[count], 10) cv2.circle(frame, handLeftPoints[partA], 5, (0, 0, 255), thickness=3, lineType=cv2.FILLED) cv2.circle(frame, handLeftPoints[partB], 5, (255, 255, 255), thickness=4, lineType=cv2.FILLED) count += 1 return frame
@eel.expose def exit_openpose(): os.system('taskkill /f /im OpenPoseDemo.exe')
@eel.expose def openpose(): '\n Starting OpenPoseDemo.exe\n and storing json files to temporary folder [Keypoints]\n ' print('Starting OpenPose') os.chdir('bin\\openpose') subprocess.Popen('bin\\OpenPoseDemo.exe --hand --write_json ..\\..\\Keypoints --net_resolution 128x128 --number_people_max 1', shell=True) os.chdir('..\\..') '\n Creating temp folder and initializing with zero padded json file\n ' dirName = 'Keypoints' fileName = 'PSL\\000000000000_keypoints.json' try: os.mkdir(dirName) shutil.copy(fileName, dirName) print('Directory ', dirName, ' Created ') except FileExistsError: print('Directory ', dirName, ' already exists')
@eel.expose def match(speech, mode): global label, lastLabel '\n Load each .json file from Keypoints folder and\n predict the label\n ' for entry in os.scandir('Keypoints'): if entry.is_file(): if (os.path.splitext(entry)[1] == '.json'): filePlotName = entry.name try: js = json.loads(open(('Keypoints\\' + filePlotName)).read()) for items in js['people']: pose = items['pose_keypoints_2d'] handRight = items['hand_right_keypoints_2d'] handLeft = items['hand_left_keypoints_2d'] pose_points = helper.removePoints(pose) posePoints = helper.join_points(pose_points) hand_right_Points = helper.removePoints(handRight) handRightPoints = helper.join_points(hand_right_Points) hand_left_points = helper.removePoints(handLeft) handLeftPoints = helper.join_points(hand_left_points) frame = plotPose(posePoints, handRightPoints, handLeftPoints) cv2.imwrite((('gui\\Learn_images\\' + filePlotName) + '.jpg'), frame) frame = cv2.imread('PSL\\BLACK_background.jpg') eel.get_fileName(filePlotName) except: print('Decoding JSON has failed') pass try: if (mode == 0): label = alphabet.match_ann(('Keypoints\\' + filePlotName)) if (mode == 1): label = word.match_ann(('Keypoints\\' + filePlotName)) print(label) except Exception: pass if ((label != 'no match') and (label != 'no confidence') and (label != lastLabel)): lastLabel = label if (speech == 1): try: mp3 = (('data\\speech\\' + label) + '.mp3') mixer.init() mixer.music.load(mp3) mixer.music.play() except: pass return label
def test_file1_method1(): x = 5 y = 6 assert ((x + 1) == y), 'test failed' assert (x == y), 'test failed'
def test_file1_method2(): x = 5 y = 6 assert ((x + 1) == y), 'test failed'
class Vocabulary(dict): '\n Bi-directional look up dictionary for the vocabulary\n\n Args:\n (dict): the default python dict class is extended\n ' def __init__(self, vocabulary_file_name): with open(vocabulary_file_name) as vocabulary_file: for line in vocabulary_file: (key, value) = line.split() self[int(key)] = value self[0] = '<PAD>' def __setitem__(self, key, value): if (key in self): raise Exception('Repeat Key', key) if (value in self): raise Exception('Repeat value', value) dict.__setitem__(self, key, value) dict.__setitem__(self, value, key) def __delitem__(self, key): dict.__delitem__(self, self[key]) dict.__delitem__(self, key) def __len__(self): return (dict.__len__(self) // 2)
class QAData(): '\n Load the train/predecit/test data\n ' def __init__(self): self.vocabulary = Vocabulary('./data/vocab_all.txt') self.dec_timesteps = 150 self.enc_timesteps = 150 self.answers = pickle.load(open('./data/answers.pkl', 'rb')) self.training_set = pickle.load(open('./data/train.pkl', 'rb')) def pad(self, data, length): '\n pad the data to meet given length requirement\n\n Args:\n data (vector): vector of question or answer\n length(integer): length of desired vector\n ' from keras.preprocessing.sequence import pad_sequences return pad_sequences(data, maxlen=length, padding='post', truncating='post', value=0) def get_training_data(self): '\n Return training question and answers\n ' questions = [] good_answers = [] for (j, qa) in enumerate(self.training_set): questions.extend(([qa['question']] * len(qa['answers']))) good_answers.extend([self.answers[i] for i in qa['answers']]) questions = self.pad(questions, self.enc_timesteps) good_answers = self.pad(good_answers, self.dec_timesteps) bad_answers = self.pad(random.sample(list(self.answers.values()), len(good_answers)), self.dec_timesteps) return (questions, good_answers, bad_answers) def process_data(self, d): '\n Process the predection data\n ' indices = (d['good'] + d['bad']) answers = self.pad([self.answers[i] for i in indices], self.dec_timesteps) question = self.pad(([d['question']] * len(indices)), self.enc_timesteps) return (indices, answers, question) def process_test_data(self, question, answers): '\n Process the test data\n ' answer_unpadded = [] for answer in answers: print(answer.split(' ')) answer_unpadded.append([self.vocabulary[word] for word in answer.split(' ')]) answers = self.pad(answer_unpadded, self.dec_timesteps) question = self.pad(([[self.vocabulary[word] for word in question.split(' ')]] * len(answers)), self.enc_timesteps) return (answers, question)
class QAModel(): def get_cosine_similarity(self): dot = (lambda a, b: K.batch_dot(a, b, axes=1)) return (lambda x: (dot(x[0], x[1]) / K.maximum(K.sqrt((dot(x[0], x[0]) * dot(x[1], x[1]))), K.epsilon()))) def get_bilstm_model(self, embedding_file, vocab_size): '\n Return the bilstm training and prediction model\n\n Args:\n embedding_file (str): embedding file name\n vacab_size (integer): size of the vocabulary\n\n Returns:\n training_model: model used to train using cosine similarity loss\n prediction_model: model used to predict the similarity\n ' margin = 0.05 enc_timesteps = 150 dec_timesteps = 150 hidden_dim = 128 question = Input(shape=(enc_timesteps,), dtype='int32', name='question_base') answer = Input(shape=(dec_timesteps,), dtype='int32', name='answer') answer_good = Input(shape=(dec_timesteps,), dtype='int32', name='answer_good_base') answer_bad = Input(shape=(dec_timesteps,), dtype='int32', name='answer_bad_base') weights = np.load(embedding_file) qa_embedding = Embedding(input_dim=vocab_size, output_dim=weights.shape[1], mask_zero=True, weights=[weights]) bi_lstm = Bidirectional(LSTM(activation='tanh', dropout=0.2, units=hidden_dim, return_sequences=False)) question_embedding = qa_embedding(question) question_enc_1 = bi_lstm(question_embedding) answer_embedding = qa_embedding(answer) answer_enc_1 = bi_lstm(answer_embedding) similarity = self.get_cosine_similarity() question_answer_merged = merge(inputs=[question_enc_1, answer_enc_1], mode=similarity, output_shape=(lambda _: (None, 1))) lstm_model = Model(name='bi_lstm', inputs=[question, answer], outputs=question_answer_merged) good_similarity = lstm_model([question, answer_good]) bad_similarity = lstm_model([question, answer_bad]) loss = merge([good_similarity, bad_similarity], mode=(lambda x: K.relu(((margin - x[0]) + x[1]))), output_shape=(lambda x: x[0])) training_model = Model(inputs=[question, answer_good, answer_bad], outputs=loss, name='training_model') training_model.compile(loss=(lambda y_true, y_pred: y_pred), optimizer='rmsprop') prediction_model = Model(inputs=[question, answer_good], outputs=good_similarity, name='prediction_model') prediction_model.compile(loss=(lambda y_true, y_pred: y_pred), optimizer='rmsprop') return (training_model, prediction_model) def get_lstm_cnn_model(self, embedding_file, vocab_size): '\n Return the bilstm + cnn training and prediction model\n\n Args:\n embedding_file (str): embedding file name\n vacab_size (integer): size of the vocabulary\n\n Returns:\n training_model: model used to train using cosine similarity loss\n prediction_model: model used to predict the similarity\n ' margin = 0.05 hidden_dim = 200 enc_timesteps = 150 dec_timesteps = 150 weights = np.load(embedding_file) question = Input(shape=(enc_timesteps,), dtype='int32', name='question_base') answer = Input(shape=(dec_timesteps,), dtype='int32', name='answer_good_base') answer_good = Input(shape=(dec_timesteps,), dtype='int32', name='answer_good_base') answer_bad = Input(shape=(dec_timesteps,), dtype='int32', name='answer_bad_base') qa_embedding = Embedding(input_dim=vocab_size, output_dim=weights.shape[1], weights=[weights]) question_embedding = qa_embedding(question) answer_embedding = qa_embedding(answer) f_rnn = LSTM(hidden_dim, return_sequences=True) b_rnn = LSTM(hidden_dim, return_sequences=True) qf_rnn = f_rnn(question_embedding) qb_rnn = b_rnn(question_embedding) question_pool = merge([qf_rnn, qb_rnn], mode='concat', concat_axis=(- 1)) af_rnn = f_rnn(answer_embedding) ab_rnn = b_rnn(answer_embedding) answer_pool = merge([af_rnn, ab_rnn], mode='concat', concat_axis=(- 1)) cnns = [Convolution1D(filter_length=filter_length, nb_filter=500, activation='tanh', border_mode='same') for filter_length in [1, 2, 3, 5]] question_cnn = merge([cnn(question_pool) for cnn in cnns], mode='concat') answer_cnn = merge([cnn(answer_pool) for cnn in cnns], mode='concat') maxpool = Lambda((lambda x: K.max(x, axis=1, keepdims=False)), output_shape=(lambda x: (x[0], x[2]))) maxpool.supports_masking = True question_pool = maxpool(question_cnn) answer_pool = maxpool(answer_cnn) similarity = self.get_cosine_similarity() merged_model = merge([question_pool, answer_pool], mode=similarity, output_shape=(lambda _: (None, 1))) lstm_convolution_model = Model(inputs=[question, answer], outputs=merged_model, name='lstm_convolution_model') good_similarity = lstm_convolution_model([question, answer_good]) bad_similarity = lstm_convolution_model([question, answer_bad]) loss = merge([good_similarity, bad_similarity], mode=(lambda x: K.relu(((margin - x[0]) + x[1]))), output_shape=(lambda x: x[0])) prediction_model = Model(inputs=[question, answer_good], outputs=good_similarity, name='prediction_model') prediction_model.compile(loss=(lambda y_true, y_pred: y_pred), optimizer='rmsprop') training_model = Model(inputs=[question, answer_good, answer_bad], outputs=loss, name='training_model') training_model.compile(loss=(lambda y_true, y_pred: y_pred), optimizer='rmsprop') return (training_model, prediction_model)
def main(mode='test', question=None, answers=None): '\n This function is used to train, predict or test\n\n Args:\n mode (str): train/preddict/test\n question (str): this contains the question\n answers (list): this contains list of answers in string format\n\n Returns:\n index (integer): index of the most likely answer\n ' vocabulary = Vocabulary('./data/vocab_all.txt') embedding_file = './data/word2vec_100_dim.embeddings' qa_model = QAModel() (train_model, predict_model) = qa_model.get_lstm_cnn_model(embedding_file, len(vocabulary)) epoch = 1 if (mode == 'train'): for i in range(epoch): print('Training epoch', i) qa_data = QAData() (questions, good_answers, bad_answers) = qa_data.get_training_data() Y = np.zeros(shape=(questions.shape[0],)) train_model.fit([questions, good_answers, bad_answers], Y, epochs=1, batch_size=64, validation_split=0.1, verbose=1) train_model.save_weights((('model/train_weights_epoch_' + str(epoch)) + '.h5'), overwrite=True) predict_model.save_weights((('model/predict_weights_epoch_' + str(epoch)) + '.h5'), overwrite=True) elif (mode == 'predict'): data = pickle.load(open('./data/dev.pkl', 'rb')) random.shuffle(data) qa_data = QAData() predict_model.load_weights('model/cnnlastm_predict_weights_epoch_1.h5') c = 0 c1 = 0 for (i, d) in enumerate(data): print(i, len(data)) (indices, answers, question) = qa_data.process_data(d) sims = predict_model.predict([question, answers]) n_good = len(d['good']) max_r = np.argmax(sims) max_n = np.argmax(sims[:n_good]) r = rankdata(sims, method='max') c += (1 if (max_r == max_n) else 0) c1 += (1 / float(((r[max_r] - r[max_n]) + 1))) precision = (c / float(len(data))) mrr = (c1 / float(len(data))) print('Precision', precision) print('MRR', mrr) elif (mode == 'test'): qa_data = QAData() (answers, question) = qa_data.process_test_data(question, answers) predict_model.load_weights('model/cnnlastm_predict_weights_epoch_1.h5') sims = predict_model.predict([question, answers]) max_r = np.argmax(sims) return max_r
def test(question, answers): return main(mode='test', question=question, answers=answers)
class S(SimpleHTTPRequestHandler): def do_POST(self): print('incomming http: ', self.path) content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length).decode('utf-8') post_data = json.loads(post_data) question = post_data['question'] answers = post_data['answers'].split('||') response = answers[test(question, answers)] self.send_response(200) self.wfile.write(response.encode())
def run(server_class=HTTPServer, handler_class=S, port=80): server_address = ('', port) httpd = server_class(server_address, handler_class) print('Starting httpd...') httpd.serve_forever()
def get_width(size_kb): if (size_kb < 10): width = 32 elif (10 <= size_kb < 30): width = 64 elif (30 <= size_kb < 60): width = 128 elif (60 <= size_kb < 100): width = 256 elif (100 <= size_kb < 200): width = 384 elif (200 <= size_kb < 500): width = 512 elif (500 <= size_kb < 1000): width = 768 else: width = 1024 return width
def load_1d_dex(dex_file, max_size=80): file_size = (os.stat(dex_file).st_size >> 20) if (file_size < max_size): with open(dex_file, 'rb') as fp: hexstring = binascii.hexlify(fp.read()) byte_list = [int(hexstring[i:(i + 2)], 16) for i in range(0, len(hexstring), 2)] return np.array(byte_list, dtype=np.uint8)
def get_dex_info(dex_file): dex_info = defaultdict(int) with open(dex_file, 'rb') as f: dex = DalvikVMFormat(f.read()) dex_info['file_size'] = dex.get_header_item().file_size dex_info['header_size'] = dex.get_header_item().header_size dex_info['string_ids_size'] = dex.get_header_item().string_ids_size dex_info['string_ids_off'] = dex.get_header_item().string_ids_off dex_info['type_ids_size'] = dex.get_header_item().type_ids_size dex_info['type_ids_off'] = dex.get_header_item().type_ids_off dex_info['proto_ids_size'] = dex.get_header_item().proto_ids_size dex_info['proto_ids_off'] = dex.get_header_item().proto_ids_off dex_info['field_ids_size'] = dex.get_header_item().field_ids_size dex_info['field_ids_off'] = dex.get_header_item().field_ids_off dex_info['method_ids_size'] = dex.get_header_item().method_ids_size dex_info['method_ids_off'] = dex.get_header_item().method_ids_off dex_info['class_defs_size'] = dex.get_header_item().class_defs_size dex_info['class_defs_off'] = dex.get_header_item().class_defs_off dex_info['data_size'] = dex.get_header_item().data_size dex_info['data_off'] = dex.get_header_item().data_off dex_info['link_size'] = dex.get_header_item().link_size dex_info['link_off'] = dex.get_header_item().link_off return dex_info
def set_color(dex_info, dex_b, dex_r, dex_g): s0_end = dex_info['header_size'] dex_r[0:s0_end] = dex_b[0:s0_end] dex_b[0:s0_end] = 0 s7_idx = dex_info['data_off'] e7_idx = (s7_idx + dex_info['data_size']) dex_g[s7_idx:e7_idx] = dex_b[s7_idx:e7_idx] dex_b[s7_idx:e7_idx] = 0 return (dex_r, dex_g)
def get_linear(dex_array, size_kb): width = get_width(size_kb) height = int((len(dex_array) / width)) dex_array = dex_array[:(height * width)] dex_array_2d = np.reshape(dex_array, (height, width)) return dex_array_2d
def create_linear_image(dex_path): dex_info = get_dex_info(dex_path) dex_b = load_1d_dex(dex_path) dex_r = np.zeros(len(dex_b), dtype=np.uint8) dex_g = np.zeros(len(dex_b), dtype=np.uint8) (dex_r, dex_g) = set_color(dex_info, dex_b, dex_r, dex_g) file_kb = int((os.path.getsize(dex_path) / 1000)) b_c = get_linear(dex_b, file_kb) r_c = get_linear(dex_r, file_kb) g_c = get_linear(dex_g, file_kb) im = np.stack((r_c, g_c, b_c), axis=(- 1)) im = Image.fromarray(im) image_sizes = [512, 256, 128, 64, 32] for size in image_sizes: image_path = (dex_path.rsplit('/', 1)[0].replace('temp_data/', 'image_data_benign/{}/'.format(size)) + '.png') os.makedirs(os.path.dirname(image_path), exist_ok=True) im_resized = im.resize(size=(size, size), resample=Image.ANTIALIAS) im_resized.save(image_path)
def binary_focal_loss(gamma=2.0, alpha=0.25): '\n Binary form of focal loss.\n\n FL(p_t) = -alpha * (1 - p_t)**gamma * log(p_t)\n\n where p = sigmoid(x), p_t = p or 1 - p depending on if the label is 1 or 0, respectively.\n\n References:\n https://arxiv.org/pdf/1708.02002.pdf\n Usage:\n model.compile(loss=[binary_focal_loss(alpha=.25, gamma=2)], metrics=["accuracy"], optimizer=adam)\n\n ' def binary_focal_loss_fixed(y_true, y_pred): '\n :param y_true: A tensor of the same shape as `y_pred`\n :param y_pred: A tensor resulting from a sigmoid\n :return: Output tensor.\n ' y_true = tf.cast(y_true, tf.float32) epsilon = K.epsilon() y_pred = K.clip(y_pred, epsilon, (1.0 - epsilon)) p_t = tf.where(K.equal(y_true, 1), y_pred, (1 - y_pred)) alpha_factor = (K.ones_like(y_true) * alpha) alpha_t = tf.where(K.equal(y_true, 1), alpha_factor, (1 - alpha_factor)) cross_entropy = (- K.log(p_t)) weight = (alpha_t * K.pow((1 - p_t), gamma)) loss = (weight * cross_entropy) loss = K.mean(K.sum(loss, axis=1)) return loss return binary_focal_loss_fixed
def categorical_focal_loss(alpha, gamma=2.0): '\n Softmax version of focal loss.\n When there is a skew between different categories/labels in your data set, you can try to apply this function as a\n loss.\n m\n FL = ∑ -alpha * (1 - p_o,c)^gamma * y_o,c * log(p_o,c)\n c=1\n\n where m = number of classes, c = class and o = observation\n\n Parameters:\n alpha -- the same as weighing factor in balanced cross entropy. Alpha is used to specify the weight of different\n categories/labels, the size of the array needs to be consistent with the number of classes.\n gamma -- focusing parameter for modulating factor (1-p)\n\n Default value:\n gamma -- 2.0 as mentioned in the paper\n alpha -- 0.25 as mentioned in the paper\n\n References:\n Official paper: https://arxiv.org/pdf/1708.02002.pdf\n https://www.tensorflow.org/api_docs/python/tf/keras/backend/categorical_crossentropy\n\n Usage:\n model.compile(loss=[categorical_focal_loss(alpha=[[.25, .25, .25]], gamma=2)], metrics=["accuracy"], optimizer=adam)\n ' alpha = np.array(alpha, dtype=np.float32) def categorical_focal_loss_fixed(y_true, y_pred): '\n :param y_true: A tensor of the same shape as `y_pred`\n :param y_pred: A tensor resulting from a softmax\n :return: Output tensor.\n ' epsilon = K.epsilon() y_pred = K.clip(y_pred, epsilon, (1.0 - epsilon)) cross_entropy = ((- y_true) * K.log(y_pred)) loss = ((alpha * K.pow((1 - y_pred), gamma)) * cross_entropy) return K.mean(K.sum(loss, axis=(- 1))) return categorical_focal_loss_fixed
def get_effective_class_weights(args): '\n Determines class weighting according to the following paper\n - https://arxiv.org/abs/1901.05555\n ' (unique, class_frequencies) = np.unique(args['y_train'], return_counts=True) effective_num = [((1 - args['reweight_beta']) / (1 - np.power(args['reweight_beta'], c_i))) for c_i in class_frequencies] class_weights = ((effective_num / sum(effective_num)) * args['num_classes']) print('calculated class frequencies') class_weights = {k: v for (k, v) in enumerate(class_weights)} return class_weights
def get_loss(args): if (args['reweight'] == 'effective_num'): class_weights = get_effective_class_weights(args) else: class_weights = {i: 1 for i in range(args['num_classes'])} if (args['loss'] == 'categorical_focal_loss'): if (type(class_weights) is dict): alpha = [class_weights[i] for i in class_weights.keys()] else: alpha = class_weights loss = [categorical_focal_loss(alpha=[alpha], gamma=2)] class_weights = {i: (1.0 / args['num_classes']) for i in range(args['num_classes'])} else: loss = args['loss'] return (loss, class_weights)
def filter_types(args, lines): types_to_exclude = ['adware', 'trojan', 'benign', 'riskware'] filtered_files = [] files = [((args['image_dir'] + file.strip()) + '.png') for file in lines] for file in files: mtype = file.split('malnet-images/')[1].rsplit('/', 2)[0] if (mtype not in types_to_exclude): filtered_files.append(file) return filtered_files
def get_split_info(args): with open((os.getcwd() + '/split_info/{}/train.txt'.format(args['group'])), 'r') as f: lines_train = f.readlines() with open((os.getcwd() + '/split_info/{}/val.txt'.format(args['group'])), 'r') as f: lines_val = f.readlines() with open((os.getcwd() + '/split_info/{}/test.txt'.format(args['group'])), 'r') as f: lines_test = f.readlines() if args['malnet_tiny']: files_train = filter_types(args, lines_train) files_val = filter_types(args, lines_val) files_test = filter_types(args, lines_test) else: files_train = [((args['image_dir'] + file.strip()) + '.png') for file in lines_train] files_val = [((args['image_dir'] + file.strip()) + '.png') for file in lines_val] files_test = [((args['image_dir'] + file.strip()) + '.png') for file in lines_test] if (args['group'] == 'type'): labels = sorted(list(set([file.split('malnet-images/')[1].rsplit('/', 2)[0] for file in files_train]))) label_dict = {t: idx for (idx, t) in enumerate(labels)} train_labels = [label_dict[file.split('malnet-images/')[1].rsplit('/', 2)[0]] for file in files_train] val_labels = [label_dict[file.split('malnet-images/')[1].rsplit('/', 2)[0]] for file in files_val] test_labels = [label_dict[file.split('malnet-images/')[1].rsplit('/', 2)[0]] for file in files_test] elif (args['group'] == 'family'): labels = sorted(list(set([file.split('malnet-images/')[1].rsplit('/', 2)[1] for file in files_train]))) label_dict = {t: idx for (idx, t) in enumerate(labels)} train_labels = [label_dict[file.split('malnet-images/')[1].rsplit('/', 2)[1]] for file in files_train] val_labels = [label_dict[file.split('malnet-images/')[1].rsplit('/', 2)[1]] for file in files_val] test_labels = [label_dict[file.split('malnet-images/')[1].rsplit('/', 2)[1]] for file in files_test] elif (args['group'] == 'binary'): labels = ['benign', 'malicious'] label_dict = {t: idx for (idx, t) in enumerate(labels)} train_labels = [(0 if ('benign' in file.split('malnet-images/')[1].rsplit('/', 2)[0]) else 1) for file in files_train] val_labels = [(0 if ('benign' in file.split('malnet-images/')[1].rsplit('/', 2)[0]) else 1) for file in files_val] test_labels = [(0 if ('benign' in file.split('malnet-images/')[1].rsplit('/', 2)[0]) else 1) for file in files_test] else: print('Group does not exist') exit(1) print('Number of train samples: {}, val samples: {}, test samples: {}'.format(len(files_train), len(files_val), len(files_test))) return (files_train, files_val, files_test, train_labels, val_labels, test_labels, label_dict)
def create_image_symlinks(args): print('Creating image symlinks') (files_train, files_val, files_test, _, _, _, _) = get_split_info(args) dst_dir = (args['data_dir'] + 'malnet_tiny={}/{}/'.format(args['malnet_tiny'], args['group'])) for src_path in files_train: dst_path = src_path.replace(args['image_dir'], (dst_dir + 'train/')) if (args['group'] == 'binary'): if ('benign' not in dst_path): dst_path = ((dst_path.split('train/')[0] + 'train/malicious/') + dst_path.split('train/')[1].split('/')[2]) else: dst_path = ((dst_path.split('train/')[0] + 'train/benign/') + dst_path.split('train/')[1].split('/')[2]) elif (args['group'] == 'family'): dst_path = ((dst_path.split('train/')[0] + 'train/') + '/'.join(dst_path.split('train/')[1].split('/')[1:3])) if (not os.path.exists(dst_path)): os.makedirs(os.path.dirname(dst_path), exist_ok=True) os.symlink(src_path, dst_path) for src_path in files_val: dst_path = src_path.replace(args['image_dir'], (dst_dir + 'val/')) if (args['group'] == 'binary'): if ('benign' not in dst_path): dst_path = ((dst_path.split('val/')[0] + 'val/malicious/') + dst_path.split('val/')[1].split('/')[2]) else: dst_path = ((dst_path.split('val/')[0] + 'val/benign/') + dst_path.split('val/')[1].split('/')[2]) elif (args['group'] == 'family'): dst_path = ((dst_path.split('val/')[0] + 'val/') + '/'.join(dst_path.split('val/')[1].split('/')[1:3])) if (not os.path.exists(dst_path)): os.makedirs(os.path.dirname(dst_path), exist_ok=True) os.symlink(src_path, dst_path) for src_path in files_test: dst_path = src_path.replace(args['image_dir'], (dst_dir + 'test/')) if (args['group'] == 'binary'): if ('benign' not in dst_path): dst_path = ((dst_path.split('test/')[0] + 'test/malicious/') + dst_path.split('test/')[1].split('/')[2]) else: dst_path = ((dst_path.split('test/')[0] + 'test/benign/') + dst_path.split('test/')[1].split('/')[2]) elif (args['group'] == 'family'): dst_path = ((dst_path.split('test/')[0] + 'test/') + '/'.join(dst_path.split('test/')[1].split('/')[1:3])) if (not os.path.exists(dst_path)): os.makedirs(os.path.dirname(dst_path), exist_ok=True) os.symlink(src_path, dst_path) print('Finished creating symlinks')
def plot_results(graph, steps, results, title): plt.figure(figsize=(6.4, 4.8)) for (method, result) in results.items(): result = [(r / len(graph)) for r in result] plt.plot(list(range(steps)), result, label=method) plt.ylim(0, 1) plt.ylabel('LCC') plt.xlabel('N_rm / N') plt.title(title) plt.legend() save_dir = (os.getcwd() + '/plots/') os.makedirs(save_dir, exist_ok=True) plt.savefig(((save_dir + title) + '.pdf')) plt.show() plt.clf()
def main(): graph = graph_loader(graph_type='ky2', seed=1) params = {'runs': 1, 'steps': 30, 'seed': 1, 'attack': 'rb_node', 'attack_approx': int((0.1 * len(graph))), 'plot_transition': True, 'gif_animation': True, 'gif_snaps': True, 'edge_style': None, 'node_style': None, 'fa_iter': 20} print('Creating example visualization') a = Attack(graph, **params) a.run_simulation() node_attacks = ['rnd_node', 'id_node', 'rd_node', 'ib_node', 'rb_node'] edge_attacks = ['rnd_edge', 'id_edge', 'rd_edge', 'ib_edge', 'rb_edge'] params['runs'] = 10 params['steps'] = (len(graph) - 1) params['plot_transition'] = False params['gif_animation'] = False params['gif_snaps'] = False print('Running node attacks') results = defaultdict(str) for attack in node_attacks: params['attack'] = attack if (('rb' in attack) or ('ib' in attack)): params['attack_approx'] = int((0.1 * len(graph))) else: params['attack_approx'] = None a = Attack(graph, **params) results[attack] = a.run_simulation() plot_results(graph, params['steps'], results, title='water:node-attacks_runs={}'.format(params['runs'])) print('Running edge attacks') results = defaultdict(str) for attack in edge_attacks: params['attack'] = attack if (('rb' in attack) or ('ib' in attack)): params['attack_approx'] = int((0.1 * len(graph))) else: params['attack_approx'] = None a = Attack(graph, **params) results[attack] = a.run_simulation() plot_results(graph, params['steps'], results, title='water:edge-attacks_runs={}'.format(params['runs']))
def plot_results(graph, params, results, xlabel='Steps', line_label='', experiment=''): plt.figure(figsize=(6.4, 4.8)) title = '{}:step={},l={},r={},k_a={},attack={},k_d={},defense={}'.format(experiment, params['steps'], params['l'], params['r'], params['k_a'], params['attack'], params['k_d'], params['defense']) for (strength, result) in results.items(): result_norm = [(r / len(graph)) for r in result] plt.plot(result_norm, label='{}: {}'.format(line_label, strength)) plt.xlabel(xlabel) plt.ylabel(params['robust_measure']) plt.ylim(0, 1) save_dir = (((os.getcwd() + '/plots/') + experiment) + '/') os.makedirs(save_dir, exist_ok=True) plt.legend() plt.title(title) plt.savefig(((save_dir + title) + '.pdf')) plt.show() plt.clf()
def experiment_redundancy(graph): params = {'runs': 10, 'steps': 100, 'seed': 1, 'l': 0.8, 'r': 0.2, 'c': int((0.1 * len(graph))), 'k_a': 5, 'attack': 'id_node', 'attack_approx': None, 'k_d': 0, 'defense': None, 'robust_measure': 'largest_connected_component', 'plot_transition': False, 'gif_animation': False, 'edge_style': None, 'node_style': 'spectral', 'fa_iter': 2000} results = defaultdict(list) redundancy = np.arange(0, 0.5, 0.1) for (idx, r) in enumerate(redundancy): params['r'] = r if (idx == 2): params['plot_transition'] = True params['gif_animation'] = False params['gif_snaps'] = False else: params['plot_transition'] = False params['gif_animation'] = False params['gif_snaps'] = False cf = Cascading(graph, **params) results[r] = cf.run_simulation() plot_results(graph, params, results, xlabel='Steps', line_label='Redundancy', experiment='redundancy')
def experiment_attack(graph): params = {'runs': 10, 'steps': 100, 'seed': 1, 'l': 0.8, 'r': 0.4, 'c': int((0.1 * len(graph))), 'k_a': 5, 'attack': 'rnd_node', 'attack_approx': None, 'k_d': 0, 'defense': None, 'robust_measure': 'largest_connected_component', 'plot_transition': False, 'gif_animation': False, 'edge_style': None, 'node_style': 'spectral', 'fa_iter': 2000} results = defaultdict(list) attack_strength = np.arange(2, 11, 2) for (idx, k_a) in enumerate(attack_strength): params['k_a'] = k_a if (idx == 2): params['plot_transition'] = False params['gif_animation'] = False else: params['plot_transition'] = False params['gif_animation'] = False cf = Cascading(graph, **params) results[k_a] = cf.run_simulation() plot_results(graph, params, results, xlabel='Steps', line_label='k_a', experiment='rnd_node_attack') params['attack'] = 'id_node' results = defaultdict(list) for (idx, k_a) in enumerate(attack_strength): params['k_a'] = k_a if (idx == 2): params['plot_transition'] = False params['gif_animation'] = False else: params['plot_transition'] = False params['gif_animation'] = False cf = Cascading(graph, **params) results[k_a] = cf.run_simulation() plot_results(graph, params, results, xlabel='Steps', line_label='k_a', experiment='id_node_attack')
def experiment_defense(graph): params = {'runs': 10, 'steps': 100, 'seed': 1, 'l': 0.8, 'r': 0.2, 'c': int((0.1 * len(graph))), 'k_a': 5, 'attack': 'id_node', 'attack_approx': None, 'k_d': 0, 'defense': 'add_edge_preferential', 'robust_measure': 'largest_connected_component', 'plot_transition': False, 'gif_animation': False, 'edge_style': None, 'node_style': 'spectral', 'fa_iter': 2000} results = defaultdict(list) defense_strength = np.arange(10, 51, 10) for (idx, k_d) in enumerate(defense_strength): params['k_d'] = k_d if (idx == 2): params['plot_transition'] = False params['gif_animation'] = False else: params['plot_transition'] = False params['gif_animation'] = False cf = Cascading(graph, **params) results[k_d] = cf.run_simulation() plot_results(graph, params, results, xlabel='Steps', line_label='k_d', experiment='add_edge_pref') params['defense'] = 'pr_node' defense_strength = np.arange(1, 10, 2) results = defaultdict(list) for (idx, k_d) in enumerate(defense_strength): params['k_d'] = k_d if (idx == 2): params['plot_transition'] = False params['gif_animation'] = False else: params['plot_transition'] = False params['gif_animation'] = False cf = Cascading(graph, **params) results[k_d] = cf.run_simulation() plot_results(graph, params, results, xlabel='Steps', line_label='k_d', experiment='add_node_pr')
def main(): graph = electrical().copy() experiment_redundancy(graph)
def plot_results(graph, steps, results, title): plt.figure(figsize=(6.4, 4.8)) for (method, result) in results.items(): result = [(r / len(graph)) for r in result] plt.plot(list(range(steps)), result, label=method) plt.ylim(0, 1) plt.ylabel('LCC') plt.xlabel('N_rm / N') plt.title(title) plt.legend() save_dir = (os.getcwd() + '/plots/') os.makedirs(save_dir, exist_ok=True) plt.savefig(((save_dir + title) + '.pdf')) plt.show() plt.clf()
def main(): graph = graph_loader(graph_type='ky2', seed=1) params = {'runs': 10, 'steps': 30, 'seed': 1, 'k_a': 30, 'attack': 'rb_node', 'attack_approx': int((0.1 * len(graph))), 'defense': 'rewire_edge_preferential', 'plot_transition': False, 'gif_animation': False, 'edge_style': None, 'node_style': None, 'fa_iter': 20} edge_defenses = ['rewire_edge_random', 'rewire_edge_random_neighbor', 'rewire_edge_preferential_random', 'add_edge_random', 'add_edge_preferential'] print('Running edge defenses') results = defaultdict(str) for defense in edge_defenses: params['defense'] = defense a = Defense(graph, **params) results[defense] = a.run_simulation() plot_results(graph, params['steps'], results, title='water:edge_defense_runs={},attack={},'.format(params['runs'], params['attack']))
def plot_results(graph, params, results): plt.figure(figsize=(6.4, 4.8)) title = '{}_epidemic:diffusion={},method={},k={}'.format(params['model'], params['diffusion'], params['method'], params['k']) for (strength, result) in results.items(): result_norm = [(r / len(graph)) for r in result] plt.plot(result_norm, label='Effective strength: {}'.format(strength)) plt.xlabel('Steps') plt.ylabel('Infected Nodes') plt.legend() plt.yscale('log') plt.ylim(0.001, 1) plt.title(title) save_dir = (((os.getcwd() + '/plots/') + title) + '/') os.makedirs(save_dir, exist_ok=True) plt.savefig(((save_dir + title) + '.pdf')) plt.show() plt.clf()
def run_epidemic_experiment(params): graph = as_733().copy() results = defaultdict(list) b_list = np.arange(0, 0.005, 0.001) for (idx, b) in enumerate(b_list): params['b'] = b if (idx == 1): params['plot_transition'] = True params['gif_animation'] = True params['gif_snaps'] = True else: params['plot_transition'] = False params['gif_animation'] = False params['gif_snaps'] = False ds = Diffusion(graph, **params) result = ds.run_simulation() results[ds.get_effective_strength()] = result plot_results(graph, params, results)
def main(): sis_params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 1, 'steps': 5000, 'robust_measure': 'largest_connected_component', 'k': 15, 'diffusion': None, 'method': None, 'plot_transition': False, 'gif_animation': False, 'seed': 1, 'edge_style': 'bundled', 'node_style': 'force_atlas', 'fa_iter': 20} run_epidemic_experiment(sis_params) sis_params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 5000, 'robust_measure': 'largest_connected_component', 'k': 50, 'diffusion': 'max', 'method': 'add_edge_random', 'plot_transition': False, 'gif_animation': False, 'seed': 1, 'edge_style': 'bundled', 'node_style': 'force_atlas', 'fa_iter': 20} sis_params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 5000, 'robust_measure': 'largest_connected_component', 'k': 5, 'diffusion': 'min', 'method': 'ns_node', 'plot_transition': False, 'gif_animation': False, 'seed': 1, 'edge_style': 'bundled', 'node_style': 'force_atlas', 'fa_iter': 20} run_epidemic_experiment(sis_params)
def measure_time(graph, measure, timeout): start = time.time() if (measure in spectral_approx): k = 30 measure = measure.replace('_approx', '') elif (measure in graph_approx): k = int((0.1 * len(graph))) measure = measure.replace('_approx', '') else: k = np.inf result = run_measure(graph, measure, k, timeout=timeout) end = time.time() run_time = math.ceil((end - start)) if (result is None): run_time = None return (len(graph), run_time)
def parallelize_evaluation(graphs, measure, timeout): if (measure in not_parallelized): n_jobs = 1 else: n_jobs = len(graphs) data = Parallel(n_jobs=n_jobs)((delayed(measure_time)(graph, measure, timeout) for graph in graphs)) sorted(data, key=itemgetter(0)) run_times = [d[1] for d in data] return run_times
def test_scalability(timeout=10): results = defaultdict(list) nodes = [100, 1000, 10000, 100000, 1000000] graphs = [graph_loader(graph_type='CSF', n=n, seed=1) for n in nodes] measures = get_measures() measures = ((measures + graph_approx) + spectral_approx) for measure in tqdm(measures): run_times = parallelize_evaluation(graphs, measure, timeout) results[measure] = run_times color = plt.cm.gist_ncar(np.linspace(0, 0.9, len(measures))) mpl.rcParams['axes.prop_cycle'] = cycler.cycler('color', color) mpl.rcParams['legend.fontsize'] = 5 (fig, axes) = plt.subplots(ncols=5, figsize=(((5 * 6) - 1), 5)) for (measure, run_time) in results.items(): axes[0].plot(nodes, run_time, label=measure, linewidth=1, linestyle=measure_style[measure]) axes[0].set_xlabel('Number of nodes') axes[0].set_ylabel('Time in seconds') axes[1].plot(nodes, run_time, label=measure, linewidth=1, linestyle=measure_style[measure]) axes[1].set_xscale('log') axes[1].set_xlabel('Number of nodes (log-scale)') axes[1].set_ylabel('Time in seconds') axes[2].plot(nodes, run_time, label=measure, linewidth=1, linestyle=measure_style[measure]) axes[2].set_xscale('log') axes[2].set_yscale('log') axes[2].set_xlabel('Number of nodes (log-scale)') axes[2].set_ylabel('Time in seconds (log-scale)') axes[0].legend() plt.title('Clustered Scale Free Graph') save_dir = (os.getcwd() + '/plots/') os.makedirs(save_dir, exist_ok=True) plt.savefig((save_dir + 'scalability.pdf'))