def response_list_files(sock): response = ('\n'.join([ fid(f) + ';' + f + ';' + str(getsize(f)) for f in listdir(DIR) if isfile(join(DIR, f)) ]) or 'No files available at the moment.') + '\n' sock.sendall(response.encode('ascii'))
def upload(sock, filename=None): # Send command. sent = sock.sendall(SERVER_COMMAND.UPLOAD.command.name.encode('ascii')) if sent == 0: raise RuntimeError('Socket connection broken') # Handle ask for filename and filesize. msg = 'filename_filesize' if not recv_until(sock, len(msg), [msg]): raise RuntimeError('Protocol violation!') # Send file name and size. if not filename: filename = input('Filename: ') filesize = getsize(filename) sent = sock.sendall((filename + ';' + str(filesize)).encode('ascii')) if sent == 0: raise RuntimeError('Socket connection broken') # Handle upload begin. msg = 'ready to receive a file' if not recv_until(sock, len(msg), [msg]): raise RuntimeError('Protocol violation!') # Upload with open(filename, 'rb') as f: print(f'-> Uploading file ({filename})') sock.sendall(f.read()) # Verify upload. file_id = recv_until(sock, 32) # md5 -> 128 bit = 32 hex. if file_id == fid(filename): print('SUCCESS! File is not currupted..') else: print('ERROR! File is corrupted..')
def download(sock, filename=None): # Execute LIST_FILES command before to get filenames, sizes and ids. command = SERVER_COMMAND.LIST_FILES files = command.request(sock, False) msg = 'No files available at the moment.\n' if msg == files: print(msg) return # NOTE: Parsing should work..string matched regex before. files = list(map(lambda x: x.split(';'), files.split('\n')[:-1])) # Execute download command. sent = sock.sendall(SERVER_COMMAND.DOWNLOAD.command.name.encode('ascii')) if sent == 0: raise RuntimeError('Socket connection broken') # Handle ask for file id. msg = 'file_id' if not recv_until(sock, len(msg), [msg]): raise RuntimeError('Protocol violation!') # Get file id and size. file_id = None file_size = None if not filename: filename = input('Filename: ') files = list(filter(lambda x: filename == x[1], files)) if len(files) > 0: file_id = files[0][0] file_size = int(files[0][2]) else: raise RuntimeError('File does not exist!') # Send file id. sent = sock.sendall(file_id.encode('ascii')) if sent == 0: raise RuntimeError('Socket connection broken') # Handle file byte stream. response = recv_until(sock, file_size, decoding=None) if not response: raise RuntimeError('Protocol violation!') print('-> Receiveing ', end='') print(response[:20], end='') print('...') if isfile(filename): # NOTE: not specified. filename = filename + '.download' with open(filename, 'wb') as f: f.write(response) if file_id == fid(filename): print('SUCCESS! File is not currupted..') else: print('ERROR! File is corrupted..')
def response_download(sock): # Ask for file id. sock.sendall('file_id'.encode('ascii')) file_id = recv_until(sock, 32, '^[a-zA-Z0-9]{32}$') if not file_id: raise RuntimeError('Protocol violation!') for p in listdir(DIR): path = join(DIR, p) if isfile(path) and fid(path) == file_id: with open(path, 'rb') as f: print(f'-> Sending file ({path})') sock.sendall(f.read()) return raise RuntimeError('Invalid file id!')
def validation_epoch_end( self, outputs: List[Tuple[torch.Tensor, torch.Tensor]]) -> None: if isinstance(self.val_dataloader().dataset, ImageLoader): self.val_dataloader().dataset.val = False else: self.val_dataloader().dataset.dataset.val = False fid_score = fid(self.forged_images, self.reference_images, self.hparams.feature_dimensionality_fid, self.device) ssim_score = ssim(self.forged_images, self.reference_images, data_range=255) psnr_score = psnr(self.forged_images, self.reference_images, data_range=255) self.log('FID_score', fid_score, on_step=False, on_epoch=True) self.log('SSIM', ssim_score, on_step=False, on_epoch=True) self.log('PSNR', psnr_score, on_step=False, on_epoch=True)
def response_upload(sock): # Send question for filename and filesize. sent = sock.sendall('filename_filesize'.encode('ascii')) if sent == 0: raise RuntimeError('Socket connection broken') # Handle ask for filename and filesize. # TODO: handle path traversel attacks. response = recv_until(sock, 300, '^[a-zA-Z0-9._]{3,255}[;][0-9]+$') if not response: raise RuntimeError('Protocol violation!') filename, filesize = response.split(';') filesize = int(filesize) # Send ready to receive. sent = sock.sendall('ready to receive a file'.encode('ascii')) if sent == 0: raise RuntimeError('Socket connection broken') # Handle file byte stream. response = recv_until(sock, filesize, decoding=None) if not response: raise RuntimeError('Protocol violation!') print('-> Receiveing ', end='') print(response[:20], end='') print('...') if isfile(filename): # NOTE: not specified. filename = filename + '.upload' # Write file. with open(filename, 'wb') as f: f.write(response) # Send file id. sent = sock.sendall(fid(filename).encode('ascii')) if sent == 0: raise RuntimeError('Socket connection broken')
reference_tensor = torch.cat(reference, 0).reshape(len(inputs), 1, inputs[0].shape[1], inputs[0].shape[2]) inputs_tensor = torch.cat(inputs, 0).reshape( (len(inputs), 1, inputs[0].shape[1], inputs[0].shape[2])) forged_tensor = forged_tensor.expand(-1, 3, -1, -1).clone().to(device) reference_tensor = reference_tensor.expand(-1, 3, -1, -1).clone().to(device) inputs_tensor = inputs_tensor.expand(-1, 3, -1, -1).clone().to(device) forged_tensor *= 255 reference_tensor *= 255 inputs_tensor *= 255 fid_forged = fid(forged_tensor, reference_tensor, 192, torch.device(device)) fid_input = fid(inputs_tensor, reference_tensor, 192, torch.device(device)) print(f"FID Score input: {fid_input}") print(f"FID Score forged: {fid_forged}") ssims_forged = {} psnrs_forged = {} ssims_input = {} psnrs_input = {} ssims_forged["value"] = [] psnrs_forged["value"] = [] ssims_input["value"] = [] psnrs_input["value"] = [] ssims_forged["dataset"] = [] psnrs_forged["dataset"] = []
device=device, hook=get_avgpool, ) fake_logits = F.softmax(fake_logits, dim=1) fake_softmax.append(fake_logits) fake_features.append(fake_feats) fake_features = torch.cat(fake_features, dim=0) fake_softmax = torch.cat(fake_softmax, dim=0) # calculate inception score inc_score = inception_score(fake_softmax) # calculate fid mu_fake = fake_features.mean(dim=0) sigma_fake = get_covariance(fake_features) fid_score = fid(mu_real, mu_fake, sigma_real, sigma_fake) writer.add_scalar("scores/FID", fid_score.item(), global_step=global_step) writer.add_scalar("scores/IS", inc_score.item(), global_step=global_step) del inception # save best checkpoint if fid_score.item() < best_fid: torch.save(gen.state_dict(), os.path.join(logdir, "gen_best.pth")) best_fid = fid_score.item() # if __name__ == "__main__": # # print(sha)