<?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 Niranj Rajasekaran on Medium]]></title>
        <description><![CDATA[Stories by Niranj Rajasekaran on Medium]]></description>
        <link>https://medium.com/@niranjrajasekaran?source=rss-89311ce0489a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MctYeHVgSjFyjg7bj4xfvw.jpeg</url>
            <title>Stories by Niranj Rajasekaran on Medium</title>
            <link>https://medium.com/@niranjrajasekaran?source=rss-89311ce0489a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:43:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@niranjrajasekaran/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[My Weekend Battle with Port 53: Setting Up AdGuard Home to Protect Kids Online]]></title>
            <link>https://medium.com/@niranjrajasekaran/my-weekend-battle-with-port-53-setting-up-adguard-home-to-protect-kids-online-683e2c0b5efb?source=rss-89311ce0489a------2</link>
            <guid isPermaLink="false">https://medium.com/p/683e2c0b5efb</guid>
            <category><![CDATA[oracle-cloud]]></category>
            <category><![CDATA[parenting]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[digitalocean]]></category>
            <dc:creator><![CDATA[Niranj Rajasekaran]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 08:47:34 GMT</pubDate>
            <atom:updated>2025-08-18T08:47:34.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXWW-uLx9XE2vKwSqq_j9g.png" /></figure><h3>1. Introduction — The Why</h3><p><em>“It all started with my kids. Like most kids today, they’re drawn to YouTube, Instagram, and endless reels. I wanted them to enjoy the internet but not get swallowed by it. So I thought: simple fix — block social media at home. Just a weekend project, right? Spoiler: it wasn’t.”</em></p><h3>2. Choosing the Tools — AdGuard Home</h3><p><em>“After some searching, I landed on AdGuard Home. A DNS-based filter that could block ads, trackers, and even entire websites before they even reached my kids’ devices. Perfect in theory: set it up once, and the whole house is protected. That was the plan. And then reality hit.”</em></p><h3>3. The Cloud Struggles — Oracle Cloud vs Digital Ocean</h3><p><em>“Like any engineer who loves a freebie, I first tried Oracle Cloud’s always-free VM. Specs were good, cost was zero — what could go wrong? Turns out, plenty. Oracle Cloud doesn’t allow external DNS on Port 53. I learned this the hard way after hours of failed attempts. Port 53 is sacred territory in the internet world, and Oracle locks it down to prevent abuse. Fair. But frustrating.<br> So I moved to Digital Ocean. It wasn’t free, but within minutes, things worked. Sometimes, the paid option really is the ‘cheaper’ one if you value your sanity.”</em></p><h3>4. The Technical Core — Port 53 and Why It Matters</h3><p><em>“This was my first real battle. For the uninitiated: Port 53 is the lifeline of the internet’s phonebook — DNS. Without it, nothing loads. Most providers block it by default for customers because bad actors abuse DNS for attacks. Unfortunately, that means hobbyists like me get caught in the crossfire. I wrestled with iptables rules, custom ports, and even toyed with encrypted DNS to sneak around the block. What I thought would be plug-and-play quickly became a deep dive into how the internet really works.”</em></p><h3>5. The Google TV &amp; Mobile Challenge — Dynamic DNS Bypass</h3><p><em>“Just when I thought I had victory in my hands, my Google TV laughed at me. No matter what DNS I forced at the router, it stubbornly went back to Google’s 8.8.8.8. It felt like playing chess with a device that was always one move ahead.<br> And then came the kids’ mobile devices. Changing DNS there was as easy as flipping a switch. All my AdGuard rules went out the window. The real fight wasn’t with the servers or configs — it was with devices actively trying to escape my setup.”</em></p><h3>6. The Outcome — Did It Work?</h3><p><em>“So, did it work? Mostly. On laptops and most devices, AdGuard did its job beautifully — ads gone, social media blocked. On Google TV and mobile? Let’s just say it’s an ongoing battle. I did manage to firewall some of Google’s hardcoded DNS, which gave me partial victory. But I realized something important: there is no one-time fix. It’s an arms race between curious kids, stubborn devices, and tired parents.”</em></p><h3>7. Takeaways for Other Parents / Hobbyists</h3><p><strong>If you’re thinking of doing this yourself, here are my lessons</strong>:</p><ol><li>Don’t rely on Oracle Cloud if Port 53 matters to you. Save yourself the headache.</li><li>Digital Ocean (or any paid provider) might just be worth the small cost.</li><li>Expect devices like Google TV to bypass your DNS rules — be ready with firewalls.</li><li>And finally, remember: technology helps, but parenting is still the hard part. Blocking Instagram is easy, explaining <em>why</em> you’re blocking it is harder.</li></ol><h3>8. Closing</h3><p><em>“What started as a weekend project turned into a crash course in networking, cloud quirks, and modern device stubbornness. I set out to protect my kids from social media, and along the way, I learned more about the internet than I expected. Maybe next weekend, I’ll try something easier… like climbing Everest.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=683e2c0b5efb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering __slots__ in Python: Save Memory, Boost Speed]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@niranjrajasekaran/mastering-slots-in-python-save-memory-boost-speed-382b2b3912fe?source=rss-89311ce0489a------2"><img src="https://cdn-images-1.medium.com/max/2600/1*wtI-aVDS3uEgSSlpPZjUIA.jpeg" width="2944"></a></p><p class="medium-feed-snippet">When you create a normal Python class, every instance gets a dynamic attribute dictionary (__dict__) for storing its attributes.</p><p class="medium-feed-link"><a href="https://medium.com/@niranjrajasekaran/mastering-slots-in-python-save-memory-boost-speed-382b2b3912fe?source=rss-89311ce0489a------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@niranjrajasekaran/mastering-slots-in-python-save-memory-boost-speed-382b2b3912fe?source=rss-89311ce0489a------2</link>
            <guid isPermaLink="false">https://medium.com/p/382b2b3912fe</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Niranj Rajasekaran]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 12:36:15 GMT</pubDate>
            <atom:updated>2025-08-14T16:59:16.493Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The Hidden Environmental Cost of High-Performing Servers: A GPT Perspective]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://ai.plainenglish.io/the-hidden-environmental-cost-of-high-performing-servers-a-gpt-perspective-37c2f5956cbd?source=rss-89311ce0489a------2"><img src="https://cdn-images-1.medium.com/max/2600/1*TfDksLjt_9ovaWIEHLf-Uw.png" width="6912"></a></p><p class="medium-feed-snippet">Introduction:</p><p class="medium-feed-link"><a href="https://ai.plainenglish.io/the-hidden-environmental-cost-of-high-performing-servers-a-gpt-perspective-37c2f5956cbd?source=rss-89311ce0489a------2">Continue reading on Artificial Intelligence in Plain English »</a></p></div>]]></description>
            <link>https://ai.plainenglish.io/the-hidden-environmental-cost-of-high-performing-servers-a-gpt-perspective-37c2f5956cbd?source=rss-89311ce0489a------2</link>
            <guid isPermaLink="false">https://medium.com/p/37c2f5956cbd</guid>
            <category><![CDATA[computing]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[water]]></category>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Niranj Rajasekaran]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 02:15:48 GMT</pubDate>
            <atom:updated>2023-09-15T04:39:38.246Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Dockerizing FastAPI: A Comprehensive Guide]]></title>
            <link>https://medium.com/@niranjrajasekaran/dockerizing-fastapi-a-comprehensive-guide-804cf5c3d746?source=rss-89311ce0489a------2</link>
            <guid isPermaLink="false">https://medium.com/p/804cf5c3d746</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[uvicorn]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Niranj Rajasekaran]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 00:50:12 GMT</pubDate>
            <atom:updated>2023-09-10T00:50:12.706Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCLaA57FOnR9-E85l1eepw.png" /></figure><p><strong>Introduction</strong></p><p>In the realm of software development, the need for efficient, scalable, and consistent environments is paramount. Enter Docker, a tool that has revolutionized the way developers package, distribute, and run applications. This guide will not only walk you through Dockerizing a FastAPI application but will also shed light on Docker’s history, its distinction from Virtual Machines, and best practices for production deployment.</p><p><strong>A Deep Dive into Docker’s History</strong></p><p>Docker, while a household name now, began as an ambitious project in 2013. Solomon Hykes, Docker’s founder, introduced it at PyCon, aiming to simplify container technology that had been around for years but was complex and inaccessible. Docker’s introduction was timely; it addressed the growing need for consistent and scalable application deployment. Over the years, it has evolved, with a vast ecosystem and community support, becoming the gold standard for containerization.</p><p><strong>Understanding the Docker Phenomenon: Docker vs. Virtual Machines (VMs)</strong></p><p>To truly appreciate Docker, one must understand its predecessor: the Virtual Machine (VM). Here’s a detailed comparison:</p><p>1. <strong>Architecture</strong>: VMs run an entire OS instance on top of the host hardware, facilitated by a Hypervisor. Docker containers, however, run on the host OS, sharing its kernel but maintaining isolation.</p><p>2. <strong>Resource Overhead</strong>: VMs are resource-intensive, often requiring dedicated CPU and memory allocations. Docker containers are lightweight, consuming minimal resources, leading to better system utilization.</p><p>3. <strong>Startup Time</strong>: VMs can take minutes to boot up, while Docker containers can start in seconds, ensuring rapid application scaling.</p><p>4. <strong>Portability</strong>: Docker containers encapsulate all dependencies, ensuring the phrase “it works on my machine” holds true across all environments.</p><p>5. <strong>Security</strong>: VMs provide strong isolation, but with the right configurations (like user namespaces), Docker can achieve comparable security levels.</p><p><strong>The Art of Dockerizing a FastAPI Application</strong></p><p>FastAPI, a modern web framework for building APIs, is known for its speed and Pythonic nature. Let’s Dockerize it:</p><p><strong>Step 1: Crafting a FastAPI Application</strong></p><p>If you’re new to FastAPI, here’s a simple application:</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/&quot;)<br>def read_root():<br>   return {&quot;Hello&quot;: &quot;Docker World!&quot;}</pre><p><strong>Step 2: The Heart of Docker — The Dockerfile</strong></p><p>The Dockerfile is a blueprint for your Docker image. Here’s an enhanced Dockerfile for our FastAPI application:</p><pre># Use an official Python runtime as a base image<br>FROM python:3.9-slim<br><br># Set environment variables for non-interactive apt installs<br>ENV DEBIAN_FRONTEND=noninteractive<br><br># Update and install any required dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y - no-install-recommends apt-utils<br><br># Set the working directory inside the container<br>WORKDIR /app<br><br># Copy the application to the container<br>COPY . /app<br><br># Install FastAPI, Uvicorn, and any other dependencies<br>RUN pip install - no-cache-dir fastapi[all] uvicorn<br><br># Expose the port Uvicorn will run on<br>EXPOSE 80<br><br># Command to run the application using Uvicorn<br>CMD [&quot;uvicorn&quot;, &quot;app:app&quot;, &quot; - host&quot;, &quot;0.0.0.0&quot;, &quot; - port&quot;, &quot;80&quot;]</pre><p><strong>Step 3: Building the Docker Image</strong></p><p>With the Dockerfile in place, navigate to the directory containing it and run:</p><pre>docker build -t myfastapiapp:latest .</pre><p><strong>Step 4: Breathing Life into the Image — Running the Docker Container</strong></p><p>To run your FastAPI application inside a Docker container:</p><pre>docker run -d -p 4000:80 myfastapiapp:latest</pre><p>Your FastAPI application is now accessible at `<a href="http://localhost:4000`"><strong>http://localhost:4000</strong>`</a>.</p><p><strong>Best Practices for Deploying FastAPI in Production</strong></p><p>Deploying in production requires additional considerations:</p><p>1. <strong>Production-ready Server</strong>: Pair Uvicorn with Gunicorn for a robust production setup.</p><p>2. <strong>Optimizing Docker Images</strong>: Use multi-stage builds to reduce image size and potential attack vectors.</p><p>3. <strong>Managing Secrets</strong>: Never hard-code secrets. Use Docker secrets, environment variables, or orchestration tools like Kubernetes for secret management.</p><p>4. <strong>Monitoring &amp; Logging</strong>: Tools like Prometheus and Grafana for monitoring and ELK Stack for logging can be invaluable.</p><p>5. <strong>Continuous Deployment</strong>: Automate your deployment process using CI/CD pipelines, ensuring seamless updates and rollbacks.</p><p>6. <strong>Scaling</strong>: Use orchestration tools like Docker Swarm or Kubernetes to manage, scale, and maintain container health.</p><p><strong>Conclusion</strong></p><p>Docker’s rise to prominence is a testament to its utility in addressing modern software challenges. By Dockerizing your FastAPI application, you harness the power of containerization, ensuring scalability, consistency, and efficiency. As with any tool, mastery comes with understanding and practice. So, embark on your Docker journey and explore the myriad possibilities it offers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=804cf5c3d746" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Prompt Engineering in OpenAI: A Deep Dive]]></title>
            <link>https://medium.com/@niranjrajasekaran/mastering-prompt-engineering-in-openai-a-deep-dive-386056974548?source=rss-89311ce0489a------2</link>
            <guid isPermaLink="false">https://medium.com/p/386056974548</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Niranj Rajasekaran]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 07:56:34 GMT</pubDate>
            <atom:updated>2023-09-08T08:01:08.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KlD_ZyBodL4e-GeLOCOFA.png" /></figure><p>In the world of artificial intelligence, particularly with models like those from OpenAI, the way you communicate your request is paramount. This communication is encapsulated in what we call “prompt engineering.” Let’s embark on a comprehensive exploration of this topic, delving into its intricacies and understanding its significance through detailed examples.</p><p><strong>Understanding the Basics</strong></p><p><strong>Prompt Engineering</strong> is akin to the art of asking the right questions. It’s about crafting a specific input (or prompt) to elicit the desired output from a model. The better your prompt, the more accurate, detailed, or nuanced your answer will be.</p><p><strong>The Significance of Prompt Engineering</strong></p><p>1. <strong>Precision</strong>: A well-crafted prompt can lead the model to a more precise answer, reducing the chances of vagueness.<br>2. <strong>Efficiency</strong>: Time and computational resources can be saved if the model doesn’t have to guess the user’s intent.<br>3. <strong>Safety</strong>: By guiding the model with a clear prompt, there’s a reduced risk of generating inappropriate or harmful content.</p><p><strong>Prompt Engineering in Action: Detailed Examples</strong></p><p>1. <strong>Contextual Understanding</strong>:<br> — <strong>Prompt</strong>: “Explain gravity.”<br> — <strong>Refined Prompt</strong>: “Explain the concept of gravity as understood in Einstein’s theory of relativity.”<br> <br> The first prompt might yield a general high-school level explanation, while the second would delve into the specifics of relativity.</p><p>2. <strong>Guided Exploration</strong>:<br> — <strong>Prompt</strong>: “Write about water.”<br> — <strong>Refined Prompt</strong>: “Discuss the importance of water conservation in arid regions and suggest three methods to achieve it.”<br> <br> The initial prompt is too broad, while the refined one guides the model towards a specific topic and even asks for solutions.</p><p>3. <strong>Clarity Over Ambiguity</strong>:<br> — <strong>Prompt</strong>: “Talk about apples.”<br> — <strong>Refined Prompt</strong>: “Describe the nutritional benefits of consuming apples regularly.”<br> <br> The latter ensures the model focuses on health and nutrition rather than, say, the history of apple cultivation.</p><p><strong>Crafting the Perfect Prompt: Strategies and Techniques</strong></p><p>1. <strong>Iterative Refinement</strong>: Start with a base prompt, evaluate the output, and then refine. This cycle can be repeated until the desired response is achieved.<br> <br> <strong>Example</strong>: If researching a historical event:<br> — <strong>Initial Prompt</strong>: “French Revolution.”<br> — <strong>First Iteration</strong>: “Causes of the French Revolution.”<br> — <strong>Second Iteration</strong>: “Economic and social causes of the French Revolution of 1789.”</p><p>2. <strong>Positional Framing</strong>: Sometimes, placing the most important information at the beginning of the prompt can yield better results.</p><p><strong>Example</strong>:<br> — <strong>Regular Prompt</strong>: “After explaining its history, describe the architectural features of the Colosseum in Rome.”<br> — <strong>Positional Framing</strong>: “Focusing on its architectural features, describe the Colosseum in Rome and touch upon its history.”</p><p>3. <strong>Explicit Contextualization</strong>: If you’re looking for a specific type of answer (like a summary, debate, or a story), state that format explicitly.</p><p><strong>Example</strong>:<br> — <strong>Regular Prompt</strong>: “Discuss the pros and cons of nuclear energy.”<br> — <strong>Explicit Contextualization</strong>: “Write a debate script where one person supports nuclear energy highlighting its benefits and the other opposes it, pointing out its risks.”</p><p><strong>Advanced Prompting Techniques</strong></p><p>1. <strong>Temperature and Max Tokens</strong>: Beyond the textual prompt, using parameters like temperature (which controls randomness) and max tokens (which limits response length) can further refine outputs.</p><p>2. <strong>Chain Prompting</strong>: Use the output of one prompt as the input for another. This can be useful for multi-step problems or to dive deeper into a topic.</p><p><strong>Example</strong>:<br> — <strong>First Prompt</strong>: “List the main renewable energy sources.”<br> — <strong>Second Prompt</strong> (using the output of the first)*: “Explain the working principle behind solar panels.”</p><p>3. <strong>Prompting with Examples</strong>: Sometimes, providing an example within the prompt can guide the model towards the desired format or depth of the answer.</p><p><strong>Example</strong>:<br> — <strong>Prompt</strong>: “Translate the following English sentences to French: ‘Hello, how are you?’ Example: ‘The sky is blue’ translates to ‘Le ciel est bleu’.”</p><p><strong>The Future of Prompt Engineering and Staying Updated</strong></p><p>As models like GPT-4 and its successors evolve, so will the techniques and nuances of prompt engineering. It’s essential to:</p><p>1. <strong>Engage with OpenAI’s Community</strong>: Participate in forums, read research papers, and engage in community experiments.<br>2. <strong>Regularly Test and Experiment</strong>: As models update, previously effective prompts might need tweaking.<br>3. <strong>Collaborate and Share</strong>: Team up with peers to share findings and collaborate on complex prompts.</p><p><strong>Conclusion</strong></p><p>Prompt engineering is a dynamic and evolving field. It’s the bridge between human intent and machine capability. By mastering this art, we can harness the full potential of models like GPT-4, ensuring precise, efficient, and safe outputs. As we move forward, staying updated, experimenting, and collaborating will be the keys to success in this domain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=386056974548" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Voice: A Hands-On Guide to OpenAI’s Speech-to-Text with Python]]></title>
            <link>https://python.plainenglish.io/unlocking-voice-a-hands-on-guide-to-openais-speech-to-text-with-python-e785238b4e4?source=rss-89311ce0489a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e785238b4e4</guid>
            <category><![CDATA[speech-to-text-conversion]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Niranj Rajasekaran]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 11:22:19 GMT</pubDate>
            <atom:updated>2023-09-07T01:41:20.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAVCtUZJpyqPBraPchf2Dw.png" /></figure><p>Speech-to-text technology has been a game-changer in many industries, from transcription services to voice assistants. OpenAI, known for its cutting-edge research and products, has also ventured into this domain. In this blog post, we’ll explore OpenAI’s speech-to-text capabilities and walk through some Python code examples to get you started.</p><p><strong>What is Speech-to-Text?</strong></p><p>Speech-to-text (STT), also known as automatic speech recognition (ASR), is the process of converting spoken language into written text. This technology has a wide range of applications, including transcription services, voice assistants, and accessibility features for the differently-abled.</p><p><strong>OpenAI’s Approach to Speech-to-Text</strong></p><p>OpenAI has always been at the forefront of AI research. Their approach to speech-to-text is no exception. Leveraging deep learning models, OpenAI’s STT system is trained on vast amounts of data, making it capable of understanding various accents, dialects, and nuances in spoken language.</p><p><strong>Key Features:</strong></p><p>1. <strong>High Accuracy</strong>: OpenAI’s models are trained on diverse datasets, ensuring high accuracy across different accents and languages.<br>2. <strong>Low Latency</strong>: Real-time applications require quick responses, and OpenAI’s STT is optimized for low latency.<br>3. <strong>Scalability</strong>: Whether you’re transcribing a single interview or processing hours of audio data, OpenAI’s STT scales to meet your needs.</p><p><strong>Getting Started with OpenAI’s Speech-to-Text in Python</strong></p><p>Let’s dive into some Python code examples to see OpenAI’s STT in action.</p><p><strong>Prerequisites</strong>:</p><p>1. <strong>Python</strong>: Ensure you have Python installed.<br>2. <strong>OpenAI Python Client</strong>: Install it using poetry:</p><pre>poetry add openai</pre><p>3. <strong>API Key</strong>: Sign up on OpenAI’s platform and obtain your API key.</p><p><strong>Basic Usage</strong>:</p><p>Here’s a simple example to transcribe a short audio clip:</p><pre>import openai<br><br># Initialize the OpenAI client with your API key<br>openai.api_key = &#39;YOUR_API_KEY&#39;<br><br># Open the audio file<br>audio_file= open(&quot;/path/to/file/audio.mp3&quot;, &quot;rb&quot;)<br><br># Get the transcript using whisper-1 model<br>transcript = openai.Audio.transcribe(&quot;whisper-1&quot;, audio_file)<br><br># Print the transcription<br>print(transcript)</pre><p><strong>Handling Longer Audio Files</strong>:</p><p>For longer audio files, it’s a good practice to split the audio into smaller chunks and process them sequentially. Here’s a basic example using the `pydub` library:</p><pre>from pydub import AudioSegment<br>import openai<br><br><br>openai.api_key = &#39;YOUR_API_KEY&#39;<br><br><br>def transcribe_large_file(file_path, chunk_size=30000):<br>   # Load the audio file<br>   audio = AudioSegment.from_wav(file_path)<br> <br>   # Split the audio into chunks<br>   chunks = [audio[i:i + chunk_size] for i in range(0, len(audio), chunk_size)]<br> <br>   transcriptions = []<br><br>   for chunk in chunks:<br>       # Save the chunk to a temporary file<br>       chunk.export(&quot;temp_chunk.wav&quot;, format=&quot;wav&quot;)<br> <br>    # Transcribe the chunk<br>    response = openai.Audio.transcribe(&quot;whisper-1&quot;, &quot;temp_chunk.wav&quot;)<br>    <br>    transcriptions.append(response)<br>    return &#39; &#39;.join(transcriptions)<br><br>print(transcribe_large_file(&quot;path_to_your_large_audio_file.wav&quot;))</pre><p>Remember to install `pydub` using `pip install pydub` and also ensure you have FFmpeg installed, as `pydub` relies on it.</p><p><strong>Potential Applications:</strong></p><p>1. T<strong>ranscription Services</strong>: Convert interviews, lectures, or any spoken content into text.<br>2. <strong>Voice Assistants</strong>: Build your voice-controlled applications.<br>3. <strong>Accessibility</strong>: Make content accessible to those who prefer or need text over audio.</p><p><strong>Conclusion</strong>:</p><p>OpenAI’s speech-to-text is a powerful tool that, when combined with Python, becomes highly accessible and versatile. Whether you’re a developer looking to integrate voice features into your app or a researcher aiming to transcribe hours of interviews, OpenAI’s STT has got you covered.</p><p><strong><em>Remember, while the technology is impressive, always be mindful of user privacy. Always obtain the necessary permissions before recording or transcribing any conversations.</em></strong></p><p>Happy coding!</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e785238b4e4" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/unlocking-voice-a-hands-on-guide-to-openais-speech-to-text-with-python-e785238b4e4">Unlocking Voice: A Hands-On Guide to OpenAI’s Speech-to-Text with Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting Handwritten Text to Digital Format: Cloud, Pricing, and the Challenges of Starting from…]]></title>
            <link>https://python.plainenglish.io/converting-handwritten-text-to-digital-format-cloud-pricing-and-the-challenges-of-starting-from-3288f4c56cfb?source=rss-89311ce0489a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3288f4c56cfb</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Niranj Rajasekaran]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 11:34:53 GMT</pubDate>
            <atom:updated>2023-09-05T00:23:08.917Z</atom:updated>
            <content:encoded><![CDATA[<h3>Converting Handwritten Text to Digital Format: Cloud, Pricing, and the Challenges of Starting from Scratch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QyFG9aYUNj95IAVvgQhKBg.png" /></figure><p>In the digital age, the ability to convert handwritten text into a digital format is invaluable. Whether it’s for digitizing old documents, processing forms, or making handwritten notes searchable, the applications are vast. In a <a href="https://blog.niranjrajasekaran.com/a-deep-dive-into-converting-handwritten-tables-in-images-to-excel-using-python-87317f71d31d">previous exploration</a>, I delved into the power of OpenCV and PyTesseract. Today, we’re expanding our horizons to AWS Textract and its cloud counterparts, while also shedding light on the potential pitfalls of building a solution from scratch.</p><p><strong>AWS Textract</strong></p><p>Amazon Web Services (AWS) is a behemoth in the cloud services sector, offering a myriad of services tailored for various needs. Among these is Amazon Textract.</p><p><strong>What is AWS Textract?</strong></p><p>Amazon Textract is a fully managed machine learning service that automatically extracts text, forms, and tables from scanned documents. It’s not just another OCR tool; it’s designed to understand the structure of a document. This means it can identify columns in tables, content in form fields, and more.</p><p><strong>Pricing</strong>:</p><p><strong>Analyze Document API</strong></p><ul><li>Pages with tables: $0.015 per page for the first 1 million pages, and $0.01 per page after that.</li><li>Pages with forms: $0.05 per page for the first 1 million pages, and $0.04 per page after that.</li><li>Pages with tables and forms: $0.070 per page for the first 1 million pages, and $0.055 per page after that.</li><li>Pages with queries: $0.015 per page for the first 1 million pages, and $0.01 per page after that.</li></ul><p><strong>Detect Document Text API</strong></p><ul><li>$0.0005 per character for the first 1 million characters, and $0.0004 per character after that.</li></ul><p><strong>Analyze ID Documents API</strong></p><ul><li>$0.03 per page.</li></ul><p><strong>Cloud Alternatives</strong></p><p>The cloud ecosystem is vast, with major players like Google and Microsoft offering their solutions. Let’s explore them.</p><p>1. <strong>Google Cloud Vision OCR (Google Compute Engine)</strong>: Google’s foray into the OCR world is through its Vision API. This tool is not just an OCR; it’s a comprehensive image analysis tool. For our purposes, its ability to detect and extract text from images, including handwritten content, is of prime importance.</p><p><strong>Pricing</strong>: <a href="https://cloud.google.com/vision/pricing">Check here</a></p><p>2. <strong>Azure Computer Vision (Azure)</strong>: Microsoft’s Azure platform isn’t left behind in this race. Their Computer Vision service is a testament to their commitment to AI and machine learning. This service can extract both printed and handwritten text from images, and it supports a multitude of languages.</p><p><strong>Pricing</strong>: <a href="https://azure.microsoft.com/en-us/pricing/details/cognitive-services/computer-vision/">Check here</a></p><p><strong>The Challenges of Starting with OpenCV and Tesseract</strong></p><p>OpenCV and Tesseract are open-source tools that have been invaluable to developers worldwide. However, building a solution from scratch using these tools can be akin to reinventing the wheel. Here’s why:</p><p>1. <strong>Development Time</strong>: Crafting a solution from the ground up is time-consuming. With OpenCV and Tesseract, you’re responsible for every detail, from image preprocessing to error handling. Every handwritten text is unique, and handling the myriad of styles and nuances can be daunting.</p><p>2. <strong>Scalability</strong>: While a local solution might work for a few images, what happens when you need to process thousands daily? Cloud solutions are designed to scale effortlessly, but with local solutions, you might find yourself grappling with performance bottlenecks.</p><p>3. <strong>Accuracy</strong>: Tesseract is powerful, but it’s not infallible. Cloud solutions often benefit from being trained on vast and diverse datasets, potentially offering superior accuracy. This is especially true for diverse handwriting styles, where nuances can significantly impact recognition accuracy.</p><p>4. <strong>Maintenance</strong>: Technology evolves, and software needs updates. With a DIY approach, you’re the developer, the tester, and the maintainer. Cloud solutions, being managed services, offload this responsibility, ensuring you always have access to the latest and greatest features without the associated maintenance headaches.</p><p>5. <strong>Cost</strong>: While it might seem that open-source solutions are “free”, there’s a hidden cost. The time you invest in development, the potential business costs of inaccuracies, and the ongoing maintenance can, in the long run, surpass the costs of a managed cloud solution.</p><p><strong>Conclusion</strong></p><p>The journey from handwritten text to digital format is filled with challenges and decisions. Tools like OpenCV and Tesseract offer a hands-on approach, giving developers granular control. However, as projects grow and scale becomes a concern, the allure of managed cloud solutions like AWS Textract, Google Cloud Vision OCR, and Azure Computer Vision becomes hard to ignore. They offer a blend of scalability, accuracy, and reduced maintenance, making them a compelling choice for businesses and large-scale applications. As always, the right tool depends on your specific needs, budget, and long-term vision.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3288f4c56cfb" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/converting-handwritten-text-to-digital-format-cloud-pricing-and-the-challenges-of-starting-from-3288f4c56cfb">Converting Handwritten Text to Digital Format: Cloud, Pricing, and the Challenges of Starting from…</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into Converting Handwritten Tables in Images to Excel Using Python]]></title>
            <link>https://python.plainenglish.io/a-deep-dive-into-converting-handwritten-tables-in-images-to-excel-using-python-87317f71d31d?source=rss-89311ce0489a------2</link>
            <guid isPermaLink="false">https://medium.com/p/87317f71d31d</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[tesseract]]></category>
            <dc:creator><![CDATA[Niranj Rajasekaran]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 13:35:05 GMT</pubDate>
            <atom:updated>2023-09-01T01:15:29.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJYNxgzboX9a-36eNeaQYA.png" /></figure><p>In today’s digital age, integrating handwritten content into digital formats is a common requirement. Here, we’ll take a detailed journey into converting handwritten tables from images into Excel using Python, OpenCV, and Tesseract.</p><p><strong>Prerequisites</strong>:<br>1. <strong>Python</strong>: Ensure y<a href="https://www.python.org/">ou have Python installed. If not, visit Python’s official website</a> for installation guidelines.<br>2. <strong>Libraries</strong>: Install required Python libraries with:</p><pre>pip install pytesseract opencv-python openpyxl</pre><p>1. <strong>Image Pre-processing with OpenCV</strong>:<br>Pre-processing is pivotal. It optimizes the image, maximizing the success rate of the OCR.</p><p>1.1 <strong>Reading the Image</strong>:</p><p>Load the image into Python using OpenCV.</p><pre>import cv2<br>image = cv2.imread(&#39;table_image.jpg&#39;)</pre><p>1.2 <strong>Grayscale Conversion</strong>:<br>Color complexities can hinder the OCR process. Converting to grayscale simplifies the image.</p><pre>gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)</pre><p>1.3 <strong>Binarization</strong>:<br>Binarization makes the image black and white, further reducing complexities.</p><pre>_, binary_image = cv2.threshold(gray_image, 128, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)</pre><p><strong>Note</strong>: `THRESH_BINARY_INV` and `THRESH_OTSU` are thresholding techniques to automate the selection of the threshold value.*</p><p>1.4 <strong>Save for Verification</strong> (Optional):<br>It’s often useful to visualize the pre-processed image to ensure accuracy.</p><pre>cv2.imwrite(&#39;processed_image.jpg&#39;, binary_image)</pre><p>2. <strong>Text Extraction with Pytesseract</strong>:<br>With the image prepared, Tesseract’s power can now be harnessed.</p><p>2.1 <strong>Extract Text</strong>:</p><pre>from pytesseract import image_to_string<br>extracted_text = image_to_string(binary_image)</pre><p>Tesseract examines the image and deciphers the text content, outputting a string.</p><p>2.2 <strong>Save for Manual Review</strong>:<br>Before moving to Excel, it’s prudent to review the output, ensuring characters have been identified correctly.</p><pre>with open(&#39;output.txt&#39;, &#39;w&#39;) as file:<br>    file.write(extracted_text)</pre><p>3. <strong>Structuring Data for Excel</strong>:<br>The extracted text needs formatting before Excel can use it effectively.</p><p>3.1 <strong>Setting Up Excel</strong>:</p><pre>from openpyxl import Workbook<br><br>wb = Workbook()<br>ws = wb.active</pre><p>This sets up a new Excel workbook and sheet.</p><p>3.2 <strong>Parsing the Extracted Text</strong>:<br>The text must be broken down into a tabular format.</p><pre>rows = extracted_text.strip().split(&#39;\n&#39;)<br><br>for r_index, row in enumerate(rows, start=1):<br>   columns = row.split(&#39;\t&#39;)<br><br>   for c_index, cell_value in enumerate(columns, start=1):<br>       ws.cell(row=r_index, column=c_index, value=cell_value.strip())</pre><p><strong>Note</strong>: This assumes that rows are separated by new lines (`\n`) and columns by tabs (`\t`). Adjust as necessary based on your data’s format.*</p><p>3.3 <strong>Save to Excel</strong>:</p><pre>wb.save(&#39;output.xlsx&#39;)</pre><p>4. <strong>Manual Refinement</strong>:<br>Automated OCR, especially with handwriting, might have inaccuracies. Open `output.xlsx` and verify the content. Look for:</p><p>- Misinterpreted characters<br>- Merged cells that need splitting<br>- Formatting inconsistencies</p><p><strong>Conclusion</strong>:<br>By combining Python’s versatility, OpenCV’s image-processing capabilities, and Tesseract’s powerful OCR, the transition from handwritten tables to digital format becomes achievable. Still, due to the variability of handwriting, always anticipate some manual refinement to ensure data integrity.</p><p>This guide offers a basic walkthrough, but the realm of image processing and OCR is vast. As you dive deeper, you might encounter more sophisticated challenges, requiring advanced techniques. Yet, with Python at your side, solutions are just a few lines of code away.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87317f71d31d" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/a-deep-dive-into-converting-handwritten-tables-in-images-to-excel-using-python-87317f71d31d">A Deep Dive into Converting Handwritten Tables in Images to Excel Using Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Databases: The New Age Data Storage Paradigm]]></title>
            <link>https://python.plainenglish.io/vector-databases-the-new-age-data-storage-paradigm-aad26bd22d2?source=rss-89311ce0489a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aad26bd22d2</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Niranj Rajasekaran]]></dc:creator>
            <pubDate>Wed, 30 Aug 2023 14:00:50 GMT</pubDate>
            <atom:updated>2023-08-31T05:32:12.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeCmnHw2yfWBIbSKP_IOtQ.png" /></figure><p>In the digital age, data is constantly evolving. Traditional database architectures and storage solutions are being challenged by novel, high-dimensional, and complex data structures. Vector databases have emerged as a prominent answer to these challenges. In this blog, we’ll dive deep into understanding what vector databases are, their unique features, and how they differ from traditional databases.</p><p><strong>1. How Vector Databases Differ from Normal Databases</strong></p><p>The primary distinction between traditional databases (like SQL or NoSQL) and vector databases lies in the kind of data they store and how they query it.</p><p><strong>Traditional Databases</strong>:<br>- Structured around tabular data, with columns and rows.<br>- Efficient at handling relational queries, where you are primarily looking for exact matches or specific values.<br> <br><strong>Vector Databases</strong>:<br>- Designed to handle high-dimensional vector data.<br>- Efficient at similarity-based searches, allowing for fuzzy matching rather than exact matches.</p><p><strong>2. The Data Structure Behind Vector Databases</strong></p><p>Vector databases primarily store vectors. A vector, in this context, is a mathematical representation of data in high-dimensional space. Consider a simple example: In traditional databases, an image might be stored as a series of bytes. In a vector database, this image is stored as a series of numbers (a vector) that represents its features.</p><p>Vector databases often use data structures such as:<br>- <strong>KD-trees</strong>: Efficient for multidimensional key searches.<br>- <strong>Ball trees</strong>: Specially designed for high dimensional metric spaces.<br>- <strong>Hashing</strong>: Like locality-sensitive hashing (LSH) for approximate nearest neighbor search in sublinear time.</p><p><strong>3. Use Cases of Vector Databases with Real-Life Examples</strong></p><p><strong>Image and Video Recognition</strong>: <br>One of the most popular use cases is in image and video recognition. Consider platforms like Pinterest or Instagram where users search for similar images. Instead of comparing pixel-by-pixel, vectors represent features, and similarity search is faster and more accurate.</p><p><strong>Recommendation Engines</strong>: <br>Netflix or Spotify, for example, needs to quickly sift through vast amounts of data to recommend a movie or song. By transforming user preferences and content into vectors, they can achieve fast, similarity-based searches to provide real-time recommendations.</p><p><strong>Semantic Text Search</strong>:*<br>For platforms like Medium or Google Docs, vector databases can provide semantic search. Instead of finding exact text matches, the system can find documents with similar meanings, even if they don’t use the same words.</p><p><strong>Anomaly Detection</strong>:<br>In cybersecurity, systems need to detect unusual patterns or behaviors. Transforming network data into vectors and using similarity searches, any deviation or anomaly can be quickly identified.</p><p><strong>4. Other Main Topics:</strong></p><p><strong>Scalability and Performance</strong>:<br>While vector databases provide powerful features, they can be resource-intensive. Understanding how they scale and what impacts performance is crucial.</p><p><strong>Integration with Machine Learning</strong>:<br>Vector databases often pair with ML models, especially deep learning. These models convert raw data (like images or text) into vectors.</p><p><strong>Security Concerns</strong>:<br>Given that vector databases often deal with sensitive data (like user behavior or personal images), security is a pivotal concern. Encryption, access controls, and auditing are vital.</p><p><strong>Future and Evolution</strong>:<br>With the growth of AI and ML, vector databases are set to evolve. Understanding where the industry is heading can provide insights for businesses and developers alike.</p><p>In conclusion, vector databases are revolutionizing the way we store and query data, especially in contexts where similarity matters more than exact matches. As data continues to grow in complexity, so will the tools and systems we devise to handle them, and vector databases are a testament to this innovation.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aad26bd22d2" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/vector-databases-the-new-age-data-storage-paradigm-aad26bd22d2">Vector Databases: The New Age Data Storage Paradigm</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI with GraphQL: Delving Deep into Modern API Development]]></title>
            <link>https://python.plainenglish.io/fastapi-with-graphql-delving-deep-into-modern-api-development-f268ecc65a4f?source=rss-89311ce0489a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f268ecc65a4f</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Niranj Rajasekaran]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 13:00:29 GMT</pubDate>
            <atom:updated>2023-08-30T00:39:15.941Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vnWkCGL1zjIMj3ASs_P3A.png" /></figure><p><strong>Introduction</strong></p><p>FastAPI and GraphQL, when combined, offer the promise of speedy development without compromising on the rich feature set. Building on our previous foundation, let’s delve into more advanced facets of this integration.</p><p><strong>1. Setting the Stage: Advanced Installation</strong></p><p>To provide more advanced examples, we’ll be integrating the ORM (Object-Relational Mapping) tool SQLAlchemy for database interactions:</p><pre>pip install fastapi[all] uvicorn graphene graphene-sqlalchemy databases</pre><p><strong>2. SQLAlchemy Models with FastAPI &amp; GraphQL</strong></p><p>First, let’s establish a basic database model using SQLAlchemy:</p><pre>from sqlalchemy import create_engine, Column, Integer, String<br>from sqlalchemy.ext.declarative import declarative_base<br>from sqlalchemy.orm import sessionmaker<br><br><br>Base = declarative_base()<br>engine = create_engine(&#39;sqlite:///./test.db&#39;)<br>SessionLocal = sessionmaker(bind=engine)<br><br>class User(Base):<br>   __tablename__ = &quot;users&quot;<br>   id = Column(Integer, primary_key=True, index=True)<br>   name = Column(String, index=True)</pre><p><strong>3. Integrating Graphene with SQLAlchemy</strong></p><p>Graphene provides a way to integrate with SQLAlchemy seamlessly, translating ORM models to GraphQL objects:</p><pre>from graphene import ObjectType, Field, String<br>from graphene_sqlalchemy import SQLAlchemyObjectType<br><br><br>class UserType(SQLAlchemyObjectType):<br><br>   class Meta:<br>       model = User<br>       only_fields = (&quot;id&quot;, &quot;name&quot;)<br><br><br>class Query(ObjectType):<br>    user = Field(UserType, id=Int(required=True))<br><br>    def resolve_user(self, info, id):<br>       session = SessionLocal()<br>       user = session.query(User).filter(User.id == id).first()<br>       session.close()<br>       return user</pre><p><strong>4. Implementing GraphQL Mutations</strong></p><p>Mutations are essential for data manipulation operations in GraphQL:</p><pre>from graphene import Mutation<br><br>class CreateUser(Mutation):<br>    class Arguments:<br>        name = String(required=True)<br><br>    ok = Boolean()<br>    user = Field(lambda: UserType)<br><br>    @staticmethod<br>    def mutate(root, info, name):<br>        session = SessionLocal()<br>        user = User(name=name)<br>        session.add(user)<br>        session.commit()<br>        session.refresh(user)<br>        session.close()<br>        ok = True<br>        return CreateUser(user=user, ok=ok)<br><br>class Mutation(ObjectType):<br>    create_user = CreateUser.Field()</pre><p><strong>5. Integrating Everything</strong></p><p>To make everything work together, we’ll update the FastAPI app route:</p><pre>app.add_route(&quot;/&quot;, GraphQLApp(schema=graphene.Schema(query=Query, mutation=Mutation)))</pre><p><strong>6. Running &amp; Testing</strong></p><p>Now, run your application:</p><pre>uvicorn main:app - reload</pre><p>Access `<a href="http://127.0.0.1:8000`"><strong>http://127.0.0.1:8000</strong></a>`, and you can run complex GraphQL queries and mutations:</p><p><strong>Example Query:</strong></p><pre>{<br>  user(id: 1) {<br>    name<br>  }<br>}</pre><p><strong>Example Mutation:</strong></p><pre>mutation {<br>  createUser(name: &quot;Alice&quot;) {<br>    user {<br>      id<br>      name<br>    }<br>    ok<br>  }<br>}</pre><p><strong>7. Advanced Features &amp; Best Practices</strong></p><p>- <strong>Batching &amp; Caching</strong>: Utilize tools like DataLoader to batch requests and avoid the “N+1” query problem.<br> <br>- <strong>Error Handling</strong>: Graphene provides a mechanism to define custom error formats and handle them gracefully.<br> <br>- <strong>Subscriptions</strong>: For real-time updates, GraphQL supports subscriptions. With FastAPI’s support for WebSockets, integrating this becomes efficient.</p><p><strong>Conclusion</strong></p><p>Integrating GraphQL into FastAPI applications, especially with the power of ORM tools like SQLAlchemy, elevates the API development experience. It enables clear, concise, and powerful data operations, ensuring that modern web applications can function at their best. As with any tool, the key lies in understanding its nuances and using it wisely, allowing for scalable, performant, and maintainable applications.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f268ecc65a4f" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/fastapi-with-graphql-delving-deep-into-modern-api-development-f268ecc65a4f">FastAPI with GraphQL: Delving Deep into Modern API Development</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>