<?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 Bibek Lamichhane on Medium]]></title>
        <description><![CDATA[Stories by Bibek Lamichhane on Medium]]></description>
        <link>https://medium.com/@lamichhane.kebib?source=rss-108de0e84b8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Bibek Lamichhane on Medium</title>
            <link>https://medium.com/@lamichhane.kebib?source=rss-108de0e84b8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:18:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lamichhane.kebib/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 Journey with PDF Content Extraction and Embeddings]]></title>
            <link>https://medium.com/@lamichhane.kebib/my-journey-with-pdf-content-extraction-and-embeddings-f04160ccd7bb?source=rss-108de0e84b8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f04160ccd7bb</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Bibek Lamichhane]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 09:29:25 GMT</pubDate>
            <atom:updated>2024-10-16T09:29:25.900Z</atom:updated>
            <content:encoded><![CDATA[<p>As a backend engineer, I recently embarked on an interesting project aimed at extracting text, tables, and images from PDFs, along with calculating embeddings to enable semantic search and document similarity. This project took me through a variety of technologies and approaches, from PDF extraction in Golang to embedding models in Python, offering me deep insights into both traditional backend work and AI-based solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zAMxJ70zEdXjjJiK50iSQ.png" /></figure><p><strong>Initial Challenges with PDF Extraction in Golang</strong></p><p>At the start of the project, I was tasked with extracting content from PDFs using Golang. Naturally, I explored various popular libraries, including:</p><ul><li><strong>pdfcpu</strong></li><li><strong>UniPDF</strong></li><li><strong>rsc/pdf</strong></li><li><strong>jung-kurt/gofpdf</strong></li><li><strong>seehuhn/go-pdf</strong></li></ul><p>While these libraries offered basic functionality, none provided the level of accuracy and precision we needed in terms of extracting images, tables, and styled text. The formatting, particularly text alignment (left, right, justified, center), was hard to maintain, which made it challenging for our specific requirements.</p><p>After discussing the limitations with my team, we decided to explore Python-based libraries, given Python’s rich ecosystem for handling PDFs and text processing.</p><h4>Transitioning to Python and PyMuPDF</h4><p>I came across the <strong>PyMuPDF</strong> library (also known as <strong>fitz</strong>), and the results were quite promising. It allowed me to extract the content of PDFs — text, images, and metadata — with a higher degree of accuracy compared to the Golang packages I had tried. PyMuPDF’s documentation was comprehensive, and I found numerous articles and resources that helped me understand how to utilize the library effectively.</p><p>However, while working with text extraction, I encountered an issue: I couldn’t maintain the formatting of the text, such as alignment (left, center, justified), which was crucial for our project. Despite this limitation, I was able to extract text and metadata and store them in PostgreSQL. The extracted content was stored in <strong>JSON format</strong> and <strong>text</strong> for further analysis.</p><h4>Embedding PDFs and Vector Search with pgvector</h4><p>As the project evolved, the requirements expanded to include embedding the content of PDFs for semantic search and similarity comparison. Being a junior backend engineer with limited knowledge of embeddings, I had a steep learning curve ahead of me.</p><p>I first attempted to set up <strong>pgvector</strong> (a PostgreSQL extension for storing and querying vector embeddings) on my local machine, but I encountered several issues. Eventually, I turned to Docker for an easier setup, which worked flawlessly.</p><p>Working with large PDFs (sometimes exceeding 60–70 pages), I needed to handle embedding efficiently. Since embedding models have limitations on context length, I implemented a <strong>chunking</strong> mechanism to break large PDFs into smaller sections, then generated embeddings for each chunk and stored them in the database.</p><h4>Using Mistral and BGE-Base-EN Embeddings</h4><p>Initially, I used API keys for generating embeddings, but I encountered issues with rate limits when using <strong>OpenAI’s embedding API</strong>. After researching alternatives, I experimented with <strong>Mistral AI embeddings</strong>. Eventually, after consulting with an AI mentor, I switched to using the <strong>BGE-Large-EN model</strong> for embeddings, which fit our needs better.</p><p>However, my local machine (with just 4GB DDR3 RAM and an i5 5th-gen CPU) couldn’t handle the BGE-Large model, so I switched to the <strong>BGE-Base-EN-v1.5</strong> model, which worked perfectly within my hardware limitations.</p><h4>Calculating Similarity Between PDFs</h4><p>One of the final tasks I worked on was calculating the similarity between PDFs. Given that we had chunked the PDFs, each document had multiple embeddings. My approach was to:</p><ol><li><strong>Compute the mean embedding</strong> for the chunked text from the given PDF.</li><li>Select embeddings of other PDFs, compute their mean embeddings, and store them in a variable.</li><li><strong>Calculate the cosine similarity</strong> (also known as <strong>L2 distance</strong>) between the mean embeddings of the two PDFs.</li></ol><p>This approach allowed us to compute the similarity between large PDF documents efficiently and effectively.</p><h3>Lessons Learned</h3><p>Working on this project was a significant learning experience for me. I became comfortable with PDF content extraction, embeddings, and handling large documents in chunks. I also gained hands-on experience with setting up and using <strong>pgvector</strong> for vector search in PostgreSQL. Additionally, diving into <strong>cosine similarity</strong> and learning to work with <strong>LLM embeddings</strong> added to my growing skill set in AI-related backend tasks.</p><p>Moving forward, I plan to continue exploring more advanced embedding models and further refine the PDF similarity engine we’ve developed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f04160ccd7bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Implementation of Go Project Structure]]></title>
            <link>https://medium.com/@lamichhane.kebib/clean-implementation-of-go-project-structure-1f01cc60d581?source=rss-108de0e84b8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f01cc60d581</guid>
            <category><![CDATA[project-structure]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Bibek Lamichhane]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 04:42:35 GMT</pubDate>
            <atom:updated>2024-09-25T04:42:35.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this blog post, we’ll explore a clean and modular project structure for a Go application, following the principles of clean architecture. We’ll create a simple REST API with user signup, login, and profile management features, using Gin as the web framework and MongoDB as the database.</p><h3>Project Architecture</h3><p>Our project follows a clean architecture pattern, with the following directories and their responsibilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*HmHxkB5VAH74JB4bCT4-TQ.png" /><figcaption>architecture</figcaption></figure><h3>Directory Explanation</h3><ol><li><strong>api</strong>: Contains the API-related code, including controllers, middleware, and route binding.</li><li><strong>bootstrap</strong>: Initializes the application, database, and environment variables.</li><li><strong>cmd</strong>: Holds the main application file that starts the server.</li><li><strong>domain</strong>: Defines the domain entities, value objects, and interfaces.</li><li><strong>internal</strong>: Contains internal utility functions and packages.</li><li><strong>mongo</strong>: MongoDB-related code, such as database initialization and client management.</li><li><strong>repository</strong>: Implements the data access layer, interacting with the database.</li><li><strong>usecase</strong>: Contains the business logic and use cases for the application.</li></ol><pre><br>.├── Dockerfile           # Image file<br>├── api<br>│   ├── controller       # Controllers<br>│   ├── middleware       # Middleware (JWT authentication)<br>│   └── route            # Route binding<br>├── bootstrap<br>│   ├── app.go           # Core class<br>│   ├── database.go      # Database<br>│   └── env.go           # Configuration class<br>├── cmd<br>│   └── main.go          # Startup command<br>├── docker-compose.yaml  <br>├── domain               # Domain layer<br>├── go.mod               <br>├── go.sum               <br>├── internal             # Internal utilities<br>│   └── tokenutil        <br>├── mongo                # MongoDB<br>│   └── mongo.go         <br>├── repository           # Repository layer<br>└── usecase              # Use case layer</pre><h4>Parameter Configuration &amp; Project Startup</h4><p>In cmd/main.go, we set up the application, configure environment variables, and start the Gin server:</p><pre>./cmd/main.go</pre><pre>type Application struct {<br>    Env   *Env<br>    Mongo mongo.Client<br>}<br><br>type Env struct {<br>    AppEnv            string `mapstructure:&quot;APP_ENV&quot;`<br>    ServerAddress     string `mapstructure:&quot;SERVER_ADDRESS&quot;`<br>    ContextTimeout    int    `mapstructure:&quot;CONTEXT_TIMEOUT&quot;`<br>    DBHost            string `mapstructure:&quot;DB_HOST&quot;`<br>    DBPort            string `mapstructure:&quot;DB_PORT&quot;`<br>    ...<br>}<br><br>func main() {<br>    // app is the instance of the entire application, managing key resources throughout its lifecycle<br>    app := bootstrap.App()<br>    <br>    // Configuration variables<br>    env := app.Env<br>    <br>    // Database instance<br>    db := app.Mongo.Database(env.DBName)<br>    defer app.CloseDBConnection()<br>    <br>    timeout := time.Duration(env.ContextTimeout) * time.Second<br>    <br>    // Creating a gin instance<br>    gin := gin.Default()<br>    <br>    // Route binding<br>    route.Setup(env, timeout, db, gin)<br>    <br>    // Running the server<br>    gin.Run(env.ServerAddress)<br>}</pre><h4>Interface Layer</h4><p>In the api/controller directory, we define the interface for the use case layer and implement the controller methods:</p><pre>./api/controller/login_controller.go</pre><pre><br>// Business layer interface<br><br><br>type SignupUsecase interface {<br>    Create(c context.Context, user *User) error<br>    GetUserByEmail(c context.Context, email string) (User, error)<br>    CreateAccessToken(user *User, secret string, expiry int) (accessToken string, err error)<br>    CreateRefreshToken(user *User, secret string, expiry int) (refreshToken string, err error)<br>}<br>​<br>type LoginController struct {<br>   LoginUsecase domain.LoginUsecase<br>   Env          *bootstrap.Env<br>}<br>​<br>func (lc *LoginController) Login(c *gin.Context) {<br>   var request domain.LoginRequest<br>​<br>   err := c.ShouldBind(&amp;request)<br>   if err != nil {<br>      c.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: err.Error()})<br>      return<br>   }<br>​<br>   user, err := lc.LoginUsecase.GetUserByEmail(c, request.Email)<br>   if err != nil {<br>      c.JSON(http.StatusNotFound, domain.ErrorResponse{Message: &quot;User not found with the given email&quot;})<br>      return<br>   }<br>​<br>   if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(request.Password)) != nil {<br>      c.JSON(http.StatusUnauthorized, domain.ErrorResponse{Message: &quot;Invalid credentials&quot;})<br>      return<br>   }<br>​<br>   accessToken, err := lc.LoginUsecase.CreateAccessToken(&amp;user, lc.Env.AccessTokenSecret, lc.Env.AccessTokenExpiryHour)<br>   if err != nil {<br>      c.JSON(http.StatusInternalServerError, domain.ErrorResponse{Message: err.Error()})<br>      return<br>   }<br>​<br>   refreshToken, err := lc.LoginUsecase.CreateRefreshToken(&amp;user, lc.Env.RefreshTokenSecret, lc.Env.RefreshTokenExpiryHour)<br>   if err != nil {<br>      c.JSON(http.StatusInternalServerError, domain.ErrorResponse{Message: err.Error()})<br>      return<br>   }<br>​<br>   loginResponse := domain.LoginResponse{<br>      AccessToken:  accessToken,<br>      RefreshToken: refreshToken,<br>   }<br>​<br>   c.JSON(http.StatusOK, loginResponse)<br>}</pre><h4>Business Layer</h4><p>In the usecase directory, we implement the business logic and use cases, following the interface defined in the interface layer:</p><pre>./usecase/login_usecase.go</pre><pre><br><br>// Data anti-corruption layer interface<br>type UserRepository interface {<br>    Create(c context.Context, user *User) error<br>    Fetch(c context.Context) ([]User, error)<br>    GetByEmail(c context.Context, email string) (User, error)<br>    GetByID(c context.Context, id string) (User, error)<br>}<br>​<br>type loginUsecase struct {<br>   userRepository domain.UserRepository<br>   contextTimeout time.Duration<br>}<br>​<br>func NewLoginUsecase(userRepository domain.UserRepository, timeout time.Duration) domain.LoginUsecase {<br>   return &amp;loginUsecase{<br>      userRepository: userRepository,<br>      contextTimeout: timeout,<br>   }<br>}<br>​<br>func (lu *loginUsecase) GetUserByEmail(c context.Context, email string) (domain.User, error) {<br>   ctx, cancel := context.WithTimeout(c, lu.contextTimeout)<br>   defer cancel()<br>   return lu.userRepository.GetByEmail(ctx, email)<br>}<br>​<br>func (lu *loginUsecase) CreateAccessToken(user *domain.User, secret string, expiry int) (accessToken string, err error) {<br>   return tokenutil.CreateAccessToken(user, secret, expiry)<br>}<br>​<br>func (lu *loginUsecase) CreateRefreshToken(user *domain.User, secret string, expiry int) (refreshToken string, err error) {<br>   return tokenutil.CreateRefreshToken(user, secret, expiry)<br>}</pre><h4>Repository Layer</h4><p>In the repository directory, we implement the data access layer, interacting with the MongoDB database:</p><pre>./repository/user_repository.go</pre><pre><br><br>// Data operation layer interface<br><br><br>type Database interface {<br>    Collection(string) Collection<br>    Client() Client<br>}<br>​<br>type userRepository struct {<br>   database   mongo.Database<br>   collection string<br>}<br>​<br>func NewUserRepository(db mongo.Database, collection string) domain.UserRepository {<br>   return &amp;userRepository{<br>      database:   db,<br>      collection: collection,<br>   }<br>}<br>​<br>func (ur *userRepository) Create(c context.Context, user *domain.User) error {<br>   collection := ur.database.Collection(ur.collection)<br>​<br>   _, err := collection.InsertOne(c, user)<br>​<br>   return err<br>}<br>​<br>func (ur *userRepository) Fetch(c context.Context) ([]domain.User, error) {<br>   collection := ur.database.Collection(ur.collection)<br>​<br>   opts := options.Find().SetProjection(bson.D{{Key: &quot;password&quot;, Value: 0}})<br>   cursor, err := collection.Find(c, bson.D{}, opts)<br>​<br>   if err != nil {<br>      return nil, err<br>   }<br>​<br>   var users []domain.User<br>​<br>   err = cursor.All(c, &amp;users)<br>   if users == nil {<br>      return []domain.User{}, err<br>   }<br>​<br>   return users, err<br>}<br>​<br>func (ur *userRepository) GetByEmail(c context.Context, email string) (domain.User, error) {<br>   collection := ur.database.Collection(ur.collection)<br>   var user domain.User<br>   err := collection.FindOne(c, bson.M{&quot;email&quot;: email}).Decode(&amp;user)<br>   return user, err<br>}<br>​<br>func (ur *userRepository) GetByID(c context.Context, id string) (domain.User, error) {<br>   collection := ur.database.Collection(ur.collection)<br>​<br>   var user domain.User<br>​<br>   idHex, err := primitive.ObjectIDFromHex(id)<br>   if err != nil {<br>      return user, err<br>   }<br>​<br>   err = collection.FindOne(c, bson.M{&quot;_id&quot;: idHex}).Decode(&amp;user)<br>   return user, err<br>}</pre><h4>Data Layer</h4><p>In the mongo directory, we initialize the MongoDB client and provide methods to interact with the database:</p><pre>./mongo/mongo.go</pre><pre>type mongoDatabase struct {<br>   db *mongo.Database<br>}<br>​<br>func (md *mongoDatabase) Collection(colName string) Collection {<br>    collection := md.db.Collection(colName)<br>    return &amp;mongoCollection{coll: collection}<br>}<br>​<br>func (md *mongoDatabase) Client() Client {<br>    client := md.db.Client()<br>    return &amp;mongoClient{cl: client}<br>}</pre><h3>Singleton and Encapsulation</h3><p>In the route package, we set up the route binding for the application, following the singleton and encapsulation principles:</p><pre><br><br>func Setup(env *bootstrap.Env, timeout time.Duration, db mongo.Database, gin *gin.Engine) {<br>   publicRouter := gin.Group(&quot;&quot;)<br>   // All Public APIs<br>   NewSignupRouter(env, timeout, db, publicRouter)<br>   NewLoginRouter(env, timeout, db, publicRouter)<br>   NewRefreshTokenRouter(env, timeout, db, publicRouter)<br>​<br>   protectedRouter := gin.Group(&quot;&quot;)<br>   // Middleware to verify AccessToken<br>   protectedRouter.Use(middleware.JwtAuthMiddleware(env.AccessTokenSecret))<br>   // All Private APIs<br>   NewProfileRouter(env, timeout, db, protectedRouter)<br>   NewTaskRouter(env, timeout, db, protectedRouter)<br>}</pre><p>By following this clean architecture pattern, we achieve a modular, testable, and maintainable Go application. The project structure promotes separation of concerns, making it easier to understand, develop, and scale the application over time.<br>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f01cc60d581" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>