def __init__(self, in_cvs: str, in_json: str, in_enc: str, out_enc: str, out_name: str): self._information = Information() self._in_cvs = in_cvs self._in_json = in_json self._in_enc = in_enc self._out_enc = out_enc self._out_name = out_name self._is_load_stat_done = False self._is_load_data_done = False
def instruction_query(): """ Offers to open a file on their computer with rules and scoring. """ print("\nWould you like a score chart/list of rules") print("to look at while you play (y/n)?") if yes_or_no("Note: this will open a file on your computer. > "): try: os.startfile("Scorechart.txt") except FileNotFoundError: Information.make_scoring_file() os.startfile("Scorechart.txt")
def inf(self): #bővebbinf. gomb függvény indexes = self.tableWidget.selectionModel().selectedRows() #kijelölt sor tmp = [] if indexes: #van-e kiválasztva valami for index in sorted(indexes): for i in range(len(self.cars)): if index.data() == self.cars[i][0]: #kimásolja a tmp változóba a megfelelő sort tmp.append(self.cars[i]) break if len(tmp) > 0: #van-e valami a tmp-be information = Information(tmp, self.cardata) #példányosítás , változó átadás és autók adatai information.exec_() #meghívja az információs ablakot else: QMessageBox.about(self, "Hiba", "A bővebb információhoz ki kell választani valamit a táblázatból!") #kivételkezelés
def first_time(): """ This asks players if they've played the game before. If they say yes it prints a short description of the game's rules. """ while True: first_time = input("Is this your first time playing the game? (y/n): ") if first_time == "y": Information.instructions() Information.make_scoring_file() break elif first_time == "n": break else: print("Please enter 'y' or 'n'")
def __init__(self, screen_size): self.screen = pygame.display.set_mode(screen_size, pygame.FULLSCREEN) self.screen.fill([255, 255, 255]) self.map = Map(self.screen, screen_size) self.strategy = Strategy(self.screen, screen_size) self.information = Information(self.screen, screen_size) self.fullmap = FullMap(self.screen, screen_size)
def __init__( self, parent=None, ): super(MainWindow, self).__init__(parent) self.setupUi(self) #item1=None #导入外部定义的Class self.Face = Face() self.SqlOperator = SqlOperator() self.information = Information() self.cameraThread = VideoThread() self.recomThread = RecomThread() self.ret = '' self.num = '' #self.major = '' #self.infor_img = [] # self.git_thread = CloneThread() self.__information = CommonHelper.FrameCustomerTitle( self.information, "信息采集界面") self.__information.move(160, 110) self.__information.resize(765, 443) # self.book_infor = Book_infor(self.item) # self.__book_infor = CommonHelper.FrameCustomerTitle(self.book_infor, "图书详情界面") # self.__book_infor.move(160, 100) # self.__book_infor.resize(850, 660) self.QMessageBox = QtWidgets.QMessageBox() self.icon = QtGui.QIcon() #设置图标 self.item = QtWidgets.QListWidgetItem() self.font = QtGui.QFont() #设置字体 self.font.setPointSize(12) self.Logopic() #logo图片 #显示时间 timer = QTimer(self) timer.timeout.connect(self.showtime) timer.start()
class FinanceManagerController: def __init__(self, name): self.information = Information(name) @property def history(self): return self.information.history def balance(self): content = [] for i in CurrencyRatesModel.get_rates(): bal = self.information.current_balance / float(i["buy"]) content.append([i["ccy"], bal, i["buy"]]) return [["UAH", self.information.current_balance, 1]] + content def update_balance(self, income): self.information.amount = int(income) self.information.current_balance += int(income) history = History(int(income), datetime.now().isoformat()) self.information.history.append(history) self.information.save()
def __init__(self): print("Initializing sensors...") # First, use iio to detect supported sensors self.device_count = idetect.detect_iio_sensors() if self.device_count > 0: self.readfrom = "iio_sensors" self.context = _create_context() self.sensor = IIO_READER() # Print the iio info information = Information(self.context) information.write_information() # More sensor types can be added here # make sure to change the value of self.readfrom # If this is still unset, no sensors were found; quit! if self.readfrom == 'unset': print('No suitable sensors found! Exiting.') sys.exit()
def extract_information(results, name, radius=None): print '***** extracting the information *****' info = Information(name) for result in results: # print len(result['typeProbHistory']) # print (len(result['historyParameters'])) # print info.AGA_max_len_hist # print info.ABU_max_len_hist # print info.PF_max_len_hist if result['estimationMode'] == 'AGA': if len(result['typeProbHistory']) > info.AGA_max_len_hist: info.AGA_max_len_hist = len(result['typeProbHistory']) info.AGA_estimationHist.append(result['historyParameters']) info.AGA_typeProbHistory.append(result['typeProbHistory']) info.AGA_trueParameter.append(result['trueParameters']) info.AGA_errors.append( calculate_error(result['trueParameters'], result['historyParameters'])) if result['estimationMode'] == 'ABU': if len(result['typeProbHistory']) > info.ABU_max_len_hist: info.ABU_max_len_hist = len(result['typeProbHistory']) info.ABU_estimationHist.append(result['historyParameters']) info.ABU_typeProbHistory.append(result['typeProbHistory']) info.ABU_trueParameter.append(result['trueParameters']) info.ABU_errors.append( calculate_error(result['trueParameters'], result['historyParameters'])) if result['estimationMode'] == 'MIN': if radius != None: print radius, result['mainAgentRadius'], radius == result[ 'mainAgentRadius'] if radius == result['mainAgentRadius']: if len(result['typeProbHistory']) > info.PF_max_len_hist: info.PF_max_len_hist = len(result['typeProbHistory']) info.PF_typeProbHistory.append(result['typeProbHistory']) info.PF_estimationHist.append(result['historyParameters']) info.PF_trueParameter.append(result['trueParameters']) info.PF_errors.append( calculate_error(result['trueParameters'], result['historyParameters'])) else: if len(result['typeProbHistory']) > info.PF_max_len_hist: info.PF_max_len_hist = len(result['typeProbHistory']) info.PF_typeProbHistory.append(result['typeProbHistory']) info.PF_estimationHist.append(result['historyParameters']) info.PF_trueParameter.append(result['trueParameters']) info.PF_errors.append( calculate_error(result['trueParameters'], result['historyParameters'])) return info
def extract_data(comment_data): #有些评论没有'title'属相。。。。这太匪夷所思了 if 'title' in comment_data.select('span[class="name"]')[0].attrs: user_information = comment_data.select( 'span[class="name"]')[0]['title'] + '_' + comment_data.select( 'span[class="name"]')[0].string else: user_information = comment_data.select('span[class="name"]')[0].string user_floor = comment_data.select('span[class="floor"]')[0].string #用户评论目前不太好取出来,所以暂且不取评论内容,只将用户上传的图片取出来 user_img_list = comment_data.select('img') #如果该用户没有上传图片,则不统计 if (len(user_img_list) == 0): return img_urls = [] for img in user_img_list: img_urls.append(img['src']) liked_num = int( comment_data.select('span[class="supportComment"]')[0].select('em') [0].string) return Information(user_information, img_urls, liked_num, user_floor)
def _process(file_path): storage = Information() print(f"ini {file_path}:", end=" ") config = loader_writer.load_ini(file_path, "utf-8") print("OK") is_correct_loading = loader_writer.load(storage, config["input"]["csv"], config["input"]["json"], config["input"]["encoding"]) print(f"json?=csv:", end=" ") if is_correct_loading: print("OK") else: print("UPS") print(f"output {config['output']['fname']}:", end=" ") loader_writer.output(storage, config["output"]["fname"], config["output"]["encoding"]) print("OK")
def __init__(self): self.builder = Gtk.Builder() self.builder.add_from_file(const.MAIN_PROG_FOLDER + const.UI_FOLDER + "main_ui.glade") handlers = { "on_open": self.on_open, "on_quit": self.on_quit, "run_fpga": self.run_fpga, "run_histopac": self.run_histopac, ###change to self.run_histopac "run_anizpac": self.run_anizpac, ###change to self.run_anizpac "run_pypac_signal": self.run_pypac_signal, "edit_config": self.edit_config, "edit_constants": self.edit_constants, "on_start": self.on_start, "on_stop": self.on_stop, "on_save": self.on_save, "on_pause": self.on_pause, "on_clear": self.on_clear, "zoom_en_shrink": self.z_en_shrink, "zoom_en_squeeze": self.z_en_squeeze, "zoom_en_left": self.z_en_mov_l, "zoom_en_right": self.z_en_mov_r, "zoom_en_up": self.z_en_up, "zoom_en_down": self.z_en_down, "zoom_en_log": self.z_en_log, "zoom_en_zero": self.z_en_zero, "zoom_t_shrink": self.z_t_shrink, "zoom_t_squeeze": self.z_t_squeeze, "zoom_t_left": self.z_t_left, "zoom_t_right": self.z_t_right, "zoom_t_down": self.z_t_down, "zoom_t_up": self.z_t_up, "zoom_t_log": self.z_t_log } self.builder.connect_signals(handlers) self.main_win = self.builder.get_object("main_win") self.init_Figs() main_grid = self.builder.get_object("main_grid") self.attach_Figs(main_grid) #tmp_foldername = "/home/das/job/plis/histo/apr14_4det_porog=90_delay=100_coinc_10h_night" self.curr_histo_folder = const.DEFAULT_CURR_HISTO_FOLDER self.spectra = Spectra(self.curr_histo_folder) self.fill_Figs(self.spectra.histo) zoom_args = { "en_magnification": 1e2, "en_v_step": 5e3, "en_h_step": 1e2, "t_magnification": 1e2, "t_v_step": 1e3, "t_h_step": 100.0 } self.zoom = Zoom(self.en_fig, self.t_fig, self.en_axes, self.t_axes, zoom_args) self.logger = Logger(path.join(const.MAIN_PROG_FOLDER, "journal.log")) self.logger.info("Program initialization OK") self.update_counts([0] * 4) self.info_textview = self.builder.get_object("info_textview") self.information = Information(self.info_textview) self.statusbar = self.builder.get_object("main_statusbar")
def extract_information(results, name, radius=None): # print '***** extracting the information *****' info = Information(name) for result in results: # print len(result['typeProbHistory']) # print (len(result['historyParameters'])) # print info.AGA_max_len_hist # print info.ABU_max_len_hist # print info.OGE_max_len_hist if result['parameter_estimation_mode'] == 'TRUE': # print 'true' # print 'time step:', result['timeSteps'] # print result['type_estimation_mode'] if len(result['typeProbHistory']) > info.TRUE_max_len_hist: info.TRUE_max_len_hist = len(result['typeProbHistory']) info.TRUE_timeSteps.append(result['timeSteps']) # info.TRUE_estimationHist.append(result['historyParameters']) # info.TRUE_typeProbHistory.append(result['typeProbHistory']) # info.TRUE_trueParameter.append(result['trueParameters']) # info.TRUE_errors.append(calculate_error(result['trueParameters'], result['historyParameters'])) if result['parameter_estimation_mode'] == 'AGA': if len(result['typeProbHistory']) > info.AGA_max_len_hist: info.AGA_max_len_hist = len(result['typeProbHistory']) info.AGA_timeSteps.append(result['timeSteps']) info.AGA_estimationHist.append(result['historyParameters']) info.AGA_typeProbHistory.append(result['typeProbHistory']) info.AGA_trueParameter.append(result['trueParameters']) error = calculate_error(result['trueParameters'], result['historyParameters']) # print 'AGA', result['path'], error info.AGA_errors.append(error) if result['parameter_estimation_mode'] == 'ABU': if len(result['typeProbHistory']) > info.ABU_max_len_hist: info.ABU_max_len_hist = len(result['typeProbHistory']) info.ABU_timeSteps.append(result['timeSteps']) info.ABU_estimationHist.append(result['historyParameters']) info.ABU_typeProbHistory.append(result['typeProbHistory']) info.ABU_trueParameter.append(result['trueParameters']) error = calculate_error(result['trueParameters'], result['historyParameters']) # print 'ABU', result['path'] , error info.ABU_errors.append(error) if result['parameter_estimation_mode'] == 'MIN': if radius != None: # print radius, result['mainAgentRadius'], radius == result['mainAgentRadius'] if radius == result['mainAgentRadius']: if len(result['typeProbHistory']) > info.OGE_max_len_hist: info.OGE_max_len_hist = len(result['typeProbHistory']) info.OGE_timeSteps.append(result['timeSteps']) info.OGE_typeProbHistory.append(result['typeProbHistory']) info.OGE_estimationHist.append(result['historyParameters']) info.OGE_trueParameter.append(result['trueParameters']) error = calculate_error(result['trueParameters'], result['historyParameters']) # print 'OGE', result['path'], error info.OGE_errors.append(error) else: if len(result['typeProbHistory']) > info.OGE_max_len_hist: info.OGE_max_len_hist = len(result['typeProbHistory']) info.OGE_timeSteps.append(result['timeSteps']) info.OGE_typeProbHistory.append(result['typeProbHistory']) info.OGE_estimationHist.append(result['historyParameters']) info.OGE_trueParameter.append(result['trueParameters']) error = calculate_error(result['trueParameters'], result['historyParameters']) # print 'OGE', result['path'], error info.OGE_errors.append(error) # print name print "number of AGA: ", len(info.AGA_timeSteps) print "number of ABU: ", len(info.ABU_timeSteps) print "number of OGE: ", len(info.OGE_timeSteps) return info
class MainWindow(QMainWindow, Ui_MainWindow, QThread): """ Class documentation goes here. """ #PictureFrame = pyqtSignal(int) def book_detial_1(self, item): self.book_detial = Book_detial(item) self.__book_detial = CommonHelper.FrameCustomerTitle( self.book_detial, "图书详情界面") self.__book_detial.move(160, 100) self.__book_detial.resize(850, 660) self.__book_detial.show() def __init__( self, parent=None, ): super(MainWindow, self).__init__(parent) self.setupUi(self) #item1=None #导入外部定义的Class self.Face = Face() self.SqlOperator = SqlOperator() self.information = Information() self.cameraThread = VideoThread() self.recomThread = RecomThread() self.ret = '' self.num = '' #self.major = '' #self.infor_img = [] # self.git_thread = CloneThread() self.__information = CommonHelper.FrameCustomerTitle( self.information, "信息采集界面") self.__information.move(160, 110) self.__information.resize(765, 443) # self.book_infor = Book_infor(self.item) # self.__book_infor = CommonHelper.FrameCustomerTitle(self.book_infor, "图书详情界面") # self.__book_infor.move(160, 100) # self.__book_infor.resize(850, 660) self.QMessageBox = QtWidgets.QMessageBox() self.icon = QtGui.QIcon() #设置图标 self.item = QtWidgets.QListWidgetItem() self.font = QtGui.QFont() #设置字体 self.font.setPointSize(12) self.Logopic() #logo图片 #显示时间 timer = QTimer(self) timer.timeout.connect(self.showtime) timer.start() # self.openCamera.clicked.connect(self.OpenCamera) # self.cameraThread.VideoFrame.connect(self.Fresh_Video)#Video_Thread线程开启后捕捉摄像头调用Fresh_Video刷新界面 # self.cameraThread.OpenVideoFlag.connect(self.Un_Open_Camera) #开启摄像头失败触发Un_Open_Camera函数 #logo图片 def Logopic(self): Im = cv2.imread('D:\\Face_book\\logo.png') # 通过Opencv读入一张图片 image_height, image_width = Im.shape[:2] # 获取图像的高,宽 QIm = cv2.cvtColor( Im, cv2.COLOR_BGR2RGB) # opencv读图片是BGR,qt显示要RGB,所以需要转换一下 QIm = QImage(QIm.data, image_width, image_height, QImage.Format_RGB888) self.LogoLabel.setScaledContents(True) #图片自适应大小 self.LogoLabel.setPixmap( QPixmap.fromImage(QIm)) # 将QImage显示在之前创建的QLabel控件中 #视频区初始化图片 self.CameraLabel.setScaledContents(True) #图片自适应大小 self.CameraLabel.setPixmap(QPixmap.fromImage(QIm)) #显示时间 def showtime(self): now = QDate.currentDate() data = now.toString(Qt.DefaultLocaleLongDate) #2018年10月5日 time_1 = QTime.currentTime() time_1 = time_1.toString(Qt.DefaultLocaleLongDate) #10:36:35 self.time_label.setText(data + time_1) # def OpenCamera(self): # #打开摄像头 # global t # #isopend=1 # # self.cap = cv2.VideoCapture() # if (not self.cap.isOpened()): # self.cap.open(0) # self.cap.set(3, 500) # self.cap.set(4, 600) # #isopend=0 # #self.PictureFrame.emit(isopend) ## pool = threadpool.ThreadPool(10) ## requests = threadpool.makeRequests(self.Show_img, ()) ## [pool.putRequest(req) for req in requests] ## pool.wait() # t =threading.Thread(target=self.Show_img,args=()) # t.start() # ## #获取当前帧图片 # def Show_img(self): # while True: # # QtCore.QCoreApplication.processEvents() # time.sleep(0.001) # self.ret, self.imread_img = self.cap.read() # rert_1, self.infor_img = self.cap.read() # if not self.ret: # print('error: failed to capture image') # return -1 # # self.detectorface() # # height, width= self.imread_img.shape[:2] # self.input_img = cv2.cvtColor(self.imread_img, cv2.COLOR_BGR2RGB) # self.show_pic = QImage(self.input_img.data, width, height, QImage.Format_RGB888) # self.CameraLabel.setScaledContents(True)#图片自适应大小 # #self.label_show_camera.setGeometry(0, 0, 241, 211)#图片显示的位置(最左上角的点+大小) # # 转为QImage对象 # self.CameraLabel.setPixmap(QPixmap.fromImage(self.show_pic)) # # def detectorface(self): # self.detector = dlib.get_frontal_face_detector() # img_gray = cv2.cvtColor(self.imread_img, cv2.COLOR_RGB2GRAY) # faces = self.detector(img_gray, 0) # # faces = facecompare.Face.detect(self.input_img) # if (len(faces) != 0): # # for i in range(len(faces)): # for k, d in enumerate(faces): # # 用红色矩形框出人脸 # cv2.rectangle(self.imread_img, (d.left(), d.top()), (d.right(), d.bottom()), (0, 0, 255), 3) def OpenCamera(self): if not self.cameraThread.isRunning(): self.cameraThread.start() self.openCamera.setText("关闭摄像头") else: self.cameraThread.Stop_Video() self.Logopic() def Fresh_Video(self, show_pic): self.CameraLabel.setScaledContents(True) #图片自适应大小 self.CameraLabel.setPixmap(QPixmap.fromImage(show_pic)) #self.VideoLabel.setPixmap(QPixmap.fromImage(qImg)) def Un_Open_Camera(self, bool): QtWidgets.QMessageBox.warning(self, "警告", "打开摄像头失败") #self.openCamera.setText("打开摄像头") def start_recomThread(self): if not self.recomThread.start(): self.recomThread.start() def start_gidentify(self): #self.recomThread.start() self.num, score = self.recomThread.gidentify() print(self.num) print(score) if (self.num == -1 and score == -1): self.QMessageBox.warning(self, '警告', '未检测到人脸,请检查网络连接或靠近识别') return 0 if (self.num != -1 and score > 0.80): result = self.recomThread.info_gidentify(self.num) #读取数据库信息 #print(result) if result == None: self.QMessageBox.warning(self, '警告', '数据库可能没有您的数据或者靠近再次识别') else: self.Name_label.setText(result[2]) self.Num_label.setText(result[3]) self.Class_label.setText(result[5]) self.Major_label.setText(result[4]) self.love_recom(result[3]) self.Class_recom(result[3]) self.Major_recom(result[4]) self.History(result[3]) self.Hot_recom(result[3]) self.Newbook_recom(result[3]) else: self.QMessageBox.warning(self, '警告', '数据库可能没有您的数据或者检查网络连接再次识别') # def gidentify(self): # #cv2.imwrite("./recommend.jpg", self.imread_img) # self.num, score= self.Face.compare("./recommend.jpg") # #img = cv2.cvtColor(self.imread_img, cv2.COLOR_RGB2GRAY) ## self.num, score= self.Face.compare(self.imread_img) # # print(self.num) # print(score) # # if(self.num ==-1 and score == -1): # self.QMessageBox.warning(self, '警告', '未检测到人脸,请检查网络连接或靠近识别') # return 0 # # if(self.num != -1 and score > 0.80): # result = self.SqlOperator.searchbystunum(self.num)#读取数据库信息 # if result == None: # self.QMessageBox.warning(self, '警告', '数据库可能没有您的数据或者靠近再次识别') # else: # self.Name_label.setText(result[2]) # self.Num_label.setText(result[3]) # self.Class_label.setText(result[5]) # self.Major_label.setText(result[4]) # self.love_recom(result[3]) # self.Class_recom() # self.Major_recom(result[4]) # self.History(result[3]) # self.Hot_recom() # self.Newbook_recom() # else: # self.QMessageBox.warning(self, '警告', '请检查网络连接或者靠近再次识别') def Search_book(self): my_str = self.Search_line.text() if (my_str == ''): self.QMessageBox.information(self, '警告', '请输入搜索内容') else: #self.search_result = self.SqlOperator.search_by_name(str(my_str).strip()) self.search_result = self.recomThread.Search_book(my_str) #print(self.search_result) for result in self.search_result: item = QtWidgets.QListWidgetItem(list(result)[1]) self.icon.addPixmap(QtGui.QPixmap(list(result)[9]), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(self.icon) self.Search_listWidget.setFont(self.font) item.setWhatsThis(list(result)[9]) self.Search_listWidget.addItem(item) ##################################### #喜好推荐 def love_recom(self, num): # lover_result_2=[] # lover_result = self.SqlOperator.search_lover_bystunum(str(num)) # if lover_result != None: # lover_result_1=str(list(lover_result)[0]).split('|') # #print(1) # for i in lover_result_1: # lover_result_2+=self.SqlOperator.searchdata(str(i)) # lover_result_2=list(lover_result_2) # random.shuffle (lover_result_2) # #print(lover_result_2) lover_result_2 = self.recomThread.love_recom(num) random.shuffle(lover_result_2) if (lover_result_2 == None): self.favor_listWidget.addItem('暂无推荐') else: for result in lover_result_2[:9]: #print((list(result)[1])) item = QtWidgets.QListWidgetItem(list(result)[1]) self.icon.addPixmap(QtGui.QPixmap(list(result)[9]), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(self.icon) self.favor_listWidget.setFont(self.font) item.setWhatsThis(list(result)[9]) self.favor_listWidget.addItem(item) #年级推荐 def Class_recom(self, num): # class_result=[] # self.class_listWidget.clear() # if self.num != -1: # class_result = self.SqlOperator.searchAll() # class_result=list(class_result) # random.shuffle (class_result) #print(lover_result_2) self.class_listWidget.clear() class_result = self.recomThread.class_recom(num) random.shuffle(class_result) if (class_result == None): self.class_listWidget.addItem('暂无推荐') else: for result in class_result[:9]: #print((list(result)[1])) item = QtWidgets.QListWidgetItem(list(result)[1]) self.icon.addPixmap(QtGui.QPixmap(list(result)[9]), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(self.icon) self.class_listWidget.setFont(self.font) item.setWhatsThis(list(result)[9]) self.class_listWidget.addItem(item) #专业推荐 def Major_recom(self, major): # major_result=[] # self.major_listWidget.clear() # major_result = self.SqlOperator.searchMajor(major) # major_result=list(major_result) # random.shuffle (major_result) self.major_listWidget.clear() major_result = self.recomThread.major_recom(major) random.shuffle(major_result) if (major_result == None): self.major_listWidget.addItem('暂无借书记录') else: for result in major_result[:9]: #print((list(result)[1])) item = QtWidgets.QListWidgetItem(list(result)[1]) self.icon.addPixmap(QtGui.QPixmap(list(result)[9]), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(self.icon) self.major_listWidget.setFont(self.font) item.setWhatsThis(list(result)[9]) self.major_listWidget.addItem(item) #历史记录 def History(self, num): # self.history_listWidget.clear() # self.history_result = self.SqlOperator.searchbynum(num) self.history_listWidget.clear() self.history_result = self.recomThread.history(num) if (self.history_result == None): self.history_listWidget.addItem('暂无借书记录') else: for result in self.history_result: item = QtWidgets.QListWidgetItem(list(result)[2]) #icon = QtGui.QIcon() self.icon.addPixmap(QtGui.QPixmap(list(result)[1]), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(self.icon) self.history_listWidget.setFont(self.font) item.setWhatsThis(list(result)[1]) self.history_listWidget.addItem(item) #热门推荐 def Hot_recom(self, num): # hot_result=[] # self.hot_listWidget.clear() # if self.num != -1: # hot_result = self.SqlOperator.searchAll() # hot_result=list(hot_result) # random.shuffle (hot_result) # #print(lover_result_2) self.hot_listWidget.clear() hot_result = self.recomThread.hot_recom(num) random.shuffle(hot_result) if (hot_result == None): self.hot_listWidget.addItem('暂无借书记录') else: for result in hot_result[:9]: #print((list(result)[1])) item = QtWidgets.QListWidgetItem(list(result)[1]) self.icon.addPixmap(QtGui.QPixmap(list(result)[9]), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(self.icon) self.hot_listWidget.setFont(self.font) item.setWhatsThis(list(result)[9]) self.hot_listWidget.addItem(item) def Newbook_recom(self, num): # newbook_result=[] # self.Newbook_listWidget.clear() # if self.num != -1: # newbook_result = self.SqlOperator.searchAll() # newbook_result=list(newbook_result) # random.shuffle (newbook_result) # #print(lover_result_2) self.Newbook_listWidget.clear() newbook_result = self.recomThread.newbook_recom(num) random.shuffle(newbook_result) if (newbook_result == None): self.Newbook_listWidget.addItem('暂无借书记录') else: for result in newbook_result[:9]: #print((list(result)[1])) item = QtWidgets.QListWidgetItem(list(result)[1]) self.icon.addPixmap(QtGui.QPixmap(list(result)[9]), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(self.icon) self.Newbook_listWidget.setFont(self.font) item.setWhatsThis(list(result)[9]) self.Newbook_listWidget.addItem(item) #打开摄像头 @pyqtSlot() def on_openCamera_clicked(self): # self.git_thread.OpenCamera() #打开摄像头 # self.git_thread.show_img() # #self.PictureFrame.connect(self.Show_img) self.OpenCamera() #打开摄像头 self.cameraThread.VideoFrame.connect( self.Fresh_Video) #Video_Thread线程开启后捕捉摄像头调用Fresh_Video刷新界面 self.cameraThread.OpenVideoFlag.connect( self.Un_Open_Camera) #开启摄像头失败触发Un_Open_Camera函数 #进行识别 @pyqtSlot() def on_recommend_pushButton_clicked(self): #if not self.ret: if not self.cameraThread.isRunning(): QMessageBox.information(self, '提示', '请先打开摄像头') else: #清空上次记录 self.Name_label.clear() self.Num_label.clear() self.Class_label.clear() self.Major_label.clear() #self.gidentify() #进行识别推荐 self.start_recomThread() self.start_gidentify() #信息采集 @pyqtSlot() def on_Info_pushButton_clicked(self): #if not self.ret: if not self.cameraThread.isRunning(): print(not self.cameraThread.isRunning()) QMessageBox.information(self, '提示', '请先打开摄像头') else: #cv2.imwrite("./infor.jpg", self.infor_img) self.information.Infor_img("./infor.jpg") self.__information.show() #图书搜索 @pyqtSlot() def on_Serach_pushButton_clicked(self): self.Search_listWidget.clear() self.Search_book() @pyqtSlot() def on_Clera_pushButton_clicked(self): self.Search_line.setText('') #清空 @pyqtSlot(QListWidgetItem) def on_Search_listWidget_itemClicked(self, item): #self.__book_infor.show() self.book_detial_1(item) @pyqtSlot(QListWidgetItem) def on_favor_listWidget_itemClicked(self, item): #self.__book_infor.show() self.book_detial_1(item) @pyqtSlot(QListWidgetItem) def on_class_listWidget_itemClicked(self, item): #self.__book_infor.show() self.book_detial_1(item) @pyqtSlot(QListWidgetItem) def on_history_listWidget_itemClicked(self, item): #QMessageBox.information(self, '提示', '请选择其他版面点击') self.book_detial_1(item) @pyqtSlot(QListWidgetItem) def on_hot_listWidget_itemClicked(self, item): #self.__book_infor.show() self.book_detial_1(item) @pyqtSlot(QListWidgetItem) def on_major_listWidget_itemClicked(self, item): #self.__book_infor.show() self.book_detial_1(item) @pyqtSlot(QListWidgetItem) def on_Newbook_listWidget_itemClicked(self, item): self.book_detial_1(item)
class UI(): def __init__(self): self.builder = Gtk.Builder() self.builder.add_from_file(const.MAIN_PROG_FOLDER + const.UI_FOLDER + "main_ui.glade") handlers = { "on_open": self.on_open, "on_quit": self.on_quit, "run_fpga": self.run_fpga, "run_histopac": self.run_histopac, ###change to self.run_histopac "run_anizpac": self.run_anizpac, ###change to self.run_anizpac "run_pypac_signal": self.run_pypac_signal, "edit_config": self.edit_config, "edit_constants": self.edit_constants, "on_start": self.on_start, "on_stop": self.on_stop, "on_save": self.on_save, "on_pause": self.on_pause, "on_clear": self.on_clear, "zoom_en_shrink": self.z_en_shrink, "zoom_en_squeeze": self.z_en_squeeze, "zoom_en_left": self.z_en_mov_l, "zoom_en_right": self.z_en_mov_r, "zoom_en_up": self.z_en_up, "zoom_en_down": self.z_en_down, "zoom_en_log": self.z_en_log, "zoom_en_zero": self.z_en_zero, "zoom_t_shrink": self.z_t_shrink, "zoom_t_squeeze": self.z_t_squeeze, "zoom_t_left": self.z_t_left, "zoom_t_right": self.z_t_right, "zoom_t_down": self.z_t_down, "zoom_t_up": self.z_t_up, "zoom_t_log": self.z_t_log } self.builder.connect_signals(handlers) self.main_win = self.builder.get_object("main_win") self.init_Figs() main_grid = self.builder.get_object("main_grid") self.attach_Figs(main_grid) #tmp_foldername = "/home/das/job/plis/histo/apr14_4det_porog=90_delay=100_coinc_10h_night" self.curr_histo_folder = const.DEFAULT_CURR_HISTO_FOLDER self.spectra = Spectra(self.curr_histo_folder) self.fill_Figs(self.spectra.histo) zoom_args = { "en_magnification": 1e2, "en_v_step": 5e3, "en_h_step": 1e2, "t_magnification": 1e2, "t_v_step": 1e3, "t_h_step": 100.0 } self.zoom = Zoom(self.en_fig, self.t_fig, self.en_axes, self.t_axes, zoom_args) self.logger = Logger(path.join(const.MAIN_PROG_FOLDER, "journal.log")) self.logger.info("Program initialization OK") self.update_counts([0] * 4) self.info_textview = self.builder.get_object("info_textview") self.information = Information(self.info_textview) self.statusbar = self.builder.get_object("main_statusbar") def create_t_title(self, i): titles = [ "D1-D2", "D2-D1", "D1-D3", "D3-D1", "D1-D4", "D4-D1", "D2-D3", "D3-D2", "D2-D4", "D4-D2", "D3-D4", "D4-D3" ] return titles[i] def init_Figs(self): def format_yticks(y, pos): threshold_divider = 300 if y < threshold_divider: return "{:.0f}".format(y) else: return "{:.1f}k".format(y / 1e3) self.en_fig = [] self.en_axes = [] for i in range(0, const.DET_NUM): self.en_fig.append(Figure(figsize=(1, 1), dpi=80, frameon=False)) self.en_axes.append(self.en_fig[i].add_subplot(111)) ###adjust subplots to specific size if i == 0: self.en_fig[i].subplots_adjust(left=0.2, bottom=0.05, right=0.99, top=0.97) else: self.en_fig[i].subplots_adjust(left=0.05, bottom=0.05, right=0.99, top=0.97) ### ###xlim ylim self.en_axes[i].set_xlim(0, const.HIST_SIZE) self.en_axes[i].set_ylim(bottom=-1) ### ###x, y ticks self.en_axes[i].set_xticks([0, 1000, 2000, 3000, 4000]) self.en_axes[i].minorticks_on() # self.en_axes[i].xaxis.set_major_formatter( FuncFormatter(lambda x, pos: "{:.0f}k".format(x/1e3)) ) if i == 0: self.en_axes[i].yaxis.set_major_formatter( FuncFormatter(format_yticks)) else: self.en_axes[i].yaxis.set_major_formatter(NullFormatter()) ### self.t_fig = [] self.t_axes = [] for i in range(0, 12): self.t_fig.append(Figure(figsize=(1, 1), dpi=80, frameon=False)) self.t_axes.append(self.t_fig[i].add_subplot(111)) title_text = self.create_t_title(i) if (i == 0) or (i == 1): self.t_fig[i].suptitle(title_text, x=0.45, y=0.95) else: self.t_fig[i].suptitle(title_text, x=0.3, y=0.95) ###adjust subplots to specific size if i == 0: self.t_fig[i].subplots_adjust(left=0.2, bottom=0.05, right=0.99, top=0.99) elif i == 1: self.t_fig[i].subplots_adjust(left=0.2, bottom=0.05, right=0.99, top=0.99) elif i in [2, 4, 6, 8, 10]: self.t_fig[i].subplots_adjust(left=0.05, bottom=0.05, right=0.99, top=0.99) else: self.t_fig[i].subplots_adjust(left=0.05, bottom=0.05, right=0.99, top=0.99) ### ###xlim ylim self.t_axes[i].set_xlim(0, const.HIST_SIZE) self.t_axes[i].set_ylim(bottom=-1) ### ###x, y ticks self.t_axes[i].set_xticks([0, 1000, 2000, 3000, 4000]) self.t_axes[i].minorticks_on() #self.t_axes[i].xaxis.set_major_formatter( FuncFormatter(lambda x, pos: "{:.0f}k".format(x/1e3)) ) if (i == 0) or (i == 1): self.t_axes[i].yaxis.set_major_formatter( FuncFormatter(format_yticks)) else: self.t_axes[i].yaxis.set_major_formatter(NullFormatter()) ### def attach_Figs(self, grid): for i in range(4): en_d_vbox_name = "en_d{:d}_vbox".format(i) en_d_vbox = self.builder.get_object(en_d_vbox_name) en_d_vbox.pack_start(FigureCanvas(self.en_fig[i]), True, True, 0) col, row = 0, 1 for i in range(6): grid.attach(FigureCanvas(self.t_fig[2 * i]), col, row, 1, 1) col += 1 col, row = 0, 2 for i in range(6): grid.attach(FigureCanvas(self.t_fig[2 * i + 1]), col, row, 1, 1) col += 1 def fill_Figs(self, histo): histo_np_arr = np.array(histo) max_histo_en = histo_np_arr[0:const.DET_NUM].max() or 1 max_histo_t = histo_np_arr[const.DET_NUM:].max() or 1 self.en_axes_line = [0] * const.DET_NUM self.t_axes_line = [0] * 12 for i in range(0, const.DET_NUM): x_data = np.arange(const.HIST_SIZE) y_data = histo_np_arr[i] self.en_axes_line[i], = self.en_axes[i].plot(x_data, y_data, color="blue") self.en_axes[i].set_ylim(top=max_histo_en) for i in range(0, 12): x_data = np.arange(const.HIST_SIZE) y_data = histo_np_arr[const.DET_NUM + i] self.t_axes_line[i], = self.t_axes[i].plot(x_data, y_data, color="red") self.t_axes[i].set_ylim(top=max_histo_t) def update_Figs(self, histo): histo_np_arr = np.array(histo) max_histo_en = histo_np_arr[0:const.DET_NUM].max() or 1 max_histo_t = histo_np_arr[const.DET_NUM:, 1:].max() or 1 ###for test t = time() ### print("max_histo_en = {}".format(max_histo_en)) for i in range(0, const.DET_NUM): self.en_axes[i].set_ylim(bottom=-1, top=max_histo_en + 1) self.en_axes_line[i].set_ydata(histo_np_arr[i]) self.en_fig[i].canvas.draw() for i in range(0, 12): self.t_axes[i].set_ylim(bottom=-1, top=max_histo_t + 1) self.t_axes_line[i].set_ydata(histo_np_arr[const.DET_NUM + i]) self.t_fig[i].canvas.draw() text = "{} {}".format( self.create_t_title(i), np.sum(histo_np_arr[const.DET_NUM + i][1:])) if (i == 0) or (i == 1): self.t_fig[i].suptitle(text, x=0.55, y=0.95) else: self.t_fig[i].suptitle(text, x=0.4, y=0.95) print("plotting time = {}".format(time() - t)) def update_counts(self, det_counts): all_zero_counts = 0 for i in range(0, const.DET_NUM): if det_counts[i] == 0: all_zero_counts += 1 text = "D{:d} ".format(i + 1) if det_counts[i] < 1e3: text += "{:.0f}".format(det_counts[i]) else: text += "{:.2f}K".format(det_counts[i] / 1e3) #text = "D{:d} {:.2f}K".format(i + 1, det_counts[i]/1e3) if i == 0: self.en_fig[i].suptitle(text, x=0.45, y=0.95) else: self.en_fig[i].suptitle(text, x=0.3, y=0.95) for i in range(0, const.DET_NUM): self.en_fig[i].canvas.draw() def on_open(self, *args): print("open histo") fcd = Gtk.FileChooserDialog("Open", None, Gtk.FileChooserAction.SELECT_FOLDER, \ ("Cancel", Gtk.ResponseType.CANCEL, "Open", Gtk.ResponseType.OK)) fcd.set_current_folder(self.curr_histo_folder) response = fcd.run() if response == Gtk.ResponseType.OK: self.curr_histo_folder = fcd.get_current_folder() self.spectra = Spectra(self.curr_histo_folder) self.update_Figs(self.spectra.histo) fcd.destroy() elif response == Gtk.ResponseType.CANCEL: fcd.destroy() def on_quit(self, *args): Gtk.main_quit(*args) def run_fpga(self, *args): print("Run fpga app") self.fpga = FPGA() self.fpga.win.show_all() def run_histopac(self, *args): self.logger.info("Run histopac") histopac_exe = path.join(const.HISTOPAC_PROG_FOLDER, const.HISTOPAC_PROG_NAME) from os import chdir chdir(const.HISTOPAC_PROG_FOLDER) system("{:s} {:s}".format(histopac_exe, self.curr_histo_folder)) def run_anizpac(self, *args): self.logger.info("Run anizpac") #Chdir to anizpac #call anizpac def run_pypac_signal(self, *args): self.logger.info("Run pypac signal app") file_list = os.listdir(self.curr_histo_folder) signal_file = None for name in file_list: try: if name.split('.')[1] == "sgnl": if self.curr_histo_folder[-1] == '/': signal_file = self.curr_histo_folder + name else: signal_file = self.curr_histo_folder + '/' + name break except IndexError: None if signal_file is not None: pypac_exe = path.join(const.PYPAC_PROG_FOLDER, const.PYPAC_PROG_NAME) system("{:s} -i {:s}".format(pypac_exe, signal_file)) else: text = "There are no signal files in current histo folder: {:s}".format( self.curr_histo_folder) self.statusbar_push("error", err_msg=text) print("!Error: " + text) def run_pypac_histo(self, *args): print("Run pypac histo app") ''' if "fpga" not in self.__dict__: print("Run FPGA should be started first") self.fpga = FPGA() ''' system("{:s} -h {:s}".format( const.PYPAC_PROG_FOLDER + const.PYPAC_PROG_NAME, self.curr_histo_folder)) def edit_config(self, *args): system("{:s} {:s}".format(const.TXT_EDITOR, const.MAIN_PROG_FOLDER + const.CFG_FILE)) def edit_constants(self, *args): system("{:s} {:s}".format( const.TXT_EDITOR, const.MAIN_PROG_FOLDER + const.CONSTANTS_FILE)) def on_start(self, *args): btn = args[0] if "fpga" not in self.__dict__: print("Run FPGA should be started first") self.fpga = FPGA() print("On start | print acq_time = {}".format(self.fpga.acq_time)) self.fpga.save_consts_cfg(self.fpga.histo_folder) ###should be moved to separate func info = { "name": self.fpga.histo_folder, "start": localtime(), "expos": self.fpga.acq_time, "time": 1, "intens": 0, } self.information.update(info) ### self.curr_histo_folder = self.fpga.histo_folder print("signal flag = {}".format(self.fpga.with_signals_flag)) if self.fpga.with_signals_flag: prog_name = const.HDRAINER_EXE + "(with signals)" else: prog_name = const.HDRAINER_EXE self.hdrainer = Hdrainer(prog_name, self.fpga.acq_time, self.fpga.coinc, self.fpga.en_range, self.fpga.histo_folder) self.thread_args = {"ret": -1} t1 = Thread(target=self.hdrainer.start) t1.start() self.online_flag = 1 GLib.timeout_add_seconds(const.SLEEP_S_FIG_UPDATE, self.read_plot_online_histo, self.fpga.histo_folder) GLib.timeout_add_seconds(const.SLEEP_S_COUNTS_UPDATE, self.update_counts_online_histo) self.glib_loop = GLib.MainLoop() self.glib_loop.run() #self.glib_loop.quit() t1.join() ret = self.hdrainer.ret if (ret != 0 or ret is None): text = prog_name + " error! Return code {}.".format(ret) self.statusbar_push("error", err_msg=text) else: text = "Success execution of {} | execution_time = {:d}".format( prog_name, self.fpga.acq_time) self.statusbar_push("ok", normal_msg=text) print(text) info["time"] = 0 info["intens"] = 0 self.information.update(info) self.hdrainer.det_counts = [0] * 4 self.update_counts(self.hdrainer.det_counts) btn.handler_block_by_func(self.on_start) btn.set_active(False) btn.handler_unblock_by_func(self.on_start) def on_stop(self, *args): print("On stop") self.hdrainer.stop() def on_save(self, *args): self.logger.info("On save") fcd = Gtk.FileChooserDialog(title="Save", parent=None, \ action=Gtk.FileChooserAction.SELECT_FOLDER) fcd.add_buttons("Cancel", Gtk.ResponseType.CANCEL, "Save", Gtk.ResponseType.OK) fcd.set_current_folder(self.curr_histo_folder) response = fcd.run() if response == Gtk.ResponseType.OK: self.curr_histo_folder = fcd.get_current_folder() self.spectra.savebin_histo_files(self.curr_histo_folder) fcd.destroy() elif response == Gtk.ResponseType.CANCEL: fcd.destroy() else: print(type(response), response) def on_pause(self, *args): print("On pause") def on_clear(self, *args): print("On clear") def z_en_shrink(self, *args): print("z_en_shrink") self.zoom.en_x_shrink() def z_en_squeeze(self, *args): print("z_en_squeeze") self.zoom.en_x_squeeze() def z_en_mov_l(self, *args): print("z_en_mov_l") self.zoom.en_x_move_l() def z_en_mov_r(self, *args): print("z_en_mov_r") self.zoom.en_x_move_r() def z_en_up(self, *args): print("z_en_up") self.zoom.en_y_up() def z_en_down(self, *args): print("z_en_down") self.zoom.en_y_down() def z_en_log(self, *args): print("z_en_log") self.zoom.en_log() btn = args[0] if btn.get_label() == "log": btn.set_label("lin") else: btn.set_label("log") def z_en_zero(self, *args): print("z_en_zero") self.zoom.en_zero() def z_t_shrink(self, *args): print("z_t_shrink") self.zoom.t_x_shrink() def z_t_squeeze(self, *args): print("z_t_squeeze") self.zoom.t_x_squeeze() def z_t_left(self, *args): self.zoom.t_x_move_l() def z_t_right(self, *args): self.zoom.t_x_move_r() def z_t_up(self, *args): self.zoom.t_y_up() def z_t_down(self, *args): self.zoom.t_y_down() def z_t_log(self, *args): print("z_t_log") self.zoom.t_log() btn = args[0] if btn.get_label() == "log": btn.set_label("lin") else: btn.set_label("log") def read_plot_online_histo(self, hdir): #now readbin_histo each 1 sec!!! #update_counts should be each 1 sec only #histo read should be 1 time ~100 sec histo = self.spectra.readbin_histo_files(hdir) self.update_Figs(histo) if self.hdrainer.online: res = True else: self.glib_loop.quit() res = False return res def update_counts_online_histo(self): #Update EN and T spk counts (top on the fig) self.update_counts(self.hdrainer.det_counts) info = { "time": self.hdrainer.exec_time, "intens": self.hdrainer.cycles_per_time, } self.information.update(info) if self.hdrainer.online: res = True else: self.glib_loop.quit() res = False return res def is_glib_alive(self, x): print("main loop is alive? {}".format(self.glib_loop.is_running())) def statusbar_push(self, context, normal_msg="", err_msg=""): context_id = self.statusbar.get_context_id(context) if err_msg: msg = "!Error!: " + err_msg else: msg = normal_msg self.statusbar.push(context_id, msg)
from information import Information from wishlist import Wishlist from trade import Trade from images import Images intents = discord.Intents.default() intents.members = True load_dotenv() BOT_TOKEN = os.getenv('BOT_TOKEN') bot = commands.Bot(command_prefix='*', intents=intents) bot.add_cog(Roll(bot)) bot.add_cog(Admin(bot)) bot.add_cog(Profile(bot)) bot.add_cog(Information(bot)) bot.add_cog(Wishlist(bot)) bot.add_cog(Trade(bot)) bot.add_cog(Images(bot)) #### Bot commands #### @bot.command() async def ping(ctx): await ctx.message.delete() await ctx.send('Yup, I\'m awake.', delete_after=5) #### Bot event handlers ####
def pupil_process(self, paths): pupil_deep = PupilDeep() process = ProcessImage() pupil = Pupil(pupil_deep) draw = DrawImages() information = Information() self._path_label = paths['path_label'] self._add_label(self._title_label) exam = cv2.VideoCapture(paths['path_exam']) fps = exam.get(cv2.CAP_PROP_FPS) patient_exam, param_exam = information.get_information_exam(paths['path_information'], fps) number_frame = 0 while True: _, frame = exam.read() if (frame is None) or ((self._frame_stop > 0) and (number_frame >= self._frame_stop)): break if (self._frame_start > 0) and (number_frame < self._frame_start): number_frame += 1 continue original = np.copy(frame) img_orig_gray = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY) self._save_images({'original': original}, number_frame, paths['path_out']) img_process, flash = process.process_image(original) self._save_images({'process': img_process}, number_frame, paths['path_out']) img_mean, img_std, img_median = img_process.mean(), img_process.std(), np.median(img_process) center, radius, points, images, mean_binary = pupil.pupil_detect(img_process) binary = images['binary_pre_process'] binary = draw.mark_center(binary, center) binary = draw.draw_circles(binary, points, 2, self._white_color) self._save_images({'binary': binary}, number_frame, paths['path_out'], center) img_process = draw.mark_center(img_process, center) img_process = draw.draw_circles(img_process, points, 2, self._white_color) img_process = draw.draw_circles(img_process, [(center[0], center[1])], radius, self._white_color) self._save_images({'img_process': img_process}, number_frame, paths['path_out']) self._save_histogram(images['histogram'], number_frame, paths['path_out']) img_presentation = cv2.hconcat([img_orig_gray, binary, img_process]) label = 'Frame=%d;Radius=%d;Center=(%d,%d);BinMean=(%f)' % ( number_frame, radius, center[0], center[1], mean_binary) self._show_image(img_presentation, label, number_frame, paths['path_out']) flash_information, color_information = information.get_information_params(number_frame) params = [patient_exam, param_exam, number_frame, center[0], center[1], radius, flash, flash_information, color_information, 0, img_mean, img_std, img_median] self._add_params_label(params) number_frame += 1 cv2.destroyAllWindows() exam.release()
def process(self,doc_obj): """Checks and fills information for each cluster in clusterlist of given document""" NESet = doc_obj.getNESet() NERMap = doc_obj.getNERMap() mentionPOSMap = doc_obj.getParserObject().getMentionPOSMap() for mentionCluster in doc_obj.getMentionClustersList(): number = Information() gender = Information() animacy = Information() head = mentionCluster.getHeadMention().lower() headSpan = mentionCluster.getHeadSpan() singularByMap = None if headSpan in mentionPOSMap.keys() and mentionPOSMap[headSpan].startswith("NN"): if mentionPOSMap[headSpan].endswith("S"): singularByMap = False else: singularByMap = True if head in self.__maleSet: gender.addValues("male") headWords = head.split() for w in headWords: if w in self.__maleSet: gender.addValues("male") if w in self.__femaleSet: gender.addValues("female") if head in self.__femaleSet: gender.addValues("female") if head in self.__neutralSet: gender.addValues("neutral") if head in self.__animateSet or (headSpan in NESet and NERMap[headSpan] == 'PERSON'): animacy.addValues("animate") elif head in self.__inanimateSet or (headSpan in NESet and NERMap[headSpan] != 'PERSON'): animacy.addValues("inanimate") else: animacy.addValues("animate") animacy.addValues("inanimate") if head in self.__singularSet or headSpan in NESet or singularByMap == True: number.addValues("singular") if head in self.__pluralSet or singularByMap == False: number.addValues("plural") if head in self.__namegenderDict.keys(): gender.addValues(self.__namegenderDict[head]) mentionCluster.addInformation(infokeys.gender,gender) mentionCluster.addInformation(infokeys.number,number) mentionCluster.addInformation(infokeys.animacy,animacy)
with open('files.txt') as file_read: for line in file_read.readlines(): work_files.append(line.replace('\n', '').replace('.avi', '.mp4')) path_exams = '/media/marcos/Dados/Projects/Results/PupilLocator/Exams' files_exists = [x.replace('.avi', '.mp4') for x in os.listdir(path_exams)] if os.path.exists(video_path): files = [x for x in os.listdir(video_path) if ('.mp4' in x) and (x in work_files) and (x not in files_exists)] files = ['benchmark_final.avi'] for file in files: file_in = '{}/{}'.format(video_path, file) name_exam = file.replace('.avi', '') run(model, sess, file_in, information, name_exam) if __name__ == "__main__": model_name = "3A4Bh-Ref25" model_type = "INC" video_path = '/media/marcos/Dados/Projects/Datasets/Exams' # initial a logger logger = Logger(model_type, model_name, "", config, dir="models/") logger.log("Start inferring model...") information = Information() main(model_type, model_name, logger, information, video_path)
def __init__(self, name): self.information = Information(name)
class Builder: """ Reads and processes data to construct the Information object. Stores and returns configuration and processed information. """ def __init__(self, in_cvs: str, in_json: str, in_enc: str, out_enc: str, out_name: str): self._information = Information() self._in_cvs = in_cvs self._in_json = in_json self._in_enc = in_enc self._out_enc = out_enc self._out_name = out_name self._is_load_stat_done = False self._is_load_data_done = False def load_data(self): """ Reads information from the main CVS file about each of the students Transmits collected information to the Information class the class Information. In case of impossibility to read data - raise ReadCvsError In case of incorrect data - raise InputCvsError """ try: with open(self._in_cvs, 'r', encoding=self._in_enc) as read_file: reader = csv.DictReader(read_file, delimiter=';') for row in reader: self._information.load(row['name1'], row['name2'], row['group'], row['whom'], row['course'], row['data'], row['when'], row['num'], row['kind'], row['aud']) self._is_load_data_done = True except OSError: self._information.clear_data() raise ReadCvsError() except LoadError as e: self._information.clear_data() raise InputCvsError(str(e)) def load_stat(self): """ Reads additional statistical information from the json file to verify the data. In case of impossibility to read data - raise ReadJsonError In case of incorrect data - raise InputJsonError """ try: with open(self._in_json, encoding=self._in_enc) as read_file: data = json.load(read_file) cnt_missed_4_lessons = data["кількість пропусків на четвертих парах"] cnt_missed_lectures = data["кількість пропусків лекцій"] self._information.set_stat(cnt_missed_4_lessons, cnt_missed_lectures) self._is_load_stat_done = True except OSError: self._information.clear_stat() raise ReadJsonError() except BaseException: self._information.clear_stat() raise InputJsonError() def is_product_done(self) -> bool: """returns the logical value of checking the complete correctness of the data""" return self._is_load_data_done and self._is_load_stat_done def get_product_information(self) -> Information: """ Returns the constructed instance of the information class. In case the Information class is not yet constructed, it returns None """ if self.is_product_done(): return self._information def get_name_cvs(self): return self._in_cvs def get_name_json(self): return self._in_json def get_name_outpath(self): return self._out_name def get_enc_outpath(self): return self._out_enc
def __init__(self, tag, info, end="\n"): self.tag = tag self.end = end Information.__init__(self, info)