def config_local(base_directory, conf_directory): """ Upload custom configuration files for local server. """ local_path = utils.file_path('postgres/local.conf') remote_path = '{}/local.conf'.format(conf_directory) result = put(local_path, remote_path, mode=0644, use_sudo=True) if result.succeeded: pg_conf = '{}/postgresql.conf'.format(base_directory) files.append(pg_conf, "include_dir = 'conf.d'", use_sudo=True) # Set file owner to "postgres". usr = grp = 'postgres' sudo('chown {}:{} {}'.format(usr, grp, remote_path)) # Grant access to remote clients. hba_conf = '{}/pg_hba.conf'.format(base_directory) files.append(hba_conf, 'host all all 0.0.0.0/0 md5', use_sudo=True)
def config(): """ Upload a custom configuration file. :Example: fab --config=config.conf nginx.config """ local = utils.file_path('nginx', 'default') remote = '/etc/nginx/sites-available/default' target = '/etc/nginx/sites-enabled/default' put(local, remote, mode='0644', use_sudo=True) # Change owner to "root". sudo('chown root:root {}'.format(remote)) # Remove old symlink. sudo('rm {}'.format(target)) # Create new symlink. sudo('ln -s {} {}'.format(remote, target)) # Create the nginx log directory. run('mkdir -p {}'.format(utils.home('logs', 'nginx')))
def config_svisor(): filename = 'bugtrax.conf' local_file = utils.file_path('supervisor', filename) remote_file = '/etc/supervisor/conf.d/{0}'.format(filename) put(local_file, remote_file, mode=644, use_sudo=True)
def load_model(self): ''' Load the Keras prediction model ''' self.model = Sequential() self.model.add(keras.layers.Dense(9, activation='relu', input_shape=(None, 6),dtype='float32')) self.model.add(keras.layers.LSTM(50, return_sequences=False)) self.model.add(keras.layers.Dense(9, activation='tanh')) self.model.add(keras.layers.Dense(3, activation='softmax')) self.model.compile(optimizer='adam', loss='categorical_crossentropy') self.model.load_weights(file_path("model/RPS-50.h5"))
def install(name): """ Upload and install the dependencies in the requirements file. :param name: The name of the virtual environment to use. :Example: fab --config=config.conf python.install:name=myvenv """ base = '/home/{}/venvs/{}/base.txt'.format(env.user, name) prod = '/home/{}/venvs/{}/prod.txt'.format(env.user, name) # Upload requirements file. put(utils.file_path('requirements', 'base.txt'), base) put(utils.file_path('requirements', 'prod.txt'), prod) # Activate the virtual environment. with prefix('source /home/{}/venvs/{}/bin/activate'.format(env.user, name)): run('pip install -r {}'.format(prod))
def call_service(service, sender_address): config = config_parser( configuration ) for section in config.sections(): for (function, file) in config.items(section): if(function == service): file = "ROUS/"+file filepath = utils.file_path(file) module = imp.load_source(function, filepath) call_func = getattr(module, function) #the goods, magic is here call_func(sender_address) return True return False
def config_django(): require('PROJECT_NAME') project = env.PROJECT_NAME filename = 'prod.py' local_file = utils.file_path('project', filename) remote_file = utils.home('apps', project, 'config', 'settings', filename) put(local_file, remote_file)
def process_play(self, predictions): '''Process gameplay after a successful detection''' self.big_text.text = "" print(predictions) computer_choice = self.game.next_play() choice = max(range(len(predictions)), key=lambda index: predictions[index]['confidence']) player_choice = predictions[choice]['class'] self.last_play = player_choice x = predictions[choice]['x'] - (predictions[choice]['width'] // 2) y = predictions[choice]['y'] - (predictions[choice]['height'] // 2) w = predictions[choice]['width'] h = predictions[choice]['height'] frame = self.last_frame[y:y + h, x:x + w] self.display_image(frame, self.player_img) if computer_choice == "Rock": self.computer_img.source = file_path('img/rock.png') elif computer_choice == "Paper": self.computer_img.source = file_path('img/paper.png') else: self.computer_img.source = file_path('img/scissors.png') self.wrong.opacity = 0.5 # Make button visible print("Computer chose " + computer_choice) self.computer_label.text = "Computer - " + computer_choice print("Player chose " + player_choice) self.player_label.text = "Player - " + player_choice self.game.add_round(player_choice, computer_choice) score = self.game.get_score() self.score_label.text = "Computer: " + str(score.computer) + \ ", Player: " + str(score.player)
def __init__(self): self.code = { 'cat': [1, 0, 0], 'dust': [0, 1, 0], 'water': [0, 0, 1] } pack = 'media.images_train' train_data = [ (Neuron(load(file_path(pack, 'cat1.png'))), self.code['cat']), (Neuron(load(file_path(pack, 'cat2.png'))), self.code['cat']), (Neuron(load(file_path(pack, 'cat3.png'))), self.code['cat']), (Neuron(load(file_path(pack, 'dust1.png'))), self.code['dust']), (Neuron(load(file_path(pack, 'dust2.png'))), self.code['dust']), (Neuron(load(file_path(pack, 'dust3.png'))), self.code['dust']), (Neuron(load(file_path(pack, 'water1.png'))), self.code['water']), (Neuron(load(file_path(pack, 'water2.png'))), self.code['water']), (Neuron(load(file_path(pack, 'water3.png'))), self.code['water']), ] for x, output in train_data: x.prepare() self.net = buildNetwork( 4, 3, 3, hiddenclass=TanhLayer, outclass=SoftmaxLayer ) data = SupervisedDataSet(4, 3) for x, output in train_data: data.addSample( ( x.contours / 100.0, x.color[0] / 1000.0, x.color[1] / 1000.0, x.color[2] / 1000.0, ), output ) trainer = BackpropTrainer( self.net, momentum=0.1, verbose=True, weightdecay=0.01 ) trainer.trainOnDataset(data, 1000) # 1000 iterations trainer.testOnData(verbose=True)
def load_classes(self): '''Load YOLO model class file''' classes_path = self.config.get_property('classes_path') if classes_path is None: raise KeyError('Configuration property "classes_path" not \ configured') try: f = open(file_path(classes_path), "rt") classes = f.read().rstrip('\n').split('\n') f.close() return classes except FileNotFoundError as e: print('Class file not found') exit(1)
def __init__(self): self.code = {'cat': [1, 0, 0], 'dust': [0, 1, 0], 'water': [0, 0, 1]} pack = 'media.images_train' train_data = [ (Neuron(load(file_path(pack, 'cat1.png'))), self.code['cat']), (Neuron(load(file_path(pack, 'cat2.png'))), self.code['cat']), (Neuron(load(file_path(pack, 'cat3.png'))), self.code['cat']), (Neuron(load(file_path(pack, 'dust1.png'))), self.code['dust']), (Neuron(load(file_path(pack, 'dust2.png'))), self.code['dust']), (Neuron(load(file_path(pack, 'dust3.png'))), self.code['dust']), (Neuron(load(file_path(pack, 'water1.png'))), self.code['water']), (Neuron(load(file_path(pack, 'water2.png'))), self.code['water']), (Neuron(load(file_path(pack, 'water3.png'))), self.code['water']), ] for x, output in train_data: x.prepare() self.net = buildNetwork(4, 3, 3, hiddenclass=TanhLayer, outclass=SoftmaxLayer) data = SupervisedDataSet(4, 3) for x, output in train_data: data.addSample(( x.contours / 100.0, x.color[0] / 1000.0, x.color[1] / 1000.0, x.color[2] / 1000.0, ), output) trainer = BackpropTrainer(self.net, momentum=0.1, verbose=True, weightdecay=0.01) trainer.trainOnDataset(data, 1000) # 1000 iterations trainer.testOnData(verbose=True)
def processThreadBody(self): '''Thread body which handles YOLO processing''' # These values could be updated after the thread starts # Get configuration values weights_path = file_path(self.config.get_property('weights_path')) cfg_path = file_path(self.config.get_property('cfg_path')) inpWidth = self.config.get_property('inpWidth') inpHeight = self.config.get_property('inpHeight') scale = self.config.get_property('scale') mean = self.config.get_property('mean') confThreshold = self.config.get_property('confThreshold') nmsThreshold = self.config.get_property('nmsThreshold') circle_scale = self.config.get_property('circle_scale') # Iniitialize the OpenCV darknet DNN module net = cv.dnn.readNet(weights_path, cfg_path, 'darknet') outNames = net.getUnconnectedOutLayersNames() frameWidth, frameHeight = self.ImageProvider.get_dimensions() while True: if not self.processing: time.sleep(0.1) else: ret, frame = self.ImageProvider.get_frame() if ret: self.ImageProvider.clear_frames() framePredictions = list() blob = cv.dnn.blobFromImage(frame, size=(inpWidth, inpHeight), swapRB=False, ddepth=cv.CV_8U) net.setInput(blob, scalefactor=scale, mean=mean) outs = net.forward(outNames) boxes = [] confidences = [] classIDs = [] for out in outs: for detection in out: scores = detection[5:8] classId = np.argmax(scores) confidence = scores[classId] if confidence > confThreshold: center_x = int(detection[0] * frameWidth) center_y = int(detection[1] * frameHeight) width = int(detection[2] * frameWidth) height = int(detection[3] * frameHeight) left = int(center_x - width / 2) top = int(center_y - height / 2) classIDs.append(classId) confidences.append(float(confidence)) boxes.append([left, top, width, height]) indices = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold) for i in indices: i = i[0] box = boxes[i] left = box[0] top = box[1] width = box[2] height = box[3] center_x = int(left + (width / 2)) center_y = int(top + (height / 2)) object = self.classes[classIDs[i]] if self.draw: if object == "Rock": color = (255, 0, 0) elif object == "Paper": color = (0, 255, 0) elif object == "Scissors": color = (0, 0, 255) cv.rectangle(frame, (center_x - int(width / 2), center_y + int(height / 2)), (center_x + int(width / 2), center_y - int(height / 2)), color) prediction = { 'x': center_x, 'y': center_y, 'width': width, 'height': height, 'class': object, 'confidence': confidences[i] } framePredictions.append(prediction) self.processedQueue.put(frame) self.predictionQueue.put(framePredictions)
def config_path(basepath): return utils.file_path(basepath)
def build(self): '''Build the user interface''' self.title = 'Rock Paper Scissors' self.configuration = Config() self.camera = ImageProvider() self.process = ImageProcessor(self.camera, self.configuration) self.game = Game() self.LB = LabelBoxUpload() sidebar_width = 0.3 frame_width, frame_height = self.camera.get_dimensions() win_width, win_height = Window.size # Set window size and position Window.left = (win_width - frame_width) / 2 Window.size = (frame_width, frame_height / (1 + sidebar_width)) # Play button self.play = Button(text="Play", size_hint_x=1.0, size_hint_y=0.1, font_size=50) self.score_label = Label(text="", size_hint_y=0.1, font_size='20sp') self.play.bind(on_press=self.start_game) # Main image and text overlay self.img_layout = AnchorLayout(anchor_x='left', anchor_y='center') self.img = Image(keep_ratio=True, allow_stretch=True, size_hint_x=1) self.big_text = Label(text="", font_size='75sp', markup=True) self.img_layout.add_widget(self.img) self.img_layout.add_widget(self.big_text) # Main layout self.layout = BoxLayout(orientation='horizontal') self.sidebar = BoxLayout(orientation='vertical', size_hint_x=sidebar_width) # Bottom layout to display small images self.plays_layout = GridLayout(cols=1, size_hint=(.5, .3), padding=(2, 2), pos_hint={'center_x': .5}) self.player_img = Image(keep_ratio=True, allow_stretch=True, size_hint_x=.5, size_hint_y=1, source=file_path("img/black.png")) self.wrong = Button(text="Something Wrong?", size_hint_y=.04, opacity=0) self.wrong.bind(on_press=self.correction) self.computer_img = Image(keep_ratio=True, allow_stretch=True, size_hint_x=.5, size_hint_y=1, source=file_path("img/black.png")) self.player_label = Label(text="", size_hint_x=.2) self.computer_label = Label(text="", size_hint_x=.2) self.plays_layout.add_widget(self.player_img) self.plays_layout.add_widget(self.player_label) self.plays_layout.add_widget(self.computer_img) self.plays_layout.add_widget(self.computer_label) self.sidebar.add_widget(self.play) self.sidebar.add_widget(self.score_label) self.sidebar.add_widget(self.plays_layout) self.sidebar.add_widget(self.wrong) self.layout.add_widget(self.img_layout) self.layout.add_widget(self.sidebar) self.active_game = False self.last_frame = None self.last_play = None self.computer_score = 0 self.player_score = 0 Clock.schedule_interval(self.update, 1.0 / 33.0) return self.layout
from core.classification import Classification from core.neuron import NeuralNetwork from model.cleaner import Cleaner from model.gameboard import GameBoard from model.object import Object from settings import (CELL_MARGIN, CELL_HEIGHT, CELL_WIDTH, DIR_DOWN, DIR_LEFT, DIR_RIGHT, DIR_UP, GRID_HEIGHT, GRID_WIDTH, SCREEN_SIZE) from utils import file_path # Initialize neural network NETWORK = NeuralNetwork() # Initialize classification (creates decision tree based on training set) CLASSIFICATION = Classification( file_path('media.training_sets', 'train_cleaning'), file_path('media.training_sets', 'train_refill'), ) CLASSIFICATION.draw_cleaning_tree() CLASSIFICATION.draw_refill_tree() # Initialize display pygame.init() pygame.display.set_caption('PRO CLEANER 9000') SCREEN = pygame.display.set_mode(SCREEN_SIZE) CLOCK = pygame.time.Clock() # Load paths of images IMAGES = { 'floor': file_path('media.images', 'floor_cell.jpg'), 'agent': file_path('media.images', 'cleaner.png'),
from model.gameboard import GameBoard from model.object import Object from settings import ( CELL_MARGIN, CELL_HEIGHT, CELL_WIDTH, DIR_DOWN, DIR_LEFT, DIR_RIGHT, DIR_UP, GRID_HEIGHT, GRID_WIDTH, SCREEN_SIZE ) from utils import file_path # Initialize neural network NETWORK = NeuralNetwork() # Initialize classification (creates decision tree based on training set) CLASSIFICATION = Classification( file_path('media.training_sets', 'train_cleaning'), file_path('media.training_sets', 'train_refill'), ) CLASSIFICATION.draw_cleaning_tree() CLASSIFICATION.draw_refill_tree() # Initialize display pygame.init() pygame.display.set_caption('PRO CLEANER 9000') SCREEN = pygame.display.set_mode(SCREEN_SIZE) CLOCK = pygame.time.Clock() # Load paths of images IMAGES = {