import time import streamlit as st from os import environ class Timer(): total = 0 expander = None def __init__(self, pt_name, en_name): self.pt_name = pt_name self.en_name = en_name if environ['PORTUGUESE'] == 'true': self.portuguese = True elif environ['PORTUGUESE'] == 'false': self.portuguese = False else: raise EnvironmentError if not Timer.expander: if self.portuguese: Timer.expander = st.expander('Ver progresso') else: Timer.expander = st.expander('See progress') self.display = Timer.expander.empty() def __enter__(self): if self.portuguese: self.display.info(f'Executando "{self.pt_name}"...') else: self.display.info(f'Running "{self.en_name}"...') self.start_time = time.time() def __exit__(self, type, value, traceback): end_time = time.time() elapsed_time = end_time - self.start_time Timer.total += elapsed_time self.display.empty() if self.portuguese: Timer.expander.info(f'"{self.pt_name}" terminou em {elapsed_time:.2f} s') else: Timer.expander.info(f'"{self.en_name}" finished in {elapsed_time:.2f} s') # for manually starting the timer def start(self): if self.portuguese: self.display.warning(f'Executando "{self.pt_name}"...') else: self.display.warning(f'Running "{self.en_name}"...') self.start_time = time.time() # for manually stopping the timer def stop(self): end_time = time.time() elapsed_time = end_time - self.start_time Timer.total += elapsed_time self.display.empty() if self.portuguese: Timer.expander.warning(f'"{self.pt_name}" terminou em {elapsed_time:.2f} s') else: Timer.expander.warning(f'"{self.en_name}" finished in {elapsed_time:.2f} s') def reset(): Timer.total = 0 Timer.expander = None def show_total(): if environ['PORTUGUESE'] == 'true': Timer.expander.success(f'Tempo de execução total: {Timer.total:.2f} s') elif environ['PORTUGUESE'] == 'false': Timer.expander.success(f'Total elapsed time: {Timer.total:.2f} s') def time_it(pt_name, en_name): def decorator(func): def wrapper(*args, **kwargs): timer = Timer(pt_name, en_name) timer.start() result = func(*args, **kwargs) timer.stop() return result return wrapper return decorator