Guavacoderepo commited on
Commit
d45a77c
·
verified ·
1 Parent(s): 4f46494

Upload 8 files

Browse files
src/pages/__pycache__/auth.cpython-312.pyc ADDED
Binary file (5.24 kB). View file
 
src/pages/__pycache__/chat.cpython-312.pyc ADDED
Binary file (3.76 kB). View file
 
src/pages/auth.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ from src.utils.history import retrieve_history
4
+ from src.schemas.schemas import UserModel
5
+
6
+ # List of possible user roles for registration dropdown
7
+ roles = ["engineering", "marketing", "finance", "hr", "general", "executives"]
8
+
9
+
10
+ # Login page UI and logic
11
+ def login_page():
12
+ st.title("Login Page")
13
+
14
+ # User inputs for credentials
15
+ username = st.text_input("Username")
16
+ password = st.text_input("Password", type="password")
17
+ api_key = st.text_input("Openai API Key", type="password")
18
+
19
+ # Center the buttons using three columns
20
+ col1, _, _ = st.columns([2, 2, 1])
21
+
22
+ # Place both buttons in the left column (col1)
23
+ with col1:
24
+ login_clicked = st.button("Login")
25
+ register_clicked = st.button("Don't have an account? Register")
26
+
27
+ if login_clicked:
28
+ # Check if API key is provided
29
+ if not api_key.strip():
30
+ st.warning("⚠️ Please enter your OpenAI API Key before logging in.")
31
+ else:
32
+ try:
33
+ # Send POST request to FastAPI login endpoint with credentials
34
+ response = requests.post(
35
+ "https://finsolve-chatbot-backend.onrender.com/api/v1/auth/login",
36
+ json={"username": username, "password": password, "api_key": api_key}
37
+ )
38
+
39
+ if response.status_code == 200:
40
+ user_resp = response.json()
41
+ role = "employee" if user_resp['user']['role'] == "general" else user_resp['user']['role']
42
+ user_resp['user']['role'] = role
43
+ user_model = UserModel(**user_resp)
44
+
45
+ st.success(f"✅ Login successful, Welcome, {user_model.user.username}, (Role: {user_model.user.role})")
46
+ st.session_state.token = user_model.token
47
+ st.session_state.user = user_model.user
48
+ retrieve_history()
49
+ st.rerun()
50
+ else:
51
+ st.error(f"❌ Login failed: {response.json().get('msg', 'Invalid credentials')}")
52
+
53
+ except Exception as e:
54
+ st.error(f"⚠️ Error connecting to server: {e}")
55
+
56
+
57
+ if register_clicked:
58
+ # Switch UI to registration page and rerun app
59
+ st.session_state.is_login = False
60
+ st.rerun()
61
+
62
+
63
+ # Registration page UI and logic
64
+ def registration_page():
65
+ st.title("Registration Page")
66
+
67
+ # User inputs for new account creation
68
+ username = st.text_input("Username")
69
+ role = st.selectbox("Select Role", roles)
70
+ password = st.text_input("Password", type="password")
71
+
72
+ role = "general" if role == "employee" else role
73
+
74
+ # Center the buttons using three columns
75
+ col1, _, _ = st.columns([2, 2, 1])
76
+
77
+ # Place both buttons in the left column (col1)
78
+ with col1:
79
+ register_clicked = st.button("Register")
80
+ login_clicked = st.button("Already have an account? Login")
81
+
82
+ if register_clicked:
83
+ try:
84
+ # Send POST request to FastAPI registration endpoint with user data
85
+ response = requests.post(
86
+ "https://finsolve-chatbot-backend.onrender.com/api/v1/auth/register",
87
+ json={"username": username, "password": password, "role": role}
88
+ )
89
+
90
+ if response.status_code == 200:
91
+
92
+ # Switch UI back to login page
93
+ st.session_state.is_login = True
94
+
95
+ # Refresh app to show login UI
96
+ st.rerun()
97
+
98
+ # Show success message on successful registration
99
+ st.success(f"✅ Registration of {username} successful!")
100
+
101
+ else:
102
+ # Show API error message on failure
103
+ st.error(f"❌ Registration failed: {response.json().get('msg', 'Unknown error')}")
104
+
105
+ except Exception as e:
106
+ # Handle unexpected errors gracefully
107
+ st.error(f"⚠️ Error connecting to server: {e}")
108
+
109
+ if login_clicked:
110
+ # Switch UI back to login page and rerun
111
+ st.session_state.is_login = True
112
+ st.rerun()
113
+
114
+
115
+ # Function to handle user logout
116
+ def logout():
117
+ # Clear session data such as auth token and messages
118
+ st.session_state.token = None
119
+ st.session_state.messages = []
120
+
121
+ # Refresh app to redirect to login page
122
+ st.rerun()
src/pages/chat.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ from .auth import logout
4
+ from src.schemas.schemas import User
5
+
6
+ # Main chat UI function
7
+ def chat_ui():
8
+ st.title("FinSolve Technologies Chatbot")
9
+
10
+ user:User = st.session_state.user
11
+
12
+ # Sidebar section for user info and logout button
13
+ with st.sidebar:
14
+ st.write(f"Welcome: {user.username}")
15
+ st.write(user.role.value.capitalize())
16
+
17
+ # Logout button
18
+ if st.button("🔒 Logout"):
19
+ logout()
20
+
21
+ # Display clickable link for resources
22
+ st.markdown(
23
+ "[View resources](https://github.com/guavacoderepo/Role-based-chatbot/tree/main/backend/resources)",
24
+ unsafe_allow_html=True
25
+ )
26
+
27
+ # Display existing chat history
28
+ for message in st.session_state.messages:
29
+ with st.chat_message(message["role"]):
30
+ st.markdown(message["content"])
31
+
32
+ # Prompt user for new chat input
33
+ if prompt := st.chat_input("What is up?"):
34
+ # Store user input in session state
35
+ st.session_state.messages.append({"role": "user", "content": prompt})
36
+
37
+ # Display user input in the chat interface
38
+ with st.chat_message("user"):
39
+ st.markdown(prompt)
40
+
41
+ # Make POST request to backend API
42
+ try:
43
+ response = requests.post(
44
+ "https://finsolve-chatbot-backend.onrender.com/api/v1/chat/start",
45
+ json={"prompt": prompt},
46
+ headers={
47
+ "Authorization": f"Bearer {st.session_state.token}"
48
+ }
49
+ )
50
+ response.raise_for_status()
51
+
52
+ # Check the response content type
53
+ content_type = response.headers.get("content-type", "")
54
+
55
+ # If it's a PDF, show download button
56
+ if "application/pdf" in content_type:
57
+ st.success("📄 PDF is ready to download!")
58
+ st.download_button(
59
+ label="📥 Click to download PDF",
60
+ data=response.content,
61
+ file_name=f"{user.username}_{user.role.value}_summary.pdf",
62
+ mime="application/pdf"
63
+ )
64
+ assistant_text = "✅ I've generated a PDF summary for you!"
65
+ else:
66
+ # If it's text response, parse and display
67
+ assistant_reply = response.json()
68
+ assistant_text = assistant_reply.get('response', 'No response received.')
69
+
70
+ except Exception as e:
71
+ # Handle any errors during request
72
+ assistant_text = f"❌ Error: {str(e)}"
73
+
74
+ # Display assistant response
75
+ with st.chat_message("assistant"):
76
+ st.markdown(assistant_text)
77
+
78
+ # Save assistant response to session
79
+ st.session_state.messages.append({"role": "assistant", "content": assistant_text})
src/schemas/__pycache__/schemas.cpython-312.pyc ADDED
Binary file (1.16 kB). View file
 
src/schemas/schemas.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ from enum import Enum
3
+ from typing import Optional
4
+
5
+ class Roles(Enum):
6
+ Engineering = "engineering"
7
+ Employee = "employee"
8
+ Finance = "finance"
9
+ Executives = "executives"
10
+ Marketing = "marketing"
11
+ HR = "hr"
12
+
13
+ class User(BaseModel):
14
+ id:int
15
+ username:str
16
+ role: Roles
17
+
18
+ class UserModel(BaseModel):
19
+ status: bool
20
+ user: User
21
+ token: Optional[str] = None
src/utils/__pycache__/history.cpython-312.pyc ADDED
Binary file (1.18 kB). View file
 
src/utils/history.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+
4
+ # Function to retrieve chat history from backend
5
+ def retrieve_history():
6
+ # Send GET request to backend `/history` endpoint with user credentials
7
+ response = requests.get(
8
+ "https://finsolve-chatbot-backend.onrender.com/api/v1/chat/history",
9
+ headers={
10
+ "Authorization": f"Bearer {st.session_state.token}"
11
+ }
12
+ )
13
+
14
+ # Parse JSON response containing previous chat entries
15
+ mesages = response.json()
16
+
17
+ # Initialize the messages list in session state if not already present
18
+ if "messages" not in st.session_state:
19
+ st.session_state.messages = []
20
+
21
+ # Loop through each entry and append user and assistant messages to the session state
22
+ for entry in mesages:
23
+ st.session_state.messages.append({
24
+ "role": "user",
25
+ "content": entry["prompt"]
26
+ })
27
+ st.session_state.messages.append({
28
+ "role": "assistant",
29
+ "content": entry["response"]
30
+ })