Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
__main__.py246 linesDownload Raw Back to rich
1import colorsys2import io3from time import process_time4 5from rich import box6from rich.color import Color7from rich.console import Console, ConsoleOptions, Group, RenderableType, RenderResult8from rich.markdown import Markdown9from rich.measure import Measurement10from rich.pretty import Pretty11from rich.segment import Segment12from rich.style import Style13from rich.syntax import Syntax14from rich.table import Table15from rich.text import Text16 17 18class ColorBox:19    def __rich_console__(20        self, console: Console, options: ConsoleOptions21    ) -> RenderResult:22        for y in range(0, 5):23            for x in range(options.max_width):24                h = x / options.max_width25                l = 0.1 + ((y / 5) * 0.7)26                r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)27                r2, g2, b2 = colorsys.hls_to_rgb(h, l + 0.7 / 10, 1.0)28                bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)29                color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)30                yield Segment("▄", Style(color=color, bgcolor=bgcolor))31            yield Segment.line()32 33    def __rich_measure__(34        self, console: "Console", options: ConsoleOptions35    ) -> Measurement:36        return Measurement(1, options.max_width)37 38 39def make_test_card() -> Table:40    """Get a renderable that demonstrates a number of features."""41    table = Table.grid(padding=1, pad_edge=True)42    table.title = "Rich features"43    table.add_column("Feature", no_wrap=True, justify="center", style="bold red")44    table.add_column("Demonstration")45 46    color_table = Table(47        box=None,48        expand=False,49        show_header=False,50        show_edge=False,51        pad_edge=False,52    )53    color_table.add_row(54        (55            "✓ [bold green]4-bit color[/]\n"56            "✓ [bold blue]8-bit color[/]\n"57            "✓ [bold magenta]Truecolor (16.7 million)[/]\n"58            "✓ [bold yellow]Dumb terminals[/]\n"59            "✓ [bold cyan]Automatic color conversion"60        ),61        ColorBox(),62    )63 64    table.add_row("Colors", color_table)65 66    table.add_row(67        "Styles",68        "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].",69    )70 71    lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus."72    lorem_table = Table.grid(padding=1, collapse_padding=True)73    lorem_table.pad_edge = False74    lorem_table.add_row(75        Text(lorem, justify="left", style="green"),76        Text(lorem, justify="center", style="yellow"),77        Text(lorem, justify="right", style="blue"),78        Text(lorem, justify="full", style="red"),79    )80    table.add_row(81        "Text",82        Group(83            Text.from_markup(84                """Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\n"""85            ),86            lorem_table,87        ),88    )89 90    def comparison(renderable1: RenderableType, renderable2: RenderableType) -> Table:91        table = Table(show_header=False, pad_edge=False, box=None, expand=True)92        table.add_column("1", ratio=1)93        table.add_column("2", ratio=1)94        table.add_row(renderable1, renderable2)95        return table96 97    table.add_row(98        "Asian\nlanguage\nsupport",99        ":flag_for_china:  该库支持中文,日文和韩文文本!\n:flag_for_japan:  ライブラリは中国語、日本語、韓国語のテキストをサポートしています\n:flag_for_south_korea:  이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다",100    )101 102    markup_example = (103        "[bold magenta]Rich[/] supports a simple [i]bbcode[/i]-like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! "104        ":+1: :apple: :ant: :bear: :baguette_bread: :bus: "105    )106    table.add_row("Markup", markup_example)107 108    example_table = Table(109        show_edge=False,110        show_header=True,111        expand=False,112        row_styles=["none", "dim"],113        box=box.SIMPLE,114    )115    example_table.add_column("[green]Date", style="green", no_wrap=True)116    example_table.add_column("[blue]Title", style="blue")117    example_table.add_column(118        "[cyan]Production Budget",119        style="cyan",120        justify="right",121        no_wrap=True,122    )123    example_table.add_column(124        "[magenta]Box Office",125        style="magenta",126        justify="right",127        no_wrap=True,128    )129    example_table.add_row(130        "Dec 20, 2019",131        "Star Wars: The Rise of Skywalker",132        "$275,000,000",133        "$375,126,118",134    )135    example_table.add_row(136        "May 25, 2018",137        "[b]Solo[/]: A Star Wars Story",138        "$275,000,000",139        "$393,151,347",140    )141    example_table.add_row(142        "Dec 15, 2017",143        "Star Wars Ep. VIII: The Last Jedi",144        "$262,000,000",145        "[bold]$1,332,539,889[/bold]",146    )147    example_table.add_row(148        "May 19, 1999",149        "Star Wars Ep. [b]I[/b]: [i]The phantom Menace",150        "$115,000,000",151        "$1,027,044,677",152    )153 154    table.add_row("Tables", example_table)155 156    code = '''\157def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:158    """Iterate and generate a tuple with a flag for last value."""159    iter_values = iter(values)160    try:161        previous_value = next(iter_values)162    except StopIteration:163        return164    for value in iter_values:165        yield False, previous_value166        previous_value = value167    yield True, previous_value'''168 169    pretty_data = {170        "foo": [171            3.1427,172            (173                "Paul Atreides",174                "Vladimir Harkonnen",175                "Thufir Hawat",176            ),177        ],178        "atomic": (False, True, None),179    }180    table.add_row(181        "Syntax\nhighlighting\n&\npretty\nprinting",182        comparison(183            Syntax(code, "python3", line_numbers=True, indent_guides=True),184            Pretty(pretty_data, indent_guides=True),185        ),186    )187 188    markdown_example = """\189# Markdown190 191Supports much of the *markdown* __syntax__!192 193- Headers194- Basic formatting: **bold**, *italic*, `code`195- Block quotes196- Lists, and more...197    """198    table.add_row(199        "Markdown", comparison("[cyan]" + markdown_example, Markdown(markdown_example))200    )201 202    table.add_row(203        "+more!",204        """Progress bars, columns, styled logging handler, tracebacks, etc...""",205    )206    return table207 208 209if __name__ == "__main__":  # pragma: no cover210    from rich.panel import Panel211 212    console = Console(213        file=io.StringIO(),214        force_terminal=True,215    )216    test_card = make_test_card()217 218    # Print once to warm cache219    start = process_time()220    console.print(test_card)221    pre_cache_taken = round((process_time() - start) * 1000.0, 1)222 223    console.file = io.StringIO()224 225    start = process_time()226    console.print(test_card)227    taken = round((process_time() - start) * 1000.0, 1)228 229    c = Console(record=True)230    c.print(test_card)231 232    console = Console()233    console.print(f"[dim]rendered in [not dim]{pre_cache_taken}ms[/] (cold cache)")234    console.print(f"[dim]rendered in [not dim]{taken}ms[/] (warm cache)")235    console.print()236    console.print(237        Panel(238            "[b magenta]Hope you enjoy using Rich![/]\n\n"239            "Consider sponsoring to ensure this project is maintained.\n\n"240            "[cyan]https://github.com/sponsors/willmcgugan[/cyan]",241            border_style="green",242            title="Help ensure Rich is maintained",243            padding=(1, 2),244        )245    )246 
codekingpro/portable-devtools · Team Ai