|
|
|
|
|
""" |
|
|
Visualization script using PandasAI. |
|
|
|
|
|
This script creates a sample dataframe and uses PandasAI to generate |
|
|
and save visualizations based on user queries. |
|
|
|
|
|
Usage: |
|
|
python visualize.py "Create a bar chart of sales by region" |
|
|
|
|
|
Requirements: |
|
|
- pandas |
|
|
- pandasai |
|
|
- matplotlib |
|
|
""" |
|
|
|
|
|
import os |
|
|
import sys |
|
|
import pandas as pd |
|
|
import matplotlib.pyplot as plt |
|
|
import pandasai as pai |
|
|
from dotenv import load_dotenv |
|
|
|
|
|
|
|
|
def create_sample_dataframe(): |
|
|
"""Create a sample dataframe with sales data.""" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data = { |
|
|
'Year': [2023, 2023, 2023, 2023, 2023, 2023, 2023, 2023] |
|
|
} |
|
|
return pai.DataFrame(data) |
|
|
|
|
|
|
|
|
def visualize_data(df, query): |
|
|
""" |
|
|
Generate visualization based on user query using PandasAI. |
|
|
|
|
|
Args: |
|
|
df: Pandas DataFrame containing the data |
|
|
query: User query string describing the desired visualization |
|
|
|
|
|
Returns: |
|
|
Path to the saved visualization file |
|
|
""" |
|
|
|
|
|
|
|
|
|
|
|
try: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
load_dotenv() |
|
|
pai.api_key.set(os.environ["PANDAS_KEY"]) |
|
|
|
|
|
df.chat(query) |
|
|
|
|
|
|
|
|
print(f"Generating visualization for query: '{query}'") |
|
|
|
|
|
|
|
|
output_file = "visualization_output.png" |
|
|
plt.savefig(output_file) |
|
|
plt.close() |
|
|
|
|
|
print(f"Visualization saved to {output_file}") |
|
|
return output_file |
|
|
|
|
|
except Exception as e: |
|
|
print(f"Error generating visualization: {str(e)}") |
|
|
return None |
|
|
|
|
|
|
|
|
def main(): |
|
|
"""Main function to run the visualization script.""" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
query = "Plot a bar chart of sales by region" |
|
|
|
|
|
|
|
|
df = create_sample_dataframe() |
|
|
print("Sample DataFrame created:") |
|
|
print(df.head()) |
|
|
|
|
|
|
|
|
output_file = visualize_data(df, query) |
|
|
|
|
|
if output_file: |
|
|
print(f"Visualization process completed. Output saved to: {output_file}") |
|
|
else: |
|
|
print("Visualization process failed.") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |