<?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 Aditya Vishnu on Medium]]></title>
        <description><![CDATA[Stories by Aditya Vishnu on Medium]]></description>
        <link>https://medium.com/@iamadityavishnu?source=rss-bd349f0b0ca4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vpHivPHC652snls7opR1Lg.jpeg</url>
            <title>Stories by Aditya Vishnu on Medium</title>
            <link>https://medium.com/@iamadityavishnu?source=rss-bd349f0b0ca4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:17:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamadityavishnu/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[How I Used Agentic AI to Build a Prompt-to-Video App (Using Open Source, No Costly APIs)]]></title>
            <link>https://medium.com/@iamadityavishnu/how-i-used-agentic-ai-to-build-a-prompt-to-video-app-using-open-source-no-costly-apis-9423923b2d60?source=rss-bd349f0b0ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9423923b2d60</guid>
            <category><![CDATA[manim]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Aditya Vishnu]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 11:04:33 GMT</pubDate>
            <atom:updated>2026-06-30T11:04:33.924Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“The journey of turning text into explainer videos — without relying on expensive proprietary APIs.”</em></p><p>Explainer videos are everywhere — startups use them to pitch, educators use them to teach, and creators use them to share ideas. But making one usually means hours of scripting, designing, and editing… or paying for expensive tools.</p><p>Well… hold my beer 😎.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*544t7ehBlUFh6GZb2m9guQ.gif" /><figcaption>A quick flow of Mnemo (sped up)</figcaption></figure><p>Meet <strong>Mnemo</strong> — a <strong>prompt-to-video generator</strong> I built during an internal hackathon at my company, <a href="https://www.thinkingcode.com/"><em>ThinkingCode Technologies</em></a>. Over the past few months, we’ve been experimenting heavily with <strong>agentic AI applications</strong>, and our CTO Mr. Prashanth Prabhu decided to challenge us with a simple but exciting problem statement: <em>“build a prompt-to-video generator.”</em></p><p>For example, the user might ask “<em>What are Vector Embeddings?</em>” and the application should produce a 5–10 minute explainer video that clearly and creatively breaks down the technical concept — no manual scripting, editing, or design work.</p><p>I immediately sketched out a plan and locked in the core tech stack: Python with FastAPI for the backend and Next.js for the frontend.</p><p>Everything in between, though, was a playground — the hackathon gave me the perfect excuse to try out some projects and services I had been curious about. Two highlights were <strong>OpenAI’s new open model gpt-oss-120b</strong> and the <a href="https://cloud.cerebras.ai/?referral_code=t6wwjkyw"><strong>Cerebras</strong></a><strong> inference engine</strong>, which I was eager to experiment with in a real build.</p><p><a href="https://cloud.cerebras.ai/?referral_code=t6wwjkyw"><strong>Cerebras</strong></a> is known for its lightning-fast LLM output — hitting speeds of nearly <strong>3,000 tokens per second</strong>. At first, I started with <strong>DeepSeek R1</strong>, which delivered solid results. But because my pipeline required multiple LLM calls, the script generation step was painfully slow.</p><p>Switching to <strong>Cerebras inference</strong> made a night-and-day difference. The speed boost transformed the workflow, turning what felt like a bottleneck into a smooth process.</p><p>The agentic framework powering the application was developed in-house at <strong>ThinkingCode</strong> for building agentic applications across our products. While I could have used any open-source agentic framework, the <a href="https://thinkingcode.ai/"><strong>ThinkingCode.ai</strong></a><strong> agent framework</strong> stood out for its predictability and proven reliability in production environments.</p><p>In the current landscape of agentic AI, <strong>predictability</strong> is often sacrificed in favor of open-ended adaptability. Many new frameworks focus heavily on giving agents freedom — allowing them to decide their own reasoning paths. But this can lead to unpredictable behaviors, inconsistent outcomes, and difficulty in debugging or scaling. For production-grade systems, unpredictability is a deal-breaker.</p><p>That’s where <strong>opinionated agent frameworks</strong> make a difference. By enforcing structured reasoning patterns, clear task boundaries, and predictable handoffs between agents, they balance <strong>adaptability with control</strong>. The <strong>ThinkingCode.ai framework</strong> is built on top of this philosophy — an opinionated agentic fabric that captures the best of both worlds, making it a dependable foundation for any agentic workflow.</p><p>Here is how the flow works. To generate the script, I designed a multi-step strategy inspired by how movies are structured:</p><ol><li><strong>Divide the video into segments</strong> — much like scenes and shots in a film.</li><li><strong>Define segment types</strong> — intro, narration, image, equation, bullet points, quiz, etc.</li><li><strong>Segment Planner Agent</strong> — the first agent decides which segments to include and in what order so that the video delivers a coherent narrative within the time constraints.</li><li><strong>Narration Maker Agent</strong> — the next agent takes each segment, identifies its type, and generates both the narration and the corresponding on-screen content.</li><li><strong>Incremental generation with context</strong> — the narration maker agent calls the LLM to build each segment step by step, always keeping previous segments in context. This ensures continuity across the video and also bypasses the intentional output-length limits of LLMs to create the entire script in one pass.</li><li><strong>Master Script</strong> — once complete, the entire video script is stored in JSON format, serving as the single source of truth for the final video.</li></ol><p>With the script ready, the next challenge was to translate it into an actual video.</p><p>For this, I turned to a tool I had experimented with quite a bit back in 2020: <strong>Manim</strong>. Short for <em>Mathematical Animation</em>, Manim might already be familiar to anyone who has watched <a href="https://www.youtube.com/@3blue1brown"><strong>3Blue1Brown</strong></a> on YouTube — the channel famous for its beautiful math and AI explainer videos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0m6PUC1MXCCfKf27DvQNaA.jpeg" /><figcaption>An image segment frame from one of the generated video</figcaption></figure><p>The library was originally created by the channel owner mathematician <em>Grant Sanderson </em>to produce his own content. Later, he open-sourced it, and today it’s actively maintained under the <a href="https://github.com/ManimCommunity/manim"><strong>manim-community</strong></a><strong> </strong>repository on GitHub.</p><p>The LLM created <strong>master script</strong> contains both the narration and the segment-specific metadata. For example, if a segment is a <em>quiz</em>, its metadata includes the question, options, and correct answer. If it’s an <em>image segment</em>, the metadata stores the prompt used to generate that image.</p><p>This metadata then drives the <strong>video creation pipeline</strong>, which uses it to generate individual segment videos. Once all segments are ready, they’re combined to produce the final video.</p><p>For generating the narration audio, I used the <a href="https://github.com/coqui-ai/TTS"><strong>Coqui TTS</strong></a> engine. Coqui delivers impressive voice quality when given good sample references — it can even clone your favorite presenter’s voice. Narrations for each segment are generated first, and then the video duration is adjusted to perfectly match the audio length.</p><p>Then came a challenge that was too noticeable to ignore — <strong>synchronizing the audio with the video in the quiz segments</strong>. The quiz segment will show the question, list down 4 options, start a countdown and finally reveal the answer. The narration also follows this order. The tricky part was <strong>perfectly matching the moment the narrator says the correct answer with the moment the answer gets highlighted on screen</strong>. If they were even slightly out of sync, the viewing experience felt awkward; the answer might be highlighted while the narrator was still reading the question, or the voice might declare the answer after the highlight had already appeared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPxZTPoY2EW1KCZAc9_nyg.jpeg" /><figcaption>A quiz segment frame from an explainer video about transformers</figcaption></figure><p>To solve this, I added a simple but effective rule: the LLM must always include the phrase <em>“the answer is”</em> right before announcing the correct option. I then used the <a href="https://github.com/openai/whisper"><strong>OpenAI Whisper</strong></a> model (open source) to transcribe the narration and <strong>extract the exact timestamp of that phrase</strong>. The ending timestamp of that phrase became the <strong>trigger point for the highlight animation</strong>, ensuring perfect alignment between audio and visuals.</p><p>The other segment types didn’t pose major synchronization issues, so I left them as-is. But if needed, the same timestamp-based approach could easily be applied.</p><p>Finally, to bring more life to the video, I added an <strong>animated character</strong> with simple mouth movements. The animation toggles between two images — open-mouth and closed-mouth depending on the audio amplitude crossing a given threshold. It’s a simple but effective trick. With a bit more work, additional postures and random toggling could make the animation feel even more dynamic. The lip-sync isn’t winning any Oscars yet — but that’s next on the to-do list.</p><p>The application frontend was built with <a href="https://nextjs.org/"><strong>Next.js</strong></a> — a React-based web framework. I decided to build the backend using <a href="https://fastapi.tiangolo.com/"><strong>FastAPI</strong></a><strong> </strong>in Python because most of the heavy lifting like media processing was already handled in Python. FastAPI allowed me to keep the backend lightweight, fast and clean. For additional backend services such as database, authentication, and storage, I used <a href="https://supabase.com/"><strong>Supabase</strong></a>.</p><p>To build the UI, I used popular component libraries like <a href="https://www.hyperui.dev/"><strong>HyperUI</strong></a><strong> </strong>and <a href="https://ui.aceternity.com/"><strong>AceternityUI</strong></a>. The styling was done with <a href="https://tailwindcss.com/"><strong>Tailwind CSS</strong></a>, and animations were added using Framer <a href="https://motion.dev/"><strong>Motion</strong></a>.</p><p>Since the video creation took some time, I wanted to give the users realtime update on the progress of the video. To achieve this, I used <a href="https://ntfy.sh/"><strong>ntfy</strong></a>, which is a simple HTTP-based pub-sub notification service. Once the notification is ready, the users will be notified and taken to the preview page where they can watch their video.</p><p>The types of segments included in the video are avatar narration (with bullet points, images, and formulas), quizzes, tables, equations, and an intro section with the video title prepended to every video.</p><p>For generating info-graphic images relevant to the topic, <a href="https://huggingface.co/Qwen/Qwen-Image"><strong>Qwen/Qwen-Image</strong></a> was used. The only API I paid for was Qwen-Image as my laptop took one look at the model and said, ‘Yeah… that’s not happening’. But it only costed me around ₹1.30 per image and the image generation was pretty fast (less than ~8 seconds). All these segments are then stitched together using <a href="https://ffmpeg.org/"><strong>FFmpeg</strong></a><strong> </strong>to generate the final output.</p><p>Here is a sample prompt and the generated image:</p><pre>A clear, educational diagram of a green plant leaf under the sun.<br>Yellow sun rays are shown entering the leaf. Arrows indicate inputs:<br>&quot;Carbon dioxide&quot; from the air and &quot;Water&quot; from the roots.<br>Style requirements: Educational diagram style, Clean and clear design,<br>Bright colors, English text only, Easy to understand for students,<br>Professional infographic quality, Clear labels and text inside the image,<br>Scientific accuracy, Suitable for learning materials.<br>Quality: High resolution, sharp details, educational poster quality.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzlGsOfbxZpCcNQU3RNMgA.png" /><figcaption>Image generated from Qwen-Image on Hugging Face</figcaption></figure><p>As for what’s next — the project is still under development. Future updates will include features like allowing users to edit individual segments through prompts, making the content more flexible and interactive. I also plan to give users more control over video duration, target audience, and narration style. A major UX enhancement on the roadmap is introducing multiple “presenters” — each with their own distinct presentation style, avatars and voice — so users can curate the viewing experience to their audience.</p><p>Here is a sample video from the current version.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fg-OStH9BYpg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dg-OStH9BYpg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fg-OStH9BYpg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b3c85e7ef6cf16039e27e650df176a9/href">https://medium.com/media/5b3c85e7ef6cf16039e27e650df176a9/href</a></iframe><p>Mnemo ended up securing <strong>first place in the hackathon</strong>, which was an incredibly rewarding experience. Huge thanks to <strong>Prashanth Prabhu </strong>for his guidance and support, and to <strong>all my colleagues</strong> for their encouragement throughout the project.</p><p>Thanks for taking the time to read about the project! I’d love to hear your thoughts, ideas or feedback in the comments — let’s start a conversation about AI-powered explainer videos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9423923b2d60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting to know FastAPI]]></title>
            <link>https://medium.com/total-brainstorming/getting-to-know-fastapi-7fb4791d3e50?source=rss-bd349f0b0ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fb4791d3e50</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[textblob]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <dc:creator><![CDATA[Aditya Vishnu]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 11:01:59 GMT</pubDate>
            <atom:updated>2022-02-17T11:01:59.912Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>In this article you will get to know a novel method of constructing APIs with Python using FastAPI. It is a powerful, high-performance, Python type hint based web framework.</p><p>If you ask why FastAPI, I would say it is very clean, well documented and easy to understand framework than its predecessors. It will improve your coding speed tremendously. Also you can access the automatic interactive API documentation either on Swagger UI or on ReDoc UI.</p><p>We will see the rest of the features on the go.</p><p>In the end we will also see how to build an application with FastAPI that can predict what people thinks about something based on sentiment analysis done on tweets from Twitter.</p><p>For this we are using Twitter API to extract tweets based on user input. Then we analyze each tweet using TextBlob (a library in Python for sentiment analysis). Bases on the analysis TextBlob returns a polarity for each tweet, which we can use to classify tweets as either positive, neutral or negative. Finally the total percentage of positive, neutral and negative tweets are returned and shown to the user through a web interface running on localhost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*bL9js5jKMJy9ghZYQS-fAQ.png" /><figcaption>The front-end of this application running on localhost. ‘Cyberpunk 2077’ was my keyword.</figcaption></figure><p>Now back to FastAPI, let’s start with installation:</p><pre>pip install fastapi[all]</pre><p>Running this command will include FastAPI as well as the ASGI server ‘Uvicorn’. After the installation is complete let’s take a look at this basic program.</p><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/&quot;)<br>async def my_function():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><p>Save this to main.py file and run the server using:</p><pre>uvicorn main:app --reload</pre><p>This command will run the uvicorn server on our localhost on port number <em>8000. </em>And with the--reload, every time we make some change in our code the server automatically restarts. This is very useful at the time of development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*eza0m0jkuAJO9Snb38twLQ.png" /><figcaption>Anaconda Prompt running uvicorn server for a python file named test.py with FastAPI instance named ‘app’.</figcaption></figure><p>You can also start the server from within the python program using:</p><pre>from fastapi import FastAPI<br><strong>import uvicorn</strong></pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/&quot;)<br>async def my_function():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><pre><strong>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(app, host=&quot;127.0.0.1&quot;, port=8000)</strong></pre><p><em>To stop the server press Ctrl + C on the terminal. Otherwise, you won’t be able to use the same port until the next restart. The port will stay engaged.</em></p><p>Now let’s see what the code does.</p><p>Obviously we need to import the FastAPI library. Then we create an object named <strong>app</strong> using the FastAPI() class. You can name it anything, not just app, it’s just an instance of the class. But remember to use the same name when you run uvicorn uvicorn main:<strong>app </strong>— reload or uvicorn.run(<strong>app</strong>, host=”127.0.0.1&quot;, port=8000).</p><p><strong>Creating a path operation</strong></p><p>The path refers to the last prat of the URL. That is whatever comes after https://domain-name.com.</p><p>For example, in the URL : https://domain-name.com/search/keyword the path is /search/keyword. We define a path inside a decorator in FastAPI.</p><p>Using different paths we can use the API to handle different purposes.</p><p>The @app.get<strong>(&quot;/&quot;)</strong> decorator before defining a function tell FastAPI that the function just below it is responsible for handling whatever requests that comes under this path.</p><p>Also there are different ‘methods’ for communicating over the HTTP protocol. Like, GET, POST, PUT, DELETE etc, to name a few. This ‘method’ is also specified in the decorator as@app.<strong>get</strong>(&quot;/&quot;) (here I used the get method). The first part of the decorator is the name of our FastAPI instance <strong>app</strong>.</p><p><strong>Defining the path operation function</strong></p><p>Once you specify the request method and the path, then you have to define the function that should work when a request is created on the path defined.</p><pre>async def my_function():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><p>Here my_function() is the function that we created for the path (“/”) (i.e the root path). The async keyword tells the program to wait until some slow process finished its work. The program also works without the the async keyword.</p><p>Finally the output that the function my_function() generated is returned in JSON format. You can return an int, string, list , dictionary and some other complex data models too. Here return {“message”: “Hello World”} is returned with message as the key and “Hello World” as the value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*KgpriCsD1FOetb9R1OpYJQ.png" /><figcaption>This is what the response will look like when we load the server at http://127.0.0.1:8000/</figcaption></figure><h4><strong>Path Parameters</strong></h4><p>What if our path operation function needs to take in some arguments and returns some response after doing some operations on it. This is exactly what we need in our sentiment analysis program. So this is how we do it.</p><p>Consider a logic which returns the square of a number…</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br><br>@app.get(&quot;/square/<strong>{number}</strong>&quot;)<br>async def my_function(<strong>number</strong>):<br>    number = int(number)<br>    square = number ** 2<br>    return {&quot;square&quot;: square}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*9QjXNnoq3OEZoyn_LvR_tA.png" /><figcaption>This is what the output will look like</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCTVF4Mm1yBeSxYapr_dLg.png" /><figcaption>This is what it looks like in the Swagger UI</figcaption></figure><p>We have to specify the parameter after the path like “/square/<strong>{number}</strong>”. The {<strong>number</strong>} is passed to the function as argument and square operations is performed on it and then returned.</p><p><strong>Data validation using Python type annotations</strong></p><p>Did you notice in the last code snippet that I had to convert the argument number to integer type before performing the square operation? This is because the number is passed as a string (“5” instead of just 5). This is where we can make use of explicit type annotations.</p><p>We can set the type of the parameters using Python type annotations like this def my_function(<strong>number: int</strong>). This will throw an error if we try to pass a string as the path variable. And this will also automatically parse the numbers as integers instead of numbers in the form of strings (eg: 5 instead of “5”).</p><p>The modified code with type validation will look like this:</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br><br>@app.get(&quot;/square/{number}&quot;)<br>async def my_function(<strong>number: int</strong>):<br>    square = number ** 2<br>    return {&quot;square&quot;: square}</pre><p>If we try to pass as string instead of an integer, the error will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*S_0EekQKyLd9JTw886mzxg.png" /><figcaption>This error says that the value passed is not an integer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsYkH1dUQUrGH4zjN0l4MQ.png" /><figcaption>The documentation automatically marks the value to be an integer in the Swagger UI</figcaption></figure><h4><strong>Query Parameters</strong></h4><p>Path parameters are used to identify a specific resource while query parameters are used to sort or filter those resources. A sample URL with query parameters is as follows:</p><p>— http://127.0.0.1:8000/products/?max-price=5000&amp;free-delivery=True</p><p>They are key-value pairs that appears after ? and separated using &amp;.</p><p>Here is a code snippet that shows an example of query parameters in FastAPI:</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br><br><strong>@app.get(&quot;/exponent/&quot;)</strong><br>async def my_function<strong>(number: int, power: int):</strong><br>    <strong>result = number ** power<br>    return {&quot;result&quot;: result}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*eWT6lJmJLRtGYkRJSCXpMg.png" /><figcaption>Output for the above code snippet with query parameters</figcaption></figure><p><strong>Setting default values and optional parameters</strong></p><p>We can also set some <strong>default values </strong>to our parameters. That is, if we don’t explicitly pass a value the default value is taken for operations.</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br><br>@app.get(&quot;/exponent/&quot;)<br>async def my_function(number: int, <strong>power: int = 2</strong>):<br>    result = number ** power<br>    return {&quot;result&quot;: result}</pre><p>Consider in this case, we want to set the default exponent to find the square of a number, if the user did not pass the exponent value. To do that, we just assign a default value for the argument as:</p><p>power: int = 2</p><p>The default value is assigned automatically if we don’t pass any value through our request URL like: http://127.0.0.1:8000/exponent/?number=6. So for this query the output should be: {“result”:36}.</p><p>Also note that, if we try to load http://127.0.0.1:8000/exponent/?number=6 without setting a default value, we will get an error, because FastAPI expects two parameters to be passed.</p><p><strong>Optional parameters</strong></p><p>We can also set some parameter to be optional. See for example, the below code:</p><pre><strong>from typing import Optional</strong><br><br>from fastapi import FastAPI<br><br>app = FastAPI()<br><br><br>@app.get(&quot;/exponent/&quot;)<br>async def my_function(number: int, <br>                      power: int = 2,<br>                      <strong>odd_number_check: Optional[bool] = None</strong>):<br>    result = number ** power<br>    <strong>if odd_number_check:<br>        if result % 2 != 0:<br>            return {&quot;result&quot;: result, &quot;is_odd&quot;: True}</strong><br>    return {&quot;result&quot;: result}</pre><p>The output for the above code for normal request would be like the previous outputs. But if we add an extra parameter like this:</p><p>http://127.0.0.1:8000/exponent/?number=7&amp;power=4<strong>&amp;odd_number_check=True</strong></p><p>Our output would be (i.e the parameter <strong>odd_number_check</strong> is optional here):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*jpe2WnapPI6caowgR6frUg.png" /><figcaption>Here odd_number_check is set to ‘True’ which will modify the response as above</figcaption></figure><p>Also keep in mind that the below given URLs are parsed to give the same result as above by the FastAPI:</p><p>http://127.0.0.1:8000/exponent/?number=7&amp;power=4&amp;odd_number_check=<strong>1</strong></p><p>http://127.0.0.1:8000/exponent/?number=7&amp;power=4&amp;odd_number_check=<strong>yes</strong></p><p>http://127.0.0.1:8000/exponent/?number=7&amp;power=4&amp;odd_number_check=<strong>on</strong></p><p>Make sure you assign the None value to optional parameters or else FastAPI will take other values assigned as the default values.</p><p>Let’s stop at this point for now. I think this is enough for you to play around with FastAPI before going to deeper features.</p><p><strong>Now let’s see the code for Tweet Analyzer using FastAPI.</strong></p><pre>import tweepy<br>import pandas as pd<br>from fastapi import FastAPI<br><strong>from fastapi.middleware.cors import CORSMiddleware</strong><br>import uvicorn<br>import re<br>from textblob import TextBlob<br><br>app = FastAPI()<br><br><strong>origins = [<br>    &quot;http://localhost&quot;<br>]</strong><br><br><strong>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=origins<br>)</strong><br><br><br>@app.post(&quot;/analyse/{keyword}&quot;)<br>async def fetch_tweets(keyword: str):<br>    api_key = &#39;YOUR_API_KEY&#39;<br>    api_key_secret = &#39;YOUR_API_SECRET_KEY&#39;<br><br>    access_token = &#39;YOUR_ACCESS_TOKEN&#39;<br>    access_token_secret = &#39;YOUR_ACCESS_TOKEN_SECRET&#39;<br><br>    auth = tweepy.OAuthHandler(api_key, api_key_secret)<br>    auth.set_access_token(access_token, access_token_secret)<br><br>    api = tweepy.API(auth)<br><br>    no_of_tweets = 100<br><br>    tweets = api.search(q=keyword, lang=&quot;en&quot;, count=no_of_tweets)<br><br>    negative_tweets, positive_tweets = 0, 0<br><br>    for tweet in tweets:<br>        cleaned_tweet = &#39; &#39;.join(re.sub(&quot;(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)&quot;, &quot; &quot;, tweet.text).split())<br><br>        analysis = TextBlob(cleaned_tweet)<br><br>        if analysis.sentiment.polarity &lt; 0:<br>            negative_tweets += 1<br>        elif analysis.sentiment.polarity &gt; 0:<br>            positive_tweets += 1<br><br>    positive_percent = (positive_tweets / no_of_tweets) * 100<br>    negative_percent = (negative_tweets / no_of_tweets) * 100<br><br>    print(&quot;Tweets Analyzed successfully!&quot;)<br><br>    return {&quot;positive&quot;: f&quot;{positive_percent}%&quot;,<br>            &quot;negative&quot;: f&quot;{negative_percent}%&quot;,<br>            &quot;neutral&quot;: f&quot;{float(100 - (positive_tweets + negative_tweets))}%&quot;}<br><br><br>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(app, host=&quot;127.0.0.1&quot;, port=8000)</pre><p>You may have noticed some alien codes in the above code like:</p><pre><strong>origins = [<br>    &quot;http://localhost&quot;<br>]</strong><br><br><strong>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=origins<br>)</strong></pre><p>These are necessary to establish a successful connection between the front-end and the back-end when both are running on different servers. Here I am sending requests from my <em>localhost, </em>so I have to tell FastAPI that connections from this origin (http://localhost/) is safe to allow.</p><p>Now let’s see the request part running on our web browser:</p><pre>&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js&quot;&gt;&lt;/script&gt;</pre><pre>&lt;section&gt;</pre><pre>&lt;div class=&quot;form-container&quot;&gt;</pre><pre>&lt;div&gt;</pre><pre>&lt;h1&gt;Enter the keyword&lt;/h1&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;hr&gt;</pre><pre>&lt;div&gt;</pre><pre>&lt;table&gt;</pre><pre>&lt;tr&gt;</pre><pre>&lt;td&gt;&lt;label for=&quot;keyword&quot;&gt;What do people think about:&lt;/label&gt;&lt;/td&gt;</pre><pre>&lt;/tr&gt;</pre><pre>&lt;tr&gt;</pre><pre>&lt;td&gt;&lt;input type=&quot;text&quot; id=&quot;keyword&quot; placeholder=&quot;Enter your keyword here&quot;&gt;&lt;/td&gt;</pre><pre>&lt;/tr&gt;</pre><pre>&lt;tr&gt;</pre><pre>&lt;td&gt;&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; id=&quot;submit-button&quot;&gt;&lt;/td&gt;</pre><pre>&lt;/tr&gt;</pre><pre>&lt;/table&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;setiment-display&quot;&gt;</pre><pre>&lt;div&gt;</pre><pre>&lt;h2 style=&quot;color: green&quot;&gt;Percentage of positive tweets: &lt;span id=&quot;positive&quot;&gt;&lt;/span&gt;&lt;/h2&gt;</pre><pre>&lt;h2 style=&quot;color: red&quot;&gt;Percentage of negative tweets: &lt;span id=&quot;negative&quot;&gt;&lt;/span&gt;&lt;/h2&gt;</pre><pre>&lt;h2 style=&quot;color: rgb(214, 157, 1)&quot;&gt;Percentage of neutral tweets: &lt;span id=&quot;neutral&quot;&gt;&lt;/span&gt;&lt;/h2&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;script&gt;</pre><pre>$(&quot;#submit-button&quot;).click(function(){</pre><pre>var keyword = document.getElementById(&quot;keyword&quot;).value;</pre><pre>var url = &quot;http://127.0.0.1:8000/analyse/&quot; + keyword;</pre><pre>var request = new XMLHttpRequest()</pre><pre>request.open(&#39;POST&#39;, url, true)</pre><pre>request.onload = function () {</pre><pre>var data = JSON.parse(this.response)</pre><pre>var table = document.getElementById(&quot;myTable&quot;);</pre><pre>if (request.status &gt;= 200 &amp;&amp; request.status &lt; 400) {</pre><pre>var positive = document.getElementById(&quot;positive&quot;);</pre><pre>var negative = document.getElementById(&quot;negative&quot;);</pre><pre>var neutral = document.getElementById(&quot;neutral&quot;);</pre><pre>positive.innerHTML = data.positive;</pre><pre>negative.innerHTML = data.negative;</pre><pre>neutral.innerHTML = data.neutral;</pre><pre>} else {</pre><pre>console.log(&#39;error&#39;)</pre><pre>}</pre><pre>}</pre><pre>request.send()</pre><pre>})</pre><pre>&lt;/script&gt;</pre><pre>&lt;/section&gt;</pre><p>This is just an introduction to FastAPI. It has got even more features with the same simplicity. Have some fun with it. 😃</p><p>To find more about FastAPI go to: <a href="https://fastapi.tiangolo.com/tutorial/">https://fastapi.tiangolo.com/tutorial/</a></p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fb4791d3e50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/total-brainstorming/getting-to-know-fastapi-7fb4791d3e50">Getting to know FastAPI</a> was originally published in <a href="https://medium.com/total-brainstorming">Total Brainstorming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BIRCH Clustering Algorithm]]></title>
            <link>https://medium.com/@iamadityavishnu/birch-clustering-algorithm-7897b679ed6d?source=rss-bd349f0b0ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7897b679ed6d</guid>
            <category><![CDATA[birch]]></category>
            <dc:creator><![CDATA[Aditya Vishnu]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 18:28:41 GMT</pubDate>
            <atom:updated>2022-02-20T14:35:16.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9fQTC2ETO6p_5ayw" /><figcaption>Photo by <a href="https://unsplash.com/@wizwow?utm_source=medium&amp;utm_medium=referral">Donald Giannatti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Clustering is part of an unsupervised machine learning task where data points are clustered or grouped together based on their relative position to each other. If the data points are populated together in a data space they are clustered together. BIRCH is such an algorithm to cluster data points in a datasets. But what makes BIRCH different is its ability to perform well on large datasets. Conventional clustering algorithms fail to cluster large data. They were not efficient in terms of memory and time complexity. The problem arises when the availability of memory is very little compared to the actual data size and also the I/O time it take to complete the task.</p><p>BIRCH stands for Balanced Iterative Reducing and Clustering using Hierarchies. It is a kind of hierarchical clustering algorithms as the name suggests. It works only on metric datasets, meaning the datasets having data that could somehow be measured — height, weight etc. The core concept of BIRCH is its Clustering Feature (CF) which is a representation of the data in the cluster. Let us see in more detail how BIRCH works.</p><p>Before that we need to see some math used for finding the centroid <em>X0</em>, radius <em>R</em> and diameter <em>D</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*CUR1UC5qDKAuR_PJGekQOA.png" /><figcaption>Equation for centroid, radius and diameter — image from original paper</figcaption></figure><h4>Clustering Feature (CF)</h4><p>BIRCH minimizes the memory requirement for the data points by summarizing the data in the cluster into a triple called Clustering Feature. So we can say that a CF is a compact representation of a cluster of data. All the data in such a cluster could be regenerated from the CF. A CF is represented as:</p><p><em>CF = (N, LS, SS)</em></p><p>Where <em>N</em> is the number of data points in the cluster, <em>LS</em> is the linear sum of the data points and <em>SS</em> is the squared sum of the data points.</p><p><strong>CF Additivity Theorem: </strong>Take <em>CF</em> vectors of two disjoint clusters <em>CF₁</em> and <em>CF₂</em>.</p><p><em>CF₁ = (N₁, LS₁, SS₁) and CF₂ = (N₂, LS₂, SS₂)</em></p><p>The Additivity Theorem states that the <em>CF </em>vector of the cluster resulting from merging the two disjoint clusters can we represented as:</p><p><em>CF₁ + CF₂ = (N₁ + N₂, LS₁ + LS₂ , SS₁ + SS₂)</em></p><p>Now lets see the main data representation of the CF.</p><h4>CF Tree</h4><p>A CF Tree is the actual data structure representing the data points. It is similar to the B+ tree. Every node in the CF tree is also a sub-cluster. There are two attributes to the nodes — the branching factor (B) and the threshold (T).</p><p>The branching factor limits the number of sub clusters that a CF node can have. The threshold value limits the maximum radius that a cluster can have. Each node also has two pointer pointing to the previous and the next nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/0*O9xcVXRVi8wMIG6H.png" /><figcaption>A CF Tree</figcaption></figure><p>Lets see how operations are done on the CF tree.</p><h4>Insertion algorithm</h4><p>Inserting a data point to the CF tree goes through the following steps:</p><ol><li>Identifying the appropriate leaf: Starting from the root node, the data point travels down recursively by choosing the closest child node.</li><li>Modifying the leaf: When the data point reaches the leaf node, it checks whether it could be added to the cluster. If adding the point makes the cluster expand its threshold value, the leaf node is split and the new data is added.</li><li>Modifying the path to the leaf: All the updates are made available to the rest of the nodes, from the leaf node to the root node.</li></ol><h4>Clustering algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*TVjs1EaOzsbmcKqGl0tacg.png" /><figcaption>4 Phases in BIRCH clustering algorithm — image from original paper</figcaption></figure><p>The four phases in the BIRCH clustering algorithm are as follows:</p><ul><li><strong>Phase 1: </strong>Start with an initial random threshold value and try to add points into the tree. If adding a point makes the memory to run out, increase the threshold to include more data points to the cluster.</li><li><strong>Phase 2: </strong>[Optional] Removes outliers and grouping clusters. This phase is essentially preparing the data for the phase 3.</li><li><strong>Phase 3: </strong>Clustering the leaf nodes in the CF value using an existing clustering algorithm, say for example the agglomerative hierarchical clustering.</li><li><strong>Phase 4: </strong>[Optional] Doing additional passes over the data and reassigning data points to the closest centroid from phase 3. We can repeat this step as many times. The results will only improve.</li></ul><h4>Conclusion</h4><p>BIRCH is an efficient clustering algorithm for very large datasets where memory requirement and I/O time is very high in conventional algorithms. It can decently classify such datasets even on a single iteration. It can also be the input for other clustering algorithms, basically like a data preprocessing technique.</p><p>Reference: [BIRCH: An Efficient Data Clustering Method for Very Large Database] <a href="https://dl.acm.org/doi/pdf/10.1145/235968.233324">https://dl.acm.org/doi/pdf/10.1145/235968.233324</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7897b679ed6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>