Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attempting to access non-existent attribute 'Figure' in plotly.express #1259

Open
harshvardhanchand opened this issue Jun 28, 2024 · 3 comments
Labels
bug Something isn't working

Comments

@harshvardhanchand
Copy link

harshvardhanchand commented Jun 28, 2024

System Info

python version 3.11
Pandas Ai version 2.2.7

馃悰 Describe the bug

It is trying to access non existent attribute of Plotly Figure even with the Judge Agent enabled
Screenshot 2024-06-29 at 12 38 06鈥疉M

import os
import logging
import pandas as pd
import streamlit as st
import pickle
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import plotly.express as px
from some_module import PandasConnector, SmartDataframe, Agent, select_relevant_datasets, llm, judge, StreamlitResponse

def read_csv_and_metadata(code):
code = str(code)
report_file = 'REPORT_' + code + '.csv'
metadata_file = code + '_METADATA.csv'
report_path = os.path.join(folder_path, report_file)
metadata_path = os.path.join(folder_path, metadata_file)

if not os.path.isfile(metadata_path):
    logging.warning(f"Skipping {report_path} as metadata file {metadata_file} does not exist")
    return None

try:
    df = pd.read_csv(report_path)
    metadata = pd.read_csv(metadata_path)
    field_descriptions = metadata.set_index('VariableName')['Long_Description'].to_dict()
    connector = PandasConnector({"original_df": df}, name=code, field_descriptions=field_descriptions)
    return SmartDataframe(connector, config={
        "enforce_privacy": False,
        "response_parser": StreamlitResponse,
        "llm": llm,
        "open_charts": False,
        "save_charts": False,
        "enable_cache": False,
        "save_charts_path": user_defined_path,
    })
except Exception as e:
    logging.error(f"Error reading {report_path} or {metadata_path}: {e}")
    return None

Streamlit app initialization

try:
with open('preprocessed_data.pkl', 'rb') as f:
data = pickle.load(f)
preprocessed_corpus = data['preprocessed_corpus']
abbreviation_map = data['abbreviation_map']

except FileNotFoundError:
st.error("Data file not found. Please ensure the file is in the correct location.")
st.stop()
except pd.errors.EmptyDataError:
st.error("Data file is empty. Please provide a valid CSV file.")
st.stop()
except Exception as e:
st.error(f"An error occurred while loading the data file: {e}")
st.stop()

Streamlit UI setup

st.title("Query Response App")
st.write("Enter your query below and receive a response from the trained model.")

st.session_state['started'] = True

User interaction section

if 'started' in st.session_state and st.session_state['started']:
st.title("Chat")

user_query = st.text_input("Your Query:")

if st.button("Submit"):
    if user_query:
        relevant_datasets = select_relevant_datasets(user_query)
        
        output_list = [read_csv_and_metadata(code) for code in relevant_datasets if read_csv_and_metadata(code) is not None]

        if output_list:
            sdf = agent = Agent(output_list, judge=judge, config={"llm": llm})

            try:
                response = sdf.chat(user_query)
                if isinstance(response, str):
                    if os.path.isfile(response):
                        im = plt.imread(response)
                        st.image(im)
                        os.remove(response)
                    else:
                        st.write(response)
                elif isinstance(response, pd.DataFrame):
                    st.dataframe(response)
                elif isinstance(response, int):
                    st.write(response)
                elif isinstance(response, np.ndarray):
                    st.write(response)
                elif isinstance(response, plt.Figure):
                    st.pyplot(response)
                elif isinstance(response, Image.Image):
                    st.image(response, caption='Custom Image')
                elif isinstance(response, px.Figure):
                    st.plotly_chart(response)
                else:
                    st.write(response)

            except Exception as e:
                st.error('An error occurred during chat processing. Please try again.')
                st.error(str(e))
        else:
            st.write("No relevant datasets found.")
    else:
        st.write("Please enter a query to receive a response.")
@dosubot dosubot bot added the bug Something isn't working label Jun 28, 2024
Copy link

dosubot bot commented Jun 28, 2024

Hello, @harshvardhanchand! I'm here to assist you with any bugs, questions, or contributions you may have. Let's work together to solve the issue you're experiencing.

To resolve the error "module 'plotly.express' has no attribute 'Figure'", you should use plotly.graph_objects.Figure instead of plotly.express.Figure. Plotly Express does not have a Figure attribute; it is part of the plotly.graph_objects module.

Here is an example of how you can create a figure using plotly.graph_objects:

import plotly.graph_objects as go

# Create a figure
fig = go.Figure()

# Add a trace
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]))

# Show the figure
fig.show()

Make sure you have the plotly package installed, as specified in your pyproject.toml:

[tool.poetry.dependencies]
plotly = {version = "^5.15.0", optional = true}

This should resolve the error and allow you to create and manipulate figures in your web application [1].

To continue talking to Dosu, mention @dosu.

@harshvardhanchand
Copy link
Author

Hello, @harshvardhanchand! I'm here to assist you with any bugs, questions, or contributions you may have. Let's work together to solve the issue you're experiencing.

To resolve the error "module 'plotly.express' has no attribute 'Figure'", you should use plotly.graph_objects.Figure instead of plotly.express.Figure. Plotly Express does not have a Figure attribute; it is part of the plotly.graph_objects module.

Here is an example of how you can create a figure using plotly.graph_objects:

import plotly.graph_objects as go

# Create a figure
fig = go.Figure()

# Add a trace
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]))

# Show the figure
fig.show()

Make sure you have the plotly package installed, as specified in your pyproject.toml:

[tool.poetry.dependencies]
plotly = {version = "^5.15.0", optional = true}

This should resolve the error and allow you to create and manipulate figures in your web application [1].

To continue talking to Dosu, mention @dosu.

I want pandasai agent to recognise what to use and what not to use this reply doesn't make sense

Copy link

dosubot bot commented Jun 28, 2024

To ensure the Pandas AI agent automatically handles the correct Plotly module without manual intervention, you can install the optional plotly dependency for pandasai. This will make the necessary Plotly module available for use by the Pandas AI agent.

You can install the plotly dependency using the following command:

pip install pandasai[plotly]

This will include the Plotly module as part of the PandasAI installation, allowing the Pandas AI agent to handle Plotly without requiring manual intervention. The CodeGenerator class in pandasai is designed to generate code for various types of plots, including those that use Plotly, ensuring the correct module is used automatically [1][2].

To continue talking to Dosu, mention @dosu.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant