<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Story Melange</title>
<link>https://www.storymelange.com/</link>
<atom:link href="https://www.storymelange.com/index.xml" rel="self" type="application/rss+xml"/>
<description>Real stories of building systems and leading teams, from quick espresso shots to slow pours.</description>
<generator>quarto-1.8.26</generator>
<lastBuildDate>Fri, 21 Nov 2025 00:00:00 GMT</lastBuildDate>
<item>
  <title>Why Kubernetes Autoscaling Matters for ML and Embedded Developers</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/kubernetes/why-kubernetes-autoscaling-matters-for-ml-and-embedded-developers.html</link>
  <description><![CDATA[ 




<section id="motivation" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="motivation"><span class="header-section-number">1</span> Motivation</h2>
<p>For ML and embedded engineers, deployment technologies such as Kubernetes can feel distant. But the scaling behavior increasingly shapes how modern products are not only run, but how they are developed; think OTA updates, remote fleet monitoring, and model serving.</p>
<p>In the last weeks I built a small Kubernetes autscaling demo.</p>
<p>My aim: understand better how Horizontal Pod Autoscaling (HPA) behaves under real and chaotic load.</p>
<p>Many Kubernetes explanations stay <a href="https://medium.com/@rphilogene/what-is-kubernetes-what-you-need-to-know-as-a-developer-674af25e3947">conceptual</a> or stop at <a href="https://spacelift.io/blog/kubernetes-tutorial">the starting of pods</a>.</p>
<p>I wanted something you can stress and watch adapt in real time.</p>
</section>
<section id="the-demo" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="the-demo"><span class="header-section-number">2</span> The demo</h2>
<p>My demo model is a tiny web service with a CPU-burning backend in C++. A Typescript frontend simulates impatient users who repeatedly press <code>F5</code>.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/kubernetes/overview_gui.jpg" class="img-fluid figure-img"></p>
<figcaption>Frontend to adjust user number and load, see video at the end of post.</figcaption>
</figure>
</div>
<p>When the backend gets overloaded, Kubernetes starts creating more replicas; when the load drops, the cluster scales down. You can see the load rise, the scaling events and even scaling oscillations under chaotic load.</p>
</section>
<section id="insights" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="insights"><span class="header-section-number">3</span> Insights</h2>
<p>Infrastructure is not my main leg. My top 4 insights from the point of view of an ML/embedded developer.</p>
<section id="scaling-is-delayed-by-design" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="scaling-is-delayed-by-design"><span class="header-section-number">3.1</span> Scaling is delayed by design</h3>
<p>Even with aggressive scaling settings, the <code>HPA</code> decisions trail the user load. The information flow is <code>kubelet</code>-&gt; <code>Metrics Server</code>-&gt; <code>HPA</code>, each taking multiple seconds. This avoids reacting to instantaneous load spikes.</p>
</section>
<section id="cpu-based-autoscaling-is-sensitive-to-user-behavior" class="level3" data-number="3.2">
<h3 data-number="3.2" class="anchored" data-anchor-id="cpu-based-autoscaling-is-sensitive-to-user-behavior"><span class="header-section-number">3.2</span> CPU-based autoscaling is sensitive to user behavior</h3>
<p>My earliest attempt was to launch another request after receiving the response. This just overwhelms the CPU with requests, and scaling goes through the roof. I had to add a realistic “think time” to reflect what is actually happening in real life. Press <code>F5</code>, watch the content, only then press <code>F5</code> again. Another option would be hard rate limits on the server side.</p>
</section>
<section id="percentage-based-scaling-is-trickier-than-scale-by-one-scaling" class="level3" data-number="3.3">
<h3 data-number="3.3" class="anchored" data-anchor-id="percentage-based-scaling-is-trickier-than-scale-by-one-scaling"><span class="header-section-number">3.3</span> Percentage based scaling is trickier than scale by one scaling</h3>
<p>For up-scaling, I used an increase-by-one-pod rule. For down-scaling, I allowed withdrawing as many pods as quickly as possible. My thinking: too-slow down-scaling wastes resources. The surprise: aggressive scaling leads to oscillations in the pod numbers.</p>
</section>
<section id="the-demo-mirrors-real-system-behavior-surprisingly-well" class="level3" data-number="3.4">
<h3 data-number="3.4" class="anchored" data-anchor-id="the-demo-mirrors-real-system-behavior-surprisingly-well"><span class="header-section-number">3.4</span> The demo mirrors real system behavior surprisingly well</h3>
<p>Despite its simplicity, the demo showed aspects that we can also experience in real production settings: the morning user burst, ill-timed lunchtime updates, traffic spikes and scaling overshoot.</p>
</section>
</section>
<section id="try-it-yourself" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="try-it-yourself"><span class="header-section-number">4</span> Try it yourself</h2>
<p>If you want to experiment with autoscaling to understand better what is happening on your projects Kubernetes cluster, full code, configurations can be found here:</p>
<p><a href="https://github.com/dolind/demo_autoscale">https://github.com/dolind/demo_autoscale</a></p>
<p>The demo is a reminder that infrastructure knowledge is no longer optional. Even for non-cloud or ML-heavy teams, a bit of systems intuition goes a long way.</p>
<p>This project is done. I’ll be shifting back to ML-focused work now.</p>
</section>
<section id="bonus-material" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="bonus-material"><span class="header-section-number">5</span> Bonus Material</h2>
<section id="explore-the-demo-by-video" class="level3" data-number="5.1">
<h3 data-number="5.1" class="anchored" data-anchor-id="explore-the-demo-by-video"><span class="header-section-number">5.1</span> Explore the demo by Video</h3>
<p>If you do not want to run the demo yourself, here is a full recording of a session. Yellow lines indicate a rise of user numbers, greed pod up-scaling, red down-scaling.</p>
<video width="1024" controls="">
<source src="out.mp4" type="video/mp4">
</video>
</section>
<section id="technical-deep-dive" class="level3" data-number="5.2">
<h3 data-number="5.2" class="anchored" data-anchor-id="technical-deep-dive"><span class="header-section-number">5.2</span> Technical deep dive</h3>
<p>A full technical deep dive — including setup, architecture, and detailed scaling analysis — is available <a href="../../../posts/projects/kubernetes/kubernetes-for-the-seasoned-noncloud-software-developer.html">here</a>.</p>


</section>
</section>

 ]]></description>
  <category>Software Engineering</category>
  <category>Applied Engineering</category>
  <guid>https://www.storymelange.com/posts/projects/kubernetes/why-kubernetes-autoscaling-matters-for-ml-and-embedded-developers.html</guid>
  <pubDate>Fri, 21 Nov 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>C++ in your Browser. Is WebAssembly worth the effort?</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/webassembly/c-in-your-browser-is-webassembly-worth-the-effort.html</link>
  <description><![CDATA[ 




<section id="c-for-the-masses" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="c-for-the-masses"><span class="header-section-number">1</span> C++ for the Masses</h2>
<p>C++ is often treated as a legacy programming language. Or something you only need when you are worried about low level system performance. With WebAssembly, that boundary is shifting.</p>
<p>The benefit of WebAssembly: free client side compute. You wrap you costly backend logic and ship it to the client.</p>
<p>While I have been familiar with the idea, I wanted to see how this turns out in practice.</p>
<p>Spoiler. Yes compute is free, development time isn’t. <a href="https://delicate-limit-0c06.docachaorg-132.workers.dev/">You can see the solution here</a></p>
</section>
<section id="the-color-contrast-grid" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="the-color-contrast-grid"><span class="header-section-number">2</span> The color contrast grid</h2>
<p>I built a small program that arrangers colors in a grid to maximize contrast between neighbors. While simple, the search space is fast and optimization algorithms are difficult to implement.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/webassembly/colors.jpeg" class="img-fluid figure-img"></p>
<figcaption>colors.jpeg</figcaption>
</figure>
</div>
<p>Besides brute force, I tried hill climbing and simulated annealing. But the problem is actually a little bit more complex than I thought and would need more time.</p>
<p>Therefore, I focused on straightforward C++ improvement: inlining of functions, avoiding to reallocate memory inside loops and lookup tables. The speedups are between 15% to 30%.</p>
</section>
<section id="getting-c-data-into-the-browser-window" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="getting-c-data-into-the-browser-window"><span class="header-section-number">3</span> Getting C++ Data into the Browser Window</h2>
<p>WebAssembly offers a way to run high-performance code safely in the browser. Using Emscripten, I compiled the solver into a module and connected it to a small TypeScript UI.</p>
<p><strong>Biggest lesson learned: complex objects cannot cross the boundary by value.</strong></p>
<p>Simply evoking call by value functions of complex objects lead to memory leaks. We can use shared memory buffers to avoid these leaks.</p>
<p>We need</p>
<ul>
<li>a fixed buffer in Typescript</li>
<li>a C++ function to fill the buffer</li>
<li>another Typescript function to read from it</li>
</ul>
<p>I implemented this using an additional webworker, as I run several grids at the same time</p>
<p><em>Buffer declaration in the main.ts</em></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode typescript code-with-copy"><code class="sourceCode typescript"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// We first declare the buffer and allocate memory</span></span>
<span id="cb1-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> canvasRGBBuffers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">SharedArrayBuffer</span>[] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>  </span>
<span id="cb1-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> canvasRGBViews<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Uint8Array</span>[] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-4"></span>
<span id="cb1-5">canvasRGBBuffers[canvasIndex] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">new</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">SharedArrayBuffer</span>(dim <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dim <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> </span>
<span id="cb1-6">canvasRGBViews[canvasIndex] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">new</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Uint8Array</span>(rgbSAB)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p><em>C++ Function</em></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode c++ code-with-copy"><code class="sourceCode cpp"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// In my example I have a global object storing pointers to the algorithms</span></span>
<span id="cb2-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>unordered_map<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>unique_ptr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>Algorithm<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> algos<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-3"></span>
<span id="cb2-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// This is the actual function that reads the grid</span></span>
<span id="cb2-5"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">void</span> export_grid_rgb<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>uint8_t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> max_len<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// get grid from the algorithm</span></span>
<span id="cb2-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">auto</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>algo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>algos<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>at<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">);</span>  </span>
<span id="cb2-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">auto</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>grid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> algo<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>getBestGrid<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">();</span></span>
<span id="cb2-9"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span></span>
<span id="cb2-10"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-11"></span>
<span id="cb2-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Emscripten Binding to export to typescript</span></span>
<span id="cb2-13">function<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"export_grid_rgb"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>  </span>
<span id="cb2-14">         optional_override<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">([](</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uintptr_t</span> ptr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> len<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>  </span>
<span id="cb2-15">             <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">auto</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>buf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">reinterpret_cast</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>uint8_t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*&gt;(</span>ptr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">);</span>  </span>
<span id="cb2-16">             export_grid_rgb<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> buf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> len<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">);</span>  </span>
<span id="cb2-17">         <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">})</span>  </span>
<span id="cb2-18"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">);</span></span></code></pre></div></div>
<p><em>Typescript Invocation in the worker</em></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode typescript code-with-copy"><code class="sourceCode typescript"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Receive callback in worker, receives the memory and then forwards the pointer</span></span>
<span id="cb3-2">self<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">onmessage</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> (ev) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {  </span>
<span id="cb3-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> {  </span>
<span id="cb3-4">        sab<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>   </span>
<span id="cb3-5">    } <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ev<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> createModule <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span>(scriptUrl))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">default</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>  </span>
<span id="cb3-7">wasmModule <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">createModule</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-8"></span>
<span id="cb3-9"></span>
<span id="cb3-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> sharedRGB <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">new</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Uint8Array</span>(sab)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> rgbLen <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sharedRGB<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>  </span>
<span id="cb3-12"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> wasmRGBPtr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> wasmModule<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">_malloc</span>(rgbLen)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-13">wasmModule<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">export_grid_rgb</span>(canvasIndex<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> wasmRGBPtr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> rgbLen)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-14">}</span></code></pre></div></div>
<p><em>Typescript main</em></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode typescript code-with-copy"><code class="sourceCode typescript"><span id="cb4-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Send command in main</span></span>
<span id="cb4-2">worker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">postMessage</span>({  </span>
<span id="cb4-3">    sab<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> canvasRGBBuffers[canvasIndex]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>  </span>
<span id="cb4-4">})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-5"></span>
<span id="cb4-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Receive callback in main only uses the view on the buffer</span></span>
<span id="cb4-7">worker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">onmessage</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (ev) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {  </span>
<span id="cb4-8"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span></span>
<span id="cb4-9">  </span>
<span id="cb4-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> rgbView <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> canvasRGBViews<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>  </span>
<span id="cb4-11">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">drawGridFromRGB</span>(canvas<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> rgbView<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> dim)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-12">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span></span>
<span id="cb4-13">}</span></code></pre></div></div>
</section>
<section id="webassembly-limitations" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="webassembly-limitations"><span class="header-section-number">4</span> Webassembly Limitations</h2>
<section id="resources" class="level3" data-number="4.1">
<h3 data-number="4.1" class="anchored" data-anchor-id="resources"><span class="header-section-number">4.1</span> Resources</h3>
<p>I discovered there are resource limitations.</p>
<ul>
<li>16GB of memory</li>
<li>Main thread wasm must yield back every 30 odd seconds to avoid dialogs</li>
<li>Worker threads may be put to sleep if window not in focus</li>
</ul>
<p>However, that is the size of a small cloud virtual PC. Another aligned technology that allows the usage of gpu is WebGPU. For an intro to both, see <a href="https://developer.chrome.com/blog/io24-webassembly-webgpu-1">this</a>.</p>
<p>Currently GPU access in Webassembly is only possible via the JS-apis. But once direct access is possible, there could be even better performance gains.</p>
</section>
<section id="webhosting" class="level3" data-number="4.2">
<h3 data-number="4.2" class="anchored" data-anchor-id="webhosting"><span class="header-section-number">4.2</span> Webhosting</h3>
<p>To use the webworkers, we require threads. And to use those we need special CORS headers. These headers are not available on Github Pages, why I needed to host the project on Cloudflare. For hobbiest, that just one extra layer.</p>
</section>
</section>
<section id="summary" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="summary"><span class="header-section-number">5</span> Summary</h2>
<p>As you can see getting something to work in WebAssembly is requires quite a lot of boilerplate code. As the technology is less used LLMs are less of a help. While I used LLMs to create this examples a lot of manual effort was necessary.</p>
<p>For many prototypes, this effort would be better directed into the value adding activities.</p>
<p>This leads to a dilemma: say you have a business idea that would work well if the cloud compute would not be ruining the business case. WebAssembly could make it fly, but to get to working prototype you would be better off developing a FastApi Backend with Python and some pybind bindings for the C++ part.</p>
<p>Some Example Ideas</p>
<ul>
<li>Scientific compute with free tier computations</li>
<li>Client Side ML of SLMs or voice transcription</li>
</ul>
<p>But I guess that is always the case with infrastructure technology. There is always an upfront cost that needs to be paid.</p>
<hr>
<p>Source Code is available <a href="https://github.com/dolind/color_contrast_wasm">here</a></p>
<p>Project is live <a href="https://broad-band-5ac8.docachaorg-132.workers.dev/">here</a></p>


</section>

 ]]></description>
  <category>C++</category>
  <category>Applied Engineering</category>
  <category>Software Engineering</category>
  <guid>https://www.storymelange.com/posts/projects/webassembly/c-in-your-browser-is-webassembly-worth-the-effort.html</guid>
  <pubDate>Wed, 19 Nov 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Writing, Doing, and Building an ML Productivity Pipeline</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/writing-doing-and-building-an-ml-productivity-pipeline.html</link>
  <description><![CDATA[ 




<section id="two-ways-to-learn-new-software-technologies" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="two-ways-to-learn-new-software-technologies"><span class="header-section-number">1</span> Two ways to learn new software technologies</h2>
<p>I tend to learn in two modes. Sometimes I rush in: open the editor, copy a snippet, patch things together until it runs. Other times I slow down: write as I go, explain decisions, leave a trail I can follow later. The first approach builds momentum while the second builds understanding. The hard skill is knowing when to switch.</p>
<p>Working with modern machine learning tools like Kaggle notebooks, Hugging Face Spaces, Gradio, I wanted a workflow that remains flexible. While writing can feel slower in the moment it clarifies thinking and prevents rework. In contrast, the speedy approach is energizing; yet without notes I quickly get lost.</p>
<p>The solution, for me, is a simple pipeline where exploration, implementation, and communication are part of the same loop.</p>
<p>This post outlines that loop.</p>
<p>I drafted much of it while building a small computer-vision project: the <a href="https://www.storymelange.com/posts/projects/cheese_classifier/meet-the-cheese.html?utm_source=chatgpt.com"><strong>cheese classifier</strong></a>.</p>
</section>
<section id="the-pipeline-at-a-glance" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="the-pipeline-at-a-glance"><span class="header-section-number">2</span> The pipeline at a glance</h2>
<ol type="1">
<li>Problem definition and model training</li>
<li>App for inference of the model</li>
<li>Writing and publishing</li>
</ol>
<p>In practice, this linear process is done in cycles. Training informs the demo, the demo shapes the story, the story clarifies what to train next.</p>
<section id="stage-1-problem-definition-and-model-training" class="level3" data-number="2.1">
<h3 data-number="2.1" class="anchored" data-anchor-id="stage-1-problem-definition-and-model-training"><span class="header-section-number">2.1</span> Stage 1: problem definition and model training</h3>
<p>Most projects begin with a problem statement and end with a model. I often do the reverse when I’m learning. I try a new tool or method first which I find interesting. Then I look for a problem it can help to solve. A word of warning: that approach is definitely not how you should build a successfully commercial product</p>
<p>Machine learning splits cleanly into <strong>training</strong> and <strong>inference</strong>. Inference behaves like ordinary software, which consists of functions with inputs and outputs. Training is exploratory: choices about data, features, and objectives evolve as you learn. Without a record, it’s easy to lose your course.</p>
<p>This is where notebooks earn their place. Jupyter notebooks let code, results, and reasoning sit together. If kept in a lab style with comments, you can see what changed and why, when refering back to them.</p>
<p>However, raw notebooks don’t play well with Git. Tools like <code>nbdev</code> help by turning notebooks into maintainable modules. When you work on Kaggle data, sometimes it can be better to run your code locally, or another remote environment. I use a small environment-check snippets to let notebooks run outside or in Kaggle; full code for <a href="https://gist.github.com/dolind/ce4d2a5431aa85f294263995713a0206">kaggle auth</a> and <a href="https://gist.github.com/dolind/42518f35ea70c590fed82169bc223929">data import</a>.</p>
</section>
<section id="stage-2-building-the-app" class="level3" data-number="2.2">
<h3 data-number="2.2" class="anchored" data-anchor-id="stage-2-building-the-app"><span class="header-section-number">2.2</span> Stage 2: building the app</h3>
<p>What better badge for your portfolio than making a small demo into a public one. I use <strong>Gradio</strong> hosted on Hugging Face to wrap inference in a minimal interface.</p>
<p>The app shifts the mindset from internal exploration to external communication.</p>
<p>A public demo also sets a direction for the write-up. If a reader can click and see the behavior, the post can focus on choices and trade-offs rather than screenshots. The reverse is also true: no demo, then I use screenshots in the post.</p>
</section>
<section id="stage-3-writing-and-publishing" class="level3" data-number="2.3">
<h3 data-number="2.3" class="anchored" data-anchor-id="stage-3-writing-and-publishing"><span class="header-section-number">2.3</span> Stage 3: writing and publishing</h3>
<p>Writing closes the loop. It converts a set of experiments into a sequence of decisions. As in all good research writing the order might not be the same. I publish with <strong>Quarto</strong> because it treats Markdown, Jupyter, and Git automatically. The pipeline feels coherent rather than stitched together. <a href="../posts/blogging-with-quarto.html">See also my other article</a>.</p>
<p>There are two workable ways to organize files:</p>
<ul>
<li><p><strong>Single repository:</strong> everything, experiments, app, and post, lives together: simple to navigate, slightly messier over time.</p></li>
<li><p><strong>Separate repositories with selective syncing:</strong> experiments and app live in their own project directories. Curated notebooks, flow into the blog: cleaner long term, but requires a small amount of helper scripts.</p></li>
</ul>
<p>I use the second approach. In my blog all imported files live under <code>projects/</code> sometimes with subdirectories. When a notebook is worth sharing, I redact it in the original repo and sync it into the blog repository. While this means I loose some linking ability in my notes app <strong>Obsidian</strong>, It keeps the writing close to the work.</p>
</section>
</section>
<section id="summary-snippets" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="summary-snippets"><span class="header-section-number">3</span> Summary snippets</h2>
<ul>
<li><p><strong>Decide the mode before you start:</strong> sprint when you need momentum; write when choices are piling up and you can’t see the path.</p></li>
<li><p><strong>Document decisions in Jupyter notebooks, not everything:</strong> note what changed, why it changed, and what you learned.</p></li>
<li><p><strong>Treat the demo as a learning tool:</strong> if the interface feels confused, the model probably is; fixing the demo often clarifies the model.</p></li>
<li><p><strong>Keep writing near the code:</strong> whether you use one repo or two, reduce the distance between experiments and narrative.</p></li>
<li><p><strong>Publish smaller; publish sooner:</strong> a short post attached to a working demo beats everything.</p></li>
</ul>
</section>
<section id="conclusion" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="conclusion"><span class="header-section-number">4</span> Conclusion</h2>
<p>Paraphrase from everyone’s favourite ChatBot: Productivity isn’t doing more; it’s designing loops that help you learn while you work.</p>


</section>

 ]]></description>
  <category>Machine Learning</category>
  <category>Knowledge Work</category>
  <category>Software Engineering</category>
  <guid>https://www.storymelange.com/posts/writing-doing-and-building-an-ml-productivity-pipeline.html</guid>
  <pubDate>Tue, 11 Nov 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>The Hidden Cost of “Magic” Schemas</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/recipescanner/the-hidden-cost-of-magic-schemas.html</link>
  <description><![CDATA[ 




<section id="the-allure-of-auto-generated-schemas" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="the-allure-of-auto-generated-schemas"><span class="header-section-number">1</span> The allure of auto-generated schemas</h2>
<p>Every engineer eventually meets the siren song of the “single source of truth.” <strong>DRY</strong>, the holy grail of software engineering.</p>
<p>Don’t Repeat Yourself! Then why define models twice in a backend app? Once for the database, once for the API? Why not auto-generate definitions of one from the other?</p>
<p>I thought the same while building my recipe scanner app.</p>
<p>With a neat utility, I could turn my SQLAlchemy model into a Pydantic schema in one line.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">RecipeOut <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sqlalchemy_to_pydantic(RecipeORM)</span></code></pre></div></div>
<p>It worked beautifully… until it didn’t.</p>
<p>What started as convenience quietly eroded my trust boundaries. For a deeper explanation of trust boundaries see <a href="../../../posts/projects/recipescanner/when-to-use-pydantic-in-your-app.html">my post Pydantic vs.&nbsp;Dataclass</a>.</p>
<p>A harmless migration broke the entire API:</p>
<ul>
<li>A new internal column appeared in the public OpenAPI docs.<br>
</li>
<li>A new nullable database field caused UI validation failures.<br>
</li>
<li>Even lazy-loaded relationships started firing extra queries during serialization.</li>
</ul>
<p>Clear symptoms of automation not being useful but hollowing out your design.</p>
<p>For early prototypes this shortcut might be acceptable. But how do you know when to stop?</p>
<p>The rest of this post explores what to do instead.</p>
</section>
<section id="design-the-data-flow-of-your-application" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="design-the-data-flow-of-your-application"><span class="header-section-number">2</span> Design the data flow of your application</h2>
<section id="the-walking-skeleton-mindset" class="level3" data-number="2.1">
<h3 data-number="2.1" class="anchored" data-anchor-id="the-walking-skeleton-mindset"><span class="header-section-number">2.1</span> The “walking-skeleton” mindset</h3>
<p>Define the end-to-end data flow as one vertical slice through the system.</p>
<p>In our case: upload → pipeline → DB → JSON → UI.</p>
<ol type="1">
<li><p><strong>Vocabulary first</strong><br>
List the nouns (“Recipe”, “OCR Block”, “Nutrition”) and relationships.</p></li>
<li><p><strong>Minimal DTOs</strong><br>
Hand-write just enough Pydantic schemas for that first slice.</p></li>
<li><p><strong>Stub everything else</strong><br>
Fake OCR, canned LLM responses, in-memory cache.</p></li>
<li><p><strong>Ship &amp; test</strong><br>
When the UI renders, your contract is real.</p></li>
<li><p><strong>Iterate</strong><br>
Replace stubs with real logic.</p></li>
</ol>
</section>
<section id="controlled-divergence-incoherence" class="level3" data-number="2.2">
<h3 data-number="2.2" class="anchored" data-anchor-id="controlled-divergence-incoherence"><span class="header-section-number">2.2</span> Controlled Divergence ≠ Incoherence</h3>
<p>It’s healthy for the <em>storage</em> model and the <em>API</em> schema to diverge. What is needed for database indexing and searching might not even be necessary in your internal services, yet alone any public API.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Layer</th>
<th>Optimised For</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Database</strong></td>
<td>Joins, constraints, indexes, archival columns</td>
<td><code>recipe_version_id</code>, <code>deleted_at</code>, <code>INT2</code> for tiny enums</td>
</tr>
<tr class="even">
<td><strong>API / Pipeline</strong></td>
<td>Clear intent, validation, front-end friendliness</td>
<td><code>ingredients: List[str]</code>, camelCase, enum labels</td>
</tr>
</tbody>
</table>
<p>You can still auto convert from the database entry and drop every additional field, <code>dto = RecipeRead.from_orm(orm_obj)</code>) . Defintions stay <strong>coherent</strong>, but are not <strong>coupled</strong>. Or use <code>model_dump()</code> to write a JSON blob of the pydantic model to the database, if you must store it.</p>
</section>
<section id="triplet-schemas-create-update-read" class="level3" data-number="2.3">
<h3 data-number="2.3" class="anchored" data-anchor-id="triplet-schemas-create-update-read"><span class="header-section-number">2.3</span> Triplet Schemas: Create / Update / Read</h3>
<p>I thought that the triplet schema appraoch utter redundancy when starting to develop my backend. Turns out it is not. You will be thankfully for any <code>Optional</code> field. And it is nice to not fill in fake ids, which are overwritten by the database on creation of a recipe, this removes clutter from your code.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> RecipeCreate(BaseModel):</span>
<span id="cb2-2">    title: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>               <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># required</span></span>
<span id="cb2-3">    calories: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>          </span>
<span id="cb2-4"></span>
<span id="cb2-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> RecipeUpdate(BaseModel):</span>
<span id="cb2-6">    title: Optional[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>]     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># patch semantics</span></span>
<span id="cb2-7">    calories: Optional[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>]</span>
<span id="cb2-8"></span>
<span id="cb2-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> RecipeRead(BaseModel):</span>
<span id="cb2-10">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb2-11">    title: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb2-12">    calories: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span></span></code></pre></div></div>
<p>For naming convention, pick a convention early and stick to it. Even if it feels verbose, teammates (and future you) will navigate the repo with ease.</p>
<p><strong>Further Benefits:</strong></p>
<ul>
<li>Make-fields-required-later without breaking PATCH routes.</li>
<li>Disallow mutation of field <code>id</code> simply by omitting it in <code>Update</code>.</li>
<li>OpenAPI docs become self-explanatory.</li>
</ul>
</section>
<section id="wrapper-dtos-keep-lists-clean" class="level3" data-number="2.4">
<h3 data-number="2.4" class="anchored" data-anchor-id="wrapper-dtos-keep-lists-clean"><span class="header-section-number">2.4</span> Wrapper DTOs Keep Lists Clean</h3>
<p>Having lists or multiple fields in your routes makes debugging in your browser harder.</p>
<p>Use a wrapper. Here is pagination of recipe search results:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> RecipePage(BaseModel):</span>
<span id="cb3-2">    items: List[RecipeRead]</span>
<span id="cb3-3">    total: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb3-4">    skip:  <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb3-5">    limit: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb3-6">    has_more: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span></span></code></pre></div></div>
<p>This pattern lets you extend api complexity without disturbing the inner DTO. And of course there is no connection to the database schema.</p>
</section>
</section>
<section id="final-take-aways" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="final-take-aways"><span class="header-section-number">3</span> Final Take-aways</h2>
<ul>
<li><p>Automatic models are a scaffold, not a contract. Use only them only in prototypes.</p></li>
<li><p>Model vocab first, ship a thin end to end slice, iterate.</p></li>
<li><p>Embrace <strong>purposeful divergence</strong> between DB and API.</p></li>
<li><p>Redundant names and schema triplets pay dividends in clarity, validation, and future refactors.</p></li>
</ul>
<p>Good systems age well not because they’re perfectly DRY, but because their trust boundaries are deliberate.<br>
Writing your schemas by hand is an act of intent. You decide what is exposed in the API and what remains inside the backend.</p>
<p><strong>Keep in my mind: Automation can help you move fast, but clarity is what helps you keep moving.</strong></p>
<p>That’s the real tradeoff behind “auto-generated schemas”: not speed versus redundancy, but convenience versus comprehension.</p>


</section>

 ]]></description>
  <category>Software Engineering</category>
  <category>Python</category>
  <guid>https://www.storymelange.com/posts/projects/recipescanner/the-hidden-cost-of-magic-schemas.html</guid>
  <pubDate>Sat, 08 Nov 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Can AI fix your shopping list?</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/recipescanner/smart_shopping_list.html</link>
  <description><![CDATA[ 




<section id="meet-the-data" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="meet-the-data"><span class="header-section-number">1</span> Meet the data</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/unsplash_photo.jpg" class="img-fluid figure-img"></p>
<figcaption>A dumb shopping list, albeit an easy one</figcaption>
</figure>
</div>
<p>Most shopping or recipe apps can make a list — but few can <em>aggregate</em> it correctly. Ask them to combine “1 l milk”, “1 l lait”, and “1 l Milch”, and they’ll happily buy you one liter of each.</p>
<p>Can multilingual AI models understand that <em>milk</em>, <em>lait</em>, and <em>Milch</em> are the same thing? We’ll explore a full pipeline — from regex parsing to multilingual embeddings, fuzzy matching, and translation —</p>
<p><em>(Spoiler: not as far as you’d hope.)</em></p>
<section id="simple-test-cases" class="level3" data-number="1.1">
<h3 data-number="1.1" class="anchored" data-anchor-id="simple-test-cases"><span class="header-section-number">1.1</span> Simple test cases</h3>
<p>Let’s have a look at some test cases, to make things clearer:</p>
<div id="de7a3c853356d7aa" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:25:39.945854Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:25:39.938871Z&quot;}}" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">test_cases<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb1-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Milk family ===</span></span>
<span id="cb1-3">    {</span>
<span id="cb1-4">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l milk"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l lait"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l Milch"</span>],</span>
<span id="cb1-5">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3l milk"</span>]</span>
<span id="cb1-6">    },</span>
<span id="cb1-7">    {</span>
<span id="cb1-8">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l whole milk"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l lait entier"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l Vollmilch"</span>],</span>
<span id="cb1-9">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3l milk"</span>]</span>
<span id="cb1-10">    },</span>
<span id="cb1-11">    {</span>
<span id="cb1-12">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l hot milk"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l warme Milch"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l lait chaud"</span>],</span>
<span id="cb1-13">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3l milk"</span>]</span>
<span id="cb1-14">    },</span>
<span id="cb1-15"></span>
<span id="cb1-16">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Sugar ===</span></span>
<span id="cb1-17">    {</span>
<span id="cb1-18">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1000g sugar"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1kg Zucker"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1kg sucre"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 EL Zucker"</span>],</span>
<span id="cb1-19">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3kg sugar"</span>]</span>
<span id="cb1-20">    },</span>
<span id="cb1-21">    {</span>
<span id="cb1-22">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1kg brown sugar"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1kg sucre blanc"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1kg weißer Zucker"</span>],</span>
<span id="cb1-23">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1kg brown sugar"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1kg white sugar"</span>]</span>
<span id="cb1-24">    },</span>
<span id="cb1-25"></span>
<span id="cb1-26">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Eggs ===</span></span>
<span id="cb1-27">    {</span>
<span id="cb1-28">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 eggs"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 œuf"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Ei"</span>],</span>
<span id="cb1-29">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"4 eggs"</span>]</span>
<span id="cb1-30">    },</span>
<span id="cb1-31"></span>
<span id="cb1-32">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Bread ===</span></span>
<span id="cb1-33">    {</span>
<span id="cb1-34">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 baguette"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 bread"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Brot"</span>],</span>
<span id="cb1-35">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 bread"</span>]</span>
<span id="cb1-36">    },</span>
<span id="cb1-37"></span>
<span id="cb1-38">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Water &amp; wine distinction ===</span></span>
<span id="cb1-39">    {</span>
<span id="cb1-40">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 bottle of water"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 bouteille de vin"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Flasche Wasser"</span>],</span>
<span id="cb1-41">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 bottles of water"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 bottle of wine"</span>]</span>
<span id="cb1-42">    },</span>
<span id="cb1-43"></span>
<span id="cb1-44">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Branded/variant milk ===</span></span>
<span id="cb1-45">    {</span>
<span id="cb1-46">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l Oatly milk"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l lait Oatly"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1l Oatly Milch"</span>],</span>
<span id="cb1-47">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3l Oatly Milk"</span>]</span>
<span id="cb1-48">    },</span>
<span id="cb1-49"></span>
<span id="cb1-50">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Rice ===</span></span>
<span id="cb1-51">    {</span>
<span id="cb1-52">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"½kg rice"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"500g Reis"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"500g riz"</span>],</span>
<span id="cb1-53">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1.5kg rice"</span>]</span>
<span id="cb1-54">    },</span>
<span id="cb1-55"></span>
<span id="cb1-56">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Onion ===</span></span>
<span id="cb1-57">    {</span>
<span id="cb1-58">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 onion"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 oignon"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Zwiebel"</span>],</span>
<span id="cb1-59">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 onions"</span>]</span>
<span id="cb1-60">    },</span>
<span id="cb1-61"></span>
<span id="cb1-62">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Bell pepper ===</span></span>
<span id="cb1-63">    {</span>
<span id="cb1-64">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 bell pepper"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 capsicum"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 poivron"</span>],</span>
<span id="cb1-65">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 bell peppers"</span>]</span>
<span id="cb1-66">    },</span>
<span id="cb1-67"></span>
<span id="cb1-68">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Red pepper flakes ===</span></span>
<span id="cb1-69">    {</span>
<span id="cb1-70">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 red pepper flakes"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 chili flakes"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 piment concassé"</span>],</span>
<span id="cb1-71">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 red pepper flakes"</span>]</span>
<span id="cb1-72">    },</span>
<span id="cb1-73"></span>
<span id="cb1-74">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Butter ===</span></span>
<span id="cb1-75">    {</span>
<span id="cb1-76">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 tbsp butter"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 cuillère de beurre"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 EL Butter"</span>],</span>
<span id="cb1-77">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 tbsp butter"</span>]</span>
<span id="cb1-78">    },</span>
<span id="cb1-79"></span>
<span id="cb1-80">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Salt ===</span></span>
<span id="cb1-81">    {</span>
<span id="cb1-82">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 tsp salt"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 TL Salz"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 cuillère à café de sel"</span>],</span>
<span id="cb1-83">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 tsp salt"</span>]</span>
<span id="cb1-84">    },</span>
<span id="cb1-85"></span>
<span id="cb1-86">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Tomato cans ===</span></span>
<span id="cb1-87">    {</span>
<span id="cb1-88">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 can crushed tomatoes"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 boîte de tomates concassées"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Dose Tomatenstücke"</span>],</span>
<span id="cb1-89">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 cans crushed tomatoes"</span>]</span>
<span id="cb1-90">    },</span>
<span id="cb1-91"></span>
<span id="cb1-92">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Yogurt ===</span></span>
<span id="cb1-93">    {</span>
<span id="cb1-94">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 cup yogurt"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 tasse de yaourt"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Becher Joghurt"</span>],</span>
<span id="cb1-95">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 cups yogurt"</span>]</span>
<span id="cb1-96">    },</span>
<span id="cb1-97"></span>
<span id="cb1-98">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Oil ===</span></span>
<span id="cb1-99">    {</span>
<span id="cb1-100">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 tbsp olive oil"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 EL Olivenöl"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 cuillère à soupe d'huile d'olive"</span>],</span>
<span id="cb1-101">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 tbsp olive oil"</span>]</span>
<span id="cb1-102">    },</span>
<span id="cb1-103"></span>
<span id="cb1-104">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Bread variants shouldn’t merge with pastry ===</span></span>
<span id="cb1-105">    {</span>
<span id="cb1-106">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 croissant"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 pain"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 bread"</span>],</span>
<span id="cb1-107">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 bread"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 croissant"</span>]</span>
<span id="cb1-108">    },</span>
<span id="cb1-109"></span>
<span id="cb1-110">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Cheese ===</span></span>
<span id="cb1-111">    {</span>
<span id="cb1-112">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"100g cheese"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"100g fromage"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"100g Käse"</span>],</span>
<span id="cb1-113">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"300g cheese"</span>]</span>
<span id="cb1-114">    },</span>
<span id="cb1-115"></span>
<span id="cb1-116">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Flour ===</span></span>
<span id="cb1-117">    {</span>
<span id="cb1-118">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1kg flour"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1000g Mehl"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1kg farine"</span>],</span>
<span id="cb1-119">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3kg flour"</span>]</span>
<span id="cb1-120">    },</span>
<span id="cb1-121">]</span>
<span id="cb1-122"></span></code></pre></div></div>
</div>
</section>
<section id="long-phrases-test-cases" class="level3" data-number="1.2">
<h3 data-number="1.2" class="anchored" data-anchor-id="long-phrases-test-cases"><span class="header-section-number">1.2</span> Long phrases test cases</h3>
<p>In addition, we will also examine what will happen on longer phrases:</p>
<div id="3c5008cf0cb2a78c" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:12:45.135082Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:12:45.129998Z&quot;}}" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">test_cases_long_sentences <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb2-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Quantities with comments ===</span></span>
<span id="cb2-3">    {</span>
<span id="cb2-4">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 large yellow onion, coarsely chopped"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 oignon jaune haché"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 große gelbe Zwiebel, gehackt"</span>],</span>
<span id="cb2-5">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 onions"</span>]</span>
<span id="cb2-6">    },</span>
<span id="cb2-7">    {</span>
<span id="cb2-8">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 cups mango chunks, (2 large mangoes) (fresh or frozen)"</span>],</span>
<span id="cb2-9">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 cups mango chunks"</span>]</span>
<span id="cb2-10">    },</span>
<span id="cb2-11">    {</span>
<span id="cb2-12">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"½ cup butter (softened)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"100g beurre (ramolli)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"100g Butter (weich)"</span>],</span>
<span id="cb2-13">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1.5 sticks butter"</span>] </span>
<span id="cb2-14">    },</span>
<span id="cb2-15">    {</span>
<span id="cb2-16">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 tbsp minced cilantro, leaves and stems"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 EL gehackter Koriander"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 cuillère à soupe de coriandre hachée"</span>],</span>
<span id="cb2-17">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 tbsp cilantro"</span>]</span>
<span id="cb2-18">    },</span>
<span id="cb2-19"></span>
<span id="cb2-20">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Multi-part phrases ===</span></span>
<span id="cb2-21">    {</span>
<span id="cb2-22">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 bell pepper, cut in pieces"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 poivron coupé en morceaux"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Paprika in Stücke geschnitten"</span>],</span>
<span id="cb2-23">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 bell peppers"</span>]</span>
<span id="cb2-24">    },</span>
<span id="cb2-25">    {</span>
<span id="cb2-26">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 cloves garlic, finely chopped"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 gousses d’ail hachées"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 Knoblauchzehen, fein gehackt"</span>],</span>
<span id="cb2-27">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"6 cloves garlic"</span>]</span>
<span id="cb2-28">    },</span>
<span id="cb2-29">    {</span>
<span id="cb2-30">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 stalk bell peppers, cut in pieces"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Stiel Paprika, geschnitten"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 tige de poivron, coupée"</span>],</span>
<span id="cb2-31">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 bell peppers"</span>]</span>
<span id="cb2-32">    },</span>
<span id="cb2-33"></span>
<span id="cb2-34">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Fractional &amp; descriptive ===</span></span>
<span id="cb2-35">    {</span>
<span id="cb2-36">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1½ tsp garam masala"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 cuillère à café de garam masala"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 TL Garam Masala"</span>],</span>
<span id="cb2-37">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 tsp garam masala"</span>]</span>
<span id="cb2-38">    },</span>
<span id="cb2-39">    {</span>
<span id="cb2-40">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"a pinch of salt"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"une pincée de sel"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"eine Prise Salz"</span>],</span>
<span id="cb2-41">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 pinches salt"</span>]</span>
<span id="cb2-42">    },</span>
<span id="cb2-43">    {</span>
<span id="cb2-44">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"a handful of nuts"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"une poignée de noix"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"eine Handvoll Nüsse"</span>],</span>
<span id="cb2-45">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 handfuls nuts"</span>]</span>
<span id="cb2-46">    },</span>
<span id="cb2-47"></span>
<span id="cb2-48">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Compounds / alternatives ===</span></span>
<span id="cb2-49">    {</span>
<span id="cb2-50">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 cups milk or cream"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 tasses de lait ou de crème"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 Tassen Milch oder Sahne"</span>],</span>
<span id="cb2-51">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"6 cups milk or cream"</span>]</span>
<span id="cb2-52">    },</span>
<span id="cb2-53">    {</span>
<span id="cb2-54">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 tbsp olive oil, plus extra for frying"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 EL Olivenöl, zusätzlich zum Braten"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 cuillère à soupe d’huile d’olive, plus pour la cuisson"</span>],</span>
<span id="cb2-55">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 tbsp olive oil"</span>]</span>
<span id="cb2-56">    },</span>
<span id="cb2-57">    {</span>
<span id="cb2-58">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 cup chopped tomatoes (canned)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 boîte de tomates concassées"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Dose gehackte Tomaten"</span>],</span>
<span id="cb2-59">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 cups chopped tomatoes"</span>]</span>
<span id="cb2-60">    },</span>
<span id="cb2-61"></span>
<span id="cb2-62">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Units expressed as nouns ===</span></span>
<span id="cb2-63">    {</span>
<span id="cb2-64">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 bottle of water"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 bouteille d’eau"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Flasche Wasser"</span>],</span>
<span id="cb2-65">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 bottles of water"</span>]</span>
<span id="cb2-66">    },</span>
<span id="cb2-67">    {</span>
<span id="cb2-68">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 can coconut milk"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 boîte de lait de coco"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 Dose Kokosmilch"</span>],</span>
<span id="cb2-69">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 cans coconut milk"</span>]</span>
<span id="cb2-70">    },</span>
<span id="cb2-71"></span>
<span id="cb2-72">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Descriptive words shouldn’t break grouping ===</span></span>
<span id="cb2-73">    {</span>
<span id="cb2-74">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 large potato"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 grosse pomme de terre"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1 große Kartoffel"</span>],</span>
<span id="cb2-75">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3 potatoes"</span>]</span>
<span id="cb2-76">    },</span>
<span id="cb2-77">    {</span>
<span id="cb2-78">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 small onions"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 petits oignons"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2 kleine Zwiebeln"</span>],</span>
<span id="cb2-79">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>: [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"6 onions"</span>]</span>
<span id="cb2-80">    },</span>
<span id="cb2-81">]</span></code></pre></div></div>
</div>
</section>
</section>
<section id="simple-approach" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="simple-approach"><span class="header-section-number">2</span> Simple Approach</h2>
<p>For a human aggregating the items on the list is fairly easy. What similar items exist? And how many?</p>
<p>For a computer, this is not so easy.</p>
<p>I came up with a simple pipeline</p>
<ol type="1">
<li>We start by separating numbers from pure text. This should allow us to identify quantity and units, we’ll use regex for this.</li>
<li>As there will be multiple languages with similar words, we need to detect similar concepts. This will be done via multi language embeddings.</li>
<li>Once we have grouped items via embeddings, we aggregate the quantity. We need to normalize quantities to do this.</li>
</ol>
<section id="using-regex-what-is-the-unit-of-4-apples" class="level3" data-number="2.1">
<h3 data-number="2.1" class="anchored" data-anchor-id="using-regex-what-is-the-unit-of-4-apples"><span class="header-section-number">2.1</span> Using Regex: What is the unit of 4 Apples?</h3>
<p>While developing a solution, I discovered that embedding models have issues with numeric content. The reason is that we are looking at very short sequences. Numeric content leds to identical tokens for different items. If the numeric token is more than a certain threshold, things purely become similar due to the numeric component</p>
<p>We ’ll use a simple regex approach. Quantities are most of the time at the front of the ingredients.</p>
<p>Units are predefined as there only exists a limited set of units in each language. We will limit ourselves to english, french and german here. Let’s build unit map:</p>
<div id="fe719fe53fda1900" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-24T19:51:27.812496Z&quot;,&quot;start_time&quot;:&quot;2025-10-24T19:51:27.808690Z&quot;}}" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === Multilingual normalization map ===</span></span>
<span id="cb3-2">UNIT_MAP <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb3-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === volume ===</span></span>
<span id="cb3-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lt"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>,</span>
<span id="cb3-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"liter"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"liters"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>,          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># EN</span></span>
<span id="cb3-6">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"litre"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"litres"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>,          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FR</span></span>
<span id="cb3-7">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"literen"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"liter"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"literes"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"litern"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># DE plural inflections</span></span>
<span id="cb3-8">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"millilitre"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"millilitres"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span>,</span>
<span id="cb3-9">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"milliliter"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"milliliters"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span>,</span>
<span id="cb3-10">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === weight ===</span></span>
<span id="cb3-11">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gram"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grams"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>,</span>
<span id="cb3-12">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gramme"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grammes"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>,        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FR</span></span>
<span id="cb3-13">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gramm"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gramme"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grammen"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># DE</span></span>
<span id="cb3-14">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kilogram"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kilograms"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>,</span>
<span id="cb3-15">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kilogramme"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kilogrammes"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>,      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FR</span></span>
<span id="cb3-16">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kilogramm"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kilogramme"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kilogrammen"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># DE</span></span>
<span id="cb3-17">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === spoons &amp; cups ===</span></span>
<span id="cb3-18">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cup"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cup"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cups"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cup"</span>,</span>
<span id="cb3-19">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tasse"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cup"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tasses"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cup"</span>,      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FR</span></span>
<span id="cb3-20">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"becher"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cup"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tasse"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cup"</span>,      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># DE</span></span>
<span id="cb3-21">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tablespoon"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tablespoons"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>,</span>
<span id="cb3-22">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuillère"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuillerée"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuillères"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FR</span></span>
<span id="cb3-23">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"esslöffel"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"el"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>,    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># DE</span></span>
<span id="cb3-24">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tsp"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tsp"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"teaspoon"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tsp"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"teaspoons"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tsp"</span>,</span>
<span id="cb3-25">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tl"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tsp"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"teelöffel"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tsp"</span>,      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># DE</span></span>
<span id="cb3-26">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuillère à café"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tsp"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cc"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tsp"</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FR</span></span>
<span id="cb3-27">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># === qualitative small measures ===</span></span>
<span id="cb3-28">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pinch"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pinch"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pinches"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pinch"</span>,</span>
<span id="cb3-29">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pincée"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pinch"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pincées"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pinch"</span>,</span>
<span id="cb3-30">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"prise"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pinch"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"prisen"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pinch"</span>,</span>
<span id="cb3-31">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dash"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dash"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashes"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dash"</span>,</span>
<span id="cb3-32">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"goutte"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drop"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gouttes"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drop"</span>,</span>
<span id="cb3-33">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tropfen"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drop"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tropf"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drop"</span>,</span>
<span id="cb3-34">}</span></code></pre></div></div>
</div>
<p>For simplicity we assume that volumes can be converted to grams, regardless of food type. In most cases this leads to an upper bound, as water often has the highest density of all food types. As a result, we would just buy too much food.</p>
<div id="b74bd2936e7233bc" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:12:47.115102Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:12:47.110322Z&quot;}}" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">VOLUME_EQUIVALENTS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cup"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">240</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tsp"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>}</span>
<span id="cb4-2">WEIGHT_EQUIVALENTS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>}</span>
<span id="cb4-3"></span>
<span id="cb4-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> normalize_unit(raw_unit: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>:</span>
<span id="cb4-5">    raw_unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> raw_unit.lower().strip()</span>
<span id="cb4-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> UNIT_MAP.get(raw_unit, raw_unit)</span>
<span id="cb4-7"></span>
<span id="cb4-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> convert_to_base(qty: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>, unit: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb4-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> unit <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> VOLUME_EQUIVALENTS:</span>
<span id="cb4-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> qty <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> VOLUME_EQUIVALENTS[unit], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span></span>
<span id="cb4-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> unit <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> WEIGHT_EQUIVALENTS:</span>
<span id="cb4-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> qty <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> WEIGHT_EQUIVALENTS[unit], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span></span>
<span id="cb4-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> qty, unit</span></code></pre></div></div>
</div>
<p>Next comes the actual regex function. It searches for number and units. The remainder is assumed to be the ingredient. An Edge case is unitless quantities like <code>4 apples</code>. We catch this with a comparison to the units in the <code>UNIT_MAP</code>.</p>
<div id="2dbcc9ed9a38a0c6" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> re</span>
<span id="cb5-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> rapidfuzz.distance <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> JaroWinkler</span>
<span id="cb5-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> parse_item(text: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb5-4">    text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> text.strip()</span>
<span id="cb5-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Match multiple number + unit combos, e.g. "1l 200g", "2 Tassen Zucker"</span></span>
<span id="cb5-6">    matches <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.findall(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">(</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\d</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>(?:<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[.,]</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\d</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">½</span><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">¼</span><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">¾</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\s</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">(</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[a-zA-ZÀ-ÿ]</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, text)</span>
<span id="cb5-7">    remainder <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.sub(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">^</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">((</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\d</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>(?:<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[.,]</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\d</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">½</span><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">¼</span><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">¾</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\s</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[a-zA-ZÀ-ÿ]</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\s</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">''</span>, text).strip().lower()</span>
<span id="cb5-8"></span>
<span id="cb5-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> matches:</span>
<span id="cb5-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> [(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, remainder)]</span>
<span id="cb5-11">    result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb5-12">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> qty_str, unit_str <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> matches:</span>
<span id="cb5-13">        qty <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb5-14">            <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> qty_str <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"½"</span></span>
<span id="cb5-15">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> qty_str <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"¼"</span></span>
<span id="cb5-16">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> qty_str <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"¾"</span></span>
<span id="cb5-17">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(qty_str.replace(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">','</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'.'</span>))</span>
<span id="cb5-18">        )</span>
<span id="cb5-19">        raw <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> unit_str.lower().strip()</span>
<span id="cb5-20">        norm_unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> normalize_unit(raw)</span>
<span id="cb5-21">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> norm_unit <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> UNIT_MAP.values():</span>
<span id="cb5-22">            result.append((qty, norm_unit, remainder))</span>
<span id="cb5-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb5-24">            result.append((qty, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>unit_str<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>lower()<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>remainder<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>.strip()))</span>
<span id="cb5-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> result</span></code></pre></div></div>
</div>
<div id="91ceffd8af97d77c" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:12:48.204447Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:12:48.195501Z&quot;}}" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">parse_item(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'4 apples'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="6">
<pre><code>[(4.0, None, 'apples')]</code></pre>
</div>
</div>
<div id="1c72ef4b74363b7d" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:12:50.295384Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:12:50.283935Z&quot;}}" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">parse_item(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"100g chocolate"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="7">
<pre><code>[(100.0, 'g', 'chocolate')]</code></pre>
</div>
</div>
<p>Let’s do it for one test case:</p>
<div id="3b1928d9b51cbe6e" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:12:50.844445Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:12:50.839864Z&quot;}}" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">test_cases[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="8">
<pre><code>['1000g sugar', '1kg Zucker', '1kg sucre', '1 EL Zucker']</code></pre>
</div>
</div>
<div id="806d8669e3c88662" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:12:51.098101Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:12:51.095845Z&quot;}}" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> parse_items_list(texts):</span>
<span id="cb12-2">    results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb12-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> text <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> texts:</span>
<span id="cb12-4">        parsed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parse_item(text)</span>
<span id="cb12-5">        results.extend(parsed)</span>
<span id="cb12-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> results</span></code></pre></div></div>
</div>
<div id="2114d246d37f775b" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:12:51.308164Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:12:51.303534Z&quot;}}" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1">converted<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parse_items_list(test_cases[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>converted</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="10">
<pre><code>[(1000.0, 'g', 'sugar'),
 (1.0, 'kg', 'zucker'),
 (1.0, 'kg', 'sucre'),
 (1.0, 'tbsp', 'zucker')]</code></pre>
</div>
</div>
<p>Soo sweet, it works!</p>
</section>
<section id="embeddings-for-clustering-putting-together-what-belongs-together" class="level3" data-number="2.2">
<h3 data-number="2.2" class="anchored" data-anchor-id="embeddings-for-clustering-putting-together-what-belongs-together"><span class="header-section-number">2.2</span> Embeddings for clustering: putting together, what belongs together</h3>
<p>The next phase is the identification of similar concepts. For this we use an embedding model.</p>
<p>The hardest part consists in finding an embedding model that works well with our data. Ingredients can be multilingual and their length can range from one short word to several words.</p>
<p>A simple one word model would be a simple dictionary. As we have longer phrases, we need a sentence model.</p>
<p>One such model is <code>paraphrase-multilingual-MiniLM-L12-v2</code>.</p>
<div id="bcb755bfd679e1b2" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:01.010860Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:12:55.753194Z&quot;}}" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sentence_transformers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> SentenceTransformer, util</span>
<span id="cb15-2">model_emb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> SentenceTransformer(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"paraphrase-multilingual-MiniLM-L12-v2"</span>)</span></code></pre></div></div>
</div>
<p>Similar embeddings are frequently identified using cosine similarity.</p>
<div id="fa09678b24c48e0d" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:01.830813Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:01.819952Z&quot;}}" data-execution_count="12">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_same_concept(a: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, b: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, model, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>:</span>
<span id="cb16-2">    emb_a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.encode(a, normalize_embeddings<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb16-3">    emb_b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.encode(b, normalize_embeddings<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb16-4">    sim <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> util.cos_sim(emb_a, emb_b).item()</span>
<span id="cb16-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> sim <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> threshold</span></code></pre></div></div>
</div>
<p>This is pairwise comparison and we need to transform our list.</p>
<div id="31ba25c958601a27" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:04.946472Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:04.934219Z&quot;}}" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> itertools <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> combinations</span>
<span id="cb17-2"></span>
<span id="cb17-3">names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [t[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> t <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> converted]</span>
<span id="cb17-4"></span>
<span id="cb17-5">pairs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>({<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">tuple</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sorted</span>(p)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> p <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> combinations(names, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)})</span>
<span id="cb17-6">pairs</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="13">
<pre><code>[('sucre', 'sugar'),
 ('zucker', 'zucker'),
 ('sucre', 'zucker'),
 ('sugar', 'zucker')]</code></pre>
</div>
</div>
<div id="4b96a4dce21cece9" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:09.957934Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:09.723948Z&quot;}}" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> a, b <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> pairs:</span>
<span id="cb19-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(is_same_concept(a,b, model_emb))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>True
True
True
True</code></pre>
</div>
</div>
<p>Voila.</p>
<p>But what we are actually interested in is the number of similar concepts and which item belongs to which concept.</p>
<p>To do this we use a similarity matrix. And then search for clusters in the matrix.</p>
<div id="dbdbe6d3bc6b6f64" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:11.840105Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:11.836220Z&quot;}}" data-execution_count="15">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cluster_same_concept(names, model, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>):</span>
<span id="cb21-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Encode all names</span></span>
<span id="cb21-3">    embeddings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.encode(names, normalize_embeddings<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb21-4">    n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(names)</span>
<span id="cb21-5">    sim_matrix <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> util.cos_sim(embeddings, embeddings).numpy()</span>
<span id="cb21-6"></span>
<span id="cb21-7">    cluster_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n</span>
<span id="cb21-8">    current_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb21-9"></span>
<span id="cb21-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb21-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> cluster_id[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:</span>
<span id="cb21-12">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># already assigned</span></span>
<span id="cb21-13">        cluster_id[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> current_id</span>
<span id="cb21-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, n):</span>
<span id="cb21-15">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> sim_matrix[i, j] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> threshold:</span>
<span id="cb21-16">                cluster_id[j] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> current_id</span>
<span id="cb21-17">        current_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb21-18"></span>
<span id="cb21-19">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># map each name to its assigned cluster id</span></span>
<span id="cb21-20">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {names[i]: cluster_id[i] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n)}</span></code></pre></div></div>
</div>
<p>Let’s look at a longer list.</p>
<div id="323206b9d1c7e65e" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:14.118824Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:14.091740Z&quot;}}" data-execution_count="16">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1">names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sugar"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"zucker"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sucre"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"milk"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Milch"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lait"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bread"</span>]</span>
<span id="cb22-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cluster_same_concept(names, model_emb, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>).items():</span>
<span id="cb22-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>cid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:2d}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>sugar →  0
zucker →  0
sucre →  0
milk →  1
Milch →  2
lait →  1
bread →  3</code></pre>
</div>
</div>
<p>Not too bad. But <code>Milch</code> was identified as its own category, instead of adding it to <code>milk</code>.</p>
<p>The issue is that single words provide little information for cosine similarity of tokens.</p>
<p>There are four things we could do. First, lower the threshold and risk grouping unrelated concepts, second, we could use a better clustering algo, third contextualize, and fourth use fuzzy matching for small words.</p>
<section id="approach-1-lowering-the-threshold" class="level4" data-number="2.2.1">
<h4 data-number="2.2.1" class="anchored" data-anchor-id="approach-1-lowering-the-threshold"><span class="header-section-number">2.2.1</span> Approach 1: lowering the threshold</h4>
<p>Let’s start with approach 1.</p>
<div id="5f9e413200201a40" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:19.899312Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:19.886794Z&quot;}}" data-execution_count="17">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cluster_same_concept(names, model_emb, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.65</span>).items():</span>
<span id="cb24-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>cid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:2d}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>sugar →  0
zucker →  0
sucre →  0
milk →  1
Milch →  1
lait →  1
bread →  2</code></pre>
</div>
</div>
<p>That one worked, but I had to lower the threshold to 0.65, which makes the algo brittle.</p>
</section>
<section id="approach-2-transitive-clustering" class="level4" data-number="2.2.2">
<h4 data-number="2.2.2" class="anchored" data-anchor-id="approach-2-transitive-clustering"><span class="header-section-number">2.2.2</span> Approach 2: transitive clustering</h4>
<p>Inside our similarity matrix we only do pair wise clustering. If <code>milk</code> is only partly similar to <code>Milch</code> and <code>Milch</code> and <code>lait</code> are more similar, the current algo does not cluster everything if <code>lait</code> and <code>milk</code> are similar.</p>
<p>What we need is transitive clustering. One way to do this is via a <a href="https://en.wikipedia.org/wiki/Cluster_analysis">connected component clustering</a>.</p>
<div id="8f3ac1ec2306cb8e" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:34.369023Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:34.365829Z&quot;}}" data-execution_count="19">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cluster_same_concept_transitive(names, model, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>):</span>
<span id="cb26-2">    embeddings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.encode(names, normalize_embeddings<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb26-3">    sim_matrix <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> util.cos_sim(embeddings, embeddings).numpy()</span>
<span id="cb26-4">    n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(names)</span>
<span id="cb26-5"></span>
<span id="cb26-6">    adjacency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sim_matrix <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> threshold</span>
<span id="cb26-7"></span>
<span id="cb26-8">    visited <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n</span>
<span id="cb26-9">    clusters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n</span>
<span id="cb26-10">    cluster_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb26-11"></span>
<span id="cb26-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> dfs(i, cid):</span>
<span id="cb26-13">        visited[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb26-14">        clusters[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cid</span>
<span id="cb26-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb26-16">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> adjacency[i, j] <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> visited[j]:</span>
<span id="cb26-17">                dfs(j, cid)</span>
<span id="cb26-18"></span>
<span id="cb26-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb26-20">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> visited[i]:</span>
<span id="cb26-21">            dfs(i, cluster_id)</span>
<span id="cb26-22">            cluster_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb26-23"></span>
<span id="cb26-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {names[i]: clusters[i] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n)}</span></code></pre></div></div>
</div>
<div id="f45299d47a50b572" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:34.729191Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:34.698863Z&quot;}}" data-execution_count="20">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cluster_same_concept_transitive(names, model_emb, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.71</span>).items():</span>
<span id="cb27-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>cid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:2d}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>sugar →  0
zucker →  0
sucre →  0
milk →  1
Milch →  1
lait →  1
bread →  2</code></pre>
</div>
</div>
<p>Now, the threshold only needs to be lowered to 0.71.</p>
</section>
<section id="approach-3-contextualization" class="level4" data-number="2.2.3">
<h4 data-number="2.2.3" class="anchored" data-anchor-id="approach-3-contextualization"><span class="header-section-number">2.2.3</span> Approach 3: contextualization</h4>
<p>The third approach, contextualise, is rooted in the ways the embeddings were created. Multilingual embeddings are most often trained from sentences; not dictionary expressions like humans learn them for translation tasks. We can add a static expression to put all expressions in the same corner of the embedding space. By forcing a static expression of the input, we make the similarity expression less sensitive to milk vs.&nbsp;Milch.</p>
<div id="9291481d3d7a5f21" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:41.329921Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:41.327371Z&quot;}}" data-execution_count="21">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb29-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> contextualize(name):</span>
<span id="cb29-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f" this is a food ingredient called </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>name<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span></code></pre></div></div>
</div>
<div id="d6e2128f5c67cafe" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:41.739960Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:41.722868Z&quot;}}" data-execution_count="22">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cluster_same_concept_transitive_context(names, model, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>):</span>
<span id="cb30-2">    embeddings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.encode([contextualize(n) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> names], normalize_embeddings<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb30-3"></span>
<span id="cb30-4">    sim_matrix <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> util.cos_sim(embeddings, embeddings).numpy()</span>
<span id="cb30-5">    n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(names)</span>
<span id="cb30-6"></span>
<span id="cb30-7">    adjacency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sim_matrix <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> threshold</span>
<span id="cb30-8"></span>
<span id="cb30-9">    visited <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n</span>
<span id="cb30-10">    clusters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n</span>
<span id="cb30-11">    cluster_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb30-12"></span>
<span id="cb30-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> dfs(i, cid):</span>
<span id="cb30-14">        visited[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb30-15">        clusters[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cid</span>
<span id="cb30-16">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb30-17">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> adjacency[i, j] <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> visited[j]:</span>
<span id="cb30-18">                dfs(j, cid)</span>
<span id="cb30-19"></span>
<span id="cb30-20">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb30-21">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> visited[i]:</span>
<span id="cb30-22">            dfs(i, cluster_id)</span>
<span id="cb30-23">            cluster_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb30-24"></span>
<span id="cb30-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {names[i]: clusters[i] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n)}</span></code></pre></div></div>
</div>
<div id="895f5436b462955d" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:49.042978Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:49.016757Z&quot;}}" data-execution_count="23">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb31-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cluster_same_concept_transitive_context(names, model_emb, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.74</span>).items():</span>
<span id="cb31-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>cid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:2d}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>sugar →  0
zucker →  0
sucre →  0
milk →  1
Milch →  2
lait →  2
bread →  0</code></pre>
</div>
</div>
<div id="f6185055096b878a" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:49.372222Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:49.352968Z&quot;}}" data-execution_count="24">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb33-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cluster_same_concept_transitive_context(names, model_emb, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.73</span>).items():</span>
<span id="cb33-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>cid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:2d}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>sugar →  0
zucker →  0
sucre →  0
milk →  0
Milch →  0
lait →  0
bread →  0</code></pre>
</div>
</div>
<p>Oops. That did not work as expected. We go from bad to worse. #### Second Example: don’t spoil the milk Let’s try another datapoint.</p>
<div id="2a7c46704261aee2" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:13:55.873237Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:13:55.868157Z&quot;}}" data-execution_count="25">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb35-1">converted<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parse_items_list(test_cases[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>])</span>
<span id="cb35-2">names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [t[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> t <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> converted]</span>
<span id="cb35-3">names</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="25">
<pre><code>['hot milk', 'warme milch', 'lait chaud']</code></pre>
</div>
</div>
<div id="4b24018c8db3a566" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:14:06.168766Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:14:06.153152Z&quot;}}" data-execution_count="26">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cluster_same_concept(names, model_emb, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.96</span>).items():</span>
<span id="cb37-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>cid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:2d}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>hot milk →  0
warme milch →  0
lait chaud →  0</code></pre>
</div>
</div>
<div id="53bc8f1bd2aea042" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:14:06.443840Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:14:06.424684Z&quot;}}" data-execution_count="27">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb39" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb39-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cluster_same_concept_transitive(names, model_emb, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.98</span>).items():</span>
<span id="cb39-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>cid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:2d}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>hot milk →  0
warme milch →  0
lait chaud →  0</code></pre>
</div>
</div>
<div id="42af285449b97b60" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:14:06.830766Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:14:06.811552Z&quot;}}" data-execution_count="28">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb41" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb41-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cluster_same_concept_transitive_context(names, model_emb, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.70</span>).items():</span>
<span id="cb41-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>cid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:2d}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>hot milk →  0
warme milch →  0
lait chaud →  0</code></pre>
</div>
</div>
</section>
<section id="approach-4-dealing-with-one-word-ingredients-via-fuzzy-matching" class="level4" data-number="2.2.4">
<h4 data-number="2.2.4" class="anchored" data-anchor-id="approach-4-dealing-with-one-word-ingredients-via-fuzzy-matching"><span class="header-section-number">2.2.4</span> Approach 4: dealing with one word ingredients via fuzzy matching</h4>
<p>One-word ingredients are a bit tricky. They can lead to only one token in the sentence. Embeddings are not able to capture the meaning of a single word and are not robust against spelling mistakes</p>
<p>Fuzzy matching might work better. We compare strings directly and count distances or number of permutations to turn one in the other.Levenshtein distance and Jaro Winkler are two such metrics. Without diving too deep: on small words with a similar prefix (milk &amp; Milch), jaro winkler can lead to better results.</p>
<div id="42eb3172c968ed59" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:14:09.398734Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:14:09.388037Z&quot;}}" data-execution_count="29">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb43-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb43-2"></span>
<span id="cb43-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cluster_same_concept_transitive_winkler(names, model, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>, jaro_thresh<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>):</span>
<span id="cb43-4">    embeddings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.encode(names, normalize_embeddings<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb43-5">    sim_matrix <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> util.cos_sim(embeddings, embeddings).numpy()</span>
<span id="cb43-6">    n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(names)</span>
<span id="cb43-7"></span>
<span id="cb43-8">    adjacency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros((n, n), dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>)</span>
<span id="cb43-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb43-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb43-11">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> j:</span>
<span id="cb43-12">                adjacency[i, j] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb43-13">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span>
<span id="cb43-14">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Embedding similarity</span></span>
<span id="cb43-15">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> sim_matrix[i, j] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> threshold:</span>
<span id="cb43-16">                adjacency[i, j] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb43-17">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span>
<span id="cb43-18">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Jaro–Winkler fallback</span></span>
<span id="cb43-19">            jw <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> JaroWinkler.similarity(names[i].lower(), names[j].lower())</span>
<span id="cb43-20">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> jw <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> jaro_thresh:</span>
<span id="cb43-21">                adjacency[i, j] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb43-22"></span>
<span id="cb43-23">    visited <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n</span>
<span id="cb43-24">    clusters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n</span>
<span id="cb43-25">    cluster_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb43-26"></span>
<span id="cb43-27">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> dfs(i, cid):</span>
<span id="cb43-28">        visited[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb43-29">        clusters[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cid</span>
<span id="cb43-30">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb43-31">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> adjacency[i, j] <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> visited[j]:</span>
<span id="cb43-32">                dfs(j, cid)</span>
<span id="cb43-33"></span>
<span id="cb43-34">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb43-35">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> visited[i]:</span>
<span id="cb43-36">            dfs(i, cluster_id)</span>
<span id="cb43-37">            cluster_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb43-38"></span>
<span id="cb43-39">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {names[i]: clusters[i] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n)}</span></code></pre></div></div>
</div>
<div id="32dcd21221481e1a" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:14:12.731278Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:14:12.719430Z&quot;}}" data-execution_count="30">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb44" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb44-1">names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sugar"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"zucker"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sucre"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"milk"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Milch"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lait"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bread"</span>]</span>
<span id="cb44-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cluster_same_concept_transitive_winkler(names, model_emb, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.90</span>, jaro_thresh<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.84</span>).items():</span>
<span id="cb44-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>cid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:2d}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>sugar →  0
zucker →  0
sucre →  0
milk →  1
Milch →  1
lait →  1
bread →  2</code></pre>
</div>
</div>
<p>That helped quite a lot. Before we only had 0.71.</p>
</section>
</section>
<section id="normalization-of-quantities-and-merging" class="level3" data-number="2.3">
<h3 data-number="2.3" class="anchored" data-anchor-id="normalization-of-quantities-and-merging"><span class="header-section-number">2.3</span> Normalization of quantities and merging</h3>
<p>Now we have quantities, units and now which items belong together. We need two helpers to combine all this. One to get the Labels of each cluster. And the second to aggregate across units. In this second function we use the <code>convert_to_base</code> function we define earlier and which allows us adding g to ml.</p>
<div id="6e37ab288f30156f" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:35:42.365272Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:35:42.361307Z&quot;}}" data-execution_count="101">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb46" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb46-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> collections <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> defaultdict</span>
<span id="cb46-2"></span>
<span id="cb46-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_cluster_labels(clusters):</span>
<span id="cb46-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Invert {name -&gt; cid} into {cid -&gt; representative name}."""</span></span>
<span id="cb46-5">    groups <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>)</span>
<span id="cb46-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> name, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> clusters.items():</span>
<span id="cb46-7">        groups[cid].append(name)</span>
<span id="cb46-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {cid: names[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> cid, names <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> groups.items()}</span>
<span id="cb46-9"></span>
<span id="cb46-10">VOLUME_UNITS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cup"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tbsp"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tsp"</span>}</span>
<span id="cb46-11">WEIGHT_UNITS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span>}</span>
<span id="cb46-12"></span>
<span id="cb46-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> unify_units_1to1(qty, unit):</span>
<span id="cb46-14">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Normalize all weight units to grams and volume units to milliliters."""</span></span>
<span id="cb46-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(unit, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb46-16">        unit_str <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> unit.strip().lower()</span>
<span id="cb46-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb46-18">        unit_str <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">getattr</span>(unit, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">getattr</span>(unit, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unit"</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(unit)</span>
<span id="cb46-19">        unit_str <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> unit_str.strip().lower()</span>
<span id="cb46-20"></span>
<span id="cb46-21">    unit_str <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> UNIT_MAP.get(unit_str, unit_str)</span>
<span id="cb46-22"></span>
<span id="cb46-23">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Handle weights</span></span>
<span id="cb46-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> unit_str <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> WEIGHT_UNITS:</span>
<span id="cb46-25">        qty, base <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> convert_to_base(qty, unit_str)</span>
<span id="cb46-26">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> qty, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span></span>
<span id="cb46-27"></span>
<span id="cb46-28">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Handle volumes</span></span>
<span id="cb46-29">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> unit_str <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> VOLUME_UNITS:</span>
<span id="cb46-30">        qty, base <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> convert_to_base(qty, unit_str)</span>
<span id="cb46-31">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> qty, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span></span>
<span id="cb46-32"></span>
<span id="cb46-33">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Unknown or nonstandard unit</span></span>
<span id="cb46-34">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb46-35">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> qty, unit_str <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span></code></pre></div></div>
</div>
<p>Now comes the final aggregation logic. I added the final version here, which has an if block as we will later reuse this function, with a different input.</p>
<div id="1bade07501fec05e" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:14:20.142529Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:14:20.136825Z&quot;}}" data-execution_count="32">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb47" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb47-1"></span>
<span id="cb47-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> aggregate_by_concept(items, clusters):</span>
<span id="cb47-3">    totals <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb47-4">    labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_cluster_labels(clusters)</span>
<span id="cb47-5"></span>
<span id="cb47-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> item <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> items:</span>
<span id="cb47-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(item, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>):</span>
<span id="cb47-8">            qty <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> item.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"quantity"</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>)</span>
<span id="cb47-9">            unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> item.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unit"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>)</span>
<span id="cb47-10">            name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> item.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>).lower()</span>
<span id="cb47-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb47-12">            qty, unit, name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> item</span>
<span id="cb47-13">            name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> name.lower()</span>
<span id="cb47-14">        cid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> clusters.get(name)</span>
<span id="cb47-15">        q, base <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> unify_units_1to1(qty, unit)</span>
<span id="cb47-16">        totals[(cid, base)] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> q</span>
<span id="cb47-17"></span>
<span id="cb47-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span>  [(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(q, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>), u, labels.get(cid, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(cid))) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (cid, u), q <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> totals.items()]</span></code></pre></div></div>
</div>
<div id="aa8e79d9506f59d0" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:14:22.637210Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:14:22.624130Z&quot;}}" data-execution_count="33">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb48" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb48-1">converted<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parse_items_list(test_cases[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>])</span>
<span id="cb48-2">names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [t[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> t <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> converted]</span>
<span id="cb48-3">clusters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cluster_same_concept_transitive(names, model_emb)</span>
<span id="cb48-4">merged <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> aggregate_by_concept(converted, clusters)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> merged</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="33">
<pre><code>[(3015.0, 'g', 'sugar')]</code></pre>
</div>
</div>
<p>That is the result we want. Let’s polish it a little.</p>
<div id="8f0356bb9774beef" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:37:04.946025Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:37:04.941947Z&quot;}}" data-execution_count="108">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb50" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb50-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> format_aggregate(aggregated):</span>
<span id="cb50-2">    formatted <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb50-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> qty, unit, cid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> aggregated:</span>
<span id="cb50-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ml"</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> qty <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>:</span>
<span id="cb50-5">            qty <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span></span>
<span id="cb50-6">            unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"l"</span></span>
<span id="cb50-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"g"</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> qty <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>:</span>
<span id="cb50-8">            qty <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span></span>
<span id="cb50-9">            unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kg"</span></span>
<span id="cb50-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span>:</span>
<span id="cb50-11">            unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span>
<span id="cb50-12">        formatted.append(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>qty<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:g}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>unit<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>cid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb50-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> formatted</span>
<span id="cb50-14">format_aggregate(merged)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="108">
<pre><code>['3.015 kg sugar']</code></pre>
</div>
</div>
</section>
<section id="test-case-evaluation" class="level3" data-number="2.4">
<h3 data-number="2.4" class="anchored" data-anchor-id="test-case-evaluation"><span class="header-section-number">2.4</span> Test case evaluation</h3>
<p>Now comes the moment of truth. We define our test function.</p>
<div id="3db0c04004a4d35e" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:14:55.242768Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:14:55.240057Z&quot;}}" data-execution_count="36">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb52" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb52-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> convert(ing_list, model):</span>
<span id="cb52-2">    converted<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parse_items_list(ing_list)</span>
<span id="cb52-3">    names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [t[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> t <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> converted]</span>
<span id="cb52-4">    clusters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cluster_same_concept_transitive_winkler(names, model, jaro_thresh<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.65</span>, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.60</span>)</span>
<span id="cb52-5">    merged <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> aggregate_by_concept(converted, clusters)</span>
<span id="cb52-6">    out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> format_aggregate(merged)</span>
<span id="cb52-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> out</span></code></pre></div></div>
</div>
<div id="189e7702154cedbb" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:14:55.920293Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:14:55.678887Z&quot;}}" data-execution_count="37">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb53" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb53-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> case <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> test_cases:</span>
<span id="cb53-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>],convert(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>], model_emb))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>['3l milk'] ['3kg milk']
['3l milk'] ['3kg whole milk']
['3l milk'] ['3kg hot milk']
['3kg sugar'] ['3.015kg sugar']
['1kg brown sugar', '1kg white sugar'] ['3kg brown sugar']
['4 eggs'] ['3 eggs', '1 ei']
['3 bread'] ['2 baguette', '1 brot']
['2 bottles of water', '1 bottle of wine'] ['3 bottle of water']
['3l Oatly Milk'] ['3kg oatly milk']
['1.5kg rice'] ['1.5kg rice']
['3 onions'] ['2 onion', '1 zwiebel']
['3 bell peppers'] ['1 bell pepper', '1 capsicum', '1 poivron']
['3 red pepper flakes'] ['2 red pepper flakes', '1 piment concassé']
['3 tbsp butter'] ['45g butter']
['3 tsp salt'] ['25g salt']
['3 cans crushed tomatoes'] ['3 can crushed tomatoes']
['3 cups yogurt'] ['720g yogurt']
['3 tbsp olive oil'] ['45g olive oil']
['2 bread', '1 croissant'] ['1 croissant', '1 pain', '1 bread']
['300g cheese'] ['200g cheese', '100g käse']
['3kg flour'] ['2kg flour', '1kg mehl']</code></pre>
</div>
</div>
<p>Again, I had to lower the thresholds quite dramatically to get some sensible outputs.</p>
<p>As we can see, this process is far from perfect. Luckily for us, we are not the first computer scientists who are going food shopping.</p>
</section>
</section>
<section id="using-third-party-libraries" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="using-third-party-libraries"><span class="header-section-number">3</span> Using third party libraries</h2>
<section id="intro" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="intro"><span class="header-section-number">3.1</span> Intro</h3>
<p>There are many other projects which deal with shopping lists and ingredients. <a href="https://github.com/strangetom/ingredient-parser">Ingredient Parser</a> sticks out as it already uses a data-driven approach trained on ingredient data.</p>
<p>I was thinking about this myself, but then discovered this project. Assembling a dataset is a lot of work cudos to the author. We will use this parser.</p>
<p>Another approach, which I discovered in <a href="https://github.com/mealie-recipes/mealie">Meallie</a> is the use of an LLM with a Prompt. In my opinion, that becomes quite costly. For a self-hosted version with a few recipes, this might be ok, for a hosted version that will turn out to be expensive. Mealie uses a confidence logic similar to the threshold approach we used with embeddings and the Jaro Winkler.</p>
</section>
<section id="need-for-translations" class="level3" data-number="3.2">
<h3 data-number="3.2" class="anchored" data-anchor-id="need-for-translations"><span class="header-section-number">3.2</span> Need for translations</h3>
<section id="architecture" class="level4" data-number="3.2.1">
<h4 data-number="3.2.1" class="anchored" data-anchor-id="architecture"><span class="header-section-number">3.2.1</span> Architecture</h4>
<p>If we are going to rely on ingredient parser, there is one further issue. The model was trained using English words. Any non-English word will lead to less good results.</p>
<p>As now everything is in English, we need to back-translate to the target language. That has the advantage that we can have different input languages.</p>
<p>we will have the following pipeline:</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">flowchart TD
    A[Raw input] --&gt; B[Translate to English]
    B --&gt; C[Ingredient Parser]
    C --&gt; D[Embedding Model]
    D --&gt; E[Aggregation]
    E --&gt; F[Translate Output Back for UI]
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
</section>
<section id="finding-a-good-model" class="level4" data-number="3.2.2">
<h4 data-number="3.2.2" class="anchored" data-anchor-id="finding-a-good-model"><span class="header-section-number">3.2.2</span> Finding a good model</h4>
<p>We need a multilanguage model. My intention is to use client side translation to reduce the server load. One such model is MarianMT based Helsinki-NLP models. They are small (300MB) and fast. The downside is that they require knowing the source language. We need to use <code>langdetect</code> to detect the language. Side note: that is actually how the recipe on device android app started back in 2020.</p>
<div id="90d6976b70266e4a" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:18:19.425666Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:18:19.384267Z&quot;}}" data-execution_count="47">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb55" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb55-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> transformers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> MarianMTModel, MarianTokenizer</span>
<span id="cb55-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> langdetect <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> detect</span>
<span id="cb55-3"></span>
<span id="cb55-4">MODELS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb55-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fr'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Helsinki-NLP/opus-mt-fr-en'</span>,</span>
<span id="cb55-6">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'de'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Helsinki-NLP/opus-mt-de-en'</span></span>
<span id="cb55-7">}</span>
<span id="cb55-8"></span>
<span id="cb55-9">cache <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb55-10"></span>
<span id="cb55-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> translate_to_english_helsinki_with_langdetect(text):</span>
<span id="cb55-12">    lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect(text)</span>
<span id="cb55-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> lang <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> MODELS:</span>
<span id="cb55-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> text, lang</span>
<span id="cb55-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> lang <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cache:</span>
<span id="cb55-16">        name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> MODELS[lang]</span>
<span id="cb55-17">        cache[lang] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb55-18">            MarianTokenizer.from_pretrained(name),</span>
<span id="cb55-19">            MarianMTModel.from_pretrained(name)</span>
<span id="cb55-20">        )</span>
<span id="cb55-21">    tok, mod <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cache[lang]</span>
<span id="cb55-22">    inputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tok(text, return_tensors<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pt"</span>)</span>
<span id="cb55-23">    outputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mod.generate(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>inputs)</span>
<span id="cb55-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tok.decode(outputs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], skip_special_tokens<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>), lang</span></code></pre></div></div>
</div>
<div id="dc566f4199ec8dee" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:15:28.893541Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:15:25.954301Z&quot;}}" data-execution_count="40">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb56" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb56-1">translated_all <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb56-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, case <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(test_cases, start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb56-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">=== Test case </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> ==="</span>)</span>
<span id="cb56-4"></span>
<span id="cb56-5">    translated, lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(translate_to_english_helsinki_with_langdetect(x) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>]))</span>
<span id="cb56-6">    translated_all.append({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>:translated})</span>
<span id="cb56-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> orig, trans, la <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>], translated, lang):</span>
<span id="cb56-8">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>orig<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:&lt;30}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>trans<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">; lang: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>la<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>
=== Test case 1 ===
1l milk                        → 1l milk; lang: et
1l lait                        → 1L milk; lang: fr
1l Milch                       → 1l Milch; lang: it

=== Test case 2 ===
1l whole milk                  → 1l whole milk; lang: en
1l lait entier                 → 1l whole milk; lang: fr
1l Vollmilch                   → 1l Vollmilch; lang: it

=== Test case 3 ===
1l hot milk                    → 1l hot milk; lang: et
1l warme Milch                 → 1l warme Milch; lang: en
1l lait chaud                  → 1l hot milk; lang: fr

=== Test case 4 ===
1000g sugar                    → 1000g sugar; lang: tl
1kg Zucker                     → 1kg of sugar; lang: de
1kg sucre                      → 1kg sucre; lang: en
1 EL Zucker                    → 1 tbsp sugar; lang: de

=== Test case 5 ===
1kg brown sugar                → 1kg brown sugar; lang: en
1kg sucre blanc                → 1kg sucre blanc; lang: en
1kg weißer Zucker              → 1 kg of white sugar; lang: de

=== Test case 6 ===
2 eggs                         → 2 eggs; lang: no
1 œuf                          → 1 egg; lang: fr
1 Ei                           → 1 egg; lang: de

=== Test case 7 ===
1 baguette                     → 1 baguette; lang: no
1 bread                        → 1 bread; lang: pt
1 Brot                         → 1 Brot; lang: en

=== Test case 8 ===
1 bottle of water              → 1 bottle of water; lang: en
1 bouteille de vin             → 1 bottle of wine; lang: fr
1 Flasche Wasser               → 1 bottle of water; lang: de

=== Test case 9 ===
1l Oatly milk                  → 1l Oatly milk; lang: hu
1l lait Oatly                  → 1l Oatly milk; lang: fr
1l Oatly Milch                 → 1l Oatly Milch; lang: en

=== Test case 10 ===
½kg rice                       → ½kg rice; lang: en
500g Reis                      → 500g rice; lang: de
500g riz                       → 500g riz; lang: hr

=== Test case 11 ===
1 onion                        → 1 onion; lang: en
1 oignon                       → 1 oignon; lang: it
1 Zwiebel                      → 1 onion; lang: de

=== Test case 12 ===
1 bell pepper                  → 1 bell pepper; lang: sv
1 capsicum                     → 1 capsicum; lang: ro
1 poivron                      → 1 poivron; lang: sl

=== Test case 13 ===
1 red pepper flakes            → 1 red pepper flakes; lang: no
1 chili flakes                 → 1 chili flakes; lang: sw
1 piment concassé              → 1 piment concassé; lang: ca

=== Test case 14 ===
1 tbsp butter                  → 1 tbsp butter; lang: no
1 cuillère de beurre           → 1 spoon of butter; lang: fr
1 EL Butter                    → 1 tbsp butter; lang: de

=== Test case 15 ===
1 tsp salt                     → 1 tsp salt; lang: fi
1 TL Salz                      → 1 TL salt; lang: de
1 cuillère à café de sel       → 1 teaspoon of salt; lang: fr

=== Test case 16 ===
1 can crushed tomatoes         → 1 can crushed tomatoes; lang: en
1 boîte de tomates concassées  → 1 can of crushed tomatoes; lang: fr
1 Dose Tomatenstücke           → 1 can of tomato pieces; lang: de

=== Test case 17 ===
1 cup yogurt                   → 1 cup yogurt; lang: ro
1 tasse de yaourt              → 1 cup of yogurt; lang: fr
1 Becher Joghurt               → 1 cup of yoghurt; lang: de

=== Test case 18 ===
1 tbsp olive oil               → 1 tbsp olive oil; lang: fi
1 EL Olivenöl                  → 1 EL Olivenöl; lang: sv
1 cuillère à soupe d'huile d'olive → 1 tablespoon of olive oil; lang: fr

=== Test case 19 ===
1 croissant                    → 1 increasing; lang: fr
1 pain                         → 1 pain; lang: fi
1 bread                        → 1 bread; lang: es

=== Test case 20 ===
100g cheese                    → 100g cheese; lang: nl
100g fromage                   → 100g fromage; lang: da
100g Käse                      → 100g Käse; lang: sv

=== Test case 21 ===
1kg flour                      → 1kg flour; lang: da
1000g Mehl                     → 1000g flour; lang: de
1kg farine                     → 1kg farine; lang: no</code></pre>
</div>
</div>
<p>Langdetect fails to detect the language quite frequently, and we cannot translate. We should definitely normalize the numeric parts by splitting them from the letters.</p>
<div id="40b35b91389d5a78" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:17:13.761153Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:17:13.758426Z&quot;}}" data-execution_count="44">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb58" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb58-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> normalize_qty(text):</span>
<span id="cb58-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># add space between digits and letters (1l → 1 l)</span></span>
<span id="cb58-3">    text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.sub(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">(</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\d</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)(</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[a-zA-Z]</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\1</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\2</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, text)</span>
<span id="cb58-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> text.strip()</span></code></pre></div></div>
</div>
<div id="237f4cf6abef9cec" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:17:29.338009Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:17:26.629304Z&quot;}}" data-execution_count="45">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb59" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb59-1">translated_all <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb59-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, case <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(test_cases, start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb59-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">=== Test case </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> ==="</span>)</span>
<span id="cb59-4"></span>
<span id="cb59-5">    translated, lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(translate_to_english_helsinki_with_langdetect(normalize_qty(x)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>]))</span>
<span id="cb59-6">    translated_all.append({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>:translated})</span>
<span id="cb59-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> orig, trans, la <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>], translated, lang):</span>
<span id="cb59-8">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>orig<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:&lt;30}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>trans<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">; lang: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>la<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>
=== Test case 1 ===
1l milk                        → 1 l milk; lang: et
1l lait                        → 1 l milk; lang: fr
1l Milch                       → 1 l Milch; lang: it

=== Test case 2 ===
1l whole milk                  → 1 l whole milk; lang: en
1l lait entier                 → 1 l whole milk; lang: fr
1l Vollmilch                   → 1 l Vollmilch; lang: it

=== Test case 3 ===
1l hot milk                    → 1 l hot milk; lang: et
1l warme Milch                 → 1 l warme Milch; lang: en
1l lait chaud                  → 1 l hot milk; lang: fr

=== Test case 4 ===
1000g sugar                    → 1000 g sugar; lang: tl
1kg Zucker                     → 1 kg sugar; lang: de
1kg sucre                      → 1 kg sucre; lang: en
1 EL Zucker                    → 1 tbsp sugar; lang: de

=== Test case 5 ===
1kg brown sugar                → 1 kg brown sugar; lang: en
1kg sucre blanc                → 1 kg sucre blanc; lang: en
1kg weißer Zucker              → 1 kg of white sugar; lang: de

=== Test case 6 ===
2 eggs                         → 2 eggs; lang: no
1 œuf                          → 1 egg; lang: fr
1 Ei                           → 1 egg; lang: de

=== Test case 7 ===
1 baguette                     → 1 baguette; lang: no
1 bread                        → 1 bread; lang: es
1 Brot                         → 1 Brot; lang: en

=== Test case 8 ===
1 bottle of water              → 1 bottle of water; lang: en
1 bouteille de vin             → 1 bottle of wine; lang: fr
1 Flasche Wasser               → 1 bottle of water; lang: de

=== Test case 9 ===
1l Oatly milk                  → 1 l Oatly milk; lang: hu
1l lait Oatly                  → 1 l Oatly milk; lang: fr
1l Oatly Milch                 → 1 l Oatly Milch; lang: en

=== Test case 10 ===
½kg rice                       → ½kg rice; lang: en
500g Reis                      → 500 g rice; lang: de
500g riz                       → 500 g riz; lang: hr

=== Test case 11 ===
1 onion                        → 1 onion; lang: en
1 oignon                       → 1 oignon; lang: it
1 Zwiebel                      → 1 onion; lang: de

=== Test case 12 ===
1 bell pepper                  → 1 bell pepper; lang: sv
1 capsicum                     → 1 capsicum; lang: ro
1 poivron                      → 1 poivron; lang: sl

=== Test case 13 ===
1 red pepper flakes            → 1 red pepper flakes; lang: no
1 chili flakes                 → 1 chili flakes; lang: sw
1 piment concassé              → 1 piment concassé; lang: ca

=== Test case 14 ===
1 tbsp butter                  → 1 tbsp butter; lang: en
1 cuillère de beurre           → 1 spoon of butter; lang: fr
1 EL Butter                    → 1 EL Butter; lang: no

=== Test case 15 ===
1 tsp salt                     → 1 tsp salt; lang: lv
1 TL Salz                      → 1 TL salt; lang: de
1 cuillère à café de sel       → 1 teaspoon of salt; lang: fr

=== Test case 16 ===
1 can crushed tomatoes         → 1 can crushed tomatoes; lang: en
1 boîte de tomates concassées  → 1 can of crushed tomatoes; lang: fr
1 Dose Tomatenstücke           → 1 can of tomato pieces; lang: de

=== Test case 17 ===
1 cup yogurt                   → 1 cup yogurt; lang: ro
1 tasse de yaourt              → 1 cup of yogurt; lang: fr
1 Becher Joghurt               → 1 cup of yoghurt; lang: de

=== Test case 18 ===
1 tbsp olive oil               → 1 tbsp olive oil; lang: fi
1 EL Olivenöl                  → 1 EL Olivenöl; lang: sv
1 cuillère à soupe d'huile d'olive → 1 tablespoon of olive oil; lang: fr

=== Test case 19 ===
1 croissant                    → 1 increasing; lang: fr
1 pain                         → 1 pain; lang: fi
1 bread                        → 1 bread; lang: pt

=== Test case 20 ===
100g cheese                    → 100 g cheese; lang: nl
100g fromage                   → 100 g fromage; lang: da
100g Käse                      → 100 g Käse; lang: sv

=== Test case 21 ===
1kg flour                      → 1 kg flour; lang: da
1000g Mehl                     → 1000 g flour; lang: de
1kg farine                     → 1 kg farine; lang: no</code></pre>
</div>
</div>
<p>Not much better.</p>
<p>Then, there is a Helsinki-NLP allrounder model, which knows many languages at the expense of accuracy.</p>
<div id="3853417e01d562c7" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:18:25.536442Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:18:25.533104Z&quot;}}" data-execution_count="48">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb61" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb61-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> functools</span>
<span id="cb61-2"></span>
<span id="cb61-3">MODEL_NAME <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Helsinki-NLP/opus-mt-mul-en"</span></span>
<span id="cb61-4"></span>
<span id="cb61-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Lazy-load for reuse</span></span>
<span id="cb61-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@functools.lru_cache</span>(maxsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb61-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_multilingual_translator():</span>
<span id="cb61-8">    tokenizer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> MarianTokenizer.from_pretrained(MODEL_NAME)</span>
<span id="cb61-9">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> MarianMTModel.from_pretrained(MODEL_NAME)</span>
<span id="cb61-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tokenizer, model</span></code></pre></div></div>
</div>
<div id="e4b35f27ad90b732" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:18:26.653396Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:18:26.650072Z&quot;}}" data-execution_count="49">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb62" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb62-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> translate_to_english_helsinki(text: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>:</span>
<span id="cb62-2">    text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> text.strip()</span>
<span id="cb62-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> text:</span>
<span id="cb62-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> text</span>
<span id="cb62-5"></span>
<span id="cb62-6">    tok, mod <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_multilingual_translator()</span>
<span id="cb62-7"></span>
<span id="cb62-8">    batch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tok([text], return_tensors<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pt"</span>, truncation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb62-9">    gen <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mod.generate(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>batch, max_new_tokens<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">64</span>)</span>
<span id="cb62-10">    result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tok.decode(gen[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], skip_special_tokens<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb62-11"></span>
<span id="cb62-12">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> result.strip()</span></code></pre></div></div>
</div>
<div id="aab43526a0be6f03" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:18:36.080823Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:18:27.580519Z&quot;}}" data-execution_count="50">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb63" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb63-1">translated_all <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb63-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, case <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(test_cases, start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb63-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">=== Test case </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> ==="</span>)</span>
<span id="cb63-4"></span>
<span id="cb63-5">    translated <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [translate_to_english_helsinki(x) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>]]</span>
<span id="cb63-6">    translated_all.append({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>:translated})</span>
<span id="cb63-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> orig, trans <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>], translated):</span>
<span id="cb63-8">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>orig<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:&lt;30}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>trans<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>
=== Test case 1 ===
1l milk                        → 1l milk
1l lait                        → 1 l
1l Milch                       → 1l Milk

=== Test case 2 ===
1l whole milk                  → 1l whole milk
1l lait entier                 → 1l leaves all
1l Vollmilch                   → 1l Full milk

=== Test case 3 ===
1l hot milk                    → 1l hot milk
1l warme Milch                 → 1l hot milk
1l lait chaud                  → 1 L to the left

=== Test case 4 ===
1000g sugar                    → 1000g sugar
1kg Zucker                     → 1kg Sugar
1kg sucre                      → 1kg sugar
1 EL Zucker                    → 1 EL Sugar

=== Test case 5 ===
1kg brown sugar                → 1kg brown sugar
1kg sucre blanc                → 1kg white sugar
1kg weißer Zucker              → 1kg white sugar

=== Test case 6 ===
2 eggs                         → 2 eggs
1 œuf                          → 1 egg
1 Ei                           → 1 Yes

=== Test case 7 ===
1 baguette                     → 1 baguette
1 bread                        → 1 board
1 Brot                         → 1 Brot

=== Test case 8 ===
1 bottle of water              → 1 bottle of water
1 bouteille de vin             → 1 bottle of wine
1 Flasche Wasser               → 1 bottle of water

=== Test case 9 ===
1l Oatly milk                  → 1l Oatly milk
1l lait Oatly                  → 1l Leave Oatly
1l Oatly Milch                 → 1l Oatly Milk

=== Test case 10 ===
½kg rice                       → 1⁄2kg of rice
500g Reis                      → 500g Reis
500g riz                       → 500g rice

=== Test case 11 ===
1 onion                        → 1 onion
1 oignon                       → 1 firenon
1 Zwiebel                      → 1 Double

=== Test case 12 ===
1 bell pepper                  → 1 bell pepper
1 capsicum                     → 1 capsicum
1 poivron                      → 1 piovirone

=== Test case 13 ===
1 red pepper flakes            → 1 red pepper flakes
1 chili flakes                 → 1 Chilean flakes
1 piment concassé              → 1 Pim Concazed

=== Test case 14 ===
1 tbsp butter                  → 1 tbsp Butter
1 cuillère de beurre           → 1 glass of beer
1 EL Butter                    → 1 EL Butter

=== Test case 15 ===
1 tsp salt                     → 1 tsp salt
1 TL Salz                      → 1 TL Salz
1 cuillère à café de sel       → 1 silver coffee cooker

=== Test case 16 ===
1 can crushed tomatoes         → 1 can cross-sectional tomatoes
1 boîte de tomates concassées  → 1 box of sliced tomatoes
1 Dose Tomatenstücke           → 1 Dose of Tomatoes

=== Test case 17 ===
1 cup yogurt                   → 1 cup yogurt
1 tasse de yaourt              → 1 yourt rate
1 Becher Joghurt               → 1 Becher Joghurt

=== Test case 18 ===
1 tbsp olive oil               → 1 tbsp of olive oil
1 EL Olivenöl                  → 1 EU Olive oil
1 cuillère à soupe d'huile d'olive → 1 olive oil soup cooler

=== Test case 19 ===
1 croissant                    → 1 significant place
1 pain                         → 1 pen
1 bread                        → 1 board

=== Test case 20 ===
100g cheese                    → 100g cheese
100g fromage                   → 100g of cheese
100g Käse                      → 100g Käse

=== Test case 21 ===
1kg flour                      → 1kg flower
1000g Mehl                     → 1000g Mehl
1kg farine                     → 1kg far</code></pre>
</div>
</div>
<p>Mixed results.Sometimes it is better, but then it completely fails.</p>
<p>There would be bigger models to try Facebook’s m2m100 or NLLB. Besides being too big for a browser-based application, the common flaw in all those models, they require a source language. Facebook’s NLLB (No Language Left Behind). However, even the smallest distilled model is 2.4g.</p>
<p>However, there is one thing we can do. There is Facebook’s Fasttext library, which works on subword embeddings (character n-grams). That could mean it works well on single words. We first need to get the weights of the model.</p>
<p>Sadly, the model relies on an old numpy version. I saw no other version than to patch the file directly.</p>
<div id="32330a103dc432bf" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:19:53.680252Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:19:53.677339Z&quot;}}" data-execution_count="53">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb65" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb65-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> os <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> path</span>
<span id="cb65-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> path.exists(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lid.176.bin"</span>):</span>
<span id="cb65-3">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>wget https:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span>dl.fbaipublicfiles.com<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>fasttext<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>supervised<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>models<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>lid<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.176</span>.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bin</span></span></code></pre></div></div>
</div>
<div id="9684480044e30240" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:20:19.304346Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:20:19.156383Z&quot;}}" data-execution_count="55">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb66" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb66-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> os, fasttext, inspect</span>
<span id="cb66-2"></span>
<span id="cb66-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Locate FastText.py in your environment</span></span>
<span id="cb66-4">ft_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> os.path.join(os.path.dirname(inspect.getfile(fasttext)), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"FastText.py"</span>)</span>
<span id="cb66-5"></span>
<span id="cb66-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Read the file</span></span>
<span id="cb66-7"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(ft_path, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r"</span>, encoding<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"utf-8"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb66-8">    content <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> f.read()</span>
<span id="cb66-9"></span>
<span id="cb66-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Check if it's already patched</span></span>
<span id="cb66-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"np.asarray(probs)"</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> content:</span>
<span id="cb66-12">    patched <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> content.replace(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"np.array(probs, copy=False)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"np.asarray(probs)"</span>)</span>
<span id="cb66-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(ft_path, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"w"</span>, encoding<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"utf-8"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb66-14">        f.write(patched)</span>
<span id="cb66-15">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"✅ Patched FastText.py — replaced np.array(..., copy=False) with np.asarray(...)."</span>)</span>
<span id="cb66-16"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb66-17">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"✅ Already patched — no action needed."</span>)</span>
<span id="cb66-18"></span>
<span id="cb66-19"></span>
<span id="cb66-20"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> sys, gc, importlib</span>
<span id="cb66-21">mods <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [m <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> m <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> sys.modules <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> m.startswith(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fasttext"</span>)]</span>
<span id="cb66-22"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> m <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> mods:</span>
<span id="cb66-23">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">del</span> sys.modules[m]</span>
<span id="cb66-24">gc.collect()</span>
<span id="cb66-25"></span>
<span id="cb66-26"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> fasttext</span>
<span id="cb66-27">importlib.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">reload</span>(fasttext)</span>
<span id="cb66-28"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fasttext reloaded with patched FastText.py"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>✅ Already patched — no action needed.
fasttext reloaded with patched FastText.py</code></pre>
</div>
</div>
<div id="cb0e5812b25e9a76" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:20:25.539863Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:20:25.408680Z&quot;}}" data-execution_count="56">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb68" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb68-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> fasttext</span>
<span id="cb68-2"></span>
<span id="cb68-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Load pretrained language identification model</span></span>
<span id="cb68-4">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fasttext.load_model(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lid.176.bin"</span>)</span>
<span id="cb68-5"></span>
<span id="cb68-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> detect_lang(text: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb68-7">    labels, probs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.predict(text)</span>
<span id="cb68-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> labels[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].replace(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"__label__"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>), <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(probs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb68-9"></span>
<span id="cb68-10"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(detect_lang(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lait"</span>))     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ('fr', 0.99)</span></span>
<span id="cb68-11"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(detect_lang(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Milch"</span>))    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ('de', 0.98)</span></span>
<span id="cb68-12"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(detect_lang(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"egg"</span>))      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ('en', 0.99)</span></span>
<span id="cb68-13"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(detect_lang(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Zucker"</span>))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ('de', 0.97)</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>('fr', 0.9928548336029053)
('de', 0.8860894441604614)
('en', 0.5928217768669128)
('de', 0.486892431974411)</code></pre>
</div>
</div>
<p>That worked quite nicely. We can use it to replace langdetect.</p>
<div id="bc55f6df519ff6f3" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:21:03.722712Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:21:03.718255Z&quot;}}" data-execution_count="58">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb70" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb70-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> translate_to_english_helsinki_with_fastdetect(text, fastdetect_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model):</span>
<span id="cb70-2">    labels, probs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fastdetect_model.predict(text)</span>
<span id="cb70-3">    lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> labels[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].replace(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"__label__"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>)</span>
<span id="cb70-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> lang <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> MODELS <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'en'</span>:</span>
<span id="cb70-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> text, lang</span>
<span id="cb70-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> lang <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cache:</span>
<span id="cb70-7">        name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> MODELS[lang]</span>
<span id="cb70-8">        cache[lang] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb70-9">            MarianTokenizer.from_pretrained(name),</span>
<span id="cb70-10">            MarianMTModel.from_pretrained(name)</span>
<span id="cb70-11">        )</span>
<span id="cb70-12">    tok, mod <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cache[lang]</span>
<span id="cb70-13">    inputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tok(text, return_tensors<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pt"</span>)</span>
<span id="cb70-14">    outputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mod.generate(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>inputs)</span>
<span id="cb70-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tok.decode(outputs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], skip_special_tokens<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>), lang</span></code></pre></div></div>
</div>
<div id="9740630211b7bb5b" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:21:12.223102Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:21:05.998334Z&quot;}}" data-execution_count="59">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb71" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb71-1">translated_all <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb71-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, case <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(test_cases, start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb71-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">=== Test case </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> ==="</span>)</span>
<span id="cb71-4"></span>
<span id="cb71-5">    translated, lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(translate_to_english_helsinki_with_fastdetect(normalize_qty(x)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>]))</span>
<span id="cb71-6">    translated_all.append({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>:translated})</span>
<span id="cb71-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> orig, trans, la <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>], translated, lang):</span>
<span id="cb71-8">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>orig<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:&lt;30}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>trans<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">; lang: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>la<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>
=== Test case 1 ===
1l milk                        → 1 l milk; lang: en
1l lait                        → 1 l milk; lang: fr
1l Milch                       → 1 l milk; lang: de

=== Test case 2 ===
1l whole milk                  → 1 l whole milk; lang: en
1l lait entier                 → 1 l whole milk; lang: fr
1l Vollmilch                   → 1 l whole milk; lang: de

=== Test case 3 ===
1l hot milk                    → 1 l hot milk; lang: en
1l warme Milch                 → 1 l warm milk; lang: de
1l lait chaud                  → 1 l hot milk; lang: fr

=== Test case 4 ===
1000g sugar                    → 1000 g sugar; lang: en
1kg Zucker                     → 1 kg sugar; lang: de
1kg sucre                      → 1 kg sugar; lang: fr
1 EL Zucker                    → 1 tbsp sugar; lang: de

=== Test case 5 ===
1kg brown sugar                → 1 kg brown sugar; lang: en
1kg sucre blanc                → 1 kg white sugar; lang: fr
1kg weißer Zucker              → 1 kg of white sugar; lang: de

=== Test case 6 ===
2 eggs                         → 2 eggs; lang: en
1 œuf                          → 1 egg; lang: fr
1 Ei                           → 1 Ei; lang: pt

=== Test case 7 ===
1 baguette                     → 1 wand; lang: fr
1 bread                        → 1 bread; lang: en
1 Brot                         → 1 bread; lang: de

=== Test case 8 ===
1 bottle of water              → 1 bottle of water; lang: en
1 bouteille de vin             → 1 bottle of wine; lang: fr
1 Flasche Wasser               → 1 bottle of water; lang: de

=== Test case 9 ===
1l Oatly milk                  → 1 l Oatly milk; lang: en
1l lait Oatly                  → 1 l Oatly milk; lang: fr
1l Oatly Milch                 → 1 l Oatly Milch; lang: en

=== Test case 10 ===
½kg rice                       → ½kg rice; lang: en
500g Reis                      → 500 g Reis; lang: en
500g riz                       → 500 g riz; lang: es

=== Test case 11 ===
1 onion                        → 1 onion; lang: pl
1 oignon                       → 1 oignon; lang: id
1 Zwiebel                      → 1 onion; lang: de

=== Test case 12 ===
1 bell pepper                  → 1 bell pepper; lang: en
1 capsicum                     → 1 capsicum; lang: la
1 poivron                      → 1 poivron; lang: pt

=== Test case 13 ===
1 red pepper flakes            → 1 red pepper flakes; lang: en
1 chili flakes                 → 1 chili flakes; lang: en
1 piment concassé              → 1 crushed chilli; lang: fr

=== Test case 14 ===
1 tbsp butter                  → 1 tbsp butter; lang: en
1 cuillère de beurre           → 1 spoon of butter; lang: fr
1 EL Butter                    → 1 EL Butter; lang: en

=== Test case 15 ===
1 tsp salt                     → 1 tsp salt; lang: en
1 TL Salz                      → 1 TL salt; lang: de
1 cuillère à café de sel       → 1 teaspoon of salt; lang: fr

=== Test case 16 ===
1 can crushed tomatoes         → 1 can crushed tomatoes; lang: en
1 boîte de tomates concassées  → 1 can of crushed tomatoes; lang: fr
1 Dose Tomatenstücke           → 1 can of tomato pieces; lang: de

=== Test case 17 ===
1 cup yogurt                   → 1 cup yogurt; lang: en
1 tasse de yaourt              → 1 cup of yogurt; lang: fr
1 Becher Joghurt               → 1 Becher Joghurt; lang: en

=== Test case 18 ===
1 tbsp olive oil               → 1 tbsp olive oil; lang: en
1 EL Olivenöl                  → 1 EL Olivenöl; lang: eo
1 cuillère à soupe d'huile d'olive → 1 tablespoon of olive oil; lang: fr

=== Test case 19 ===
1 croissant                    → 1 increasing; lang: fr
1 pain                         → 1 pain; lang: en
1 bread                        → 1 bread; lang: en

=== Test case 20 ===
100g cheese                    → 100 g cheese; lang: en
100g fromage                   → 100 g fromage; lang: en
100g Käse                      → 100 g cheese; lang: de

=== Test case 21 ===
1kg flour                      → 1 kg flour; lang: en
1000g Mehl                     → 1000 g flour; lang: de
1kg farine                     → 1 kg farine; lang: en</code></pre>
</div>
</div>
<p>That is a lot better, but we get misclassifications. If we know what language we expect we can map to the closest language.</p>
<div id="fe64212757b4dd02" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:22:23.820802Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:22:23.816505Z&quot;}}" data-execution_count="60">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb73" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb73-1"></span>
<span id="cb73-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> translate_to_english_helsinki_with_fastdetect_v2(text, fastdetect_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model):</span>
<span id="cb73-3">    labels, probs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fastdetect_model.predict(text)</span>
<span id="cb73-4">    lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> labels[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].replace(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"__label__"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>)</span>
<span id="cb73-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> lang <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pt'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'es'</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'id'</span>]:</span>
<span id="cb73-6">        lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fr'</span></span>
<span id="cb73-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> lang <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> MODELS <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'en'</span>:</span>
<span id="cb73-8">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> text, lang</span>
<span id="cb73-9"></span>
<span id="cb73-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> lang <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cache:</span>
<span id="cb73-11">        name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> MODELS[lang]</span>
<span id="cb73-12">        cache[lang] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb73-13">            MarianTokenizer.from_pretrained(name),</span>
<span id="cb73-14">            MarianMTModel.from_pretrained(name)</span>
<span id="cb73-15">        )</span>
<span id="cb73-16">    tok, mod <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cache[lang]</span>
<span id="cb73-17">    inputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tok(text, return_tensors<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pt"</span>)</span>
<span id="cb73-18">    outputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mod.generate(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>inputs)</span>
<span id="cb73-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tok.decode(outputs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], skip_special_tokens<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>), lang</span></code></pre></div></div>
</div>
<div id="d42f6b1241d13504" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:22:29.142126Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:22:26.052442Z&quot;}}" data-execution_count="61">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb74" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb74-1">translated_all <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb74-2"></span>
<span id="cb74-3"></span>
<span id="cb74-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, case <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(test_cases, start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb74-5">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">=== Test case </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> ==="</span>)</span>
<span id="cb74-6"></span>
<span id="cb74-7"></span>
<span id="cb74-8">    translated, lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(translate_to_english_helsinki_with_fastdetect_v2(normalize_qty(x)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>]))</span>
<span id="cb74-9">    translated_all.append({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>:translated})</span>
<span id="cb74-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> orig, trans, la <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>], translated, lang):</span>
<span id="cb74-11">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>orig<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:&lt;30}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> → </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>trans<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">; lang: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>la<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>
=== Test case 1 ===
1l milk                        → 1 l milk; lang: en
1l lait                        → 1 l milk; lang: fr
1l Milch                       → 1 l milk; lang: de

=== Test case 2 ===
1l whole milk                  → 1 l whole milk; lang: en
1l lait entier                 → 1 l whole milk; lang: fr
1l Vollmilch                   → 1 l whole milk; lang: de

=== Test case 3 ===
1l hot milk                    → 1 l hot milk; lang: en
1l warme Milch                 → 1 l warm milk; lang: de
1l lait chaud                  → 1 l hot milk; lang: fr

=== Test case 4 ===
1000g sugar                    → 1000 g sugar; lang: en
1kg Zucker                     → 1 kg sugar; lang: de
1kg sucre                      → 1 kg sugar; lang: fr
1 EL Zucker                    → 1 tbsp sugar; lang: de

=== Test case 5 ===
1kg brown sugar                → 1 kg brown sugar; lang: en
1kg sucre blanc                → 1 kg white sugar; lang: fr
1kg weißer Zucker              → 1 kg of white sugar; lang: de

=== Test case 6 ===
2 eggs                         → 2 eggs; lang: en
1 œuf                          → 1 egg; lang: fr
1 Ei                           → 1 Ei; lang: fr

=== Test case 7 ===
1 baguette                     → 1 wand; lang: fr
1 bread                        → 1 bread; lang: en
1 Brot                         → 1 bread; lang: de

=== Test case 8 ===
1 bottle of water              → 1 bottle of water; lang: en
1 bouteille de vin             → 1 bottle of wine; lang: fr
1 Flasche Wasser               → 1 bottle of water; lang: de

=== Test case 9 ===
1l Oatly milk                  → 1 l Oatly milk; lang: en
1l lait Oatly                  → 1 l Oatly milk; lang: fr
1l Oatly Milch                 → 1 l Oatly Milch; lang: en

=== Test case 10 ===
½kg rice                       → ½kg rice; lang: en
500g Reis                      → 500 g Reis; lang: en
500g riz                       → 500 g rice; lang: fr

=== Test case 11 ===
1 onion                        → 1 onion; lang: pl
1 oignon                       → 1 onion; lang: fr
1 Zwiebel                      → 1 onion; lang: de

=== Test case 12 ===
1 bell pepper                  → 1 bell pepper; lang: en
1 capsicum                     → 1 capsicum; lang: la
1 poivron                      → 1 pepper; lang: fr

=== Test case 13 ===
1 red pepper flakes            → 1 red pepper flakes; lang: en
1 chili flakes                 → 1 chili flakes; lang: en
1 piment concassé              → 1 crushed chilli; lang: fr

=== Test case 14 ===
1 tbsp butter                  → 1 tbsp butter; lang: en
1 cuillère de beurre           → 1 spoon of butter; lang: fr
1 EL Butter                    → 1 EL Butter; lang: en

=== Test case 15 ===
1 tsp salt                     → 1 tsp salt; lang: en
1 TL Salz                      → 1 TL salt; lang: de
1 cuillère à café de sel       → 1 teaspoon of salt; lang: fr

=== Test case 16 ===
1 can crushed tomatoes         → 1 can crushed tomatoes; lang: en
1 boîte de tomates concassées  → 1 can of crushed tomatoes; lang: fr
1 Dose Tomatenstücke           → 1 can of tomato pieces; lang: de

=== Test case 17 ===
1 cup yogurt                   → 1 cup yogurt; lang: en
1 tasse de yaourt              → 1 cup of yogurt; lang: fr
1 Becher Joghurt               → 1 Becher Joghurt; lang: en

=== Test case 18 ===
1 tbsp olive oil               → 1 tbsp olive oil; lang: en
1 EL Olivenöl                  → 1 EL Olivenöl; lang: eo
1 cuillère à soupe d'huile d'olive → 1 tablespoon of olive oil; lang: fr

=== Test case 19 ===
1 croissant                    → 1 increasing; lang: fr
1 pain                         → 1 pain; lang: en
1 bread                        → 1 bread; lang: en

=== Test case 20 ===
100g cheese                    → 100 g cheese; lang: en
100g fromage                   → 100 g fromage; lang: en
100g Käse                      → 100 g cheese; lang: de

=== Test case 21 ===
1kg flour                      → 1 kg flour; lang: en
1000g Mehl                     → 1000 g flour; lang: de
1kg farine                     → 1 kg farine; lang: en</code></pre>
</div>
</div>
<p>That looks quite good, though not 100% perfect.</p>
</section>
</section>
<section id="ingredient-parsing" class="level3" data-number="3.3">
<h3 data-number="3.3" class="anchored" data-anchor-id="ingredient-parsing"><span class="header-section-number">3.3</span> Ingredient parsing</h3>
<p>Now that everything is sort of in english, we can use the <code>ingredient parser</code></p>
<div id="c6486f818eee8e71" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:44:21.310575Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:44:21.302230Z&quot;}}" data-execution_count="122">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb76" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb76-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> ingredient_parser <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> parse_ingredient</span>
<span id="cb76-2"></span>
<span id="cb76-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> parse_ingredient_line(text: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb76-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb76-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parse an English ingredient line into structured (quantity, unit, name, note)</span></span>
<span id="cb76-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    using the `ingredient-parser` package.</span></span>
<span id="cb76-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb76-8">    parsed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parse_ingredient(text)</span>
<span id="cb76-9"></span>
<span id="cb76-10">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Extract quantity</span></span>
<span id="cb76-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> parsed.amount <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> parsed.amount[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].quantity <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>:</span>
<span id="cb76-12">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Supports ranges, fractions, etc.</span></span>
<span id="cb76-13">        qty <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(parsed.amount[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].quantity)</span>
<span id="cb76-14">        unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parsed.amount[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].unit <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span>
<span id="cb76-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb76-16">        qty, unit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span>
<span id="cb76-17"></span>
<span id="cb76-18">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Extract main food name</span></span>
<span id="cb76-19">    name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parsed.name[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].text <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> parsed.name <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span>
<span id="cb76-20"></span>
<span id="cb76-21">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Optional note (preparation, comment, etc.)</span></span>
<span id="cb76-22">    note <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span>
<span id="cb76-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> parsed.comment:</span>
<span id="cb76-24">        note <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parsed.comment.text</span>
<span id="cb76-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> parsed.preparation:</span>
<span id="cb76-26">        note <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parsed.preparation.text</span>
<span id="cb76-27">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> parsed.size:</span>
<span id="cb76-28">        note <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parsed.size.text</span>
<span id="cb76-29"></span>
<span id="cb76-30">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {</span>
<span id="cb76-31">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"quantity"</span>: qty,</span>
<span id="cb76-32">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unit"</span>: unit,</span>
<span id="cb76-33">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>: name,</span>
<span id="cb76-34">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"note"</span>: note</span>
<span id="cb76-35">    }</span></code></pre></div></div>
</div>
<div id="17e35a409058abe9" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:23:03.290035Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:23:03.279524Z&quot;}}" data-execution_count="63">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb77" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb77-1">translated_all[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="63">
<pre><code>('1000 g sugar', '1 kg sugar', '1 kg sugar', '1 tbsp sugar')</code></pre>
</div>
</div>
<div id="fe1d930231389808" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:23:10.450639Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:23:10.442407Z&quot;}}" data-execution_count="66">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb79" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb79-1"></span>
<span id="cb79-2">converted <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [parse_ingredient_line(item) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> item <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> translated_all[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>]]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> converted</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="66">
<pre><code>[{'quantity': 1000.0, 'unit': &lt;Unit('gram')&gt;, 'name': 'sugar', 'note': ''},
 {'quantity': 1.0, 'unit': &lt;Unit('kilogram')&gt;, 'name': 'sugar', 'note': ''},
 {'quantity': 1.0, 'unit': &lt;Unit('kilogram')&gt;, 'name': 'sugar', 'note': ''},
 {'quantity': 1.0, 'unit': &lt;Unit('tablespoon')&gt;, 'name': 'sugar', 'note': ''}]</code></pre>
</div>
</div>
<div id="bf516cf87c621685" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:23:14.676807Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:23:14.673074Z&quot;}}" data-execution_count="67">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb81" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb81-1">names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [t[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> t <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> converted]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> names</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="67">
<pre><code>['sugar', 'sugar', 'sugar', 'sugar']</code></pre>
</div>
</div>
</section>
<section id="clustering-aggregation-output" class="level3" data-number="3.4">
<h3 data-number="3.4" class="anchored" data-anchor-id="clustering-aggregation-output"><span class="header-section-number">3.4</span> Clustering, aggregation &amp; output</h3>
<p>The next steps work the same way as before</p>
<div id="7e5f26e1c568cf3f" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:23:29.925254Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:23:29.895912Z&quot;}}" data-execution_count="69">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb83" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb83-1">clusters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cluster_same_concept_transitive_winkler(names, model_emb)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>clusters</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="69">
<pre><code>{'sugar': 0}</code></pre>
</div>
</div>
<div id="dbc5a2b3bdb40aae" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:23:38.356433Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:23:38.353156Z&quot;}}" data-execution_count="70">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb85" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb85-1">merged <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> aggregate_by_concept(converted, clusters)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>merged</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="70">
<pre><code>[(3015.0, 'g', 'sugar')]</code></pre>
</div>
</div>
<div id="bc15626b59f4d0ec" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:23:41.207678Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:23:41.204149Z&quot;}}" data-execution_count="71">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb87" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb87-1">out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> format_aggregate(merged)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>out</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="71">
<pre><code>['3.015kg sugar']</code></pre>
</div>
</div>
</section>
<section id="backtranslation" class="level3" data-number="3.5">
<h3 data-number="3.5" class="anchored" data-anchor-id="backtranslation"><span class="header-section-number">3.5</span> Backtranslation</h3>
<p>The user will have his own native language; therefore, we need to translate back from English to that language. However, this time we know the languages, so we do not need fastdetect.</p>
<div id="ff313a1a8d7d41f0" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:23:46.410904Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:23:46.405191Z&quot;}}" data-execution_count="72">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb89" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb89-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> transformers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> MarianMTModel, MarianTokenizer</span>
<span id="cb89-2"></span>
<span id="cb89-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Add the reverse models</span></span>
<span id="cb89-4">BACK_MODELS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb89-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fr'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Helsinki-NLP/opus-mt-en-fr'</span>,</span>
<span id="cb89-6">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'de'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Helsinki-NLP/opus-mt-en-de'</span></span>
<span id="cb89-7">}</span>
<span id="cb89-8"></span>
<span id="cb89-9">back_cache <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb89-10"></span>
<span id="cb89-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> back_translate_from_english(text, target_lang):</span>
<span id="cb89-12">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb89-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Translate English text back into the target language ('fr' or 'de')</span></span>
<span id="cb89-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    using OPUS-MT.  Falls back to English if no model is defined.</span></span>
<span id="cb89-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb89-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> target_lang <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> BACK_MODELS <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> target_lang <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"en"</span>:</span>
<span id="cb89-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> text</span>
<span id="cb89-18"></span>
<span id="cb89-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> target_lang <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> back_cache:</span>
<span id="cb89-20">        model_name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> BACK_MODELS[target_lang]</span>
<span id="cb89-21">        back_cache[target_lang] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb89-22">            MarianTokenizer.from_pretrained(model_name),</span>
<span id="cb89-23">            MarianMTModel.from_pretrained(model_name)</span>
<span id="cb89-24">        )</span>
<span id="cb89-25"></span>
<span id="cb89-26">    tok, mod <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> back_cache[target_lang]</span>
<span id="cb89-27">    inputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tok(text, return_tensors<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pt"</span>, truncation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb89-28">    outputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mod.generate(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>inputs)</span>
<span id="cb89-29">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tok.decode(outputs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], skip_special_tokens<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div></div>
</div>
<div id="2531a9c9dbdf71bb" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:23:51.289387Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:23:49.396988Z&quot;}}" data-execution_count="73">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb90" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb90-1">back_translate_from_english(out, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'de'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="73">
<pre><code>'3,015 kg Zucker'</code></pre>
</div>
</div>
<p>The models even translated the floating point seperator from ‘.’ to ‘,’ . However, we now need four models for three languages. Maybe a bigger model is not too bad.</p>
</section>
<section id="evaluation" class="level3" data-number="3.6">
<h3 data-number="3.6" class="anchored" data-anchor-id="evaluation"><span class="header-section-number">3.6</span> Evaluation</h3>
<div id="6d242544cd1a9da2" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:47:01.134176Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:47:01.120640Z&quot;}}" data-execution_count="132">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb92" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb92-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> convert_ingredient_parser(ing_list, model):</span>
<span id="cb92-2">    translated_all<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[]</span>
<span id="cb92-3"></span>
<span id="cb92-4">    translated <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [a <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> a, _ <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> (translate_to_english_helsinki_with_fastdetect_v2(normalize_qty(x)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> ing_list)]</span>
<span id="cb92-5">    translated_all.append({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>:translated})</span>
<span id="cb92-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> translated_all:</span>
<span id="cb92-7">        converted <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [parse_ingredient_line(item) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> item <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>]]</span>
<span id="cb92-8"></span>
<span id="cb92-9">    names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [t[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> t <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> converted]</span>
<span id="cb92-10">    clusters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cluster_same_concept_transitive_winkler(names, model)</span>
<span id="cb92-11">    merged <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> aggregate_by_concept(converted, clusters)</span>
<span id="cb92-12">    out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> format_aggregate(merged)</span>
<span id="cb92-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> out</span></code></pre></div></div>
</div>
<div id="fd57e3bd19762727" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:47:05.708049Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:47:02.174458Z&quot;}}" data-execution_count="133">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb93" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb93-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> case <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> test_cases:</span>
<span id="cb93-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>],convert_ingredient_parser(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>], model_emb))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>['3l milk'] ['3 l milk']
['3l milk'] ['3 l whole milk']
['3l milk'] ['3 l hot milk']
['3kg sugar'] ['3 kg sugar', '15 ml sugar']
['1kg brown sugar', '1kg white sugar'] ['3 kg brown sugar']
['4 eggs'] ['3  eggs', '1  None']
['3 bread'] ['1  wand', '2  bread']
['2 bottles of water', '1 bottle of wine'] ['2 bottle water', '1 bottle wine']
['3l Oatly Milk'] ['3 l None']
['1.5kg rice'] ['1 kg rice', '500 g None']
['3 onions'] ['3  onion']
['3 bell peppers'] ['2  bell pepper', '1  capsicum']
['3 red pepper flakes'] ['1  red pepper flakes', '2  chili flakes']
['3 tbsp butter'] ['15 ml butter', '1  butter', '1  None']
['3 tsp salt'] ['10 ml salt', '1  None']
['3 cans crushed tomatoes'] ['3 can crushed tomatoes']
['3 cups yogurt'] ['480 ml yogurt', '1  None']
['3 tbsp olive oil'] ['30 ml olive oil', '1  None']
['2 bread', '1 croissant'] ['1  increasing', '1  pain', '1  bread']
['300g cheese'] ['300 g cheese']
['3kg flour'] ['3 kg flour']</code></pre>
</div>
</div>
<div id="5d98a59b50352f99" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-15T09:47:13.312545Z&quot;,&quot;start_time&quot;:&quot;2025-10-15T09:47:09.665635Z&quot;}}" data-execution_count="134">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb95" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb95-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> case <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> test_cases_long_sentences:</span>
<span id="cb95-2">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected"</span>],convert_ingredient_parser(case[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span>], model_emb))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>['3 onions'] ['3  yellow onion']
['2 cups mango chunks'] ['480 ml mango chunks']
['1.5 sticks butter'] ['120 ml butter', '200 g butter']
['3 tbsp cilantro'] ['15 ml cilantro', '1  None', '15 ml coriander']
['3 bell peppers'] ['3  bell pepper']
['6 cloves garlic'] ['6 cloves garlic']
['3 bell peppers'] ['2 stalk bell peppers', '1  tige de poivron']
['3 tsp garam masala'] ['12.5 ml garam masala', '1  None']
['3 pinches salt'] ['3  salt']
['3 handfuls nuts'] ['3  nuts']
['6 cups milk or cream'] ['1.44 l milk']
['3 tbsp olive oil'] ['45 ml olive oil']
['3 cups chopped tomatoes'] ['240 ml tomatoes', '2 can tomatoes']
['3 bottles of water'] ['3 bottle water']
['3 cans coconut milk'] ['2 can coconut milk', '1 box coconut milk']
['3 potatoes'] ['3  potato']
['6 onions'] ['4  onions', '2  petits oignons']</code></pre>
</div>
</div>
</section>
</section>
<section id="lesssons-learned" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="lesssons-learned"><span class="header-section-number">4</span> Lesssons learned</h2>
<p>After all this, the verdict is still “not convinced.”</p>
<p>The translation models sometimes work impressively well. For short, multilingual phrases like ingredients (<code>riz</code>), the context is sometime too thin to provide meaningful embeddings.</p>
<p>The experiments reveal a big flaw in the use of NLP. Much of our daily communication is implicit. Humans excel at resolving short information flow in the current context. LLM would need to be told the same context, exploding token cost and making the approach economically unrealistic.</p>
<p>For production use, hybrid approaches will win: structured ontology with model-based matching and maybe some translation. However, that is exactly what I wanted to avoid. The user needs to input data. For a new user it is not evident that he could speed up the process by teaching the computer instead of doing the work himself. If users are to benefit from shared data, strict processes for privacy protection become necessary.</p>


</section>

 ]]></description>
  <category>Machine Learning</category>
  <category>Applied Engineering</category>
  <guid>https://www.storymelange.com/posts/projects/recipescanner/smart_shopping_list.html</guid>
  <pubDate>Tue, 04 Nov 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>When to use pydantic in your app?</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/recipescanner/when-to-use-pydantic-in-your-app.html</link>
  <description><![CDATA[ 




<section id="a-tale-of-two-classes" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="a-tale-of-two-classes"><span class="header-section-number">1</span> A tale of two classes</h2>
<section id="the-balance-between-structure-and-speed" class="level3" data-number="1.1">
<h3 data-number="1.1" class="anchored" data-anchor-id="the-balance-between-structure-and-speed"><span class="header-section-number">1.1</span> The balance between structure and speed</h3>
<p>AI agents, LLM api calls and the overall microservice architecture of modernd AI applications passes data over many interfaces. The real challenge behind all this is not speed, but managing complexity and structure.</p>
<p>Too much validation at the interfaces and your system drags. Too little, and single malformed entry can blow everything up.</p>
</section>
<section id="a-debugging-nightmare" class="level3" data-number="1.2">
<h3 data-number="1.2" class="anchored" data-anchor-id="a-debugging-nightmare"><span class="header-section-number">1.2</span> A debugging nightmare</h3>
<p>I recently started building a recipe-digitization platform for cookbooks.</p>
<p>The data of single “recipe” object snakes through:</p>
<ol type="1">
<li>The frontend app.</li>
<li>FastAPI (request body validation).</li>
<li>A LangGraph pipeline that does OCR, LLM classification, nutrition maths.</li>
<li>PostgreSQL for storage.</li>
<li>Retrieval from storage.</li>
<li>Another LangGraph pipeline for recommendations and question answering</li>
</ol>
<p>That data crosses <strong>six</strong> trust boundaries. One malformed field and the whole chain can break. Without proper testing or custom exceptions it will not even be clear where the chain broke.</p>
<p>Imagine the frontend sends <code>"calories": "three hundred"</code> instead of <code>300</code>.<br>
FastAPI happily passes it along, the LangGraph pipeline classifies it, your nutrition module tries to sum up the numbers — and somewhere deep inside, Python raises <code>TypeError: unsupported operand type(s) for +: 'int' and 'str'</code>.<br>
By then the stack trace is six layers deep and no one remembers which hop introduced the bad data.</p>
</section>
<section id="why-pydantic-matters" class="level3" data-number="1.3">
<h3 data-number="1.3" class="anchored" data-anchor-id="why-pydantic-matters"><span class="header-section-number">1.3</span> Why Pydantic matters</h3>
<p>Interface contracts is where Pydantic shines: every hop can call <code>model_validate()</code>. The invalid or missing fields are found at every link.</p>
<p>With an ordinary class you’d need a minefield of <code>if not isinstance()</code> checks or hope that the error explodes somewhere downstream and you have good exception handling in place.</p>
</section>
<section id="when-speed-wins" class="level3" data-number="1.4">
<h3 data-number="1.4" class="anchored" data-anchor-id="when-speed-wins"><span class="header-section-number">1.4</span> When speed wins</h3>
<p>But if your code is a tight loop (<a href="../../../posts/clean-architecture/premature-optimization-and-the-importance-of-algorithms.html">see also this post</a>), which mutates ten thousand bounding-boxes per second, the extra validation overhead is waste you can’t afford.</p>
<p>That’s when a plain <code>@dataclass</code> is better.</p>
</section>
<section id="the-decision-that-shapes-your-system" class="level3" data-number="1.5">
<h3 data-number="1.5" class="anchored" data-anchor-id="the-decision-that-shapes-your-system"><span class="header-section-number">1.5</span> The decision that shapes your system</h3>
<p>So how do you decide when to pick which. The decision is usually done early in the development, as switching comes at a cost.</p>
<p>Read on for my guide of <code>pydantic</code> vs.&nbsp;<code>dataclass</code>.</p>
</section>
</section>
<section id="when-pydantic-has-the-top-hand" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="when-pydantic-has-the-top-hand"><span class="header-section-number">2</span> When Pydantic has the top hand</h2>
<section id="anything-public" class="level3" data-number="2.1">
<h3 data-number="2.1" class="anchored" data-anchor-id="anything-public"><span class="header-section-number">2.1</span> Anything public</h3>
<p>Public means “untrusted”: browser forms, mobile apps, webhook payloads, micro-service messages.</p>
<p>A rule of thumb: <strong>If humans or foreign code can hit an endpoint, wrap the payload in Pydantic.</strong></p>
<p>Pydantic will:</p>
<ul>
<li>Coerce <code>"42"</code> into <code>int(42)</code> and reject <code>"forty-two"</code>.</li>
<li>Produce gorgeous, self-updating OpenAPI docs for your front-enders.</li>
<li>Hand you a neat <code>.model_dump()</code> dict ready for JSON or logging.</li>
</ul>
</section>
<section id="pipes-dags-and-other-data-hurricanes" class="level3" data-number="2.2">
<h3 data-number="2.2" class="anchored" data-anchor-id="pipes-dags-and-other-data-hurricanes"><span class="header-section-number">2.2</span> Pipes, DAGs and other data hurricanes</h3>
<p>In a LangGraph or Airflow style pipeline, data hops from node to node.<br>
A single corrupted value will keep blowing up later nodes. It can be hard to track down the root cause.</p>
<p>Declaring each node’s input and output as Pydantic acts as formalization of the interface contract. If the contract is broken a validation error is raised immediately.</p>
</section>
<section id="anything-you-need-to-document" class="level3" data-number="2.3">
<h3 data-number="2.3" class="anchored" data-anchor-id="anything-you-need-to-document"><span class="header-section-number">2.3</span> Anything you need to document</h3>
<p>If your product requires interface documentation of modules, explaining the interface in a docstring is waste.<br>
Pydantic (especially inside FastAPI) auto-publishes a living JSON schema. Your docs automatically stay aligned with reality; no code-docu schism.</p>
</section>
</section>
<section id="when-a-dataclass-wins" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="when-a-dataclass-wins"><span class="header-section-number">3</span> When a dataclass wins</h2>
<section id="performance-critical-inner-loops" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="performance-critical-inner-loops"><span class="header-section-number">3.1</span> Performance-critical inner loops</h3>
<p>Parsing and validating thousands of objects per second costs CPU.<br>
If you’re:</p>
<ul>
<li>Transforming video frames</li>
<li>Running physics simulations</li>
<li>Streaming sensor data</li>
</ul>
<p>…then a bare <code>@dataclass</code> is often 10-15× faster to instantiate. You already trust the numbers, only the documentation of the interface contract requires more manual effort now.</p>
</section>
<section id="immutable-configuration" class="level3" data-number="3.2">
<h3 data-number="3.2" class="anchored" data-anchor-id="immutable-configuration"><span class="header-section-number">3.2</span> Immutable configuration</h3>
<p>App-level settings—API keys, directory paths—are loaded once at boot. After that they never change.<br>
A frozen <code>@dataclass</code> is lighter. You can still parse env files with tools like <code>python-dotenv</code>.</p>
</section>
<section id="library-code-that-must-stay-dependency-free" class="level3" data-number="3.3">
<h3 data-number="3.3" class="anchored" data-anchor-id="library-code-that-must-stay-dependency-free"><span class="header-section-number">3.3</span> Library code that must stay dependency-free</h3>
<p>If you publish a small library, dragging in Pydantic’s dependency tree is overkill for users.</p>
<p>Plain classes keep your footprint tiny and import times fast.</p>
</section>
<section id="behaviour-heavy-domain-objects" class="level3" data-number="3.4">
<h3 data-number="3.4" class="anchored" data-anchor-id="behaviour-heavy-domain-objects"><span class="header-section-number">3.4</span> Behaviour-heavy domain objects</h3>
<p>The more your class behaves like an <em>actor</em> (lots of methods, cached properties, custom <code>__eq__</code>), the less benefit you get from declarative validation. Pydantic is just additional formalism with little added value.</p>
</section>
</section>
<section id="practical-tips-for-your-project" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="practical-tips-for-your-project"><span class="header-section-number">4</span> Practical tips for your project</h2>
<section id="a-hybrid-pattern-that-scales" class="level3" data-number="4.1">
<h3 data-number="4.1" class="anchored" data-anchor-id="a-hybrid-pattern-that-scales"><span class="header-section-number">4.1</span> A hybrid pattern that scales</h3>
<p>From my research, I found that most large back-ends settle on three layers:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Layer</th>
<th>Typical choice</th>
<th>Rationale</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Edge / API</strong></td>
<td>Pydantic</td>
<td>Strong validation + OpenAPI</td>
</tr>
<tr class="even">
<td><strong>Core logic</strong></td>
<td>Mix &amp; match</td>
<td>Pydantic where data hops, dataclass for hot loops</td>
</tr>
<tr class="odd">
<td><strong>Persistence</strong></td>
<td>SQLAlchemy models</td>
<td>Mirrors DB; cast to/from Pydantic with <code>.model_validate()</code></td>
</tr>
</tbody>
</table>
<p>That means you can convert like so:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">dto   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RecipeRead.model_validate(orm_obj, from_attributes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ORM → DTO</span></span>
<span id="cb1-2">orm_obj.calories <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dto.calories                                   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># DTO → ORM</span></span></code></pre></div></div>
<p>No reflection required, and the mapping is crystal-clear.</p>
</section>
<section id="naming-endings-save-future-tears" class="level3" data-number="4.2">
<h3 data-number="4.2" class="anchored" data-anchor-id="naming-endings-save-future-tears"><span class="header-section-number">4.2</span> Naming endings save future tears</h3>
<p>Pydantic is frequently used on Public APIs, which support create, update, read methods.</p>
<p>Pick a convention on day one and never break it:</p>
<ul>
<li><code>RecipeCreate</code>, <code>RecipeUpdate</code>, <code>RecipeRead</code></li>
<li>Or <code>RecipeIn</code>, <code>RecipePatch</code>, <code>RecipeOut</code></li>
<li>Wrappers like <code>RecipePage</code>, <code>RecipeFilters</code></li>
</ul>
<p>When I started doing it, I thought three nearly identical models are redundant. Yet when the tar pit of complexity tries to drag you in, you are happy for every stick that you can reach; or in other words if you defined a Update Class with optional fields.</p>
</section>
<section id="decision-graph" class="level3" data-number="4.3">
<h3 data-number="4.3" class="anchored" data-anchor-id="decision-graph"><span class="header-section-number">4.3</span> Decision Graph</h3>
<p>You can use this graph to decide what to use.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">flowchart TD

A([Start]) --&gt; B{Will external input&lt;br/&gt;populate it?}

B --&gt;|Yes| P1[Pydantic]

B --&gt;|No| C{Does it cross a thread,&lt;br/&gt;process or service boundary?}

C --&gt;|Yes| P1[Pydantic]

C --&gt;|No| D{Instantiated in a tight loop&lt;br/&gt;thousands of times?}

D --&gt;|Yes| D1[Dataclass]

D --&gt;|No| E{Need brainy behaviour:&lt;br/&gt;caching, math ops, etc.?}

E --&gt;|Yes| CL[Plain class]

E --&gt;|No| F{Need OpenAPI or&lt;br/&gt;JSON Schema?}

F --&gt;|Yes| P1[Pydantic]

F --&gt;|No| CL[Plain class]
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
</section>
</section>
<section id="the-bottom-line" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="the-bottom-line"><span class="header-section-number">5</span> The bottom line</h2>
<ul>
<li>Pydantic is <em>not</em> just syntactic sugar; it is a contract, a validator, and a documentation generator baked into one.</li>
<li>Dataclasses and plain classes are perfect for tight, trusted, logic-heavy cores.</li>
<li>Large projects thrive when they <strong>mix them intentionally</strong>: Pydantic at the boundaries, dataclasses for heavy lifting.</li>
</ul>
<p>The real skill isn’t memorizing which decorator to use; it’s learning to see your system as a <strong>chain of trust boundaries</strong>.</p>
<p>Pydantic, dataclasses, or plain classes are just different ways of declaring that <strong>trust</strong>, what you <strong>verify</strong>, and where <strong>errors should surface</strong>.</p>
<p>In larger systems, this mindset scales beyond Python: enterprise teams in any language end up building similar constructs to formalize trust at their interfaces. The principle of trust boundaries endures.</p>
<p>In the end that also applies how people work together. Teams thrive on clear contracts and responsibility.</p>
<p>Structure buys clarity and, and clarity buys speed. Pydantic is one tool to execute this philosophy.</p>


</section>

 ]]></description>
  <category>Python</category>
  <category>Software Engineering</category>
  <guid>https://www.storymelange.com/posts/projects/recipescanner/when-to-use-pydantic-in-your-app.html</guid>
  <pubDate>Tue, 28 Oct 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>How LLMs help and don’t help developing software</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/a-year-in-pictures/how-llms-help-and-dont-help-developing-software.html</link>
  <description><![CDATA[ 




<section id="the-promised-land-of-vibe-coding" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="the-promised-land-of-vibe-coding"><span class="header-section-number">1</span> The promised land of vibe coding</h2>
<p>Everyone says large language models make developers faster.</p>
<p>I used to believe that too until I spent a week rebuilding a simple image pipeline with ChatGPT.</p>
<p>What I found wasn’t just slower progress. I found a new kind of slowness. The kind that exposes how shallow your understanding really is.</p>
<p>This is a story about how LLMs help and don’t help us develop software; where they speed up flow, and where they quietly erode focus, judgment, and attention.</p>
<section id="enter-the-test-subject-my-4-year-old-epaper-picture-frame" class="level3" data-number="1.1">
<h3 data-number="1.1" class="anchored" data-anchor-id="enter-the-test-subject-my-4-year-old-epaper-picture-frame"><span class="header-section-number">1.1</span> Enter the test subject: my 4-year-old Epaper picture frame</h3>
<section id="a-long-time-ago" class="level4" data-number="1.1.1">
<h4 data-number="1.1.1" class="anchored" data-anchor-id="a-long-time-ago"><span class="header-section-number">1.1.1</span> A long time ago</h4>
<p>Some years ago I developed an <a href="https://github.com/dolind/a-year-in-pictures">Epaper-based picture frame</a>.</p>
<p>The limited bit depth (3-bit) makes gray-scale images look flat. I used a dithering approach to get sharper images.</p>
<p>The core of that project was hardware embedded engineering, so I kept the software side light and relied on a GIMP batch processing pipeline.</p>
<p>GIMP has an implementation of the <a href="https://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering">Floyd-Steinberg dithering</a>.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/a-year-in-pictures/gimp.jpg" class="img-fluid figure-img"></p>
<figcaption>Gimp Version of Dithering with Floyd-Steinberg</figcaption>
</figure>
</div>
<p>I tried before to automate the process and do a simple script for image conversion. In my previous attempts, I could not get the exact same result as GIMP.</p>
</section>
<section id="the-age-of-ai-copilot-co" class="level4" data-number="1.1.2">
<h4 data-number="1.1.2" class="anchored" data-anchor-id="the-age-of-ai-copilot-co"><span class="header-section-number">1.1.2</span> The age of AI, Copilot &amp; Co</h4>
<p>In 2025, every software developer will have used AI-assisted programming. Some think it is useful; others are not entirely convinced.</p>
<p>I currently develop an AI-powered Meal Planner. I use ChatGPT a lot in the development as it allows me to outsource manual coding of trivial tasks, so I can focus on architecture tasks or more complex algorithms.</p>
<p>Lately, the responses have become better. So much, that I thought I could just redo the entire pipeline in a browser window. - We are all vibe coding now, aren’t we?</p>
<p>The Truth: in the end, I managed it.</p>
<p>See the fully working <a href="https://www.storymelange.com/a-year-in-pictures/">Demo</a> to play with.</p>
</section>
<section id="llms-make-us-faster" class="level4" data-number="1.1.3">
<h4 data-number="1.1.3" class="anchored" data-anchor-id="llms-make-us-faster"><span class="header-section-number">1.1.3</span> LLMs make us faster!</h4>
<p>That was my unequivocal belief before I sat out on this journey. Boy, was I wrong.</p>
<p>Using an LLM to do this side project led to many failed attempts and dead ends. With the change to GPT5, the LLM has become more confident in proposing false solutions.</p>
<p>This leads me to the core question I want to explore in this post: “Where do LLMs actually help us develop softwrae, and where do they mislead us?”</p>
<p>Read on, for the seven lessons I am going to share with you.</p>
</section>
</section>
</section>
<section id="lesson-1-llms-make-hard-problems-look-easy" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="lesson-1-llms-make-hard-problems-look-easy"><span class="header-section-number">2</span> Lesson #1: LLMs make hard problems look easy</h2>
<p>When I started recreating GIMPs Floyd-Steinberg dithering, I thought I’d be done in a breeze. After all, the algo is well documented and fairly simple. What could go wrong?</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/a-year-in-pictures/v6.jpg" class="img-fluid figure-img"></p>
<figcaption>Python implementation of Floyd-Steinberg, seems noisier than GIMP</figcaption>
</figure>
</div>
<p>Yet, my results looked noisier and flatter. A quick Google Search revealed others had reported similar mismatch, <a href="https://discourse.gnome.org/t/how-to-implement-the-floyd-steinberg-algorithm-from-gimp-in-your-code/23111">discussion here</a>.</p>
<p>Next comes what every curious engineer with the power of a mighty LLM at his fingertips would do: ask ChatGPT to reimplement <a href="https://gitlab.gnome.org/GNOME/gimp/-/blob/281548a022a0e7f3eaaa38e42ec29f919519c33a/app/core/gimpimage-convert-indexed.c#L3768">GIMP’s code</a>.</p>
<p>At first glance, the code seemed straightforward: C code, only heavily relying on raw pointers.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode c code-with-copy"><code class="sourceCode c"><span id="cb1-1">  src_buf  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> g_malloc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> src_bpp<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">);</span></span>
<span id="cb1-2">  dest_buf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> g_malloc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dest_bpp<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">);</span></span>
<span id="cb1-3">  next_row <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> g_new <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>gint<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">);</span></span>
<span id="cb1-4">  prev_row <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> g_new0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>gint<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">);</span></span></code></pre></div></div>
<p>ChatGPT immediately produced a fully working version,</p>
<p>…only the results were wrong.</p>
<p>Because the full code is too long for the context window, I tried to be clever: breaking it into smaller parts, adding missing functions.</p>
<p>Digging deeper, I found the issue is that the code relies on far more functions for tone mapping, error diffusion limits, histogram caching. Which rely on even more function.</p>
<p>None of which were in the initial prompt.</p>
<p>While I was adding more and more context, I was never getting the same result. What should have been the work of an afternoon already stretched over two days.</p>
<p>Then I realized the problem was not the LLM or GIMPS pointer code. The issue is, as always, the person in front of the machine; me.</p>
<p>Of course, I knew LLMs are good at pretending to be fluent, even when they are not. But the issue is that I could not recognize the illiteracy of ChatGPT with the dithering algo.</p>
<p><strong>Beginner Lesson</strong></p>
<p>LLMs can make hard problems look easy. Fluent coding isn’t the same as real understanding. LLMs expand the search space, not the understanding space.</p>
<p><strong>Intermediate Lesson</strong></p>
<p>Expand your own understanding space</p>
<ul>
<li>Understand an unknown solution and own it conceptually</li>
<li>Ask the model to explain its reasoning; don’t accept logic that feels incomplete</li>
<li>Explore boundaries with contrastive examples to see where it breaks.</li>
<li>Externalize your learning: keep a logbook, sketch diagrams, and track conversation branches.</li>
</ul>
<p><strong>Mastery Lesson</strong></p>
<p>Cultivate your intuition of when an LLM can be trusted, even in unfamiliar domains. That will make you truly faster.</p>
</section>
<section id="lesson-2-focus-on-the-value-add" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="lesson-2-focus-on-the-value-add"><span class="header-section-number">3</span> Lesson #2: Focus on the value add</h2>
<p>I probably should have been satisfied with my 1-bit Floyd Steinberg pipeline. Let’s recall, the real goal is to have my pictures on the wall in a dynamic picture frame.</p>
<p>But here’s the catch: going through my pictures and sorting them is actually far more effort than the conversion for the picture frame. The optimization of code paths, dithering algo testing and chasing marginal speedups did not add value to the actual problem.</p>
<p>That is the quiet but biggest danger of LLMs for mid-career developers: <em>you can solve so many problems, that you forget which ones are worth solving.</em></p>
<p>ChatGPT &amp; Co lower the barrier to a 50% solution; quick, plausible, traditionally used to get further funding. Those half-baked solutions create new problems: bugs, improvements to make, experiments to run.</p>
<p>From a meta perspective, it’s not so different from how low-impact tasks survive inside large organizations: easy to start, hard to stop.</p>
<p><strong>Beginner Lesson</strong></p>
<p>Learn to spot when ChatGPT suggests optimizations that don’t matter.</p>
<p><strong>Intermediate Lesson</strong></p>
<p>Adopt a product mindset. Clearly formulate the goal and what you want to achieve. Define what “done” means. Hold that line when the LLM tempts you with shiny detours.</p>
<p><strong>Mastery Lesson</strong></p>
<p>The tool amplifies habits. Develop good habits, drop bad ones.</p>
<ul>
<li>Calibrate to value: Write down <em>The value of this work is * because it improves * </em>. Revisit this statement after each hour.</li>
<li>Curiosity within boundaries: use constraints, time boxes, iteration caps</li>
<li>Mode awareness: define the mode: learning (speed, breadth, discovery) or production(depth, polish, delivery)</li>
<li>Reflection logbook: what helped, what kind of question was misleading? Reread your chats or transcripts.</li>
<li>Debug your thinking: ask yourself if you are framing the problem wrong.</li>
<li>Cultivate Strategic Boredom: stop when it is enough</li>
</ul>
</section>
<section id="lesson-3-correct-initial-framing-beats-repeated-prompting" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="lesson-3-correct-initial-framing-beats-repeated-prompting"><span class="header-section-number">4</span> Lesson #3: Correct initial framing beats repeated prompting</h2>
<p>Frustrated, I was about to give up. Then I stumbled across a new approach: the <a href="https://www.cada.art/columns/untitled">Teddy-Beau Algorithm</a>.</p>
<p>The algorithm creates multiple differently exposed versions of the image, then applies patterned dithering to each, and finally fuses the most contrasting regions. As a result, details stand out while maintaining the textured dither effect.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/a-year-in-pictures/v1.jpg" class="img-fluid figure-img"></p>
<figcaption>Teddy Beau 2D algorithm, has more contrast; the Bayer pattern leads to antialiasing effects when displayed smaller than actual size though.</figcaption>
</figure>
</div>
<p>The <a href="https://untitled.cada.art/gen.js">demo code</a> is written in JavaScript. As the author points out, it is not optimized and takes quite long.</p>
<p>So naturally, I asked my LLM buddy for help: <em>“How to optimize this for performance?”</em></p>
<p>ChatGPT responded like an eager intern:</p>
<ul>
<li>Flatten 2D arrays to 1D.</li>
<li>Avoid expensive array methods like <code>push</code>.</li>
<li>Use typed arrays for pre-allocation.</li>
<li>Try <code>Uint8ClampedArray</code> for automatic clamping.</li>
</ul>
<p>One more thing. Lately, I have been exploring how to push ML workloads to the client to reduce compute cost and preserve data privacy. This is made possible using a technique called <strong>WebGPU</strong>.</p>
<p>I doubled down and added the usage of <strong>WebGPU</strong> to my requirements. The dream of every product manager focusing on buzzwords alone: <strong>GPU acceleration</strong>, <strong>client-side compute</strong>, <strong>data privacy</strong>.</p>
<p>I asked for a straightaway optimization with fingers crossed.</p>
<p>The first result? A gray picture.</p>
<p>Then came hours of debugging, chasing error messages like a true VibeCoder.</p>
<p>Eventually, I gave up.</p>
<p>The realization: I didn’t need faster code.<br>
I needed a clearer architecture: what to optimize, in what order, and why.</p>
<p><strong>Beginner Lesson</strong></p>
<p>Don’t ask: “Make this faster”! Define what faster means; or explore this with the help of the LLM.</p>
<p><strong>Intermediate lesson</strong></p>
<p>Be an architect. Specify technical constraints. Define performance goals, and make the trade-offs explicit.</p>
<p><strong>Mastery Lesson</strong></p>
<p>Use the LLM to map the landscape, not to sprint through it. Explore what-ifs. Guard against LLM’s instinct to jump to code too quickly. Keep it in design mode.</p>
</section>
<section id="lesson-4-do-not-succumb-to-the-illusion-of-progress" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="lesson-4-do-not-succumb-to-the-illusion-of-progress"><span class="header-section-number">5</span> Lesson #4: Do not succumb to the illusion of progress</h2>
<p>I started from scratch, with an architect’s mindset. First, I asked to include the existing code on a web page that allows modifying parameters with sliders. That worked nicely. Then I told ChatGPT that we are going step by step in the transformation towards a WebGPU version.</p>
<p>The Plan:</p>
<ul>
<li>remove splice</li>
<li>flatten to 1D with typed arrays<br>
</li>
<li>pre-allocate arrays<br>
</li>
<li>replace Laplacian of Gaussian with Difference of Gaussian<br>
</li>
<li>SIMD: no map, only for<br>
</li>
<li>worker thread<br>
</li>
<li>use WebGL<br>
</li>
<li>use WebGPU</li>
</ul>
<p>The incremental work went smoothly and then WebGPU delivered the final wow effect: from 500 ms down to 20 ms for a 1MP image. I was ecstatic. Maybe this algorithm could even handle video!</p>
<p>But when I looked closer, the pictures weren’t pleasing.<br>
The contrast was wrong; the textures felt flat. The <em>fast</em> version looked worse than the slow one.</p>
<p>It turned out that Difference of Gaussian is not the same as Laplacian of Gaussian and that the whole histogram calculation had been changed.</p>
<p>In chasing performance without reflection, I had altered the architecture.</p>
<p>In hindsight, the obvious solution: go slow and use tests. But in that moment, momentum felt like mastery.</p>
<p><strong>Beginner Lesson</strong></p>
<p>“Working” code does not imply “correct” code. Pure vibe coding hides understanding behind motion.</p>
<p><strong>Intermediate Lesson</strong></p>
<p>Resist the illusion of speed. Go slow and write tests. Verify that the tests are correctly written by the LLM. Validate progress with objective, measurable evidence.</p>
<p><strong>Mastery Lesson</strong></p>
<p>Let the model amplify your rigor, not bypass it. Ask for test scaffolds, validation metrics. Let the LLM be your QA nightmare. True velocity comes from confidence in correctness.</p>
</section>
<section id="lesson-5-allow-failures.-do-not-suffer-from-the-sunken-cost-fallacy." class="level2" data-number="6">
<h2 data-number="6" class="anchored" data-anchor-id="lesson-5-allow-failures.-do-not-suffer-from-the-sunken-cost-fallacy."><span class="header-section-number">6</span> Lesson #5: Allow failures. Do not suffer from the sunken cost fallacy.</h2>
<p>I probably should have stopped.</p>
<p>But after getting so close, it felt wrong to quit. “All I need are a few simple tests,” I told myself. I started working on 3x3 images and actually managed to progress quickly through the codebase.</p>
<p>However, I underestimated the issues that arise in complex floating-point algorithms. The algorithm is doing several passes for the actual dithering and combines Bayer-based dithering with error diffusion (the original article explains this in more detail).</p>
<p>That means any rounding errors can propagate through the image.</p>
<p>On small samples, the errors make no change. On full-size images, the algorithm fell apart.</p>
<p>In fact, I never got 100% equality on a 1MP image with the highest settings for iterative processing, even after days chasing tiny differences caused by inequality signs, truncation, and clamping.</p>
<p>At some point, I realized I wasn’t debugging anymore — I was <em>defending my investment</em>.<br>
The LLM kept offering “helpful” directions, and I kept following, the way I once followed overconfident colleagues early in my career.</p>
<p>They sounded sure. So did the model.<br>
But confidence isn’t correctness.</p>
<p>Sometimes, the real progress is in allowing failure.</p>
<p><strong>Beginner Lesson</strong></p>
<p>When you keep solving the same issue, that is not progress, that is pure grind. Know when to stop.</p>
<p><strong>Intermediate Lesson</strong></p>
<p>LLMs remove friction in syntax and reference lookup. But they also remove the pauses that help us think. Deliberately reintroduce these pauses. Use time-boxing or amount of code change.</p>
<p><strong>Mastery Lesson</strong></p>
<p>Use the LLM to structure your reflection. Ask for summaries, dead ends, and hypotheses that were made.</p>
</section>
<section id="lesson-6-technology-fixation-hides-the-real-problem" class="level2" data-number="7">
<h2 data-number="7" class="anchored" data-anchor-id="lesson-6-technology-fixation-hides-the-real-problem"><span class="header-section-number">7</span> Lesson #6: Technology fixation hides the real problem</h2>
<p>Eventually, I made the algorithm’s result identical.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/a-year-in-pictures/v2.jpg" class="img-fluid figure-img"></p>
<figcaption>1D optimized version, same as 2D version</figcaption>
</figure>
</div>
<p>But the speedups I’d worked so hard for had almost vanished. In single-pass runs, performance improved from 380 ms to 350ms. Only in the multi-pass runs did it look better: 4.7s down to 2s.</p>
<p>Still, I wasn’t done. I wanted to use <strong>WebGPU</strong>.</p>
<p>So, I turned to ChatGPT once again.<br>
It happily produced WebGPU code. Due to the immature state of WebGPU and limited sources, the code was incomplete and buggy, but plausible. I fixed syntax errors, adjusted shader parameters, and eventually got something to run.</p>
<p>The result: an educational detour into shaders, pipelines, and GPU execution (Yes, I am a GPU engineer now :-)).</p>
<p>Performance improvements were good: using 2 passes, from 2s down to 1s. Using 6 passes: 25s down to 2.8s.</p>
<p>Again, visual result was worse than the CPU version.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/a-year-in-pictures/v3.jpg" class="img-fluid figure-img"></p>
<figcaption>GPU Version is darker and more uniform</figcaption>
</figure>
</div>
<p>That’s when I finally stopped myself.</p>
<p>Somewhere along the way, I had forgotten that looking better was the reason I had selected the algorithm.</p>
<p><strong>Beginner Lesson</strong></p>
<p>Speed gains are meaningless if they don’t serve the goal. Always ask: What does this achieve? What impact does it have on the outcome?</p>
<p><strong>Intermediate Lesson</strong></p>
<p>AI tools make every technical path feel accessible. And in part that is true. But every new route has hidden costs. For every new route you take, define what success means. If the gain doesn’t improve the purpose, skip it.</p>
<p><strong>Mastery Lesson</strong></p>
<p>Again, focus on the landscape. Let curiosity drive exploration, but set limits with an intent. AI’s biggest cost isn’t in tokens; it’s your attention.</p>
</section>
<section id="lesson-7-ai-mirrors-your-thinking-including-your-flaws" class="level2" data-number="8">
<h2 data-number="8" class="anchored" data-anchor-id="lesson-7-ai-mirrors-your-thinking-including-your-flaws"><span class="header-section-number">8</span> Lesson #7: AI mirrors your thinking, including your flaws</h2>
<p>Lesson 6 was about chasing performance. This lesson is quite similar but focuses on features.</p>
<p>Using an LLM chat, everything feels easy. You start with a clear goal, then you drift and start exploring aspects which feel productive but aren’t.</p>
<p>It’s a lot like browsing the internet: you end up finding things you never searched.</p>
<p>The issue with the LLM is that it reinforces you in the believe of wrong ideas. That’s why many say AI assistants only work well “in the hands of an expert.”</p>
<p>I agree only partly. An expert would only need the AI for very mundane tasks, like code completion. It’s the non-expert, facing a new domain who gains the most. But only if he manages to stop the wandering mind and meandering that come with it.</p>
<p>AI is an amplifier, not a guide. It doesn’t tell you when your reasoning is off; it makes your detour smoother. To quote I, Robot: you need to “ask the right questions”.</p>
<p>In traditional software teams, that role falls to senior engineers and technical managers. They define the what and the why of the product.</p>
<p>With LLMs, you need to play the roles yourself to be successful. You’re not just writing code; you’re managing a conversation that can spiral without direction.</p>
<p>Back to our real problem: displaying images on Epaper. When I read through the Inkplate code and API, I noticed that it also supports a 3bit mode. Quick modification in my 1bit Python script: a simple 3-bit Floyd–Steinberg algorithm almost looks 8bit Grayscale.</p>
<p>Then why not use the Teddy-Beau algorithm with 3bit?</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/a-year-in-pictures/v5.jpg" class="img-fluid figure-img"></p>
<figcaption>3bit Floyd Steinberg, looks almost like an 8bit grayscale picture</figcaption>
</figure>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/a-year-in-pictures/v4.jpg" class="img-fluid figure-img"></p>
<figcaption>3bit Teddy Beau, more contrast in the trees but too much in the sky in this picture.</figcaption>
</figure>
</div>
<p>Comparing the two 3bit versions, I actually like the 3bit Floyd-Steinberg more than the 3bit Teddy-Beau. What was wrong this time, you might wonder? Everything looks good?</p>
<p>Epaper has a non-linear color curve. What looked perfect on a monitor looked wrong on the device.</p>
<p>Finally, I chose the Teddy Beau algorithm with 1Bit, which from 2 meters away looks a lot better than on a computer screen.</p>
<p><strong>Beginner Lesson</strong></p>
<p>LLM rarely correct wrong assumptions unless prompted to do so.</p>
<p><strong>Intermediate Lesson</strong></p>
<p>Don’t expect the LLM to know your true goal. Define context, constraints, and success criteria yourself. The system prompt is your friend.</p>
<p><strong>Mastery Lesson</strong></p>
<p>Treat the LLM as a mirror, not a mentor. Its responses reflect your framing, clarity, and discipline. You’re not its student. You’re its manager!</p>
</section>
<section id="conclusion-the-real-work-is-thinking" class="level2" data-number="9">
<h2 data-number="9" class="anchored" data-anchor-id="conclusion-the-real-work-is-thinking"><span class="header-section-number">9</span> Conclusion: The real work is thinking</h2>
<p>After a week of chasing algorithmic performance gains, I realized the project’s real contribution wasn’t in the image pipeline. Instead, it was in understanding how humans and machines can think together.</p>
<p>Rather than exposing the limits of its reasoning the LLM revealed the limits of mine. In this article every lesson mapped to a deeper skill.</p>
<ul>
<li><strong>Conceptual clarity</strong> to increase your understanding space</li>
<li><strong>Prioritization</strong> to focus on value, not optimization.</li>
<li><strong>Problem definition</strong> to frame correctly before prompting.</li>
<li><strong>Discipline</strong> to follow a stable process</li>
<li><strong>Self-awareness</strong> to allow failures.</li>
<li><strong>Purpose alignment</strong> to avoid focusing on technology alone.</li>
<li><strong>Judgment</strong> to intentionally direct human-machine interaction</li>
</ul>
<p>In short, AI is not a shortcut to mastery. It’s a mirror, reflecting your strengths, weaknesses, and habits on steroids.</p>
<p>The promise of LLMs isn’t speed; it’s awareness.</p>
<p>They expose how we think, where we skip steps, and how easily we confuse momentum for mastery.</p>
<p>Working with an LLM is no longer about writing code faster.<br>
It’s about developing a clearer mind.</p>
<p>In the end, building software, and yourself, means learning to manage not just a tool, but your own attention.</p>
<p>That’s the real craft of this new era: knowing when to move fast, and when to slow down on purpose.</p>
<hr>
<p>A hammer is only as precise as the hand (and mind) that wields it.</p>
<hr>
<p>The algorithms can be compared <a href="https://www.storymelange.com/a-year-in-pictures/">here</a>. Source Code can be found <a href="https://github.com/dolind/a-year-in-pictures">here</a>.</p>


</section>

 ]]></description>
  <category>Software Engineering</category>
  <category>Management</category>
  <category>Generative AI</category>
  <guid>https://www.storymelange.com/posts/projects/a-year-in-pictures/how-llms-help-and-dont-help-developing-software.html</guid>
  <pubDate>Sat, 25 Oct 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Page Segmentation: The easy and the hard way</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/recipescanner/page_segmentation.html</link>
  <description><![CDATA[ 




<section id="many-ways-lead-to-digitized-documents" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="many-ways-lead-to-digitized-documents"><span class="header-section-number">1</span> Many ways lead to digitized documents</h2>
<p>When I first started working on recipescanner, the biggest issue was scanning multi column pages and multi recipe pages. How to group the output from the OCR scan in such a way that recipes are not mixed with each other?</p>
<p>The following table shows different options of workflows, from image to fully parsed recipe.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 21%">
<col style="width: 27%">
<col style="width: 18%">
<col style="width: 13%">
<col style="width: 14%">
<col style="width: 3%">
</colgroup>
<thead>
<tr class="header">
<th><strong>Option</strong></th>
<th><strong>How it Works</strong></th>
<th><strong>Speed (per page)</strong></th>
<th><strong>Needs</strong></th>
<th><strong>Best When</strong></th>
<th><strong>Cost</strong></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>1. OCR → LLM Parsing</strong></td>
<td>Extract with OCR, LLM for classification</td>
<td>3–5 s (small LLM)<br>15–30 s (vision-LLM)</td>
<td>GPU or strong CPU, few GB RAM</td>
<td>Layouts are messy</td>
<td>Medium</td>
</tr>
<tr class="even">
<td><strong>2. Vision → Text (Donut / Pix2Struct)</strong></td>
<td>End-to-end vision does classification</td>
<td>0.8–2 s on GPU</td>
<td>GPU / NNAPI required</td>
<td>Handwriting, warped images</td>
<td>High</td>
</tr>
<tr class="odd">
<td><strong>3. OCR → Segmentation → Rules / Small Model</strong></td>
<td>Extract with OCR, Rules or DecisionTree for classification</td>
<td>0.3 s on CPU</td>
<td>CPU only, ~400 MB RAM</td>
<td>Scans are clean and structured</td>
<td>Low</td>
</tr>
</tbody>
</table>
<p>For pages with multiple recipes, the approach can be separated into two stages.</p>
<ol type="1">
<li>Image to Text Blocks and recipe sections</li>
<li>Classification of each recipe into ingredients, description, …</li>
</ol>
<p>The division of the task into smaller tasks allows us to use less complex methods. In this notebook we focus on the task #1.</p>
<section id="using-llm-api" class="level3" data-number="1.1">
<h3 data-number="1.1" class="anchored" data-anchor-id="using-llm-api"><span class="header-section-number">1.1</span> Using LLM API</h3>
<p>Nowadays, one straightforward solution is to run an LLM on the OCR output and ask it to cluster the text. You can even set up a complete workflow: cluster the text, check it, extract ingredients and instructions and the check again to ensure all content is used recipes are not mixed up.</p>
<p>The downside about all this? It is expensive to run. Especially if we introduce correctness checks. How much more expensive?</p>
<p>For reference, Google currently charges $1.5 per 1000 pages, whereas as Mistral asks for $3 per 1000 pages for annotated output. Google’s new interface, which (like Mistral) relies on Vision Transformers also charges asks for $1.5 per 1000 pages. Layout parsing costs extra at $10 per 1000 pages.</p>
<p>Let’s say each of your users has about 2000 books he wants to convert. That results to $23 per user; and that is without classification. A custom extractor sets you back another $20. So the full workflow is about $50 per user. Again only for recipe extraction. Interaction with the recipe database will probably cost around $3 per month.</p>
</section>
<section id="the-new-way-end-to-end-conversion" class="level3" data-number="1.2">
<h3 data-number="1.2" class="anchored" data-anchor-id="the-new-way-end-to-end-conversion"><span class="header-section-number">1.2</span> The new way: end-to-end conversion</h3>
<p>I recently tested <a href="https://github.com/docling-project/docling">Docling</a>, a transformer-based architecture. It has created quite a buzz recently.</p>
<p>Here is my short evaluation. On the document which we are going to use throughout this notebook, it failed. The deterministic demo (temperature=0) got stuck in an inference loop. I tried increasing temperature and add other tweaks to help the model escape local optima. This came at the cost of accuracy.</p>
<p>The model repeated titles as ingredients for other recipes and failed to stop properly.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/pictures/docling.jpg" class="img-fluid figure-img"></p>
<figcaption>Docling Result: one recipe title is not detected as such</figcaption>
</figure>
</div>
<p>The model has issue with line breaks: “Die Pilze damit bin-den” became “Pilze damit ben den” including line breaks.</p>
<p>On top of that, the speed was poor on a legacy GPU (GTX 1080), despite running at full load for the full time of 22 seconds! Memory consumption was steadily increasing as more tokens were decoded, just barely fitting on the 8GB GPU with 6.5GB max usage.</p>
<p>Reflecting on the architecture, I suspect it must work better on obscure edge cases. Complex Formats with overlaying figures or strongly nested tables could perform better.</p>
<p>Strangely, even the <a href="https://huggingface.co/spaces/ibm-granite/granite-docling-258m-demo">demo</a> mostly showcases simple formats.</p>
</section>
<section id="the-not-so-easy-way" class="level3" data-number="1.3">
<h3 data-number="1.3" class="anchored" data-anchor-id="the-not-so-easy-way"><span class="header-section-number">1.3</span> The not so easy way</h3>
<p>Layout Parsing is not new. In fact, it became popular about three years ago.</p>
<p>One such layout parser is the actual <a href="https://github.com/Layout-Parser/layout-parser">LayoutParser</a>. It combines an automatic analysis of OCR output and segmentation. Unfortunately, the segmentation is done with <a href="https://github.com/facebookresearch/detectron2">detecron2</a>. The active development seems to have stopped and it no longer works on my python installation (Python 3.12). My research revealed Python 3.9 as the last working version.</p>
<p>A more recent model is <a href="https://github.com/opendatalab/DocLayout-YOLO">DocLayout-YOLO</a>. Based on the already massive YOLO dataset, it uses a very large document dataset to identify bounding boxes and classification in a combined loss function.</p>
<p>What it lacks, however, is an automatic connection to OCR. One can either crop and ocr the text boxes or align with the OCR output.</p>
<p>Here is an example:</p>
<div id="368819313651c34d" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:35.426827Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:31.465697Z&quot;}}" data-execution_count="1">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Standard library</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> glob</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> json</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> os</span>
<span id="cb1-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> random</span>
<span id="cb1-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> warnings</span>
<span id="cb1-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> difflib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> SequenceMatcher</span>
<span id="cb1-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pathlib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Path</span>
<span id="cb1-9"></span>
<span id="cb1-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Third-party</span></span>
<span id="cb1-11"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> cv2</span>
<span id="cb1-12"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.patches <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> patches</span>
<span id="cb1-13"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-14"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-15"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-16"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> PIL <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Image, ImageDraw</span>
<span id="cb1-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Local / custom</span></span>
<span id="cb1-18"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> doclayout_yolo <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> YOLOv10</span>
<span id="cb1-19"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> accuracy_score</span>
<span id="cb1-20"></span>
<span id="cb1-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Jupyter magic</span></span>
<span id="cb1-22"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>matplotlib inline</span>
<span id="cb1-23"></span>
<span id="cb1-24"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Suppress all warnings (optional)</span></span>
<span id="cb1-25">warnings.filterwarnings(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ignore"</span>)</span></code></pre></div></div>
</details>
</div>
<div id="573b417a046662b9" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:36.390445Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:35.434196Z&quot;}}" data-execution_count="2">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> YOLOv10(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/models/doclayout_yolo.pt"</span>)</span>
<span id="cb2-2">det_res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.predict(</span>
<span id="cb2-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/20250922_135514.jpg"</span>,</span>
<span id="cb2-4">    imgsz<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>,</span>
<span id="cb2-5">    conf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>,</span>
<span id="cb2-6">    device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda:0"</span>,</span>
<span id="cb2-7">    verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb2-8">)</span></code></pre></div></div>
</details>
</div>
<div id="7e24ef28af72d99" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:37.380890Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:36.448593Z&quot;}}" data-execution_count="3">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">annotated_frame <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> det_res[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].plot(pil<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, line_width<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, font_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>)</span>
<span id="cb3-2">img_rgb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB)</span>
<span id="cb3-3"></span>
<span id="cb3-4">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>))</span>
<span id="cb3-5">plt.imshow(img_rgb)</span>
<span id="cb3-6">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb3-7">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Segmentation using Doclayout YOLO"</span>)</span>
<span id="cb3-8">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/page_segmentation_files/figure-html/cell-4-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Despite knowing nothing about the text, the CNN could still discover the layout. Which is clear, you don’t need to understand a language to break a book into paragraphs.</p>
<p>There are some errors in how the titles are handled. Bright red boxes highlight detected titles, and we can see that there are too many.</p>
<p>When we run the CUDA-enabled version, the total runtime is 164ms, 650ms for cold start, whereas on CPU it can take up to 1.6s.</p>
</section>
<section id="using-only-domain-knowledge" class="level3" data-number="1.4">
<h3 data-number="1.4" class="anchored" data-anchor-id="using-only-domain-knowledge"><span class="header-section-number">1.4</span> Using only domain knowledge</h3>
<p>And then there’s the domain knowledge approach. That is how I started. If we know all the text on a page, its location, and assume it’s a recipe: can we identify where recipes end, and which text belongs to which recipe?</p>
<p>In this notebook, I will examine this way and how it compares to DocLayout-YOLO.</p>
</section>
</section>
<section id="converting-data-to-dataframes" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="converting-data-to-dataframes"><span class="header-section-number">2</span> Converting Data to Dataframes</h2>
<p>We will perform a statistical analysis and therefore convert the data to pandas dataframes.</p>
<section id="ocr" class="level3" data-number="2.1">
<h3 data-number="2.1" class="anchored" data-anchor-id="ocr"><span class="header-section-number">2.1</span> OCR</h3>
<p>In my project, I currently rely on Google cloud OCR. Therefore, we need to convert the API response to a dataframe. While doing so, we also add information on font_size and word count.</p>
<div id="e6e251f78119f03b" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:37.476243Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:37.469423Z&quot;}}" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> ocr_json_to_df(ocr_json):</span>
<span id="cb4-2">    rows <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb4-3"></span>
<span id="cb4-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> block <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> ocr_json:</span>
<span id="cb4-5">        block_type <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> block[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blockType"</span>]</span>
<span id="cb4-6">        verts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> block[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"boundingBox"</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vertices"</span>]</span>
<span id="cb4-7">        x1, y1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb4-8">        x2, y2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb4-9"></span>
<span id="cb4-10">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Reconstruct text from words and establish size</span></span>
<span id="cb4-11">        block_words <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb4-12">        average_word_height_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb4-13">        word_counter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb4-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> para_idx, para <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(block.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"paragraphs"</span>, [])):</span>
<span id="cb4-15">            paragraph_words <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb4-16">            paragraph_average_word_height_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb4-17">            paragraph_word_counter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb4-18">            para_verts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> para[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"boundingBox"</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vertices"</span>]</span>
<span id="cb4-19">            px1, py1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> para_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), para_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb4-20">            px2, py2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> para_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), para_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb4-21">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> word_idx, word <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(para.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"words"</span>, [])):</span>
<span id="cb4-22">                symbols <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [s[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> word.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"symbols"</span>, [])]</span>
<span id="cb4-23">                word_text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>.join(symbols)</span>
<span id="cb4-24">                block_words.append(word_text)</span>
<span id="cb4-25">                paragraph_words.append(word_text)</span>
<span id="cb4-26"></span>
<span id="cb4-27">                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># store word-level rows (optional)</span></span>
<span id="cb4-28">                word_verts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> word[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"boundingBox"</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vertices"</span>]</span>
<span id="cb4-29">                wx1, wy1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> word_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), word_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb4-30">                wx3, wy3 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> word_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), word_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb4-31">                average_word_height_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> (wy3 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> wy1)</span>
<span id="cb4-32">                word_counter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb4-33">                paragraph_average_word_height_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> (wy3 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> wy1)</span>
<span id="cb4-34">                paragraph_word_counter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb4-35"></span>
<span id="cb4-36">            rows.append({</span>
<span id="cb4-37">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"level"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"paragraph"</span>,</span>
<span id="cb4-38">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>: px1, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>: py1, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>: px2, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>: py2,</span>
<span id="cb4-39">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>: paragraph_average_word_height_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> paragraph_word_counter,</span>
<span id="cb4-40">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" "</span>.join(paragraph_words),</span>
<span id="cb4-41">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block_type"</span>: block_type</span>
<span id="cb4-42">            })</span>
<span id="cb4-43"></span>
<span id="cb4-44">        rows.append({</span>
<span id="cb4-45">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"level"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block"</span>,</span>
<span id="cb4-46">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>: x1, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>: y1, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>: x2, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>: y2,</span>
<span id="cb4-47">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>: average_word_height_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> word_counter,</span>
<span id="cb4-48">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" "</span>.join(block_words),</span>
<span id="cb4-49">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block_type"</span>: block_type</span>
<span id="cb4-50">        })</span>
<span id="cb4-51"></span>
<span id="cb4-52">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame(rows)</span>
<span id="cb4-53"></span>
<span id="cb4-54">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"word_count"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>.split().<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>()</span>
<span id="cb4-55"></span>
<span id="cb4-56">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df</span></code></pre></div></div>
</div>
<div id="aa4ce5a151505b36" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:37.524435Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:37.521989Z&quot;}}" data-execution_count="5">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> read_json(image_id):</span>
<span id="cb5-2">    json_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Path(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/ocr/"</span>)</span>
<span id="cb5-3"></span>
<span id="cb5-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(json_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>image_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">.json"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb5-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> json.load(f)</span></code></pre></div></div>
</details>
</div>
<div id="60abe229ba438436" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:37.591057Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:37.569583Z&quot;}}" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"20250922_135514"</span></span>
<span id="cb6-2">page <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_json(filename)</span>
<span id="cb6-3">df_ocr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ocr_json_to_df(page)</span></code></pre></div></div>
</div>
<p>Let’s split block and paragraph rows for further processing.</p>
<div id="566429f15e7ef7d0" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:37.631557Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:37.622058Z&quot;}}" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">df_block <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_ocr[df_ocr[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"level"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block"</span>]</span>
<span id="cb7-2">df_para <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_ocr[df_ocr[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"level"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"paragraph"</span>]</span>
<span id="cb7-3">df_block.head()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="7">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">level</th>
<th data-quarto-table-cell-role="th">x1</th>
<th data-quarto-table-cell-role="th">y1</th>
<th data-quarto-table-cell-role="th">x2</th>
<th data-quarto-table-cell-role="th">y2</th>
<th data-quarto-table-cell-role="th">font_size</th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">block_type</th>
<th data-quarto-table-cell-role="th">word_count</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">1</th>
<td>block</td>
<td>874</td>
<td>2331</td>
<td>911</td>
<td>2355</td>
<td>24.000000</td>
<td>64</td>
<td>TEXT</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>block</td>
<td>853</td>
<td>484</td>
<td>1510</td>
<td>1389</td>
<td>31.902913</td>
<td>Die Butter zerlassen , das Weißbrot von beiden...</td>
<td>TEXT</td>
<td>103</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td>block</td>
<td>878</td>
<td>1501</td>
<td>1404</td>
<td>1737</td>
<td>52.375000</td>
<td>Soupe à l'ail bonne femme Knoblauchsuppe nach ...</td>
<td>TEXT</td>
<td>8</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">16</th>
<td>block</td>
<td>875</td>
<td>1815</td>
<td>1291</td>
<td>2081</td>
<td>32.761905</td>
<td>2 Stangen Porree ( Lauch ) 250 g enthäutete To...</td>
<td>TEXT</td>
<td>21</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">19</th>
<td>block</td>
<td>877</td>
<td>2101</td>
<td>989</td>
<td>2176</td>
<td>26.500000</td>
<td>Salz Pfeffer</td>
<td>TEXT</td>
<td>2</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
</section>
<section id="doclayout-yolo" class="level3" data-number="2.2">
<h3 data-number="2.2" class="anchored" data-anchor-id="doclayout-yolo"><span class="header-section-number">2.2</span> Doclayout YOLO</h3>
<p>DocLayout-YOLO returns boxes, labels, and confidence levels.</p>
<div id="5b8b22213bbe4418" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:37.679842Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:37.676535Z&quot;}}" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> yolo_to_df(result):</span>
<span id="cb8-2">    boxes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> result.boxes.xyxy.cpu().numpy()</span>
<span id="cb8-3">    labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> result.boxes.cls.cpu().numpy().astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>)</span>
<span id="cb8-4">    scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> result.boxes.conf.cpu().numpy()</span>
<span id="cb8-5">    names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> result.names</span>
<span id="cb8-6"></span>
<span id="cb8-7">    records <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb8-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> box, lbl, score <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(boxes, labels, scores):</span>
<span id="cb8-9">        x1, y1, x2, y2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> box.tolist()</span>
<span id="cb8-10">        label <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> names[lbl]</span>
<span id="cb8-11">        records.append({</span>
<span id="cb8-12">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>: x1,</span>
<span id="cb8-13">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>: y1,</span>
<span id="cb8-14">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>: x2,</span>
<span id="cb8-15">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>: y2,</span>
<span id="cb8-16">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: label,</span>
<span id="cb8-17">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"confidence"</span>: score,</span>
<span id="cb8-18">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>: (label.lower() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>)</span>
<span id="cb8-19">        })</span>
<span id="cb8-20"></span>
<span id="cb8-21">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> pd.DataFrame(records)</span></code></pre></div></div>
</div>
<div id="5508e190f5de7817" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:38.206181Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:37.932006Z&quot;}}" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">det_res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.predict(</span>
<span id="cb9-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/20250922_135514.jpg"</span>,</span>
<span id="cb9-3">    imgsz<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>,</span>
<span id="cb9-4">    conf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>,</span>
<span id="cb9-5">    device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda:0"</span>,</span>
<span id="cb9-6">    verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb9-7">)</span>
<span id="cb9-8">df_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> yolo_to_df(det_res[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>df_yolo</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="9">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">x1</th>
<th data-quarto-table-cell-role="th">y1</th>
<th data-quarto-table-cell-role="th">x2</th>
<th data-quarto-table-cell-role="th">y2</th>
<th data-quarto-table-cell-role="th">label</th>
<th data-quarto-table-cell-role="th">confidence</th>
<th data-quarto-table-cell-role="th">is_title</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>879.157227</td>
<td>1498.183594</td>
<td>1404.824463</td>
<td>1631.679443</td>
<td>title</td>
<td>0.922120</td>
<td>True</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>879.624573</td>
<td>1643.227661</td>
<td>1357.394409</td>
<td>1753.128174</td>
<td>plain text</td>
<td>0.903516</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>3569.065430</td>
<td>2246.001465</td>
<td>3609.026123</td>
<td>2281.185547</td>
<td>abandon</td>
<td>0.831622</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>2968.354492</td>
<td>450.490784</td>
<td>3297.232910</td>
<td>592.068970</td>
<td>title</td>
<td>0.809443</td>
<td>True</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">4</th>
<td>870.937500</td>
<td>2327.354248</td>
<td>912.915344</td>
<td>2362.086182</td>
<td>abandon</td>
<td>0.795582</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">5</th>
<td>874.531006</td>
<td>1780.801758</td>
<td>1492.744629</td>
<td>2286.900391</td>
<td>table</td>
<td>0.727726</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">6</th>
<td>1527.393433</td>
<td>598.798950</td>
<td>2144.085449</td>
<td>1672.833618</td>
<td>plain text</td>
<td>0.705026</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>2974.093750</td>
<td>598.492249</td>
<td>3467.499023</td>
<td>654.774719</td>
<td>plain text</td>
<td>0.638011</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">8</th>
<td>877.592163</td>
<td>465.383392</td>
<td>1481.144409</td>
<td>1402.559326</td>
<td>plain text</td>
<td>0.626123</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">9</th>
<td>2980.972656</td>
<td>682.661133</td>
<td>3532.022705</td>
<td>1200.553101</td>
<td>table</td>
<td>0.596943</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td>1526.767578</td>
<td>597.575073</td>
<td>2054.986328</td>
<td>686.416992</td>
<td>plain text</td>
<td>0.583433</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">11</th>
<td>2316.687988</td>
<td>450.310455</td>
<td>2927.670898</td>
<td>824.062439</td>
<td>plain text</td>
<td>0.513546</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">12</th>
<td>3022.026855</td>
<td>1725.583984</td>
<td>3593.486572</td>
<td>2192.724609</td>
<td>plain text</td>
<td>0.488287</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">13</th>
<td>2325.665283</td>
<td>856.174072</td>
<td>2937.416748</td>
<td>1041.672241</td>
<td>plain text</td>
<td>0.481687</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">14</th>
<td>2330.425537</td>
<td>1042.294434</td>
<td>2914.214844</td>
<td>1225.915161</td>
<td>plain text</td>
<td>0.477337</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">15</th>
<td>1532.011597</td>
<td>1245.381348</td>
<td>2047.088745</td>
<td>1337.381592</td>
<td>plain text</td>
<td>0.455887</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">16</th>
<td>2350.650879</td>
<td>1689.926758</td>
<td>2967.089355</td>
<td>1876.195068</td>
<td>plain text</td>
<td>0.453441</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">17</th>
<td>2337.659668</td>
<td>1229.601807</td>
<td>2960.235352</td>
<td>1686.113770</td>
<td>plain text</td>
<td>0.445066</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">18</th>
<td>1522.936157</td>
<td>457.546967</td>
<td>1769.362915</td>
<td>547.661194</td>
<td>title</td>
<td>0.433465</td>
<td>True</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">19</th>
<td>1525.181885</td>
<td>461.238281</td>
<td>1770.478882</td>
<td>548.516296</td>
<td>title</td>
<td>0.419111</td>
<td>True</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">20</th>
<td>1537.929932</td>
<td>1843.337891</td>
<td>2071.566162</td>
<td>1914.832031</td>
<td>title</td>
<td>0.392423</td>
<td>True</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">21</th>
<td>882.206665</td>
<td>469.045898</td>
<td>1474.692993</td>
<td>848.210815</td>
<td>plain text</td>
<td>0.391044</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">22</th>
<td>2355.457520</td>
<td>1878.174194</td>
<td>2988.262939</td>
<td>2259.762207</td>
<td>plain text</td>
<td>0.389824</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">23</th>
<td>882.791809</td>
<td>845.683289</td>
<td>1476.399170</td>
<td>982.723877</td>
<td>plain text</td>
<td>0.378071</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">24</th>
<td>3001.068604</td>
<td>1266.987061</td>
<td>3527.293213</td>
<td>1354.325928</td>
<td>plain text</td>
<td>0.370774</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">25</th>
<td>3006.092529</td>
<td>1268.646606</td>
<td>3583.754639</td>
<td>2200.445557</td>
<td>plain text</td>
<td>0.360401</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">26</th>
<td>1535.614624</td>
<td>1842.507202</td>
<td>2077.353516</td>
<td>1984.601807</td>
<td>title</td>
<td>0.337300</td>
<td>True</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">27</th>
<td>880.934509</td>
<td>1258.313110</td>
<td>1462.825928</td>
<td>1400.205078</td>
<td>plain text</td>
<td>0.305315</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">28</th>
<td>881.682800</td>
<td>1118.672363</td>
<td>1455.794189</td>
<td>1258.220947</td>
<td>plain text</td>
<td>0.294823</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">29</th>
<td>882.505371</td>
<td>982.659119</td>
<td>1479.449707</td>
<td>1116.903931</td>
<td>plain text</td>
<td>0.263816</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">30</th>
<td>1534.299072</td>
<td>1620.801636</td>
<td>2126.622803</td>
<td>1667.255005</td>
<td>plain text</td>
<td>0.257625</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">31</th>
<td>1533.716064</td>
<td>1338.074707</td>
<td>2135.751709</td>
<td>1658.443481</td>
<td>plain text</td>
<td>0.245955</td>
<td>False</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">32</th>
<td>1533.999634</td>
<td>2035.315918</td>
<td>2170.545654</td>
<td>2285.304443</td>
<td>plain text</td>
<td>0.232413</td>
<td>False</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">33</th>
<td>1537.556274</td>
<td>1929.555420</td>
<td>1743.389038</td>
<td>1981.646973</td>
<td>plain text</td>
<td>0.227065</td>
<td>False</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>In both cases, we can see that the title detection is not optimal. In the case of the block-based detection it will be difficult to separate “Soupe à l’ail bonne femme Knoblauchsuppe nach”.</p>
<p>For DocLayout-YOLO, there are too many titles. Ingredients were detected as title as they are on top of a column and in bold.</p>
</section>
</section>
<section id="title-detection" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="title-detection"><span class="header-section-number">3</span> Title detection</h2>
<section id="title-detection-using-ocr" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="title-detection-using-ocr"><span class="header-section-number">3.1</span> Title detection using OCR</h3>
<p>Let’s try to improve the title detection. We start with the OCR blocks.</p>
<div id="9e9b80683b054ec2" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:38.449566Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:38.443865Z&quot;}}" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">df_block[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="10">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">font_size</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">1</th>
<td>64</td>
<td>24.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>Die Butter zerlassen , das Weißbrot von beiden...</td>
<td>31.902913</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td>Soupe à l'ail bonne femme Knoblauchsuppe nach ...</td>
<td>52.375000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">16</th>
<td>2 Stangen Porree ( Lauch ) 250 g enthäutete To...</td>
<td>32.761905</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">19</th>
<td>Salz Pfeffer</td>
<td>26.500000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">21</th>
<td>einige runde , ausgestochene Toast- brotscheiben</td>
<td>34.000000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">24</th>
<td>Speiseöl Parmesankäse</td>
<td>29.500000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">27</th>
<td>Den Porree putzen , waschen , in Ringe schneid...</td>
<td>35.600000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">29</th>
<td>zerdrücken .</td>
<td>25.500000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">34</th>
<td>Das Öl erhitzen , das Gemüse mit den Knoblauch...</td>
<td>33.516854</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">36</th>
<td>Gigot de chevreuil</td>
<td>62.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">38</th>
<td>Rehblatt</td>
<td>37.000000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">41</th>
<td>800 g Rehblatt ( Schulter ) Salz , Pfeffer 50 ...</td>
<td>34.187500</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">43</th>
<td>2 Schalotten</td>
<td>26.500000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">49</th>
<td>2 zerdrückte Wacholderbeeren 2 zerdrückte Knob...</td>
<td>32.347826</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">51</th>
<td>2 Teel . Weizenmehl 125 ml ( 1 ) Schlagsahne</td>
<td>33.600000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">56</th>
<td>Das Rehblatt unter fließendem kal- tem Wasser ...</td>
<td>33.964072</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">58</th>
<td>Croûtes aux champignons Champignons in Pasteten</td>
<td>45.666667</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">60</th>
<td>500 g Champignons 50 g Butter</td>
<td>33.500000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">62</th>
<td>Salz Pfeffer</td>
<td>25.500000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">69</th>
<td>Cayennepfeffer 125 ml ( 1 ) Wasser 2 gestriche...</td>
<td>32.321429</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">73</th>
<td>Die Champignons putzen , waschen , vierteln . ...</td>
<td>32.377193</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">75</th>
<td>55</td>
<td>-1.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">77</th>
<td>65</td>
<td>26.000000</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>Titles are in index 10, 36, and 58. For index 10 and 58, the title is together with the subtitles. Both have a bigger average line height (fontsize) than the rest. Almost by factor 1.5. With this in mind we create our title detector. Just to be sure we limit the amount of words, too.</p>
<p>Luckily we extracted this information earlier in our dataframe.</p>
<div id="4e2ccf57416c1577" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:38.824099Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:38.820351Z&quot;}}" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> detect_titles(df, font_factor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>, max_words<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>):</span>
<span id="cb11-2">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"word_count"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].copy()</span>
<span id="cb11-3"></span>
<span id="cb11-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(df) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:</span>
<span id="cb11-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df</span>
<span id="cb11-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># compute mean font size ignoring NaNs</span></span>
<span id="cb11-7">    mean_font_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>].mean()</span>
<span id="cb11-8"></span>
<span id="cb11-9">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb11-10">            (df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> font_factor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> mean_font_size) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span></span>
<span id="cb11-11">            (df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"word_count"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> max_words) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span></span>
<span id="cb11-12">             (df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb11-13">    )</span>
<span id="cb11-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df[df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>]]</span></code></pre></div></div>
</div>
<div id="1968057f07a4eb12" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:39.200353Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:39.193399Z&quot;}}" data-execution_count="12">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1">df_titles_blocks <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_titles(df_block)</span>
<span id="cb12-2">df_titles_blocks[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="12">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">is_title</th>
<th data-quarto-table-cell-role="th">font_size</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td>Soupe à l'ail bonne femme Knoblauchsuppe nach ...</td>
<td>True</td>
<td>52.375000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">36</th>
<td>Gigot de chevreuil</td>
<td>True</td>
<td>62.000000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">58</th>
<td>Croûtes aux champignons Champignons in Pasteten</td>
<td>True</td>
<td>45.666667</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<div id="cd4392da77882a68" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:39.714303Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:39.706089Z&quot;}}" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1">df_titles_para <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_titles(df_para)</span>
<span id="cb13-2">df_titles_para[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="13">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">is_title</th>
<th data-quarto-table-cell-role="th">font_size</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">8</th>
<td>Soupe à l'ail bonne femme</td>
<td>True</td>
<td>56.600000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">9</th>
<td>Knoblauchsuppe nach Hausfrauenart</td>
<td>True</td>
<td>45.333333</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">35</th>
<td>Gigot de chevreuil</td>
<td>True</td>
<td>62.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">57</th>
<td>Croûtes aux champignons Champignons in Pasteten</td>
<td>True</td>
<td>45.666667</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>In the case of blocks, the subtitle is detected with the title in a block. And in the case of the paragraphs, it has an almost equal font size. For the third title, separation is not possible on paragraph level.</p>
<p>Now it would be great to include this information back into the dataframe.</p>
<div id="bc2f6ba21b829d43" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:39.784515Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:39.781919Z&quot;}}" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> add_titles_to_df(original, titles):</span>
<span id="cb14-2">    original[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb14-3">    original.loc[titles.index, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> titles[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>]</span></code></pre></div></div>
</div>
<div id="4474b5bd51801b54" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:39.962474Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:39.955421Z&quot;}}" data-execution_count="15">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1">add_titles_to_df(df_block, df_titles_blocks)</span>
<span id="cb15-2">df_block[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="15">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">is_title</th>
<th data-quarto-table-cell-role="th">font_size</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">1</th>
<td>64</td>
<td>False</td>
<td>24.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>Die Butter zerlassen , das Weißbrot von beiden...</td>
<td>False</td>
<td>31.902913</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td>Soupe à l'ail bonne femme Knoblauchsuppe nach ...</td>
<td>True</td>
<td>52.375000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">16</th>
<td>2 Stangen Porree ( Lauch ) 250 g enthäutete To...</td>
<td>False</td>
<td>32.761905</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">19</th>
<td>Salz Pfeffer</td>
<td>False</td>
<td>26.500000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">21</th>
<td>einige runde , ausgestochene Toast- brotscheiben</td>
<td>False</td>
<td>34.000000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">24</th>
<td>Speiseöl Parmesankäse</td>
<td>False</td>
<td>29.500000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">27</th>
<td>Den Porree putzen , waschen , in Ringe schneid...</td>
<td>False</td>
<td>35.600000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">29</th>
<td>zerdrücken .</td>
<td>False</td>
<td>25.500000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">34</th>
<td>Das Öl erhitzen , das Gemüse mit den Knoblauch...</td>
<td>False</td>
<td>33.516854</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">36</th>
<td>Gigot de chevreuil</td>
<td>True</td>
<td>62.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">38</th>
<td>Rehblatt</td>
<td>False</td>
<td>37.000000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">41</th>
<td>800 g Rehblatt ( Schulter ) Salz , Pfeffer 50 ...</td>
<td>False</td>
<td>34.187500</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">43</th>
<td>2 Schalotten</td>
<td>False</td>
<td>26.500000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">49</th>
<td>2 zerdrückte Wacholderbeeren 2 zerdrückte Knob...</td>
<td>False</td>
<td>32.347826</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">51</th>
<td>2 Teel . Weizenmehl 125 ml ( 1 ) Schlagsahne</td>
<td>False</td>
<td>33.600000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">56</th>
<td>Das Rehblatt unter fließendem kal- tem Wasser ...</td>
<td>False</td>
<td>33.964072</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">58</th>
<td>Croûtes aux champignons Champignons in Pasteten</td>
<td>True</td>
<td>45.666667</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">60</th>
<td>500 g Champignons 50 g Butter</td>
<td>False</td>
<td>33.500000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">62</th>
<td>Salz Pfeffer</td>
<td>False</td>
<td>25.500000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">69</th>
<td>Cayennepfeffer 125 ml ( 1 ) Wasser 2 gestriche...</td>
<td>False</td>
<td>32.321429</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">73</th>
<td>Die Champignons putzen , waschen , vierteln . ...</td>
<td>False</td>
<td>32.377193</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">75</th>
<td>55</td>
<td>False</td>
<td>-1.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">77</th>
<td>65</td>
<td>False</td>
<td>26.000000</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>Let’s do the same for the paragraphs.</p>
<div id="9ffa1986a5345b7f" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:40.093023Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:40.089874Z&quot;}}" data-execution_count="16">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1">add_titles_to_df(df_para, df_titles_para)</span></code></pre></div></div>
</div>
</section>
<section id="title-detection-using-doclayout-yolo-and-ocr" class="level3" data-number="3.2">
<h3 data-number="3.2" class="anchored" data-anchor-id="title-detection-using-doclayout-yolo-and-ocr"><span class="header-section-number">3.2</span> Title detection using DocLayout-YOLO and OCR</h3>
<p>Luckily, the layout detector already flags which blocks are title. The issue: there is no text in any of those blocks. Most of the blocks span multiple lines, which means our font-size approach does not work. We do not know how many lines or words exist.</p>
<p>This is where DocLayout-YOLO falls short. We could run every single block through OCR. On a local OCR program that could be as effective as full page detection, maybe even better. But since we rely on Google OCR, that approach would lead to very high cost, as billing is per request.</p>
<p>Instead, we align the two boxes and copy every OCR word which falls in a Doclayout boxes to the related dataframe row.</p>
<div id="e74b2b04dc3f57cc" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:40.295343Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:40.291555Z&quot;}}" data-execution_count="17">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1">df_titles_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_yolo[df_yolo[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>]].copy()</span>
<span id="cb17-2">df_titles_yolo[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span>
<span id="cb17-3">df_titles_yolo[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"average_word_height_sum"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb17-4">df_titles_yolo[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"word_count"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span></code></pre></div></div>
</div>
<div id="b71eec136915cd50" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:40.504814Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:40.340237Z&quot;}}" data-execution_count="18">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> block <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> page:</span>
<span id="cb18-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> para_idx, para <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(block.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"paragraphs"</span>, [])):</span>
<span id="cb18-3"></span>
<span id="cb18-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> word_idx, word <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(para.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"words"</span>, [])):</span>
<span id="cb18-5">            symbols <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [s[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> word.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"symbols"</span>, [])]</span>
<span id="cb18-6">            word_text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>.join(symbols)</span>
<span id="cb18-7">            word_verts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> word[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"boundingBox"</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vertices"</span>]</span>
<span id="cb18-8">            wx1, wy1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> word_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), word_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb18-9">            wx2, wy2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> word_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), word_verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb18-10">            wcx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (wx1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> wx2) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb18-11">            wcy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (wy1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> wy2) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb18-12">            word_height <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(wy2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> wy1)</span>
<span id="cb18-13"></span>
<span id="cb18-14">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># assign to title box if inside</span></span>
<span id="cb18-15">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> idx, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df_titles_yolo.iterrows():</span>
<span id="cb18-16">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> wcx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>]) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> wcy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>]):</span>
<span id="cb18-17">                    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># append word text</span></span>
<span id="cb18-18">                    df_titles_yolo.at[idx, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" "</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> word_text</span>
<span id="cb18-19">                    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># accumulate height + count</span></span>
<span id="cb18-20">                    df_titles_yolo.at[idx, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"average_word_height_sum"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> word_height</span>
<span id="cb18-21">                    df_titles_yolo.at[idx, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"word_count"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb18-22">                    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># can only be in one title</span></span>
<span id="cb18-23">                    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span></code></pre></div></div>
</div>
<div id="d89e3ee5e60d0591" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:40.521118Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:40.515404Z&quot;}}" data-execution_count="19">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1">df_titles_yolo[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_titles_yolo.average_word_height_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> df_titles_yolo.word_count</span>
<span id="cb19-2">df_titles_yolo[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="19">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">is_title</th>
<th data-quarto-table-cell-role="th">font_size</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>Soupe à l'ail bonne femme</td>
<td>True</td>
<td>56.600000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>Croûtes aux champignons</td>
<td>True</td>
<td>47.333333</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">18</th>
<td>Speiseöl Parmesankäse</td>
<td>True</td>
<td>29.500000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">19</th>
<td></td>
<td>True</td>
<td>NaN</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">20</th>
<td>Gigot de chevreuil</td>
<td>True</td>
<td>62.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">26</th>
<td>Rehblatt</td>
<td>True</td>
<td>37.000000</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>As indicated earlier, we have different kind of false positives. Only the “Rehblatt” is similar to the previous case, of subtitles in the paragraph based detection. Luckily for us, this time font size should work well.</p>
<div id="d02cf8e28c6d146" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:40.648399Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:40.641222Z&quot;}}" data-execution_count="20">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1">df_titles_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_titles(df_titles_yolo, font_factor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb20-2">df_titles_yolo[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="20">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">is_title</th>
<th data-quarto-table-cell-role="th">font_size</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>Soupe à l'ail bonne femme</td>
<td>True</td>
<td>56.600000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>Croûtes aux champignons</td>
<td>True</td>
<td>47.333333</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">20</th>
<td>Gigot de chevreuil</td>
<td>True</td>
<td>62.000000</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>As expected it worked even without a safety factor. We wrap this in a function.</p>
<div id="e6041440f2219a3c" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:41.029343Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:41.024530Z&quot;}}" data-execution_count="21">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> add_text_and_font_size_to_layout_df(df, ocr_page):</span>
<span id="cb21-2">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span>
<span id="cb21-3">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"average_word_height_sum"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb21-4">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"word_count"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb21-5">    unassigned_words <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb21-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> block <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> ocr_page:</span>
<span id="cb21-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> para_idx, para <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(block.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"paragraphs"</span>, [])):</span>
<span id="cb21-8"></span>
<span id="cb21-9">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> word_idx, word <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(para.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"words"</span>, [])):</span>
<span id="cb21-10">                symbols <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [s[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> word.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"symbols"</span>, [])]</span>
<span id="cb21-11">                word_text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>.join(symbols)</span>
<span id="cb21-12">                verts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> word[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"boundingBox"</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vertices"</span>]</span>
<span id="cb21-13">                wx1, wy1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb21-14">                wx2, wy2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), verts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb21-15">                wcx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (wx1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> wx2) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb21-16">                wcy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (wy1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> wy2) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb21-17">                word_height <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(wy2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> wy1)</span>
<span id="cb21-18"></span>
<span id="cb21-19">                assigned <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb21-20">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> idx, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df.iterrows():</span>
<span id="cb21-21">                    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> wcx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>]) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> wcy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>]):</span>
<span id="cb21-22">                        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># append word text</span></span>
<span id="cb21-23">                        df.at[idx, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" "</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> word_text</span>
<span id="cb21-24">                        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># accumulate height + count</span></span>
<span id="cb21-25">                        df.at[idx, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"average_word_height_sum"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> word_height</span>
<span id="cb21-26">                        df.at[idx, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"word_count"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb21-27">                        assigned <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb21-28">                        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb21-29"></span>
<span id="cb21-30">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> assigned:</span>
<span id="cb21-31">                    unassigned_words.append({</span>
<span id="cb21-32">                        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>: word_text,</span>
<span id="cb21-33">                        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>: wcx,</span>
<span id="cb21-34">                        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>: wcy,</span>
<span id="cb21-35">                        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"height"</span>: word_height</span>
<span id="cb21-36">                    })</span>
<span id="cb21-37">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(unassigned_words) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb21-38">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unassigned words:"</span>)</span>
<span id="cb21-39">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.average_word_height_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> df.word_count</span>
<span id="cb21-40">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df</span></code></pre></div></div>
</div>
<p>Note, I included a small debug hint, which should trigger if there are any unassigned words.</p>
<p>Next, it would be great to include this information back into the dataframe.</p>
<p>The complete code for DocLayout-YOLO.</p>
<div id="1649b27802044865" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:41.536586Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:41.104614Z&quot;}}" data-execution_count="22">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1">df_yolo_font_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> add_text_and_font_size_to_layout_df(df_yolo.copy(), page)</span>
<span id="cb22-2">df_titles_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_titles(df_yolo_font_size[df_yolo_font_size.is_title], font_factor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb22-3">add_titles_to_df(df_yolo_font_size, df_titles_yolo)</span>
<span id="cb22-4">df_yolo_font_size[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"font_size"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>unassigned words:</code></pre>
</div>
<div class="cell-output cell-output-display" data-execution_count="22">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">is_title</th>
<th data-quarto-table-cell-role="th">font_size</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>Soupe à l'ail bonne femme</td>
<td>True</td>
<td>56.600000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>Knoblauchsuppe nach Hausfrauenart</td>
<td>False</td>
<td>45.333333</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>65</td>
<td>False</td>
<td>26.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>Croûtes aux champignons</td>
<td>True</td>
<td>47.333333</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">4</th>
<td>64</td>
<td>False</td>
<td>24.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">5</th>
<td>2 Stangen Porree ( Lauch ) 250 g enthäutete T...</td>
<td>False</td>
<td>32.586207</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">6</th>
<td>Den Porree putzen , waschen , in Ringe schnei...</td>
<td>False</td>
<td>33.900826</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>Champignons in Pasteten</td>
<td>False</td>
<td>44.000000</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">8</th>
<td>Die Butter zerlassen , das Weißbrot von beide...</td>
<td>False</td>
<td>31.902913</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">9</th>
<td>500 g Champignons g Butter Salz Pfeffer Cayen...</td>
<td>False</td>
<td>32.142857</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">11</th>
<td>zerdrückte Wacholderbeeren zerdrückte Knoblau...</td>
<td>False</td>
<td>32.419355</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">12</th>
<td>Sahne und Petersilie unterrühren . Die Champi...</td>
<td>False</td>
<td>32.016667</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">13</th>
<td>Das Rehblatt unter fließendem kal- tem Wasser...</td>
<td>False</td>
<td>35.842105</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">14</th>
<td>Den Speck in Streifen schneiden . Die Butter ...</td>
<td>False</td>
<td>34.090909</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">15</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">16</th>
<td>Fleisch von den Knochen Das gare lösen , in P...</td>
<td>False</td>
<td>30.380952</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">17</th>
<td>Schalotten abziehen , vierteln , mit den Wach...</td>
<td>False</td>
<td>32.963636</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">18</th>
<td>Speiseöl Parmesankäse</td>
<td>False</td>
<td>29.500000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">19</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">20</th>
<td>Gigot de chevreuil</td>
<td>True</td>
<td>62.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">21</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">22</th>
<td>Den Bratensatz mit etwas Wasser los- kochen u...</td>
<td>False</td>
<td>35.877551</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">23</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">24</th>
<td>Die Champignons putzen , waschen , vierteln .</td>
<td>False</td>
<td>31.250000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">25</th>
<td>Die Butter zerlassen , die Champi- gnons dari...</td>
<td>False</td>
<td>33.043478</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">26</th>
<td>Rehblatt</td>
<td>False</td>
<td>37.000000</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">27</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">28</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">29</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">30</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">31</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">32</th>
<td>800 g Rehblatt ( Schulter ) Salz , Pfeffer 50...</td>
<td>False</td>
<td>33.333333</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">33</th>
<td></td>
<td>False</td>
<td>NaN</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
</section>
</section>
<section id="recipe-detection-using-only-ocr" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="recipe-detection-using-only-ocr"><span class="header-section-number">4</span> Recipe detection using only OCR</h2>
<p>Now with the titles cleaned, we know the number of titles. Next step is the distribution of the rows of each dataframe to the recipes.</p>
<p>An important domain knowledge, or prior knowledge, is that almost all recipe formats are organized in columns. Titles are usually placed somewhere in these columns, and a title marks the beginning of a recipe.</p>
<p>The main drawback: any other layout format cannot be processed.</p>
<p>We will do this approach in two steps:</p>
<ol type="1">
<li>Split the text into columns based on the row’s bounding box</li>
<li>Split columns into recipes based on title position.</li>
</ol>
<section id="working-on-ocr-block-level" class="level3" data-number="4.1">
<h3 data-number="4.1" class="anchored" data-anchor-id="working-on-ocr-block-level"><span class="header-section-number">4.1</span> Working on OCR Block level</h3>
<p>This was actually the hardest part. For the sake of brevity I only provide the final result and not the full way.</p>
<section id="column-detection" class="level4" data-number="4.1.1">
<h4 data-number="4.1.1" class="anchored" data-anchor-id="column-detection"><span class="header-section-number">4.1.1</span> Column detection</h4>
<p>The OCR pipeline has already discovered fragments of text that belong together, and organized them into paragraphs and blocks.</p>
<p>Our algorithm works with two approaches.</p>
<ol type="1">
<li>We assume there are no more than five columns, and they are evenly distributed. When column size is unequal, that is usually the case if ingredients are in a column.</li>
</ol>
<p>We search for the best fit. Fit is defined by a score, which is the absolute distance of left beginning of the box and column centers.</p>
<ol start="2" type="1">
<li>We try to establish the number of columns with a normalized, area-weighted histogram. A valid column is defined by having 50% of the text amount of the maximum column. That of course assumes equal length of recipes. Because this assumption is shaky, the first approach is preferred.</li>
</ol>
<div id="12b8bad7a2fdea06" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:41.645357Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:41.616201Z&quot;}}" data-execution_count="23">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> detect_columns(df, max_cols<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, error_threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>):</span>
<span id="cb24-2">    page_width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>()</span>
<span id="cb24-3">    best_n, best_score, best_assignments <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inf"</span>), <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb24-4"></span>
<span id="cb24-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n_cols <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, max_cols <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb24-6">        col_width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> page_width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_cols</span>
<span id="cb24-7">        col_centers <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [(i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> col_width <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n_cols)]</span>
<span id="cb24-8"></span>
<span id="cb24-9">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Assign each block to nearest center</span></span>
<span id="cb24-10">        assignments <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb24-11">        errors <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb24-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>]:</span>
<span id="cb24-13">            dists <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> c) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> c <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> col_centers]</span>
<span id="cb24-14">            col_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(np.argmin(dists))</span>
<span id="cb24-15">            assignments.append(col_idx)</span>
<span id="cb24-16">            errors.append(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(dists))</span>
<span id="cb24-17"></span>
<span id="cb24-18">        score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.mean(errors)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># lower = better alignment</span></span>
<span id="cb24-19">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> best_score:</span>
<span id="cb24-20">            best_score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score</span>
<span id="cb24-21">            best_n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> n_cols</span>
<span id="cb24-22">            best_assignments <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> assignments</span>
<span id="cb24-23"></span>
<span id="cb24-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> best_score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> error_threshold:</span>
<span id="cb24-25">        df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> best_assignments</span>
<span id="cb24-26"></span>
<span id="cb24-27">        col_boxes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb24-28">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> col_id, group <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df.groupby(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>):</span>
<span id="cb24-29">            col_boxes.append({</span>
<span id="cb24-30">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>: col_id,</span>
<span id="cb24-31">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_x1"</span>: group[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(),</span>
<span id="cb24-32">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_y1"</span>: group[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(),</span>
<span id="cb24-33">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_x2"</span>: group[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(),</span>
<span id="cb24-34">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_y2"</span>: group[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>()</span>
<span id="cb24-35">            })</span>
<span id="cb24-36"></span>
<span id="cb24-37">        col_boxes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame(col_boxes).sort_values(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_x1"</span>).reset_index(drop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb24-38">        col_boxes[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(col_boxes))</span>
<span id="cb24-39">        df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>({old: new <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> new, old <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(col_boxes[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>])})</span>
<span id="cb24-40">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> col_boxes, df</span>
<span id="cb24-41">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb24-42">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Fallback to histogram based method</span></span>
<span id="cb24-43">        df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"area"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>])</span>
<span id="cb24-44">        hist, bin_edges <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.histogram(</span>
<span id="cb24-45">            df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>],</span>
<span id="cb24-46">            bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb24-47">            weights<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"area"</span>]</span>
<span id="cb24-48">        )</span>
<span id="cb24-49">        hist_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> hist <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(hist)</span>
<span id="cb24-50">        valid_bins <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.where(hist_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb24-51">        bin_centers <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (bin_edges[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> bin_edges[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb24-52">        col_centers <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> bin_centers[valid_bins]</span>
<span id="cb24-53"></span>
<span id="cb24-54">        df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">apply</span>(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> x: np.argmin(np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(col_centers <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> x)))</span>
<span id="cb24-55"></span>
<span id="cb24-56">        col_boxes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb24-57">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> col_id, group <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df.groupby(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>):</span>
<span id="cb24-58">            col_boxes.append({</span>
<span id="cb24-59">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>: col_id,</span>
<span id="cb24-60">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_x1"</span>: group[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(),</span>
<span id="cb24-61">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_y1"</span>: group[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(),</span>
<span id="cb24-62">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_x2"</span>: group[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(),</span>
<span id="cb24-63">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_y2"</span>: group[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>()</span>
<span id="cb24-64">            })</span>
<span id="cb24-65"></span>
<span id="cb24-66">        col_boxes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame(col_boxes).sort_values(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_x1"</span>).reset_index(drop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb24-67">        col_boxes[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(col_boxes))</span>
<span id="cb24-68">        df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>({old: new <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> new, old <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(col_boxes[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>])})</span>
<span id="cb24-69"></span>
<span id="cb24-70">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> col_boxes, df</span></code></pre></div></div>
</div>
<div id="d215f2717bee7ecc" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:41.811338Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:41.801390Z&quot;}}" data-execution_count="24">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1">cols, df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_columns(df_block.copy())</span>
<span id="cb25-2">cols</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="24">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">col_id</th>
<th data-quarto-table-cell-role="th">col_x1</th>
<th data-quarto-table-cell-role="th">col_y1</th>
<th data-quarto-table-cell-role="th">col_x2</th>
<th data-quarto-table-cell-role="th">col_y2</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>0</td>
<td>853</td>
<td>484</td>
<td>1510</td>
<td>2355</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>1</td>
<td>1526</td>
<td>467</td>
<td>2138</td>
<td>2271</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>2</td>
<td>2306</td>
<td>474</td>
<td>2993</td>
<td>2249</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>3</td>
<td>2973</td>
<td>455</td>
<td>3608</td>
<td>2274</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<div id="6203ac2f2fb4bdcb" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:41.933085Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:41.927250Z&quot;}}" data-execution_count="25">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1">df[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="25">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">col_id</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">1</th>
<td>64</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>Die Butter zerlassen , das Weißbrot von beiden...</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td>Soupe à l'ail bonne femme Knoblauchsuppe nach ...</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">16</th>
<td>2 Stangen Porree ( Lauch ) 250 g enthäutete To...</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">19</th>
<td>Salz Pfeffer</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">21</th>
<td>einige runde , ausgestochene Toast- brotscheiben</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">24</th>
<td>Speiseöl Parmesankäse</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">27</th>
<td>Den Porree putzen , waschen , in Ringe schneid...</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">29</th>
<td>zerdrücken .</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">34</th>
<td>Das Öl erhitzen , das Gemüse mit den Knoblauch...</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">36</th>
<td>Gigot de chevreuil</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">38</th>
<td>Rehblatt</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">41</th>
<td>800 g Rehblatt ( Schulter ) Salz , Pfeffer 50 ...</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">43</th>
<td>2 Schalotten</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">49</th>
<td>2 zerdrückte Wacholderbeeren 2 zerdrückte Knob...</td>
<td>2</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">51</th>
<td>2 Teel . Weizenmehl 125 ml ( 1 ) Schlagsahne</td>
<td>2</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">56</th>
<td>Das Rehblatt unter fließendem kal- tem Wasser ...</td>
<td>2</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">58</th>
<td>Croûtes aux champignons Champignons in Pasteten</td>
<td>3</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">60</th>
<td>500 g Champignons 50 g Butter</td>
<td>3</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">62</th>
<td>Salz Pfeffer</td>
<td>3</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">69</th>
<td>Cayennepfeffer 125 ml ( 1 ) Wasser 2 gestriche...</td>
<td>3</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">73</th>
<td>Die Champignons putzen , waschen , vierteln . ...</td>
<td>3</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">75</th>
<td>55</td>
<td>3</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">77</th>
<td>65</td>
<td>3</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>The number of columns is correct.</p>
</section>
<section id="recipe-detection" class="level4" data-number="4.1.2">
<h4 data-number="4.1.2" class="anchored" data-anchor-id="recipe-detection"><span class="header-section-number">4.1.2</span> Recipe detection</h4>
<p>We now proceed by grouping the blocks into recipes. This function is the work of many failed iterations.</p>
<p>Since we have established columns, we treat all text as if it were in one big column. Whenever a title appears, we start a new recipe.</p>
<p>I solved the subtitle issue by checking that the gap to the previous title is similar to the title font size. If so, it is a subtitle, not a new recipe.</p>
<div id="b62c38b4e9cbfd34" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:42.242827Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:42.238576Z&quot;}}" data-execution_count="26">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> group_recipes(df, subtitle_factor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>):</span>
<span id="cb27-2">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.copy()</span>
<span id="cb27-3">    recipe_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb27-4">    all_recipes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb27-5">    recipe_map <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb27-6"></span>
<span id="cb27-7">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Sort by column, then y</span></span>
<span id="cb27-8">    cols <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sorted</span>(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>].unique())</span>
<span id="cb27-9">    last_recipe_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb27-10">    current_recipe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blocks"</span>: []}</span>
<span id="cb27-11"></span>
<span id="cb27-12">    last_title_font <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb27-13"></span>
<span id="cb27-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> col <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cols:</span>
<span id="cb27-15">        col_blocks <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> col].sort_values(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>)</span>
<span id="cb27-16">        last_title_bottom <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb27-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> idx, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> col_blocks.iterrows():</span>
<span id="cb27-18"></span>
<span id="cb27-19">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> row.is_title:</span>
<span id="cb27-20">                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># check if this title is actually a subtitle</span></span>
<span id="cb27-21">                subtitle_gap <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (last_title_font <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> row.font_size) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> subtitle_factor</span>
<span id="cb27-22"></span>
<span id="cb27-23">                is_subtitle <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb27-24">                        current_recipe[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>] <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb27-25">                        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> last_title_bottom) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> subtitle_gap</span>
<span id="cb27-26">                )</span>
<span id="cb27-27"></span>
<span id="cb27-28">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> is_subtitle:</span>
<span id="cb27-29">                    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># merge into current recipe title</span></span>
<span id="cb27-30">                    current_recipe[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" "</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> row.text</span>
<span id="cb27-31">                    current_recipe[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blocks"</span>].append(row.text)</span>
<span id="cb27-32">                    recipe_map[idx] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> last_recipe_id</span>
<span id="cb27-33">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb27-34"></span>
<span id="cb27-35">                    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> current_recipe[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>] <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb27-36">                        all_recipes.append(current_recipe)</span>
<span id="cb27-37"></span>
<span id="cb27-38">                    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># start new recipe</span></span>
<span id="cb27-39">                    recipe_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb27-40">                    current_recipe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>: row.text, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blocks"</span>: [row.text]}</span>
<span id="cb27-41">                    recipe_map[idx] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> recipe_id</span>
<span id="cb27-42">                    last_recipe_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> recipe_id</span>
<span id="cb27-43"></span>
<span id="cb27-44">                last_title_bottom <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>]</span>
<span id="cb27-45">                last_title_font <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> row.font_size</span>
<span id="cb27-46"></span>
<span id="cb27-47">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb27-48"></span>
<span id="cb27-49">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> last_recipe_id <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb27-50">                    recipe_map[idx] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># orphan</span></span>
<span id="cb27-51">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb27-52">                    recipe_map[idx] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> last_recipe_id</span>
<span id="cb27-53">                    current_recipe[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blocks"</span>].append(row.text)</span>
<span id="cb27-54"></span>
<span id="cb27-55">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> current_recipe[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>] <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb27-56">        all_recipes.append(current_recipe)</span>
<span id="cb27-57"></span>
<span id="cb27-58">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.index.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>(recipe_map).fillna(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>).astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>)</span>
<span id="cb27-59">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df, all_recipes</span></code></pre></div></div>
</div>
<div id="d992487dc9c3c8b2" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:42.315299Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:42.308988Z&quot;}}" data-execution_count="27">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1">df, recipes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> group_recipes(df)</span></code></pre></div></div>
</div>
<div id="b964c3ba9e4c1be" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:42.370225Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:42.364582Z&quot;}}" data-execution_count="28">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb29-1">df[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="28">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">recipe_id</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">1</th>
<td>64</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>Die Butter zerlassen , das Weißbrot von beiden...</td>
<td>-1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td>Soupe à l'ail bonne femme Knoblauchsuppe nach ...</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">16</th>
<td>2 Stangen Porree ( Lauch ) 250 g enthäutete To...</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">19</th>
<td>Salz Pfeffer</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">21</th>
<td>einige runde , ausgestochene Toast- brotscheiben</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">24</th>
<td>Speiseöl Parmesankäse</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">27</th>
<td>Den Porree putzen , waschen , in Ringe schneid...</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">29</th>
<td>zerdrücken .</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">34</th>
<td>Das Öl erhitzen , das Gemüse mit den Knoblauch...</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">36</th>
<td>Gigot de chevreuil</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">38</th>
<td>Rehblatt</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">41</th>
<td>800 g Rehblatt ( Schulter ) Salz , Pfeffer 50 ...</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">43</th>
<td>2 Schalotten</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">49</th>
<td>2 zerdrückte Wacholderbeeren 2 zerdrückte Knob...</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">51</th>
<td>2 Teel . Weizenmehl 125 ml ( 1 ) Schlagsahne</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">56</th>
<td>Das Rehblatt unter fließendem kal- tem Wasser ...</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">58</th>
<td>Croûtes aux champignons Champignons in Pasteten</td>
<td>2</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">60</th>
<td>500 g Champignons 50 g Butter</td>
<td>2</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">62</th>
<td>Salz Pfeffer</td>
<td>2</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">69</th>
<td>Cayennepfeffer 125 ml ( 1 ) Wasser 2 gestriche...</td>
<td>2</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">73</th>
<td>Die Champignons putzen , waschen , vierteln . ...</td>
<td>2</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">75</th>
<td>55</td>
<td>2</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">77</th>
<td>65</td>
<td>2</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>Nice, even the fragment of the previous recipe in the first column was treated correctly. Only the page number was wrongly attributed to the first recipe.</p>
<p>A picture says more than a thousand words.</p>
<div id="f846903460fdaf63" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:42.471011Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:42.466856Z&quot;}}" data-execution_count="29">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_recipes(df, image, save<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>):</span>
<span id="cb30-2">    colors <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb30-3">    fig <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>))</span>
<span id="cb30-4">    plt.imshow(image)</span>
<span id="cb30-5"></span>
<span id="cb30-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df.iterrows():</span>
<span id="cb30-7">        rid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>]</span>
<span id="cb30-8">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> rid <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> colors:</span>
<span id="cb30-9">            colors[rid] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [random.random(), random.random(), random.random()]</span>
<span id="cb30-10">        color <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> colors[rid]</span>
<span id="cb30-11"></span>
<span id="cb30-12">        rect <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> patches.Rectangle(</span>
<span id="cb30-13">            (row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>], row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>]),</span>
<span id="cb30-14">            row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>],</span>
<span id="cb30-15">            row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>],</span>
<span id="cb30-16">            linewidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb30-17">            edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>color,</span>
<span id="cb30-18">            facecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span></span>
<span id="cb30-19">        )</span>
<span id="cb30-20">        plt.gca().add_patch(rect)</span>
<span id="cb30-21"></span>
<span id="cb30-22">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>]:</span>
<span id="cb30-23">            plt.text(row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>], row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>][:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>],</span>
<span id="cb30-24">                     color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>color, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, weight<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>)</span>
<span id="cb30-25"></span>
<span id="cb30-26">    plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb30-27">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> save:</span>
<span id="cb30-28">        fig.savefig(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"result.jpg"</span>)</span>
<span id="cb30-29">    plt.show()</span>
<span id="cb30-30"></span></code></pre></div></div>
</div>
<div id="1e71e83f5292750a" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:44.043593Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:42.638144Z&quot;}}" data-execution_count="30">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb31-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> read_image(image_id,):</span>
<span id="cb31-2">    image_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Path(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw"</span>)</span>
<span id="cb31-3">    filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> image_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>image_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">.jpg"</span></span>
<span id="cb31-4">    image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Image.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(filename)</span>
<span id="cb31-5"></span>
<span id="cb31-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> image</span>
<span id="cb31-7">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_image(filename)</span>
<span id="cb31-8">plot_recipes(df, image, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/page_segmentation_files/figure-html/cell-31-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>As we can see this approach also works quite well.</p>
</section>
</section>
<section id="working-on-ocr-paragraph-level" class="level3" data-number="4.2">
<h3 data-number="4.2" class="anchored" data-anchor-id="working-on-ocr-paragraph-level"><span class="header-section-number">4.2</span> Working on OCR paragraph level</h3>
<p>We will try OCR Paragraphs. Thanks to the subtitle workaround it also works for this recipe. However, doing so introduce another variable in the whole process and making it more brittle.</p>
<p>We can see that the first sub-title is printed in fat as the table still thinks it is a title.</p>
<div id="ba44b9a14b4364d1" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:44.898508Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:44.127150Z&quot;}}" data-execution_count="31">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1">cols, df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_columns(df_para.copy())</span>
<span id="cb32-2">df, recipes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> group_recipes(df)</span>
<span id="cb32-3">plot_recipes(df, image)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/page_segmentation_files/figure-html/cell-32-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="generalization-of-ocr-based-splitting" class="level3" data-number="4.3">
<h3 data-number="4.3" class="anchored" data-anchor-id="generalization-of-ocr-based-splitting"><span class="header-section-number">4.3</span> Generalization of OCR based splitting</h3>
<p>Let’s extend the algorithm to two other formats and see if it succeeds</p>
<div id="876d87d6f6bdc678" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:46.208371Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:44.972242Z&quot;}}" data-execution_count="32">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb33-1">filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"IMG_2077"</span></span>
<span id="cb33-2">page <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_json(filename)</span>
<span id="cb33-3">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ocr_json_to_df(page)</span>
<span id="cb33-4">df_block <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"level"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block"</span>]</span>
<span id="cb33-5">titles <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_titles(df_block.copy())</span>
<span id="cb33-6">add_titles_to_df(df_block, titles)</span>
<span id="cb33-7">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_image(filename)</span>
<span id="cb33-8">cols, df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_columns(df_block.copy())</span>
<span id="cb33-9">df, recipes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> group_recipes(df, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>)</span>
<span id="cb33-10">plot_recipes(df, image)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/page_segmentation_files/figure-html/cell-33-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="c5cb8c9e9eaf9c56" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:47.497538Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:46.298025Z&quot;}}" data-execution_count="33">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb34-1">filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"IMG_2074"</span></span>
<span id="cb34-2">page <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_json(filename)</span>
<span id="cb34-3">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ocr_json_to_df(page)</span>
<span id="cb34-4">df_block <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"level"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block"</span>]</span>
<span id="cb34-5">titles <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_titles(df_block.copy())</span>
<span id="cb34-6">add_titles_to_df(df_block, titles)</span>
<span id="cb34-7">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_image(filename)</span>
<span id="cb34-8">cols, df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_columns(df_block.copy())</span>
<span id="cb34-9">df, recipes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> group_recipes(df, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>)</span>
<span id="cb34-10">plot_recipes(df, image)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/page_segmentation_files/figure-html/cell-34-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="8158c7585fb8a699" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:47.629418Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:47.625709Z&quot;}}" data-execution_count="34">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb35-1">recipes</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="34">
<pre><code>[{'title': 'Ein würziger Schweinebraten aus der Normandie RÔTI DE PORC AUX POMMES CARAMÉLISÉES',
  'blocks': ['Ein würziger Schweinebraten aus der Normandie RÔTI DE PORC',
   'AUX POMMES CARAMÉLISÉES',
   'SCHWEINEBRATEN MIT KARAMELLISIERTEN ÄPFELN',
   'Wenig Rosmarinnadeln , die Salbeiblätter , Arbeitsaufwand : 30 Minuten die Knoblauchzehen und die Fenchelsamen im Mörser zerstoßen . Salz und Pfeffer zuge- ben . - Die Äpfel schälen , entkernen und in Schnitze schneiden . - Den Zucker mit dem Zitronensaft in einer Bratpfanne erhitzen . Sobald er hellbraun wird , die Äpfel zuge- ben , gut wenden , die Butter in Flocken zu- geben , mit 3 bis 5 EL Wasser ablöschen und ca. 5 Minuten garen . Salzen und pfeffern.- 3 bis 4 Einschnitte im Fleisch anbringen . Die Öffnungen mit der Gewürzmischung fül- len . Das Fleisch zu einem Rollbraten schnü- 2 dl Apfelwein ren , salzen und pfeffern . - Die Rosmarin-',
   'Bratzeit : 2 Stunden Für 4 Personen 5 Zweige Rosmarin 2-3 Salbeiblätter 2 Knoblauchzehen 1 Prise Fenchelsamen Salz , Pfeffer',
   '500 g säuerliche Äpfel 50g Rohzucker 1 EL Zitronensaft 2 EL frische Butter 1 kg magerer Schweinehals 2 EL zimmerwarme Bratbutter',
   'zweige verteilt unter der Schnur anbringen . Das Fleisch mit der weichen Bratbutter bestreichen . In einer Bratkasserolle rundum an- braten . - Den Apfelwein zufügen und zugedeckt bei kleiner Hitze 2 Stunden garen . - Den Bratenfond mit 1 bis 2 EL Wasser aufkochen . 1/3 der Äpfel pürieren und mit dem Bratenjus gut mischen , abschme- cken . - Die restlichen Apfelschnitze rasch erwärmen und als Garni- tur zum tranchierten Braten servieren . Getränk : Rustikaler Rotwein , zum Beispiel aus der Provence Anmerkung : Diese ausgeprägten Zutaten passen auch gut zu Kalb- fleisch . Deshalb lässt sich nach demselben Rezept ebenso gut ein',
   'Kalbsbratenzubereiten .']}]</code></pre>
</div>
</div>
<p>This last layout is one of my favourites in terms of complexity. Triple title and a deeply nested format. The heuristic title detection with all the domain knowledge captures all the three titles together in the final extract. I’m looking forward, how this performs on completely unseen layouts.</p>
</section>
</section>
<section id="recipe-detection-using-doc-layout-yolo" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="recipe-detection-using-doc-layout-yolo"><span class="header-section-number">5</span> Recipe detection using doc-layout YOLO</h2>
<p>We already know title detection works better with the YOLO detector, but what about the columns and recipes?</p>
<p>Once again, we proceed in a two-step approach. First columns, then recipes.</p>
<section id="detecting-columns" class="level3" data-number="5.1">
<h3 data-number="5.1" class="anchored" data-anchor-id="detecting-columns"><span class="header-section-number">5.1</span> Detecting columns</h3>
<p>We use the previously defined function to find columns based on bounding box positions. At this stage, no text is required.</p>
<div id="ecc7296c74b13ffc" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:47.684901Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:47.675291Z&quot;}}" data-execution_count="35">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1">col_df, df_yolo_font_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_columns(df_yolo_font_size)</span></code></pre></div></div>
</div>
<div id="ddcea89110aea63" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:47.738120Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:47.732070Z&quot;}}" data-execution_count="36">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb38" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb38-1">df_yolo_font_size[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="36">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">is_title</th>
<th data-quarto-table-cell-role="th">col_id</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>Soupe à l'ail bonne femme</td>
<td>True</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>Knoblauchsuppe nach Hausfrauenart</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>65</td>
<td>False</td>
<td>3</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>Croûtes aux champignons</td>
<td>True</td>
<td>3</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">4</th>
<td>64</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">5</th>
<td>2 Stangen Porree ( Lauch ) 250 g enthäutete T...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">6</th>
<td>Den Porree putzen , waschen , in Ringe schnei...</td>
<td>False</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>Champignons in Pasteten</td>
<td>False</td>
<td>3</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">8</th>
<td>Die Butter zerlassen , das Weißbrot von beide...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">9</th>
<td>500 g Champignons g Butter Salz Pfeffer Cayen...</td>
<td>False</td>
<td>3</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td></td>
<td>False</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">11</th>
<td>zerdrückte Wacholderbeeren zerdrückte Knoblau...</td>
<td>False</td>
<td>2</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">12</th>
<td>Sahne und Petersilie unterrühren . Die Champi...</td>
<td>False</td>
<td>3</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">13</th>
<td>Das Rehblatt unter fließendem kal- tem Wasser...</td>
<td>False</td>
<td>2</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">14</th>
<td>Den Speck in Streifen schneiden . Die Butter ...</td>
<td>False</td>
<td>2</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">15</th>
<td></td>
<td>False</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">16</th>
<td>Fleisch von den Knochen Das gare lösen , in P...</td>
<td>False</td>
<td>2</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">17</th>
<td>Schalotten abziehen , vierteln , mit den Wach...</td>
<td>False</td>
<td>2</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">18</th>
<td>Speiseöl Parmesankäse</td>
<td>False</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">19</th>
<td></td>
<td>False</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">20</th>
<td>Gigot de chevreuil</td>
<td>True</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">21</th>
<td></td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">22</th>
<td>Den Bratensatz mit etwas Wasser los- kochen u...</td>
<td>False</td>
<td>2</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">23</th>
<td></td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">24</th>
<td>Die Champignons putzen , waschen , vierteln .</td>
<td>False</td>
<td>3</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">25</th>
<td>Die Butter zerlassen , die Champi- gnons dari...</td>
<td>False</td>
<td>3</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">26</th>
<td>Rehblatt</td>
<td>False</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">27</th>
<td></td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">28</th>
<td></td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">29</th>
<td></td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">30</th>
<td></td>
<td>False</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">31</th>
<td></td>
<td>False</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">32</th>
<td>800 g Rehblatt ( Schulter ) Salz , Pfeffer 50...</td>
<td>False</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">33</th>
<td></td>
<td>False</td>
<td>1</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>Again we have four columns. As the DocLayout-YOLO detector counts different, it is not obvious if <code>col_id</code> is correct. We therefore plot the result.</p>
<div id="e1d02841ed3ecbfa" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:48.861758Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:47.853814Z&quot;}}" data-execution_count="37">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb39" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb39-1">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_image(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"20250922_135514"</span>)</span>
<span id="cb39-2"></span>
<span id="cb39-3">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>))</span>
<span id="cb39-4">ax.imshow(image)</span>
<span id="cb39-5"></span>
<span id="cb39-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># YOLO boxes</span></span>
<span id="cb39-7"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df_yolo_font_size.iterrows():</span>
<span id="cb39-8">    color <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"red"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blue"</span></span>
<span id="cb39-9">    rect <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> patches.Rectangle(</span>
<span id="cb39-10">        (row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>], row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>]),</span>
<span id="cb39-11">        row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>],</span>
<span id="cb39-12">        row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>],</span>
<span id="cb39-13">        linewidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb39-14">        edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>color,</span>
<span id="cb39-15">        facecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span></span>
<span id="cb39-16">    )</span>
<span id="cb39-17">    ax.add_patch(rect)</span>
<span id="cb39-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>]:</span>
<span id="cb39-19">        ax.text(row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>], row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TITLE"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"red"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, weight<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>)</span>
<span id="cb39-20"></span>
<span id="cb39-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Column boxes</span></span>
<span id="cb39-22"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> col_df <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb39-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> col_df.iterrows():</span>
<span id="cb39-24">        rect <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> patches.Rectangle(</span>
<span id="cb39-25">            (row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_x1"</span>], row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_y1"</span>]),</span>
<span id="cb39-26">            row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_x2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_x1"</span>],</span>
<span id="cb39-27">            row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_y2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_y1"</span>],</span>
<span id="cb39-28">            linewidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb39-29">            edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"green"</span>,</span>
<span id="cb39-30">            facecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span>,</span>
<span id="cb39-31">            linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"--"</span></span>
<span id="cb39-32">        )</span>
<span id="cb39-33">        ax.add_patch(rect)</span>
<span id="cb39-34">        ax.text(row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_x1"</span>], row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_y1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"COLUMN"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"green"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb39-35"></span>
<span id="cb39-36">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb39-37">plt.show()</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/page_segmentation_files/figure-html/cell-38-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>First, columns are correct.</p>
<p>There are also empty cells which we need to filter for the grouping.</p>
<p>Then we can call our grouping function.</p>
<div id="760b91b902704239" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:49.008174Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:49.000280Z&quot;}}" data-execution_count="38">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb40" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb40-1">sections_df, recipes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> group_recipes(df_yolo_font_size[df_yolo_font_size.text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> recipes</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="38">
<pre><code>[{'title': " Soupe à l'ail bonne femme",
  'blocks': [" Soupe à l'ail bonne femme",
   ' Knoblauchsuppe nach Hausfrauenart',
   ' 2 Stangen Porree ( Lauch ) 250 g enthäutete Tomaten 3-5 Knoblauchzehen 3 EBI . Speiseöl 2 große Kartoffeln 141 Fleischbrühe Salz Pfeffer einige runde , ausgestochene Toast- brotscheiben',
   ' 64',
   ' Speiseöl Parmesankäse',
   ' Den Porree putzen , waschen , in Ringe schneiden . Die Tomaten halbieren , die Stenge- lansätze herausschneiden , das Toma- tenfleisch in Würfel schneiden . Die Knoblauchzehen abziehen und zerdrücken . Das Öl erhitzen , das Gemüse mit den Knoblauchzehen darin andünsten . Die Kartoffeln schälen , waschen , in Scheiben schneiden , mit der Fleisch- brühe zu dem Gemüse geben , zum Kochen bringen , etwa 30 Minuten kochen lassen . Die Suppe mit Salz und Pfeffer abschmecken . Die Toastbrotscheiben mit dem Spei- seöl bestreichen , mit Parmesankäse bestreuen , in den auf 200-225 Grad ( Gas : Stufe 4-5 ) vorgeheizten Back- ofen schieben und 8-10 Minuten überbacken . Das Brot heiß zu der Suppe reichen .',
   ' Rehblatt']},
 {'title': ' Gigot de chevreuil',
  'blocks': [' Gigot de chevreuil',
   ' 800 g Rehblatt ( Schulter ) Salz , Pfeffer 50 g durchwachsener Speck 25 g Butter 2 Schalotten',
   ' zerdrückte Wacholderbeeren zerdrückte Knoblauchzehen 2-3 Thymianzweige 125 ml ( 1 ) Rotwein 250 ml ( 1 ) Wasser 10 g Butter 2 Teel . Weizenmehl 125 ml ( 1 ) Schlagsahne',
   ' Das Rehblatt unter fließendem kal- tem Wasser abspülen , trockentupfen , enthäuten und mit Salz und Pfeffer einreiben .',
   ' Den Speck in Streifen schneiden . Die Butter ( 25 g ) zerlassen , die Speckstreifen und das Fleisch darin anbraten .',
   ' Schalotten abziehen , vierteln , mit den Wacholderbeeren und den gewaschenen Thymianzweigen zu dem Fleisch geben . Den Rotwein und etwas von dem Wasser hinzugießen . Das Fleisch etwa 1 Stunde schmoren lassen , ab und zu wenden und mit dem Bratensatz begießen . Die ver- dampfte Flüssigkeit nach und nach durch Wasser ersetzen .',
   ' Fleisch von den Knochen Das gare lösen , in Portionsstücke schneiden , auf einer vorgewärmten Platte anrichten und warm stellen .',
   ' Den Bratensatz mit etwas Wasser los- kochen und durch ein Sieb gießen . Die Butter ( 10 g ) mit dem Weizen- mehl verrühren , zum Bratensatz geben , mit einem Schneebesen durchschlagen und aufkochen lassen . Die Sahne unterrühren . Die Sauce mit Salz und Pfeffer abschmecken .']},
 {'title': ' Croûtes aux champignons',
  'blocks': [' Croûtes aux champignons',
   ' Champignons in Pasteten',
   ' 500 g Champignons g Butter Salz Pfeffer Cayennepfeffer 125 ml ( 1 ) Wasser 2 gestrichene EBI . Speisestärke 3 EBI . Schlagsahne 2 EBI . gehackte Petersilie Zitronensaft 4 Blätterteigpasteten ( fertig gekauft )',
   ' Die Champignons putzen , waschen , vierteln .',
   ' Die Butter zerlassen , die Champi- gnons darin andünsten , mit Salz , Pfeffer und Cayennepfeffer würzen . Das Wasser hinzugießen , in etwa 10 Minuten gar dünsten lassen . Die Speisestärke mit 3 EBI . kaltem Wasser anrühren , die Pilze damit bin- den .',
   ' Sahne und Petersilie unterrühren . Die Champignons mit den Gewürzen und dem Zitronensaft abschmecken . Von den Pasteten Hülsen und Deckel auf ein Backblech legen und in den auf 200-225 Grad ( Gas : Stufe 4-5 ) vorgeheizten Backofen schieben und in etwa 5 Minuten erwärmen . Die Champignons in die Pasteten fül- len , die Deckel darauf setzen .',
   ' 65']}]</code></pre>
</div>
</div>
<p>There is an issue with nested blocks: title “gigot de chevreuil” and “Rehblatt”. Somehow Rehblatt ended up in recipe 0.</p>
</section>
<section id="generalization-of-yolo-doclayoutocr" class="level3" data-number="5.2">
<h3 data-number="5.2" class="anchored" data-anchor-id="generalization-of-yolo-doclayoutocr"><span class="header-section-number">5.2</span> Generalization of YOLO-doclayout+OCR</h3>
<p>Again we check, how other recipes perform. This time we look at the dataframe.</p>
<div id="44fe7ec37806f707" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:49.440548Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:49.066064Z&quot;}}" data-execution_count="39">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb42" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb42-1">filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"IMG_2077"</span></span>
<span id="cb42-2">page <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_json(filename)</span>
<span id="cb42-3"></span>
<span id="cb42-4">det_res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.predict(</span>
<span id="cb42-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/IMG_2077.jpg"</span>,</span>
<span id="cb42-6">    imgsz<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>,</span>
<span id="cb42-7">    conf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>,</span>
<span id="cb42-8">    device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda:0"</span>,</span>
<span id="cb42-9">    verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb42-10">)</span>
<span id="cb42-11">df_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> yolo_to_df(det_res[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb42-12"></span>
<span id="cb42-13">df_yolo_font_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> add_text_and_font_size_to_layout_df(df_yolo.copy(), page)</span>
<span id="cb42-14"></span>
<span id="cb42-15">df_titles_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_titles(df_yolo_font_size[df_yolo_font_size.is_title].copy(), font_factor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb42-16">add_titles_to_df(df_yolo_font_size, df_titles_yolo)</span>
<span id="cb42-17"></span>
<span id="cb42-18">col_df, df_yolo_font_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_columns(df_yolo_font_size.copy())</span>
<span id="cb42-19">sections_df, recipes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> group_recipes(df_yolo_font_size[df_yolo_font_size.text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>])</span>
<span id="cb42-20">sections_df[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>]]</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display" data-execution_count="39">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">is_title</th>
<th data-quarto-table-cell-role="th">recipe_id</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>Préchauffez le four à 220 ° C . Faites cuire ...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>Mélangez les fèves dans un saladier avec le f...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>Toastez les tranches de pain . Répartissez le...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>Salade de poulet , fèves , fenouil et concomb...</td>
<td>True</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">4</th>
<td>L'estragon est utilisé en phytothérapie pour ...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">5</th>
<td>Pour 4 personnes Préparation : 10 min Cuisson...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">6</th>
<td>Pelez le concombre ( s'il n'est pas bio ) et ...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>Parfait pour le soir !</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">8</th>
<td>✓ 1 cuil . à café de zestes de citron</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">9</th>
<td>126 PLATS DETOX</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td>✓2 cuil . à soupe d'estragon frais haché</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">11</th>
<td>✓ 8 tranches de pain de campagne aux graines ...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">12</th>
<td>✓ 1 cuil . à soupe de vinaigre de vin rouge</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">13</th>
<td>✓ 2 gros blancs de poulet ( ou 4 petits )</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">14</th>
<td>✓2 cuil . à café de jus de citron frais</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">15</th>
<td>✓ 150 g de fèves ( surgelées ) 1 petit concom...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">16</th>
<td>✓ Huile d'olive ✓ Sel , poivre</td>
<td>False</td>
<td>0</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<div id="52ad695e1a335b7" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:49.880393Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:49.502222Z&quot;}}" data-execution_count="40">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb43-1">filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"IMG_2074"</span></span>
<span id="cb43-2">page <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_json(filename)</span>
<span id="cb43-3"></span>
<span id="cb43-4">det_res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.predict(</span>
<span id="cb43-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/IMG_2074.jpg"</span>,</span>
<span id="cb43-6">    imgsz<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>,</span>
<span id="cb43-7">    conf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>,</span>
<span id="cb43-8">    device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda:0"</span>,</span>
<span id="cb43-9">    verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb43-10">)</span>
<span id="cb43-11">df_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> yolo_to_df(det_res[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb43-12"></span>
<span id="cb43-13">df_yolo_font_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> add_text_and_font_size_to_layout_df(df_yolo.copy(), page)</span>
<span id="cb43-14"></span>
<span id="cb43-15">df_titles_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_titles(df_yolo_font_size[df_yolo_font_size.is_title].copy(), font_factor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb43-16">add_titles_to_df(df_yolo_font_size, df_titles_yolo)</span>
<span id="cb43-17"></span>
<span id="cb43-18">col_df, df_yolo_font_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_columns(df_yolo_font_size.copy())</span>
<span id="cb43-19">sections_df, recipes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> group_recipes(df_yolo_font_size[df_yolo_font_size.text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>])</span>
<span id="cb43-20">sections_df[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"is_title"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>]]</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>unassigned words:</code></pre>
</div>
<div class="cell-output cell-output-display" data-execution_count="40">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">is_title</th>
<th data-quarto-table-cell-role="th">recipe_id</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>Für 4 Personen Zweige Rosmarin 2-3 Salbeiblät...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>zweige verteilt unter der Schnur anbringen . ...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>RÔTI DE PORC POMMES CARAMÉLISÉES</td>
<td>True</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>Bratzeit : 2 Stunden : 30 Minuten</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">4</th>
<td>SCHWEINEBRATEN MIT KARAMELLISIERTEN ÄPFELN</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">5</th>
<td>Rosmarinnadeln , die Salbeiblätter , die Knob...</td>
<td>False</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">6</th>
<td>Ein würziger Schweinebraten aus der Normandie</td>
<td>False</td>
<td>-1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>Getränk : Rustikaler Rotwein , zum Beispiel a...</td>
<td>False</td>
<td>0</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>Here we run into the first issue: the triple subtile leads to missing text in the final segmentation, shown as “-1” in the recipe_id column.</p>
<p>Something actually worse than the wrong identified title in the pure OCR case.</p>
</section>
</section>
<section id="comparison-of-pure-ocr-pipeline-vs-ocryolo-doclayout" class="level2" data-number="6">
<h2 data-number="6" class="anchored" data-anchor-id="comparison-of-pure-ocr-pipeline-vs-ocryolo-doclayout"><span class="header-section-number">6</span> Comparison of pure OCR pipeline vs OCR+YOLO-doclayout</h2>
<p>We will compare the two approaches by wrapping them in functions To make the comparison clearer, we’ll also use a different recipe this time.</p>
<div id="b5f9256347697bfe" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:50.205991Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:50.202131Z&quot;}}" data-execution_count="41">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb45" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb45-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_recipes_ocr_only_block(filename, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'block'</span>):</span>
<span id="cb45-2">    page <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_json(filename)</span>
<span id="cb45-3">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ocr_json_to_df(page)</span>
<span id="cb45-4">    df_block <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"level"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span>]</span>
<span id="cb45-5"></span>
<span id="cb45-6">    titles <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_titles(df_block.copy())</span>
<span id="cb45-7">    add_titles_to_df(df_block, titles)</span>
<span id="cb45-8"></span>
<span id="cb45-9">    cols, df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_columns(df_block.copy())</span>
<span id="cb45-10">    df, recipes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> group_recipes(df)</span>
<span id="cb45-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df, recipes</span>
<span id="cb45-12"></span>
<span id="cb45-13"></span>
<span id="cb45-14"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_recipes_yolo(filename):</span>
<span id="cb45-15">    page <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_json(filename)</span>
<span id="cb45-16"></span>
<span id="cb45-17">    det_res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.predict(</span>
<span id="cb45-18">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".jpg"</span>,</span>
<span id="cb45-19">        imgsz<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>,</span>
<span id="cb45-20">        conf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>,</span>
<span id="cb45-21">        device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda:0"</span>,</span>
<span id="cb45-22">        verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb45-23">    )</span>
<span id="cb45-24">    df_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> yolo_to_df(det_res[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb45-25"></span>
<span id="cb45-26">    df_yolo_font_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> add_text_and_font_size_to_layout_df(df_yolo.copy(), page)</span>
<span id="cb45-27"></span>
<span id="cb45-28">    df_titles_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_titles(df_yolo_font_size[df_yolo_font_size.is_title].copy(), font_factor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb45-29">    add_titles_to_df(df_yolo_font_size, df_titles_yolo)</span>
<span id="cb45-30"></span>
<span id="cb45-31">    col_df, df_yolo_font_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_columns(df_yolo_font_size.copy())</span>
<span id="cb45-32">    sections_df, recipes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> group_recipes(df_yolo_font_size[df_yolo_font_size.text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>])</span>
<span id="cb45-33">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> sections_df, recipes</span></code></pre></div></div>
</div>
<section id="runtime-comparison" class="level3" data-number="6.1">
<h3 data-number="6.1" class="anchored" data-anchor-id="runtime-comparison"><span class="header-section-number">6.1</span> Runtime comparison</h3>
<div id="5b67cb170be11fd5" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:50.277191Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:50.252300Z&quot;}}" data-execution_count="42">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb46" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb46-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>time</span>
<span id="cb46-2">df_ocr, r_ocr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_recipes_ocr_only_block(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"IMG_2073"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>CPU times: user 22.5 ms, sys: 162 μs, total: 22.7 ms
Wall time: 22.1 ms</code></pre>
</div>
</div>
<div id="1ea40ecefd4c868a" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:50.692511Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:50.304186Z&quot;}}" data-execution_count="43">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb48" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb48-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>time</span>
<span id="cb48-2"></span>
<span id="cb48-3">df_yolo, r_yolo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_recipes_yolo(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"IMG_2073"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>unassigned words:
CPU times: user 354 ms, sys: 31.9 ms, total: 386 ms
Wall time: 386 ms</code></pre>
</div>
</div>
<p>The OCR only approach is 20x faster, as we do not need to access the GPU. Without GPU it would take even more time.</p>
</section>
<section id="recipe-output-comparison" class="level3" data-number="6.2">
<h3 data-number="6.2" class="anchored" data-anchor-id="recipe-output-comparison"><span class="header-section-number">6.2</span> Recipe output comparison</h3>
<p>Let’s check if we discovered the same recipes. For that we try to realign the different rows and put the recipe ids of each approach on the ocr dataframe.</p>
<div id="ece8a537cc940465" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:50.703680Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:50.698782Z&quot;}}" data-execution_count="44">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb50" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb50-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> attach_yolo_recipe_ids(df_ocr, df_yolo, pad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, min_iou<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>):</span>
<span id="cb50-2">    df_ocr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_ocr.copy()</span>
<span id="cb50-3">    recipe_ids <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb50-4"></span>
<span id="cb50-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _, block <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df_ocr.iterrows():</span>
<span id="cb50-6">        bx1, by1, bx2, by2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> block[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>], block[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>], block[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>], block[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>]</span>
<span id="cb50-7"></span>
<span id="cb50-8">        assigned_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb50-9">        best_iou <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb50-10">        candidate_boxes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb50-11"></span>
<span id="cb50-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _, yrow <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df_yolo.iterrows():</span>
<span id="cb50-13">            yx1, yy1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pad, yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pad</span>
<span id="cb50-14">            yx2, yy2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> pad, yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> pad</span>
<span id="cb50-15"></span>
<span id="cb50-16">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Check containment first</span></span>
<span id="cb50-17">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (bx1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> yx1) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (by1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> yy1) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (bx2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> yx2) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (by2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> yy2):</span>
<span id="cb50-18">                candidate_boxes.append((yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>], (yx2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> yx1) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (yy2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> yy1)))</span>
<span id="cb50-19"></span>
<span id="cb50-20">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># IoU calculation</span></span>
<span id="cb50-21">            inter_x1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(bx1, yx1)</span>
<span id="cb50-22">            inter_y1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(by1, yy1)</span>
<span id="cb50-23">            inter_x2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(bx2, yx2)</span>
<span id="cb50-24">            inter_y2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(by2, yy2)</span>
<span id="cb50-25">            inter_w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, inter_x2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> inter_x1)</span>
<span id="cb50-26">            inter_h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, inter_y2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> inter_y1)</span>
<span id="cb50-27">            inter_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> inter_w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> inter_h</span>
<span id="cb50-28"></span>
<span id="cb50-29">            block_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (bx2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> bx1) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (by2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> by1)</span>
<span id="cb50-30">            yolo_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (yx2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> yx1) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (yy2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> yy1)</span>
<span id="cb50-31">            union_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> block_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> yolo_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> inter_area</span>
<span id="cb50-32"></span>
<span id="cb50-33">            iou <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> inter_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> union_area <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> union_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb50-34"></span>
<span id="cb50-35">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> iou <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> best_iou:</span>
<span id="cb50-36">                best_iou <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> iou</span>
<span id="cb50-37">                assigned_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>]</span>
<span id="cb50-38"></span>
<span id="cb50-39">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Prefer containment rule</span></span>
<span id="cb50-40">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> candidate_boxes:</span>
<span id="cb50-41">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># pick smallest enclosing box (most specific title/region)</span></span>
<span id="cb50-42">            assigned_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(candidate_boxes, key<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> x: x[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb50-43">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> best_iou <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> min_iou:</span>
<span id="cb50-44">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># fallback centroid if IoU too small</span></span>
<span id="cb50-45">            bcx, bcy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (bx1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> bx2) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, (by1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> by2) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb50-46">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _, yrow <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df_yolo.iterrows():</span>
<span id="cb50-47">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> bcx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span>]) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> bcy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y2"</span>]):</span>
<span id="cb50-48">                    assigned_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> yrow[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>]</span>
<span id="cb50-49">                    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb50-50"></span>
<span id="cb50-51">        recipe_ids.append(assigned_id)</span>
<span id="cb50-52"></span>
<span id="cb50-53">    df_ocr[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id_yolo"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> recipe_ids</span>
<span id="cb50-54">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df_ocr</span></code></pre></div></div>
</div>
<div id="815249d0448bbda1" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:50.765404Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:50.753389Z&quot;}}" data-execution_count="45">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb51" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb51-1">combined <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> attach_yolo_recipe_ids(df_ocr, df_yolo)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> combined[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id_yolo"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="45">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">recipe_id</th>
<th data-quarto-table-cell-role="th">recipe_id_yolo</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">1</th>
<td>0</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">4</th>
<td>0</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">11</th>
<td>0</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">14</th>
<td>0</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">16</th>
<td>0</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">20</th>
<td>0</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">23</th>
<td>0</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">28</th>
<td>0</td>
<td>-1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">32</th>
<td>0</td>
<td>-1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">34</th>
<td>0</td>
<td>-1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">39</th>
<td>0</td>
<td>-1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">41</th>
<td>0</td>
<td>-1</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>Something has gone wrong.</p>
<p>Let’s look at the recipes</p>
<div id="31a192b5c36a65d5" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:50.906509Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:50.894840Z&quot;}}" data-execution_count="46">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb52" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb52-1">r_ocr</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="46">
<pre><code>[{'title': 'Merlu Koskera',
  'blocks': ['Merlu Koskera',
   'Pour 6 personnes : Temps de préparation : 30 minutes Temps de cuisson : 20 minutes',
   "Ingrédients : • 6 médaillons de merlu • 300 g d'asperges blanches en conserve • 500 g de petits pois en conserve • 1 poignée de palourdes • 1 poignée de moules ⚫ 3 œufs durs",
   "• 10 cl de vin blanc sec type Irouléguy • 1 cuillère à café de purée de piment d'Espelette • 4 gousses d'ail",
   '• Persil',
   "• 3 cuillères à soupe de farine • Sel de Guérande • Poudre de piment d'Espelette",
   "• Huile d'olive • 20 cl de fumet de poisson",
   "Faites un hachis d'ail et de persil . Réservez . Salez et farinez les médaillons de merlu . Réservez . Dans une cocotte , faites ouvrir les moules et les palourdes , conservez leur jus . Dans une sauteuse , faites revenir les médaillons de merlu dans l'huile d'olive mélangée à la purée",
   "de piment durant 2 minutes de chaque côté . Dans un plat en terre , déposez les médaillons de merlu . Réservez . Faites revenir pendant quelques minutes le hachis de persil et d'ail dans l'huile d'olive . Saupoudrez de farine , arrosez du jus des coquillages , du vin blanc et du fumet de poisson .",
   'Versez sur les médaillons .',
   'Ajoutez les moules , les palourdes , les asperges et les petits pois . Laissez mijoter à feu doux pendant 10 minutes . Ajoutez les œufs durs en quartier avant la fin de la cuisson . Saupoudrez de persil et de poudre de piment .',
   'Servez sans attendre .']}]</code></pre>
</div>
</div>
<div id="52a1a9ae78915812" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:51.216932Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:51.213995Z&quot;}}" data-execution_count="47">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb54" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb54-1">r_yolo</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="47">
<pre><code>[{'title': ' Merlu Koskera',
  'blocks': [' Merlu Koskera',
   ' Pour 6 personnes : Temps de préparation : 30 minutes Temps de cuisson : 20 minutes',
   ' Ingrédients :',
   " 6 médaillons de merlu 300 g d'asperges blanches en conserve • 500 g de petits pois en conserve • 1 poignée de palourdes • 1 poignée de moules ⚫ 3 œufs durs • 10 cl de vin blanc sec type Irouléguy • 1 cuillère à café de purée de piment d'Espelette • 4 gousses d'ail • Persil • 3 cuillères à soupe de farine • Sel de Guérande • Poudre de piment d'Espelette • Huile d'olive • 20 cl de fumet de poisson"]}]</code></pre>
</div>
</div>
<p>We are missing text in the DocLayout-YOLO recipe. When we look at the input dataframe, we see there are two columns.</p>
<div id="4b5e17df5f7bf3fe" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:51.291335Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:51.285666Z&quot;}}" data-execution_count="48">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb56" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb56-1">df_yolo[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>]]</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="48">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">text</th>
<th data-quarto-table-cell-role="th">col_id</th>
<th data-quarto-table-cell-role="th">recipe_id</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>Faites un hachis d'ail et de persil . Réserve...</td>
<td>0</td>
<td>-1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>6 médaillons de merlu 300 g d'asperges blanch...</td>
<td>1</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>Pour 6 personnes : Temps de préparation : 30 ...</td>
<td>1</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>Merlu Koskera</td>
<td>1</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">4</th>
<td>Ingrédients :</td>
<td>1</td>
<td>0</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>But when we look at the image there is only one.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/pictures/IMG_2073.jpg" class="img-fluid figure-img"></p>
<figcaption>skew image</figcaption>
</figure>
</div>
<p>A grain of salt: the shortcomings could be related to my optimization towards the heuristic approach.</p>
</section>
</section>
<section id="quantitative-analysis" class="level2" data-number="7">
<h2 data-number="7" class="anchored" data-anchor-id="quantitative-analysis"><span class="header-section-number">7</span> Quantitative analysis</h2>
<p>To evaluate the performance, I did define some reference data, with recipe title and the correct OCR block to recipe mapping.</p>
<div id="d23365fe2b8ba1fe" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:51.506944Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:51.502703Z&quot;}}" data-execution_count="49">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb57" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb57-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/ground-truth/ground-truth.json"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r"</span>, encoding<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"utf-8"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb57-2">    reference <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> json.load(f)</span>
<span id="cb57-3"></span>
<span id="cb57-4">reference_map <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {page[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"page_id"</span>]: page <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> page <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> reference[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data"</span>]}</span></code></pre></div></div>
</div>
<div id="a646e33789cf1a71" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:51.900099Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:51.897724Z&quot;}}" data-execution_count="50">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb58" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb58-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> evaluate_page(page_id, df_ocr, reference_map):</span>
<span id="cb58-2">    ref <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> reference_map[page_id]</span>
<span id="cb58-3"></span>
<span id="cb58-4">    df_ocr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_ocr.sort_values([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col_id"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y1"</span>]).reset_index(drop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb58-5">    df_ocr[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id_ref"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ref[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"reference_sections"</span>]</span>
<span id="cb58-6"></span>
<span id="cb58-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df_ocr, ref</span></code></pre></div></div>
</div>
<div id="8fffcbbfef6903d2" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:52.079912Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:52.077403Z&quot;}}" data-execution_count="51">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb59" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb59-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> compute_metrics(df):</span>
<span id="cb59-2">    y_ref <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id_ref"</span>]</span>
<span id="cb59-3">    y_ocr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span>]</span>
<span id="cb59-4"></span>
<span id="cb59-5">    results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb59-6"></span>
<span id="cb59-7">    results[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ocr_acc"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> accuracy_score(y_ref, y_ocr) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipe_id"</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb59-8"></span>
<span id="cb59-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> results</span></code></pre></div></div>
</div>
<div id="d627d834830e3636" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:52.317399Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:52.313171Z&quot;}}" data-execution_count="52">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb60" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb60-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> title_accuracy_from_recipes(recipes, ref_titles, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>):</span>
<span id="cb60-2">    pred_titles <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>].strip() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> recipes <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> r.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>)]</span>
<span id="cb60-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(pred_titles)</span>
<span id="cb60-4">    ref_titles <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [rt.strip() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> rt <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> ref_titles]</span>
<span id="cb60-5"></span>
<span id="cb60-6">    matches <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb60-7">    matched <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb60-8"></span>
<span id="cb60-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> rt <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> ref_titles:</span>
<span id="cb60-10">        scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [(pt, SequenceMatcher(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, pt.lower(), rt.lower()).ratio()) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> pt <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> pred_titles]</span>
<span id="cb60-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> scores:</span>
<span id="cb60-12">            best_pred, best_score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(scores, key<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> x: x[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb60-13">            matches.append((rt, best_pred, best_score))</span>
<span id="cb60-14">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> best_score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> threshold:</span>
<span id="cb60-15">                matched <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb60-16">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb60-17">            matches.append((rt, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>))</span>
<span id="cb60-18"></span>
<span id="cb60-19">    accuracy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> matched <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(ref_titles) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> ref_titles <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span></span>
<span id="cb60-20">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> accuracy, matches</span></code></pre></div></div>
</div>
<div id="137b5baa8f5a756" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:52.540074Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:52.325340Z&quot;}}" data-execution_count="53">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb61" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb61-1"></span>
<span id="cb61-2">all_metrics <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb61-3"></span>
<span id="cb61-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> json_path <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> glob.glob(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/*.jpg"</span>):</span>
<span id="cb61-5">    page_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> os.path.splitext(os.path.basename(json_path))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb61-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> page_id <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> reference_map:</span>
<span id="cb61-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span>
<span id="cb61-8"></span>
<span id="cb61-9">    df_ocr, recipes_ocr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_recipes_ocr_only_block(page_id)</span>
<span id="cb61-10"></span>
<span id="cb61-11">    df_eval, ref <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> evaluate_page(page_id, df_ocr,  reference_map)</span>
<span id="cb61-12">    metrics <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> compute_metrics(df_eval)</span>
<span id="cb61-13"></span>
<span id="cb61-14">    ref_titles <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> ref[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"recipes"</span>]]</span>
<span id="cb61-15"></span>
<span id="cb61-16">    ocr_acc, ocr_matches <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> title_accuracy_from_recipes(recipes_ocr, ref_titles, threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>)</span>
<span id="cb61-17"></span>
<span id="cb61-18">    metrics.update({</span>
<span id="cb61-19">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># OCR metrics</span></span>
<span id="cb61-20">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ocr_title_accuracy"</span>: ocr_acc,</span>
<span id="cb61-21">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ocr_title_matches"</span>: ocr_matches,</span>
<span id="cb61-22">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ocr_num_pred_recipes"</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(recipes_ocr),</span>
<span id="cb61-23"></span>
<span id="cb61-24">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Reference info</span></span>
<span id="cb61-25">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"num_ref_recipes"</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(ref_titles),</span>
<span id="cb61-26">    })</span>
<span id="cb61-27"></span>
<span id="cb61-28">    all_metrics.append((page_id, metrics))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>['Merlu Koskera']
['Artichauts à la sauce vinaigrette Artischocken mit Vinaigrette ( Foto S. 63 )', 'Asperges ,, sauce mousseline❝ Spargel mit abgeschlagener Sauce', '2 EBI . steifgeschlagene Schlagsahne']
["Soupe à l'ail bonne femme Knoblauchsuppe nach Hausfrauenart", 'Gigot de chevreuil']
["Dinde pochée au lait d'amande , mange - tout et haricots", 'Info nutrition']
['Croquetas', 'Boudin noir sur Canapé']
['Lapin aux pruneaux']
["Soupe à l'ail bonne femme Knoblauchsuppe nach Hausfrauenart", 'Gigot de chevreuil', 'Croûtes aux champignons Champignons in Pasteten']
['Variantes', '92 PLATS FEEL GOOD']
['Salade de poulet , fèves , fenouil et concombre sur toasts']
['Ein würziger Schweinebraten aus der Normandie RÔTI DE PORC AUX POMMES CARAMÉLISÉES']
['Mulligatawny']
['Croûtes aux champignons Champignons in Pasteten']</code></pre>
</div>
</div>
<div id="188708fb44dedb66" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-02T18:46:52.562954Z&quot;,&quot;start_time&quot;:&quot;2025-10-02T18:46:52.550092Z&quot;}}" data-execution_count="54">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb63" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb63-1">df_metrics <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame(</span>
<span id="cb63-2">    [{<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"page_id"</span>: pid}, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>m} <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> pid, m <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> all_metrics]</span>
<span id="cb63-3">)</span>
<span id="cb63-4">df_metrics</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="54">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">page_id</th>
<th data-quarto-table-cell-role="th">ocr_acc</th>
<th data-quarto-table-cell-role="th">ocr_title_accuracy</th>
<th data-quarto-table-cell-role="th">ocr_title_matches</th>
<th data-quarto-table-cell-role="th">ocr_num_pred_recipes</th>
<th data-quarto-table-cell-role="th">num_ref_recipes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>IMG_2073</td>
<td>1.000000</td>
<td>1.000000</td>
<td>[(Merlu Koskera, Merlu Koskera, 1.0)]</td>
<td>1</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>20250922_135453</td>
<td>0.750000</td>
<td>0.000000</td>
<td>[(Artichauts à la sauce vinaigrette, Artichaut...</td>
<td>3</td>
<td>2</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>20250922_135507</td>
<td>1.000000</td>
<td>0.500000</td>
<td>[(Soupe à l'ail bonne femme, Soupe à l'ail bon...</td>
<td>2</td>
<td>2</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>IMG_2079</td>
<td>0.692308</td>
<td>1.000000</td>
<td>[(Dinde pochée au lait d'amande, mange - tout ...</td>
<td>2</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">4</th>
<td>20250922_213505</td>
<td>1.000000</td>
<td>1.000000</td>
<td>[(Croquetas, Croquetas, 1.0), (Boudin noir sur...</td>
<td>2</td>
<td>2</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">5</th>
<td>IMG_2078</td>
<td>1.000000</td>
<td>1.000000</td>
<td>[(Lapin aux pruneaux, Lapin aux pruneaux, 1.0)]</td>
<td>1</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">6</th>
<td>20250922_135514</td>
<td>0.916667</td>
<td>0.333333</td>
<td>[(Soupe à l'ail bonne femme, Soupe à l'ail bon...</td>
<td>3</td>
<td>3</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>IMG_2080</td>
<td>0.125000</td>
<td>0.000000</td>
<td>[(Gnocchi sans gluten à la patate douce et pes...</td>
<td>2</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">8</th>
<td>IMG_2077</td>
<td>1.000000</td>
<td>1.000000</td>
<td>[(Salade de poulet, fèves, fenouil et concombr...</td>
<td>1</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">9</th>
<td>IMG_2074</td>
<td>1.000000</td>
<td>0.000000</td>
<td>[(RÔTI DE PORC POMMES CARAMÉLISÉES, Ein würzig...</td>
<td>1</td>
<td>1</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td>IMG_2076</td>
<td>1.000000</td>
<td>1.000000</td>
<td>[(Mulligatawny, Mulligatawny, 1.0)]</td>
<td>1</td>
<td>1</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">11</th>
<td>20250922_135510</td>
<td>1.000000</td>
<td>0.000000</td>
<td>[(Croûtes aux champignons, Croûtes aux champig...</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>In short, the algorithm is far from perfect.</p>
<p>Most errors result from incorrect titles. When the titles are wrong, to too many recipes are created.</p>
</section>
<section id="outlook" class="level2" data-number="8">
<h2 data-number="8" class="anchored" data-anchor-id="outlook"><span class="header-section-number">8</span> Outlook</h2>
<p>A few possible improvements include:</p>
<ul>
<li>stabilizing titles with DocLayout-YOLO</li>
<li>using book-dependent settings adjusted based on user feedback</li>
<li>allowing manual user overrides</li>
<li>training a classifier solely on OCR data, but with much larger datasets</li>
</ul>
<p>We’ll see how this evolves once it’s integrated into the main app.</p>


</section>

 ]]></description>
  <category>Python</category>
  <category>Computer Vision</category>
  <category>Machine Learning</category>
  <category>Generative AI</category>
  <guid>https://www.storymelange.com/posts/projects/recipescanner/page_segmentation.html</guid>
  <pubDate>Fri, 24 Oct 2025 00:00:00 GMT</pubDate>
  <media:content url="https://www.storymelange.com/posts/projects/recipescanner/pictures/result.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Is training your own classifier really worth it?</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/recipescanner/text_or_image_doclayout.html</link>
  <description><![CDATA[ 




<section id="what-happened-so-far" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="what-happened-so-far"><span class="header-section-number">1</span> What happened so far</h2>
<p>I recently trained a text or page classifier, which helped me dramatically speed up the sorting of scans for further processing in an OCR pipeline.</p>
<p>Recently I have been using Doclayout-YOLO for further processing of the text pages and especially the pages with mixed layout.</p>
<p>Doclayout-YOLO has proofed quite reliable in detecting existing text with bounding boxes. In addition it is optimized for speed.</p>
<p>When I finished the first part of this classifier I had the idea, why not just count the number or size of text boxes on a page?</p>
</section>
<section id="doclayout-yolo" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="doclayout-yolo"><span class="header-section-number">2</span> Doclayout-YOLO</h2>
<p>Doclayout-YOLO was trained on top of YOLO10 with 300k synthetic documents. YOLO is a End-to-end object detection network, whereas Resnet is first a classification network. While object detection can be done with a resnet by outputting 4 numbers for each pixel. It requires further processing. This makes it slower than YOLO. YOLO splits the image into boxes and then detects classes within those boxes.</p>
<div id="initial_id" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T18:25:23.126195Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T18:25:21.371478Z&quot;}}" data-execution_count="3">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> cv2</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> doclayout_yolo <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> YOLOv10</span></code></pre></div></div>
</details>
</div>
<section id="first-impression" class="level3" data-number="2.1">
<h3 data-number="2.1" class="anchored" data-anchor-id="first-impression"><span class="header-section-number">2.1</span> First impression</h3>
<p>We first load the model to the GPU.</p>
<div id="9aab4ab49c65e7a8" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T18:25:25.197053Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T18:25:24.853873Z&quot;}}" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> YOLOv10(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/models/doclayout_yolo.pt"</span>)</span>
<span id="cb2-2">model.to(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda:0"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</div>
<p>and then examine one page</p>
<div id="d219b32c20229e81" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T18:25:28.415932Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T18:25:26.936196Z&quot;}}" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">det_res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.predict(</span>
<span id="cb3-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/text_page/IMG_0751.JPG"</span>,</span>
<span id="cb3-3">    imgsz<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>,</span>
<span id="cb3-4">    conf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>,</span>
<span id="cb3-5">    device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda:0"</span>,</span>
<span id="cb3-6">    verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb3-7">)</span>
<span id="cb3-8"></span>
<span id="cb3-9">annotated_frame <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> det_res[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].plot(pil<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, line_width<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, font_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>)</span>
<span id="cb3-10">img_rgb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB)</span>
<span id="cb3-11"></span>
<span id="cb3-12">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>))</span>
<span id="cb3-13">plt.imshow(img_rgb)</span>
<span id="cb3-14">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb3-15">plt.show()</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/text_or_image_doclayout_files/figure-html/cell-4-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>We can clearly see title, text and image boxes. The model ignores areas of white space. That the part outside of the book is recognized as image seems understandable, as the model has no concept of the entity <code>book</code>.</p>
</section>
</section>
<section id="text-or-not" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="text-or-not"><span class="header-section-number">3</span> Text or not</h2>
<p>The model returns the type of box. A text box is of the class 1.</p>
<p>Let’s first count text boxes</p>
<div id="bec5c2e945e91eb4" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T18:25:46.047592Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T18:25:46.038072Z&quot;}}" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"></span>
<span id="cb4-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> count_text_boxes(model, filename, conf_threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>):</span>
<span id="cb4-3">    det_res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.predict(</span>
<span id="cb4-4">        filename,</span>
<span id="cb4-5">        imgsz<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>,</span>
<span id="cb4-6">        conf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>conf_threshold,</span>
<span id="cb4-7">        verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb4-8">    )</span>
<span id="cb4-9">    detections <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> det_res[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].boxes</span>
<span id="cb4-10"></span>
<span id="cb4-11">    text_boxes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb4-12">        box <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> box <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> detections</span>
<span id="cb4-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(box.cls) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(box.conf) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> conf_threshold</span>
<span id="cb4-14">    ]</span>
<span id="cb4-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(text_boxes)</span></code></pre></div></div>
</div>
<div id="2b09ec1ad1c58bd1" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T18:26:22.346071Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T18:26:22.169572Z&quot;}}" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>time</span>
<span id="cb5-2">count_text_boxes(model, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/text_page/IMG_0751.JPG"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>CPU times: user 144 ms, sys: 31 ms, total: 175 ms
Wall time: 172 ms</code></pre>
</div>
<div class="cell-output cell-output-display" data-execution_count="10">
<pre><code>11</code></pre>
</div>
</div>
<p>There are 11 text boxes. The result was obtained in 179ms. My self trained CNN needs 160ms.</p>
<p>We allow one text box for image pages</p>
<div id="574460a7c7d8b052" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T18:26:40.932939Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T18:26:40.923344Z&quot;}}" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_text_page(model, filename, conf_threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, box_threshold<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb8-2">    text_box_count <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> count_text_boxes(model, filename, conf_threshold)</span>
<span id="cb8-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> text_box_count <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> box_threshold:</span>
<span id="cb8-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb8-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span></code></pre></div></div>
</div>
<div id="ba02ec0aef7682f4" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T14:59:18.262095Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T14:59:18.076339Z&quot;}}" data-execution_count="60">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">is_text_page(model, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/text_page/IMG_0751.JPG"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="60">
<pre><code>True</code></pre>
</div>
</div>
<section id="evaluation" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="evaluation"><span class="header-section-number">3.1</span> Evaluation</h3>
<p>We will evaluate this on image pages and on text pages.</p>
<div id="e7009f9804d1bdb4" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T15:03:40.916505Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T15:02:46.751563Z&quot;}}" data-execution_count="64">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> glob</span>
<span id="cb11-2"></span>
<span id="cb11-3">total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb11-4">incorrect <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb11-5">incorrect_files <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb11-6"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> glob.glob(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/image_page/*.JPG"</span>):</span>
<span id="cb11-7">    total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb11-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> is_text_page(model, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>):</span>
<span id="cb11-9">        incorrect <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb11-10">        incorrect_files.append(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>)</span>
<span id="cb11-11"></span>
<span id="cb11-12">incorrect</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="64">
<pre><code>1</code></pre>
</div>
</div>
<div id="ef0a62b43638367b" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T15:03:48.703823Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T15:03:48.509527Z&quot;}}" data-execution_count="65">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1">count_text_boxes(model, incorrect_files[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="65">
<pre><code>5</code></pre>
</div>
</div>
<div id="e13bf72f28dc1d3f" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T15:04:16.745542Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T15:04:16.735960Z&quot;}}" data-execution_count="67">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>incorrect<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>total</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="67">
<pre><code>0.9969604863221885</code></pre>
</div>
</div>
<p>99.6% is far higher than any score, I obtained during training. On the other hand 5 boxes is clearly an outlier which needs to be accepted with this simple approach.</p>
<p>Let’s check the text pages</p>
<div id="39dc0b5d9205dfe2" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T15:06:44.823463Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T15:05:49.020732Z&quot;}}" data-execution_count="68">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> glob</span>
<span id="cb17-2"></span>
<span id="cb17-3">total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb17-4">incorrect <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb17-5">incorrect_files <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb17-6"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> glob.glob(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/text_page/*.JPG"</span>):</span>
<span id="cb17-7">    total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb17-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> is_text_page(model, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>):</span>
<span id="cb17-9">        incorrect <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb17-10">        incorrect_files.append(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>)</span></code></pre></div></div>
</div>
<div id="e39f98e3c0e171d8" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T12:55:19.334303Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T12:55:19.329300Z&quot;}}" data-execution_count="46">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1">incorrect</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="46">
<pre><code>0</code></pre>
</div>
</div>
<p>We have 100% correct identification.</p>
</section>
<section id="performance-on-cpu" class="level3" data-number="3.2">
<h3 data-number="3.2" class="anchored" data-anchor-id="performance-on-cpu"><span class="header-section-number">3.2</span> Performance on CPU</h3>
<p>One place where the OCR based model was a bottleneck was automated testing. The slow performance dramatically slowed down the tests.</p>
<p>In the actual usage, the slow performance was is not that important as we proceed with api calls later on, which are slow too.</p>
<div id="a4c86b93686785b5" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T18:26:34.415538Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T18:26:34.306229Z&quot;}}" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1">model2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> YOLOv10(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/models/doclayout_yolo.pt"</span>)</span>
<span id="cb20-2">model2.to(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cpu"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</div>
<div id="d981f3d7abee8f60" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T18:26:46.803870Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T18:26:45.774278Z&quot;}}" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>time</span>
<span id="cb21-2">is_text_page(model2, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/text_page/IMG_0751.JPG"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>CPU times: user 5.06 s, sys: 368 ms, total: 5.43 s
Wall time: 1.02 s</code></pre>
</div>
<div class="cell-output cell-output-display" data-execution_count="14">
<pre><code>True</code></pre>
</div>
</div>
<p>On CPU the model is slower by factor 6.</p>
</section>
</section>
<section id="foundation-models-with-some-logic-often-win" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="foundation-models-with-some-logic-often-win"><span class="header-section-number">4</span> Foundation models with some logic often win</h2>
<p>In the way we are using Doclayout-YOLO it can be called a foundation model.</p>
<p>Instead of spending time an resources on training of our own model, it can be quicker to run some post-processing on the output of a foundational model.</p>
<p>Most counterintuitive we are using a regression-classification model to perform pure classification.</p>


</section>

 ]]></description>
  <category>Computer Vision</category>
  <category>Machine Learning</category>
  <category>Python</category>
  <guid>https://www.storymelange.com/posts/projects/recipescanner/text_or_image_doclayout.html</guid>
  <pubDate>Thu, 02 Oct 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Text or Image</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/recipescanner/text_or_image_page.html</link>
  <description><![CDATA[ 




<section id="what-makes-text-page-a-page-full-of-text" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="what-makes-text-page-a-page-full-of-text"><span class="header-section-number">1</span> What makes text page a page full of text?</h2>
<p>That is the question I asked myself recently. I ’ve been working on a recipe digitization app, aka the recipe scanner app.</p>
<p>The idea is simple: take snapshots of your favourite recipes from books or magazines. Then a pipeline guides you through the digitization with as little manual effort as possible.</p>
<p>This pipeline relies on several API calls: OCR for text extraction LLM inference. OCR calls are billed per request and LLMs per token.</p>
<p>The pipeline should automatically skip those expensive stages whenever possible.</p>
<p>Here are two example pages:</p>
<div class="quarto-layout-panel" data-layout-ncol="2">
<div class="quarto-layout-row">
<div class="quarto-layout-cell" style="flex-basis: 50.0%;justify-content: flex-start;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/pictures/intro_1.jpg" class="img-fluid figure-img"></p>
<figcaption>Image Page</figcaption>
</figure>
</div>
</div>
<div class="quarto-layout-cell" style="flex-basis: 50.0%;justify-content: flex-start;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/pictures/intro_2.jpg" class="img-fluid figure-img"></p>
<figcaption>Text Page</figcaption>
</figure>
</div>
</div>
</div>
</div>
<section id="first-attempts-and-a-working-solution" class="level3" data-number="1.1">
<h3 data-number="1.1" class="anchored" data-anchor-id="first-attempts-and-a-working-solution"><span class="header-section-number">1.1</span> First attempts and a working solution</h3>
<p>I started with purely computer vision-based methods, based on structure, color simplicity, and edge density. However, on my small test dataset of six images, I did not get a 100% working solution.</p>
<p>I then reverted to a more complex solution, using a OCR. Even with a local tool like <code>Pytesseract</code>, the results are very good. If more than 50 words are detected, that’s a text page.</p>
<p>The solution works but is slow as OCR favors high resolution images.</p>
<p>In this notebook I will try to deliver a CNN-based classifier that should run quicker while still achieving high accuracy.</p>
</section>
</section>
<section id="deep-learning-to-the-rescue" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="deep-learning-to-the-rescue"><span class="header-section-number">2</span> Deep learning to the rescue</h2>
<p>I trained a first model based on existing scans I had available. Due to copyright restrictions, the dataset is not public.</p>
<p>For the future, each user could build their own dataset. The initial samples can be selected by the OCR pipeline or the user clicking. Then a classifier is trained. Once it is accurate enough, we switch the pipeline to the quicker CNN classifier.</p>
<div id="d901ac71868f57cb" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:16:45.463150Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:16:45.456180Z&quot;}}" data-execution_count="32">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastai.vision.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">all</span> <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastcore.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">all</span> <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span></span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> PIL <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Image, ImageOps</span>
<span id="cb1-4">set_seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>, reproducible<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div></div>
</details>
</div>
<section id="cleaning-the-data-with-help-of-the-first-model" class="level3" data-number="2.1">
<h3 data-number="2.1" class="anchored" data-anchor-id="cleaning-the-data-with-help-of-the-first-model"><span class="header-section-number">2.1</span> Cleaning the data with help of the first model</h3>
</section>
<section id="choice-of-model-and-setup" class="level3" data-number="2.2">
<h3 data-number="2.2" class="anchored" data-anchor-id="choice-of-model-and-setup"><span class="header-section-number">2.2</span> Choice of model and setup</h3>
<p>Before we dive into different options for modeling, we will do a quick pass through the data and see which images do not fit well. The data has two categories <code>image_page</code> or <code>text_page</code>. The dataset is balanced with 330 image pages to 355 text pages. We will therefore stick to accuracy as metric.</p>
<p>We use 20 % validation data. The images are too big for the net. Therefore, we resize to 192 px. We pad to preserve aspect ratio. Rotations are dealt with on loading.</p>
<p>For the first pass we choose <code>resnet18</code>.</p>
<div id="f034dac29a99b671" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:16:47.275063Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:16:47.268988Z&quot;}}" data-execution_count="33">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> correct_exif_orientation(fn):</span>
<span id="cb2-2">    img <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Image.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(fn)</span>
<span id="cb2-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> ImageOps.exif_transpose(img)</span>
<span id="cb2-4"></span>
<span id="cb2-5">pages <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DataBlock(</span>
<span id="cb2-6">    blocks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(ImageBlock, CategoryBlock),</span>
<span id="cb2-7">    get_items<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>get_image_files,</span>
<span id="cb2-8">    splitter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>RandomSplitter(valid_pct<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, seed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>),</span>
<span id="cb2-9">    get_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>parent_label,</span>
<span id="cb2-10">    get_x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>correct_exif_orientation,</span>
<span id="cb2-11">    item_tfms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[Resize(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">192</span>,method<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pad'</span>, pad_mode<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'zeros'</span>)]</span>
<span id="cb2-12">)</span></code></pre></div></div>
</div>
<p>Let’s load our data and inspect.</p>
<div id="bb134695a06c4557" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:17:02.297671Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:16:50.903411Z&quot;}}" data-execution_count="34">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">dls <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pages.dataloaders(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/"</span>)</span>
<span id="cb3-2">dls.show_batch()</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/text_or_image_page_files/figure-html/cell-4-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>We define a learner and fine-tune.</p>
<div id="655e98c407c88a92" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:17:02.479319Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:17:02.316292Z&quot;}}" data-execution_count="35">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">set_seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>, reproducible<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb4-2">learn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> vision_learner(dls, resnet18, metrics<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>accuracy)</span></code></pre></div></div>
</div>
<div id="e5886fa0ca749756" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:18:54.310124Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:17:03.022598Z&quot;}}" data-execution_count="36">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">learn.fine_tune(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.682892</td>
<td>0.014835</td>
<td>0.992754</td>
<td>00:27</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.063574</td>
<td>0.009595</td>
<td>0.992754</td>
<td>00:26</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.044590</td>
<td>0.019105</td>
<td>0.985507</td>
<td>00:28</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.031911</td>
<td>0.012100</td>
<td>0.985507</td>
<td>00:28</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>After three iterations we already have 100% accuracy. There is certainly something wrong with our training approach.</p>
</section>
<section id="avoiding-overfitting-and-data-leakage" class="level3" data-number="2.3">
<h3 data-number="2.3" class="anchored" data-anchor-id="avoiding-overfitting-and-data-leakage"><span class="header-section-number">2.3</span> Avoiding overfitting and data leakage</h3>
<p>I use random splitter, which means that there are no unknown formats in the validation set. The algorithm will just have memorized the formats of the books in the training data. In addition, it overfitted during the first run.</p>
<p>We will reserve one format for the validation set. Starting from image<code>IMG_0552</code> only images of this new format exist. We will use this information for the splitter.</p>
<div id="da1ffe020afc7112" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:18:54.471921Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:18:54.458148Z&quot;}}" data-execution_count="37">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> GroupShuffleSplit</span>
<span id="cb6-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb6-3"></span>
<span id="cb6-4">items <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_image_files(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/"</span>)</span>
<span id="cb6-5"></span>
<span id="cb6-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_source(fn):</span>
<span id="cb6-7">    num <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(fn.stem.split(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"_"</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb6-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> num <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">552</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"B"</span></span>
<span id="cb6-9"></span>
<span id="cb6-10">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fn"</span>: items})</span>
<span id="cb6-11">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"source"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fn"</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>(get_source)</span>
<span id="cb6-12"></span>
<span id="cb6-13">gss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GroupShuffleSplit(test_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb6-14">train_idx, valid_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span>(gss.split(df, groups<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"source"</span>]))</span>
<span id="cb6-15"></span>
<span id="cb6-16">format_splitter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> IndexSplitter(valid_idx)</span></code></pre></div></div>
</div>
<div id="bbf3cc210613838b" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:18:54.852891Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:18:54.506609Z&quot;}}" data-execution_count="38">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">pages <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DataBlock(</span>
<span id="cb7-2">    blocks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(ImageBlock, CategoryBlock),</span>
<span id="cb7-3">    get_items<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>get_image_files,</span>
<span id="cb7-4">    splitter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>format_splitter,</span>
<span id="cb7-5">    get_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>parent_label,</span>
<span id="cb7-6">    get_x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>correct_exif_orientation,</span>
<span id="cb7-7">    item_tfms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[Resize(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">192</span>, method<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pad'</span>, pad_mode<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'zeros'</span>)]</span>
<span id="cb7-8"></span>
<span id="cb7-9">)</span>
<span id="cb7-10">dls <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pages.dataloaders(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/"</span>)</span></code></pre></div></div>
</div>
<p>And run training again</p>
<div id="c45222e7fd83ca98" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:20:50.893566Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:18:54.858799Z&quot;}}" data-execution_count="39">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">set_seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>, reproducible<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb8-2">learn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> vision_learner(dls, resnet18, metrics<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>accuracy)</span>
<span id="cb8-3">learn.fine_tune(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.643476</td>
<td>0.222453</td>
<td>0.946341</td>
<td>00:28</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.021866</td>
<td>0.284040</td>
<td>0.946341</td>
<td>00:29</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.012767</td>
<td>0.209461</td>
<td>0.946341</td>
<td>00:28</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.008253</td>
<td>0.213438</td>
<td>0.941463</td>
<td>00:29</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Let’s look at the poorest performers</p>
<div id="b5cbe05eb3c611af" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:21:01.900320Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:20:51.029864Z&quot;}}" data-execution_count="40">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">interp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ClassificationInterpretation.from_learner(learn)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
</div>
<div id="ab33443781498c15" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:21:04.323621Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:21:01.997593Z&quot;}}" data-execution_count="41">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">interp.plot_top_losses(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/text_or_image_page_files/figure-html/cell-11-output-3.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>As expected, most of the top losses come from the new category in the validation set: text with big picture. Let’s try cropping instead of padding.</p>
<div id="9f130eda48e481af" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:21:04.780929Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:21:04.436231Z&quot;}}" data-execution_count="42">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">pages_crop <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DataBlock(</span>
<span id="cb11-2">    blocks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(ImageBlock, CategoryBlock),</span>
<span id="cb11-3">    get_items<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>get_image_files,</span>
<span id="cb11-4">    splitter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>format_splitter,</span>
<span id="cb11-5">    get_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>parent_label,</span>
<span id="cb11-6">    get_x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>correct_exif_orientation,</span>
<span id="cb11-7">    item_tfms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>RandomResizedCrop(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">192</span>, min_scale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>))</span>
<span id="cb11-8"></span>
<span id="cb11-9">dls_crop <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pages.dataloaders(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/"</span>)</span></code></pre></div></div>
</div>
<div id="25b688e5b912e087" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:23:05.569527Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:21:04.787618Z&quot;}}" data-execution_count="43">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1">set_seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>, reproducible<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb12-2">learn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> vision_learner(dls_crop, resnet18, metrics<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>accuracy)</span>
<span id="cb12-3">learn.fine_tune(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.572427</td>
<td>0.259774</td>
<td>0.936585</td>
<td>00:28</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.038109</td>
<td>0.242050</td>
<td>0.941463</td>
<td>00:30</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.037208</td>
<td>0.183234</td>
<td>0.956098</td>
<td>00:31</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.025155</td>
<td>0.147071</td>
<td>0.956098</td>
<td>00:30</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Interestingly the results are slightly better. But during testing I saw the inverse when using other seeds. To remain consistent we switch to cropping.</p>
</section>
</section>
<section id="improving-even-further" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="improving-even-further"><span class="header-section-number">3</span> Improving even further</h2>
<p>Now with the basics settled, let’s try to improve further our 95.6% accuracy.</p>
<section id="learning-rate-tuning" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="learning-rate-tuning"><span class="header-section-number">3.1</span> Learning rate tuning</h3>
<p>We start by tuning the the learning rate. In addition to using the learning rate finder, we increase the duration where we only train the head, as the dataset is small.</p>
<div id="917dc2e8cd9d9849" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:48:12.325535Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:48:12.111477Z&quot;}}" data-execution_count="53">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1">set_seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>, reproducible<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb13-2">learn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> vision_learner(dls, resnet18, metrics<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>accuracy)</span></code></pre></div></div>
</div>
<div id="7ebeda72aa980f54" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T08:56:16.090225Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:51:48.284744Z&quot;}}" data-execution_count="56">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1">learn.lr_find(suggest_funcs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(minimum, steep, valley))</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
<div class="cell-output cell-output-display" data-execution_count="56">
<pre><code>SuggestedLRs(minimum=0.05248074531555176, steep=0.00019054606673307717, valley=0.0006918309954926372)</code></pre>
</div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/text_or_image_page_files/figure-html/cell-15-output-4.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="f67e72c33cb80ebc" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T09:11:32.346687Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T08:57:16.581191Z&quot;}}" data-execution_count="57">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1">learn.fine_tune(</span>
<span id="cb16-2">    <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>,</span>
<span id="cb16-3">    base_lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">6.9e-4</span>,</span>
<span id="cb16-4">    freeze_epochs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># train the head</span></span>
<span id="cb16-5">)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>1.063496</td>
<td>0.927946</td>
<td>0.512195</td>
<td>00:32</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.779015</td>
<td>0.373030</td>
<td>0.882927</td>
<td>00:33</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.518703</td>
<td>0.255721</td>
<td>0.921951</td>
<td>00:32</td>
</tr>
<tr class="even">
<td>3</td>
<td>0.373917</td>
<td>0.246510</td>
<td>0.941463</td>
<td>00:34</td>
</tr>
<tr class="odd">
<td>4</td>
<td>0.279082</td>
<td>0.242445</td>
<td>0.941463</td>
<td>00:32</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.018540</td>
<td>0.215797</td>
<td>0.941463</td>
<td>00:35</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.016864</td>
<td>0.187548</td>
<td>0.951219</td>
<td>00:37</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.012505</td>
<td>0.173968</td>
<td>0.956098</td>
<td>00:35</td>
</tr>
<tr class="even">
<td>3</td>
<td>0.009071</td>
<td>0.161985</td>
<td>0.960976</td>
<td>00:35</td>
</tr>
<tr class="odd">
<td>4</td>
<td>0.006918</td>
<td>0.166117</td>
<td>0.956098</td>
<td>00:32</td>
</tr>
<tr class="even">
<td>5</td>
<td>0.005747</td>
<td>0.176520</td>
<td>0.956098</td>
<td>00:33</td>
</tr>
<tr class="odd">
<td>6</td>
<td>0.004610</td>
<td>0.178823</td>
<td>0.956098</td>
<td>00:35</td>
</tr>
<tr class="even">
<td>7</td>
<td>0.004979</td>
<td>0.168676</td>
<td>0.960976</td>
<td>00:36</td>
</tr>
<tr class="odd">
<td>8</td>
<td>0.004130</td>
<td>0.163851</td>
<td>0.960976</td>
<td>00:36</td>
</tr>
<tr class="even">
<td>9</td>
<td>0.003458</td>
<td>0.168914</td>
<td>0.965854</td>
<td>00:35</td>
</tr>
<tr class="odd">
<td>10</td>
<td>0.002940</td>
<td>0.190041</td>
<td>0.956098</td>
<td>00:37</td>
</tr>
<tr class="even">
<td>11</td>
<td>0.002547</td>
<td>0.178129</td>
<td>0.956098</td>
<td>00:37</td>
</tr>
<tr class="odd">
<td>12</td>
<td>0.002212</td>
<td>0.184677</td>
<td>0.956098</td>
<td>00:36</td>
</tr>
<tr class="even">
<td>13</td>
<td>0.002100</td>
<td>0.182207</td>
<td>0.960976</td>
<td>00:34</td>
</tr>
<tr class="odd">
<td>14</td>
<td>0.001811</td>
<td>0.182882</td>
<td>0.956098</td>
<td>00:32</td>
</tr>
<tr class="even">
<td>15</td>
<td>0.001629</td>
<td>0.184585</td>
<td>0.956098</td>
<td>00:30</td>
</tr>
<tr class="odd">
<td>16</td>
<td>0.001452</td>
<td>0.182009</td>
<td>0.956098</td>
<td>00:31</td>
</tr>
<tr class="even">
<td>17</td>
<td>0.001260</td>
<td>0.187534</td>
<td>0.956098</td>
<td>00:31</td>
</tr>
<tr class="odd">
<td>18</td>
<td>0.001156</td>
<td>0.192596</td>
<td>0.956098</td>
<td>00:32</td>
</tr>
<tr class="even">
<td>19</td>
<td>0.001018</td>
<td>0.186388</td>
<td>0.956098</td>
<td>00:31</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>We managed a higher accuarcy of 96.5%, but training training diverged.</p>
</section>
<section id="increasing-input-data-size" class="level3" data-number="3.2">
<h3 data-number="3.2" class="anchored" data-anchor-id="increasing-input-data-size"><span class="header-section-number">3.2</span> Increasing input data size</h3>
<p>The text could be too blured at 192px. We increase image size to 320px and follow the same approach as before. To avoid unnecessary calls, when the training is overfitting I added the callbacks.</p>
<div id="6229d7175acbce6b" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T09:35:11.496582Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T09:35:11.248358Z&quot;}}" data-execution_count="71">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1">set_seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>, reproducible<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb17-2">pages <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DataBlock(</span>
<span id="cb17-3">    blocks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(ImageBlock, CategoryBlock),</span>
<span id="cb17-4">    get_items<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>get_image_files,</span>
<span id="cb17-5">    splitter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>format_splitter,</span>
<span id="cb17-6">    get_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>parent_label,</span>
<span id="cb17-7">    get_x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>correct_exif_orientation,</span>
<span id="cb17-8">    item_tfms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[RandomResizedCrop(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span>, min_scale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>)]</span>
<span id="cb17-9"></span>
<span id="cb17-10">)</span>
<span id="cb17-11">dls <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pages.dataloaders(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/"</span>)</span></code></pre></div></div>
</div>
<div id="401c2bcae44b93ad" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T09:35:12.299537Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T09:35:12.143742Z&quot;}}" data-execution_count="72">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1">learn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> vision_learner(dls, resnet18, metrics<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>accuracy)</span></code></pre></div></div>
</div>
<div id="6bb0f5546b26612d" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T09:23:36.320938Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T09:20:34.039241Z&quot;}}" data-execution_count="67">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1">learn.lr_find(suggest_funcs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(minimum, steep, valley))</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
<div class="cell-output cell-output-display" data-execution_count="67">
<pre><code>SuggestedLRs(minimum=0.05248074531555176, steep=0.0002290867705596611, valley=0.0014454397605732083)</code></pre>
</div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/text_or_image_page_files/figure-html/cell-19-output-4.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="79bd2e63258139bd" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T09:40:00.880254Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T09:35:13.965694Z&quot;}}" data-execution_count="73">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1">learn.fine_tune(</span>
<span id="cb21-2">    <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>,</span>
<span id="cb21-3">    base_lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.4e-3</span>,</span>
<span id="cb21-4">    freeze_epochs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># train the head</span></span>
<span id="cb21-5">    cbs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[</span>
<span id="cb21-6">        EarlyStoppingCallback(monitor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid_loss'</span>, patience<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>),</span>
<span id="cb21-7">        SaveModelCallback(monitor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid_loss'</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># saves best model</span></span>
<span id="cb21-8">    ]</span>
<span id="cb21-9">)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>1.024766</td>
<td>0.579390</td>
<td>0.775610</td>
<td>00:24</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.583699</td>
<td>0.165269</td>
<td>0.946341</td>
<td>00:24</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.370840</td>
<td>0.201217</td>
<td>0.956098</td>
<td>00:24</td>
</tr>
<tr class="even">
<td>3</td>
<td>0.263847</td>
<td>0.208855</td>
<td>0.956098</td>
<td>00:23</td>
</tr>
<tr class="odd">
<td>4</td>
<td>0.198083</td>
<td>0.187529</td>
<td>0.960976</td>
<td>00:23</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Better model found at epoch 0 with valid_loss value: 0.5793901085853577.
Better model found at epoch 1 with valid_loss value: 0.16526909172534943.
No improvement since epoch 1: early stopping</code></pre>
</div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.037425</td>
<td>0.131343</td>
<td>0.960976</td>
<td>00:23</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.034193</td>
<td>0.105369</td>
<td>0.965854</td>
<td>00:23</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.023509</td>
<td>0.091661</td>
<td>0.975610</td>
<td>00:24</td>
</tr>
<tr class="even">
<td>3</td>
<td>0.016545</td>
<td>0.084221</td>
<td>0.975610</td>
<td>00:24</td>
</tr>
<tr class="odd">
<td>4</td>
<td>0.012769</td>
<td>0.091403</td>
<td>0.975610</td>
<td>00:23</td>
</tr>
<tr class="even">
<td>5</td>
<td>0.010076</td>
<td>0.113227</td>
<td>0.970732</td>
<td>00:23</td>
</tr>
<tr class="odd">
<td>6</td>
<td>0.008031</td>
<td>0.133027</td>
<td>0.960976</td>
<td>00:23</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Better model found at epoch 0 with valid_loss value: 0.13134345412254333.
Better model found at epoch 1 with valid_loss value: 0.10536907613277435.
Better model found at epoch 2 with valid_loss value: 0.09166132658720016.
Better model found at epoch 3 with valid_loss value: 0.08422137051820755.
No improvement since epoch 3: early stopping</code></pre>
</div>
</div>
<p>We made it to 97.5%.</p>
<section id="data-augmentation" class="level4" data-number="3.2.1">
<h4 data-number="3.2.1" class="anchored" data-anchor-id="data-augmentation"><span class="header-section-number">3.2.1</span> Data augmentation</h4>
<p>As a last step we try introducing data augmentation. Same procedure as before.</p>
<div id="fe7aec5f8ea1cc1f" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T09:46:18.057437Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T09:46:17.698114Z&quot;}}" data-execution_count="74">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1">set_seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>, reproducible<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb24-2">pages <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DataBlock(</span>
<span id="cb24-3">    blocks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(ImageBlock, CategoryBlock),</span>
<span id="cb24-4">    get_items<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>get_image_files,</span>
<span id="cb24-5">    splitter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>format_splitter,</span>
<span id="cb24-6">    get_x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>correct_exif_orientation,</span>
<span id="cb24-7">    get_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>parent_label,</span>
<span id="cb24-8">    item_tfms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[RandomResizedCrop(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span>, min_scale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>)],</span>
<span id="cb24-9">batch_tfms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>aug_transforms(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),)</span>
<span id="cb24-10"></span>
<span id="cb24-11">dls <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pages.dataloaders(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/"</span>)</span></code></pre></div></div>
</div>
<div id="605d5469d1247170" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T09:49:08.941939Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T09:46:39.976943Z&quot;}}" data-execution_count="75">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1">learn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> vision_learner(dls, resnet18, metrics<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>accuracy)</span>
<span id="cb25-2">learn.lr_find(suggest_funcs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(minimum, steep, valley))</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
<div class="cell-output cell-output-display" data-execution_count="75">
<pre><code>SuggestedLRs(minimum=0.03630780577659607, steep=0.00019054606673307717, valley=0.0010000000474974513)</code></pre>
</div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/text_or_image_page_files/figure-html/cell-22-output-4.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="689cbabbf16e28da" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T09:55:56.891062Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T09:50:35.522297Z&quot;}}" data-execution_count="76">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1">learn.fine_tune(</span>
<span id="cb27-2">    <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>,</span>
<span id="cb27-3">    base_lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span>,</span>
<span id="cb27-4">    freeze_epochs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># train the head</span></span>
<span id="cb27-5">    cbs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[</span>
<span id="cb27-6">        EarlyStoppingCallback(monitor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid_loss'</span>, patience<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>),</span>
<span id="cb27-7">        SaveModelCallback(monitor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid_loss'</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># saves best model</span></span>
<span id="cb27-8">    ]</span>
<span id="cb27-9">)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>1.149485</td>
<td>0.779582</td>
<td>0.668293</td>
<td>00:23</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.707324</td>
<td>0.202957</td>
<td>0.921951</td>
<td>00:22</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.463376</td>
<td>0.184458</td>
<td>0.960976</td>
<td>00:21</td>
</tr>
<tr class="even">
<td>3</td>
<td>0.335166</td>
<td>0.195367</td>
<td>0.960976</td>
<td>00:21</td>
</tr>
<tr class="odd">
<td>4</td>
<td>0.252198</td>
<td>0.193939</td>
<td>0.960976</td>
<td>00:21</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Better model found at epoch 0 with valid_loss value: 0.7795820832252502.
Better model found at epoch 1 with valid_loss value: 0.20295678079128265.
Better model found at epoch 2 with valid_loss value: 0.18445810675621033.</code></pre>
</div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.042519</td>
<td>0.198141</td>
<td>0.951219</td>
<td>00:21</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.032583</td>
<td>0.187754</td>
<td>0.956098</td>
<td>00:22</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.022516</td>
<td>0.144986</td>
<td>0.960976</td>
<td>00:23</td>
</tr>
<tr class="even">
<td>3</td>
<td>0.017273</td>
<td>0.113910</td>
<td>0.960976</td>
<td>00:22</td>
</tr>
<tr class="odd">
<td>4</td>
<td>0.013913</td>
<td>0.097062</td>
<td>0.970732</td>
<td>00:22</td>
</tr>
<tr class="even">
<td>5</td>
<td>0.011357</td>
<td>0.096084</td>
<td>0.975610</td>
<td>00:23</td>
</tr>
<tr class="odd">
<td>6</td>
<td>0.009134</td>
<td>0.102647</td>
<td>0.975610</td>
<td>00:23</td>
</tr>
<tr class="even">
<td>7</td>
<td>0.007552</td>
<td>0.121601</td>
<td>0.965854</td>
<td>00:23</td>
</tr>
<tr class="odd">
<td>8</td>
<td>0.007619</td>
<td>0.155179</td>
<td>0.960976</td>
<td>00:26</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Better model found at epoch 0 with valid_loss value: 0.19814081490039825.
Better model found at epoch 1 with valid_loss value: 0.18775445222854614.
Better model found at epoch 2 with valid_loss value: 0.14498622715473175.
Better model found at epoch 3 with valid_loss value: 0.11391040682792664.
Better model found at epoch 4 with valid_loss value: 0.0970616415143013.
Better model found at epoch 5 with valid_loss value: 0.096084363758564.
No improvement since epoch 5: early stopping</code></pre>
</div>
</div>
<p>The augmentations did not achieve a lower validation loss and training started to diverge earlier.</p>
<p>At this point we could certainly try to do more things. Work on weight decay and dropout. That is certainly an optimization, which should be done once the model is in production.</p>
</section>
</section>
<section id="bigger-model" class="level3" data-number="3.3">
<h3 data-number="3.3" class="anchored" data-anchor-id="bigger-model"><span class="header-section-number">3.3</span> Bigger Model</h3>
<p>One last thing, we will do. Try a bigger model.</p>
<div id="8685270d60525aa3" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T11:45:02.465338Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T11:45:02.242444Z&quot;}}" data-execution_count="138">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1">set_seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>, reproducible<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb30-2">pages <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DataBlock(</span>
<span id="cb30-3">    blocks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(ImageBlock, CategoryBlock),</span>
<span id="cb30-4">    get_items<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>get_image_files,</span>
<span id="cb30-5">    splitter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>format_splitter,</span>
<span id="cb30-6">    get_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>parent_label,</span>
<span id="cb30-7">    get_x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>correct_exif_orientation,</span>
<span id="cb30-8">    item_tfms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[RandomResizedCrop(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span>, min_scale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>)]</span>
<span id="cb30-9"></span>
<span id="cb30-10">)</span>
<span id="cb30-11">dls <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pages.dataloaders(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/"</span>)</span></code></pre></div></div>
</div>
<div id="e75e40e4a7e6c2d3" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T10:15:59.956250Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T10:15:59.483258Z&quot;}}" data-execution_count="89">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb31-1">learn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> vision_learner(dls, resnet34, metrics<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>accuracy)</span></code></pre></div></div>
</div>
<div id="f6173825b82ef1f8" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T10:04:29.449930Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T10:01:49.964874Z&quot;}}" data-execution_count="79">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1">learn.lr_find(suggest_funcs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(minimum, steep, valley))</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
<div class="cell-output cell-output-display" data-execution_count="79">
<pre><code>SuggestedLRs(minimum=0.04365158379077912, steep=6.309573450380412e-07, valley=0.0012022644514217973)</code></pre>
</div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/text_or_image_page_files/figure-html/cell-26-output-4.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="b0fcc78eab945312" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T10:19:42.801122Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T10:16:01.779831Z&quot;}}" data-execution_count="90">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb34-1">learn.fine_tune(</span>
<span id="cb34-2">    <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>,</span>
<span id="cb34-3">    base_lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span>,</span>
<span id="cb34-4">    freeze_epochs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># train the head</span></span>
<span id="cb34-5">    cbs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[</span>
<span id="cb34-6">        EarlyStoppingCallback(monitor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid_loss'</span>, patience<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>),</span>
<span id="cb34-7">        SaveModelCallback(monitor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid_loss'</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># saves best model</span></span>
<span id="cb34-8">    ]</span>
<span id="cb34-9">)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>1.027827</td>
<td>0.761079</td>
<td>0.585366</td>
<td>00:24</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.634203</td>
<td>0.074252</td>
<td>0.980488</td>
<td>00:23</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.415216</td>
<td>0.089031</td>
<td>0.985366</td>
<td>00:24</td>
</tr>
<tr class="even">
<td>3</td>
<td>0.295387</td>
<td>0.111100</td>
<td>0.980488</td>
<td>00:23</td>
</tr>
<tr class="odd">
<td>4</td>
<td>0.225855</td>
<td>0.114145</td>
<td>0.990244</td>
<td>00:24</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Better model found at epoch 0 with valid_loss value: 0.7610787749290466.
Better model found at epoch 1 with valid_loss value: 0.07425229251384735.
No improvement since epoch 1: early stopping</code></pre>
</div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.042249</td>
<td>0.067354</td>
<td>0.990244</td>
<td>00:23</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.030849</td>
<td>0.069564</td>
<td>0.990244</td>
<td>00:24</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.026555</td>
<td>0.074522</td>
<td>0.990244</td>
<td>00:26</td>
</tr>
<tr class="even">
<td>3</td>
<td>0.019717</td>
<td>0.079238</td>
<td>0.990244</td>
<td>00:26</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Better model found at epoch 0 with valid_loss value: 0.06735362857580185.
No improvement since epoch 0: early stopping</code></pre>
</div>
</div>
<p>The bigger model lead to 99% accuracy. This certainly is promising. On the other hand, we only have a few different formats in the training set. To guard against out of domain errors we will stick to the resnet18.</p>
<div id="c62c5276f4aa69d1" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T10:28:06.272329Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T10:20:34.833959Z&quot;}}" data-execution_count="91">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1">set_seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>, reproducible<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb37-2">pages <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DataBlock(</span>
<span id="cb37-3">    blocks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(ImageBlock, CategoryBlock),</span>
<span id="cb37-4">    get_items<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>get_image_files,</span>
<span id="cb37-5">    splitter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>format_splitter,</span>
<span id="cb37-6">    get_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>parent_label,</span>
<span id="cb37-7">    get_x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>correct_exif_orientation,</span>
<span id="cb37-8">    item_tfms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[RandomResizedCrop(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span>, min_scale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>)]</span>
<span id="cb37-9"></span>
<span id="cb37-10">)</span>
<span id="cb37-11">dls <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pages.dataloaders(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/raw/"</span>)</span>
<span id="cb37-12">learn.lr_find(suggest_funcs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(minimum, steep, valley))</span>
<span id="cb37-13">learn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> vision_learner(dls, resnet18, metrics<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>accuracy)</span>
<span id="cb37-14">learn.fine_tune(</span>
<span id="cb37-15">    <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>,</span>
<span id="cb37-16">    base_lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.4e-3</span>,</span>
<span id="cb37-17">    freeze_epochs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># train the head</span></span>
<span id="cb37-18">    cbs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[</span>
<span id="cb37-19">        EarlyStoppingCallback(monitor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid_loss'</span>, patience<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>),</span>
<span id="cb37-20">        SaveModelCallback(monitor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid_loss'</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># saves best model</span></span>
<span id="cb37-21">    ]</span>
<span id="cb37-22">)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>1.059075</td>
<td>0.661225</td>
<td>0.721951</td>
<td>00:24</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.592713</td>
<td>0.315692</td>
<td>0.912195</td>
<td>00:23</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.383400</td>
<td>0.343516</td>
<td>0.926829</td>
<td>00:24</td>
</tr>
<tr class="even">
<td>3</td>
<td>0.274423</td>
<td>0.343230</td>
<td>0.941463</td>
<td>00:23</td>
</tr>
<tr class="odd">
<td>4</td>
<td>0.203259</td>
<td>0.317037</td>
<td>0.941463</td>
<td>00:22</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Better model found at epoch 0 with valid_loss value: 0.6612254977226257.
Better model found at epoch 1 with valid_loss value: 0.31569164991378784.
No improvement since epoch 1: early stopping</code></pre>
</div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">epoch</th>
<th data-quarto-table-cell-role="th">train_loss</th>
<th data-quarto-table-cell-role="th">valid_loss</th>
<th data-quarto-table-cell-role="th">accuracy</th>
<th data-quarto-table-cell-role="th">time</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0.054644</td>
<td>0.231042</td>
<td>0.926829</td>
<td>00:23</td>
</tr>
<tr class="even">
<td>1</td>
<td>0.039082</td>
<td>0.173815</td>
<td>0.941463</td>
<td>00:23</td>
</tr>
<tr class="odd">
<td>2</td>
<td>0.026822</td>
<td>0.126490</td>
<td>0.956098</td>
<td>00:24</td>
</tr>
<tr class="even">
<td>3</td>
<td>0.018999</td>
<td>0.112197</td>
<td>0.970732</td>
<td>00:24</td>
</tr>
<tr class="odd">
<td>4</td>
<td>0.014812</td>
<td>0.110572</td>
<td>0.970732</td>
<td>00:23</td>
</tr>
<tr class="even">
<td>5</td>
<td>0.012533</td>
<td>0.140026</td>
<td>0.960976</td>
<td>00:25</td>
</tr>
<tr class="odd">
<td>6</td>
<td>0.009940</td>
<td>0.154067</td>
<td>0.956098</td>
<td>00:24</td>
</tr>
<tr class="even">
<td>7</td>
<td>0.008640</td>
<td>0.139433</td>
<td>0.965854</td>
<td>00:26</td>
</tr>
</tbody>
</table>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Better model found at epoch 0 with valid_loss value: 0.2310423105955124.
Better model found at epoch 1 with valid_loss value: 0.17381496727466583.
Better model found at epoch 2 with valid_loss value: 0.12649033963680267.
Better model found at epoch 3 with valid_loss value: 0.11219745874404907.
Better model found at epoch 4 with valid_loss value: 0.11057160794734955.
No improvement since epoch 4: early stopping</code></pre>
</div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/text_or_image_page_files/figure-html/cell-28-output-9.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="995df5553b9105b8" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T10:53:55.806251Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T10:53:43.097804Z&quot;}}" data-execution_count="96">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb40" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb40-1">interp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>  ClassificationInterpretation.from_learner(learn)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
</div>
<div id="ffcc0b057854f023" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T10:53:59.198395Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T10:53:56.789728Z&quot;}}" data-execution_count="97">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb41" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb41-1">interp.plot_top_losses(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/text_or_image_page_files/figure-html/cell-30-output-3.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="inference" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="inference"><span class="header-section-number">4</span> Inference</h2>
<p>Our goal is a pure pytorch inference. To avoid any preproccessing mistakes, we will start with fastai pipeline.</p>
<section id="fastai-first" class="level3" data-number="4.1">
<h3 data-number="4.1" class="anchored" data-anchor-id="fastai-first"><span class="header-section-number">4.1</span> Fastai first</h3>
<div id="d0a8706ae551b7a1" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T10:52:42.021692Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T10:52:41.927747Z&quot;}}" data-execution_count="92">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb42" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb42-1">learn.export(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/models/page_classifier.pkl"</span>)</span></code></pre></div></div>
</div>
<div id="e16557c6af26c597" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T11:49:08.160305Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T11:49:08.135342Z&quot;}}" data-execution_count="139">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb43-1">learn_inf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> load_learner(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/models/page_classifier.pkl"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</div>
<div id="6f62b8273edce446" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T11:57:17.075254Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T11:57:16.920260Z&quot;}}" data-execution_count="141">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb44" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb44-1">pred_class, pred_idx, probs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> learn_inf.predict(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pictures/inf_1.jpg"</span>)</span>
<span id="cb44-2"></span>
<span id="cb44-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Prediction: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>pred_class<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb44-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Probabilities: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>probs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
<div class="cell-output cell-output-stdout">
<pre><code>Prediction: image_page
Probabilities: tensor([0.7906, 0.2094])</code></pre>
</div>
</div>
<div id="b932b52f25d295cb" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T11:57:18.131994Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T11:57:17.980162Z&quot;}}" data-execution_count="142">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb46" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb46-1">pred_class, pred_idx, probs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> learn.predict(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pictures/inf_2.jpg"</span>)</span>
<span id="cb46-2"></span>
<span id="cb46-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Prediction: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>pred_class<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb46-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Probabilities: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>probs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display">

<style>
    /* Turns off some styling */
    progress {
        /* gets rid of default border in Firefox and Opera. */
        border: none;
        /* Needs to be in here for Safari polyfill so background images work as expected. */
        background-size: auto;
    }
    progress:not([value]), progress:not([value])::-webkit-progress-bar {
        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);
    }
    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
        background: #F44336;
    }
</style>
</div>
<div class="cell-output cell-output-display">

</div>
<div class="cell-output cell-output-stdout">
<pre><code>Prediction: text_page
Probabilities: tensor([0.0087, 0.9913])</code></pre>
</div>
</div>
<p>The result for the second image is correct, whereas for the first it is wrong. Again from the text with big image type.</p>
<p>When we look at the pictures, we see that the text page picture has an image with text. It could be that the CNN learned these patterns and interpreted the image as text.</p>
<div class="quarto-layout-panel" data-layout-ncol="2">
<div class="quarto-layout-row">
<div class="quarto-layout-cell" style="flex-basis: 50.0%;justify-content: flex-start;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/pictures/inf_1.jpg" class="img-fluid figure-img"></p>
<figcaption>Infered as Image Page</figcaption>
</figure>
</div>
</div>
<div class="quarto-layout-cell" style="flex-basis: 50.0%;justify-content: flex-start;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/pictures/inf_2.jpg" class="img-fluid figure-img"></p>
<figcaption>Infered as Text Page</figcaption>
</figure>
</div>
</div>
</div>
</div>
</section>
<section id="pytorch" class="level3" data-number="4.2">
<h3 data-number="4.2" class="anchored" data-anchor-id="pytorch"><span class="header-section-number">4.2</span> Pytorch</h3>
<p>To use model in pytorch only we need to convert it to torchscript.</p>
<div id="f4adea342054d60a" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T11:49:33.385953Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T11:49:32.820443Z&quot;}}" data-execution_count="140">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb48" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb48-1">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> learn_inf.model</span>
<span id="cb48-2">model.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()</span>
<span id="cb48-3"></span>
<span id="cb48-4"></span>
<span id="cb48-5">example_input <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.randn(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># batch, channels, H, W</span></span>
<span id="cb48-6">traced <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.jit.trace(model, example_input)</span>
<span id="cb48-7">traced.save(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/models/page_classifier.pt"</span>)</span></code></pre></div></div>
</div>
<p>We will later use the following code in the app</p>
<div id="a48cd46772ff74e9" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T11:17:47.887845Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T11:17:47.835094Z&quot;}}" data-execution_count="130">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb49" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb49-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch</span>
<span id="cb49-2">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.jit.load(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/models/page_classifier.pt"</span>)</span>
<span id="cb49-3">model.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</div>
<div id="4b6bd779ba5c9f4b" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T11:16:11.079776Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T11:16:11.076993Z&quot;}}" data-execution_count="122">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb50" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb50-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> torchvision <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> transforms</span>
<span id="cb50-2">tfm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> transforms.Compose([</span>
<span id="cb50-3">    transforms.Resize(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span>, interpolation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>transforms.InterpolationMode.BILINEAR),</span>
<span id="cb50-4">    transforms.CenterCrop(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span>),</span>
<span id="cb50-5">    transforms.ToTensor(),</span>
<span id="cb50-6">    transforms.Normalize(mean<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.485</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.456</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.406</span>],</span>
<span id="cb50-7">                         std<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.229</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.224</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.225</span>])</span>
<span id="cb50-8">])</span>
<span id="cb50-9"></span></code></pre></div></div>
</div>
<div id="58e8f0a5b175c84c" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T11:16:11.586797Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T11:16:11.584039Z&quot;}}" data-execution_count="123">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb51" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb51-1">labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"image_page"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text_page"</span>]</span>
<span id="cb51-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict_image(path):</span>
<span id="cb51-3">    img <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Image.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(path).convert(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"RGB"</span>)</span>
<span id="cb51-4">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tfm(img).unsqueeze(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># add batch dim</span></span>
<span id="cb51-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> torch.no_grad():</span>
<span id="cb51-6">        out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(x)</span>
<span id="cb51-7">        probs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.softmax(out, dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb51-8">        pred_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> probs.argmax().item()</span>
<span id="cb51-9">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> labels[pred_idx], probs.tolist()</span></code></pre></div></div>
</div>
<div id="e679e7fc1ff92fa4" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T11:16:12.270365Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T11:16:12.089953Z&quot;}}" data-execution_count="124">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb52" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb52-1">predict_image(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pictures/inf_1.jpg"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="124">
<pre><code>('image_page', [0.8300915360450745, 0.16990840435028076])</code></pre>
</div>
</div>
<div id="67e681551cd159f9" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-10-01T11:16:15.667314Z&quot;,&quot;start_time&quot;:&quot;2025-10-01T11:16:15.501142Z&quot;}}" data-execution_count="126">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb54" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb54-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>time</span>
<span id="cb54-2">predict_image(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pictures/inf_2.jpg"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>CPU times: user 315 ms, sys: 22.1 ms, total: 337 ms
Wall time: 163 ms</code></pre>
</div>
<div class="cell-output cell-output-display" data-execution_count="126">
<pre><code>('text_page', [0.030374446883797646, 0.9696255922317505])</code></pre>
</div>
</div>
<p>The results are very similar 83% vs 80% for the wrong classification. We will accept the small deviations from fast.ai for now.</p>
</section>
</section>
<section id="outlook" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="outlook"><span class="header-section-number">5</span> Outlook</h2>
<p>We have 160ms runtime for one image at 97.5% accuracy to detect if it is an image. This score could increase if we increase the dataset size and add more layouts.</p>
<p>A completely different approach could also work. In the next notebook, I will be working with YOLO-doclayout. a fast detector that detects the occurrence of text or image blocks on a page. If there are no text boxes, then there is no text.</p>
<div id="b1a5487579750ec9" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb57" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"></code></pre></div></div>
</div>


</section>

 ]]></description>
  <category>Computer Vision</category>
  <category>Machine Learning</category>
  <category>Python</category>
  <guid>https://www.storymelange.com/posts/projects/recipescanner/text_or_image_page.html</guid>
  <pubDate>Mon, 29 Sep 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Beauty is in the eye of the beholder</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/recipescanner/thumbnail_optimization.html</link>
  <description><![CDATA[ 




<section id="why-we-need-thumbnails" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="why-we-need-thumbnails"><span class="header-section-number">1</span> Why we need thumbnails</h2>
<p>The recipescanner allows scanning books and creating recipes with thumbnails. These Thumbnails should look nice and provide a good first impression of the meal.</p>
<p>There are three categories of recipes:</p>
<ol type="1">
<li>The picture that belongs to the recipe is identified.</li>
<li>The recipe does not have a picture.</li>
<li>We have a picture and several recipes, but we don’t know which recipe the picture belongs to.</li>
</ol>
<p>In this notebook we will examine case 1 and case 2. Case 3 is part of the page segmentation task, which I’ll cover in another notebook.</p>
</section>
<section id="what-makes-a-good-thumbnail" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="what-makes-a-good-thumbnail"><span class="header-section-number">2</span> What makes a good thumbnail</h2>
<p>We have a picture of a recipe and want to create a good thumbnail from it. Simply resizing the image often produces thumbnails that lack detail.</p>
<p>A better, straightforward solution is to center-crop the picture to the size of the thumbnail.</p>
<p>The rationale: plates are usually centered in recipe photos.</p>
<p>But what if that’s not the case?</p>
<p>Does this method produce aesthetically pleasing thumbnails, and is there a way to improve in case of non-centered subjects?</p>
<p>The short answer: yes.</p>
<p>See the following picture</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method.jpg" class="img-fluid figure-img"></p>
<figcaption>Improvements in Thumbnail generation</figcaption>
</figure>
</div>
<p>Read on to discover how we do this.</p>
</section>
<section id="straightforward-solution-center-crop-of-pictures" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="straightforward-solution-center-crop-of-pictures"><span class="header-section-number">3</span> Straightforward solution: center crop of pictures</h2>
<div id="7f0a2aad-8010-4aa8-9331-526e6da3253a" class="cell" data-execution_count="4">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Standard library</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> os</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> tempfile</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> glob <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> glob</span>
<span id="cb1-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pathlib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Path</span>
<span id="cb1-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> os.path <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> expanduser</span>
<span id="cb1-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> urllib.request <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> urlretrieve</span>
<span id="cb1-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> warnings</span>
<span id="cb1-9"></span>
<span id="cb1-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Third-party</span></span>
<span id="cb1-11"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> cv2 <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> cv</span>
<span id="cb1-12"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-13"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-14"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> open_clip</span>
<span id="cb1-15"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-16"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> seaborn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> sns</span>
<span id="cb1-17"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch</span>
<span id="cb1-18"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch.nn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> nn</span>
<span id="cb1-19"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch.nn.functional <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> F</span>
<span id="cb1-20"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torchvision</span>
<span id="cb1-21"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> PIL <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Image, ImageOps</span>
<span id="cb1-22"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> gradio_client <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Client, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>, handle_file</span>
<span id="cb1-23"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> torchvision <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> transforms</span>
<span id="cb1-24"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> torchvision.transforms <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> InterpolationMode</span>
<span id="cb1-25"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> tqdm</span>
<span id="cb1-26"></span>
<span id="cb1-27"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Local modules</span></span>
<span id="cb1-28"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> aesthetic_predictor_v2_5 <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> convert_v2_5_from_siglip</span>
<span id="cb1-29"></span>
<span id="cb1-30"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Jupyter magic</span></span>
<span id="cb1-31"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>matplotlib inline</span>
<span id="cb1-32"></span>
<span id="cb1-33"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Suppress all warnings (optional)</span></span>
<span id="cb1-34">warnings.filterwarnings(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ignore"</span>)</span>
<span id="cb1-35"></span>
<span id="cb1-36"></span>
<span id="cb1-37">DATA_DIR <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Path(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/covers"</span>)</span>
<span id="cb1-38">THUMB_SIZE <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span></span>
<span id="cb1-39">NROW <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span></span>
<span id="cb1-40"></span>
<span id="cb1-41"></span>
<span id="cb1-42">thumb_transform <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> transforms.Compose([</span>
<span id="cb1-43">    transforms.Resize(THUMB_SIZE, interpolation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>InterpolationMode.LANCZOS),</span>
<span id="cb1-44">    transforms.CenterCrop(THUMB_SIZE),</span>
<span id="cb1-45">    transforms.ToTensor()</span>
<span id="cb1-46">])</span>
<span id="cb1-47"></span>
<span id="cb1-48">to_pil <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> transforms.ToPILImage()</span>
<span id="cb1-49">to_tensor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> transforms.ToTensor()</span>
<span id="cb1-50"></span>
<span id="cb1-51"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> show_image_grid(images, nrow<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>NROW, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)):</span>
<span id="cb1-52">    grid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torchvision.utils.make_grid(images, nrow<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nrow)</span>
<span id="cb1-53">    plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>figsize)</span>
<span id="cb1-54">    plt.imshow(grid.permute(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb1-55">    plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb1-56">    plt.show()</span></code></pre></div></div>
</details>
</div>
<p>Let’s first load our sample data and apply center-cropping.</p>
<div id="74404772-88aa-4351-a01e-3f2bef591729" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">files <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sorted</span>(glob(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(DATA_DIR <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"*.JPG"</span>)))</span>
<span id="cb2-2"></span>
<span id="cb2-3">images <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [thumb_transform(Image.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(f).convert(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"RGB"</span>)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> f <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> files]</span>
<span id="cb2-4">show_image_grid(images)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-3-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>As we can see, many picture look quite good. However, in some images the dish gets cut off. We could certainly do better.</p>
<p>For a human it’s obvious that we should center the plate in the thumbnail. For a computer that is challenging as plates are coming in different shapes, and sometimes there are no plates at all. In our specific case, the images are also upside down.</p>
<p>We’ll see later that this is still solvable. Before we get there, though, let’s first define what makes a picture <strong>look good</strong>.</p>
<p>For that, we need a metric.</p>
</section>
<section id="how-to-measure-beauty" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="how-to-measure-beauty"><span class="header-section-number">4</span> How to measure beauty</h2>
<p>Wouldn’t it be great if we could define a metric that tells us how good a picture is? How beautiful it looks?</p>
<p>In fact, there is a way to do this. We can use Aesthetic Predictor models. Let’s look at two such Models <code>LAION</code> and <code>Aesthetic Predictor V2.5</code>.</p>
<section id="laion" class="level3" data-number="4.1">
<h3 data-number="4.1" class="anchored" data-anchor-id="laion"><span class="header-section-number">4.1</span> LAION</h3>
<p>LAION is the older of the two models.</p>
<p>It is “a linear estimator on top of CLIP to predict the aesthetic quality of pictures.”</p>
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/aesthetic_predictor.jpg" width="600"></p>
<p>But how does it work?</p>
<p><code>Contrastive Language-Image Pretraining (CLIP)</code> is a multimodal model introduced in 2021. It’s based on</p>
<ul>
<li>A text encoder, usually GPT like</li>
<li>A vision encoder, a vision transformer</li>
</ul>
<p>Both encoders produce embeddings, and the model produces combined embeddings with a dimensionality of 768. CLIP was trained on image-caption pairs and used cosine similarity to align text and image embeddings as close as possible.</p>
<p>This allowed the model to identify the best caption for a given image, or vice-versa.</p>
<p><code>LAION</code> builds on top of <code>CLIP</code>, but scales it up to billions of images compared to clips 400 million.</p>
<p>On top of this embedding model, a linear regression model is trained using a much smaller dataset. The model is define by,</p>
<p><img src="https://latex.codecogs.com/png.latex?score=%20W%20*%20%5Cvec%7Bemb%7D%20+%20b"></p>
<p>Where W and b are the weights and bias of the linear regression model.</p>
</section>
<section id="aesthetic-predictor-v2.5" class="level3" data-number="4.2">
<h3 data-number="4.2" class="anchored" data-anchor-id="aesthetic-predictor-v2.5"><span class="header-section-number">4.2</span> Aesthetic Predictor V2.5</h3>
<p>In AI, four years is a long time.</p>
<p>In 2023 Google introduced SigLIP, Sigmoid Loss for Language–Image Pretraining.</p>
<p>The original CLIP model from OpenAI uses a contrastive loss function. Core to this function is a softmax over all image pairs. Even though all images can not be included at once, this is approximated using a very large batch size. This large batch size requires expensive compute hardware.</p>
<p>Another limitation of LAION was its the underperformance across diverse domains.</p>
<p>SigLIP addresses both problems:</p>
<ul>
<li>First it uses a sigmoid loss function. Smaller batch sizes can be used.</li>
<li>Second it uses more data, being more robust to diverse domains.</li>
</ul>
<p>So let’s check the aesthetic scores for our images.</p>
</section>
<section id="calculating-scores-with-aesthetic-predictor-2.5" class="level3" data-number="4.3">
<h3 data-number="4.3" class="anchored" data-anchor-id="calculating-scores-with-aesthetic-predictor-2.5"><span class="header-section-number">4.3</span> Calculating scores with Aesthetic Predictor 2.5</h3>
<p>We will start with the newer model. Unfortunately, my GPU is too old and is no longer supported by PyTorch version required for this model.</p>
<p>We can use the Hugginface Api or CPU, though.</p>
<section id="using-the-hugging-face-api-for-aesthetic-predictor-2.5" class="level4" data-number="4.3.1">
<h4 data-number="4.3.1" class="anchored" data-anchor-id="using-the-hugging-face-api-for-aesthetic-predictor-2.5"><span class="header-section-number">4.3.1</span> Using the Hugging Face API for Aesthetic Predictor 2.5</h4>
<div id="46651e0fa3a33240" class="cell" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>time</span>
<span id="cb3-2"></span>
<span id="cb3-3">client <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Client(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"discus0434/aesthetic-predictor-v2-5"</span>)</span>
<span id="cb3-4"></span>
<span id="cb3-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict_with_ae25api(img_tensor, client):</span>
<span id="cb3-6">    img <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> to_pil(img_tensor.cpu())</span>
<span id="cb3-7"></span>
<span id="cb3-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> tempfile.NamedTemporaryFile(suffix<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".png"</span>, delete<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> t:</span>
<span id="cb3-9">        img.save(t.name, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">format</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"PNG"</span>)</span>
<span id="cb3-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> client.predict(image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>(t.name), api_name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/inference"</span>)</span>
<span id="cb3-11"></span>
<span id="cb3-12">scores_api <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [predict_with_ae25api(img, client) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> images]</span>
<span id="cb3-13"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(scores_api)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Loaded as API: https://discus0434-aesthetic-predictor-v2-5.hf.space ✔
['4.712978', '4.985875', '5.3126655', '5.0395384', '4.75456', '4.390934', '5.410819', '5.163789', '5.7570896', '5.6178026', '5.0622964', '4.242473', '4.695843', '5.7283096', '5.394037', '5.970618', '5.013522', '5.021712', '5.727453', '4.788595', '5.810698', '5.6538353', '5.338957', '5.173321', '5.7376328', '5.856394', '4.9087625', '5.0130215', '5.60766', '4.9622364', '5.304905', '4.6225524', '4.5034065', '5.2350173', '5.9285026', '5.1088295', '5.6992407', '5.356913', '5.652878', '5.0367103', '4.662853', '4.8960724', '5.1651015', '5.030403', '4.730472', '5.0686293', '5.6805077', '5.1905656', '5.3466654', '5.454918', '5.108632', '5.384975', '5.2946644', '6.0702987', '5.935483', '5.140892', '4.4770913', '4.819613', '5.5843506', '5.7856994']
CPU times: user 14.3 s, sys: 432 ms, total: 14.7 s
Wall time: 4min 38s</code></pre>
</div>
</div>
<p>4 Minutes for the execution is quite long. Let’s try CPU.</p>
</section>
<section id="running-aesthetic-predictor-2.5-locally-on-cpu" class="level4" data-number="4.3.2">
<h4 data-number="4.3.2" class="anchored" data-anchor-id="running-aesthetic-predictor-2.5-locally-on-cpu"><span class="header-section-number">4.3.2</span> Running Aesthetic Predictor 2.5 locally on CPU</h4>
<p>We first define a function, so we can reuse it later.</p>
<div id="d9af6c4be51cd8c8" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_aesthetic_scores_v25(images, batch_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>):</span>
<span id="cb5-2"></span>
<span id="cb5-3">    model, preproc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> convert_v2_5_from_siglip(</span>
<span id="cb5-4">        low_cpu_mem_usage<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb5-5">        trust_remote_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb5-6">    )</span>
<span id="cb5-7">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()</span>
<span id="cb5-8"></span>
<span id="cb5-9">    scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb5-10"></span>
<span id="cb5-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> torch.inference_mode():</span>
<span id="cb5-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(images), batch_size):</span>
<span id="cb5-13">            batch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> images[i:i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>batch_size]</span>
<span id="cb5-14">            batch_tensor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.stack(batch)</span>
<span id="cb5-15">            batch_tensor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> F.interpolate(batch_tensor, size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">384</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">384</span>), mode<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bilinear"</span>, align_corners<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb5-16">    </span>
<span id="cb5-17">            mean <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.tensor(preproc.image_mean).view(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-18">            std  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.tensor(preproc.image_std).view(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-19">            batch_tensor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (batch_tensor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mean) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> std</span>
<span id="cb5-20">            </span>
<span id="cb5-21">            logits <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(batch_tensor).logits.squeeze(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-22">            batch_scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> logits.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>().cpu().numpy()</span>
<span id="cb5-23">    </span>
<span id="cb5-24">            scores.extend(batch_scores)</span>
<span id="cb5-25"></span>
<span id="cb5-26">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> scores</span></code></pre></div></div>
</div>
<div id="43fb61ce257bc26a" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>time</span>
<span id="cb6-2">scores_ap25 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_aesthetic_scores_v25(images, batch_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>CPU times: user 7min 47s, sys: 47.3 s, total: 8min 34s
Wall time: 1min 27s</code></pre>
</div>
</div>
<div id="7fcfa3ef-e640-426f-b792-ff465c285ba4" class="cell" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">np.array(scores_ap25).mean()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="9">
<pre><code>np.float32(5.3517203)</code></pre>
</div>
</div>
<p>With 1.5 minutes, this approach is faster than calling the api.</p>
<p>One possible use case is iterative improvement of the score through an algorithmic approach. In such a scenario, we should aim to process all 60 images within just a few seconds.</p>
<p>LAION has lower requirements on the hardware, we’ll try it next.</p>
</section>
</section>
<section id="calculating-scores-with-laion-on-gpu" class="level3" data-number="4.4">
<h3 data-number="4.4" class="anchored" data-anchor-id="calculating-scores-with-laion-on-gpu"><span class="header-section-number">4.4</span> Calculating scores with LAION on GPU</h3>
<p>From the <a href="https://github.com/LAION-AI/aesthetic-predictor">LAION github repository</a>, we find the following function:</p>
<div id="cac2228460e1094c" class="cell" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_aesthetic_model(clip_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vit_l_14"</span>):</span>
<span id="cb10-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""load the aethetic model"""</span></span>
<span id="cb10-3">    home <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> expanduser(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"~"</span>)</span>
<span id="cb10-4">    cache_folder <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> home <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/.cache/emb_reader"</span></span>
<span id="cb10-5">    path_to_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cache_folder <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/sa_0_4_"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>clip_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"_linear.pth"</span></span>
<span id="cb10-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> os.path.exists(path_to_model):</span>
<span id="cb10-7">        os.makedirs(cache_folder, exist_ok<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb10-8">        url_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb10-9">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://github.com/LAION-AI/aesthetic-predictor/blob/main/sa_0_4_"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>clip_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"_linear.pth?raw=true"</span></span>
<span id="cb10-10">        )</span>
<span id="cb10-11">        urlretrieve(url_model, path_to_model)</span>
<span id="cb10-12">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> clip_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vit_l_14"</span>:</span>
<span id="cb10-13">        m <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">768</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb10-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> clip_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vit_b_32"</span>:</span>
<span id="cb10-15">        m <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb10-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb10-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ValueError</span>()</span>
<span id="cb10-18">    s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.load(path_to_model)</span>
<span id="cb10-19">    m.load_state_dict(s)</span>
<span id="cb10-20">    m.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()</span>
<span id="cb10-21">    device <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> torch.cuda.is_available() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cpu"</span></span>
<span id="cb10-22">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> m.to(device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>torch.float32)</span></code></pre></div></div>
</div>
<p>This is just the linear head of the whole estimator. We need to run the CLIP model for scoring as well.</p>
<div id="a0d5366da15ce7d6" class="cell" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> score_with_laion(torch_images):</span>
<span id="cb11-2">    device <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> torch.cuda.is_available() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cpu"</span></span>
<span id="cb11-3">    dtype  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.float32</span>
<span id="cb11-4"></span>
<span id="cb11-5">    clip_model_name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ViT-L-14"</span></span>
<span id="cb11-6">    clip_ckpt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"openai"</span></span>
<span id="cb11-7"></span>
<span id="cb11-8">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># CLIP encoder + preprocess (must match the LAION head variant)</span></span>
<span id="cb11-9">    model, _, preprocess <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> open_clip.create_model_and_transforms(clip_model_name, pretrained<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>clip_ckpt)</span>
<span id="cb11-10">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.to(device).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()</span>
<span id="cb11-11"></span>
<span id="cb11-12">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Linear estimator</span></span>
<span id="cb11-13">    head <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_aesthetic_model()</span>
<span id="cb11-14"></span>
<span id="cb11-15">    images_preprocessed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [preprocess(to_pil(img)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> torch_images]</span>
<span id="cb11-16">    batch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.stack(images_preprocessed).to(device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dtype)</span>
<span id="cb11-17"></span>
<span id="cb11-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> torch.inference_mode():</span>
<span id="cb11-19">        clip_embeddings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.encode_image(batch)</span>
<span id="cb11-20">        clip_embeddings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> clip_embeddings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> clip_embeddings.norm(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, keepdim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>).clamp_min(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>)</span>
<span id="cb11-21">        clip_embeddings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> clip_embeddings.to(dtype) </span>
<span id="cb11-22">        scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> head(clip_embeddings).squeeze(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>().cpu().numpy()</span>
<span id="cb11-23"></span>
<span id="cb11-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> scores</span></code></pre></div></div>
</div>
<p>Running on our images.</p>
<div id="4c2229dd07bd3175" class="cell" data-execution_count="12">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>time</span>
<span id="cb12-2">scores_laion <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score_with_laion(images)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>CPU times: user 10.4 s, sys: 559 ms, total: 11 s
Wall time: 7.89 s</code></pre>
</div>
</div>
<p>As expected, the GPU calculation is a lot faster, and 8.5 seconds is less than what we would need.</p>
<p>Let’s examine min and max result.</p>
<div id="164a268e8b192d02" class="cell" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1">scores_laion</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="13">
<pre><code>array([4.682658 , 5.5719824, 4.7548094, 5.6179185, 5.8664765, 5.2028084,
       6.0401983, 6.153771 , 4.6438675, 5.7687664, 5.8421736, 5.352836 ,
       5.795928 , 6.3411045, 5.2397337, 6.822626 , 5.9344873, 5.9164524,
       5.7080965, 5.8545227, 6.7204437, 5.451813 , 6.035965 , 6.1448298,
       6.310848 , 6.398098 , 6.13536  , 6.0679417, 5.075293 , 6.218848 ,
       4.5623236, 5.423691 , 5.0390825, 6.200203 , 5.6596227, 4.7416925,
       5.774774 , 6.2334433, 5.8048406, 5.828251 , 5.0799165, 4.574512 ,
       5.1658216, 6.413603 , 5.409901 , 5.9421396, 6.02083  , 5.6725616,
       5.6838965, 5.1442785, 4.757121 , 5.8007193, 6.006052 , 5.8004303,
       6.1855965, 4.3213387, 5.9920015, 5.3351316, 6.3207726, 5.7225537],
      dtype=float32)</code></pre>
</div>
</div>
<div id="85fcdd65e1199670" class="cell" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1">min_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argmin(scores_laion)</span>
<span id="cb16-2">min_score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scores_laion[min_idx]</span>
<span id="cb16-3"></span>
<span id="cb16-4">max_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argmax(scores_laion)</span>
<span id="cb16-5">max_score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scores_laion[max_idx]</span>
<span id="cb16-6"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Minimum score is </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>min_score<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> and maximum score is </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>max_score<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb16-7"></span>
<span id="cb16-8">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>))</span>
<span id="cb16-9"></span>
<span id="cb16-10">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb16-11">img_min <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> images[min_idx].permute(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb16-12">plt.imshow(img_min)</span>
<span id="cb16-13">plt.title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"min_score: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>min_score<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.4f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb16-14">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb16-15"></span>
<span id="cb16-16">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb16-17">img_max <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> images[max_idx].permute(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb16-18">plt.imshow(img_max)</span>
<span id="cb16-19">plt.title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"max_score: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>max_score<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.4f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb16-20">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb16-21"></span>
<span id="cb16-22"></span>
<span id="cb16-23">plt.show()</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Minimum score is 4.321338653564453 and maximum score is 6.822626113891602</code></pre>
</div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-12-output-2.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>While the plates are cut in both pictures, the higher rated picture somehow looks better.</p>
</section>
<section id="comparing-the-two-predictors" class="level3" data-number="4.5">
<h3 data-number="4.5" class="anchored" data-anchor-id="comparing-the-two-predictors"><span class="header-section-number">4.5</span> Comparing the two predictors</h3>
<p>Let’s see how the two scores of LAION and Aesthetic Predictor align.</p>
<div id="c33f479909c1f622" class="cell" data-execution_count="15">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1">scores_ap25<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(scores_ap25)</span>
<span id="cb18-2">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame({</span>
<span id="cb18-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"LAION Score"</span>: (scores_laion <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> scores_laion.mean()) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>scores_laion.std(),</span>
<span id="cb18-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"AE25 Score"</span>: (scores_ap25 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> scores_ap25.mean()) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>scores_ap25.std()</span>
<span id="cb18-5">})</span>
<span id="cb18-6"></span>
<span id="cb18-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Create scatter plot</span></span>
<span id="cb18-8">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>))</span>
<span id="cb18-9">sns.scatterplot(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>df, x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"LAION Score"</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"AE25 Score"</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>)</span>
<span id="cb18-10"></span>
<span id="cb18-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Improve visualization</span></span>
<span id="cb18-12">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Aesthetic Score Comparison: LAION vs SigLIP"</span>)</span>
<span id="cb18-13">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"LAION Aesthetic Score"</span>)</span>
<span id="cb18-14">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SigLIP Aesthetic Score"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="15">
<pre><code>Text(0, 0.5, 'SigLIP Aesthetic Score')</code></pre>
</div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-13-output-2.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="436db79c5fb3010e" class="cell" data-execution_count="16">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.stats <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pearsonr, spearmanr</span>
<span id="cb20-2">pearson_corr, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pearsonr(scores_laion, scores_ap25)</span>
<span id="cb20-3">spearman_corr, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> spearmanr(scores_laion, scores_ap25)</span></code></pre></div></div>
</div>
<div id="90b971b7490c292f" class="cell" data-execution_count="17">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Pearson correlation is </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>pearson_corr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, Spearman correlation is </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>spearman_corr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Pearson correlation is 0.268462598323822, Spearman correlation is 0.22606279522089476</code></pre>
</div>
</div>
<p>Values close to 0.2 indicate that there is little correlation between the CLIP-based and the SIGLIP-based evaluations. The picture confirms the numerical values, too.</p>
<p>At first, this might seem surprising. Should a good image not always look good?</p>
<p>Not necessarily. Beauty lies in the eye of the beholder. And in fact, those two models are different. The difference in the loss functions is not the only factor that changed.</p>
<p>The two models were trained on very different datasets.</p>
<ul>
<li><code>LAION</code> is primarily focused on Photography</li>
<li><code>SIGLIP</code> focuses on much broader range of web images.</li>
</ul>
<p>As a result, images with bright, unrealistic colours may score higher using <code>SIGLIP</code> than with <code>LAION</code>.</p>
</section>
</section>
<section id="optimizing-thumbnails-with-global-methods" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="optimizing-thumbnails-with-global-methods"><span class="header-section-number">5</span> Optimizing thumbnails with global methods</h2>
<p>Due to the significant speed advantage on my machine, I will focus on LAION. Let’s create a baseline.</p>
<div id="2d409bd5a42ecf4d" class="cell" data-execution_count="18">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1">baseline_score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scores_laion.mean()</span>
<span id="cb23-2">baseline_score</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="18">
<pre><code>np.float32(5.671463)</code></pre>
</div>
</div>
<p>In theory, several improvements are possible.</p>
<p>Non-crop improvements, modifying the entire image - Correct orientation - Color correction - Glare and noise reduction</p>
<p>Crop-based improvements try to locate a plate in the image and crop. - Use saliency maps to highlight the most important object in the image - Use segmentation models to find all contours - Use bounding box object detection models like YOLO to detect the dish - Perform optimizations on (x, y, zoom) by scoring multiple crops and treating the search for the perfect crop as an optimization problem</p>
<section id="correct-orientation" class="level3" data-number="5.1">
<h3 data-number="5.1" class="anchored" data-anchor-id="correct-orientation"><span class="header-section-number">5.1</span> Correct orientation</h3>
<p>This is the most obvious one.</p>
<div id="823ad578385cff28" class="cell" data-execution_count="19">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1">images_correct_orientation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [thumb_transform(ImageOps.exif_transpose(Image.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(f)).convert(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"RGB"</span>)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> f <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> files]</span></code></pre></div></div>
</div>
<div id="7f333631-2f19-48ea-b9e2-254918d62ae1" class="cell" data-execution_count="20">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1">show_image_grid(images_correct_orientation)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-18-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="b2b7176163b173f1" class="cell" data-execution_count="21">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1">scores_laion_correct_orientation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score_with_laion(images_correct_orientation)</span></code></pre></div></div>
</div>
<div id="171a8c15429a48b7" class="cell" data-execution_count="22">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1">scores_laion_correct_orientation.mean()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="22">
<pre><code>np.float32(5.8733764)</code></pre>
</div>
</div>
<p>As we can see correct orientation leads to a better score.</p>
</section>
<section id="color-correction-and-denoising" class="level3" data-number="5.2">
<h3 data-number="5.2" class="anchored" data-anchor-id="color-correction-and-denoising"><span class="header-section-number">5.2</span> Color correction and denoising</h3>
<p>I experiment with applying color correction and denoising on some samples. However, in most cases this actually lowers the score.</p>
<p>One possible explanation is that the model was trained on untreated sRGB pictures. By altering the images too much, we risk creating an out-of-domain.</p>
<p>Nevertheless, we will still apply a mild correction to to reduce glare, but only after cropping.</p>
</section>
</section>
<section id="optimizing-thumbnails-with-cropping-using-saliency-maps" class="level2" data-number="6">
<h2 data-number="6" class="anchored" data-anchor-id="optimizing-thumbnails-with-cropping-using-saliency-maps"><span class="header-section-number">6</span> Optimizing Thumbnails with cropping using saliency maps</h2>
<p>Saliency detection attempts to identify which parts of an image are the most visually important.</p>
<p>We have two lightweight options for generating saliency maps:</p>
<ul>
<li>Opencv-based fine-grained saliency map</li>
<li>U²-Net</li>
</ul>
<p>We will not use the Opencv Method.</p>
<p>Opencv algorithm compares pixel color variations with their neighbours. However, the approach is outdated and quite slow, making it not suitable for our purpose.</p>
<section id="u²-net-saliency-map" class="level3" data-number="6.1">
<h3 data-number="6.1" class="anchored" data-anchor-id="u²-net-saliency-map"><span class="header-section-number">6.1</span> U²-Net saliency map</h3>
<p>U²-Net is a deep learning model for salient object detection that uses a nested U-shaped architecture with Residual U-blocks (RSUs) for efficient multi-scale feature extraction. It delivers high-accuracy segmentation and is widely used for background removal.</p>
<p>We aim to identify the main dish as the foreground. Instead of removing the background, we’ll simply use the saliency map to crop the dish region.</p>
<p>Let’s start by testing it on a sample picture.</p>
<div id="3ea1bed31b0e8df" class="cell" data-execution_count="23">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1">test_image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Image.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(files[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb30-2">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb30-3">plt.imshow(test_image)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-21-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Which we need to turn</p>
<div id="1ec5968bb429603e" class="cell" data-execution_count="24">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb31-1">transposed_image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ImageOps.exif_transpose(test_image).convert(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"RGB"</span>)</span>
<span id="cb31-2">transposed_image_np <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(transposed_image)</span>
<span id="cb31-3">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb31-4">plt.imshow(transposed_image_np)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-22-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>We need to scale down the picture to 320px, as the model was trained on this and convert to pytorch.</p>
<div id="4d56d3bd85eccfaa" class="cell" data-execution_count="25">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1">arr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> transposed_image_np.astype(np.float32) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">255.0</span></span>
<span id="cb32-2">H, W <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> arr.shape[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb32-3">scale <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(H, W), <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>)</span>
<span id="cb32-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> scale <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>:</span>
<span id="cb32-5">    newW, newH <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(W <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> scale)), <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(H <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> scale))</span>
<span id="cb32-6">    arr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.resize(arr, (newW, newH), interpolation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cv.INTER_AREA)</span>
<span id="cb32-7"></span>
<span id="cb32-8">ten <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.from_numpy(arr).permute(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>).unsqueeze(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>).to(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda"</span>)</span></code></pre></div></div>
</div>
<p>Next, let’s load the model, and examine if it correctly loaded. If so We should see definitions of RSUs. I copied definition and weights from <a href="https://github.com/xuebinqin/U-2-Net/">https://github.com/xuebinqin/U-2-Net/</a>.</p>
<div id="2e03df17e1df6bb2" class="cell" data-execution_count="68">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb33-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> u2net <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> U2NET</span>
<span id="cb33-2">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> U2NET(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb33-3">state <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.load(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data/u2net.pth"</span>, map_location<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cuda'</span>)</span>
<span id="cb33-4">model.load_state_dict(state, strict<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb33-5">model.to(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda"</span>)</span>
<span id="cb33-6">_ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()</span></code></pre></div></div>
</div>
<p>This seems identical to what is specified in the sources.</p>
<p>Let’s run the the model. U²-Net produces multiple maps; one at each level of the u-net. We are only interested in the upper layer.</p>
<div id="551c1298d0f42b11" class="cell" data-execution_count="27">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb34-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> torch.inference_mode():</span>
<span id="cb34-2">    out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(ten)</span>
<span id="cb34-3">    pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(out, (<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">tuple</span>)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> out</span>
<span id="cb34-4">    sal_small <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.sigmoid(pred)</span></code></pre></div></div>
</div>
<p>For futher processing we will convert back to uint8 and inspect the output.</p>
<div id="5715b09e90bf1f8c" class="cell" data-execution_count="28">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb35-1">sal_u8 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (sal_small.detach().clamp(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>).cpu().numpy() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span>).astype(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"uint8"</span>).squeeze()</span>
<span id="cb35-2">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb35-3">plt.imshow(sal_u8)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-26-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>The main plate is correctly identified.</p>
</section>
<section id="optimized-pipeline" class="level3" data-number="6.2">
<h3 data-number="6.2" class="anchored" data-anchor-id="optimized-pipeline"><span class="header-section-number">6.2</span> Optimized pipeline</h3>
<p>We start by defining a function to run inference on a unscaled numpy/opencv image.</p>
<div id="4af7ba2c2bd6a600" class="cell" data-execution_count="29">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb36" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb36-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> run_u2_on_pil(model, image,resolution<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span>):</span>
<span id="cb36-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># preprocessing</span></span>
<span id="cb36-3">    H, W <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> image.shape[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb36-4">    scale <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(resolution <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(H, W), <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>)</span>
<span id="cb36-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> scale <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>:</span>
<span id="cb36-6">        newW, newH <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(W <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> scale)), <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(H <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> scale))</span>
<span id="cb36-7">        target_image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.resize(image, (newW, newH), interpolation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cv.INTER_AREA)</span>
<span id="cb36-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb36-9">        target_image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> image</span>
<span id="cb36-10">    ten <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (torch.from_numpy(target_image).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>().permute(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">255.0</span>).unsqueeze(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>).to(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda"</span>)</span>
<span id="cb36-11"></span>
<span id="cb36-12">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># getting saliency map</span></span>
<span id="cb36-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> torch.inference_mode():</span>
<span id="cb36-14">        out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(ten)</span>
<span id="cb36-15">        pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(out, (<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">tuple</span>)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> out</span>
<span id="cb36-16">        sal_small <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.sigmoid(pred)</span>
<span id="cb36-17"></span>
<span id="cb36-18">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># postprocessing back to original scale and cpu</span></span>
<span id="cb36-19">    sal_full <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> F.interpolate(sal_small, size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(H, W), mode<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bilinear"</span>, align_corners<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb36-20">    sal_full <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sal_full.squeeze(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>).squeeze(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>).clamp(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>).detach().cpu().numpy().astype(np.float32)</span>
<span id="cb36-21">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> sal_full</span></code></pre></div></div>
</div>
<div id="e9a913dae612a413" class="cell" data-execution_count="30">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1">sal_full <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> run_u2_on_pil(model, transposed_image_np)</span></code></pre></div></div>
</div>
<p>Let’s add an edge detector. The edge detector uses the Scharr operator on the luminance.</p>
<div id="26a2ee25bdb76632" class="cell" data-execution_count="31">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb38" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb38-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> rim_prior_from_L(image_uint8):</span>
<span id="cb38-2">    L <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.cvtColor(image_uint8, cv.COLOR_RGB2LAB)[:,:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb38-3">    gx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.Scharr(L, cv.CV_32F, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb38-4">    gy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.Scharr(L, cv.CV_32F, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb38-5">    mag <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.magnitude(gx, gy)</span>
<span id="cb38-6">    mag <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.GaussianBlur(mag, (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb38-7">    mag <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> mag.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>()</span>
<span id="cb38-8">    mag <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/=</span> (mag.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>)</span>
<span id="cb38-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> mag.astype(np.float32)</span>
<span id="cb38-10"></span>
<span id="cb38-11">R <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rim_prior_from_L(transposed_image_np)</span>
<span id="cb38-12">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb38-13">plt.imshow(R)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-29-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>We fuse the two detections, doing so gives us a slightly nicer visualization.</p>
<div id="dc045c9a5583ec3" class="cell" data-execution_count="32">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb39" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb39-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Fuse</span></span>
<span id="cb39-2">S_fused <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.85</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>sal_full <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.15</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>R</span>
<span id="cb39-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Normalize</span></span>
<span id="cb39-4">S_fused <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> S_fused.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>()</span>
<span id="cb39-5">S_fused <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/=</span> (S_fused.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>)</span></code></pre></div></div>
</div>
<div id="fc858ef3e2e89e2e" class="cell" data-execution_count="69">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb40" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb40-1">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>))</span>
<span id="cb40-2"></span>
<span id="cb40-3">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb40-4">plt.imshow(transposed_image_np)</span>
<span id="cb40-5">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Original"</span>)</span>
<span id="cb40-6">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb40-7">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb40-8">plt.imshow(S_fused , cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inferno"</span>)</span>
<span id="cb40-9">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fused Saliency"</span>)</span>
<span id="cb40-10">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb40-11">plt.tight_layout()</span>
<span id="cb40-12">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-31-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Next, we are interested in generating a bounding box around the main dish.</p>
<div id="a654deabd091e212" class="cell" data-execution_count="34">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb41" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb41-1">S8 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.clip(S_fused <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> S_fused.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span>).astype(np.uint8)</span>
<span id="cb41-2">_, mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.threshold(S8, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span>, cv.THRESH_BINARY <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> cv.THRESH_OTSU)</span>
<span id="cb41-3">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb41-4">plt.imshow(mask)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-32-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>We remove small islands through close open transforms. Eventually we search the largest component.</p>
<div id="6f132fe604ea8298" class="cell" data-execution_count="35">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb42" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb42-1">mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.morphologyEx(mask, cv.MORPH_CLOSE, np.ones((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>), np.uint8))</span>
<span id="cb42-2">mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.morphologyEx(mask, cv.MORPH_OPEN,  np.ones((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>),  np.uint8))</span>
<span id="cb42-3">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb42-4">plt.imshow(mask)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-33-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="7293ea0a7bb3fabb" class="cell" data-execution_count="36">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb43-1">num, labels, stats, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.connectedComponentsWithStats(mask, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)</span></code></pre></div></div>
</div>
<div id="10b7e252c3458890" class="cell" data-execution_count="37">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb44" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb44-1">img_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> H <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> W</span>
<span id="cb44-2">best_i, best_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb44-3"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, num):</span>
<span id="cb44-4">    x, y, w, h, area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> stats[i]</span>
<span id="cb44-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> best_area <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> img_area:</span>
<span id="cb44-6">        best_i, best_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> i, area</span></code></pre></div></div>
</div>
<div id="164dfac4cde10fb8" class="cell" data-execution_count="38">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb45" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb45-1">x, y, w, h, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> stats[best_i]</span>
<span id="cb45-2">cx, cy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span></span></code></pre></div></div>
</div>
<div id="c2256a254783e725" class="cell" data-execution_count="39">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb46" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb46-1">out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> transposed_image_np.copy()</span>
<span id="cb46-2">cv.rectangle(out, (x, y), (x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>w,y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>h), (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb46-3">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb46-4">plt.imshow(out)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-37-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>The green bounding box shows very nicely how we detected the plate. Let’s turn this into a function, which produces a resized square crop while respecting image boundaries.</p>
<div id="26b00e3c83777882" class="cell" data-execution_count="40">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb47" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb47-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> crop_on_saliency_map(saliency_map, image):</span>
<span id="cb47-2">    S8 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.clip(saliency_map <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> saliency_map.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span>).astype(np.uint8)</span>
<span id="cb47-3">    _, mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.threshold(S8, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span>, cv.THRESH_BINARY <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> cv.THRESH_OTSU)</span>
<span id="cb47-4">    mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.morphologyEx(mask, cv.MORPH_CLOSE, np.ones((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>), np.uint8))</span>
<span id="cb47-5"></span>
<span id="cb47-6">    mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.morphologyEx(mask, cv.MORPH_OPEN,  np.ones((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>),  np.uint8))</span>
<span id="cb47-7">    num, labels, stats, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.connectedComponentsWithStats(mask, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)</span>
<span id="cb47-8">    img_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> H <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> W</span>
<span id="cb47-9">    best_i, best_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb47-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, num):</span>
<span id="cb47-11">        x, y, w, h, area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> stats[i]</span>
<span id="cb47-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> best_area <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> img_area:</span>
<span id="cb47-13">            best_i, best_area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> i, area</span>
<span id="cb47-14">    x, y, w, h, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> stats[best_i]</span>
<span id="cb47-15">    cx, cy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span></span>
<span id="cb47-16"></span>
<span id="cb47-17">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># make image square and shift if we are too close to the border</span></span>
<span id="cb47-18">    pad <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span></span>
<span id="cb47-19">    w2, h2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pad), h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pad)</span>
<span id="cb47-20">    side <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(w2, h2)</span>
<span id="cb47-21">    side_px <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(side)), W, H)</span>
<span id="cb47-22">    half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> side_px <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span></span>
<span id="cb47-23"></span>
<span id="cb47-24">    cx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(np.clip(cx, half, W <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> half))</span>
<span id="cb47-25">    cy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(np.clip(cy, half, H <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> half))</span>
<span id="cb47-26"></span>
<span id="cb47-27">    x0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(cx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> half))</span>
<span id="cb47-28">    y0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(cy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> half))</span>
<span id="cb47-29">    </span>
<span id="cb47-30">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># guard against rounding pushing us out of bounds</span></span>
<span id="cb47-31">    x0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(x0, W <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> side_px))</span>
<span id="cb47-32">    y0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(y0, H <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> side_px))</span>
<span id="cb47-33">    x1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> side_px</span>
<span id="cb47-34">    y1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> side_px</span>
<span id="cb47-35"></span>
<span id="cb47-36">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># crop and resize    </span></span>
<span id="cb47-37">    crop <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> image[y0:y1, x0:x1]</span>
<span id="cb47-38">    interp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.INTER_AREA <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(crop.shape[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> cv.INTER_LINEAR</span>
<span id="cb47-39">    crop <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.resize(crop, (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span>), interpolation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>interp)</span>
<span id="cb47-40">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> crop</span></code></pre></div></div>
</div>
<div id="40f6a70e3648cb62" class="cell" data-execution_count="41">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb48" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb48-1">result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> crop_on_saliency_map(S_fused, transposed_image_np)</span>
<span id="cb48-2">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb48-3">plt.imshow(result)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-39-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>This is the correct crop of the plate in the picture. Next, we score the cropped image.</p>
<div id="db632751bd4470a3" class="cell" data-execution_count="42">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb49" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb49-1">scores_laion_cropped <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score_with_laion([to_tensor(transposed_image)])</span></code></pre></div></div>
</div>
<div id="3882c65a53944d60" class="cell" data-execution_count="43">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb50" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb50-1">scores_laion_cropped</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="43">
<pre><code>array([5.954031], dtype=float32)</code></pre>
</div>
</div>
<p>This score is higher than our baseline score. That means correct cropping has a effect.</p>
</section>
<section id="improving-even-more" class="level3" data-number="6.3">
<h3 data-number="6.3" class="anchored" data-anchor-id="improving-even-more"><span class="header-section-number">6.3</span> Improving even more</h3>
<p>On some images, there are too many fine details. The network will detect the whole page as salient object. We need to run the network with another input resolution. We can run several resolutions and decide which is best after scoring. A quicker approach is to examine the size of the main component in the picture, if it is too large we need to increase the resolution.</p>
<p>Therefore, we define a function, which checks if we cover too much of the page with one component, where “too much” means 80%.</p>
<div id="68ce828a-1bf5-4b36-92f8-59c9d829adc3" class="cell" data-execution_count="44">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb52" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb52-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _looks_like_full_page(sal, area_frac_thresh<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.80</span>,require_border_touch<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>):</span>
<span id="cb52-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Heuristic: is the biggest component huge and touching the image border?"""</span></span>
<span id="cb52-3">    S8 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (np.clip(sal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span>)).astype(np.uint8)</span>
<span id="cb52-4">    _, mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.threshold(S8, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span>, cv.THRESH_BINARY <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> cv.THRESH_OTSU)</span>
<span id="cb52-5">    num, labels, stats, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.connectedComponentsWithStats(mask, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)</span>
<span id="cb52-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> num <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:</span>
<span id="cb52-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb52-8">        </span>
<span id="cb52-9">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># largest component (skip background 0)</span></span>
<span id="cb52-10">    idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> np.argmax(stats[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:, cv.CC_STAT_AREA])</span>
<span id="cb52-11">    x, y, w, h, area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> stats[idx]</span>
<span id="cb52-12">    H, W <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sal.shape[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb52-13">    area_frac <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> area <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(H <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> W)</span>
<span id="cb52-14">    touches <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> (y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> (x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> W) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> (y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> H)</span>
<span id="cb52-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> (area_frac <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> area_frac_thresh) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (touches <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> require_border_touch <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div></div>
</div>
<p>With this function in place we can run a small optimization function. It will run over predefined scales and check if the result does not look like the full page. We start with smaller resolutions as these tend to produce the full page saliency map.</p>
<div id="4c48a1e0-0159-40c8-9177-16bc4a3c98b3" class="cell" data-execution_count="45">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb53" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb53-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> run_u2_autoscale(model, image_np, sizes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">320</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">480</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">640</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">896</span>), device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cuda"</span>):</span>
<span id="cb53-2"></span>
<span id="cb53-3">    last_sal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb53-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(sizes):</span>
<span id="cb53-5">        sal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> run_u2_on_pil(model, image_np, s)</span>
<span id="cb53-6">        last_sal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sal</span>
<span id="cb53-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> _looks_like_full_page(sal):</span>
<span id="cb53-8">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> sal</span>
<span id="cb53-9">            </span>
<span id="cb53-10">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># If even the largest still looks like a page, fall back to a small multi-scale fuse (max)</span></span>
<span id="cb53-11">    sal_big <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> last_sal</span>
<span id="cb53-12">    sal_small <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> run_u2_on_pil(model, image_np, sizes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb53-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.maximum(sal_big, sal_small)</span></code></pre></div></div>
</div>
</section>
<section id="the-full-pipeline" class="level3" data-number="6.4">
<h3 data-number="6.4" class="anchored" data-anchor-id="the-full-pipeline"><span class="header-section-number">6.4</span> The full pipeline</h3>
<p>Now with everything in place we can define a function that creates the fused saliency map, the bounding box, and finally crops.</p>
<div id="70c03d445e599ccf" class="cell" data-execution_count="46">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb54" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb54-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> full_crop_pipeline(model, image):</span>
<span id="cb54-2">    transposed_image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(ImageOps.exif_transpose(image).convert(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"RGB"</span>))</span>
<span id="cb54-3">    </span>
<span id="cb54-4">    sal_full <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> run_u2_autoscale(model, transposed_image)</span>
<span id="cb54-5"></span>
<span id="cb54-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># run edge detector</span></span>
<span id="cb54-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> rim_prior_from_L(image_uint8):</span>
<span id="cb54-8">        L <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.cvtColor(image_uint8, cv.COLOR_RGB2LAB)[:,:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb54-9">        gx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.Scharr(L, cv.CV_32F, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb54-10">        gy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.Scharr(L, cv.CV_32F, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb54-11">        mag <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.magnitude(gx, gy)</span>
<span id="cb54-12">        mag <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.GaussianBlur(mag, (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb54-13">        mag <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> mag.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>()</span>
<span id="cb54-14">        mag <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/=</span> (mag.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>)</span>
<span id="cb54-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> mag.astype(np.float32)</span>
<span id="cb54-16"></span>
<span id="cb54-17">    R <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rim_prior_from_L(transposed_image)</span>
<span id="cb54-18"></span>
<span id="cb54-19">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Fuse</span></span>
<span id="cb54-20">    S_fused <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.85</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>sal_full <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.15</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>R</span>
<span id="cb54-21">    </span>
<span id="cb54-22">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Normalize</span></span>
<span id="cb54-23">    S_fused <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> S_fused.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>()</span>
<span id="cb54-24">    S_fused <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/=</span> (S_fused.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>)</span>
<span id="cb54-25"></span>
<span id="cb54-26">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Crop</span></span>
<span id="cb54-27">    cropped <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> crop_on_saliency_map(S_fused, transposed_image)</span>
<span id="cb54-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> cropped</span></code></pre></div></div>
</div>
<div id="c2c45b7db787b297" class="cell" data-execution_count="47">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb55" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb55-1">cropped_test_image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> full_crop_pipeline(model, test_image)</span>
<span id="cb55-2">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb55-3">plt.imshow(cropped_test_image)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-45-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>As expected we get the same picture.</p>
<p>Let’s calculate for all images and score.</p>
<div id="b4860e72b8585cc7" class="cell" data-execution_count="48">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb56" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb56-1">cropped_images<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb56-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> tqdm.tqdm(files):</span>
<span id="cb56-3">    cropped_images.append(full_crop_pipeline(model, Image.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>)))</span></code></pre></div></div>
</div>
<div id="a57ee29d85530658" class="cell" data-execution_count="49">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb57" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb57-1">scores_laion_cropped <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score_with_laion([to_tensor(img) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cropped_images])</span></code></pre></div></div>
</div>
<div id="3c0d5479f3d59257" class="cell" data-execution_count="50">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb58" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb58-1">scores_laion_cropped.mean()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="50">
<pre><code>np.float32(5.951551)</code></pre>
</div>
</div>
<p>This mean score is slightly better than the uncropped. let’s check the details.</p>
<div id="5c55f0a4c95f034" class="cell" data-execution_count="51">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb60" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb60-1">improvement <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (scores_laion_cropped<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>scores_laion_correct_orientation)</span>
<span id="cb60-2">improvement.mean()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="51">
<pre><code>np.float32(0.07817339)</code></pre>
</div>
</div>
<div id="bd2e3144e7799b76" class="cell" data-execution_count="52">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb62" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb62-1">improvement.std()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="52">
<pre><code>np.float32(0.3198055)</code></pre>
</div>
</div>
<p>The high standard deviation means some images improved a lot more, some got worse. Let’s identify the worst decline in the score.</p>
<div id="83404a2d3eda1c8e" class="cell" data-execution_count="53">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb64" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb64-1">np.argmin(scores_laion_cropped<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>scores_laion_correct_orientation)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="53">
<pre><code>np.int64(22)</code></pre>
</div>
</div>
<div id="80e0409e6273d1b8" class="cell" data-execution_count="54">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb66" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb66-1">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb66-2">plt.imshow(cropped_images[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>])</span>
<span id="cb66-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(improvement[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>])</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>-0.76167774</code></pre>
</div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-52-output-2.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>The image is a perfect crop. It is not obvious why the score decreased. In terms of results it is exactly what we want. The same is true for almost all other images, as we can see below.</p>
<div id="56df0b26460ca9cf" class="cell" data-execution_count="55">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb68" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb68-1">show_image_grid([to_tensor(img) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cropped_images])</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-53-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="postprocessing" class="level3" data-number="6.5">
<h3 data-number="6.5" class="anchored" data-anchor-id="postprocessing"><span class="header-section-number">6.5</span> Postprocessing</h3>
<p>The pictures were done with a mobile phone camera. This is the quickest way to digitize a book without expensive equipment. There is some glare from glossy paper and non-perfect light condition. Let’s try to improve.</p>
<div id="5d38565326851cc3" class="cell" data-execution_count="56">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb69" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb69-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> reduce_glare(img):</span>
<span id="cb69-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Ensure BGR → LAB (good for luminance adjustments)</span></span>
<span id="cb69-3">    lab <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.cvtColor(img, cv.COLOR_RGB2LAB)</span>
<span id="cb69-4">    l, a, b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.split(lab)</span>
<span id="cb69-5"></span>
<span id="cb69-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Apply CLAHE on L-channel, 2.0 and 8.8 produce moderately aggressive results</span></span>
<span id="cb69-7">    clahe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.createCLAHE(clipLimit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>, tileGridSize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>))</span>
<span id="cb69-8">    cl <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> clahe.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">apply</span>(l)</span>
<span id="cb69-9"></span>
<span id="cb69-10">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Merge and convert back</span></span>
<span id="cb69-11">    limg <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.merge((cl, a, b))</span>
<span id="cb69-12">    final <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.cvtColor(limg, cv.COLOR_LAB2RGB)</span>
<span id="cb69-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> final</span>
<span id="cb69-14"></span>
<span id="cb69-15"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> detect_glare_mask(img, thresh<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">230</span>):</span>
<span id="cb69-16">    hsv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.cvtColor(img, cv.COLOR_RGB2HSV)</span>
<span id="cb69-17">    h, s, v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.split(hsv)</span>
<span id="cb69-18">    mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> thresh).astype(np.uint8) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span></span>
<span id="cb69-19"></span>
<span id="cb69-20">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Optional: clean up mask</span></span>
<span id="cb69-21">    kernel <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.ones((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>), np.uint8)</span>
<span id="cb69-22">    mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.morphologyEx(mask, cv.MORPH_CLOSE, kernel)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># fill small holes</span></span>
<span id="cb69-23">    mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.morphologyEx(mask, cv.MORPH_OPEN, kernel)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># remove tiny specks</span></span>
<span id="cb69-24"></span>
<span id="cb69-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> mask</span>
<span id="cb69-26"></span>
<span id="cb69-27"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> inpaint_glare(img, thresh):</span>
<span id="cb69-28">    mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> detect_glare_mask(img, thresh<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>thresh)</span>
<span id="cb69-29">    gray <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.cvtColor(img, cv.COLOR_RGB2GRAY)</span>
<span id="cb69-30">    </span>
<span id="cb69-31">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Detect glare: very bright areas</span></span>
<span id="cb69-32">    img_bgr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.cvtColor(img, cv.COLOR_RGB2BGR)</span>
<span id="cb69-33">    inpainted_bgr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.inpaint(img_bgr, mask, inpaintRadius<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, flags<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cv.INPAINT_TELEA)</span>
<span id="cb69-34">    inpainted_rgb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cv.cvtColor(inpainted_bgr, cv.COLOR_BGR2RGB)</span>
<span id="cb69-35">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> inpainted_rgb</span></code></pre></div></div>
</div>
<div id="9df43bfa1e5acf9d" class="cell" data-execution_count="57">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb70" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb70-1">crop_glare_reduced <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [reduce_glare(img) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cropped_images]</span>
<span id="cb70-2">crop_glare_reduced_and_inpainted <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [inpaint_glare(img,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">240</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> crop_glare_reduced]</span></code></pre></div></div>
</div>
<div id="d1b5c8fa88fa0552" class="cell" data-execution_count="58">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb71" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb71-1">show_image_grid([to_tensor(img) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> crop_glare_reduced])</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-56-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="7f1ae0ab6f232806" class="cell" data-execution_count="59">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb72" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb72-1">show_image_grid([to_tensor(img) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> crop_glare_reduced_and_inpainted])</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-57-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="26b6c473ec68dc71" class="cell" data-execution_count="60">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb73" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb73-1">scores_laion_cropped_fixed_glare <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score_with_laion([to_tensor(img) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> crop_glare_reduced])</span>
<span id="cb73-2">scores_laion_cropped_fixed_glare.mean()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="60">
<pre><code>np.float32(5.9497223)</code></pre>
</div>
</div>
<div id="efd4be69453d082c" class="cell" data-execution_count="61">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb75" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb75-1">scores_laion_cropped_fixed_glare_inpaint <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score_with_laion([to_tensor(img) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> crop_glare_reduced_and_inpainted])</span>
<span id="cb75-2">scores_laion_cropped_fixed_glare_inpaint.mean()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="61">
<pre><code>np.float32(5.816769)</code></pre>
</div>
</div>
<p>Subjectively the pictures look better. The average score is a little lower for histogram equalization and gets bad for mask-based glare inpainting. Let’s check a single image.</p>
<div id="4473424a75852d34" class="cell" data-execution_count="62">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb77" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb77-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(scores_laion_cropped[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>],scores_laion_cropped_fixed_glare[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>],scores_laion_cropped_fixed_glare_inpaint[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>6.1202517 6.257745 6.3136473</code></pre>
</div>
</div>
<p>This tells a completely other story. Here the images got better, the more processing was applied. We will do a visual inspection.</p>
<div id="29ce579482d3c7c1" class="cell" data-execution_count="63">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb79" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb79-1">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>))</span>
<span id="cb79-2"></span>
<span id="cb79-3">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb79-4">plt.imshow(cropped_images[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb79-5">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"No Glare Fix"</span>)</span>
<span id="cb79-6">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb79-7">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb79-8">plt.imshow(crop_glare_reduced[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] , cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inferno"</span>)</span>
<span id="cb79-9">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Histogram Equalization"</span>)</span>
<span id="cb79-10">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb79-11">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb79-12">plt.imshow(crop_glare_reduced_and_inpainted[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] , cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inferno"</span>)</span>
<span id="cb79-13">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Inpainting"</span>)</span>
<span id="cb79-14">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb79-15">plt.tight_layout()</span>
<span id="cb79-16">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-61-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>The strong glare is succesfully removed, without introducing artifacts or too high contrast.As we can see glare reduction can deliver improvements. Let’s combine the best of all.</p>
<div id="5379d7a75a4a81e1" class="cell" data-execution_count="64">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb80" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb80-1">scores_list <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [scores_laion_cropped, scores_laion_cropped_fixed_glare, scores_laion_cropped_fixed_glare_inpaint]</span>
<span id="cb80-2">images_list <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [cropped_images, crop_glare_reduced, crop_glare_reduced_and_inpainted]</span>
<span id="cb80-3"></span>
<span id="cb80-4">scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.stack(scores_list, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb80-5">best_indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scores.argmax(axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb80-6">best_scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scores.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb80-7"></span>
<span id="cb80-8">N <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scores.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb80-9">best_images <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [images_list[idx][i] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, idx <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(best_indices)]</span>
<span id="cb80-10">best_scores.mean()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="64">
<pre><code>np.float32(6.1018143)</code></pre>
</div>
</div>
<div id="7d77ce52116634cb" class="cell" data-execution_count="65">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb82" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb82-1">show_image_grid([to_tensor(img) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> img <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> best_images])</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-63-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Now we have an average improvement. Let’s check a picture with a lot of glare</p>
<div id="909fa75a159015d6" class="cell" data-execution_count="66">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb83" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb83-1">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>))</span>
<span id="cb83-2"></span>
<span id="cb83-3">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb83-4">plt.imshow(best_images[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">29</span>])</span>
<span id="cb83-5">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Best Image"</span>)</span>
<span id="cb83-6">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb83-7">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb83-8">plt.imshow(crop_glare_reduced[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">29</span>] , cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inferno"</span>)</span>
<span id="cb83-9">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Histogram Equalization"</span>)</span>
<span id="cb83-10">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb83-11">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb83-12">plt.imshow(crop_glare_reduced_and_inpainted[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">29</span>] , cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inferno"</span>)</span>
<span id="cb83-13">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Inpainting"</span>)</span>
<span id="cb83-14">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb83-15">plt.tight_layout()</span>
<span id="cb83-16">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-64-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>The best picture is the one without post-processing. Personally I like the histogram equalization most. The inpainting has to strong artifacts in the non glare parts. There is too much contrast on the parts of the image which were not affected by the glare. With more work this could certainly be improved.</p>
<p>Finally, my impression is that the LAION score is not good for our use case of food photography. The scores are too close together.</p>
</section>
</section>
<section id="other-methods" class="level2" data-number="7">
<h2 data-number="7" class="anchored" data-anchor-id="other-methods"><span class="header-section-number">7</span> Other methods</h2>
<section id="segmentation" class="level3" data-number="7.1">
<h3 data-number="7.1" class="anchored" data-anchor-id="segmentation"><span class="header-section-number">7.1</span> Segmentation</h3>
<p>When I brainstormed ideas, I considered using segmentation models. On of the most advanced segmentation models is (Segment Anything)[https://segment-anything.com/demo].</p>
<p>For a problematic image, the segmentation model gives the following result: <img src="https://www.storymelange.com/posts/projects/recipescanner/segmentation.jpg" class="img-fluid" alt="segmentation.png"></p>
<p>However, identifying the best crop would require significant post- processing. Assuming we always look for dishes, which is not necessarily the case, we could look for smooth large shapes.</p>
</section>
<section id="object-detection" class="level3" data-number="7.2">
<h3 data-number="7.2" class="anchored" data-anchor-id="object-detection"><span class="header-section-number">7.2</span> Object detection</h3>
<p>Bounding box object detection algorithms can, in theory, locate the plates quite well. The main drawback is that I would need to train such a detector myself, which requires a lot of labeled data.</p>
<p>While there are backbones such as YOLO, we would still require several hundreds of labeled images.</p>
<p>This could be a viable refinement once a significant number of images has been processed.</p>
</section>
<section id="direct-optimization" class="level3" data-number="7.3">
<h3 data-number="7.3" class="anchored" data-anchor-id="direct-optimization"><span class="header-section-number">7.3</span> Direct optimization</h3>
<p>Another possible approach is a brute-force optimization method. We would run an optimization algorithm that uses LAION to score the images. Based on the gradients we would vary the crop zone.</p>
<p>However, from my experiments with saliency-based images, the aesthetic score is somewhat subjective and not always intuitive. To make this approach effective, the scoring function would likely need to be reworked. While there is certainly room for experimentation here, this method would require more research and fine-tuning.</p>
</section>
</section>
<section id="summary" class="level2" data-number="8">
<h2 data-number="8" class="anchored" data-anchor-id="summary"><span class="header-section-number">8</span> Summary</h2>
<p>What did we learn?</p>
<p>We found that it is possible to generate better thumbnails using slightly more intelligent techniques. I used a multi-scale saliency algorithm to identify the dominant object in each image. This lead to a average score increase of 1.3%.</p>
<p>Additionally, glare reduction makes the pictures subjectively nicer, but it actually leads to a lower mean score.</p>
<p>This raises an interesting question: how should we score good-looking thumbnails? The LAION classifier can help slightly improve images, but in some cases, it actually prefers images with more glare.</p>
<div id="5f6704bc-8384-43bc-85dc-5476dfc445fe" class="cell" data-execution_count="67">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb84" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb84-1">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>))</span>
<span id="cb84-2"></span>
<span id="cb84-3">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb84-4">plt.imshow(to_pil(images_correct_orientation[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">29</span>]))</span>
<span id="cb84-5">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Center Crop"</span>)</span>
<span id="cb84-6">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb84-7">plt.subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb84-8">plt.imshow(crop_glare_reduced[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">29</span>] , cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inferno"</span>)</span>
<span id="cb84-9">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Saliency Map Crop with Glare Removal"</span>)</span>
<span id="cb84-10">plt.axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)</span>
<span id="cb84-11">plt.tight_layout()</span>
<span id="cb84-12">plt.savefig(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"best_thumbnail_method.jpg"</span>, dpi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>, bbox_inches<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tight"</span>)</span>
<span id="cb84-13">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method_files/figure-html/cell-65-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="bonus-section-case-2-recipes-without-images" class="level2" data-number="9">
<h2 data-number="9" class="anchored" data-anchor-id="bonus-section-case-2-recipes-without-images"><span class="header-section-number">9</span> Bonus Section: case 2 recipes without images</h2>
<p>What if we have no images at all. Then the only option is image generation.</p>
<p>However, this is computationally far more costly as the previous processing. And it does not seem to work that well.</p>
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/photo.jpg" width="600"></p>
<p><em>Real photo</em></p>
<p>With this prompt : <em>A bright, photorealistic cookbook-style photo of a freshly cooked Thai-style chicken stir-fry with cashews, beautifully plated on a white ceramic dish. The dish features tender, thinly sliced chicken thighs coated in a glossy, rich sauce made from oyster sauce, soy sauce, and fish sauce. Golden-brown roasted cashews scattered evenly, thin wedges of onion, vibrant green onion pieces, and delicate slices of red cayenne pepper for a pop of color. Served alongside a small bowl of perfectly steamed jasmine rice. The composition is clean and minimal, shot on a light wooden kitchen table with natural daylight. Soft, even lighting with gentle shadows, crisp textures, and realistic color tones. High-end food photography, cookbook aesthetic, ultra-HD.</em></p>
<p>Leads to this quite unrealistic picture from Chatgpt and FluxSchnell</p>
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/chatgpt.jpg" width="600"></p>
<p><em>ChatGPT</em></p>
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/fluxschnell.jpg" width="600"></p>
<p><em>Fluxschnell</em></p>
<p>Personally i find those less appealing than real photos, even though Flux Schnell comes at a much lower price tag.</p>
<p>Slighly better is Stable diffusion</p>
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/stablediffusion.jpg" width="600"></p>
<p><em>Stable Diffusion</em></p>
<p>Until one has cooked the recipe this is the only option to have a picture.</p>
<p>It would be interesting to see how the saliency map methods works on real pictures of the cooked food.</p>


</section>

 ]]></description>
  <category>Computer Vision</category>
  <category>Machine Learning</category>
  <category>Python</category>
  <guid>https://www.storymelange.com/posts/projects/recipescanner/thumbnail_optimization.html</guid>
  <pubDate>Fri, 05 Sep 2025 00:00:00 GMT</pubDate>
  <media:content url="https://www.storymelange.com/posts/projects/recipescanner/best_thumbnail_method.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>What I have been reading: What is a ml compiler</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/technical/what-i-have-been-reading-what-is-a-ml-compiler.html</link>
  <description><![CDATA[ 




<section id="what-is-a-ml-compiler" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="what-is-a-ml-compiler"><span class="header-section-number">1</span> What is a ml compiler?</h2>
<p>It all started with a big failure. I had bought a coral TPU with the intention to create a Webcam Software which modifies the users appereance. Something similar to <a href="https://avatarify.ai/.md">https://avatarify.ai/</a>.</p>
<p>This is not possible, as the coral TPU only supports a subset of TensorflowLite instructions. Probably a project down the line, to make a clear writeup of the findings and learnings.</p>
<p>I came across <a href="https://petewarden.com/2021/12/24/why-are-ml-compilers-so-hard/?utm_source=chatgpt.com">Pete Warden’s article</a>,and a few other resources, and I wanted to collect my thoughts and notes here.</p>
<p>This is not a deep dive into implementation details but rather an attempt to connect the dots on what ML compilers are, why they’re challenging, and where the ecosystem is headed.</p>
</section>
<section id="ml-compilers-aim-at-optimizing-model-execution" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="ml-compilers-aim-at-optimizing-model-execution"><span class="header-section-number">2</span> ML Compilers aim at optimizing model execution</h2>
<p>In frameworks like <strong>TensorFlow</strong> or <strong>PyTorch</strong>, ML models are represented as <strong>graphs</strong>—directed acyclic graphs (DAGs) of computations. These frameworks typically <strong>interpret</strong> the graph at runtime, similar to how Python interprets code line by line.</p>
<p>An <strong>ML compiler</strong> takes this model graph and <strong>optimizes it for performance and/or portability</strong>. nstead of executing the model exactly as defined, the compiler transforms the graph into a more efficient form or into a representation that can run on a wider range of devices (CPUs, GPUs, TPUs, edge hardware, etc.).</p>
<p>For example, <strong>XLA</strong> (Accelerated Linear Algebra) — TensorFlow’s compiler — takes the layers of a graph and converts them into <code>HLOs</code> (High-Level Operations). These HLOs form an <strong>intermediate representation (IR)</strong> that XLA can analyze and optimize before generating code for the target device.</p>
<p>The “high” in <strong>High-Level Operation</strong> refers either to the level of abstraction or to the fact that it sits at the top of XLA’s compilation pipeline.</p>
</section>
<section id="not-the-same-as-your-standard-compiler" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="not-the-same-as-your-standard-compiler"><span class="header-section-number">3</span> Not the same as your standard compiler</h2>
<p>For traditional software engineers, a <strong>compiler</strong> usually means something straightforward:</p>
<ul>
<li>Take a <strong>text file</strong> (e.g., C++ source code)</li>
<li>Turn it into a <strong>binary executable</strong></li>
<li>Run it directly on the target platform</li>
</ul>
<p>ML compilers, on the other hand, often <strong>don’t produce a final executable</strong>. Instead, they transform the model into <strong>another intermediate representation</strong>. In many cases, the “compiled” model is not ready to execute on its own. It requires further processing before running.</p>
<p>This can make the term <strong>“compiler”</strong> a bit misleading. It’s less like GCC and more like a pipeline of transformations where performance tuning, graph simplification, and device-specific optimizations happen in stages.</p>
</section>
<section id="early-stage-of-standardization" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="early-stage-of-standardization"><span class="header-section-number">4</span> Early stage of standardization</h2>
<p>Machine learning is experiencing the age of the the wild west. Everybody is defining their <strong>own functions, operators, and layers</strong>.Reuse does not exist.</p>
<p>Unlike C++—which has around <a href="https://www.fluentcpp.com/getthemap/?utm_source=chatgpt.com">60 keywords and ~105 STL algorithms</a>—there’s no common “vocabulary” for ML models.</p>
<p>Some Symptoms:</p>
<ul>
<li>Even small <strong>1% performance gains</strong> can lead teams to define <strong>new custom operators</strong>.</li>
<li>These operators may improve benchmark scores but <strong>hurt portability</strong>.</li>
<li>When it comes time to <strong>deploy models</strong> across devices, you quickly discover that <strong>many operations aren’t supported</strong> on certain hardware.</li>
</ul>
<p>What’s missing is a <strong>meta-language for layers</strong>—a standard abstraction layer that frameworks, compilers, and hardware vendors could agree on. Without this, interoperability remains painful.</p>
</section>
<section id="digging-deeper-high-level-irs-a-key-abstraction" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="digging-deeper-high-level-irs-a-key-abstraction"><span class="header-section-number">5</span> Digging Deeper High-Level IRs: A Key Abstraction</h2>
<p>A great explanation of this comes from <a href="https://uditagarwal.in/ml-compilers-part-1-high-level-intermediate-representation/">Udit Agarwal’s article</a>.</p>
<p>Unlike traditional compilers, where intermediate representations (IRs) are close to the hardware,“high-level IRs are hardware-agnostic and provides a much-needed abstraction”</p>
<p>These IRs provide:</p>
<ul>
<li>A <strong>unified representation</strong> of the model</li>
<li>A way to perform <strong>graph-level optimizations</strong></li>
<li>An abstraction layer that allows targeting multiple backends</li>
</ul>
<p>Because ML models are represented as <strong>DAGs</strong>, the IR captures both the operations (nodes) and the data dependencies (edges). These DAGs can be <strong>symbolic</strong> (fully defined before execution, like in TensorFlow 1.x) or <strong>imperative</strong> (built on the fly, like in PyTorch).</p>
</section>
<section id="graph-optimization-making-models-faster" class="level2" data-number="6">
<h2 data-number="6" class="anchored" data-anchor-id="graph-optimization-making-models-faster"><span class="header-section-number">6</span> Graph Optimization: Making Models Faster</h2>
<p>Once a model is converted into a graph, ML compilers apply a range of <strong>optimization techniques</strong>:</p>
<ul>
<li><strong>Operator fusion</strong> – Combine multiple layers into a single kernel</li>
<li><strong>Constant folding</strong> – Precompute values where possible</li>
<li><strong>Memory optimizations</strong> – Reuse buffers and reduce allocations</li>
<li><strong>Quantization</strong> – Use lower-precision arithmetic where safe</li>
<li>the side lists different optimization techniques</li>
</ul>
<p>These transformations can significantly improve performance on specialized hardware. If you want a deeper dive, check out another of Agarwal’s articles <a href="https://uditagarwal.in/ml-compilers-part-2-graph-optimizations/?utm_source=chatgpt.com">another of Agarwal’s articles</a></p>


</section>

 ]]></description>
  <category>C++</category>
  <category>Machine Learning</category>
  <category>Applied Engineering</category>
  <guid>https://www.storymelange.com/posts/technical/what-i-have-been-reading-what-is-a-ml-compiler.html</guid>
  <pubDate>Sun, 31 Aug 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Choosing the Right Metric for Classification Models</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/technical/choosing-the-right-metric-for-classification-models.html</link>
  <description><![CDATA[ 




<p>When evaluating machine learning models, accuracy is often the first metric that comes to mind. However, <strong>accuracy alone can be misleading</strong>, especially in cases where the dataset is imbalanced or when different types of misclassifications have different consequences. Choosing the right evaluation metric is crucial for ensuring that the model performs well in real-world applications.</p>
<section id="accuracy-is-best-for-balanced-datasets" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="accuracy-is-best-for-balanced-datasets"><span class="header-section-number">1</span> Accuracy is best for balanced datasets</h2>
<p>Accuracy measures the percentage of correctly classified instances in a dataset. It is calculated as:</p>
<p><img src="https://latex.codecogs.com/png.latex?Accuracy%20=%20%5Cfrac%7BTP%20+%20TN%7D%7BTP%20+%20TN%20+%20FP%20+%20FN%7D"></p>
<p>Where:</p>
<ul>
<li><strong>TP (True Positives)</strong> = Correctly predicted positives</li>
<li><strong>TN (True Negatives)</strong> = Correctly predicted negatives</li>
<li><strong>FP (False Positives)</strong> = Incorrectly predicted positives</li>
<li><strong>FN (False Negatives)</strong> = Incorrectly predicted negatives</li>
</ul>
<p>For a more detailed definition see, <a href="../../posts/technical/precisionrecall-vs-fntnfptp.html">Precision, Recall, and the Confusion Matrix</a>.</p>
<p>Accuracy works well when the dataset is <strong>balanced</strong> and the cost of false positives and false negatives is roughly the same.</p>
<p><strong>Example:</strong></p>
<p>In <strong>image classification</strong>, where we classify objects like “dog vs.&nbsp;cat” with roughly equal numbers of each class, accuracy is a reliable metric.</p>
<p><strong>Counter-Example:</strong></p>
<p>Imagine a fraud detection system where only <strong>1% of transactions</strong> are fraudulent. A naive model that predicts “non-fraud” for every transaction would be <strong>99% accurate</strong> but completely useless in identifying fraud.</p>
</section>
<section id="precision-when-false-positives-are-costly" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="precision-when-false-positives-are-costly"><span class="header-section-number">2</span> Precision, when false positives are costly</h2>
<p>Precision measures how many of the positive predictions are actually correct:</p>
<p><img src="https://latex.codecogs.com/png.latex?Precision%20=%20%5Cfrac%7BTP%7D%7BTP%20+%20FP%7D"></p>
<p>A high precision means <strong>fewer false positives</strong>, which is important when a false positive carries significant consequences.</p>
<p><strong>Example:</strong></p>
<ul>
<li><strong>Spam email filtering</strong> → Marking an important email as spam (false positive) can cause users to miss critical messages.</li>
<li><strong>Hiring decisions</strong> → Selecting the wrong candidate (false positive) could be costly for a company.</li>
</ul>
<p><strong>Counter-Example:</strong></p>
<p>If false negatives (missed positive cases) are more harmful, <strong>recall</strong> is the better metric.</p>
<hr>
</section>
<section id="recall-when-false-negatives-are-costly" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="recall-when-false-negatives-are-costly"><span class="header-section-number">3</span> Recall, when false negatives are costly</h2>
<p>Recall (also called <strong>sensitivity</strong> or <strong>true positive rate</strong>) measures how many actual positives are correctly identified:</p>
<p><img src="https://latex.codecogs.com/png.latex?Recall%20=%20%5Cfrac%7BTP%7D%7BTP%20+%20FN%7D"></p>
<p>A high recall means the model <strong>captures most actual positive cases</strong>, even if it produces some false positives.</p>
<p><strong>Example:</strong></p>
<ul>
<li><strong>Cancer detection</strong> → A false negative (failing to detect cancer) is much worse than a false positive (a healthy person being sent for more tests).</li>
<li><strong>Fraud detection</strong> → Missing a fraudulent transaction is riskier than investigating a few false alarms.</li>
</ul>
<p><strong>Counter-Example:</strong></p>
<p>If false positives are expensive or disruptive, <strong>precision</strong> is the better metric.</p>
<hr>
</section>
<section id="f1-score-when-you-need-a-balance" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="f1-score-when-you-need-a-balance"><span class="header-section-number">4</span> F1-Score, when you need a balance</h2>
<p>F1-score is the <strong>harmonic mean</strong> of precision and recall:</p>
<p><img src="https://latex.codecogs.com/png.latex?F1%20=%202%20%5Ctimes%20%5Cfrac%7B%5Ctext%7BPrecision%7D%20%5Ctimes%20%5Ctext%7BRecall%7D%7D%7B%5Ctext%7BPrecision%7D%20+%20%5Ctext%7BRecall%7D%7D"></p>
<p>F1-score is particularly useful in cases where the dataset is <strong>imbalanced</strong>, and both false positives and false negatives matter.</p>
<p><strong>Example:</strong></p>
<ul>
<li><strong>Fake news detection</strong> → You need to both <strong>catch fake news (recall)</strong> and <strong>avoid falsely labeling real news as fake (precision)</strong>.</li>
<li><strong>Medical diagnostics</strong> → It’s important to minimize both <strong>missed diagnoses (FN)</strong> and <strong>false alarms (FP)</strong>.</li>
</ul>
<p><strong>Counter-Example:</strong></p>
<p>If the dataset is balanced and errors are equally costly, <strong>accuracy</strong> is often sufficient.</p>
</section>
<section id="auc-roc-when-you-need-to-rank-predictions" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="auc-roc-when-you-need-to-rank-predictions"><span class="header-section-number">5</span> AUC-ROC, when you need to rank predictions</h2>
<p>AUC-ROC (Area Under the Receiver Operating Characteristic Curve) measures a model’s ability to <strong>distinguish between classes</strong> at different thresholds.</p>
<p>The ROC curve plots:</p>
<ul>
<li><strong>True Positive Rate (Recall)</strong> vs.&nbsp;<strong>False Positive Rate</strong></li>
<li>AUC (Area Under Curve) <strong>closer to 1</strong> means better classification performance.</li>
</ul>
<p><strong>Example:</strong></p>
<ul>
<li><strong>Credit risk assessment</strong> → Banks rank loan applicants from “low risk” to “high risk” rather than making a strict yes/no decision.</li>
<li><strong>Medical triage systems</strong> → Doctors prioritize high-risk patients based on a ranking rather than a strict diagnosis.</li>
</ul>
<p><strong>Counter-Example:</strong></p>
<p>AUC-ROC is great for ranking, but for specific misclassification penalties, <strong>precision, recall, or F1-score</strong> might be better.</p>
</section>
<section id="decision-graph" class="level2" data-number="6">
<h2 data-number="6" class="anchored" data-anchor-id="decision-graph"><span class="header-section-number">6</span> Decision Graph</h2>
<p>I came up with a simple decision graph</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">flowchart TD

A[Start] --&gt; B{Dataset balanced?}

B -- Yes --&gt; C[Use Accuracy]

B -- No --&gt; D{What matters more?}

D -- Balance FP &amp; FN --&gt; E[F1-score]

D -- Avoid False Positives --&gt; F[Precision]

D -- Avoid False Negatives --&gt; G[Recall]

C --&gt; H{Need ranking?}

E --&gt; H

F --&gt; H

G --&gt; H

H -- Yes --&gt; I[AUC-ROC]

H -- No --&gt; J[Done]
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<table class="caption-top table">
<colgroup>
<col style="width: 36%">
<col style="width: 15%">
<col style="width: 47%">
</colgroup>
<thead>
<tr class="header">
<th><strong>Scenario</strong></th>
<th><strong>Best Metric</strong></th>
<th><strong>Why?</strong></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Balanced dataset</strong></td>
<td><strong>Accuracy</strong></td>
<td>Errors are equally important.</td>
</tr>
<tr class="even">
<td><strong>Imbalanced dataset</strong></td>
<td><strong>F1-score</strong></td>
<td>Balances false positives &amp; false negatives.</td>
</tr>
<tr class="odd">
<td><strong>False positives are costly</strong></td>
<td><strong>Precision</strong></td>
<td>Avoids unnecessary alarms.</td>
</tr>
<tr class="even">
<td><strong>False negatives are costly</strong></td>
<td><strong>Recall</strong></td>
<td>Ensures we catch as many positives as possible.</td>
</tr>
<tr class="odd">
<td><strong>Need ranking, not classification</strong></td>
<td><strong>AUC-ROC</strong></td>
<td>Measures how well the model separates classes.</td>
</tr>
</tbody>
</table>
</section>
<section id="final-thoughts" class="level2" data-number="7">
<h2 data-number="7" class="anchored" data-anchor-id="final-thoughts"><span class="header-section-number">7</span> <strong>Final Thoughts</strong></h2>
<p>Choosing the right metric is <strong>critical</strong> to building a model that truly performs well in its intended application. Instead of blindly relying on accuracy, always consider:</p>
<ul>
<li><strong>Is the dataset balanced or imbalanced?</strong></li>
<li><strong>Is it worse to have a false positive or a false negative?</strong></li>
<li><strong>Are you making a hard classification or ranking predictions?</strong></li>
</ul>
<p>By aligning the evaluation metric with your real-world goals, you’ll ensure that your model delivers meaningful and impactful results.</p>


</section>

 ]]></description>
  <category>Machine Learning</category>
  <category>Data Science</category>
  <guid>https://www.storymelange.com/posts/technical/choosing-the-right-metric-for-classification-models.html</guid>
  <pubDate>Fri, 29 Aug 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Avoiding Python version chaos in ML</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/technical/avoiding-python-version-chaos-in-ml.html</link>
  <description><![CDATA[ 




<section id="frequently-changing-projects" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="frequently-changing-projects"><span class="header-section-number">1</span> Frequently changing projects</h2>
<p>When I started with my first machine learning (ML) project in 2020 it naively tried to install <code>cuda</code> on my pc. It took me a day. There were multiple incompatible libraries and difficult to install packages.</p>
<p>Even recently, another issue arose, when switching between projects quickly. A bare-metal installation is not practical in this setup. It gets messy fast — especially when one project needs Python 3.10 with TensorFlow 2.15 + GPU, and another wants 3.12 with different dependencies.</p>
<p>Thankfully, Docker solves all of that.</p>
<section id="how-is-docker-particularly-useful-for-ml-dev" class="level3" data-number="1.1">
<h3 data-number="1.1" class="anchored" data-anchor-id="how-is-docker-particularly-useful-for-ml-dev"><span class="header-section-number">1.1</span> How is Docker particularly useful for ML Dev?</h3>
<p>Docker lets you isolate your dev environment per project, without affecting your system Python. This also can be done via a virtual environment. However, once you need another base python version, you still need to change your system.</p>
<p>That means you can use <strong>any Python version</strong> inside the container, e.g., Python 3.10 even if your host has 3.12.</p>
<p>You can install <code>TensorFlow</code>, <code>PyTorch</code> as well as <code>CUDA</code> with NVIDIA containers without polluting your system.</p>
</section>
</section>
<section id="quick-setup-for-ml-dev" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="quick-setup-for-ml-dev"><span class="header-section-number">2</span> Quick Setup for ML Dev</h2>
<p><strong>Dockerfile (GPU + TensorFlow + Keras):</strong></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode dockerfile code-with-copy"><code class="sourceCode dockerfile"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">FROM</span> tensorflow/tensorflow:2.15.0-gpu</span>
<span id="cb1-2"></span>
<span id="cb1-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">WORKDIR</span> /app</span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">COPY</span> requirements.txt .</span>
<span id="cb1-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">RUN</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">pip</span> install <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--no-cache-dir</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-r</span> requirements.txt</span>
<span id="cb1-7"></span>
<span id="cb1-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">CMD</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bash"</span>]</span></code></pre></div></div>
<p><strong>docker-compose.yml (GPU enabled):</strong></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">version</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.8"</span></span>
<span id="cb2-2"></span>
<span id="cb2-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">services</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb2-4"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">keras-dev</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb2-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">build</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> .</span></span>
<span id="cb2-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">image</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> keras-dev</span></span>
<span id="cb2-7"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">volumes</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb2-8"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> .:/app</span></span>
<span id="cb2-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> /your/local/data:/mnt/storage</span></span>
<span id="cb2-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runtime</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> nvidia</span></span>
<span id="cb2-11"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">environment</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb2-12"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> NVIDIA_VISIBLE_DEVICES=all</span></span>
<span id="cb2-13"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tty</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">true</span></span></code></pre></div></div>
<p>Build and run:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">docker-compose</span> up <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--build</span></span></code></pre></div></div>
</section>
<section id="ide-integration-using-in-pycharm-pro" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="ide-integration-using-in-pycharm-pro"><span class="header-section-number">3</span> IDE Integration, Using in PyCharm (Pro)</h2>
<ol type="1">
<li>Add Docker-Compose interpreter</li>
<li>Point to your <code>docker-compose.yml</code></li>
<li>Select the <code>keras-dev</code> service</li>
<li>Use <code>/usr/local/bin/python</code> as the interpreter path</li>
<li>Enable GPU with NVIDIA Container Toolkit</li>
</ol>
<p>Full dev environment with terminal, debugging, and Python completion — inside the container.</p>
<hr>
<section id="bonus-one-time-setup-for-gpu-access" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="bonus-one-time-setup-for-gpu-access"><span class="header-section-number">3.1</span> Bonus: One-Time Setup for GPU Access</h3>
<p><strong>Install NVIDIA Container Toolkit:</strong></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb4-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sudo</span> apt install nvidia-container-toolkit</span>
<span id="cb4-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sudo</span> nvidia-ctk runtime configure <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--runtime</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>docker</span>
<span id="cb4-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sudo</span> systemctl restart docker</span></code></pre></div></div>
<p><strong>Allow docker without sudo:</strong></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb5-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sudo</span> usermod <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-aG</span> docker <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">$USER</span></span>
<span id="cb5-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">newgrp</span> docker</span></code></pre></div></div>


</section>
</section>

 ]]></description>
  <category>Machine Learning</category>
  <category>Software Engineering</category>
  <category>Python</category>
  <guid>https://www.storymelange.com/posts/technical/avoiding-python-version-chaos-in-ml.html</guid>
  <pubDate>Thu, 28 Aug 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>How Neural Networks Hear Music</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/deejai/deejai-xai.html</link>
  <description><![CDATA[ 




<section id="playing-dj" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="playing-dj"><span class="header-section-number">1</span> Playing DJ</h2>
<p>I recently got to play DJ at a private party. Usually, this involves endless hours of listening through songs. You then try to figure out what track fits best where, how to build energy, and what to avoid. It is like a radio DJ with a static playlist. Creating a static playlist that matches the vibe at different times throughout the night can be tough work.</p>
<p>But now we have AI. Everything is soo easy.</p>
<p>That was my state of mind, when I started with <a href="https://github.com/teticio/Deej-AI">Deej-AI</a>.</p>
<p>My idea was simple: tell the AI what music I like and let it handle the playlist. With clear instructions provided by the creator in the repository, I anticipated having my perfect playlist ready in no time.</p>
<section id="playlist-creation-with-deej-ai" class="level3" data-number="1.1">
<h3 data-number="1.1" class="anchored" data-anchor-id="playlist-creation-with-deej-ai"><span class="header-section-number">1.1</span> Playlist creation with Deej-AI</h3>
<p>I started by selecting a few hundred songs I love. I did not care much about the order or proportion of style, hoping the software would seamlessly fill in the gaps. Running the software quickly generated playlists, which looked okayish at a first glance. Looking deeper, imperfections began to show. As I preferred no song repetitions, the playlist noticeably deteriorated towards the end when the algorithm ran out of optimal matches.</p>
<p>This highlighted a crucial issue of Deej-AI: the lack of global optimization. Deej-AI could suggest suitable songs individually but struggled to maintain consistency and match the overall mood progression throughout the evening. Think of a good mixtape or a carefully curated DJ playlist. The AI creation was the opposite.</p>
<p>Respecting different times of day and specific moods was impossible due to the absence of a robust global layout editor. Even though the software offered gap-filling functionality, it still required explicit instructions about what was missing. In the end, creating a truly seamless playlist still required significant manual effort.</p>
</section>
<section id="why-did-the-computer-pick-song-a-over-song-b" class="level3" data-number="1.2">
<h3 data-number="1.2" class="anchored" data-anchor-id="why-did-the-computer-pick-song-a-over-song-b"><span class="header-section-number">1.2</span> Why did the computer pick song A over song B?</h3>
<p>Despite the lack of features, the picks sometimes pleasantly surprised me; sometimes just surprised. This curiosity led me deeper: why exactly was one song selected over another?</p>
<p>In this article, we’ll explore these choices through three lenses:</p>
<p>We will examine our data at three different scales</p>
<ul>
<li><p><strong>Macro-level</strong> with t-SNE visualization: to reveal groups of songs and overall patterns in the playlist.</p></li>
<li><p><strong>Meso-level</strong> with Grad-CAM: highlighting crucial parts of audio spectrograms that influenced song selection.</p></li>
<li><p><strong>Micro-level</strong> with Integrated Gradients: examining the precise contribution of individual audio features.</p></li>
</ul>
<p>By dissecting these layers of explainability, I’ll show how your favourite music app works on auto-listening. I hope this is not only valuable for developers, but anybody wondering about why he often ends up with mainstream music on YouTube .</p>
</section>
</section>
<section id="music-just-another-form-of-data" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="music-just-another-form-of-data"><span class="header-section-number">2</span> Music, just another form of Data</h2>
<p>Before we dive into the tools, let’s first clarify what our data looks like. In the following, we look at metadata, audio and embeddings.</p>
<section id="theme-metadata" class="level3" data-number="2.1">
<h3 data-number="2.1" class="anchored" data-anchor-id="theme-metadata"><span class="header-section-number">2.1</span> Theme metadata</h3>
<p>To help the tool generate better playlists, I divided the day into two distinct segments: a calm part and a more energetic, danceable part. We’ll store this information as metadata and revisit it later in our analysis.</p>
<p>We note which song is in which sublist, as we will require this later.</p>
<div id="d75ddac5bdba3863" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:39.879608Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:39.873814Z&quot;}}" data-execution_count="33">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> csv</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pathlib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Path</span>
<span id="cb1-3"></span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-5"></span>
<span id="cb1-6"></span>
<span id="cb1-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_manifest():</span>
<span id="cb1-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/app/data/raw-previews/explainabletrack_manifest.csv"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"w"</span>, newline<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">''</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb1-9">        writer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> csv.writer(f)</span>
<span id="cb1-10">        writer.writerow([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"filename"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theme"</span>])</span>
<span id="cb1-11"></span>
<span id="cb1-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> theme_dir <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> Path(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/app/data/raw-previews/separate"</span>).iterdir():</span>
<span id="cb1-13">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> theme_dir.is_dir():</span>
<span id="cb1-14">                theme <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> theme_dir.name</span>
<span id="cb1-15">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> audio_file <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> theme_dir.glob(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"*.mp3"</span>):</span>
<span id="cb1-16">                    writer.writerow([audio_file.name, theme])</span></code></pre></div></div>
</details>
</div>
<div id="fc1a42e2de617f8f" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:39.937258Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:39.934438Z&quot;}}" data-execution_count="34">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">create_manifest()</span></code></pre></div></div>
</div>
<p>We now have a table with data, also called tabular data. Your music provider has much bigger tables with a lot more columns (genre, speed, mood, …). For simplicity, we restrict ourselves. Let’s look at the data.</p>
<div id="2ef0ae3438d96111" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:40.021036Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:40.013321Z&quot;}}" data-execution_count="35">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">manifest <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_csv(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/app/data/raw-previews/explainabletrack_manifest.csv"</span>)</span>
<span id="cb3-2">manifest.head()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="35">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">filename</th>
<th data-quarto-table-cell-role="th">theme</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>With Or Without You - U2.mp3</td>
<td>ruhig</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>La javanaise - Serge Gainsbourg.mp3</td>
<td>ruhig</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>Djadja - Aya Nakamura.mp3</td>
<td>ruhig</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>Le chant des sirènes - Fréro Delavega.mp3</td>
<td>ruhig</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">4</th>
<td>start.mp3</td>
<td>ruhig</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>And recheck the count in the two categories.</p>
<div id="8dc76dbfbaa2cfac" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:40.792455Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:40.788886Z&quot;}}" data-execution_count="36">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">manifest.theme.value_counts()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="36">
<pre><code>theme
party    129
ruhig    116
Name: count, dtype: int64</code></pre>
</div>
</div>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Paths in this notebook
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>I use a dockerized version of Deej-Ai, which can be found on my GitHub. Therefore, paths are inside the docker, this is why paths sometimes start with <code>/app</code> and sometimes with <code>/opt</code>.</p>
</div>
</div>
</div>
</section>
<section id="audio-data" class="level3" data-number="2.2">
<h3 data-number="2.2" class="anchored" data-anchor-id="audio-data"><span class="header-section-number">2.2</span> Audio data</h3>
<p>We are going to study sound signals. Sound is usually analyzed with the help of a spectrogram. While a lot more complex models exist, spectrogram can be just processed as images. This allows us to a simple classification analysis with something as simple as <code>Resnet</code> model.</p>
<p>The following picture shows a spectrogram. On the x-axis is the time. The y-axis shows the frequencies. The color is the amplitude of the wave form at this frequency and time.</p>
<div id="1977779fc79fc42c" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:42.322982Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:41.951851Z&quot;}}" data-execution_count="37">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> librosa</span>
<span id="cb6-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> librosa.display</span>
<span id="cb6-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb6-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb6-5"></span>
<span id="cb6-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Load audio</span></span>
<span id="cb6-7">filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/app/data/raw-previews/combined/Purple Rain - Prince.mp3'</span></span>
<span id="cb6-8">y, sr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> librosa.load(filename, sr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22050</span>)</span>
<span id="cb6-9"></span>
<span id="cb6-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Create log-Mel spectrogram, this converts the waveform into a picture</span></span>
<span id="cb6-11">n_fft <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2048</span></span>
<span id="cb6-12">hop_length <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span></span>
<span id="cb6-13">n_mels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">96</span></span>
<span id="cb6-14"></span>
<span id="cb6-15">S <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> librosa.feature.melspectrogram(y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y, sr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sr, n_fft<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_fft,</span>
<span id="cb6-16">                                   hop_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>hop_length, n_mels<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_mels)</span>
<span id="cb6-17">log_S <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> librosa.power_to_db(S, ref<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>)</span>
<span id="cb6-18"></span>
<span id="cb6-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># normalize the spectogram for further processing</span></span>
<span id="cb6-20">log_S <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (log_S <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(log_S)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(log_S) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(log_S))</span>
<span id="cb6-21"></span>
<span id="cb6-22">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb6-23">librosa.display.specshow(log_S, sr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sr, hop_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>hop_length,</span>
<span id="cb6-24">                         x_axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'time'</span>, y_axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mel'</span>)</span>
<span id="cb6-25">plt.colorbar(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">format</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'%+2.0f dB'</span>)</span>
<span id="cb6-26">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Log-Mel Spectrogram"</span>)</span>
<span id="cb6-27">plt.tight_layout()</span>
<span id="cb6-28">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-6-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<section id="slicing-images" class="level4" data-number="2.2.1">
<h4 data-number="2.2.1" class="anchored" data-anchor-id="slicing-images"><span class="header-section-number">2.2.1</span> Slicing images</h4>
<p>We use spectrogram images to classify the songs. The procedure is identical to your favourite bear or chesse classifier. However, classifying the full spectrogram of one song as a whole is often not very helpful. The songs are usually defined by local features. We either need a more complex model than a CNN, or we reduce the data the CNN sees. In practice, the latter option means we are going to slice the image.</p>
<p>For the study, we use spotify track previews. They usually provide a good sample of the track itself. A more comprehensive analysis would study the whole track and respect intra-track variation.</p>
<p>Let’s slice a track.</p>
<div id="3b53a9f17bff8a1" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:43.260650Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:43.255721Z&quot;}}" data-execution_count="38">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> slice_image(slice_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">216</span>, stride<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">216</span>):</span>
<span id="cb7-2">    slices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb7-3">    starts_sec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb7-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> start <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, log_S.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> slice_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, stride):</span>
<span id="cb7-5">        end <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> start <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> slice_size</span>
<span id="cb7-6">        slices.append(log_S[:, start:end])</span>
<span id="cb7-7">        start_sec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> start <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> hop_length <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sr</span>
<span id="cb7-8">        end_sec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> end <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> hop_length <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sr</span>
<span id="cb7-9">        starts_sec.append((start_sec, end_sec))</span>
<span id="cb7-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> slices, starts_sec</span>
<span id="cb7-11"></span>
<span id="cb7-12">slices, starts_sec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> slice_image()</span>
<span id="cb7-13"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Number of slices"</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(slices))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Number of slices 5</code></pre>
</div>
</div>
<p>Let’s create a side-by-side view of full spectrogram and slices</p>
<div id="86661be6ea1a991b" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:44.254861Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:43.823012Z&quot;}}" data-execution_count="39">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">num_slices_to_show <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb9-2">fig, axs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>), gridspec_kw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'height_ratios'</span>: [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]}, sharex<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb9-3"></span>
<span id="cb9-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">## Plot full spectrogram</span></span>
<span id="cb9-5">librosa.display.specshow(log_S, sr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sr, hop_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>hop_length,</span>
<span id="cb9-6">                         x_axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'time'</span>, y_axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mel'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb9-7">axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Full Log-Mel Spectrogram"</span>)</span>
<span id="cb9-8">axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mel bin"</span>)</span>
<span id="cb9-9"></span>
<span id="cb9-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Overlay slices</span></span>
<span id="cb9-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(num_slices_to_show, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(slices))):</span>
<span id="cb9-12">    start, end <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> starts_sec[i]</span>
<span id="cb9-13">    axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].axvspan(start, end, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span>, facecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'none'</span>, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'--'</span>)</span>
<span id="cb9-14"></span>
<span id="cb9-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Slice image</span></span>
<span id="cb9-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">## Slices stitched together horizontally, padded to full time width</span></span>
<span id="cb9-17">slice_canvas <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros_like(log_S) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.nan  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># fill with NaNs</span></span>
<span id="cb9-18"></span>
<span id="cb9-19"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(num_slices_to_show, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(slices))):</span>
<span id="cb9-20">    start_frame <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(starts_sec[i][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> hop_length)</span>
<span id="cb9-21">    slice_data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> slices[i]</span>
<span id="cb9-22">    slice_canvas[:, start_frame:start_frame <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> slice_data.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> slice_data</span>
<span id="cb9-23"></span>
<span id="cb9-24">librosa.display.specshow(slice_canvas, sr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sr, hop_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>hop_length,</span>
<span id="cb9-25">                         x_axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'time'</span>, y_axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mel'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb9-26"></span>
<span id="cb9-27"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(num_slices_to_show, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(slices))):</span>
<span id="cb9-28">    start, end <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> starts_sec[i]</span>
<span id="cb9-29">    axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].axvspan(start, end, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span>, facecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'none'</span>, lw<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'--'</span>)</span>
<span id="cb9-30"></span>
<span id="cb9-31">axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>num_slices_to_show<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> Aligned Slices (padded to full duration)"</span>)</span>
<span id="cb9-32">axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mel bin"</span>)</span>
<span id="cb9-33"></span>
<span id="cb9-34">plt.tight_layout()</span>
<span id="cb9-35">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-8-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Finally, let’s define a function for slicing which we will be using later.</p>
<div id="d9e8faf89406a8cb" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:44.483227Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:44.474435Z&quot;}}" data-execution_count="40">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> mp3_to_slices(path):</span>
<span id="cb10-2">    N_MELS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">96</span></span>
<span id="cb10-3">    SLICE_SIZE <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">216</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># must match model input</span></span>
<span id="cb10-4">    y, sr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> librosa.load(path, sr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22050</span>)</span>
<span id="cb10-5">    S <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> librosa.feature.melspectrogram(y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y, sr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22050</span>, n_fft<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2048</span>,</span>
<span id="cb10-6">                                       hop_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span>, n_mels<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>N_MELS, fmax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb10-7">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.ndarray(shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(S.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> SLICE_SIZE, N_MELS, SLICE_SIZE, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb10-8"></span>
<span id="cb10-9">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># we use the original code to get the same input batch size</span></span>
<span id="cb10-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">slice</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(S.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> SLICE_SIZE):</span>
<span id="cb10-11">        log_S <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> librosa.power_to_db(S[:, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">slice</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> SLICE_SIZE: (<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">slice</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> SLICE_SIZE], ref<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>)</span>
<span id="cb10-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(log_S) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(log_S) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb10-13">            log_S <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (log_S <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(log_S)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(log_S) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(log_S))</span>
<span id="cb10-14">        x[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">slice</span>, :, :, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> log_S</span>
<span id="cb10-15"></span>
<span id="cb10-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> x</span></code></pre></div></div>
</div>
</section>
</section>
<section id="embeddings" class="level3" data-number="2.3">
<h3 data-number="2.3" class="anchored" data-anchor-id="embeddings"><span class="header-section-number">2.3</span> Embeddings</h3>
<p>Instead of working with the spectrogram images in the model, the author of Deej-AI has done something a little bit more complex. He was not interested in knowing which song sounds similar to another, but which songs are usually played together. From this knowledge, he inferred that similar sounding new songs could be also played together with songs in the database.</p>
<p>The understanding of song lyrics and context is implicit in the playlists.</p>
<p>He therefore first encoded many playlists and then matched the spectrograms against this in another training.</p>
<p>The complete Training Inference Pipeline can be visualized like this.</p>
<div class="cell" data-fig-width="3.5" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">---
format:
  html:
    mermaid:
      theme: neutral
---
flowchart TB
  %% === Training #1: Track2Vec ===
  subgraph T1[Training #1: Track2Vec]
    A1[Audio Files] --&gt; |Organize| B1[Playlists]
    B1 --&gt; |Train Track2Vec| C[100D Embeddings]
  end


  %% === Training #2: Mp3ToVec ===
  subgraph T2[Training #2: Mp3ToVec]
    D1[Audio Files] --&gt;|Convert &amp; Slice| E1[Log-Mel Spectrograms]
    C --&gt; |Use| F1[Embeddings as Labels]
    E1 --&gt;  E2[Training Input]
    F1 --&gt;  E2[Training Input]
    E2 --&gt; |Train with Cosine Similarity Loss| G1[CNN with 100D Output]
  end

  %% === Inference ===
  subgraph INF[Inference]
    I1[Audio Files] --&gt; |Convert &amp; Slice| I2[Log-Mel Spectrograms]
    G1 --&gt; |Use| I3[Inference Model]
    I2 --&gt; I4[Inference Input]
    I3 --&gt; I4[Inference Input]
    I4 --&gt; |run model| I5[100D Embeddings]
    I6[Query Idx] --&gt; |Cosine Similarity to Find Similar Songs To Query| I7[Best Next Song]
    I5 --&gt; I6
  end

    subgraph t[Training]
        T1
        T2

    end
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<p>Instead of using strings as <code>Labels</code>, the embeddings from the Spotify playlist-based Training act as such. Therefore, it is better to speak of dependent variable <img src="https://latex.codecogs.com/png.latex?y">. Our labels have the dimension of 100. The second network is a standard classification.</p>
<p>During inference, the predicted output for every spectrogram is a 100D vector. The spectrogram acts as features <img src="https://latex.codecogs.com/png.latex?X_%7Binf%7D">. In a final step, we rank songs by the best fit to our query.</p>
<p>To answer our questions “Why was song A chosen?” we only need to analyze the inference related to training #2.</p>
<p>We already had a look at <img src="https://latex.codecogs.com/png.latex?X">. Now let’s look at the dependent variable <img src="https://latex.codecogs.com/png.latex?y">.</p>
</section>
</section>
<section id="t-sne-for-high-dimensionality-data." class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="t-sne-for-high-dimensionality-data."><span class="header-section-number">3</span> T-SNE for high dimensionality data.</h2>
<p>We are interested in visualizing our labels. I ran the embedding creation in <code>Deej-Ai</code> with <code>MP3ToVec</code>. This is done via <code>model.predict(x)</code>. Where <img src="https://latex.codecogs.com/png.latex?x"> are the slices we defined earlier. The data was then stored.</p>
<div id="24e45a46f37dcb09" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:44.668989Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:44.663985Z&quot;}}" data-execution_count="41">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pickle</span>
<span id="cb11-2"></span>
<span id="cb11-3">filenames <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/opt/project/data/raw-previews/combined/'</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> f <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> f <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> manifest[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'filename'</span>]]</span>
<span id="cb11-4"></span>
<span id="cb11-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/app/data/pickles/combined/mp3tovecs/mp3tovec.p"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rb"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb11-6">    mp3tovecs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pickle.load(f)</span>
<span id="cb11-7"></span>
<span id="cb11-8">X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.vstack([mp3tovecs[f] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> f <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> filenames <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> f <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> mp3tovecs])</span></code></pre></div></div>
</div>
<p>The issue, the data is of the form 100D for each file. How to visualize this. A straightforward approach would be a matrix plot.</p>
<div id="9bc111d516aa2d7e" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:44.966470Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:44.792385Z&quot;}}" data-execution_count="42">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb12-2">plt.imshow(X, cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'viridis'</span>)</span>
<span id="cb12-3">plt.colorbar()</span>
<span id="cb12-4">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Embedded Vectors Visualization"</span>)</span>
<span id="cb12-5">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Song Index"</span>)</span>
<span id="cb12-6">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Embedded Vector"</span>)</span>
<span id="cb12-7">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-11-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>From this we can actually not see much. Only that many dimensions are characteristic in their value (vertical lines)</p>
<p>We need to reduce the dimensions to plot this data in a scatter plot. T-distributed stochastic neighbor embedding (TNSE) is a popular dimensionality reduction technique. You can read more on <a href="https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding">wikipedia</a>. But as with any complex method, there are some caveats. A nice article about the limitations is in <a href="https://distill.pub/2016/misread-tsne/">distill.pub</a>.</p>
<section id="t-sne-limitations-tldr" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="t-sne-limitations-tldr"><span class="header-section-number">3.1</span> T-SNE Limitations TL;DR;</h3>
<ul>
<li>Distances are not reliable: Global structure is often distorted; distances between clusters are meaningless.</li>
<li>Cluster sizes are misleading: Size/shape doesn’t reflect actual data density or variance.</li>
<li>Clusters can be artifacts: t-SNE can create apparent groupings even from random data.</li>
<li>Sensitive to hyperparameters: Perplexity, learning rate, and iterations drastically affect results.</li>
<li>Non-deterministic: Results vary with different random seeds; always run multiple times.</li>
<li>No generalization: Can’t project new data without retraining (non-parametric).</li>
<li>Slow on large datasets: Scales poorly; approximations or UMAP may be better.</li>
</ul>
</section>
<section id="t-sne-best-practice-tldr" class="level3" data-number="3.2">
<h3 data-number="3.2" class="anchored" data-anchor-id="t-sne-best-practice-tldr"><span class="header-section-number">3.2</span> T-SNE Best Practice TL;DR;</h3>
<ul>
<li>Tune parameters carefully.</li>
<li>Run multiple times to check stability.</li>
<li>Don’t trust distances, cluster sizes, or shapes.</li>
<li>Use it for exploration, not clustering or quantification.</li>
<li>Compare with PCA, UMAP, or other embeddings.</li>
</ul>
<p>In short, the main issue is the sensitive to the hyperparameters. A recent paper, <a href="https://www.sciencedirect.com/science/article/pii/S2468502X22000201">Gove et al.&nbsp;2022</a>, came up with a comprehensive study. In contrast to a previous study <a href="https://www.sciencedirect.com/science/article/pii/S2468502X22000201#b19">Kobak and Berens, 2019</a>, the authors found no dependence on the size of the dataset (previously 1% of dataset size). The previous results translate to perplexity of 2.5. This means any point is just influenced by 2 other points. This often overstressed the local structure. Instead, we focus on the newer <code>magic recipe</code>.</p>
</section>
<section id="the-magic-recipe" class="level3" data-number="3.3">
<h3 data-number="3.3" class="anchored" data-anchor-id="the-magic-recipe"><span class="header-section-number">3.3</span> The magic recipe</h3>
<p>Here is a summary of the findings:</p>
<p>Begin with</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1">perplexity <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span></span>
<span id="cb13-2">learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb13-3">exaggeration <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb13-4">iters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Above 1000 iters low variation</span></span></code></pre></div></div>
<p>Then tune by visual inspection</p>
<ul>
<li>Blobs? → raise exaggeration to 3–4.</li>
<li>Lost global shape? → double learning-rate or bump perplexity (never past 16).</li>
<li>Over-compressed? → lower exaggeration or learning-rate.</li>
</ul>
<p>Big data (≫20 k points): try perplexity ≈ n/100 and lr ≈ n/12.</p>
</section>
<section id="t-sne-for-the-playlist-data" class="level3" data-number="3.4">
<h3 data-number="3.4" class="anchored" data-anchor-id="t-sne-for-the-playlist-data"><span class="header-section-number">3.4</span> T-SNE for the playlist data</h3>
<p>Let’s apply these findings to our data. To check the stability of the result, we treat this as a convergence issue and write a function that checks the solution for stability.</p>
<div id="37a8e7e302a847e3" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:51:45.152725Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:45.145831Z&quot;}}" data-execution_count="43">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.manifold <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> TSNE</span>
<span id="cb14-2"></span>
<span id="cb14-3"></span>
<span id="cb14-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> tsne_until_converged(</span>
<span id="cb14-5">        X,</span>
<span id="cb14-6">        step_iter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">250</span>,</span>
<span id="cb14-7">        max_iter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>,</span>
<span id="cb14-8">        tol<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span>,</span>
<span id="cb14-9">        random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>,</span>
<span id="cb14-10">        verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb14-11">        perplexity<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,</span>
<span id="cb14-12">        learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb14-13">        exaggeration<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb14-14">):</span>
<span id="cb14-15">    n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb14-16"></span>
<span id="cb14-17">    common <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>(</span>
<span id="cb14-18">        n_components<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb14-19">        perplexity<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>perplexity,</span>
<span id="cb14-20">        learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>learning_rate,</span>
<span id="cb14-21">        early_exaggeration<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>exaggeration,</span>
<span id="cb14-22">        init<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pca"</span>,</span>
<span id="cb14-23">        random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>random_state,</span>
<span id="cb14-24">        verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>,</span>
<span id="cb14-25">    )</span>
<span id="cb14-26"></span>
<span id="cb14-27">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># we always start at 250</span></span>
<span id="cb14-28">    total_iter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">250</span></span>
<span id="cb14-29">    tsne <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TSNE(max_iter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>total_iter, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>common)</span>
<span id="cb14-30">    Y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tsne.fit_transform(X)</span>
<span id="cb14-31"></span>
<span id="cb14-32">    history <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb14-33">    prev <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Y.copy()</span>
<span id="cb14-34"></span>
<span id="cb14-35">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span> total_iter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> max_iter:</span>
<span id="cb14-36">        total_iter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> step_iter</span>
<span id="cb14-37">        tsne <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TSNE(</span>
<span id="cb14-38">            max_iter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>total_iter,</span>
<span id="cb14-39">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>common,</span>
<span id="cb14-40">        )</span>
<span id="cb14-41">        Y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tsne.fit_transform(X)</span>
<span id="cb14-42"></span>
<span id="cb14-43">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Check the stability</span></span>
<span id="cb14-44">        delta <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linalg.norm(Y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> prev, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>).mean()</span>
<span id="cb14-45">        history.append(delta)</span>
<span id="cb14-46">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> verbose:</span>
<span id="cb14-47">            <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"[</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>total_iter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> step_iter<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> iters] mean move = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>delta<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.6f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb14-48"></span>
<span id="cb14-49">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> delta <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> tol:</span>
<span id="cb14-50">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> verbose:</span>
<span id="cb14-51">                <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"✓ Converged"</span>)</span>
<span id="cb14-52">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb14-53"></span>
<span id="cb14-54">        prev <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Y.copy()</span>
<span id="cb14-55"></span>
<span id="cb14-56">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Y, history, total_iter</span></code></pre></div></div>
</div>
<p>Here are my iterations, which I did follow the <code>magic recipe</code>.</p>
<div id="f733ac0f937e2378" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:52:46.599083Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:51:45.299724Z&quot;}}" data-execution_count="44">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>capture</span>
<span id="cb15-2">embedding1, movement1, max_iter1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tsne_until_converged(X)</span></code></pre></div></div>
</div>
<div id="7ff90ca41a3927c6" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:26.318420Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:52:46.736438Z&quot;}}" data-execution_count="45">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>capture</span>
<span id="cb16-2">embedding2, movement2, max_iter2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tsne_until_converged(X, perplexity<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span></code></pre></div></div>
</div>
<div id="341eeb8992c38450" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:31.732070Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:26.363399Z&quot;}}" data-execution_count="46">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>capture</span>
<span id="cb17-2">embedding3, movement3, max_iter3 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tsne_until_converged(X, perplexity<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>)</span></code></pre></div></div>
</div>
<div id="8e7b65142ef78554" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:39.656007Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:31.762667Z&quot;}}" data-execution_count="47">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>capture</span>
<span id="cb18-2">embedding4, movement4, max_iter4 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tsne_until_converged(X, perplexity<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, exaggeration<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
</div>
<div id="400f723227dc329d" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:50.644823Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:39.687526Z&quot;}}" data-execution_count="48">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>capture</span>
<span id="cb19-2">embedding5, movement5, max_iter5 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tsne_until_converged(X, perplexity<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, exaggeration<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>)</span></code></pre></div></div>
</div>
<p>Let’s plot the 2D data and the stability of the embeddings.</p>
<div id="e3392e018557b543" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:50.668246Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:50.663396Z&quot;}}" data-execution_count="49">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># for plotting we define a helper function</span></span>
<span id="cb20-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb20-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> seaborn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> sns</span>
<span id="cb20-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb20-5"></span>
<span id="cb20-6"></span>
<span id="cb20-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_tsne_results(</span>
<span id="cb20-8">        results,</span>
<span id="cb20-9">        filenames<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb20-10">        titles<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb20-11">        palette<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Set2"</span>,</span>
<span id="cb20-12">        figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>),</span>
<span id="cb20-13">):</span>
<span id="cb20-14">    n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(results)</span>
<span id="cb20-15">    fig, axes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(nrows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n, ncols<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(figsize[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n, figsize[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb20-16"></span>
<span id="cb20-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, (embedding, movement) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(results):</span>
<span id="cb20-18">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1. Plot embedding</span></span>
<span id="cb20-19">        tsne_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame({</span>
<span id="cb20-20">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>: embedding[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>],</span>
<span id="cb20-21">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>: embedding[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>],</span>
<span id="cb20-22">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: filenames <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> filenames <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(embedding)</span>
<span id="cb20-23">        })</span>
<span id="cb20-24"></span>
<span id="cb20-25">        ax1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[i, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb20-26">        sns.scatterplot(</span>
<span id="cb20-27">            data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tsne_df,</span>
<span id="cb20-28">            x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>,</span>
<span id="cb20-29">            hue<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>,</span>
<span id="cb20-30">            palette<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>palette,</span>
<span id="cb20-31">            s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k'</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>,</span>
<span id="cb20-32">            ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax1,</span>
<span id="cb20-33">            legend<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"auto"</span></span>
<span id="cb20-34">        )</span>
<span id="cb20-35">        ax1.set_title(titles[i] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> titles <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"t-SNE Embedding </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb20-36">        ax1.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TSNE-1"</span>)</span>
<span id="cb20-37">        ax1.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TSNE-2"</span>)</span>
<span id="cb20-38"></span>
<span id="cb20-39">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 2. Plot movement curve</span></span>
<span id="cb20-40">        ax2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[i, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb20-41">        ax2.plot(movement, marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'o'</span>, linewidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span>)</span>
<span id="cb20-42">        ax2.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mean Movement per Step"</span>)</span>
<span id="cb20-43">        ax2.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Step"</span>)</span>
<span id="cb20-44">        ax2.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mean Δ Position"</span>)</span>
<span id="cb20-45">        ax2.grid(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb20-46"></span>
<span id="cb20-47">    plt.tight_layout()</span>
<span id="cb20-48">    plt.show()</span></code></pre></div></div>
</details>
</div>
<div id="d754faa7a7d673de" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:52.003712Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:50.726126Z&quot;}}" data-execution_count="50">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1">results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb21-2">    (embedding1, movement1),</span>
<span id="cb21-3">    (embedding2, movement2),</span>
<span id="cb21-4">    (embedding3, movement3),</span>
<span id="cb21-5">    (embedding4, movement4),</span>
<span id="cb21-6">    (embedding5, movement5),</span>
<span id="cb21-7">]</span>
<span id="cb21-8"></span>
<span id="cb21-9">plot_tsne_results(results, titles<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Run 1 p=5"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Run 2 p=10"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Run 3 p=16"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Run 4 p=16,e=3"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Run 5 p=16,e=3, l=40"</span>])</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-19-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>There is not much variation. There are three distinctive groups in all pictures. The standard setting in run2 leads to vertically squeezed distribution. The result in this respect seems better in run 5, with early exaggeration and increased learning rate.</p>
</section>
<section id="can-we-see-two-groups-party-and-quite-in-the-data" class="level3" data-number="3.5">
<h3 data-number="3.5" class="anchored" data-anchor-id="can-we-see-two-groups-party-and-quite-in-the-data"><span class="header-section-number">3.5</span> Can we see two groups (party and quite) in the data?</h3>
<p>As mentioned earlier, I was not entirely happy with the matches. As a result, triaged the files into two groups. One which I experienced as quiet. Let’s see if we can confirm this very subjective impression in the data, even though we never told the model that these two groups exist.</p>
<p>We define the data to be plotted to include theme and filename.</p>
<div id="38570518a9f6b9f8" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:52.079980Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:52.075880Z&quot;}}" data-execution_count="51">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Load manifest again</span></span>
<span id="cb22-2">manifest <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_csv(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/app/data/raw-previews/explainabletrack_manifest.csv"</span>)</span>
<span id="cb22-3">labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [f <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> f <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> manifest[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'theme'</span>]]</span>
<span id="cb22-4">tsne_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame({</span>
<span id="cb22-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>: embedding5[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>],</span>
<span id="cb22-6">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>: embedding5[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>],</span>
<span id="cb22-7">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theme"</span>: labels,</span>
<span id="cb22-8">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"filename"</span>: filenames</span>
<span id="cb22-9">})</span></code></pre></div></div>
</details>
</div>
<div id="afc52969ac8b0e2a" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:52.322217Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:52.158538Z&quot;}}" data-execution_count="52">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1">sns.scatterplot(</span>
<span id="cb23-2">    data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tsne_df,</span>
<span id="cb23-3">    x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'x'</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y'</span>,</span>
<span id="cb23-4">    hue<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'theme'</span>,</span>
<span id="cb23-5">    palette<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Set2'</span>,</span>
<span id="cb23-6">    s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k'</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span></span>
<span id="cb23-7">)</span>
<span id="cb23-8"></span>
<span id="cb23-9">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t-SNE Projection Colored by Manual Theme Label"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>)</span>
<span id="cb23-10">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TSNE-1"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb23-11">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TSNE-2"</span>)</span>
<span id="cb23-12">plt.legend(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Theme"</span>)</span>
<span id="cb23-13">plt.tight_layout()</span>
<span id="cb23-14">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-21-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Overall, the data does not fit the perceived feature of “quietness.” The only think that is noticeable in the picture is a clustering of green points to the left and the bottom of the patch 2 and 3, respectively.</p>
<section id="intra--and-inter-theme-similarity" class="level4" data-number="3.5.1">
<h4 data-number="3.5.1" class="anchored" data-anchor-id="intra--and-inter-theme-similarity"><span class="header-section-number">3.5.1</span> Intra- and inter-theme similarity</h4>
<p>We can express this in numbers and calculate intra- and inter-theme similarity. The themes should be distinct and have little variation.</p>
<div id="a1e6bb814d6a26b6" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:52.418895Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:52.398804Z&quot;}}" data-execution_count="53">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics.pairwise <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> cosine_distances</span>
<span id="cb24-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> itertools</span>
<span id="cb24-3"></span>
<span id="cb24-4">theme_to_indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tsne_df.groupby(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theme"</span>).groups</span>
<span id="cb24-5">theme_names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(theme_to_indices.keys())</span>
<span id="cb24-6"></span>
<span id="cb24-7">similarity_stats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb24-8"></span>
<span id="cb24-9"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> t1, t2 <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> itertools.combinations_with_replacement(theme_names, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>):</span>
<span id="cb24-10">    i1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(theme_to_indices[t1])</span>
<span id="cb24-11">    i2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(theme_to_indices[t2])</span>
<span id="cb24-12"></span>
<span id="cb24-13">    vec1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X[i1]</span>
<span id="cb24-14">    vec2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X[i2]</span>
<span id="cb24-15"></span>
<span id="cb24-16">    distances <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cosine_distances(vec1, vec2)</span>
<span id="cb24-17">    mean_distance <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> distances.mean()</span>
<span id="cb24-18"></span>
<span id="cb24-19">    similarity_stats.append({</span>
<span id="cb24-20">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theme_1"</span>: t1,</span>
<span id="cb24-21">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theme_2"</span>: t2,</span>
<span id="cb24-22">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mean_cosine_distance"</span>: mean_distance</span>
<span id="cb24-23">    })</span>
<span id="cb24-24"></span>
<span id="cb24-25">similarity_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame(similarity_stats)</span>
<span id="cb24-26">similarity_df.sort_values(by<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mean_cosine_distance"</span>, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb24-27">similarity_df</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display" data-execution_count="53">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">theme_1</th>
<th data-quarto-table-cell-role="th">theme_2</th>
<th data-quarto-table-cell-role="th">mean_cosine_distance</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>party</td>
<td>party</td>
<td>0.040207</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">2</th>
<td>ruhig</td>
<td>ruhig</td>
<td>0.046004</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">1</th>
<td>party</td>
<td>ruhig</td>
<td>0.048002</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<div id="29be69e84c773b4e" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:52.543930Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:52.532247Z&quot;}}" data-execution_count="54">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> silhouette_score</span>
<span id="cb25-2"></span>
<span id="cb25-3">score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> silhouette_score(X, labels, metric<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cosine'</span>)</span>
<span id="cb25-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Silhouette Score (cosine): </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>score<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>Silhouette Score (cosine): 0.085</code></pre>
</div>
</div>
<p>All of these numbers are very close to zero. This data backs the visual impression: The manual groups have nothing to do with the automatic selection. This explains why I was not satisfied. Features that I deemed important are somehow not in the data. Interesting.</p>
</section>
</section>
<section id="similarity-analysis-of-single-songs" class="level3" data-number="3.6">
<h3 data-number="3.6" class="anchored" data-anchor-id="similarity-analysis-of-single-songs"><span class="header-section-number">3.6</span> Similarity analysis of single songs</h3>
<p>Let’s study more how the model behaves with respect to a query. Our query song is Purple Rain - Prince.</p>
<p>My final playlist had this ordering</p>
<ul>
<li>Luna - Bombay Bicycle Club.mp3</li>
<li>Purple Rain - Prince.mp3</li>
<li>Everybody Wants To Rule The World - Tears For Fears.mp3</li>
<li>Kiss from a Rose - Seal.mp3</li>
</ul>
<p>We first define some helpers</p>
<div id="33924bf9bc71274d" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:52.711267Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:52.707724Z&quot;}}" data-execution_count="55">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics.pairwise <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> cosine_similarity</span>
<span id="cb27-2"></span>
<span id="cb27-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_vector_by_name(db, search_term):</span>
<span id="cb27-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> db[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/opt/project/data/raw-previews/combined/"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> search_term <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".mp3"</span>]</span>
<span id="cb27-5"></span>
<span id="cb27-6"></span>
<span id="cb27-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> compare_songs(song_A, song_B, db):</span>
<span id="cb27-8">    song_A_vec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_vector_by_name(db, song_A)</span>
<span id="cb27-9">    song_B_vec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_vector_by_name(db, song_B)</span>
<span id="cb27-10"></span>
<span id="cb27-11">    sim <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cosine_similarity(song_A_vec.reshape(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), song_B_vec.reshape(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb27-12">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Similarity to </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>song_A<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>sim<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb27-13"></span>
<span id="cb27-14"></span>
<span id="cb27-15"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> most_similar_song(song_A_vec, vectors, filenames):</span>
<span id="cb27-16">    sims <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cosine_similarity(song_A_vec.reshape(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), vectors)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb27-17">    min_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argmin(sims)</span>
<span id="cb27-18">    min_score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sims[min_idx]</span>
<span id="cb27-19"></span>
<span id="cb27-20">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Weakest match cosine similarity: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>min_score<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb27-21">    sorted_indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(sims)[::<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Descending order</span></span>
<span id="cb27-22"></span>
<span id="cb27-23">    second_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sorted_indices[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb27-24"></span>
<span id="cb27-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> filenames[second_idx], sims[second_idx]</span></code></pre></div></div>
</div>
<p>Let’s see what is the best fitting song to <code>Purple Rain</code>.</p>
<div id="8e57c6c2b60b7a23" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:52.794788Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:52.787888Z&quot;}}" data-execution_count="56">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1">best_match, score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> most_similar_song(get_vector_by_name(mp3tovecs, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Purple Rain - Prince"</span>), X, filenames)</span>
<span id="cb28-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Best match: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>best_match<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> — cosine sim: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>score<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Weakest match cosine similarity: 0.825
Best match: /opt/project/data/raw-previews/combined/Mesmerise - Temples.mp3 — cosine sim: 0.999</code></pre>
</div>
</div>
<p>Again, we confirm that the automatic matching produced something different from my selection. Let’s compare all songs and also one which is completely off.</p>
<div id="e4a9833fdcba9a3f" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:52.913093Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:52.907640Z&quot;}}" data-execution_count="57">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1">compare_songs(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Purple Rain - Prince"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Everybody Wants To Rule The World - Tears For Fears"</span>, mp3tovecs)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Similarity to Purple Rain - Prince: 0.998</code></pre>
</div>
</div>
<div id="3b29ae9da2063f65" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:53.029642Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:53.018114Z&quot;}}" data-execution_count="58">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1">compare_songs(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Purple Rain - Prince"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Luna - Bombay Bicycle Club"</span>, mp3tovecs)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Similarity to Purple Rain - Prince: 0.995</code></pre>
</div>
</div>
<div id="2b75ad617c4369e1" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:53.142905Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:53.139684Z&quot;}}" data-execution_count="59">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb34-1">compare_songs(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Purple Rain - Prince"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mr. Brightside - The Killers"</span>, mp3tovecs)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Similarity to Purple Rain - Prince: 0.933</code></pre>
</div>
</div>
<div id="d725b3d890bce977" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:53.240952Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:53.236714Z&quot;}}" data-execution_count="60">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb36" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb36-1">compare_songs(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Purple Rain - Prince"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Kiss from a Rose - Seal"</span>, mp3tovecs)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Similarity to Purple Rain - Prince: 0.990</code></pre>
</div>
</div>
<section id="plotting-single-songs-in-tsne-plot" class="level4" data-number="3.6.1">
<h4 data-number="3.6.1" class="anchored" data-anchor-id="plotting-single-songs-in-tsne-plot"><span class="header-section-number">3.6.1</span> Plotting single songs in TSNE plot</h4>
<p>As a final step, we want to visualize what we have just expressed in numbers. How are the songs related to the plot?</p>
<div id="f98a64ddfe2638ef" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:53.341832Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:53.338436Z&quot;}}" data-execution_count="61">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb38" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb38-1">labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(filenames)</span>
<span id="cb38-2"></span>
<span id="cb38-3">songs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Purple Rain - Prince"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mesmerise - Temples"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Everybody Wants To Rule The World - Tears For Fears"</span>,</span>
<span id="cb38-4">         <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mr. Brightside - The Killers"</span>, ]</span>
<span id="cb38-5"></span>
<span id="cb38-6"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, f <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(filenames):</span>
<span id="cb38-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> song <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> songs:</span>
<span id="cb38-8">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> song <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> f:</span>
<span id="cb38-9">            labels[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> song</span>
<span id="cb38-10">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb38-11"></span>
<span id="cb38-12">tsne_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame({</span>
<span id="cb38-13">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>: embedding5[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>],</span>
<span id="cb38-14">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>: embedding5[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>],</span>
<span id="cb38-15">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theme"</span>: labels,</span>
<span id="cb38-16">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"filename"</span>: filenames</span>
<span id="cb38-17">})</span></code></pre></div></div>
</details>
</div>
<div id="4a3065e00e22916" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:53.666031Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:53.432143Z&quot;}}" data-execution_count="62">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb39" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb39-1">palette <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb39-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#bbbbbb"</span>,</span>
<span id="cb39-3">    songs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"black"</span>,</span>
<span id="cb39-4">    songs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"green"</span>,</span>
<span id="cb39-5">    songs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"orange"</span>,</span>
<span id="cb39-6">    songs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"red"</span>,</span>
<span id="cb39-7"></span>
<span id="cb39-8">}</span>
<span id="cb39-9"></span>
<span id="cb39-10">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>))</span>
<span id="cb39-11">sns.scatterplot(</span>
<span id="cb39-12">    data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tsne_df,</span>
<span id="cb39-13">    x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>,</span>
<span id="cb39-14">    hue<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theme"</span>, hue_order<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span>, songs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], songs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], songs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], songs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]],</span>
<span id="cb39-15">    palette<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>palette,</span>
<span id="cb39-16">    s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"k"</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span></span>
<span id="cb39-17">)</span>
<span id="cb39-18">plt.legend(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Label"</span>, loc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"best"</span>)</span>
<span id="cb39-19">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t-SNE with three highlighted songs"</span>)</span>
<span id="cb39-20">plt.tight_layout()</span>
<span id="cb39-21">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-31-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>The picture confirms it again. <code>Temples - Mesmerise</code> is the best match. It should have been picked. It appears The nearby match <code>Everybody Wants To Rule The World - Tears For Fears</code> was not the closest match and only got taken because I interfered with the playlist creation.</p>
</section>
</section>
</section>
<section id="grad-cam" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="grad-cam"><span class="header-section-number">4</span> Grad-CAM</h2>
<p>Our Mp3ToVec network already tells us how close two songs are (cosine similarity), but not where that closeness comes from.</p>
<p>Are there any regions in the spectrogram that lead to the exact match? Which time–frequency zones triggered the network to declare “this query sounds like Song A (and not Song B)”. In the next section, we will look at Integrated Gradients, which observes down to pixel level. Grad-CAM offers a complementary, big-picture view.</p>
<section id="background" class="level3" data-number="4.1">
<h3 data-number="4.1" class="anchored" data-anchor-id="background"><span class="header-section-number">4.1</span> Background</h3>
<p>Grad-CAM works by examining the last convolutional layer, which acts as the model’s feature detector. We then use the gradient of the similarity score with respect to Song A to weight these feature maps.</p>
<p>Finally, we project the weighted activation maps back onto the spectrogram. This results in a coarse heatmap; red blobs where the CNN focused, and blank areas elsewhere.</p>
<p>In terms of interpretability, this allows a visual inspection, which goes beyond simple scores.</p>
</section>
<section id="implementation" class="level3" data-number="4.2">
<h3 data-number="4.2" class="anchored" data-anchor-id="implementation"><span class="header-section-number">4.2</span> Implementation</h3>
<div id="88e5343c07387d5b" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:54.284930Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:53.717439Z&quot;}}" data-execution_count="63">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb40" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb40-1"></span>
<span id="cb40-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> tensorflow.keras.models <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> load_model</span>
<span id="cb40-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> tensorflow <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tf</span>
<span id="cb40-4">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> load_model(</span>
<span id="cb40-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/app/speccy_model'</span>,</span>
<span id="cb40-6">    custom_objects<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{</span>
<span id="cb40-7">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cosine_proximity'</span>:</span>
<span id="cb40-8">            tf.compat.v1.keras.losses.cosine_proximity</span>
<span id="cb40-9">    })</span>
<span id="cb40-10">model.trainable <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb40-11">conv_layer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.get_layer(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"separable_conv2d_3"</span>)</span></code></pre></div></div>
</div>
<div id="67a874e0-9b4b-45d7-81f3-d1ba9b04eb4c" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:54.297801Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:54.288553Z&quot;}}" data-execution_count="64">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb41" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb41-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.ndimage <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> gaussian_filter</span>
<span id="cb41-2"></span>
<span id="cb41-3"></span>
<span id="cb41-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> score_fn(emb):</span>
<span id="cb41-5">    emb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.nn.l2_normalize(emb, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb41-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tf.tensordot(emb, vec_A, axes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb41-7">    </span>
<span id="cb41-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> grad_cam(slice_tensor,</span>
<span id="cb41-9">             model, conv_layer, score_fn,</span>
<span id="cb41-10">             eps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-8</span>):</span>
<span id="cb41-11">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># build a model that gives conv feature-maps and final embedding</span></span>
<span id="cb41-12">    grad_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.keras.Model(</span>
<span id="cb41-13">        inputs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model.inputs,</span>
<span id="cb41-14">        outputs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[conv_layer.output, model.output]</span>
<span id="cb41-15">    )</span>
<span id="cb41-16"></span>
<span id="cb41-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> tf.GradientTape() <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tape:</span>
<span id="cb41-18">        conv_out, preds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> grad_model(slice_tensor)</span>
<span id="cb41-19">        tape.watch(conv_out)</span>
<span id="cb41-20">        score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score_fn(preds)</span>
<span id="cb41-21"></span>
<span id="cb41-22">    </span>
<span id="cb41-23">    grads <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tape.gradient(score, conv_out) </span>
<span id="cb41-24">    weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.reduce_mean(grads, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb41-25"></span>
<span id="cb41-26">    cam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.reduce_sum(weights[:, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, :] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> conv_out, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] </span>
<span id="cb41-27">    cam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.nn.relu(cam)</span>
<span id="cb41-28"></span>
<span id="cb41-29">    cam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.image.resize(cam[..., <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>], slice_tensor.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>])[..., <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb41-30">    cam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (cam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tf.reduce_min(cam)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (tf.reduce_max(cam) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tf.reduce_min(cam) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> eps)</span>
<span id="cb41-31">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> cam.numpy()</span>
<span id="cb41-32"></span>
<span id="cb41-33"></span>
<span id="cb41-34"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> full_song_grad_cam(model, query_slices, vec_A, conv_layer,</span>
<span id="cb41-35">                       n_mels<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">96</span>, slice_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">216</span>, sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span>):</span>
<span id="cb41-36">    </span>
<span id="cb41-37">    vec_A_tf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.constant(vec_A <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> np.linalg.norm(vec_A), tf.float32)</span>
<span id="cb41-38"></span>
<span id="cb41-39">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> score_fn(embedding):</span>
<span id="cb41-40">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tf.tensordot(tf.nn.l2_normalize(embedding, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), vec_A_tf, axes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb41-41">        </span>
<span id="cb41-42">    gc_full <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros((n_mels, query_slices.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> slice_size))</span>
<span id="cb41-43"></span>
<span id="cb41-44">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, slice_tensor <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(query_slices):</span>
<span id="cb41-45">        slice_tensor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> slice_tensor[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, ...]</span>
<span id="cb41-46">        gc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> grad_cam(slice_tensor, model, conv_layer, score_fn)</span>
<span id="cb41-47">        gc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gaussian_filter(gc, sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sigma)</span>
<span id="cb41-48">        gc_full[:, i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> slice_size: (i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> slice_size] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gc</span>
<span id="cb41-49">        </span>
<span id="cb41-50">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> gc_full</span></code></pre></div></div>
</div>
<p>Now that we have defined a function to do GRAD-CAM for the full song. Let’s study the difference for song A and song B. We will get an answer which regions where more important to which song and which were identically important.</p>
<div id="58ba55447fcbb4ed" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:54.399259Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:54.328741Z&quot;}}" data-execution_count="65">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb42" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb42-1">vec_A <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mp3tovecs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/opt/project/data/raw-previews/combined/Mesmerise - Temples.mp3'</span>]</span>
<span id="cb42-2">vec_B <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mp3tovecs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/opt/project/data/raw-previews/combined/Everybody Wants To Rule The World - Tears For Fears.mp3'</span>]</span>
<span id="cb42-3">x_query <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mp3_to_slices(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/app/data/raw-previews/combined/Purple Rain - Prince.mp3'</span>)</span></code></pre></div></div>
</div>
<div id="cb509551315d67e7" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:54.656253Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:54.406999Z&quot;}}" data-execution_count="66">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb43-1">cam_A <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> full_song_grad_cam(model, x_query, vec_A, conv_layer)</span>
<span id="cb43-2">cam_B <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> full_song_grad_cam(model, x_query, vec_B, conv_layer)</span>
<span id="cb43-3"></span>
<span id="cb43-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># we use signed log, as the songs are very close together.</span></span>
<span id="cb43-5">diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.math.log((cam_A <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-5</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (cam_B <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-5</span>))</span>
<span id="cb43-6">diff_clipped <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.clip_by_value(diff, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.0</span>)</span></code></pre></div></div>
</div>
<div id="74feded6537067c9" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:54.882899Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:54.691103Z&quot;}}" data-execution_count="67">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb44" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb44-1">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>))</span>
<span id="cb44-2"></span>
<span id="cb44-3">plt.imshow(diff_clipped, cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"berlin"</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lower"</span>, aspect<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"auto"</span>)</span>
<span id="cb44-4">plt.colorbar(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Grad-CAM intensity"</span>)</span>
<span id="cb44-5">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Where the CNN ‘looked’ to match Song A"</span>)</span>
<span id="cb44-6">plt.tight_layout()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb44-7">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-36-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Thanks to the clipping, the graph is easy to read. The Song had a lot more information, which made it similar to the query song.</p>
<p>Only at the very end are some blue spots. This could indicate that the spotify preview covers only the less relevant sections of the entire song for the particular comparison. Whereas I was listening to the full song. Song B seems better for the rhythm as the blue patches repeat.</p>
<p>We will dive deeper into this in the next section.</p>
</section>
</section>
<section id="integrated-gradients" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="integrated-gradients"><span class="header-section-number">5</span> Integrated gradients</h2>
<p>Why did the model prefer Song A over Song B? We know that the model turns spectrograms into 100-D vectors and ranks candidates using cosine similarity. That alone doesn’t tell us why one track got a higher score than another. To dig deeper, we use Integrated Gradients (IG). This method helps identify which parts of a spectrogram contribute most to the similarity score, that is which pixels or frequencies increase the score.</p>
<p>In contrast to Grad-Cam, we do not look at the feature level, but on input level through the entire network.</p>
<section id="background-1" class="level3" data-number="5.1">
<h3 data-number="5.1" class="anchored" data-anchor-id="background-1"><span class="header-section-number">5.1</span> Background</h3>
<p>IG works by comparing the actual input (the spectrogram) to a baseline input, typically silence.</p>
<p>We then gradually transition from the baseline to the real input by scaling the spectrogram with a factor <img src="https://latex.codecogs.com/png.latex?%5Calpha">.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20x_%CE%B1%20=%20baseline%20+%20%5Calpha%20%C3%97%20(input%20-%20baseline)%20"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Calpha%20%E2%88%88%20%5B0,1%5D"></p>
<p>At each step, we compute the gradient of the output with respect to the input. When we average across all steps, we get the average contribution of each pixel.</p>
<p>In <code>Pytorch</code> we have the <code>Captum</code> library to directly do this. However, <code>Deej-AI</code> works on an older keras 2.13. We need to implement Integrated Gradients from scratch.</p>
</section>
<section id="from-scratch-development-of-integrated-gradients" class="level3" data-number="5.2">
<h3 data-number="5.2" class="anchored" data-anchor-id="from-scratch-development-of-integrated-gradients"><span class="header-section-number">5.2</span> From scratch development of integrated gradients</h3>
<section id="method-for-one-slice" class="level4" data-number="5.2.1">
<h4 data-number="5.2.1" class="anchored" data-anchor-id="method-for-one-slice"><span class="header-section-number">5.2.1</span> Method for one slice</h4>
<p>We define the integrated gradients for one slice</p>
<p>Let’s first clarify what we expect from the model</p>
<p>Luckily for a linear model <img src="https://latex.codecogs.com/png.latex?f(x)%20=%20w%5E%5Ctop%20x%20+%20b"></p>
<p>the Integrated Gradients have the closed-form</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathrm%7BIG%7D(x)%20%5C;=%5C;%20(x%20-%20x_0)%5C,%5Codot%5C,w"></p>
<p>We intend to use integrated gradients to check the impact on the cosine similarity score. Therefore, we need to integrate the L2 norm in the function. This has side effects in testing. We need to make the code modular to accommodate for this.</p>
<div id="d710f19e2b350dc1" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:54.954015Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:54.947722Z&quot;}}" data-execution_count="68">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb45" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb45-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> tensorflow <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tf</span>
<span id="cb45-2"></span>
<span id="cb45-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># for testing, we will test on raw attribution without normalization</span></span>
<span id="cb45-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> default_score_fn(preds, target_vec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb45-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> target_vec <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb45-6">        t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.reshape(tf.convert_to_tensor(target_vec, tf.float32), [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb45-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tf.reduce_sum(preds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb45-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb45-9">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tf.reduce_sum(preds, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb45-10"></span>
<span id="cb45-11"></span>
<span id="cb45-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># we are interested on the effect of the cosine similarity score, therefore, we will need to do L2</span></span>
<span id="cb45-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cosine_score_fn(preds, target_vec):</span>
<span id="cb45-14">    p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.nn.l2_normalize(preds, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb45-15">    t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.nn.l2_normalize(target_vec, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb45-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tf.reduce_sum(p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb45-17"></span>
<span id="cb45-18"></span>
<span id="cb45-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># this is the function for one slice</span></span>
<span id="cb45-20"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> ig_one_slice(</span>
<span id="cb45-21">        model,</span>
<span id="cb45-22">        query_slice,</span>
<span id="cb45-23">        target_vec,</span>
<span id="cb45-24">        baseline_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb45-25">        steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span>,</span>
<span id="cb45-26">        score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>default_score_fn</span>
<span id="cb45-27">):</span>
<span id="cb45-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> baseline_slice <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb45-29">        baseline_slice <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.zeros_like(query_slice, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32)</span>
<span id="cb45-30"></span>
<span id="cb45-31">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># make sure we work on f32</span></span>
<span id="cb45-32">    query_slice <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.convert_to_tensor(query_slice, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32)</span>
<span id="cb45-33">    baseline_slice <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.convert_to_tensor(baseline_slice, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32)</span>
<span id="cb45-34">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> target_vec <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb45-35">        target_vec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.convert_to_tensor(target_vec, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32)</span>
<span id="cb45-36">        target_vec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.reshape(target_vec, [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb45-37"></span>
<span id="cb45-38">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Remove batch dim for interpolation</span></span>
<span id="cb45-39">    start <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.squeeze(baseline_slice, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># (96,216,1)</span></span>
<span id="cb45-40">    end <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.squeeze(query_slice, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># (96,216,1)</span></span>
<span id="cb45-41"></span>
<span id="cb45-42">    alphas <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.linspace(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, steps)[:, tf.newaxis, tf.newaxis, tf.newaxis]</span>
<span id="cb45-43">    interpolated <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> start <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> alphas <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (end <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> start)</span>
<span id="cb45-44"></span>
<span id="cb45-45">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Compute gradients</span></span>
<span id="cb45-46">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> tf.GradientTape() <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tape:</span>
<span id="cb45-47">        tape.watch(interpolated)</span>
<span id="cb45-48">        preds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(interpolated)</span>
<span id="cb45-49">        scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score_fn(preds, target_vec)</span>
<span id="cb45-50"></span>
<span id="cb45-51">    grads <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tape.gradient(scores, interpolated)</span>
<span id="cb45-52">    avg_grads <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.reduce_mean(grads, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb45-53"></span>
<span id="cb45-54">    ig <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (end <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> start) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> avg_grads</span>
<span id="cb45-55">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> ig</span></code></pre></div></div>
</div>
<p>Gradients can be noisy. We add some smoothing to get a better visual representation. We use a two-pass smoothing. First on the slice and later on the final output.</p>
<div id="7cace7e71412b037" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:55.003841Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:54.998265Z&quot;}}" data-execution_count="69">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb46" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb46-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.ndimage <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> gaussian_filter</span>
<span id="cb46-2"></span>
<span id="cb46-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> ig_one_slice_smooth(</span>
<span id="cb46-4">        model,</span>
<span id="cb46-5">        query_slice,</span>
<span id="cb46-6">        target_vec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb46-7">        baseline_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb46-8">        steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span>,</span>
<span id="cb46-9">        score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>default_score_fn,</span>
<span id="cb46-10">        sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb46-11">):</span>
<span id="cb46-12">    ig_raw <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_one_slice(</span>
<span id="cb46-13">        model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model,</span>
<span id="cb46-14">        query_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>query_slice,</span>
<span id="cb46-15">        target_vec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>target_vec,</span>
<span id="cb46-16">        baseline_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>baseline_slice,</span>
<span id="cb46-17">        steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>steps,</span>
<span id="cb46-18">        score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>score_fn</span>
<span id="cb46-19">    )</span>
<span id="cb46-20"></span>
<span id="cb46-21">    ig_map <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_raw.numpy().squeeze()</span>
<span id="cb46-22">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> gaussian_filter(ig_map, sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sigma)</span></code></pre></div></div>
</div>
</section>
<section id="testing-with-a-closed-form-solution" class="level4" data-number="5.2.2">
<h4 data-number="5.2.2" class="anchored" data-anchor-id="testing-with-a-closed-form-solution"><span class="header-section-number">5.2.2</span> Testing with a closed form solution</h4>
<div id="c4f77444afd44d4f" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:55.062982Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:55.058512Z&quot;}}" data-execution_count="70">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb47" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb47-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_for_ig_one_slice():</span>
<span id="cb47-2">    H, W <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb47-3"></span>
<span id="cb47-4">    flat_vals <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(H <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> W, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.float32)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [0, 1, 2, 3, 4, 5]</span></span>
<span id="cb47-5">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> flat_vals.reshape((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, H, W, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># shape: (1,2,3,1)</span></span>
<span id="cb47-6">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.constant(x)</span>
<span id="cb47-7"></span>
<span id="cb47-8">    x0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.zeros_like(x)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># shape: (1,2,3,1)</span></span>
<span id="cb47-9"></span>
<span id="cb47-10">    w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.constant(flat_vals, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># weights = [0,1,2,3,4,5]</span></span>
<span id="cb47-11">    b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.constant(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span>, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32)</span>
<span id="cb47-12"></span>
<span id="cb47-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> LinearModel(tf.keras.Model):</span>
<span id="cb47-14">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, w, b):</span>
<span id="cb47-15">            <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>().<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>()</span>
<span id="cb47-16">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> w</span>
<span id="cb47-17">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> b</span>
<span id="cb47-18"></span>
<span id="cb47-19">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> call(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, inp):</span>
<span id="cb47-20">            flat <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.reshape(inp, [inp.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># (batch, D)</span></span>
<span id="cb47-21">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># return a *vector* of length 1 so IG still works with a scalar output</span></span>
<span id="cb47-22">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> tf.matmul(flat, tf.expand_dims(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.w, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.b</span>
<span id="cb47-23"></span>
<span id="cb47-24">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> LinearModel(w, b)</span>
<span id="cb47-25"></span>
<span id="cb47-26">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># For this scalar-output model, set target_vec = [1.], so that</span></span>
<span id="cb47-27">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># scores = f(interpolated) * 1  and grad(scores) = grad f.</span></span>
<span id="cb47-28">    target_vec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.</span>], dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.float32)</span>
<span id="cb47-29"></span>
<span id="cb47-30">    ig_out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_one_slice(model, query_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>x, target_vec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>target_vec, baseline_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>x0, steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>)</span>
<span id="cb47-31">    ig_out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_out.numpy().reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb47-32"></span>
<span id="cb47-33">    closed_form <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> x0).numpy().reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> flat_vals  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># shape (6,)</span></span>
<span id="cb47-34"></span>
<span id="cb47-35">    tf.debugging.assert_near(ig_out, closed_form, atol<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>)</span></code></pre></div></div>
</details>
</div>
<div id="79d7dad848adc543" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:55.161331Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:55.121638Z&quot;}}" data-execution_count="71">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb48" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb48-1">test_for_ig_one_slice()</span></code></pre></div></div>
</div>
<p>q.e.d.</p>
</section>
<section id="testing-with-real-data" class="level4" data-number="5.2.3">
<h4 data-number="5.2.3" class="anchored" data-anchor-id="testing-with-real-data"><span class="header-section-number">5.2.3</span> Testing with real data</h4>
<p>We will first examine the result for one slice, without any baseline or target vector. This produces the raw attribution of each pixel to the output value of the model.</p>
<div id="1d141c1561945832" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:55.739338Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:55.184639Z&quot;}}" data-execution_count="72">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb49" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb49-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> tensorflow.keras.models <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> load_model</span>
<span id="cb49-2"></span>
<span id="cb49-3">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> load_model(</span>
<span id="cb49-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/app/speccy_model'</span>,</span>
<span id="cb49-5">    custom_objects<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{</span>
<span id="cb49-6">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cosine_proximity'</span>:</span>
<span id="cb49-7">            tf.compat.v1.keras.losses.cosine_proximity</span>
<span id="cb49-8">    })</span>
<span id="cb49-9">model.trainable <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span></code></pre></div></div>
</div>
<div id="9b73b6c350306161" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:55.825499Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:55.757279Z&quot;}}" data-execution_count="73">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb50" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb50-1">query_slices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mp3_to_slices(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/app/data/raw-previews/combined/Purple Rain - Prince.mp3"</span>)</span></code></pre></div></div>
</div>
<div id="8f1ffbfd33a720c" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:56.216651Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:55.906254Z&quot;}}" data-execution_count="74">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb51" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb51-1">ig_test_map <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_one_slice_smooth(model, query_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>query_slices[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span></code></pre></div></div>
</div>
<p>Now comes the second filtering function, which we only use for postprocessing.</p>
<div id="f5dc9989e3581c98" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:56.237979Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:56.234634Z&quot;}}" data-execution_count="75">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb52" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb52-1"></span>
<span id="cb52-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.ndimage <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> gaussian_filter</span>
<span id="cb52-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb52-4"></span>
<span id="cb52-5"></span>
<span id="cb52-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> highlight_ig_regions(</span>
<span id="cb52-7">        ig_map,</span>
<span id="cb52-8">        percentile<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">90</span>,</span>
<span id="cb52-9">        sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.5</span>,</span>
<span id="cb52-10">        colormap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>plt.cm.berlin,</span>
<span id="cb52-11">        alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.85</span></span>
<span id="cb52-12">):</span>
<span id="cb52-13">    abs_map <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(ig_map)</span>
<span id="cb52-14">    thr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.percentile(abs_map[abs_map <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], percentile)</span>
<span id="cb52-15">    mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> abs_map <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> thr</span>
<span id="cb52-16">    masked <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.where(mask, ig_map, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>)</span>
<span id="cb52-17"></span>
<span id="cb52-18">    masked <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gaussian_filter(masked, sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sigma)</span>
<span id="cb52-19"></span>
<span id="cb52-20">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Normalize and map to colormap</span></span>
<span id="cb52-21">    vmax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(masked)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-9</span></span>
<span id="cb52-22">    normed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (masked <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> vmax)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span></span>
<span id="cb52-23">    rgba <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> colormap(normed)</span>
<span id="cb52-24"></span>
<span id="cb52-25">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Set alpha only where masked &gt; 0</span></span>
<span id="cb52-26">    rgba[..., <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(masked) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> alpha</span>
<span id="cb52-27"></span>
<span id="cb52-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> rgba, masked</span></code></pre></div></div>
</div>
<div id="efb4bcc9765972ba" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:56.508534Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:56.332219Z&quot;}}" data-execution_count="76">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb53" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb53-1">rgba_img, smoothed_mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> highlight_ig_regions(ig_test_map, percentile<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">95</span>, sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>)</span>
<span id="cb53-2">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb53-3">plt.imshow(smoothed_mask, aspect<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'auto'</span>, origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lower'</span>, cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'seismic'</span>)</span>
<span id="cb53-4">plt.colorbar(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Attribution'</span>)</span>
<span id="cb53-5">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Integrated Gradients Attribution"</span>)</span>
<span id="cb53-6">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Time"</span>)</span>
<span id="cb53-7">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"n_mel"</span>)</span>
<span id="cb53-8">plt.tight_layout()</span>
<span id="cb53-9">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-45-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>We can see which frequencies in the sample added to the model output.</p>
</section>
</section>
<section id="analysis-why-song-a-got-picked-over-song-b" class="level3" data-number="5.3">
<h3 data-number="5.3" class="anchored" data-anchor-id="analysis-why-song-a-got-picked-over-song-b"><span class="header-section-number">5.3</span> Analysis: Why Song A got picked over Song B</h3>
<p>We did a lot of work until now. Much of which has been the development of the integrated gradients.</p>
<p>What we were originally interested in is the question of why Song A was chosen over Song B for a query Song.</p>
<p>For this to work, we now need to take our real model, the one that produced the 100D embeddings.</p>
<p>As well as three songs.</p>
<ul>
<li>For us this is <code>Purple Rain</code> for the query.</li>
<li><code>Mesmerise</code> for Song A,</li>
<li>and <code>Everybody wants to rule the world</code> for Song B.</li>
</ul>
<p>Song A and Song B are very close together. While experimenting, I found that using the gradients is challenging in this case.</p>
<p>There are two ways we can calculate contrastive IG.</p>
<p>The standard way: subtract IG</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cmathrm%7BIG%7D_A(x)%20=%20(x%20-%20x')%20%5Codot%20%5Cfrac%7B1%7D%7Bm%7D%20%5Csum_%7Bk=1%7D%5Em%20%5Cnabla_x%20F_A%5Cleft(x'%20+%20%5Cfrac%7Bk%7D%7Bm%7D(x%20-%20x')%5Cright)%0A"></p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cmathrm%7BIG%7D_B(x)%20=%20(x%20-%20x')%20%5Codot%20%5Cfrac%7B1%7D%7Bm%7D%20%5Csum_%7Bk=1%7D%5Em%20%5Cnabla_x%20F_B%5Cleft(x'%20+%20%5Cfrac%7Bk%7D%7Bm%7D(x%20-%20x')%5Cright)%0A"></p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cmathrm%7BContrastIG%7D(x)%20=%20%5Cmathrm%7BIG%7D_A(x)%20-%20%5Cmathrm%7BIG%7D_B(x)%0A"></p>
<p>and method 2 that can be helpful if the embeddings are very close. The reason is that first taking the gradient and then calculating the difference amplifies the noise. This method has been introduced by <a href="https://arxiv.org/abs/1703.01365">Sundararajan et al.&nbsp;2017</a>.</p>
<p>The second method uses one scoring function, as described in the Captum interpretability library and aligned with contrastive explanation principles from <a href="https://arxiv.org/abs/1802.07623">Dhurandhar et al.&nbsp;2018</a>.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AF(x)%20=%20%5Ctext%7Bsim%7D(x,%20A)%20-%20%5Ctext%7Bsim%7D(x,%20B)%0A"></p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cmathrm%7BContrastIG%7D(x)%20=%20(x%20-%20x')%20%5Codot%20%5Cfrac%7B1%7D%7Bm%7D%20%5Csum_%7Bk=1%7D%5Em%20%5Cnabla_x%20%5Cleft%5B%20F%5Cleft(x'%20+%20%5Cfrac%7Bk%7D%7Bm%7D(x%20-%20x')%5Cright)%20%5Cright%5D%0A"></p>
<p>We will try both.</p>
<section id="getting-the-data-ready" class="level4" data-number="5.3.1">
<h4 data-number="5.3.1" class="anchored" data-anchor-id="getting-the-data-ready"><span class="header-section-number">5.3.1</span> Getting the data ready</h4>
<p>We need</p>
<ul>
<li>load our model: the one that produces the vectors.</li>
<li>the spectrogram of the query song. The analysis is built on it</li>
<li>the vector of song A, the best Match. We answer which parts of the query made it go to song A? we use song A as direction of analysis.</li>
<li>the vector of song B.</li>
</ul>
<div id="f9f4b81e46c14cf8" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:57.107207Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:56.565415Z&quot;}}" data-execution_count="77">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb54" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb54-1">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.keras.models.load_model(</span>
<span id="cb54-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/app/speccy_model"</span>,</span>
<span id="cb54-3">    custom_objects<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cosine_proximity'</span>: tf.compat.v1.keras.losses.cosine_proximity}</span>
<span id="cb54-4">)</span>
<span id="cb54-5">model.trainable <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span></code></pre></div></div>
</div>
<div id="5321167dc9684234" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:57.304773Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:57.128786Z&quot;}}" data-execution_count="78">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb55" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb55-1">query_slices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mp3_to_slices(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/app/data/raw-previews/combined/Purple Rain - Prince.mp3"</span>)</span>
<span id="cb55-2">b_slices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mp3_to_slices(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/app/data/raw-previews/combined/Everybody Wants To Rule The World - Tears For Fears.mp3"</span>)</span></code></pre></div></div>
</div>
<div id="428d4b24f4f98da8" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:57.352082Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:57.347091Z&quot;}}" data-execution_count="79">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb56" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb56-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pickle</span>
<span id="cb56-2"></span>
<span id="cb56-3"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/app/data/pickles/combined/mp3tovecs/mp3tovec.p"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rb"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb56-4">    mp3tovecs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pickle.load(f)</span>
<span id="cb56-5"></span>
<span id="cb56-6">vec_A <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mp3tovecs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/opt/project/data/raw-previews/combined/Mesmerise - Temples.mp3'</span>]</span>
<span id="cb56-7">vec_B <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mp3tovecs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/opt/project/data/raw-previews/combined/Everybody Wants To Rule The World - Tears For Fears.mp3'</span>]</span></code></pre></div></div>
</div>
<p>Let’s confirm shapes</p>
<div id="82906c90800be6ef" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:57.451594Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:57.447122Z&quot;}}" data-execution_count="80">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb57" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb57-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(query_slices.shape)</span>
<span id="cb57-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(model.input_shape)</span>
<span id="cb57-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(vec_A.shape)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>(5, 96, 216, 1)
(None, 96, 216, 1)
(100,)</code></pre>
</div>
</div>
</section>
<section id="method-1" class="level4" data-number="5.3.2">
<h4 data-number="5.3.2" class="anchored" data-anchor-id="method-1"><span class="header-section-number">5.3.2</span> Method 1</h4>
<p>We first run method 1, using silence as baseline.</p>
<div id="d65ab5de3705709f" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:57.870287Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:57.513910Z&quot;}}" data-execution_count="81">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb59" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb59-1">ig_raw_a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_one_slice_smooth(</span>
<span id="cb59-2">    model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model,</span>
<span id="cb59-3">    query_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>query_slices[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>],</span>
<span id="cb59-4">    target_vec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.nn.l2_normalize(tf.convert_to_tensor(vec_A, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32), axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),</span>
<span id="cb59-5">    baseline_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb59-6">    score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cosine_score_fn,</span>
<span id="cb59-7">)</span>
<span id="cb59-8"></span>
<span id="cb59-9">ig_raw_b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_one_slice_smooth(</span>
<span id="cb59-10">    model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model,</span>
<span id="cb59-11">    query_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>query_slices[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>],</span>
<span id="cb59-12">    target_vec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.nn.l2_normalize(tf.convert_to_tensor(vec_B, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32), axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),</span>
<span id="cb59-13">    baseline_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb59-14">    score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cosine_score_fn,</span>
<span id="cb59-15">)</span>
<span id="cb59-16">ig_contrast_method_1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (ig_raw_a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> ig_raw_b)</span></code></pre></div></div>
</div>
<div id="7621e3bf2f80065f" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:58.090025Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:57.918730Z&quot;}}" data-execution_count="82">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb60" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb60-1">rgba_img, smoothed_mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> highlight_ig_regions(ig_contrast_method_1, percentile<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">99</span>, sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5.0</span>)</span>
<span id="cb60-2">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb60-3">plt.imshow(rgba_img, origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lower"</span>, aspect<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"auto"</span>)</span>
<span id="cb60-4">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Aggregated IG – why model prefers Song A over Song B"</span>)</span>
<span id="cb60-5">plt.colorbar(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A &gt; B (red)   |   B &gt; A (blue)"</span>)</span>
<span id="cb60-6">plt.tight_layout()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb60-7">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-51-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>There is not much insight that we can gain from this picture. We will see if the full song analysis can help. We define a function that assembles the full heatmap.</p>
<div id="643080663bd20548" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:58.139698Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:58.136036Z&quot;}}" data-execution_count="83">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb61" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb61-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> full_song_contrastive_ig_method1(</span>
<span id="cb61-2">        model,</span>
<span id="cb61-3">        query_slices,</span>
<span id="cb61-4">        vec_A,</span>
<span id="cb61-5">        vec_B,</span>
<span id="cb61-6">        score_fn,</span>
<span id="cb61-7">        steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span>,</span>
<span id="cb61-8">        sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb61-9">):</span>
<span id="cb61-10">    n_slices, H, W, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> query_slices.shape</span>
<span id="cb61-11">    full_contrast <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros((H, n_slices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> W), dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.float32)</span>
<span id="cb61-12"></span>
<span id="cb61-13">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Normalize target vectors once</span></span>
<span id="cb61-14">    vec_a_tf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.nn.l2_normalize(tf.convert_to_tensor(vec_A, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32), axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb61-15">    vec_b_tf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.nn.l2_normalize(tf.convert_to_tensor(vec_B, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32), axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb61-16"></span>
<span id="cb61-17">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># iterate over all slices</span></span>
<span id="cb61-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n_slices):</span>
<span id="cb61-19">        q_slice <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> query_slices[i:i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb61-20"></span>
<span id="cb61-21">        ig_a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_one_slice_smooth(</span>
<span id="cb61-22">            model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model,</span>
<span id="cb61-23">            query_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>q_slice,</span>
<span id="cb61-24">            target_vec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>vec_a_tf,</span>
<span id="cb61-25">            baseline_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb61-26">            score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>score_fn,</span>
<span id="cb61-27">            steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>steps,</span>
<span id="cb61-28">            sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sigma</span>
<span id="cb61-29">        )</span>
<span id="cb61-30"></span>
<span id="cb61-31">        ig_b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_one_slice_smooth(</span>
<span id="cb61-32">            model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model,</span>
<span id="cb61-33">            query_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>q_slice,</span>
<span id="cb61-34">            target_vec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>vec_b_tf,</span>
<span id="cb61-35">            baseline_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb61-36">            score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>score_fn,</span>
<span id="cb61-37">            steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>steps,</span>
<span id="cb61-38">            sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sigma</span>
<span id="cb61-39">        )</span>
<span id="cb61-40"></span>
<span id="cb61-41">        ig_contrast <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> ig_b</span>
<span id="cb61-42"></span>
<span id="cb61-43">        full_contrast[:, i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> W:(i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> W] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_contrast</span>
<span id="cb61-44"></span>
<span id="cb61-45">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> full_contrast</span>
<span id="cb61-46">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># (H,W)</span></span></code></pre></div></div>
</div>
<p>… and run it.</p>
<div id="ac0f8d17d7261809" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:53:59.950539Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:58.227006Z&quot;}}" data-execution_count="84">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb62" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb62-1">full_ig_method_1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> full_song_contrastive_ig_method1(</span>
<span id="cb62-2">    model,</span>
<span id="cb62-3">    query_slices<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>query_slices,</span>
<span id="cb62-4">    vec_A<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>vec_A,</span>
<span id="cb62-5">    vec_B<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>vec_B,</span>
<span id="cb62-6">    score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cosine_score_fn,</span>
<span id="cb62-7">)</span></code></pre></div></div>
</div>
<div id="b214475eff1457" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:54:00.223554Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:53:59.990945Z&quot;}}" data-execution_count="85">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb63" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb63-1">rgba_img, smoothed_mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> highlight_ig_regions(full_ig_method_1, percentile<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">99</span>, sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">8.0</span>)</span>
<span id="cb63-2">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb63-3">plt.imshow(rgba_img, origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lower"</span>, aspect<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"auto"</span>)</span>
<span id="cb63-4">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Aggregated IG – why model prefers Song A over Song B"</span>)</span>
<span id="cb63-5">plt.colorbar(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A &gt; B (red)   |   B &gt; A (blue)"</span>)</span>
<span id="cb63-6">plt.tight_layout()</span>
<span id="cb63-7">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-54-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>The result is somewhat disappointing. Overall, the algorithm should have identified song B as the next song. There are only some red spots at the bottom in the lower frequencies.</p>
<p>Let’s again switch to a quantitative analysis and plot frequencies in bins.</p>
<div id="93863da8358c1c01" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:54:00.800674Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:54:00.308517Z&quot;}}" data-execution_count="86">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb64" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb64-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> librosa</span>
<span id="cb64-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb64-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb64-4"></span>
<span id="cb64-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Simulated IG data, for example,</span></span>
<span id="cb64-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Replace with your actual full_ig array</span></span>
<span id="cb64-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_ig_to_bins(full_ig):</span>
<span id="cb64-8">    band <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> full_ig.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb64-9">    sr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22050</span></span>
<span id="cb64-10">    num_bins <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">96</span></span>
<span id="cb64-11">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Mel frequency bin edges and centers</span></span>
<span id="cb64-12">    mel_edges <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> librosa.mel_frequencies(n_mels<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>full_ig.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, fmin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, fmax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb64-13"></span>
<span id="cb64-14">    centres <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (mel_edges[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> mel_edges[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># in kHz</span></span>
<span id="cb64-15">    mel_widths <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.diff(librosa.hz_to_mel(mel_edges))</span>
<span id="cb64-16"></span>
<span id="cb64-17">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Color by attribution sign</span></span>
<span id="cb64-18">    colors <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.where(band <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"crimson"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"royalblue"</span>)</span>
<span id="cb64-19">    ig, axs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>), sharey<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb64-20"></span>
<span id="cb64-21">    new_mel_edges <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(band), num_bins <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>)</span>
<span id="cb64-22"></span>
<span id="cb64-23">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Aggregate original bins into fewer bins</span></span>
<span id="cb64-24">    band_reduced <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([</span>
<span id="cb64-25">        band[new_mel_edges[i]:new_mel_edges[i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>()</span>
<span id="cb64-26">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_bins)</span>
<span id="cb64-27">    ])</span>
<span id="cb64-28"></span>
<span id="cb64-29">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Compute centers of the new bins (in kHz)</span></span>
<span id="cb64-30">    mel_centers_reduced <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([</span>
<span id="cb64-31">        (mel_edges[new_mel_edges[i]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> mel_edges[new_mel_edges[i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span></span>
<span id="cb64-32">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_bins)</span>
<span id="cb64-33">    ])</span>
<span id="cb64-34"></span>
<span id="cb64-35">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Colors based on attribution sign</span></span>
<span id="cb64-36">    colors <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.where(band_reduced <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"crimson"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"royalblue"</span>)</span>
<span id="cb64-37"></span>
<span id="cb64-38">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- Left: Simple index-based plot ---</span></span>
<span id="cb64-39">    axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].bar(np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(band)), band, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>colors, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'black'</span>)</span>
<span id="cb64-40">    axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X-axis: Mel Band Index (0–95)"</span>)</span>
<span id="cb64-41">    axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mel Band Index"</span>)</span>
<span id="cb64-42">    axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Net Attribution"</span>)</span>
<span id="cb64-43">    axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].axhline(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k'</span>, linewidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>)</span>
<span id="cb64-44"></span>
<span id="cb64-45">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- Right: Mel-scale-accurate plot ---</span></span>
<span id="cb64-46">    plt.bar(mel_centers_reduced, band_reduced,</span>
<span id="cb64-47">            width<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.diff(mel_edges[new_mel_edges]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>,</span>
<span id="cb64-48">            color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>colors, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'black'</span>)</span>
<span id="cb64-49">    axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X-axis: Frequency (kHz)"</span>)</span>
<span id="cb64-50">    axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Frequency (kHz)"</span>)</span>
<span id="cb64-51">    axs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].axhline(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k'</span>, linewidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>)</span>
<span id="cb64-52"></span>
<span id="cb64-53">    plt.tight_layout()</span>
<span id="cb64-54">    plt.suptitle(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Comparison: Index vs Khz Attribution"</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.05</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>)</span>
<span id="cb64-55">    plt.show()</span>
<span id="cb64-56"></span>
<span id="cb64-57"></span>
<span id="cb64-58">plot_ig_to_bins(full_ig_method_1)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-55-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>The heatmap is transformed into two barcharts:</p>
<ul>
<li><p>As mel band index (aligned with the vertical axis of the IG heatmap)</p></li>
<li><p>Converted to real-world frequency in kHz. We can see the nonlinear nature of the mel scale from this.</p></li>
</ul>
<p>Both songs seem quite balanced in terms of attribution. It is not clear why the song was picked.</p>
<p>One potential reason: The embeddings are very close. Therefore, the noise in the gradient generation dominates. We can rerun the analysis with smoothing per slice.</p>
<div id="d171034f36be9ba7" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:54:02.941542Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:54:00.881519Z&quot;}}" data-execution_count="87">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb65" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb65-1">full_ig_method_1_smoothed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> full_song_contrastive_ig_method1(</span>
<span id="cb65-2">    model,</span>
<span id="cb65-3">    query_slices<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>query_slices,</span>
<span id="cb65-4">    vec_A<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>vec_A,</span>
<span id="cb65-5">    vec_B<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>vec_B,</span>
<span id="cb65-6">    score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cosine_score_fn,</span>
<span id="cb65-7">    sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span></span>
<span id="cb65-8">)</span>
<span id="cb65-9">plot_ig_to_bins(full_ig_method_1_smoothed)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-56-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>The smoothing made the graphs easier to read. Attribution is very low. Song B is better in the low frequencies. Whereas a song A is better in the high frequencies. The graphs look nice, but there is a catch… Let’s look at method2 first.</p>
</section>
<section id="method-2" class="level4" data-number="5.3.3">
<h4 data-number="5.3.3" class="anchored" data-anchor-id="method-2"><span class="header-section-number">5.3.3</span> Method 2</h4>
<p>In the presence of weak gradients, method 2 suggests not calculating extra differences but using a single scoring function. This is done by making song B the baseline.</p>
<section id="implementation-1" class="level5" data-number="5.3.3.1">
<h5 data-number="5.3.3.1" class="anchored" data-anchor-id="implementation-1"><span class="header-section-number">5.3.3.1</span> Implementation</h5>
<div id="369e4db63e602b03" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:54:03.020Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:54:03.014939Z&quot;}}" data-execution_count="88">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb66" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb66-1"></span>
<span id="cb66-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> full_song_ig_method_2(</span>
<span id="cb66-3">        model,</span>
<span id="cb66-4">        query_slices,</span>
<span id="cb66-5">        vec_A,</span>
<span id="cb66-6">        baseline_slices,</span>
<span id="cb66-7">        score_fn,</span>
<span id="cb66-8">        steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span>,</span>
<span id="cb66-9">        sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb66-10">):</span>
<span id="cb66-11">    n_slices, H, W, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> query_slices.shape</span>
<span id="cb66-12">    full_contrast <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros((H, n_slices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> W), dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.float32)</span>
<span id="cb66-13"></span>
<span id="cb66-14">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Normalize target vectors once</span></span>
<span id="cb66-15">    vecA_tf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tf.nn.l2_normalize(tf.convert_to_tensor(vec_A, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>tf.float32), axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb66-16"></span>
<span id="cb66-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n_slices):</span>
<span id="cb66-18">        q_slice <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> query_slices[i:i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb66-19">        b_slice <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> baseline_slices[i:i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb66-20"></span>
<span id="cb66-21">        ig_slice_m2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_one_slice_smooth(</span>
<span id="cb66-22">            model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model,</span>
<span id="cb66-23">            query_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>q_slice,</span>
<span id="cb66-24">            target_vec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>vecA_tf,</span>
<span id="cb66-25">            baseline_slice<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>b_slice,</span>
<span id="cb66-26">            score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>score_fn,</span>
<span id="cb66-27">            steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>steps,</span>
<span id="cb66-28">            sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sigma</span>
<span id="cb66-29">        )</span>
<span id="cb66-30"></span>
<span id="cb66-31">        full_contrast[:, i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> W:(i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> W] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ig_slice_m2.squeeze()</span>
<span id="cb66-32"></span>
<span id="cb66-33">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> full_contrast</span></code></pre></div></div>
</div>
</section>
<section id="without-filtering" class="level5" data-number="5.3.3.2">
<h5 data-number="5.3.3.2" class="anchored" data-anchor-id="without-filtering"><span class="header-section-number">5.3.3.2</span> Without Filtering</h5>
<div id="8341ed514d3839e1" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:54:03.948004Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:54:03.083675Z&quot;}}" data-execution_count="89">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb67" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb67-1">full_ig_method_2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> full_song_ig_method_2(</span>
<span id="cb67-2">    model,</span>
<span id="cb67-3">    query_slices<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>query_slices,</span>
<span id="cb67-4">    vec_A<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>vec_A,</span>
<span id="cb67-5">    baseline_slices<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>b_slices,</span>
<span id="cb67-6">    score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cosine_score_fn,</span>
<span id="cb67-7">)</span></code></pre></div></div>
</details>
</div>
<div id="35729781298daa9b" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:54:04.216201Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:54:03.977195Z&quot;}}" data-execution_count="90">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb68" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb68-1">rgba_img, smoothed_mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> highlight_ig_regions(full_ig_method_2, percentile<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">95</span>, sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.5</span>)</span>
<span id="cb68-2">plt.figure(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb68-3"></span>
<span id="cb68-4">plt.imshow(rgba_img, origin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lower"</span>, aspect<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"auto"</span>)</span>
<span id="cb68-5">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Aggregated IG – why model prefers Song A over Song B"</span>)</span>
<span id="cb68-6">plt.colorbar(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A &gt; B (red)   |   B &gt; A (blue)"</span>)</span>
<span id="cb68-7">plt.tight_layout()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb68-8">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-59-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="945112ddf14342b5" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:54:04.638949Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:54:04.307379Z&quot;}}" data-execution_count="91">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb69" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb69-1">plot_ig_to_bins(full_ig_method_2)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-60-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="with-filtering" class="level4" data-number="5.3.4">
<h4 data-number="5.3.4" class="anchored" data-anchor-id="with-filtering"><span class="header-section-number">5.3.4</span> With Filtering</h4>
<div id="2ce00f2ced43fa78" class="cell" data-quarto-private-1="{&quot;key&quot;:&quot;ExecuteTime&quot;,&quot;value&quot;:{&quot;end_time&quot;:&quot;2025-07-15T11:54:05.912397Z&quot;,&quot;start_time&quot;:&quot;2025-07-15T11:54:04.720761Z&quot;}}" data-execution_count="92">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb70" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb70-1">full_ig_method_2_smoothed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> full_song_ig_method_2(</span>
<span id="cb70-2">    model,</span>
<span id="cb70-3">    query_slices<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>query_slices,</span>
<span id="cb70-4">    vec_A<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>vec_A,</span>
<span id="cb70-5">    baseline_slices<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>b_slices,</span>
<span id="cb70-6">    score_fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cosine_score_fn,</span>
<span id="cb70-7">    sigma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span></span>
<span id="cb70-8">)</span>
<span id="cb70-9">plot_ig_to_bins(full_ig_method_2_smoothed)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/deejai/explainability_files/figure-html/cell-61-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Now, Song A is favored in the lower frequencies, while Song B shows more influence in the upper bands.</p>
</section>
</section>
<section id="conclusion-method-1-vs.-method-2" class="level3" data-number="5.4">
<h3 data-number="5.4" class="anchored" data-anchor-id="conclusion-method-1-vs.-method-2"><span class="header-section-number">5.4</span> Conclusion Method 1 vs.&nbsp;Method 2</h3>
<p>One possible reason why Method 1 (subtracting filtered IGs) gives misleading results: If we apply Gaussian filtering before computing the difference, we might distort subtle but meaningful gradients. Since the raw attributions are weak overall, smoothing may disproportionately amplify or suppress regions — leading to an inaccurate contrast map. In fact, the raw IG maps for A and B look much more similar, and only diverge sharply after filtering.</p>
<p>This suggests that Method 2, which uses a single contrastive score function (sim(x, A) - sim(x, B)), is more stable and reliable in cases where the attribution signal is weak and gradients are low.</p>
</section>
<section id="interpretation" class="level3" data-number="5.5">
<h3 data-number="5.5" class="anchored" data-anchor-id="interpretation"><span class="header-section-number">5.5</span> Interpretation</h3>
<p>Assuming Method 2 provides the correct contrastive explanation, we can proceed with an interpretation. Overall, a Song A is a much better match in the low and mid-frequencies. These findings suggest that the song A’s similarity to the query (in this case, Purple Rain) is driven by features like kick drums, basslines, or low-mid instrumentation — all of which live in those bands.</p>
<p>Between 5 kHz and 9 kHz, we see increasing attribution for Song B. These frequencies often correspond to vocals, snares, cymbals, or presence-related features.</p>
<p>Interestingly, I listened to the tracks on a phone-conference headset, which emphasizes exactly that frequency range. So this auditory similarity aligns with what we hear — and validates the contrastive IG result.</p>
</section>
</section>
<section id="summary" class="level2" data-number="6">
<h2 data-number="6" class="anchored" data-anchor-id="summary"><span class="header-section-number">6</span> Summary</h2>
<section id="what-did-we-learn" class="level3" data-number="6.1">
<h3 data-number="6.1" class="anchored" data-anchor-id="what-did-we-learn"><span class="header-section-number">6.1</span> What did we learn?</h3>
<p>T-SNE analysis showed no clear clusters labeled “silent” or “party.” My subjective categories don’t appear to have a strong representation in the embedding space — at least not visibly</p>
<p>For two nearly identical songs:</p>
<ul>
<li><p>T-SNE placed their embeddings close together in 2D space, confirming high similarity.</p></li>
<li><p>Grad-CAM revealed that Song A (the model’s top match) contained more regions that aligned well with the query’s audio features.</p></li>
<li><p>Integrated Gradients highlighted that Song A had stronger matches in the lower frequencies, whereas my personal impression focused on higher-frequency features where Song B was better.</p></li>
</ul>
</section>
<section id="take-away" class="level3" data-number="6.2">
<h3 data-number="6.2" class="anchored" data-anchor-id="take-away"><span class="header-section-number">6.2</span> Take away</h3>
<p>Streaming platforms don’t just recommend popular songs; they can also suggest new or unknown music by analyzing the audio content directly through audio embeddings. While commercial systems use more advanced models and larger infrastructure, the core principles are the same as the methods demonstrated here. In addition, platforms incorporate collaborative filtering, user history, and social data to drive final recommendations.</p>
<p>What started as an experiment with a small CNN and a few audio clips turned into a concrete example of how machines “hear” music. Deep learning allows us to go beyond surface-level metadata like genre or artist, learning fine-grained acoustic patterns directly from the audio.</p>
<p>By exploring techniques like Grad-CAM, Integrated Gradients, and embedding visualization, we’ve opened a window into how machine learning models make decisions about music — and how we can interpret those decisions.</p>
<p>This type of analysis helps explain:</p>
<ul>
<li><p>Why a recommendation “feels right”; even if you can’t explain it yourself</p></li>
<li><p>Why playlist transitions often make musical sense, even when songs come from different genres</p></li>
</ul>
<p>If a basic model trained on a few spectrogram slices can already show interpretable behavior, imagine the scale and nuance of systems like Spotify, Apple Music, or TikTok.</p>
<p>This project isn’t just about “how one match happened.” It’s a glimpse into how modern recommendation systems think. Understanding these systems is important for a thoughtful usage.</p>


</section>
</section>

 ]]></description>
  <category>Computer Vision</category>
  <category>Generative AI</category>
  <category>Python</category>
  <guid>https://www.storymelange.com/posts/projects/deejai/deejai-xai.html</guid>
  <pubDate>Tue, 15 Jul 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>The Rebirth of the recipescanner - part 2</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/recipescanner/the-rebirth-of-the-recipescanner-part.html</link>
  <description><![CDATA[ 




<section id="what-happenend-in-part-1" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="what-happenend-in-part-1"><span class="header-section-number">1</span> What happenend in part 1</h2>
<section id="mealplanning-paralysis" class="level3" data-number="1.1">
<h3 data-number="1.1" class="anchored" data-anchor-id="mealplanning-paralysis"><span class="header-section-number">1.1</span> Meal‑planning paralysis</h3>
<p>Turning half a shelf of cookbooks into a week’s meals shouldn’t take longer than cooking itself. Yet this frequently happenend to me, when I tried to&nbsp;get recipes from my books, copy ingredients, and build a shopping list by hand. Family life can be stressful, and who has time to read through all the books and make creative meal plans? Me, no.</p>
</section>
<section id="recipescanner-previous-versions" class="level3" data-number="1.2">
<h3 data-number="1.2" class="anchored" data-anchor-id="recipescanner-previous-versions"><span class="header-section-number">1.2</span> Recipescanner, previous versions</h3>
<p>My first attempt at this was the <code>Recipescanner</code>, see <a href="../../../posts/projects/recipescanner/the-rebirth-of-the-recipescanner.html">part 1</a> In his different versions it turned Book pages in Paprika recipes. Aggregation of the cooking list was done by Paprika. This saved time with the mechanical tasks, but not with creativity. I still hat to hunt for the dishes, which fit well together.</p>
</section>
</section>
<section id="attempt-2-just-ask-chatgpt" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="attempt-2-just-ask-chatgpt"><span class="header-section-number">2</span> Attempt #2 “Just ask ChatGPT”</h2>
<p>Lately I noticed I will just turn to ChatGPT. While the recipes are quite ok, there often lack the little extra. Good cookbooks and special food blogs often provide this extra information. To my experience, online recipe collections do not provide all the little tricks in the recipe, as average cooks often write them. The same applies for complete meal plans. Ok, but somehow not that fascinating.</p>
<p>LLMs usually provide the average answers. And average cooks do not have recipes with the certain sparkle. Skillful prompt engineering or follow-up prompts could certainly surface this information from the vast amount of training data.</p>
<p>I think the main issue is one of uncertainty. You assume that there are special tricks for a recipe you do not know. But you do not know in what area of cooking they are: preparation, order of adding, temperature? Doing so requires often a very skillful intuition. In my experience, why expert programmers can get so much more from LLMs than beginners for programming? They have the intuition to ask the right questions.</p>
</section>
<section id="idea-lets-just-chat-about-our-recipes" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="idea-lets-just-chat-about-our-recipes"><span class="header-section-number">3</span> Idea: Let’s just chat about our recipes</h2>
<p>For our recipes, the solution could be easier. We rephrase the question. Instead of asking for the generation of a new (unique) recipe, we ask just to select from a collection of known recipes. This assumes our recipe collection only has outstanding books and notes, but we do not remember where to look.</p>
<p>What we would then do is a simple vector-based similarity search, which fits our request. Then we either just furnish the recipes or we make up a recipe based on the recipes we found. In the second case, it is much more likely that the answer contains the little extra we search.</p>
<p>The entire process of querying a database before generation is called Retrieval Augmented Generation (RAG).</p>
<p>This is something which can be done with local chat apps. <code>Gpt4all</code> can create embeddings for the recipes and use a generic chat to talk about them.</p>
<section id="going-beyond-chatting" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="going-beyond-chatting"><span class="header-section-number">3.1</span> Going beyond chatting</h3>
<p>But wait, there is more we could do. When we create a meal plan and a shopping list, we create data. We could use that data.</p>
<p>What if we had an agent? We could ask to generate plans for us based on our wishes. It could also check what weekly promotions exist or offer seasonal suggestions. Even better, you would know what you cooked last week. He could know what you like and could ask what you liked or disliked about last week’s meals.</p>
<p>It is like a personal chef. Only he does not cook. Maybe that could be an extension :-).</p>
<p>This article is not only about the history of the recipescanner. It is the kickoff to an endeavour to create an AI agent that chats with about recipes and meal plans.</p>
</section>
</section>
<section id="getting-to-work" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="getting-to-work"><span class="header-section-number">4</span> Getting to work</h2>
<section id="product-engineering-meets-ai-agent" class="level3" data-number="4.1">
<h3 data-number="4.1" class="anchored" data-anchor-id="product-engineering-meets-ai-agent"><span class="header-section-number">4.1</span> Product engineering meets AI Agent</h3>
<p>The general direction is clear. A software that does all the meal planning.</p>
<p>With all the hype about AI agent, we are going to build one.</p>
<p>One issue, what kind of tool should the agent actually work with. Integrating it with Paprika, my current app is too complex. I could certainly search for a basic recipe app and try to integrate it.</p>
<p>One key aspect of my workflow is the digitalization. Few to no apps have this in a way I want it. Therefore, I built a meal planner from scratch with Python and React.</p>
<p>There is some upfront work to generate the meal planned before getting to the actual LLM work.</p>
<p>The Versions I currently aim for:</p>
<ol type="1">
<li><p>Replacement of current Paprika based workflow. Web-app for manual recipe handling via frontend. Basic chat app with different model providers (local for testing and online for better performance). Scanning and Recipe generation, as in the previous version.</p></li>
<li><p>A Langgraph based chat app to talk about recipes in database and meal plans. RAG Chat.</p></li>
<li><p>Trigger creation of new recipes and meal plans. Iterative workflow.</p></li>
<li><p>Take nutritional and seasonal information into account. Diet plan. Backfill missing data in recipes.</p></li>
</ol>
</section>
<section id="how-to-start" class="level3" data-number="4.2">
<h3 data-number="4.2" class="anchored" data-anchor-id="how-to-start"><span class="header-section-number">4.2</span> How to start</h3>
<p>Back to software engineering. In <a href="../../../posts/projects/uml-analyser/do-you-know-the-hidden-paths-of-your-code.html">Do you know the hidden paths of your code</a>, I talked about the importance of architecture.</p>
<p>Another question I follow in this project: LLMs are a big missing puzzle piece in creating better architecture, but how to use them effectively? With all the hype on AI code generation, I was quite optimistic. I would advance with the legacy part.</p>
<p>After a lot of discussion, I asked ChatGPT to create a good starting prompt for my idea:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb1-1">You are a senior full-stack engineer and AI-agent architect.  </span>
<span id="cb1-2">Task: walk me step-by-step through building a **chat-based weekly meal-planner** with these features:</span>
<span id="cb1-3"></span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">1. </span>**Tech stack**  </span>
<span id="cb1-6"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Python 3.12, FastAPI backend  </span>
<span id="cb1-7"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Postgres + pgvector for recipes &amp; embeddings  </span>
<span id="cb1-8"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>LangChain + LangGraph for an agent with a planning loop and persistent state  </span>
<span id="cb1-9"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>OR-Tools (or PuLP) to solve the nutrient/effort constraint model  </span>
<span id="cb1-10"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>React (Vite) chat UI</span>
<span id="cb1-11"></span>
<span id="cb1-12"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">1. </span>**Core requirements**  </span>
<span id="cb1-13"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>take pictures and use google ocr to get json</span>
<span id="cb1-14"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Ingest/parse recipe JSON → add tags, nutrition, effort minutes, fill a database entry. currently i use paprika recipes format to store data</span>
<span id="cb1-15"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>bulk mode for pictures</span>
<span id="cb1-16"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Vector search for recipe Q&amp;A (RAG node)  </span>
<span id="cb1-17"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Planning node builds a 7-day plan that:  </span>
<span id="cb1-18">     • hits user kcal/macro targets ±10 %  </span>
<span id="cb1-19">     • caps hands-on cooking time per day  </span>
<span id="cb1-20">     • avoids any recipe used in the previous 3 weeks  </span>
<span id="cb1-21"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Approval loop: if the user types “change”, the graph re-plans until accepted  </span>
<span id="cb1-22"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>On acceptance, write <span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">`meal_plan`</span> table and return a shopping list grouped by aisle  </span>
<span id="cb1-23"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Persist <span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">`recent_recipes`</span> (rolling 21 recipes) and chat history in Redis</span>
<span id="cb1-24"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>ui: similar to chatgpt. left side menu and session overview. ability to browse through recipes. should work on desktop and mobile.</span>
<span id="cb1-25"></span>
<span id="cb1-26"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">3. </span>**Deliverables to produce in this session**  </span>
<span id="cb1-27"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>High-level architecture diagram  </span>
<span id="cb1-28"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Database schema SQL  </span>
<span id="cb1-29"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>LangGraph code skeleton with nodes and edges  </span>
<span id="cb1-30"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Sample FastAPI route that streams assistant responses  </span>
<span id="cb1-31"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Minimal React chat component calling the API  </span>
<span id="cb1-32"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">   - </span>Docker-compose file for Postgres+backend</span>
<span id="cb1-33"></span>
<span id="cb1-34">Give concise explanations; focus on runnable code and folder structure. Assume I know the basics—skip introductions. After each section, wait for my “next” before continuing.</span></code></pre></div></div>
<p>In stage 3, we already see the issue. The computer would dive directly into coding. With such an extensive project that would lead to a big mess.</p>
<p>Instead, I spent some time on the architecture. You can find the details below.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/Meal_Planner_Component_Diagram.svg" class="img-fluid figure-img"></p>
<figcaption>The first version offered by the language model. Without diving into the details. There seem to be too many blocks.</figcaption>
</figure>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/Meal_Planner_Component_Diagram__Simplified_.svg" class="img-fluid figure-img"></p>
<figcaption>After some modifications I settled on this.</figcaption>
</figure>
</div>
<p>This leads me to the next big issue. Big bang building is equal to the Big bang integration. As such, we need incremental working versions.</p>
<p>I kicked it off with a JetBrains AI Assitant do the coding. It started with the impressive generation of 47 files and a fully functional mocked frontend.</p>
<p>Wow, at that speed, I would finish in a week.</p>
<p>Well,…</p>
<p>…</p>
<p>Spoiler for the next article. Not so fast. Remember: “The only way to go fast is to go well”. And it turned out the LLM does not go well for bigger projects.</p>


</section>
</section>

 ]]></description>
  <category>Software Engineering</category>
  <category>Generative AI</category>
  <category>Python</category>
  <guid>https://www.storymelange.com/posts/projects/recipescanner/the-rebirth-of-the-recipescanner-part.html</guid>
  <pubDate>Mon, 07 Jul 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>From damping factor to learning rate</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/technical/from-damping-factor-to-learning-rate.html</link>
  <description><![CDATA[ 




<section id="my-journey-in-the-land-of-machine-learning" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="my-journey-in-the-land-of-machine-learning"><span class="header-section-number">1</span> My journey in the land of Machine Learning</h2>
<p>When I first heard about machine learning in the middle of the 2010s, it occurred as a big black box for me. I have a PhD in computational material science, and as such, find the concepts quite easy to grasp. Yet, I am often stunned how similar yet how different the fields are.</p>
<p>The core difference is that people in these fields receive different training and have developed aptitudes for different terms and jargon.</p>
<p>I often find the ML jargon difficult to understand. However, once you get your head around it, it actually becomes easier to understand.</p>
<p>Before getting deeper in the field, I found it hard to accept the pretentious term of <code>learning</code>.</p>
<p>How were systems supposed to learn, as we humans learn? When you scratch the surface, you clearly recognize that the learning is an optimization algorithm.</p>
<p>In this blog I want to focus on the particular technical term of the <code>learning rate</code>. From the outside, this is the rate of learning of our algorithm. But what does it mean for the mathematically learned fellow? Especially, what does it mean to all the computational scientists?</p>
<p>In the following, I will contrast the concept in ML with the very similar approach in the finite element method, known too many physical computational scientists.</p>
</section>
<section id="fem" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="fem"><span class="header-section-number">2</span> FEM</h2>
<section id="background" class="level3" data-number="2.1">
<h3 data-number="2.1" class="anchored" data-anchor-id="background"><span class="header-section-number">2.1</span> Background</h3>
<p>The Finite Element Method (FEM) began in the 1940s for aerospace structural analysis and grew with computing advances in the 1950s–60s. It works by breaking down complex structures into smaller, manageable elements, solving equations over these elements, and assembling the results. Today, FEM is vital in simulating real-world physics across engineering and science.</p>
</section>
<section id="fem-and-the-step-size-in-line-search" class="level3" data-number="2.2">
<h3 data-number="2.2" class="anchored" data-anchor-id="fem-and-the-step-size-in-line-search"><span class="header-section-number">2.2</span> FEM and the step size in line search</h3>
<p>In mechanical application of the finite element method, we are interest to solve the equation: <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BK%7D%20%5Cmathbf%7Bu%7D%20=%20%5Cmathbf%7Bf%7D_%7B%5Ctext%7Bext%7D%7D"></p>
<p>where:</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BK%7D"> is the global stiffness matrix.</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bu%7D"> are the nodal displacements (unknowns).</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bf%7D_%7B%5Ctext%7Bext%7D%7D"> are the nodal forces.</li>
</ul>
<p>The residual is <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Br%7D=%5Cmathbf%7Bf%7D_%7B%5Ctext%7Bext%7D%7D-%5Cmathbf%7BK%7D%5Cmathbf%7Bu%7D">.</p>
<p>A gradient-descent-based update rule takes the form:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cmathbf%7Bu%7D_%7Bt+1%7D%20=%20%5Cmathbf%7Bu%7D_t%20-%20%5Calpha%20(%5Cmathbf%7BK%7D%20%5Cmathbf%7Bu%7D_t-%5Cmathbf%7Bf%7D_%7B%5Ctext%7Bext%7D%7D)%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Calpha"> is the step size or damping factor, which controls update magnitude.</p>
<p>In a linear system we can use a potential to describe this</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cnabla_%7B%5Cmathbf%7Bu%7D%7D%20%5CPi=%5Cmathbf%7BK%7D%20%5Cmathbf%7Bu%7D_t-%5Cmathbf%7Bf%7D_%7B%5Ctext%7Bext%7D%7D"></p>
<p>so we get</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cmathbf%7Bu%7D_%7Bt+1%7D%20=%20%5Cmathbf%7Bu%7D_t%20-%20%5Calpha%20%5Cnabla_%7B%5Cmathbf%7Bu%7D%7D%20%5CPi%0A"></p>
<p>An illustration is in the following picture.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/technical/Gradient_descent.svg" class="img-fluid figure-img"></p>
<figcaption>The step size is the length of each arrow.</figcaption>
</figure>
</div>
<p>If computational resources allow and the matrix <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BK%7D"> is not too large, a <strong>direct solution</strong> can be obtained using:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bu%7D%20=%20%5Cmathbf%7BK%7D%5E%7B-1%7D%20%5Cmathbf%7Bf%7D_%7B%5Ctext%7Bext%7D%7D"></p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Notation
</div>
</div>
<div class="callout-body-container callout-body">
<p>In this document I use <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bx%7D"> for a vector and <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D"> for a matrix.</p>
</div>
</div>
</section>
<section id="influence-of-nonlinearity" class="level3" data-number="2.3">
<h3 data-number="2.3" class="anchored" data-anchor-id="influence-of-nonlinearity"><span class="header-section-number">2.3</span> Influence of Nonlinearity</h3>
<p>For linear mechanics, the solution is straightforward. The issue arises only when we introduce non-linearity.</p>
<p>Nonlinearities arise from</p>
<ul>
<li>large displacement paths,</li>
<li>large rotations</li>
<li>energy dissipating process (plasticity)</li>
<li>damping</li>
</ul>
<p>In the presence of large displacements, these non-linearities lead to ill-conditioning of the matrix <img src="https://latex.codecogs.com/png.latex?K">. A tiny step size would be necessary unless matrix K is adapted. Many solution algorithms exist.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bu%7D_%7Bt+1%7D%20=%20%5Cmathbf%7Bu%7D_t%20+%20%5Calpha_t%20%5Cmathbf%7BK%7D%5E%7B-1%7D%20%5Cmathbf%7Br%7D_t"></p>
<p>We find the optimal <img src="https://latex.codecogs.com/png.latex?%5Calpha_t"> by minimizing the strain energy functional.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Calpha_t%20=%20%5Carg%5Cmin_%7B%5Calpha%7D%20J(%5Cmathbf%7Bu%7D_t%20%20-%20%5Calpha%20%5Cmathbf%7BK%7D%5E%7B-1%7D%20%5Cmathbf%7Br%7D_t)"></p>
<p>One major issue is that the stiffness matrix is variable, there is only a <code>tangent stiffness matrix</code>, <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BK%7D_t">, which requires frequent recomputation. This tangent matrix is also called in more general terms the Hessian, which describes the second-order curvature. We will not get into the details here, but we will get back to it below.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Ill-conditioning
</div>
</div>
<div class="callout-body-container callout-body">
<p>The following picture shows geometry as one of the ill-conditioning causes. One element is a lot bigger than the other.</p>
<p><img src="https://www.storymelange.com/posts/technical/ill_conditioning_12.gif" class="img-fluid" alt="A unequal size of elements leads to a ill-conditioned matrix, https://www.lusas.com/user_area/theory/ill_conditioned_matrices.html">.</p>
<p>Here’s an example of an ill-conditioned matrix:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BK%7D%20=%20%5Cbegin%7Bbmatrix%7D%2010%20&amp;%2010%20%5C%5C%2010%20&amp;%2010.0001%20%5Cend%7Bbmatrix%7D"></p>
<p>This matrix has a high condition number, making it sensitive to small changes in input, which can lead to large errors in numerical computations.</p>
</div>
</div>
</section>
</section>
<section id="machine-learning" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="machine-learning"><span class="header-section-number">3</span> Machine learning</h2>
<section id="linear-models" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="linear-models"><span class="header-section-number">3.1</span> Linear models</h3>
<p>Machine learning began with linear models like the equation:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7By%7D=%5Cmathbf%7BX%7D%5Cmathbf%7Bw%7D+%5Cmathbf%7Bb%7D">.</p>
<p>It draws from statistics and early perceptron models of the 1950s.</p>
<p>Here</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7By%7D"> is the vector of output labels (dependent variable)</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D"> is the feature matrix, the input data, or independent variable</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D"> are the weights(model parameters)</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bb%7D"> are biases, which we can include in w</li>
</ul>
<p>You can write this as: <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D%5Cmathbf%7Bw%7D=%5Cmathbf%7By%7D"></p>
<p>A direct solution equivalent to the FEM equation</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bu%7D%20=%20%5Cmathbf%7BK%7D%5E%7B-1%7D%20%5Cmathbf%7Br%7D"></p>
<p>is the equivalent least squares solution is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D%20=%20(%5Cmathbf%7BX%7D%5ET%20%5Cmathbf%7BX%7D)%5E%7B-1%7D%20%5Cmathbf%7BX%7D%5ET%20%5Cmathbf%7By%7D"></p>
<p>where (<img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D%5ET%20%5Cmathbf%7BX%7D)%5E%7B-1%7D"> is like the inverse of the stiffness matrix, <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BK%7D%5E%7B-1%7D"> .</p>
</section>
<section id="influence-of-size-and-non-linearity" class="level3" data-number="3.2">
<h3 data-number="3.2" class="anchored" data-anchor-id="influence-of-size-and-non-linearity"><span class="header-section-number">3.2</span> Influence of size and non-linearity</h3>
<p>However, ML problems usually have many more parameters than than FEM problems. This brings a few drawbacks for the direct solution.</p>
<ul>
<li>matrix inversion is costly and works at <img src="https://latex.codecogs.com/png.latex?O(n%5E3)"> in time.</li>
<li>and requires <img src="https://latex.codecogs.com/png.latex?O(n%5E2)"> in space.</li>
<li>correlated features, can lead to near-singular matrices making inversion impossible.</li>
</ul>
<p>In addition, it would only work for linear problems, whereas many issues are non-linear, expressed as:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7By%7D%20=%20f(%5Cmathbf%7BX%7D,%20%5Cmathbf%7Bw%7D)"></p>
<p>where - <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7By%7D"> is the output vector - <img src="https://latex.codecogs.com/png.latex?f(%5Cmathbf%7BX%7D,%20%5Cmathbf%7Bw%7D)"> is a general function</p>
<p>Development has focused on iterative methods. Here, the same solvers exist as for FEM: gradient descent, conjugate gradient, or L-BFGS. Mini-batches solve the space requirement issue by analyzing only a small subset. This is then called <code>stochastic gradient descent</code>.</p>
</section>
<section id="gradient-descent" class="level3" data-number="3.3">
<h3 data-number="3.3" class="anchored" data-anchor-id="gradient-descent"><span class="header-section-number">3.3</span> Gradient descent</h3>
<p>Instead of direct inversion, ML often uses <code>gradient descent``, similar to</code>iterative solvers in FEM` (like conjugate gradient method):</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D_%7Bt+1%7D%20=%20%5Cmathbf%7Bw%7D_t%20-%20%5Calpha%20%5Cnabla%20J(%5Cmathbf%7Bw%7D_t)">,</p>
<p>where <img src="https://latex.codecogs.com/png.latex?J(%5Cmathbf%7Bw%7D)"> is the loss function (analogous to potential energy in FEM). Now <img src="https://latex.codecogs.com/png.latex?%5Calpha"> is the learning rate, but you can see the equation is identical to the FEM equation.</p>
<p>In our analogy, the stiffness matrix <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BK%7D"> is replaced by the loss function. A common choice for regression problems is the <code>Mean Squared Error (MSE)</code>:</p>
<p><img src="https://latex.codecogs.com/png.latex?J(%5Cmathbf%7Bw%7D)%20=%20%5Cfrac%7B1%7D%7BN%7D%20%5Csum_%7Bi=1%7D%5E%7BN%7D%20(y_i%20-%20%5Cmathbf%7BX%7D_i%20%5Cmathbf%7Bw%7D)%5E2"></p>
<p>where:</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?N"> is the number of samples.</li>
<li><img src="https://latex.codecogs.com/png.latex?y_i"> is the true label.</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D_i"> is the feature vector (row) for sample i in the matrix.</li>
</ul>
<p>The gradient of the loss function is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cnabla%20J(%5Cmathbf%7Bw%7D)%20=%20-%5Cfrac%7B2%7D%7BN%7D%20%5Csum_%7Bi=1%7D%5E%7BN%7D%20(y_i%20-%20%5Cmathbf%7BX%7D_i%20%5Cmathbf%7Bw%7D)%20%5Cmathbf%7BX%7D_i"></p>
<p>For more complex problems, first order gradient descent is not enough, we need second order approaches. We examine the curvature and then it is called the Hessian. But again, as for FEM, this is too complex for this article.</p>
</section>
<section id="batch-size" class="level3" data-number="3.4">
<h3 data-number="3.4" class="anchored" data-anchor-id="batch-size"><span class="header-section-number">3.4</span> Batch size</h3>
<p>As already mentioned, ML problems use a lot of parameters and a lot of data. The size of the data, which is filled in the matrix is called the <code>batch</code>. Using a <code>batch size</code> smaller than the full data is called a <code>mini-batch</code>. We then use a <code>stochastic gradient descent</code>. It is called stochastic as we use a sample of the full data.</p>
<p>In theory, the mini-batch can go down to 1. In practice this is rare.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D_%7Bt+1%7D%20=%20%5Cmathbf%7Bw%7D_t%20-%20%5Calpha%20%5Cfrac%7B1%7D%7B%7CB%7C%7D%20%5Csum_%7Bi%20%5Cin%20B%7D%20%5Cnabla%20J_i(%5Cmathbf%7Bw%7D_t)"></p>
<p>where</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%7CB%7C"> is the batch size</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cnabla%20J_i"> is the evaluation of the loss function for the batch sample</li>
</ul>
<p>This approach of divide and conquer is a classic in computer science. In the FEM similar approaches have been developed for large-scale problems, see for example the PGD and other reduced order modeling techniques.</p>
</section>
<section id="the-learning-rate-limits-progress" class="level3" data-number="3.5">
<h3 data-number="3.5" class="anchored" data-anchor-id="the-learning-rate-limits-progress"><span class="header-section-number">3.5</span> The learning rate, limits progress</h3>
<p>We have previously examined analogies between many optimization equations. One concept that remains to be discussed is the <strong>damping factor</strong>—a critical component in both numerical methods and machine learning.</p>
<p>Returning to the idea of <strong>line search</strong>, we can observe that a similar approach to what is used in FEM can also be applied in machine learning. In this context, the <strong>learning rate becomes variable</strong>, adapting at each iteration to minimize the objective function along the descent direction:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Calpha_t%20=%20%5Carg%5Cmin_%7B%5Calpha%7D%20J(%5Cmathbf%7Bw%7D_t%20-%20%5Calpha%20%5Cnabla%20J(%5Cmathbf%7Bw%7D_t))"></p>
<p>For small to medium ml problems, this is an excellent solution. This approach ensures a stable convergence of the training process. The issue is that each extra forward/backward pass doubles cost. If your package offers “line search”, this is often backtracking or heuristic scaling.</p>
<p>For deep learning tasks, inventive folks have come up with explicit prescriptive updates, like the ADAM optimizer. It handles the update rate for each parameter solely based on the gradients.</p>
<p><img src="https://latex.codecogs.com/png.latex?m_t%20=%20%5Cbeta_1%20m_%7Bt-1%7D%20+%20(1%20-%20%5Cbeta_1)%20%5Cnabla%20J(%5Cmathbf%7Bw%7D_t)"></p>
<p><img src="https://latex.codecogs.com/png.latex?v_t%20=%20%5Cbeta_2%20v_%7Bt-1%7D%20+%20(1%20-%20%5Cbeta_2)%20(%5Cnabla%20J(%5Cmathbf%7Bw%7D_t))%5E2"></p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D_%7Bt+1%7D%20=%20%5Cmathbf%7Bw%7D_t%20-%20%5Cfrac%7B%5Calpha%20m_t%7D%7B%5Csqrt%7Bv_t%7D%20+%20%5Cepsilon%7D"></p>
<p>where:</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?m_t"> is the <strong>moving average of gradients</strong> (momentum-like behavior).</li>
<li><img src="https://latex.codecogs.com/png.latex?v_t"> tracks the <strong>moving average of squared gradients</strong> (scales learning rates).</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cbeta_1"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta_2"> control exponential decay rates.</li>
</ul>
<p>For the FEM guys reading this: this approach resembles explicit dynamics mass scaling of the time step. There, we calculate the permissible step size for each element and then add any artificial mass to each element. This artificial mass brings the global step size to a desired target.</p>
<p>Numerically, the approaches differ. Some ensure convergence directly or iteratively; others use update rules and heuristics.</p>
<p>Iterative solvers, such as <strong>BFGS and L-BFGS</strong>, still have their place in more specialized fields that have higher demands on accuracy or suffer from greater instability.</p>
<p>The major advantage is that L-BFGS can converge faster than SGD.</p>
<p>People use it on classic ML problems, with datasets that fit in memory, that is no mini-batch and especially reinforcement learning to handle the instabilities better.</p>
<p>Another field where a BFGS could be better is fine tuning, small networks, hyper parameter optimization, and word embeddings.</p>
<p>The field of machine learning is much less mature than FEM, in terms of terminology and also in the development of new numerical methods.</p>
</section>
</section>
<section id="final-comparison" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="final-comparison"><span class="header-section-number">4</span> Final comparison</h2>
<p>We explored the basics of both fields and pointed out analogies. The analogies often stem from the fact that the underlying optimization math was used. If you are deeped interested in the basics, start <a href="https://en.wikipedia.org/wiki/Mathematical_optimization">here</a>.</p>
<p>Here is a final comparison table</p>
<table class="caption-top table">
<colgroup>
<col style="width: 69%">
<col style="width: 31%">
</colgroup>
<thead>
<tr class="header">
<th>FEM</th>
<th>ML</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Damping / time step <img src="https://latex.codecogs.com/png.latex?%5Calpha"></td>
<td>Learning rate <img src="https://latex.codecogs.com/png.latex?%5Calpha"></td>
</tr>
<tr class="even">
<td>Load vector <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bf%7D_%7B%5Ctext%7Bext%7D%7D"></td>
<td>Labels <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7By%7D"></td>
</tr>
<tr class="odd">
<td>Displacements <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bu%7D"></td>
<td>Parameters <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D"></td>
</tr>
<tr class="even">
<td>Residual <img src="https://latex.codecogs.com/png.latex?%5Cnabla_%7B%5Cmathbf%7Bu%7D%7D%20%5CPi=%5Cmathbf%7BK%7D%20%5Cmathbf%7Bu%7D_t-%5Cmathbf%7Bf%7D_%7B%5Ctext%7Bext%7D%7D"></td>
<td>Gradient <img src="https://latex.codecogs.com/png.latex?%5Cnabla%20J(%5Cmathbf%7Bw%7D)"></td>
</tr>
<tr class="odd">
<td>Tangent Stiffness matrix <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BK%7D_t"></td>
<td>Hessian / curvature of loss <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BH%7D"></td>
</tr>
</tbody>
</table>


</section>

 ]]></description>
  <category>Machine Learning</category>
  <category>Applied Engineering</category>
  <guid>https://www.storymelange.com/posts/technical/from-damping-factor-to-learning-rate.html</guid>
  <pubDate>Sat, 05 Jul 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Blog Update July 2025</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/blog-update-july.html</link>
  <description><![CDATA[ 




<section id="blog-updates" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="blog-updates"><span class="header-section-number">1</span> Blog Updates</h2>
<p>I decided to give the blog a long planned overhaul.</p>
<p>Let’s start with the different topics</p>
</section>
<section id="comments" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="comments"><span class="header-section-number">2</span> Comments</h2>
<p>I decided to enable comments via https://utteranc.es/. It seems the most lightweight approach to comments. Comments only work if you have a Github account. Bad for the non-techies. Good to keep the spamers away.</p>
<p>For any follow bloggers. Put the utterance section in the <code>_metadata.yml</code> in posts. To limit it to sites with content and not on the listing sites.</p>
<p>In addition, I use a small comments header to visually separate the comments.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode html code-with-copy"><code class="sourceCode html"><span id="cb1-1"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">h2</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">&gt;</span>Comments<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;/</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">h2</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">&gt;</span>  </span>
<span id="cb1-2"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">p</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">&gt;</span>Join the discussion below.<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;/</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">p</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">&gt;</span></span></code></pre></div></div>
<p>Implementation is straightforward use</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode yml code-with-copy"><code class="sourceCode yaml"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span></span>
<span id="cb2-2"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span></span>
<span id="cb2-3"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">include-after-body</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> comments-header.html  </span></span>
<span id="cb2-4"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">comments</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span></span>
<span id="cb2-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">utterances</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span></span>
<span id="cb2-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">        </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">repo</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> dolind/dolind.github.io  </span></span>
<span id="cb2-7"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">        </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">issue-term</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> pathname  </span></span>
<span id="cb2-8"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">        </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">label</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> comment  </span></span>
<span id="cb2-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">        </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> github-light</span></span></code></pre></div></div>
</section>
<section id="blog-theme" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="blog-theme"><span class="header-section-number">3</span> Blog theme</h2>
<p>Going strong on coffee, I opted for</p>
<p><em>Real stories of building systems and leading teams, from quick espresso shots to slow pours</em>.</p>
</section>
<section id="rss-feed" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="rss-feed"><span class="header-section-number">4</span> RSS Feed</h2>
<p>It was enabled before, but i did not have a button in the navbar. Now it is there.</p>
</section>
<section id="newsletter" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="newsletter"><span class="header-section-number">5</span> Newsletter</h2>
<p>Biggest update. I have a RSS based Newsletter. You can signup here:</p>
<p>I followed this guide: https://forbo7.github.io/forblog/posts/7_blog_subscriptions.html</p>
<p>Sadly, the layout is a bit off, I will fix that another time.</p>


</section>

 ]]></description>
  <category>Knowledge Work</category>
  <category>Growth</category>
  <guid>https://www.storymelange.com/posts/blog-update-july.html</guid>
  <pubDate>Fri, 04 Jul 2025 00:00:00 GMT</pubDate>
  <media:content url="https://www.storymelange.com/quarto.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>The Rebirth of the recipescanner</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/recipescanner/the-rebirth-of-the-recipescanner.html</link>
  <description><![CDATA[ 




<section id="cooking-without-ingredients-is-difficult" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="cooking-without-ingredients-is-difficult"><span class="header-section-number">1</span> Cooking without ingredients is difficult</h2>
<p>Dear Reader, are you fond of cooking? If yes, then you are facing the challenges of meal planning and searching for recipes. Even more, you still have to go out and buy groceries every week. I do not dislike those tasks. They can be fun but they take time. Time better spent cooking. Personally, I find cooking relaxing, whereas the preparation and shopping often add more strees to my busy schedule.</p>
<section id="tired-of-skimming-books" class="level3" data-number="1.1">
<h3 data-number="1.1" class="anchored" data-anchor-id="tired-of-skimming-books"><span class="header-section-number">1.1</span> Tired of skimming books</h3>
<p>There are many apps, which can plan, guide and organize shopping list. I did not intend to reinvent the wheel. My specific issue was that my recipes are in books. I have to read through books and then assemble a shopping list. Much like my Grandmother would have done.</p>
<p>Tired of skimming books, I was searching for a way to digitize my existing recipe book collection as easy as possible. In April 2019, I decided to build a small sidekick application whose differentiator would be to to scan and digitize physical cookbooks. This endeavour was about to breathe new life into the dusty cookbook.</p>
<p>In the beginning, I started prototyping in python using OpenCV and TesseractOCR.</p>
<p>I had non-working drafts for the entire software. What I did not have was a working software.</p>
<p>This came much to my suprise, as I followed good engineering practices, including test driven development. At least what I believed good practices to be. This is related to the Dunning Kruger Effect. A popular, but wrong representation below. Why this is misleading and more on the actual outcome of the study <a href="https://graphpaperdiaries.com/2017/08/20/the-real-dunning-kruger-graph/.md">here</a>.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="https://www.independent.co.uk/arts-entertainment/books/features/how-meryl-streep-showed-us-why-the-least-able-have-no-idea-of-their-own-incompetence-a7205316.html"><img src="https://www.storymelange.com/posts/projects/recipescanner/dunning_kruger_independent.jpg" class="img-fluid figure-img"></a></p>
<figcaption>Dunning Kruger Effect. I am the green Point, back in 2019.</figcaption>
</figure>
</div>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Test driven Developement (TDD)
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>Test-Driven Development (TDD) is a software development practice where you write tests <em>before</em> writing the implementation. The ideal programming cycle becomes: write a failing test → write just enough code to pass the test → refactor.</p>
<p>In contrast, to me, it meant writing tests <em>close to</em> the implementation. Often after the fact. I only later in my life became to grasp the idea and benefits of <em>test-first</em>.</p>
</div>
</div>
</div>
<p>After two months of experimentation with various new technologies, I had developed a rudimentary approach. It worked based on simple rules of text position and length, as well as some keywords. I relied on domain knowledge of recipe books: <em>title is at the top</em>, <em>ingredients appear as a block and often start with numbers</em>. I realized the limitations of this approach as I developed a working prototype. Too much variation and the rules would fail. However, i thought of creating just enough data to bootstrap an ML process.</p>
<p>Then the project went dormant for ten months.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/recipescanner/result_2019.jpg" class="img-fluid figure-img"></p>
<figcaption>The first recipe with classified entries. Colors show the different fields</figcaption>
</figure>
</div>
</section>
<section id="machine-learning-on-mobile-devices" class="level3" data-number="1.2">
<h3 data-number="1.2" class="anchored" data-anchor-id="machine-learning-on-mobile-devices"><span class="header-section-number">1.2</span> Machine learning on mobile devices</h3>
<p>In the meantime, I had discovered <a href="https://www.paprikaapp.com/">Paprika</a> as my recipe organization app.</p>
<p>The previous app suffered from poor <code>OCR</code> results using <code>Tesseract</code>. <code>Tesseract</code> works best on traditional scans. I was working on phone pictures shot with a shaky hand during low evening light.</p>
<p>I got interested in mobile machine learning applications around that time. Any privacy issue becomes much easier compared to cloud based solutions. In addition, any compute cost in data centers could be reduced to almost zero.</p>
<p>I explored <code>Google's ML Kit</code>, which offers on-device <code>OCR</code> optimized for smartphone. I downloaded the according <a href="https://github.com/googlesamples/mlkit.">demo app</a>.</p>
<p>Around November 2020, I had figured out how to program a <code>OCR</code> app on <code>android</code> using <code>Kotlin</code>. Compared to tesseract the results where not even better, Google’s structured <code>OCR</code> output simplified the recipe extraction problem.</p>
<p>My complex problems of getting ingredients from books was reduced:</p>
<ul>
<li>Paprika handles recipe organizatio and shopping list. Everything must be in English.</li>
<li>Google ML kit is the <code>OCR</code> scanner, and translates to English.</li>
<li>My app focuses on parsing structured OCR Output to recipe data.</li>
</ul>
<p>By January 2021, I had the core logic working in python. In another project, I was working on custom <code>C++</code> applications for an Android camera. Therefore, I went the <code>C++</code> route and used <code>Android NDK</code>. In hindsight, that was a terrible decision as it bloated the tech stack.</p>
<p>From there it took another 4 months until April 2021 up to the working release of the Recipe scanner.</p>
<p>Even though the app worked and I had cleared many operational stages in the Google Play Store, it never made it to the ultimate public release.</p>
<p><strong>Recipe Scanner Android Version</strong></p>
<table class="caption-top">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th><img src="https://www.storymelange.com/posts/projects/recipescanner/Recipe Scanner_1.jpg" class="img-fluid"></th>
<th><img src="https://www.storymelange.com/posts/projects/recipescanner/Recipe Scanner_2.jpg" class="img-fluid"></th>
<th><img src="https://www.storymelange.com/posts/projects/recipescanner/Recipe Scanner_3.jpg" class="img-fluid"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
<section id="the-year-chatgpt-killed-the-app" class="level3" data-number="1.3">
<h3 data-number="1.3" class="anchored" data-anchor-id="the-year-chatgpt-killed-the-app"><span class="header-section-number">1.3</span> 2023 The year ChatGPT killed the app</h3>
<p>The android app worked well by analysing the Json output of the <code>Google OCR</code>. The rule system was more complex, but still failed if the books were too complex. I decided in 2022 to not go done the machine learning alley, because I focused on storytelling (this blog) and software engineering management.</p>
<p>By 2023, managing machine learning projects had become part of my professional life. Simultaneously, the emergence of ChatGPT offered new possibilities. Instead of going the difficult route of doing embeddings, I tried simple prompt engineering.</p>
<p>Initially, single-step prompts struggled with accuracy, especially with non-English recipes. To overcome this, I designed the following structured prompt:</p>
<pre><code>The user provides a recipe. Do not translate anything. Create a YAML file formatted as follows:

---
name: My Tasty Recipe
servings: 4-6 servings
prep_time: 10 min
cook_time: 30 min
nutritional_info: 500 calories
difficulty: Easy
notes: |
  add interesting notes here
ingredients: |
  ingredient 1
  ingredient 2
  (do not translate)
directions: |
  list necessary steps
  (do not translate)</code></pre>
<p>Surprisingly, this simple prompt effectively solved the parsing issue.</p>
<p>The remaining work reduced to produce glue code between the Google api, the ChatGPT api and the Paprika api to automate recipe uploads to Paprika.</p>
<p>Taking the pictures had become the most difficult aspect of digitizing recipe books. In a way this had become a low - to no code solution.</p>
<p>Frustrated that all the hard work of learning had been for nothing, I stopped development again and did not even bother to write this post.</p>
</section>
<section id="what-i-learned" class="level3" data-number="1.4">
<h3 data-number="1.4" class="anchored" data-anchor-id="what-i-learned"><span class="header-section-number">1.4</span> What I learned</h3>
<p>Selecting the right programming language is critical but challenging. I explored Python, Java, Kotlin, and C++, each with strengths and drawbacks:</p>
<ul>
<li><p><strong>Python</strong>: Excellent prototyping, weak Android support</p></li>
<li><p><strong>Kotlin</strong>: Intuitive syntax but Android-centric</p></li>
<li><p><strong>Java</strong>: Robust but hindered by asynchronous callback complexity</p></li>
<li><p><strong>C++</strong>: High performance but complexity and segmentation faults with Android NDK</p></li>
</ul>
<p>Large Language Models (LLMs) changed all this.</p>
<blockquote class="blockquote">
<p>The value of 90% of my skills just dropped to $0. The leverage for the remaining 10% went up 1000x.</p>
<p>Kent Beck</p>
</blockquote>
<p>I agree. knowing the ins and outs of each language has become low value. For me, what still bears high value: Algorithm design and knowledge of the complete software development cycle. For the very technical aspects a good book on software architecture: <strong>Software Architecture in Practice - Len Bass et al.</strong>.</p>
<p>For the recipescanner, what matters most: data structures, architecture, deployment.</p>
<p>It feels good to have put out a piece of software in the world. Software, which at least for me makes my life easier.</p>
<p>Hopefully, in the future also for other people as I decided to continue this project.</p>


</section>
</section>

 ]]></description>
  <category>Software Engineering</category>
  <category>Machine Learning</category>
  <category>Python</category>
  <category>C++</category>
  <guid>https://www.storymelange.com/posts/projects/recipescanner/the-rebirth-of-the-recipescanner.html</guid>
  <pubDate>Thu, 03 Jul 2025 00:00:00 GMT</pubDate>
  <media:content url="https://www.storymelange.com/posts/projects/recipescanner/result_2019.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Do you know the hidden paths of your code?</title>
  <dc:creator>Dominik Lindner</dc:creator>
  <link>https://www.storymelange.com/posts/projects/uml-analyser/do-you-know-the-hidden-paths-of-your-code.html</link>
  <description><![CDATA[ 




<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/uml-analyser/package_graphbased.svg" class="img-fluid figure-img"></p>
<figcaption>Try seeing the forest for the trees.</figcaption>
</figure>
</div>
<section id="what-if-we-had-a-zoom-button-for-our-code" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="what-if-we-had-a-zoom-button-for-our-code"><span class="header-section-number">1</span> What if we had a zoom button for our code?</h2>
<p>Think about code as a Digital Map. From far away, you can see the continents. When you zoom in, rivers and mountains appear. Then cities. Highways and train lines become visible. Then smaller streets. At the second to lowest level, you can see the street layout of a neighborhood. Until finally you can see one house or a tree.</p>
<p>Even better when you search for a route from A to B. You can usually see it on all zoom levels. Quickly grasping the entire journey, as well as local challenges.</p>
<p>What if we had something equivalent for code? First the module architecture and finally the code lines? And then what if we could see data flow in this full picture on several levels?</p>
<p>I have to express my thanks to a former colleague of mine, who coined the term <code>zoom button</code> for this. In the following, I describe my approach to get closer to this <code>zoom button</code>.</p>
</section>
<section id="part-i-a-picture-says-more-than-a-thousand-words" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="part-i-a-picture-says-more-than-a-thousand-words"><span class="header-section-number">2</span> Part I: A picture says more than a thousand words</h2>
<p>And so does a diagram. This part is about my motivation for doing this work. If you are only interested in results, skip it and go to part II.</p>
<section id="software-engineering-is-about-reading-code" class="level3" data-number="2.1">
<h3 data-number="2.1" class="anchored" data-anchor-id="software-engineering-is-about-reading-code"><span class="header-section-number">2.1</span> Software engineering is about reading code</h3>
<blockquote class="blockquote">
<p>There are 10 types of people in this world, those who understand binary and those who don’t.</p>
</blockquote>
<section id="what-beginners-and-non-software-developers-do-not-get" class="level4" data-number="2.1.1">
<h4 data-number="2.1.1" class="anchored" data-anchor-id="what-beginners-and-non-software-developers-do-not-get"><span class="header-section-number">2.1.1</span> What Beginners and Non software Developers do not get</h4>
<p>A novice expects that developing software is all about writing code. And I have to admit that just hacking away can initially feel good. Directly coding and doing everything from scratch feels so powerful. The raw power is just at your fingertips. You are the wizard of the computer - in then end you will pay dearly. You get stuck in the mud of your code. This is blind activism.</p>
<p>Large companies are not immune to this. In fact, sometimes the management structure incentivizes quick hacks and fast coding over constant architecture development.</p>
</section>
<section id="the-role-of-non-software-people" class="level4" data-number="2.1.2">
<h4 data-number="2.1.2" class="anchored" data-anchor-id="the-role-of-non-software-people"><span class="header-section-number">2.1.2</span> The role of non-software people</h4>
<p>The rise of non-code application and then the onset of the hype of LLM in 2022 have led to the fear that programming and software developers have no future. In the future, anybody can code. Personally, I disagree with this. My argument is not purely based on self-preservation. Instead, I believe AI can replace that simple apps that were done before by a single developer. However, the software engineers concerned will move to bigger projects. Similar as we do not know every single assembler instruction or binary instruction, we might no longer know every single code line in our precious masterpiece.</p>
<p>Teams will focus on higher value tasks or just be quicker in developing new features. Engineers will focus more on higher-level tasks: system engineering, architecture and customer interaction. There could be a conversion of specialized engineering roles. The same team might do requirements, design, Code, and testing. Concentrating multiple roles on fewer staff. The cost of friction in human interactions will do the rest. The excessive cost of inter-team communication outweighs specialized teams’ remaining advantages. But until we get there, it will be a few more years with a lot of unforeseen changes.</p>
</section>
<section id="we-always-face-new-code" class="level4" data-number="2.1.3">
<h4 data-number="2.1.3" class="anchored" data-anchor-id="we-always-face-new-code"><span class="header-section-number">2.1.3</span> We always face new code</h4>
<p>As we learn more and more during our journey as software developers, we discover reading code is far more important than writing. Usually we read someone else’s code and try to understand it.</p>
<p>For consulting-work or a short-term project, this is obvious.</p>
<p>If you always work on the same enormous project, you need to switch assignments and will work on different components. In fact, a dynamic and growing software business will always need to pivot the existing engineering staff to other tasks. Just hiring new engineers is not cost efficient.</p>
<p>Even when you work all by yourself. Remembering the details of your code becomes difficult after about six months.</p>
<p>So regardless of your works nature. If you are productive, you will frequently encounter new code which needs to put into your works context. We need to understand if the code is doing what it should do. Figuring out what it should is about as hard as ensuring that it is doing this.</p>
<p>That is why I believe software engineers can not be replaced. Problem discovery and formulation is currently engrained in the process of writing code. Removing or simplifying the process of writing, will not remove problem discovery and formulation.</p>
</section>
</section>
<section id="how-we-approach-unknown-code" class="level3" data-number="2.2">
<h3 data-number="2.2" class="anchored" data-anchor-id="how-we-approach-unknown-code"><span class="header-section-number">2.2</span> How we approach unknown code</h3>
<section id="missing-documentation-makes-it-harder" class="level4" data-number="2.2.1">
<h4 data-number="2.2.1" class="anchored" data-anchor-id="missing-documentation-makes-it-harder"><span class="header-section-number">2.2.1</span> Missing documentation makes it harder</h4>
<p>Sadly, not all codebases have perfect documentation. The more innovative the business is, the more it will rely on exploration. Often, the original creator quickly produced and then abandoned his software. Take open source source software. While there are many gems with an outstanding code standard, there are as many counterexamples. Even more, even a perfectly documented code, becomes difficult to use if relies on a framework and there are major shifts in the framework.</p>
<p>One such shift is the change from Python 2 to Python 3. Projects can go stale as it becomes more difficult to update them.</p>
<p>The lack of documentation and especially lack of documented software architecture profoundly hinders grasping the code from a top-down perspective. The only solution, dig through the code.</p>
</section>
<section id="poorly-designed-software-takes-a-long-time-to-understand" class="level4" data-number="2.2.2">
<h4 data-number="2.2.2" class="anchored" data-anchor-id="poorly-designed-software-takes-a-long-time-to-understand"><span class="header-section-number">2.2.2</span> Poorly designed software takes a long time to understand</h4>
<p>Poorly written software may have suboptimal abstraction and encapsulation.</p>
<p>An example: Because of performance issues, it can be necessary to use a data structure as an input/output parameter. However, while this is comfortable, it increases code complexity dramatically. This mechanism invites us to just pass on a massive data structure and change a bit about it. Take enough of these functions and complexity will blow up in your face. A similar code smell is the <code>god object</code>. In such a class, side effects are none-obvious.</p>
<p>The only way to uncover the hidden connections is to read the complete code and keep track of the connections and dependencies which are important to you. Even with a modern IDE (search, find usage), this remains a very time-consuming task.</p>
</section>
</section>
<section id="solid-principles-and-model-based-system-engineering" class="level3" data-number="2.3">
<h3 data-number="2.3" class="anchored" data-anchor-id="solid-principles-and-model-based-system-engineering"><span class="header-section-number">2.3</span> SOLID principles and model-based system engineering</h3>
<section id="towards-a-clean-architecture" class="level4" data-number="2.3.1">
<h4 data-number="2.3.1" class="anchored" data-anchor-id="towards-a-clean-architecture"><span class="header-section-number">2.3.1</span> Towards a clean architecture</h4>
<p>While I read about the importance of SOLID principles and good architecture in <code>Clean Architecture</code>, I thought about the code I produced myself. Where did I not apply these principles?</p>
<p>My biggest programming sin is definitively the code that I wrote during my PhD. A non-linear finite element solver, with different material models and integration schemes.</p>
<p>It lacked so many things. While it had classes, it did not obey all SOLID principles. In particular, it violated dependency inversion. The most abstract classes depended usually on the most concrete classes. For example, instead of using a high level builder, an intermediate level featured flags to select the proper material model. This whole architecture made it quite difficult to test the code. Of course, it did not matter to me, as the thoughts of code coverage and TDD had never crossed my mind.</p>
<p>Now, having done a in-depth study of ‘Clean Architecture’ and the details about dependency inversion, I wanted to make a clean architecture for my FEM solver.</p>
<p>I did not even know where to start. Of course my code had an architecture. The architecture had, however, mostly grown organically.</p>
</section>
<section id="model-based-engineering" class="level4" data-number="2.3.2">
<h4 data-number="2.3.2" class="anchored" data-anchor-id="model-based-engineering"><span class="header-section-number">2.3.2</span> Model based engineering</h4>
<p>As a software developer, I’ve grown fond of using simple Mermaid or PlantUML diagrams. These small diagrams are more formal than paper-based drawings, while still allowing enough freedom to detail the abstractions. UML is the go to tool to formalize your architecture.</p>
<p>Choosing a pure paper based approach or digital paper in form of text files, one faces the issue to keep source and documentation always in sync.</p>
<p>It was when working on a large-scale project with a dedicated modelling team; I learned about model-based system engineering. Tools like <code>Enterprise Architecture</code> can generate code from UML diagrams. Some of those tools can even analyse your code and create UML diagrams.</p>
<p>As a result, you get two views on the same software. One abstract (UML/SysML) and one very concrete (Code). The computer takes care to keep both in sync.</p>
<p>The abstract system models are usually consistent over several abstraction levels. However, the connection to code only happens at the lowest level. If the connection were to happen on any level, these models could act as the zoom button for the software.</p>
<p>The major drawback? Usability. Nowadays, software engineers use an IDE. And once being accustomed to their favourite IDE, they do not want to leave it.</p>
<p>Tools like Enterprise Architect have a steep learning curve, while not having any of the features a modern IDE has. In practice this seems not important. Many safety-aware businesses using model-based system engineering create special roles dedicated to these tools. This introduces the drawback of splitting the model and the code over two people instead of bringing everything closer together.</p>
<p>In addition, these tools can be pricey. A no-go for small to medium-sized projects.</p>
<p>Another alternative I discovered is the C4 diagram <code>https://c4model.com</code>. There are some projects that aim to automate the creation <code>https://structurizr.com/</code>.</p>
</section>
</section>
<section id="the-two-way-problem-of-model-based-engineering" class="level3" data-number="2.4">
<h3 data-number="2.4" class="anchored" data-anchor-id="the-two-way-problem-of-model-based-engineering"><span class="header-section-number">2.4</span> The two-way problem of model-based engineering</h3>
<section id="forward-code-to-diagrams" class="level4" data-number="2.4.1">
<h4 data-number="2.4.1" class="anchored" data-anchor-id="forward-code-to-diagrams"><span class="header-section-number">2.4.1</span> Forward: Code to diagrams</h4>
<p>Generating diagrams from code is state-of-the art. In the following I will only dive into the tools for this usage. Most of the time, tools focus on the class at hand or automatic generation of class diagrams over several classes.</p>
</section>
<section id="backward-diagrams-to-code" class="level4" data-number="2.4.2">
<h4 data-number="2.4.2" class="anchored" data-anchor-id="backward-diagrams-to-code"><span class="header-section-number">2.4.2</span> Backward: Diagrams to code</h4>
<p>The other way round generating code from diagrams can be much more difficult. Existing system engineering tools can do this. Correct application of MBSE, in fact, results in very detailed diagrams; the model has already gathered all the information. Therefore it is easy to afterwards generate template based modules. This was actually not my idea when I thought about abstraction and a zoom button. As a side node, doing so usually leads to a schism between software engineers and system engineers. In addition, the lack of connection between the two tools usually results in duplicated information.</p>
<p>A better approach could be the use of multimodal large language models. In an ideal world, we would draw a diagram and describe what we want. The computer would adjust the diagram to the correct constraints and then implement the code. Currently, in 2025, that is not how code generation works, even though the field is moving fast. The part of the constraints is lacking.</p>
<p>There are disadvantages to this approach. First, such diagrams would need to be flexible enough to facilitate discussion with all stakeholders. Discussions often leave out important details. Potentially, by writing done these assumptions, a LLM could take care of adding the abstracted information in the diagram.</p>
<p>Second, Model-based engineering enforces formalism, leading to better performance through standardized solutions. However, for the highest performance, we usually need to cut corners. This requires the direct modification of the code by us. That again would be the other direction again. Depending on the domain, it could be faster to directly write the code yourself.</p>
</section>
</section>
</section>
<section id="part-ii-capturing-all-dependencies-in-one-diagram" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="part-ii-capturing-all-dependencies-in-one-diagram"><span class="header-section-number">3</span> Part II: capturing all dependencies in one diagram</h2>
<p>When I looked into the subtopic of code to diagrams, I focused on Python. Static-typed languages like C++ are even better for code analysis because of the explicit typing in the code. Many C++ programmers use <code>doxygen</code> extensively. For Python, the code needs to have type hints, for everything beyond base types.</p>
<p>I found a few open source tools: <code>Pyreverse</code>, <code>Pynsource</code> and <code>Py2Puml</code>. As I explain below, <code>Py2Puml</code> is the best one. However, it falls short in the documentation of class methods. Not really satisfied with the output, I wrote some modifications. Finally, I considered how to better caputure dependencies using graphs. That is why I wrote <code>Py2Graph</code>.</p>
<section id="meet-our-guinea-pig-package-productworld" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="meet-our-guinea-pig-package-productworld"><span class="header-section-number">3.1</span> Meet our guinea-pig package: Productworld</h3>
<p>To evaluate the different programs, I came up with a simple package: <code>Productworld</code>.</p>
<p>Below, you find the package structure and the full code.</p>
<p>Important to me was the use of an abstract class and the occurrence of the other classes in signature, member list, and function bodies. I also wanted free functions to be documented. Regardless how important, free functions do not exist in a standard UML class diagram. So I expected the tools to fall short here.</p>
<section id="packages-and-components" class="level4" data-number="3.1.1">
<h4 data-number="3.1.1" class="anchored" data-anchor-id="packages-and-components"><span class="header-section-number">3.1.1</span> Packages and Components</h4>
<pre><code>
productworld/
├── base/
│   ├── base.py
│   └── customer.py
└── products/
    └── products.py
</code></pre>
</section>
<section id="the-full-code" class="level4" data-number="3.1.2">
<h4 data-number="3.1.2" class="anchored" data-anchor-id="the-full-code"><span class="header-section-number">3.1.2</span> The full code</h4>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># base.py</span></span>
<span id="cb2-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> abc <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ABC, abstractmethod  </span>
<span id="cb2-3">  </span>
<span id="cb2-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Product(ABC):  </span>
<span id="cb2-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, product_id, name):  </span>
<span id="cb2-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.product_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> product_id  </span>
<span id="cb2-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> name  </span>
<span id="cb2-8">  </span>
<span id="cb2-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abstractmethod</span>  </span>
<span id="cb2-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_price(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):  </span>
<span id="cb2-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span>  </span>
<span id="cb2-12">  </span>
<span id="cb2-13">  </span>
<span id="cb2-14"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> NewOrder:  </span>
<span id="cb2-15">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, order_id, product: Product, quantity):  </span>
<span id="cb2-16">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.order_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> order_id  </span>
<span id="cb2-17">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.product:Product <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> product  </span>
<span id="cb2-18">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.quantity <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> quantity  </span>
<span id="cb2-19">  </span>
<span id="cb2-20">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> calculate_total(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, product:Product)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>:  </span>
<span id="cb2-21">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.product.price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.quantity  </span>
<span id="cb2-22">  </span>
<span id="cb2-23"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Order:  </span>
<span id="cb2-24">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, order_id, product:Product, quantity):  </span>
<span id="cb2-25">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.order_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> order_id  </span>
<span id="cb2-26">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.product <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Product()  </span>
<span id="cb2-27">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.quantity <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> quantity  </span>
<span id="cb2-28">  </span>
<span id="cb2-29">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> calculate_total(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>:  </span>
<span id="cb2-30">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.product.price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.quantity  </span>
<span id="cb2-31">  </span>
<span id="cb2-32">          </span>
<span id="cb2-33"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fancyFunc(order: Order):  </span>
<span id="cb2-34">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>  </span>
<span id="cb2-35">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> funkyFunc():  </span>
<span id="cb2-36"> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span></span>
<span id="cb2-37"></span>
<span id="cb2-38"></span>
<span id="cb2-39"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># customer.py</span></span>
<span id="cb2-40"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> List  </span>
<span id="cb2-41">  </span>
<span id="cb2-42"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> productworld.base.base <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Order,fancyFunc, NewOrder  </span>
<span id="cb2-43">  </span>
<span id="cb2-44">  </span>
<span id="cb2-45"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Customer:  </span>
<span id="cb2-46">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, customer_id, name):  </span>
<span id="cb2-47">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.customer_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> customer_id  </span>
<span id="cb2-48">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> name  </span>
<span id="cb2-49">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.orders <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []  </span>
<span id="cb2-50">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.newestOrder :NewOrder <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> NewOrder()  </span>
<span id="cb2-51">  </span>
<span id="cb2-52">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> add_order(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, order: Order):  </span>
<span id="cb2-53">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.orders.append(order)  </span>
<span id="cb2-54">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.orders.append(NewOrder())  </span>
<span id="cb2-55">        fancyFunc(order)  </span>
<span id="cb2-56">  </span>
<span id="cb2-57">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_total_spent(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>:  </span>
<span id="cb2-58">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(order.calculate_total() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> order <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.orders)</span>
<span id="cb2-59"></span>
<span id="cb2-60"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># products.py</span></span>
<span id="cb2-61"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> productworld.base.base <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Product  </span>
<span id="cb2-62">  </span>
<span id="cb2-63"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> productworld.base.base <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> funkyFunc  </span>
<span id="cb2-64">       </span>
<span id="cb2-65"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> PhysicalProduct(Product):  </span>
<span id="cb2-66">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, product_id, name, price):  </span>
<span id="cb2-67">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>().<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(product_id, name)  </span>
<span id="cb2-68">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> price  </span>
<span id="cb2-69">  </span>
<span id="cb2-70">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_price(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):  </span>
<span id="cb2-71">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price  </span>
<span id="cb2-72">  </span>
<span id="cb2-73"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> DigitalProduct(Product):  </span>
<span id="cb2-74">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, product_id, name, price, discount):  </span>
<span id="cb2-75">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>().<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(product_id, name)  </span>
<span id="cb2-76">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> price  </span>
<span id="cb2-77">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.discount <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> discount  </span>
<span id="cb2-78">        funkyFunc()  </span>
<span id="cb2-79">  </span>
<span id="cb2-80">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_price(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>:  </span>
<span id="cb2-81">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.discount)   </span>
<span id="cb2-82">          </span>
<span id="cb2-83"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Productfactory():  </span>
<span id="cb2-84"> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_product(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>,pid:<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span>PhysicalProduct<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>DigitalProduct:  </span>
<span id="cb2-85">   <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> PhysicalProduct()  </span>
<span id="cb2-86">     </span>
<span id="cb2-87"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_product(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>,pid:<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span>PhysicalProduct<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>DigitalProduct:  </span>
<span id="cb2-88">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> PhysicalProduct()</span></code></pre></div></div>
</section>
</section>
<section id="existing-tools" class="level3" data-number="3.2">
<h3 data-number="3.2" class="anchored" data-anchor-id="existing-tools"><span class="header-section-number">3.2</span> Existing tools</h3>
<section id="pyreverse" class="level4" data-number="3.2.1">
<h4 data-number="3.2.1" class="anchored" data-anchor-id="pyreverse"><span class="header-section-number">3.2.1</span> Pyreverse</h4>
<p><code>Pyreverse</code> is part of <code>Pylint</code> and allows you to create an UML diagram for your code.</p>
<p>If you have Pylint installed, you can easily run it with the following command:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">pyreverse</span>  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-ALSmy</span>  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-o</span> puml     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--verbose</span> . </span></code></pre></div></div>
<p>What works well:</p>
<ul>
<li><p>Inheritance is correctly captured</p></li>
<li><p>Aggregation is correctly captured</p></li>
<li><p>Argument and return types are identified</p></li>
</ul>
<p>What does not work:</p>
<ul>
<li><p>Packages and components are not shown</p></li>
<li><p>Argument and return type dependencies are not resolved</p></li>
<li><p>It is a pure UML Class diagram, therefore free functions are not covered</p></li>
<li><p>Usage of classes in function body is not covered</p></li>
</ul>
<p>This is the picture I got:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/uml-analyser/classes_pyreverse.svg" class="img-fluid figure-img"></p>
<figcaption>Pyreverse is a good start, but lacks critical connections</figcaption>
</figure>
</div>
</section>
<section id="pynsource" class="level4" data-number="3.2.2">
<h4 data-number="3.2.2" class="anchored" data-anchor-id="pynsource"><span class="header-section-number">3.2.2</span> Pynsource</h4>
<p>Next I tried <code>Pynsource</code>, which offers a GUI. Adding new files is cumbersome. It’s impossible to update a complete model. Overall, I do not recommend this. The result is worse than <code>Pyreverse</code>.</p>
<p>What works:</p>
<ul>
<li><p>Inheritance is correctly captured</p></li>
<li><p>Aggregation is captured as a normal dependency</p></li>
<li><p>Usage of classes in function body is covered as dependency</p></li>
</ul>
<p>What does not work:</p>
<ul>
<li><p>Packages and components are not shown</p></li>
<li><p>Argument and return type dependencies are not resolved</p></li>
<li><p>It is a pure UML Class diagram, therefore free functions are not covered</p></li>
<li><p>Member types are not identified</p></li>
</ul>
<p>In the free version, no saving of the <code>UML</code> file is possible, only a screenshot.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/uml-analyser/pynsource.jpg" class="img-fluid figure-img"></p>
<figcaption>Pynsource has even less information</figcaption>
</figure>
</div>
</section>
<section id="py2puml" class="level4" data-number="3.2.3">
<h4 data-number="3.2.3" class="anchored" data-anchor-id="py2puml"><span class="header-section-number">3.2.3</span> Py2puml</h4>
<p>Finally, I tested <code>Py2puml</code>.</p>
<p>What works:</p>
<ul>
<li><p>Inheritance is correctly captured</p></li>
<li><p>Aggregation is captured as a composition</p></li>
<li><p>Member types are identified</p></li>
<li><p>Packages and components are not shown</p></li>
<li><p>Abstract class is correctly shown</p></li>
</ul>
<p>As I am focused on a clean architecture with dependency inversion, the correct capture of the abstract class is strong plus.</p>
<p>What does not work:</p>
<ul>
<li><p>Class methods are not shown and as such, no argument and return type dependencies are resolved</p></li>
<li><p>It is a pure UML Class diagram, therefore free functions are not covered</p></li>
<li><p>Usage of classes in function body is not covered</p></li>
</ul>
<p>Overall, I like this the most. The packages reflect the driectories and the components the files. The notion of different levels can be found in this picture.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/uml-analyser/classes_py2puml_main.svg" class="img-fluid figure-img"></p>
<figcaption>Py2puml provides us with information on the module structure, but missing class methods.</figcaption>
</figure>
</div>
</section>
</section>
<section id="my-contribution" class="level3" data-number="3.3">
<h3 data-number="3.3" class="anchored" data-anchor-id="my-contribution"><span class="header-section-number">3.3</span> My Contribution</h3>
<p>As highlighted above, none of the programs clearly delivered what I wanted to do.</p>
<p>My favourite was <code>Py2Puml</code>. First, I addressed its major drawback: missing functions.</p>
<section id="py2puml-with-methods" class="level4" data-number="3.3.1">
<h4 data-number="3.3.1" class="anchored" data-anchor-id="py2puml-with-methods"><span class="header-section-number">3.3.1</span> Py2puml with methods</h4>
<p>Luckily for me, there is a py2puml fork that tries to deal with the class method. Details can be found in the pull requests for the py2puml, <a href="https://github.com/lucsorel/py2puml/pull/43">here</a>.</p>
<p>Unfortunately, the structure of py2puml has changed since the fork date, and the merge is not that straightforward. The PR remains in limbo for 2 years.</p>
<p>I performed a rudimentary merge of this fork, but this clearly ruined my secondary goal of finding something suitable for production, not just a hobby. I now have loaded myself with a vast pile of technical debt.</p>
<p>My code is often a mixture of classes and free functions. Therefore, I collect all free functions in Annotation called <code>Methods</code>. Such an annotation exists in every component, every file. Some other minor changes were done as well.</p>
<p>These changes addressed almost all the critical points of <code>Py2Puml</code></p>
<p>What does still not work:</p>
<ul>
<li>Usage of classes in function body is not covered</li>
</ul>
<p>The picture is now much more detailed. There are several connections that did not exist before. The richness of this picture would allow us to add different zoom levels and options. We could clearly hide, for example, the usage of free functions within the same component. However, we should highlight usage across components.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/uml-analyser/classes_py2puml_mod.svg" class="img-fluid figure-img"></p>
<figcaption>Class methods are back thanks to an old fork.</figcaption>
</figure>
</div>
</section>
<section id="the-next-level-py2graph" class="level4" data-number="3.3.2">
<h4 data-number="3.3.2" class="anchored" data-anchor-id="the-next-level-py2graph"><span class="header-section-number">3.3.2</span> The next level: Py2Graph</h4>
<section id="problem-description" class="level6" data-number="3.3.2.0.1">
<h6 data-number="3.3.2.0.1" class="anchored" data-anchor-id="problem-description"><span class="header-section-number">3.3.2.0.1</span> Problem description</h6>
<p>There remains the missing linkage of functions that are used within the body of another function. For an inspection, that is quite bad. By changing a class A that is used within the body of another class’ B function, we influence behavior of class B. This is exactly the sort of connection we are interested in and which should be visible. The question is <code>Which classes does class A influence</code>.</p>
<p>The second drawback is performance. Even on this tiny example, the <code>Py2Puml</code> requires almost 20 milliseconds. For something which should work in not much more than a few milliseconds, that is too long.</p>
</section>
<section id="digging-deeper" class="level6" data-number="3.3.2.0.2">
<h6 data-number="3.3.2.0.2" class="anchored" data-anchor-id="digging-deeper"><span class="header-section-number">3.3.2.0.2</span> Digging deeper</h6>
<p>The reason is in the architecture of <code>Py2puml</code>. It basically collects lists and then merges them together. To correctly cover all dependencies, we need two passes on the entire codebase. First, we identify existing functions, and then we identify their usage within other classes.</p>
<p>The same issue applies for the function body. In theory that could also be made to work for the original approach using list.</p>
</section>
<section id="my-approach-graphs" class="level6" data-number="3.3.2.0.3">
<h6 data-number="3.3.2.0.3" class="anchored" data-anchor-id="my-approach-graphs"><span class="header-section-number">3.3.2.0.3</span> My Approach: Graphs</h6>
<p>I avoided these issues by using another data structure. Instead of using lists, I moved to a graph-based analysis.</p>
<p>My analysis first analysis all entities (files, modules, classes, functions, members) in hierarchical order. I create a graph node for every parsed entity.</p>
<p>Edges link contained entities or types with their parent. So a module contains classes, which contain functions and members. This approach ensures coverage of connections within functions. Naturally, this analysis might not include the class used, thus preventing a link. This problem is the two pass issue, again.</p>
<p>We resolved the two-pass issue by using a placeholder node for expressions the parser had not yet visited. Once the parser analyzes the true entity, it replaces the placeholder node, but keeps its connections.</p>
<p>If placeholder nodes remain, that is usually a sign that the expression is not from the package in analysis. The system suppresses placeholders in the output.</p>
</section>
<section id="analysis-of-solution" class="level5" data-number="3.3.2.1">
<h5 data-number="3.3.2.1" class="anchored" data-anchor-id="analysis-of-solution"><span class="header-section-number">3.3.2.1</span> Analysis of solution</h5>
<p>My approach only took 3ms. The speedup actually surprised me. I attribute it to the more efficient implementation of <code>networkx digraph</code>, compared to manual parsing of list and dicts.</p>
<p>There can now be multiple relationships between two elements, as we distinguish usage in the class and usage in the class methods. The diagram is becoming more complex. This is exactly what I had in mind when I started my tjourney. It is far easier to reduce the full picture to something less than making sense of an incomplete picture.</p>
<p>The new connection is visible in the connection to <code>base.base.fancyFunc</code> and <code>base.base.funkyFunc</code>. <code>Order</code> is used by<code>fancyFunc</code>. But in the previous version both functions were not used by anybody. In the new version you can see that <code>funkyFunc</code> is used by <code>DigitalProduct</code>. Whereas <code>fancyFunc</code> is used by <code>Customer</code>.</p>
<p>In the final version of the code I changed to straight lines.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/uml-analyser/classes_py2graph.svg" class="zoomable img-fluid figure-img"></p>
<figcaption>Usage of a graph structure helps us to get the all connections.</figcaption>
</figure>
</div>
</section>
<section id="a-bigger-example" class="level5" data-number="3.3.2.2">
<h5 data-number="3.3.2.2" class="anchored" data-anchor-id="a-bigger-example"><span class="header-section-number">3.3.2.2</span> A bigger example</h5>
<p>As initially mentioned, my interest in reverse diagram generation stemmed from my FEM solver. I rewrote parts of it in Python to test how to implement dependency inversion. And how this would look like in the project class diagram. Just for the record, I provide the full view here.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/uml-analyser/package_graphbased.svg" class="zoomable img-fluid figure-img"></p>
<figcaption>Full view of a python port of my FEM solver classes</figcaption>
</figure>
</div>
</section>
</section>
</section>
</section>
<section id="part-iii-whats-next---productization" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="part-iii-whats-next---productization"><span class="header-section-number">4</span> Part III: what’s next - Productization</h2>
<p>So far, this has been a nice study to learn more about UML class relations and the usage of graphs.</p>
<p>But how could this actually add value in a real project? Remember my colleague who came up with the name <code>zoom button</code>? Clearly we need to run this in a more integrated fashion. It should be a zoom button on a current version of the software. That is why runtime is critical.</p>
<section id="live-preview" class="level3" data-number="4.1">
<h3 data-number="4.1" class="anchored" data-anchor-id="live-preview"><span class="header-section-number">4.1</span> Live preview</h3>
<p>In <code>Pycharm</code> the <code>PlantUML</code> plugin can provide a live view of the <code>UML</code> text file.</p>
<p>I implemented something similar: A live view that analysis the entire project.</p>
<p>Saving triggers a new generation of the diagram.</p>
<p>Here we have two screenshots: in the second I introduced <code>self.newPrice = 100</code> to <code>PhysicalProduct</code>. Because of the slow render time, the change was instant. Type is correctly inferred as <code>int</code> from using <code>100</code>.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/uml-analyser/screen1.jpg" class="zoomable img-fluid figure-img"></p>
<figcaption>Screenshot before the manipulation</figcaption>
</figure>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/uml-analyser/screen2.jpg" class="zoomable img-fluid figure-img"></p>
<figcaption>Screenshot after adding a member variable</figcaption>
</figure>
</div>
<p>The implementation works by watching for file changes and running a docker image with PlantUML. Upon detecting a change, analyzis is triggered. The UML code from <code>Py2Graph</code> is sent to the PlantUML server. The Server returns the image to the frontend for Display.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://www.storymelange.com/posts/projects/uml-analyser/app.svg" class="img-fluid figure-img"></p>
<figcaption>Deployment view of the live mode</figcaption>
</figure>
</div>
</section>
<section id="the-complete-zoom-button" class="level3" data-number="4.2">
<h3 data-number="4.2" class="anchored" data-anchor-id="the-complete-zoom-button"><span class="header-section-number">4.2</span> The complete zoom button</h3>
<p>I set out to develop the zoom button. Clearly, by showing a more complete picture with all modules, component, and dependencies, we have done the first step. What is missing now is too selectively show information.</p>
<p>This would require to drop certain information from the graph and then send it to the render server. Highlighting a class’s influence zones would be acccomplished the same way. Thanks to the graph-based structure, we only need to carry out these steps on a graph, not on lists or text files.</p>
</section>
<section id="going-beyond-the-zoom-button" class="level3" data-number="4.3">
<h3 data-number="4.3" class="anchored" data-anchor-id="going-beyond-the-zoom-button"><span class="header-section-number">4.3</span> Going beyond the zoom button</h3>
<p>What else could be done.</p>
<p>A call graph or a natural language model can auto-generate sequence diagrams, visualizing data flow as in LabVIEW/Simulink.</p>
<p>If any of these applications are interesting to you, just drop me a message and let’s discuss.</p>
<p><a href="https://github.com/dolind/py2puml">Sources for the <code>Py2Puml</code> mod</a></p>
<p><a href="https://github.com/dolind/py2graph">Sources for <code>Py2Graph</code></a></p>
<script>
document.querySelectorAll(".zoomable").forEach(img => {
  img.style.cursor = "zoom-in";
  img.addEventListener("click", () => {
    img.style.transform = img.style.transform === "scale(2)" ? "scale(1)" : "scale(2)";
    img.style.transition = "transform 0.25s ease";
  });
});
</script>


</section>
</section>

 ]]></description>
  <category>Software Engineering</category>
  <category>Python</category>
  <guid>https://www.storymelange.com/posts/projects/uml-analyser/do-you-know-the-hidden-paths-of-your-code.html</guid>
  <pubDate>Wed, 14 May 2025 00:00:00 GMT</pubDate>
</item>
</channel>
</rss>
