コード例 #1
0
ファイル: program.py プロジェクト: InspiredCoders/bellerophon
def rename():
    """
    Main code to run
    """
    program_config = ConfigManager()
    db_location = program_config.get_config("database_location")

    blacklist_file_location = program_config.get_config("blacklist_file")
    print(os.path.realpath(__file__))
    blacklist_file_location = os.path.join(ConfigManager.current_dir,
                                           blacklist_file_location)
    target_location = input(
        "Provide target directory location(fully qualified location):")
    bellerophone = Bellerophone(blacklist_file_location)
    print("Renaming is in progress...")
    bellerophone.crawl_and_rename(target_location, True)
    if bellerophone.log == []:
        print("No objects to rename!")
    else:
        print("Renaming is completed and saving tracks...")
    with DatabaseContext(db_location) as db:
        db.create_processing_history_table()
    with DatabaseContext(db_location) as db:
        for child in bellerophone.log:
            db.insert_into_processing_history_table(child[0], child[1],
                                                    child[2], child[3],
                                                    child[4], child[5],
                                                    child[6], child[7])
    print("Execution completed.")
コード例 #2
0
class TokenManager():
    '''
    Manages JSON web tokens and gives a token response back based on given user
    '''
    def __init__(self):

        self.config = ConfigManager()
        self.key = Fernet.generate_key()
        #self.config.set_crypto(self.key)
        self.frn: Fernet = Fernet(self.config.get_crypto())

    def get_unencrypted_token(self, t: bytes) -> bytes:
        '''
        Unencrypts the given JWT

        @token: (bytes)-> JWT Token
        @returns: (bytes) -> A encrypted token.
        '''

        return self.frn.decrypt(t)

    def get_encrypted_token(self, user: UserLogin) -> bytes:
        '''
        Gives a JWT response encoded.

        @user: UserLogin -> username and password from the login form in front end
        @returns: str -> A JWT token
        '''

        token: str = jwt.encode(    #This token is to be given to the user
            {
                "username" : user.username,
                "password" : user.password,
                "exp" : datetime.datetime.utcnow() + datetime.timedelta(days=1)
            },
            self.config.get_config("secret"),
            algorithm="HS256"
        )

        return self.frn.encrypt(token)  #encrypting the login JWT

    def get_payload(self, token: bytes) -> dict:
        '''
        Gets the payload data from a given token, decoded using a secret.

        @token: str -> the JWT
        @returns: dict -> The user's information.
        '''

        payload: dict = jwt.decode(token,
                                   self.config.get_config("secret"),
                                   algorithms=["HS256"])
        return payload
コード例 #3
0
    def __init__(self):
        self.hour = None
        self.minute = None
        self.time_window_hours = ConfigManager.get_config()['hours_to_check']
        self.time_window_minutes = ConfigManager.get_config(
        )['minutes_to_check']

        self.music_player = MusicPlayer()
        self.camera = Camera()
        self.model = Model()

        # for storing images
        self.counter = 0
コード例 #4
0
ファイル: model.py プロジェクト: oBoii/alarm
 def __init__(self):
     # https://github.com/keras-team/keras/issues/5640
     self.session = tf.Session(graph=tf.Graph())
     with self.session.graph.as_default():
         tf.keras.backend.set_session(self.session)
         self.model = tf.keras.models.load_model(
             ConfigManager.get_config()['model'])
コード例 #5
0
ファイル: program.py プロジェクト: InspiredCoders/bellerophon
def find_replace():
    """
    Find and Replace
    """
    program_config = ConfigManager()
    db_location = program_config.get_config("database_location")

    target_location = input(
        "Provide target directory location(fully qualified location):")
    bellerophone = Bellerophone("")
    old_string = input("FIND:")
    if old_string:
        new_string = input("REPLACE:")
        if new_string:
            bellerophone.crawl_and_find_and_replace(target_location, True,
                                                    old_string, new_string)
        if bellerophone.log == []:
            print("No objects to rename!")
        else:
            print("Renaming is completed and saving tracks...")
        with DatabaseContext(db_location) as db:
            db.create_processing_history_table()
        with DatabaseContext(db_location) as db:
            for child in bellerophone.log:
                db.insert_into_processing_history_table(
                    child[0], child[1], child[2], child[3], child[4], child[5],
                    child[6], child[7])
    print("Execution completed.")
コード例 #6
0
ファイル: camera.py プロジェクト: oBoii/alarm
    def save_image(image, reason='automatic'):
        save_path = ConfigManager.get_config()['save_image_path']
        if reason == ('automatic'
                      and not ConfigManager.get_config()['automatic_save']
                      ) or len(save_path) == 0:
            return

        skip = ConfigManager.get_config()['skip_image_count']
        count = len(os.listdir(save_path)) + skip

        now = datetime.datetime.now()
        file_name = '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day,
                                               now.hour, now.minute,
                                               now.second)

        file_path_name = '{}image{}_{}.jpg'.format(save_path, count, file_name)
        cv2.imwrite(file_path_name, image)
コード例 #7
0
ファイル: main.py プロジェクト: oBoii/alarm
def init():
    t = SetInterval(2, tick)
    t.start()

    if ConfigManager.get_config()['production'] == 'True':
        app.run(host='0.0.0.0')
    else:
        app.run()
コード例 #8
0
ファイル: camera.py プロジェクト: oBoii/alarm
    def capture_screenshot():
        if Camera.use_camera:
            Camera.camera.start_preview()

            stream = io.BytesIO()
            Camera.camera.capture(stream, format='jpeg')

            data = np.fromstring(stream.getvalue(), dtype=np.uint8)
            image = cv2.imdecode(data, cv2.IMREAD_COLOR)

            Camera.camera.stop_preview()
        else:
            im_path = ConfigManager.get_config()['test_image_path']
            image = cv2.imread(im_path)

        return image
コード例 #9
0
ファイル: music_player.py プロジェクト: oBoii/alarm
class MusicPlayer():
    p = None
    is_playing = False
    audio_file = ConfigManager.get_config()['audio_file']

    @staticmethod
    def play():
        if not MusicPlayer.is_playing:
            if is_linux():
                MusicPlayer.play_on_linux()
            else:
                MusicPlayer.play_on_windows()

            MusicPlayer.is_playing = True

    @staticmethod
    def stop():
        if MusicPlayer.is_playing:
            print("Stopping music...")
            if is_linux():
                MusicPlayer.stop_on_linux()
            MusicPlayer.is_playing = False

    @staticmethod
    def play_on_linux():
        print('Playing music linux...')

        pygame.init()
        pygame.mixer.music.load(MusicPlayer.audio_file)
        pygame.mixer.music.play(-1)  # -1 for continuous loop

    @staticmethod
    def play_on_windows():
        print('playing music windows...')
        winsound.PlaySound(MusicPlayer.audio_file, winsound.SND_ASYNC)

    @staticmethod
    def stop_on_linux():
        print('stopping music linux...')
        pygame.mixer.music.stop()

    @staticmethod
    def stop_on_windows():
        print('stopping music windows...')
        winsound.PlaySound(None, winsound.SND_PURGE)
コード例 #10
0
ファイル: camera.py プロジェクト: oBoii/alarm
class Camera:
    use_camera = ConfigManager.get_config()['use_camera'] == 'True'

    if use_camera:
        from picamera import PiCamera
        camera = PiCamera()
        camera.resolution = (650, 480)

    @staticmethod
    def capture_screenshot():
        if Camera.use_camera:
            Camera.camera.start_preview()

            stream = io.BytesIO()
            Camera.camera.capture(stream, format='jpeg')

            data = np.fromstring(stream.getvalue(), dtype=np.uint8)
            image = cv2.imdecode(data, cv2.IMREAD_COLOR)

            Camera.camera.stop_preview()
        else:
            im_path = ConfigManager.get_config()['test_image_path']
            image = cv2.imread(im_path)

        return image

    @staticmethod
    def save_image(image, reason='automatic'):
        save_path = ConfigManager.get_config()['save_image_path']
        if reason == ('automatic'
                      and not ConfigManager.get_config()['automatic_save']
                      ) or len(save_path) == 0:
            return

        skip = ConfigManager.get_config()['skip_image_count']
        count = len(os.listdir(save_path)) + skip

        now = datetime.datetime.now()
        file_name = '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day,
                                               now.hour, now.minute,
                                               now.second)

        file_path_name = '{}image{}_{}.jpg'.format(save_path, count, file_name)
        cv2.imwrite(file_path_name, image)
コード例 #11
0
class Karaoke:
    """
    This class is basically the main class.
    It uses all other classes to execute commands inserted from the ui
    If it has a valid config, it will start
    If it does not have a valid config
    """

    def __init__(self):
        self.config_manager = ConfigManager()

        if self.config_manager.has_valid_config():
            print("Valid config file is detected")
            self.setup()
        else:
            print("No valid config file is found")

    def has_valid_config(self):
        if not self.config_manager.has_valid_config():
            print("Invalid config")
            return False
        if not self.csv_manager.is_csv_valid():
            print("Invalid tracklist")
            return False
        
        return True

    def get_video_directory(self):
        return self.config_manager.get_config('PATHS', 'video_directory')

    def set_video_directory(self, video_dir):
        return self.config_manager.set_config('PATHS', 'video_directory', video_dir)

    def get_tracklist_file(self):
        return self.config_manager.get_config('PATHS', 'tracklist_file')

    def set_tracklist_file(self, tracklist_file):
        return self.config_manager.set_config('PATHS', 'tracklist_file', tracklist_file)

    def setup(self):
        self.setup_csv_file_manager()
        self.setup_mpv_manager()

    def setup_csv_file_manager(self):
        tracklist = self.config_manager.get_config('PATHS', 'tracklist_file')
        self.csv_manager = CsvManager(tracklist)

    def setup_mpv_manager(self):
        video_dir = self.config_manager.get_config('PATHS', 'video_directory')
        song_completed_callback = self.csv_manager.record_song_played
        self.mpv_manager = MpvManger(song_completed_callback, video_dir)

    def test(self):
        playlist = self.csv_manager.generate_red_playlist()
        self.mpv_manager.play_playlist(playlist)

    def get_all_playlists(self):
        try:
            playlists = self.csv_manager.get_all_playlist_names()
        except AttributeError:
            playlists = []
        return playlists

    def play_playlist(self, playlist_name, shuffle=False, longest_not_played_first=False):
        playlist = self.csv_manager.get_playlist_by_name(playlist_name, shuffle, longest_not_played_first)
        self.mpv_manager.play_playlist(playlist)

    def allowed_to_alter_csv_file(self):
        return self.csv_manager.allowed_to_alter_csv_file()