Python fastapi asyncio or threading + multiprocessing, which is better approach

Please help me find out a best (better) approach to use multiprocessing with fastapi

I have a project where i have one endpoint. Where heavy ocr model(easyocr) is imported and initialized in different process.

When you are sending image to, it will send it to other process via multiprocessing.Manager().Queue()

And here are a real problem. I don’t know a good way to wait/await for a moment when other process will recognize text from this image and then re awake to send it to user

I dont want to create new process every time some one make a request, cuz it will take very long time to import easyocr module and init its model.

Here is a structure of my project:

verbumapi/  
├── __init__.py  
├── easyocr_api
│   ├── __init__.py
│   ├── recognition.py
│   └── router.py
├── main.py
├── multiproc_manager
│   ├── __init__.py
│   └── manager.py

Here is code:
main.py

import multiprocessing

from fastapi import FastAPI

from verbumapi.easyocr_api.router import router as router_easyocr
from verbumapi.multiproc_manager.manager import (
    easyocr_img_queue,
    easyocr_text_shared_dict
)
from verbumapi.easyocr_api.recognition import easyocr_process


app = FastAPI(title='VerbumAPI')

app.include_router(router_easyocr)

easyocr_process = multiprocessing.Process(
    target=easyocr_process, args=(easyocr_img_queue, easyocr_text_shared_dict)
)

easyocr_process.start()

multiproc_manager/manager.py

from multiprocessing import Manager


manager = Manager()

easyocr_img_queue = manager.Queue()
easyocr_text_shared_dict = manager.dict()

easyocr_api/recognition.py

from multiprocessing.managers import DictProxy # noqa
from multiprocessing.queues import Queue

list_of_langs = ['en', 'ru']

def easyocr_process(img_queue: Queue, text_shared_dict: DictProxy):
    import easyocr

    model = easyocr.Reader(list_of_langs)

    while True:
        if img_queue.empty():
            continue
        image, img_hash = img_queue.get()
        
        result = model.readtext(
            image,
            paragraph=True,
            detail=0,
            decoder='wordbeamsearch',
            beamWidth=15,
        )

        text_shared_dict[img_hash] = result

easyocr_api/router.py


import asyncio
import hashlib

from fastapi import APIRouter, Depends, UploadFile, File

from verbumapi.easyocr_api.recognition import get_loaded_languages
from verbumapi.multiproc_manager.manager import (
    easyocr_img_queue,
    easyocr_text_shared_dict,
)
from verbumapi.utils import validate_and_read_img

router = APIRouter(
    prefix='/easyocr',
    tags=['EasyOCR'],
)

# HERE is question about this function
@router.post('/recognize')
async def recognize(image: bytes = Depends(validate_and_read_img)):
    image_hash = hashlib.md5(image).hexdigest()

    easyocr_img_queue.put((image, image_hash))
    
    await asyncio.sleep(0.020)
    while image_hash not in easyocr_text_shared_dict:
        await asyncio.sleep(0.020)

    text = easyocr_text_shared_dict.pop(image_hash)
    return {
        'data': text,
        'detail': 'text from image was successfully recognized',
    }

What is the best way to “wait” for result from other process in recognize(image: bytes = Depends(validate_and_read_img))

The way I already have
OR
This way

@router.post('/recognize')
# removed async
def recognize(image: bytes = Depends(validate_and_read_img)):
    image_hash = hashlib.md5(image).hexdigest()

    easyocr_img_queue.put((image, image_hash))
    
    # removed await statements and sleep
    while image_hash not in easyocr_text_shared_dict:
        pass

    text = easyocr_text_shared_dict.pop(image_hash)
    return {
        'data': text,
        'detail': 'text from image was successfully recognized',
    }

So it will force FastAPI to create thread for this endpoint

OR any other way?

Which way will be the fastest and more optimized?

New contributor

ReYaN WTF is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật