<?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 Akhileshwar Gurram on Medium]]></title>
        <description><![CDATA[Stories by Akhileshwar Gurram on Medium]]></description>
        <link>https://medium.com/@gurramakhileshwar333?source=rss-5cf0b082454f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b8q_qwR0DVWlIXMWiEJqLQ.jpeg</url>
            <title>Stories by Akhileshwar Gurram on Medium</title>
            <link>https://medium.com/@gurramakhileshwar333?source=rss-5cf0b082454f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:57:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gurramakhileshwar333/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[Demystifying Vector Stores: A Beginners Guide for Improved RAG Systems using PostgreSQL]]></title>
            <link>https://medium.com/@gurramakhileshwar333/demystifying-vector-stores-a-beginners-guide-for-improved-rag-systems-using-postgresql-d191cdd4d386?source=rss-5cf0b082454f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d191cdd4d386</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Akhileshwar Gurram]]></dc:creator>
            <pubDate>Sat, 29 Jun 2024 12:52:56 GMT</pubDate>
            <atom:updated>2024-06-29T12:52:56.901Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rz1-rsZf3y31wl3n5B8zNA.jpeg" /><figcaption>Image generated by Microsoft Copilot</figcaption></figure><p>In our <a href="https://medium.com/@gurramakhileshwar333/demystifying-vector-stores-a-beginners-guide-for-improved-rag-systems-using-numpy-a9bd9eba0142">previous post</a>, we explored the basics of vector stores and their importance in Retrieval-Augmented Generation (RAG) systems. We implemented a basic version of a Vectorstore using numpy; now, let’s take our implementation a step further by integrating PostgreSQL with pgvector to create a more robust and scalable vector store solution.</p><p><a href="https://medium.com/@gurramakhileshwar333/demystifying-vector-stores-a-beginners-guide-for-improved-rag-systems-using-numpy-a9bd9eba0142">Demystifying Vector Stores: A Beginners Guide for Improved RAG Systems using Numpy</a></p><h4>Why PostgreSQL and pgvector?</h4><p>PostgreSQL is a powerful, open-source relational database system known for its reliability and extensibility. <a href="https://github.com/pgvector/pgvector"><strong>pgvector</strong></a> is an extension for PostgreSQL that adds support for vector operations, making it an excellent choice for building production-ready vector stores. By using PostgreSQL with pgvector, we can:</p><ol><li>Persist our embeddings in a reliable database system</li><li>Leverage SQL for complex queries and data management</li><li>Scale our vector store more effectively</li><li>Benefit from PostgreSQL’s rich ecosystem of tools and extensions</li><li>Deploy our vectorstore like any other postgres db deployment</li></ol><h4>Our Enhanced Vector Store Implementation</h4><p>Let’s explore a more advanced implementation that leverages PostgreSQL with pgvector. This approach offers several improvements over our previous in-memory vector store:</p><ol><li><strong>Persistence</strong>: Embeddings are stored in a PostgreSQL database, allowing for data retention across system restarts.</li><li><strong>Scalability</strong>: PostgreSQL can handle large volumes of data, making it suitable for production environments.</li><li><strong>Flexibility</strong>: Support for multiple embedding models and similarity metrics.</li><li><strong>Efficiency</strong>: Utilizes pgvector for fast similarity searches on large datasets.</li><li><strong>SQL Integration</strong>: Allows for complex queries and data management using SQL.</li></ol><h4>Key Components:</h4><ol><li><strong>PostgresVectorStore Class</strong>: The core of our implementation, managing database operations.</li><li><strong>Multiple Embedding Models</strong>: Support for OpenAI and SentenceTransformer models.</li><li><strong>Various Similarity Metrics</strong>: L2 (Euclidean) distance, inner product, and cosine similarity.</li><li><strong>Database Integration</strong>: Using PostgreSQL with pgvector for persistent storage.</li><li><strong>Asynchronous Operations</strong>: Support for bulk inserts and parallel processing.</li></ol><h4>Code Walkthrough</h4><p>Let’s break down the <a href="https://github.com/Maveric-k07/vecky/blob/main/main.py"><strong>code</strong></a> step by step to understand its components and functionality.</p><ol><li>Enum Class for Similarity Metric</li></ol><pre>class BaseEmbeddingModel(ABC):<br>    @abstractmethod<br>    def encode(self, text: Union[str, List[str]]) -&gt; List[float]:<br>        pass<br><br>    @property<br>    @abstractmethod<br>    def dimension(self) -&gt; int:<br>        pass<br><br><br>class SentenceTransformerModel(BaseEmbeddingModel):<br>    def __init__(self, model_name: str):<br>        self.model = SentenceTransformer(model_name)<br><br>    def encode(self, text: Union[str, List[str]]) -&gt; List[float]:<br>        return self.model.encode(text).tolist()<br><br>    @property<br>    def dimension(self) -&gt; int:<br>        return self.model.get_sentence_embedding_dimension()<br><br><br>class OpenAIEmbeddingModel(BaseEmbeddingModel):<br>    def __init__(self, model_name: str = &quot;text-embedding-3-small&quot;):<br>        self.client = OpenAI(api_key=os.getenv(&quot;OPENAI_API_KEY&quot;))<br>        self.model_name = model_name<br><br>    def encode(self, text: Union[str, List[str]]) -&gt; List[float]:<br>        if isinstance(text, str):<br>            text = [text]<br>        response = self.client.embeddings.create(input=text, model=self.model_name)<br>        return response.data[0].embedding<br><br>    @property<br>    def dimension(self) -&gt; int:<br>        return 1536  # OpenAI&#39;s embedding dimension<br><br><br>class EmbeddingModelType(Enum):<br>    SENTENCE_TRANSFORMER = &quot;sentence_transformer&quot;<br>    OPENAI = &quot;openai&quot;</pre><p>Here we have a flexible system for managing different embedding models. It uses an abstract base class to define a common interface, which specific model classes implement. This allows the application to use various embedding models interchangeably, encapsulating each model’s unique logic while maintaining a consistent interface, and allowing addition of more embedding models in the future.</p><p>2. Document Model</p><pre>class Document(SQLModel, table=True):<br>    __tablename__ = &quot;vecky-documents&quot;<br><br>    id: UUID = Field(default_factory=uuid4, primary_key=True, index=True)<br>    collection_name: str = Field(default=&quot;vecky&quot;, index=True)<br>    content: str<br>    embedding: List[float] = Field(<br>        sa_column=Column(Vector(1536))<br>    )</pre><p>This Document class represents a database table for storing document embeddings in a vector database. It defines the structure for storing document content along with its vector representation, using SQLModel for ORM capabilities. The class includes fields for a unique identifier, <strong>collection name</strong>, text content, and a <a href="https://platform.openai.com/docs/models/embeddings">1536-dimensional</a> vector embedding.</p><blockquote>The collection_name here allows us to support storage of multiple documents and then query on the embeddings based on the collection name.</blockquote><p>3. <strong>VectorDatabase</strong> Class</p><p>The VectorDatabase class handles document embedding and similarity search.</p><pre>class VectorDatabase:<br>    DEFAULT_COLLECTION = &quot;vecky&quot;<br><br>    def __init__(<br>        self,<br>        db_url: str,<br>        embedding_model: BaseEmbeddingModel,<br>        similarity_metric: SimilarityMetric = SimilarityMetric.COSINE,<br>    ):<br>        self.engine = create_engine(db_url)<br>        SQLModel.metadata.create_all(self.engine)<br>        self.Session = sessionmaker(bind=self.engine)<br>        self.embedding_model = embedding_model<br>        self.similarity_metric = similarity_metric<br>        self._set_similarity_function()</pre><p>Here we are using the create_engine function and the sessionmaker functions to help with connecting with our postgreSQL database and create a session.</p><p>4. Function Setting Similarity Metric</p><pre>def _set_similarity_function(self):<br>      if self.similarity_metric == SimilarityMetric.EUCLIDEAN:<br>          self._sim_func = lambda x, y: x.l2_distance(y)<br>      elif self.similarity_metric == SimilarityMetric.COSINE:<br>          self._sim_func = lambda x, y: 1 - x.cosine_distance(y)<br>      else:<br>          raise ValueError(f&quot;Unsupported similarity metric: {self.similarity_metric}&quot;)</pre><p>This method sets the similarity function based on the chosen metric. The functions used to calculate the distance are powered by <a href="https://github.com/pgvector/pgvector?tab=readme-ov-file#querying"><strong>pgvector</strong></a><strong>.</strong></p><p>5. Class Method for Initialization And Creating Embeddings</p><pre>def ensure_embedding_dimension(embedding, target_dim=1536):<br>    if len(embedding) &gt; target_dim:<br>        return embedding[:target_dim]<br>    elif len(embedding) &lt; target_dim:<br>        return embedding + [0.0] * (target_dim - len(embedding))<br>    return embedding <br><br>@classmethod<br>def from_documents(<br>      cls,<br>      db_url: str,<br>      docs: List[str],<br>      embedding_model_type: EmbeddingModelType,<br>      model_name: str,<br>      collection_name: Optional[str] = None,<br>      similarity_metric: SimilarityMetric = SimilarityMetric.COSINE,<br>    ):<br>        if embedding_model_type == EmbeddingModelType.SENTENCE_TRANSFORMER:<br>            embedding_model = SentenceTransformerModel(model_name)<br>        elif embedding_model_type == EmbeddingModelType.OPENAI:<br>            embedding_model = OpenAIEmbeddingModel(model_name)<br>        else:<br>            raise ValueError(<br>                f&quot;Unsupported embedding model type: {embedding_model_type}&quot;<br>            )<br><br>        instance = cls(db_url, embedding_model, similarity_metric)<br>        instance.add_documents(docs, collection_name)<br>        return instance<br><br> def add_documents(self, docs: List[str], collection_name: Optional[str] = None):<br>      collection_name = collection_name or self.DEFAULT_COLLECTION<br>      session = self.Session()<br>      try:<br>          for doc in docs:<br>              embedding = self.embedding_model.encode(doc)<br>              embedding = ensure_embedding_dimension(embedding=embedding)<br>              db_doc = Document(<br>                  content=doc,<br>                  embedding=embedding,<br>                  collection_name=collection_name,<br>              )<br>              db_doc = Document.model_validate(db_doc)<br>              session.add(db_doc)<br>          session.commit()<br>      finally:<br>          session.close()</pre><p>These methods work together to initialize and populate a vector database with documents. The from_documents class method creates a new instance of the database, setting up the specified embedding model and similarity metric. It then uses the add_documents method to process and store the provided documents. The add_documents method handles the actual insertion of documents into the database, encoding each document into a vector embedding, creating a Document object with the content and embedding, and adding it to the database session.</p><p>6. Search Method with Timing</p><pre>@measure_time<br>def search(self, query: str, collection_name: Optional[str] = None, k: int = 5):<br>        query_embedding = self.embedding_model.encode(query)<br>        query_embedding = ensure_embedding_dimension(query_embedding)<br><br>        session = self.Session()<br>        try:<br>            similarity_function = self._sim_func(<br>                Document.embedding, query_embedding<br>            ).label(&quot;similarity&quot;)<br>            stmt = select(<br>                Document.content,<br>                similarity_function,<br>            ).order_by(similarity_function)<br><br>            if collection_name:<br>                stmt = stmt.filter(Document.collection_name == collection_name)<br><br>            stmt = stmt.limit(k)<br>            results = session.execute(stmt).all()<br>            return [r.content for r in results], [r.similarity for r in results]<br>        finally:<br>            session.close()</pre><p>The search method finds the top k similar documents to the query:</p><ul><li>Encodes the query.</li><li>Computes similarities based on the metric selected and the collection name provided.</li><li>Retrieves and returns the top k documents and their scores, along with the execution time.</li></ul><h4>Let’s see a working example:</h4><p>This example demonstrates how to set up a vectorstore powered by postgreSQL, perform searches, add new documents, and change the similarity metric for finding semantically similar documents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a0d4371f93105d2adb9d05fb08ab1cb/href">https://medium.com/media/4a0d4371f93105d2adb9d05fb08ab1cb/href</a></iframe><p>In the above example we are:</p><ol><li><strong>Setting a collection name for our document</strong>: We set our collection name as “park-stories-3” which provides us with a logical partition between different documents.</li><li><strong>Prepare Documents</strong>: Create a list of documents by splitting a large text block into individual lines.</li><li><strong>Create the Vector Database</strong>: Initialize a VectorDatabase with the list of documents, the embedding model, and a chosen similarity metric (cosine similarity) and most importantly the connection string to our <a href="https://gist.github.com/Maveric-k07/7797d15a2dff9c88037ceea10d1e6900"><strong>postgresSQL database with pgvector extension installed</strong></a>.</li><li><strong>Perform a Search</strong>: Search for the top k (e.g., 5) most similar documents to a query using the database and print the results, similarity scores, and search time.</li><li><strong>Add New Documents</strong>: Add additional documents to the same collection in the database.</li><li><strong>Change the Similarity Metric</strong>: Showcase switching the similarity metric from cosine similarity to Euclidean distance.</li><li><strong>Perform Another Search</strong>: Conduct the same search again with the updated similarity metric and print the new results, scores, and search time.</li></ol><h4>Output</h4><ol><li>Using SentenceTransformer model:</li></ol><pre>Loading embedding model...<br>Creating vector database for 10 documents...<br>VectorDatabase(total_documents=10, num_collections=1, embedding_model=SentenceTransformer, similarity_metric=COSINE)<br><br>Most similar documents: [&#39;No one could quite remember when the old railway handcar had been abandoned beside the rusting tracks. But every full moon, the neighborhood kids gathered to take turns pumping the stubborn lever, half-hoping the stubborn thing might finally roll to life with heavy metallic creaks.&#39;, &quot;The circus had left town weeks ago, but Timmy swore he could still hear the faint calling of the ringmaster&#39;s voice. He followed it into an overgrown field where the tattered remains of a striped tent lay haunting the weeds, casting serpentine shadows in the moonlight.&quot;]<br>Similarity scores: [0.14731377363204956, 0.16992301226121143]<br>Search time: 71.51 ms<br><br>Added 2 new documents. Total documents: VectorDatabase(total_documents=12, num_collections=1, embedding_model=SentenceTransformer, similarity_metric=COSINE)<br>Changed similarity metric to EUCLIDEAN<br><br>Updated search results:<br>Most similar documents: [&#39;Emma enjoyed her day at the park.&#39;, &#39;Emma pressed her palm against the chilled windowpane, mesmerized by the fragile, lacy patterns that the frost had etched across the glass. She yearned to reach through, to trace those intricate whorls and skim her fingertips through the frozen fractals glittering in the winter dawn.&#39;, &#39;The attic was a forgotten sanctuary where sunbeams danced through clouds of golden dust. Among the clutter, Alice discovered an intricate jewel-encrusted dagger - surely just an antique stage prop. But when she grasped its ornate hilt, her mind was gripped by visions of torchlit battles.&#39;]<br>Similarity scores: [0.9555073341195951, 1.1045957427381219, 1.1788095908610696]<br>Search time: 75.99 ms</pre><p>2. Using OpenAI embedding model (text-embedding-3-small):</p><pre>Loading embedding model...<br>Creating vector database for 10 documents...<br>VectorDatabase(total_documents=52, num_collections=1, embedding_model=OpenAIEmbeddingModel, similarity_metric=COSINE)<br><br>Most similar documents: [&#39;The park had many fun activities.&#39;, &#39;In the stillness of the autumn forest, a single crimson leaf drifted lazily downward, twirling and dancing through gilded shafts of sunlight. Lila watched it in silent reverie until it finally came to rest atop her upturned palm - a transient beauty now preserved in memory.&#39;]<br>Similarity scores: [0.13583580891232283, 0.1414692466575379]<br>Search time: 416.04 ms<br><br>Added 2 new documents. Total documents: VectorDatabase(total_documents=54, num_collections=1, embedding_model=OpenAIEmbeddingModel, similarity_metric=COSINE)<br><br>Updated search results:<br>Most similar documents: [&#39;The park had many fun activities.&#39;, &#39;The park had many fun activities.&#39;, &#39;In the stillness of the autumn forest, a single crimson leaf drifted lazily downward, twirling and dancing through gilded shafts of sunlight. Lila watched it in silent reverie until it finally came to rest atop her upturned palm - a transient beauty now preserved in memory.&#39;]<br>Similarity scores: [0.13583580891232283, 0.13583580891232283, 0.1414692466575379]<br>Search time: 415.67 ms</pre><p>Entries in the database look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2csImwLpW51nVorkJoxlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdpU4cw3EAR0FOeN2hYZag.png" /><figcaption>pgadmin view of the ingested documents</figcaption></figure><h3>Conclusion</h3><p>We have successfully implemented our own version of a vectorstore that is powered by PostgreSQL and pgvector. You can now try and improve on this by adding async and batch operations to make the ingestion even faster for larger documents; even try adding more embedding models! You can even replicate what <strong>langchain</strong> is doing with their implementation of the same at <a href="https://python.langchain.com/v0.2/docs/integrations/vectorstores/pgvector/"><strong>PGVector</strong></a><strong>. </strong>Hope you had fun!</p><p>You can find the code for the above at <a href="https://github.com/Maveric-k07/vecky/blob/main/main.py">GitHub</a>.</p><blockquote>Find more interesting articles on Backend and AI at <a href="https://medium.com/@gurramakhileshwar333">Medium</a></blockquote><blockquote>Connect with me: <a href="https://www.linkedin.com/in/akhileshwar-gurram-b434591b6/"><em>Linkedin</em></a><em> </em><a href="https://x.com/akhileshwar333"><em>Twitter</em></a><em> </em><a href="https://github.com/Maveric-k07"><em>GitHub</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d191cdd4d386" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Vector Stores: A Beginners Guide for Improved RAG Systems using Numpy]]></title>
            <link>https://medium.com/@gurramakhileshwar333/demystifying-vector-stores-a-beginners-guide-for-improved-rag-systems-using-numpy-a9bd9eba0142?source=rss-5cf0b082454f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9bd9eba0142</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Akhileshwar Gurram]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 09:47:40 GMT</pubDate>
            <atom:updated>2024-06-29T12:39:40.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-7bdzMkz_gPfCdO_DcJOg.jpeg" /><figcaption>Image generated by Microsoft Copilot.</figcaption></figure><p>In the world of natural language processing, vector stores have become indispensable tools, particularly for enhancing Retrieval-Augmented Generation (RAG) systems. But what exactly are vector stores, and how do they work under the hood? Let’s dive in with a simple implementation that showcases the core concepts.</p><h3><strong>What are Vector Stores?</strong></h3><p>At their core, vector stores are specialized databases designed to store and efficiently retrieve high-dimensional vector representations of data. In the context of NLP, these vectors typically represent the semantic meaning of text. The magic of vector stores lies in their ability to find similar vectors quickly, which translates to finding semantically similar text.</p><h3><strong>Why Vector Stores Matter for RAG</strong></h3><p>Retrieval-Augmented Generation systems rely heavily on finding relevant information to inform their outputs. Traditional keyword-based search often falls short when dealing with nuanced or conceptually similar content. Vector stores shine here by enabling <a href="https://en.wikipedia.org/wiki/Semantic_search"><strong>semantic search</strong></a> — finding content based on meaning rather than exact word matches. This significantly improves the quality and relevance of retrieved information, leading to more accurate and contextually appropriate generated responses.</p><h4><strong>Our Simple Vector Store Implementation</strong></h4><p>Let’s walk through a basic vector store implementation to understand the key components and processes involved. This code provides a foundation for understanding how production-grade vector stores operate.</p><h4><strong>Key Components:</strong></h4><ol><li><strong>VectorDatabase Class</strong>: The heart of our implementation.</li><li><strong>Embedding Model</strong>: We use SentenceTransformer to convert text to vectors.</li><li><strong>Similarity Metrics</strong>: We implement both Euclidean distance and Cosine similarity.</li><li><strong>Search Functionality</strong>: To find the most similar documents to a query.</li></ol><h4><strong>Code Walkthrough</strong></h4><p>Let’s break down the <a href="https://github.com/Maveric-k07/vecky/blob/main/vectordatabase.py"><strong>code</strong></a> step by step to understand its components and functionality.</p><ol><li>Enum Class for Similarity Metric</li></ol><pre>from enum import Enum<br>class SimilarityMetric(Enum):<br>    EUCLIDEAN = 1<br>    COSINE = 2</pre><p>This Enum class defines two types of similarity metrics: EUCLIDEAN and COSINE.</p><p>2. Measure Time Decorator</p><pre>import time<br><br>def measure_time(func):<br>    def wrapper(*args, **kwargs):<br>        start_time = time.time()<br>        result = func(*args, **kwargs)<br>        execution_time = (time.time() - start_time) * 1000  # Convert to milliseconds<br>        return result, execution_time<br><br>    return wrapper</pre><p>The measure_time decorator measures the execution time of a function in milliseconds. It wraps the function, recording the time before and after its execution.</p><p>3. <strong>VectorDatabase</strong> Class</p><p>The VectorDatabase class handles document embedding and similarity search.</p><pre>from typing import List, Tuple<br>import numpy as np<br>from sentence_transformers import SentenceTransformer<br><br>class VectorDatabase:<br>    def __init__(<br>        self,<br>        documents: List[str] = None,<br>        embedding_model: SentenceTransformer = None,<br>        similarity_metric: SimilarityMetric = SimilarityMetric.EUCLIDEAN,<br>    ):<br>        self.documents = np.array(documents) if documents else None<br>        self.embedding_model = embedding_model<br>        self.similarity_metric = similarity_metric<br>        self.embeddings = None<br>        self._set_similarity_function()</pre><ul><li>documents: List of documents to be stored.</li><li>embedding_model: A pre-trained model from SentenceTransformer to generate embeddings.</li><li>similarity_metric: The metric to use for similarity search (EUCLIDEAN by default).</li></ul><p>4. Function Setting Similarity Metric</p><pre>    def _set_similarity_function(self):<br>        if self.similarity_metric == SimilarityMetric.EUCLIDEAN:<br>            self._similarity_func = self._euclidean_distance<br>        elif self.similarity_metric == SimilarityMetric.COSINE:<br>            self._similarity_func = self._cosine_similarity<br>        else:<br>            raise ValueError(f&quot;Unsupported similarity metric: {self.similarity_metric}&quot;)</pre><p>This method sets the similarity function based on the chosen metric.</p><p>5. Similarity Functions</p><pre>    @staticmethod<br>    def _euclidean_distance(a, b):<br>        distances = np.linalg.norm(a - b, axis=1)<br>        return 1 / (1 + distances)  # Normalize to 0-1 range, where 1 is most similar<br><br>    @staticmethod<br>    def _cosine_similarity(a, b):<br>        norm_a = np.linalg.norm(a, axis=1, keepdims=True)<br>        norm_b = np.linalg.norm(b)<br>        cosine_sim = np.dot(a / norm_a, b / norm_b).flatten()<br>        return (cosine_sim + 1) / 2</pre><ul><li>_euclidean_distance: Computes Euclidean distance and normalizes it.</li><li>_cosine_similarity: Computes cosine similarity and scales it to the 0-1 range.</li></ul><p>6. Class Method for Initialization</p><pre>    @classmethod<br>    def from_documents(<br>        cls,<br>        documents: List[str],<br>        embedding_model: SentenceTransformer,<br>        similarity_metric: SimilarityMetric = SimilarityMetric.EUCLIDEAN,<br>    ) -&gt; &quot;VectorDatabase&quot;:<br>        instance = cls(documents, embedding_model, similarity_metric)<br>        instance.create_embeddings()<br>        return instance</pre><p>This class method initializes the VectorDatabase from a list of documents, creates embeddings, and returns the instance.</p><p>7. Creating Embeddings</p><pre>    def create_embeddings(self):<br>        if self.documents is None or self.embedding_model is None:<br>            raise ValueError(<br>                &quot;Documents and embedding model must be set before creating embeddings&quot;<br>            )<br>        self.embeddings = self.embedding_model.encode(self.documents)</pre><p>This method creates embeddings for the documents using the specified embedding model. In our case it is sentence_transformers/all-MiniLM-L12-v2 .</p><p>8. Search Method with Timing</p><pre>    @measure_time<br>    def search(self, query: str, k: int = 5) -&gt; Tuple[List[str], np.ndarray, float]:<br>        if self.embeddings is None:<br>            raise ValueError(<br>                &quot;Embeddings have not been created. Call create_embeddings() first.&quot;<br>            )<br><br>        query_embedding = self.embedding_model.encode([query])[0]<br>        similarities = self._similarity_func(self.embeddings, query_embedding)<br><br>        top_indices = np.argsort(similarities)[:k]<br>        top_documents = self.documents[top_indices].tolist()<br>        top_scores = similarities[top_indices]<br><br>        return top_documents, top_scores</pre><p>The search method finds the top k similar documents to the query:</p><ul><li>Encodes the query.</li><li>Computes similarities based on the metric selected.</li><li>Retrieves and returns the top k documents and their scores, along with the execution time.</li></ul><p>9. Adding New Documents</p><pre>    def add_documents(self, new_documents: List[str]):<br>        if self.documents is None:<br>            self.documents = np.array(new_documents)<br>        else:<br>            self.documents = np.concatenate((self.documents, np.array(new_documents)))<br><br>        new_embeddings = self.embedding_model.encode(new_documents)<br>        if self.embeddings is None:<br>            self.embeddings = new_embeddings<br>        else:<br>            self.embeddings = np.vstack((self.embeddings, new_embeddings))</pre><p>This method adds new documents to the existing database and updates the embeddings accordingly using <a href="https://numpy.org/doc/stable/reference/generated/numpy.vstack.html">np.vstack</a>.</p><h4>Let’s see a working example:</h4><p>This example demonstrates how to set up a vector database, perform searches, add new documents, and change the similarity metric for finding semantically similar documents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/604c43f99098c6cc4847cf0dd89c242d/href">https://medium.com/media/604c43f99098c6cc4847cf0dd89c242d/href</a></iframe><p>In the above example we are:</p><ol><li><strong>Loading the Embedding Model</strong>: Load a pre-trained <em>SentenceTransformer</em> model to convert text into vector embeddings.</li><li><strong>Prepare Documents</strong>: Create a list of documents by splitting a large text block into individual lines.</li><li><strong>Create the Vector Database</strong>: Initialize a VectorDatabase with the list of documents, the embedding model, and a chosen similarity metric (cosine similarity).</li><li><strong>Perform a Search</strong>: Search for the top k (e.g., 5) most similar documents to a query using the database and print the results, similarity scores, and search time.</li><li><strong>Add New Documents</strong>: Add additional documents to the database and update the embeddings accordingly.</li><li><strong>Change the Similarity Metric</strong>: Showcase switching the similarity metric from cosine similarity to Euclidean distance.</li><li><strong>Perform Another Search</strong>: Conduct the same search again with the updated similarity metric and print the new results, scores, and search time.</li></ol><h4><strong>Output</strong></h4><pre>Loading embedding model...<br>Creating vector database for 10 documents...<br>VectorDatabase(num_documents=10, embedding_model=SentenceTransformer, similarity_metric=COSINE)<br><br>Most similar documents: [&#39;No one could quite remember when the old railway handcar had been abandoned beside the rusting tracks. But every full moon, the neighborhood kids gathered to take turns pumping the stubborn lever, half-hoping the stubborn thing might finally roll to life with heavy metallic creaks.&#39;, &quot;The circus had left town weeks ago, but Timmy swore he could still hear the faint calling of the ringmaster&#39;s voice. He followed it into an overgrown field where the tattered remains of a striped tent lay haunting the weeds, casting serpentine shadows in the moonlight.&quot;]<br>Similarity scores: [0.57365686 0.5849615 ]<br>Search time: 25.90 ms<br><br>Added 2 new documents. Total documents: 12<br>Changed similarity metric to EUCLIDEAN<br><br>Updated search results:<br>Most similar documents: [&#39;The park had many fun activities.&#39;, &#39;No one could quite remember when the old railway handcar had been abandoned beside the rusting tracks. But every full moon, the neighborhood kids gathered to take turns pumping the stubborn lever, half-hoping the stubborn thing might finally roll to life with heavy metallic creaks.&#39;]<br>Similarity scores: [0.4259584 0.4336703]<br>Search time: 23.65 ms</pre><h4><strong>How It All Comes Together</strong></h4><ol><li>We initialize our database with a set of documents and an embedding model.</li><li>The documents are converted to vector embeddings.</li><li>When a search query comes in, it’s also converted to a vector.</li><li>We calculate the similarity between the query vector and all document vectors.</li><li>The most similar documents are returned as the search results.</li></ol><p>This simple implementation demonstrates the core concepts behind vector stores. In production systems, additional optimizations are added for speed and scale, and more efficient and powerful models and algorithms are used for indexing, chunking and clustering, but the fundamental idea remains the same.</p><h4><strong>Conclusion</strong></h4><p>By understanding how vector stores work, we can better appreciate their role in improving <strong>RAG</strong> systems. They enable semantic search capabilities that go beyond simple keyword matching, allowing for more nuanced and contextually relevant information retrieval. This, in turn, leads to more accurate and helpful generated responses in RAG applications.</p><p>You can find the code for the above at <a href="https://github.com/Maveric-k07/vecky/blob/main/vectordatabase.py">GitHub</a>.</p><p>Inspiration from: <a href="https://x.com/mrsiipa/status/1802336919659188305">https://x.com/mrsiipa/status/1802336919659188305</a></p><blockquote><em>In the next article let’s go work our way through improving the existing VectorStore for a more production ready application; powered by Postgres database and OpenAI’s embedding models.</em></blockquote><blockquote><em>Connect with me: </em><a href="https://www.linkedin.com/in/akhileshwar-gurram-b434591b6/">Linkedin</a> <a href="https://x.com/akhileshwar333">Twitter</a> <a href="https://github.com/Maveric-k07">GitHub</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9bd9eba0142" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring GPT-3: The Ultimate Guide to Fine-Tuning GPT3 with OpenAI]]></title>
            <link>https://medium.com/@gurramakhileshwar333/exploring-gpt-3-the-ultimate-guide-to-fine-tuning-gpt3-with-openai-4e2451179936?source=rss-5cf0b082454f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e2451179936</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[gpt-3]]></category>
            <dc:creator><![CDATA[Akhileshwar Gurram]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 09:49:27 GMT</pubDate>
            <atom:updated>2023-03-31T09:49:27.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aE5gDL0VOVAQYGAIibQDuQ.png" /></figure><h3>Introduction</h3><p>Let’s first get to know a little bit about GPT and how it works before diving into fine-tuning.</p><p>A language model is a type of machine learning model that is designed to predict the likelihood of the next word given the context and the current words. Essentially, a language model is trained on a large dataset of text, and it uses this data to learn patterns in the language, such as the likelihood of certain words following others. Once a language model is trained, it can be used for a variety of tasks, such as generating new text or predicting the next word in a sentence and GPT is an example of this.</p><p>GPT-3 (Generative Pre-trained Transformer 3) is a large, powerful language model developed by OpenAI that has been trained on a large corpus of text data, after scanning through the entirety of the internet on various datasets. Due to its large size and capability, GPT-3 can perform a wide variety of language-based tasks, including text generation, text completion, translation, and more.</p><h3>Why Fine-Tune GPT</h3><p>Fine-tuning GPT involves taking a pre-trained language model, such as GPT, and updating its parameters on a specific task or domain. Fine-tuning allows the model to adapt to a specific task by adjusting its learned parameters to better predict the text based on new training data.</p><p>There are several reasons why you might want to fine-tune GPT:</p><ol><li><strong>Adapt to a specific task:</strong> GPT is pre-trained on a large corpus of text, hence it better suits for general tasks and is optimized for a specific task, such as sentiment analysis or question-answering. Fine-tuning allows the model to adapt to the specific requirements of the task by updating its parameters.</li><li><strong>Improve performance:</strong> Fine-tuning can result in better accuracy and higher quality output, as it is focused on a specific task.</li><li><strong>Transfer learning:</strong> Fine-tuning a pre-trained model can be an effective form of transfer learning. Instead of training a new model from scratch, you can start with a pre-trained model and fine-tune it for your specific task. This can save time and resources while still achieving good results.</li></ol><h3>Fine-Tune GPT</h3><p>To fine-tune GPT-3, the pre-trained model is utilized as a starting point and trained on a smaller dataset that is tailored to the specific task at hand. This process involves initializing the pre-trained weights and adjusting the model’s parameters to the new data.</p><p>By fine-tuning GPT-3, its accuracy and effectiveness can be improved for specific tasks, making it a valuable tool for natural language processing applications.</p><h4>Getting the training dataset</h4><p>When fine-tuning a GPT-3 model, we need a training dataset that comprises examples tailored to the target task or field. The size of the dataset and structure may differ depending on the task’s complexity .</p><ul><li>Text generation tasks require datasets of text prompts and target outputs, enabling the model to learn how to generate appropriate text for each prompt.</li><li>Question-answering tasks use datasets containing question-answer pairs, which help the model generate accurate answers for similar questions.</li><li>Text classification tasks rely on labeled datasets comprising text samples and corresponding category labels.</li><li>Language translation tasks rely on parallel text examples in two languages, which the model uses to learn how to translate text between them.</li></ul><p>Let’s see a couple of examples for doing this:</p><ol><li><strong>Language Translation: </strong>Let’s say you want to fine-tune GPT-3 to translate specific sentences. You might create a dataset that consists of a set of text prompts and corresponding translation outputs. For example:</li></ol><pre>{&quot;prompt&quot;: &quot;Ich spreche kein Deutsch&quot;, &quot;completion&quot;: &quot;I don&#39;t speak German&quot;}<br>{&quot;prompt&quot;: &quot;La casa es grande y hermosa&quot;, &quot;completion&quot;: &quot;The house is big and beautiful&quot;}</pre><p>2. <strong>Text Generation: </strong>Suppose you’re working on an app that helps writers overcome blocks, they enter with whatever they’ve got so far and the completion would be a possible continuation that the writer can modify. For example:</p><pre>{&quot;prompt&quot;: &quot;The sun was setting over the horizon&quot;, &quot;completion&quot;: &quot;and the sky turned a beautiful shade of pink and orange.&quot;}<br>{&quot;prompt&quot;: &quot;The old house on the hill was abandoned&quot;, &quot;completion&quot;: &quot;and the windows were boarded up, but some say they could still hear strange noises coming from inside.&quot;}</pre><p>3. <strong>Sentiment analysis</strong> involves determining the degree of positivity or negativity in a particular tweet. A typical dataset for sentiment analysis might include examples that resemble the following format:</p><pre>{&quot;prompt&quot;:&quot;Overjoyed with the new iPhone! -&gt;&quot;, &quot;completion&quot;:&quot; positive&quot;}<br>{&quot;prompt&quot;:&quot;@lakers disappoint for a third straight night https://t.co/38EFe43 -&gt;&quot;, &quot;completion&quot;:&quot; negative&quot;}</pre><p>The training data must be a<strong> </strong><a href="https://jsonlines.org/"><strong>JSONL</strong></a> document, where each line is a prompt-completion pair corresponding to a training example. It should look like this:</p><pre>{&quot;prompt&quot;: &quot;&lt;prompt text&gt;&quot;, &quot;completion&quot;: &quot;&lt;ideal generated text&gt;&quot;}<br>{&quot;prompt&quot;: &quot;&lt;prompt text&gt;&quot;, &quot;completion&quot;: &quot;&lt;ideal generated text&gt;&quot;}<br>{&quot;prompt&quot;: &quot;&lt;prompt text&gt;&quot;, &quot;completion&quot;: &quot;&lt;ideal generated text&gt;&quot;}</pre><p>OpenAI has provided some <a href="https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset"><strong>best-practices</strong></a> for preparing our dataset, so as to get better training results.</p><h3>Let’s start the Fine-tuning</h3><h4>Step 1. Prepare the Dataset</h4><p>As we saw above, our training data needs to be in the JSONL format, and OpenAI has a great tool that takes a <strong>CSV, TSV, XLSX, JSON</strong> or <strong>JSONL</strong> file, and save the output into a JSONL file ready for fine-tuning, after guiding you through the process of suggested changes. We can create the JSONL files for both <strong>train</strong> and <strong>validation </strong>datasets. Check out more about the tool <a href="https://platform.openai.com/docs/guides/fine-tuning/cli-data-preparation-tool">here</a>.</p><h4>Step 2. Create a fine-tuned model</h4><p>Currently OpenAI supports Fine-Tuning of ada, babbage, curie, or davinci models, and the corresponding pricing for the Fine-Tuning is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*vjG8iu4VJ-CSAI_hzmnnsw.png" /></figure><p>Once you have chosen which model to Fine-Tune, you can use the OpenAI CLI to start the Fine-Tuning as follows:</p><p>Set your OpenAI API key in the CLI (You can install the CLI using <a href="https://pypi.org/project/openai/">PIP</a>):</p><p>On windows use <strong>set </strong>and on other machines use <strong>export</strong></p><pre>set OPENAI_API_KEY=&quot;&lt;OPENAI_API_KEY&gt;&quot;</pre><p>Creating a Fine-Tuning requires you to specify the model name and the path to the training file or the training file_id if the file is already uploaded. Other optional parameters you can use are:</p><ol><li>Validation file (for model validation)</li><li>Suffix (for giving your Fine-Tuned model a custom name)</li></ol><p>Other <a href="https://platform.openai.com/docs/guides/fine-tuning/hyperparameters">Hyperparameters</a> you can use are:</p><ul><li>model: The name of the base model to fine-tune. You can select one of &quot;ada&quot;, &quot;babbage&quot;, &quot;curie&quot;, or &quot;davinci&quot;. To learn more about these models, see the <a href="https://platform.openai.com/docs/models">Models</a> documentation.</li><li>n_epochs - defaults to 4. The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.</li><li>batch_size - defaults to ~0.2% of the number of examples in the training set, capped at 256. The batch size is the number of training examples used to train a single forward and backward pass. In general, we&#39;ve found that larger batch sizes tend to work better for larger datasets.</li><li>learning_rate_multiplier - defaults to 0.05, 0.1, or 0.2 depending on final batch_size. The fine-tuning learning rate is the original learning rate used for pretraining multiplied by this multiplier. We recommend experimenting with values in the range 0.02 to 0.2 to see what produces the best results. Empirically, we&#39;ve found that larger learning rates often perform better with larger batch sizes.</li><li>compute_classification_metrics - defaults to False. If True, for fine-tuning for classification tasks, computes classification-specific metrics (accuracy, F-1 score, etc) on the validation set at the end of every epoch.</li></ul><p>Start the Fine-Tune with the following command and change the parameters as required:</p><pre>openai api fine_tunes.create -t &lt;TRAIN_FILE_ID_OR_PATH&gt; \<br>  -v &lt;VALIDATION_FILE_ID_OR_PATH&gt; \<br>  -m &lt;MODEL&gt; \<br>  --suffix &quot;custom model name&quot;</pre><p>It could look something like this:</p><pre>openai api fine_tunes.create -t test.jsonl -v test.jsonl -m ada --suffix &quot;my-fine-tune&quot;</pre><p>Once you’ve initiated a fine-tune job, it may take a while to finish. Your job could be placed in a queue behind other jobs in our system, and the training process for our model could last for several minutes or even hours, depending on the model and the size of the dataset. In the event that the event stream is disrupted, you can continue it by executing:</p><pre>openai api fine_tunes.follow -i &lt;YOUR_FINE_TUNE_JOB_ID&gt;</pre><p>In addition to creating a fine-tune job, you can also list existing jobs, retrieve the status of a job, or cancel a job.</p><pre># List all created fine-tunes<br>openai api fine_tunes.list<br><br># Retrieve the state of a fine-tune. <br>openai api fine_tunes.get -i &lt;YOUR_FINE_TUNE_JOB_ID&gt;<br><br># Cancel a job<br>openai api fine_tunes.cancel -i &lt;YOUR_FINE_TUNE_JOB_ID&gt;</pre><p>After your Fine-Tuning job is done, you can access the results as follows:</p><pre>openai api fine_tunes.results -i &lt;YOUR_FINE_TUNE_JOB_ID&gt;</pre><p>Save the Fine-Tuning <strong>results </strong>to a csv as follows:</p><pre>openai api fine_tunes.results -i &lt;YOUR_FINE_TUNE_JOB_ID&gt; &gt; results.csv</pre><p>The csv will contain the following <strong>9</strong> columns for analysis:</p><p>step ,elapsed_tokens ,elapsed_examples ,training_loss,<br>training_sequence_accuracy ,training_token_accuracy ,validation_loss,<br>validation_sequence_accuracy ,validation_sequence_accuracy</p><h4>Step 3. Make Requests to the Fine-Tuned Model</h4><p>You can start making requests by passing the model name as the model parameter of a completion request:</p><p>OpenAI CLI:</p><pre>openai api completions.create -m &lt;FINE_TUNED_MODEL&gt; -p &lt;YOUR_PROMPT&gt;</pre><p>cURL:</p><pre>curl https://api.openai.com/v1/completions \<br>  -H &quot;Authorization: Bearer $OPENAI_API_KEY&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;prompt&quot;: YOUR_PROMPT, &quot;model&quot;: FINE_TUNED_MODEL}&#39;</pre><p>Python:</p><pre>import openai<br>response = openai.Completion.create(<br>    model=FINE_TUNED_MODEL,<br>    prompt=YOUR_PROMPT)</pre><h4>Step 4. <strong>Delete </strong>a Fine-Tuned model</h4><p>For deleting the created Fine-Tuned model, we can run:</p><pre>openai api models.delete -i &lt;FINE_TUNED_MODEL&gt;</pre><h3>Conclusion</h3><p>In this post, we have seen what GPT is and what it can do! For efficient integration of the GPT models with our applications, it is suggested to Fine-Tune a GPT model to our specific task, and now you can do it too!</p><p>References:<br><a href="https://platform.openai.com/docs/guides/fine-tuning/">https://platform.openai.com/docs/guides/fine-tuning/</a></p><blockquote><em>Connect with me:</em></blockquote><ul><li><a href="https://www.linkedin.com/in/akhileshwar-gurram-b434591b6/"><strong>Linkedin</strong></a></li><li><a href="https://twitter.com/AkhileshwarG07"><strong>Twitter</strong></a></li><li><a href="https://github.com/Maveric-k07"><strong>GitHub</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e2451179936" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Searchable PDF using AWS Textract — Get it running locally]]></title>
            <link>https://medium.com/@gurramakhileshwar333/searchable-pdf-using-aws-textract-get-it-running-locally-f3ec9a1b908b?source=rss-5cf0b082454f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3ec9a1b908b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-textract]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Akhileshwar Gurram]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 19:27:21 GMT</pubDate>
            <atom:updated>2023-03-21T19:48:02.256Z</atom:updated>
            <content:encoded><![CDATA[<h3>PDF to Searchable PDF using AWS Textract — Get it running locally</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*RYuGNj72k-iaf6E_allTTA.png" /></figure><p>We work with PDFs all the time, we scan important documents and notes as images and save them as PDFs. Here the PDF document is essentially a digital image of a physical document, and any text within the document is treated as an image.</p><p>Hence, you cannot select or search for text within the document, as it is not recognized as text by the computer.</p><p>On the other hand, a <strong>searchable</strong> PDF contains both images and text, and the text is recognized and stored as separate data within the PDF file. So, now you can select and search for text within the document, just as you would with a Word document or other text files. This makes it easier to find specific information within the document, as you can use keywords to search for relevant text.</p><p>There might be many reasons for you to convert your image PDF to a searchable one, let’s see how we can do that using AWS!</p><h3>AWS Textract</h3><p>One of the huge range of services made available for us to use by AWS includes <strong>Textract.</strong></p><blockquote><a href="https://docs.aws.amazon.com/textract/latest/dg/what-is.html"><strong>Amazon Textract</strong></a> is based on the same proven, highly scalable, deep-learning technology that was developed by Amazon’s computer vision scientists to analyze billions of images and videos daily. You don’t need any machine learning expertise to use it, as Amazon Textract includes simple, easy-to-use API operations that can analyze image files and PDF files</blockquote><h4><strong>Sync vs Async process</strong></h4><p>AWS Textract gives us the option to start an asynchronous process for analyzing a document (PDF or image). It orchestrates an entire architecture involving multiple stages for an efficient, reliable, and easy OCR process, where we just have to upload a PDF file to an <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html"><strong>S3 bucket</strong></a> and we get back the searchable pdf file.</p><p>This is made possible owing to the wide range of services provided by <a href="https://aws.amazon.com/products/"><strong>AWS</strong></a>, we have <strong>lambda</strong> functions, <strong>S3 buckets, SNS service, </strong>and<strong> DynamoDB</strong> in the pipeline shown in the <a href="https://github.com/aws-samples/amazon-textract-large-scale-selectable-pdf"><strong>AWS samples repo</strong></a><strong> </strong>(check it out for the code to set up and run the asynchronous document process)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBuHnQ5C2gIspqRUVXTIlw.png" /><figcaption>Architecture diagram of the <em>large-scale-selectable-pdf</em> application. Image from <a href="https://github.com/aws-samples/amazon-textract-large-scale-selectable-pdf">GitHub</a></figcaption></figure><p>As we can see, this is a large-scale solution for processing a high number of multi-page PDFs and making them searchable. Of course, this comes at a cost, in the pay-per-use model of AWS you will have to pay for the resources used for processing your documents. Check out the pricing models for various services by AWS <a href="https://aws.amazon.com/pricing/?aws-products-pricing.sort-by=item.additionalFields.productNameLowercase&amp;aws-products-pricing.sort-order=asc&amp;awsf.Free%20Tier%20Type=*all&amp;awsf.tech-category=*all">here</a>.</p><p>However, for processing a single or a handful of multi-paged documents we don’t require the entire architecture. Let’s see how we can get it running locally!</p><h3>Searchable PDF</h3><p>To begin making API requests to AWS Textract, first, we need to have an AWS account and have the AWS CLI installed on our machine. Make sure to also add the configuration details for your AWS account in the CLI. Follow <a href="https://repost.aws/knowledge-center/create-and-activate-aws-account"><strong>this</strong></a><strong> </strong>and <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html"><strong>this</strong></a><strong> </strong>for a step-by-step procedure to do the above.</p><p>Now that we have our AWS account setup, let’s look at an example PDF that we’re going to use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*l8myeRxUqunNbZ0fSB113Q.png" /><figcaption>Scanned image saved as a PDF document.</figcaption></figure><p>The above document is non-searchable, let’s use it as the input and generate a searchable PDF of the same.</p><h3>Setting up our work environment</h3><p>Create a new working directory named “<strong><em>myapp” :</em></strong></p><pre>$ mkdir myapp<br>$ cd myapp</pre><p>Now let’s create a virtual environment and activate it:</p><pre>$ python -m venv venv<br>$ source venv/bin/activate</pre><p>Add the following dependencies to your <em>requirements.txt</em> file:</p><pre>boto3<br>PyMuPDF</pre><p>Install the dependencies from your terminal:</p><pre>(venv)$ pip install -r requirements.txt</pre><p>Let’s now use the <em>input.pdf </em>file and create a searchable PDF from it as follows:</p><p>In your <em>main.py </em>add:</p><pre>import boto3<br>import json<br><br>textract_client = boto3.client(&quot;textract&quot;)<br><br>with open(&quot;input.pdf&quot;, &quot;rb&quot;) as document_file:<br>    print(document_file)<br>    document_bytes = document_file.read()<br><br>    response = textract_client.analyze_document(<br>        Document={&quot;Bytes&quot;: document_bytes}, FeatureTypes=[&#39;TABLES&#39;,&#39;FORMS&#39;]<br>    )<br><br>    json.dump(response, open(&quot;response.json&quot;, &quot;w&quot;))</pre><p>Here, we are using the <strong><em>analyze_document </em></strong>API of the Textract client using <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/textract/client/analyze_document.html"><strong>Boto3</strong></a>. We are sending a blob of base64-encoded document bytes in the <strong>Document </strong>parameter, and in the <strong>FeatureTypes </strong>we want Textract to identify tables and forms in our PDF document.</p><p>We are saving the response from the <strong><em>analyze_document </em></strong>to the <em>response.json </em>file for further processing.</p><p>Run the <em>main.py </em>and you should see a <em>response.json </em>appear if everything goes well!</p><pre>(venv)$ python main.py</pre><p>Let’s use the <strong><em>geometry.py </em></strong>file from the aws-samples repo from <a href="https://github.com/aws-samples/amazon-textract-large-scale-selectable-pdf/blob/main/selectable_pdf_infra/selectable_pdf_infra/lambda_layer/helpertools/helpertools/geometry.py"><strong>here</strong></a><strong>. </strong>Your <em>geometry.py </em>file should look as follows:</p><pre>&#39;&#39;&#39;<br>&#39;&#39;&#39;<br>from typing import Dict, Optional<br><br># classes<br># -------<br>class BoundingBox():<br>    &#39;&#39;&#39;<br>    Class to manipulate a bounding box (bbox). A bounding box is a rectangle aligned with <br>    the coordinate system. The bounding box are defined on coordinate system with x <br>    pointing toward east and y pointing toward north. This is the usual coordinate <br>    system used in euclidian geometry (i.e. lower left origin). Note that images <br>    generally have a a cordinate system defined with a upper left origin. <br>    &#39;&#39;&#39;<br>    # constructors<br>    def __init__(self, left: float, bottom: float, right: float, top: float) -&gt; None:<br>        &#39;&#39;&#39;<br>        constructor.<br>        &#39;&#39;&#39;<br>        self.bounds = [left, bottom, right, top]<br>        <br>    @classmethod<br>    def from_textract_bbox(cls, textract_bbox: Dict[str, float]) -&gt; None:<br>        &#39;&#39;&#39;<br>        Construct a BoundingBox object from the bounding box defined by an AWS Textract <br>        output json. As Textract uses a coordinate system with a upper left origin <br>        (i.e. y pointing downward), the definition of bottom=top+height (note <br>        the &quot;+&quot;, instead of a &quot;-&quot;).<br>        &#39;&#39;&#39;<br>        return cls(<br>            left=textract_bbox[&#39;Left&#39;],<br>            bottom=textract_bbox[&#39;Top&#39;]+textract_bbox[&#39;Height&#39;],<br>            right=textract_bbox[&#39;Left&#39;]+textract_bbox[&#39;Width&#39;],<br>            top=textract_bbox[&#39;Top&#39;],<br>        )<br><br>    # class methods<br>    def scale(self, x_scale: None, y_scale: Optional[float]=None) -&gt; None:<br>        &#39;&#39;&#39;<br>        Scale a bounding box by a  x and y factor. If y is not defined, the bbox is <br>        scaled by x in all directions<br>        &#39;&#39;&#39;<br>        if not y_scale:<br>            y_scale = x_scale<br>        self.bounds[0] *= x_scale<br>        self.bounds[1] *= y_scale<br>        self.bounds[2] *= x_scale<br>        self.bounds[3] *= y_scale<br><br>    # overload methods<br>    def __getitem__(self, key):<br>        return self.bounds[key]<br><br>    def __setitem__(self, key, value):<br>        self.bounds[key] = value<br><br>    # getters<br>    @property<br>    def left(self) -&gt; float:<br>        return self.bounds[0]<br><br>    @property<br>    def bottom(self) -&gt; float:<br>        return self.bounds[1]<br><br>    @property<br>    def right(self) -&gt; float:<br>        return self.bounds[2]<br><br>    @property<br>    def top(self) -&gt; float:<br>        return self.bounds[3]<br><br>    @property<br>    def width(self) -&gt; float:<br>        return abs(self.bounds[0]-self.bounds[2])<br><br>    @property<br>    def height(self) -&gt; float:<br>        return abs(self.bounds[3]-self.bounds[1])</pre><p>This class will help us in manipulating the bounding boxes in our document as required.</p><p>Now, let’s process the response.json and create a new searchable PDF, add the following to your <strong><em>process.py</em></strong> file:</p><pre>import json<br>import fitz<br>from geometry import BoundingBox<br>import math<br>from typing import Dict, Optional, List, Any<br><br><br># ----------------------------------------------<br><br>def make_pdf_doc_searchable(<br>    pdf_doc: fitz.Document,<br>    textract_blocks: List[Dict[str, Any]],<br>    add_word_bbox: bool = False,<br>    show_selectable_char: bool = False,<br>    pdf_image_dpi: int = 200,<br>    verbose: bool = False,<br>) -&gt; fitz.Document:<br>    &quot;&quot;&quot; &quot;&quot;&quot;<br>    # save the pages as images (jpg) and buddle these images into a pdf document (pdf_doc_img)<br>    pdf_doc_img = fitz.open()<br>    for ppi, pdf_page in enumerate(pdf_doc.pages()):<br>        pdf_pix_map = pdf_page.get_pixmap(dpi=pdf_image_dpi, colorspace=&quot;RGB&quot;)<br>        pdf_page_img = pdf_doc_img.new_page(<br>            width=pdf_page.rect.width, height=pdf_page.rect.height<br>        )<br>        xref = pdf_page_img.insert_image(rect=pdf_page.rect, pixmap=pdf_pix_map)<br>    pdf_doc.close()<br><br>    # add the searchable character to the image PDF and bounding boxes if required by user<br>    print_step = 1000<br>    bbox_color = (220 / 255, 20 / 255, 60 / 255)  # red-ish color<br>    fontsize_initial = 15<br>    for blocki, block in enumerate(textract_blocks):<br>        if verbose:<br>            if blocki % print_step == 0:<br>                print(<br>                    (<br>                        f&quot;processing blocks {blocki} to {blocki+print_step} out of {len(textract_blocks)} blocks&quot;<br>                    )<br>                )<br>        if block[&quot;BlockType&quot;] == &quot;WORD&quot;:<br>            # get the page object<br>            page = 0  # zero-counting<br>            pdf_page = pdf_doc_img[page]<br>            # get the bbox object and scale it to the page pixel size<br>            bbox = BoundingBox.from_textract_bbox(block[&quot;Geometry&quot;][&quot;BoundingBox&quot;])<br>            bbox.scale(pdf_page.rect.width, pdf_page.rect.height)<br><br>            # draw a bbox around each word<br>            if add_word_bbox:<br>                pdf_rect = fitz.Rect(bbox.left, bbox.top, bbox.right, bbox.bottom)<br>                pdf_page.draw_rect(<br>                    pdf_rect,<br>                    color=bbox_color,<br>                    fill=None,<br>                    width=0.7,<br>                    dashes=None,<br>                    overlay=True,<br>                    morph=None,<br>                )<br><br>            # add some text next to the bboxs<br>            fill_opacity = 1 if show_selectable_char else 0<br>            text = block[&quot;Text&quot;]<br>            text_length = fitz.get_text_length(<br>                text, fontname=&quot;helv&quot;, fontsize=fontsize_initial<br>            )<br>            fontsize_optimal = int(<br>                math.floor((bbox.width / text_length) * fontsize_initial)<br>            )<br>            rc = pdf_page.insert_text(<br>                point=fitz.Point(bbox.left, bbox.bottom),  # bottom-left of 1st char<br>                text=text,<br>                fontname=&quot;helv&quot;,  # the default font<br>                fontsize=fontsize_optimal,<br>                rotate=0,<br>                color=bbox_color,<br>                fill_opacity=fill_opacity,<br>            )<br><br>    return pdf_doc_img<br><br># ----------------------------------------------<br><br><br>doc = fitz.open(&quot;input.pdf&quot;)<br>data = json.load(open(&quot;response.json&quot;))<br><br>textract_blocks = data[&quot;Blocks&quot;]<br>print(f&quot;no. of blocks {len(textract_blocks)}&quot;)<br><br>num_word_blocks = 0<br>for blk in textract_blocks:<br>    if blk[&quot;BlockType&quot;] == &quot;WORD&quot;:<br>        num_word_blocks += 1<br>print(f&quot;number of WORD blocks {num_word_blocks}&quot;)<br><br>selectable_pdf_doc = make_pdf_doc_searchable(<br>    pdf_doc=doc,<br>    textract_blocks=textract_blocks,<br>    add_word_bbox=True,<br>    show_selectable_char=False,<br>    pdf_image_dpi=200,<br>    verbose=True,<br>)<br><br>selectable_pdf_doc.save(&quot;output.pdf&quot;)</pre><p><strong><em>make_pdf_doc_searchable </em></strong>is a utility function that takes in the PDF doc, textract_blocks from the response as input along with other parameters to generate a new PDF that is now searchable. We have set the <strong><em>add_word_bbox=True </em></strong>to draw the bounding boxes for each word identified during OCR.</p><p>Now, let’s run the <em>process.py </em>file to create a new searchable PDF:</p><pre>(venv)$ python process.py</pre><p>Your <em>output.pdf </em>should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*p3GA6vlbjhJU3KJTDUYzjg.png" /><figcaption>Searchable PDF as an output.</figcaption></figure><h3>Conclusion</h3><p>And we’re done! We took a simple image saved as a PDF document and made it into a searchable one using AWS Textract for OCR. This PDF now has the ability to search for text and also has the bounding boxes information for us to use.</p><p>For a long-running job with a large number of multi-page PDF documents, it is recommended to use the architecture provided by AWS <a href="https://github.com/aws-samples/amazon-textract-large-scale-selectable-pdf/">here</a>.</p><p>Caution: This method currently works only for single-paged PDF files, will update this article once I have figured out how to do the same for multi-page PDFs.</p><blockquote><em>Connect with me:</em></blockquote><ul><li><a href="https://www.linkedin.com/in/akhileshwar-gurram-b434591b6/">Linkedin</a></li><li><a href="https://twitter.com/AkhileshwarG07">Twitter</a></li><li><a href="https://github.com/Maveric-k07">GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3ec9a1b908b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get your Beanies: A Beginner’s Guide to Beanie — MongoDB ODM for Python]]></title>
            <link>https://medium.com/@gurramakhileshwar333/get-your-beanies-a-beginners-guide-to-beanie-mongodb-odm-for-python-b715c3f59a92?source=rss-5cf0b082454f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b715c3f59a92</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mongo]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Akhileshwar Gurram]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 10:53:37 GMT</pubDate>
            <atom:updated>2023-03-19T12:54:45.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>Get your Beanies: A Beginner’s Guide to Beanie — MongoDB ODM for Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*6iCMUYHxAPeKrnzR1AFisg.png" /><figcaption>MongoDb — one of the most widely used no-SQL database</figcaption></figure><p>Working with MongoDB in Python and constantly dealing with low-level details like connecting to the database or manually serializing and de-serializing data can be tiring.</p><h3>ODM libraries to the rescue</h3><p>Object-document mapping (ODM) libraries abstract away the complexities of MongoDB and allow you to work with Python objects instead. With an ODM, you can focus on your application logic instead of worrying about database connections, query languages, and other low-level details.</p><p>There are several ODM libraries available for Python, including Motor, MongoEngine, and Beanie. While each of these libraries has its own strengths and weaknesses, I believe that Beanie provides a great starting point for most of the CRUD projects used in applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8K6miUML6RgrM_KaUVMBw.png" /><figcaption>Beanie — Asynchronous Python object-document mapper (ODM) for MongoDB</figcaption></figure><p>Beanie offers a clean and intuitive syntax, a powerful data model system, and first-class <strong>asyncio</strong> support. Plus, with Beanie, you get the benefits of the latest MongoDB features and optimizations. Let’s now give Beanie a try and see how it can simplify your development with MongoDB using python <strong>FastAPI</strong>?</p><h4>Setting up our environment with FastAPI and Beanie</h4><p>Create a new working directory named “<strong><em>myapp” :</em></strong></p><pre>$ mkdir myapp<br>$ cd myapp</pre><p>Now let’s create a virtual environment and activate it:</p><pre>$ python -m venv venv<br>$ source venv/bin/activate</pre><p>Next, create the following files and folders:</p><pre>├── app<br>│   ├── __init__.py<br>│   ├── main.py<br>│   └── server<br>│       ├── app.py<br>│       ├── database.py<br>│       ├── models<br>│       └── routes<br>|       └── utils<br>|          ├── pydantic_encoder.py<br>└── requirements.txt</pre><p>Add the following dependencies to your <em>requirements.txt</em> file:</p><pre>beanie<br>fastapi<br>uvicorn</pre><p>Install the dependencies from your terminal:</p><pre>(venv)$ pip install -r requirements.txt</pre><p>In the <em>app/main.py</em> file, define an entry point for running our application:</p><pre>import uvicorn<br><br>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(&quot;server.app:app&quot;, host=&quot;0.0.0.0&quot;, port=8000, reload=True)</pre><p>Here, we run a <a href="https://www.uvicorn.org/">uvicorn</a> server on port:8000 and reload on every file change.</p><p>Before starting the server via the entry point file, let’s create a base route in <em>server/app.py</em>:</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br><br>@app.get(&quot;/&quot;, tags=[&quot;Root&quot;])<br>async def index() -&gt; dict:<br>    return {&quot;message&quot;: &quot;Welcome to your books app!&quot;}</pre><p>Let’s now run the <em>main.py</em> file to test out our FastAPI setup:</p><pre>(venv)$ python app/main.py</pre><p>Go to <a href="http://localhost:8000/">http://localhost:8000</a> in your browser. You should see:</p><pre>{<br>  &quot;message&quot;: &quot;Welcome to your books app&quot;<br>}</pre><h3>What Are We Building?</h3><p>We’ll be building a book — review application that allow us perform the following operations:</p><ul><li>Create books</li><li>Add reviews</li><li>Read books</li><li>Update books</li><li>Delete books</li></ul><p>Let’s use Beanie to configure the database model for our application.</p><h3>Database Schema</h3><p>Beanie allows us to create <a href="https://roman-right.github.io/beanie/api-documentation/document/">documents</a> that are used to interact with collections in the database. Documents represent our database schema. They are defined by creating child classes that inherit the Document class from Beanie. The Document class is powered by Pydantic&#39;s BaseModel, which makes it simple to build collections, database schema, and sample data shown in the interactive Swagger docs page.</p><p>For example:</p><pre>from beanie import Document<br><br><br>class Blog(Document):<br>    title: str<br>    content: str<br>    date: datetime<br>    author: str<br><br>    class Settings:<br>        name = &quot;blog_collection&quot;</pre><p>The document defined represents how articles will be stored in the database. However, it’s a normal document class with no database collection associated with it. To associate a collection, we simply add a Settings class as a subclass.</p><p>Now that we have an idea of how schemas are created, let’s create the schema for our application. In the “server/models” folder, create a new file called book<em>.py</em>:</p><pre>from beanie import Document<br>from pydantic import BaseModel<br>from typing import Optional<br><br><br>class Book(Document):<br>    title: str<br>    author: str<br>    published_year: int<br>    reviews: list[str] = []<br><br>    class Settings:<br>        name = &quot;books_collection&quot;<br></pre><p>We could very well define sample schema data to make it simpler for developers to use the API using the interactive Swagger docs, using the Config subclass like so:</p><pre>from beanie import Document<br>from pydantic import BaseModel<br>from typing import List, Optional<br><br><br>class Review(Document):<br>    review: str<br><br><br>class Book(Document):<br>    title: str<br>    author: str<br>    published_year: int<br>    reviews: List[str] = []<br><br>    class Settings:<br>        name = &quot;books&quot;<br><br>    class Config:<br>        schema_extra = {<br>            &quot;example&quot;: {<br>                &quot;title&quot;: &quot;The Great Gatsby&quot;,<br>                &quot;author&quot;: &quot;F. Scott Fitzgerald&quot;,<br>                &quot;published_year&quot;: 1925,<br>                &quot;review&quot;: &quot;Excellent course!&quot;,<br>            }<br>        }<br><br><br>class UpdateBook(BaseModel):<br>    title: Optional[str]<br>    author: Optional[str]<br>    published_year: Optional[int]</pre><p>Here we have defined a Beanie document calledBook that represents how a book will be stored in thebook_collection . We have also added the UpdateBook pydantic model that will help us in updating the book details.</p><p>This schema will be used in the routes to enforce the proper request body.</p><h3>MongoDB</h3><p>In this section, we’ll connect to MongoDB and configure our application to communicate with it.</p><blockquote><em>According to </em><a href="https://en.wikipedia.org/wiki/MongoDB"><em>Wikipedia</em></a><em>, MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.</em></blockquote><h3>MongoDB Setup</h3><p>If you don’t have MongoDB installed on your machine, refer to the <a href="https://docs.mongodb.com/manual/installation/">installation</a> guide from the docs. Once installed, continue with the guide to run the <a href="https://docs.mongodb.com/manual/reference/program/mongod/#bin.mongod"><strong>mongod</strong></a> daemon process. Once done, you can verify that MongoDB is up and running, by connecting to the instance via the mongo shell command:</p><pre>$ mongo</pre><pre>$ mongo --version<br>MongoDB shell version v6.0.0<br><br>Build Info: {<br>    &quot;version&quot;: &quot;6.0.0&quot;,<br>    &quot;gitVersion&quot;: &quot;e61bf27c2f6a83fed36e5a13c008a32d563babe2&quot;,<br>    &quot;modules&quot;: [],<br>    &quot;allocator&quot;: &quot;tcmalloc&quot;,<br>    &quot;environment&quot;: {<br>        &quot;distarch&quot;: &quot;x86_64&quot;,<br>        &quot;target_arch&quot;: &quot;x86_64&quot;<br>    }<br>}</pre><p>This tutorial uses MongoDB Community Edition v6.0.0.</p><h3>Set up the Database</h3><p>In server/d<em>atabase.py</em>, add the following:</p><pre>from beanie import init_beanie<br>import motor.motor_asyncio<br><br>from server.models.book import Book<br><br><br>async def init_db():<br>    client = motor.motor_asyncio.AsyncIOMotorClient(<br>        &quot;mongodb://localhost:27017&quot;<br>    )<br><br>    #client = motor.motor_asyncio.AsyncIOMotorClient(<br>    #    &quot;mongodb+srv://&lt;username&gt;:&lt;password&gt;@cluster0.zlhkso0.mongodb.net/?retryWrites=true&amp;w=majority&quot;<br>    #)<br><br>    await init_beanie(database=client.db_name, document_models=[Book])</pre><p>We imported the <a href="https://roman-right.github.io/beanie/tutorial/initialization/">init_beanie</a> method which is responsible for initializing the database engine powered by <a href="https://motor.readthedocs.io/en/stable/api-asyncio/asyncio_motor_client.html#motor.motor_asyncio.AsyncIOMotorClient">motor.motor_asyncio</a>. The init_beanie method takes two arguments:</p><ol><li>database - The name of the database to be used.</li><li>document_models - A list of document models defined -- the Book model, in our case.</li></ol><p>You can either connect to a local instance of mongo, by running the <a href="https://www.mongodb.com/docs/manual/reference/program/mongod/"><em>mongod</em></a><em> daemon, </em>or connect to a cloud mongoDb instance at mongoDb Atlas using the uri.</p><p>The init_db function will be invoked in the application startup event. Update <em>app.py</em> to include the startup event:</p><pre>from fastapi import FastAPI<br>from server.database import init_db<br><br>app = FastAPI()<br><br>@app.on_event(&quot;startup&quot;)<br>async def start_db():<br>    await init_db()<br><br>@app.get(&quot;/&quot;, tags=[&quot;Root&quot;])<br>async def read_root() -&gt; dict:<br>    return {&quot;message&quot;: &quot;Welcome to your beanie powered app!&quot;}</pre><p>Now that we have our database configurations in place, let’s get to the routes.</p><h3>Routes</h3><p>In this section, we’ll build the routes to perform CRUD operations on our database from the application:</p><ol><li>POST book</li><li>GET single book and GET all books</li><li>PUT (update) single book</li><li>PATCH new review for a book</li><li>DELETE single book</li></ol><p>In the “routes” folder, create a file called book<em>.py</em></p><pre>from fastapi import APIRouter, HTTPException, status<br><br>from server.models.book import Book<br><br>router = APIRouter()</pre><p>PydanticObjectId will be used for type hinting the ID argument when fetching a single request. We also imported the <em>APIRouter </em>class, which manages route operations. We have the model class that was previously defined.</p><p>We can interact with the database directly and write less code thanks to Beanie document models. In a database collection, for instance, all we need to do to get all the records is:</p><pre>books = await Book.find_all().to_list()<br>return books</pre><p>Let’s now register the route in our <em>app.py</em></p><pre>from fastapi import FastAPI<br>from server.database import init_db<br><br>from server.routes.book import router as Router<br><br><br>app = FastAPI()<br>app.include_router(Router, tags=[&quot;Books&quot;], prefix=&quot;/books&quot;)<br><br><br>@app.on_event(&quot;startup&quot;)<br>async def start_db():<br>    await init_db()<br><br><br>@app.get(&quot;/&quot;, tags=[&quot;Root&quot;])<br>async def index() -&gt; dict:<br>    return {&quot;message&quot;: &quot;Welcome to your books app!&quot;}</pre><h4>Create</h4><p>In <em>routes/book.py</em>, add the following:</p><pre>@router.post(&quot;/&quot;, status_code=status.HTTP_201_CREATED, response_model=Book)<br>async def create_book(book: Book):<br>    await book.insert()<br>    return book</pre><p>Here, we defined the route function, which takes an argument of the type Book. As stated earlier, the document class can interact with the database directly. We are also defining a response status code and a response model for ease of use.</p><p>The new record is created by calling the <a href="https://beanie-odm.dev/api-documentation/document/#documentinsert">insert()</a> method.</p><p>You can now test out this route at <a href="http://localhost:8000/docs">http://localhost:8000/docs</a>, FastAPI provides us with cool UI for testing out our API powered by OpenAPI docs and SwaggerUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNePPC40RPUZCpaqEYbpLQ.png" /><figcaption>Try out the route with the example document</figcaption></figure><p>After executing you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtF-XO6tuAMPuiWdf-jRtw.png" /><figcaption>Document inserted to our db</figcaption></figure><p>Congratulations! We have successfully inserted a document into the database. Let’s now work on fetching the document/s from it.</p><h4>Read</h4><p>In <em>routes/book.py</em>, add the following:</p><pre>from typing import List<br><br>@router.get(&quot;/&quot;, response_model=List[Book])<br>async def get_books():<br>    books = await Book.find_all().to_list()<br>    return books<br><br><br>@router.get(&quot;/{id}&quot;, response_model=Book)<br>async def get_book(id: PydanticObjectId):<br>    book = await Book.get(id)<br>    if not book:<br>        raise HTTPException(<br>            status_code=status.HTTP_404_NOT_FOUND, detail=f&quot;Book with id {id} not found&quot;<br>        )<br><br>    return book</pre><p>In the code block above, we defined two functions:</p><ol><li>In the first function, we retrieved all the books using the <a href="https://roman-right.github.io/beanie/tutorial/finding-documents/#finding-documents">find_all()</a> method. The to_list() method is appended so the results are returned in a list.</li><li>In the second, the function takes an ID of type ObjectiD, the default encoding for MongoDB IDs. The record is retrieved using the <a href="https://roman-right.github.io/beanie/api-documentation/document/#documentget">get()</a> method.</li></ol><p>Let’s test out this route at <a href="http://localhost:8000/docs">http://localhost:8000/docs</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHj2pUZLJnZvfddcpxTh0g.png" /><figcaption>Get all books</figcaption></figure><p>We can test it out using the following curl request as well:</p><pre>curl -X &#39;GET&#39; \<br>  &#39;http://localhost:8000/books/&#39; \<br>  -H &#39;accept: application/json&#39;</pre><p>We can also get a single book with its <em>id </em>as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1w8ZgGAFErzpE3GdSQVgQ.png" /><figcaption>Getting the book with its <strong><em>id</em></strong></figcaption></figure><h4>Update</h4><p>Next, let’s build the route for updating the details of the book:</p><p>We need an encoder function while updating to only account for the values that are not <em>None. </em>Add the following to the <em>utils/pydantic_encoder.py </em>file:</p><pre>from fastapi.encoders import jsonable_encoder<br><br><br>def encode_input(data) -&gt; dict:<br>    data = jsonable_encoder(data)<br>    data = {k: v for k, v in data.items() if v is not None}<br>    return data</pre><p>Now, let’s add the route for updating the book:</p><pre>from server.models.book import UpdateBook<br><br>@router.put(&quot;/{id}&quot;, response_model=Book)<br>async def update_book(id: PydanticObjectId, book_data: UpdateBook):<br>    book = await Book.get(id)<br>    if not book:<br>        raise HTTPException(<br>            status_code=status.HTTP_404_NOT_FOUND, detail=f&quot;Book with id {id} not found&quot;<br>        )<br>    book_data = pydantic_encoder.encode_input(book_data)<br>    _ = await book.update({&quot;$set&quot;: book_data})<br>    updated_book = await Book.get(id)<br>    return updated_book</pre><p>Let’s test this out by updating our book at <a href="http://localhost:8000/docs">http://localhost:8000/docs</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Izi3ReGw8bYimlUWH2Uwww.png" /><figcaption>Test out the route with only the attributes you want to update</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3KnObgDRBc1ncy0zMUycGw.png" /><figcaption>Successful update in the db</figcaption></figure><h4>Add Review</h4><p>Let’s build a route to add reviews to the book:</p><pre>@router.post(&quot;/{id}/reviews&quot;, response_model=Book)<br>async def add_review(id: PydanticObjectId, review: str):<br>    book = await Book.get(id)<br>    if not book:<br>        raise HTTPException(<br>            status_code=status.HTTP_404_NOT_FOUND, detail=f&quot;Book with id {id} not found&quot;<br>        )<br>    _ = await book.update({&quot;$push&quot;: {&quot;reviews&quot;: review}})<br>    updated_book = await book.get(id)<br>    return updated_book</pre><p>Here, we are appending a review to the <em>reviews </em>list of a Book object. This is done using the <strong><em>$push</em></strong><em> </em>operator. Let’s test this route by adding reviews to our book.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dt_StU1q4irtaNYY714usQ.png" /><figcaption>Adding reviews to a particular book.</figcaption></figure><h4>Delete</h4><p>Let’s finally add the delete route to our <em>api_router</em> now:</p><pre>@router.delete(&quot;/{id}&quot;, status_code=status.HTTP_204_NO_CONTENT)<br>async def delete_book(id: PydanticObjectId):<br>    book = await Book.get(id)<br>    if not book:<br>        raise HTTPException(<br>            status_code=status.HTTP_404_NOT_FOUND, detail=f&quot;Book with id {id} not found&quot;<br>        )<br>    await book.delete()<br>    return {&quot;message&quot;: &quot;Book deleted successfully&quot;}</pre><p>So, we first checked if the record exists before deleting it. The record is deleted by calling the <a href="https://roman-right.github.io/beanie/api-documentation/document/#documentdelete">delete()</a> method.</p><p>Testing this out at <a href="http://localhost:8000/docs">http://localhost:8000/docs</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cLLbOLdJ1Xj0R5QkqMmZw.png" /><figcaption>204 response indicates a successful deletion.</figcaption></figure><h3>Conclusion</h3><p>In this tutorial, we learnt how to use FastAPI, MongoDB, and Beanie ODM to develop a CRUD application. We have also seen how to test out our routes using the <em>docs </em>provided by FastAPI. You can find the code used in this tutorial at <a href="https://github.com/Maveric-k07/Beanie-CRUD">GitHub</a>.</p><p>Hope you had fun!</p><p>What else can we do?</p><ol><li>Set up unit and integration tests with <strong><em>pytest</em></strong>.</li><li>Add additional routes and functionality, maybe authentication!</li><li>Create a GitHub repo for your application and configure CI/CD with GitHub Actions.</li><li>Deploy this application on AWS lambda, and add CI/CD to it.</li></ol><blockquote>Connect with me:</blockquote><ul><li><a href="https://www.linkedin.com/in/akhileshwar-gurram-b434591b6/">Linkedin</a></li><li><a href="https://twitter.com/AkhileshwarG07">Twitter</a></li><li><a href="https://github.com/Maveric-k07">GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b715c3f59a92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>