File size: 21,163 Bytes
de7b716 00c0d2b 0dc341f 24cbc9a eb2147a 0dc341f eb2147a 0dc341f 00c0d2b 06388b5 eb2147a 8873a5c 8251e4d 8873a5c 06388b5 0dc341f 06388b5 0ea49b5 06388b5 073d060 0ea49b5 06388b5 436586a de7b716 de400cc 3c6a020 00c0d2b 436586a de7b716 de400cc de7b716 de400cc eb2147a de400cc eb2147a de400cc eb2147a de400cc eb2147a 3c6a020 436586a 3c6a020 0fe5446 eb2147a 0dc341f eb2147a 0fe5446 eb2147a 0fe5446 eb2147a 0fe5446 eb2147a 0dc341f 2b0d981 eb2147a 2b0d981 eb2147a 0dc341f 073a415 cf6133b 0fe5446 cf6133b 0dc341f eb2147a ea1f759 0fe5446 678720e 0dc341f 0fe5446 0dc341f da1da84 ea1f759 de400cc de7b716 83152ea 86a95d5 83152ea eb2147a de7b716 83152ea 00c0d2b 4600a8b 678720e 0dc341f ea1f759 678720e eb2147a 86a95d5 00c0d2b 86a95d5 4600a8b 86a95d5 06388b5 4600a8b 0fe5446 86a95d5 de7b716 0dc341f 00c0d2b 83152ea 48b2398 83152ea de7b716 0dc341f eb2147a 5d0030d 51ed47e 0fe5446 c3c8897 ce41c1d d72e943 4020dbd 83152ea 4020dbd 5d0030d de7b716 0fe5446 0dc341f 612ce70 073a415 f7f3eab 00c0d2b f7f3eab 00c0d2b f7f3eab 0dc341f de7b716 4faaa69 0dc341f 00c0d2b 83152ea de7b716 83152ea 0dc341f 83152ea 4faaa69 0dc341f 83152ea 00c0d2b de7b716 24cbc9a 83152ea f7f3eab 83152ea de7b716 0dc341f 06388b5 de7b716 0dc341f 00c0d2b 83152ea de7b716 83152ea eb2147a 83152ea 6103c97 9ff73e7 06388b5 9ff73e7 0dc341f 4faaa69 0dc341f 4faaa69 eb2147a 0dc341f 0ea49b5 39073fc 0dc341f 4faaa69 0ec0371 4faaa69 ecc53f5 3c6a020 ecc53f5 4faaa69 ecc53f5 4faaa69 0dc341f 4faaa69 0dc341f 4faaa69 0dc341f 4faaa69 0dc341f 4faaa69 0dc341f eb2147a 3c6a020 00c0d2b 3c6a020 00c0d2b eb2147a 0dc341f 4faaa69 0dc341f 4020dbd 0dc341f fafbcc3 38fa440 fafbcc3 506c033 8d4f7ad b314c6f 506c033 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 |
import uuid
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
import json
import random
import os
import string
import logging
from datetime import datetime
from huggingface_hub import login, HfApi, hf_hub_download
# Set up logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("app.log"),
logging.StreamHandler()
])
logger = logging.getLogger(__name__)
# Use the Hugging Face token from environment variables
hf_token = os.environ.get("HF_TOKEN")
if hf_token:
login(token=hf_token)
else:
logger.error("HF_TOKEN not found in environment variables")
app = Flask(__name__)
app.config['SECRET_KEY'] = 'supersecretkey' # Change this to a random secret key
# File-based session storage
SESSION_DIR = '/tmp/sessions'
os.makedirs(SESSION_DIR, exist_ok=True)
# Update the VISUALIZATION_DIRS dictionary
VISUALIZATION_DIRS = {
"No-XAI": "htmls_NO_XAI_mod",
"Dater": "htmls_DATER_mod2",
"Chain-of-Table": "htmls_COT_mod",
"Plan-of-SQLs": "htmls_POS_mod2",
"Text2SQL": "htmls_Text2SQL"
}
# Update the get_method_dir function
def get_method_dir(method):
if method == 'No-XAI':
return 'NO_XAI'
elif method == 'Dater':
return 'DATER'
elif method == 'Chain-of-Table':
return 'COT'
elif method == 'Plan-of-SQLs':
return 'POS'
elif method == 'Text2SQL':
return 'Text2SQL'
else:
return None
# Update the METHODS list
METHODS = ["No-XAI", "Dater", "Chain-of-Table", "Plan-of-SQLs", "Text2SQL"]
def generate_session_id():
return str(uuid.uuid4())
def save_session_data(session_id, data):
file_path = os.path.join(SESSION_DIR, f'{session_id}.json')
with open(file_path, 'w') as f:
json.dump(data, f)
logger.info(f"Session data saved for session {session_id}")
def load_session_data(session_id):
file_path = os.path.join(SESSION_DIR, f'{session_id}.json')
if os.path.exists(file_path):
with open(file_path, 'r') as f:
return json.load(f)
return None
def save_session_data_to_hf(session_id, data):
try:
username = data.get('username', 'unknown')
seed = data.get('seed', 'unknown')
start_time = data.get('start_time', datetime.now().isoformat())
file_name = f'{username}_seed{seed}_{start_time}_{session_id}_session.json'
file_name = "".join(c for c in file_name if c.isalnum() or c in ['_', '-', '.'])
json_data = json.dumps(data, indent=4)
temp_file_path = f"/tmp/{file_name}"
with open(temp_file_path, 'w') as f:
f.write(json_data)
api = HfApi()
repo_path = "session_data_foward_simulation"
api.upload_file(
path_or_fileobj=temp_file_path,
path_in_repo=f"{repo_path}/{file_name}",
repo_id="luulinh90s/Tabular-LLM-Study-Data",
repo_type="space",
)
os.remove(temp_file_path)
logger.info(f"Session data saved for session {session_id} in Hugging Face Data Space")
except Exception as e:
logger.exception(f"Error saving session data for session {session_id}: {e}")
#
# def load_samples():
# common_samples = []
# categories = ["TP", "TN", "FP", "FN"]
#
# for category in categories:
# files = set(os.listdir(f'htmls_NO_XAI_mod/{category}'))
# for method in ["Dater", "Chain-of-Table", "Plan-of-SQLs", "Text2SQL"]:
# method_dir = VISUALIZATION_DIRS[method]
# files &= set(os.listdir(f'{method_dir}/{category}'))
#
# for file in files:
# common_samples.append({'category': category, 'file': file})
#
# logger.info(f"Found {len(common_samples)} common samples across all methods")
# return common_samples
def load_samples(method, metadata):
common_samples = []
categories = ["TP", "TN", "FP", "FN"]
for category in categories:
# files = set(os.listdir(f'htmls_NO_XAI_mod/{category}'))
method_dir = VISUALIZATION_DIRS[method]
files = set(os.listdir(f'{method_dir}/{category}'))
for file in files:
index = file.split('-')[1].split('.')[0]
metadata_key = f"{get_method_dir(method)}_test-{index}.html"
sample_metadata = metadata.get(metadata_key, {})
common_samples.append({
'category': category,
'file': file,
'metadata': sample_metadata
})
logger.info(f"Found {len(common_samples)} samples for method {method}")
return common_samples
def select_balanced_samples(samples):
try:
# Separate samples into two groups
tp_fp_samples = [s for s in samples if s['category'] in ['TP', 'FP']]
tn_fn_samples = [s for s in samples if s['category'] in ['TN', 'FN']]
# Check if we have enough samples in each group
if len(tp_fp_samples) < 5 or len(tn_fn_samples) < 5:
logger.warning(f"Not enough samples in each category. TP+FP: {len(tp_fp_samples)}, TN+FN: {len(tn_fn_samples)}")
return samples if len(samples) <= 10 else random.sample(samples, 10)
# Select 5 samples from each group
selected_tp_fp = random.sample(tp_fp_samples, 5)
selected_tn_fn = random.sample(tn_fn_samples, 5)
# Combine and shuffle the selected samples
selected_samples = selected_tp_fp + selected_tn_fn
random.shuffle(selected_samples)
logger.info(f"Selected 10 balanced samples: 5 from TP+FP, 5 from TN+FN")
return selected_samples
except Exception as e:
logger.exception("Error selecting balanced samples")
return []
# @app.route('/')
# def introduction():
# return render_template('introduction.html')
@app.route('/attribution')
def attribution():
return render_template('attribution.html')
#
# @app.route('/index', methods=['GET', 'POST'])
# def index():
# if request.method == 'POST':
# username = request.form.get('username')
# seed = request.form.get('seed')
# method = request.form.get('method')
# if not username or not seed or not method:
# return render_template('index.html', error="Please fill in all fields and select a method.")
# if method not in ['Chain-of-Table', 'Plan-of-SQLs', 'Dater', 'Text2SQL']:
# return render_template('index.html', error="Invalid method selected.")
# try:
# seed = int(seed)
# random.seed(seed)
# all_samples = load_samples()
# selected_samples = select_balanced_samples(all_samples)
# if len(selected_samples) == 0:
# return render_template('index.html', error="No common samples were found")
# start_time = datetime.now().isoformat()
# session_id = generate_session_id()
# session_data = {
# 'username': username,
# 'seed': str(seed),
# 'method': method,
# 'selected_samples': selected_samples,
# 'current_index': 0,
# 'responses': [],
# 'start_time': start_time,
# 'session_id': session_id
# }
# save_session_data(session_id, session_data)
# logger.info(f"Session data stored for user {username}, method {method}, session_id {session_id}")
#
# # Redirect to explanation for all methods
# return redirect(url_for('explanation', session_id=session_id))
# except Exception as e:
# logger.exception(f"Error in index route: {e}")
# return render_template('index.html', error="An error occurred. Please try again.")
# return render_template('index.html', show_no_xai=False)
@app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
username = request.form.get('username')
seed = request.form.get('seed')
method = request.form.get('method')
if not username or not seed or not method:
return render_template('index.html', error="Please fill in all fields and select a method.")
if method not in ['Chain-of-Table', 'Plan-of-SQLs', 'Dater', 'Text2SQL', 'No-XAI']:
return render_template('index.html', error="Invalid method selected.")
try:
seed = int(seed)
random.seed(seed)
# Load the appropriate metadata file
if method == "Chain-of-Table":
json_file = 'Tabular_LLMs_human_study_vis_6_COT.json'
elif method == "Plan-of-SQLs":
json_file = 'Tabular_LLMs_human_study_vis_6_POS.json'
elif method == "Dater":
json_file = 'Tabular_LLMs_human_study_vis_6_DATER.json'
elif method == "No-XAI":
json_file = 'Tabular_LLMs_human_study_vis_6_NO_XAI.json'
elif method == "Text2SQL":
json_file = 'Tabular_LLMs_human_study_vis_6_Text2SQL.json'
with open(json_file, 'r') as f:
metadata = json.load(f)
all_samples = load_samples(method, metadata)
selected_samples = select_balanced_samples(all_samples)
if len(selected_samples) == 0:
return render_template('index.html', error="No common samples were found")
start_time = datetime.now().isoformat()
session_id = generate_session_id()
session_data = {
'username': username,
'seed': str(seed),
'method': method,
'selected_samples': selected_samples,
'current_index': 0,
'responses': [],
'start_time': start_time,
'session_id': session_id
}
save_session_data(session_id, session_data)
logger.info(f"Session data stored for user {username}, method {method}, session_id {session_id}")
# Redirect to explanation for all methods
return redirect(url_for('explanation', session_id=session_id))
except Exception as e:
logger.exception(f"Error in index route: {e}")
return render_template('index.html', error="An error occurred. Please try again.")
return render_template('index.html', show_no_xai=False)
@app.route('/explanation/<session_id>')
def explanation(session_id):
session_data = load_session_data(session_id)
if not session_data:
logger.error(f"No session data found for session ID: {session_id}")
return redirect(url_for('index'))
method = session_data.get('method')
if not method:
logger.error(f"No method found in session data for session ID: {session_id}")
return redirect(url_for('index'))
if method == 'Chain-of-Table':
return render_template('cot_intro.html', session_id=session_id)
elif method == 'Plan-of-SQLs':
return render_template('pos_intro.html', session_id=session_id)
elif method == 'Dater':
return render_template('dater_intro.html', session_id=session_id)
elif method == 'Text2SQL':
return render_template('text2sql_intro.html', session_id=session_id)
else:
logger.error(f"Invalid method '{method}' for session ID: {session_id}")
return redirect(url_for('index'))
#
# @app.route('/experiment/<session_id>', methods=['GET', 'POST'])
# def experiment(session_id):
# try:
# session_data = load_session_data(session_id)
# if not session_data:
# return redirect(url_for('index'))
#
# selected_samples = session_data['selected_samples']
#
# method = session_data['method']
# current_index = session_data['current_index']
#
# if current_index >= len(selected_samples):
# return redirect(url_for('completed', session_id=session_id))
#
# sample = selected_samples[current_index]
# visualization_dir = VISUALIZATION_DIRS[method]
# visualization_path = f"{visualization_dir}/{sample['category']}/{sample['file']}"
#
# statement = """
# Please note that in select row function, starting index is 0 for Chain-of-Table and 1 for Dater and Index * represents the selection for all rows.
# """
#
# return render_template('experiment.html',
# sample_id=current_index,
# statement=statement,
# visualization=url_for('send_visualization', filename=visualization_path),
# session_id=session_id,
# method=method)
# except Exception as e:
# logger.exception(f"An error occurred in the experiment route: {e}")
# return "An error occurred", 500
@app.route('/experiment/<session_id>', methods=['GET', 'POST'])
def experiment(session_id):
try:
session_data = load_session_data(session_id)
if not session_data:
return redirect(url_for('index'))
selected_samples = session_data['selected_samples']
method = session_data['method']
current_index = session_data['current_index']
if current_index >= len(selected_samples):
return redirect(url_for('completed', session_id=session_id))
sample = selected_samples[current_index]
visualization_dir = VISUALIZATION_DIRS[method]
visualization_path = f"{visualization_dir}/{sample['category']}/{sample['file']}"
# Extract metadata
metadata = sample.get('metadata', {})
# Log the metadata
logger.info(f"Sample metadata for session {session_id}, method {method}, index {current_index}: {metadata}")
statement = metadata['statement']
if method == 'Text2SQL':
statement = f""
return render_template('experiment.html',
sample_id=current_index,
statement=statement,
visualization=url_for('send_visualization', filename=visualization_path),
session_id=session_id,
method=method,
metadata=metadata) # Pass metadata to the template
except Exception as e:
logger.exception(f"An error occurred in the experiment route: {e}")
return "An error occurred", 500
@app.route('/')
def root():
return redirect(url_for('consent'))
@app.route('/consent', methods=['GET', 'POST'])
def consent():
if request.method == 'POST':
# User has agreed to the consent
return redirect(url_for('introduction'))
return render_template('consent.html')
@app.route('/introduction')
def introduction():
return render_template('introduction.html')
@app.route('/subjective/<session_id>', methods=['GET', 'POST'])
def subjective(session_id):
if request.method == 'POST':
understanding = request.form.get('understanding')
session_data = load_session_data(session_id)
if not session_data:
logger.error(f"No session data found for session: {session_id}")
return redirect(url_for('index'))
session_data['subjective_feedback'] = understanding
save_session_data(session_id, session_data)
return redirect(url_for('completed', session_id=session_id))
return render_template('subjective.html', session_id=session_id)
@app.route('/feedback', methods=['POST'])
def feedback():
try:
session_id = request.form['session_id']
prediction = request.form['prediction']
session_data = load_session_data(session_id)
if not session_data:
logger.error(f"No session data found for session: {session_id}")
return redirect(url_for('index'))
session_data['responses'].append({
'sample_id': session_data['current_index'],
'user_prediction': prediction
})
session_data['current_index'] += 1
save_session_data(session_id, session_data)
logger.info(f"Prediction saved for session {session_id}, sample {session_data['current_index'] - 1}")
if session_data['current_index'] >= len(session_data['selected_samples']):
return redirect(url_for('subjective', session_id=session_id))
return redirect(url_for('experiment', session_id=session_id))
except Exception as e:
logger.exception(f"Error in feedback route: {e}")
return "An error occurred", 500
# Update the completed route to include Text2SQL
@app.route('/completed/<session_id>')
def completed(session_id):
try:
session_data = load_session_data(session_id)
if not session_data:
logger.error(f"No session data found for session: {session_id}")
return redirect(url_for('index'))
session_data['end_time'] = datetime.now().isoformat()
responses = session_data['responses']
method = session_data['method']
if method == "Chain-of-Table":
json_file = 'Tabular_LLMs_human_study_vis_6_COT.json'
elif method == "Plan-of-SQLs":
json_file = 'Tabular_LLMs_human_study_vis_6_POS.json'
elif method == "Dater":
json_file = 'Tabular_LLMs_human_study_vis_6_DATER.json'
elif method == "No-XAI":
json_file = 'Tabular_LLMs_human_study_vis_6_NO_XAI.json'
elif method == "Text2SQL":
json_file = 'Tabular_LLMs_human_study_vis_6_Text2SQL.json'
else:
return "Invalid method", 400
with open(json_file, 'r') as f:
ground_truth = json.load(f)
correct_predictions = 0
true_predictions = 0
false_predictions = 0
for response in responses:
sample_id = response['sample_id']
user_prediction = response['user_prediction']
visualization_file = session_data['selected_samples'][sample_id]['file']
index = visualization_file.split('-')[1].split('.')[0]
ground_truth_key = f"{get_method_dir(method)}_test-{index}.html"
logger.info(f"ground_truth_key: {ground_truth_key}")
if ground_truth_key in ground_truth:
# TODO: Important Note ->
# Using model prediction as we are doing forward simulation
# Please use ground_truth[ground_truth_key]['answer'].upper() if running verification task
model_prediction = ground_truth[ground_truth_key]['prediction'].upper()
if user_prediction.upper() == model_prediction:
correct_predictions += 1
if user_prediction.upper() == "TRUE":
true_predictions += 1
elif user_prediction.upper() == "FALSE":
false_predictions += 1
else:
logger.warning(f"Missing key in ground truth: {ground_truth_key}")
accuracy = (correct_predictions / len(responses)) * 100 if responses else 0
accuracy = round(accuracy, 2)
true_percentage = (true_predictions / len(responses)) * 100 if len(responses) else 0
false_percentage = (false_predictions / len(responses)) * 100 if len(responses) else 0
true_percentage = round(true_percentage, 2)
false_percentage = round(false_percentage, 2)
session_data['accuracy'] = accuracy
session_data['true_percentage'] = true_percentage
session_data['false_percentage'] = false_percentage
# Save all the data to Hugging Face at the end
save_session_data_to_hf(session_id, session_data)
# Remove the local session data file
os.remove(os.path.join(SESSION_DIR, f'{session_id}.json'))
return render_template('completed.html',
accuracy=accuracy,
true_percentage=true_percentage,
false_percentage=false_percentage)
except Exception as e:
logger.exception(f"An error occurred in the completed route: {e}")
return "An error occurred", 500
@app.route('/visualizations/<path:filename>')
def send_visualization(filename):
logger.info(f"Attempting to serve file: {filename}")
base_dir = os.getcwd()
file_path = os.path.normpath(os.path.join(base_dir, filename))
if not file_path.startswith(base_dir):
return "Access denied", 403
if not os.path.exists(file_path):
return "File not found", 404
directory = os.path.dirname(file_path)
file_name = os.path.basename(file_path)
logger.info(f"Serving file from directory: {directory}, filename: {file_name}")
return send_from_directory(directory, file_name)
@app.route('/visualizations/<path:filename>')
def send_examples(filename):
return send_from_directory('', filename)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860, debug=True) |