import pandas as pd import numpy as np import plotly.express as px import streamlit as st import mysql.connector import requests import os import git import plotly.graph_objects as go import json import re from streamlit_option_menu import option_menu #set the configuration of the Page st.set_page_config( page_title="Phone-Pe Pulse Visualization by Shivasai", page_icon="✨", menu_items={ 'About': "# This is Youtube Analytics app Which was developed by Shiva sai!" } ) # Function to convert states to code from def state_change(state): if state =="Andaman & Nicobar Island": state_changed = "andaman-&-nicobar-islands" elif state =='Dadra and Nagar Haveli and Daman and Diu': state_changed = "dadra-&-nagar-haveli-&-daman-&-diu" elif state == 'Arunanchal Pradesh': state_changed = 'arunachal-pradesh' else: state = state.lower() state_changed = re.sub(r'\s+','-',state) return state_changed mydb = mysql.connector.connect(host='localhost', user='root', password='Shiva@607' ) mycursor = mydb.cursor() sql = "Use project2_phonepe" mycursor.execute(sql) def mainlogo(): st.markdown( """
PhonePe Logo

Data Visualization

""", unsafe_allow_html=True ) def home(): mainlogo() st.write("PhonePe Pulse Data Overview: PhonePe Pulse is a comprehensive dataset that provides insights into digital payment trends across India. It includes detailed information on transaction volumes, transaction amounts, and user registrations, categorized by states, districts, and transaction types. This data helps in understanding the adoption and usage patterns of digital payments in different regions and time periods.") #request data from the Phone pe pulse def DataCollection(): mainlogo() try: git.Repo.clone_from("https://github.com/PhonePe/pulse.git", 'phonepe_pulse_git') st.success("Successfully Cloned the Data") except: pass #Transactions data def get_Transaction_Data(): path1=r"C:/Users/shiva/Downloads/Projects-DataVisualization/phonepe_pulse_git/data/aggregated/transaction/country/india/state/" state_data=os.listdir(path1) columns1 = {'State': [], 'Year': [], 'Quarter': [], 'Transaction_type': [], 'Transaction_count': [], 'Transaction_amount': []} for state in state_data: path2=path1+state+"/" year_data=os.listdir(path2) for year in year_data: path3=path2+year+"/" file_data=os.listdir(path3) for file in file_data: file_path=path3+file data=open(file_path,"r") A=json.load(data) for i in A["data"]["transactionData"]: name=i["name"] count=i["paymentInstruments"][0]["count"] amount=i["paymentInstruments"][0]["amount"] columns1['Transaction_type'].append(name) columns1['Transaction_count'].append(count) columns1['Transaction_amount'].append(amount) columns1['State'].append(state) columns1['Year'].append(year) columns1['Quarter'].append(int(file.strip('.json'))) df_agg_trans = pd.DataFrame(columns1) return df_agg_trans #user Data def get_User_Data(): path1=r"C:/Users/shiva/Downloads/Projects-DataVisualization/phonepe_pulse_git/data/aggregated/user/country/india/state/" state_data=os.listdir(path1) columns1 = {'State': [], 'Year': [], 'Quarter': [], 'Brands': [], 'Count': [], 'Percentage': []} for state in state_data: path2=path1+state+"/" year_data=os.listdir(path2) for year in year_data: path3=path2+year+"/" file_data=os.listdir(path3) for file in file_data: file_path=path3+file data=open(file_path,"r") B=json.load(data) if B["data"]["usersByDevice"] is not None: for i in B["data"]["usersByDevice"]: brand = i["brand"] count = i["count"] percentage = i["percentage"] columns1['Brands'].append(brand) columns1['Count'].append(count) columns1['Percentage'].append(percentage) columns1['State'].append(state) columns1['Year'].append(year) columns1['Quarter'].append(int(file.strip('.json'))) else: columns1['Brands'].append(None) columns1['Count'].append(None) columns1['Percentage'].append(None) columns1['State'].append(state) columns1['Year'].append(year) columns1['Quarter'].append(int(file.strip('.json'))) df_agg_trans = pd.DataFrame(columns1) return df_agg_trans #Transaction Map Data def get_Transaction_Map_Data(): path1=r"C:/Users/shiva/Downloads/Projects-DataVisualization/phonepe_pulse_git/data/map/transaction/hover/country/india/state/" state_data=os.listdir(path1) columns1 = {'State': [], 'Year': [], 'Quarter': [], 'District': [], 'Count': [], 'Amount': []} for state in state_data: path2=path1+state+"/" year_data=os.listdir(path2) for year in year_data: path3=path2+year+"/" file_data=os.listdir(path3) for file in file_data: file_path=path3+file data=open(file_path,"r") C=json.load(data) for i in C["data"]["hoverDataList"]: Distrct=i["name"] metric = i["metric"] # Check if metric is a list or dictionary if isinstance(metric, dict): count = metric.get("count") Amount = metric.get("amount") elif isinstance(metric, list) and len(metric) > 0: # Assuming the first element of the list contains the relevant data count = metric[0].get("count") Amount = metric[0].get("amount") else: count = None Amount = None columns1['District'].append(Distrct) columns1['Count'].append(count) columns1["Amount"].append(Amount) columns1['State'].append(state) columns1['Year'].append(year) columns1['Quarter'].append(int(file.strip('.json'))) df_agg_trans = pd.DataFrame(columns1) return df_agg_trans #User Map Data def get_user_Map_Data(): path1=r"C:/Users/shiva/Downloads/Projects-DataVisualization/phonepe_pulse_git/data/map/user/hover/country/india/state/" state_data=os.listdir(path1) columns1 = {'State': [], 'Year': [], 'Quarter': [], 'District': [], 'RegisteredUser': [], 'AppOpens': []} for state in state_data: path2=path1+state+"/" year_data=os.listdir(path2) for year in year_data: path3=path2+year+"/" file_data=os.listdir(path3) for file in file_data: file_path=path3+file data=open(file_path,"r") C=json.load(data) for i in C["data"]["hoverData"].items(): District=i[0] RegisteredUser=i[1]["registeredUsers"] Appones=i[1]["appOpens"] columns1["District"].append(District) columns1["RegisteredUser"].append(RegisteredUser) columns1["AppOpens"].append(Appones) columns1['State'].append(state) columns1['Year'].append(year) columns1['Quarter'].append(int(file.strip('.json'))) df_agg_trans = pd.DataFrame(columns1) return df_agg_trans #Top 10 Transaction Data #User Map Data def get_Transaction_Top_Data(): path1=r"C:/Users/shiva/Downloads/Projects-DataVisualization/phonepe_pulse_git/data/top/transaction/country/india/state/" state_data=os.listdir(path1) columns1 = {'State': [], 'Year': [], 'Quarter': [], 'District': [], 'Count': [], 'Amount': []} for state in state_data: path2=path1+state+"/" year_data=os.listdir(path2) for year in year_data: path3=path2+year+"/" file_data=os.listdir(path3) for file in file_data: file_path=path3+file data=open(file_path,"r") C=json.load(data) for i in C["data"]["districts"]: District=i["entityName"] Count=i["metric"]["count"] Amount=i["metric"]["amount"] columns1["District"].append(District) columns1["Count"].append(Count) columns1["Amount"].append(Amount) columns1['State'].append(state) columns1['Year'].append(year) columns1['Quarter'].append(int(file.strip('.json'))) df_agg_trans = pd.DataFrame(columns1) return df_agg_trans def get_User_Top_Data(): path1=r"C:/Users/shiva/Downloads/Projects-DataVisualization/phonepe_pulse_git/data/top/user/country/india/state/" state_data=os.listdir(path1) columns1 = {'State': [], 'Year': [], 'Quarter': [], 'District': [], 'RegisteredUsers': []} for state in state_data: path2=path1+state+"/" year_data=os.listdir(path2) for year in year_data: path3=path2+year+"/" file_data=os.listdir(path3) for file in file_data: file_path=path3+file data=open(file_path,"r") C=json.load(data) for i in C["data"]["districts"]: District=i["name"] RegisteredUsers=i["registeredUsers"] columns1["District"].append(District) columns1["RegisteredUsers"].append(RegisteredUsers) columns1['State'].append(state) columns1['Year'].append(year) columns1['Quarter'].append(int(file.strip('.json'))) df_agg_trans = pd.DataFrame(columns1) return df_agg_trans def DataOverview(): mainlogo() trans_data=get_Transaction_Data() user_data=get_User_Data() trans_map=get_Transaction_Map_Data() user_map_Data=get_user_Map_Data() Top_transaction_Data=get_Transaction_Top_Data() Top_User_Data=get_User_Top_Data() st.subheader("Transaction Aggregated Data") st.dataframe(trans_data) st.subheader("User Aggregated Data") st.dataframe(user_data) st.subheader("Transaction Map Data") st.dataframe(trans_map) st.subheader("User Map Data") st.dataframe(user_map_Data) st.subheader("Top Transaction Data") st.dataframe(Top_transaction_Data) st.subheader("Top User Data") st.dataframe(Top_User_Data) def PreprocessData(): # Collect all the data trans_data = get_Transaction_Data() user_data = get_User_Data() trans_map = get_Transaction_Map_Data() user_map_Data = get_user_Map_Data() top_transaction_Data = get_Transaction_Top_Data() top_user_Data = get_User_Top_Data() # Drop rows with null values trans_data_clean = trans_data.dropna() user_data_clean = user_data.dropna() trans_map_clean = trans_map.dropna() user_map_Data_clean = user_map_Data.dropna() top_transaction_Data_clean = top_transaction_Data.dropna() top_user_Data_clean = top_user_Data.dropna() # If needed, return the cleaned dataframes for further use return trans_data_clean, user_data_clean, trans_map_clean, user_map_Data_clean, top_transaction_Data_clean, top_user_Data_clean def InsertAggregatedTransactionData(proces_data): proces_data["Year"]= pd.to_numeric(proces_data["Year"],errors="coerce") proces_data['Transaction_count']= pd.to_numeric(proces_data["Transaction_count"],errors="coerce") proces_data['Transaction_amount']= pd.to_numeric(proces_data["Transaction_amount"],errors="coerce") max_value = proces_data['Transaction_amount'].max() min_value = proces_data['Transaction_amount'].min() print(f"Max transaction amount: {max_value}, Min transaction amount: {min_value}") proces_data_to_insert = [tuple(row) for row in proces_data.values]#process every row proces_data['Transaction_amount'] = proces_data['Transaction_amount'].round(10) st.dataframe(proces_data['Transaction_amount']) # st.write(f'channel dataframes----->',proces_data_to_insert) # Inserting Channel Data to MySQL try: for row in proces_data_to_insert: insert_sql = "INSERT INTO Aggregate_Transaction_Data(state, year, quarter, transaction_type,transaction_count,transaction_amount) VALUES(%s,%s,%s,%s,%s,%s)" mycursor.execute(insert_sql, row) mydb.commit() except Exception as e: print("Error inserting data: ", e) # Optionally, display the error in Streamlit st.error(f"Error inserting data: {e}") def InsertAggregatedUserData(proces_data): proces_data["Year"]= pd.to_numeric(proces_data["Year"],errors="coerce") proces_data['Count']= pd.to_numeric(proces_data["Count"],errors="coerce") proces_data['Percentage']= pd.to_numeric(proces_data["Percentage"],errors="coerce") proces_data_to_insert = [tuple(row) for row in proces_data.values]#process every row # Inserting Channel Data to MySQL try: for row in proces_data_to_insert: insert_sql = "INSERT INTO User_Aggregated_Data(state, year, Quater, Brands,Count,Percentage) VALUES(%s,%s,%s,%s,%s,%s)" mycursor.execute(insert_sql, row) mydb.commit() except Exception as e: print("Error inserting data: ", e) # Optionally, display the error in Streamlit st.error(f"Error inserting data: {e}") def InsertTransactionMapData(proces_data): proces_data["Year"]= pd.to_numeric(proces_data["Year"],errors="coerce") proces_data['Count']= pd.to_numeric(proces_data["Count"],errors="coerce") proces_data['Amount']= pd.to_numeric(proces_data["Amount"],errors="coerce") proces_data_to_insert = [tuple(row) for row in proces_data.values]#process every row # Inserting Channel Data to MySQL try: for row in proces_data_to_insert: insert_sql = "INSERT INTO Transaction_Map_Data(state, year, quater, District,Count,Amount) VALUES(%s,%s,%s,%s,%s,%s)" mycursor.execute(insert_sql, row) mydb.commit() except Exception as e: print("Error inserting data: ", e) # Optionally, display the error in Streamlit st.error(f"Error inserting data: {e}") def InsertUserMapData(proces_data): proces_data["Year"]= pd.to_numeric(proces_data["Year"],errors="coerce") proces_data['RegisteredUser']= pd.to_numeric(proces_data["RegisteredUser"],errors="coerce") proces_data['AppOpens']= pd.to_numeric(proces_data["AppOpens"],errors="coerce") proces_data_to_insert = [tuple(row) for row in proces_data.values]#process every row # Inserting Channel Data to MySQL try: for row in proces_data_to_insert: insert_sql = "INSERT INTO User_Map_Data(state, year, quater, District,RegisteredUser,AppOpens) VALUES(%s,%s,%s,%s,%s,%s)" mycursor.execute(insert_sql, row) mydb.commit() except Exception as e: print("Error inserting data: ", e) # Optionally, display the error in Streamlit st.error(f"Error inserting data: {e}") def InsertTopTransactionData(proces_data): proces_data["Year"]= pd.to_numeric(proces_data["Year"],errors="coerce") proces_data['Count']= pd.to_numeric(proces_data["Count"],errors="coerce") proces_data['Amount']= pd.to_numeric(proces_data["Amount"],errors="coerce") proces_data_to_insert = [tuple(row) for row in proces_data.values]#process every row # Inserting Channel Data to MySQL try: for row in proces_data_to_insert: st.write(f"row---->{row}") insert_sql = "INSERT INTO Top_Transaction_Data(state, year, quater, District,Count,Amount) VALUES(%s,%s,%s,%s,%s,%s)" mycursor.execute(insert_sql, row) mydb.commit() except Exception as e: print("Error inserting data: ", e) # Optionally, display the error in Streamlit st.error(f"Error inserting data: {e}") def InsertTopUserData(proces_data): proces_data["Year"]= pd.to_numeric(proces_data["Year"],errors="coerce") proces_data['RegisteredUsers']= pd.to_numeric(proces_data["RegisteredUsers"],errors="coerce") proces_data_to_insert = [tuple(row) for row in proces_data.values]#process every row # Inserting Channel Data to MySQL try: for row in proces_data_to_insert: # st.write(f"row---->{row}") insert_sql = "INSERT INTO Top_user_Data(state, year, quater, District,RegisteredUser) VALUES(%s,%s,%s,%s,%s)" mycursor.execute(insert_sql, row) mydb.commit() except Exception as e: print("Error inserting data: ", e) # Optionally, display the error in Streamlit st.error(f"Error inserting data: {e}") def MigrateToSQL(proces_data): mainlogo() if st.button("Migrate Data"): InsertAggregatedTransactionData(proces_data[0]) InsertAggregatedUserData(proces_data[1]) InsertTransactionMapData(proces_data[2]) InsertUserMapData(proces_data[3]) InsertTopTransactionData(proces_data[4]) InsertTopUserData(proces_data[5]) # insert_video_SQL(proces_data) st.success("SuccessFully Migrated To SQL",icon="✅") # Mapping of slugified names to original names slug_to_original = { 'andaman-&-nicobar-islands': 'Andaman & Nicobar Island', 'andhra-pradesh': 'Andhra Pradesh', 'arunachal-pradesh': 'Arunanchal Pradesh', 'assam': 'Assam', 'bihar': 'Bihar', 'chandigarh': 'Chandigarh', 'chhattisgarh': 'Chhattisgarh', 'dadra-&-nagar-haveli-&-daman-&-diu': 'Dadara & Nagar Havelli', 'delhi': 'Delhi', 'goa': 'Goa', 'gujarat': 'Gujarat', 'haryana': 'Haryana', 'himachal-pradesh': 'Himachal Pradesh', 'jammu-&-kashmir': 'Jammu & Kashmir', 'jharkhand': 'Jharkhand', 'karnataka': 'Karnataka', 'kerala': 'Kerala', 'ladakh': 'Ladakh', 'lakshadweep': 'Lakshadweep', 'madhya-pradesh': 'Madhya Pradesh', 'maharashtra': 'Maharashtra', 'manipur': 'Manipur', 'meghalaya': 'Meghalaya', 'mizoram': 'Mizoram', 'nagaland': 'Nagaland', 'odisha': 'Odisha', 'puducherry': 'Puducherry', 'punjab': 'Punjab', 'rajasthan': 'Rajasthan', 'sikkim': 'Sikkim', 'tamil-nadu': 'Tamil Nadu', 'telangana': 'Telangana', 'tripura': 'Tripura', 'uttar-pradesh': 'Uttar Pradesh', 'uttarakhand': 'Uttarakhand', 'west-bengal': 'West Bengal' } # Function to map slugified name to original name def convert_state_name(slugified_name): return slug_to_original.get(slugified_name, slugified_name) def Section2(): #Section 2 #Geo Locations st.header("Total Users In Each State") col1,col2,col3,col4=st.columns(4,gap='small') with col1: type = st.selectbox( 'Transactions or Users', ('Transactions', 'Users'),key="TypeSelectionBox1") with col2: state = st.selectbox( 'State', ('All','Andaman & Nicobar Island', 'Andhra Pradesh', 'Arunanchal Pradesh', 'Assam', 'Bihar', 'Chandigarh', 'Chhattisgarh', 'Dadara & Nagar Havelli', 'Delhi', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jammu & Kashmir', 'Jharkhand', 'Karnataka', 'Kerala', 'Ladakh', 'Lakshadweep', 'Madhya Pradesh', 'Maharashtra', 'Manipur', 'Meghalaya', 'Mizoram', 'Nagaland', 'Odisha', 'Puducherry', 'Punjab', 'Rajasthan', 'Sikkim', 'Tamil Nadu', 'Telangana', 'Tripura', 'Uttarakhand', 'Uttar Pradesh', 'West Bengal'), key="stateselectionBox1" ) with col3: year = st.selectbox( 'Year', ('2018','2019','2020','2021','2022','2023','2024'),key="yearselectionBox1") with col4: quarter = st.selectbox('Quarter',('1', '2', '3', '4'),key="quaterselectionBox1") if(year == '2024' and (quarter == "3" or quarter == "4")): st.warning("The transaction data for the quater 3 and 4 is still not available because it is going on now") else: if(type == "Transactions"): if(state != 'All'): try: values=[year,state_change(state),quarter] query="select state,sum(Count) as transaction_Count,sum(Amount) as transaction_Amount from transaction_map_data where Year = %s and State= %s and quater=%s group by state order by state" mycursor.execute(query,values) data = mycursor.fetchall() data_df = pd.DataFrame(data,columns=['State','transaction_Count','transaction_Amount']) st.dataframe(data_df) except Exception as e: st.error(e) else: try: values=[year,quarter] query="select state,sum(Count) as transaction_Count,sum(Amount) as transaction_Amount from transaction_map_data where Year = %s and quater=%s group by state order by state" mycursor.execute(query,values) data = mycursor.fetchall() data_df = pd.DataFrame(data,columns=['State','transaction_Count','transaction_Amount']) st.dataframe(data_df) except Exception as e: st.error(e) if not data_df.empty: df=data_df with st.container(): st.header("Total Transaction Amount In Each State") # Apply the conversion function to the 'State' column df['State'] = df['State'].apply(convert_state_name) indian_states=json.load(open('states_india.geojson')) fig= go.Figure(go.Choropleth( geojson=indian_states, featureidkey="properties.st_nm", # Ensure this key matches the state names in your geojson file locations=df['State'],#this needs to match the locations z=df['transaction_Amount'],#which intensity needs to apply where depends on this colorscale="Viridis",#color scale we are using colorbar_title="Tranaction Amount", marker_line_color='darkgray', # Outline of the states marker_line_width=0.5 )) fig.update_geos(fitbounds="locations", visible=False,projection_type="mercator", showland=True, showocean=True, oceancolor="LightBlue",) fig.update_layout(height=600, width=800,plot_bgcolor="rgb(100, 240, 240)",margin={"r":0,"t":0,"l":0,"b":0}) st.plotly_chart(fig,use_container_width=True) elif(type == 'Users'): if(state != 'All'): try: values=[year,state_change(state),quarter] query="select state,sum(RegisteredUser) as TotalUsers from user_map_data where Year = %s and State= %s and quater=%s group by state order by state" mycursor.execute(query,values) data = mycursor.fetchall() data_df = pd.DataFrame(data,columns=['State','TotalUsers']) st.dataframe(data_df) except Exception as e: st.error(e) else: try: values=[year,quarter] query="select state,sum(RegisteredUser) as TotalUsers from user_map_data where Year = %s and quater=%s group by state order by state" mycursor.execute(query,values) data = mycursor.fetchall() data_df = pd.DataFrame(data,columns=['State','TotalUsers']) st.dataframe(data_df) except Exception as e: st.error(e) if not data_df.empty: df=data_df with st.container(): # Apply the conversion function to the 'State' column df['State'] = df['State'].apply(convert_state_name) indian_states=json.load(open('states_india.geojson')) # st.dataframe(df['State']) # st.write(indian_states) # for feature in indian_states["features"]: # st.write(feature["properties"]["st_nm"]) fig= go.Figure(go.Choropleth( geojson=indian_states, featureidkey="properties.st_nm", # Ensure this key matches the state names in your geojson file locations=df['State'],#this needs to match the locations z=df['TotalUsers'],#which intensity needs to apply where depends on this colorscale="Rainbow",#color scale we are using colorbar_title="TotalUsers", marker_line_color='darkgray', # Outline of the states marker_line_width=0.5 )) fig.update_geos(fitbounds="locations", visible=False,projection_type="mercator", showland=True,showocean=True, oceancolor="LightBlue",) fig.update_layout(height=600, width=800,margin={"r":0,"t":0,"l":0,"b":0}) st.plotly_chart(fig,use_container_width=True) def Section3(): # col1, col2, col3 = st.columns([3,1,3]) st.header("Transactions Amount Based On Transaction Type") #Draw the Bar chart based on the transaction type col,col4,col5,col6=st.columns(4,gap='medium') with col: type= type = st.selectbox( 'Transactions or Users', ('Transactions', 'Users'),key="TypeSelectionBox4") with col4: state = st.selectbox( 'State', ('All','Andaman & Nicobar Island', 'Andhra Pradesh', 'Arunanchal Pradesh', 'Assam', 'Bihar', 'Chandigarh', 'Chhattisgarh', 'Dadara & Nagar Havelli', 'Delhi', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jammu & Kashmir', 'Jharkhand', 'Karnataka', 'Kerala', 'Ladakh', 'Lakshadweep', 'Madhya Pradesh', 'Maharashtra', 'Manipur', 'Meghalaya', 'Mizoram', 'Nagaland', 'Odisha', 'Puducherry', 'Punjab', 'Rajasthan', 'Sikkim', 'Tamil Nadu', 'Telangana', 'Tripura', 'Uttarakhand', 'Uttar Pradesh', 'West Bengal'),key="stateSelectionBox2") with col5: year = st.selectbox( 'Year', ('2018','2019','2020','2021','2022','2023','2024'),key="yearSelectionBox2") with col6: quarter = st.selectbox('Quarter',('1', '2', '3', '4'),key="quaterSelectionBox2") if(year == '2024' and (quarter == "3" or quarter == "4")): st.warning("The transaction data for the quater 3 and 4 is still not available because it is going on now") else: if(type == 'Transactions'): if(state != "All"): values=[year,state_change(state),quarter] query="select transaction_type,sum(transaction_amount) as TotalAmount from aggregate_transaction_data where year=%s and state=%s and quarter =%s group by transaction_type" mycursor.execute(query,values) data=mycursor.fetchall() data_df=pd.DataFrame(data,columns=["transaction_type","TotalAmount"]) st.dataframe(data_df) else: values=[year,quarter] query=query="select transaction_type,sum(transaction_amount) as TotalAmount from aggregate_transaction_data where year=%s and quarter =%s group by transaction_type" mycursor.execute(query,values) data=mycursor.fetchall() data_df=pd.DataFrame(data,columns=["transaction_type","TotalAmount"]) st.dataframe(data_df) if not data_df.empty: # Create the bar chart fig = go.Figure(go.Bar( x=data_df['transaction_type'], y=data_df['TotalAmount'], marker_color='lightskyblue' )) fig.update_layout( title='Transaction Amount by Type', xaxis_title='Transaction Type', yaxis_title='Total Amount', xaxis_tickangle=-45 ) st.plotly_chart(fig, use_container_width=True) if not data_df.empty: hovertemplate = ( '%{label}
' # Label 'Amount: %{value:₹,.2f}
' # Value formatted as currency 'Percentage: %{percent:.1%}' # Percentage ) # Create the pie chart fig = go.Figure(go.Pie( labels=data_df['transaction_type'], values=data_df['TotalAmount'], hole=0.5, # Add a hole to create a donut chart (optional) hovertemplate=hovertemplate, title='Transaction Amount Distribution by Type' )) fig.update_layout( title='Transaction Amount Distribution by Type', autosize=True ) st.plotly_chart(fig, use_container_width=True) elif(type=='Users'): if(state != "All"): values=[year,state_change(state),quarter] query="select Brands,sum(Count) as totalCount from user_aggregated_data where Year=%s and State=%s and Quater=%s group by Brands" mycursor.execute(query,values) data=mycursor.fetchall() data_df=pd.DataFrame(data,columns=["Brands","totalCount"]) st.dataframe(data_df) else: values=[year,quarter] query=query="select Brands,sum(Count) as totalCount from user_aggregated_data where Year=%s and Quater=%s group by Brands" mycursor.execute(query,values) data=mycursor.fetchall() data_df=pd.DataFrame(data,columns=["Brands","totalCount"]) st.dataframe(data_df) if not data_df.empty: # Create the bar chart fig = go.Figure(go.Bar( x=data_df['Brands'], y=data_df['totalCount'], marker_color='lightskyblue' )) fig.update_layout( title='Transaction No of Users by Brands', xaxis_title='Brands', yaxis_title='totalCount', xaxis_tickangle=-45 ) st.plotly_chart(fig, use_container_width=True) if not data_df.empty: hovertemplate = ( '%{label}
' # Label 'Amount: %{value:₹,.2f}
' # Value formatted as currency 'Percentage: %{percent:.1%}' # Percentage ) # Create the pie chart fig = go.Figure(go.Pie( labels=data_df['Brands'], values=data_df['totalCount'], hole=0.5, # Add a hole to create a donut chart (optional) hovertemplate=hovertemplate, title='Transaction No of Users by Brands' )) fig.update_layout( title='Transaction No of Users by Brands', autosize=True ) st.plotly_chart(fig, use_container_width=True) def section4(): # col1, col2, col3 = st.columns([3,1,3]) st.header("Line Chart for Registered Users and Transaction amount") #Draw the Bar chart based on the transaction type col7,col8,col9=st.columns(3,gap='medium') with col7: type= type = st.selectbox( 'Transactions or Users', ('Transactions', 'Users'),key="TypeSelectionBox3") with col8: state = st.selectbox( 'State', ("All",'Andaman & Nicobar Island', 'Andhra Pradesh', 'Arunanchal Pradesh', 'Assam', 'Bihar', 'Chandigarh', 'Chhattisgarh', 'Dadara & Nagar Havelli', 'Delhi', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jammu & Kashmir', 'Jharkhand', 'Karnataka', 'Kerala', 'Ladakh', 'Lakshadweep', 'Madhya Pradesh', 'Maharashtra', 'Manipur', 'Meghalaya', 'Mizoram', 'Nagaland', 'Odisha', 'Puducherry', 'Punjab', 'Rajasthan', 'Sikkim', 'Tamil Nadu', 'Telangana', 'Tripura', 'Uttarakhand', 'Uttar Pradesh', 'West Bengal'),key="stateSelectionBox3") with col9: year = st.selectbox( 'Year', ('2018','2019','2020','2021','2022','2023','2024'),key="yearSelectionBox3") if(type == "Transactions"): if(state != "All"): values=[year,state_change(state)] query="select quarter,sum(transaction_amount) as total_amount from aggregate_transaction_data where year=%s and state=%s group by quarter" mycursor.execute(query,values) data=mycursor.fetchall() data_df=pd.DataFrame(data,columns=["quater","total_amount"]) st.dataframe(data_df) else: values=[year] query=query="select quarter,sum(transaction_amount) as total_amount from aggregate_transaction_data where year=%s group by quarter" mycursor.execute(query,values) data=mycursor.fetchall() data_df=pd.DataFrame(data,columns=["quater","total_amount"]) st.dataframe(data_df) if not data_df.empty: # Create the bar chart fig = go.Figure(go.Scatter( x=data_df['quater'], y=data_df['total_amount'], mode='lines+markers', marker=dict(color='lightskyblue') )) fig.update_layout( title='Transaction Amount by Quarter', xaxis_title='Quarter', yaxis_title='Total Amount', xaxis_tickangle=-45 ) st.plotly_chart(fig, use_container_width=True) elif(type == "Users"): if(state != "All"): values=[year,state_change(state)] query="select Quater,sum(RegisteredUser) as total_users from user_map_data where year=%s and state=%s group by Quater;" mycursor.execute(query,values) data=mycursor.fetchall() data_df=pd.DataFrame(data,columns=["quater","total_users"]) st.dataframe(data_df) else: values=[year] query="select Quater,sum(RegisteredUser) as total_users from user_map_data where year=%s group by Quater;" mycursor.execute(query,values) data=mycursor.fetchall() data_df=pd.DataFrame(data,columns=["quater","total_users"]) st.dataframe(data_df) if not data_df.empty: # Create the bar chart fig = go.Figure(go.Scatter( x=data_df['quater'], y=data_df['total_users'], mode='lines+markers', marker=dict(color='lightskyblue') )) fig.update_layout( title='Transaction Amount by Quarter', xaxis_title='Quarter', yaxis_title='Total Users', xaxis_tickangle=-45 ) st.plotly_chart(fig, use_container_width=True) def DataVisualization(): mainlogo() list_options=['Select one',"Highest Users From the Disctrict","Highest transaction Amount","Highest transactions"] #Section 1 col10,col11,col12 = st.columns(3) User_query="select sum(RegisteredUser) as total_registered_users, state from User_Map_Data group by state order by total_registered_users desc limit 1" mycursor.execute(User_query) User_data=mycursor.fetchall() state=User_data[0][1] state = state.title().replace('-', ' ') users = str(int(User_data[0][0])) col10.metric("Most Users",value=state,delta=users+' Users') Transaction_query="select sum(Count) as transaction_Count,State from transaction_map_data group by State order by transaction_Count desc limit 1" mycursor.execute(Transaction_query) Transaction_data=mycursor.fetchall() state=Transaction_data[0][1] state = state.title().replace('-', ' ') transactions = str(int(Transaction_data[0][0])) col11.metric( "Most Transactions",value=state,delta=transactions+' Transactions') TransactionAmount_query="select sum(Amount) as transaction_Amount,State from transaction_map_data group by State order by transaction_Amount desc limit 1" mycursor.execute(TransactionAmount_query) Transaction_Amount_data=mycursor.fetchall() state=Transaction_Amount_data[0][1] state = state.title().replace('-', ' ') transactions_amount = str(int(Transaction_Amount_data[0][0])) col12.metric( "Most Transactions Amounts",value=state,delta=transactions_amount+' Transactions Amounts') # Insert a horizontal line st.markdown("
", unsafe_allow_html=True) Section2() Section3() section4() # Sidebar with st.sidebar: option =option_menu("Main Menu", ["Home", 'Data Collection','Data Overview','Migrating Data to SQL','Data Insights','Exit'], icons=['house-fill', 'graph-up-arrow', 'file-bar-graph', 'save-fill', 'search', 'box-arrow-right'], menu_icon="cast", default_index=0,styles={ "container": {"padding": "0!important", "background-color": "#0E1117"}, "icon": {"color": "#6c6c6c", "font-size": "25px"}, "nav-link": { "font-size": "16px", "text-align": "left", "margin": "10px", "color": "#FfFFF", }, "nav-link-selected": {"background-color": "#0E1117", "color": "white"}, }) # Main content if option == 'Home': home() elif option == 'Data Collection': DataCollection() elif option == 'Data Overview': DataOverview() elif option == 'Migrating Data to SQL Database': ProccessedData=PreprocessData() MigrateToSQL(ProccessedData) elif option == 'Data Insights': DataVisualization() elif option == 'Exit': st.write("Thank you for using the application!")