Data-Excel / app.py
SHAMIL SHAHBAZ AWAN
Update app.py
b5e2763 verified
Raw
History Blame
4.56 kB
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
from io import StringIO
# Function to load the uploaded file (CSV or Excel)
def load_file(uploaded_file):
"""Load data from an uploaded file."""
try:
if uploaded_file.type == "text/csv":
data = pd.read_csv(uploaded_file)
elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
data = pd.read_excel(uploaded_file)
else:
st.error("Unsupported file type.")
return None
return data
except Exception as e:
st.error(f"Error loading file: {e}")
return None
# Function to generate graph based on user query
def 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 sales
if '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 time
if '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 relationships
columns = 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 column
column = 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:
st.error(f"Error generating graph: {e}")
# Streamlit App Interface
def main():
st.set_page_config(page_title="Data Visualization App", page_icon="📊", layout="wide")
# Set background image
st.markdown(
"""
<style>
.stApp {
background-image: url('https://cdn.pixabay.com/photo/2016/06/02/02/33/triangles-1430105_1280.png');
background-size: cover;
}
</style>
""", unsafe_allow_html=True
)
st.title("Data Visualization App")
st.markdown("Created by: Shamil Shahbaz", unsafe_allow_html=True)
# File upload section
uploaded_file = st.file_uploader("Upload a CSV or Excel file", type=["csv", "xlsx"])
if uploaded_file is not None:
# Load and display data
data = load_file(uploaded_file)
if data is not None:
st.write("Dataset preview:", data.head())
# User input for graph generation
query = st.text_input("Enter your query (e.g., 'Generate a bar chart for countries and gross sales')")
if query:
# Generate the graph based on the query
generate_graph(data, query)
if __name__ == "__main__":
main()