<?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 Sarthak Bhatkar on Medium]]></title>
        <description><![CDATA[Stories by Sarthak Bhatkar on Medium]]></description>
        <link>https://medium.com/@sarthakbhatkar?source=rss-ae83a5b3c660------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vOV3q-DjW7ttC574</url>
            <title>Stories by Sarthak Bhatkar on Medium</title>
            <link>https://medium.com/@sarthakbhatkar?source=rss-ae83a5b3c660------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:54:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sarthakbhatkar/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[Why I Built an Async-First, Enterprise-Compliant, Multi-Backend Python Caching Library From Scratch]]></title>
            <link>https://medium.com/@sarthakbhatkar/why-i-built-an-async-first-enterprise-compliant-multi-backend-python-caching-library-from-scratch-5e1c725fc68d?source=rss-ae83a5b3c660------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e1c725fc68d</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sarthak Bhatkar]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 16:00:46 GMT</pubDate>
            <atom:updated>2026-03-22T16:00:46.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7AW3BypwJkyGXNIJp4GqRQ.png" /><figcaption>cachestack installation</figcaption></figure><p>I didn’t plan to build a caching library. Nobody wakes up and thinks “I should spend three weeks writing something that already exists.” But here we are.</p><p>It started with a BlackDuck scan.</p><h3>A BlackDuck flag and a missing afternoon</h3><p>Our pipeline flagged diskcache. Not for a CVE. Not for anything in the actual code. The issue was that the SPDX license identifier in its PyPI metadata didn&#39;t line up cleanly with what our enterprise scanner expected. That was enough. Legal got involved. The library had to go.</p><p>So I did the sensible thing first: I looked for a replacement.</p><p>I spent a full day evaluating options. dogpile.cache is mature but it&#39;s sync-first and bolting async onto it felt wrong for a codebase that had fully moved to asyncio. aiocache is async-native and reasonably designed but it pulls in more than I wanted and the backends have enough rough edges that I&#39;d essentially be wrapping it anyway. cashews has an interesting API but it&#39;s opinionated in ways that didn&#39;t fit. cachelib is Flask-ecosystem, sync only, not a fit.</p><p>None of them hit what I actually needed: async-first, multi-backend, and clean enough to pass enterprise security scans without arguments.</p><p>So I opened a new folder and typed touch pyproject.toml.</p><p>This ended up becoming a production-grade caching layer with async support, tiered backends, and built-in stampede protection. Something I couldn’t find in existing libraries without compromises.</p><h3>But why not just use Redis directly?</h3><p>Fair question. Most people ask it.</p><p>Redis is great. But “just use Redis” assumes things that aren’t always true in practice:</p><p><strong>Infrastructure cost.</strong> In local development, a Redis dependency means every developer on the team needs a running Redis instance. That’s a Docker container, a config file, a port conflict, and a “it works on my machine” waiting to happen. A file-based or in-memory fallback for local dev actually saves time.</p><p><strong>Enterprise compliance.</strong> Adding any networked service to a production system inside a bank or financial institution involves security reviews, network segmentation approvals, and sometimes months of procurement. An in-process memory cache has none of that overhead.</p><p><strong>Multi-layer control.</strong> Serving hot data from memory, warm data from Redis, and cold data from Postgres is a pattern that makes sense at scale. Managing that manually every time is repetitive and error-prone. It should be a library feature.</p><p><strong>Compliance surface.</strong> Redis has no compliance issues. But every third-party dependency does. I wanted one caching library with a clean, audited dependency graph instead of three separate libraries duct-taped together.</p><h3>What I actually wanted to build</h3><p>Before writing any implementation I wrote down the constraints. Habit I picked up after shipping things that worked but were annoying to maintain.</p><p>The list was short:</p><ul><li>Same get, set, delete API regardless of which backend you&#39;re talking to</li><li>Every method is a coroutine by default, sync support is a thin wrapper</li><li>Zero mandatory dependencies, backends are optional extras</li><li>MIT or Apache 2.0 license with a proper SPDX identifier, every dependency audited for compliance</li><li>Tiered caching as a first-class feature, not an afterthought</li></ul><p>That last one was important. Tiered caching (L1 memory, L2 Redis, L3 Postgres) is a pattern I’d implemented manually three times across different projects. It deserved to live in a library.</p><p>A note on async-first: most caching libraries in Python are sync-first. In an asyncio service, that means threadpools, blocking I/O, or awkward wrappers. All of which defeat the purpose of an event loop. If you’re building with FastAPI or any modern async Python stack, you feel this immediately. Every await you can&#39;t use is friction you didn&#39;t sign up for.</p><h3>How it’s built</h3><p>The whole thing is built around a BaseCache ABC. Eight async methods. Every backend implements them.</p><pre>class BaseCache(ABC):<br>    async def get(self, key: str) -&gt; Optional[Any]: ...<br>    async def set(self, key: str, value: Any, ttl: Optional[int] = None) -&gt; None: ...<br>    async def delete(self, key: str) -&gt; None: ...<br>    async def exists(self, key: str) -&gt; bool: ...<br>    async def clear(self) -&gt; None: ...<br>    async def get_many(self, keys: List[str]) -&gt; Dict[str, Any]: ...<br>    async def set_many(self, mapping: Dict[str, Any], ttl: Optional[int] = None) -&gt; None: ...<br>    async def delete_many(self, keys: List[str]) -&gt; None: ...</pre><p>Once this contract existed, every backend became an isolated problem. The memory backend uses cachetools for LRU/LFU/TTL. Redis wraps redis.asyncio. Postgres uses asyncpg with a connection pool and creates its own schema on first use. Nothing bleeds into anything else.</p><p>The dependency audit for each optional extra:</p><ul><li>cachetools: MIT</li><li>redis-py: MIT</li><li>asyncpg: Apache 2.0</li><li>aiomcache: MIT</li><li>msgpack: Apache 2.0</li></ul><p>No GPL anywhere in the graph. BlackDuck clean.</p><p>The tiered read path looks like this:</p><pre>Incoming request<br>      |<br>      v<br> [L1 Memory]  &lt;-- check first, fastest<br>      |<br>    miss<br>      |<br>      v<br>  [L2 Redis]  &lt;-- check second<br>      |<br>    miss<br>      |<br>      v<br>[L3 Postgres] &lt;-- source of truth<br>      |<br>     hit<br>      |<br>      v<br> Backfill L2, then L1<br>      |<br>      v<br> Return value</pre><p>On a cache hit at any layer, the value is backfilled into every faster layer above it. Next request hits L1 and never goes further.</p><h3>Stampede protection: the engineering I’m proudest of</h3><p>TieredCache is where the interesting engineering happened.</p><p>The basic read path above is simple. What’s not simple is what happens when a key expires and 50 requests arrive at the same millisecond. All of them miss L1. All of them miss L2. All of them go to Postgres simultaneously. You’ve just turned a cache miss into a database storm. Cache stampede. Without protection, your cache turns into a multiplier on database load instead of a reducer.</p><p>Without protection:</p><pre>Key expires<br>    |<br>    v<br>50 concurrent requests<br>    |<br>    v<br>50 L1 misses<br>50 L2 misses<br>50 Postgres queries  &lt;-- your DB just got hit 50 times for one key</pre><p>The fix is to let exactly one coroutine fetch from the database while the rest wait:</p><pre>async def get(self, key: str) -&gt; Optional[Any]:<br>    if key not in self._locks:<br>        self._locks[key] = asyncio.Lock()</pre><pre>    async with self._locks[key]:<br>        # Re-check L1 inside the lock.<br>        # If another coroutine already fetched and backfilled, we&#39;re done.<br>        value = await self.backends[0].get(key)<br>        if value is not None:<br>            return value<br>        value = await self._fetch_from_layers(key)<br>        await self._backfill(key, value)<br>        return value</pre><p>Per-key asyncio.Lock objects. The first coroutine grabs the lock and hits the database. Everyone else waits. When the lock releases they check L1 again and find the value already there.</p><p>I tested this with 20 concurrent coroutines all requesting the same expired key:</p><pre>Scenario: 20 concurrent requests for a single expired key</pre><pre>Without stampede protection:<br>  DB queries fired: 20<br>  Avg response time: ~120ms (queue pressure + DB load)</pre><pre>With cachestack TieredCache:<br>  DB queries fired: 1<br>  Avg response time: ~35ms</pre><p>One database call instead of twenty. That difference compounds fast under real traffic.</p><h3>Four problems I should have seen coming (the file backend)</h3><p>The original library had Memory, Redis, Postgres, and Memcached. No file backend. A week after finishing the first version I realized I’d missed the most obvious use case: cross-process caching with zero infrastructure. No Redis server. No Postgres. Just disk.</p><p>I thought it would take a few hours.</p><p>It took four debugging sessions spread across two days, and every single problem was something I should have anticipated.</p><p><strong>Problem 1: JSON only handles JSON types.</strong></p><p>My first implementation used json.dumps for serialization. Clean, human-readable, zero extra dependencies. Then I tried to cache a datetime object. TypeError: Object of type datetime is not JSON serializable.</p><p>Switched the default serializer to Pickle. Now datetime, set, custom classes all work out of the box. JsonSerializer is still available as an option if you want human-readable files on disk.</p><p><strong>Problem 2: Files don’t garbage collect themselves.</strong></p><p>Expired entries in Redis disappear automatically. Expired files on disk just sit there. In a long-running application that caches thousands of unique keys, this turns into a disk bloat problem quietly and then suddenly.</p><p>The fix was a purge_expired() method plus an auto_purge_interval config option that triggers cleanup passively during writes. You can also call purge_expired() from a scheduler if you want more control over timing.</p><p><strong>Problem 3: Windows has opinions about file replacement.</strong></p><p>My atomic write pattern was: write to a temp file, then os.replace() to the target. This is the correct way to do atomic writes. It works perfectly on Linux.</p><p>On Windows, os.replace() raises PermissionError if another thread has the target file open at the exact same moment. Not consistently. Not always. Just sometimes, under concurrent load, which makes it the worst kind of bug to debug.</p><p>The fix was a retry loop. Five attempts with exponential back-off: 5ms, 10ms, 20ms, 40ms. After that it raises. In practice the retry succeeds on the first or second attempt. Windows-safe without adding any perceptible latency.</p><p><strong>Problem 4: I was testing it wrong.</strong></p><p>One test tried to pickle a class defined inside the test function itself:</p><pre>async def test_pickle_serializer_custom_object(tmp_path):<br>    class MyObj:  # defined inside the test function<br>        ...<br>    obj = MyObj(42)<br>    await cache.set(&quot;obj&quot;, obj)  # fails</pre><p>Pickle serializes objects by their fully qualified module path. A class defined inside a function has no importable path. Deserialization fails with AttributeError: Can&#39;t get local object.</p><p>The library was fine. My test was wrong. Moving MyObj to module level fixed it immediately.</p><p>I spent 20 minutes convinced I had a fundamental Pickle bug before I actually read the error message.</p><h3>When to use cachestack (and when not to)</h3><p>I want to be honest about this because most library authors aren’t.</p><p><strong>Use cachestack if:</strong></p><ul><li>You’re building async Python services and need a caching layer that doesn’t fight your event loop</li><li>You’re in an enterprise or regulated environment where every dependency goes through a security scan</li><li>You want tiered caching (memory + Redis + Postgres) without implementing the backfill and stampede logic yourself</li><li>You need a file-based fallback for local dev or CI environments that don’t have Redis</li></ul><p><strong>Don’t use it if:</strong></p><ul><li>You already have a stable Redis-only setup and it’s working well, don’t introduce a new library for no reason</li><li>You’re on Python 3.10 or lower (cachestack targets 3.11+)</li><li>You need distributed locking across multiple nodes (the stampede protection is in-process only)</li><li>You’re using a managed cloud caching solution (ElastiCache, Momento, Upstash) and don’t need the abstraction layer</li></ul><p>Not the right tool for everything. Knowing the boundary is part of the job.</p><h3>Publishing to PyPI</h3><p>The actual publish process is three commands:</p><pre>python -m build<br>twine check dist/*<br>twine upload dist/*</pre><p>A few things worth knowing before you get there:</p><p>Check the name before you write a line of code. pip index versions yournamehere. If it returns results, the name is taken. I checked cachestack early. It was free.</p><p>TestPyPI exists and you should use it. twine upload --repository testpypi dist/* gives you a live preview of your package page where you can verify the README renders correctly and the install actually works before touching the real index.</p><p>PyPI does not let you re-upload the same version number. Ever. If you push 0.1.0 and then notice you forgot to update the GitHub URL in pyproject.toml, that&#39;s a 0.1.1 now. There is no overwrite and no delete-and-reupload. Pick your version numbers carefully before you push.</p><h3>What building this actually taught me</h3><p>The API surface is harder than the implementation. I rewrote the internal file I/O three times and nobody noticed. If I’d changed the FileConfig field names after people started using it, I&#39;d have broken their code. The public interface deserves the most careful thought before anything else gets written.</p><p>The hardest part wasn’t writing the backends. It was designing an interface that wouldn’t need to change once people started depending on it.</p><p>Zero dependencies is a real discipline. Every time I wanted to reach for a convenience package I had to ask: is this MIT or Apache? Does it have a stable release history? Does it add surface area for the next BlackDuck scan? The answer was usually “use stdlib instead.” The library is leaner for it.</p><p>Platform differences matter more than you expect for anything that touches the filesystem. Everything worked on Linux. Windows had the file locking issue. I didn’t test on Windows until late in the process and I paid for that with two debugging sessions I could have avoided.</p><p>And the most useful thing: when a test fails, read the error message before changing any code. Both of my test failures were test bugs, not library bugs. One said “Can’t get local object”. Pickle being very literal about exactly what was wrong. The other said “Access is denied”. Windows being very literal about exactly what was wrong. The answers were in the error messages the whole time.</p><h3>Where to find it</h3><p>GitHub: <a href="https://github.com/sarthakbhatkar1/cachestack">https://github.com/sarthakbhatkar1/cachestack</a></p><p>PyPI: <a href="https://pypi.org/project/cachestack/">https://pypi.org/project/cachestack/</a></p><pre>pip install cachestack</pre><p>If you break something, open an issue. If you know a better way to handle the Windows atomic write problem, open a PR.</p><p>I built this to solve a real problem in a real codebase. If you’re running it in production, your feedback matters more than anything else here.</p><p><em>I’m a Senior Associate at State Street building AI/ML infrastructure and Generative AI platforms for one of the largest financial institutions in the world. Most AI content talks about models. I write about what sits underneath them: inference infrastructure, compliance constraints, latency tradeoffs, and the engineering decisions that never make it into a paper. If that sounds like the stuff you actually deal with at work, follow along.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e1c725fc68d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Economics of Production AI Systems — Part I]]></title>
            <link>https://medium.com/@sarthakbhatkar/the-economics-of-production-ai-systems-part-i-51b41f384a44?source=rss-ae83a5b3c660------2</link>
            <guid isPermaLink="false">https://medium.com/p/51b41f384a44</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[systems-engineering]]></category>
            <dc:creator><![CDATA[Sarthak Bhatkar]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 15:26:41 GMT</pubDate>
            <atom:updated>2026-02-22T15:26:41.317Z</atom:updated>
            <content:encoded><![CDATA[<h3>Inference Economics at Scale: When Throughput Becomes the Constraint</h3><p>For several years, AI progress has been framed around capability.</p><p>More parameters.<br>Longer context windows.<br>Higher benchmark scores.</p><p>That framing works in research.</p><p>In production-scale systems, the constraint shifts.</p><p>The defining variable is no longer raw model capability.</p><p>It is how much usable intelligence you can extract per GPU hour, per unit of memory, under real concurrency and latency constraints.</p><p>At scale, inference economics becomes the binding constraint.</p><h3>The Optimization Target Changes at Scale</h3><p>In research, the objective is accuracy.</p><p>In large-scale serving environments, the objective becomes:</p><ul><li>Throughput per GPU hour</li><li>Memory density under concurrency</li><li>p95 / p99 latency stability</li><li>Tail behavior under burst</li><li>Degradation characteristics during failure</li></ul><p>At small volumes, model choice is a quality decision.</p><p>At fleet scale, it is a resource allocation decision.</p><p>A 10% increase in average tokens per request may translate into:</p><ul><li>Larger KV cache footprint</li><li>Fewer concurrent sequences per GPU</li><li>Higher queue depth</li><li>Amplified p99 latency</li><li>Lower effective hardware utilization</li></ul><p>Inference economics is not abstract.</p><p>It is visible in cluster utilization graphs.</p><h3>Context Length Is a Concurrency Decision</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7IQ420tfGbsu98Xsw8ukA.png" /><figcaption>KV Memory → Concurrency → Tail Latency Diagram</figcaption></figure><p>Transformer attention scales poorly with sequence length.</p><p>Longer context increases:</p><ul><li>KV cache residency</li><li>Activation memory</li><li>Fragmentation risk</li><li>Latency variance</li></ul><p>KV caching trades recomputation for memory residency.</p><p>At fleet scale, the constraint is rarely compute first — it is memory density.</p><p>Larger KV footprints reduce concurrent sequence capacity per GPU.<br> Reduced concurrency increases queue depth.<br> Increased queue depth amplifies p99 latency.</p><p>Context length is therefore not just a capability decision.</p><p>It is a concurrency decision.</p><h3>Batching Is a Throughput Lever — and a Latency Risk</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1UitasmJwnrGON0o6Z6wQ.png" /><figcaption><em>Batching Is a Throughput Lever — and a Latency Risk</em></figcaption></figure><p>Batching improves GPU utilization and amortizes kernel launches.</p><p>But batching competes directly with latency SLAs.</p><p>Aggressive batching strategies:</p><ul><li>Improve tokens/sec</li><li>Reduce cost per generated token</li><li>Increase tail latency</li></ul><p>Serving systems constantly navigate this tension:</p><p>Throughput efficiency<br> vs<br> Responsiveness under real-time load</p><p>The optimal batch size is not static.</p><p>It shifts with traffic distribution, model behavior, and SLA targets.</p><h3>Routing Is an Infrastructure Commitment</h3><p>Multi-model routing is often framed as a cost optimization technique.</p><p>In high-scale systems, it is a control-plane problem.</p><p>Routing introduces:</p><ul><li>Cross-model evaluation requirements</li><li>Confidence calibration</li><li>Traffic segmentation complexity</li><li>Testing matrix expansion</li><li>Observability overhead</li></ul><p>Naïve routing fails for predictable reasons:</p><ul><li>Evaluation drift goes unnoticed</li><li>Distribution shifts invalidate thresholds</li><li>Misrouted traffic amplifies retries</li><li>Downstream systems absorb hidden cost</li></ul><p>A routing layer is not a wrapper.</p><p>It is a persistent systems responsibility.</p><h3>A Failure Mode That Looks Cheap on Paper</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Npl8rvE6rNHP26jRchi6uA.png" /><figcaption>Routing Failure Amplification Diagram</figcaption></figure><p>Consider a routing strategy where:</p><ul><li>70% of traffic goes to a smaller model</li><li>8% of that traffic produces subtly degraded outputs</li><li>5% triggers fallback retries</li><li>3% escalates to human validation</li></ul><p>On paper, inference cost drops.</p><p>In practice:</p><ul><li>Retry amplification increases GPU utilization</li><li>Human review dominates marginal savings</li><li>Queue depth increases under burst</li><li>Tail latency worsens</li></ul><p>The system appears economically efficient at the average.</p><p>It degrades economically at the tail.</p><p>At scale, tail behavior dominates.</p><h3>Quantization, Speculative Decoding, and the Real Levers</h3><p>Significant economic leverage often comes from:</p><ul><li>INT8 / INT4 quantization reducing VRAM footprint</li><li>Paged attention mitigating fragmentation</li><li>Speculative decoding reducing wall-clock latency</li><li>Activation recomputation strategies</li><li>Serving framework choices (vLLM, TGI, TensorRT-LLM)</li></ul><p>Each lever shifts a different axis:</p><p>Memory<br> Throughput<br> Latency<br> Accuracy</p><p>None are free.</p><p>Quantization trades precision for efficiency.<br> Speculative decoding trades architectural simplicity for latency gains.<br> Paged attention trades implementation complexity for memory stability.</p><p>At infra scale, these tradeoffs often outweigh model selection itself.</p><h3>API vs Self-Hosted Economics</h3><p>For API consumers, cost is metered per token.</p><p>For self-hosted systems, cost is amortized per GPU hour.</p><p>The accounting changes.</p><p>The constraint does not.</p><p>Per-token pricing becomes:</p><ul><li>GPU amortization</li><li>Power and cooling cost</li><li>VRAM density decisions</li><li>Scheduler efficiency</li><li>Fleet utilization stability</li></ul><p>In both cases, the system is bounded by deployment economics.</p><h3>Safety Competes With Throughput</h3><p>Safety layers are not free abstractions. They consume measurable budget.</p><p>Examples:</p><ul><li>A secondary classification pass adding 35–50ms per request</li><li>Structured output validation increasing p99 latency by 10–15%</li><li>Redundant moderation calls doubling token generation on edge cases</li></ul><p>Each layer consumes:</p><ul><li>GPU cycles</li><li>Memory residency</li><li>Latency budget</li></ul><p>In high-utilization systems operating near saturation, these layers directly reduce effective throughput.</p><p>When systems approach capacity limits, safety instrumentation is often pressured — not because it lacks importance, but because it competes with SLAs.</p><p>Efficient inference creates slack.<br> Slack enables redundancy.<br> Redundancy enables safety.</p><p>Alignment at scale is constrained by architecture, not intention.</p><h3>The System Is the Product</h3><p>At infra scale, the model is a workload.</p><p>The differentiator is:</p><ul><li>How efficiently it is served</li><li>How predictably it behaves under load</li><li>How economically it scales</li><li>How resiliently it degrades</li></ul><p>The winning systems are not necessarily those with the largest models.</p><p>They are those that extract the most useful work per unit of hardware.</p><h3>Final Thesis</h3><p>Model capability will continue to advance.</p><p>But in high-scale production environments, capability is bounded by deployment economics.</p><p>The defining skill of the next generation of AI engineers will not be model selection alone.</p><p>It will be designing serving systems that:</p><ul><li>Disaggregate prefill and decode to stabilize latency</li><li>Use continuous batching without violating SLAs</li><li>Allocate KV memory to maximize concurrency density</li><li>Apply quantization without destabilizing quality</li><li>Route traffic without amplifying tail failure</li></ul><p>At scale, the model is a workload.</p><p>The system is the product.</p><p>Inference economics is the constraint surface on which large-scale AI systems survive.</p><p>Part II will expand the lens beyond inference into training amortization, retrieval infrastructure, human oversight cost, and vendor dependency risk.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51b41f384a44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Landed My First Job in the IT Industry: A Guide for Students]]></title>
            <link>https://medium.com/@sarthakbhatkar/how-i-landed-my-first-job-in-the-it-industry-a-guide-for-students-54814eef211f?source=rss-ae83a5b3c660------2</link>
            <guid isPermaLink="false">https://medium.com/p/54814eef211f</guid>
            <category><![CDATA[it-career-advice]]></category>
            <category><![CDATA[engineering-career]]></category>
            <category><![CDATA[career-advice]]></category>
            <dc:creator><![CDATA[Sarthak Bhatkar]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 08:50:17 GMT</pubDate>
            <atom:updated>2025-01-26T08:50:17.754Z</atom:updated>
            <content:encoded><![CDATA[<p>Back in 2019, when I enrolled in my computer engineering program, I was excited and optimistic. Like many others, I thought the college would give me everything I needed to secure a high-paying job after graduation. I imagined structured guidance, clear instructions on what to learn, and a smooth path toward achieving my dreams. But within a couple of semesters, I realized that’s not how it works in most engineering colleges.</p><p>If you’re currently pursuing an engineering degree or planning to land a job in the IT sector, I want to share what I wish someone had told me early on. Here’s a guide, based on my experience, to help you navigate this journey.</p><h3>1. College Won’t Teach You Everything</h3><p>Let’s face it — colleges focus on theoretical knowledge, but the IT industry demands practical skills. During my first two years, I learned a lot about computer engineering, but most of it felt disconnected from what companies actually look for. It wasn’t until my fifth semester that I started understanding how to prepare for job interviews.</p><p>If you’re in college right now, take this as a reminder: you need to take charge of your learning. The curriculum is just a starting point.</p><h3>2. Find Your Interest in the IT Sector</h3><p>The IT industry is vast, and blindly following trends can be overwhelming. Early on, I didn’t know whether I wanted to be a software developer, data scientist, or cybersecurity specialist. To figure this out, I explored different areas:</p><ul><li><strong>Competitive Programming:</strong> It was like solving puzzles. I liked the challenge and how it helped me improve my problem-solving skills.</li><li><strong>Web Development:</strong> Building websites was fun! Seeing something I created come to life was super satisfying, and I learned a lot about how things work behind the scenes.</li><li><strong>Machine Learning:</strong> I found it fascinating to work on projects where data could be used to make predictions. It felt like I was learning something truly futuristic.</li></ul><p>Even though I eventually chose to focus on machine learning, I genuinely enjoyed everything I tried. Each experience taught me something new and gave me a better understanding of the industry.</p><p>If you’re just starting out, my advice is to explore as much as you can. Don’t feel pressured to pick a specific path right away — try different things and enjoy the journey. You’ll figure out what you like as you go.</p><h3>3. Start Early and Plan Strategically</h3><p>If I could go back in time, I’d advise my first-year self to begin earlier and plan smarter. Here’s a refined roadmap for the four years:</p><p><strong>First Year: Build Strong Foundations</strong></p><ul><li>Start by learning the basics of programming with languages like C, C++, Python, or Java.</li><li>Focus on understanding core concepts like variables, loops, functions, and object-oriented programming.</li><li>Work on small, hands-on projects (e.g., calculators, basic games, or to-do apps) to reinforce your knowledge and build confidence.</li></ul><p><strong>Second Year: Master Core Concepts</strong></p><ul><li>Dive deep into Data Structures and Algorithms (DSA) — the cornerstone of IT and tech interviews. Topics like arrays, linked lists, trees, and dynamic programming are essential.</li><li>Solve problems on platforms like LeetCode, HackerRank, or Codeforces to enhance your problem-solving skills.</li><li>Begin applying for internships or exploring open-source contributions to gain practical experience and exposure to real-world coding environments.</li></ul><p><strong>Third Year: Gain Practical Experience</strong></p><ul><li>Focus on building substantial projects that showcase your technical skills and creativity. Examples include web applications, mobile apps, or machine learning models.</li><li>Actively seek internships to apply your knowledge in a professional setting. Internships not only enhance your learning but also help you build a strong network.</li><li>Explore advanced topics or specialized domains like AI, cloud computing, or cybersecurity if they align with your interests.</li></ul><p><strong>Final Year: Prepare for the Transition</strong></p><ul><li>Refine your resume, tailoring it to highlight your skills, projects, and internship experiences effectively.</li><li>Practice mock interviews, both technical and behavioral, to gain confidence and identify areas of improvement.</li><li>Focus on securing your first job by applying to relevant roles, attending campus placement drives, or leveraging professional networks like LinkedIn.</li></ul><p>This step-by-step strategy ensures you stay ahead, build relevant skills, and transition smoothly from academia to industry.</p><h3>4. Master Technical Skills</h3><p>Here’s the harsh truth: companies care about what you can do, not what you’ve studied. To stand out, focus on these areas:</p><ul><li><strong>Programming</strong>: Master one language deeply (I chose C and Python).</li><li><strong>Data Structures and Algorithms</strong>: Dedicate time to platforms like LeetCode, CodeChef and HackerRank.</li><li><strong>Development Skills</strong>: Learn web or app development. Personally, I enjoyed artificial intelligence and machine learning to solve the problem statements.</li><li><strong>Cloud and Databases</strong>: Get hands-on experience with cloud platforms like AWS or Azure and learn SQL thoroughly.</li></ul><p>The earlier you start practicing, the easier it becomes to tackle technical interviews later.</p><h3>5. Build Projects That Matter</h3><p>One of the most valuable lessons I’ve learned is that recruiters love seeing projects on your resume. Projects demonstrate your ability to apply skills in real-world scenarios, which sets you apart from the crowd. Here are some impactful projects that can boost your resume:</p><ul><li><strong>Personal Portfolio Website</strong><br>Create a polished website to showcase your work, skills, and accomplishments. It’s a great way to leave a lasting impression on potential employers.</li><li><strong>CRUD Operations Website</strong><br>Build a functional web application that implements Create, Read, Update, and Delete operations. Use popular technologies like React, Flask, or Node.js to showcase your full-stack development skills.</li><li><strong>Algorithmic Simulation</strong><br>Develop a simulation of a core algorithm using Java or C++. For instance, simulate pathfinding algorithms like A* or sorting techniques to highlight your understanding of algorithms and data structures.</li><li><strong>Generative AI Application</strong><br>Work on a trending technology project, such as a Generative AI application. For example, check out my blog on simplifying PDF table extraction with LLMs and Streamlit <a href="https://medium.com/@lostvaynesarthak/simplify-pdf-table-extraction-with-llmsherpa-and-streamlit-f70d0ff8b7a7">here</a>. Projects like these show your adaptability to new technologies.</li><li><strong>Machine Learning Project</strong><br>Create a small ML model, such as predicting house prices using datasets like Kaggle’s housing data. This showcases your data analysis and machine learning skills.</li></ul><p>These projects not only helped me learn and grow but also boosted my confidence during interviews. Remember, the goal isn’t perfection — it’s consistent progress. Each project is a stepping stone to mastering your craft and impressing potential employers.</p><h3>6. Take Internships Seriously</h3><p>My first internship was a game-changer. It gave me a glimpse of how the industry works and taught me so much more than I expected. Here’s what worked for me and what I’d recommend:</p><ul><li><strong>Start Early</strong><br>Don’t wait until the last minute to look for internships. Platforms like LinkedIn and Internshala are great places to start your search.</li><li><strong>Ask for Referrals</strong><br>Instead of just applying to every job posting, try reaching out to people for referrals. A lot of others will already have applied directly, so having a referral can give you an edge.</li><li><strong>Look at Startups</strong><br>If you’re finding it hard to land an internship, consider startups. They usually give you more responsibility and hands-on experience, which can be super valuable.</li><li><strong>Focus on Learning</strong><br>Don’t think of an internship as just something to add to your resume. Use it as a chance to learn, make mistakes, and figure out how things actually work in the real world.</li></ul><p>During my internship, I worked on a real product that actual customers used. That experience stood out in my interviews and gave me confidence. Internships aren’t just about landing your first job — they’re about building skills and figuring out what you enjoy doing.</p><h3>7. Your Resume and LinkedIn Matter More Than You Think</h3><p>When I started applying for jobs, I realized just how important a strong resume and LinkedIn profile are. They’re often your first impression, and they can make or break your chances. Here’s what worked for me:</p><ul><li><strong>Resume Tips:</strong><br>Keep it concise and highlight the key things: your skills, projects, internships, and achievements. Recruiters spend only a few seconds scanning each resume, so make it easy to read. Stick to one page if you can, and tailor your resume for each job you apply to. If you need inspiration, you can check out this <a href="https://drive.google.com/file/d/17YFrwdBCe3m5jah30zxPCsg0sQtsllDT/view">sample resume</a> for reference.</li><li><strong>LinkedIn Tips:</strong><br>Keep your profile up-to-date. Showcase your projects, internships, certifications, and skills. Use LinkedIn to connect with professionals in your field, alumni from your college, or anyone who might provide career advice.</li></ul><p>One of the best parts about LinkedIn is the networking opportunities. By reaching out and connecting with people, I even managed to land a couple of interview calls!</p><p>Your resume and LinkedIn are powerful tools — use them wisely to stand out from the crowd.</p><h3>8. Prepare for Interviews Like a Pro</h3><p>The IT interview process can be daunting, but preparation is key. Most interviews consist of:</p><ul><li><strong>Technical Rounds</strong>: Focus on DSA, coding, and core subjects.</li><li><strong>Problem-Solving Tests</strong>: Practice aptitude and reasoning questions.</li><li><strong>HR Rounds</strong>: Be genuine. Talk about your strengths, weaknesses, and why you want the role.</li></ul><p>Mock interviews helped me a lot. They gave me a chance to refine my answers and build confidence.</p><h3>9. Learn Beyond the Classroom</h3><p>I leaned heavily on online resources. Here’s what worked for me:</p><ul><li><strong>Coding Practice</strong>: LeetCode, CodeChef, and HackerRank.</li><li><strong>Courses</strong>: Azure &amp; AWS certifications</li><li><strong>YouTube</strong>: Channels like freecodecamp and TechLead.</li><li><strong>Communities</strong>: GitHub, Reddit, and LinkedIn groups.</li></ul><p>The internet is your best friend — use it wisely.</p><h3>10. Stay Curious and Persistent</h3><p>The IT industry changes rapidly, and what’s hot today might not be tomorrow. During my journey, I made it a point to stay curious and adapt. Whether it was learning a new framework or contributing to an open-source project, I never stopped learning.</p><p>There were moments of self-doubt, especially during tough interviews, but persistence paid off. Every rejection taught me something new.</p><h3>Conclusion</h3><p>Landing a job in the IT industry as an engineering student isn’t easy, but it’s achievable with the right mindset and effort. My journey wasn’t perfect, and I made plenty of mistakes along the way. But looking back, every challenge was a learning opportunity.</p><p>If you’re in college and reading this, remember: take charge of your career early. Build your skills, work on meaningful projects, and prepare strategically for interviews. The IT world is full of opportunities — you just need to be ready to grab them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54814eef211f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API Fundamentals: A Beginner's Guide]]></title>
            <link>https://medium.com/@sarthakbhatkar/rest-api-fundamentals-a-begginers-guide-efc0cf51da75?source=rss-ae83a5b3c660------2</link>
            <guid isPermaLink="false">https://medium.com/p/efc0cf51da75</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[rest-api-design]]></category>
            <dc:creator><![CDATA[Sarthak Bhatkar]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 21:39:46 GMT</pubDate>
            <atom:updated>2024-09-16T21:41:03.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*R2fjxdARCIMiaZec.jpg" /></figure><p>In today’s connected world, APIs (Application Programming Interfaces) are the backbone of modern software development, allowing different systems to communicate. One of the most widely used types of API is the REST API (Representational State Transfer). It’s the go-to architecture for designing networked applications due to its simplicity, scalability, and stateless nature. In this article, we’ll explore the core principles of REST API, how it works, and why it has become so popular.</p><h3>What is a REST API?</h3><p>A <strong>REST API</strong> is an interface that allows clients (such as web browsers or mobile apps) to interact with a server via the internet. It follows the <strong>REST</strong> <strong>architecture</strong> principles, introduced by Roy Fielding in 2000. RESTful services rely on HTTP requests to perform operations like <strong>Create</strong>, <strong>Read</strong>, <strong>Update</strong>, and <strong>Delete</strong> (often referred to as CRUD).</p><h3><strong>Core Principles of REST</strong></h3><p>To qualify as a RESTful API, certain architectural constraints must be adhered to. Here are the key REST principles:</p><p><strong>Statelessness</strong></p><ul><li>Every request from a client to a server must contain all the necessary information to understand and process the request. The server does not store the client’s state between requests, meaning each request is independent of the others. This stateless nature makes REST highly scalable.</li></ul><p><strong>Client-Server Architecture</strong></p><ul><li>REST enforces a clear separation between the client and server. The client handles the user interface and interacts with the server, which processes data and business logic. This separation ensures that both the client and server can evolve independently.</li></ul><p><strong>Uniform Interface</strong></p><ul><li>REST APIs must have a consistent and uniform way of interacting with resources. This is achieved through well-defined URIs (Uniform Resource Identifiers) and HTTP methods. The four primary HTTP methods used are:<br> - <strong>GET</strong>: Retrieve data from the server.<br> - POST: Submit data to the server to create a new resource.<br> - PUT: Update an existing resource or create it if it doesn’t exist.<br> - DELETE: Remove a resource from the server.</li></ul><p><strong>Resource-Based</strong></p><ul><li>In REST, everything is considered a resource, and each resource is identified by a unique URI. Resources can be anything from a user, a product, or a blog post. The URI structure should be simple, intuitive, and hierarchical. For example:</li></ul><pre>/api/users<br>/api/users/{user_id}<br>/api/products/{product_id}</pre><p><strong>Stateless Caching</strong></p><ul><li>REST allows the use of caching mechanisms to improve performance. When a client requests data, the server can specify whether the response should be cached. This reduces unnecessary load on the server by eliminating redundant requests.</li></ul><p><strong>Layered System</strong></p><ul><li>RESTful APIs can be designed with layers. A client may not necessarily know whether it is interacting with the actual server or an intermediary layer (such as a load balancer or cache). This abstraction allows for better scalability and security.</li></ul><p><strong>Code on Demand (Optional)</strong></p><ul><li>Though optional, REST APIs can extend functionality by sending executable code (such as JavaScript) to the client. This code can be executed on the client side to extend features dynamically, though this is less common in most APIs.</li></ul><h3>How REST Works</h3><p>When you interact with a REST API, you’re essentially using the HTTP protocol to make requests. Let’s break down the most commonly used HTTP methods:</p><ul><li><strong>GET</strong>: Used to fetch data from a resource. It’s read-only and safe since it doesn’t modify any data. Example: GET /api/users/123 retrieves user details with the ID 123.</li><li><strong>POST</strong>: Used to create a new resource on the server. Example: POST /api/users might add a new user, with the details provided in the request body.</li><li><strong>PUT</strong>: Used to update an existing resource, or create it if it doesn’t exist. Example: PUT /api/users/123 updates the user with ID 123.</li><li><strong>DELETE</strong>: Used to remove a resource. Example: DELETE /api/users/123 deletes the user with ID 123.</li></ul><h3>REST vs. Other API Architectures</h3><p>You may have heard of alternatives like SOAP (Simple Object Access Protocol) or GraphQL. So how does REST compare?</p><ul><li><strong>REST vs. SOAP</strong>: SOAP is a protocol that uses XML to exchange messages, while REST is an architectural style that can handle multiple data formats (such as JSON, XML, etc.). SOAP is more rigid but offers more built-in security features. REST is lighter and easier to use.</li><li><strong>REST vs. GraphQL</strong>: GraphQL allows clients to specify exactly what data they need, whereas REST may return a fixed structure. This makes GraphQL more flexible in some cases, but REST remains easier to cache and scale.</li></ul><h3>Best Practices for Designing REST APIs</h3><p><strong>Use Meaningful URIs</strong></p><ul><li>Keep URIs intuitive and resource-oriented. Avoid using verbs in URIs since the HTTP methods already define the action.</li><li>Example: Prefer /api/users/123 over /api/getUserDetails/123.</li></ul><p><strong>Version Your API</strong></p><ul><li>Always include versioning in your API design. This prevents breaking changes for existing clients when new features are introduced.</li><li>Example: /api/v1/users for version 1, /api/v2/users for version 2.</li></ul><p><strong>Use HTTP Status Codes Correctly</strong></p><ul><li>Utilize standard HTTP status codes to provide clear feedback to the client:<br> - <strong>200 OK</strong>: The request was successful.<br> - <strong>201 Created</strong>: A resource was successfully created.<br> - <strong>400 Bad Request</strong>: The request was malformed or invalid.<br> - <strong>404 Not Found</strong>: The requested resource doesn’t exist.<br> - <strong>500 Internal Server Error</strong>: The server encountered an error.</li></ul><p><strong>Leverage JSON</strong></p><ul><li>JSON (JavaScript Object Notation) is the most common data format for REST APIs due to its simplicity and compatibility across platforms. Always return data in a standard and easy-to-read format.</li></ul><p><strong>Implement Authentication &amp; Security</strong></p><ul><li>REST APIs often handle sensitive data, so it’s critical to secure them using authentication (like OAuth) and encryption (using HTTPS).</li></ul><p><strong>Conclusion</strong></p><p>REST APIs have become a cornerstone of modern software development due to their flexibility, scalability, and simplicity. Understanding the fundamentals of REST and how to design APIs around its principles will enable you to build better, more robust web services. Whether you’re developing a small mobile app or a large-scale enterprise system, mastering REST API concepts will be a valuable skill in your developer toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efc0cf51da75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify PDF Table Extraction with LLMSherpa and Streamlit]]></title>
            <link>https://medium.com/@sarthakbhatkar/simplify-pdf-table-extraction-with-llmsherpa-and-streamlit-f70d0ff8b7a7?source=rss-ae83a5b3c660------2</link>
            <guid isPermaLink="false">https://medium.com/p/f70d0ff8b7a7</guid>
            <category><![CDATA[llmsherpa]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[table-extraction]]></category>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <category><![CDATA[pdf-extraction]]></category>
            <dc:creator><![CDATA[Sarthak Bhatkar]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 04:05:29 GMT</pubDate>
            <atom:updated>2024-07-23T04:05:29.373Z</atom:updated>
            <content:encoded><![CDATA[<p>The rise of document understanding tools has opened doors to exciting applications. These tools, often powered by machine learning, can extract meaning from various document formats. But working with these tools can be hindered by the complexity of document structures, particularly PDFs.</p><p>This is where LLMSherpa comes in. LLMSherpa is a developer toolkit designed to bridge the gap between document understanding tools and real-world applications, specifically those that involve PDFs.</p><p><strong>The PDF Parsing Challenge</strong></p><p>PDFs are a ubiquitous document format, but for document understanding tools, they can be a challenge. The rich formatting and layout make it difficult for these tools to directly understand the content. Extracting text, identifying structure, and navigating different elements within a PDF require additional processing.</p><p><strong>LLMSherpa to the Rescue</strong></p><p>LLMSherpa tackles this challenge by offering a suite of tools for PDF parsing. Here’s how it streamlines the process:</p><ul><li><strong>Clean Text Extraction:</strong> LLMSherpa can accurately extract text content from PDFs, ensuring document understanding tools receive clean, unformatted text for optimal processing.</li><li><strong>Structural Awareness:</strong> It goes beyond simple text extraction. LLMSherpa can identify the layout structure of a PDF, recognizing sections, tables, paragraphs, and other elements. This allows you to target specific sections of the PDF for analysis.</li><li><strong>Preprocessing Magic:</strong> LLMSherpa can handle unwanted elements like headers, footers, and page numbers. It removes these distractions, providing a streamlined text corpus for the document understanding tool.</li></ul><p><strong>Benefits of Using LLMSherpa</strong></p><p>By simplifying PDF parsing, LLMSherpa empowers developers to focus on what truly matters: building intelligent applications that leverage document understanding tools. Here are some key benefits:</p><ul><li><strong>Reduced Development Time:</strong> Spend less time wrestling with PDF parsing and more time building your core application logic.</li><li><strong>Improved Accuracy:</strong> Ensure your document understanding tool receives clean, structured data for optimal performance.</li><li><strong>Enhanced Functionality:</strong> Unlock new possibilities for your applications by incorporating the power of PDF data analysis.</li></ul><p><strong>Getting Started with LLMSherpaLLMSherpa</strong></p><p>Install docker in your local desktop and then run the below commands. First to pull the image and then to run it.</p><pre>docker pull ghcr.io/nlmatics/nlm-ingestor:latest<br><br>docker run -p 5010:5001 ghcr.io/nlmatics/nlm-ingestor:latest</pre><p>And install llmsherpa and streamlit:</p><pre>pip install llmsherpa streamlit</pre><p><strong>Why Extract Tables from PDFs?</strong></p><p>PDFs are a common document format, but extracting data from tables within them can be challenging. This app tackles this challenge by leveraging LLMSherpa’s ability to parse PDFs and identify tables.</p><pre># Simple table extraction using llmshera and Streamlit <br>import pandas as pd<br>import streamlit as st<br>from bs4 import BeautifulSoup<br>from llmsherpa.readers import LayoutPDFReader<br><br>llmsherpa_api_url = &quot;http://127.0.0.1:5010/api/parseDocument?renderFormat=all&quot;<br><br>pdf_url = &quot;https://abc.xyz/assets/91/b3/3f9213d14ce3ae27e1038e01a0e0/2024q1-alphabet-earnings-release-pdf.pdf&quot;<br>pdf_reader = LayoutPDFReader(llmsherpa_api_url)<br><br>st.title(&#39;Table extraction using llmsherpa&#39;)<br><br><br>uploaded_file = st.file_uploader(&quot;Choose a file&quot;)<br>st.markdown(&quot;&quot;&quot;---&quot;&quot;&quot;)<br><br>#########################<br><br># Sample data (replace with your actual data)<br>df_list = []<br><br><br>if uploaded_file is not None:<br>    bytes_data = uploaded_file.getvalue()<br><br>    with open(&#39;store.pdf&#39;, &#39;wb&#39;) as pdf_file:<br>        pdf_file.write(bytes_data)<br>    doc = pdf_reader.read_pdf(&#39;./store.pdf&#39;)<br>    # html_string = doc.tables()[5].to_html()<br>    data_list = [_table.to_html() for _table in doc.tables()]<br><br>    for html_string in data_list:<br>        soup = BeautifulSoup(html_string, &#39;html.parser&#39;)<br>        table = soup.find(&#39;table&#39;)<br><br>        # Extract table data into rows and columns<br>        if table:<br>            table_data = []<br>            for row in table.find_all(&#39;tr&#39;):<br>                cells = [cell.text.strip() for cell in row.find_all([&#39;th&#39;, &#39;td&#39;])]<br>                table_data.append(cells)<br><br>            # Create pandas DataFrame (handle potential column name issues)<br>            df = pd.DataFrame(table_data[1:])<br>            df = df.fillna(&quot;None&quot;, inplace=False)<br>        df_list.append(df)<br><br>        # st.table(df)<br>    else:<br>        print(f&quot;Tables are not found...&quot;)<br><br>    if &quot;current_index&quot; not in st.session_state:<br>        st.session_state[&quot;current_index&quot;] = 0<br><br>    # Display current data item<br>    st.write(f&quot;Extracted Table:&quot;)<br>    st.table(df_list[st.session_state[&quot;current_index&quot;]])<br><br>    col1, col2 = st.columns(2)<br><br>    if col1.button(&quot;Previous&quot;):<br>        if st.session_state[&quot;current_index&quot;] &gt; 0:<br>            st.session_state[&quot;current_index&quot;] -= 1<br><br>    if col2.button(&quot;Next&quot;):<br>        if st.session_state[&quot;current_index&quot;] &lt; len(df_list) - 1:<br>            st.session_state[&quot;current_index&quot;] += 1</pre><p><strong>Here’s a breakdown of the code:</strong></p><ol><li><strong>Import Libraries:</strong> We import pandas for data manipulation, streamlit for building the web app, BeautifulSoup for parsing HTML, and LayoutPDFReader from LLMSherpa for PDF processing.</li><li><strong>Set up Streamlit App:</strong> We define a title for the app and a file uploader for users to select a PDF.</li><li><strong>Process Uploaded PDF (if any):<br>*</strong>If a PDF is uploaded, we read its content as bytes.<br>*We temporarily store the PDF data using open and write functions.<br>*LLMSherpa’s read_pdf function is used to parse the PDF and extract its content.</li><li><strong>Extract Tables:<br></strong>*We iterate through the extracted tables using a list comprehension.<br>*For each table, we convert it to HTML format using to_html.<br>*BeautifulSoup parses the HTML to create a structured representation.<br>*We then extract table data (rows and columns) and create a pandas DataFrame.</li><li><strong>Display and Navigate Extracted Tables (if any):<br></strong>*The extracted tables are stored in a list df_list.<br>*Streamlit’s session_state manages the current table index for navigation.<br>*We display the currently selected table using st.table.<br>*Buttons for “Previous” and “Next” tables are implemented using columns and button elements in Streamlit.</li></ol><p><strong>Running the App:</strong></p><ol><li>Save the code as a Python file (e.g., pdf_table_extractor.py).</li><li>Ensure you have LLMSherpa running with the specified API URL (http://127.0.0.1:5010/api/parseDocument?renderFormat=all).</li><li>Run the script using streamlit run pdf_table_extractor.py.</li><li>Upload a PDF containing tables, and the app will extract and display them, allowing you to navigate through multiple tables if present.</li></ol><p>And the app would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*n6HxepG50aPCCjnPQ48tBw.png" /></figure><p><strong>This is a basic example, but it demonstrates the potential of LLMSherpa and Streamlit for simplifying table extraction from PDFs. With further development, you can enhance this app with features like data cleaning or exporting the extracted data.</strong></p><p><strong>The Future of Document Understanding and LLMSherpa</strong></p><p>Document understanding tools hold immense potential for unlocking insights from various document formats. LLMSherpa paves the way for more accessible and powerful applications by simplifying PDF integration. As document understanding technology continues to evolve, LLMSherpa will likely adapt and expand its capabilities, making it an even more valuable tool for developers.</p><p><strong>Have you explored using document understanding tools with PDFs? Share your thoughts and experiences in the comments below!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f70d0ff8b7a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>