HFswapnil commited on
Commit
dca0165
ยท
verified ยท
1 Parent(s): d9dadfa

Rename src/streamlit_app.py to src/main.py

Browse files
Files changed (2) hide show
  1. src/main.py +202 -0
  2. src/streamlit_app.py +0 -40
src/main.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import sqlite3
4
+ import hashlib
5
+ from datetime import datetime
6
+ from localization_eval import evaluate_submission
7
+
8
+ # --- CONFIGURATION & SETUP ---
9
+ st.set_page_config(
10
+ page_title="AI Benchmark Arena",
11
+ page_icon="๐Ÿ†",
12
+ layout="wide",
13
+ initial_sidebar_state="expanded"
14
+ )
15
+
16
+ DB_NAME = "./benchmark.db"
17
+
18
+
19
+ def init_db():
20
+ conn = sqlite3.connect(DB_NAME)
21
+ c = conn.cursor()
22
+ # User Table
23
+ c.execute('''CREATE TABLE IF NOT EXISTS users
24
+ (username TEXT PRIMARY KEY, password TEXT)''')
25
+ # Submissions Table
26
+ c.execute('''CREATE TABLE IF NOT EXISTS submissions
27
+ (id INTEGER PRIMARY KEY AUTOINCREMENT,
28
+ username TEXT, score REAL, timestamp DATETIME)''')
29
+ conn.commit()
30
+ conn.close()
31
+
32
+ def make_hashes(password):
33
+ return hashlib.sha256(str.encode(password)).hexdigest()
34
+
35
+ def check_hashes(password, hashed_text):
36
+ if make_hashes(password) == hashed_text:
37
+ return hashed_text
38
+ return False
39
+
40
+ def add_user(username, password):
41
+ conn = sqlite3.connect(DB_NAME)
42
+ c = conn.cursor()
43
+ try:
44
+ c.execute('INSERT INTO users(username, password) VALUES (?,?)',
45
+ (username, make_hashes(password)))
46
+ conn.commit()
47
+ return True
48
+ except sqlite3.IntegrityError:
49
+ return False
50
+ finally:
51
+ conn.close()
52
+
53
+ def login_user(username, password):
54
+ conn = sqlite3.connect(DB_NAME)
55
+ c = conn.cursor()
56
+ c.execute('SELECT * FROM users WHERE username =? AND password = ?',
57
+ (username, make_hashes(password)))
58
+ data = c.fetchall()
59
+ conn.close()
60
+ return data
61
+
62
+ def save_submission(username, score):
63
+ conn = sqlite3.connect(DB_NAME)
64
+ c = conn.cursor()
65
+ c.execute('INSERT INTO submissions(username, score, timestamp) VALUES (?,?,?)',
66
+ (username, score, datetime.now()))
67
+ conn.commit()
68
+ conn.close()
69
+
70
+ def get_leaderboard_data():
71
+ conn = sqlite3.connect(DB_NAME)
72
+ # Get the BEST score for each user
73
+ query = """
74
+ SELECT username, MAX(score) as best_accuracy, MAX(timestamp) as last_submission
75
+ FROM submissions
76
+ GROUP BY username
77
+ ORDER BY best_accuracy DESC
78
+ """
79
+ df = pd.read_sql_query(query, conn)
80
+ conn.close()
81
+ return df
82
+
83
+ # --- User Interface ---
84
+
85
+ def ui_login_signup():
86
+ st.title("Welcome to Benchmark Arena ๐Ÿ†")
87
+
88
+ tab1, tab2 = st.tabs(["Login", "Sign Up"])
89
+
90
+ with tab1:
91
+ st.subheader("Sign In")
92
+ username = st.text_input("Username", key="login_user")
93
+ password = st.text_input("Password", type='password', key="login_pass")
94
+
95
+ if st.button("Login"):
96
+ if login_user(username, password):
97
+ st.session_state['logged_in'] = True
98
+ st.session_state['username'] = username
99
+ st.rerun()
100
+ else:
101
+ st.error("Username or Password incorrect")
102
+
103
+ with tab2:
104
+ st.subheader("Create New Account")
105
+ new_user = st.text_input("Username", key="new_user")
106
+ new_pass = st.text_input("Password", type='password', key="new_pass")
107
+
108
+ if st.button("Sign Up"):
109
+ if add_user(new_user, new_pass):
110
+ st.success("Account created! Please navigate to Login.")
111
+ else:
112
+ st.warning("Username already exists.")
113
+
114
+ def main_app():
115
+ # Sidebar Navigation
116
+ st.sidebar.title(f"Hi, {st.session_state['username']}!")
117
+ menu = ["Submit Model", "Leaderboard"]
118
+ choice = st.sidebar.radio("Navigation", menu)
119
+
120
+ st.sidebar.markdown("---")
121
+ if st.sidebar.button("Logout"):
122
+ st.session_state['logged_in'] = False
123
+ st.session_state['username'] = None
124
+ st.rerun()
125
+
126
+ # --- PAGE: SUBMIT MODEL ---
127
+ if choice == "Submit Model":
128
+ st.header("๐Ÿš€ Submit your Predictions")
129
+
130
+ col1, col2 = st.columns([2, 1])
131
+
132
+ with col1:
133
+ # st.info("Upload your CSV file. It must contain `id` and `prediction` columns.")
134
+ uploaded_file = st.file_uploader("Choose a CSV file", type="json")
135
+
136
+
137
+ if uploaded_file is not None:
138
+ save_path = f"./{uploaded_file.name}"
139
+
140
+ # Write the file to the current directory
141
+ with open(save_path, "wb") as f:
142
+ f.write(uploaded_file.getbuffer())
143
+
144
+ if st.button("Evaluate"):
145
+ with st.spinner('Calculating score against Ground Truth...'):
146
+ score = evaluate_submission("./biv_query.json", save_path)
147
+ st.success(f"Score : {score}")
148
+ if score is not None:
149
+ save_submission(st.session_state['username'], score)
150
+ st.balloons()
151
+ st.success("Submission Successful!")
152
+
153
+ # Display Metrics
154
+ st.metric(label="Your Model Accuracy Score", value=f"{score}%")
155
+
156
+ with col2:
157
+ st.markdown("### Sample Format")
158
+ st.dataframe(pd.DataFrame({'id': [1, 2], 'prediction': [100, 205]}), hide_index=True)
159
+
160
+ # --- PAGE: LEADERBOARD ---
161
+ elif choice == "Leaderboard":
162
+
163
+ st.header("๐Ÿ† Leaderboard")
164
+ st.write("Rankings based on the highest accuracy score achieved.")
165
+
166
+ df_leaderboard = get_leaderboard_data()
167
+
168
+ if not df_leaderboard.empty:
169
+ # styling the leaderboard
170
+ st.dataframe(
171
+ df_leaderboard,
172
+ column_config={
173
+ "username": "Participant",
174
+ "best_accuracy": st.column_config.ProgressColumn(
175
+ "Accuracy Score",
176
+ format="%.2f%%",
177
+ min_value=0,
178
+ max_value=100,
179
+ ),
180
+ "last_submission": st.column_config.DatetimeColumn(
181
+ "Last Active",
182
+ format="D MMM YYYY, h:mm a",
183
+ ),
184
+ },
185
+ use_container_width=True,
186
+ hide_index=True,
187
+ )
188
+ else:
189
+ st.info("No submissions yet. Be the first!")
190
+
191
+ if __name__ == '__main__':
192
+ init_db()
193
+
194
+ # Session State Initialization
195
+ if 'logged_in' not in st.session_state:
196
+ st.session_state['logged_in'] = False
197
+ st.session_state['username'] = None
198
+
199
+ if not st.session_state['logged_in']:
200
+ ui_login_signup()
201
+ else:
202
+ main_app()
src/streamlit_app.py DELETED
@@ -1,40 +0,0 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
- import streamlit as st
5
-
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))