khankashif commited on
Commit
511a6dd
Β·
verified Β·
1 Parent(s): 4c1127d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -136
app.py CHANGED
@@ -1,147 +1,77 @@
1
  import streamlit as st
2
- import os
3
- import requests
4
- from dotenv import load_dotenv
5
- import bcrypt
6
 
7
- # Load environment variables
8
- load_dotenv()
9
-
10
- # Retrieve Hugging Face API key from .env file
11
- api_key = os.getenv("HUGGINGFACE_API_KEY")
12
- headers = {"Authorization": f"Bearer {api_key}"}
13
-
14
- # Function to query the Llama model using Hugging Face Inference API
15
- def query_llama(prompt):
16
- # Replace with the correct endpoint for your open source Llama model
17
- API_URL = "https://api-inference.huggingface.co/models/meta-llama/Llama-2-70b-chat"
18
- payload = {"inputs": prompt}
19
- response = requests.post(API_URL, headers=headers, json=payload)
20
- if response.status_code == 200:
21
- output = response.json()[0].get("generated_text", "No output generated.")
22
- return output
23
- else:
24
- return f"Error: {response.status_code} - {response.text}"
25
 
26
- # -----------------------
27
- # User Authentication Setup
28
- # -----------------------
29
- if "users" not in st.session_state:
30
- # Pre-register a user "kashif" with password "password" for demonstration
31
- hashed = bcrypt.hashpw("password".encode(), bcrypt.gensalt())
32
- st.session_state.users = {
33
- "kashif": {"password": hashed, "balance": 1000.0, "transactions": []}
34
- }
35
 
36
- if "logged_in" not in st.session_state:
37
- st.session_state.logged_in = False
38
- if "current_user" not in st.session_state:
39
- st.session_state.current_user = None
40
 
41
  def register_user(username, password):
42
- users = st.session_state.users
43
- if username in users:
44
- return False, "Username already exists."
45
- hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
46
- users[username] = {"password": hashed, "balance": 0.0, "transactions": []}
47
- st.session_state.users = users
48
- return True, "Registration successful! Please login."
49
-
50
- def login(username, password):
51
- users = st.session_state.users
52
- if username in users:
53
- stored_hash = users[username]["password"]
54
- if bcrypt.checkpw(password.encode(), stored_hash):
55
- st.session_state.logged_in = True
56
- st.session_state.current_user = username
57
- return True
58
  return False
59
 
60
- def logout():
61
- st.session_state.logged_in = False
62
- st.session_state.current_user = None
63
-
64
- def update_balance(username, amount, operation):
65
- if operation == "deposit":
66
- st.session_state.users[username]["balance"] += amount
67
- elif operation == "withdraw":
68
- st.session_state.users[username]["balance"] -= amount
69
-
70
- def add_transaction(username, trans_type, amount):
71
- transaction = {"type": trans_type, "amount": amount}
72
- st.session_state.users[username]["transactions"].append(transaction)
73
-
74
- # -----------------------
75
- # Streamlit App UI
76
- # -----------------------
77
- st.title("Banking Chatbot with Llama AI Integration")
78
-
79
- # Toggle between Login and Register
80
- auth_mode = st.radio("Select Option", ["Login", "Register"])
81
-
82
- if auth_mode == "Register":
83
- st.header("Register")
84
- reg_username = st.text_input("Choose a Username", key="reg_username")
85
- reg_password = st.text_input("Choose a Password", type="password", key="reg_password")
86
- reg_confirm = st.text_input("Confirm Password", type="password", key="reg_confirm")
87
- if st.button("Register"):
88
- if reg_password != reg_confirm:
89
- st.error("Passwords do not match.")
90
- else:
91
- success, message = register_user(reg_username, reg_password)
92
- if success:
93
- st.success(message)
94
- else:
95
- st.error(message)
96
-
97
- if auth_mode == "Login":
98
- st.header("Login")
99
- username = st.text_input("Username", key="login_username")
100
- password = st.text_input("Password", type="password", key="login_password")
101
- if st.button("Login"):
102
- if login(username, password):
103
- st.success("Logged in successfully!")
104
- else:
105
- st.error("Invalid username or password.")
106
-
107
- if st.session_state.logged_in:
108
- st.sidebar.write(f"Logged in as: {st.session_state.current_user}")
109
- if st.sidebar.button("Logout"):
110
- logout()
111
- st.sidebar.success("Logged out.")
112
-
113
- st.header("Banking Operations")
114
- current_user = st.session_state.current_user
115
- user_data = st.session_state.users[current_user]
116
- st.write("**Current Balance:** $", user_data["balance"])
117
-
118
- action = st.selectbox("Select Operation", ["Deposit", "Withdraw"])
119
- amount = st.number_input("Enter Amount", min_value=0.0, step=10.0)
120
- if st.button("Submit Transaction"):
121
- if action == "Deposit":
122
- update_balance(current_user, amount, "deposit")
123
- add_transaction(current_user, "deposit", amount)
124
- st.success(f"Deposited ${amount}. New balance: ${user_data['balance']}")
125
- elif action == "Withdraw":
126
- if user_data["balance"] >= amount:
127
- update_balance(current_user, amount, "withdraw")
128
- add_transaction(current_user, "withdraw", amount)
129
- st.success(f"Withdrew ${amount}. New balance: ${user_data['balance']}")
130
- else:
131
- st.error("Insufficient balance.")
132
-
133
- st.header("Transaction History")
134
- if user_data["transactions"]:
135
- for idx, t in enumerate(user_data["transactions"], start=1):
136
- st.write(f"{idx}. **{t['type'].capitalize()}**: ${t['amount']}")
137
  else:
138
- st.write("No transactions recorded.")
139
 
140
- st.header("Ask Llama AI")
141
- prompt = st.text_input("Enter your query for Llama:")
142
- if st.button("Get AI Response"):
143
- if prompt:
144
- ai_response = query_llama(prompt)
145
- st.write("Llama says:", ai_response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  else:
147
- st.error("Please enter a query.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from datetime import datetime
 
 
 
3
 
4
+ # Initialize session state for users
5
+ if 'users' not in st.session_state:
6
+ st.session_state.users = {}
7
+ if 'current_user' not in st.session_state:
8
+ st.session_state.current_user = None
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ # Authentication
11
+ st.sidebar.title("πŸ” User Authentication")
12
+ username = st.sidebar.text_input("Enter Username")
13
+ password = st.sidebar.text_input("Enter Password", type="password")
 
 
 
 
 
14
 
15
+ def authenticate(username, password):
16
+ return username in st.session_state.users and st.session_state.users[username]['password'] == password
 
 
17
 
18
  def register_user(username, password):
19
+ if username not in st.session_state.users:
20
+ st.session_state.users[username] = {
21
+ 'password': password,
22
+ 'balance': 10000.0,
23
+ 'transactions': []
24
+ }
25
+ return True
 
 
 
 
 
 
 
 
 
26
  return False
27
 
28
+ if st.sidebar.button("Login"):
29
+ if authenticate(username, password):
30
+ st.session_state.current_user = username
31
+ st.sidebar.success("βœ… Login Successful!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  else:
33
+ st.sidebar.error("❌ Invalid Username or Password")
34
 
35
+ if st.sidebar.button("Register"):
36
+ if register_user(username, password):
37
+ st.sidebar.success("βœ… Registration Successful! Please Login.")
38
+ else:
39
+ st.sidebar.error("❌ User already exists!")
40
+
41
+ if st.session_state.current_user:
42
+ user_data = st.session_state.users[st.session_state.current_user]
43
+ st.title(f"🏦 Welcome, {st.session_state.current_user}!")
44
+
45
+ # Balance
46
+ st.subheader("πŸ’° Account Balance")
47
+ st.write(f"Current Balance: **{user_data['balance']} USD**")
48
+
49
+ # Deposit
50
+ deposit_amount = st.number_input("Enter amount to deposit", min_value=0.0)
51
+ if st.button("Deposit"):
52
+ user_data['balance'] += deposit_amount
53
+ user_data['transactions'].append((datetime.now(), f"Deposited {deposit_amount} USD"))
54
+ st.success("Deposit Successful!")
55
+
56
+ # Withdraw
57
+ withdraw_amount = st.number_input("Enter amount to withdraw", min_value=0.0)
58
+ if st.button("Withdraw"):
59
+ if withdraw_amount <= user_data['balance']:
60
+ user_data['balance'] -= withdraw_amount
61
+ user_data['transactions'].append((datetime.now(), f"Withdrew {withdraw_amount} USD"))
62
+ st.success("Withdrawal Successful!")
63
  else:
64
+ st.error("Insufficient Balance!")
65
+
66
+ # Transaction History
67
+ st.subheader("πŸ“œ Transaction History")
68
+ if user_data['transactions']:
69
+ for transaction in user_data['transactions']:
70
+ st.write(f"{transaction[0].strftime('%Y-%m-%d %H:%M:%S')}: {transaction[1]}")
71
+ else:
72
+ st.write("No transactions yet.")
73
+
74
+ # Logout
75
+ if st.button("πŸšͺ Logout"):
76
+ st.session_state.current_user = None
77
+ st.rerun()