Sirivennela commited on
Commit
5c8245c
Β·
verified Β·
1 Parent(s): 0182a9b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -63
app.py CHANGED
@@ -1,66 +1,129 @@
1
  import streamlit as st
2
- import requests
3
  import pandas as pd
4
- import simple_salesforce
5
-
6
- # ---------------------- CONFIG ----------------------
7
- CLIENT_ID = "3MVG9VMBZCsTL9hnfx2eVMOHa56mwSZnvuAnPr3kVVBEQfeLYvrSfJNRRjjSlKWPLy99XM6kefg=="
8
- CLIENT_SECRET = "6F7E9C95CE20CC07FC1EBD39B34909739D99975A0EEB548240926EA0686E428E"
9
- USERNAME = "greenenergy@vedavathi.com"
10
- PASSWORD = "Vedavathi@04"+"qe4His8AcuFJucZz5NBHfGU" # Keep this as the password (without the security token)
11
- TOKEN_URL = "https://login.salesforce.com/services/oauth2/token" # For production
12
- API_VERSION = "v60.0"
13
-
14
- # ---------------------- AUTH ----------------------
15
- @st.cache_data
16
- def get_salesforce_token():
17
- data = {
18
- "grant_type": "Vedavathi@04"+"qe4His8AcuFJucZz5NBHfGU", # Corrected grant_type
19
- "client_id": "3MVG9VMBZCsTL9hnfx2eVMOHa56mwSZnvuAnPr3kVVBEQfeLYvrSfJNRRjjSlKWPLy99XM6kefg==",
20
- "client_secret":"6F7E9C95CE20CC07FC1EBD39B34909739D99975A0EEB548240926EA0686E428E" ,
21
- "username":"greenenergy@vedavathi.com" ,
22
- "password":"Vedavathi@04"+"qe4His8AcuFJucZz5NBHfGU" # Correctly concatenate password and security token
23
- }
24
- response = requests.post(TOKEN_URL, data=data)
25
-
26
- if response.status_code != 200:
27
- # Log detailed error message for better debugging
28
- error_message = response.json() if response.status_code != 200 else "No error message"
29
- st.error(f"Authentication failed! Status code: {response.status_code}, Message: {error_message}")
30
- return None, None
31
-
32
- res = response.json()
33
- return res["access_token"], res["instance_url"]
34
-
35
- # ---------------------- FETCH DATA ----------------------
36
- def fetch_pole_data(instance_url, access_token):
37
- headers = {
38
- "Authorization": f"Bearer {access_token}"
39
- }
40
- query = "SELECT Name, Location_Latitude__c, Location_Longitude__c, Camera_Status__c FROM Pole__c LIMIT 100"
41
- url = f"{instance_url}/services/data/{API_VERSION}/query?q={query}"
42
- response = requests.get(url, headers=headers)
43
-
44
- if response.status_code != 200:
45
- st.error(f"Failed to fetch Pole data! Status code: {response.status_code}, Message: {response.json()}")
46
- return pd.DataFrame()
47
-
48
- records = response.json().get("records", [])
49
- df = pd.DataFrame(records)
50
- return df[["Name", "Location_Latitude__c", "Location_Longitude__c", "Camera_Status__c"]]
51
-
52
- # ---------------------- UI ----------------------
53
- st.title("🚦Vedavathi Smart Poles Viewer")
54
-
55
- token, instance_url = get_salesforce_token()
56
-
57
- if token:
58
- if st.button("πŸ”„ Refresh Pole Data"):
59
- df = fetch_pole_data(instance_url, token)
60
- if not df.empty:
61
- st.success("Pole data loaded successfully!")
62
- st.dataframe(df, use_container_width=True)
63
- else:
64
- st.warning("No data found.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  else:
66
- st.error("Salesforce authentication failed. Check credentials.")
 
 
1
  import streamlit as st
 
2
  import pandas as pd
3
+ import plotly.express as px
4
+ from simple_salesforce import Salesforce
5
+
6
+ # Page configuration
7
+ st.set_page_config(page_title="Vedavathi Pole Dashboard", layout="wide")
8
+
9
+ # -------------------------------
10
+ # Connect to Salesforce
11
+ # -------------------------------
12
+ @st.cache_resource
13
+ def connect_salesforce():
14
+ try:
15
+ sf = Salesforce(
16
+ username="greenenergy@vedavathi.com",
17
+ password="Vedavathi@04",
18
+ security_token="jqe4His8AcuFJucZz5NBHfGU",
19
+ domain="login"
20
+ )
21
+ return sf
22
+ except Exception as e:
23
+ st.error(f"❌ Failed to connect to Salesforce: {e}")
24
+ return None
25
+
26
+ sf = connect_salesforce()
27
+
28
+ # -------------------------------
29
+ # Main App Logic
30
+ # -------------------------------
31
+ if sf:
32
+ st.success("βœ… Connected to Salesforce")
33
+
34
+ # Query Pole data
35
+ query = """
36
+ SELECT Id, Name, Location__c, Status__c, Power_Generation__c,
37
+ Fault_Status__c, Last_Maintenance_Date__c, Installed_Date__c
38
+ FROM Pole__c
39
+ LIMIT 1000
40
+ """
41
+ result = sf.query_all(query)
42
+ df = pd.DataFrame(result['records']).drop(columns='attributes')
43
+
44
+ # Clean and format data
45
+ df['Installed_Date__c'] = pd.to_datetime(df['Installed_Date__c'])
46
+ df['Last_Maintenance_Date__c'] = pd.to_datetime(df['Last_Maintenance_Date__c'])
47
+ df['Power_Generation__c'] = pd.to_numeric(df['Power_Generation__c'], errors='coerce')
48
+
49
+ # Sidebar filters
50
+ st.sidebar.header("πŸ” Filters")
51
+ status_filter = st.sidebar.multiselect("Select Pole Status", df['Status__c'].unique(), default=df['Status__c'].unique())
52
+ fault_filter = st.sidebar.multiselect("Select Fault Status", df['Fault_Status__c'].unique(), default=df['Fault_Status__c'].unique())
53
+
54
+ # Apply filters
55
+ filtered_df = df[
56
+ df['Status__c'].isin(status_filter) &
57
+ df['Fault_Status__c'].isin(fault_filter)
58
+ ]
59
+
60
+ st.title("⚑ Vedavathi Smart Pole Dashboard")
61
+
62
+ # -------------------------------
63
+ # πŸ“‹ Data Table
64
+ # -------------------------------
65
+ st.subheader("πŸ“‹ Pole Data Table")
66
+ st.dataframe(filtered_df)
67
+
68
+ # -------------------------------
69
+ # πŸ”‹ Bar Chart - Power Generation
70
+ # -------------------------------
71
+ st.subheader("πŸ”‹ Power Generation per Pole")
72
+ fig_bar = px.bar(
73
+ filtered_df,
74
+ x='Name',
75
+ y='Power_Generation__c',
76
+ color='Status__c',
77
+ title="Power Output by Pole",
78
+ height=400
79
+ )
80
+ st.plotly_chart(fig_bar, use_container_width=True)
81
+
82
+ # -------------------------------
83
+ # ⚠️ Pie Chart - Fault Status
84
+ # -------------------------------
85
+ st.subheader("⚠️ Fault Status Distribution")
86
+ pie_data = filtered_df['Fault_Status__c'].value_counts().reset_index()
87
+ pie_data.columns = ['Fault Status', 'Count']
88
+ fig_pie = px.pie(
89
+ pie_data,
90
+ names='Fault Status',
91
+ values='Count',
92
+ title="Fault Breakdown",
93
+ height=400
94
+ )
95
+ st.plotly_chart(fig_pie, use_container_width=True)
96
+
97
+ # -------------------------------
98
+ # πŸ•’ Line Chart - Installations
99
+ # -------------------------------
100
+ st.subheader("πŸ•’ Installation Trend")
101
+ install_trend = filtered_df.groupby(filtered_df['Installed_Date__c'].dt.to_period('M')).size()
102
+ install_trend.index = install_trend.index.to_timestamp()
103
+ fig_line_install = px.line(
104
+ x=install_trend.index,
105
+ y=install_trend.values,
106
+ labels={"x": "Month", "y": "Poles Installed"},
107
+ title="Installations Over Time",
108
+ markers=True
109
+ )
110
+ st.plotly_chart(fig_line_install, use_container_width=True)
111
+
112
+ # -------------------------------
113
+ # πŸ› οΈ Line Chart - Maintenance
114
+ # -------------------------------
115
+ st.subheader("πŸ› οΈ Maintenance Trend")
116
+ maint_trend = filtered_df.groupby(filtered_df['Last_Maintenance_Date__c'].dt.to_period('M')).size()
117
+ maint_trend.index = maint_trend.index.to_timestamp()
118
+ fig_line_maint = px.line(
119
+ x=maint_trend.index,
120
+ y=maint_trend.values,
121
+ labels={"x": "Month", "y": "Maintenance Events"},
122
+ title="Maintenance Over Time",
123
+ markers=True
124
+ )
125
+ st.plotly_chart(fig_line_maint, use_container_width=True)
126
+
127
  else:
128
+ st.error("❌ Could not connect to Salesforce. Check your credentials.")
129
+