import base64
from io import BytesIO
from typing import Optional
from IPython.display import HTML
from PIL import Image

def image_from_base64(encoded_string):
    return Image.open(BytesIO(base64.b64decode(encoded_string)))

def preview(mmbench_df, max_rows: Optional[int] = 5, random_state = 42):
    assert 'image' in mmbench_df.columns, "DataFrame must contain an 'image' column"

    def image_formatter(encoded_string):
        return f'<img src="data:image/jpeg;base64,{encoded_string}">'

    if max_rows is not None and len(mmbench_df) > max_rows:
        mmbench_df = mmbench_df.sample(n=max_rows, random_state=random_state)

    return HTML(mmbench_df.to_html(formatters={'image': image_formatter}, escape=False, index=False))
