Spaces:
Build error
Build error
SHAMIL SHAHBAZ AWAN commited on
Update app.py
Browse files20 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727320 unmodified linesst.error(f"Error loading file: {e}")return None# Function to generate graph based on user querydef generate_graph(data, query):"""Generate a graph based on user query."""try:fig, ax = plt.subplots(figsize=(10, 6))if "bar" in query.lower() and "gross sales" in query.lower():# Bar chart for countries and gross salesif 'country' in data.columns and 'gross_sales' in data.columns:country_data = data[['country', 'gross_sales']].groupby('country').sum().reset_index()sns.barplot(x='country', y='gross_sales', data=country_data, ax=ax, color='skyblue')ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')st.pyplot(fig)else:st.error("The dataset must contain 'country' and 'gross_sales' columns.")elif "line" in query.lower() and "sales trend" in query.lower():# Line chart for sales trend over timeif 'date' in data.columns and 'sales' in data.columns:data['date'] = pd.to_datetime(data['date'])sales_trend = data.groupby('date')['sales'].sum().reset_index()sns.lineplot(x='date', y='sales', data=sales_trend, ax=ax)ax.set_title("Sales Trend Over Time")st.pyplot(fig)else:st.error("The dataset must contain 'date' and 'sales' columns.")elif "scatter" in query.lower() and "relationship" in query.lower():# Scatter plot for relationshipscolumns = query.lower().split("between")[-1].strip().split("and")x_col = columns[0].strip()y_col = columns[1].strip()if x_col in data.columns and y_col in data.columns:sns.scatterplot(x=x_col, y=y_col, data=data, ax=ax)ax.set_title(f"Scatter Plot: {x_col} vs {y_col}")st.pyplot(fig)else:st.error(f"The dataset must contain '{x_col}' and '{y_col}' columns.")elif "histogram" in query.lower():# Histogram for a specified columncolumn = query.lower().split("for")[-1].strip()if column in data.columns:sns.histplot(data[column], bins=20, kde=True, ax=ax, color='green')ax.set_title(f"Histogram of {column}")st.pyplot(fig)else:st.error(f"The dataset must contain the column '{column}'.")else:st.error("Unsupported graph type. Try asking for a bar chart, line chart, scatter plot, or histogram.")except Exception as e:20 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848520 unmodified linesst.error(f"Error loading file: {e}")return None# Function to infer column names based on synonymsdef infer_column(data, synonyms):"""Infer a column name based on synonyms."""for column in data.columns:if column.lower() in synonyms:return columnreturn None# Function to generate graph based on user querydef generate_graph(data, query):"""Generate a graph based on user query."""try:fig, ax = plt.subplots(figsize=(10, 6))# Infer column namescountry_col = infer_column(data, {"country", "countries"})sales_col = infer_column(data, {"gross_sales", "sales", "revenue"})date_col = infer_column(data, {"date", "time"})if "bar" in query.lower() and country_col and sales_col:# Bar chart for countries and gross salescountry_data = data[[country_col, sales_col]].groupby(country_col).sum().reset_index()sns.barplot(x=country_col, y=sales_col, data=country_data, ax=ax, color='skyblue')ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')ax.set_title(f"Bar Chart: {country_col} vs {sales_col}")st.pyplot(fig)elif "line" in query.lower() and date_col and sales_col:# Line chart for sales trend over timedata[date_col] = pd.to_datetime(data[date_col])sales_trend = data.groupby(date_col)[sales_col].sum().reset_index()sns.lineplot(x=date_col, y=sales_col, data=sales_trend, ax=ax)ax.set_title(f"Line Chart: {sales_col} Over Time")st.pyplot(fig)elif "scatter" in query.lower():# Scatter plot for relationshipsif "between" in query.lower():columns = query.lower().split("between")[-1].strip().split("and")if len(columns) == 2:x_col = infer_column(data, {columns[0].strip()})y_col = infer_column(data, {columns[1].strip()})if x_col and y_col:sns.scatterplot(x=x_col, y=y_col, data=data, ax=ax)ax.set_title(f"Scatter Plot: {x_col} vs {y_col}")st.pyplot(fig)returnst.error("Please specify valid columns for the scatter plot.")elif "histogram" in query.lower():# Histogram for a specified columnif "for" in query.lower():column = query.lower().split("for")[-1].strip()hist_col = infer_column(data, {column})if hist_col:sns.histplot(data[hist_col], bins=20, kde=True, ax=ax, color='green')ax.set_title(f"Histogram of {hist_col}")st.pyplot(fig)returnst.error("Please specify a valid column for the histogram.")else:st.error("Unsupported graph type. Try asking for a bar chart, line chart, scatter plot, or histogram.")except Exception as e:
app.py+48-36