def from_idh_csv(filename): entries = rows.import_from_csv(filename) # lista de codes codes = [ e.code.strip() for e in sorted(entries, key=lambda x: x.idh, reverse=True) ] #lista de language languages = [ e.language.strip() for e in sorted(entries, key=lambda x: x.idh, reverse=True) ] codelang = remove_consecutives({'codes': codes, 'languages': languages}) chain_str = ' - '.join(codes) cprint.ok(f"Translation chain: {chain_str}.") cprint.ok(f"Input text: {TEXT}\n") start_codelang = {'codes': 'pt', 'languages': 'Portuguese'} text, result = chain_translate_text(TEXT, start_codelang, codelang, monitoring=False) cprint.ok("\n##### RESULTS ######\n") cprint.ok(text) print() cprint.ok(result)
def calculateInterest(): while True: origin = int(input(_("What is the original number? "))) rate = float( input( _("What is the rate of interest in percentage (without the percent sign)? " ))) print() howMany = int( input( _('''How many units of time would you like to calculate? Essentially, one unit of time could be one month, or one decade. It all depends on what you typed in the rate of interest question: it could be per year, per decade...we didn't ask. It was up to you to type the correct amount in the rate question. We have no idea what the rate represented: it could have been that rate per century for all we know. This calculator wasn't programmed with the ability to track time. So, with that out of the way, type the amount we should multiply the interest by (aka the amount of units of time).\nType it: ''' ))) inRealNumbers = percentage(whole=origin, percent=rate) number = origin + (inRealNumbers * howMany) logging.info( "INTERESTCALC: origin: %s rate: %s howMany: %s answer: %s" % (origin, rate, howMany, number)) cprint.info(_("The answer is: \n%s" % number)) doItAgain = input(_("Would you like to do it again (Y/n)? ")) doItAgain = doItAgain.lower() if doItAgain == _("y"): pass else: cprint.ok(_("Going back...")) break
async def interact(conn, svr, connector, method, args, verbose=False): try: await connector except Exception as e: print("Unable to connect to server: %s" % e) return -1 cprint.info("\nConnected to: %s\n" % svr) if verbose: donate = await conn.RPC('server.donation_address') if donate: cprint.info("Donations: " + donate) motd = await conn.RPC('server.banner') cprint.info("\n---\n%s\n---" % motd) # XXX TODO do a simple REPL here if method: cprint.warn("\nMethod: %s" % method) # risky type cocerce here args = [(int(i) if i.isdigit() else i) for i in args] try: rv = await conn.RPC(method, *args) cprint.ok(json.dumps(rv, indent=1)) except ElectrumErrorResponse as e: cprint.err(e) conn.close()
def log( ): #https://stackoverflow.com/questions/33754670/calculate-logarithm-in-python import math while True: base = input( _("What base would you like to use? \nCurrently supported: 10 (base 10), e (natural)" )) if base == "10": cprint.info(_("Using base 10")) number = int(input(_("What is the number? "))) cprint.info(_("That equals:")) cprint.info(math.log10(number)) logging.info( "User used base 10 logarithm with number %s, getting a result of %s" % (number, (math.log10(number)))) break elif base.lower() == "e": cprint.info(_("Using natural logarithm")) number = int(input(_("What is the number? "))) cprint.info("That equals...") cprint.info(math.log(number)) logging.info( "User used natural logarithm with number %s, getting a result of %s" % (number, (math.log(number)))) break else: cprint.err(_("The logarithm you typed is not available.")) cprint.ok(_("Try again.")) logging.info( "User attempted to use a logarithm that is unavailable.")
def saveTrtGraph(graph, model_path, save_in): ''' Save the TRT optimized graph into a frozen graph file. ''' opt_dir = os.path.dirname(save_in) if not os.path.exists(opt_dir): os.makedirs(opt_dir) with open(save_in, 'wb') as f: f.write(graph.SerializeToString()) cprint.ok(f'Graph saved in {save_in}')
def update_index_with_sketch(sketch_name, title, cover, pyp5js): """ Updates index.html with new the new sketch """ sketch_dir = SKETCH_DIR.child(sketch_name) if not sketch_dir.exists(): cprint.err(f"There's no directory for the sketch {sketch_name}", interrupt=True) desc, desc_ptbr = '', '' while not desc: desc = input("Enter with sketch's description: ").strip() while not desc_ptbr: desc_ptbr = input("Entre com a descrição do sketch (PT-BR): ").strip() title = title or f'#{sketch_name}' if pyp5js: template = templates.get_template('new_pyp5js_entry_snippet.html') else: template = templates.get_template('new_entry_snippet.html') today = date.today() ctx = { 'sketch_id': sketch_name, 'title': title, 'cover': cover, 'sketch_date': f'{today:%m/%d/%Y}', 'description': desc, } content = template.render(ctx) index_template = templates.get_template('index_base.html') new_index_content = index_template.render(new_sketch_content=content) with open(SKETCH_DIR.child('index.html'), 'w') as fd: fd.write(new_index_content) content = template.render(ctx) index_template = templates.get_template('index_base.html') base_index_content = index_template.render(new_sketch_content='{{ new_sketch_content }}\n\n' + content) with open(TEMPLATES_DIR.child('index_base.html'), 'w') as fd: fd.write(base_index_content) cprint.ok("\nTweet content:") tweet_template = templates.get_template('tweet_template.txt') ctx = { 'eng_desc': desc, 'pt_desc': desc_ptbr, 'name': sketch_name, 'pyp5js': pyp5js, } content = tweet_template.render(**ctx) cprint.ok(content)
def compile_sketch(sketch_name, refresh, template): """ Command to update your sketch files (index, js codes etc) \nExample: $ pyp5js compile my_sketch """ files = commands.compile_sketch(sketch_name.replace("/", ""), refresh, template) cprint.ok( f"Your sketch is ready and available at file://{files.index_html.absolute()}" )
def load_graphdef(self, graph_def): ''' Plug a graph def into the main graph of the detector session . ''' conf = tf.compat.v1.ConfigProto(log_device_placement=False) # conf.gpu_options.allow_growth = True conf.gpu_options.per_process_gpu_memory_fraction = 0.4 graph = tf.compat.v1.Graph() with graph.as_default(): tf.import_graph_def(graph_def, name='') # Now we use the previously allocated session attribute self.sess = tf.compat.v1.Session(graph=graph, config=conf) cprint.ok('Loaded the graph definition!')
def transcrypt_sketch(sketch_name): """ Command to generate the P5.js code for a python sketch Params: - sketch_name: name of the sketch Example: $ pyp5js transcrypt my_sketch """ files = commands.transcrypt_sketch(sketch_name) cprint.ok(f"Your sketch is ready and available at file://{files.index_html.absolute()}")
def transcrypt_sketch(sketch_name, sketch_dir): """ Command to generate the P5.js code for a python sketch Params: - sketch_name: name of the sketch Opitionals - sketch_dir: sketch's directory (defaults to {sketch_name}) """ index_file = commands.transcrypt_sketch(sketch_name, sketch_dir) cprint.ok(f"Your sketch is ready and available at {index_file}")
def base(): base = int( input('''What base would you like to convert to? Available: 2 (binary) 8 (octo) 10 (decimal (normal)) 16 (hex) Type 2, 8, 10, or 16: ''')) if base == 2: origin = int(input(_("Type the original number: "))) #bin() the number printThis = "=" + str(bin(origin)) logging.info("User binaried number %s, getting a result of %s" % (origin, printThis)) cprint.info(printThis) elif base == 8: result = int(input(_("Type the original number: "))) #oct() the number printThis = "=" + str(oct(result)) logging.info("User oct'ed number %s, getting a result of %s" % (result, printThis)) cprint.info(printThis) elif base == 10: base = int( input( _('''Converting from a base to decimal (normal). Example bases: 2 - Binary 8 - Oct 16 - Hexadecimal Or, type 1 for ord. Type: '''))) if base == 1: base2Print = "ord" else: base2Print = "base " + base original = int( input( _("Please enter the number to be converted from %s: " % base2Print))) if base == 1: eureka = chr(original) else: eureka = int(original, base) logging.info("User int'ed number %s from %s, getting a result of %s" % (original, base2Print, eureka)) cprint.info(_("That equals...\n%s" % eureka)) cprint.ok( _("TIP: If you got no answer, it might be that it was a Unicode character that it can't render. E.g. \\x06 would just be a blank space, like so: \x06" )) elif base == 16: result = int(input( _("Type the original number: "))) #ask for original number printThis = "=" + hex(result) logging.info("User hexed number %s, getting a result of %s" % (result, printThis)) cprint.info(printThis)
def processError(self, error, verbose=False, debug=False): ''' This method computes the proper PID response given an error, and commands it to the motors (via function send() to provide softness). ''' P = self.Kc * error * self.scaling_factor I = self.Ki * (error + self.cumulative_error) * self.scaling_factor if self.prev_error != 0: # To avoid jumps because of the huge derivative D = self.Kd * (error - self.prev_error) * self.scaling_factor else: D = 0 response = P + I + D if verbose: # Print outputs cprint.ok(' P >> %.3f' % (P)) cprint.ok(' I >> %.3f' % (I)) cprint.ok(' D >> %.3f' % (D)) cprint.ok(' Response >> %.3f' % (response)) # Limiting response! if abs(response) > self.limiter: response = np.sign(response) * self.limiter if not debug: self._sendCommand(response) # Update parameters for the next iteration self.prev_error = error self.cumulative_error += error # Returning response for printing it return response
def computeResponse(self, error): '''Compute the appropriate response.''' if np.isnan(error): return self.last_response if self.isInRange(error): # Reset the memory and stop moving. self.prev_error = 0 self.cumulative_error = 0 self.last_response = 0 cprint.ok('\tNull response (target in range)') return 0 # Compute the response from # the relative error otherwise rel_error = error - self.center P = self.Kp * rel_error I = self.Ki * (rel_error + self.cumulative_error) if abs(self.prev_error ) > 0: # To avoid jumps because of the huge derivative D = self.Kd * (rel_error - self.prev_error) else: D = 0 response = P + I + D if self.verbose: # Print outputs cprint.info(f'\tP >> {P:.3f}') cprint.info(f'\tI >> {I:.3f}') cprint.info(f'\tD >> {D:.3f}') cprint.ok(f'\tResponse >> {response:.3f}') # Limiting response! if abs(response) > self.limit: response = np.sign(response) * self.limit # Update parameters for the next iteration self.prev_error = rel_error self.cumulative_error += rel_error if self.soften: response = np.mean([self.last_response, response]) self.last_response = response # Returning the response value return response
def write_benchmark(self, total_times, model_name, rosbag_file, arch, write_iters=True): # Convert the lapse measurements to milliseconds total_ms = np.array(total_times) total_ms[:, 0] = TO_MS_VEC(total_ms[:, 0]) # Filter the non-empty inferences nonempty = total_ms[total_ms[:, 1] > 0] dic = {} # Metadata dic['1.- Meta'] = { '1.- ModelName': model_name, '2.- ROSBag': rosbag_file, '3.- Architecture': arch, } # Stats stats_total = { 'Mean': f'{total_ms[:, 0].mean():.4f} ms', 'Std': f'{total_ms[:, 0].std():.4f} ms', } stats_nonempty = { 'Mean': f'{nonempty[:, 0].mean():.4f} ms', 'Std': f'{nonempty[:, 0].std():.4f} ms', } dic['2.- Stats'] = { '1.- Total': stats_total, '2.- NonEmpty': stats_nonempty, } if write_iters: iters = {} for idx, iteration in enumerate(total_ms): iters[idx] = { 'InferenceTime': f'{iteration[0]:.4f} ms', 'NumDetections': iteration[1] } dic['3.- Iterations'] = iters # Finally, dump the results into the requested file. with open(self.save_in, 'w') as f: yaml.dump(dic, f) cprint.ok(f'Benchmark written in {self.save_in}!')
def on_modified(self, event): cprint.info(f"New change in {event.src_path}") # monkey patch on the observer handlers to avoid recursion handlers_config = self.observer._handlers.copy() handlers_copy = {} compile_sketch_js(self.sketch) queue = self.observer.event_queue while queue.qsize(): queue.get() index_file = self.sketch.index_html cprint.ok( f"Your sketch is ready and available at file://{index_file.absolute()}" )
def loadFrozenGraph(model_path, write_nodes): ''' Load a frozen graph from a .pb file. ''' model_path = os.path.join(MODELS_DIR, model_path) pb_path = os.path.join(model_path, FG_NAME) # Check the existance if not os.path.isfile(pb_path): cprint.fatal(f'Error: the file {pb_path} does not exist.', interrupt=True) cprint.info('Loading the frozen graph...') graph_def = tf.compat.v1.GraphDef() with tf.io.gfile.GFile(pb_path, 'rb') as fid: serialized_graph = fid.read() graph_def.ParseFromString(serialized_graph) tf.import_graph_def(graph_def, name='') cprint.ok('Loaded!') if write_nodes: writeNodes(model_path, graph_def) return graph_def
def showUserWhatIThink(whatDOyouthink): cprint.ok(_("I think you want me to: ")) cprint.ok(whatDOyouthink) if _("y") in input(_("Is this correct? (Y/n)")).lower(): logging.info( "Palc chose the right calculation (%s) for calc choice that (should be) shown above." % whatDOyouthink) else: cprint.info( _("Try different wording. Or, if you want that calculation choice to be made right, file a ticket." )) if _("y") in input( _("Would you like to file a ticket? (Y/n)\nType: ")).lower(): import webbrowser webbrowser.open("http://github.com/thetechrobo/support/issues/new") logging.info( "User chose to file a ticket because they didn't want Palc to %s" % whatDOyouthink) cprint.info(_("Proceeding with the function I thought it was.")) else: cprint.info( _("OK, proceeding with the function I thought it was."))
def main(): with open('./config.yaml') as f: config = yaml.load(f, Loader=yaml.SafeLoader) # Read config if config: cprint.ok("load config is " + json.dumps(config)) else: cprint.info("load config file `config.yaml` failed") # Set logger logging.basicConfig( format= "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s", level=logging.INFO, handlers=[ logging.FileHandler("./log/detect.log", mode='a', encoding=None, delay=False), logging.StreamHandler() ]) # Get environment variables source = os.environ.get('DETECT_SOURCE') or config.get("source") keys = config.get("keys") if os.environ.get('DETECT_KEYS') is not None: keys = os.environ.get('DETECT_KEYS').split(",") street = os.environ.get('DETECT_STREET') or config.get("street") interval = os.environ.get('DETECT_INTERVAL') or config.get("interval") device = os.environ.get('DETECT_DEVICE') or config.get("device") report_url = os.environ.get('REPORT_URL') or config.get("report_url") category = os.environ.get('CATEGORY') or config.get("category") title = os.environ.get('TITLE') or config.get("title") # Run detect reporter = Reporter(report_url, interval, street, title, category) detect(source, device, keys, reporter)
def configure_new_sketch(sketch_name, sketch_dir): """ Create dir and configure boilerplate Params: - sketch_name: name of the sketch (will create a {sketch_name}.py) Opitionals - sketch_dir: directory to save the sketch (defaults to {sketch_name}) """ sketch_py = commands.new_sketch(sketch_name, sketch_dir) cprint.ok(f"Your sketch was created!") cprint.ok( f"Please, open and edit the file {sketch_py} to draw. When you're ready to see your results, just run:" ) cprint.ok(f"\t pyp5js transcrypt {sketch_name}")
def configure_new_sketch(sketch_name, monitor): """ Create dir and configure boilerplate Params: - sketch_name: name of the sketch (will create a {sketch_name}.py) Opitionals: - monitor: start the monitor command as well Example: $ pyp5js new my_sketch """ files = commands.new_sketch(sketch_name) cprint.ok(f"Your sketch was created!") if not monitor: cprint.ok(f"Please, open and edit the file {files.sketch_py} to draw. When you're ready to see your results, just run:") cmd = f"\t pyp5js transcrypt {sketch_name}" cprint.ok(cmd) cprint.ok(f"And open file://{files.index_html.absolute()} on your browser to see yor results!") else: cprint.ok(f"Please, open and edit the file {sketch_py} to draw.") cprint.ok(f"And open file://{files.index_html.absolute()} on your browser to see yor results!") commands.monitor_sketch(sketch_name)
def palc(): while True: print(_("Press any key to continue..."), end="", flush=True) if _IS_WINDOWS: msvcrt.getch() else: fd = sys.stdin.fileno() settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, settings) print(chr(27) + '[2j' ) #First attempt at clearing the screen with ANSI escape codes. print('\033c' ) #Second attempt at clearing the screen with ANSI escape codes. print('\x1bc' ) #Third attempt at clearing the screen with ANSI escape codes. #CALCULATION CHOICE calc = input( _("What calculation do you wish to do? (Type `?' for a list of commands)\nType: " )) logging.info("Got calc choice %s" % calc) calc = calc.lower() #make variable "calc" lowercase #HELP if "?" in calc: logging.info("User needed help") h() elif _("help") in calc: logging.info("User needed help") h() #TAX elif _("tax") in calc: showUserWhatIThink(_("calculate tax")) taxCalc() #SQUARE elif _("sq") in calc: showUserWhatIThink(_("square a number")) n = int(input(_("Number to square? "))) cprint.info(n * n) logging.info("User squared number %s got result %s" % (n, (n * n))) elif "[]" in calc: showUserWhatIThink(_("square a number")) n = int(input(_("Number to square? "))) logging.info("User squared number %s got result %s" % (n, (n * n))) cprint.info(n * n) #DIVISION elif "/" in calc: showUserWhatIThink(_("divide a number")) div() elif "div" in calc: showUserWhatIThink(_("divide a number")) div() #SUBTRACTION elif "-" in calc: showUserWhatIThink(_("subtract a number from a number")) sub() elif _("sub") in calc: showUserWhatIThink(_("subtract a number from a number")) sub() elif "min" in calc: showUserWhatIThink(_("subtract a number from a number")) sub() #ADDITION elif "+" in calc: showUserWhatIThink(_("add two numbers")) add() elif "add" in calc: showUserWhatIThink(_("add two numbers")) add() elif "plus" in calc: showUserWhatIThink(_("add two numbers")) add() #MODULO elif "%" in calc: showUserWhatIThink( _("find the remainder of two numbers after division")) mod() elif "mod" in calc: showUserWhatIThink( _("find the remainder of two numbers after division")) mod() #AREA elif _("area") in calc: showUserWhatIThink(_("calculate area")) area() elif "#" in calc: showUserWhatIThink(_("calculate area")) area() #VOLUME elif _("vol") in calc: showUserWhatIThink(_("use the volume calculator")) uc() #CUBE elif "{}" in calc: showUserWhatIThink(_("cube a number")) cubedNumber = int(input(_("\nType the number to be cubed: "))) print() cprint.info(cubedNumber**3) #Manually cube number logging.info("User cubed number %s got result %s" % (cubedNumber, (cubedNumber**3))) print() elif _("cube") in calc: showUserWhatIThink(_("cube a number")) cubedNumber = int(input(_("\nType the number to be cubed: "))) print() cprint.info(cubedNumber**3) #Manually cube number logging.info("User cubed number %s got result %s" % (cubedNumber, (cubedNumber**3))) print() #EXIT elif _("quit") in calc: showUserWhatIThink(_("quit")) logging.info("User exited using `quit' command") e() elif "exit" in calc: showUserWhatIThink(_("exit")) logging.info("User exited using `exit' command") e() #MULTIPLICATION elif "*" in calc: showUserWhatIThink(_("multiply a number")) multi() elif "x" in calc: showUserWhatIThink(_("multiply a number")) multi() elif "multi" in calc: showUserWhatIThink(_("multiply a number")) multi() #EXPONENTS elif "power" in calc: showUserWhatIThink(_("use the exponent function")) origin = float(input(_("Original number?"))) ex = float(input(_("Exponent? "))) cprint.info(origin**ex) logging.info("User exponented number %s with %s, getting %s" % (origin, ex, (origin**ex))) elif "ex" in calc: showUserWhatIThink(_("use the exponent function")) origin = float(input(_("Original number?"))) ex = float(input(_("Exponent? "))) cprint.info("=%s" % origin**ex) logging.info("User exponented number %s with %s, getting %s" % (origin, ex, (origin**ex))) #CUBE TWICE elif "{2}" in calc: cprint.err(_("The \" CUBE TWICE \" feature was discontinued.")) logging.error( "User attempted to use cube twice function but it's discontinued" ) #ROOTS elif _("root") in calc: showUserWhatIThink( _("use the root function (opposite of exponents)")) root = input(_("Square root or cube root? (square/cube)\nType: ")) root = root.lower() if _("square") in root: num = input(_("Number to be rooted?")) cprint.info(_("That equals.....\n", num**0.5)) logging.info("user sqrooted number %s" % (num**0.5)) elif "cube" in root: cu() else: cprint.err( _("Currently I don't support the root you chose. Hopefully this will change :)" )) logging.error("User used non-existent root (%s)" % root) #EASTER EGG! elif "=" in calc: showUserWhatIThink( _("use the equals function (completely useless)")) number = int(input(_("\nType in a number: "))) if number == 42: cprint.info( _("=42 -- the answer to life, the universe, and everything" )) logging.info("User got the easter egg") else: cprint.err(_("Do you really need a calculator for this?")) logging.info("User used the `=' feature for number %s" % number) #NUMBER SYSTEMS elif "base" in calc: showUserWhatIThink(_("convert number systems")) base() #ORD elif "ord" in calc: showUserWhatIThink(_("ord a number")) result = str(ord(int(input(_("Type in the number to ord: "))))) logging.info("User ord'ed to get result %s" % result) cprint.info("= %s" % result) #LOGARITHM elif _("log") in calc: showUserWhatIThink(_("use the logarithm function")) log() #MEMORY elif "mem" in calc: showUserWhatIThink(_("use the memory function")) memOrRecall = input( _("Would you like to set the memory or recall? (set / recall)\nType: " )) if _("set") in memOrRecall.lower(): remember() elif _("recall") in memOrRecall.lower(): readMyMemory() else: cprint.err(_("You did not type an answer.\nAbort.")) logging.error( "User didn't type an answer in MEM function (typed %s)" % memOrRecall) #FIBONACCI elif "fib" in calc: showUserWhatIThink(_("use the fibonacci calculator")) cprint.ok(_("Starting fibonacci sequence. Please wait.")) fib() #PERCENTAGE elif _("percent" ) in calc: #SOURCE: https://stackoverflow.com/a/5998010/9654083 showUserWhatIThink(_("use the percentage function")) whichOne = int( input( _('''1 - Calculate "What is x% of y?" 2 - Convert a number to percentage. Type: '''))) if whichOne == 1: whatIsPercent() elif whichOne == 2: getPercentageRN() else: cprint.err(_("You didn't type a valid answer. Abort.")) logging.info( "User did not answer correct percentage interpretation (typed %s)" % whichOne) #INTEREST elif _("interest") in calc: showUserWhatIThink(_("use the interest calculator")) calculateInterest() #TEMPERATURE elif "temperature" in calc: showUserWhatIThink(_("use the temperature converter")) tempCalc() #CONVERSIONS elif "conver" in calc: showUserWhatIThink(_("use the converter functions")) conversion = int(input(_("1 - Convert temperature units\nType: "))) if conversion == 1: tempCalc() #OTHERWISE elif calc == "": logging.error("User attempted to type nothing as a command") cprint.err(_("Type something!")) elif calc is None: logging.error("User attempted to type nothing as a command") cprint.err(_("Type something!")) else: logging.error("User typed an invalid command (%s)" % calc) cprint.err( _(''' I don't understand your request. Here are the currently supported calculations: multiplication, division, subtraction, addition, modulo, square, area, volume, cube, power, root, ord, fibonacci, logarithm, memory, percentage calculator, interest calculator, temperature, and base. Sorry for the inconvenience '''))
def follow(self): full_image = self.camera.get_rgb_image() img2show = cv2.cvtColor(full_image, cv2.COLOR_RGB2BGR) self.network.predict() self.detection_boxes = self.network.boxes self.detection_scores = self.network.scores for xmin, ymin, xmax, ymax in self.detection_boxes: cv2.rectangle(img2show, (xmin, ymax), (xmax, ymin), (0, 0, 255), 5) self.persons = self.person_tracker.evalPersons(self.detection_boxes, self.detection_scores, full_image) self.faces = self.person_tracker.getFaces(full_image) cprint.info('\t........%d/%d faces detected........' % (len(self.faces), len(self.persons))) mom_found_now = False # Iteration over all faces and persons... for person in self.persons: if person.is_mom: self.mom_coords = person.coords mom_found_now = True break else: faces = person.ftrk.tracked_faces if len(faces) > 0: face = faces[0] [f_width, f_height] = [face[2] - face[0], face[3] - face[1]] f_total_box = np.zeros(4, dtype=np.int16) f_total_box[:2] = person[:2] + face[:2] f_total_box[2:4] = f_total_box[:2] + [f_width, f_height] cropped_face = full_image[f_total_box[1]:f_total_box[3], f_total_box[0]:f_total_box[2], :] # We compute the likelihood with mom... dist_to_mom = self.siamese_network.distanceToMom( cropped_face) if dist_to_mom < self.face_thres: # Unset other moms for idx2 in range(len(self.persons)): self.person_tracker.tracked_persons[ idx2].is_mom = False # And set that person to mom. self.person_tracker.tracked_persons[idx].is_mom = True self.mom_coords = person.coords mom_found_now = True break if mom_found_now: cprint.ok("\t\t Mom found") cprint.ok(str(self.mom_coords)) #[xmin, ymin, xmax, ymax] = self.mom_coords #cv2.rectangle(img2show, (xmin, ymax), (xmax, ymin), (0,255,0), 5) else: cprint.warn("\t\t Looking for mom...") return img2show
import yaml from jinja2 import Environment, FileSystemLoader, select_autoescape from unipath import Path from cprint import cprint PYP5_DIR = Path(__file__).parent TEMPLATES_DIR = PYP5_DIR.child('templates') ASSETS_DIR = PYP5_DIR.child('assets') if __name__ == '__main__': with open(ASSETS_DIR.child('p5_methods.yml')) as fd: methods_names = yaml.load(fd.read())['methods'] with open(ASSETS_DIR.child('p5_variables.yml')) as fd: variables_names = yaml.load(fd.read())['variables'] templates = Environment(loader=FileSystemLoader(TEMPLATES_DIR)) pyp5_template = templates.get_template('pytop5js.py.template') context = {'function_names': methods_names, 'variables_names': variables_names} pyp5_content = pyp5_template.render(context) pyp5_path = PYP5_DIR.child('pytop5js.py') with open(pyp5_path, 'w') as fd: fd.write(pyp5_content) cprint.ok(f"File {pyp5_path} was updated with success.")
def move(self): ''' Method called on each iteration. Detects persons and look for mom. Commands the robot towards mom if it is found. ''' # We get the full RGB and D images. full_image = self.camera.getImage() d = self.depth.getImage() full_depth, _, _ = cv2.split(d) def goToMom(mom_box): ''' Function to go towards mom. ''' # We compute the distance to mom ################################ ############### v ############## ################################ mom_depth = full_depth[mom_box[1]:mom_box[3], mom_box[0]:mom_box[2]] distance, grid = self.estimateDepth(mom_depth) # V error processing (go forward/backward) error = distance - self.v_center if self.prev_error is not None: d_error = abs(error - self.prev_error) else: d_error = 0 # Avoid jumps if d_error < 10.0: if error < -self.v_margin: # Too near v = self.v_PID.processError(error, verbose=True) cprint.warn(' Distance: %d px (too near) >> VX = %.3f m/s' % (distance, v)) # Avoid overswitching if not self.margin_expanded: self.v_margin = self.v_margin - 5 self.margin_expanded = True self.margin_expanded = True cprint.info("New margin: %d" % (self.v_margin)) elif error > self.v_margin: # Too far v = self.v_PID.processError(error, verbose=True) cprint.warn(' Distance: %d px (too far) >> VX = %.3f m/s' % (distance, v)) # Avoid overswitching if not self.margin_expanded: self.v_margin = self.v_margin - 5 self.margin_expanded = True cprint.info("New margin: %d" % (self.v_margin)) else: # Inside range (OK) cprint.ok(' Distance: %d px (under control)' % (distance)) self.v_PID.resetError() self.v_PID.brake() if self.margin_expanded and error < self.original_v_margin: # The margin can be restored... cprint.info("Margin restored.") self.v_margin = self.original_v_margin self.margin_expanded = False self.prev_error = error # Now, we compute the necessary turning ################################ ############### w ############## ################################ mom_center = (mom_box[2] + mom_box[0]) / 2 h_error = self.center_coords[0] - mom_center if abs(h_error) > self.w_margin: # Turning... w = self.w_PID.processError(h_error, verbose=False) if w < 0: turn_dir = 'right' else: turn_dir = 'left' cprint.warn(' Angle: %d px >> Turning %s (w: %.3f r/s)' % (h_error, turn_dir, w)) else: # Inside the angle margin (OK) cprint.ok(' Angle: %d px (under control)' % (h_error)) self.w_PID.resetError() self.w_PID.brake() # Network outputs. Exclusively high score people detections. self.detection_boxes = self.network.boxes self.detection_scores = self.network.scores # num_detections = len(self.detection_boxes) # We retrieve every detected face on the current frame. self.persons = self.person_tracker.evalPersons(self.detection_boxes, self.detection_scores, full_image) # Now, we look for faces in those persons. print "" self.faces = self.person_tracker.getFaces(full_image) cprint.info('\t........%d/%d faces detected........' % (len(self.faces), len(self.persons))) mom_found_now = False # Iteration over all faces and persons... for idx in range(len(self.persons)): person = self.persons[idx] if person.is_mom: self.mom_coords = person.coords mom_found_now = True break else: faces = person.ftrk.tracked_faces if len(faces) > 0: face = faces[0] [f_width, f_height] = [face[2] - face[0], face[3] - face[1]] f_total_box = np.zeros(4, dtype=np.int16) f_total_box[:2] = person[:2] + face[:2] f_total_box[2:4] = f_total_box[:2] + [f_width, f_height] cropped_face = full_image[f_total_box[1]:f_total_box[3], f_total_box[0]:f_total_box[2], :] # We compute the likelihood with mom... dist_to_mom = self.siamese_network.distanceToMom(cropped_face) if dist_to_mom < self.face_thres: # Unset other moms for idx2 in range(len(self.persons)): self.person_tracker.tracked_persons[idx2].is_mom = False # And set that person to mom. self.person_tracker.tracked_persons[idx].is_mom = True self.mom_coords = person.coords mom_found_now = True break # If mom is being tracked, we move the robot towards it. if mom_found_now: cprint.ok("\t\t Mom found") goToMom(self.mom_coords) else: cprint.warn("\t\t Looking for mom...") self.v_PID.lostResponse() self.w_PID.lostResponse()
def console_ok(msg): now_time = datetime.now().strftime("%d/%m/%Y %H:%M:%S.%f") cprint.ok('%s [OK] - %s' % (now_time, msg))
if __name__ == '__main__': # Parameter parsing descr = ''' Receives images from a video source and run neural detection inferences on the provided images. Shows the results in a GUI.''' parser = argparse.ArgumentParser(description=descr) parser.add_argument('config_file', type=str, help='Path for the YML configuration file') args = parser.parse_args() source, cam_params, net_params = utils.readConfig(args.config_file) # Camera cam = utils.getVideoSource(source, cam_params) cprint.ok('Camera ready') # Threading the camera... t_cam = ThreadCamera(cam) t_cam.start() # Inference network net = DetectionNetwork(net_params) net.setCamera(cam) cprint.ok('Network ready') # Threading the network... t_network = ThreadNetwork(net) t_network.start() app = QtWidgets.QApplication(sys.argv)
def goToMom(mom_box): ''' Function to go towards mom. ''' # We compute the distance to mom ################################ ############### v ############## ################################ mom_depth = full_depth[mom_box[1]:mom_box[3], mom_box[0]:mom_box[2]] distance, grid = self.estimateDepth(mom_depth) # V error processing (go forward/backward) error = distance - self.v_center if self.prev_error is not None: d_error = abs(error - self.prev_error) else: d_error = 0 # Avoid jumps if d_error < 10.0: if error < -self.v_margin: # Too near v = self.v_PID.processError(error, verbose=True) cprint.warn(' Distance: %d px (too near) >> VX = %.3f m/s' % (distance, v)) # Avoid overswitching if not self.margin_expanded: self.v_margin = self.v_margin - 5 self.margin_expanded = True self.margin_expanded = True cprint.info("New margin: %d" % (self.v_margin)) elif error > self.v_margin: # Too far v = self.v_PID.processError(error, verbose=True) cprint.warn(' Distance: %d px (too far) >> VX = %.3f m/s' % (distance, v)) # Avoid overswitching if not self.margin_expanded: self.v_margin = self.v_margin - 5 self.margin_expanded = True cprint.info("New margin: %d" % (self.v_margin)) else: # Inside range (OK) cprint.ok(' Distance: %d px (under control)' % (distance)) self.v_PID.resetError() self.v_PID.brake() if self.margin_expanded and error < self.original_v_margin: # The margin can be restored... cprint.info("Margin restored.") self.v_margin = self.original_v_margin self.margin_expanded = False self.prev_error = error # Now, we compute the necessary turning ################################ ############### w ############## ################################ mom_center = (mom_box[2] + mom_box[0]) / 2 h_error = self.center_coords[0] - mom_center if abs(h_error) > self.w_margin: # Turning... w = self.w_PID.processError(h_error, verbose=False) if w < 0: turn_dir = 'right' else: turn_dir = 'left' cprint.warn(' Angle: %d px >> Turning %s (w: %.3f r/s)' % (h_error, turn_dir, w)) else: # Inside the angle margin (OK) cprint.ok(' Angle: %d px (under control)' % (h_error)) self.w_PID.resetError() self.w_PID.brake()
logging.critical("Could not access file func.py (%s)" % e) cprint.fatal(_( "I can't access the file func.py. This file is necessary for proper function of the Software." ), interrupt=True) logging.info("Successfully imported func.py") try: from basicfunc import * except Exception as e: logging.critical("Could Not Access basicfunc.py (%s)" % e) cprint.fatal(_( "I can't access file basicfunc.py. This file is necessary for proper function of the Software." ), interrupt=True) logging.info("Success import basicfunc.py !") cprint.ok(_("Loading...............\n")) time.sleep(2) def palc(): while True: print(_("Press any key to continue..."), end="", flush=True) if _IS_WINDOWS: msvcrt.getch() else: fd = sys.stdin.fileno() settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) sys.stdin.read(1) finally:
input_w = args.input_w input_h = args.input_h precision = args.precision mss = args.mss mce = args.mce allow_growth = args.allow_growth arch = args.arch write_nodes = args.write_nodes save_in = args.save_in if model_format == 'frozen': # The input and output names have to be provided input_names = args.input_names output_names = args.output_names graph_def = loadFrozenGraph(model_dir, write_nodes) else: graph_def, input_names, output_names = loadCheckpoint(model_dir, write_nodes) cprint.ok('Graph loaded') # These nodes can't be optimized blacklist_nodes = input_names + output_names # Run the optimization! trt_graph = optim_graph(graph_def, blacklist_nodes, precision, mss, mce) if trt_graph is None: cprint.fatal('Error: optimization not completed.', interrupt=True) cprint.ok('Optimization done!') # And dump the graph into a new .pb file trt_path = saveTrtGraph(trt_graph, model_dir, save_in)
import yaml from cprint import cprint from pyp5js.fs import Pyp5jsLibFiles, Pyp5jsSketchFiles from pyp5js.templates_renderer import get_pytop5js_content, get_target_sketch_template_content if __name__ == '__main__': pyp5js_files = Pyp5jsLibFiles() with open(pyp5js_files.p5_yml) as fd: data = yaml.load(fd.read()) p5_data, dom_data = data['p5'], data['dom'] methods_names = p5_data['methods'] + dom_data['methods'] event_function_names = p5_data['events'] variables_names = p5_data['variables'] + dom_data['variables'] pyp5_content = get_pytop5js_content(variables_names, methods_names, event_function_names) with open(pyp5js_files.pytop5js, 'w') as fd: fd.write(pyp5_content) cprint.ok(f"File {pyp5js_files.pytop5js} was updated with success.") target_content = get_target_sketch_template_content(event_function_names) with open(pyp5js_files.target_sketch_template, 'w') as fd: fd.write(target_content) cprint.ok( f"File {pyp5js_files.target_sketch_template} was updated with success." )