def heating_SensorRefresh(**kwargs): db = conf.db.conn data = dict() for item in db.keys("temp_sensor_*"): sensor = pickle.loads(db.get(item)) data[conf.HeatingSensors.items[sensor["sensorId"]]] = sensor data["heating_state"] = utils.toInt(db.get("heating_state")) data["heating_time"] = utils.toInt(db.get("heating_time")) return data
def drawObjects(image, boxes, labels, probs, color=(200, 0, 0), drawBoxes=True, drawLabels=True, drawProbs=True, printToConsole=True): if probs is None or len(probs) == 0: probs = repeat(1., len(boxes)) if printToConsole: print("---------") for box, label, prob in zip(boxes, labels, probs): x1, y1, x2, y2 = toInt(*box) if drawBoxes: cv2.rectangle(image, (x1, y1), (x2, y2), color, 1) if drawLabels: text = str(label) if drawProbs: probPct = int(round(prob * 100)) if probPct < 100: text = f"{label}:{probPct}" textOrd = x1, min(y2, imHeight(image)) - 1 cv2.putText(image, text, textOrd, cv2.FONT_HERSHEY_SIMPLEX, .5, color) if printToConsole: print(label, prob) return image
def check(self): db = conf.db.conn self.__heatingCounter = utils.toInt(db.get("__heatingCounter")) + 1 db.set("__heatingCounter", self.__heatingCounter) self.checkTemperature()
def drawSeparateObjects(srcImage, boxes, labels, probs, drawProp=True, color=(0, 0, 200)): # stack from left to right images = [] for box, label, prob in zip(boxes, labels, probs): image = srcImage.copy() images.append(image) x1, y1, x2, y2 = toInt(*box) cv2.rectangle(image, (x1, y1), (x2, y2), color, 1) labelCoord = x1, y1 labelText = str(label) if drawProp: scoreInPercents = int(round(prob * 100)) if scoreInPercents < 100: labelText = f"{label}:{scoreInPercents}" cv2.putText(image, labelText, labelCoord, cv2.FONT_HERSHEY_SIMPLEX, .5, color) stack = np.vstack if imWidth(srcImage) > imHeight(srcImage) else np.hstack return stack(images)
def post(self): try: data = json.loads(self.request.body) id = utils.toInt(data.get("id")) if id: e = models.Customers.get_by_id(id) if e is None: raise Exception('Specified customer was not found!') else: e = models.Customers() e.name = data.get("name") e.contact = data.get("contact") e.contactTitle = data.get("contactTitle") e.email = data.get("email") e.mobile = data.get("mobile") e.landline = data.get("landline") e.addr = data.get("addr") e.notes = data.get("notes") e.active = data.get("active") or False e.put() self.return_json(e.to_dict()) except: self.return_msg()
def changeHeatingState(self, value): db = conf.db.conn month = ("%s-%s") % (time.localtime().tm_year, time.localtime().tm_mon) # read actual value oldValue = utils.toInt(db.get("heating_state")) if oldValue != value: req = "/?p=%s&v=%s" % (conf.Heating.port, value) data = self.sendReq(conf.Heating.hwIp, req) data = json.loads(data) newValue = int(data.get("v")) db.set("heating_state", newValue) tm = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) data = db.get("heating_time_%s" % month) if not data: data = list() else: data = pickle.loads(data) if oldValue == 0 and value == 1: data.append({"date": tm, "status": True}) else: data.append({"date": tm, "status": False}) db.set("heating_time_%s" % month, pickle.dumps(data))
def newTopic(request,fid): form = Form() fields = request.getForm() user = users.get_current_user() uid = user.user_id() # sanitize title = utils.toStr(fields.get('title',''),80) imp = utils.toInt(fields.get('importance','0')) author = utils.toStr(fields.get('author',''),40) email = fields.get('email') url = fields.get('url') content= utils.toTxt(fields.get('content',''),9000) # validate ok=True warn=[] if email or url: form.ok=False form.redirect=True form.url='%s/%s'%(app.root,fid) return form if not title: warn.append('Title can not be empty') ok=False if title==title.upper(): warn.append('Title can not be all caps') ok=False if not author: warn.append('You need to identify as the author') ok=False if author==author.upper(): warn.append('Author can not be all caps') ok=False if not content: warn.append('You must enter some content') ok=False if content==content.upper(): warn.append('Content can not be all caps') ok=False if ok: dat1 = {'forumid':fid,'title':title,'userid':str(uid),'author':author,'importance':imp} rec1 = models.newTopic(dat1) tid = rec1.topicid dat2 = {'topicid':tid,'forumid':fid,'userid':str(uid),'author':author,'content':content} rec2 = models.newMessage(dat2) form.ok = True form.url = '%s/%s/%s'%(app.root,fid,tid) else: form.ok = False form.warn = warn form.data = { 'forum' :models.getForum(fid), 'warn' :warn, 'title' :title, 'author' :author, 'content':content } return form
def delete(self): try: id = utils.toInt(self.request.get("id")) e = models.Customers.get_by_id(id) e.key.delete() self.return_msg('Customer was deleted') except: self.return_msg()
def drawDigits(image, boxes, digits, color=(0, 200, 0)): for box, digit in zip(boxes, digits): x1, y1, x2, y2 = toInt(*box) textOrd = (x1 + x2) // 2, (y1 + y2) // 2 cv2.putText(image, str(digit), textOrd, cv2.FONT_HERSHEY_SIMPLEX, .8, color, 2) return image
def newForum(request): form = Form() fields = request.getForm() # sanitize title = utils.toStr(fields.get('title', ''), 80) desc = utils.toStr(fields.get('desc', ''), 120) url = utils.idify(fields.get('url', ''), 40) order = utils.toInt(fields.get('order')) # validate ok = True warn = [] if not url: warn.append('Forum needs a permalink') ok = False if not title: warn.append('Title can not be empty') ok = False if title == title.upper(): warn.append('Title can not be all caps') ok = False if not desc: warn.append('You must enter some description') ok = False if desc == desc.upper(): warn.append('Description can not be all caps') ok = False if ok: if not order: order = models.getNextOrder() data = { 'url': url, 'title': title, 'description': desc, 'order': order } rec = models.newForum(data) form.ok = True form.url = '%s/admin/forum' % (app.root) form.redirect = True else: form.ok = False form.warn = warn form.data = { 'forum': models.getForum(fid), 'warn': warn, 'title': title, 'author': author, 'content': content } return form
def newForum(request): form = Form() fields = request.getForm() # sanitize title = utils.toStr(fields.get('title',''), 80) desc = utils.toStr(fields.get('desc' ,''),120) url = utils.idify(fields.get('url' ,''), 40) order = utils.toInt(fields.get('order')) # validate ok=True warn=[] if not url: warn.append('Forum needs a permalink') ok=False if not title: warn.append('Title can not be empty') ok=False if title==title.upper(): warn.append('Title can not be all caps') ok=False if not desc: warn.append('You must enter some description') ok=False if desc==desc.upper(): warn.append('Description can not be all caps') ok=False if ok: if not order: order=models.getNextOrder() data = {'url':url,'title':title,'description':desc,'order':order} rec = models.newForum(data) form.ok = True form.url = '%s/admin/forum'%(app.root) form.redirect = True else: form.ok = False form.warn = warn form.data = { 'forum' :models.getForum(fid), 'warn' :warn, 'title' :title, 'author' :author, 'content':content } return form
def main(): # imagesPattern = '/hdd/Datasets/counters/1_from_phone/1_all_downsized/*.jpg' # imagesPattern = '/hdd/Datasets/counters/2_from_phone/val/*.jpg' # imagesPattern = '/hdd/Datasets/counters/1_from_phone/val/*.jpg' # imagesPattern = '/hdd/Datasets/counters/3_from_phone/*.jpg' # imagesPattern = '/hdd/Datasets/counters/4_from_phone/*.jpg' imagesPattern = '/hdd/Datasets/counters/5_from_phone/*.jpg' screenDetector = CounterScreenModel( '../counter_screen/model/weights/2_from_scratch/weights.h5') digitsDetector = DigitsOnScreenModel('./weights/weights_23_0.282.h5') counterScreenLabel = 1 for image_path in sorted(glob(imagesPattern)): image = cv2.imread(image_path)[..., ::-1] # to RGB image = fit_image_to_shape(image, (1000, 1800)) boxes, labels, probs = screenDetector.detect(image, 0.8) # filter only screens onlyScreens = ((b, l, p) for b, l, p in zip(boxes, labels, probs) if l == counterScreenLabel) boxes, labels, probs = unzip(onlyScreens, [], [], []) if len(boxes) == 0: continue screenImg = None for box in boxes: x1, y1, x2, y2 = toInt(*box) screenImg = imageByBox(image, box) screenImg = fitToWidth(screenImg, digitsDetector.net_size, 0) digits = digitsDetector.detect(screenImg, .5) print(digits) cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 200), 1) if imshowWait(img=(image[..., ::-1], image_path), screenImg=screenImg[..., ::-1]) == 27: break
def drawBoxes(image, boxes, color=(0, 0, 200)): for x1, y1, x2, y2 in boxes: x1, y1, x2, y2 = toInt(x1, y1, x2, y2) cv2.rectangle(image, (x1, y1), (x2, y2), color, 1) return image
def imageByBox(srcImage, box, copy=True): x1, y1, x2, y2 = toInt(*box) boxImage = srcImage[y1:y2, x1:x2] if copy: boxImage = boxImage.copy() return boxImage
def newPoll(request): form = Form() fields = request.getForm() # sanitize title = utils.toStr(fields.get('title',''),120) image = utils.toStr(fields.get('image',''),250) isopen = fields.get('isopen',False) single = fields.get('single',False) block = fields.get('block' ,False) close = fields.get('close' ,False) closeon = utils.toDtm(fields.get('closeon',None)) type = 0 if single else 1 restrict = 1 if block else 0 status = 1 if isopen else 0 closeon = closeon if close else None slots = utils.toInt(fields.get('slots',0)) # poll poll={ 'title' : title, 'image' : image, 'closeon' : closeon, 'type' : type, 'restrict': restrict, 'status' : status } # options pos = 0 options=[] for i in range(1,slots+1): option = fields.get('option'+str(i),'') if option: pos+=1 options.append({'title':option,'position':pos}) # validate warn=[] form.ok=True if not title: form.ok=False warn.append('Title is required') if pos<2: form.ok=False warn.append('At least two options are required') # process if form.ok: models.registerPoll(poll,options) form.url = app.root+'/admin' else: poll['slots'] = pos poll['isopen'] = 'checked' if isopen else '' poll['single'] = 'checked' if single else '' poll['block'] = 'checked' if block else '' poll['close'] = 'checked' if close else '' if pos<5: poll['slots']=5 for i in range(pos,5): options.append({'title':'','position':i+1}) form.data={'warn':warn,'poll':poll,'options':options} return form
def editPoll(request,pollid): form = Form() fields = request.getForm() # sanitize title = utils.toStr(fields.get('title',''),120) image = utils.toStr(fields.get('image',''),250) isopen = fields.get('isopen',False) single = fields.get('single',False) block = fields.get('block' ,False) close = fields.get('close' ,False) closeon = utils.toDtm(fields.get('closeon',None)) type = 0 if single else 1 restrict = 1 if block else 0 status = 1 if isopen else 0 closeon = closeon if close else None slots = utils.toInt(fields.get('slots',0)) # poll poll={ 'pollid' : pollid, 'title' : title, 'image' : image, 'closeon' : closeon, 'type' : type, 'restrict': restrict, 'status' : status } # options pos = 0 options=[] for i in range(1,slots+1): option = fields.get('option'+str(i),'') optionid = fields.get('optionid'+str(i),'') # if has title but not optionid: insert option # if has title and has optionid: modify option # if not title but has optionid: delete option if option and optionid: pos+=1 options.append({'optionid':optionid,'title':option,'position':pos}) elif option and not optionid: pos+=1 options.append({'optionid':'','title':option,'position':pos}) else: options.append({'optionid':optionid,'title':'','position':0}) # validate warn=[] form.ok=True if not title: form.ok=False warn.append('Title is required') if pos<2: form.ok=False warn.append('At least two options are required') # process if form.ok: models.savePoll(poll,options) form.url = app.root+'/admin/viewpoll/'+pollid else: poll['slots'] = pos poll['isopen'] = 'checked' if isopen else '' poll['single'] = 'checked' if single else '' poll['block'] = 'checked' if block else '' poll['close'] = 'checked' if close else '' #remove deleted options clean=[] for item in options: if item['position']>0: clean.append(item) if pos<5: poll['slots']=5 for i in range(pos,5): clean.append({'optionid':'','title':'','position':i+1}) form.data={'warn':warn,'poll':poll,'options':clean} return form
def display(img, screenBox, digits, digitBoxes): x1, y1, x2, y2 = toInt(*screenBox) cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 200), 1) return drawObjects(img, digitBoxes, digits, None)
def newTopic(request, fid): form = Form() fields = request.getForm() user = users.get_current_user() uid = user.user_id() # sanitize title = utils.toStr(fields.get('title', ''), 80) imp = utils.toInt(fields.get('importance', '0')) author = utils.toStr(fields.get('author', ''), 40) email = fields.get('email') url = fields.get('url') content = utils.toTxt(fields.get('content', ''), 9000) # validate ok = True warn = [] if email or url: form.ok = False form.redirect = True form.url = '%s/%s' % (app.root, fid) return form if not title: warn.append('Title can not be empty') ok = False if title == title.upper(): warn.append('Title can not be all caps') ok = False if not author: warn.append('You need to identify as the author') ok = False if author == author.upper(): warn.append('Author can not be all caps') ok = False if not content: warn.append('You must enter some content') ok = False if content == content.upper(): warn.append('Content can not be all caps') ok = False if ok: dat1 = { 'forumid': fid, 'title': title, 'userid': str(uid), 'author': author, 'importance': imp } rec1 = models.newTopic(dat1) tid = rec1.topicid dat2 = { 'topicid': tid, 'forumid': fid, 'userid': str(uid), 'author': author, 'content': content } rec2 = models.newMessage(dat2) form.ok = True form.url = '%s/%s/%s' % (app.root, fid, tid) else: form.ok = False form.warn = warn form.data = { 'forum': models.getForum(fid), 'warn': warn, 'title': title, 'author': author, 'content': content } return form
def analyze(self): # Update application copy of input/output dir (in case user didn't use buttons) self.inputDir = self.lineEdit_inputDir.text() self.outputDir = self.lineEdit_outputDir.text() # Get all user options opts = { 'input_dir': self.inputDir, 'output_dir': self.outputDir, 'bool_analyze_full': self.checkBox_setTime.checkState(), 'start_time': utils.toInt(self.lineEdit_startTime.text()), 'end_time': utils.toInt(self.lineEdit_endTime.text()), 'bool_removeClipped': self.checkBox_removeClipped.checkState(), 'bool_deleteClips': self.checkBox_deleteClips.checkState(), 'bool_makeSpectrograms': self.checkBox_spectrograms.checkState(), 'bool_parseFilename': self.checkBox_parseFilename.checkState(), 'filename_delimiter': self.lineEdit_filenameDelimiter.text(), 'filename_categories': [s for s in self.lineEdit_filenameCategories.text().split(',')], 'bool_useAva': self.checkBox_useAva.checkState(), 'avaFoldername': self.lineEdit_avaFolder.text(), 'bool_inferSilence': self.checkBox_useSilenceFile.checkState(), 'silenceFilename': self.lineEdit_silenceFile.text(), 'silenceThreshold': self.spinBox_silenceThresh.value(), 'silenceBuffer': self.spinBox_bufferLen.value(), 'silenceMinLen': self.spinBox_minSilenceLen.value() } # TODO: Generalize error catching try: progress = QtWidgets.QProgressDialog( "Processing files...", "Abort", 0, len(os.listdir(opts['input_dir']))) progress.setWindowModality(QtCore.Qt.WindowModal) self.vocBatch = pipeline.pipe(opts) except exceptions.TimeBoundError as error: error_dialog = QtWidgets.QErrorMessage() error_dialog.setWindowModality(QtCore.Qt.WindowModal) error_dialog.showMessage(error.error_string()) error_dialog.exec_() return except exceptions.FilenameParseError as error: error_dialog = QtWidgets.QErrorMessage() error_dialog.setWindowModality(QtCore.Qt.WindowModal) error_dialog.showMessage(error.error_string()) error_dialog.exec_() return except exceptions.NoInputError as error: error_dialog = QtWidgets.QErrorMessage() error_dialog.setWindowModality(QtCore.Qt.WindowModal) error_dialog.showMessage(error.error_string()) error_dialog.exec_() return self.loadOutputTables(self.lineEdit_outputDir.text()) if opts['bool_makeSpectrograms']: self.loadSpectrograms(opts['output_dir'])