File size: 5,834 Bytes
cc57572
 
9f92e30
cc57572
 
 
4347f12
 
89e508b
 
 
 
1d64ba6
 
32b031f
89e508b
4347f12
9f92e30
89e508b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2132a09
89e508b
208f1e5
 
 
 
 
 
 
 
 
 
 
 
2132a09
 
89e508b
cc57572
 
0d27fcd
 
cc57572
 
 
 
89e508b
 
 
 
 
 
 
 
cc57572
 
 
 
 
 
 
 
 
 
 
67afffb
772b7d8
cc57572
d2a511f
cc57572
3dd51cc
cc57572
3dd51cc
 
 
 
 
 
 
 
63acd78
3dd51cc
 
 
cc57572
 
 
 
 
 
 
 
 
 
 
 
4347f12
cc57572
 
 
 
ab0b014
a235308
cc57572
 
 
 
 
 
 
208f1e5
67afffb
cc57572
4347f12
2132a09
 
cc57572
4347f12
 
d2a511f
 
 
 
 
5a8f0d9
d2a511f
 
 
 
5a8f0d9
 
d2a511f
 
f536adb
 
d2a511f
 
 
cc57572
 
4347f12
cc57572
4347f12
d2a511f
4d8c16f
 
cc57572
4347f12
d2a511f
c547b9c
89e508b
 
 
 
24b77a6
89e508b
 
 
 
 
 
142a644
2132a09
208f1e5
2132a09
 
142a644
208f1e5
2132a09
ef132d8
 
142a644
cc57572
 
 
2c50f3f
cc57572
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import firebase_admin
from firebase_admin import credentials, firestore, auth
import streamlit as st
import requests
import pandas as pd
from datetime import datetime
from st_on_hover_tabs import on_hover_tabs
import streamlit as st
import os
from pandasai.llm import GoogleGemini
from pandasai import SmartDataframe
from pandasai.responses.response_parser import  ResponseParser
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import random

st.set_page_config(layout="wide")

class StreamLitResponse(ResponseParser):
        def __init__(self,context) -> None:
              super().__init__(context)
        def format_dataframe(self,result):
               st.dataframe(result['value'])
               return
        def format_plot(self,result):
               st.image(result['value'])
               return
        def format_other(self, result):
               st.write(result['value'])
               return

gemini_api_key = os.environ['Gemini']

def generateResponse(dataFrame,prompt):
        llm = GoogleGemini(api_key=gemini_api_key)
        pandas_agent = SmartDataframe(dataFrame,config={"llm":llm, "response_parser":StreamLitResponse})
        answer = pandas_agent.chat(prompt)
        return answer

def generate_random_team():

  men_names = ["John Khumalo", "Michael Smith", "David Johnson", "Jessica Mandela"]
  women_names = ["Emily Brown", "Olivia Nkosi", "Sophia Miller", "Thomas Sithole"]

  team_members = [
      {
          "name": name,
          "status": random.choice(["visiting site", "ready for deployment"]),
          "contact": f"077123456{i+1}",  # Replace with actual contact format
          "whatsapp": "📱"
      }
      for i, name in enumerate(men_names + women_names)
  ]
  random.shuffle(team_members)
  return team_members

# Initialize Firebase app
if not firebase_admin._apps:
   
    cred = credentials.Certificate("ecomplaintbook-firebase-adminsdk-4q5bo-d27afe12f8.json")
    firebase_admin.initialize_app(cred)

db = firestore.client()

complaints_ref = db.collection('complaints')

complaints_list = []
for doc in complaints_ref.stream():
    a = doc.to_dict()
    complaints_list.append(a)

complaints_df = pd.DataFrame(complaints_list)

# Function to fetch user profile from Firebase
def fetch_user_profile_from_firebase(user_id):
    user_profile_ref = db.collection("users").document(user_id)
    user_profile = user_profile_ref.get().to_dict()
    return user_profile


# Function for user authentication
def user_authentication():
     # Add image and title
    st.image("ecomp1.jpg", width=200)
    st.title("Be Heard")

    st.header("Admin Dashboard")
    
   
        # If the user is an existing user, prompt for email and password
    email = st.text_input("Email")
    password = st.text_input("Password", type="password")
    if st.button("Sign In"):
        try:
            user = auth.get_user_by_email(email)
            st.success(f"Welcome back, {user.email}!")
            user_id = user.uid
            st.session_state.user_id = user_id
            st.rerun()
        except auth.UserNotFoundError:
            st.error("User not found. Please check your credentials or sign up.")
        except Exception as e:
                st.error(f"Error during sign-in: {e}")









# Main Streamlit app
def main():
    st.markdown('<style>' + open('./style.css').read() + '</style>', unsafe_allow_html=True)
    if "user_id" not in st.session_state:
        user_authentication()
        return

    
    st.title("Be Heard")

    user_id = st.session_state.user_id


  

# Sidebar
    st.sidebar.title("Be Heard")
    st.sidebar.image("ecomp1.jpg", use_column_width=True)

    with st.sidebar:
        tabs = on_hover_tabs(tabName=['Dashboard', 'Map', 'Chat', 'Response Team'], 
                         iconName=['dashboard', 'map', 'chat', 'person'], default_choice=0)

    if tabs =='Dashboard':
        st.header("Complaints")

        # Create two columns
        col1, col2 = st.columns(2)
   
        with col1:
    # Pie Chart for Resolution Status
            fig, ax = plt.subplots()
            complaints_df['resolution_status'].value_counts().plot(kind='pie', autopct='%1.1f%%', ax=ax)
            ax.set_ylabel('')
            st.pyplot(fig)

    # Word Cloud for Complaint Description
        with col2:
            text = " ".join(complaints_df['complaint_description'])
            wordcloud = WordCloud(background_color='white', width=800, height=800).generate(text)
            plt.figure(figsize=(8, 8))
            plt.imshow(wordcloud, interpolation='bilinear')
            plt.axis('off')
            st.pyplot(plt)


        st.dataframe(complaints_df)

    elif tabs == 'Map':
        st.header("Google Maps view of eThekwini complaints")
        st.markdown("""" <iframe src="https://www.google.com/maps/d/u/0/embed?mid=16Fo-30K46Sq5NbHYW6d7pWtggO-QKAU&ehbc=2E312F" width="640" height="480"></iframe> """,
                    unsafe_allow_html=True)

    elif tabs == 'Chat':
        st.header("eThekwini Chat Powered by Gemini")
        st.write("Get visualizations and analysis from our Gemini powered agent")
    

        # Display the data
        with st.expander("Preview"):
            st.write(complaints_df.head(3))

        # Plot the data
        user_input = st.text_input("Type your message here",placeholder="Ask me about complaints from eThekwini residents")
        if user_input:
            answer = generateResponse(dataFrame=complaints_df,prompt=user_input)
            st.write(answer)

    elif tabs == 'Response Team':
        st.header("Durban Response Team")

        team = generate_random_team()

        st.table(team)
        

       
    

    if st.button("Logout", key="logout_button"):
        del st.session_state["user_id"]
        st.rerun()

if __name__ == "__main__":
    main()