Skip to content

Commit

Permalink
Improved Docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
PointlessUser committed Jun 29, 2023
1 parent 37b0433 commit f40e7a9
Show file tree
Hide file tree
Showing 7 changed files with 402 additions and 113 deletions.
64 changes: 50 additions & 14 deletions mecsimcalc/general_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,43 @@ def input_to_file(
input_file: str, metadata: bool = False
) -> Union[io.BytesIO, Tuple[io.BytesIO, str]]:
"""
Converts a base64 encoded string into a file object and metadata
>>> input_to_file(
input_file: str,
metadata: bool = False
) -> Union[io.BytesIO, Tuple[io.BytesIO, str]]
Args:
input_file (str): Base64 encoded string, prefixed with metadata
metadata (bool, optional): Flag to return metadata with the file. (Defaults to False)
Transforms a Base64 encoded string into a file object. Optionally, the file metadata can also be returned.
Raises:
ValueError: If the input string doesn't contain ';base64,' which is required to separate metadata and file data.
# Parameters
input_file : str
A Base64 encoded string prefixed with metadata.
metadata : bool, optional
If set to True, the function also returns the metadata. Default is False.
Returns:
io.BytesIO: If metadata is False, return the decoded file data (The thing you get when you open a file in Python)
(io.BytesIO, str): If metadata is True, returns a tuple containing the decoded file data and its metadata.
# Raises
* `ValueError`:
If the input string does not contain ';base64,' which is required to separate metadata and file data.
# Returns
* `Union[io.BytesIO, Tuple[io.BytesIO, str]]` :
* `metadata | False` : io.BytesIO - Returns a file object containing the file data.
* `metadata | True` : Tuple[io.BytesIO, str] - Returns a tuple containing the file object and the metadata.
**Note:** The file object is open and can be used with Python file functions (e.g., file.read()).
# Examples
**Without metadata**
>>> input_file = inputs["input_file"]
>>> file = msc.input_to_file(input_file)
(file is now ready to be used with Python file functions) (e.g., file.read())
**With metadata**
>>> input_file = inputs["input_file"]
>>> file, metadata = msc.input_to_file(input_file, metadata=True)
(metadata holds information about the file, such as the file type)
"""
if ";base64," not in input_file:
raise ValueError("Invalid input: must contain ';base64,'")
Expand All @@ -33,13 +58,24 @@ def input_to_file(

def metadata_to_filetype(metadata: str) -> str:
"""
Extracts the file type from the metadata
>>> metadata_to_filetype(metadata: str) -> str
Extracts the file type from the metadata string.
# Parameters
metadata : str
A metadata string typically in the form "Data:<MIME type>;base64,"
Args:
metadata (str): Metadata string typically in the form "Data:<MIME type>;base64,"
# Returns
* `str` :
The extracted file type (e.g., 'csv'). For a Microsoft Excel file, it returns 'xlsx'.
Returns:
str: Extracted file type (e.g. "csv"). For a Microsoft Excel file, it returns "xlsx".
# Example
>>> input_file = inputs["input_file"]
>>> file, metadata = msc.input_to_file(input_file, metadata=True)
>>> file_type = msc.metadata_to_filetype(metadata)
>>> print(file_type)
jpeg
"""
match = re.search(r"/(.+);base64,", metadata)
file_type = match[1] if match else ""
Expand Down
150 changes: 119 additions & 31 deletions mecsimcalc/image_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,44 @@
from mecsimcalc import input_to_file, metadata_to_filetype

# Define a dictionary for file type conversions
file_type_mappings = {"jpg": "jpeg", "tif": "tiff", "ico": "x-icon", "svg": "svg+xml", "jpeg": "jpeg", "tiff": "tiff", "x-icon": "x-icon", "svg+xml": "svg+xml"}
file_type_mappings = {
"jpg": "jpeg",
"tif": "tiff",
"ico": "x-icon",
"svg": "svg+xml",
"jpeg": "jpeg",
"tiff": "tiff",
"x-icon": "x-icon",
"svg+xml": "svg+xml",
"png": "png",
}


def file_to_PIL(file: io.BytesIO) -> Image.Image:
"""
Transforms a file into a Pillow Image object.
>>> file_to_PIL(file: io.BytesIO) -> Image.Image
Args:
file (io.BytesIO): A file object containing image data (using open with 'rb' mode)
Converts a binary file object into a PIL Image object.
Raises:
ValueError: If the file object doesn't contain image data.
# Parameters
file : io.BytesIO
A binary file object containing image data.
Returns:
PIL.Image.Image: An image object created from the file data.
"""
# Raises
* `ValueError` :
If the file object does not contain valid image data.
# Returns
* `PIL.Image.Image` :
An image object created from the file data.
# Examples
>>> input_file = inputs["input_file"]
>>> file = msc.input_to_file(input_file)
>>> image = msc.file_to_PIL(file)
(image is now ready to be used with Pillow functions)
"""
try:
return Image.open(file)
except IOError as e:
Expand All @@ -33,20 +55,44 @@ def input_to_PIL(
input_file: str, get_file_type: bool = False
) -> Union[Image.Image, Tuple[Image.Image, str]]:
"""
Decodes a Base64 encoded string into a Pillow image object, and optionally retrieves the file type.
>>> input_to_PIL(
input_file: str,
get_file_type: bool = False
) -> Union[Image.Image, Tuple[Image.Image, str]]
Decodes a Base64 encoded string into a PIL Image object. Optionally, the file type can also be returned.
# Parameters
input_file : str
A Base64 encoded string containing image data.
get_file_type : bool, optional
If set to True, the function also returns the file type. Default is False.
Args:
input_file (str): Base64 encoded string containing image data.
get_file_type (bool, optional): If True, the function also returns the file type. (Defaults to False)
# Returns
* `Union[PIL.Image.Image, Tuple[PIL.Image.Image, str]]` :
* `If get_file_type | False` : PIL.Image.Image - Returns an image object created from the file data.
* `If get_file_type | True` : Tuple[PIL.Image.Image, str] - Returns a tuple containing the image object and the file type.
Returns:
Union[PIL.Image.Image, Tuple[PIL.Image.Image, str]]: If get_file_type is False, a Pillow image object is returned.
If get_file_type is True, a tuple containing the Pillow image object and the file type is returned.
# Examples
**Without file type**
>>> input_file = inputs["input_file"]
>>> image = msc.input_to_PIL(input_file)
(Image is now ready to be used with Pillow functions)
**With file type**
>>> input_file = inputs["input_file"]
>>> image, file_type = msc.input_to_PIL(input_file, get_file_type=True)
>>> print(file_type)
png
(image is now ready to be used with Pillow functions)
"""
# Decode the base64 string into a file-like object and extract metadata
# Decode the base64 string into a binary file object and extract metadata
file_data, metadata = input_to_file(input_file, metadata=True)

# Load the file data into a Pillow Image
# Convert the file data into a PIL Image object
image = file_to_PIL(file_data)

if get_file_type:
Expand All @@ -67,22 +113,64 @@ def print_image(
download_file_type: str = "png",
) -> Union[str, Tuple[str, str]]:
"""
>>> print_image(
image: Image.Image,
width: int = 200,
height: int = 200,
original_size: bool = False,
download: bool = False,
download_text: str = "Download Image",
download_file_name: str = "myimg",
download_file_type: str = "png"
) -> Union[str, Tuple[str, str]]
Transforms a Pillow image into an HTML image, with an optional download link.
Args:
image (PIL.Image.Image): A Pillow image object.
width (int, optional): The width for the displayed image, in pixels. (Defaults to 200)
height (int, optional): The height for the displayed image, in pixels. (Defaults to 200)
original_size (bool, optional): If True, the image will retain its original size. (Defaults to False)
download (bool, optional): If True, a download link will be provided. (Defaults to False)
download_text (str, optional): The text for the download link. (Defaults to "Download Image")
download_file_name (str, optional): The name for the downloaded file. (Defaults to 'myimg')
download_file_type (str, optional): The file type for the downloaded file. (Defaults to "png")
Returns:
Union[str, Tuple[str, str]]: If download is False, an HTML string containing the image is returned.
If download is True, a tuple containing the HTML string for the image and the download link is returned.
# Parameters
image : PIL.Image.Image
A Pillow image object.
width : int, optional
The width for the displayed image, in pixels. (Defaults to 200)
height : int, optional
The height for the displayed image, in pixels. (Defaults to 200)
original_size : bool, optional
If True, the image will retain its original size. (Defaults to False)
download : bool, optional
If True, a download link will be provided. (Defaults to False)
download_text : str, optional
The text for the download link. (Defaults to "Download Image")
download_file_name : str, optional
The name for the downloaded file. (Defaults to 'myimg')
download_file_type : str, optional
The file type for the downloaded file. (Defaults to "png")
# Returns
* `Union[str, Tuple[str, str]]` :
* `download | False` : str (html image) - Returns an HTML string containing the image
* `download | True` : Tuple[str, str] - Returns a tuple containing the HTML string and the download link
# Examples
**Without download link, with original size**
>>> input_file = inputs["input_file"]
>>> image = msc.input_to_PIL(input_file)
>>> html_image = msc.print_image(image, original_size=True)
>>> return {
"html_image": html_image
}
**With download link and original file type**
>>> input_file = inputs["input_file"]
>>> image, file_type = msc.input_to_PIL(input_file, get_file_type=True)
>>> html_image, download_link = msc.print_image(image, download=True, download_file_type = file_type)
>>> return {
"html_image": html_image,
"download_link": download_link
}
"""

# Create a copy for display, preserving the original image
display_image = image.copy()

Expand Down
58 changes: 47 additions & 11 deletions mecsimcalc/plotting_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,55 @@ def print_plot(
download_file_name: str = "myplot",
) -> Union[str, Tuple[str, str]]:
"""
>>> print_plot(
plot_obj: Union[plt.Axes, figure.Figure],
width: int = 500,
dpi: int = 100,
download: bool = False,
download_text: str = "Download Plot",
download_file_name: str = "myplot"
) -> Union[str, Tuple[str, str]]
Converts a matplotlib plot into an HTML image tag and optionally provides a download link for the image.
Args:
plot_obj (Union[plt.Axes, figure.Figure]): The matplotlib plot to be converted.
width (int, optional): The width of the image in pixels. (Defaults to 500)
dpi (int, optional): The DPI of the image. (Defaults to 100)
download (bool, optional): If set to True, a download link will be provided. (Defaults to False)
download_text (str, optional): The text to be displayed for the download link. (Defaults to "Download Plot")
download_file_name (str, optional): The name of the downloaded file. (Defaults to 'myplot')
Returns:
Union[str, Tuple[str, str]]: If download is False, returns the HTML image as a string.
If download is True, returns a tuple of the HTML image and the download link as strings.
# Parameters
plot_obj : Union[plt.Axes, figure.Figure]
The matplotlib plot to be converted.
width : int, optional
The width of the image in pixels. (Defaults to 500)
dpi : int, optional
The DPI of the image. (Defaults to 100)
download : bool, optional
If set to True, a download link will be provided. (Defaults to False)
download_text : str, optional
The text to be displayed for the download link. (Defaults to "Download Plot")
download_file_name : str, optional
The name of the downloaded file. (Defaults to 'myplot')
# Returns
Union[str, Tuple[str, str]] :
* `download | False` : str - Returns the HTML image as a string.
* `download | True` : Tuple[str, str] - Returns the HTML image and the download link
# Examples
**Without Download Link**
>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 2, 3])
>>> plot = msc.print_plot(ax)
>>> return {
"plot": plot
}
**With Download Link and Custom Download Text**
>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 2, 3])
>>> plot, download_link = msc.print_plot(ax, download=True, download_text="Download My Plot")
>>> return {
"plot": plot,
"download_link": download_link
}
"""

# Check if plot_obj is a matplotlib Axes object
Expand Down

0 comments on commit f40e7a9

Please sign in to comment.