def cli(ctx, eighties, commandfile, outputfile, file, author, title, date): """Simple program that greets NAME for a total of COUNT times.""" click.echo(set_title("Guten Haiku"), nl=False) if ctx.invoked_subcommand is None: if not (commandfile or file): if eighties: loading_sequence(("Loading Guten Haiku", LOGO), (None, USAGE)) else: click.echo(USAGE) exit(0) if not models.MODELS_ARE_DOWNLOADED: click.echo( f"{red}models are not downloaded, run {magenta}gutenhaiku setup" ) exit(1) if not (len(file) == len(author) == len(title) == len(date)): click.echo( f"{red}bad args: -f, -a, -t, -d needs to be same amount") exit(1) if eighties: loading_sequence(("Loading Guten Haiku", LOGO)) click.echo( magenta + f"\n Now processing {len(file)} {'books' if len(file)>1 else 'book'}\n" f" Starting with {yellow}{title[0]} {magenta}by {yellow}{author[0]}{magenta}\n" f" {random.choice(nice_things_to_say)}\n" f"{green} We start by doing some loading of {magenta}fancy AI models{green}", nl=False, ) for i in range(1, 9, 4): time.sleep(i / 4.0) click.echo(".", nl=False) from gutenhaiku import pipeline if eighties: click.echo(".", nl=False) time.sleep(0.2) click.echo( f"\n{green} Now we are ready to scan through the book, enjoy!\n" ) for f, a, t, d in zip(file, author, title, date): for data in pipeline.process_generator( f.read(), progress_bar=click.progressbar): data["author"] = a data["title"] = t data["date"] = d.isoformat() if eighties: click.echo(clear_line()) click.echo(format_haiku_json(**data)) outputfile.write(json.dumps(data) + "\n") click.echo(clear_line()) if eighties: click.echo(f"\n{green} All done, have a great day!\n")
def setup(eighties): if eighties: loading_sequence(("Loading Guten Haiku", LOGO)) if models.MODELS_ARE_DOWNLOADED: click.echo(green + "Models are already downloaded, exiting") exit(0) click.echo(green + "Downloading models") download.download_models(click.progressbar) click.echo(clear_line()) click.echo(green + "Done")
async def print_progress(): nonlocal working, done, failed last_height = 0 step = 0 # But it looks sexy in the console! while len(queue) > 0 or working > 0: message = (ansi.clear_line() + ansi.Cursor.UP(1)) * last_height message += '{clear}\r{cy}Queued: {cg}{nq}{cy} Working: {cg}{nw}' \ '{cy} Done: {cg}{nd}{cy} Failed: {cr}{nf}{r}\n\n'.format( clear=ansi.clear_line(), cy=Fore.YELLOW, cg=Fore.GREEN, cr=Fore.RED, r=Fore.RESET, nq=len(queue), nw=working, nd=done, nf=failed) for val in bc.download_status.values(): if val['status'] not in ('downloading', 'converting', 'requested'): continue message += Fore.YELLOW + '[' + Fore.BLUE if val['status'] in ('converting', 'requested'): bar = '.. .. ..' message += bar[step:step + 4] elif val['status'] == 'downloading': message += "{:>4.0%}".format(val['downloaded_size'] / val['size']) message += "{cy}] {cc}{v[item].name}{cy} by {cg}{v[item].artist}{r}\n".format( cy=Fore.YELLOW, cc=Fore.CYAN, cg=Fore.GREEN, r=Fore.RESET, v=val) last_height = message.count("\n") print(message, end="") step = (step + 1) % 3 await asyncio.sleep(0.5)
def execute(self): """Parse the command line options and launch the requested command. If the command is 'help' then print the help message for the subcommand; if no subcommand is given, print the standard help message. Note: This is the entry point method for the containenv command defined in setup.py. """ from pprint import pprint as pp verbose_stream = StringIO() atexit.register(lambda: print( clear_line() + verbose_stream.getvalue(), file=sys.stderr, end='') ) try: tokens = docopt(self._DEFAULT_DOC, version='containenv {}'.format(VERSION), options_first=True) # alias command # print('command line tokens') # pp(tokens) command = self._get_command(tokens) # Process options if tokens['--verbose']: debug_level = int(tokens['--debug']) # default == logging default handler = logging.StreamHandler(verbose_stream) handler.setLevel(debug_level) rl = logging.getLogger() rl.setLevel(debug_level) logger.info("debug level set to {}".format(debug_level)) handler.setFormatter(LogColorFormatter()) rl.addHandler(handler) logger.debug('Verbose logging activated') # All options are now processed self._run_command([command] + tokens['<args>']) except (KeyboardInterrupt, EOFError): sys.exit("Cancelling at the User's request.") except Exception as e: logger.exception(e) sys.exit(e)
def test_emit_loop_record(self): loop = 0 loop_id = uuid.uuid4() while loop < 2: for i in range(3): record = makeLogRecord({ 'msg': 'test {}'.format(i), 'loop': loop_id, 'reset': i == 0, }) self.handler.emit(record) loop += 1 self.assertEqual(len(self.stream.write.call_args_list), 7, 'Should have accounted for moving cursor up') for index, arg in enumerate(self.stream.write.call_args_list): line = arg[0][0] if index == 3: self.assertTrue(line.startswith(Cursor.UP(4))) else: self.assertTrue(line.startswith(clear_line()))
def update(self, msg): self._log_raw('update', Fore.CYAN, msg, clear_line() + '\r')
def format(self, record): msg = super(LogLoopStreamHandler, self).format(record) if record.__dict__.get("loop"): msg = "{}{}".format(clear_line(), msg) return msg
def print_temp_message(msg: str): """ print a message and reset the cursor to the begining of the line """ print(clear_line(), msg, Cursor.BACK(len(msg)), sep="", end="", flush=True)