furqankassa/DockerImageRecognitionToText
0
1host =2 if repo_name = System.get_env("SPACE_REPO_NAME") do3 "#{System.get_env("SPACE_AUTHOR_NAME")}-#{repo_name}.hf.space"4 |> String.replace("_", "-")5 |> String.downcase(:ascii)6 else7 "localhost"8 end9 10Application.put_env(:phoenix, :json_library, Jason)11 12Application.put_env(:phoenix_demo, PhoenixDemo.Endpoint,13 url: [host: host],14 http: [15 ip: {0, 0, 0, 0, 0, 0, 0, 0},16 port: String.to_integer(System.get_env("PORT") || "4000"),17 transport_options: [socket_opts: [:inet6]]18 ],19 server: true,20 live_view: [signing_salt: :crypto.strong_rand_bytes(8) |> Base.encode16()],21 secret_key_base: :crypto.strong_rand_bytes(32) |> Base.encode16(),22 pubsub_server: PhoenixDemo.PubSub23)24 25Mix.install([26 {:plug_cowboy, "~> 2.6"},27 {:jason, "~> 1.4"},28 {:phoenix, "~> 1.7.0-rc.0", override: true},29 {:phoenix_live_view, "~> 0.18.3"},30 {:bumblebee, "~> 0.1.0"},31 {:nx, "~> 0.4.1"},32 {:exla, "~> 0.4.1"}33])34 35Application.put_env(:nx, :default_backend, EXLA.Backend)36 37defmodule PhoenixDemo.Layouts do38 use Phoenix.Component39 40 def render("live.html", assigns) do41 ~H"""42 <script src="//cdn.jsdelivr.net/npm/phoenix@1.7.0-rc.0/priv/static/phoenix.min.js"></script>43 <script src="//cdn.jsdelivr.net/npm/phoenix_live_view@0.18.3/priv/static/phoenix_live_view.min.js"></script>44 <script>45 const ImageInput = {46 mounted(){47 const DROP_CLASSES = ["bg-blue-100", "border-blue-300"]48 this.boundHeight = parseInt(this.el.dataset.height)49 this.boundWidth = parseInt(this.el.dataset.width)50 this.inputEl = this.el.querySelector(`#${this.el.id}-input`)51 this.previewEl = this.el.querySelector(`#${this.el.id}-preview`)52 this.el.addEventListener("click", e => this.inputEl.click())53 this.inputEl.addEventListener("change", e => this.loadFile(event.target.files))54 this.el.addEventListener("dragover", e => {55 e.stopPropagation()56 e.preventDefault()57 e.dataTransfer.dropEffect = "copy"58 })59 this.el.addEventListener("drop", e => {60 e.stopPropagation()61 e.preventDefault()62 this.loadFile(e.dataTransfer.files)63 })64 this.el.addEventListener("dragenter", e => this.el.classList.add(...DROP_CLASSES))65 this.el.addEventListener("drop", e => this.el.classList.remove(...DROP_CLASSES))66 this.el.addEventListener("dragleave", e => {67 if(!this.el.contains(e.relatedTarget)){ this.el.classList.remove(...DROP_CLASSES) }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.result82 }83 reader.readAsDataURL(file)84 },85 setPreview(imgEl){86 const previewImgEl = imgEl.cloneNode()87 previewImgEl.style.maxHeight = "100%"88 this.previewEl.replaceChildren(previewImgEl)89 },90 toCanvas(imgEl){91 // We resize the image, such that it fits in the configured height x width, but92 // keep the aspect ratio. We could also easily crop, pad or squash the image, if desired93 const canvas = document.createElement("canvas")94 const ctx = canvas.getContext("2d")95 const widthScale = this.boundWidth / imgEl.width96 const heightScale = this.boundHeight / imgEl.height97 const scale = Math.min(widthScale, heightScale)98 canvas.width = Math.round(imgEl.width * scale)99 canvas.height = Math.round(imgEl.height * scale)100 ctx.drawImage(imgEl, 0, 0, imgEl.width, imgEl.height, 0, 0, canvas.width, canvas.height)101 return canvas102 },103 canvasToBlob(canvas){104 const imageData = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height)105 const buffer = this.imageDataToRGBBuffer(imageData)106 const meta = new ArrayBuffer(8)107 const view = new DataView(meta)108 view.setUint32(0, canvas.height, false)109 view.setUint32(4, canvas.width, false)110 return new Blob([meta, buffer], {type: "application/octet-stream"})111 },112 imageDataToRGBBuffer(imageData){113 const pixelCount = imageData.width * imageData.height114 const bytes = new Uint8ClampedArray(pixelCount * 3)115 for(let i = 0; i < pixelCount; i++) {116 bytes[i * 3] = imageData.data[i * 4]117 bytes[i * 3 + 1] = imageData.data[i * 4 + 1]118 bytes[i * 3 + 2] = imageData.data[i * 4 + 2]119 }120 return bytes.buffer121 }122 }123 const liveSocket = new LiveView.LiveSocket("/live", Phoenix.Socket, {hooks: {ImageInput}})124 liveSocket.connect()125 </script>126 <script src="https://cdn.tailwindcss.com"></script>127 <%= @inner_content %>128 """129 end130end131defmodule PhoenixDemo.ErrorView do132 def render(_, _), do: "error"133end134defmodule PhoenixDemo.SampleLive do135 use Phoenix.LiveView, layout: {PhoenixDemo.Layouts, :live}136 def mount(_params, _session, socket) do137 {:ok,138 socket139 |> assign(label: nil, running: false, task_ref: nil)140 |> allow_upload(:image,141 accept: :any,142 max_entries: 1,143 max_file_size: 300_000,144 progress: &handle_progress/3,145 auto_upload: true146 )}147 end148 def render(assigns) do149 ~H"""150 <div class="h-screen w-screen flex items-center justify-center antialiased bg-gray-100">151 <div class="flex flex-col items-center w-1/2">152 <h1 class="text-slate-900 font-extrabold text-3xl tracking-tight text-center">Elixir image classification demo</h1>153 <p class="mt-6 text-lg text-slate-600 text-center max-w-3xl mx-auto">154 Powered by <a href="https://github.com/elixir-nx/bumblebee" target="_blank" class="font-mono font-medium text-sky-500">Bumblebee</a>,155 an Nx/Axon library for pre-trained and transformer NN models with <a href="https://huggingface.co">🤗</a> integration.156 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)157 </p>158 <form class="m-0 flex flex-col items-center space-y-2 mt-8" phx-change="noop" phx-submit="noop">159 <.image_input id="image" upload={@uploads.image} height={224} width={224} />160 </form>161 <div class="mt-6 flex space-x-1.5 items-center text-gray-600 text-xl">162 <span>Label:</span>163 <%= if @running do %>164 <.spinner />165 <% else %>166 <span class="text-gray-900 font-medium"><%= @label || "?" %></span>167 <% end %>168 </div>169 <p class="text-lg text-center max-w-3xl mx-auto fixed top-2 right-2">170 <a href="https://huggingface.co/spaces/DockerTemplates/single_file_phx_bumblebee_ml/tree/main" target="_blank" class="ml-6 text-sky-500 hover:text-sky-700 font-mono font-medium">171 View the source172 <span class="sr-only">view source on Hugging Face</span>173 <img alt="Hugging Face's logo" class="md:mr-2 w-7 inline" src="https://huggingface.co/front/assets/huggingface_logo-noborder.svg">174 </a>175 </p>176 </div>177 </div>178 """179 end180 181 defp image_input(assigns) do182 ~H"""183 <div184 id={@id}185 class="inline-flex p-4 border-2 border-dashed border-gray-200 rounded-lg cursor-pointer bg-white"186 phx-hook="ImageInput"187 data-height={@height}188 data-width={@width}189 >190 <.live_file_input upload={@upload} class="hidden" />191 <input id={"#{@id}-input"} type="file" class="hidden" />192 <div193 class="h-[300px] w-[300px] flex items-center justify-center"194 id={"#{@id}-preview"}195 phx-update="ignore"196 >197 <div class="text-gray-500 text-center">198 Drag an image file here or click to open file browser199 </div>200 </div>201 </div>202 """203 end204 defp spinner(assigns) do205 ~H"""206 <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">207 <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" />208 <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" />209 </svg>210 """211 end212 213 def handle_progress(:image, entry, socket) do214 if entry.done? do215 socket216 |> consume_uploaded_entries(:image, fn meta, _ -> {:ok, File.read!(meta.path)} end)217 |> case do218 [binary] ->219 image = decode_as_tensor(binary)220 task = Task.async(fn -> Nx.Serving.batched_run(PhoenixDemo.Serving, image) end)221 {:noreply, assign(socket, running: true, task_ref: task.ref)}222 223 [] ->224 {:noreply, socket}225 end226 else227 {:noreply, socket}228 end229 end230 231 defp decode_as_tensor(<<height::32-integer, width::32-integer, data::binary>>) do232 data |> Nx.from_binary(:u8) |> Nx.reshape({height, width, 3})233 end234 235 # We need phx-change and phx-submit on the form for live uploads236 def handle_event("noop", %{}, socket) do237 {:noreply, socket}238 end239 240 def handle_info({ref, result}, %{assigns: %{task_ref: ref}} = socket) do241 Process.demonitor(ref, [:flush])242 %{predictions: [%{label: label}]} = result243 {:noreply, assign(socket, label: label, running: false)}244 end245end246 247defmodule PhoenixDemo.Router do248 use Phoenix.Router249 import Phoenix.LiveView.Router250 251 pipeline :browser do252 plug(:accepts, ["html"])253 end254 255 scope "/", PhoenixDemo do256 pipe_through(:browser)257 258 live("/", SampleLive, :index)259 end260end261 262defmodule PhoenixDemo.Endpoint do263 use Phoenix.Endpoint, otp_app: :phoenix_demo264 265 socket("/live", Phoenix.LiveView.Socket)266 plug(PhoenixDemo.Router)267end268 269# Application startup270 271{:ok, model_info} = Bumblebee.load_model({:hf, "microsoft/resnet-50"})272{:ok, featurizer} = Bumblebee.load_featurizer({:hf, "microsoft/resnet-50"})273 274serving =275 Bumblebee.Vision.image_classification(model_info, featurizer,276 top_k: 1,277 compile: [batch_size: 10],278 defn_options: [compiler: EXLA]279 )280 281# Dry run for copying cached mix install from builder to runner282if System.get_env("EXS_DRY_RUN") == "true" do283 System.halt(0)284else285 {:ok, _} =286 Supervisor.start_link(287 [288 {Phoenix.PubSub, name: PhoenixDemo.PubSub},289 PhoenixDemo.Endpoint,290 {Nx.Serving, serving: serving, name: PhoenixDemo.Serving, batch_timeout: 100}291 ],292 strategy: :one_for_one293 )294 295 Process.sleep(:infinity)296end297 