osanseviero HF staff aleDsz commited on
Commit
40e7569
0 Parent(s):

Duplicate from livebook-dev/single_file_phx_bumblebee_ml

Browse files

Co-authored-by: Alexandre de Souza <aleDsz@users.noreply.huggingface.co>

Files changed (4) hide show
  1. .gitattributes +34 -0
  2. Dockerfile +71 -0
  3. README.md +18 -0
  4. run.exs +305 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Find eligible builder and runner images on Docker Hub. We use Ubuntu/Debian instead of
2
+ # Alpine to avoid DNS resolution issues in production.
3
+ #
4
+ # https://hub.docker.com/r/hexpm/elixir/tags?page=1&name=ubuntu
5
+ # https://hub.docker.com/_/ubuntu?tab=tags
6
+ #
7
+ #
8
+ # This file is based on these images:
9
+ #
10
+ # - https://hub.docker.com/r/hexpm/elixir/tags - for the build image
11
+ # - https://hub.docker.com/_/debian?tab=tags&page=1&name=bullseye-20210902-slim - for the release image
12
+ # - https://pkgs.org/ - resource for finding needed packages
13
+ # - Ex: hexpm/elixir:1.13.4-erlang-24.0.1-debian-bullseye-20210902-slim
14
+ #
15
+ ARG ELIXIR_VERSION=1.14.2
16
+ ARG OTP_VERSION=25.1
17
+ ARG DEBIAN_VERSION=bullseye-20220801-slim
18
+
19
+ ARG BUILDER_IMAGE="hexpm/elixir:${ELIXIR_VERSION}-erlang-${OTP_VERSION}-debian-${DEBIAN_VERSION}"
20
+ ARG RUNNER_IMAGE="hexpm/elixir:${ELIXIR_VERSION}-erlang-${OTP_VERSION}-debian-${DEBIAN_VERSION}"
21
+
22
+ FROM ${BUILDER_IMAGE} as builder
23
+
24
+ # install build dependencies
25
+ RUN apt-get update -y && apt-get install -y build-essential git curl \
26
+ && apt-get clean && rm -f /var/lib/apt/lists/*_*
27
+
28
+ # prepare build dir
29
+ WORKDIR /app
30
+
31
+ # set build ENV
32
+ ENV MIX_ENV="prod"
33
+ ENV MIX_HOME="/app/.mix"
34
+ ENV EXS_DRY_RUN="true"
35
+ ENV MIX_INSTALL_DIR="/app/.mix"
36
+ ENV BUMBLEBEE_CACHE_DIR="/app/.bumblebee"
37
+
38
+ # install hex + rebar
39
+ RUN mix local.hex --force && \
40
+ mix local.rebar --force
41
+
42
+ # install mix dependencies
43
+ COPY run.exs ./
44
+ RUN elixir ./run.exs
45
+
46
+ # start a new build stage so that the final image will only contain
47
+ # the compiled release and other runtime necessities
48
+ FROM ${RUNNER_IMAGE}
49
+
50
+ # install build dependencies
51
+ RUN apt-get update -y && apt-get install -y build-essential git curl \
52
+ && apt-get clean && rm -f /var/lib/apt/lists/*_*
53
+
54
+ WORKDIR "/app"
55
+
56
+ # set runner ENV
57
+ ENV MIX_ENV="prod"
58
+ ENV MIX_HOME="/app/.mix"
59
+ ENV MIX_INSTALL_DIR="/app/.mix"
60
+ ENV BUMBLEBEE_CACHE_DIR="/app/.bumblebee"
61
+ ENV SHELL=/bin/bash
62
+ ENV PORT=7860
63
+
64
+ EXPOSE 7860
65
+
66
+ # Only copy the final release from the build stage
67
+ COPY --from=builder --chown=nobody:root /app/.mix/ ./.mix
68
+ COPY --from=builder --chown=nobody:root /app/.bumblebee/ ./.bumblebee
69
+ COPY --from=builder --chown=nobody:root /app/run.exs ./
70
+
71
+ CMD ["elixir", "/app/run.exs"]
README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Phoenix image classification in a single file
3
+ emoji: 📚
4
+ colorFrom: red
5
+ colorTo: indigo
6
+ sdk: docker
7
+ fullWidth: true
8
+ pinned: false
9
+ duplicated_from: livebook-dev/single_file_phx_bumblebee_ml
10
+ ---
11
+
12
+ # Phoenix image classification in a single file
13
+
14
+ To deploy your own app, duplicate this Space and get started.
15
+
16
+ ## Acknowledgments
17
+
18
+ This Space is based on the [single file Phoenix app for Fly.io](https://github.com/chrismccord/single_file_phx_bumblebee_ml) from @chrismccord.
run.exs ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ host =
2
+ if repo_name = System.get_env("SPACE_REPO_NAME") do
3
+ "#{System.get_env("SPACE_AUTHOR_NAME")}-#{String.replace(repo_name, "_", "-")}.hf.space"
4
+ else
5
+ "localhost"
6
+ end
7
+
8
+ Application.put_env(:phoenix, :json_library, Jason)
9
+
10
+ Application.put_env(:phoenix_demo, PhoenixDemo.Endpoint,
11
+ url: [host: host],
12
+ http: [
13
+ ip: {0, 0, 0, 0, 0, 0, 0, 0},
14
+ port: String.to_integer(System.get_env("PORT") || "4000"),
15
+ transport_options: [socket_opts: [:inet6]]
16
+ ],
17
+ server: true,
18
+ live_view: [signing_salt: :crypto.strong_rand_bytes(8) |> Base.encode16()],
19
+ secret_key_base: :crypto.strong_rand_bytes(32) |> Base.encode16(),
20
+ pubsub_server: PhoenixDemo.PubSub
21
+ )
22
+
23
+ Mix.install([
24
+ {:plug_cowboy, "~> 2.6"},
25
+ {:jason, "~> 1.4"},
26
+ {:phoenix, "~> 1.7.0-rc.0", override: true},
27
+ {:phoenix_live_view, "~> 0.18.3"},
28
+ {:bumblebee, "~> 0.1.0"},
29
+ {:nx, "~> 0.4.1"},
30
+ {:exla, "~> 0.4.1"}
31
+ ])
32
+
33
+ Application.put_env(:nx, :default_backend, EXLA.Backend)
34
+
35
+ defmodule PhoenixDemo.Layouts do
36
+ use Phoenix.Component
37
+
38
+ def render("live.html", assigns) do
39
+ ~H"""
40
+ <script src="//cdn.jsdelivr.net/npm/phoenix@1.7.0-rc.0/priv/static/phoenix.min.js"></script>
41
+ <script src="//cdn.jsdelivr.net/npm/phoenix_live_view@0.18.3/priv/static/phoenix_live_view.min.js"></script>
42
+ <script>
43
+ const ImageInput = {
44
+ mounted(){
45
+ const DROP_CLASSES = ["bg-blue-100", "border-blue-300"]
46
+ this.boundHeight = parseInt(this.el.dataset.height)
47
+ this.boundWidth = parseInt(this.el.dataset.width)
48
+ this.inputEl = this.el.querySelector(`#${this.el.id}-input`)
49
+ this.previewEl = this.el.querySelector(`#${this.el.id}-preview`)
50
+
51
+ this.el.addEventListener("click", e => this.inputEl.click())
52
+ this.inputEl.addEventListener("change", e => this.loadFile(event.target.files))
53
+ this.el.addEventListener("dragover", e => {
54
+ e.stopPropagation()
55
+ e.preventDefault()
56
+ e.dataTransfer.dropEffect = "copy"
57
+ })
58
+ this.el.addEventListener("drop", e => {
59
+ e.stopPropagation()
60
+ e.preventDefault()
61
+ this.loadFile(e.dataTransfer.files)
62
+ })
63
+ this.el.addEventListener("dragenter", e => this.el.classList.add(...DROP_CLASSES))
64
+ this.el.addEventListener("drop", e => this.el.classList.remove(...DROP_CLASSES))
65
+ this.el.addEventListener("dragleave", e => {
66
+ if(!this.el.contains(e.relatedTarget)){ this.el.classList.remove(...DROP_CLASSES) }
67
+ })
68
+ },
69
+
70
+ loadFile(files){
71
+ const file = files && files[0]
72
+ if(!file){ return }
73
+ const reader = new FileReader()
74
+ reader.onload = (readerEvent) => {
75
+ const imgEl = document.createElement("img")
76
+ imgEl.addEventListener("load", (loadEvent) => {
77
+ this.setPreview(imgEl)
78
+ const blob = this.canvasToBlob(this.toCanvas(imgEl))
79
+ this.upload("image", [blob])
80
+ })
81
+ imgEl.src = readerEvent.target.result
82
+ }
83
+ reader.readAsDataURL(file)
84
+ },
85
+
86
+ setPreview(imgEl){
87
+ const previewImgEl = imgEl.cloneNode()
88
+ previewImgEl.style.maxHeight = "100%"
89
+ this.previewEl.replaceChildren(previewImgEl)
90
+ },
91
+
92
+ toCanvas(imgEl){
93
+ // We resize the image, such that it fits in the configured height x width, but
94
+ // keep the aspect ratio. We could also easily crop, pad or squash the image, if desired
95
+ const canvas = document.createElement("canvas")
96
+ const ctx = canvas.getContext("2d")
97
+ const widthScale = this.boundWidth / imgEl.width
98
+ const heightScale = this.boundHeight / imgEl.height
99
+ const scale = Math.min(widthScale, heightScale)
100
+ canvas.width = Math.round(imgEl.width * scale)
101
+ canvas.height = Math.round(imgEl.height * scale)
102
+ ctx.drawImage(imgEl, 0, 0, imgEl.width, imgEl.height, 0, 0, canvas.width, canvas.height)
103
+ return canvas
104
+ },
105
+
106
+ canvasToBlob(canvas){
107
+ const imageData = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height)
108
+ const buffer = this.imageDataToRGBBuffer(imageData)
109
+ const meta = new ArrayBuffer(8)
110
+ const view = new DataView(meta)
111
+ view.setUint32(0, canvas.height, false)
112
+ view.setUint32(4, canvas.width, false)
113
+ return new Blob([meta, buffer], {type: "application/octet-stream"})
114
+ },
115
+
116
+ imageDataToRGBBuffer(imageData){
117
+ const pixelCount = imageData.width * imageData.height
118
+ const bytes = new Uint8ClampedArray(pixelCount * 3)
119
+ for(let i = 0; i < pixelCount; i++) {
120
+ bytes[i * 3] = imageData.data[i * 4]
121
+ bytes[i * 3 + 1] = imageData.data[i * 4 + 1]
122
+ bytes[i * 3 + 2] = imageData.data[i * 4 + 2]
123
+ }
124
+ return bytes.buffer
125
+ }
126
+ }
127
+ const liveSocket = new LiveView.LiveSocket("/live", Phoenix.Socket, {hooks: {ImageInput}})
128
+ liveSocket.connect()
129
+ </script>
130
+ <script src="https://cdn.tailwindcss.com"></script>
131
+ <%= @inner_content %>
132
+ """
133
+ end
134
+ end
135
+
136
+ defmodule PhoenixDemo.ErrorView do
137
+ def render(_, _), do: "error"
138
+ end
139
+
140
+ defmodule PhoenixDemo.SampleLive do
141
+ use Phoenix.LiveView, layout: {PhoenixDemo.Layouts, :live}
142
+
143
+ def mount(_params, _session, socket) do
144
+ {:ok,
145
+ socket
146
+ |> assign(label: nil, running: false, task_ref: nil)
147
+ |> allow_upload(:image,
148
+ accept: :any,
149
+ max_entries: 1,
150
+ max_file_size: 300_000,
151
+ progress: &handle_progress/3,
152
+ auto_upload: true
153
+ )}
154
+ end
155
+
156
+ def render(assigns) do
157
+ ~H"""
158
+ <div class="h-screen w-screen flex items-center justify-center antialiased bg-gray-100">
159
+ <div class="flex flex-col items-center w-1/2">
160
+ <h1 class="text-slate-900 font-extrabold text-3xl tracking-tight text-center">Elixir image classification demo</h1>
161
+ <p class="mt-6 text-lg text-slate-600 text-center max-w-3xl mx-auto">
162
+ Powered by <a href="https://github.com/elixir-nx/bumblebee" target="_blank" class="font-mono font-medium text-sky-500">Bumblebee</a>,
163
+ an Nx/Axon library for pre-trained and transformer NN models with <a href="https://huggingface.co">🤗</a> integration.
164
+ Deployed on <a href="https://huggingface.co/" target="_blank" class="font-mono font-medium text-sky-500">Hugging Face</a> CPU Basic (2vCPU · 16 GiB RAM)
165
+ </p>
166
+ <form class="m-0 flex flex-col items-center space-y-2 mt-8" phx-change="noop" phx-submit="noop">
167
+ <.image_input id="image" upload={@uploads.image} height={224} width={224} />
168
+ </form>
169
+ <div class="mt-6 flex space-x-1.5 items-center text-gray-600 text-xl">
170
+ <span>Label:</span>
171
+ <%= if @running do %>
172
+ <.spinner />
173
+ <% else %>
174
+ <span class="text-gray-900 font-medium"><%= @label || "?" %></span>
175
+ <% end %>
176
+ </div>
177
+ <p class="text-lg text-center max-w-3xl mx-auto fixed top-2 right-2">
178
+ <a href="https://huggingface.co/spaces/livebook-dev/single_file_phx_bumblebee_ml/tree/main" target="_blank" class="ml-6 text-sky-500 hover:text-sky-700 font-mono font-medium">
179
+ View the source
180
+ <span class="sr-only">view source on Hugging Face</span>
181
+ <img alt="Hugging Face's logo" class="md:mr-2 w-7 inline" src="https://huggingface.co/front/assets/huggingface_logo-noborder.svg">
182
+ </a>
183
+ </p>
184
+ </div>
185
+ </div>
186
+ """
187
+ end
188
+
189
+ defp image_input(assigns) do
190
+ ~H"""
191
+ <div
192
+ id={@id}
193
+ class="inline-flex p-4 border-2 border-dashed border-gray-200 rounded-lg cursor-pointer bg-white"
194
+ phx-hook="ImageInput"
195
+ data-height={@height}
196
+ data-width={@width}
197
+ >
198
+ <.live_file_input upload={@upload} class="hidden" />
199
+ <input id={"#{@id}-input"} type="file" class="hidden" />
200
+ <div
201
+ class="h-[300px] w-[300px] flex items-center justify-center"
202
+ id={"#{@id}-preview"}
203
+ phx-update="ignore"
204
+ >
205
+ <div class="text-gray-500 text-center">
206
+ Drag an image file here or click to open file browser
207
+ </div>
208
+ </div>
209
+ </div>
210
+ """
211
+ end
212
+
213
+ defp spinner(assigns) do
214
+ ~H"""
215
+ <svg phx-no-format class="inline mr-2 w-4 h-4 text-gray-200 animate-spin fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
216
+ <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor" />
217
+ <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill" />
218
+ </svg>
219
+ """
220
+ end
221
+
222
+ def handle_progress(:image, entry, socket) do
223
+ if entry.done? do
224
+ socket
225
+ |> consume_uploaded_entries(:image, fn meta, _ -> {:ok, File.read!(meta.path)} end)
226
+ |> case do
227
+ [binary] ->
228
+ image = decode_as_tensor(binary)
229
+ task = Task.async(fn -> Nx.Serving.batched_run(PhoenixDemo.Serving, image) end)
230
+ {:noreply, assign(socket, running: true, task_ref: task.ref)}
231
+
232
+ [] ->
233
+ {:noreply, socket}
234
+ end
235
+ else
236
+ {:noreply, socket}
237
+ end
238
+ end
239
+
240
+ defp decode_as_tensor(<<height::32-integer, width::32-integer, data::binary>>) do
241
+ data |> Nx.from_binary(:u8) |> Nx.reshape({height, width, 3})
242
+ end
243
+
244
+ # We need phx-change and phx-submit on the form for live uploads
245
+ def handle_event("noop", %{}, socket) do
246
+ {:noreply, socket}
247
+ end
248
+
249
+ def handle_info({ref, result}, %{assigns: %{task_ref: ref}} = socket) do
250
+ Process.demonitor(ref, [:flush])
251
+ %{predictions: [%{label: label}]} = result
252
+ {:noreply, assign(socket, label: label, running: false)}
253
+ end
254
+ end
255
+
256
+ defmodule PhoenixDemo.Router do
257
+ use Phoenix.Router
258
+ import Phoenix.LiveView.Router
259
+
260
+ pipeline :browser do
261
+ plug(:accepts, ["html"])
262
+ end
263
+
264
+ scope "/", PhoenixDemo do
265
+ pipe_through(:browser)
266
+
267
+ live("/", SampleLive, :index)
268
+ end
269
+ end
270
+
271
+ defmodule PhoenixDemo.Endpoint do
272
+ use Phoenix.Endpoint, otp_app: :phoenix_demo
273
+
274
+ socket("/live", Phoenix.LiveView.Socket)
275
+ plug(PhoenixDemo.Router)
276
+ end
277
+
278
+ # Application startup
279
+
280
+ {:ok, model_info} = Bumblebee.load_model({:hf, "microsoft/resnet-50"})
281
+ {:ok, featurizer} = Bumblebee.load_featurizer({:hf, "microsoft/resnet-50"})
282
+
283
+ serving =
284
+ Bumblebee.Vision.image_classification(model_info, featurizer,
285
+ top_k: 1,
286
+ compile: [batch_size: 10],
287
+ defn_options: [compiler: EXLA]
288
+ )
289
+
290
+ # Dry run for copying cached mix install from builder to runner
291
+ if System.get_env("EXS_DRY_RUN") == "true" do
292
+ System.halt(0)
293
+ else
294
+ {:ok, _} =
295
+ Supervisor.start_link(
296
+ [
297
+ {Phoenix.PubSub, name: PhoenixDemo.PubSub},
298
+ PhoenixDemo.Endpoint,
299
+ {Nx.Serving, serving: serving, name: PhoenixDemo.Serving, batch_timeout: 100}
300
+ ],
301
+ strategy: :one_for_one
302
+ )
303
+
304
+ Process.sleep(:infinity)
305
+ end