This is a sample project that explores powering React apps with Python and WebAssembly. It uses Function to compile and run an image editing function written in Python.
First, clone the project and install dependencies:
# Install deps
$ npm installNext, login to Function and create an access key.
Then create a .env.local file and place your access key:
# Function
FXN_ACCESS_KEY="fxn_..."Start the dev server and navigate to http://localhost:3000 to use the editor!
# Start the dev server
$ npm run devThe photo editor is a plain Next.js app built with Tailwind CSS and Shadcn UI. With the UI setup, the actual image editing is implemented in a Python function in editor.py:
from PIL import Image
from torch import clip
from torchvision.transforms.functional import to_pil_image, to_tensor
def edit_image (
image: Image.Image,
*,
contrast: float=0.,
) -> Image.Image:
"""
Edit an image.
"""
image_tensor = to_tensor(image)
contrast_tensor = (image_tensor - 0.5) * (contrast + 1) + 0.5
result_tensor = clip(contrast_tensor, 0., 1.)
result = to_pil_image(result_tensor)
return resultThis Python function is then compiled to WebAssembly using Function. First, install the Function CLI:
# Install the Function CLI
$ pip install --upgrade fxnThen login:
# Login to the Function CLI
$ fxn auth login <access key>Finally, compile the function:
# Compile the Python function
$ fxn compile --overwrite editor.py
