Skip to content

Instantly share code, notes, and snippets.

@ChristianAlexander
Created February 21, 2025 14:15
Show Gist options
  • Save ChristianAlexander/314111dff519fa4921260ced3f425c45 to your computer and use it in GitHub Desktop.
Save ChristianAlexander/314111dff519fa4921260ced3f425c45 to your computer and use it in GitHub Desktop.
Pythonx: Python in Elixir

Pythonx

Mix.install([
  {:pythonx, "~> 0.3.0"},
  {:kino, "~> 0.14.2"},
  {:kino_vega_lite, "~> 0.1.13"}
])

Python Initialize

Pythonx.uv_init("""
[project]
name = "project"
version = "0.0.0"
requires-python = "==3.12.*"
dependencies = [
  "transformers==4.49.0",
  "accelerate==1.4.0"
]
""")

Simple Math

scaling_factor_input = Kino.Input.number("Scaling Factor", default: 42.0)
import Pythonx

# Set the global based on a form input
scaling_factor = Kino.Input.read(scaling_factor_input)

# Use an Elixir global variable in a Python expression
~PY"""
def calculate(x):
  b = 100
  return scaling_factor * x + b

calculate(5)
"""
|> Pythonx.decode()

Stable Diffusion

prompt_input = Kino.Input.textarea("What's the problem?", default: "I have a problem with my iphone that needs to be resolved asap!!")
import Pythonx

prompt = Kino.Input.read(prompt_input)

result =
  ~PY"""
  from transformers import pipeline

  classifier = pipeline(model="facebook/bart-large-mnli")

  classifier(
      prompt.decode('utf-8'),
      candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
  )
  """
  |> Pythonx.decode()
chart_data = 
  Enum.zip(result["labels"], result["scores"])
  |> Enum.map(fn {label, score} -> %{"label" => label, "score" => score} end)

alias VegaLite, as: Vl

Vl.new(width: 500, height: 300)
|> Vl.data_from_values(chart_data)
|> Vl.mark(:bar)
|> Vl.encode_field(:x, "label", type: :nominal, title: "Labels")
|> Vl.encode_field(:y, "score", type: :quantitative, title: "Scores")
|> Vl.config(bar: [color: "#4C78A8"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment