def main(): arguments = DictObj(vars(ArgsParser.getArgv(ArgsParser.createParser()))) # arguments = DictObj({"command": "dir", "file": "D:\PyProject\setterdog\src\\user_config.json", "debug": 0}) # print(arguments) debug.getInstance(arguments.debug, "./logger.log", 0, 0) Configuration.getInstance(arguments.file, arguments.command) # print(Configuration.GI().config) """ debug.getInstance(logging.getLevelName(Configuration.GI().config.debug.logLevel), Configuration.GI().config.debug.fileName, 0, 0)""" Helper.createFolder(Configuration.GI().config.output.outputDir) Helper.createFolder(Configuration.GI().config.report.reportDir) outputFile = os.path.join(Configuration.GI().config.output.outputDir, Configuration.GI().config.output.outputFileNamePattern. format(date=Helper.getCurrentDate())) stdout = StdoutData(Configuration.GI().config.launchCommand, True, outputFile) a = Analyzer(Configuration.GI().config.pattern) a.calculatePatternMatches(stdout.getOutputData()) report = Reporter(Configuration.GI().config.report.reportDir, Configuration.GI().config.report.reportFileNamePattern.format(date=Helper.getCurrentDate()), a.expandedPattern) report.writeReport() a.returnCode(stdout.returnCode)
def __init__(self) -> None: """ Assign the speech recognition object and start the audio handling thread """ self.__listener = sr.Recognizer() __audio_proc = Thread(target=self.__outputHandler) __audio_proc.start() # Remove stragglers to avoid corruption exceptions temp_storage_dir = path.dirname(Configuration.GetFilePath("temp_microphone_storage")) for file in listdir(temp_storage_dir): remove(os.path.join(path.dirname(Configuration.GetFilePath("temp_microphone_storage")), file))
def __render(self, output_location: str) -> None: """ Initiate camera frame :param output_location: :return: """ write_process = None encodings = Configuration.known_encodings() while self.__target.isOpened(): # Read and assign current frame. render, frame = self.__target.read() if self.__lastFrame is None: self.__lastFrame = cv2.GaussianBlur( cv2.cvtColor(imutils.resize(frame, width=500), cv2.COLOR_BGR2GRAY), (21, 21), 0) continue try: if self.__isMotion(frame) or ( (datetime.now() - self.__lastDetectedTime).seconds < 5): write_process = self.__faceTrack(frame, encodings, write_process, output_location) except Exception as e: print(e) if cv2.waitKey(1) & 0xFF == ord('q'): self.close() elif render: cv2.imshow(f'Camera {self.target_id}', frame) if write_process is not None: write_process.write(frame)
def __init__(self, url): self.my_sql_config = Configuration(url, "_my_sql") self.Person_mysql = self.my_sql_config.Base.classes.person self.Scientific_project_mysql = self.my_sql_config.Base.classes.scientific_project self.Conference_mysql = self.my_sql_config.Base.classes.conference self.Publisher_mysql = self.my_sql_config.Base.classes.publisher self.Conference_info_mysql = self.my_sql_config.Base.classes.conference_info
def __init__(self, url): self.result_config = Configuration(url, "_result") self.Subdivision_result = self.result_config.Base.classes.subdivision self.Person_result = self.result_config.Base.classes.person self.Employee_result = self.result_config.Base.classes.employee self.Student_result = self.result_config.Base.classes.student self.Year_result = self.result_config.Base.classes.year self.Group_result = self.result_config.Base.classes.group_info self.Program_result = self.result_config.Base.classes.program self.Specialization_result = self.result_config.Base.classes.specialization self.Schedule_result = self.result_config.Base.classes.schedule self.Mark_result = self.result_config.Base.classes.mark self.Scientific_project_result = self.result_config.Base.classes.scientific_project self.Conference_result = self.result_config.Base.classes.conference self.Conference_info_result = self.result_config.Base.classes.conference_info self.Publisher_result = self.result_config.Base.classes.publisher self.Publication_result = self.result_config.Base.classes.publication self.Reading_list_result = self.result_config.Base.classes.reading_list self.Subject_result = self.result_config.Base.classes.subject self.Project_member_result = self.result_config.Base.classes.project_members self.Authors_result = self.result_config.Base.classes.authors self.Conference_participants = self.result_config.Base.classes.conference_participants #self.Group_schedule_result = self.result_config.Base.classes.group_schedule self.Campus_result = self.result_config.Base.classes.campus self.Faculty_result = self.result_config.Base.classes.faculty self.Payment_result = self.result_config.Base.classes.payment self.Results_result = self.result_config.Base.classes.results self.Room_result = self.result_config.Base.classes.room self.Sanitization_result = self.result_config.Base.classes.sanitization self.Semester_result = self.result_config.Base.classes.semester self.Specialization_program_result = self.result_config.Base.classes.specialization_program self.Teenant_result = self.result_config.Base.classes.teenant self.University_result = self.result_config.Base.classes.university self.Visit_result = self.result_config.Base.classes.visit
def start(self, render: bool = True) -> None: """ Currently doesnt do a lot except for starting render, placeholder if more startup functionality is required. """ if render: self.__render(Configuration.GetFilePath("video_output_location"))
def setOutput(self, text: str) -> None: """ Set audio output for handler to speak :param text: output text :return: None """ self.__output_stack.append(text) base_dir = path.dirname(Configuration.GetFilePath("temp_microphone_storage")) output_path = Configuration.GetFilePath("temp_microphone_storage").format(audio_id=len([file for file in listdir(base_dir) if path.isfile( path.join(base_dir, file))])) language = Configuration.Get("language") out = gTTS(text, lang=language) out.save(output_path)
def test_post(self): tsp = Tsp(Configuration().problem) with app.test_client() as client: data = dict(user="******", solution=json.dumps(list(range(len(tsp.solution))))) res = client.post('/submitSolution', data=data) res = json.loads(res.data.decode('utf8')) print(res) assert int(res['distance']) > 1
def __init__(self) -> None: """ Assign all device objects """ Configuration() # Initiate configuration self.__audio = src.classes.SpeechHandler() self.__video = src.classes.CameraHandler() self.__start()
def get_img(solution): tsp = Tsp(Configuration().problem) try: solution = solution.split("-") tsp.solution = solution finally: fig = tsp.draw(True) output = io.BytesIO() FigureCanvas(fig).print_png(output) return Response(output.getvalue(), mimetype='image/png')
def test_run_rnd(self): tsp = Tsp(Configuration().problem) record = 999999 for _ in range(1000000): rnd = Random() rnd.shuffle(tsp.solution) post_distance = tsp.distance(tsp.solution) if post_distance < record: record = post_distance print(post_distance) tsp.drawUI()
def __init__(self, url): self.oracle_config = Configuration(url, "_oracle") self.Person_oracle = self.oracle_config.Base.classes.person self.Year_oracle = self.oracle_config.Base.classes.year self.Program_oracle = self.oracle_config.Base.classes.program self.Mark_oracle = self.oracle_config.Base.classes.mark self.Subject_oracle = self.oracle_config.Base.classes.subject self.Subdivision_oracle = self.oracle_config.Base.classes.subdivision self.Employee_oracle = self.oracle_config.Base.classes.employee self.Group_oracle = self.oracle_config.Base.classes.group_info self.Specialization_oracle = self.oracle_config.Base.classes.specialization
def submit(user, solution, do_submit): tsp = Tsp(Configuration().problem) solution = list(filter(lambda x: str(x).isdigit(), solution)) dist = tsp.distance(solution) print(do_submit) rank = 0 if not dist: return make_response(json.dumps({'distance': "Solution is invalid"})) if not do_submit or int(do_submit): db = DBconnector() rank = db.insert_new_highscore(name=user, score=dist, solution=solution) return make_response(json.dumps({'distance': dist, 'rank': rank}))
def test_run(self): for t in range(1): s = Solver(35000) tsp = Tsp(Configuration().problem) pre_distance = tsp.distance(tsp.solution) post_distance, path = s.run() # if post_distance > 29.9: print(post_distance) print(path) assert pre_distance > post_distance tsp.solution = path tsp.drawUI()
def __init__(self, url): self.my_sql_config = Configuration(url, "_my_sql") self.Person_mysql = self.my_sql_config.Base.classes.person self.Scientific_project_mysql = self.my_sql_config.Base.classes.scientific_project self.Conference_mysql = self.my_sql_config.Base.classes.conference self.Publisher_mysql = self.my_sql_config.Base.classes.publisher self.Conference_info_mysql = self.my_sql_config.Base.classes.conference_info self.Publication_mysql = self.my_sql_config.Base.classes.publication self.Job_mysql = self.my_sql_config.Base.classes.job_position self.Authors_mysql = self.my_sql_config.Base.classes.authors self.Conference_participants_mysql = self.my_sql_config.Base.classes.participant_of_conference self.Reading_list_mysql = self.my_sql_config.Base.classes.reading_list self.Project_member_mysql = self.my_sql_config.Base.classes.project_member self.id = 1
def __init__(self, url): self.postgres_config = Configuration(url, "_postgres") self.University_postgres = self.postgres_config.Base.classes.university self.Faculty_postgres = self.postgres_config.Base.classes.faculty self.Subdivision_postgres = self.postgres_config.Base.classes.subdivision self.Specialization_postgres = self.postgres_config.Base.classes.specialization self.Student_group_postgres = self.postgres_config.Base.classes.student_group self.Student_postgres = self.postgres_config.Base.classes.student self.Semester_postgres = self.postgres_config.Base.classes.semester self.Subject_postgres = self.postgres_config.Base.classes.subject self.Employee_postgres = self.postgres_config.Base.classes.employee self.Specialization_program_postgres = self.postgres_config.Base.classes.specialization_program self.Results_postgres = self.postgres_config.Base.classes.results self.id = 1
def __init__(self): # engine = db.create_engine('dialect+driver://user:pass@host:port/db') db_path = Configuration().path_to_db engine = db.create_engine('sqlite:///{}'.format(db_path)) self.connection = engine.connect() metadata = db.MetaData() self.highscore = db.Table( 'highscore', metadata, db.Column('Id', db.Integer(), primary_key=True, autoincrement=True), db.Column('name', db.String(255), nullable=False), db.Column('datetime', db.String(255), nullable=False), db.Column('score', db.Float(), nullable=False), db.Column( 'solution', db.String(1080), )) metadata.create_all(engine)
def __init__(self, url): self.result_config = Configuration(url, "_result") self.Subdivision_result = self.result_config.Base.classes.subdivision self.Person_result = self.result_config.Base.classes.person self.Employee_result = self.result_config.Base.classes.employee self.Student_result = self.result_config.Base.classes.student self.Year_result = self.result_config.Base.classes.year self.Group_result = self.result_config.Base.classes.group_info self.Program_result = self.result_config.Base.classes.program self.Specialization_result = self.result_config.Base.classes.specialization self.Schedule_result = self.result_config.Base.classes.schedule self.Mark_result = self.result_config.Base.classes.mark self.Scientific_project_result = self.result_config.Base.classes.scientific_project self.Conference_result = self.result_config.Base.classes.conference self.Conference_info_result = self.result_config.Base.classes.conference_info self.Publisher_result = self.result_config.Base.classes.publisher self.Publication_result = self.result_config.Base.classes.publication self.Reading_list_result = self.result_config.Base.classes.reading_list self.Subject_result = self.result_config.Base.classes.subject self.Project_member_result = self.result_config.Base.classes.project_members self.Authors_result = self.result_config.Base.classes.authors self.Conference_participants = self.result_config.Base.classes.conference_participants
def __outputHandler(self) -> None: """ Output handling thread :return: None """ base_dir = path.dirname(Configuration.GetFilePath("temp_microphone_storage")) while True: for file in [path.join(base_dir, file) for file in listdir(base_dir) if path.isfile(path.join(base_dir, file))]: try: playsound.playsound(file) except playsound.PlaysoundException as e: print(f"Playback error: {e}") if path.exists(file): try: remove(file) except PermissionError as e: continue time.sleep(1)
def run(self): tsp = Tsp(Configuration().problem) c = tsp.solution record = tsp.distance(c) total_record = record best_path = None for i in range(1, self.max_epoch): c1 = random.randint(0, len(c) - 1) c2 = random.randint(0, len(c) - 1) t = c[c1] c[c1] = c[c2] c[c2] = t d = tsp.distance(c) if d < record or self.check_temp(i): if d < total_record: total_record = d best_path = deepcopy(c) record = d else: t = c[c1] c[c1] = c[c2] c[c2] = t return total_record, best_path
def __faceTrack(self, frame, encodings, write_process, output_location) -> cv2.VideoWriter: """ Track faces upon a frame :param frame: target frame :param encodings: known encodings :param write_process: (un)active write process :param output_location: output for writing process :return: updated writing process """ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) locations = face_recognition.face_locations(rgb_frame) found_names = [] try: for encoding in face_recognition.face_encodings( rgb_frame, locations): name = None match = None for set_name in encodings.keys(): match = face_recognition.compare_faces(encodings[set_name], encoding, tolerance=0.50) if match[0]: name = set_name break self.__lastDetectedTime = datetime.now() found_names.append(name) except Exception as e: print("Error parsing face name: ", e) try: for (top, right, bottom, left), name in zip(locations, found_names): cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 0), 2) cv2.rectangle(frame, (left, bottom), (right, bottom), (0, 0, 0), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX name = name if name is not None else "Unkown" cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1) if self.__extractKnownFaces: frame_slice = rgb_frame[top:bottom, left:right] file_path = os.path.join( Configuration.GetFilePath("know_face_encodings"), name) if not os.path.exists(file_path): os.mkdir(file_path) Image.fromarray(frame_slice).save( os.path.join(file_path, f"{len(os.listdir(file_path))}.png")) except Exception as e: print("Error setting face rect: ", e) if locations and write_process is None: try: day_dir, timestamp = f'{re.sub(r"[-.:]", "_", str(datetime.now()))}'.split( " ") base_dir = os.path.dirname( os.path.dirname(os.path.abspath(output_location))) if day_dir not in os.listdir(base_dir): os.mkdir( os.path.dirname( output_location.format(directory=day_dir, timestamp=""))) write_process = cv2.VideoWriter( output_location.format(directory=day_dir, timestamp=timestamp), cv2.VideoWriter_fourcc(*'XVID'), 30.0, (640, 480)) except Exception as e: print(e) elif len(locations) == 0 and write_process is not None: write_process = None return write_process
def send_tsp(): return send_file(Configuration().problem)