Ejemplo n.º 1
0
def create_ui(timestamp: datetime):
    """ Create our user interface within the console. Returns the rich Layout."""
    # https://rich.readthedocs.io/en/latest/index.html
    ui = Layout()
    ui.split_row(
        Layout(name='left'),
        Layout(name='right'),)

    panel_now = weather_now.create_weather_panel()
    panel_3h = weather_03h.create_weather_panel()
    panel_6h = weather_06h.create_weather_panel()
    panel_9h = weather_09h.create_weather_panel()
    panel_info = Panel(f"[i]{get_next_update_time(timestamp, api_delay_in_sec)}[/]")
    panel_info.box = box.ASCII
    panel_info.renderable += f"\n[i]Press [red]CTRL-C[/red] for different location at any time.[/]"

    # Future forecast panels.
    ui['right'].split_column(
        Layout(panel_3h, name='3h'),
        Layout(panel_6h, name='6h'),
        Layout(panel_9h, name='9h'),
    )

    # "now" and "info" panels.
    ui['left'].split_column(
        Layout(panel_now, name='now', ratio=3),
        Layout(panel_info, name='info'),
    )

    return ui
Ejemplo n.º 2
0
    def get_renderable(self):
        tasks_panel_rendered = self.tasks_panel.get_renderable()
        metrics_panel_rendered = self.metrics_panel.get_renderable()

        if tasks_panel_rendered is None and metrics_panel_rendered is None:
            return Align(
                Text(f"Waiting for test to start... ({self.test_name})"),
                align="center")

        layout = Layout()

        layout.split_row(
            Layout(name="running", visible=False),
            Layout(name="metrics", ratio=2, visible=False),
        )

        if metrics_panel_rendered is not None:
            layout["metrics"].visible = True
            layout["metrics"].update(metrics_panel_rendered)

        if tasks_panel_rendered is not None:
            layout["running"].visible = True
            layout["running"].update(tasks_panel_rendered)

        return Panel(layout, title=self.test_name)
Ejemplo n.º 3
0
def make_info_panel(debugger) -> Layout:
    info_layout = Layout(name='Info')
    info_layout.split_row(Layout(name='runtime_state'),
                          Layout(name='world_state'))

    pc = debugger.executor.vm_context.code.pc + 1
    insn = debugger.executor.disasm_dict[pc]
    opcode = insn.byte
    mnemonic = insn.mnemonic
    msg = debugger.executor.vm_context.msg
    info_table = Table(box=box.SIMPLE)
    info_table.grid(padding=1)
    info_table.add_column('Key', justify="middle", style="cyan", no_wrap=True)
    info_table.add_column("Value", justify="middle", style="magenta")
    info_table.add_row('PC', f'{str(pc)} ({hex(pc)})')
    info_table.add_row('Opcode', f'{int(opcode[2:], 16)} ({opcode})')
    info_table.add_row('Mnemonic', f'{mnemonic}')
    info_table.add_row('', '')
    info_table.add_row('Sender', f'0x{msg.sender.hex()}')
    if msg.to:
        info_table.add_row('To', f'0x{msg.to.hex()}')
    elif msg.storage_address:
        info_table.add_row('To', f'0x{msg.storage_address.hex()}')
    elif msg.code_address:
        info_table.add_row('To', f'0x{msg.code_address.hex()}')
    info_table.add_row('Gas Price', str(msg.gas_price))
    info_table.add_row('Nonce', str(debugger.executor.vm_context.msg.depth))

    info_panel = Panel(
        info_table,
        box=box.ROUNDED,
        title="[b red]Runtime State",
        border_style="bright_blue",
    )

    state = debugger.executor.vm_context.state
    world_state_table = Table(box=box.SIMPLE)
    world_state_table.grid(padding=1)
    world_state_table.add_column('Key',
                                 justify="middle",
                                 style="cyan",
                                 no_wrap=True)
    world_state_table.add_column("Value", justify="middle", style="magenta")
    world_state_table.add_row('coinbase', f'{state.coinbase.hex()}')
    world_state_table.add_row('timestamp', f'{state.timestamp}')
    world_state_table.add_row('block_number', f'{state.block_number}')
    world_state_table.add_row('difficulty', f'{state.difficulty}')
    world_state_table.add_row('gas_limit', f'{state.gas_limit}')

    world_state_panel = Panel(
        world_state_table,
        box=box.ROUNDED,
        title="[b red]World State",
        border_style="bright_blue",
    )

    info_layout["runtime_state"].update(info_panel)
    info_layout["world_state"].update(world_state_panel)

    return info_layout
Ejemplo n.º 4
0
def main() -> None:
    layout = Layout()
    layout.split_row(
        Layout(name="all"),
        Layout(name="bats"),
        Layout(name="run"),
        Layout(name="def"),
        Layout(name="pitch"),
    )
    layout["all"].update(Panel(
        sort_players("hitting", "defense", "baserunning", "pitching"),
        title="Overall",
    ))
    layout["bats"].update(Panel(
        sort_players("hitting"),
        title="Batting",
    ))
    layout["def"].update(Panel(
        sort_players("defense"),
        title="defense",
    ))
    layout["run"].update(Panel(
        sort_players("baserunning"),
        title="Baserunning",
    ))
    layout["pitch"].update(Panel(
        sort_players("pitching"),
        title="Pitching",
    ))
    console.print(layout)
Ejemplo n.º 5
0
def _get_binance_layout(
    bin_status: BinanceStatus,
    profit_today: Dict[str, ExchangeRate],
    profit_yesterday: Dict[str, ExchangeRate],
) -> Layout:
    """
    Binance info Layout.

    :param bin_status: current binance status.
    :param profit_today: today's calculated profit.
    :param profit_yesterday: yesterday's calcualted profit.
    :return: binance renderable layout.
    """
    layout = Layout(name="binance_status")
    layout.split_row(
        Layout(
            _get_binance_status(
                bin_status,
            ),
        ),
        Layout(
            _get_profit_table(bin_status, profit_today, profit_yesterday),
            ratio=2,
        ),
    )
    return layout
def make_layout():
    log_table = Table()
    log_table.add_column("")
    layout = Layout(name="root")

    layout.split_row(
        Layout(name="log", ratio=2),
        Layout(name="tree"),
    )
    layout["tree"].update(generate_tree_from_schema({}))
    layout["log"].update(generate_log_table([]))
    return layout
Ejemplo n.º 7
0
def test_refresh_screen():
    layout = Layout()
    layout.split_row(Layout(name="foo"), Layout(name="bar"))
    console = Console(force_terminal=True, width=20, height=5)
    console.print(layout)
    with console.screen():
        with console.capture() as capture:
            layout.refresh_screen(console, "foo")
    result = capture.get()
    print(repr(result))
    expected = "\x1b[1;1H\x1b[34m╭─\x1b[0m\x1b[34m \x1b[0m\x1b[32m'foo'\x1b[0m\x1b[34m─╮\x1b[0m\x1b[2;1H\x1b[34m│\x1b[0m Layout \x1b[34m│\x1b[0m\x1b[3;1H\x1b[34m│\x1b[0m \x1b[1m(\x1b[0m      \x1b[34m│\x1b[0m\x1b[4;1H\x1b[34m│\x1b[0m     \x1b[33mna\x1b[0m \x1b[34m│\x1b[0m\x1b[5;1H\x1b[34m╰────────╯\x1b[0m"
    assert result == expected
Ejemplo n.º 8
0
def _get_nb_layout(nb_status: NBMinerStatus) -> Layout:
    """
    Get NBMiner layout.

    :param nb_status: current NBMiner status.
    :return: renderable layout.
    """
    layout = Layout(name="miner_status", ratio=2)
    layout.split_row(
        Layout(_get_nb_stratum_table(nb_status)),
        Layout(_get_nb_devices_table(nb_status.miner.devices), ratio=2),
    )
    return layout
Ejemplo n.º 9
0
def create_layout():
    # determining the total number of rows
    total_width = 0
    row_layouts = []
    row_layout = []
    for sub_layout in sub_layouts:
        if total_width + sub_layout.minimum_size >= console.size[0]:
            row_layouts.append(row_layout)
            row_layout = [sub_layout]
            total_width = 0
        else:
            row_layout.append(sub_layout)
            total_width += sub_layout.minimum_size
    row_layouts.append(row_layout)

    to_split_col = []
    for row in row_layouts:
        tmp_layout = Layout()
        tmp_layout.split_row(*row)
        to_split_col.append(tmp_layout)

    layout.split_column(
        *to_split_col
    )
Ejemplo n.º 10
0
                ],
                expand=True,
                column_first=True,
            ),
            title=name,
        )
        for name, y in mail.items()
    ],
    column_first=True,
)

# Partition the screen into manageable chunks
layout = Layout()
layout.split_column(
    Layout(Padding(""), name="padding", size=1),
    Layout(Rule(platform.node()), name="title", size=1),
    Layout(name="content"),
)
timed_layout = Layout()
timed_layout.split_row(
    Layout(Panel(events, title="Calendar"), name="calendar"),
    Layout(Panel(mails, title="Emails"), name="email"),
)
layout["content"].split_row(
    Layout(Panel(fetch), name="fetch"),
    Layout(Panel(timed_layout, title=str(datetime.date.today())), name="timed", ratio=4),
)

# Do it
console.print(layout)
Ejemplo n.º 11
0
class TUI:
    def __init__(self, node_id, resources_by_endpoint) -> None:
        self.node_id = node_id
        self.resources_by_endpoint = resources_by_endpoint
        self.start_time = datetime.datetime.now()

        self.layout = Layout(name="root")
        self.layout.split(
            Layout(name="header", size=6),
            Layout(name="gpu", size=15),
            Layout(name="cpu", size=15),
            Layout(name="endpoints", size=19),
            Layout(name="console", ratio=1),
        )

        self.layout["header"].split_row(
            Layout(name="logo", size=70),
            Layout(name="info", ratio=1),
        )

        self.gpu_layout = Layout(name="gpu")
        self.gpu_layout.split_row(
            Layout(name="utilization", ratio=1),
            Layout(name="memory", ratio=1),
        )

        self.cpu_layout = Layout(name="cpu")
        self.cpu_layout.split_row(
            Layout(name="utilization", ratio=1),
            Layout(name="memory", ratio=1),
        )

        self.endpoints_layout = Layout(name="cpu")
        self.endpoints_layout.split_row(
            Layout(name="data", ratio=1),
            Layout(name="graph", ratio=1),
        )

        py3nvml.nvmlInit()

        self.gpu_mem_usage = [
            collections.deque(maxlen=150),
            collections.deque(maxlen=150),
        ]
        self.gpu_usage = [
            collections.deque(maxlen=150),
            collections.deque(maxlen=150)
        ]
        self.cpu_usage = [collections.deque(maxlen=150)]
        self.ram_usage = [collections.deque(maxlen=150)]

        self.layout["header"]["logo"].update(
            Text(figlet_format("PurpleSmart", font="slant"), style="magenta"))

        width, _ = shutil.get_terminal_size()
        self.console = Console(
            file=io.StringIO(),
            force_terminal=True,
            color_system="truecolor",
            width=width - 4,
        )
        logging.basicConfig(
            level="INFO",
            format="%(message)s",
            datefmt="[%X]",
            handlers=[RichHandler(rich_tracebacks=True, console=self.console)],
        )

        self.tail = LogTail(self.console)

        self.gpu_usage_graph = AsciiGraph(self.gpu_usage, 100)
        max_mem = []
        for i in range(py3nvml.nvmlDeviceGetCount()):
            handle = py3nvml.nvmlDeviceGetHandleByIndex(i)
            meminfo = py3nvml.nvmlDeviceGetMemoryInfo(handle)
            max_mem.append(meminfo.total)
        max_mem = int(round(max(max_mem) / 1024**2))
        self.gpu_mem_usage_graph = AsciiGraph(self.gpu_mem_usage, max_mem)

        self.cpu_usage_graph = AsciiGraph(self.cpu_usage, 100)
        self.ram_usage_graph = AsciiGraph(
            self.ram_usage,
            int(round(psutil.virtual_memory().total / 1024**2)))

        self.endpoints_past_values = {}
        self.stop_flag = False

    def live(self, callback):
        try:
            with Live(
                    self.layout,
                    refresh_per_second=2,
                    screen=False,
                    redirect_stderr=False,
                    redirect_stdout=False,
            ) as live:
                while True:
                    if self.stop_flag:
                        break

                    if callback:
                        callback(self)

                    if not self.resources_by_endpoint:
                        self.layout["endpoints"].update(
                            Panel(
                                Align.center(
                                    Text(
                                        "Waiting for endpoints to come alive"),
                                    vertical="middle",
                                )))
                    else:
                        self.endpoints_layout["data"].update(
                            EndpointMonitor(self.resources_by_endpoint))

                        self.endpoints_values = []
                        updated_keys = set()
                        max_value = 0
                        for (
                                endpoint_name,
                                endpoint_data,
                        ) in self.resources_by_endpoint.items():
                            updated_keys.add(endpoint_name)  # todo: finish

                            total_used = 0
                            total_max = 0
                            for entry in endpoint_data.values():
                                total_used += entry.used
                                total_max += entry.available

                            max_value = max(max_value, total_max)

                            # self.endpoints_values.append(data)
                            past_entries = self.endpoints_past_values.setdefault(
                                endpoint_name, [])
                            past_entries.append(total_used)

                            self.endpoints_values.append(past_entries)

                        self.endpoints_graph = AsciiGraph(
                            self.endpoints_values, max_value, BACKEND_COLORS)
                        self.endpoints_layout["graph"].update(
                            self.endpoints_graph)

                        self.layout["endpoints"].update(
                            Panel(self.endpoints_layout, title="Endpoints"))

                    uptime = datetime.datetime.now() - self.start_time
                    self.layout["header"]["info"].update(
                        Align.right(
                            Text(f"""Node ID: {self.node_id}
                                Uptime: {humanize.naturaldelta(uptime)}
                                https://discord.gg/94KqBcE"""),
                            vertical="middle",
                        ))

                    titles = []

                    table = Table.grid()
                    table.add_column(style="green")
                    table.add_column(no_wrap=True)

                    self.cpu_usage[0].append(psutil.cpu_percent(interval=None))
                    self.ram_usage[0].append(
                        int(round(psutil.virtual_memory().used / 1024**2)))

                    total_gpus_actual = py3nvml.nvmlDeviceGetCount()
                    for i in range(total_gpus_actual):
                        handle = py3nvml.nvmlDeviceGetHandleByIndex(i)
                        meminfo = py3nvml.nvmlDeviceGetMemoryInfo(handle)
                        utilization_info = py3nvml.nvmlDeviceGetUtilizationRates(
                            handle)

                        table.add_row(
                            py3nvml.nvmlDeviceGetName(handle),
                            str(round(meminfo.used / 1024**2)),
                        )
                        self.gpu_mem_usage[i].append(
                            round(meminfo.used / 1024**2))
                        self.gpu_usage[i].append(utilization_info.gpu)

                        color = RICH_COLORS[i]
                        titles.append(
                            f"[{color}]" + py3nvml.nvmlDeviceGetName(handle) +
                            f" {utilization_info.gpu}%, {humanize.naturalsize(meminfo.used)}/{humanize.naturalsize(meminfo.total)}"
                            + "[/]")

                    self.gpu_layout["utilization"].update(
                        self.gpu_usage_graph, )
                    self.gpu_layout["memory"].update(self.gpu_mem_usage_graph)

                    self.layout["gpu"].update(
                        Panel(self.gpu_layout, title=" ".join(titles)))

                    self.cpu_layout["utilization"].update(
                        Panel(self.cpu_usage_graph))
                    self.cpu_layout["memory"].update(
                        Panel(self.ram_usage_graph))

                    self.cpu_layout["utilization"].update(
                        self.cpu_usage_graph, )
                    self.cpu_layout["memory"].update(self.ram_usage_graph)

                    self.layout["cpu"].update(
                        Panel(self.cpu_layout, title=CPU_NAME))

                    self.layout["console"].update(self.tail)

                    sleep(1.0)
        except KeyboardInterrupt as e:
            py3nvml.nvmlShutdown()
            raise e

    def stop(self) -> None:
        self.stop_flag = True