Fredrik Sitje commited on
Commit
abc33c8
·
1 Parent(s): 940dbe5

Initialize the spaces.

Browse files
README.md CHANGED
@@ -8,7 +8,7 @@ app_port: 8501
8
  tags:
9
  - streamlit
10
  pinned: false
11
- short_description: This spaces is used to annotate/grade answers.
12
  ---
13
 
14
  # Welcome to Streamlit!
 
8
  tags:
9
  - streamlit
10
  pinned: false
11
+ short_description: A space for grading generated answers
12
  ---
13
 
14
  # Welcome to Streamlit!
requirements.txt CHANGED
@@ -1,3 +1,5 @@
1
- altair
2
  pandas
3
- streamlit
 
 
 
1
+ streamlit
2
  pandas
3
+ pyarrow
4
+ huggingface-hub
5
+ datasets
src/grading_template.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21b094fa1c104c990de260611e55e7ae8914ea35cc6048049198056e0b7057a8
3
+ size 186660
src/streamlit_app.py CHANGED
@@ -1,40 +1,1034 @@
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
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import os
4
+ import hashlib
5
+ import json
6
+ import tempfile
7
+ from huggingface_hub import HfApi, login, hf_hub_download
8
+
9
+ # Hugging Face Dataset configuration
10
+ # In HF Spaces, variables and secrets are available as environment variables
11
+ # For local development, we can also check st.secrets as a fallback
12
+ HF_DATASET_REPO = os.getenv("HF_DATASET_REPO")
13
+ HF_TOKEN = os.getenv("HF_TOKEN")
14
+
15
+ # Fallback to st.secrets for local development (if not found in environment)
16
+ if not HF_DATASET_REPO:
17
+ try:
18
+ HF_DATASET_REPO = st.secrets.get("HF_DATASET_REPO", "TransLegal/en-us-grading-answers")
19
+ except Exception:
20
+ HF_DATASET_REPO = "TransLegal/en-us-grading-answers"
21
+
22
+ if not HF_TOKEN:
23
+ try:
24
+ HF_TOKEN = st.secrets.get("HF_TOKEN", None)
25
+ except Exception:
26
+ HF_TOKEN = None
27
+
28
+ # Require HF_TOKEN - fail fast if not configured
29
+ if not HF_TOKEN:
30
+ st.error("❌ **Configuration Error**: HF_TOKEN is not set. Please configure it in Hugging Face Spaces settings (Variables and secrets).")
31
+ st.stop()
32
+
33
+ # Initialize HF API - raise exception if initialization fails
34
+ try:
35
+ login(token=HF_TOKEN)
36
+ hf_api = HfApi(token=HF_TOKEN)
37
+ except Exception as e:
38
+ st.error(f"❌ **Error initializing Hugging Face API**: {str(e)}")
39
+ st.stop()
40
+
41
+ @st.cache_data
42
+ def load_grading_template():
43
+ """Load grading template from Hugging Face Dataset"""
44
+ try:
45
+ file_path = hf_hub_download(
46
+ repo_id=HF_DATASET_REPO,
47
+ filename="grading_template.parquet",
48
+ repo_type="dataset",
49
+ token=HF_TOKEN
50
+ )
51
+ return pd.read_parquet(file_path)
52
+ except Exception as e:
53
+ st.error(f"❌ **Error loading grading template from Hugging Face Dataset**: {str(e)}")
54
+ st.error(f"Please ensure the file `grading_template.parquet` exists in the dataset repository: {HF_DATASET_REPO}")
55
+ st.stop()
56
+
57
+ # Load data from the grading template
58
+ df = load_grading_template()
59
+
60
+ # Assessment options with descriptive labels
61
+ ASSESSMENT_OPTIONS = [
62
+ "Perfect",
63
+ "Mostly correct",
64
+ "Noticeably flawed",
65
+ "Seriously wrong",
66
+ "Irrelevant / NA"
67
+ ]
68
+
69
+ # Map assessment options to scores
70
+ ASSESSMENT_TO_SCORE = {
71
+ "Perfect": "3",
72
+ "Mostly correct": "2",
73
+ "Noticeably flawed": "1",
74
+ "Seriously wrong": "0",
75
+ "Irrelevant / NA": "NA"
76
+ }
77
+
78
+ def format_snake_case(text):
79
+ """Convert snake_case to Title Case"""
80
+ return ' '.join(word.capitalize() for word in text.split('_'))
81
+
82
+ def hash_password(password):
83
+ """Hash a password using SHA256"""
84
+ return hashlib.sha256(password.encode()).hexdigest()
85
+
86
+ def load_users():
87
+ """Load user credentials from Hugging Face Dataset"""
88
+ try:
89
+ file_path = hf_hub_download(
90
+ repo_id=HF_DATASET_REPO,
91
+ filename="users/users.json",
92
+ repo_type="dataset",
93
+ token=HF_TOKEN
94
+ )
95
+ with open(file_path, 'r') as f:
96
+ return json.load(f)
97
+ except Exception:
98
+ # File doesn't exist yet (first run), return empty dict
99
+ return {}
100
+
101
+ def save_users(users):
102
+ """Save user credentials to Hugging Face Dataset"""
103
+ try:
104
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
105
+ json.dump(users, f, indent=2)
106
+ temp_path = f.name
107
+
108
+ hf_api.upload_file(
109
+ path_or_fileobj=temp_path,
110
+ path_in_repo="users/users.json",
111
+ repo_id=HF_DATASET_REPO,
112
+ repo_type="dataset",
113
+ token=HF_TOKEN
114
+ )
115
+ os.unlink(temp_path)
116
+ return True
117
+ except Exception as e:
118
+ st.error(f"❌ **Error saving users to Hugging Face Dataset**: {str(e)}")
119
+ raise
120
+
121
+ def load_user_data(username):
122
+ """Load user's answer data from Hugging Face Dataset"""
123
+ try:
124
+ file_path = hf_hub_download(
125
+ repo_id=HF_DATASET_REPO,
126
+ filename=f"users/{username}_answers.parquet",
127
+ repo_type="dataset",
128
+ token=HF_TOKEN
129
+ )
130
+ return pd.read_parquet(file_path)
131
+ except Exception:
132
+ # File doesn't exist yet (new user), create new dataframe
133
+ user_df = df.copy()
134
+ user_df['legal_accuracy_score'] = None
135
+ user_df['time_stamp'] = None
136
+ return user_df
137
+
138
+ def save_user_data(username, user_df, commit_message=None):
139
+ """Save user's answer data to Hugging Face Dataset"""
140
+ try:
141
+ with tempfile.NamedTemporaryFile(suffix='.parquet', delete=False) as f:
142
+ user_df.to_parquet(f.name, index=False)
143
+ temp_path = f.name
144
+
145
+ upload_kwargs = {
146
+ 'path_or_fileobj': temp_path,
147
+ 'path_in_repo': f"users/{username}_answers.parquet",
148
+ 'repo_id': HF_DATASET_REPO,
149
+ 'repo_type': "dataset",
150
+ 'token': HF_TOKEN
151
+ }
152
+
153
+ # Add commit_message if provided
154
+ if commit_message:
155
+ upload_kwargs['commit_message'] = commit_message
156
+
157
+ hf_api.upload_file(**upload_kwargs)
158
+ os.unlink(temp_path)
159
+ return True
160
+ except Exception as e:
161
+ st.error(f"❌ **Error saving user data to Hugging Face Dataset**: {str(e)}")
162
+ raise
163
+
164
+ def update_user_answer(username, term, category, subcategory, question, answer, score):
165
+ """Update a specific answer in the user's data (deprecated - use update_category_answers for bulk updates)"""
166
+ try:
167
+ user_df = load_user_data(username)
168
+
169
+ # Find the matching row
170
+ mask = (
171
+ (user_df['term'] == term) &
172
+ (user_df['category'] == category) &
173
+ (user_df['subcategory'] == subcategory) &
174
+ (user_df['question'] == question) &
175
+ (user_df['answer'] == answer)
176
+ )
177
+
178
+ if mask.any():
179
+ user_df.loc[mask, 'legal_accuracy_score'] = score
180
+ save_user_data(username, user_df)
181
+ return True
182
+ else:
183
+ print(f"Warning: Could not find matching row for: {term}, {category}, {subcategory}, {question}")
184
+ return False
185
+ except Exception as e:
186
+ print(f"Error updating answer: {str(e)}")
187
+ return False
188
+
189
+ def auto_score_unknown_answers(username, term, category, df):
190
+ """
191
+ Automatically score all Unknown answers for a category.
192
+ Returns list of (subcategory, question, answer, score) tuples.
193
+
194
+ Args:
195
+ username: User identifier
196
+ term: Term name
197
+ category: Category name
198
+ df: Base dataframe with all questions/answers
199
+
200
+ Returns:
201
+ List of tuples (subcategory, question, answer, score) for Unknown answers
202
+ """
203
+ # Find all Unknown answers for this term-category pair (both "Unknown." and "Unknown")
204
+ unknown_rows = df[(df['term'] == term) &
205
+ (df['category'] == category) &
206
+ ((df['answer'] == "Unknown.") | (df['answer'] == "Unknown"))]
207
+
208
+ # Return list of tuples for bulk update (score is "NA" for Irrelevant / NA)
209
+ return [(row['subcategory'], row['question'], row['answer'], "NA")
210
+ for _, row in unknown_rows.iterrows()]
211
+
212
+ def auto_score_all_unknown_answers_for_new_user(username):
213
+ """
214
+ Automatically score all Unknown answers for all categories when a new user is created.
215
+ This runs in the background during account creation.
216
+ """
217
+ try:
218
+ # Get all unique term-category pairs
219
+ term_category_pairs = df[['term', 'category']].drop_duplicates().sort_values(['term', 'category']).values.tolist()
220
+
221
+ # Process each category and save Unknown answers
222
+ for term, category in term_category_pairs:
223
+ unknown_answers = auto_score_unknown_answers(username, term, category, df)
224
+ if unknown_answers:
225
+ # Save Unknown answers for this category
226
+ commit_message = f"Auto-score Unknown answers for {username} - {term} - {category}"
227
+ update_category_answers(username, term, category, unknown_answers, commit_message=commit_message)
228
+
229
+ return True
230
+ except Exception as e:
231
+ print(f"Error auto-scoring Unknown answers for new user {username}: {str(e)}")
232
+ return False
233
+
234
+ def update_category_answers(username, term, category, answers_list, commit_message=None):
235
+ """
236
+ Update all answers for a category in a single commit.
237
+
238
+ Args:
239
+ username: User identifier
240
+ term: Term name
241
+ category: Category name
242
+ answers_list: List of tuples (subcategory, question, answer, score)
243
+ commit_message: Optional commit message (auto-generated if None)
244
+
245
+ Returns:
246
+ True if successful, False otherwise
247
+ """
248
+ try:
249
+ # Load user dataframe once
250
+ user_df = load_user_data(username)
251
+
252
+ # Get current timestamp once for all updates in this category
253
+ current_timestamp = pd.Timestamp.now()
254
+
255
+ # Update all rows in memory
256
+ updated_count = 0
257
+ for subcategory, question, answer, score in answers_list:
258
+ # Find the matching row
259
+ mask = (
260
+ (user_df['term'] == term) &
261
+ (user_df['category'] == category) &
262
+ (user_df['subcategory'] == subcategory) &
263
+ (user_df['question'] == question) &
264
+ (user_df['answer'] == answer)
265
+ )
266
+
267
+ if mask.any():
268
+ user_df.loc[mask, 'legal_accuracy_score'] = score
269
+ user_df.loc[mask, 'time_stamp'] = current_timestamp
270
+ updated_count += 1
271
+ else:
272
+ print(f"Warning: Could not find matching row for: {term}, {category}, {subcategory}, {question}")
273
+
274
+ if updated_count == 0:
275
+ print(f"Warning: No rows were updated for {username} - {term} - {category}")
276
+ return False
277
+
278
+ # Generate commit message if not provided
279
+ if commit_message is None:
280
+ commit_message = f"Update answers for {username} - {term} - {category}"
281
+
282
+ # Save once with commit message
283
+ save_user_data(username, user_df, commit_message=commit_message)
284
+ return True
285
+ except Exception as e:
286
+ print(f"Error updating category answers: {str(e)}")
287
+ return False
288
+
289
+ def get_user_answer(username, term, category, subcategory, question, answer):
290
+ """Get user's answer for a specific question"""
291
+ user_df = load_user_data(username)
292
+
293
+ mask = (
294
+ (user_df['term'] == term) &
295
+ (user_df['category'] == category) &
296
+ (user_df['subcategory'] == subcategory) &
297
+ (user_df['question'] == question) &
298
+ (user_df['answer'] == answer)
299
+ )
300
+
301
+ if mask.any():
302
+ score = user_df.loc[mask, 'legal_accuracy_score'].iloc[0]
303
+ if pd.notna(score):
304
+ return score
305
+ return None
306
+
307
+ def find_first_unanswered_category(username):
308
+ """Find the first category that hasn't been fully answered"""
309
+ user_df = load_user_data(username)
310
+
311
+ # Use the global term_category_pairs to ensure consistent ordering
312
+ # This matches the order used in the main application
313
+
314
+ for idx, (term, category) in enumerate(term_category_pairs):
315
+ # Get all subcategories for this term-category pair from base df
316
+ category_data = df[(df['term'] == term) & (df['category'] == category)]
317
+
318
+ # Check if all questions in this category are answered
319
+ all_answered = True
320
+ for _, row in category_data.iterrows():
321
+ # Check directly in user_df instead of calling get_user_answer (which reloads data)
322
+ mask = (
323
+ (user_df['term'] == row['term']) &
324
+ (user_df['category'] == row['category']) &
325
+ (user_df['subcategory'] == row['subcategory']) &
326
+ (user_df['question'] == row['question']) &
327
+ (user_df['answer'] == row['answer'])
328
+ )
329
+
330
+ if mask.any():
331
+ score = user_df.loc[mask, 'legal_accuracy_score'].iloc[0]
332
+ if pd.isna(score):
333
+ all_answered = False
334
+ break
335
+ else:
336
+ # No matching row found - question not answered
337
+ all_answered = False
338
+ break
339
+
340
+ if not all_answered:
341
+ return idx
342
+
343
+ return len(term_category_pairs) # All answered, return last index
344
+
345
+ def restore_submitted_status(username):
346
+ """Restore submitted status for categories that have all answers in parquet file"""
347
+ user_df = load_user_data(username)
348
+
349
+ # Use the global term_category_pairs to ensure consistent ordering
350
+ submitted_pairs = set()
351
+ for idx, (term, category) in enumerate(term_category_pairs):
352
+ pair_key = f"{term}_{category}_{idx}"
353
+
354
+ # Get all subcategories for this term-category pair
355
+ category_data = df[(df['term'] == term) & (df['category'] == category)]
356
+
357
+ # Check if all questions in this category are answered
358
+ all_answered = True
359
+ for _, row in category_data.iterrows():
360
+ # Check directly in user_df instead of calling get_user_answer (which reloads data)
361
+ mask = (
362
+ (user_df['term'] == row['term']) &
363
+ (user_df['category'] == row['category']) &
364
+ (user_df['subcategory'] == row['subcategory']) &
365
+ (user_df['question'] == row['question']) &
366
+ (user_df['answer'] == row['answer'])
367
+ )
368
+
369
+ if mask.any():
370
+ score = user_df.loc[mask, 'legal_accuracy_score'].iloc[0]
371
+ if pd.isna(score):
372
+ all_answered = False
373
+ break
374
+ else:
375
+ # No matching row found - question not answered
376
+ all_answered = False
377
+ break
378
+
379
+ if all_answered:
380
+ submitted_pairs.add(pair_key)
381
+
382
+ return submitted_pairs
383
+
384
+ class Subcategory:
385
+ """Represents a single subcategory with its question, answer, and radio button"""
386
+
387
+ def __init__(self, term, category, subcategory_name, df):
388
+ self.term = term
389
+ self.category = category
390
+ self.subcategory_name = subcategory_name
391
+ self.formatted_name = format_snake_case(subcategory_name)
392
+
393
+ # Get question and answer
394
+ result = df[(df['term'] == term) &
395
+ (df['category'] == category) &
396
+ (df['subcategory'] == subcategory_name)]
397
+ if len(result) > 0:
398
+ self.question = result.iloc[0]['question']
399
+ self.answer = result.iloc[0]['answer']
400
+ else:
401
+ self.question = None
402
+ self.answer = None
403
+
404
+
405
+ class Category:
406
+ """Represents a category with its subcategories"""
407
+
408
+ def __init__(self, term, category_name, df):
409
+ self.term = term
410
+ self.category_name = category_name
411
+ self.formatted_name = format_snake_case(category_name)
412
+
413
+ # Filter out subcategories where answer is "Unknown." or "Unknown"
414
+ filtered_df = df[(df['term'] == term) &
415
+ (df['category'] == category_name) &
416
+ (df['answer'] != "Unknown.") &
417
+ (df['answer'] != "Unknown")]
418
+
419
+ # Get all subcategories for this term-category pair (excluding Unknown answers)
420
+ subcategory_names = filtered_df['subcategory'].unique()
421
+ subcategory_names = sorted(subcategory_names.tolist())
422
+
423
+ # Create Subcategory instances (only for non-Unknown answers)
424
+ self.subcategories = [
425
+ Subcategory(term, category_name, subcat_name, df)
426
+ for subcat_name in subcategory_names
427
+ ]
428
+
429
+
430
+ class Term:
431
+ """Represents a term with its categories"""
432
+
433
+ def __init__(self, term_name, df):
434
+ self.term_name = term_name
435
+ self.formatted_name = format_snake_case(term_name)
436
+
437
+ # Get all categories for this term
438
+ category_names = df[df['term'] == term_name]['category'].unique()
439
+ category_names = sorted(category_names.tolist())
440
+
441
+ # Create Category instances
442
+ self.categories = [
443
+ Category(term_name, cat_name, df)
444
+ for cat_name in category_names
445
+ ]
446
+
447
+ def get_category_by_name(self, category_name):
448
+ """Get a category by its name"""
449
+ for cat in self.categories:
450
+ if cat.category_name == category_name:
451
+ return cat
452
+ return None
453
+
454
+
455
+ # Create a list of unique (term, category) pairs for navigation
456
+ term_category_pairs = df[['term', 'category']].drop_duplicates().sort_values(['term', 'category']).values.tolist()
457
+ total_pairs = len(term_category_pairs)
458
+
459
+ # Cache for Term instances
460
+ term_cache = {}
461
+
462
+ def get_term_instance(term_name):
463
+ """Get or create a Term instance"""
464
+ if term_name not in term_cache:
465
+ term_cache[term_name] = Term(term_name, df)
466
+ return term_cache[term_name]
467
+
468
+ def get_category_for_pair(term_name, category_name):
469
+ """Get Category instance for a term-category pair"""
470
+ term = get_term_instance(term_name)
471
+ return term.get_category_by_name(category_name)
472
+
473
+ # Initialize session state
474
+ if 'logged_in' not in st.session_state:
475
+ st.session_state.logged_in = False
476
+ if 'username' not in st.session_state:
477
+ st.session_state.username = None
478
+ if 'current_index' not in st.session_state:
479
+ st.session_state.current_index = 0
480
+ if 'show_term_complete' not in st.session_state:
481
+ st.session_state.show_term_complete = False
482
+ if 'completed_term' not in st.session_state:
483
+ st.session_state.completed_term = None
484
+ if 'next_term' not in st.session_state:
485
+ st.session_state.next_term = None
486
+ if 'show_term_back_warning' not in st.session_state:
487
+ st.session_state.show_term_back_warning = False
488
+ if 'back_current_term' not in st.session_state:
489
+ st.session_state.back_current_term = None
490
+ if 'back_previous_term' not in st.session_state:
491
+ st.session_state.back_previous_term = None
492
+ if 'back_current_index' not in st.session_state:
493
+ st.session_state.back_current_index = None
494
+ if 'show_guide' not in st.session_state:
495
+ st.session_state.show_guide = True
496
+ if 'submitted_pairs' not in st.session_state:
497
+ st.session_state.submitted_pairs = set() # Track which pairs have been submitted
498
+ if 'original_selections' not in st.session_state:
499
+ st.session_state.original_selections = {} # Store original selections for each pair
500
+ if 'has_unsaved_changes' not in st.session_state:
501
+ st.session_state.has_unsaved_changes = {} # Track unsaved changes per pair
502
+
503
+ # Login page
504
+ if not st.session_state.logged_in:
505
+ st.markdown("# Login")
506
+ st.markdown("Please enter your username and password to continue.")
507
+
508
+ username = st.text_input("Username")
509
+ password = st.text_input("Password", type="password")
510
+
511
+ col1, col2 = st.columns(2)
512
+ with col1:
513
+ if st.button("Login", type="primary", use_container_width=True):
514
+ users = load_users()
515
+
516
+ if username in users:
517
+ # Existing user - check password
518
+ if users[username]['password'] == hash_password(password):
519
+ st.session_state.logged_in = True
520
+ st.session_state.username = username
521
+ # Restore submitted status for previously submitted categories
522
+ st.session_state.submitted_pairs = restore_submitted_status(username)
523
+ # Find first unanswered category and resume there
524
+ resume_index = find_first_unanswered_category(username)
525
+ st.session_state.current_index = resume_index
526
+ st.rerun()
527
+ else:
528
+ st.error("Incorrect password")
529
+ else:
530
+ # Username not found - require registration
531
+ st.error("Username not found. Please register first using the 'Register New User' button.")
532
+
533
+ with col2:
534
+ if st.button("Register New User", use_container_width=True):
535
+ users = load_users()
536
+ if username in users:
537
+ st.error("Username already exists")
538
+ elif username and password:
539
+ users[username] = {'password': hash_password(password)}
540
+ save_users(users)
541
+ # Auto-score all Unknown answers for the new user in the background
542
+ auto_score_all_unknown_answers_for_new_user(username)
543
+ st.success("User registered successfully! Please click Login.")
544
+ else:
545
+ st.error("Please enter both username and password")
546
 
547
+ # Main application (only shown if logged in)
548
+ elif st.session_state.logged_in:
549
+ username = st.session_state.username
550
+ current_index = st.session_state.current_index
551
+
552
+ # Debug info (can be removed in production)
553
+ with st.sidebar:
554
+ with st.expander("Debug Info"):
555
+ st.write(f"HF Dataset Repo: `{HF_DATASET_REPO}`")
556
+ st.write(f"HF Token configured: {HF_TOKEN is not None}")
557
+ st.write(f"HF API initialized: {hf_api is not None}")
558
+ if username:
559
+ st.write(f"User parquet file: `users/{username}_answers.parquet`")
560
+ st.write(f"Users file: `users/users.json`")
561
+
562
+ # Check if we should show the annotation guide first
563
+ if st.session_state.show_guide:
564
+ # Annotation Guide Page
565
+ st.markdown("# Welcome!")
566
+ st.markdown("")
567
+ st.markdown("## Task Overview")
568
+ st.markdown("""
569
+ You are a legal expert tasked with evaluating AI-generated structured answers to 55 specific legal questions from court opinions.
570
+ Your task is to assess the legal accuracy for each question and ensure they meet the high standards required for legal education.
571
+
572
+ For each question, you will be presented with:
573
+ - **The legal question** that was asked
574
+ - **The AI-generated answer** that needs to be evaluated
575
+
576
+ Your role is to critically evaluate whether the answer is legally accurate based on your knowledge of the law. Consider:
577
+ - Does the answer correctly state the legal principle or rule?
578
+ - Are there any factual inaccuracies or misstatements of law?
579
+ - Is the answer complete and does it address the question properly?
580
+ - Would this answer be acceptable for use in legal education?
581
+ """)
582
+ st.markdown("")
583
+ st.markdown("## Grading Criteria")
584
+ st.markdown("""
585
+ Based on your general knowledge of the law, consider how legally accurate the answer is and grade it as follows:
586
+
587
+ - **Perfect** - Only when truly flawless. The answer is legally accurate, well-stated, and appropriate for legal education. It correctly explains the legal principle, rule, or concept without any discernible errors or misleading statements.
588
+
589
+ - **Mostly correct** - One very small issue or slightly awkward phrasing. The answer is generally accurate but contains minor inaccuracies, imprecise language, or could be more precise. The core legal content is correct, but there are small issues that could be improved for educational purposes.
590
+
591
+ - **Noticeably flawed** - Clear error but main idea still ok. The answer contains significant errors that substantially affect its accuracy. While not completely wrong, there are important mistakes in legal reasoning, application of law, or factual statements that would confuse or mislead students.
592
+
593
+ - **Seriously wrong** - Hallucination, wrong format, meaningless, etc. The answer contains fundamental legal errors that completely misrepresent the law, legal principle, or legal concept. The answer would mislead a student and is factually wrong at its core.
594
+
595
+ - **Irrelevant / NA** - The answer explicitly indicates that the information is unknown, unavailable, or not relevant to the question. This is appropriate when the AI correctly identifies that it cannot provide an answer.
596
+ """)
597
+ st.markdown("")
598
+ st.markdown("## Examples")
599
+ st.markdown("""
600
+ ### Example 1: Contract Formation
601
+
602
+ **Question:** What is required for a valid contract to be formed?
603
+
604
+ **AI Answer:** "A valid contract requires an offer, acceptance, consideration, and mutual assent between the parties. The parties must have the legal capacity to contract, and the subject matter must be legal."
605
+
606
+ **Evaluation:** This answer is **Perfect**. It correctly identifies the essential elements of contract formation (offer, acceptance, consideration) and mentions additional important requirements (capacity, legality). The answer is comprehensive and legally accurate.
607
+
608
+ ---
609
+
610
+ **AI Answer (Alternative):** "A contract is formed when two people agree to something and shake hands on it."
611
+
612
+ **Evaluation:** This answer would be **Seriously wrong**. While it mentions agreement, it completely misrepresents contract law by suggesting that a handshake alone is sufficient. It omits essential elements like consideration and fails to explain the legal requirements properly.
613
+
614
+ ### Example 2: Due Process Rights
615
+
616
+ **Question:** What procedural protections are required under the Due Process Clause of the Fourteenth Amendment?
617
+
618
+ **AI Answer:** "The Due Process Clause requires that individuals receive notice of proceedings against them and an opportunity to be heard. This includes the right to present evidence, cross-examine witnesses, and have a neutral decision-maker. The specific procedures required depend on the nature of the interest at stake and the context of the deprivation."
619
+
620
+ **Evaluation:** This answer is **Perfect**. It correctly identifies the core elements of procedural due process (notice and opportunity to be heard) and mentions the balancing test that courts apply. The answer is legally sound.
621
+
622
+ ---
623
+
624
+ **AI Answer (Alternative):** "Due process means you get a fair trial with a lawyer, a jury, and the right to remain silent, just like in criminal cases."
625
+
626
+ **Evaluation:** This answer would be **Noticeably flawed**. While it mentions some procedural protections, it incorrectly conflates criminal procedure rights (jury trial, right to remain silent) with the broader concept of due process, which applies to civil proceedings as well. The answer oversimplifies and contains significant inaccuracies about when these specific rights apply.
627
+ """)
628
+ st.markdown("")
629
+ st.markdown("### You've got this! Your expertise is invaluable for improving legal education.")
630
+ st.markdown("") # Spacing
631
+ col1, col2, col3 = st.columns([1, 1, 1])
632
+ with col2:
633
+ if st.button("Start Assessment", type="primary", use_container_width=True):
634
+ st.session_state.show_guide = False
635
+ st.rerun()
636
+
637
+ # Check if we should show the back warning page (moving to different term)
638
+ elif st.session_state.show_term_back_warning:
639
+ # Show warning page when going back to a different term
640
+ st.markdown(
641
+ f"""
642
+ <div style='text-align: center; font-size: 1.2em;'>
643
+ <p>You are leaving the current term</p>
644
+ <p><strong>{st.session_state.back_current_term}</strong></p>
645
+ <br>
646
+ <p>and going back to questions about the term</p>
647
+ <p><strong>{st.session_state.back_previous_term}</strong></p>
648
+ </div>
649
+ """,
650
+ unsafe_allow_html=True
651
+ )
652
+ st.markdown("") # Spacing
653
+ col1, col2, col3 = st.columns([1, 1, 1])
654
+ with col1:
655
+ if st.button("Continue to Previous Term", type="primary", use_container_width=True):
656
+ # Move to the previous term-category pair
657
+ st.session_state.current_index -= 1
658
+ st.session_state.show_term_back_warning = False
659
+ st.session_state.back_current_term = None
660
+ st.session_state.back_previous_term = None
661
+ st.session_state.back_current_index = None
662
+ st.rerun()
663
+ with col3:
664
+ if st.button(f"Stay on {st.session_state.back_current_term}", use_container_width=True):
665
+ # Cancel navigation - stay on current term
666
+ st.session_state.current_index = st.session_state.back_current_index
667
+ st.session_state.show_term_back_warning = False
668
+ st.session_state.back_current_term = None
669
+ st.session_state.back_previous_term = None
670
+ st.session_state.back_current_index = None
671
+ st.rerun()
672
+
673
+ # Check if we should show the term completion page (moving forward to different term)
674
+ elif st.session_state.show_term_complete:
675
+ # Show intermediate page between terms - centered with terms on new lines and bold
676
+ st.markdown(
677
+ f"""
678
+ <div style='text-align: center; font-size: 1.2em;'>
679
+ <p>You finished the assessment for all questions for the term</p>
680
+ <p><strong>{st.session_state.completed_term}</strong></p>
681
+ <br>
682
+ <p>The next term to be assessed is</p>
683
+ <p><strong>{st.session_state.next_term}</strong></p>
684
+ </div>
685
+ """,
686
+ unsafe_allow_html=True
687
+ )
688
+ st.markdown("") # Spacing
689
+ col1, col2, col3 = st.columns([1, 1, 1])
690
+ with col2:
691
+ if st.button("Continue to Next Term", type="primary", use_container_width=True):
692
+ # Move to the next term-category pair
693
+ st.session_state.current_index += 1
694
+ st.session_state.show_term_complete = False
695
+ st.session_state.completed_term = None
696
+ st.session_state.next_term = None
697
+ st.rerun()
698
+
699
+ elif current_index < total_pairs:
700
+ term_name, category_name = term_category_pairs[current_index]
701
+ category = get_category_for_pair(term_name, category_name)
702
+ term = get_term_instance(term_name)
703
+
704
+ # Display header
705
+ st.markdown(f"# Term: {term.formatted_name}")
706
+ st.markdown(f"## Category: {category.formatted_name}")
707
+
708
+ # Display all subcategories with their questions, answers, and radio buttons
709
+ pair_key = f"{term_name}_{category_name}_{current_index}"
710
+ is_submitted = pair_key in st.session_state.submitted_pairs
711
+
712
+ # Don't pre-load values into session_state - let the radio buttons manage their own state
713
+ # This prevents the warning about default value vs Session State API conflict
714
+
715
+ # Check if category is fully answered in parquet file
716
+ # This includes both visible subcategories and Unknown answers (which are auto-scored)
717
+ category_fully_answered = True
718
+
719
+ # Check visible subcategories
720
+ for i, subcat in enumerate(category.subcategories):
721
+ saved_score = get_user_answer(username, term_name, category_name, subcat.subcategory_name,
722
+ subcat.question, subcat.answer)
723
+ if saved_score is None:
724
+ category_fully_answered = False
725
+ break
726
+
727
+ # Also check Unknown answers (they should be auto-scored as "NA")
728
+ if category_fully_answered:
729
+ unknown_answers = auto_score_unknown_answers(username, term_name, category_name, df)
730
+ for subcategory, question, answer, score in unknown_answers:
731
+ saved_score = get_user_answer(username, term_name, category_name, subcategory, question, answer)
732
+ if saved_score is None:
733
+ category_fully_answered = False
734
+ break
735
+
736
+ # Update is_submitted based on parquet file check
737
+ if category_fully_answered and not is_submitted:
738
+ # Category is fully answered in parquet but not marked as submitted in session
739
+ # Mark it as submitted for UI purposes (to show Update button)
740
+ is_submitted = True
741
+ st.session_state.submitted_pairs.add(pair_key)
742
+
743
+ # Load original selections if this pair has been submitted
744
+ if is_submitted:
745
+ if pair_key not in st.session_state.original_selections:
746
+ st.session_state.original_selections[pair_key] = {}
747
+ for i, subcat in enumerate(category.subcategories):
748
+ radio_key = f"{pair_key}_subcat_{i}"
749
+ # Get from session_state (which was just set above) or from saved data
750
+ if radio_key in st.session_state:
751
+ st.session_state.original_selections[pair_key][radio_key] = st.session_state[radio_key]
752
+ else:
753
+ saved_score = get_user_answer(username, term_name, category_name, subcat.subcategory_name,
754
+ subcat.question, subcat.answer)
755
+ if saved_score is not None:
756
+ score_to_option = {v: k for k, v in ASSESSMENT_TO_SCORE.items()}
757
+ if saved_score in score_to_option:
758
+ st.session_state.original_selections[pair_key][radio_key] = score_to_option[saved_score]
759
+
760
+ all_selected = True
761
+ changed_count = 0
762
+ changes_info = [] # Store info about changes for display
763
+ selected_values = {} # Store all selected values for validation
764
+
765
+ for i, subcat in enumerate(category.subcategories):
766
+ st.markdown(f"**Subcategory: {subcat.formatted_name}**")
767
+
768
+ # Display question and answer in a styled box
769
+ st.markdown(
770
+ f"""
771
+ <div style='border: 2px solid #ccc; padding: 15px; margin: 10px 0; border-radius: 5px; background-color: #f9f9f9; color: #000;'>
772
+ <strong style='color: #000;'>Question:</strong> <span style='color: #000;'>{subcat.question}</span><br><br>
773
+ <strong style='color: #000;'>Answer:</strong> <span style='color: #000;'>{subcat.answer}</span>
774
+ </div>
775
+ """,
776
+ unsafe_allow_html=True
777
+ )
778
+
779
+ # Selectbox for this subcategory
780
+ radio_key = f"{pair_key}_subcat_{i}"
781
+
782
+ # Get original value for change detection
783
+ original_value = None
784
+ if is_submitted and pair_key in st.session_state.original_selections:
785
+ original_value = st.session_state.original_selections[pair_key].get(radio_key)
786
+
787
+ # Get saved value to determine if we should set a default index
788
+ # Don't pre-set session_state - only use index parameter to avoid conflicts
789
+ saved_score = get_user_answer(username, term_name, category_name, subcat.subcategory_name,
790
+ subcat.question, subcat.answer)
791
+ default_index = None
792
+
793
+ # Check if there's a saved value in parquet file
794
+ if saved_score is not None:
795
+ score_to_option = {v: k for k, v in ASSESSMENT_TO_SCORE.items()}
796
+ if saved_score in score_to_option:
797
+ saved_option = score_to_option[saved_score]
798
+ if saved_option in ASSESSMENT_OPTIONS:
799
+ default_index = ASSESSMENT_OPTIONS.index(saved_option)
800
+ # If no saved value but value exists in session_state (from user interaction), use it
801
+ elif radio_key in st.session_state:
802
+ current_value = st.session_state[radio_key]
803
+ if current_value in ASSESSMENT_OPTIONS:
804
+ default_index = ASSESSMENT_OPTIONS.index(current_value)
805
+
806
+ # Use radio buttons with index=None when no saved value to prevent default selection
807
+ # This prevents the warning about default value vs Session State API
808
+ if default_index is not None:
809
+ # Has saved value - set index to that value
810
+ selected_value = st.radio(
811
+ "Your Assessment:",
812
+ options=ASSESSMENT_OPTIONS,
813
+ key=radio_key,
814
+ index=default_index
815
+ )
816
+ else:
817
+ # No saved value - use index=None to prevent any default selection
818
+ # Radio button will return None until user makes a selection
819
+ selected_value = st.radio(
820
+ "Your Assessment:",
821
+ options=ASSESSMENT_OPTIONS,
822
+ key=radio_key,
823
+ index=None
824
+ )
825
+
826
+ # Store the selected value for later validation
827
+ selected_values[radio_key] = selected_value
828
+
829
+ # Check for changes if submitted
830
+ if is_submitted and original_value is not None:
831
+ if selected_value != original_value:
832
+ changed_count += 1
833
+ changes_info.append({
834
+ 'subcategory': subcat.formatted_name,
835
+ 'old': original_value,
836
+ 'new': selected_value
837
+ })
838
+ # Display change indicator
839
+ if selected_value is None:
840
+ st.error(f"⚠️ **Invalid selection**: Please select a valid assessment.")
841
+ elif selected_value is not None:
842
+ st.info(f"⚠️ Changed from: **{original_value}** → **{selected_value}**")
843
+
844
+ # Add separator between subcategories (except for the last one)
845
+ if i < len(category.subcategories) - 1:
846
+ st.markdown("---")
847
+
848
+ # Track unsaved changes
849
+ st.session_state.has_unsaved_changes[pair_key] = changed_count > 0
850
+
851
+ # Navigation buttons
852
+ st.markdown("") # Spacing
853
+ col1, col2, col3 = st.columns([1, 1, 1])
854
+
855
+ # Back button
856
+ with col1:
857
+ can_go_back = current_index > 0
858
+ if st.button("← Back", disabled=not can_go_back, use_container_width=True):
859
+ # Check for unsaved changes
860
+ if st.session_state.has_unsaved_changes.get(pair_key, False):
861
+ st.warning("⚠️ You have unsaved changes. Please click 'Update' before navigating.")
862
+ else:
863
+ # Check if moving to a different term
864
+ prev_index = current_index - 1
865
+ if prev_index >= 0:
866
+ prev_term_name, _ = term_category_pairs[prev_index]
867
+ if prev_term_name != term_name:
868
+ # Moving to a different term - show warning page
869
+ # Store current index so we can restore it if user cancels
870
+ st.session_state.back_current_index = current_index
871
+ st.session_state.show_term_back_warning = True
872
+ st.session_state.back_current_term = term.formatted_name
873
+ prev_term = get_term_instance(prev_term_name)
874
+ st.session_state.back_previous_term = prev_term.formatted_name
875
+ else:
876
+ # Same term, just move back
877
+ st.session_state.current_index = prev_index
878
+ st.session_state.show_term_complete = False
879
+ st.session_state.show_term_back_warning = False
880
+ else:
881
+ # Can't go back further
882
+ st.session_state.current_index = prev_index
883
+ st.session_state.show_term_complete = False
884
+ st.session_state.show_term_back_warning = False
885
+ st.rerun()
886
+
887
+ # Submit/Update button
888
+ with col2:
889
+ # Check that all selections are valid (not None)
890
+ # Use session_state as the source of truth since it's always up-to-date with current widget state
891
+ all_valid = True
892
+ for i, subcat in enumerate(category.subcategories):
893
+ radio_key = f"{pair_key}_subcat_{i}"
894
+ # Get current value from session_state (this reflects the actual current selection)
895
+ selected_value = st.session_state.get(radio_key)
896
+ # If value is None, it's not valid
897
+ if selected_value is None:
898
+ all_valid = False
899
+ break
900
+
901
+ if all_valid and len(category.subcategories) > 0:
902
+ if is_submitted and changed_count > 0:
903
+ # Update button with count
904
+ button_label = f"Update ({changed_count} answer{'s' if changed_count > 1 else ''})"
905
+ if st.button(button_label, type="primary", use_container_width=True):
906
+ # Collect all answers first
907
+ answers_list = []
908
+ for i, subcat in enumerate(category.subcategories):
909
+ radio_key = f"{pair_key}_subcat_{i}"
910
+ selected_value = st.session_state.get(radio_key)
911
+ if selected_value is not None:
912
+ score = ASSESSMENT_TO_SCORE[selected_value]
913
+ answers_list.append((subcat.subcategory_name, subcat.question, subcat.answer, score))
914
+
915
+ # Update all answers in a single commit
916
+ commit_message = f"Update answers for {username} - {term_name} - {category_name}"
917
+ save_success = update_category_answers(username, term_name, category_name, answers_list, commit_message)
918
+
919
+ if save_success:
920
+ # Save current selections as new originals
921
+ st.session_state.original_selections[pair_key] = {}
922
+ for i in range(len(category.subcategories)):
923
+ radio_key = f"{pair_key}_subcat_{i}"
924
+ if radio_key in st.session_state:
925
+ st.session_state.original_selections[pair_key][radio_key] = st.session_state[radio_key]
926
+ st.session_state.has_unsaved_changes[pair_key] = False
927
+ st.success("Answers saved successfully!")
928
+ st.rerun()
929
+ else:
930
+ st.error("Error saving some answers. Please check the console/logs for details.")
931
+ elif is_submitted:
932
+ # Already submitted, no changes
933
+ st.button("Update (0 answers)", disabled=True, use_container_width=True)
934
+ else:
935
+ # Submit button for first time
936
+ if st.button("Submit", type="primary", use_container_width=True):
937
+ # Collect all user answers
938
+ answers_list = []
939
+ for i, subcat in enumerate(category.subcategories):
940
+ radio_key = f"{pair_key}_subcat_{i}"
941
+ selected_value = st.session_state.get(radio_key)
942
+ if selected_value is not None:
943
+ score = ASSESSMENT_TO_SCORE[selected_value]
944
+ answers_list.append((subcat.subcategory_name, subcat.question, subcat.answer, score))
945
+
946
+ # Update all answers in a single commit
947
+ # Note: Unknown answers are already auto-scored during account creation
948
+ commit_message = f"Update answers for {username} - {term_name} - {category_name}"
949
+ save_success = update_category_answers(username, term_name, category_name, answers_list, commit_message)
950
+
951
+ if save_success:
952
+ # Mark as submitted and save original selections
953
+ st.session_state.submitted_pairs.add(pair_key)
954
+ st.session_state.original_selections[pair_key] = {}
955
+ for i in range(len(category.subcategories)):
956
+ radio_key = f"{pair_key}_subcat_{i}"
957
+ if radio_key in st.session_state:
958
+ st.session_state.original_selections[pair_key][radio_key] = st.session_state[radio_key]
959
+
960
+ # Check if this is the last category for the current term
961
+ current_term_name = term_name
962
+ next_index = current_index + 1
963
+
964
+ if next_index < total_pairs:
965
+ next_term_name, _ = term_category_pairs[next_index]
966
+
967
+ # Check if we're moving to a different term
968
+ if next_term_name != current_term_name:
969
+ # Show intermediate page
970
+ st.session_state.show_term_complete = True
971
+ st.session_state.completed_term = term.formatted_name
972
+ next_term = get_term_instance(next_term_name)
973
+ st.session_state.next_term = next_term.formatted_name
974
+ else:
975
+ # Same term, just move to next category
976
+ st.session_state.current_index = next_index
977
+ else:
978
+ # No more pairs, go to finish
979
+ st.session_state.current_index = next_index
980
+
981
+ st.success("Answers saved successfully!")
982
+ st.rerun()
983
+ else:
984
+ st.error("Error saving some answers. Please check the console/logs for details.")
985
+ else:
986
+ st.button("Submit", disabled=True, use_container_width=True)
987
+
988
+ # Forward button
989
+ with col3:
990
+ # Can only go forward if current pair is submitted and no unsaved changes
991
+ can_go_forward = (pair_key in st.session_state.submitted_pairs and
992
+ not st.session_state.has_unsaved_changes.get(pair_key, False) and
993
+ current_index < total_pairs - 1)
994
+
995
+ if st.button("Forward →", disabled=not can_go_forward, use_container_width=True):
996
+ if st.session_state.has_unsaved_changes.get(pair_key, False):
997
+ st.warning("⚠️ You have unsaved changes. Please click 'Update' before navigating.")
998
+ else:
999
+ # Check if moving to a different term
1000
+ next_index = current_index + 1
1001
+ if next_index < total_pairs:
1002
+ next_term_name, _ = term_category_pairs[next_index]
1003
+ if next_term_name != term_name:
1004
+ # Moving to a different term - show term switching page
1005
+ st.session_state.show_term_complete = True
1006
+ st.session_state.completed_term = term.formatted_name
1007
+ next_term = get_term_instance(next_term_name)
1008
+ st.session_state.next_term = next_term.formatted_name
1009
+ else:
1010
+ # Same term, just move forward
1011
+ st.session_state.current_index = next_index
1012
+ st.session_state.show_term_complete = False
1013
+ else:
1014
+ # No more pairs
1015
+ st.session_state.current_index = next_index
1016
+ st.session_state.show_term_complete = False
1017
+ st.session_state.show_term_back_warning = False
1018
+ st.rerun()
1019
+
1020
+ else:
1021
+ # Finished
1022
+ st.markdown("# You are finished.")
1023
+ st.markdown("## Thank you for your contribution!")
1024
+
1025
+ # Logout button
1026
+ if st.button("Logout"):
1027
+ st.session_state.logged_in = False
1028
+ st.session_state.username = None
1029
+ st.session_state.current_index = 0
1030
+ st.session_state.show_guide = True
1031
+ st.session_state.submitted_pairs = set()
1032
+ st.session_state.original_selections = {}
1033
+ st.session_state.has_unsaved_changes = {}
1034
+ st.rerun()