<?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 Rohit Raj on Medium]]></title>
        <description><![CDATA[Stories by Rohit Raj on Medium]]></description>
        <link>https://medium.com/@rohitraj-iit?source=rss-b91c54732ae6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qFP0zzX-w_090xQJ.</url>
            <title>Stories by Rohit Raj on Medium</title>
            <link>https://medium.com/@rohitraj-iit?source=rss-b91c54732ae6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:24:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohitraj-iit/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[I Built a Chrome Extension That Turns My Twitter Feed Into a Structured Intelligence Briefing]]></title>
            <link>https://rohitraj-iit.medium.com/i-built-a-chrome-extension-that-turns-my-twitter-feed-into-a-structured-intelligence-briefing-5ae91954fe24?source=rss-b91c54732ae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ae91954fe24</guid>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 13:21:12 GMT</pubDate>
            <atom:updated>2026-04-02T13:21:12.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rx0TcDquhXz-s3BvoVkgSQ.png" /></figure><h3><em>DOM scraping, free LLMs, and a presentation layer — here’s exactly how it works</em></h3><p>There’s a particular kind of exhaustion that comes from being a heavy Twitter user.</p><p>You open the app for five minutes. You emerge forty minutes later knowing vaguely that something happened in markets, something is happening in AI, and someone is very angry about something — but you can’t quite piece it together into a coherent picture. The algorithm optimizes for engagement, not comprehension. You’ve consumed a lot of noise and retained very little signal.</p><p>I got tired of it. So I built a tool to fix it.</p><h3>What It Does</h3><p>The extension has three distinct layers that run as a pipeline:</p><p><strong>1. Scroll and scrape your live feed</strong></p><p>The extension injects a content script into any x.com or twitter.com page and automatically scrolls it, collecting tweets as they load. It&#39;s fully configurable — you set the maximum tweet count, scroll delay, and how many idle rounds before it stops. It extracts tweet URL, author name, handle, timestamp, and text for every post it finds.</p><p><strong>2. Send the batch to an LLM for event and stance analysis</strong></p><p>The collected tweets are bundled into a structured prompt and sent to <a href="https://openrouter.ai/">OpenRouter</a> — which lets you route to dozens of models, including free-tier ones. The default model in the extension is stepfun/step-3.5-flash:free. The prompt asks the model to do two things: identify the major events being discussed across the feed, and for each event, classify every relevant tweet&#39;s <em>stance</em> — Support, Favour, Reporting, Critical, or Neutral — with a brief explanation of why.</p><p>The LLM returns structured JSON. Here’s the exact schema it’s asked to produce:</p><pre>{<br>  &quot;events&quot;: [<br>    {<br>      &quot;event_name&quot;: &quot;Name of the event&quot;,<br>      &quot;description&quot;: &quot;Brief summary of what happened&quot;,<br>      &quot;tweets&quot;: [<br>        {<br>          &quot;handle&quot;: &quot;@username&quot;,<br>          &quot;stance&quot;: &quot;Support/Favour/Critical/Neutral/Reporting&quot;,<br>          &quot;explanation&quot;: &quot;Why this stance was assigned&quot;<br>        }<br>      ]<br>    }<br>  ]<br>}</pre><p><strong>3. Render a full presentation view</strong></p><p>The analysis isn’t just dumped into the popup. There’s a full-page report that opens in a new tab — a proper editorial-style dashboard with a sidebar event index, stance breakdown chips, a “Support Spotlight” section that surfaces the most explicitly positive tweets, and aggregate stats across all events. It was designed to be presentation-ready, not just an export screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejU6HUR6UyqFx_E5-GVEbQ.png" /></figure><h3>The Part That Actually Took Time: DOM Scraping</h3><p>Every technical writeup about AI tools skips over the boring part. Here’s the boring part.</p><p>Twitter’s frontend is a React SPA with dynamic class names that can change at any time. There are no stable semantic selectors you can rely on long-term. The extension targets article[data-testid=&#39;tweet&#39;] — one of the few relatively stable data attributes Twitter has kept consistent. From there, extracting the handle requires navigating up and down the DOM tree: find the time element, walk to the closest status anchor, parse the URL pattern /username/status/xxx, fall back to the User-Name div if that fails, fall back to regex on inner text if that fails too.</p><p>The extension also has to handle SPA navigation. When you move between timelines without a full page reload, the content script is still running from the previous page. A MutationObserver watches for URL changes and resets collection state accordingly.</p><p>None of this is glamorous. But it’s the reason a naive version of this tool breaks constantly and this one doesn’t.</p><h3>Why Free-Tier LLMs Are Good Enough Here</h3><p>One of the deliberate choices in the extension is defaulting to a free model via OpenRouter rather than requiring a paid OpenAI key.</p><p>The analysis task isn’t asking for creativity or deep reasoning — it’s asking for structured extraction and classification over a batch of short texts. Free-tier models handle this well. The prompt enforces response_format: { type: &quot;json_object&quot; } to eliminate any risk of the model returning prose instead of parseable JSON, and wraps the parse in error handling so a malformed response doesn&#39;t crash the whole pipeline.</p><p>For most users, the API cost of this workflow is literally zero.</p><h3>What the Output Actually Looks Like</h3><p>After a typical 200-tweet collection run, the analysis surfaces roughly 5–10 distinct events being discussed across your feed — each with a tweet count, a stance breakdown, and individual explanations per tweet.</p><p>The Support Spotlight section is the most immediately useful part: it isolates the tweets where accounts you follow are explicitly endorsing or favouring something, which is a different signal from neutral reporting. If five people you trust are all supporting the same position on a market call or a product launch, that cluster is worth your attention.</p><p>The full presentation can also be loaded from any previously exported JSON file — so you can archive briefings and reload them later.</p><h3>The Broader Point</h3><p>A scraping layer, an NLP pipeline, a classification system, a JSON export, and a polished frontend dashboard: two years ago, this is a multi-week project.</p><p>The LLM handles almost the entire intelligence layer. I wrote glue code, a prompt, and a frontend. The model handles entity recognition, clustering, classification, and explanation generation. What remained was the “boring” engineering — reliable DOM traversal, edge case handling, SPA navigation — which is now the <em>interesting</em> part of the build, because it’s where the actual craft lives.</p><p>This changes the calculus on what’s worth building for personal use. Problems I used to dismiss as too much effort for a solo workflow are now tractable in an afternoon. That compounding shift is what I think people are still underestimating.</p><h3>Try It Yourself</h3><p>The full source is on GitHub: <a href="https://github.com/rohitrajiit/twitter2ext"><strong>github.com/rohitrajiit/twitter2ext</strong></a></p><p>To load it:</p><ol><li>Clone or download the repo</li><li>Open chrome://extensions and enable Developer Mode</li><li>Click “Load unpacked” and select the extension folder</li><li>Open any Twitter/X timeline and hit Start</li></ol><p>You’ll need a free <a href="https://openrouter.ai/">OpenRouter</a> API key for the analysis step. No paid tier required.</p><p><em>If you build on this or adapt it for a different feed — LinkedIn, Hacker News, a newsletter digest — I’d be curious to hear how the prompt holds up across different content types.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ae91954fe24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I learnt trying to write a novel using AI]]></title>
            <link>https://rohitraj-iit.medium.com/what-i-learnt-trying-to-write-a-novel-using-ai-383b3fb5fb8b?source=rss-b91c54732ae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/383b3fb5fb8b</guid>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 17:34:06 GMT</pubDate>
            <atom:updated>2026-03-14T17:34:06.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Meiv7lhmOrOY4FwwHQuw-g.png" /></figure><p>I’ve spent months trying to write a post-apocalyptic novel with an AI collaborator. Here’s what the process taught me about the difference between generating text and actually telling a story.</p><h3>The Idea</h3><p>I’m a programmer by inclination. I think in systems, in cause and effect, in branches that diverge and merge. So when I decided to write a novel, the first thing I did was map it like a codebase. Chapters were modules. Characters were objects with state. Plot was a dependency graph. And AI, I assumed, would be a very fast compiler.</p><p>The novel itself emerged from a deceptively simple question: <em>what happens to human society when all the electricity goes out — permanently?</em> A large solar flare strips the world of its electrical infrastructure. No internet, no motors, no supply chains. Within months, industrial civilisation folds, and humanity is left navigating a world that physically resembles the 19th century but carries the psychological memory of everything it has lost. The novel follows several characters navigating the unglamorous challenge of rebuilding meaning and structure in a world returned to pre-industrial conditions.</p><p>The story is rich with systemic questions — what breaks first, what holds together, how communities form under scarcity. These felt like exactly the kind of cause-and-effect problems a language model would be well-suited to reason about. I was partially right.</p><p>You can follow the work-in-progress here: <a href="https://github.com/rohitrajiit/Silent_Dawn_Novel">github.com/rohitrajiit/Silent_Dawn_Novel</a></p><h3>Novel Writing Looks a Lot Like Programming</h3><p>Once I started working, the structural similarities were striking. A plot is a directed graph. Every scene is a node with preconditions — what must have already happened — and consequences — what becomes possible next. Branch a character’s decision one way and you’ve forked your narrative like a Git branch, with all the merge conflicts that follow.</p><p>Cause and effect is everything. Just as a function call propagates through a call stack, a character’s trauma in chapter three reverberates through chapter seventeen. The logic has to be consistent. Continuity errors are bugs. A character who lost her hand in act one cannot casually carry a basket in act three.</p><p>This analogy also extends to modularity. Complex storylines benefit from the same decomposition instinct a programmer applies to unwieldy code: separate concerns, define clear interfaces between subplots, don’t let one thread pollute another. The instincts transfer surprisingly well.</p><h3>But There’s No Compiler for Fiction</h3><p>In programming, the compiler is merciless and honest. It will tell you exactly where your logic broke, on which line, with what error. You get feedback in milliseconds. There is a ground truth.</p><p>Fiction has no such oracle. When a chapter feels wrong — when the pacing drags, when a character’s motivation doesn’t hold up, when two plot threads contradict each other three chapters later — there’s no debugger to run. The only test suite is a human reader’s sense of coherence, which is slow, subjective, and hard to automate.</p><p>Working with AI amplified specific problems:</p><p><strong>Context window limits.</strong> A novel is long. You cannot fit it all into one session. The AI would write chapter eight with apparent confidence, unaware it was contradicting a detail established in chapter two — not because it was incapable, but because chapter two simply wasn’t in the window.</p><p><strong>No continuity enforcement.</strong> In code, a typed interface catches a mismatch between modules. In prose, a character’s eye colour quietly changes between chapters and nothing flags it. The mixing of plot threads and timelines happens silently.</p><p><strong>No verification step.</strong> After writing a function, you run it. After writing a chapter, you have nothing but your own rereading — which is fallible, especially when you’ve been staring at the same text for hours.</p><p>The gap between coding and writing, in this sense, is the gap between a discipline with ground truth and one without it.</p><h3>Words Are Not Feelings</h3><p>This is where the comparison to programming breaks down most profoundly. Code that runs correctly is, by definition, correct code. But prose that is grammatically sound, narratively consistent, and structurally coherent can still be completely lifeless.</p><p>Reading a great novel is like travelling through space and time. The AI can plot the journey — it cannot make you feel the gravity.</p><p>A great novel doesn’t just convey events — it creates a pressurised interior world that the reader inhabits. When you read Chekhov or Tolstoy, something peculiar happens: you forget you’re reading. You feel the temperature of the room, the weight of a silence between two characters, the particular quality of a winter afternoon’s light. This is not information transfer. It’s something closer to transportation.</p><p>AI-generated prose, in my experience, tends to be accurate but not immersive. It reports events rather than inhabiting them. Characters perform emotions rather than experiencing them. The AI captures plot — the skeleton of story — but struggles to fill it with the soft tissue that makes a reader feel they’ve gone somewhere and returned changed.</p><p>This is not a failure of intelligence. It may be a failure of something harder to define: a model trained on descriptions of experience lacks the accumulation of lived experience that a human writer draws from unconsciously. The specific texture of grief, of longing, of embarrassment — the AI has read about these states extensively, but there is a real question of whether that reading has been metabolised into something that can be written from the inside.</p><h3>Why Writing Lags Behind Coding in AI Progress</h3><p>In the last few years, AI has transformed software engineering at a visible pace. The improvement is fast and measurable — there are benchmarks, tests, real-world deployments that confirm the gains.</p><p>The improvement in creative writing has been slower and harder to see. I think this reflects something structural about the two domains.</p><p>Code has ground truth. A function either returns the correct value or it doesn’t. AI coding models can therefore be trained on feedback signals that are sharp and objective. Literary quality has no equivalent oracle. “This is beautiful prose” is not a signal you can compute. The reward model for creative writing is fundamentally squishy — it lives in the aesthetic responses of human readers, which are variable, contextual, and resistant to formalisation.</p><p>Progress in writing quality will require something harder than better benchmarks. It may require new ways of thinking about what the training signal even is.</p><h3>How I Actually Built This</h3><p>Given the constraints, I had to engineer around them. The system I settled on was deliberately modular:</p><p><strong>Model: Claude Opus 4.5 under extended thinking.</strong> For complex narrative decisions — cause-and-effect chains spanning multiple chapters, world-building consistency — the deeper reasoning made a genuine difference over standard mode.</p><p><strong>Separate file per chapter.</strong> Each chapter lived in its own file. This kept context focused and enforced modularity. When writing a chapter, the relevant context was loaded explicitly rather than hoping the model would recall it from a long scroll.</p><p><strong>Individual character timeline files.</strong> Each major character had a dedicated timeline document — a chronological log of where they were, what they knew, what had changed for them. This served as a continuity bible and was injected as context when writing scenes involving that character.</p><p><strong>A master plot file.</strong> A single source of truth for the novel’s overall arc, major turning points, and world-building rules. Referenced at the start of each session to anchor the AI in the larger structure.</p><p><strong>Manual continuity review.</strong> After any session that introduced new events, the affected timeline files were updated by hand. Treating consistency as a first-class concern, not an afterthought.</p><p>The architecture that worked was less about prompting and more about information management — deciding, carefully, what context the model needed and when.</p><h3>What This Experiment Is Actually About</h3><p>Writing a novel with AI is a useful mirror for understanding what AI currently is and isn’t. It is a remarkable system-builder and a competent logician. It can hold a large, complex structure in mind and reason about it carefully. It can generate fluent prose that covers enormous amounts of narrative ground.</p><p>What it cannot do — or cannot yet do reliably — is make you feel as though you’ve lived inside another world for the duration of reading. That peculiar, irreplaceable experience of literature is still, somehow, beyond the reach of the machine.</p><p>The experiment continues. The novel isn’t finished. And I’m still not sure whether the final draft will be a novel in the truest sense, or a very well-organised synopsis dressed in chapters. The answer to that question might tell us something important about what stories actually are.</p><p><em>Silent Dawn is a work in progress. The repository is open: </em><a href="https://github.com/rohitrajiit/Silent_Dawn_Novel"><em>github.com/rohitrajiit/Silent_Dawn_Novel</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=383b3fb5fb8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Inconsistency is a Feature, Not a Bug]]></title>
            <link>https://rohitraj-iit.medium.com/your-inconsistency-is-a-feature-not-a-bug-48e9d496981e?source=rss-b91c54732ae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/48e9d496981e</guid>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Sat, 07 Feb 2026 15:01:30 GMT</pubDate>
            <atom:updated>2026-02-07T15:01:30.079Z</atom:updated>
            <content:encoded><![CDATA[<p>We are living in the Golden Age of Guilt.</p><p>You know the feeling. You wake up, check your phone, and are immediately bombarded by the &quot;High-Performance&quot; brigade. The 5 AM Club. The Atomic Habit builders. The Tech Bros meditating in ice baths. They all have the same message: Consistency is King.</p><p>If you aren&#39;t grinding 24/7, if you abandoned that hobby you started last month, or if you can’t focus on a spreadsheet for four hours straight, you are told you are broken. You lack &quot;grit.&quot; You need to buy another book to fix your &quot;laziness.&quot;</p><p>But what if I told you that the self-help industry is gaslighting you?</p><p>What if your inconsistency, your fickleness, and your refusal to stick to the plan aren&#39;t moral failings—but the very biological features that keep our species alive?</p><p>1. The &quot;Death Spiral&quot; of Perfect Discipline<br>We tend to think of discipline as the ultimate virtue. But in nature, perfect discipline is often a suicide pact.</p><p>Take the Army Ant. These ants are the most disciplined creatures on earth. They follow the pheromone trail of the leader with zero questions and zero deviation. It works great—until the leader accidentally loops back on its own trail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SE5JPKWccRYi1WlTxddLSQ.jpeg" /></figure><p>When this happens, the ants enter an Ant Mill. They march in a perfect, disciplined circle until they die of exhaustion. They lack the cognitive flexibility to stop, look around, and say, &quot;Hey, this isn&#39;t working.&quot;</p><p>Or consider the Sea Turtle. For millions of years, hatchlings followed a strict rule: Move toward the brightest light. It used to be the moon. Now, it’s streetlights. Because they cannot override their programming, they march disciplinedly into traffic.</p><p>Blind consistency is an evolutionary trap. When you &quot;quit&quot; a project halfway through or suddenly change your career path, you aren&#39;t being weak. You are avoiding the Death Spiral. You are executing a human &quot;override command&quot; because your brain realized the environment has changed.</p><p>2. Evolution Loves a Screw-Up<br>If DNA were perfectly disciplined—if it copied itself with 100% accuracy every time—we would all still be single-celled amoebas.</p><p>Evolution is literally driven by a lack of discipline. It relies on genetic &quot;copying errors&quot; (mutations).</p><p>The &quot;disciplined&quot; genes copied the old code perfectly.</p><p>The &quot;sloppy&quot; genes made a mistake and accidentally created a thumb, or a bigger brain, or the ability to digest milk.</p><p>When the Ice Age hit, the &quot;disciplined&quot; populations who stayed in the fertile valley and refused to move? They died. The human species was saved by the malcontents—the restless, fickle wanderers who couldn&#39;t sit still and walked into the unknown.</p><p>Your refusal to &quot;fit in&quot; or &quot;settle down&quot; isn&#39;t a bug. It’s the genetic variance that insures our species against extinction.</p><p>3. You Are Not Lazy, You Are &quot;Undomesticated&quot;<br>Why is the self-help industry a multi-billion dollar juggernaut? Because it is selling medication for a lifestyle we aren&#39;t designed for.</p><p>We diagnose ourselves with &quot;short attention spans&quot; because we can&#39;t stare at a screen for 8 hours. But in the wild, hyper-focus gets you killed. If a deer ignores the snapping twig because it is &quot;deeply focused&quot; on grazing, it gets eaten. Your &quot;distractibility&quot; is actually high situational awareness.</p><p>We call ourselves &quot;lazy&quot; because we procrastinate. But nature favors energy conservation. A lion doesn&#39;t run laps to hit 10,000 steps; it sleeps until it needs to hunt. Your body resisting &quot;the grind&quot; is just your biology screaming that burning calories for no immediate reward is stupid.</p><p>The Takeaway<br>The reason you struggle to be a robot is that you are not a machine.</p><p>Machines are consistent. Machines are disciplined. But machines are also fragile. If you change the inputs, the machine breaks.</p><p>Humans are messy. We are fickle. We contradict ourselves. And that is why we win.</p><p>So, the next time you feel guilty for pivoting, for quitting, or for spending a day doing absolutely nothing—stop. You aren&#39;t failing at being a worker. You are succeeding at being human.</p><p>Stop trying to fix your nature. Start trusting your override switch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48e9d496981e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Death of Originality]]></title>
            <link>https://rohitraj-iit.medium.com/death-of-originality-7976030f66f6?source=rss-b91c54732ae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7976030f66f6</guid>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 17:48:28 GMT</pubDate>
            <atom:updated>2024-12-26T18:05:20.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7PIgV0jFYc2n36rS_us8XQ.jpeg" /></figure><p>Sorry for this AI-generated image. Otherwise, nobody will read this article.</p><p>I opened my medium feed. There was not even a single article that was not just a variation of an existing idea.</p><p>I opened Instagram, people want to visit the most trending places or make reels on the same audio on which already 10000 people have made reels.</p><p>Open X. People will keep posting and commenting on the same topic on which everyone else has made 10000 comments.</p><p>Open News website, every news website will report on the same 10 -20 stories on which everybody else is reporting.</p><p>Despite more than four billion people connecting through social media. People are more lonelier than ever.</p><p>Despite widely accessible information, people are drowning in misinformation. Now elections are a competition on who can spread more disinformation.</p><p>Now Generative AI is only making this problem even worse. To avoid paying money, news websites increasingly use AI-generated images in their articles.</p><p>It is like information is being generated at explosive pace. But under gravity of its own mass, information is collapsing towards 10 relevant topics of the day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKfUe5CunXJQ0iMV_P1T4g.jpeg" /></figure><p>For wonder, despite access to tens of thousands of movies and series, people still watch the trash movie released this week.</p><p>One of the key reasons behind this is Social media algorithms. They actively reward uniformity. When a post “goes viral,” the platforms elevate similar content to feed users more of what has already proven to engage. In effect, this encourages creators to replicate formulas that already work — same reels audio, same trending topics, same clickbait headlines — because that’s how you get seen.</p><p>With an avalanche of information at our fingertips, many people feel overwhelmed. In that exhaustion, they return to what’s familiar or trending rather than exploring the obscure corners of the internet. People watch “the trash movie released this week” not because it’s necessarily good, but because it’s what everyone else is talking about and it’s easy to join the conversation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7976030f66f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why AGI is close yet so Far Away]]></title>
            <link>https://rohitraj-iit.medium.com/why-agi-is-close-yet-so-far-away-51373309c3ab?source=rss-b91c54732ae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/51373309c3ab</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[agi]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 11:23:04 GMT</pubDate>
            <atom:updated>2024-12-09T06:42:45.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5SlRGw9yufyqMYebX461w.png" /></figure><p>I have long been fascinated by computer chess programs. Today’s top engines — Stockfish and Leela Chess Zero — are marvels of machine learning and computational efficiency. They evaluate positions with astonishing depth, often looking more than forty moves ahead. By contrast, even world-class grandmasters struggle to consistently see more than seven or eight moves deep, and the average chess enthusiast can barely manage two or three moves before losing track. Yet despite their near-“godlike” skill in this narrow domain, these engines still make mistakes against each other. Even with extraordinary processing power and perfected algorithms, the complexity of chess ensures occasional inaccuracies.</p><p>What makes chess noteworthy is its tight constraints. Chess is a closed system: it has strictly defined rules, limited possible moves, and a binary outcome — win, lose, or draw. This bounded nature allows programs to train on billions of self-play games, and from these experiences directly map sequences of moves to final results.</p><p>But real life is unimaginably more complex. Instead of a neatly defined set of moves, there are countless possibilities unfolding at every moment. Actions in life seldom have universally agreed-upon evaluation metrics. A choice that seems beneficial in one context might be harmful in another; a short-term gain could produce long-term catastrophe. Unlike chess, the “game” of reality does not present consistent, limited data or clear-cut success criteria.</p><p>This is why we remain far from achieving Artificial General Intelligence (AGI). Current Large Language Models (LLMs), like GPT-4, are trained by predicting the next word in text. Language, while richly expressive, is still much more constrained than open-ended reality. Its vocabulary and structures are finite, enabling LLMs to master pattern recognition and synthesis within textual data. But to surpass human intelligence in a general sense, AI would need to train on environments more complex than anything humans have fully understood, let alone digitized.</p><p>Here we encounter another often-overlooked factor: we underestimate the complexity of human intelligence itself. True, it might be easy to imagine an AI outcalculating the average person in certain tasks. But human society’s collective intelligence has achieved feats that beggar belief: we have journeyed into space, manipulated matter at scales smaller than atoms, and built microchips with billions of transistors. None of this was achieved by a single mind; it required thousands of layers of abstract reasoning developed across decades by some of our brightest thinkers, all building on the knowledge of those who came before. For an AGI to truly benefit human society at a meaningful level, it must not simply outpace the average individual — it must match or surpass the collaborative, cumulative genius of our entire civilization.</p><p>So far, the most remarkable AI advances beyond GPT-4’s capabilities have come from well-structured scientific and mathematical domains. Areas like mathematics, physics, chemistry, and coding present clearer rules and well-defined objectives. OpenAI’s O1 models, for instance, introduced around September, significantly improved reasoning in math and coding by carefully scaling inference compute and encouraging the model to think through multiple “layers” before answering. They sometimes take minutes to consider a complex problem, resulting in more accurate and inventive solutions.</p><p>Another landmark example is DeepMind’s AlphaFold, which tackled the protein folding problem. Though biological systems are complex, the prediction of protein structures still fits into a scientific framework with rigorous criteria for success. This allowed machine learning — augmented by reinforcement learning — to achieve a dramatic breakthrough in a domain long considered one of biology’s grand challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*8U1yyKh_Aq0cXd7RIrOzuw.jpeg" /></figure><p>However, the success in these specialized areas does not readily translate to the open complexity of social, economic, and moral decision-making. The presence of clearly defined goals and success metrics enables AI to improve and even exceed human capabilities in narrow tasks. But outside these niches, the constraints vanish and reliable evaluation becomes murky. Without structured data or a coherent method to judge progress, training AGI remains an elusive goal.</p><p><strong>Conclusion</strong></p><p>In the journey toward AGI, we find ourselves simultaneously closer than ever before and yet still profoundly distant. We can develop models that outperform humans on specialized tasks — chess, mathematics, protein folding, coding — and these feats grow more impressive by the day. But to reach true general intelligence, to surpass not just the average human but the collective intellectual might of our global society, AI must grapple with complexity that defies neat quantification. It’s one thing to solve equations or predict protein structures; it’s another to navigate the tangled webs of real life and achieve lasting, broadly beneficial outcomes.</p><p>This chasm will not be bridged by sheer scale of data or compute alone. It demands new training paradigms, careful evaluation methods, and perhaps entirely new understandings of what intelligence and knowledge really mean. Until we can successfully encode and navigate the open-ended intricacies of the real world — or develop creative methods that allow AI to learn and reason beyond predefined rules — AGI will remain a distant beacon, enticing and unreachable, shining just beyond the edge of our current understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51373309c3ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A gentle introduction to OpenAI Swarm Library]]></title>
            <link>https://rohitraj-iit.medium.com/a-gentle-introduction-to-openai-swarm-library-a56c778f93bd?source=rss-b91c54732ae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a56c778f93bd</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 18:01:43 GMT</pubDate>
            <atom:updated>2025-07-30T13:23:00.033Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to make agent using OpenAI Swarm library</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-9HpDqstT2OZwmRFNe0zg.png" /></figure><p>A few days back OpenAI management conducted an AMA session on Reddit. Sam Altman said in that session that the use of agents will be a major use case for LLMs in 2025.</p><p>In this article I explain how to create agents using OpenAI library.</p><p>LLMs are already quite capable. Major companies are working to make them more reliable as an agent. If you want to implement an Agent by yourself, you can use Structured output and Function Calling features in OpenAI API. To make it easier to implement agents using these features, OpenAI launched Swarm library.</p><p><a href="https://github.com/openai/swarm">GitHub - openai/swarm: Educational framework exploring ergonomic, lightweight multi-agent orchestration. Managed by OpenAI Solution team.</a></p><p>Swarm Libary makes heavy use of Function Calling feature in OpenAI API. So before reading up Swarm library I will recommend reading up on OpenAI Function Calling feature.</p><p><a href="https://platform.openai.com/docs/guides/function-calling">https://platform.openai.com/docs/guides/function-calling</a></p><p>Despite its name, function calling does not directly invoke any function itself. Instead, you provide a list of available tools (functions) within a chat completion request through the OpenAI Chat API. This setup includes passing function definitions alongside the user prompt. If the language model determines that a response to the user’s prompt requires using one of these tools, its reply will include a function call along with the necessary arguments</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEUbS0y_eYJysQWiAK1LgA.png" /></figure><p>Now OpenAI Swarm library takes it a step further. It introduces the concept of agent. Each agent can have its own custom prompt, message history, context variables and available tools.</p><p>When the Swarm agent’s run method is called, it performs the following steps:</p><ol><li>It makes an API request to the OpenAI chat completion endpoint, including the agent’s tools (Python functions), message history, and the user’s prompt.</li><li>If the OpenAI API returns text output, this output is sent back to the user and added to the message history.</li><li>The agent’s tools must be Python functions. If a function has arguments beyond context variables, the API will return a function call with the necessary argument values. If an argument’s value can’t be inferred from the user input, the language model will prompt for the missing information.</li><li>The Swarm agent executes any function calls returned by the language model. If a function only uses context variables, those are the only arguments passed.</li><li>The function’s return type determines the next steps:<br> • If the function returns a Result object (from the Swarm library), the Result.value is added to the message history. The Result.context_variables contain the updated context, which is then set as the new context variables. After handling all function calls, the OpenAI chat completion endpoint is called again.<br> • If the function returns an Agent, the message history is passed to that agent, and the OpenAI chat completion endpoint is called again with the new agent’s instructions and tools.</li><li>Finally, the agent provides a response object containing the agent’s response and any updated context variables.</li></ol><p><strong>Stock Price Agent</strong></p><p>I have used the library to implement an Agent for analysis of stock price data.</p><ol><li>First import necessary libraries and helper function</li></ol><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import requests<br>from swarm import Swarm<br>from swarm.types import Result<br>import json<br>from swarm import Agent<br><br>def pretty_print_messages(messages) -&gt; None:<br>    for message in messages:<br>        if message[&quot;role&quot;] != &quot;assistant&quot;:<br>            continue<br><br>        # print agent name in blue<br>        print(f&quot;\033[94m{message[&#39;sender&#39;]}\033[0m:&quot;, end=&quot; &quot;)<br><br>        # print response, if any<br>        if message[&quot;content&quot;]:<br>            print(message[&quot;content&quot;])<br><br>        # print tool calls in purple, if any<br>        tool_calls = message.get(&quot;tool_calls&quot;) or []<br>        if len(tool_calls) &gt; 1:<br>            print()<br>        for tool_call in tool_calls:<br>            f = tool_call[&quot;function&quot;]<br>            name, args = f[&quot;name&quot;], f[&quot;arguments&quot;]<br>            arg_str = json.dumps(json.loads(args)).replace(&quot;:&quot;, &quot;=&quot;)<br>            print(f&quot;\033[95m{name}\033[0m({arg_str[1:-1]})&quot;)</pre><p>2. Define context variables and helper functions</p><pre>context_variables ={&quot;ISIN&quot;:&quot;&quot;,&quot;data&quot;:&quot;&quot;}<br>def plotopenprice(ISIN,todate,fromdate):<br>    url = f&#39;https://api.upstox.com/v2/historical-candle/NSE_EQ%7C{ISIN}/day/{todate}/{fromdate}&#39;<br>    headers = {<br>                &#39;Accept&#39;: &#39;application/json&#39;<br>              }<br>    <br>    response = requests.get(url, headers=headers)<br>    data= response.json()<br>    df = data[&#39;data&#39;][&#39;candles&#39;]<br>    df = pd.DataFrame(df,columns=[&#39;Date&#39;,&#39;Open&#39;,&#39;High&#39;,&#39;Low&#39;,&#39;Close&#39;,&#39;Volume&#39;,&#39;OpenInterest&#39;])<br>    df[&#39;Date&#39;] = pd.to_datetime(df[&#39;Date&#39;]) <br>    df.set_index(&#39;Date&#39;, inplace=True)<br>    df[&#39;Open&#39;].plot()<br>    plt.xlabel(&quot;Date&quot;)<br>    plt.ylabel(&quot;Open&quot;)<br>    plt.show()<br>    return Result(value=str(df[&quot;Open&quot;][-1]),context_variables={&#39;ISIN&#39;:ISIN,&#39;data&#39;:df})<br><br>def averageprice(context_variables):<br>    return context_variables[&#39;data&#39;][&#39;Open&#39;].mean()<br><br>def miniumumprice(context_variables):<br>    return context_variables[&#39;data&#39;][&#39;Open&#39;].min()<br><br>def maximumprice(context_variables):<br>    return context_variables[&#39;data&#39;][&#39;Open&#39;].max()<br><br>def returnisin(context_variables):<br>    return context_variables[&quot;ISIN&quot;]</pre><p>3. Insantiate our Agent</p><pre>upstox_agent = Agent(<br>    name=&quot;Upstox Agent&quot;,<br>    instructions=&quot;You are a helpful agent.&quot;,<br>    functions=[plotopenprice, averageprice, miniumumprice, maximumprice, returnisin],<br>    context_variables=context_variables,<br>)</pre><p>4 Run event loop</p><pre>client = Swarm()<br>print(&quot;Starting Swarm CLI 🐝&quot;)<br><br>messages = []<br>agent = upstox_agent<br>stream = False<br><br>while True:<br>    user_input = input(&quot;\033[90mUser\033[0m: &quot;)<br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input})<br><br>    response = client.run(<br>        agent=agent,<br>        messages=messages,<br>        context_variables=context_variables or {},<br>        stream=stream,<br>        debug=False,<br>    )<br><br>    if stream:<br>        response = process_and_print_streaming_response(response)<br>    else:<br>        pretty_print_messages(response.messages)<br><br>    messages.extend(response.messages)<br>    agent = response.agent<br>    context_variables= response.context_variables<br>    print(context_variables)</pre><p>Swarm library has run_demo_loop function for running an agent in a loop. But it has a bug. It does not update context variables after each loop. So I wrote a modified agent loop as above.</p><p>a. Running the agent , I can fetch stock price data using chat</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKT_ZrDauFe4B1yPvSUqFQ.png" /></figure><p>b. The tools of agent have access to context variables as seen from the following call</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h9cUQDa_3oJjeVIw4p0-oQ.png" /></figure><p>c. Stock price data is plotted in part a. I can do operations on it using the tools of agents</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zR5cjK3Z4MmgYeqCyHDK4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vh5M_mOnRWckUR2LNoUyFA.png" /></figure><p>One thing to note is that context variables are not passed to OpenAI API. So you can use agents to do complicated operations on big data without triggering significant API costs.</p><p>d. This stock price agent can be further worked upon. We can let know for which stock price data is available. So agent will download stock price data only if it is not available. We can refactor context variables to hold data for multiple stocks so that we can do even more complicated operations across multiple scrips etc.</p><p>This straightforward example demonstrates how to create agents using the OpenAI library. In the future, a company’s competitive edge may hinge on the quality of its AI agents.</p><p>If you liked the article please clap and subscribe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a56c778f93bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to do Voice Cloning in Python]]></title>
            <link>https://rohitraj-iit.medium.com/how-to-do-voice-cloning-in-python-dfaa610cb873?source=rss-b91c54732ae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfaa610cb873</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 11:54:47 GMT</pubDate>
            <atom:updated>2024-10-31T11:54:47.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1BzmSfD6yOgBUB6qtqkXA.png" /></figure><p>Voice cloning has become so easy now that you should not believe authenticity of audio.</p><p>A Few weeks back, the F5-TTS library was launched, making it very clone with only 15 second voice sample.</p><p><a href="https://github.com/SWivid/F5-TTS">GitHub - SWivid/F5-TTS: Official code for &quot;F5-TTS: A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching&quot;</a></p><p>You can follow the following steps to clone voice</p><ol><li>Run following commands in command shell to install the library</li></ol><pre>conda create -n f5-tts python=3.10<br>conda activate f5-tts<br><br># Install pytorch with your CUDA version, e.g., if this fails library will run on CPU<br>pip install torch==2.3.0+cu118 torchaudio==2.3.0+cu118 --extra-index-url https://download.pytorch.org/whl/cu118<br><br>pip install git+https://github.com/SWivid/F5-TTS.git</pre><p>2 Run the following command to launch the Gradio UI</p><pre>f5-tts_infer-gradio</pre><p>Now navigate to <a href="http://localhost:3000/">http://localhost:7860/</a> on your browser. You have to upload 15 second long source audio. And type text to convert to speech. It will generate audio for your text in source audio voice. I tried it for my wife voice. It was genuinely scary, how good was the output.</p><p>Instead of using Gradio UI, you can it following command line tool</p><pre># Leave --ref_text &quot;&quot; will have ASR model transcribe (extra GPU memory usage)<br>f5-tts_infer-cli \<br>--model &quot;F5-TTS&quot; \<br>--ref_audio &quot;ref_audio.wav&quot; \<br>--ref_text &quot;The content, subtitle or transcription of reference audio.&quot; \<br>--gen_text &quot;Some text you want TTS model generate for you.&quot;</pre><p>You can also use its command line tool to generate audio containing more than one voice.</p><p>For this you have to create .toml line in following format</p><pre># F5-TTS | E2-TTS<br>model = &quot;F5-TTS&quot;<br>ref_audio = &quot;infer/examples/multi/main.flac&quot;<br># If an empty &quot;&quot;, transcribes the reference audio automatically.<br>ref_text = &quot;&quot;<br>gen_text = &quot;&quot;<br># File with text to generate. Ignores the text above.<br>gen_file = &quot;infer/examples/multi/story.txt&quot;<br>remove_silence = true<br>output_dir = &quot;tests&quot;<br><br>[voices.town]<br>ref_audio = &quot;infer/examples/multi/town.flac&quot;<br>ref_text = &quot;&quot;<br><br>[voices.country]<br>ref_audio = &quot;infer/examples/multi/country.flac&quot;<br>ref_text = &quot;&quot;</pre><p>You have to text to generate in following format. You should mark the voice with [main] [town] [country] whenever you want to change voice.</p><pre>A Town Mouse and a Country Mouse were acquaintances, and the Country Mouse one day invited his friend to come and see him at his home in the fields. The Town Mouse came, and they sat down to a dinner of barleycorns and roots, the latter of which had a distinctly earthy flavour. The fare was not much to the taste of the guest, and presently he broke out with [town] “My poor dear friend, you live here no better than the ants. Now, you should just see how I fare! My larder is a regular horn of plenty. You must come and stay with me, and I promise you you shall live on the fat of the land.” [main] So when he returned to town he took the Country Mouse with him, and showed him into a larder containing flour and oatmeal and figs and honey and dates. The Country Mouse had never seen anything like it, and sat down to enjoy the luxuries his friend provided: but before they had well begun, the door of the larder opened and someone came in. The two Mice scampered off and hid themselves in a narrow and exceedingly uncomfortable hole. Presently, when all was quiet, they ventured out again; but someone else came in, and off they scuttled again. This was too much for the visitor. [country] “Goodbye,” [main] said he, [country] “I’m off. You live in the lap of luxury, I can see, but you are surrounded by dangers; whereas at home I can enjoy my simple dinner of roots and corn in peace.”</pre><p>Then you have to pass your toml file to tool using following command</p><pre>f5-tts_infer-cli -c custom.toml</pre><p>I would request you to not use this library for spamming. But people need to be aware what existing machine learning tools are capable of.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfaa610cb873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: Optical Character Recognition Using Zerox library]]></title>
            <link>https://blog.gopenai.com/part-2-optical-character-recognition-using-zerox-library-aef7d8c39bab?source=rss-b91c54732ae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/aef7d8c39bab</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 16:43:39 GMT</pubDate>
            <atom:updated>2024-10-31T17:40:22.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdICm0hw9NkL88bvLq7FrA.jpeg" /></figure><p>Few days back I wrote about how PaddleOCR is state of art in OCR but LLMs are increasingly being used for OCR.</p><p><a href="https://medium.com/@rohitraj-iit/optical-character-recognition-in-python-e430e0657c67">https://medium.com/@rohitraj-iit/optical-character-recognition-in-python-e430e0657c67</a></p><p>Few days Y-Combinator CEO tweeted about Zerox library as being the best OCR product.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/garrytan/status/1851397770198052869&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2629512fd3060a7ae227ac8ef41b0ae/href">https://medium.com/media/a2629512fd3060a7ae227ac8ef41b0ae/href</a></iframe><p><a href="https://github.com/getomni-ai/zerox">GitHub - getomni-ai/zerox: Zero shot pdf OCR with gpt-4o-mini</a></p><p>This library uses vision capabilities of LLM to extract text and content from PDF files and generate output in markdown format.</p><p>I tested the library on the following document. It is a SEBI master circular. It is a complicated PDF containing a lot of table content.</p><p><a href="https://www.sebi.gov.in/legal/master-circulars/sep-2024/master-circular-on-surveillance-of-securities-market_86929.html">Master Circular on Surveillance of Securities Market</a></p><p><strong>Library Installation</strong></p><p>First I installed the python version of library using</p><pre>pip install py-zerox</pre><p>Before installing the library you have to check if you have poppler-utils installed. You can check by running following command in shell</p><pre>pdftotext -v</pre><p>On my MacBook I installed it by using the following command</p><pre>brew install poppler</pre><p>Then I run OCR using the following code</p><pre><br><br>from pyzerox import zerox<br>import os<br>import json<br>import asyncio<br><br>###################### Example for OpenAI ######################<br>model = &quot;gpt-4o-mini&quot; ## openai model<br>os.environ[&quot;OPENAI_API_KEY&quot;] = &#39;paste your key here&#39;<br>file_path= &#39;/Users/rohitraj/Downloads/1720528330792.pdf&#39;<br><br>## placeholder for additional model kwargs which might be required for some models<br>kwargs = {}<br><br>## system prompt to use for the vision model<br>custom_system_prompt = None<br><br># Define main async entrypoint<br>async def main():<br>    ## process only some pages or all<br>    select_pages = None ## None for all, but could be int or list(int) page numbers (1 indexed)<br><br>    output_dir = &quot;./output_test&quot; ## directory to save the consolidated markdown file<br>    result = await zerox(file_path=file_path, model=model, output_dir=output_dir,<br>                        custom_system_prompt=custom_system_prompt,select_pages=select_pages, **kwargs)<br>    return result<br><br><br># run the main function:<br>result = asyncio.run(main())<br><br># print markdown result<br>print(result)</pre><p>For my input pdf of 28 pages, it made 29 requests to OpenAI 4o mini API and used 715,000 input tokens and 10000 output tokens</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHKNC3yt1iCq5Ynki4sdFw.png" /></figure><p>For GPT 4o mini it costed me 0.11 dollar for pdf. It is quite expensive even with GPT 4o mini. If I had used GPT 4o it would have costed quite a bit more.</p><p>Output of the library is quite good. But it is much more costly and slower than PaddleOCR.</p><p>If it is worth your money depends upon how complicated your PDF is. As PaddleOCR does not extract table data properly. But using LLM calls on pdf pages sans table content is quite an overkill.</p><p>You can go through it and see if output of library is useful to you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/090fd8cf5c71c2ba2afc1cb838fb2e78/href">https://medium.com/media/090fd8cf5c71c2ba2afc1cb838fb2e78/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aef7d8c39bab" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/part-2-optical-character-recognition-using-zerox-library-aef7d8c39bab">Part 2: Optical Character Recognition Using Zerox library</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optical Character Recognition in Python]]></title>
            <link>https://rohitraj-iit.medium.com/optical-character-recognition-in-python-e430e0657c67?source=rss-b91c54732ae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e430e0657c67</guid>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 06:26:11 GMT</pubDate>
            <atom:updated>2024-10-30T16:27:36.948Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1: Optical Character Recognition in Python</h3><p>PaddleOCR is the best open-source library for Optical character recognition. But if you want output in structured format you can use existing LLMs. In this article I will show how to do Optical Character Recognition using both PaddleOCR and Claude Sonnet.</p><ol><li>PaddleOCR</li></ol><p>First install libraries</p><pre>pip install paddleocr<br>pip install paddlepaddle</pre><p>Then you can do OCR using following code</p><pre>from paddleocr import PaddleOCR, draw_ocr<br>import cv2<br><br># Initialize the OCR model with the desired language<br>ocr = PaddleOCR(use_angle_cls=True, lang=&#39;en&#39;)  # Set &#39;lang&#39; based on the language you want<br><br># Run inference on an image<br>img_path = &#39;path_to_your_image.jpg&#39;<br>result = ocr.ocr(img_path, cls=True)<br><br># Display the result<br>for line in result:<br>    print(line)<br><br># Optional: Draw the detected text on the image<br>image = cv2.imread(img_path)<br>boxes = [line[0] for line in result[0]]<br>texts = [line[1][0] for line in result[0]]<br>scores = [line[1][1] for line in result[0]]<br><br># Draw and display the image with detected text<br>from paddleocr import draw_ocr<br>image_with_boxes = draw_ocr(image, boxes, texts, scores)<br>cv2.imshow(&quot;OCR Result&quot;, image_with_boxes)<br>cv2.waitKey(0)</pre><p>2. Claude Sonnet</p><p>First install libraries</p><pre>pip install anthropic</pre><p>Then obtain API key from claude website and initialise anthropic client</p><pre>import anthropic<br><br>client = anthropic.Anthropic(api_key= ANTHROPIC_API_KEY)</pre><p>Then you can OCR using following code</p><pre>import os<br>import base64<br>import anthropic<br><br>client = anthropic.Anthropic(api_key= ANTHROPIC_API_KEY)<br><br># Function to encode the image<br>def encode_image(image_path):<br>  with open(image_path, &quot;rb&quot;) as image_file:<br>    return base64.b64encode(image_file.read()).decode(&#39;utf-8&#39;)<br><br>img_path = &#39;path_to_your_image.jpg&#39;<br><br>base64_image = encode_image(img_path)<br>message = client.messages.create(<br>    model=&quot;claude-3-5-sonnet-20240620&quot;,<br>    max_tokens=1024,<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: [<br>                {<br>                    &quot;type&quot;: &quot;image&quot;,<br>                    &quot;source&quot;: {<br>                        &quot;type&quot;: &quot;base64&quot;,<br>                        &quot;media_type&quot;: f&quot;image/{img_path.split(&#39;.&#39;)[-1]}&quot;,<br>                        &quot;data&quot;: base64_image,<br>                    },<br>                },<br>                {<br>                    &quot;type&quot;: &quot;text&quot;,<br>                    &quot;text&quot;: &quot;Return text in this image&quot;<br>                }<br>            ],<br>        }<br>    ],<br>)<br>print(message.content[0].text)</pre><p>If you are only extracting text then paddleOCR is better. But for extracting tables or structured data, Claude Sonnet or any other equivalent LLM will be better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e430e0657c67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get Unique Count in Excel]]></title>
            <link>https://rohitraj-iit.medium.com/how-to-get-unique-count-in-excel-0f41e25dafa9?source=rss-b91c54732ae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f41e25dafa9</guid>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[vba]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 14:12:03 GMT</pubDate>
            <atom:updated>2024-09-12T14:12:03.409Z</atom:updated>
            <content:encoded><![CDATA[<p>If like me you are stuck with Excel version&lt;2021, then getting distinct counts in a range is an never-ending challenge.</p><p>For just getting unique values in a single column this article lists out several ways to get unique count</p><p><a href="https://www.ablebits.com/office-addins-blog/count-distinct-unique-values-excel/">Count unique and distinct values in Excel with formula or pivot table</a></p><p>But if you want to use a formula to get unique count in range where we want to filter based on certain conditions. Then there are no good solutions to this in the abovementioned article. Even ‘UNIQUE’ formula in Excel 2021 is not sufficient.</p><p>I wanted the flexibility of Excel SUMIFS formula. I want the formula to return discount count in a range where adjacent columns satisfy given conditions.</p><p>For this, I have written the following macro</p><pre>Function CountUniqueConditions(rngValues As Range, ParamArray criteriaRangesAndValues() As Variant) As Long<br>    Dim dict As Object<br>    Set dict = CreateObject(&quot;Scripting.Dictionary&quot;)<br>    <br>    Dim i As Long, j As Long<br>    Dim valueKey As String<br>    Dim resultCount As Long<br>    Dim criteriaRange As Range<br>    Dim criteriaValue As Variant<br>    Dim allCriteriaSatisfied As Boolean<br>    <br>    resultCount = 0<br>    <br>    &#39; Loop through the range of values<br>    For i = 1 To rngValues.Count<br>        allCriteriaSatisfied = True<br>        <br>        &#39; Loop through the criteria and check if each is satisfied<br>        For j = LBound(criteriaRangesAndValues) To UBound(criteriaRangesAndValues) Step 2<br>            Set criteriaRange = criteriaRangesAndValues(j)<br>            criteriaValue = criteriaRangesAndValues(j + 1)<br>            <br>            &#39; Check if the current criteria is satisfied<br>            If criteriaRange.Cells(i, 1).Value &lt;&gt; criteriaValue Then<br>                allCriteriaSatisfied = False<br>                Exit For<br>            End If<br>        Next j<br>        <br>        &#39; If all criteria are satisfied (or no criteria given), process the value<br>        If allCriteriaSatisfied Then<br>            valueKey = CStr(rngValues.Cells(i, 1).Value)<br>            <br>            &#39; If this value is not yet in the dictionary, add it<br>            If Not dict.exists(valueKey) Then<br>                dict.Add valueKey, True<br>                resultCount = resultCount + 1<br>            End If<br>        End If<br>    Next i<br>    <br>    &#39; Return the count of unique values<br>    CountUniqueConditions = resultCount<br>End Function</pre><p>Saved this VBA macro in your Excel workbook and enable macros in your Excel. Then you can use this macro function to get unique counts in the following manner.</p><ol><li><strong>No criteria (just counting unique values):</strong></li></ol><pre>=CountUniqueConditions(A2:A10)</pre><p>If you don&#39;t give any additional conditions then it would return a distinct count in your range.</p><p>2. <strong>One criterion (column B should match “criteria1”):</strong></p><pre>=CountUniqueConditions(A2:A10, B2:B10, &quot;criteria1&quot;)</pre><p>In a similar format as SUMIFS formula, you can give a condition for the adjacent column, it will return a distinct count in A2:A10 only where values in B2:B10 equals “criteria1”.</p><p>3. <strong>Multiple criteria (as many as needed):</strong></p><pre>=CountUniqueConditions(A2:A10, B2:B10, &quot;criteria1&quot;, C2:C10, &quot;criteria2&quot;, D2:D10, &quot;criteria3&quot;)</pre><p>You can give as many criteria as needed.</p><p>If you like this formula then please clap and subscribe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f41e25dafa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>