Search⌘ K
AI Features

Implement OCR API Using FastAPI - 2

Explore how to create an OCR API by saving images to a server, extracting text using Tesseract with FastAPI, and handling multiple image uploads asynchronously. Understand the process flow for optimizing API response time with concurrent processing.

Save images to the server

Let’s now create a function that accepts your image, the path of the directory on the server where you want to store the image, and the name of the saved image. We can name this function _save_file_to_server().

Python 3.8
import shutil
import os
def _save_file_to_server(uploaded_file, path=".", save_as="default"):
extension = os.path.splitext(uploaded_file.filename)[-1]
temp_file = os.path.join(path, save_as + extension)
with open(temp_file, "wb") as buffer:
shutil.copyfileobj(uploaded_file.file, buffer)
return temp_file

Explanation

  • On line 1, we import the required packages.

  • On line 3, we define our function and also assign the default values to the path parameter and the save_as parameter, which is the name of the image while saving on the server.

  • On line 5, we try to find out the extension of the uploaded file. In our case, it can be png, jpg, or any other image format.

  • On line 6, we create the image path using the os module.

  • On lines 8 and 9, we copy the uploaded image onto our server directory. ...