transformers-js-py


Nametransformers-js-py JSON
Version 0.10.0 PyPI version JSON
download
home_pagehttps://github.com/whitphx/transformers.js.py
Summary
upload_time2024-02-26 14:20:27
maintainer
docs_urlNone
authorYuichiro Tachibana (Tsuchiya)
requires_python>=3.10,<4.0
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Transformers.js.py 🤗

[![Test, Build, and Publish](https://github.com/whitphx/transformers.js.py/actions/workflows/main.yml/badge.svg)](https://github.com/whitphx/transformers.js.py/actions/workflows/main.yml)
[![PyPI](https://img.shields.io/pypi/v/transformers-js-py)](https://pypi.org/project/transformers-js-py/)

**Use [Transformers.js](https://huggingface.co/docs/transformers.js/index) on [Pyodide](https://pyodide.org/en/stable/) and Pyodide-based frameworks such as [JupyterLite](https://jupyterlite.readthedocs.io/en/latest/), [stlite (Streamlit)](https://github.com/whitphx/stlite), [Shinylive (Shiny for Python)](https://shiny.posit.co/py/docs/shinylive.html), [PyScript](https://pyscript.net/), [HoloViz Panel](https://panel.holoviz.org), and so on.**

The original [Transformers](https://huggingface.co/docs/transformers/index) can't be used in a browser environment. [Transformers.js](https://huggingface.co/docs/transformers.js/index) is a JavaScript version of Transformers that can be installed on browsers, but we can't use it from Pyodide.
This package is **a thin wrapper of Transformers.js to proxy its API to Pyodide**.

## API

The API is more like Transformers.js than the original Transformers.

<table>
<tr>
<th width="50%" align="center"><b>Transformers.js</b></th>
<th width="50%" align="center"><b>Transformers.js.py</b></th>
</tr>
<tr>
<td>

```javascript
import { pipeline } from '@xenova/transformers';

// Allocate a pipeline for sentiment-analysis
let pipe = await pipeline('sentiment-analysis');

let out = await pipe('I love transformers!');
// [{'label': 'POSITIVE', 'score': 0.999817686}]
```

</td>
<td>

```python
from transformers_js_py import import_transformers_js

transformers = await import_transformers_js()
pipeline = transformers.pipeline

# Allocate a pipeline for sentiment-analysis
pipe = await pipeline('sentiment-analysis')

out = await pipe('I love transformers!')
# [{'label': 'POSITIVE', 'score': 0.999817686}]
```

</td>
</tr>
</table>

See the [Transformers.js document](https://github.com/xenova/transformers.js/) for available features.

### Special Case: `as_url()`
Certain methods of Transformers.js accept a URL as an input. However, when using Transformers.js.py on Pyodide, there may be instances where we want to pass a local file path from the virtual file system, rather than a URL. In such scenarios, the `as_url()` function can be used to convert a local file path into a URL.

```python
# Example
from transformers_js import import_transformers_js, as_url

transformers = await import_transformers_js()
pipeline = transformers.pipeline
pipe = await pipeline('image-classification')

local_image_path = "/path/to/image.jpg"

input_url = as_url(local_image_path)  # Converts a local file path into a URL that can be passed to `pipe()`
result = await pipe(input_url)
```

## Examples

### JupyterLite

![JupyterLite screenshot](./docs/images/JupyterLite.png)

👉Try this code snippet on https://jupyter.org/try-jupyter/lab/index.html

```python
%pip install transformers_js_py

from transformers_js_py import import_transformers_js

transformers = await import_transformers_js()
pipeline = transformers.pipeline

pipe = await pipeline('sentiment-analysis')

out = await pipe('I love transformers!')

print(out)
```

### stlite (Serverless Streamlit)

[![stlite sharing screenshot](./docs/images/stlite_sharing.png)](https://edit.share.stlite.net/#!ChBzdHJlYW1saXRfYXBwLnB5EpMEChBzdHJlYW1saXRfYXBwLnB5Ev4DCvsDaW1wb3J0IHN0cmVhbWxpdCBhcyBzdAoKZnJvbSB0cmFuc2Zvcm1lcnNfanMgaW1wb3J0IGltcG9ydF90cmFuc2Zvcm1lcnNfanMKCnN0LnRpdGxlKCJTZW50aW1lbnQgYW5hbHlzaXMiKQoKdGV4dCA9IHN0LnRleHRfaW5wdXQoIklucHV0IHNvbWUgdGV4dCIsICJJIGxvdmUgdHJhbnNmb3JtZXJzISIpCgppZiB0ZXh0OgogICAgd2l0aCBzdC5zcGlubmVyKCk6CiAgICAgICAgdHJhbnNmb3JtZXJzID0gYXdhaXQgaW1wb3J0X3RyYW5zZm9ybWVyc19qcygpCiAgICAgICAgcGlwZWxpbmUgPSB0cmFuc2Zvcm1lcnMucGlwZWxpbmUKICAgICAgICBpZiAicGlwZSIgbm90IGluIHN0LnNlc3Npb25fc3RhdGU6CiAgICAgICAgICAgIHN0LnNlc3Npb25fc3RhdGVbInBpcGUiXSA9IGF3YWl0IHBpcGVsaW5lKCdzZW50aW1lbnQtYW5hbHlzaXMnKQogICAgICAgIHBpcGUgPSBzdC5zZXNzaW9uX3N0YXRlWyJwaXBlIl0KICAgICAgICBvdXQgPSBhd2FpdCBwaXBlKHRleHQpCiAgICBzdC53cml0ZShvdXQpGhJ0cmFuc2Zvcm1lcnNfanNfcHk,)

[👉 Online Demo](https://edit.share.stlite.net/#!ChBzdHJlYW1saXRfYXBwLnB5EpMEChBzdHJlYW1saXRfYXBwLnB5Ev4DCvsDaW1wb3J0IHN0cmVhbWxpdCBhcyBzdAoKZnJvbSB0cmFuc2Zvcm1lcnNfanMgaW1wb3J0IGltcG9ydF90cmFuc2Zvcm1lcnNfanMKCnN0LnRpdGxlKCJTZW50aW1lbnQgYW5hbHlzaXMiKQoKdGV4dCA9IHN0LnRleHRfaW5wdXQoIklucHV0IHNvbWUgdGV4dCIsICJJIGxvdmUgdHJhbnNmb3JtZXJzISIpCgppZiB0ZXh0OgogICAgd2l0aCBzdC5zcGlubmVyKCk6CiAgICAgICAgdHJhbnNmb3JtZXJzID0gYXdhaXQgaW1wb3J0X3RyYW5zZm9ybWVyc19qcygpCiAgICAgICAgcGlwZWxpbmUgPSB0cmFuc2Zvcm1lcnMucGlwZWxpbmUKICAgICAgICBpZiAicGlwZSIgbm90IGluIHN0LnNlc3Npb25fc3RhdGU6CiAgICAgICAgICAgIHN0LnNlc3Npb25fc3RhdGVbInBpcGUiXSA9IGF3YWl0IHBpcGVsaW5lKCdzZW50aW1lbnQtYW5hbHlzaXMnKQogICAgICAgIHBpcGUgPSBzdC5zZXNzaW9uX3N0YXRlWyJwaXBlIl0KICAgICAgICBvdXQgPSBhd2FpdCBwaXBlKHRleHQpCiAgICBzdC53cml0ZShvdXQpGhJ0cmFuc2Zvcm1lcnNfanNfcHk,) : try out this code online.

```python
import streamlit as st

from transformers_js_py import import_transformers_js

st.title("Sentiment analysis")

text = st.text_input("Input some text", "I love transformers!")

if text:
    with st.spinner():
        transformers = await import_transformers_js()
        pipeline = transformers.pipeline
        if "pipe" not in st.session_state:
            st.session_state["pipe"] = await pipeline('sentiment-analysis')
        pipe = st.session_state["pipe"]
        out = await pipe(text)
    st.write(out)
```

### Gradio-lite

![Gradio-lite screenshot](./docs/images/Gradio-lite.png)

Save the following code as an HTML file and open it in a browser.

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.css" />
  <title>Transformers.js with Gradio-lite</title>
  <style>
    html, body {
      margin: 0;
      padding: 0;
      height: 100%;
      width: 100%;
    }
    gradio-lite {
      height: 100%;
      width: 100%;
    }
  </style>
</head>
<body>
<gradio-lite>

<gradio-requirements>
transformers_js_py
</gradio-requirements>

<gradio-file name="app.py" entrypoint>
import gradio as gr
from transformers_js_py import import_transformers_js

transformers = await import_transformers_js()
pipeline = transformers.pipeline

pipe = await pipeline('sentiment-analysis')

async def process(text):
    return await pipe(text)

demo = gr.Interface(fn=process, inputs="text", outputs="json")

demo.launch()
</gradio-file>

</gradio-lite>
</body>
</html>
```

[👉 Online demo](https://huggingface.co/spaces/abidlabs/gradio-lite-classify)

For more details about Gradio-lite, please read [Gradio-Lite: Serverless Gradio Running Entirely in Your Browser (huggingface.co)](https://huggingface.co/blog/gradio-lite).

### Shinylive

[![Shinylive screenshot](./docs/images/Shinylive.png)](https://shinylive.io/py/editor/#code=NobwRAdghgtgpmAXGKAHVA6VBPMAaMAYwHsIAXOcpMAMwCdiYACAZwAsBLCbJjmVYnTJMAgujxM6lACZw6EgK4cAOhHqMmZOlAgsag+HRYB9AFYte-QcL4ChxrTr0G5J86tVpUxpUwC8TEpYUADmcMY0ADZK0gAUqkyJgRwYXKgKZA5wAB5k8WAUucr4TMUAKjk2EOlkxRKokVCEcGzEkbJ0fsUAouRympXFAJR4CUlBxBk1WbnGAG5yAEZQZHz5ZEVgI6pDHhCqsjSscgt0sWkZEpNkNRIscCwsHKRDiGOJAALXNe9MH1IQDoYQq1CBJJhQFjYCCEJiHTS5WKvX7gjhHCDEKo1YGVJFvMHgwmJKRkBR0MHFSn7AlExy6fR0QwWAJQADuUA4Nis9jpzkZrjMLCRKKSqA4qDgkS4cH8mm09JcRiw4sl0r2RMSYolsrZHOEWtVEDg+Xu5D4lDIAFodFBItgnixhuqNdcdezOUwDedqhkcYihrtqRrJHBSeTWFpYtdA3svLKxKhYl4fBw7ic5BJZIsFCE-GU6Ao4IGwABfPDgaDwahSACOSik8HILGBuXwRFIFCoyF5DKZlvMlpwpYAukA)

[👉 Online demo](https://shinylive.io/py/editor/#code=NobwRAdghgtgpmAXGKAHVA6VBPMAaMAYwHsIAXOcpMAMwCdiYACAZwAsBLCbJjmVYnTJMAgujxM6lACZw6EgK4cAOhHqMmZOlAgsag+HRYB9AFYte-QcL4ChxrTr0G5J86tVpUxpUwC8TEpYUADmcMY0ADZK0gAUqkyJgRwYXKgKZA5wAB5k8WAUucr4TMUAKjk2EOlkxRKokVCEcGzEkbJ0fsUAouRympXFAJR4CUlBxBk1WbnGAG5yAEZQZHz5ZEVgI6pDHhCqsjSscgt0sWkZEpNkNRIscCwsHKRDiGOJAALXNe9MH1IQDoYQq1CBJJhQFjYCCEJiHTS5WKvX7gjhHCDEKo1YGVJFvMHgwmJKRkBR0MHFSn7AlExy6fR0QwWAJQADuUA4Nis9jpzkZrjMLCRKKSqA4qDgkS4cH8mm09JcRiw4sl0r2RMSYolsrZHOEWtVEDg+Xu5D4lDIAFodFBItgnixhuqNdcdezOUwDedqhkcYihrtqRrJHBSeTWFpYtdA3svLKxKhYl4fBw7ic5BJZIsFCE-GU6Ao4IGwABfPDgaDwahSACOSik8HILGBuXwRFIFCoyF5DKZlvMlpwpYAukA) : try out this code online.

```python
from shiny import App, render, ui
from transformers_js_py import import_transformers_js

app_ui = ui.page_fluid(
    ui.input_text("text", "Text input", placeholder="Enter text"),
    ui.output_text_verbatim("txt"),
)


def server(input, output, session):
    @output
    @render.text
    async def txt():
        if not input.text():
            return ""

        transformers = await import_transformers_js()
        pipeline = transformers.pipeline

        pipe = await pipeline('sentiment-analysis')

        out = await pipe(input.text())

        return str(out)


app = App(app_ui, server, debug=True)
```

### PyScript

![PyScript screenshot](./docs/images/PyScript.png)

👉Try this code snippet on https://pyscript.com/

```html
<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
  </head>
  <body>
    <input type="text" value="" id="text-input" />
    <button py-click="run()" id="run-button">Run</button>

    <py-config>
        packages = ["transformers-js-py"]
    </py-config>
    <py-script>
        import asyncio
        from transformers_js_py import import_transformers_js

        text_input = Element("text-input")

        async def main(input_data):
            transformers = await import_transformers_js()
            pipeline = transformers.pipeline
            pipe = await pipeline('sentiment-analysis')
            out = await pipe(input_data)
            print(out)

        def run():
            print("Start")
            input_data = text_input.value
            if input_data.strip() == "":
                print("No data input.")
                return

            future = asyncio.ensure_future(main(input_data))
    </py-script>
  </body>
</html>

```

### Panel

With [HoloViz Panel](https://panel.holoviz.org) you develop your app on your laptop and convert it to [Pyodide](https://pyodide.org/en/stable/) or [PyScript](https://pyscript.net/) by running [`panel convert`](https://panel.holoviz.org/how_to/wasm/convert.html).

![HoloViz Panel Transformers App](docs/images/Panel.png)

Install the requirements

```bash
pip install panel transformers_js_py
```

Create the **app.py** file in your favorite editor or IDE.

```python
import panel as pn

pn.extension(sizing_mode="stretch_width", design="material")

@pn.cache
async def _get_pipeline(model="sentiment-analysis"):
    from transformers_js_py import import_transformers_js
    transformers = await import_transformers_js()
    return await transformers.pipeline(model)


text_input = pn.widgets.TextInput(placeholder="Send a message", name="Message")
button = pn.widgets.Button(name="Send", icon="send", align="end", button_type="primary")

@pn.depends(text_input, button)
async def _response(text, event):
    if not text:
        return {}
    pipe = await _get_pipeline()
    return await pipe(text)

pn.Column(
    text_input, button, pn.pane.JSON(_response, depth=2)
).servable()
```

Convert the app to [Pyodide](https://pyodide.org/en/stable/). For more options like *hot reload* check out the [Panel Convert](https://panel.holoviz.org/how_to/wasm/convert.html) guide.

```bash
panel convert app.py --to pyodide-worker --out pyodide --requirements transformers_js_py
```

Now serve the app

```bash
python -m http.server -d pyodide
```

Finally you can try out the app by opening [localhost:8000/app.html](http://localhost:8000/app.html)

<details>
    <summary><h4>Panel Chat App Example</h4></summary>

You can also use `transformers_js_py` with [Panels Chat Components](https://panel.holoviz.org/reference/index.html#chat).

![HoloViz Panel Transformers App](docs/images/PanelChat.png)

```python
import panel as pn

MODEL = "sentiment-analysis"
pn.chat.ChatMessage.default_avatars["hugging face"] = "🤗"

pn.extension(design="material")

@pn.cache
async def _get_pipeline(model):
    from transformers_js_py import import_transformers_js
    transformers = await import_transformers_js()
    return await transformers.pipeline(model)

async def callback(contents: str, user: str, instance: pn.chat.ChatInterface):
    pipe = await _get_pipeline(MODEL)
    response = await pipe(contents)
    label, score = response[0]["label"], round(response[0]["score"], 2)
    return f"""I feel a {label} vibe here (score: {score})"""

welcome_message = pn.chat.ChatMessage(
    f"I'm a Hugging Face Transformers `{MODEL}` model.\n\nPlease *send a message*!",
    user="Hugging Face",
)

pn.chat.ChatInterface(
    welcome_message, placeholder_text="Loading the model ...",
    callback=callback, callback_user="Hugging Face",
).servable()
```

For more chat examples see [Panel Chat Examples](https://holoviz-topics.github.io/panel-chat-examples/).
</details>

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/whitphx/transformers.js.py",
    "name": "transformers-js-py",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.10,<4.0",
    "maintainer_email": "",
    "keywords": "",
    "author": "Yuichiro Tachibana (Tsuchiya)",
    "author_email": "t.yic.yt@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/35/d6/294a91623678442abe2bc5555e5f3a2394ef25de81254a41061ecc112b8c/transformers_js_py-0.10.0.tar.gz",
    "platform": null,
    "description": "# Transformers.js.py \ud83e\udd17\n\n[![Test, Build, and Publish](https://github.com/whitphx/transformers.js.py/actions/workflows/main.yml/badge.svg)](https://github.com/whitphx/transformers.js.py/actions/workflows/main.yml)\n[![PyPI](https://img.shields.io/pypi/v/transformers-js-py)](https://pypi.org/project/transformers-js-py/)\n\n**Use [Transformers.js](https://huggingface.co/docs/transformers.js/index) on [Pyodide](https://pyodide.org/en/stable/) and Pyodide-based frameworks such as [JupyterLite](https://jupyterlite.readthedocs.io/en/latest/), [stlite (Streamlit)](https://github.com/whitphx/stlite), [Shinylive (Shiny for Python)](https://shiny.posit.co/py/docs/shinylive.html), [PyScript](https://pyscript.net/), [HoloViz Panel](https://panel.holoviz.org), and so on.**\n\nThe original [Transformers](https://huggingface.co/docs/transformers/index) can't be used in a browser environment. [Transformers.js](https://huggingface.co/docs/transformers.js/index) is a JavaScript version of Transformers that can be installed on browsers, but we can't use it from Pyodide.\nThis package is **a thin wrapper of Transformers.js to proxy its API to Pyodide**.\n\n## API\n\nThe API is more like Transformers.js than the original Transformers.\n\n<table>\n<tr>\n<th width=\"50%\" align=\"center\"><b>Transformers.js</b></th>\n<th width=\"50%\" align=\"center\"><b>Transformers.js.py</b></th>\n</tr>\n<tr>\n<td>\n\n```javascript\nimport { pipeline } from '@xenova/transformers';\n\n// Allocate a pipeline for sentiment-analysis\nlet pipe = await pipeline('sentiment-analysis');\n\nlet out = await pipe('I love transformers!');\n// [{'label': 'POSITIVE', 'score': 0.999817686}]\n```\n\n</td>\n<td>\n\n```python\nfrom transformers_js_py import import_transformers_js\n\ntransformers = await import_transformers_js()\npipeline = transformers.pipeline\n\n# Allocate a pipeline for sentiment-analysis\npipe = await pipeline('sentiment-analysis')\n\nout = await pipe('I love transformers!')\n# [{'label': 'POSITIVE', 'score': 0.999817686}]\n```\n\n</td>\n</tr>\n</table>\n\nSee the [Transformers.js document](https://github.com/xenova/transformers.js/) for available features.\n\n### Special Case: `as_url()`\nCertain methods of Transformers.js accept a URL as an input. However, when using Transformers.js.py on Pyodide, there may be instances where we want to pass a local file path from the virtual file system, rather than a URL. In such scenarios, the `as_url()` function can be used to convert a local file path into a URL.\n\n```python\n# Example\nfrom transformers_js import import_transformers_js, as_url\n\ntransformers = await import_transformers_js()\npipeline = transformers.pipeline\npipe = await pipeline('image-classification')\n\nlocal_image_path = \"/path/to/image.jpg\"\n\ninput_url = as_url(local_image_path)  # Converts a local file path into a URL that can be passed to `pipe()`\nresult = await pipe(input_url)\n```\n\n## Examples\n\n### JupyterLite\n\n![JupyterLite screenshot](./docs/images/JupyterLite.png)\n\n\ud83d\udc49Try this code snippet on https://jupyter.org/try-jupyter/lab/index.html\n\n```python\n%pip install transformers_js_py\n\nfrom transformers_js_py import import_transformers_js\n\ntransformers = await import_transformers_js()\npipeline = transformers.pipeline\n\npipe = await pipeline('sentiment-analysis')\n\nout = await pipe('I love transformers!')\n\nprint(out)\n```\n\n### stlite (Serverless Streamlit)\n\n[![stlite sharing screenshot](./docs/images/stlite_sharing.png)](https://edit.share.stlite.net/#!ChBzdHJlYW1saXRfYXBwLnB5EpMEChBzdHJlYW1saXRfYXBwLnB5Ev4DCvsDaW1wb3J0IHN0cmVhbWxpdCBhcyBzdAoKZnJvbSB0cmFuc2Zvcm1lcnNfanMgaW1wb3J0IGltcG9ydF90cmFuc2Zvcm1lcnNfanMKCnN0LnRpdGxlKCJTZW50aW1lbnQgYW5hbHlzaXMiKQoKdGV4dCA9IHN0LnRleHRfaW5wdXQoIklucHV0IHNvbWUgdGV4dCIsICJJIGxvdmUgdHJhbnNmb3JtZXJzISIpCgppZiB0ZXh0OgogICAgd2l0aCBzdC5zcGlubmVyKCk6CiAgICAgICAgdHJhbnNmb3JtZXJzID0gYXdhaXQgaW1wb3J0X3RyYW5zZm9ybWVyc19qcygpCiAgICAgICAgcGlwZWxpbmUgPSB0cmFuc2Zvcm1lcnMucGlwZWxpbmUKICAgICAgICBpZiAicGlwZSIgbm90IGluIHN0LnNlc3Npb25fc3RhdGU6CiAgICAgICAgICAgIHN0LnNlc3Npb25fc3RhdGVbInBpcGUiXSA9IGF3YWl0IHBpcGVsaW5lKCdzZW50aW1lbnQtYW5hbHlzaXMnKQogICAgICAgIHBpcGUgPSBzdC5zZXNzaW9uX3N0YXRlWyJwaXBlIl0KICAgICAgICBvdXQgPSBhd2FpdCBwaXBlKHRleHQpCiAgICBzdC53cml0ZShvdXQpGhJ0cmFuc2Zvcm1lcnNfanNfcHk,)\n\n[\ud83d\udc49 Online Demo](https://edit.share.stlite.net/#!ChBzdHJlYW1saXRfYXBwLnB5EpMEChBzdHJlYW1saXRfYXBwLnB5Ev4DCvsDaW1wb3J0IHN0cmVhbWxpdCBhcyBzdAoKZnJvbSB0cmFuc2Zvcm1lcnNfanMgaW1wb3J0IGltcG9ydF90cmFuc2Zvcm1lcnNfanMKCnN0LnRpdGxlKCJTZW50aW1lbnQgYW5hbHlzaXMiKQoKdGV4dCA9IHN0LnRleHRfaW5wdXQoIklucHV0IHNvbWUgdGV4dCIsICJJIGxvdmUgdHJhbnNmb3JtZXJzISIpCgppZiB0ZXh0OgogICAgd2l0aCBzdC5zcGlubmVyKCk6CiAgICAgICAgdHJhbnNmb3JtZXJzID0gYXdhaXQgaW1wb3J0X3RyYW5zZm9ybWVyc19qcygpCiAgICAgICAgcGlwZWxpbmUgPSB0cmFuc2Zvcm1lcnMucGlwZWxpbmUKICAgICAgICBpZiAicGlwZSIgbm90IGluIHN0LnNlc3Npb25fc3RhdGU6CiAgICAgICAgICAgIHN0LnNlc3Npb25fc3RhdGVbInBpcGUiXSA9IGF3YWl0IHBpcGVsaW5lKCdzZW50aW1lbnQtYW5hbHlzaXMnKQogICAgICAgIHBpcGUgPSBzdC5zZXNzaW9uX3N0YXRlWyJwaXBlIl0KICAgICAgICBvdXQgPSBhd2FpdCBwaXBlKHRleHQpCiAgICBzdC53cml0ZShvdXQpGhJ0cmFuc2Zvcm1lcnNfanNfcHk,) : try out this code online.\n\n```python\nimport streamlit as st\n\nfrom transformers_js_py import import_transformers_js\n\nst.title(\"Sentiment analysis\")\n\ntext = st.text_input(\"Input some text\", \"I love transformers!\")\n\nif text:\n    with st.spinner():\n        transformers = await import_transformers_js()\n        pipeline = transformers.pipeline\n        if \"pipe\" not in st.session_state:\n            st.session_state[\"pipe\"] = await pipeline('sentiment-analysis')\n        pipe = st.session_state[\"pipe\"]\n        out = await pipe(text)\n    st.write(out)\n```\n\n### Gradio-lite\n\n![Gradio-lite screenshot](./docs/images/Gradio-lite.png)\n\nSave the following code as an HTML file and open it in a browser.\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <script type=\"module\" crossorigin src=\"https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.js\"></script>\n  <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.css\" />\n  <title>Transformers.js with Gradio-lite</title>\n  <style>\n    html, body {\n      margin: 0;\n      padding: 0;\n      height: 100%;\n      width: 100%;\n    }\n    gradio-lite {\n      height: 100%;\n      width: 100%;\n    }\n  </style>\n</head>\n<body>\n<gradio-lite>\n\n<gradio-requirements>\ntransformers_js_py\n</gradio-requirements>\n\n<gradio-file name=\"app.py\" entrypoint>\nimport gradio as gr\nfrom transformers_js_py import import_transformers_js\n\ntransformers = await import_transformers_js()\npipeline = transformers.pipeline\n\npipe = await pipeline('sentiment-analysis')\n\nasync def process(text):\n    return await pipe(text)\n\ndemo = gr.Interface(fn=process, inputs=\"text\", outputs=\"json\")\n\ndemo.launch()\n</gradio-file>\n\n</gradio-lite>\n</body>\n</html>\n```\n\n[\ud83d\udc49 Online demo](https://huggingface.co/spaces/abidlabs/gradio-lite-classify)\n\nFor more details about Gradio-lite, please read [Gradio-Lite: Serverless Gradio Running Entirely in Your Browser (huggingface.co)](https://huggingface.co/blog/gradio-lite).\n\n### Shinylive\n\n[![Shinylive screenshot](./docs/images/Shinylive.png)](https://shinylive.io/py/editor/#code=NobwRAdghgtgpmAXGKAHVA6VBPMAaMAYwHsIAXOcpMAMwCdiYACAZwAsBLCbJjmVYnTJMAgujxM6lACZw6EgK4cAOhHqMmZOlAgsag+HRYB9AFYte-QcL4ChxrTr0G5J86tVpUxpUwC8TEpYUADmcMY0ADZK0gAUqkyJgRwYXKgKZA5wAB5k8WAUucr4TMUAKjk2EOlkxRKokVCEcGzEkbJ0fsUAouRympXFAJR4CUlBxBk1WbnGAG5yAEZQZHz5ZEVgI6pDHhCqsjSscgt0sWkZEpNkNRIscCwsHKRDiGOJAALXNe9MH1IQDoYQq1CBJJhQFjYCCEJiHTS5WKvX7gjhHCDEKo1YGVJFvMHgwmJKRkBR0MHFSn7AlExy6fR0QwWAJQADuUA4Nis9jpzkZrjMLCRKKSqA4qDgkS4cH8mm09JcRiw4sl0r2RMSYolsrZHOEWtVEDg+Xu5D4lDIAFodFBItgnixhuqNdcdezOUwDedqhkcYihrtqRrJHBSeTWFpYtdA3svLKxKhYl4fBw7ic5BJZIsFCE-GU6Ao4IGwABfPDgaDwahSACOSik8HILGBuXwRFIFCoyF5DKZlvMlpwpYAukA)\n\n[\ud83d\udc49 Online demo](https://shinylive.io/py/editor/#code=NobwRAdghgtgpmAXGKAHVA6VBPMAaMAYwHsIAXOcpMAMwCdiYACAZwAsBLCbJjmVYnTJMAgujxM6lACZw6EgK4cAOhHqMmZOlAgsag+HRYB9AFYte-QcL4ChxrTr0G5J86tVpUxpUwC8TEpYUADmcMY0ADZK0gAUqkyJgRwYXKgKZA5wAB5k8WAUucr4TMUAKjk2EOlkxRKokVCEcGzEkbJ0fsUAouRympXFAJR4CUlBxBk1WbnGAG5yAEZQZHz5ZEVgI6pDHhCqsjSscgt0sWkZEpNkNRIscCwsHKRDiGOJAALXNe9MH1IQDoYQq1CBJJhQFjYCCEJiHTS5WKvX7gjhHCDEKo1YGVJFvMHgwmJKRkBR0MHFSn7AlExy6fR0QwWAJQADuUA4Nis9jpzkZrjMLCRKKSqA4qDgkS4cH8mm09JcRiw4sl0r2RMSYolsrZHOEWtVEDg+Xu5D4lDIAFodFBItgnixhuqNdcdezOUwDedqhkcYihrtqRrJHBSeTWFpYtdA3svLKxKhYl4fBw7ic5BJZIsFCE-GU6Ao4IGwABfPDgaDwahSACOSik8HILGBuXwRFIFCoyF5DKZlvMlpwpYAukA) : try out this code online.\n\n```python\nfrom shiny import App, render, ui\nfrom transformers_js_py import import_transformers_js\n\napp_ui = ui.page_fluid(\n    ui.input_text(\"text\", \"Text input\", placeholder=\"Enter text\"),\n    ui.output_text_verbatim(\"txt\"),\n)\n\n\ndef server(input, output, session):\n    @output\n    @render.text\n    async def txt():\n        if not input.text():\n            return \"\"\n\n        transformers = await import_transformers_js()\n        pipeline = transformers.pipeline\n\n        pipe = await pipeline('sentiment-analysis')\n\n        out = await pipe(input.text())\n\n        return str(out)\n\n\napp = App(app_ui, server, debug=True)\n```\n\n### PyScript\n\n![PyScript screenshot](./docs/images/PyScript.png)\n\n\ud83d\udc49Try this code snippet on https://pyscript.com/\n\n```html\n<html>\n  <head>\n    <link rel=\"stylesheet\" href=\"https://pyscript.net/latest/pyscript.css\" />\n    <script defer src=\"https://pyscript.net/latest/pyscript.js\"></script>\n  </head>\n  <body>\n    <input type=\"text\" value=\"\" id=\"text-input\" />\n    <button py-click=\"run()\" id=\"run-button\">Run</button>\n\n    <py-config>\n        packages = [\"transformers-js-py\"]\n    </py-config>\n    <py-script>\n        import asyncio\n        from transformers_js_py import import_transformers_js\n\n        text_input = Element(\"text-input\")\n\n        async def main(input_data):\n            transformers = await import_transformers_js()\n            pipeline = transformers.pipeline\n            pipe = await pipeline('sentiment-analysis')\n            out = await pipe(input_data)\n            print(out)\n\n        def run():\n            print(\"Start\")\n            input_data = text_input.value\n            if input_data.strip() == \"\":\n                print(\"No data input.\")\n                return\n\n            future = asyncio.ensure_future(main(input_data))\n    </py-script>\n  </body>\n</html>\n\n```\n\n### Panel\n\nWith [HoloViz Panel](https://panel.holoviz.org) you develop your app on your laptop and convert it to [Pyodide](https://pyodide.org/en/stable/) or [PyScript](https://pyscript.net/) by running [`panel convert`](https://panel.holoviz.org/how_to/wasm/convert.html).\n\n![HoloViz Panel Transformers App](docs/images/Panel.png)\n\nInstall the requirements\n\n```bash\npip install panel transformers_js_py\n```\n\nCreate the **app.py** file in your favorite editor or IDE.\n\n```python\nimport panel as pn\n\npn.extension(sizing_mode=\"stretch_width\", design=\"material\")\n\n@pn.cache\nasync def _get_pipeline(model=\"sentiment-analysis\"):\n    from transformers_js_py import import_transformers_js\n    transformers = await import_transformers_js()\n    return await transformers.pipeline(model)\n\n\ntext_input = pn.widgets.TextInput(placeholder=\"Send a message\", name=\"Message\")\nbutton = pn.widgets.Button(name=\"Send\", icon=\"send\", align=\"end\", button_type=\"primary\")\n\n@pn.depends(text_input, button)\nasync def _response(text, event):\n    if not text:\n        return {}\n    pipe = await _get_pipeline()\n    return await pipe(text)\n\npn.Column(\n    text_input, button, pn.pane.JSON(_response, depth=2)\n).servable()\n```\n\nConvert the app to [Pyodide](https://pyodide.org/en/stable/). For more options like *hot reload* check out the [Panel Convert](https://panel.holoviz.org/how_to/wasm/convert.html) guide.\n\n```bash\npanel convert app.py --to pyodide-worker --out pyodide --requirements transformers_js_py\n```\n\nNow serve the app\n\n```bash\npython -m http.server -d pyodide\n```\n\nFinally you can try out the app by opening [localhost:8000/app.html](http://localhost:8000/app.html)\n\n<details>\n    <summary><h4>Panel Chat App Example</h4></summary>\n\nYou can also use `transformers_js_py` with [Panels Chat Components](https://panel.holoviz.org/reference/index.html#chat).\n\n![HoloViz Panel Transformers App](docs/images/PanelChat.png)\n\n```python\nimport panel as pn\n\nMODEL = \"sentiment-analysis\"\npn.chat.ChatMessage.default_avatars[\"hugging face\"] = \"\ud83e\udd17\"\n\npn.extension(design=\"material\")\n\n@pn.cache\nasync def _get_pipeline(model):\n    from transformers_js_py import import_transformers_js\n    transformers = await import_transformers_js()\n    return await transformers.pipeline(model)\n\nasync def callback(contents: str, user: str, instance: pn.chat.ChatInterface):\n    pipe = await _get_pipeline(MODEL)\n    response = await pipe(contents)\n    label, score = response[0][\"label\"], round(response[0][\"score\"], 2)\n    return f\"\"\"I feel a {label} vibe here (score: {score})\"\"\"\n\nwelcome_message = pn.chat.ChatMessage(\n    f\"I'm a Hugging Face Transformers `{MODEL}` model.\\n\\nPlease *send a message*!\",\n    user=\"Hugging Face\",\n)\n\npn.chat.ChatInterface(\n    welcome_message, placeholder_text=\"Loading the model ...\",\n    callback=callback, callback_user=\"Hugging Face\",\n).servable()\n```\n\nFor more chat examples see [Panel Chat Examples](https://holoviz-topics.github.io/panel-chat-examples/).\n</details>\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "",
    "version": "0.10.0",
    "project_urls": {
        "Homepage": "https://github.com/whitphx/transformers.js.py",
        "Repository": "https://github.com/whitphx/transformers.js.py"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "920c344ebeea1bca4bb9761b6ddfa22bc3d45fd76660a5d2732023cb367ecf81",
                "md5": "b04b46e9ca58a585dc271875dfd8d729",
                "sha256": "32a2541d20d82cadd41e53fca8d4f671256e732ca62a5cef3410d0446d6a74c2"
            },
            "downloads": -1,
            "filename": "transformers_js_py-0.10.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b04b46e9ca58a585dc271875dfd8d729",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10,<4.0",
            "size": 14597,
            "upload_time": "2024-02-26T14:20:25",
            "upload_time_iso_8601": "2024-02-26T14:20:25.287390Z",
            "url": "https://files.pythonhosted.org/packages/92/0c/344ebeea1bca4bb9761b6ddfa22bc3d45fd76660a5d2732023cb367ecf81/transformers_js_py-0.10.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "35d6294a91623678442abe2bc5555e5f3a2394ef25de81254a41061ecc112b8c",
                "md5": "ea1bbc37156d060256e36e3d01fda53a",
                "sha256": "0f09657609813d540943339ad0b603bb421f185bc6d32d5f6ec9b6b63dc98917"
            },
            "downloads": -1,
            "filename": "transformers_js_py-0.10.0.tar.gz",
            "has_sig": false,
            "md5_digest": "ea1bbc37156d060256e36e3d01fda53a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10,<4.0",
            "size": 16892,
            "upload_time": "2024-02-26T14:20:27",
            "upload_time_iso_8601": "2024-02-26T14:20:27.250526Z",
            "url": "https://files.pythonhosted.org/packages/35/d6/294a91623678442abe2bc5555e5f3a2394ef25de81254a41061ecc112b8c/transformers_js_py-0.10.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-26 14:20:27",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "whitphx",
    "github_project": "transformers.js.py",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "transformers-js-py"
}
        
Elapsed time: 0.25206s