In this blog post, we’ll embark on an exciting journey of building an Image Captioning API using FastAPI and Hugging Face Transformers. Image captioning is a fascinating task that involves generating textual descriptions for given images. By leveraging the power of deep learning and natural language processing, we can create a system that automatically understands the content of an image and generates human-like captions. The example below, I input a image with a rider on a bike in a garage and the caption provides the exact details of the image.

Project Overview
👨💻 GitHub: https://github.com/askaresh/blip-image-captioning-api
The goal of this project is to develop a RESTful API that accepts an image as input and returns a generated caption describing the image. We’ll be using FastAPI, a modern and fast web framework for building APIs, along with Hugging Face Transformers, a popular library for natural language processing tasks.
The key components of our project include:
- FastAPI: A web framework for building efficient and scalable APIs in Python.
- Hugging Face Transformers: A library that provides state-of-the-art pre-trained models for various NLP tasks, including image captioning.
- Docker: A containerization platform that allows us to package our application and its dependencies into a portable and reproducible environment.
Implementation Details
To build our Image Captioning API, we started by setting up a FastAPI project and defining the necessary endpoints. The main endpoint accepts an image file and an optional text input for conditional image captioning.
We utilized the pre-trained BLIP (Bootstrapping Language-Image Pre-training) model from Hugging Face Transformers for image captioning. BLIP is a powerful model that has been trained on a large dataset of image-caption pairs and achieves impressive results in generating accurate and coherent captions.
To ensure a smooth development experience, and ability for it to run on AnyCloud I containerized our application using Docker. This allowed us to encapsulate all the dependencies, including Python libraries and the pre-trained model, into a portable and reproducible environment.
HF-IT-DOCKER/
│
├── app/
│ ├── config.py
│ ├── main.py
│ ├── model.py
│ └── utils.py
│
├── .dockerignore
├── .gitignore
├── compose.yaml
├── Dockerfile
├── logging.conf
├── README.Docker.md
└── requirements.txt
Detailed description of each file:
- app/config.py:
- This file contains the configuration settings for the application.
- It defines a
Settingsclass using thepydantic_settingslibrary to store and manage application-specific settings. - The
blip_model_namesetting specifies the name of the BLIP model to be used for image captioning.
- app/main.py:
- This is the main entry point of the FastAPI application.
- It sets up the FastAPI app, loads the BLIP model, and configures logging.
- It defines the API endpoints, including the root path (“/”) and the image captioning endpoint (“/caption”).
- The “/caption” endpoint accepts an image file and an optional text input, processes the image, generates a caption using the BLIP model, and returns the generated caption.
- app/model.py:
- This file contains the functions related to loading and using the BLIP model for image captioning.
- The
load_modelfunction loads the pre-trained BLIP model and processor based on the specified model name. - The
generate_captionfunction takes an image and optional text input, preprocesses the inputs, and generates a caption using the loaded BLIP model.
- app/utils.py:
- This file contains utility functions used in the project.
- The
load_image_from_filefunction reads an image file and converts it to the appropriate format (RGB) using the PIL library.
- .dockerignore:
- This file specifies the files and directories that should be excluded when building the Docker image.
- It helps to reduce the size of the Docker image by excluding unnecessary files and directories.
- .gitignore:
- This file specifies the files and directories that should be ignored by Git version control.
- It helps to keep the repository clean by excluding files that are not necessary to track, such as generated files, cache files, and environment-specific files.
- compose.yaml:
- This file contains the configuration for Docker Compose, which is used to define and run multi-container Docker applications.
- It defines the services, including the FastAPI server, and specifies the build context, ports, and any necessary dependencies.
- Dockerfile:
- This file contains the instructions for building the Docker image for the FastAPI application.
- It specifies the base image, sets up the working directory, installs dependencies, copies the application code, and defines the entry point for running the application.
- logging.conf:
- This file contains the configuration for the Python logging system.
- It defines the loggers, handlers, formatters, and their respective settings.
- It specifies the log levels, log file paths, and log message formats.
- README.Docker.md:
- This file provides documentation and instructions specific to running the application using Docker.
- It may include information on how to build the Docker image, run the container, and any other Docker-related details.
- requirements.txt:
- This file lists the Python dependencies required by the application.
- It includes the necessary libraries and their versions, such as FastAPI, Hugging Face Transformers, PIL, and others.
- It is used by pip to install the required packages when building the Docker image or setting up the development environment.
Lessons Learned and Debugging
Throughout the development process, I encountered several challenges and learned valuable lessons:
- Dependency Management: Managing dependencies can be tricky, especially when working with large pre-trained models. We learned the importance of properly specifying dependencies in our requirements file and using Docker to ensure consistent environments across different systems.
- Debugging Permission Issues: We encountered permission-related issues when running our application inside a Docker container. Through debugging, we learned the significance of properly setting file and directory permissions and running the container as a non-root user to enhance security.
- Logging Configuration: Proper logging is crucial for understanding the behavior of our application and troubleshooting issues. I learned how to configure logging using a configuration file and ensure that log files are written to directories with appropriate permissions.
- Testing and Error Handling: Comprehensive testing and error handling are essential for building a robust API. We implemented thorough error handling to provide meaningful error messages to API users and conducted extensive testing to ensure the reliability of our image captioning functionality.
Validation of the API
After the container is up and running go to http://localhost:8004/docs and select Post method and pick try out. Upload any image of your choice and enter the text (optional) and further click Execute. You will have the caption below as the output.


Conclusion
Building an Image Captioning API with FastAPI and Hugging Face Transformers has been an incredible learning experience. By leveraging the power of pre-trained models and containerization, I created a scalable and efficient solution for generating image captions automatically.
Through this project, I gained valuable insights into dependency management, debugging permission issues, logging configuration, and the importance of testing and error handling. These lessons will undoubtedly be applicable to future projects and contribute to our growth as developers.
I hope that this blog post has provided you with a comprehensive overview of our Image Captioning API project and inspired you to explore the fascinating world of image captioning and natural language processing. Feel free to reach out with any questions or suggestions, and happy captioning!
Thanks,
Aresh Sarkari


Recent Comments