def train(): """ Train process starting by a request. """ logging.info('Route train.') # Loading the dataset tools logging.info('Loading the dataset tools.') data_controller = DataProcessing() # Creating the ModelTrain class passing the dataset as argument logging.info( 'Creating the ModelTrain class passing the dataset as argument.') training = ModelTrain(data_controller.get_dataframe_to_train()) # Runing the trainin process logging.info('Runing the trainin process.') model, metrics = training.run() # Returning results as HTML logging.info('Returning results as HTML.') if request.method == 'GET': return render_template('train.html', metrics=[('R2', metrics[0]), ('MSE', metrics[1]), ('MAE', metrics[2])]) else: # Returning results as json return jsonify({ 'R2': metrics[0], 'MSE': metrics[1], 'MAE': metrics[2] })
def __init__(self, port_number: int) -> None: logging.info(f"Запуск сервера..") self.port_number = port_number self.sock = None self.database = DataProcessing() self.socket_init() # Список авторизации self.authenticated_list = [] # Список ip, которым надо пройти регистрацию self.reg_list = [] # Список соединений, по которым рассылаются сообщения self.connections_list = [] self.ip2username_dict = {} logging.info(f"Сервер инициализировался, слушает порт {port_number}") # Ожидаем новое соединение while True: # Новое соединение conn, addr = self.sock.accept() # Добавляем новое соединение self.connections_list.append((conn, addr)) logging.info(f"Новое соединение от {addr[0]}") t = threading.Thread(target=self.router, args=(conn, addr)) t.daemon = True t.start()
def update_output(list_of_contents, list_of_names, list_of_dates): if list_of_contents is not None: Dp = DataProcessing("", "", "") children = [ Dp.parse_contents(c, n, d) for c, n, d in zip(list_of_contents, list_of_names, list_of_dates) ] return children
def __init__(self): self.counters = PersistentCounters(COUNTERS_FILE_PATH) self.save_counters_at = None self.data_processing = DataProcessing(self.counters) self.serial_reader = BackgroundSerialReader(self.on_new_data) self.latest_data = None self.lock = threading.Lock()
def graph(id): if id == 0: Graphs().cases_of_the_world(write=True) return render_template("./graphs/world.html") data = DataProcessing().all_cases_per_day_where_country_id_equal( country_id=id) df = DataProcessing().get_dateframe(data=data) get_graph = Graphs().get_graph(dataframe=df, country_id=id, write=True) return render_template("./graphs/" + get_graph[1] + ".html")
def ad_impressions_features_computation(input_file): """ functionality to generate the data frame with only input 'uuid' and new features, which would be used create output file. :return: output data's data frame """ data = DataProcessing(input_file) # create the 'DataProcessing' object. 'DataProcessing' is a class with feature extraction and data exploration functionalities implemented. print(' DataProcessing object created') data.data_visualization() # data visualization return data.feature_extraction() # feature extraction
def process_data(): """ This function will be called only when the user needs to process the data for the neural network """ dp = DataProcessing() mix, voc =dp.clean_paths(mixtures_paths=dp.vocals_paths(path=cs.data_vocals_path), vocals_paths=dp.mixture_paths(path=cs.data_mixtures_path)) dp.make_mixture_data_cnn(paths=mix[1:3],name="spectograms") dp.make_vocal_data_cnn(paths=voc[1:3],name="spectograms")
def isolate(self, mixture_path): """ Given a song this function will apply the model and retunr the vocals Args: mixture_path ([String]): Path to the song that we won't to separate the vocals from the instrumeents. Returns: [np.array]: Time series of the vocals """ dp = DataProcessing() mixture_wa = dp.get_raw_wave(song_path=mixture_path) mixture_st = dp.compute_stft(mixture_wa) mixture_amplitude = dp.compute_amplitude(mixture_st) split_x = np.array( dp.sliding_window(mixture_amplitude, length=cs.sample_length)) split_x = split_x.reshape(len(split_x), len(split_x[0]), len(split_x[0][0]), 1) prediction = self.model.predict(split_x) prediction = np.transpose(prediction) for x in range(0, len(prediction)): for y in range(0, len(prediction[x])): prediction[x][y] = 1 if prediction[x][y] > 0.65 else 0 vocal = dp.apply_binary_mask(mixture_amplitude, prediction) vocal = dp.reverse_stft(vocal) return vocal
def main(): data_puller = DataPuller( 'https://cloudcomputing-finalproj-hkr.firebaseio.com/', '/DHT11') df = data_puller.getData() data_processor = DataProcessing(df) X_train, X_test, y_train, y_test = data_processor.getSet( time_interval_error_rate=900, feature_scale=True) trainer = Trainer(X_train, y_train, X_test, y_test) liner_model = trainer.trainLinearRegression() ridge_model = trainer.trainRidgeRegression() lasso_model = trainer.trainLassoRegression() enet_model = trainer.trainEnetRegression()
def main(): dp = DataProcessing('train_max_x', 'test_max_x') print("Data Processed") dp.parse_csv('train_max_y.csv') print("Building neural net...") cnn = CNN(dp.train_images, dp.train_y) print("Neural net built!") cnn.train_cnn() print("Training done.") cnn.test_cnn() print("Testing done")
def test_detect_faces(self): """ test the detect_dace function in data_processing module :return: None """ face_img = cv2.imread('../dataset/test/0000.0000.jpg') car_imag = np.random.randint(255, size=(160, 160, 3), dtype=np.uint8) data_processing = DataProcessing() print(type(face_img)) bounding_box_1 = data_processing.detect_faces(face_img) bounding_box_2 = data_processing.detect_faces(car_imag) condition_1 = len(bounding_box_1) == 1 and len(bounding_box_1[0]) == 4 condition_2 = len(bounding_box_2) == 0 condition = condition_1 and condition_2 self.assertEqual(condition, True)
def getDataFile(data_file='input_a_file.csv', n_problem_type='Classification', is_norm=False, normalize=[0.0, 1.0]): print('Setting problem (task)...') dataProcessing = DataProcessing() data = dataProcessing.load_data(n_problem_type, data_file) #% setParams = SettingParamter() setParams.setData(data_file, data, n_problem_type, normalize, is_norm) #Retriving paramters params = setParams.mParser.parse_args() setParams.checkParameters(params) # checking paramters return params
def graph_diff(id): if id == 0: data = DataProcessing().total_cases_per_day() df = DataProcessing().get_dateframe_diff(data=data) Graphs().get_graph(dataframe=df, country_id=0, write=True, diff=True) return render_template("./graphs/world-diff.html") data = DataProcessing().all_cases_per_day_where_country_id_equal( country_id=id) df = DataProcessing().get_dateframe_diff(data=data) get_graph = Graphs().get_graph(dataframe=df, country_id=id, write=True, diff=True) return render_template("./graphs/" + get_graph[1] + ".html")
def __clean_csv(self, files, is_control, columns_to_use=None): output = [] data_processing = DataProcessing() for f in files: print('file') print(f) csv_file = self.read_csv(f) #Add name column (filename without extention) file_without_ext = f.split("/")[-1].split(".")[0] csv_file['name'] = "_".join(file_without_ext.split("_")[:-1]) # Label: 1 for PD, 0 for HC csv_file['label'] = 0 if is_control else 1 if columns_to_use is not None: csv_file = csv_file.loc[:, csv_file.columns.isin(columns_to_use)] # Zscore all data columns #csv_file = data_processing.zscore(csv_file, columns_to_ignore=['label', 'name', 'frameTime']) output.append(csv_file) return output
def untyped_evaluation_data(self, file_path): possible_entities = set(self.index.entity_index['id_to_name'].keys()) original_generator = Data.evaluation_data_reader(file_path) for e1, e2, e1_domain, e2_domain, path in original_generator(): e1_c_domain = list(possible_entities - set(e1_domain)) e2_c_domain = list(possible_entities - set(e2_domain)) yield e1, e2, e1_c_domain, e2_c_domain, path
def __init__(self, pkg_dir): self.pkg_dir = pkg_dir self.data_acquisition = DataAcquisition() self.data_processing = DataProcessing() self.model_engineering = ModelEngineering(self.pkg_dir) self.cam_streamer = CamStreamer() #self.image_subscriber = ImageSubscriber() self.acquire_data() self.model_engineering.knn_fit(self.data_acquisition.trn_wh) self.selected_face = None self.pub_img = rospy.Publisher('/person_recognition/image/compressed', CompressedImage, queue_size=1) self.pub_txt = rospy.Publisher('/person_recognition/crowd', String, queue_size=10)
def __init__(self, BatchSize, NumWorkers): normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transformations = transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize, ]) if cfg.TripletLoss: dset_train = TripletDataProcessing( cfg.IMG_PATH, cfg.TRAIN_DATA, cfg.TRAIN_IMG_FILE, cfg.TRAIN_LABEL_FILE, transformations, cfg.TRAIN_BBOX_FILE, cfg.LANDMARKS_TRAIN_FILE, cfg.IUV_TRAIN_FILE, cfg.IMG_SIZE) dset_test = TripletDataProcessing( cfg.IMG_PATH, cfg.TEST_DATA, cfg.TEST_IMG_FILE, cfg.TEST_LABEL_FILE, transformations, cfg.TEST_BBOX_FILE, cfg.LANDMARKS_TEST_FILE, cfg.IUV_TEST_FILE, cfg.IMG_SIZE) else: dset_train = DataProcessing(cfg.IMG_PATH, cfg.TRAIN_DATA, cfg.TRAIN_IMG_FILE, cfg.TRAIN_LABEL_FILE, transformations, cfg.TRAIN_BBOX_FILE, cfg.LANDMARKS_TRAIN_FILE, cfg.IUV_TRAIN_FILE, cfg.IMG_SIZE) dset_test = DataProcessing(cfg.IMG_PATH, cfg.TEST_DATA, cfg.TEST_IMG_FILE, cfg.TEST_LABEL_FILE, transformations, cfg.TEST_BBOX_FILE, cfg.LANDMARKS_TEST_FILE, cfg.IUV_TEST_FILE, cfg.IMG_SIZE) # add bounding box to data loader self.train_loader = DataLoader(dset_train, batch_size=BatchSize, shuffle=True, num_workers=NumWorkers, pin_memory=True) self.test_loader = DataLoader(dset_test, batch_size=BatchSize, shuffle=False, num_workers=NumWorkers, pin_memory=True)
def __init__(self, port_number: int) -> None: logger.info(f"Запуск сервера..") self.port_number = port_number self.sock = None self.database = DataProcessing() self.socket_init() self.authenticated_list = [] self.reg_list = [] self.connections_list = [] self.ip2username_dict = {} logger.info(f"Сервер инициализировался, слушает порт {port_number}") self.connection_thread = None self.play_command() self.input_processing()
def main(): ''' this is the client or driver application ''' data_obj = DataProcessing(CONN_STRING, CHUNKSIZE, FILE_NAME) disk_engine = data_obj.get_database_connection() data_obj.data_cleansing_and_persistent(disk_engine, TABLE_NAME) sql_query_a = "SELECT userID, COUNT(DISTINCT trackId) as distinct_song " +\ "FROM data GROUP BY userID " +\ "ORDER BY distinct_song DESC" sql_query_b = "SELECT artistName, trackName, COUNT(*) as PlayCount " +\ "FROM data WHERE artistName IS NOT NULL " +\ "AND trackName IS NOT NULL " +\ "GROUP BY artistName, trackName " +\ "ORDER BY PlayCount DESC " +\ "LIMIT 100" #DOES NOT WORK AS SQLITE DOES NOT SUPPORT THE DATEDIFF ''' sql_query_c = "SELECT t1.userID,t1.trackName, t1.timestamp, t2.timestamp, "+\ "TIMESTAMPDIFF(Minute, t1.timestamp, t2.timestamp) AS sessionDuration "+\ "FROM data t1 INNER JOIN data t2 ON t1.userID = t2.userID "+\ "WHERE sessionDuration < 20" ''' df_a = data_obj.retrieve_query_result(sql_query_a, disk_engine) df_b = data_obj.retrieve_query_result(sql_query_b, disk_engine)
def __init__(self, port_number: int) -> None: logger.info(f"Запуск сервера..") self.port_number = port_number self.sock = None self.database = DataProcessing() self.socket_init() # Список авторизации self.authenticated_list = [] # Список ip, которым надо пройти регистрацию self.reg_list = [] # Список соединений, по которым рассылаются сообщения self.connections_list = [] self.ip2username_dict = {} logger.info(f"Сервер инициализировался, слушает порт {port_number}") self.connection_thread = None self.play_command() self.input_processing()
def __init__(self, port_number: int) -> None: logging.info(f"Инициализация сервера") self.port_number = port_number self.sock = None self.database = DataProcessing() self.socket_init() self.authenticated_list = [] self.reg_list = [] self.connections_list = [] self.ip2username_dict = {} logging.info(f"Сервер запущен на порту {port_number}") while True: conn, addr = self.sock.accept() self.connections_list.append((conn, addr)) logging.info(f"Подключение от нового адреса: {addr[0]}") t = threading.Thread(target=self.router, args=(conn, addr)) t.daemon = True t.start()
def cyto_ai_training_pipeline_log_df(self, data_df): data_processing_obj = DataProcessing() sampling_obj = DataSampling() sys_obj = SysConfig() train_obj = DataTrainning() test_set_ratio = sys_obj.get_test_set_ratio() y_key = sys_obj.get_y_key() df_output_file = sys_obj.get_df_output_file() print(data_df) #### data preprocessing print("start cast_all_to_numeric.") data_df = data_processing_obj.cast_all_to_numeric(data_df) print(data_df) print("end cast_all_to_numeric.") ### data_df.to_csv(df_output_file, index=False) print("DF output file = %s" % (df_output_file)) return data_df
def __init__(self): self.RUNNING = False self.load_config() if self.test_mode: self.API = TestApi(self.KEY, self.SECRET, BOT=self) else: self.API = Api(self.KEY, self.SECRET) self.modify_api() self.data_processing = DataProcessing() # self.INDICATORS = [NeuralNetwork(self), Ladder(self)] self.INDICATORS = [] self.VIEW = Form(self, INDICATORS=self.INDICATORS) self.VIEW.show()
def ranking_evaluation_data(self, file_name, path_length): # output: (e1, e2, e1_domain, e2_domain, path) output_types = (tf.int32, ) * 5 output_shapes = (tf.TensorShape([]), ) * 2 + (tf.TensorShape([None ]), ) * 3 file_path = self.config[file_name][path_length] if self.config['type_matching']: generator = Data.evaluation_data_reader(file_path) else: generator = lambda: self.untyped_evaluation_data(file_path) evaluation_data = tf.data.Dataset.from_generator( generator, output_types, output_shapes).prefetch(1) iterator = evaluation_data.make_initializable_iterator() datapoint = iterator.get_next() return iterator, datapoint
def cyto_cnn_training_pipeline(self, data_ary, test_ary): # data_processing_obj = DataProcessing() sampling_obj = DataSampling() sys_obj = SysConfig() train_obj = DataTrainning() process_obj = DataProcessing() TEST_VALIDATION_SPLIT = 0.33 # model_output_dir = sys_obj.get_model_output_dir() #### data preprocessing np.random.shuffle(data_ary) train_set_x, train_set_y = sampling_obj.get_x_y_from_data_ary(data_ary) print('train set shape', train_set_x.shape) train_set_x = train_set_x.reshape(train_set_x.shape[0], 432, 1220, 1) np.random.shuffle(test_ary) test_X_ary, test_Y_ary = sampling_obj.get_x_y_from_data_ary(test_ary) test_X_ary = test_X_ary.reshape(test_X_ary.shape[0], 432, 1220, 1) (test_set_x, valid_set_x, test_set_y, valid_set_y) = train_test_split(test_X_ary, test_Y_ary, test_size=TEST_VALIDATION_SPLIT) # train_set_x, train_set_y = sampling_obj.binary_ary_data_over_sampling(train_set_x, train_set_y) ### sampling my_model = train_obj.cnn_apply(train_set_x, train_set_y, valid_set_x, valid_set_y, test_X_ary, test_Y_ary) # test_score = my_model.evaluate(test_set_x, test_set_y) # test_set_diseas_score = my_model.score(test_set_disease_x, test_set_disease_y) # test_set_normal_score = my_model.score(test_set_normal_x, test_set_normal_y) # print("\ntest data set, %s: %.2f%%" % (my_model.metrics_names[1], test_score[1]*100)) # print("Test score:", test_score[0]) # print('Test accuracy:', test_score[1]) return my_model
class Pipeline(): """Launches the serial reader in a background thread, processes incoming data.""" def __init__(self): self.counters = PersistentCounters(COUNTERS_FILE_PATH) self.save_counters_at = None self.data_processing = DataProcessing(self.counters) self.serial_reader = BackgroundSerialReader(self.on_new_data) self.latest_data = None self.lock = threading.Lock() def on_new_data(self, data): """Called on each new data from the serial reader in a background thread.""" data = self.data_processing.process(data) with self.lock: self.latest_data = data now = time.monotonic() if self.save_counters_at is None or now > self.save_counters_at: self.counters.save() self.save_counters_at = now + COUNTERS_FILE_SAVE_PERIOD_MIN * 60 def get_latest_data(self): """ Returns: Latest data if available, None if no new data have been received since last call """ with self.lock: data = self.latest_data self.latest_data = None return data def start(self): self.serial_reader.start() def stop(self): self.serial_reader.interrupt() self.counters.save()
data_results = [] for j in range(len(data_file_set)): #if j < 9: # n_problem_type = 'Classification' # 'Regression' # 'Classification' #else: # n_problem_type = 'Regression' # 'Regression' # 'Classification' data_results_coll = {} for exp_num in range(EXP_RUN): data_file = data_file_set[j] is_norm = True isOptimizeParam = False normalize = [0.0, 1.0] params = SettingParamter.getDataFile(data_file, n_problem_type, is_norm, normalize) dataProcessing = DataProcessing() dataProcessing.setParams(params) data_input_values, data_target_values, random_sequence = data_partition(dataProcessing, params.n_validation_method) X_train, X_test, y_train, y_test = data_evaluation(params, data_input_values, data_target_values, params.n_validation_method) inputs = params.n_max_input_attr outputs = params.n_max_target_attr #TODO: Optimizaer setup for solve in solver: if(runOpt == '_'): if(solve == 'RMSprop'): opt = tf.keras.optimizers.RMSprop(learning_rate=0.1) if(solve == 'Adam'): opt = tf.keras.optimizers.Adam(learning_rate=0.1) if(solve == 'Adagrad'):
class Server: def __init__(self, port_number: int) -> None: logger.info(f"Запуск сервера..") self.port_number = port_number self.sock = None self.database = DataProcessing() self.socket_init() # Список авторизации self.authenticated_list = [] # Список ip, которым надо пройти регистрацию self.reg_list = [] # Список соединений, по которым рассылаются сообщения self.connections_list = [] self.ip2username_dict = {} logger.info(f"Сервер инициализировался, слушает порт {port_number}") self.connection_thread = None self.play_command() self.input_processing() def connection_processing(self): """ Метод ожидания подключений клиентов Запускается в отдельном потоке """ # Ожидаем новое соединение while self.receive_data: # Новое соединение conn, addr = self.sock.accept() # Добавляем новое соединение self.connections_list.append((conn, addr)) logger.info(f"Новое соединение от {addr[0]}") t = threading.Thread(target=self.router, args=(conn, addr)) t.daemon = True t.start() def input_processing(self): """ Метод ввода команд для управления сервером 1. Отключение сервера (завершение программы); 2. Пауза (остановка прослушивание порта); 3. Показ логов; 4. Очистка логов; 5. Очистка файла идентификации. """ commands_dict = { "exit": {"command": self.exit_command, "description": "Выход из программы"}, "pause": { "command": self.stop_command, "description": "Приостановить получение новых соединений", }, "stop": { "command": self.stop_command, "description": "Приостановить получение новых соединений", }, "play": { "command": self.play_command, "description": "Продолжить получение новых соединений", }, "start": { "command": self.play_command, "description": "Продолжить получение новых соединений", }, "start logs": { "command": self.start_logs_command, "description": "Выводить логи в консоли", }, "stop logs": { "command": self.stop_logs_command, "description": "Не выводить логи в консоли", }, "clear auth": { "command": self.clear_auth_command, "description": "Отчистка файла для авторизации пользователей", }, "clear logs": { "command": self.clear_logs_command, "description": "Отчистка файла логирования", }, } while True: command_str = input() if command_str in commands_dict: commands_dict[command_str]["command"]() else: commands_str = "\n".join( [f"{k} - {v['description']}" for k, v in commands_dict.items()] ) print(f"Команда не найдена\nДоступные команды:\n{commands_str}") def exit_command(self): """Обработчик завершения работы сервера""" logger.info("Завершаем работу сервера") sys.exit() def stop_command(self): """Команда приостановки""" if self.connection_thread is None: raise ValueError( "Нельзя остановить поток подключений, если он не был запущен!" ) self.receive_data = False logger.info("Приостановили поток получения данных клиентов") def clear_auth_command(self): """Отчистка файла авторизации""" self.database.clear() logger.info("Отчистили файл аворизации пользователей") def start_logs_command(self): """Показывает логи""" if stream_handler not in logger.handlers: logger.addHandler(stream_handler) logger.info("Возобновили показ логов в консоли") def stop_logs_command(self): """Стопает показ логов в консоли""" if stream_handler in logger.handlers: logger.removeHandler(stream_handler) logger.info("Приостановили показ логов в консоли") def clear_logs_command(self): """Отчистка файла логов""" open(LOGGER_FILE, "w").close() logger.info("Отчистили файл логов") def play_command(self): # Поток обработки подлючений от клиентов self.receive_data = True t = threading.Thread(target=self.connection_processing) t.daemon = True t.start() self.connection_thread = t def send_message(self, conn, data: Union[str, Dict[str, Any]], ip: str) -> None: """Отправка данных""" data_text = data if type(data) == dict: data = json.dumps(data, ensure_ascii=False) data = data.encode() conn.send(data) logger.info(f"Сообщение {data_text} было отправлено клиенту {ip}") def socket_init(self): """Инициализация сокета""" sock = socket.socket() sock.bind(("", self.port_number)) sock.listen(0) # Наш сокет self.sock = sock def message_logic(self, conn, client_ip): """ Получение сообщений """ data = "" while True: # Получаем данные и собираем их по кусочкам chunk = conn.recv(1024) data += chunk.decode() # Если это конец сообщения, то значит, что мы все собрали и можем отдавать данные каждому соединению if END_MESSAGE_FLAG in data: username = self.ip2username_dict[client_ip] logger.info( f"Получили сообщение {data} от клиента {client_ip} ({username})" ) data = {"username": username, "text": data} # Рассылка по каждому соединению logger.info( f"Текущее кол-во подключений к серверу: {len(self.connections_list)}" ) for connection in self.connections_list: current_conn, current_ip = connection try: self.send_message(current_conn, data, current_ip) # Если вдруг у нас появилсоь соедиение, которое уже неактивно except BrokenPipeError: continue # Обнуляемся data = "" # Значит пришла только часть большого сообщения else: logger.info(f"Приняли часть данных от клиента {client_ip}: '{data}'") # Если вообще ничего не пришло - это конец всего соединения if not chunk: break def reg_logic(self, conn, addr): """ Логика регистрации пользователя """ newuser_ip = addr[0] try: data = json.loads(conn.recv(1024).decode()) except JSONDecodeError: if newuser_ip in self.reg_list: self.reg_list.remove(newuser_ip) return newuser_password, newuser_username = hash(data["password"]), data["username"] self.database.user_reg(newuser_ip, newuser_password, newuser_username) logger.info(f"Клиент {newuser_ip} -> регистрация прошла успешно") data = {"result": True} if newuser_ip in self.reg_list: self.reg_list.remove(newuser_ip) logger.info(f"Удалили клиента {newuser_ip} из списка регистрации") self.send_message(conn, data, newuser_ip) logger.info(f"Клиент {newuser_ip}. Отправили данные о результате регистрации") def auth_logic(self, conn, addr): """ Логика авторизации клиента Запрос авторизации у нас априори меньше 1024, так что никакой цикл не запускаем """ try: user_password = hash(json.loads(conn.recv(1024).decode())["password"]) except JSONDecodeError: return client_ip = addr[0] # Проверяем на существование данных auth_result, username = self.database.user_auth(client_ip, user_password) # Если авторизация прошла успешно if auth_result == 1: logger.info(f"Клиент {client_ip} -> авторизация прошла успешно") data = {"result": True, "body": {"username": username}} if client_ip not in self.authenticated_list: self.authenticated_list.append(client_ip) self.ip2username_dict[client_ip] = username logger.info(f"Добавили клиента {client_ip} в список авторизации") # Если авторизация не удалась, но пользователь с таким ip существует elif auth_result == 0: logger.info(f"Клиент {client_ip} -> авторизация не удалась") data = {"result": False, "description": "wrong auth"} # Если пользователя с таким ip не существует, то необходима регистрация else: logger.info( f"Клиент {client_ip} -> необходима предварительная регистрация в системе" ) data = {"result": False, "description": "registration required"} if client_ip not in self.reg_list: self.reg_list.append(client_ip) logger.info(f"Добавили клиента {client_ip} в список регистрации") self.send_message(conn, data, client_ip) logger.info(f"Клиент {client_ip}. Отправили данные о результате авторизации") # Если была успешная авторизация - принимаем последующие сообщения от пользователя if auth_result == 1: self.message_logic(conn, client_ip) def router(self, conn, addr): """ Роутинг в зависимости от авторизации клиента """ logger.info("Router работает в отдельном потоке!") client_ip = addr[0] # Если клиенту нужна авторизация if client_ip in self.reg_list: self.reg_logic(conn, addr) # Если ip не авторизован - надо авторизовать elif client_ip not in self.authenticated_list: self.auth_logic(conn, addr) # Если уже был авторизован else: self.message_logic(conn, client_ip) logger.info(f"Отключение клиента {client_ip}") self.connections_list.remove((conn, addr)) # Если клиент был в списке авторизации - удаляем его if client_ip in self.authenticated_list: self.authenticated_list.remove(client_ip) print("Список соединений:") print(self.connections_list) logger.info(f"Удалили клиента {client_ip} из списка авторизации") def __del__(self): logger.info(f"Остановка сервера")
class Server: """Класс с логикой сервера""" def __init__(self, port_number: int) -> None: logger.info(f"Запуск сервера..") self.port_number = port_number self.sock = None self.database = DataProcessing() self.socket_init() # Список авторизации self.authenticated_list = [] # Список ip, которым надо пройти регистрацию self.reg_list = [] self.ip2username_dict = {} logger.info(f"Сервер инициализировался, слушает порт {port_number}") self.connection_thread = None self.play_command() self.input_processing() def connection_processing(self): """ Метод ожидания подключений клиентов Запускается в отдельном потоке """ # Ожидаем новое соединение while self.receive_data: # Новое соединение conn, addr = self.sock.accept() logger.info(f"Новое соединение от {addr[0]}") t = threading.Thread(target=self.server_router, args=(conn, addr)) t.daemon = True t.start() def input_processing(self): """ Метод ввода команд для управления сервером 1. Отключение сервера (завершение программы); 2. Пауза (остановка прослушивание порта); 3. Показ логов; 4. Очистка логов; 5. Очистка файла идентификации. """ commands_dict = { "exit": { "command": self.exit_command, "description": "Выход из программы" }, "pause": { "command": self.stop_command, "description": "Приостановить получение новых соединений", }, "stop": { "command": self.stop_command, "description": "Приостановить получение новых соединений", }, "play": { "command": self.play_command, "description": "Продолжить получение новых соединений", }, "start": { "command": self.play_command, "description": "Продолжить получение новых соединений", }, "start logs": { "command": self.start_logs_command, "description": "Выводить логи в консоли", }, "stop logs": { "command": self.stop_logs_command, "description": "Не выводить логи в консоли", }, "clear auth": { "command": self.clear_auth_command, "description": "Отчистка файла для авторизации пользователей", }, "clear logs": { "command": self.clear_logs_command, "description": "Отчистка файла логирования", }, } while True: command_str = input() if command_str in commands_dict: commands_dict[command_str]["command"]() else: commands_str = "\n".join([ f"{k} - {v['description']}" for k, v in commands_dict.items() ]) print( f"Команда не найдена\nДоступные команды:\n{commands_str}") def exit_command(self): """Обработчик завершения работы сервера""" logger.info("Завершаем работу сервера") sys.exit() def stop_command(self): """Команда приостановки""" if self.connection_thread is None: raise ValueError( "Нельзя остановить поток подключений, если он не был запущен!") self.receive_data = False logger.info("Приостановили поток получения данных клиентов") def clear_auth_command(self): """Отчистка файла авторизации""" self.database.clear() logger.info("Отчистили файл аворизации пользователей") def start_logs_command(self): """Показывает логи""" if stream_handler not in logger.handlers: logger.addHandler(stream_handler) logger.info("Возобновили показ логов в консоли") def stop_logs_command(self): """Стопает показ логов в консоли""" if stream_handler in logger.handlers: logger.removeHandler(stream_handler) logger.info("Приостановили показ логов в консоли") def clear_logs_command(self): """Отчистка файла логов""" open(LOGGER_FILE, "w").close() logger.info("Отчистили файл логов") def play_command(self): # Поток обработки подлючений от клиентов self.receive_data = True t = threading.Thread(target=self.connection_processing) t.daemon = True t.start() self.connection_thread = t def send_message(self, conn, data: Union[str, Dict[str, Any]], ip: str) -> None: """Отправка данных""" data_text = data if type(data) == dict: data = json.dumps(data, ensure_ascii=False) data += END_MESSAGE_FLAG data = data.encode() conn.send(data) logger.info(f"Сообщение {data_text} было отправлено клиенту {ip}") def socket_init(self): """Инициализация сокета""" sock = socket.socket() sock.bind(("", self.port_number)) sock.listen(0) # Наш сокет self.sock = sock def new_event_logic(self, conn, client_ip): """ Логика обработки новых событий, которые приходят с клиента """ data = "" # Имя пользователя по его ip username = self.ip2username_dict[client_ip] # Экземпляр класса для работы с файлами конкретного пользователя userfiles_logic = FTPFileProcessing(username) while True: # Получаем данные и собираем их по кусочкам chunk = conn.recv(1024) data += chunk.decode() # Если это конец сообщения, то значит, что мы все собрали и можем отдавать данные каждому соединению if END_MESSAGE_FLAG in data: data = data.replace(END_MESSAGE_FLAG, "") # Проверяем то, что это: файл или команда # Это файл if FILE_DETECT_FLAG in data: logger.info( f"Получили файл {data} от клиента {client_ip} ({username})" ) # Записываем файл file_name, file_content = data.split(FILE_DETECT_FLAG) transfer_flag = userfiles_logic.client2server_transfer( file_name, file_content) if transfer_flag: out_data = { "result": True, "description": "file received" } else: out_data = { "result": False, "description": "file saving error" } self.send_message(conn, out_data, client_ip) # Команда для получения файла пользователя с сервера elif "get" in data: description, is_result = userfiles_logic.server2client_transfer( data) out_data = { "result": is_result, "description": description } self.send_message(conn, out_data, client_ip) # Это одна из стандартных команд FTPFileProcessing else: logger.info( f"Получили команду {data} от клиента {client_ip} ({username})" ) command = data.split(" ") # Остановка работы программы if command[0] == "exit": break # Получаем результат существования команды result = userfiles_logic.router(command[0]) out_data = {"result": None, "description": None} # Если есть такая команда if result: try: description_str = result(*command[1:]) out_data = { "result": True, "description": description_str } except TypeError: description_str = f"Команда {command[0]} была вызвана с некорректными аргументами" out_data = { "result": False, "description": description_str } else: commands_str = "\n".join([ f"{key} - {value}" for ( key, value, ) in userfiles_logic.get_commands().items() ]) description_str = f"Команда {command[0]} не найдена! Список команд:\n{commands_str}" out_data = { "result": False, "description": description_str } self.send_message(conn, out_data, client_ip) # Обнуляем буфер сообщений data = "" # Значит пришла только часть большого сообщения else: logger.info( f"Приняли часть данных от клиента {client_ip}: '{data}'") # Если вообще ничего не пришло - это конец всего соединения if not chunk: break def reg_logic(self, conn, addr): """ Логика регистрации пользователя """ newuser_ip = addr[0] try: data = json.loads(conn.recv(1024).decode()) except JSONDecodeError: if newuser_ip in self.reg_list: self.reg_list.remove(newuser_ip) return newuser_password, newuser_username = hash( data["password"]), data["username"] self.database.user_reg(newuser_ip, newuser_password, newuser_username) logger.info(f"Клиент {newuser_ip} -> регистрация прошла успешно") create_flag = FTPFileProcessing.new_user_reg(newuser_username) if create_flag: logger.info( f"Клиент {newuser_ip} -> создали root-директорию {newuser_username}" ) else: logger.error( f"Клиент {newuser_ip} -> не удалось создать root-директорию {newuser_username}" ) data = {"result": True} if newuser_ip in self.reg_list: self.reg_list.remove(newuser_ip) logger.info(f"Удалили клиента {newuser_ip} из списка регистрации") self.send_message(conn, data, newuser_ip) logger.info( f"Клиент {newuser_ip}. Отправили данные о результате регистрации") def auth_logic(self, conn, addr): """ Логика авторизации клиента Запрос авторизации у нас априори меньше 1024, так что никакой цикл не запускаем """ try: user_password = hash( json.loads(conn.recv(1024).decode())["password"]) except JSONDecodeError: return client_ip = addr[0] # Проверяем на существование данных auth_result, username = self.database.user_auth( client_ip, user_password) # Если авторизация прошла успешно if auth_result == 1: logger.info(f"Клиент {client_ip} -> авторизация прошла успешно") data = {"result": True, "body": {"username": username}} if client_ip not in self.authenticated_list: self.authenticated_list.append(client_ip) self.ip2username_dict[client_ip] = username logger.info( f"Добавили клиента {client_ip} в список авторизации") # Если авторизация не удалась, но пользователь с таким ip существует elif auth_result == 0: logger.info(f"Клиент {client_ip} -> авторизация не удалась") data = {"result": False, "description": "wrong auth"} # Если пользователя с таким ip не существует, то необходима регистрация else: logger.info( f"Клиент {client_ip} -> необходима предварительная регистрация в системе" ) data = {"result": False, "description": "registration required"} if client_ip not in self.reg_list: self.reg_list.append(client_ip) logger.info( f"Добавили клиента {client_ip} в список регистрации") self.send_message(conn, data, client_ip) logger.info( f"Клиент {client_ip}. Отправили данные о результате авторизации") # Если была успешная авторизация - принимаем последующие сообщения от пользователя if auth_result == 1: self.new_event_logic(conn, client_ip) def server_router(self, conn, addr): """ Роутинг в зависимости от авторизации клиента """ logger.info("Server router работает в отдельном потоке!") client_ip = addr[0] # Если клиенту нужна авторизация if client_ip in self.reg_list: self.reg_logic(conn, addr) # Если ip не авторизован - надо авторизовать elif client_ip not in self.authenticated_list: self.auth_logic(conn, addr) # Если уже был авторизован else: self.new_event_logic(conn, client_ip) logger.info(f"Отключение клиента {client_ip}") # Если клиент был в списке авторизации - удаляем его if client_ip in self.authenticated_list: self.authenticated_list.remove(client_ip) logger.info(f"Удалили клиента {client_ip} из списка авторизации") def __del__(self): logger.info(f"Остановка сервера")
def test_model_train(self): dp = DataProcessing() dataset = dp.get_dataframe_to_train() model_predict = ModelPredict() self.assertEqual(model_predict.predict(10).shape[0], 10)