<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maryna Shabalina on Medium]]></title>
        <description><![CDATA[Stories by Maryna Shabalina on Medium]]></description>
        <link>https://medium.com/@marinakrasnovatr81?source=rss-e7c3a3856aac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AtCEuuu23bUPGXbY1eYJXw.jpeg</url>
            <title>Stories by Maryna Shabalina on Medium</title>
            <link>https://medium.com/@marinakrasnovatr81?source=rss-e7c3a3856aac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:17:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marinakrasnovatr81/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Real-Time Voice Transcription with Elixir Nx: A Practical Guide]]></title>
            <link>https://medium.com/@marinakrasnovatr81/real-time-voice-transcription-with-elixir-nx-a-practical-guide-3d455d330783?source=rss-e7c3a3856aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d455d330783</guid>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[audio-transcription]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[bumblebee]]></category>
            <dc:creator><![CDATA[Maryna Shabalina]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 19:09:27 GMT</pubDate>
            <atom:updated>2025-04-06T19:09:27.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeO0GKwZsPjpYgq6jXi7QQ.png" /></figure><p>In modern applications, voice is becoming a first-class input. Whether you’re building a collaborative tool, a live meeting assistant, or a voice-controlled interface, transcribing audio in real time can open up powerful user experiences. Traditionally, achieving this required offloading audio to third-party services or external APIs. But what if you could handle transcription directly in your Elixir application — efficiently, in real time, and without leaving the BEAM?</p><p>Thanks to the combination of Phoenix LiveView, OpenAI’s Whisper model, and the Bumblebee machine learning library, it’s now entirely possible to transcribe audio on the fly <em>with Elixir alone</em></p><h3>Why Elixir?</h3><p>Elixir’s concurrency model makes it ideal for real-time audio processing. With lightweight processes, message passing, and fault-tolerant design, it’s well-suited for building systems that ingest and process live data — like audio streams.</p><p>Phoenix, Elixir’s web framework, extends that power to the frontend via LiveView, allowing you to build reactive UI components (with JavaScript script part that recognize audio)</p><h3>How It Works: Capturing and Transcribing Audio on the client side</h3><p>The architecture looks like this</p><p>Dependencies: Add Exla and Bumblebee to your <em>mix.ex</em>:</p><pre>def deps do<br>  [<br>    # ....<br>    {:bumblebee, &quot;~&gt; 0.5.3&quot;},<br>    {:exla, &quot;~&gt; 0.7.1&quot;}<br>  ]<br>end</pre><p><strong>Client-Side Audio Capture</strong>: A browser captures microphone input and detects when the user is speaking. You can do it simply with send audio-track with some (e.g. 10 seconds) interval or write a code that detects when user(s) stop speaking<br>I have tried second approach with AI-generated JavaScript approaches, like</p><pre>const SILENCE_THRESHOLD = -65; // Adjust based on your testing<br>const SPEECH_THRESHOLD = -50; // A higher threshold for definite speech<br>const SILENCE_DURATION = 500; // 0.5 second of silence before considering speech ended<br>const SPEECH_DURATION = 100; // Minimum duration of speech to be considered valid<br><br>let audioContext;<br>let analyser;<br>let microphone;<br>let isSpeaking = false;<br>let silenceTimer;<br>let speechTimer;<br>let volumeHistory = [];<br>const HISTORY_LENGTH = 10; // Number of samples to keep for averaging<br><br>async function setupAudioAnalysis() {<br>  audioContext = new (window.AudioContext || window.webkitAudioContext)();<br>  analyser = audioContext.createAnalyser();<br>  microphone = audioContext.createMediaStreamSource(audioStrem);<br>  microphone.connect(analyser);<br>  analyser.fftSize = 1024;<br>  analyser.smoothingTimeConstant = 0.8;<br>}<br><br>function getAverageVolume() {<br>  const bufferLength = analyser.frequencyBinCount;<br>  const dataArray = new Float32Array(bufferLength);<br>  analyser.getFloatFrequencyData(dataArray);<br><br>  // Focus on the frequency range of human speech (approximately 300Hz to 3400Hz)<br>  const startIndex = Math.floor(300 * bufferLength / audioContext.sampleRate);<br>  const endIndex = Math.floor(3400 * bufferLength / audioContext.sampleRate);<br><br>  let sum = 0;<br>  let count = 0;<br>  for (let i = startIndex; i &lt; endIndex; i++) {<br>    if (dataArray[i] &gt; -100) { // Ignore very low values<br>      sum += dataArray[i];<br>      count++;<br>    }<br>  }<br>  const average = count &gt; 0 ? sum / count : -100;<br><br>  // Add to history and maintain its length<br>  volumeHistory.push(average);<br>  if (volumeHistory.length &gt; HISTORY_LENGTH) {<br>    volumeHistory.shift();<br>  }<br><br>  // Return the average of recent volumes<br>  return volumeHistory.reduce((a, b) =&gt; a + b, 0) / volumeHistory.length;<br>}<br><br>function detectSpeech() {<br>  const volume = getAverageVolume();<br><br>  if (volume &gt; SPEECH_THRESHOLD) {<br>    if (!isSpeaking) {<br>      clearTimeout(speechTimer);<br>      speechTimer = setTimeout(() =&gt; {<br>        console.log(&#39;User speaks&#39;);<br>        isSpeaking = true;<br>        startAudioRecording();<br>      }, SPEECH_DURATION);<br>    }<br>    clearTimeout(silenceTimer);<br>  } else if (volume &lt; SILENCE_THRESHOLD) {<br>    clearTimeout(speechTimer);<br>    if (isSpeaking) {<br>      clearTimeout(silenceTimer);<br>      silenceTimer = setTimeout(() =&gt; {<br>        console.log(&#39;User stopped speaking&#39;);<br>        isSpeaking = false;<br>        stopAudioRecording();<br>      }, SILENCE_DURATION);<br>    }<br>  }<br>  // If volume is between SILENCE_THRESHOLD and SPEECH_THRESHOLD, we don&#39;t change the state<br>}<br><br>function startSpeechDetection() {<br>  setInterval(detectSpeech, 50);<br>}</pre><p>but it is not working good<br>all examples of AI-generated code that detects pauses didn’t work as I needed, so I stopped with primitive version sending audio every 5 seconds:</p><pre>let audioStrem;<br>let socket;<br>let channel;<br>let pc;<br><br>let audioRecorder;<br>let audioChunks = [];<br>let audioSendInterval;<br><br>async function startAudioRecording() {<br>  audioChunks = [];<br><br>  audioRecorder = new MediaRecorder(audioStrem, { mimeType: &#39;audio/webm;codecs=opus&#39;});<br><br>  audioRecorder.ondataavailable = (event) =&gt; {<br>    if (event.data.size &gt; 0) {<br>      audioChunks.push(event.data);<br>    }<br>  };<br><br>  audioRecorder.onstop = () =&gt; {<br>    const audioBlob = new Blob(audioChunks, { type: &#39;audio/webm;codecs=opus&#39; });<br>    sendAudio(audioBlob);<br>    audioChunks = [];<br>  };<br><br>  audioRecorder.start();<br>}<br><br>function stopAudioRecording() {<br>  if (audioRecorder) {<br>    audioRecorder.stop();<br>  }<br>}<br><br>function sendAudio(audioBlob) {<br>  if (!channel || !channel.push) {<br>    console.error(&#39;Channel is not initialized or push method is not available. Cannot send audio.&#39;);<br>    return;<br>  }<br><br>  const reader = new FileReader();<br>  reader.readAsDataURL(audioBlob);<br>  reader.onloadend = () =&gt; {<br>    try {<br>      const base64AudioMessage = reader.result.split(&#39;,&#39;)[1];<br>      channel.push(&#39;audio_chunk&#39;, { audio: base64AudioMessage });<br>      console.log(&#39;📤 Audio sent:&#39;, base64AudioMessage.length, &#39;bytes&#39;);<br>    } catch (error) {<br>      console.error(&#39;Error sending audio:&#39;, error);<br>    }<br>  };<br>}<br><br>function startAudioSendingLoop() {<br>  audioSendInterval = setInterval(() =&gt; {<br>    stopAudioRecording();<br>    startAudioRecording();<br>  }, 5000); // Send audio every 5 seconds<br>}<br><br>function stopAudioSendingLoop() {<br>  if (audioSendInterval) {<br>    clearInterval(audioSendInterval);<br>  }<br>}<br><br><br>async function connect() {<br>  // .. your code <br><br>  audioStrem = await navigator.mediaDevices.getUserMedia({<br>    audio: {<br>      echoCancellation: true,<br>      noiseSuppression: true<br>    },<br>    video: false}<br>  )<br><br>  startAudioRecording();<br><br>  socket = new Socket(&#39;/socket&#39;, {});<br>  socket.connect();<br><br>  channel = socket.channel(&#39;room:&#39; + roomId, {});<br>  // ... your logic<br><br>  channel.on(&#39;audioTranscription&#39;, (msg) =&gt; {<br>    audiotranscription.innerText = msg[&#39;text&#39;]<br>  });<br><br>  // ... your logic<br>  startAudioSendingLoop()<br>}<br><br>function disconnect() {<br>  console.log(&#39;Disconnecting&#39;);<br><br>  stopAudioSendingLoop()<br><br> // ... your logic<br>}<br><br>// ... your logic</pre><p><strong>Audio Chunking</strong>: When speech is detected, audio is recorded in chunks using the MediaRecorder API</p><p><strong>Channel Communication</strong>: Each audio chunk is base64-encoded and sent to the backend over a Phoenix channel.</p><p>in <em>lib/yourapp_web/channels/your_channel.ex </em>you can asynchronously handle <em>audio_base64</em> data, for example, enque Oban job, send info to GenServer, etc</p><p>In production app, I used asynchronous handling with <em>Oban</em> to avoid any possible process bottlenecks (function <em>&amp;enqueue!</em> added to <em>Oban</em> worker inserts job with specified attributed)</p><pre>def handle_in(&quot;audio_chunk&quot;, %{&quot;audio&quot; =&gt; audio_base64}, socket) do<br>  # Async handling audio_base64 data<br>  # It can be Oban job enqueued, send info to GenServer<br>  <br>  # Oban<br>  # YourApp.Jobs.SaveAudioChunk.enqueue!(socket.assigns.room_id, audio_base64})<br>  <br>  # GenServer<br>  :ok = Room.receive_audio_msg(socket.assigns.room_id, audio_base64)<br><br>  # Very primitive solution for mvp:<br>  # write data to file immedialtely &amp; transcript it, aka<br>  # file = &quot;/tmp/#{room_id}/#{audio_id}.webm&quot;<br>  # audio_data = Base.decode64!(audio_base64)<br>  # File.write!(, audio_data)<br>  # Nx.Serving.batched_run(Recognizer.AudioServing, {:file, file})<br>  <br>  {:noreply, socket}<br>end<br><br>def handle_info({:audio_transcription, msg}, socket) do<br>  push(socket, &quot;audioTranscription&quot;, msg)<br>  {:noreply, socket}<br>end</pre><p>Room GenServer <em>room.ex</em>:</p><pre>def receive_audio_msg(room_id, audio_base64) do<br>  GenServer.cast(id(room_id), {:receive_audio_msg, audio_base64})<br>end<br><br>@impl true<br>def handle_cast({:receive_audio_msg, audio_base64}, state) do<br>  file = &quot;/tmp/audio-#{state.id}.webm&quot;<br>  audio_data = Base.decode64!(audio_base64)<br><br>  File.write!(file, audio_data)<br>  Task.async(fn -&gt; Nx.Serving.batched_run(Recognizer.AudioServing, {:file, file}) end)<br><br>  {:noreply, state}<br>end<br><br>@impl true<br>def handle_info({_ref, %{chunks: chunks}}, state) do<br>  transcription =<br>    chunks<br>    |&gt; Enum.sort_by(&amp; &amp;1.start_timestamp_seconds)<br>    |&gt; Enum.reduce(&quot;&quot;, &amp;(&amp;2 &lt;&gt; &quot;\n&quot; &lt;&gt; &amp;1.text))<br><br>  send(state.channel, {:audio_transcription, %{text: transcription}})<br>  {:noreply, state}<br>end</pre><p><strong>Transcription</strong>: On the Elixir side, the audio chunk is decoded and passed to the Whisper model via Bumblebee for transcription</p><p>To start <em>Recognizer.AudioServing</em>, in your <em>application.ex</em> add child Nx serving process:</p><pre>def start(_type, _args) do<br>  children = [<br>    # ...<br>    {Nx.Serving,<br>     serving: create_audio_serving(),<br>     name: Recognizer.AudioServing,<br>     batch_size: 4,<br>     batch_timeout: 100}<br>  ]<br>  opts = [strategy: :one_for_one, name: Recognizer.Supervisor]<br>  Supervisor.start_link(children, opts)<br>end<br><br>defp create_audio_serving() do<br>  # Load the pre-trained model<br>  {:ok, model_info} = Bumblebee.load_model({:hf, &quot;openai/whisper-tiny&quot;})<br>  {:ok, featurizer} = Bumblebee.load_featurizer({:hf, &quot;openai/whisper-tiny&quot;})<br>  {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, &quot;openai/whisper-tiny&quot;})<br>  {:ok, generation_config} = Bumblebee.load_generation_config({:hf, &quot;openai/whisper-tiny&quot;})<br><br>  Bumblebee.Audio.speech_to_text_whisper(model_info, featurizer, tokenizer, generation_config,<br>    compile: [batch_size: 4],<br>    defn_options: [<br>      compiler: EXLA<br>    ]<br>  )<br>end</pre><p><strong>Live Update</strong>: The resulting text is sent back to the client in real time and rendered instantly in the UI.</p><p>This process allows for seamless, low-latency voice transcription inside your Elixir application — without reaching out to external services.</p><h3>Links</h3><p>This solution was inspired by Elixir WebRTC <a href="https://github.com/elixir-webrtc/apps/tree/master/recognizer">recognizer</a> app what recognize web camera image</p><p>First <a href="https://elixirforum.com/t/troubleshooting-bumblebee-audio-transcription-provides-same-text-for-few-parsed-webm-files/70214">mistake</a> I did was a try to use <em>Xav</em> tensor instead of passing file as it is<br>(saving data to file was necessary <a href="https://github.com/elixir-webrtc/xav/issues/36#issuecomment-2764649559">anyway</a>)</p><p>Fix was found in <a href="https://github.com/dailydaniel/cool-whisper-server">cool-whisper-server</a> app</p><p>PR to elixir <a href="https://github.com/elixir-webrtc/apps/pull/81">web_rtc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d455d330783" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with finding similarity of Images with Elixir, part I]]></title>
            <link>https://medium.com/@marinakrasnovatr81/playing-with-finding-similarity-of-images-with-elixir-part-i-26537f013078?source=rss-e7c3a3856aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/26537f013078</guid>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[tensor]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Maryna Shabalina]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 20:50:31 GMT</pubDate>
            <atom:updated>2024-04-05T10:05:47.819Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMI3_G8mcigdCFhqg7qQxQ.jpeg" /></figure><p>Converting images to multi-dimensional vector arrays for images (tensors) using Nx, Image, Scholar, Exla in Elixir</p><p>Create an elixir server app:</p><pre>mix phx.new xena --module Xena --app xena --no-mailer --binary-id --no-assets --no-esbuild --no-gettext --no-html</pre><p>We will add PostgreSQL with pg_vector later</p><p><a href="https://github.com/elixir-nx/nx">Elixr Nx library</a> will be used to get vector arrays from images<br>Add it to <em>deps</em> in <em>mix.ex</em>:</p><pre> defp deps do<br>    [<br>      # .... phoenix deps<br>      {:pgvector, &quot;~&gt; 0.2.0&quot;},<br>      {:nx, &quot;~&gt; 0.7&quot;},<br>      {:image, &quot;~&gt; 0.37&quot;},<br>      {:scholar, &quot;~&gt; 0.2.1&quot;},<br>      {:exla, &quot;&gt;= 0.0.0&quot;}<br>    ]<br>  end</pre><p><a href="https://github.com/pgvector/pgvector-elixir">elixir pg_vector</a> — Add migration and configuration as described in doc</p><p>I have put few images to priv directory to work with:</p><pre>:~/projects/xena$ tree priv/images/<br>priv/images/<br>├── 1000001750.jpg<br>├── 1000001751.jpg<br>├── 1000001752.jpg<br>├── 1000001753.jpg<br>├── butterfly-1.jpg<br>└── butterfly-2.jpg</pre><p>Let’s convert image to tensor:</p><pre>defmodule Xena.Scripts.Distance do<br>  # ..some functions..<br><br>  def get_tensor_with_image(path) do<br>    path<br>    |&gt; File.read!()<br>    |&gt; Image.from_binary!()<br>    |&gt; Image.to_nx()<br>  end<br>  <br>  def get_tensor(path) do<br>    path<br>    |&gt; File.read!()<br>    |&gt; Nx.from_binary({:s, 8})<br>  end<br>end<br></pre><p>Let’s try to find a distance simply with &amp;Nx.from_binary/2</p><pre># In elixir console <br>t1 = Xena.Scripts.Distance.get_tensor(&quot;priv/images/butterfly-1.jpg&quot;)<br>#Nx.Tensor&lt;<br>  s8[2625573]<br>  EXLA.Backend&lt;host:0, 0.575006515.3274047506.235400&gt;<br>  [-1, -40, -1, -32, 0, 16, 74, 70, 73, 70, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, -1, -30, 1, -40, 73, 67, 67, 95, 80, 82, 79, 70, 73, 76, 69, 0, 1, 1, 0, 0, 1, -56, 0, 0, 0, 0, 4, 48, 0, 0, ...]<br>&gt;<br><br>t2 = Xena.Scripts.Distance.get_tensor(&quot;priv/images/butterfly-2.jpg&quot;)<br><br>#Nx.Tensor&lt;<br>  s8[2124606]<br>  [-1, -40, -1, -32, 0, 16, 74, 70, 73, 70, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, -1, -30, 1, -40, 73, 67, 67, 95, 80, 82, 79, 70, 73, 76, 69, 0, 1, 1, 0, 0, 1, -56, 0, 0, 0, 0, 4, 48, 0, 0, ...]<br>&gt;<br><br>Xena.Scripts.Distance.get_tensor(&quot;priv/images/butterfly-2.jpg&quot;)<br>iex(7)&gt; Scholar.Metrics.Distance.euclidean(t1, t2)<br>** (ArgumentError) tensors must be broadcast compatible, got tensors with shapes {2625573} and {2124606}<br>    (scholar 0.2.1) lib/scholar/shared.ex:86: Scholar.Shared.valid_broadcast/4<br>    (nx 0.7.1) lib/nx/defn/compiler.ex:218: Nx.Defn.Compiler.__remote__/4<br>    (scholar 0.2.1) lib/scholar/metrics/distance.ex:90: Scholar.Metrics.Distance.&quot;__defn:euclidean_n__&quot;/3<br>    (nx 0.7.1) lib/nx/defn/compiler.ex:173: Nx.Defn.Compiler.runtime_fun/3<br>    (exla 0.7.1) lib/exla/defn.ex:534: anonymous fn/4 in EXLA.Defn.compile/8<br>    (exla 0.7.1) lib/exla/defn/locked_cache.ex:36: EXLA.Defn.LockedCache.run/2<br>    (stdlib 5.2) timer.erl:270: :timer.tc/2<br>    (exla 0.7.1) lib/exla/defn.ex:532: EXLA.Defn.compile/8<br>    (exla 0.7.1) lib/exla/defn.ex:400: EXLA.Defn.__compile__/4<br>    (exla 0.7.1) lib/exla/defn.ex:385: EXLA.Defn.__jit__/5<br>    (nx 0.7.1) lib/nx/defn.ex:452: Nx.Defn.do_jit_apply/3<br>    iex:7: (file)<br>iex(7)&gt; </pre><p>Well, errror <em>** (ArgumentError) tensors must be broadcast compatible, got tensors with shapes {2625573} and {2124606} </em>says there is no way to compare tensors with different sizes</p><p>Let’s try to find a distance with &amp;Image.to_nx/1 and 3 items vectors</p><pre>iex(9)&gt; {:ok, t3_1} = Xena.Scripts.Distance.get_tensor_with_image(&quot;priv/images/butterfly-1.jpg&quot;)<br><br>{:ok,<br> #Nx.Tensor&lt;<br>   u8[height: 4624][width: 3468][bands: 3]<br>   EXLA.Backend&lt;host:0, 0.575006515.3274047504.234783&gt;<br>   [<br>     [<br>       [201, 187, 176],<br>       [212, 198, 187],<br>       [229, 215, 204],<br>       [245, 231, 220],<br>       [255, 241, 230],<br>       ...<br>     ],<br>     ...<br>   ]<br> &gt;}<br><br>iex(16)&gt; {:ok, t3_2} = Xena.Scripts.Distance.get_tensor_with_image(&quot;priv/images/butterfly-2.jpg&quot;)<br>{:ok,<br> #Nx.Tensor&lt;<br>   u8[height: 4624][width: 3468][bands: 3]<br>   EXLA.Backend&lt;host:0, 0.575006515.3274047504.234787&gt;<br>   [<br>     [<br>       [218, 195, 181],<br>       [219, 196, 182],<br>       [220, 197, 183],<br>       ...<br>     ],<br>     ...<br>   ]<br> &gt;}<br><br>iex(20)&gt; Scholar.Metrics.Distance.cosine(t3_1, t3_2)<br>#Nx.Tensor&lt;<br>  f32<br>  EXLA.Backend&lt;host:0, 0.575006515.3274047504.234793&gt;<br>  -210.25082397460938<br>&gt;<br><br>iex(21)&gt; Scholar.Metrics.Distance.hamming(t3_1, t3_2)<br>#Nx.Tensor&lt;<br>  f32<br>  EXLA.Backend&lt;host:0, 0.575006515.3274047504.234795&gt;<br>  0.9933227300643921<br>&gt;</pre><p>To find a distance between tensor, tensors should have same sizes<br>Same rule required for multi dimensional vectors</p><pre># photo of flowers<br>{:ok, t3_0} = Xena.Scripts.Distance.get_tensor_with_image(&quot;priv/images/1000001750.jpg&quot;)<br>{:ok,<br> #Nx.Tensor&lt;<br>   u8[height: 4624][width: 3468][bands: 3]<br>   EXLA.Backend&lt;host:0, 0.575006515.3274047504.234797&gt;<br>   [<br>     [<br>       [174, 164, 173],<br>       [178, 168, 177],<br>       [180, 168, 178],<br>.....<br><br># photo of same flowers with 90-degrees camera rotated<br>{:ok, t3_1} = Xena.Scripts.Distance.get_tensor_with_image(&quot;priv/images/1000001751.jpg&quot;)<br>{:ok,<br> #Nx.Tensor&lt;<br>   u8[height: 3468][width: 4624][bands: 3]<br>   EXLA.Backend&lt;host:0, 0.575006515.3274047504.234800&gt;<br>   [<br>     [<br>       [187, 175, 175],<br>       [203, 191, 191],<br>       [222, 210, 210],<br>       [231, 219, 219],<br>.....<br><br># Let&#39;s get the &#39;hamming&#39; distance<br><br>iex(24)&gt; Scholar.Metrics.Distance.hamming(t3_1, t3_0)<br>** (ArgumentError) tensors must be broadcast compatible, got tensors with shapes {3468, 4624, 3} and {4624, 3468, 3}<br>    (scholar 0.2.1) lib/scholar/shared.ex:86: Scholar.Shared.valid_broadcast/4<br>    (nx 0.7.1) lib/nx/defn/compiler.ex:218: Nx.Defn.Compiler.__remote__/4<br>    (scholar 0.2.1) lib/scholar/metrics/distance.ex:541: Scholar.Metrics.Distance.&quot;__defn:hamming_unweighted__&quot;/3<br>    (nx 0.7.1) lib/nx/defn/compiler.ex:173: Nx.Defn.Compiler.runtime_fun/3<br>    (exla 0.7.1) lib/exla/defn.ex:534: anonymous fn/4 in EXLA.Defn.compile/8<br>    (exla 0.7.1) lib/exla/defn/locked_cache.ex:36: EXLA.Defn.LockedCache.run/2<br>    (stdlib 5.2) timer.erl:270: :timer.tc/2<br>    (exla 0.7.1) lib/exla/defn.ex:532: EXLA.Defn.compile/8<br>    (exla 0.7.1) lib/exla/defn.ex:400: EXLA.Defn.__compile__/4<br>    (exla 0.7.1) lib/exla/defn.ex:385: EXLA.Defn.__jit__/5<br>    (nx 0.7.1) lib/nx/defn.ex:452: Nx.Defn.do_jit_apply/3<br>    iex:24: (file)</pre><p>Let’s rotate image <em>“priv/images/1000001750.jpg”</em> to have same size as <em>“priv/images/1000001751.jpg”</em></p><pre>t3_0 = <br>&quot;priv/images/1000001750.jpg&quot;<br>|&gt; File.read!()<br>|&gt; Image.from_binary!()<br>|&gt; Image.rotate!(90)<br>|&gt; Image.to_nx!<br><br>iex(12)&gt; Scholar.Metrics.Distance.cosine(t3_1, t3_0)<br>#Nx.Tensor&lt;<br>  f32<br>  EXLA.Backend&lt;host:0, 0.1134172738.1195769872.95893&gt;<br>  -148.31097412109375<br>&gt;</pre><p>This is my first publication in my research of processing images with elixir for AI journey — comments and critics are highly welcomed</p><p>In next publications I will try to investigate a how to find images similarity with pg_vector for PostgresSQL, because it is not suitable to keep images data to compare in elixir app</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26537f013078" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Hash Partitioning —  for UUID columns, No Triggers and Rules, evenly distribution]]></title>
            <link>https://medium.com/@marinakrasnovatr81/postgresql-hash-partitioning-for-uuid-columns-no-triggers-and-rules-evenly-distribution-db7c8e9a9088?source=rss-e7c3a3856aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/db7c8e9a9088</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[partitioning]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Maryna Shabalina]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 11:18:16 GMT</pubDate>
            <atom:updated>2024-03-23T11:18:16.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EK7ysx5k7xIKTiomo6b8Ng.jpeg" /></figure><h3>PostgreSQL Hash Partitioning — for UUID columns, No Triggers and Rules, evenly distribution</h3><p>Why?</p><blockquote>“<strong>Query performance can be improved dramatically</strong> in certain situations, particularly when most of the heavily accessed rows of the table are in a single partition or a small number of partitions. Partitioning effectively substitutes for the upper tree levels of indexes, making it more likely that the heavily-used parts of the indexes fit in memory” says <a href="https://www.postgresql.org/docs/current/ddl-partitioning.html">PostgreSQL ddl partitioning doc</a> and it’s true</blockquote><p>Supported Versions: 11+</p><p>Hash partitioning was introduced in PostgreSQL 11 version. “Manual” list and range partitioning that require writing rules, checks, triggers and can not guarantee estimated similar size of partitions are things of the past.</p><p>One of the hash partitioning advantages — you don’t have to manually write rules and check for partitioning, in is necessary in case you want to partition your table to 2 or 16 smaller tables on field, and you want it to have likely same size — for example, partitioning by UUID field, text field (not dates or numbers).</p><p><strong>The HASH function guarantees that rows distributed in all partitions with roughly same frequency.</strong></p><p>The number of partitions specified by `Modulus` and can not be changed after it is defined, it is defined when partitions created. You can not change it later, keep it in mind.</p><blockquote>Hash partitioning can work on any data type and it can work for UUID type too. It’s always recommended that the number of tables should be a <strong>power of 2</strong>, and it is also not mandatory to use the same modulus while creating the table; this will help to create the partition table later as required.</blockquote><p>^<a href="https://severalnines.com/blog/how-take-advantage-new-partitioning-features-postgresql-11/">here</a> is more details about hash partitions feature</p><p>So, lets follow the recommendation and partition table to 8 (2 in 3 power). It means MODULUS number 8 will be defined and REMAINDER is 0–7</p><pre>CREATE TABLE part_hash_test (id uuid, y text) PARTITION BY hash (id);<br>-- create child partitions<br>CREATE TABLE part_hash_test_0 PARTITION OF part_hash_test FOR VALUES WITH (MODULUS 8, REMAINDER 0);<br>CREATE TABLE part_hash_test_1 PARTITION OF part_hash_test FOR VALUES WITH (MODULUS 8, REMAINDER 1);<br>CREATE TABLE part_hash_test_2 PARTITION OF part_hash_test FOR VALUES WITH (MODULUS 8, REMAINDER 2);<br>CREATE TABLE part_hash_test_3 PARTITION OF part_hash_test FOR VALUES WITH (MODULUS 8, REMAINDER 3);<br>CREATE TABLE part_hash_test_4 PARTITION OF part_hash_test FOR VALUES WITH (MODULUS 8, REMAINDER 4);<br>CREATE TABLE part_hash_test_5 PARTITION OF part_hash_test FOR VALUES WITH (MODULUS 8, REMAINDER 5);<br>CREATE TABLE part_hash_test_6 PARTITION OF part_hash_test FOR VALUES WITH (MODULUS 8, REMAINDER 6);<br>CREATE TABLE part_hash_test_7 PARTITION OF part_hash_test FOR VALUES WITH (MODULUS 8, REMAINDER 7);</pre><p>Now lets insert half a million records to <em>part_hash_test</em> table and check how data is distributed</p><pre>test=# INSERT INTO part_hash_test SELECT uuid_generate_v4(), generate_series(0,500000);<br>INSERT 0 500001<br>test=# SELECT count(1),tableoid::regclass FROM part_hash_test GROUP by 2 order by 2 ;<br> count |     tableoid     <br>-------+------------------<br> 62482 | part_hash_test_0<br> 62331 | part_hash_test_1<br> 62322 | part_hash_test_2<br> 62431 | part_hash_test_3<br> 62649 | part_hash_test_4<br> 62657 | part_hash_test_5<br> 62656 | part_hash_test_6<br> 62473 | part_hash_test_7</pre><p>Awesome, the data is distributed evenly, the number of records in each table is approximately the same</p><p>Indexes, Unique Constraint</p><p>When index on parent table created, indexes on modulus appears automatically</p><pre>test=# select * from pg_indexes where tablename like &#39;part_hash_test%&#39;;<br> schemaname |    tablename     |        indexname        | tablespace |                                     indexdef                                      <br>------------+------------------+-------------------------+------------+-----------------------------------------------------------------------------------<br> public     | part_hash_test   | part_hash_test_id_idx   |            | CREATE INDEX part_hash_test_id_idx ON ONLY public.part_hash_test USING btree (id)<br> public     | part_hash_test_0 | part_hash_test_0_id_idx |            | CREATE INDEX part_hash_test_0_id_idx ON public.part_hash_test_0 USING btree (id)<br> public     | part_hash_test_1 | part_hash_test_1_id_idx |            | CREATE INDEX part_hash_test_1_id_idx ON public.part_hash_test_1 USING btree (id)<br> public     | part_hash_test_2 | part_hash_test_2_id_idx |            | CREATE INDEX part_hash_test_2_id_idx ON public.part_hash_test_2 USING btree (id)<br> public     | part_hash_test_3 | part_hash_test_3_id_idx |            | CREATE INDEX part_hash_test_3_id_idx ON public.part_hash_test_3 USING btree (id)<br> public     | part_hash_test_4 | part_hash_test_4_id_idx |            | CREATE INDEX part_hash_test_4_id_idx ON public.part_hash_test_4 USING btree (id)<br> public     | part_hash_test_5 | part_hash_test_5_id_idx |            | CREATE INDEX part_hash_test_5_id_idx ON public.part_hash_test_5 USING btree (id)<br> public     | part_hash_test_6 | part_hash_test_6_id_idx |            | CREATE INDEX part_hash_test_6_id_idx ON public.part_hash_test_6 USING btree (id)<br> public     | part_hash_test_7 | part_hash_test_7_id_idx |            | CREATE INDEX part_hash_test_7_id_idx ON public.part_hash_test_7 USING btree (id)<br>(9 rows)</pre><p>Note: there is no unique constraint on parent table that guarantees uniqueness across all partitions</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db7c8e9a9088" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Few popular Elixir (and Erlang) Interview Questions You would like to be prepared to]]></title>
            <link>https://medium.com/@marinakrasnovatr81/few-popular-elixir-and-erlang-interview-questions-you-would-like-to-be-prepared-to-eb5d9aa0f18?source=rss-e7c3a3856aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb5d9aa0f18</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Maryna Shabalina]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 17:16:48 GMT</pubDate>
            <atom:updated>2023-01-29T17:16:48.675Z</atom:updated>
            <content:encoded><![CDATA[<p>This article prepared for elixir, but most questions works for erlang developers as well</p><h3><strong>Data Types</strong></h3><p><strong>Basic data types: </strong>Integer, Floats, Booleans, Atoms, Strings</p><p>How much space each datatype takes?* (check the difference in implementation in languages like C, C#, Java and Erlang VM)</p><ul><li>Is there a limit for max integer value?</li><li>What is atoms? How are atoms stored in memory? Is there are an option to clear memory after created and unused atoms?</li><li>What is more efficient — atoms or strings?</li></ul><p><strong>Collections: </strong>Lists, Tuples, Keyword lists, Maps, Sets</p><ul><li>Data in elixir is immutable. So how do work adding, deleting, changing data in collections?</li><li>What is the difference between string and character list?</li><li>What is the difference between lists and tuples?</li><li>What is the difference between Keyword List and Maps?</li><li>How Elixir (Erlang) Maps works? What is the difference in implementation for maps with fewer than 32 keys and maps with 32 keys or beyond?</li><li>Common academic knowledge: hash tables, binary trees, self-balances binary trees. What is General Balanced Tree?</li><li>What is the difference between struct and map?</li></ul><p><strong>Special Data Types:</strong> <a href="https://www.erlang.org/doc/reference_manual/data_types.html#fun">Function</a>; <a href="https://www.erlang.org/doc/reference_manual/data_types.html#port-identifier">Port</a>, <a href="https://www.erlang.org/doc/reference_manual/data_types.html#reference">Reference</a>, <a href="https://www.erlang.org/doc/reference_manual/data_types.html#pid">Pid</a> — what those terms are represent?</p><p><strong>Links with good articles for experienced developers:</strong></p><p><a href="https://inquisitivedeveloper.com/lwm-elixir-6/">Elixir — Data Types</a> — how it works and implemented, with details</p><p><a href="https://www.openmymind.net/Elixir-A-Little-Beyond-The-Basics-Part-1-lists/">Lists, a little beyond the basics</a></p><p><a href="https://www.openmymind.net/Elixir-A-Little-Beyond-The-Basics-Part-3-maps/">Maps, a little beyond the basics</a></p><p><a href="https://www.honeybadger.io/blog/elixir-memory-structure/">Elixir Memory Structure</a> — I strongly recommend to read this article, since many interview question about datatypes related to memory management</p><p><a href="https://www.educative.io/answers/what-is-struct-versus-map-in-elixir">Struct vs Map</a></p><h3>Pattern matching</h3><p>Pattern matching — how it works? What operator used for it? How to destruct the value form complex data types? What happens when variable is changes to new value? How it works?</p><p>Pin operator — how it works? Is there an option to assign to value to pinned variable?</p><p>Link helps to understand: <a href="https://medium.com/@Julien_Corb/understand-the-pin-operator-in-elixir-a6f534d865a6">Pin operator</a></p><h3>Recursions</h3><ul><li>Classic recursive calls vs tail recursive calls</li><li>What are benefits of tail recursion? Head-tail list handling</li></ul><h3>Concurrency and OTP</h3><ul><li>Concurrence vs Parallel execution: what is the difference?</li><li>send and receive functions</li><li>spawn, spawn_link, monitors</li><li>What is OTP?</li><li>GenServer: synchronous functions, asynchronous functions, state</li><li>OTP Supervisors: configuration, strategies. For what cases each of strategies suits? How do each strategy restart children? Child specification: how it defines behavior? Is there an option to start Supervisor dynamically? Is there an option to add child dynamically? Supervisor Trees examples.</li><li>What happens, if GenServer receives too many messages and the process mailbox continues growing?</li></ul><p>Old but gold pdf <a href="http://lampwww.epfl.ch/resources/lamp/teaching/advancedCompiler/2004/slides/ImplementationOfConcurrency_slides.pdf">slides</a> that explains concurrency in Erlang for beginners and even middle developers</p><p>GenServer <a href="https://hexdocs.pm/elixir/1.12/GenServer.html">doc</a>, Supervisor <a href="https://hexdocs.pm/elixir/1.12/Supervisor.html#content">doc</a></p><h3><strong>BIFs and NIF</strong></h3><ul><li>Native Implemented Functions (NIFs) — what is it?</li><li>Built-in Functions (BIFs) — what is it?</li><li>NIFs and concurrency: how it works? Are NIFs are blocking? What happens with all processes, if NIF, called in one process, takes about few seconds?</li><li>What happens with process, that calls NIF and entire VM, if NIF fails?</li></ul><p><a href="https://www.erlang.org/doc/man/erl_nif.html">NIF doc</a></p><h3><strong>Storage</strong></h3><p>Elixir (erlang) processes are memory isolated. But there are still an options to share data between processes. And it is not only GenServer state.</p><ul><li><a href="https://elixirschool.com/en/lessons/storage/ets">ETS</a> and DETS: what is it, what is the difference? How data is stored and managed?</li><li><a href="https://hexdocs.pm/redix/Redix.html">Mnesia</a> — what is it? What is the difference between DETS?</li><li><a href="https://hexdocs.pm/cachex/Cachex.html">Cashex</a> library — what is the benefits of usage over simple GerServer state?</li></ul><h3>Garbage Collention</h3><ul><li>Erlang garbage collections: how it works?</li><li>What is the main feature on GC in Erlang VM?</li><li>Is it blocking? Is there “stolen time” in Erlang VM during GC</li><li>What The difference between Elixir GC and Java or C# GC?</li><li>Process Control Block, Stack and Heap — for what each part is responsible?</li></ul><p><a href="https://hamidreza-s.github.io/erlang%20garbage%20collection%20memory%20layout%20soft%20realtime/2015/08/24/erlang-garbage-collection-details-and-why-it-matters.html">Erlang Garbage Collection Details and Why It Matters</a> — great article I strongly recommend to read. It explains how Garbage Collection in Erlang VM works under the hood</p><p><a href="https://www.slideshare.net/PremSanil/cpu-steal-time-184713897">CPU “steal time” common definitions</a></p><h3>Bonus: Academic Historical Questions</h3><p>Here is 20+ academic question that often asked for trainee, junior and sometimes middle positions: Who invented Erlang? Where does Erlang syntax come from ? Who invented Elixir? What does soft realtime mean? On what purposes elixir what created?</p><p><a href="https://www.erlang.org/faq/academic.html">official erlang site</a>, <a href="https://scriptdrop.co/2020/02/25/the-history-of-elixir-a-programming-primer/">elixir history</a></p><ul><li>Who use elixir?</li></ul><p>Well, there is so many companies — from small startups to giants:</p><p>Banking giants, betting companies, popular messengers and dating apps with millions active users per day and hundreds thousands RPS (requests per seconds), booking sites, tech giants handles high load data streams from sensors, from use elixir and erlang.<br><a href="https://codesync.global/media/successful-companies-using-elixir-and-erlang/">Companies using erlang and elxir</a></p><p>In Vic.ai, <a href="https://www.vic.ai/about-us">we</a> use Elixir for intelligence accounting</p><p><a href="https://www.vic.ai/">Accounting AI software for faster invoice processing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb5d9aa0f18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elixir Phoenix + Vault: simple guide with libvault and config provider]]></title>
            <link>https://medium.com/@marinakrasnovatr81/elixir-phoenix-vault-simple-guide-with-libvault-and-config-provider-f3a9267040c2?source=rss-e7c3a3856aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3a9267040c2</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[elixirlang]]></category>
            <category><![CDATA[phoenix]]></category>
            <dc:creator><![CDATA[Maryna Shabalina]]></dc:creator>
            <pubDate>Mon, 11 Oct 2021 22:18:54 GMT</pubDate>
            <atom:updated>2021-10-18T01:20:55.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAepK7QsgWleRybZnd0AvA.jpeg" /></figure><p><a href="https://www.vaultproject.io/">Vault</a>, the tool for managing secret data, passwords and credentials, becomes more and more popular now, so here is a simple guide for writing <a href="https://elixir-lang.org/">elixir</a> phoenix application which connects to vault for getting secrets such as database URL, third-party services credentials, etc with <a href="https://github.com/matthewoden/libvault">libvault</a>.</p><p>I am going to use elixir <a href="https://hexdocs.pm/elixir/master/Config.Provider.html">config provider</a> file for release, ’cause I don’t need to use Vault for test and dev environment, Vault is used in released app only.</p><p>To authenticate elixir application in vault, vault’s <a href="https://www.vaultproject.io/docs/auth/kubernetes">kubernetes authentication</a> is used.</p><p>Create the back-end application, set id for future tables UUID type:</p><pre>$ mix phx.new hello_vault — module HV — no-html — no-assets — no-gettext — no-dashboard — no-live — no-mailer — binary-id</pre><pre>$ cd hello_vault</pre><p>Now, <a href="https://hexdocs.pm/elixir/master/Config.Provider.html">config provider</a> for release should be configured in <em>mix.ex. </em>This<em> </em>is done for using vault only when application release run and use config files <em>dev.exs, test.exs</em> during local development:</p><pre># mix.ex<br>defmodule HV.MixProject do<br>use Mix.Project</pre><pre>  def project do<br>    [<br>      ...<br>      releases: [<br>        hello_vault: [<br>          config_providers: [<br>            {HV.ConfigProviders.VaultConfigProvider, &quot;/path/to/vault/token&quot;}<br>          ],<br>          version: &quot;0.1.0&quot;,<br>          applications: [hello_vault_web: :permanent],<br>        ]<br>      ]<br>    ]<br>  end</pre><pre>...</pre><p>Add <a href="https://github.com/teamon/tesla">tesla</a> and <a href="https://github.com/matthewoden/libvault">libvault</a> <em>{:libvault, “~&gt; 0.2.3”} </em>to deps in <em>mix.config </em>and set config provider file:</p><pre>defmodule HV.MixProject do<br>  use Mix.Project<br>  <br>   defp deps do<br>    [<br>      ...<br>      {:libvault, &quot;~&gt; 0.2.3&quot;},<br>      {:tesla, &quot;~&gt; 1.3.0&quot;}<br>    ]<br>  end</pre><pre>...</pre><pre>end</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a82aae6bd8fd5f1ec9327241db1fae6/href">https://medium.com/media/9a82aae6bd8fd5f1ec9327241db1fae6/href</a></iframe><p>Now, let’s create <em>VaultConfigProvider</em> module:</p><pre>$ mkdir lib/hello_vault/config_providers/<br>$ touch lib/hello_vault/config_providers/vault_config_provider.ex</pre><p>Time to add vault configuration in <em>vault_config_provider.ex:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd9149dbdb2c40ec70503317df6e1d59/href">https://medium.com/media/dd9149dbdb2c40ec70503317df6e1d59/href</a></iframe><blockquote>Config providers are typically used during releases to load external configuration while the system boots. This is done by starting the VM with the minimum amount of applications running, then invoking all of the providers, and then restarting the system</blockquote><p>So, application restarts with vault configuration</p><p>Variable <em>vault_secrets</em> in line 30 is a map. Vault allows to keep json and arrays in secret storage, so there is no need to keep everything as string parse csv to array or json format.</p><p>First argument, config, is configuration that comes from <em>config.ex.</em></p><p>Notice, that applications <em>jason</em>, <em>hackney</em> and <em>tesla</em> should be started before you are trying to connect and authorize in Vault (lines 12-14 in example)</p><p>Function <em>fetch_vault_env!</em> was added to shut down application in case critical settings is missed.</p><p>Release application:</p><pre>$ mix release hello_vault</pre><p>Next ENV variables should be set in deployment:</p><pre>VAULT_ADDR #required<br>VAULT_K8S_ROLE #required<br>VAULT_PREFIX #required<br>VAULT_ENV_PATH #optional<br># ***<br>/path/to/vault/token is path where file that contains vault token is placed</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3a9267040c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>