Spaces:
Build error
Build error
SHAMIL SHAHBAZ AWAN commited on
Update app.py
Browse files6 unmodified lines7891011121320 unmodified lines34353637383940414243442 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001016 unmodified linesfrom transformers import pipeline# Load a lightweight NLP model for query understandingnlp = pipeline("text-classification", model="distilbert-base-uncased", tokenizer="distilbert-base-uncased")# Function to load the uploaded file (CSV or Excel)def load_file(uploaded_file):20 unmodified linesreturn None# Function to classify the user querydef classify_query(query):"""Classify the user query into graph types."""results = nlp(query)if results:return results[0]['label']return None# Function to generate graph based on user query2 unmodified linestry: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"})query_type = classify_query(query)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:st.error(f"Error generating graph: {e}")6 unmodified lines7891011121320 unmodified lines34353637383940414243442 unmodified lines474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697986 unmodified linesfrom transformers import pipeline# Load a lightweight NLP model for query understandingnlp = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")# Function to load the uploaded file (CSV or Excel)def load_file(uploaded_file):20 unmodified linesreturn None# Function to classify the user querydef classify_query(query, candidate_labels):"""Classify the user query into graph types."""results = nlp(query, candidate_labels)if results:return results['labels'][0]return None# Function to generate graph based on user query2 unmodified linestry:fig, ax = plt.subplots(figsize=(10, 6))# Infer column names dynamicallynumerical_columns = data.select_dtypes(include=['number']).columns.tolist()categorical_columns = data.select_dtypes(include=['object', 'category']).columns.tolist()datetime_columns = data.select_dtypes(include=['datetime']).columns.tolist()# Define possible graph typescandidate_labels = ["bar chart", "line chart", "scatter plot", "histogram"]query_type = classify_query(query, candidate_labels)if query_type == "bar chart" and categorical_columns and numerical_columns:# Bar chart for categorical vs numericalx_col = st.selectbox("Select the categorical column:", categorical_columns)y_col = st.selectbox("Select the numerical column:", numerical_columns)aggregated_data = data[[x_col, y_col]].groupby(x_col).sum().reset_index()sns.barplot(x=x_col, y=y_col, data=aggregated_data, ax=ax, color='skyblue')ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')ax.set_title(f"Bar Chart: {x_col} vs {y_col}")st.pyplot(fig)elif query_type == "line chart" and datetime_columns and numerical_columns:# Line chart for numerical trend over timex_col = st.selectbox("Select the datetime column:", datetime_columns)y_col = st.selectbox("Select the numerical column:", numerical_columns)data[x_col] = pd.to_datetime(data[x_col])trend_data = data.groupby(x_col)[y_col].sum().reset_index()sns.lineplot(x=x_col, y=y_col, data=trend_data, ax=ax)ax.set_title(f"Line Chart: {y_col} Over Time")st.pyplot(fig)elif query_type == "scatter plot" and len(numerical_columns) >= 2:# Scatter plot for numerical relationshipsx_col = st.selectbox("Select the x-axis numerical column:", numerical_columns)y_col = st.selectbox("Select the y-axis numerical column:", numerical_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)elif query_type == "histogram" and numerical_columns:# Histogram for a numerical columnhist_col = st.selectbox("Select the numerical column:", numerical_columns)sns.histplot(data[hist_col], bins=20, kde=True, ax=ax, color='green')ax.set_title(f"Histogram of {hist_col}")st.pyplot(fig)else:st.error("Unsupported graph type or insufficient data. Try asking for a bar chart, line chart, scatter plot, or histogram.")except Exception as e:st.error(f"Error generating graph: {e}")
app.py+45-48