def _copy_entry(entry): """ Creates a duplicate of a log entry object. Does not duplicate the info dictionary, which should ordinarily be empty). Arguments: - entry -- the entry to copy. Returns: a copy of the log entry object. ----------------------------------------------------------------- """ try: # Instantiate a new log entry object. copy = logentry.LogEntry() # Copy each individual attribute. copy.id = entry.id copy.title = entry.title copy.date = entry.date copy.time = entry.time copy.datetime = entry.datetime copy.duration = entry.duration copy.notes = entry.notes copy.recurring = entry.recurring copy.rec_interval = entry.rec_interval copy.rec_total = entry.rec_total copy.rec_child_seq = entry.rec_child_seq copy.rec_parent = entry.rec_parent return copy except Exception as err: _z_exc("wl_viewedit.py/_copy_entry", err)
def _init_entry(self, dict_entry): """ Initializes a log entry. Arguments: - dict_entry -- the dictionary to use to initialize the entry. Returns: True if the entry was successfully initialized, else False. ------------------------------------------------------------- """ try: # Create a new entry object. new_entry = logentry.LogEntry() # Try to initialize the entry with info from the # dictionary. if new_entry.from_dict(dict_entry): # If it worked, add the entry to the log object and # sort lists. self.entries.append(new_entry) self.sorts[TITLE_SORT].append( (new_entry.title, new_entry.datetime, new_entry.id)) self.sorts[DATE_SORT].append( (new_entry.datetime, new_entry.title, new_entry.id)) return True else: return False # end if except Exception as err: _z_exc("worklog.py/WorkLog/_init_entry", err)
def _do_save(self): """ Saves the log file. Allows the user to continue working with the log object. Arguments: none. Returns: True if successful; False if there was an error. ------------------------------------------------------------- """ try: self.last_modified = datetime.datetime.now() # Initialize a temporary list to hold the log data. entry_list = [] # Create a dummy entry object, which will hold data for the # log object. new_entry = logentry.LogEntry() fn = new_entry.FIELDNAMES new_entry.info = { "total_entries": self.total_entries, "date_format": self.date_format, "time_format": self.time_format, "show_help": self.show_help, "last_modified": self.last_modified } # Start the list with the dummy entry object. entry_dict = new_entry.to_dict() entry_list.append(entry_dict) # Now add all of the entries. for entry in self.entries: # For each entry object, convert to a dictionary. entry_dict = entry.to_dict() entry_list.append(entry_dict) # end for # Pass everything to the io_utils function. success = io_utils.file_write(self.filename, "csv", entry_list, fieldnames=fn) if success: # Print status. io_utils.print_status("status", f"{self.filename} saved.", line_length=self.line_length) self.changed = False return True else: return False # end if except Exception as err: _z_exc("worklog.py/WorkLog/_do_save", err)
def _add_recurring_entries(self, entry, recurrance_list): """ Adds a series of recurring entries. Arguments: - entry -- the original entry. - recurrance_list -- the list of recurring dates. Returns: nothing. ------------------------------------------------------------- """ try: # If there are no recurrances, just return. if not recurrance_list: return # end if # Finish setting the original entry's attribute. entry.rec_total = len(recurrance_list) for n, date in enumerate(recurrance_list): # Create a new entry object with the original entry's # attributes. new_entry = logentry.LogEntry() new_entry.title = entry.title # Different date. new_entry.date = date new_entry.time = entry.time # Set new datetime attribute. new_entry.datetime = wl_add.add_datetime(new_entry) new_entry.duration = entry.duration new_entry.notes = entry.notes # Recurrance-specific attributes. new_entry.recurring = False new_entry.rec_child_seq = (n + 1, len(recurrance_list)) new_entry.rec_parent = entry.id # Add the entry to the work log. self._do_sort(new_entry) self.entries.append(new_entry) # end for return except Exception as err: _z_exc("worklog.py/WorkLog/do_add_recurring_entries", err)
def _init_worklog(self, dict_entry): """ Initializes the work log object from data from a file. The first log entry read from a data file does not contain information about a task; rather, its info attribute holds data on the work log itself. Arguments: - dict_entry -- the list representation of the first log entry as read from a data file. Returns: True if data was successfully transferred to the work log object; else False. ------------------------------------------------------------- """ try: # Create a dummy log entry object to hold the data. new_entry = logentry.LogEntry() # Convert the log object information (stored in the info # field of the first entry obuject) into a dictionary. new_entry.from_dict(dict_entry) # Set the log object's attributes from the dictionary. self.total_entries = new_entry.info["total_entries"] self.show_help = new_entry.info["show_help"] self.last_modified = new_entry.info["last_modified"] # But only set the format attributes if the user has not # already set them. if not self.date_format: self.date_format = new_entry.info["date_format"] # end if if not self.time_format: self.time_format = new_entry.info["time_format"] # end if return True except Exception as err: io_utils.print_status("Error", f"Error reading log info: {err}", line_length=self.line_length) return False
def _do_add(self): """ Adds one or more entry objects to the log object. Arguments: none. Returns: nothing. ------------------------------------------------------------- """ try: # List of object attributes to set (easier than directly # iterating through the attributes). attr_list = [ "title", "date", "time", "duration", "notes", "recurring" ] # Initialize list. recurring_entries = [] # Like all of the _do methods, the entire method is inside a # loop, allowing the user to add as many entries as they # want. not_done = True while not_done: cancel = False # First, create a new log entry object. new_entry = logentry.LogEntry() # Go through the list and set values for each attribute. # Because the user can choose to back up, we don't use # a for loop to iterate through the attributes. attrib = 0 # Loop runs until the last attribute is set. while attrib < len(attr_list): # Get the attribute name. attr = attr_list[attrib] # The title attribute is the only one which does not # allow the user to go back (because it's the first # attribute set). if attr == "title": go = wl_add.add_title(self, new_entry) # end if # "date" must be convertible to a date object. elif attr == "date": go = wl_add.add_date(self, new_entry) # If the user goes back a step, clear the # previous attribute. if go == -1: new_entry.title = None # end if # "time" must be convertible to a time object. elif attr == "time": go = wl_add.add_time(self, new_entry) # If the user goes back a step... if go == -1: new_entry.date = None # end if # "duration" must be convertible to a timedelta # object. elif attr == "duration": go = wl_add.add_duration(self, new_entry) # If the user goes back a step... if go == -1: new_entry.time = None # end if # "notes" can be any string, including empty. elif attr == "notes": go = wl_add.add_note(self, new_entry) # If the user goes back a step... if go == -1: new_entry.duration = None # end if # "recurring" will either be True of False, and if # True will also return a list of recurrance date # objects. elif attr == "recurring": recurring_entries = [] go, recurring_entries = wl_add.add_recurrance( self, new_entry) # If the user goes back a step... if go == -1: new_entry.notes = None # end if # end if if go == 0: # Print that the entry was cancelled. io_utils.print_status( "Status", "Addition of this task has been cancelled.", line_length=self.line_length) # If the user aborts and does not want to start # another task, return immediately. if io_utils.yes_no("Do you want to add another task?", line_length=self.line_length): cancel = True break else: return # end if else: attrib += go # end if # end while if not cancel: not_done = self._add_entry(new_entry, recurring_entries) # end if # end while return except Exception as err: _z_exc("worklog.py/WorkLog/do_add", err)
def checkFrameForEvents(currentFrame, realFramePointOfTime, counter, eventList, orientation): entry = logentry.LogEntry(counter, realFramePointOfTime, orientation, False) currFrameRGBandIMG = Image.fromarray( cv2.cvtColor(currentFrame, cv2.COLOR_BGR2RGB)) for event in eventList: appendToLogmessage = '' isEvent = True if event.fixedPositionList: wasTrueAtLeastOneTime = False # for OR events for fixedPositionImage in event.fixedPositionList: if (isEvent or event.isOR): eventImage = Image.open(fixedPositionImage['image']).crop( fixedPositionImage['positionAndSize']) frameImage = currFrameRGBandIMG.crop( fixedPositionImage['positionAndSize'] ) #Image.fromarray( cv2.cvtColor( currentFrame, cv2.COLOR_BGR2RGB ) ).crop(fixedPositionImage['positionAndSize']) hash = 99 # just for inital value if fixedPositionImage['useEdges']: hash = mManager.getEdgePHashDistance( eventImage, frameImage) else: hash = mManager.getPHashDistance( eventImage, frameImage) if (hash < 18): isEvent = True wasTrueAtLeastOneTime = True else: isEvent = False if event.isOR and wasTrueAtLeastOneTime: isEvent = True if (len(event.searchForImageList) > 0 and isEvent): for searchForImage in event.searchForImageList: if (isEvent): searchFor = Image.open(searchForImage['image']).crop( searchForImage['positionAndSize']) isEvent = mManager.isInImage(currentFrame, searchFor, searchForImage['threshold']) if (len(event.searchForTextList) > 0 and isEvent): for text in event.searchForTextList: if (isEvent): frameImage = currFrameRGBandIMG.crop( text['positionAndSize']) if text['searchterm']: isEvent = oManager.lookForString( frameImage, text['searchterm']) else: appendToLogmessage = ' - ' + str( oManager.getStringFromImage( frameImage, text['onlyDigits'])) isEvent = True #add found event to eventlist for this frame if (isEvent): #cv2.imwrite("frametest_" + str(counter) + "_" + event.logMessage + appendToLogmessage + ".jpg", currentFrame ) # for debugging: save frame with found event to disk entry.addEvent(event.logMessage + appendToLogmessage) # add no event found in case of no events if len(entry.foundEvents) == 0: #cv2.imwrite("frametest_" + str(counter) + "_" + "NOTHING FOUND.jpg", currentFrame ) # for debugging: save frame with no event to disk entry.addEvent('NOTHING FOUND') return entry
def lookForEvents(eventList, videoFileName, videotimeStamp, videoOrientation): global counter global videoStarts global videoEnds global skippedFrames global usedframes global isVideoProcessing isVideoProcessing = True # prepare video and multiprocessing vManager = videomanager.VideoManager(videoFileName) pool = mp.Pool(numOfCores) isPortraitMode = videoOrientation # no functionality yet! videoStartTime = videotimeStamp # add start for this videosession videoStarts.append(counter) print('# starting to look for events ...') print('# Video file: ' + videoFileName) t = time.time() if (len(eventList) > 0): isFrame, lastFrame = vManager.getNextVideoFrame() isFrame, currentFrame = vManager.getNextVideoFrame() while isFrame: frameDiffMax = vManager.checkFrameDifference( lastFrame, currentFrame) frameDiffAv = vManager.checkFrameDifferenceSumAver( lastFrame, currentFrame) currentFrameTime = vManager.getTimeOfCurrentVideoFrame() realFramePointOfTime = videoStartTime + currentFrameTime if frameDiffMax > 100 or frameDiffAv > 1 or counter == 0: pool.apply_async(checkFrameForEvents, args=(currentFrame, realFramePointOfTime, counter, eventList, isPortraitMode), callback=addLogResult) usedframes = usedframes + 1 else: # no significant diff between frames, add empty event, copy events from event before after multiprocessing addLogResult( logentry.LogEntry(counter, realFramePointOfTime, isPortraitMode, True)) #pool.apply_async( addLogResult, args=( logentry.LogEntry(counter, realFramePointOfTime, isPortraitMode, True) ) ) skippedFrames = skippedFrames + 1 lastFrame = currentFrame isFrame, currentFrame = vManager.getNextVideoFrame() counter = counter + 1 pool.close() pool.join() # add video-end event videoEnds.append(counter - 1) isVideoProcessing = False print('# Time needed for processing (seconds): ' + str(time.time() - t)) print('# done with this video.')