To handle the different types of responses (ChartResponse and DataFrameResponse) and generate appropriate Markdown content, here's how you can proceed based on the details provided:
Case 1: Handling ChartResponse
If the object is of type <class 'pandasai.core.response.chart.ChartResponse'>, you need to:
Convert the chart image (either from a file path or base64 string) into a base64-encoded string.
Create a Markdown inline image using this base64 string.
Case 2: Handling DataFrameResponse
If the object is of type <class 'pandasai.core.response.dataframe.DataFrameResponse'>, you need to:
Generate an ASCII table representation of the DataFrame.
Add a collapsible Markdown block for the Python code used to produce the result.
Implementation
Here’s the Python code to generate the Markdown content:
python
import base64
from io import BytesIO
import pandas as pd
from PIL import Image
from pandasai.core.response.chart import ChartResponse
from pandasai.core.response.dataframe import DataFrameResponse
def generate_markdown(my_object):
"""Generate markdown content depending on the type of response."""
if isinstance(my_object, ChartResponse):
# Extract the base64-encoded image
img = my_object._get_image()
buffered = BytesIO()
img.save(buffered, format="PNG")
img_base64 = base64.b64encode(buffered.getvalue()).decode()
# Markdown inline image
markdown = f""
[Redacted Person] isinstance(my_object, DataFrameResponse):
# Generate ASCII table
df = my_object.value
ascii_table = df.to_string(index=False)
# Generate Python code (hidden by default in Markdown)
code_snippet = f"""
```python
# Python code to generate the DataFrame
import pandas as pd
data = {df.to_dict(orient='list')}
df = pd.DataFrame(data)
print(df)
code
"""
# Markdown content with ASCII table and hidden Python code
markdown = f"""
The base64-encoded-string is the base64 representation of the chart image.
For DataFrameResponse
markdown
Age AverageRestingBP
28 130
29 130
30 170
31 110
code
<details>
<summary>Code to produce the DataFrame (click to expand)</summary>
```python
# Python code to generate the DataFrame
import pandas as pd
data = {'Age': [28, 29, 30, 31], 'AverageRestingBP': [130, 130, 170, 110]}
df = pd.DataFrame(data)
print(df)
Explanation
ChartResponse Handling:
_get_image() is called to either load the image from a file path or decode it from a base64 string.
The image is converted into a base64-encoded string and embedded as an inline image in Markdown.
DataFrameResponse Handling:
The DataFrame is converted to an ASCII table representation using df.to_string().
Hidden Python code is added using a Markdown <details> block.
Generalization:
The function generate_markdown dynamically handles different response types and generates appropriate Markdown content based on the type.
You can test this function with different responses to verify its behavior.