gradio_somarkdown

Python library for easily interacting with trained machine learning models

SoMarkDown Component Demo

General

SMILES

KaTeX

Installation

pip install gradio_somarkdown

Usage

import gradio as gr
from gradio_somarkdown import SoMarkDown

# Example content from https://github.com/SoMarkAI/SoMarkDown/blob/main/example/example_data.js
EXAMPLE_MARKDOWN = r"""
# SoMarkDown Demo

## Image with description (For AI understaning display)
: **Figure 1:** The Stormtroopocat.

![The Stormtroopocat is sitting in the pic.](https://octodex.github.com/images/stormtroopocat.jpg)

## Tables

: **Table 1:** This is a table example in HTML syntax, only HTML format support spanning cells.

<table>
  <tr>
    <td colspan="4">
      **๐Ÿš€ SoMarkDown Overview**

      Compatible with CommonMark, supporting components such as mathematics, chemistry, and code highlighting.
    </td>
  </tr>
  <tr>
    <td>
      **๐Ÿ“ฆ Installation**

      `npm install somarkdown`
    </td>
    <td>
      **๐Ÿ“ Display Formula**

      %%%LATEX_BLOCK_0%%%
    </td>
    <td>
      **๐Ÿงช SMILES Aspirin**

      %%%LATEX_BLOCK_1%%%
    </td>
    <td>
      **โœจ Features**

      Paragraph mapping, high-speed rendering, multiple themes.
    </td>
  </tr>
  <tr>
    <td rowspan="2">
      **๐Ÿ–ผ๏ธ Image Example**

      ![A random example image](https://picsum.photos/250/250?random=1)
    </td>
    <td>
      **๐Ÿ”ข Inline Formula**

      Supports $ \KaTeX $ and chemical extensions.
    </td>
    <td>
      **๐ŸŽจ Code Highlighting**

      ```javascript
      const smd = new SoMarkDown();
      const html = smd.render(markdown)
      ```
    </td>
    <td>
      **๐Ÿท๏ธ Caption Support**

      Caption support for image and table components.
    </td>
  </tr>
  <tr>
    <td>
      **โšก Build Command**

      `npm run build`
    </td>
    <td>
      **๐Ÿ“š Goal**

      SoMarkDown is also the output target protocol for the document intelligence parsing product [SoMark](https://somark.ai/).
    </td>
    <td>
      **๐Ÿงฉ Image Understanding**

      Supports the display of image understanding results.
    </td>
  </tr>
</table>

: **Table 2:** This is a table example in markdown syntax.

| Option | Description |
| ------ | ----------- |
| data   | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext    | extension to be used for dest files. |

## Math
%%%LATEX_BLOCK_2%%%

Inline: $e^{i\pi} + 1 = 0$

## Chemical Structure
%%%LATEX_BLOCK_3%%%

SMILES syntax has been integrated into mathematical expressions, allowing them to be easily combined.

%%%LATEX_BLOCK_4%%%

## Chemistry (mhchem)
%%%LATEX_BLOCK_5%%%

## Code
Inline `code`

Indented code

    // Some comments
    line 1 of code
    line 2 of code
    line 3 of code

Block code "fences"

Sample text here...


Syntax highlighting

``` js
var foo = function (bar) {
  return bar++;
};

console.log(foo(5));

Blockquotes

Blockquotes can also be nested...

...by using additional greater-than signs right next to each other...

...or with spaces between arrows.

Lists

Unordered

  • Create a list by starting a line with +, -, or *
  • Sub-lists are made by indenting 2 spaces:
    • Marker character change forces new list start:
      • Ac tristique libero volutpat at
      • Facilisis in pretium nisl aliquet
      • Nulla volutpat aliquam velit
  • Very easy!

Ordered

  1. Lorem ipsum dolor sit amet

  2. Consectetur adipiscing elit

  3. Integer molestie lorem at massa

  4. You can use sequential numbers...

  5. ...or keep all the numbers as 1.

Start numbering with offset:

  1. foo
  2. bar

h1 Heading

h2 Heading

h3 Heading

h4 Heading

h5 Heading
h6 Heading

Horizontal Rules




Typographic replacements

Enable typographer option to see result.

(c) (C) (r) (R) (tm) (TM) (p) (P) +-

test.. test... test..... test?..... test!....

!!!!!! ???? ,, -- ---

"Smartypants, double quotes" and 'single quotes'

Emphasis

This is bold text

This is bold text

This is italic text

This is italic text

Strikethrough """.strip()

def render(text, linkify, typographer, img_desc_enabled, smiles_disable_colors, smiles_width, smiles_height, katex_throw_on_error): return SoMarkDown( value=text, linkify=linkify, typographer=typographer, img_desc_enabled=img_desc_enabled, smiles={ "disableColors": smiles_disable_colors, "width": int(smiles_width), "height": int(smiles_height), }, katex={"throwOnError": katex_throw_on_error}, )

CSS = """ /* Fancy gradient divider on the left of the output panel */ #output-col { position: relative; padding-left: 28px !important; } #output-col::before { content: ''; position: absolute; left: 10px; top: 4%; bottom: 4%; width: 2px; border-radius: 2px; background: linear-gradient( to bottom, transparent 0%, #EF871B 20%, #EF871B 80%, transparent 100% ); box-shadow: 0 0 8px rgba(239, 135, 27, 0.45); } """

with gr.Blocks(css=CSS) as demo: gr.Markdown("# SoMarkDown Component Demo")

with gr.Row():
    # โ”€โ”€ Left column: input + controls โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    with gr.Column(scale=1):
        input_text = gr.Textbox(
            value=EXAMPLE_MARKDOWN,
            lines=12,
            max_lines=40,
            label="Markdown",
            show_label=False,
        )

        gr.Markdown("**General**")
        with gr.Row():
            linkify = gr.Checkbox(label="linkify", value=True)
            typographer = gr.Checkbox(label="typographer", value=True)
            img_desc_enabled = gr.Checkbox(label="img_desc_enabled", value=True)

        gr.Markdown("**SMILES**")
        with gr.Row():
            smiles_disable_colors = gr.Checkbox(label="disableColors", value=False)
            smiles_width = gr.Number(label="width", value=150, minimum=50, maximum=600, step=10)
            smiles_height = gr.Number(label="height", value=150, minimum=50, maximum=600, step=10)

        gr.Markdown("**KaTeX**")
        with gr.Row():
            katex_throw_on_error = gr.Checkbox(label="throwOnError", value=False)

        render_btn = gr.Button("Render", variant="primary")

    # โ”€โ”€ Right column: rendered output โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    with gr.Column(scale=1, elem_id="output-col"):
        somarkdown_output = SoMarkDown(
            value=EXAMPLE_MARKDOWN,
            img_desc_enabled=True,
        )

inputs = [
    input_text,
    linkify,
    typographer,
    img_desc_enabled,
    smiles_disable_colors,
    smiles_width,
    smiles_height,
    katex_throw_on_error,
]

render_btn.click(fn=render, inputs=inputs, outputs=somarkdown_output)
input_text.change(fn=render, inputs=inputs, outputs=somarkdown_output)

if name == "main": demo.launch()


SoMarkDown

Initialization

Parameters
value: str | I18nData | Callable | None
default = None

Value to show in SoMarkDown component. If a function is provided, the function will be called each time the app loads to set the initial value of this component.

linkify: bool
default = True

If True, automatically converts URL-like text to links.

typographer: bool
default = True

If True, enables language-neutral replacements and quotes beautification.

katex: dict | None
default = None

Configuration dict for KaTeX options (e.g. ``{"throwOnError": False}``).

smiles: dict | None
default = None

Configuration dict for SMILES (chemical structure) rendering options.

img_desc_enabled: bool
default = True

If True, displays image descriptions below images.

label: str | I18nData | None
default = None

This parameter has no effect.

every: Timer | float | None
default = None

Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.

inputs: Component | Sequence[Component] | set[Component] | None
default = None

Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.

show_label: bool | None
default = None

This parameter has no effect.

rtl: bool
default = False

If True, sets the direction of the rendered text to right-to-left. Default is False, which renders text left-to-right.

visible: bool | Literal["hidden"]
default = True

If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM.

elem_id: str | None
default = None

An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.

elem_classes: list[str] | str | None
default = None

An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.

render: bool
default = True

If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.

key: int | str | tuple[int | str, ...] | None
default = None

in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render.

preserved_by_key: list[str] | str | None
default = "value"

A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.

height: int | str | None
default = None

The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If markdown content exceeds the height, the component will scroll.

max_height: int | str | None
default = None

The maximum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If markdown content exceeds the height, the component will scroll. If markdown content is shorter than the height, the component will shrink to fit the content. Will not have any effect if `height` is set and is smaller than `max_height`.

min_height: int | str | None
default = None

The minimum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If markdown content exceeds the height, the component will expand to fit the content. Will not have any effect if `height` is set and is larger than `min_height`.

container: bool
default = False

If True, the SoMarkDown component will be displayed in a container. Default is False.

padding: bool
default = False

If True, the SoMarkDown component will have a certain padding (set by the `--block-padding` CSS variable) in all directions. Default is False.

sanitize_html: bool
default = True
header_links: bool
default = False
line_breaks: bool
default = False
buttons: list[Literal["copy"]] | None
default = None
latex_delimiters: list[dict[str, str | bool]] | None
default = None

Events

Parameters
change

Triggered when the value of the SoMarkDown changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.

copy

This listener is triggered when the user copies content from the SoMarkDown. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event data

User function

The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).

  • When used as an Input, the component only impacts the input signature of the user function.
  • When used as an output, the component only impacts the return signature of the user function.

The code snippet below is accurate in cases where the component is used as both an input and an output.

  • As input: Is passed, passes the str of SoMarkDown corresponding to the displayed value.
  • As output: Should return, expects a valid str that can be rendered as SoMarkDown.
def predict(
   value: str | None
) -> str | gradio.i18n.I18nData | None:
   return value