# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/adapters.ipynb.

# %% auto 0
__all__ = ['np_2_b64', 'b64_2_np', 'b64_2_file']

# %% ../nbs/adapters.ipynb 2
import base64, cv2, numpy as np
from typing import Union
from .loader import logger
from .paths import P

# %% ../nbs/adapters.ipynb 3
def np_2_b64(image: np.ndarray) -> str:
    """Convert a numpy image to base64 string"""
    img_str = cv2.imencode(".jpg", image)[1].tobytes()
    img_b64 = base64.b64encode(img_str).decode("utf-8")
    return img_b64


def b64_2_np(input: str) -> np.ndarray:
    input = bytes(input, "utf-8")
    input = base64.b64decode(input)
    img_nparr = np.frombuffer(input, np.uint8)
    img_cv2 = cv2.imdecode(img_nparr, cv2.IMREAD_COLOR)
    img_rgb = cv2.cvtColor(img_cv2, cv2.COLOR_BGR2RGB)
    return img_rgb


def b64_2_file(
    input: str, # base64 encoded string
    fpath: Union[str, P] # Place where you want to save the file
    ) -> None:
    """Save a file encoded as a base64 `input` at given `fpath`"""
    with open(fpath, "wb") as pdf_file:
        input = bytes(input, "utf-8")
        input = base64.b64decode(input)
        pdf_file.write(input)
        logger.info(f"wrote pdf file to {fpath}")
