Skip to content

Commit 5ddc3b7

Browse files
Merge pull request #1 from ananya26102006/ananya26102006-patch-1
Add Streamlit auth and welcome page for Jarvis
2 parents 486b2b1 + 85af5eb commit 5ddc3b7

File tree

1 file changed

+186
-0
lines changed

1 file changed

+186
-0
lines changed

python.py

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
"""
2+
Filename: jarvis_auth.py
3+
Title: Jarvis — Streamlit Auth & Welcome Page
4+
Description:
5+
Single-file Streamlit page for Jarvis that displays a personalized welcome,
6+
Google-based authentication buttons, user profile (picture, name, email),
7+
and handles login/logout flow. Uses IST time helper for timestamp formatting
8+
and safe UI flows. Place this file in your Streamlit app (e.g., at the app root
9+
or in the `pages/` folder) and run with `streamlit run jarvis_auth.py`.
10+
"""
11+
12+
from datetime import datetime
13+
from time import sleep
14+
15+
import pytz
16+
import streamlit as st
17+
18+
# Replace these imports with your project's actual utility functions.
19+
# If you don't have src/utils/greeting.py, either create it or inline equivalent functions.
20+
try:
21+
from src.utils.greeting import GetRandomWelcomeMessage, GreetUser
22+
except Exception:
23+
# Fallback implementations if src.utils.greeting is not available.
24+
import random
25+
26+
def GetRandomWelcomeMessage():
27+
msgs = [
28+
"Ready when you are — how can I help?",
29+
"Good to see you! What would you like to do today?",
30+
"Nice! I'm standing by for your command.",
31+
"Welcome back — let's be productive!",
32+
]
33+
return random.choice(msgs)
34+
35+
def GreetUser(name: str) -> str:
36+
if not name:
37+
return "Hello"
38+
# simple greeting based on hour
39+
try:
40+
hour = datetime.now().hour
41+
if hour < 12:
42+
prefix = "Good morning"
43+
elif hour < 18:
44+
prefix = "Good afternoon"
45+
else:
46+
prefix = "Good evening"
47+
return f"{prefix}, {name}"
48+
except Exception:
49+
return f"Hello, {name or 'there'}"
50+
51+
52+
def unix_to_ist(timestamp: float) -> str:
53+
"""
54+
Convert a UNIX timestamp (seconds) to a human-readable IST time string.
55+
56+
Args:
57+
timestamp: seconds since epoch (float or int).
58+
59+
Returns:
60+
Formatted string like "07:34:21 PM IST".
61+
"""
62+
india_tz = pytz.timezone("Asia/Kolkata")
63+
format_str = "%I:%M:%S %p IST"
64+
# Ensure timestamp is numeric
65+
try:
66+
return datetime.fromtimestamp(float(timestamp), pytz.utc).astimezone(india_tz).strftime(format_str)
67+
except Exception:
68+
return "--:--:-- IST"
69+
70+
71+
def auth():
72+
"""
73+
Streamlit UI for authentication + profile display.
74+
75+
Note: This relies on Streamlit's built-in `st.login()` / `st.logout()` behavior
76+
which may be provided by a community auth component or a Streamlit Enterprise feature.
77+
If your environment doesn't support `st.user`, replace the checks with your app's auth flow.
78+
"""
79+
# Defensive check: some Streamlit environments won't have st.user
80+
st.set_page_config(page_title="Jarvis — Welcome", layout="centered")
81+
82+
# Title block
83+
st.markdown("## ⚡ Jarvis — Virtual AI Assistant")
84+
st.write(
85+
"Jarvis simplifies your daily tasks using natural language automation, "
86+
"device control and personalized interactions. Sign in to access your profile."
87+
)
88+
st.write("---")
89+
90+
# If the environment has st.user object (Streamlit Cloud / Enterprise), use it.
91+
use_st_user = hasattr(st, "user")
92+
93+
if use_st_user:
94+
try:
95+
user_obj = st.user
96+
except Exception:
97+
user_obj = None
98+
else:
99+
user_obj = None
100+
101+
# If no st.user support, show a fallback sign-in button and explanatory text
102+
if not user_obj:
103+
# Fallback minimal UX
104+
st.warning(
105+
"This environment doesn't expose `st.user`. Use your app's auth or run on Streamlit Cloud/Enterprise "
106+
"to enable Google authentication features."
107+
)
108+
cols = st.columns([1, 1])
109+
with cols[0]:
110+
if st.button("🔓 Simulate Sign In (Demo)"):
111+
# In demo mode, create a lightweight fake user in session state
112+
st.session_state["_demo_user"] = {
113+
"name": "Demo User",
114+
"given_name": "Demo",
115+
"email": "[email protected]",
116+
"picture": "https://avatars.dicebear.com/api/identicon/demo.svg",
117+
"is_logged_in": True,
118+
}
119+
st.experimental_rerun()
120+
with cols[1]:
121+
if st.button("❌ Clear Demo User"):
122+
st.session_state.pop("_demo_user", None)
123+
st.experimental_rerun()
124+
125+
# If demo user exists, show profile using that
126+
demo = st.session_state.get("_demo_user")
127+
if demo and demo.get("is_logged_in"):
128+
st.success(GetRandomWelcomeMessage(), icon="🤝")
129+
st.image(demo.get("picture"), caption=demo.get("name"))
130+
st.write("Email:", demo.get("email"))
131+
if st.button("Log out (demo)"):
132+
st.toast(f"Goodbye, {demo.get('name')}! See you soon!", icon="🚪")
133+
sleep(1.5)
134+
st.session_state.pop("_demo_user", None)
135+
st.experimental_rerun()
136+
return
137+
138+
# If we have st.user available from the environment:
139+
try:
140+
# st.user typically has fields: is_logged_in, name, given_name, email, picture
141+
if hasattr(st.user, "is_logged_in") and not st.user.is_logged_in:
142+
st.title("🔐 Login Required")
143+
st.write("Please authenticate using your Google account to access your Jarvis profile.")
144+
if st.button("🔓 Authenticate with Google"):
145+
# st.login may be provided by Streamlit Enterprise / Cloud
146+
try:
147+
st.login("google")
148+
except Exception:
149+
st.error("Login is not available in this environment.")
150+
else:
151+
# Display user profile
152+
given_name = getattr(st.user, "given_name", None) or getattr(st.user, "name", "there")
153+
st.title(f"🙏 {GreetUser(given_name)}")
154+
st.success(GetRandomWelcomeMessage(), icon="🤝")
155+
156+
# Profile picture
157+
picture = getattr(st.user, "picture", None)
158+
if picture:
159+
st.image(picture, caption=getattr(st.user, "name", ""), width=160)
160+
else:
161+
st.info("No profile picture available.")
162+
163+
st.write("Email:", getattr(st.user, "email", "Not provided"))
164+
165+
# Example: show last login time if available
166+
last_login_ts = getattr(st.user, "last_login", None)
167+
if last_login_ts:
168+
try:
169+
readable = unix_to_ist(last_login_ts)
170+
st.write("Last login (IST):", readable)
171+
except Exception:
172+
pass
173+
174+
if st.button("Log out"):
175+
st.toast(f"Goodbye, {getattr(st.user, 'name', 'User')}! See you soon!", icon="🚪")
176+
sleep(1.2)
177+
try:
178+
st.logout()
179+
except Exception:
180+
st.info("Logout hook not available in this environment.")
181+
except Exception as e:
182+
st.error(f"An error occurred while accessing user data: {e}")
183+
184+
185+
if __name__ == "__main__":
186+
auth()

0 commit comments

Comments
 (0)