<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bipin Nair Gopalakrishnan on Medium]]></title>
        <description><![CDATA[Stories by Bipin Nair Gopalakrishnan on Medium]]></description>
        <link>https://medium.com/@aziza.bibin?source=rss-75fc5c88de76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R8K6P4EVP-82fjNcar9fKg.jpeg</url>
            <title>Stories by Bipin Nair Gopalakrishnan on Medium</title>
            <link>https://medium.com/@aziza.bibin?source=rss-75fc5c88de76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:29:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aziza.bibin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Architecture Diagrams to Enforced Architecture: DDD + Hexagonal Architecture + ArchUnit]]></title>
            <link>https://medium.com/@aziza.bibin/from-architecture-diagrams-to-enforced-architecture-ddd-hexagonal-architecture-archunit-372aadc4033c?source=rss-75fc5c88de76------2</link>
            <guid isPermaLink="false">https://medium.com/p/372aadc4033c</guid>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[archunit]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Bipin Nair Gopalakrishnan]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 17:29:31 GMT</pubDate>
            <atom:updated>2026-08-29T17:29:31.997Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Can architecture be tested like business logic?</strong></p><p>I wanted to answer that question by building a practical Satellite Management System using <strong>Domain-Driven Design (DDD), Hexagonal Architecture, Ports &amp; Adapters, Spring Boot and ArchUnit</strong>.</p><p>The complete implementation is available on GitHub:</p><p><a href="https://github.com/hykuBipin/DDD_HEXAGONAL_ARCHUNIT_NEW?utm_source=chatgpt.com">DDD_HEXAGONAL_ARCHUNIT_NEW — GitHub</a></p><p>The project is intentionally designed around one principle:</p><blockquote><strong><em>Architecture should not only be documented. It should be executable and continuously enforced.</em></strong></blockquote><h3>The Problem: Architecture Decays</h3><p>Most projects begin with a clean architecture diagram.</p><p>A few months later, reality can look very different.</p><p>A controller directly calls a repository.</p><p>A domain object gets a Spring annotation.</p><p>A service starts depending on a concrete database implementation.</p><p>A temporary shortcut becomes permanent.</p><p>Eventually:</p><p><strong>Architecture documentation ≠ Architecture in code</strong></p><p>This project explores how we can reduce that gap.</p><p>The approach combines:</p><ul><li><strong>DDD</strong> for modeling the business domain</li><li><strong>Hexagonal Architecture</strong> for dependency isolation</li><li><strong>Ports &amp; Adapters</strong> for explicit contracts</li><li><strong>ArchUnit</strong> for automated architectural enforcement</li><li><strong>JUnit 5</strong> for behavioral and architecture validation</li></ul><h3>1. The Overall Architecture</h3><p><strong>Repository image:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwALp78T_gg_-EsDf0ICZw.png" /></figure><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 1 — Satellite Management System using DDD + Hexagonal Architecture.</em></strong><em> The domain model sits at the center while application use cases and infrastructure adapters remain outside the core.</em></blockquote><p><strong>Why this image is here:</strong><br>This is the best opening visual because it gives the reader the complete mental model before we start discussing individual layers.</p><p>The repository describes this diagram as the central visualization of the Satellite Management System architecture.</p><p>The architecture can be simplified as:</p><pre>REST / API<br>                        │<br>                        ▼<br>               Driving Adapter<br>                  Controller<br>                        │<br>                        ▼<br>                  Inbound Port<br>                        │<br>                        ▼<br>              ┌─────────────────┐<br>              │   Application   │<br>              │    Use Cases    │<br>              └────────┬────────┘<br>                       │<br>                       ▼<br>              ┌─────────────────┐<br>              │     Domain      │<br>              │     Model       │<br>              └────────┬────────┘<br>                       │<br>                       ▼<br>                 Outbound Port<br>                       │<br>              ┌────────┴────────┐<br>              ▼                 ▼<br>         JPA Adapter       Mongo Adapter<br>              │                 │<br>              ▼                 ▼<br>             SQL              MongoDB</pre><p>The important property is the <strong>dependency direction</strong>.</p><p>The inner domain should not know whether the application is using REST, PostgreSQL, MongoDB or another infrastructure technology.</p><h3>2. Start With the Domain — DDD</h3><p>The project uses a Satellite Management System as its business domain.</p><p>The domain contains concepts such as:</p><ul><li>Satellite</li><li>Orbit</li><li>Telemetry</li><li>SatelliteId</li><li>SatelliteStatus</li><li>SatelliteLaunchedEvent</li><li>AnomalyDetectedEvent</li></ul><p>The repository identifies Satellite as the aggregate root and Orbit and Telemetry as value objects.</p><p><strong>Repository image:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwALp78T_gg_-EsDf0ICZw.png" /></figure><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 2 — Domain-Driven Design view of the Satellite domain.</em></strong><em> The domain model focuses on business concepts rather than Spring, JPA or database structures.</em></blockquote><p>The idea is simple:</p><pre>Technology should serve the domain.</pre><pre>The domain should not serve the technology.</pre><p>That distinction becomes extremely important when the system grows.</p><h3>3. Ubiquitous Language</h3><p>DDD is not only about classes and packages.</p><p>It is also about creating a shared language between developers and domain experts.</p><p><strong>Repository image:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PM1R4-3gSlEv-67l_wCI4A.png" /></figure><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 3 — DDD Ubiquitous Language and Subdomains.</em></strong><em> The model separates the problem domain from core, supporting and generic concepts.</em></blockquote><p>For this project, terms such as:</p><pre>Satellite<br>Orbit<br>Telemetry<br>Launch<br>Anomaly<br>Satellite Status</pre><p>become part of the application’s vocabulary.</p><p>That makes the code easier to discuss because developers are talking in terms of the business rather than technical implementation details.</p><h3>4. Hexagonal Architecture: Protect the Core</h3><p>The next question is:</p><p><strong>How do we prevent infrastructure from leaking into the domain?</strong></p><p>Hexagonal Architecture provides the answer through <strong>Ports and Adapters</strong>.</p><p><strong>Repository image:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkCDQM0G5zrgbI-JbXhF-w.png" /></figure><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 4 — Primary/Driving and Secondary/Driven adapters surrounding the application and domain core.</em></strong></blockquote><p>The repository maps the architecture to concrete classes:</p><pre>Driving Adapter<br>    ↓<br>SatelliteController</pre><pre>Driving Port<br>    ↓<br>LaunchSatelliteUseCase</pre><pre>Application Service<br>    ↓<br>LaunchSatelliteService</pre><pre>Domain<br>    ↓<br>Satellite</pre><pre>Driven Port<br>    ↓<br>SatelliteRepository</pre><pre>Driven Adapters<br>    ↓<br>SatelliteJpaAdapter<br>SatelliteMongoAdapter</pre><p>The repository explicitly defines the controller as a driving adapter, use cases as inbound ports, repository interfaces as outbound ports, and JPA/Mongo implementations as driven adapters.</p><p>This gives us a very clear dependency boundary.</p><h3>5. The Domain Defines the Contract</h3><p>One of the most important interfaces in the project is:</p><pre>public interface SatelliteRepository {</pre><pre>    Satellite save(Satellite satellite);</pre><pre>    Optional&lt;Satellite&gt; findById(SatelliteId id);</pre><pre>    List&lt;Satellite&gt; findAll();</pre><pre>    boolean existsById(SatelliteId id);<br>}</pre><p>This interface belongs to the domain boundary.</p><p>The domain does not say:</p><pre>Use JPA.<br>Use Hibernate.<br>Use MongoDB.<br>Use PostgreSQL.</pre><p>It says:</p><blockquote><strong><em>I need a way to persist a Satellite.</em></strong></blockquote><p>Infrastructure decides how that contract is fulfilled.</p><h3>6. One Port, Multiple Database Adapters</h3><p>This is one of the strongest demonstrations in the project.</p><p><strong>Repository image:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMakMjrNDl8w_z5bJPgSFw.png" /></figure><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 5 — Multi-database adapter swapping. The same </em></strong><strong><em>SatelliteRepository port can be implemented by JPA or MongoDB without changing the domain core.</em></strong></blockquote><p>The repository contains:</p><pre>SatelliteRepository<br>       │<br>       ├──────────────► SatelliteJpaAdapter<br>       │                       │<br>       │                       ▼<br>       │                    SQL DB<br>       │<br>       └──────────────► SatelliteMongoAdapter<br>                               │<br>                               ▼<br>                            MongoDB</pre><p>The actual repository documents both SatelliteJpaAdapter and SatelliteMongoAdapter implementations.</p><p>This is where Hexagonal Architecture becomes more than a diagram.</p><p>The database implementation becomes a replaceable adapter.</p><h3>7. What About Onion Architecture?</h3><p>The same dependency principle can also be visualized using concentric layers.</p><p><strong>Repository image:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGwGeF3h5nkwBM10unIdbQ.png" /></figure><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 6 — Concentric representation of the inward dependency rule. Infrastructure remains outside while domain rules remain at the center.</em></strong></blockquote><p>You don’t need this image if the Medium article feels too long.</p><p>For a technical audience, however, it provides a useful comparison between the architectural representations.</p><p>The repository includes this diagram as one of its five architecture visualizations.</p><h3>8. The Missing Piece: Enforcement</h3><p>At this point we have a nice architecture.</p><p>But there is still a problem.</p><p>What stops another developer from doing this tomorrow?</p><pre>SatelliteController<br>       ↓<br>SatelliteJpaAdapter</pre><p>Or adding:</p><pre>@Component</pre><p>to a domain class?</p><p>Documentation cannot stop it.</p><p>Code review might catch it.</p><p>But we can do something stronger.</p><p><strong>We can make architecture executable.</strong></p><h3>9. Enter ArchUnit</h3><p>The project contains:</p><pre>HexagonalArchitectureTest.java</pre><p>with <strong>11 automated architectural rules</strong>.</p><p>These rules are executed as part of the test phase.</p><p>The repository documents rules such as:</p><ol><li>Domain must not depend on adapters</li><li>Domain model must not use Spring</li><li>Domain model must not use JPA</li><li>Application services must implement inbound ports</li><li>Application must not depend on adapters</li><li>Inbound adapters must not depend on outbound adapters</li><li>Controllers must depend on ports, not service implementations</li><li>Naming conventions must be respected</li><li>Ports must reside in the domain</li><li>Cyclic dependencies are forbidden</li><li>Layered architecture must be respected</li></ol><p>These are explicitly documented in the repository’s HexagonalArchitectureTest.java section.</p><p><strong>[IMAGE 7 — PLACE HERE]</strong></p><p><strong>Evidence image:</strong> docs/evidence/ → <strong>ArchUnit Layer Failure screenshot</strong></p><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 7 — ArchUnit detecting an architectural boundary violation.</em></strong></blockquote><p>This is arguably the most important image in the entire article.</p><p>Because now we aren’t saying:</p><blockquote><em>“The architecture should be respected.”</em></blockquote><p>We’re showing:</p><blockquote><strong><em>“The architecture can fail the build when it isn’t respected.”</em></strong></blockquote><h3>10. Architecture Becomes a Build Gate</h3><p>The execution flow is:</p><p><strong>Repository image:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1i86MV85iYljGTjWvtIoQ.png" /></figure><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 8 — Explicit architecture boundaries connecting domain, application, primary adapters and secondary adapters.</em></strong></blockquote><p>The project’s documented execution model is:</p><pre>mvn compile<br>      │<br>      ▼<br>Compiled Classes<br>      │<br>      ▼<br>mvn test<br>      │<br>      ├── Unit Tests<br>      ├── Integration Tests<br>      └── ArchUnit<br>             │<br>             ▼<br>       Architecture Valid?<br>          /          \<br>        YES           NO<br>         │             │<br>         ▼             ▼<br>   mvn package      BUILD FAILS<br>         │<br>         ▼<br>      Deploy</pre><p>ArchUnit runs during the Maven test phase after compilation and before packaging/deployment. If a rule is violated, the build fails.</p><p>That changes architecture from documentation into an engineering constraint.</p><h3>11. Proving the Architecture Can Fail</h3><p>A good architecture demonstration should prove both:</p><p><strong>PASS</strong></p><p>and</p><p><strong>FAIL</strong></p><p>The repository provides a deliberate failure scenario.</p><p>Open:</p><pre>src/main/java/com/satellite/domain/model/Satellite.java</pre><p>Add:</p><pre>import org.springframework.stereotype.Component;</pre><p>Then run:</p><pre>mvn test</pre><p>ArchUnit detects the violation.</p><p>The documented output includes:</p><pre>Architecture Violation [Priority: MEDIUM]</pre><p>for the rule preventing domain model classes from using @Component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mz09MEb8kknbXjrw.png" /></figure><p><strong>Evidence image:</strong> docs/evidence/ → <strong>ArchUnit Layer Failure screenshot</strong></p><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 9 — Deliberately introducing a forbidden Spring dependency into the domain causes ArchUnit to reject the architecture.</em></strong></blockquote><p>This is the difference between:</p><pre>Architecture documentation</pre><p>and:</p><pre>Executable architecture</pre><h3>12. Now Prove the Correct Architecture</h3><p>After removing the violation:</p><pre>mvn clean test</pre><p>the repository documents:</p><pre>Tests run: 4<br>Failures: 0<br>Errors: 0</pre><pre>Tests run: 5<br>Failures: 0<br>Errors: 0</pre><pre>Tests run: 14<br>Failures: 0<br>Errors: 0</pre><pre>Tests run: 14<br>Failures: 0<br>Errors: 0</pre><pre>Tests run: 37<br>Failures: 0<br>Errors: 0</pre><pre>BUILD SUCCESS</pre><p>The 37 tests are distributed across controller integration tests, application tests, ArchUnit tests and domain tests.</p><p><strong>Evidence image:</strong> docs/evidence/ → <strong>Surefire HTML Report</strong></p><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 10 — Successful Maven/Surefire validation: 37 tests, 0 failures, 0 errors.</em></strong></blockquote><p>This is the evidence I wanted from the project.</p><p>Not just:</p><blockquote><em>“The architecture looks clean.”</em></blockquote><p>But:</p><blockquote><strong><em>“The architecture was automatically tested.”</em></strong></blockquote><h3>13. Architecture Meets Real Domain Behavior</h3><p>The project also validates the architecture through REST APIs.</p><p>The documented flow includes:</p><pre>POST /api/v1/satellites</pre><p>to launch a satellite.</p><p>Then:</p><pre>PUT /api/v1/satellites/{id}/telemetry</pre><p>to update telemetry.</p><p>Normal telemetry can be sent with values such as:</p><pre>{<br>  &quot;batteryPercentage&quot;: 92.5,<br>  &quot;signalStrengthDbm&quot;: -68.0,<br>  &quot;temperatureCelsius&quot;: 21.5<br>}</pre><p>The project also demonstrates an anomaly scenario where battery drops below 15%, triggering an ANOMALY state transition.</p><p><strong>Evidence image:</strong> docs/evidence/ → <strong>Postman POST Launch Satellite</strong></p><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 11 — Launching a satellite through the REST driving adapter.</em></strong></blockquote><h3>14. Normal Telemetry</h3><p><strong>Evidence image:</strong> docs/evidence/ → <strong>Postman Normal Telemetry (HTTP 200 OK)</strong></p><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 12 — Normal telemetry successfully processed through the application boundary.</em></strong></blockquote><p>This demonstrates that the architecture is not isolated from application behavior.</p><p>The domain model still drives real use cases.</p><h3>15. Anomaly Detection</h3><p><strong>Evidence image:</strong> docs/evidence/ → <strong>Postman Anomaly Trigger (Status: ANOMALY)</strong></p><p><strong>Caption:</strong></p><blockquote><strong><em>Figure 13 — Low-battery telemetry triggering the Satellite domain’s anomaly state transition.</em></strong></blockquote><p>The documented example sends:</p><pre>{<br>  &quot;batteryPercentage&quot;: 10.0,<br>  &quot;signalStrengthDbm&quot;: -70.0,<br>  &quot;temperatureCelsius&quot;: 20.0<br>}</pre><p>This results in the domain transitioning to an anomaly state.</p><p>That is an important distinction:</p><p><strong>The domain contains the business rule.</strong></p><p>The REST API merely invokes it.</p><h3>16. What Each Pattern Solves</h3><p>At this point, the relationship between the techniques becomes clearer.</p><p>TechniqueResponsibilityDDDModel the business domainHexagonal ArchitectureIsolate the corePortsDefine boundariesAdaptersConnect technologyArchUnitEnforce architectural rulesJUnitValidate behaviorIntegration TestsValidate system interaction</p><p>Together:</p><pre>DDD<br> ↓<br>Business Model<br> ↓<br>Hexagonal Architecture<br> ↓<br>Explicit Boundaries<br> ↓<br>ArchUnit<br> ↓<br>Executable Architecture<br> ↓<br>Build Gate</pre><h3>17. The Most Important Lesson</h3><p>The biggest lesson from this project is:</p><blockquote><strong><em>Architecture is not a folder structure.</em></strong></blockquote><p>You can create:</p><pre>domain/<br>application/<br>infrastructure/</pre><p>and still have a tightly coupled application.</p><p>The real question is:</p><pre>WHO DEPENDS ON WHOM?</pre><p>That is why architectural rules matter.</p><p>A package structure helps humans understand the system.</p><p>Architecture tests help the team preserve it.</p><h3>18. From Documentation to Enforcement</h3><p>There is a fundamental difference between these two statements.</p><h3>Documentation</h3><pre>Domain should not depend on infrastructure.</pre><h3>Enforcement</h3><pre>@ArchTest<br>static final ArchRule domainMustNotDependOnAdapters = ...</pre><p>The first is guidance.</p><p>The second can fail the build.</p><p>That distinction becomes increasingly valuable as teams grow.</p><h3>19. Final Architecture</h3><p>The project brings together:</p><pre>REST<br>                   │<br>                   ▼<br>             Driving Adapter<br>                   │<br>                   ▼<br>              Inbound Port<br>                   │<br>                   ▼<br>             Application<br>                   │<br>                   ▼<br>                Domain<br>                   │<br>                   ▼<br>             Outbound Port<br>                /      \<br>               /        \<br>              ▼          ▼<br>          JPA Adapter  Mongo Adapter<br>              │          │<br>              ▼          ▼<br>             SQL       MongoDB</pre><p>Around this architecture sits another layer:</p><pre>ArchUnit<br>                │<br>                ▼<br>        Architecture Rules<br>                │<br>                ▼<br>           mvn test<br>                │<br>        ┌───────┴───────┐<br>        ▼               ▼<br>      PASS             FAIL<br>        │               │<br>        ▼               ▼<br>     Package          Block Build</pre><p>That is the core idea of this project.</p><h3>20. Conclusion</h3><p>DDD gives the application a meaningful business model.</p><p>Hexagonal Architecture protects that model.</p><p>Ports create explicit boundaries.</p><p>Adapters isolate technology.</p><p>ArchUnit makes those boundaries executable.</p><p>JUnit and integration tests validate the behavior around them.</p><p>And Maven turns the whole thing into a repeatable engineering feedback loop.</p><p>So instead of:</p><pre>Architecture<br>     ↓<br>Documentation</pre><p>we can build:</p><pre>Architecture<br>     ↓<br>Rules<br>     ↓<br>Automated Tests<br>     ↓<br>Build Gate<br>     ↓<br>Continuous Enforcement</pre><p><strong>Architecture should not just be something we draw.</strong></p><p><strong>It should be something our codebase can defend.</strong></p><h3>Explore the complete implementation</h3><p>The repository contains the Java implementation, architecture diagrams, evidence screenshots, presentation deck, demo guide and ArchUnit tests.</p><p><a href="https://github.com/hykuBipin/DDD_HEXAGONAL_ARCHUNIT_NEW?utm_source=chatgpt.com">GitHub — DDD + Hexagonal Architecture + ArchUnit</a></p><p>If you’re working on a Java/Spring Boot system and struggling with architectural erosion, this is an approach worth experimenting with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=372aadc4033c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TOON: Rethinking Data Representation for the Age of AI]]></title>
            <link>https://medium.com/@aziza.bibin/toon-rethinking-data-representation-for-the-age-of-ai-3e2641e68131?source=rss-75fc5c88de76------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e2641e68131</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[toon]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Bipin Nair Gopalakrishnan]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 04:13:24 GMT</pubDate>
            <atom:updated>2026-06-29T04:13:24.240Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why the Future of Intelligent Systems May Need More Than JSON</h3><p>For over two decades, <strong>JSON (JavaScript Object Notation)</strong> has been the foundation of modern software communication. From web applications and mobile apps to cloud-native microservices, JSON has become the universal language for exchanging structured data.</p><p>Its success is easy to understand. JSON is simple, lightweight, human-readable, and supported by virtually every programming language and platform.</p><p>However, software systems are evolving. We are moving beyond applications that simply exchange data toward systems that continuously build, maintain, and reason over interconnected knowledge. Artificial Intelligence, autonomous agents, enterprise knowledge systems, and collaborative workflows are beginning to expose limitations in traditional document-oriented representations.</p><p>This naturally leads to an interesting question:</p><blockquote><strong><em>What if our data representation understood relationships and object identity as first-class concepts, rather than treating everything as nested documents?</em></strong></blockquote><p>This is the idea behind <strong>TOON (Typed Object-Oriented Notation)</strong>.</p><p>While still an emerging concept, TOON represents a different way of thinking about structured information — one that aligns closely with how modern intelligent systems organize knowledge.</p><h3>The Evolution of Data Representation</h3><p>Every generation of software has introduced a representation format that addressed the needs of its time.</p><ul><li>XML emphasized structured documents.</li><li>JSON simplified data exchange for web applications.</li><li>Binary serialization formats optimized performance and network efficiency.</li></ul><p>Each solved a specific problem.</p><p>Today’s AI-driven systems introduce a new challenge — not simply transmitting information, but representing <strong>context, relationships, identity, and shared knowledge</strong>.</p><p>Traditional document formats excel at representing isolated pieces of information. They become increasingly complex when information is deeply interconnected.</p><h3>Documents vs Connected Knowledge</h3><p>Consider a customer within an enterprise system.</p><p>That customer may be connected to:</p><ul><li>Orders</li><li>Products</li><li>Support requests</li><li>Billing information</li><li>Recommendations</li><li>User preferences</li><li>Business policies</li></ul><p>Each of these entities may also reference one another.</p><p>This creates a network of relationships rather than a simple hierarchical document.</p><p>Traditional serialization formats generally represent these relationships by repeatedly nesting or duplicating information.</p><p>As systems grow, maintaining consistency across duplicated representations becomes increasingly challenging.</p><h3>A Different Perspective</h3><p>TOON approaches this problem differently.</p><p>Instead of focusing solely on documents, TOON focuses on <strong>objects and their relationships</strong>.</p><p>Conceptually, every object possesses:</p><ul><li>A unique identity</li><li>Explicit relationships</li><li>Reusable references</li><li>Rich metadata</li><li>Well-defined types</li></ul><p>Rather than repeatedly embedding the same information, objects can be referenced wherever they are needed.</p><p>The result is not merely a serialized document, but a connected representation of knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SsMFCukc2mcpbHTAhf0mjg.png" /></figure><h3>Why This Matters for AI</h3><p>Artificial Intelligence increasingly depends on context rather than isolated facts.</p><p>An AI assistant rarely answers questions using a single document.</p><p>Instead, it combines information from multiple interconnected sources:</p><ul><li>Previous conversations</li><li>User preferences</li><li>Organizational knowledge</li><li>External tools</li><li>Business rules</li><li>Historical decisions</li></ul><p>The intelligence emerges not from individual pieces of data, but from the relationships between them.</p><p>Representing those relationships efficiently becomes increasingly valuable as systems become larger and more autonomous.</p><h3>Thinking Beyond Documents</h3><p>Modern AI applications continuously build and update internal knowledge structures.</p><p>Instead of asking:</p><blockquote><em>“What does this document contain?”</em></blockquote><p>they often ask:</p><ul><li>What is connected to this entity?</li><li>What changed recently?</li><li>Which objects depend on one another?</li><li>What information is shared across multiple contexts?</li></ul><p>These are graph-oriented questions.</p><p>A representation designed around object identity and relationships naturally aligns with this style of reasoning.</p><h3>JSON and TOON Are Solving Different Problems</h3><p>It is tempting to compare TOON directly with JSON, but they address different concerns.</p><p>JSON is optimized for exchanging structured documents.</p><p>TOON is designed to represent interconnected object networks.</p><p>Rather than replacing JSON, TOON extends the conversation toward representing systems whose primary value lies in relationships rather than documents.</p><p>CapabilityJSONTOONHuman ReadabilityExcellentModerateLightweight ExchangeExcellentGoodObject IdentityLimitedNativeShared ReferencesLimitedNativeRelationship ModelingBasicRichKnowledge RepresentationModerateStrongContext PreservationLimitedStrongComplex Object NetworksModerateExcellent</p><p>Both approaches have strengths.</p><p>The appropriate choice depends on the nature of the problem being solved.</p><h3>Where TOON Could Add Value</h3><p>A relationship-oriented representation becomes increasingly useful wherever information is highly interconnected.</p><p>Potential application areas include:</p><ul><li>AI memory architectures</li><li>Multi-agent AI systems</li><li>Enterprise knowledge platforms</li><li>Semantic search systems</li><li>Knowledge graphs</li><li>Workflow orchestration</li><li>Business process automation</li><li>Recommendation engines</li><li>Intelligent assistants</li><li>Complex domain modeling</li></ul><p>These systems spend more time managing relationships than exchanging isolated documents.</p><h3>Potential Advantages</h3><h3>Richer Context</h3><p>Objects retain their identity while preserving their relationships with other entities.</p><h3>Reduced Duplication</h3><p>Shared information can be referenced instead of repeatedly copied throughout the system.</p><h3>Better Knowledge Representation</h3><p>Relationships become explicit rather than being inferred from deeply nested structures.</p><h3>Improved Maintainability</h3><p>Updating a shared object automatically reflects wherever that object is referenced.</p><h3>Natural Fit for AI</h3><p>Many AI systems already reason over connected entities rather than isolated records.</p><p>A relationship-aware representation aligns more closely with that internal model.</p><h3>Foundation for Persistent Memory</h3><p>Future AI systems are expected to maintain long-term context across conversations, workflows, and decision-making processes.</p><p>Representing persistent knowledge as interconnected objects offers a compelling architectural direction.</p><h3>Challenges to Consider</h3><p>Like any emerging approach, TOON introduces new considerations.</p><h3>Ecosystem Maturity</h3><p>JSON benefits from decades of tooling, libraries, standards, and widespread adoption.</p><p>A newer representation would require comparable ecosystem support before achieving broad adoption.</p><h3>Learning Curve</h3><p>Most developers naturally think in terms of documents.</p><p>Relationship-centric modeling requires a different architectural mindset.</p><h3>Tooling and Standards</h3><p>Visualization, debugging, validation, schema management, and interoperability become increasingly important as representations evolve beyond simple documents.</p><h3>Looking Ahead</h3><p>Artificial Intelligence is gradually shifting from answering questions to maintaining knowledge.</p><p>As AI systems evolve toward persistent memory, collaborative reasoning, and long-running autonomous workflows, the underlying representation of information may become just as important as the models themselves.</p><p>Future architectures may not simply exchange documents.</p><p>They may exchange knowledge.</p><p>Representing that knowledge efficiently requires thinking beyond nested structures and toward connected information.</p><p>Whether TOON itself becomes widely adopted or inspires future serialization standards, the underlying architectural idea is compelling:</p><blockquote><strong><em>The future of intelligent software is not defined solely by better models, but by better ways of representing the knowledge those models understand.</em></strong></blockquote><h3>Final Thoughts</h3><p>JSON transformed software development by making data exchange simple, universal, and interoperable. It continues to be the right choice for APIs, web applications, configuration, and countless other use cases.</p><p>TOON represents a different perspective — one that prioritizes object identity, relationships, and contextual knowledge. Rather than competing with JSON, it explores how information might be represented in systems where interconnected knowledge is more valuable than isolated documents.</p><p>As software enters an era increasingly shaped by AI, understanding how we model information may become as important as understanding how we process it. The next evolution in intelligent systems may not begin with a new algorithm, but with a richer way of describing the world those algorithms operate within.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e2641e68131" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Built Dieto- (AI Calorie Tracker): A Dual-Engine AI Diet Scanner for Android (YOLOv8 +…]]></title>
            <link>https://medium.com/@aziza.bibin/how-we-built-dieto-ai-calorie-tracker-a-dual-engine-ai-diet-scanner-for-android-yolov8-897d53a8175c?source=rss-75fc5c88de76------2</link>
            <guid isPermaLink="false">https://medium.com/p/897d53a8175c</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[health-technology]]></category>
            <category><![CDATA[yolov8]]></category>
            <dc:creator><![CDATA[Bipin Nair Gopalakrishnan]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 18:51:05 GMT</pubDate>
            <atom:updated>2026-06-20T18:51:05.579Z</atom:updated>
            <content:encoded><![CDATA[<h3>How We Built Dieto- (AI Calorie Tracker): A Dual-Engine AI Diet Scanner for Android (YOLOv8 + Google ML Kit OCR)</h3><p><em>Discover how to combine real-time computer vision, packaging cover text parsing, and dynamic portion scaling into a premium, offline Android application.</em></p><p>In an era dominated by cloud-based AI, mobile hardware has quietly evolved to the point where it can run sophisticated computer vision models directly in your pocket. Yet, most calorie-tracking applications still rely on tedious manual inputs or slow API requests to remote databases.</p><p>We set out to build <strong>Dieto</strong> — a premium, fully offline Android application that operates as a real-time smart diet scanner. By combining two distinct machine learning pipelines (local <strong>YOLOv8 Object Detection</strong> and <strong>Google ML Kit OCR</strong>), Dieto lets you scan a meal plate, automatically calculates portion sizes, scales macronutrients/micronutrients, and delivers personalized dietician advice instantly.</p><p>In this article, we’ll break down Dieto’s architecture, dive into the mathematical models behind our portion estimation, and share the exact technical implementation details so you can build your own smart camera scanner.</p><h3>📸 The Core Concept: Dual-Engine Scanning</h3><p>Most smart scanner apps suffer from a fatal flaw: they either <em>only</em> detect raw fruits/vegetables visually or <em>only</em> read barcodes. If you have a plate with loose broccoli and a packed cup of yogurt, standard apps fail to capture both seamlessly.</p><p>Dieto solves this by running a <strong>Dual-Engine ML Pipeline</strong> over a live CameraX feed:</p><ol><li><strong>The Visual Tracker (YOLOv8)</strong>: Detects raw and unpackaged foods (like apples, bananas, broccoli, and tomatoes) by outputting bounding boxes, class labels, and confidence scores in real time.</li><li><strong>The Cover Reader (Google ML Kit OCR)</strong>: Runs in parallel to scan packaged foods (like milk cartons, yogurt, and sandwiches). If it detects a nutrition panel, it parses the text, extracts the macronutrient metrics, and registers a custom scanned item on the fly.</li></ol><h3>🛠️ The Technical Tech Stack</h3><p>To run multiple ML models at 60 FPS on mobile devices without melting the battery, we selected a highly efficient, native stack:</p><ul><li><strong>Language / Core</strong>: Java, Android SDK (Target SDK 34 / Android 14+).</li><li><strong>Camera Feed</strong>: <strong>Android CameraX</strong> (processing image frames via an isolated background thread analyzer at 1 FPS to guarantee smooth UI rendering).</li><li><strong>Object Detection Engine</strong>: <strong>ONNX Runtime Mobile (v1.22.0)</strong> executing a quantized <strong>YOLOv8n</strong> model (yolov8n.onnx) offline.</li><li><strong>Text Recognition Engine</strong>: <strong>Google ML Kit Text Recognition</strong> (on-device API).</li><li><strong>User Interface</strong>: ConstraintLayout with vanilla CSS-equivalent styling (custom shape overlays, dynamic calorie badges, and a custom glassmorphic overlay canvas).</li><li><strong>Data Layer</strong>: Decoupled JSON registry (foods.json) loaded on startup, persisted via Android SharedPreferences.</li></ul><h3>📐 Architecture &amp; Processing Flow</h3><p>To keep the UI responsive, all image analysis happens asynchronously. The following diagram illustrates the lifecycle of a camera frame inside Dieto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXzmsPmTP8_jEAt9T2kg5w.png" /></figure><h3>🧠 Bending the Math: Dynamic Portion Size Scaling</h3><p>One of the biggest innovations in Dieto is how it translates a flat 2D image box into a portion estimate without depth-sensing hardware.</p><p>We defined a <strong>Reference Area</strong> ($A_{ref}$) in the configuration for each food item. This represents the average bounding box size (in relative pixels) when that item is placed on a plate at a standard distance. When the model detects an item, it calculates the <strong>Active Area</strong> ($A_{active}$):</p><p>$$A_{active} = \text{Width} \times \text{Height}$$</p><p>The portion size ($P$) is then computed as:</p><p>$$P = \text{Clamp}\left( \frac{A_{active}}{A_{ref}}, ; 0.5, ; 3.0 \right)$$</p><p>This portion value is rounded to the nearest half-serving (e.g., 0.5, 1.0, 1.5, 2.0, 2.5, 3.0). All nutritional values are multiplied by $P$:</p><p>$$\text{Calories}<em>{\text{scaled}} = \text{Calories}</em>{\text{base}} \times P$$ $$\text{Carbs}<em>{\text{scaled}} = \text{Carbs}</em>{\text{base}} \times P$$</p><p>For instance, if the camera detects a massive chunk of Broccoli that takes up three times the standard reference area, it is automatically registered as Broccoli (3.0 serv), scaling the calorie contribution from 30 kcal (base) to 90 kcal in the total count.</p><h3>🔬 Behind the Scenes: The OCR Nutrition Parser</h3><p>Here is how our Google ML Kit text processing pipeline works. When reading packaging labels, the app searches text blocks for standard nutrition keywords using case-insensitive regular expressions:</p><pre>// Parse text lines to detect calories and macronutrients<br>for (Text.Line line : block.getLines()) {<br>    String lineText = line.getText().toLowerCase().trim();<br>    <br>    if (lineText.contains(&quot;calories&quot;) || lineText.contains(&quot;kcal&quot;)) {<br>        int calories = extractFirstNumber(lineText);<br>        if (calories &gt; 0) activeScannedCalories = calories;<br>    }<br>    else if (lineText.contains(&quot;protein&quot;) || lineText.contains(&quot;prot&quot;)) {<br>        float protein = extractFirstFloat(lineText);<br>        if (protein &gt; 0) activeScannedProtein = protein;<br>    }<br>    else if (lineText.contains(&quot;carbohydrate&quot;) || lineText.contains(&quot;carbs&quot;)) {<br>        float carbs = extractFirstFloat(lineText);<br>        if (carbs &gt; 0) activeScannedCarbs = carbs;<br>    }<br>}</pre><p>Once parsed, if the app sees a label containing &quot;Nutrition Facts&quot;, it registers a custom food item named Milk (Scanned Label) with the exact parameters it read. The user gets a toast notification, and the custom item is placed on the plate consensus map.</p><h3>🎨 Premium UI Design: Glassmorphism</h3><p>To give the application a premium, state-of-the-art aesthetic, we abandoned standard Android styles in favor of a curated <strong>dark-mode color scheme</strong> combined with <strong>glassmorphism</strong> visual cards.</p><ul><li><strong>Harmony of Color</strong>: Built around deep graphite (#1E1E24), slate gray (#2D2D35), coral red (#FF6B6B), teal (#4ECDC4), and cream yellow (#FFE66D).</li><li><strong>Progress Tracking</strong>: Color-coded linear indicators for Carbs, Protein, Unsaturated Fats, and Saturated Fats, with a prominent glowing badge for the Kcal goal.</li><li><strong>Dietician Recommendation</strong>: An embedded cards layout featuring color-coded micro-indicators that suggest adjustments (e.g., adding sandwiches to resolve a protein deficit) based on active plate composition.</li></ul><h3>📊 Live Verification</h3><p>We tested the application directly within the Android emulator to ensure reliability. Here is how the app handles plate identification:</p><h3>Real-Time Detection Output</h3><p>When scanning a complex plate consisting of multiple items, YOLOv8 highlights the Broccoli bounds. Concurrently, manual additions layered over the screen (like Banana, Avocado, Cucumber, and Tomato) are consolidated.</p><p>The screen updates the portion values, yielding a total plate representation of <strong>469 / 650 kcal</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*5OJOqGcQzlIthOzr.png" /></figure><p>Inside the application, clicking <strong>VIEW DETAILS</strong> yields an itemized list of nutrition breakdowns, while clicking <strong>+ RECORD</strong> logs the meal to persistent storage, updating the user’s weekly history view.</p><h3>🚀 Get the Source Code</h3><p>Dieto is fully open-source. The repository contains the full CameraX configurations, ONNX inference wrappers, and the text parsing logic.</p><p>Explore the codebase and deploy it to your device: 👉 <a href="https://github.com/hykuBipin/Dieto"><strong>Dieto GitHub Repository</strong></a></p><p><em>What do you think about on-device AI for diet scanning? Let us know in the comments, and don’t forget to clap!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=897d53a8175c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Smart Eye for Your Phone: How to Create a Real-Time Object Detector App for Android]]></title>
            <link>https://medium.com/@aziza.bibin/building-a-smart-eye-for-your-phone-how-to-create-a-real-time-object-detector-app-for-android-4d24d1268771?source=rss-75fc5c88de76------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d24d1268771</guid>
            <dc:creator><![CDATA[Bipin Nair Gopalakrishnan]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 19:37:37 GMT</pubDate>
            <atom:updated>2026-06-09T19:37:37.378Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine pointing your phone’s camera around a room, and it instantly labels everything it sees — a cat, a TV, a dining table, or a bottle — with glowing green boxes. It sounds like science fiction, but it is actually one of the most accessible entry points into the world of Artificial Intelligence (AI) and mobile software development.</p><p>In this guide, we will walk you through how we built **Spacefinity**, a real-time object detector app for Android. We’ll explain the magic behind how it works, how we made the AI run directly on the phone, and how we solved real-world bugs to make it compatible with the newest Android 15 systems — all written in plain English that anyone can understand!</p><h3><strong>The Recipe: Our Tech Ingredients</strong></h3><p>To build an app that can “see” in real-time, we combined three main ingredients:</p><p>1. <strong>The Eyes (CameraX)</strong>: This is Google’s modern camera tool for Android. It handles capturing high-quality video frames from your phone’s lens and streaming them into the app dozens of times per second.<br>2. <strong>The Brain (YOLOv8)</strong>: YOLO stands for <strong>”You Only Look Once”</strong>. It is a highly optimized neural network (a virtual brain) trained on a massive dataset of images. In a single glance, it can detect up to 80 everyday objects, from people and cars to pizzas and cups.<br>3. <strong>The Engine (ONNX Runtime)</strong>: A computer science “translator” that takes our AI model and runs it at lightning-fast speeds directly on the phone’s hardware, without needing to send images to a server over the internet.</p><h3><strong>How it Works: The 3 Secrets of Mobile AI</strong></h3><p>An AI model cannot just “look” at a standard phone photo; it needs the image to be prepared in a very specific format. Here is how Spacefinity processes every frame behind the scenes in three simple steps:</p><p><strong>1. Resizing the World</strong><br>YOLOv8 can only process square images of an exact size: <strong>640 by 640 pixels</strong>. No matter how large or wide the photo from your camera is, the app immediately scales it down to this square dimension.</p><p><strong>2. Sorting Colors (The HWC-to-CHW Shift)</strong><br>A digital screen displays colors by mixing Red, Green, and Blue pixels side-by-side (like `RGB-RGB-RGB`). But our AI model wants them separated into distinct piles: all the Reds first, then all the Greens, then all the Blues. We rearrange the pixels so the AI brain can scan the color layers individually.</p><blockquote><strong>Standard Photo Layout: [Red-Green-Blue] [Red-Green-Blue] [Red-Green-Blue]</strong></blockquote><blockquote><strong>AI-Ready Photo Layout: [All Red Pixels…] [All Green Pixels…] [All Blue Pixels…]</strong></blockquote><p><strong>3. Erasing the “Double Visuals” (NMS)</strong><br>Because the AI is very eager, it might see a single cat and draw five different boxes around it, thinking they are five separate cats.</p><p>To prevent this clutter, we implement a filter called <strong>Non-Maximum Suppression (NMS)</strong>. It compares overlapping boxes and keeps only the box with the highest confidence score, erasing all the copycat boxes.</p><h3><strong>Technical Architecture &amp; Processing Flow</strong></h3><p>To bring this together, we designed a pipeline that runs asynchronously. This ensures the phone screen stays smooth (60fps) while the AI works in the background.</p><h3><strong>System Architecture Flowchart</strong></h3><p>Below is the data lifecycle of a camera frame, from raw capture to screen display:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLKrvdUxdrsl2KS6lErZPQ.png" /></figure><h3><strong>Threading and Sequence Diagram:</strong></h3><p>This timeline diagram illustrates how the background execution thread interacts with the main user interface (UI) thread to avoid lagging:</p><p><strong>UI Thread Camera Executor ONNX Engine Canvas View</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYu92tQy1OaT3E19nY_YBg.png" /></figure><h3><strong>Overcoming Real-World Roadblocks</strong></h3><p>During development, we hit two major hurdles that would crash the app immediately on modern Android devices:</p><p><strong>The Android 15 16KB Page Size Issue</strong><br>Modern phone operating systems are switching to a new internal memory structure (16KB page size) to load apps faster and save battery. However, older AI libraries were built for the old 4KB structure. When loaded, the new Android system blocked them, displaying compatibility warnings.<br>* **Our Solution**: We upgraded the app’s internal engines (ONNX Runtime to `1.22.0` and CameraX to `1.4.0`) to versions that are built to support the new 16KB standards, allowing them to load safely.</p><p><strong>The “Class” Label Mismatch</strong><br>Initially, the app displayed generic tags like `”Class 15&quot;` or `”Class 62&quot;`. This is because the app’s dictionary file only had 5 words in it, while the AI model was trying to say 80 different things.<br>* **Our Solution**: We expanded our dictionary file to list all 80 COCO categories in the correct order. Now, a cat is labeled as a `”cat”`, a TV as a `”tv”`, and a dining table as a `”dining table”`.</p><p><strong>Seeing is Believing: Spacefinity in Action</strong></p><p>Here is the step-by-step evidence of our successful installation and validation:</p><p><strong>Step 1: The App Installed &amp; Custom Logo</strong><br>Here is the Spacefinity app successfully installed on the phone’s home screen, along with the custom logo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mI39Bad0Mi_GCYWM_X4QQg.png" /></figure><p>And here is its position on the phone’s home screen (bottom right icon):</p><p><strong>Step 2: Requesting Access</strong><br>When launched for the first time, the app securely requests camera permissions from the user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*fHy9JcX2oJ7y7yYyU7ygIQ.png" /></figure><p><strong>Step 3: Real-Time Detection</strong><br>Once permission is granted, Spacefinity opens the camera. As we navigate the room, the AI model instantly identifies objects with glowing green boxes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*qgfAUJTL8nQtUvh5stsJlQ.png" /></figure><p><strong>Spotting a Cat</strong>: The model detects the virtual room’s cat model with 86% confidence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*3zfpCMvdqCMw1jmk76ODJg.png" /></figure><p><strong>Scanning the Kitchen</strong>: Walk into the kitchen, and it detects a dog, the refrigerator, and the oven:</p><h3><strong>Conclusion:</strong></h3><p>By combining modern camera frameworks with optimized AI runtimes, we’ve built a fully-functional “smart eye” that sits right on your phone’s home screen. The best part is that all of this processing happens offline on your device, ensuring privacy and speed.</p><p>Next time you open a smart camera app on your phone, you’ll know exactly how it is resizing, sorting colors, and filtering duplicate boxes to see the world!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d24d1268771" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building a Real-Time AI Cricket Commentary System using Spring AI, Ollama, WebSockets & STOMP]]></title>
            <link>https://medium.com/@aziza.bibin/building-a-real-time-ai-cricket-commentary-system-using-spring-ai-ollama-websockets-stomp-fafc2a1d26b5?source=rss-75fc5c88de76------2</link>
            <guid isPermaLink="false">https://medium.com/p/fafc2a1d26b5</guid>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[stomp]]></category>
            <dc:creator><![CDATA[Bipin Nair Gopalakrishnan]]></dc:creator>
            <pubDate>Mon, 25 May 2026 07:49:54 GMT</pubDate>
            <atom:updated>2026-05-25T07:49:54.307Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications are moving beyond traditional request-response systems.</p><p>Platforms like Cricbuzz, Cricinfo, trading dashboards, and live analytics tools require:</p><ul><li>real-time communication</li><li>event-driven architecture</li><li>AI-generated insights</li><li>low-latency updates</li></ul><p>To understand these concepts deeply, I built a real-time AI-powered cricket commentary system using:</p><ul><li>Spring Boot</li><li>Spring AI</li><li>Ollama</li><li>WebSockets</li><li>STOMP</li><li>SockJS</li></ul><p>👉 GitHub Repository:<br><a href="https://github.com/hykuBipin/live-cricket-spring-ai">https://github.com/hykuBipin/live-cricket-spring-ai</a></p><h3>🚀 What This Project Does</h3><p>This project simulates a Cricbuzz/Cricinfo-style live score platform where:</p><p>✅ Live scores are pushed instantly<br>✅ AI generates cricket commentary dynamically<br>✅ Frontend updates without refresh<br>✅ Multiple users can receive updates simultaneously<br>✅ Local LLMs run using Ollama</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*bCHjrt91aSIuGKkHXBchEA.jpeg" /></figure><pre>{<br>  &quot;team&quot;:&quot;CSK&quot;,<br>  &quot;runs&quot;:145,<br>  &quot;wickets&quot;:2,<br>  &quot;overs&quot;:&quot;15.0&quot;<br>}</pre><p>Generated AI Commentary:</p><blockquote><em>“Dhoni launches it over long-on! CSK accelerating brilliantly in the death overs.”</em></blockquote><h3>🧠 Tech Stack Used</h3><p>TechnologyPurposeJava 17Backend developmentSpring BootCore application frameworkSpring AIAI integration layerOllamaRunning local LLMsWebSocketsReal-time communicationSTOMPMessaging protocolSockJSBrowser compatibilityMavenBuild managementHTML/CSS/JavaScriptFrontend</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*r_1deU-4vtUGr6R2DBADcg.jpeg" /></figure><p>Traditional REST APIs work like this:</p><pre>Client → Request → Server → Response</pre><p>But live applications need:</p><ul><li>instant updates</li><li>persistent connections</li><li>server push architecture</li></ul><p>Polling repeatedly every few seconds is inefficient.</p><p>WebSockets solve this problem by creating a persistent full-duplex connection between browser and server.</p><h3>🔌 Understanding WebSockets + STOMP</h3><p>One of the biggest learnings from this project was understanding the difference between:</p><ul><li>WebSockets</li><li>STOMP</li><li>SockJS</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*PBnrYem14ocQHVLhpv00_Q.jpeg" /></figure><p>WebSocket creates the persistent connection between frontend and backend.</p><p>Example:</p><pre>const socket = new SockJS(&#39;/ws&#39;);</pre><p>This connects to:</p><pre>/ws</pre><p>But this endpoint is NOT a normal REST API endpoint.</p><p>It is only used for WebSocket handshake and persistent communication.</p><h3>STOMP</h3><p>STOMP is a messaging protocol that runs on top of WebSockets.</p><p>Instead of manually handling raw socket frames, STOMP provides:</p><ul><li>subscriptions</li><li>topics</li><li>broadcasting</li><li>structured messaging</li></ul><p>Frontend subscribes like this:</p><pre>stompClient.subscribe(&#39;/topic/live&#39;, function(message) {<br>   console.log(message.body);<br>});</pre><p>Meaning:</p><blockquote><em>“Whenever backend broadcasts messages to </em><em>/topic/live, deliver them instantly to this client.”</em></blockquote><h3>SockJS</h3><p>SockJS acts as a fallback mechanism for browsers that may not fully support WebSockets.</p><p>It improves compatibility and connection reliability.</p><h3>🏗️ System Architecture</h3><h3>Step-by-Step Flow</h3><h3>1️⃣ REST API receives score updates</h3><pre>POST /score</pre><p>Payload:</p><pre>{<br>  &quot;team&quot;:&quot;CSK&quot;,<br>  &quot;runs&quot;:145,<br>  &quot;wickets&quot;:2,<br>  &quot;overs&quot;:&quot;15.0&quot;<br>}</pre><h3>2️⃣ Spring AI generates commentary</h3><p>The backend sends score details to Spring AI.</p><pre>return chatClient.prompt()<br>        .user(prompt)<br>        .call()<br>        .content();</pre><p>Spring AI simplifies AI integration significantly.</p><p>Without Spring AI, we would need:</p><ul><li>manual HTTP integrations</li><li>API management</li><li>request handling</li><li>response parsing</li></ul><p>Spring AI abstracts all of that cleanly.</p><h3>🤖 Why Ollama?</h3><p>Instead of using paid APIs like OpenAI, I used Ollama to run Llama3 locally.</p><p>Benefits:</p><ul><li>local inference</li><li>privacy</li><li>no API cost</li><li>offline execution</li><li>faster experimentation</li></ul><p>Start Ollama:</p><pre>ollama serve</pre><p>Pull model:</p><pre>ollama pull llama3</pre><h3>🧠 Prompt Engineering</h3><p>Initially, the AI generated very large paragraphs.</p><p>To make commentary more realistic, I optimized the prompt:</p><pre>Generate ONE short professional live cricket commentary line.</pre><pre>Style:<br>- Like Cricbuzz or Cricinfo<br>- Maximum 20 words<br>- Exciting<br>- Realistic</pre><p>This dramatically improved the output quality.</p><h3>📡 Broadcasting Live Updates</h3><p>Once commentary is generated, backend broadcasts updates using:</p><pre>template.convertAndSend(&quot;/topic/live&quot;, response);</pre><p>All connected users instantly receive updates.</p><p>No refresh needed.</p><p>This is how many real-time systems internally work.</p><h3>🖥️ Frontend Real-Time Updates</h3><p>Frontend subscribes to:</p><pre>/topic/live</pre><p>Important:</p><p>/topic/live is NOT a browser URL.</p><p>It is a STOMP subscription topic.</p><p>This was an important concept I learned while building the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NLv5q6TayZyWdqMwb0DJw.png" /></figure><h3>WebSocketConfig</h3><p>Responsible for:</p><ul><li>enabling STOMP</li><li>WebSocket endpoint registration</li><li>broker configuration</li></ul><h3>CommentaryService</h3><p>Responsible for:</p><ul><li>prompt engineering</li><li>AI communication</li><li>commentary generation</li></ul><h3>ScoreController</h3><p>Responsible for:</p><ul><li>receiving scores</li><li>invoking AI</li><li>broadcasting events</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3n1vfueYpkPsBW44IRobw.png" /></figure><p>OUTPUT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcXVtUQ7MVbESH5_1Pyo_A.png" /></figure><p>✅ Event-driven architecture<br>✅ Real-time communication<br>✅ WebSocket internals<br>✅ STOMP protocol<br>✅ Spring AI integration<br>✅ Local LLM execution<br>✅ Prompt engineering<br>✅ Backend broadcasting systems</p><h3>🔥 Future Enhancements</h3><p>Planning to add:</p><ul><li>live scorecards</li><li>match analytics</li><li>AI win prediction</li><li>React frontend</li><li>Docker deployment</li><li>Kubernetes support</li><li>voice commentary</li><li>streaming AI responses</li></ul><h3>👨‍💻 GitHub Repository</h3><p><a href="https://github.com/hykuBipin/live-cricket-spring-ai">https://github.com/hykuBipin/live-cricket-spring-ai</a></p><h3>🎯 Final Thoughts</h3><p>This project was a great hands-on experience in combining:</p><ul><li>AI</li><li>real-time systems</li><li>event-driven architecture</li><li>Spring ecosystem</li></ul><p>Building practical systems like this helps understand how modern scalable applications work internally.</p><p>If you are exploring:</p><ul><li>Spring AI</li><li>WebSockets</li><li>Generative AI</li><li>Real-time architecture</li></ul><p>I highly recommend building something similar.</p><p>Thanks for reading 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fafc2a1d26b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Ollama: Running Language Models in Docker and Python]]></title>
            <link>https://medium.com/@aziza.bibin/getting-started-with-ollama-running-language-models-in-docker-and-python-5dda8335d85f?source=rss-75fc5c88de76------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dda8335d85f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-development]]></category>
            <dc:creator><![CDATA[Bipin Nair Gopalakrishnan]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 19:32:38 GMT</pubDate>
            <atom:updated>2025-07-13T19:32:38.039Z</atom:updated>
            <content:encoded><![CDATA[<p>The AI revolution is well underway, and running powerful GPT-like models locally is becoming more accessible than ever. In this guide, I’ll walk you through setting up a local GPT environment using Ollama, the Gemma model, Docker, and Python — enabling you to run and interact with advanced language models right on your machine.</p><h3>Step 1: Install Docker</h3><p>Docker is the backbone of this setup, providing containerization for Ollama and Gemma.</p><h3>Linux</h3><p>Open your terminal and run:</p><pre>sudo apt update &amp;&amp; sudo apt upgrade -y<br>sudo apt install docker.io -y<br>sudo systemctl start docker<br>sudo systemctl enable docker</pre><h3>Windows/macOS</h3><p>Download and install <a href="https://www.docker.com/products/docker-desktop">Docker Desktop</a> and follow the installation instructions.</p><p>Make sure Docker is running before moving on.</p><h3>Step 2: Run Ollama in Docker</h3><p>Ollama is a lightweight runtime that lets you run Gemma models locally inside a Docker container.</p><p>Run this command to start Ollama:</p><pre>docker run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama ollama/ollama</pre><ul><li>-d runs the container in the background.</li><li>-p 11434:11434 exposes port 11434 for API access.</li><li>-v ollama:/root/.ollama persists your model data.</li></ul><h3>Step 3: Download the Gemma Model</h3><p>Access the running Ollama container’s shell:</p><pre>docker exec -it ollama /bin/bash</pre><p>Inside the container, pull the Gemma model you want. For example, to pull the 4-billion parameter version.</p><pre>ollama pull gemma3:4b</pre><p>You can replace 4b with other sizes like 1b, 12b, or 27b based on your hardware capabilities.</p><h3>Step 4: Verify the Model</h3><p>Check your installed models with:</p><pre>ollama list</pre><p>You should see your Gemma model listed here.</p><h3>Step 5: Set Up Your Python Environment</h3><p>Back on your host machine (outside the container), create a project folder, e.g., local-gpt-app.</p><p>Create and activate a Python virtual environment:</p><pre>python3 -m venv venv<br>source venv/bin/activate  # On Windows: venv\Scripts\activate</pre><p>Install the requests library to interact with the Ollama API:</p><pre>pip install requests</pre><h3>Step 6: Write app.py to Interact with Ollama</h3><p>Create a file named app.py in your project folder with the following code:</p><pre>import streamlit as st</pre><pre>import requests</pre><pre>import json</pre><pre>st.title(&quot;Dost - Local Chatbot with Gemma + Ollama&quot;)</pre><pre>prompt = st.text_area(&quot;Enter your prompt:&quot;)</pre><pre>if st.button(&quot;Send&quot;):</pre><pre>with st.spinner(&quot;Generating response...&quot;):</pre><pre>response = requests.post(</pre><pre>&quot;http://localhost:11434/api/generate&quot;,</pre><pre>json={</pre><pre>&quot;model&quot;: &quot;gemma:2b&quot;,</pre><pre>&quot;prompt&quot;: prompt,</pre><pre>&quot;stream&quot;: True</pre><pre>},</pre><pre>stream=True</pre><pre>)</pre><pre>output = &quot;&quot;</pre><pre>placeholder = st.empty()  # placeholder to update the response live</pre><pre>for line in response.iter_lines():</pre><pre>if line:</pre><pre>try:</pre><pre>data = json.loads(line.decode(&quot;utf-8&quot;))</pre><pre>output += data.get(&quot;response&quot;, &quot;&quot;)</pre><pre>placeholder.markdown(output)  # update output in real time</pre><pre>except json.JSONDecodeError as e:</pre><pre>st.error(f&quot;Failed to decode: {e}&quot;)</pre><pre>st.success(&quot;Response generated successfully!&quot;)</pre><h3>Step 7: Run Your Python App</h3><p>Ensure your Docker container is running, then from your project directory run:</p><pre>python app.py</pre><p>You can now chat with your local GPT model directly from the terminal!</p><p><strong>Source Code:</strong><br>You can find the complete source code and related files for this project on <strong>GitHub:</strong><br><a href="http://git@github.com:hykuBipin/Ai_Agent_build.git">git@github.com:hykuBipin/Ai_Agent_build.git</a></p><p>This clearly attributes your repository and allows readers to access your code directly. You may also consider adding a clickable link version for easier access:</p><p>GitHub Repository: <a href="https://github.com/hykuBipin/Ai_Agent_build">Ai_Agent_build</a></p><h3>SUMMARY:</h3><pre>| Step                  | Command / Action                                                    | Notes                                                       |<br>|-----------------------|-------------------------------------------------------------------|-------------------------------------------------------------|<br>| **Install Docker (Linux)** | `sudo apt install docker.io -y`                                  | For Debian/Ubuntu systems; or install Docker Desktop on Windows/Mac |<br>| **Run Ollama container**   | `docker run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama ollama/ollama` | Runs Ollama container in detached mode, maps port 11434, mounts persistent volume |<br>| **Enter Ollama container** | `docker exec -it ollama /bin/bash`                               | Access the container shell to run commands inside           |<br>| **Pull Ollama model**      | `ollama pull gemma3:4b` (run inside container shell)             | Downloads the specified model into Ollama                    |<br>| **Set up Python venv**     | `python3 -m venv venv &amp;&amp; source venv/bin/activate`               | Creates and activates a Python virtual environment           |<br>| **Install Python deps**    | `pip install requests`                                            | Installs required Python packages                            |<br>| **Write and run app.py**   | Write your Python code (e.g., using Ollama API), then run: `python app.py` | Use the Ollama API to interact with models                   |Docker Official Site</pre><ul><li><a href="https://requests.readthedocs.io/en/latest/">Python Requests Library</a></li><li><a href="https://github.com/ollama/ollama">Ollama GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dda8335d85f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bloom Filter]]></title>
            <link>https://medium.com/@aziza.bibin/bloom-filter-f120d6448b98?source=rss-75fc5c88de76------2</link>
            <guid isPermaLink="false">https://medium.com/p/f120d6448b98</guid>
            <category><![CDATA[bloom-filter]]></category>
            <dc:creator><![CDATA[Bipin Nair Gopalakrishnan]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 17:12:37 GMT</pubDate>
            <atom:updated>2025-07-13T17:12:37.333Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What</strong></p><p>A Bloom filter is a <strong>space efficient data structure</strong> used to test whether an element is present in a set. It can tell if an element is definitely not (no false negative) in the set or might be in the set (some chances of false positives).</p><p>The Bloom filter uses multiple hash functions to map each element to a bit array.</p><blockquote>To check for membership, the same hash functions are applied to the query element, and if all corresponding bits are set to 1, it suggests that the element may be in the set. However, <strong>false positives are possible</strong>, but <strong>false negatives are not</strong>.</blockquote><figure><img alt="Highlevel design of Bloomfilter Impementation" src="https://cdn-images-1.medium.com/max/1024/1*YIzfxWARtDBpw4bKCROZxg.png" /></figure><p><strong>Why</strong></p><p>Bloom filters are ingenious data structures known for their space-efficient characteristics. They accomplish this by making a few trade-offs and using probabilistic techniques. Here’s how Bloom filters save space in data storage:</p><p><strong>Compact Representation</strong></p><p>Bloom filters use a compact representation of data compared to other data structures like hash tables or binary search trees. Instead of storing the actual elements, a Bloom filter employs a fixed-size bit array. Each element is mapped to multiple positions (bits) in this array through hash functions. As a result, the storage requirements are proportional to the size of the bit array, which can be significantly smaller than storing the elements themselves.</p><p><strong>Elimination of Redundant Data</strong></p><p>Traditional data structures often store all the elements individually. In contrast, a Bloom filter doesn’t store the elements themselves. By using multiple hash functions, it efficiently encodes the presence or absence of elements in a highly compressed form. This eliminates the need to store redundant data, which can be especially advantageous when dealing with large datasets.</p><p><strong>Constant Size</strong></p><p>The space occupied by a Bloom filter is not directly related to the number of elements it contains. Instead, it depends on parameters like the desired false positive probability and the expected number of insertions. This means that regardless of the size of the dataset, the Bloom filter maintains a relatively constant size, making it suitable for memory-constrained applications.</p><p><strong>Probabilistic Nature</strong></p><p>One of the trade-offs made by Bloom filters is their probabilistic nature. They allow for a small probability of false positives, which means that in some cases, the filter might incorrectly suggest an element is in the set when it’s not. This trade-off enables Bloom filters to achieve their space efficiency, as they don’t need to maintain complete and precise information about the elements.</p><p><strong>Scalability</strong></p><p>Bloom filters can scale effectively for large datasets without a significant increase in memory usage. The size of the bit array and the number of hash functions can be adjusted to balance memory consumption and false positive rates.</p><p><strong>Parallelism</strong></p><p>Due to the independence of hash functions and bit positions in the array, Bloom filters allow for efficient parallel processing. Multiple membership tests can be performed concurrently, making them suitable for multi-threaded or distributed systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IluZ4m9or5LTNGS3SHditw.png" /></figure><p><strong>Where</strong></p><p><strong>Bloom filters</strong> are an ingenious data structure for efficient set membership testing, offering space-efficient solutions in various applications.</p><p><strong>Bloom filters</strong> save space in data storage by using a compact representation, eliminating redundant data, maintaining constant size, minimising overhead, and leveraging their probabilistic nature. While they do have limitations, such as the possibility of false positives.</p><p>Understanding their limitations and use cases is essential for harnessing their power effectively. When memory efficiency and fast querying are essential, Bloom filters are a valuable tool in a programmer’s toolbox.</p><p><strong>Caching</strong></p><p>Web browsers use Bloom filters to quickly determine if a website is in a local cache, reducing network requests.</p><p><strong>Spell Checkers</strong></p><p>Bloom filters can help identify whether a word exists in a dictionary, improving the speed of spell checkers.</p><p><strong>Network Routers</strong></p><p>Routers use Bloom filters to efficiently decide whether an IP address is in a blacklist.</p><p><strong>Duplicate Elimination</strong></p><p>In distributed systems, Bloom filters can be employed to eliminate duplicate data transmission.</p><p><strong>Indexing</strong></p><p>When a document is inserted or updated in the database, its key or ID is hashed using one or more hash functions. These hash values are then used to determine the positions in a Bloom filter. Bits at these positions in the Bloom filter are set to 1. For example, consider a NoSQL database that uses a Bloom filter in its index. When a new document with the key “doc123” is added to the index, the Bloom filter is updated based on the hash values of “doc123.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*npG6Nnjfsrlkp0l65FDsdg.png" /></figure><p><strong>How</strong></p><p><strong>Initialization</strong></p><p>A Bloom filter begins as an array of bits, all initially set to 0.</p><p><strong>Adding Elements</strong></p><p>To add an element to the filter, it undergoes multiple hash functions that generate a set of bit positions. These positions are then set to 1 in the filter. Each hash function takes the element as input and produces an output, typically a numeric value. This output is then mapped to positions in the bit array using modulo arithmetic. For example, if you have a Bloom filter with a bit array of size m, and one of the hash functions produces an output of h, you can map it to a position in the bit array using h % m.</p><p><strong>Membership Query</strong></p><p>To check if an element is a member of the set, the same hash functions are applied to it. If all corresponding bits in the filter are set to 1, the element is considered a possible member. If any bit is 0, it is definitely not in the set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*RHlXvsGoDxxBCa4DY-dDJQ.png" /></figure><p><strong>Create InvoiceBloomFilter class</strong></p><p>In this implementation, named `InvoiceBloomFilter` class, uses a `BitSet` of size 1000 as the underlying data structure. A `BitSet` is an array-like structure that holds bits instead of traditional data types, and it’s used here to store the Bloom filter. Additionally, we have an array `hashFunctions` containing three integers (3, 5, 7). These numbers act as seeds for our hash functions, enabling us to create multiple hashes for each invoice number.</p><p>The `simpleHash` function is a private method that calculates a hash value for a given invoice number and seed. It iteratively constructs the hash by multiplying the current hash by the seed and adding the character’s ASCII value, finally taking the modulo of 1000 to ensure it fits within the `BitSet`.</p><p>The `addInvoice` method allows us to add an invoice number to the Bloom filter. It does this by generating a hash for the invoice number with each seed in `hashFunctions`, then setting the corresponding index in the `BitSet` to true.</p><p>Finally, the `checkInvoice` method allows us to check whether an invoice number might be in the set. It uses the same hash functions to get the indices in the `BitSet`. If any of these indices is false, it concludes that the invoice number is definitely not in the set. If all are true, the invoice number might be in the set, acknowledging that there could be a false positive.</p><pre>package com.sample.poc;<br>import java.util.BitSet;<br>public class InvoiceBloomFilter {<br>private BitSet bitSet = new BitSet(1000); // Initialize Bloom Filter size<br>private int[] hashFunctions = {3, 5, 7}; // Random numbers for Hashing<br>private int simpleHash(String s, int seed) {<br>int hash = 0;<br>for (int i = 0; i &lt; s.length(); i++) {<br>hash = (hash * seed) + s.charAt(i);<br>hash %= 1000;<br>}<br>return Math.abs(hash);<br>}<br>public void addInvoice(String invoiceNumber) {<br>for (int function : hashFunctions) {<br>int hash = simpleHash(invoiceNumber, function);<br>bitSet.set(hash, true);<br>}<br>}<br>public boolean checkInvoice(String invoiceNumber) {<br>for (int function : hashFunctions) {<br>int hash = simpleHash(invoiceNumber, function);<br>if (!bitSet.get(hash)) {<br>return false; // Invoice is definitely not processed<br>}<br>}<br>return true; // Invoice might have been processed<br>}<br>}</pre><p><strong>Create Main class</strong></p><pre>package com.sample.poc;<br>public class Main {<br>public static void main(String[] args) {<br>InvoiceBloomFilter invoiceBloomFilter = new InvoiceBloomFilter();<br>// Add invoices to Bloom Filter<br>invoiceBloomFilter.addInvoice(&quot;INV001&quot;);<br>invoiceBloomFilter.addInvoice(&quot;INV002&quot;);<br>invoiceBloomFilter.addInvoice(&quot;INV005&quot;);<br>invoiceBloomFilter.addInvoice(&quot;INV008&quot;);<br>invoiceBloomFilter.addInvoice(&quot;INV009&quot;);<br>// Check if invoices are in Bloom Filter<br>System.out.println(invoiceBloomFilter.checkInvoice(&quot;INV001&quot;)); // Output: true<br>System.out.println(invoiceBloomFilter.checkInvoice(&quot;INV003&quot;)); // Output: false<br>System.out.println(invoiceBloomFilter.checkInvoice(&quot;INV007&quot;)); // Output: false<br>System.out.println(invoiceBloomFilter.checkInvoice(&quot;INV008&quot;)); // Output: true<br>}<br>}</pre><p>In this example, the Bloom filter uses an array of boolean values (`bitArray`). When a new element is added to the filter, the element is hashed `numHashes` times, and the corresponding positions in the `bitArray` are set to true. To check if an element might be in the set, the filter hashes the element `numHashes` times and checks the corresponding positions in the `bitArray`.</p><p>If any of the positions is false, then the element is definitely not in the set. If all positions are true, then the element might be in the set. This is a very basic implementation and doesn’t include any optimization techniques.</p><p>The `getHash` method simply uses the built-in `hashCode` method and adds the hash number to create different hashes for the same element. This implementation can easily result in false positives, meaning that it might say that an element is in the set when it is not. However, it will never result in false negatives, meaning that if it says that an element is not in the set, then it is definitely not in the set. That’s why it’s called a probabilistic data structure.</p><p><strong>Sample Result</strong></p><p><strong>Optimization Technique</strong></p><p>Below are some of the optimization techniques for Bloom Filters</p><p><strong>Optimal Sizing</strong></p><p>Choosing appropriate parameters such as the size of the bit array (m) and the number of hash functions (k) is crucial for balancing memory usage and false positive rate.Optimal sizing involves considering the expected number of elements in the set and the acceptable false positive probability, ensuring efficient use of memory while maintaining acceptable accuracy.</p><p><strong>Hash Function Selection</strong></p><p>Selecting high-quality hash functions that produce well-distributed hash values helps minimize collisions and ensure uniform bit distribution in the array.Cryptographically secure hash functions such as SHA-256 or MurmurHash are commonly used for their strong properties and efficient computation.</p><p><strong>Double Hashing</strong></p><p>Instead of using a single hash function, employing multiple independent hash functions (double hashing) can further reduce the likelihood of collisions and improve the filter’s accuracy.Double hashing involves applying each element to multiple hash functions to generate multiple hash values, which are then used to set corresponding bits in the array.</p><p><strong>Partitioning</strong></p><p>Partitioning the Bloom Filter into multiple smaller filters can improve scalability and reduce the impact of false positives, especially in dynamic datasets.By dividing the dataset into partitions and assigning a separate Bloom Filter to each partition, the overall false positive rate can be controlled more effectively, and memory usage can be distributed more evenly.</p><p><strong>Counting Bloom Filters</strong></p><p>Counting Bloom Filters extend the basic Bloom Filter by allowing multiple occurrences of an element to be counted rather than just presence or absence.This enables support for deletion operations and more accurate representation of frequency information. However, counting Bloom Filters require additional memory overhead to store counters for each hash function.</p><p><strong>Important Considerations</strong></p><ol><li><strong>False Positives:</strong> The probabilistic nature of Bloom filters means there can be false positives. If all bits are set to 1 for a query, it suggests membership, but the element might not be in the set.</li><li><strong>No Deletion:</strong> Bloom filters do not support element deletion. Removing an element is not straightforward as it could affect other elements.</li><li><strong>Hash Functions:</strong> The quality of hash functions used is crucial. Poor hash functions can increase false positives.</li></ol><p><strong>Advantages of Bloom Filters’ functions</strong></p><ol><li><strong>Space Efficiency:</strong> Bloom filters use relatively small amounts of memory compared to other data structures like hash tables, making them ideal for applications with limited memory.</li><li><strong>Fast Membership Testing:</strong> Checking membership in a Bloom filter is extremely fast. The number of hash functions and size of the bit array can be adjusted to balance space and accuracy.</li><li><strong>Parallelism:</strong> Multiple membership tests can be performed in parallel since each query element’s hash positions are independent.</li><li><strong>No False Negatives:</strong> Bloom filters never produce false negatives. If the filter says an element is not present, it’s definitely not in the set.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*pr1xQSkWl3MITMUnhvMA1A.jpeg" /></figure><p><strong>References</strong></p><p><a href="https://www.geeksforgeeks.org/bloom-filters-in-system-design/">https://www.geeksforgeeks.org/bloom-filters-in-system-design/</a><br><a href="https://brilliant.org/wiki/bloom-filter/">https://brilliant.org/wiki/bloom-filter/</a><br><a href="https://systemdesign.one/bloom-filters-explained/">https://systemdesign.one/bloom-filters-explained/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f120d6448b98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Counting Bloom Filter[CBF]:]]></title>
            <link>https://medium.com/@aziza.bibin/counting-bloom-filter-cbf-eb8378b93b95?source=rss-75fc5c88de76------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb8378b93b95</guid>
            <category><![CDATA[counting-bloom-filter]]></category>
            <category><![CDATA[bloom-filter]]></category>
            <dc:creator><![CDATA[Bipin Nair Gopalakrishnan]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 08:42:53 GMT</pubDate>
            <atom:updated>2024-10-13T10:20:04.073Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview:</h3><p>As developers, we are constantly on the lookout for data structures and algorithms that can enhance the speed and efficiency of our applications. One such powerful tool is the <strong>Counting Bloom Filter</strong>. <strong>Counting Bloom Filter</strong> is a <strong>probabilistic data structure [</strong><a href="https://confluence.walmart.com/pages/createpage.action?spaceKey=~b0g056x&amp;title=PDS&amp;linkCreation=true&amp;fromPageId=2433088217"><strong>PDS</strong></a><strong>]</strong> used for testing whether an element is a member of a set. It is a variation of the standard Bloom filter that allows elements to be added and removed from the set. This will be helpful to check whether an element is present or not in probable among very large data. <strong>Ex:</strong> <strong>Evaluating if a user’s login ID is new or already available with lookup of existing users in Gmail DB and also the number of occurences the user logged in etc…</strong></p><p>Counting Bloom Filters are used when there’s a need for a memory-efficient structure that can quickly check whether an element is in a set. They’re especially useful when dealing with large data sets because they significantly reduce the need for disk or network I/O operations. The counting aspect of the Bloom filter allows for the implementation of delete operations, which is not possible in a traditional Bloom filter.</p><p>Counting Bloom Filters are incredibly helpful for managing large datasets efficiently due to their memory-efficiency and quick search capabilities. They can significantly minimize the need for disk or network I/O operations, leading to improved performance. The ‘counting’ feature of this data structure allows for removal of elements, which isn’t possible with a standard Bloom filter. This makes it useful in scenarios where the dataset is dynamic and elements need to be deleted over time.</p><p>Counting Bloom Filters use the same functions of Bloom Filters, but the main difference is that in Counting Bloom Filters, we add counters in every slot instead of (0 or 1). That means we can delete elements from the data structure which is not possible in Bloom Filters.</p><h3>Why ?</h3><p>A Counting Bloom filter offers several advantages, making it a good choice in certain scenarios:</p><h4>Space Efficiency</h4><p>Counting Bloom filters are space-efficient data structures, making them suitable for use in systems with space constraints.</p><h4>Deletion Capability</h4><p>Unlike standard Bloom filters, Counting Bloom filters allow for deletions, making them useful in dynamic scenarios where items need to be added and removed frequently.</p><h4>Fast Operations</h4><p>Counting Bloom filters offer constant time complexity for operations like insertions, deletions, and lookups, which is particularly advantageous when dealing with large datasets.</p><h4>Network Friendly</h4><p>They are network-friendly as they reduce the need for data transfers in distributed systems. Instead of transmitting a large set of data, one can send a Counting Bloom filter representation.</p><h4>Handling Duplicate Entries</h4><p>Counting Bloom filters can handle duplicate entries, making them ideal for counting distinct items in a stream.</p><h4>Tolerating Errors</h4><p>They can tolerate false positives, meaning that they might sometimes indicate that an item is in the set when it’s not. This can be acceptable in certain scenarios where a small error rate is acceptable for the benefit of significantly reduced memory usage.</p><p>However, one should be aware that Counting Bloom Filters can have false positives (indicating an element is present when it is not) and they do not store the actual elements, so they cannot be used to retrieve the original data.</p><figure><img alt="Eg: picture represents how does counting bloom filter maintains the count" src="https://cdn-images-1.medium.com/max/344/0*2x8Ywc_fk8FZ0q_S" /></figure><h3>Where ?</h3><h4>Web Caching</h4><p>To keep track of web pages that are in cache, and remove them when they are no longer needed or when the cache becomes full.</p><h4>Network Routing</h4><p>In a network router, it can be used to keep track of packets or routes that have been used recently and remove them when they become irrelevant.</p><h4>Internet Traffic Management</h4><p>Counting Bloom filters can be used to identify malicious IP addresses and remove them from the network.</p><h4>Database Systems</h4><p>To manage a list of transactions, and remove them once they have been processed.</p><h4>Big Data</h4><p>In a distributed system, Counting Bloom Filters can be used to efficiently check the existence of an element without actually moving the data.</p><h3>How ?</h3><p>The Counting Bloom filter allows approximating the number of times each element has been seen in the filter by incrementing the corresponding counter every time the element is added. The associated CountingBloomFilter data structure contains a bit array and the array of counters of length m, all initialized to zeros. When a new element is inserted into CountingBloomFilter, first compute its corresponding bit-positions, then for each position, we increment the associated counter, These are some basic ideas to code in any preferred language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*nFNOScfoHMFJw0YA" /></figure><p>In Java, you can use the Google Guava library to implement Counting Bloom Filter.<br>Here is a basic example:</p><p><strong>Add Spring apache commons dependencies in pom.xml:</strong></p><p>&lt;dependency&gt;<br> &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;<br> &lt;artifactId&gt;commons-collections4&lt;/artifactId&gt;<br> &lt;version&gt;4.4&lt;/version&gt;<br>&lt;/dependency&gt;</p><h4>Create CountingBloomFilter class</h4><p>The CountingBloomFilter in this code is a bit of a misnomer, as it actually implements a basic Bloom filter. A true counting Bloom filter would allow for the removal of elements and would use an array of counters instead of a BitSet. Each time an element is added, the counters at each of the hash function indices are incremented, and when an element is removed, these counters are decremented.</p><p>The `contains(String value)` method checks whether a string might be in the Bloom filter. It hashes the string with each hash function in `func` and checks whether the corresponding bit in `bits` is `true`. If any bit is not set (`false`), it means the string definitely isn’t in the set. If all bits are set (`true`), the string might be in the set, but it could also be a false positive.</p><p>package org.example;<br> <br>import java.util.BitSet;<br> <br>public class CountingBloomFilter {<br> <br> private static final int DEFAULT_SIZE = 2 &lt;&lt; 24;<br> private static final int[] seeds = new int[]{7, 11, 13, 31, 37, 61};<br> private BitSet bits = new BitSet(DEFAULT_SIZE);<br> private SimpleHash[] func = new SimpleHash[seeds.length];<br> <br> public CountingBloomFilter() {<br> for (int i = 0; i &lt; seeds.length; i++) {<br> func[i] = new SimpleHash(DEFAULT_SIZE, seeds[i]);<br> }<br> }<br> <br> public void add(String value) {<br> for (SimpleHash f : func) {<br> bits.set(f.hash(value), true);<br> }<br> }<br> <br> public boolean contains(String value) {<br> if (value == null) {<br> return false;<br> }<br> boolean ret = true;<br> for (SimpleHash f : func) {<br> ret = ret &amp;&amp; bits.get(f.hash(value));<br> }<br> return ret;<br> }<br>}</p><h4>Create SimpleHash class</h4><p>The code defines a simple custom hash function implementation in Java.It performs a bitwise XOR operation (`^`) between `h` and `h` right-shifted by 16 bits (`h &gt;&gt;&gt; 16`). Bitwise operation on the value of hash code helps in distributing the higher bits into lower ones, which can be beneficial when the hash table size is less than the max value of integer and reduces the risk of collisions in the hash function.</p><p>package org.example;<br> <br>public class SimpleHash {<br> <br> private int cap;<br> private int seed;<br> <br> public SimpleHash(int cap, int seed) {<br> this.cap = cap;<br> this.seed = seed;<br> }<br> <br> public int hash(Object value) {<br> int h;<br> return (value == null) ? 0 : Math.abs(seed * (cap - 1) &amp; ((h = value.hashCode()) ^ (h &gt;&gt;&gt; 16)));<br> }<br>}</p><h4>Sample Result</h4><h4>Important Considerations</h4><p><strong>1) False Positives:</strong><br>Counting Bloom filters can return false positives, indicating that an element might be present when it actually isn’t. The probability of false positives can be controlled by adjusting the filter’s parameters.</p><p><strong>2) Counting Limitations:</strong><br>The approximateCount() method is an approximation, and its accuracy can decrease as the count increases or the filter becomes saturated.</p><p><strong>3) Library Choice:</strong><br>The example uses the Apache Commons Collections library, but there are other Java libraries available for implementing Counting Bloom filters, such as Guava.</p><h4>Counting Bloom Filters’ functions</h4><p><strong>1) Initialization — </strong>This is the first step in using a Counting Bloom Filter. It involves creating an array of a certain size (all initially set to 0), and deciding on the number of hash functions to be used. The number of hash functions and the size of the array are related to the desired false positive rate and the expected number of elements to be added.<br><strong> 2) Hashing — </strong>This involves using multiple hash functions on the input data. Each hash function will give an index into the array. The idea behind using multiple hash functions is to distribute data evenly throughout the filter.<br><strong> 3) Adding — </strong>When an element is added to the Counting Bloom Filter, all the hash functions are computed for that element, and for each resulting hash value, the corresponding element in the array is incremented by 1.<br><strong> 4) Remove — </strong>Unlike standard Bloom Filters, Counting Bloom Filters allow for removal of elements. To remove an element, compute all the hash functions for that element, and for each resulting hash value, decrement the corresponding array element by 1. It’s important to note, however, that if you remove an element that was never added, it could lead to false negatives.<br><strong> 5) Lookup — </strong>check whether an element is in the filter, compute all the hash functions for that element, and check the corresponding array values. If all array values are greater than 0, then the element might be in the set. If any value is 0, then the element is definitely not in the set. It’s important to note that Bloom Filters can have false positives but not false negatives. In other words, it may say an element is present when it’s not (false positive), but it will never say an element is absent when it’s actually present (false negative). In the case of Counting Bloom Filters, false negatives can occur if an element was removed that was never added.</p><h3>References:</h3><p><a href="https://www.geeksforgeeks.org/counting-bloom-filters-introduction-and-implementation/">https://www.geeksforgeeks.org/counting-bloom-filters-introduction-and-implementation/</a><br><a href="https://medium.com/analytics-vidhya/cbfs-44c66b1b4a78">https://medium.com/analytics-vidhya/cbfs-44c66b1b4a78</a><br><a href="https://www.baeldung.com/guava-bloom-filter">https://www.baeldung.com/guava-bloom-filter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb8378b93b95" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>