Skip to main content

Mecsimcalc v0.1.6 documentation

This library is designed to provide a set of functions for handling and converting various types of data, such as base64 encoded data, Pandas DataFrames, and Pillow images.

General

input_to_file

[Source]

input_to_file(input_file, metadata = False)

Description:

Converts a base64 encoded string into a file object and metadata

Arguments:

ArgumentTypeDescription
input_filestrBase64 encoded string, prefixed with metadata
metadatabool (optional)Flag to return metadata with the file. (Defaults to False)

Raises:

ExceptionDescription
ValueErrorIf the input string doesn't contain ';base64,' to separate metadata and file data.

Returns:

Return TypeDescriptionCondition
io.BytesIOThe decoded file data (The thing you get when you open a file in Python)metadata is False
(io.BytesIO, str)The decoded file data and its metadatametadata is True

Example:

import mecsimcalc as msc

def main(inputs):
input_file = inputs['file']
file, metadata = msc.input_to_file(input_file, metadata = True)
print(metadata) # data:image/jpeg;base64,
print(type(file)) # <class '_io.BytesIO'>
return {"file":file}

metadata_to_filetype

[Source]

metadata_to_filetype(metadata):

Description:

Extracts the file type from the metadata

Arguments:

ArgumentTypeDescription
metadatastrThe metadata string in the form "Data:(MIME type);base64,"(returned from input_to_file)

Returns:

Return TypeDescription
strThe file type (e.g. "jpeg")

Example:

import mecsimcalc as msc

def main(inputs):
input_file = inputs['file']
file, metadata = msc.input_to_file(input_file, metadata = True)
print(metadata) # data:image/jpeg;base64,

download_file_type = msc.metadata_to_filetype(metadata)
print(download_file_type) # jpeg
return {"file":file}

Text

string_to_file

[Source]

string_to_file(
text
filename= "myfile",
download_text = "Download File",
)

Description:

Generates a downloadable text file containing the given text

Arguments:

ArgumentTypeDescription
textstrText to be downloaded
filenamestr (optional)Name of the download file. (Defaults to "myfile")
download_textstr (optional)Text to be displayed as the download link. (Defaults to "Download File")

Raises:

ExceptionDescription
TypeErrorIf the input text is not a string.

Returns:

Return TypeDescription
strHTML download link

Example:

Code step:

import mecsimcalc as msc

def main(inputs):
download_link = msc.string_to_file("Hello World!")
return {"download":download_link}

Outputs step:

# outputs.downloadLink is the html download link generated by the function
{{ outputs.download }}

Spreadsheets

file_to_dataframe

[Source]

file_to_dataframe(file_data):

Description:

Converts a base64 encoded file data into a pandas DataFrame

Arguments:

ArgumentTypeDescription
file_dataio.BytesIODecoded file data (e.g. from input_to_file)

Raises:

ExceptionDescription
pd.errors.ParserErrorIf the file data cannot be converted to a DataFrame (i.e. file is not an Excel or CSV file or is corrupted)

Returns:

Return TypeDescription
pd.DataFrameDataFrame created from file data

Example:

import mecsimcalc as msc

def main(inputs):
input_file = inputs['file']
decoded_file = msc.input_to_file(input_file)
df = msc.file_to_dataframe(decoded_file)
print(df)
# A B C
# 0 a b c
# 1 d e f
return {"df":df}

input_to_dataframe

[Source]

input_to_dataframe(file):

Description:

Converts a base64 encoded file data into a pandas DataFrame

Arguments:

ArgumentTypeDescription
input_filestrBase64 encoded file data
get_file_typeboolIf True, the function also returns the file type (Defaults to False)

Returns:

Return TypeDescriptionCondition
pd.DataFrameDataFrame created from file dataget_file_type is False
(pd.DataFrame, str)Tuple containing the DataFrame and the file typeget_file_type is True

Example:

import mecsimcalc as msc

def main(inputs):
input_file = inputs['file']
df, file_type = msc.input_to_dataframe(input_file, get_file_type = True)
print(df)
# A B C
# 0 a b c
# 1 d e f
print(file_type) # csv
return {"df":df}

[Source]

print_dataframe(
df,
download = False,
download_text = "Download Table",
download_file_name = "mytable",
download_file_type = "csv",
):

Description:

Creates an HTML table and a download link for a given DataFrame

Arguments:

ArgumentTypeDescription
dfpd.DataFrameDataFrame to be converted
downloadbool (optional)If True, function returns a download link (Defaults to False)
download_textstr (optional)Text to be displayed as the download link (Defaults to "Download Table")
download_file_namestr (optional)Name of file when downloaded (Defaults to "mytable")
download_file_typestr (optional)File type of downloaded file (Defaults to "csv")

Returns:

Return TypeDescriptionCondition
strHTML tabledownload is False
Tuple[str, str](HTML table, HTML download link)download is True

Example:

Code step:

import mecsimcalc as msc

def main(inputs):
input_file = inputs['file']
df = msc.input_to_dataframe(input_file)
table, download = msc.print_dataframe(df, download=True, download_file_name="FunkyTable", download_text="Download My Funky Table HERE!", download_file_type="xlsx")
return {
"table":table,
"download":download,
}

Outputs step:

# outputs.table is the HTML table
Displaying Table
{{ outputs.table }}

# outputs.download is the download link
Downloading Table
{{ outputs.download }}

Tables

table_to_dataframe

[Source]

table_to_dataframe(column_headers, rows) -> pd.DataFrame:

Description:

Create a DataFrame from given rows and column headers

Arguments:

ArgumentTypeDescription
column_headersList[str]List of column headers
rowsList[List[str]]List of rows to be converted into a DataFrame. Each column is a list of strings

Returns:

Return TypeDescription
pd.DataFrameDataFrame created from headers and rows

Example:

import mecsimcalc as msc

def main(inputs):
column_headers = ["A", "B", "C"]
rows = [["a", "b", "c"], ["d", "e", "f"]]
df = msc.table_to_dataframe(column_headers, rows)
print(df)
# A B C
# 0 a b c
# 1 d e f
return {"df":df}

[Source]

print_table(column_headers, rows):

Description:

Creates an HTML table from given rows and column headers

Arguments:

ArgumentTypeDescription
column_headersList[str]List of column headers
rowsList[List[str]]List of rows to be converted into a table. Each column is a list of strings
indexbool (optional)Whether to use the first column as the DataFrame's index. (Defaults to True)

Returns:

Return TypeDescription
strHTML table created from rows and headers

Example:

Code step:

import mecsimcalc as msc

def main(inputs):
column_headers = ["A", "B", "C"]
rows = [["a", "b", "c"], ["d", "e", "f"]]
table = msc.print_table(column_headers, rows)
return {"table":table}

Outputs step:

# outputs.table is the HTML table
Displaying Table
{{ outputs.table }}

Images

file_to_PIL

[Source]

file_to_PIL(file):

Description:

Transforms a file into a Pillow Image object

Arguments:

ArgumentTypeDescription
filestrDecoded file data (returned from input_to_file)

Raises:

Exception TypeDescription
ValueErrorIf the file does not contain image data

Returns:

Return TypeDescription
ImagePillow Image object

Example:

Code step:

import mecsimcalc as msc

def main(inputs):
input_file = inputs['file']
decoded_file = msc.input_to_file(input_file)
image = msc.file_to_PIL(decoded_file)
return {"image":image}

Outputs step:

# outputs.image is the Pillow Image object
Displaying Image
{{ outputs.image }}

input_to_PIL

[Source]

input_to_PIL(input_file, get_file_type=False):

Description:

Converts a base64 encoded file data into a pillow image

Arguments:

ArgumentTypeDescription
input_filestrBase64 encoded file data
get_file_typeboolIf True, the function also returns the file type (Defaults to False)

Returns:

Return TypeDescriptionCondition
PIL.Image.ImagePillow Image objectget_file_type is False
Tuple[PIL.Image.Image, str](pillow image, metadata)get_file_type is True

Example:

import mecsimcalc as msc

def main(inputs):
input_file = inputs['file']
image, file_type = msc.input_to_PIL(input_file, get_file_type=True)
print(file_type) # jpeg
print(type(image)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
return {"image":image}

[Source]

print_image(
image,
width = 200,
height = 200,
original_size = False,
download = False,
download_text = "Download Image",
download_file_name= "myimg",
download_file_type = "png",
):

Description:

Transforms a Pillow image into an HTML image, with an optional download link

Arguments:

ArgumentTypeDescription
imagePIL.Image.ImagePillow image
widthint (optional)Output width of the image in pixels (Defaults to 200)
heightint (optional)Output height of the image in pixels (Defaults to 200)
original_sizebool (optional)If True, the HTML image will be displayed in its original size (Defaults to False)
downloadbool (optional)If True, function returns a download link (Defaults to False)
download_textstr (optional)The text to be displayed on the download link (Defaults to "Download Image")
download_file_namestr (optional)The name of the image file when downloaded (Defaults to "myimg")
download_file_typestr (optional)The file type of the image when downloaded (Defaults to "png")

Returns:

Return TypeDescriptionCondition
strHTML imagedownload is False
Tuple[str, str](HTML image, download link)download is True

Example:

Code step:

import mecsimcalc as msc

def main(inputs):
input_file = inputs['file']
image, metadata = msc.input_to_PIL(input_file)
html_image, download = msc.print_image(image, original_size=True, download=True, download_text="Download Image Here", download_file_name="myimage", download_file_type="jpeg")
return {
"image":html_image,
"download":download,
}

Outputs step:

# outputs.image is the HTML image
Displaying Image
{{ outputs.image }}

# outputs.download is the download link
Downloading Image
{{ outputs.download }}

Plots

[Source]

print_plot(
plot_obj,
width = 500,
dpi= 100,
download= False,
download_text = "Download Plot",
download_file_name = "myplot",
)

Description:

Converts a matplotlib.pyplot.axis or matplotlib.figure into an HTML image tag and optionally provides a download link for the image

Arguments:

ArgumentTypeDescription
plot_objaxes or figureMatplotlib figure
widthint (optional)Output width of the image in pixels (Defaults to 500)
dpiint (optional)Output dpi of the image in pixels (Defaults to 100)
downloadbool (optional)If True, function returns a download link (Defaults to False)
download_textstr (optional)The text to be displayed on the download link (Defaults to "Download Plot")
download_file_namestr (optional)The name of the image file when downloaded (Defaults to "myplot")

Returns:

Return TypeDescriptionCondition
strHTML imagedownload is False
Tuple[str, str](HTML image, HTML download link)download is True

Example:

Code step:

import matplotlib.pyplot as plt
import numpy as np
import mecsimcalc as msc

def main(inputs):
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('A single plot')
image, download = msc.print_plot(fig, width=500, dpi=100, download=True, download_text="Download Sin Function Plot", download_file_name="sin(x)")
return {
"image":image,
"download":download,
}

Outputs step:

# outputs.image is the HTML image
Displaying Image
{{ outputs.image }}

# outputs.download is the download link
Downloading Image
{{ outputs.download }}

Quiz Toolkit

append_to_google_sheet

[Source]

append_to_google_sheet(
service_account_info = {...},
spreadsheet_id = "123abc...",
values = [["name", 12837, ...]],
range_name = 'Sheet1!A1',
include_timestamp = True
)

Description:

This function appends given values to a specified Google Sheet and optionally includes a current timestamp with each entry. It transforms data into a Google Sheets document, facilitating dynamic data entry directly from your application.

Arguments:

ArgumentTypeDescription
service_account_infodictThe service account credentials used for Google Sheets API authentication.
spreadsheet_idstrThe unique identifier of the target Google Spreadsheet.
valueslist of listsThe data to append. Each list element represents a row of data.
range_namestr (optional)The A1 notation of the range to start appending data (Defaults to 'Sheet1!A1').
include_timestampbool (optional)If True, appends the current timestamp to each row of data (Defaults to True).

Returns:

Return TypeDescription
dictThe response from the Google Sheets API, containing details of the append operation.

Example:

Code step:

import mecsimcalc as msc

def main(inputs):
service_account_info = {
# Your service account info here
}
spreadsheet_id = 'your_spreadsheet_id_here'
values = [
[ inputs['input_1'], inputs['input_2'], inputs['input_3'] ],
]
result = msc.append_to_google_sheet(service_account_info, spreadsheet_id, values)

send_gmail

[Source]

send_gmail(
sender_email='sender@example.com',
receiver_email='receiver@example.com',
subject="Quiz",
app_password = "xxxx xxxx xxxx xxxx",
values = [
["name", "grade"]
]
)

Description:

This function sends an email with specified values formatted in the message body, utilizing a service account for authentication.

Arguments:

ArgumentTypeDescription
sender_emailstrThe email address of the sender.
receiver_emailstrThe email address of the receiver.
subjectstrThe subject line of the email.
app_passwordstrThe app-specific password for the sender's email account.
valueslistA list of lists. Each list contains data to be included in the email body.

Returns:

Return TypeDescription
boolReturns True if the email was sent successfully, otherwise False.

Example Usage:

# Example code to use the send_gmail function
import mecsimcalc as msc

def main(inputs):
# Define parameters
sender_email = 'sender@example.com'
receiver_email = 'receiver@example.com'
subject = 'Test Email'
app_password = 'your_app_password_here'

name = inputs['name']
grade = inputs['grade']

values = [
[name, grade]
]

# Send the email
msc.send_gmail(sender_email, receiver_email, subject, app_password, values)