Spaces:
Build error
Build error
Commit ·
83152ea
1
Parent(s): 48b2398
update
Browse files3 unmodified lines456789106 unmodified lines17181920212223242510 unmodified lines36373839404140 unmodified lines82838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014113 unmodified lines15515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323410 unmodified lines2452462472482492502513 unmodified linesimport osimport stringimport loggingfrom flask_session import Session # Add this import# Set up logginglogging.basicConfig(level=logging.INFO,6 unmodified linesapp = Flask(__name__)app.config['SECRET_KEY'] = 'supersecretkey' # Change this to a random secret keyapp.config['SESSION_TYPE'] = 'filesystem' # Use filesystem-based sessionSession(app) # Initialize the session extension# Directories for visualizationsVISUALIZATION_DIRS_PLAN_OF_SQLS = {10 unmodified lines"FN": "htmls_COT/FN"}# Load all sample files from the directories based on the selected methoddef load_samples(method):logger.info(f"Loading samples for method: {method}")40 unmodified linesreturn "Missing username, seed, or method", 400try:# Save the method to a filewith open(f'session_data/method_{username}.txt', 'w') as f:f.write(method)seed = int(seed)random.seed(seed)all_samples = load_samples(method)selected_samples = select_balanced_samples(all_samples)logger.info(f"Number of selected samples: {len(selected_samples)}") # Log the number of samplesif len(selected_samples) == 0:logger.error("No samples were selected.")return "No samples were selected", 500random_string = generate_random_string()filename = f'{username}_{seed}_{method}_{random_string}.json'logger.info(f"Generated filename: {filename}")# Save selected samples to a JSON fileos.makedirs('session_data', exist_ok=True)with open(f'session_data/{filename}', 'w') as f:json.dump(selected_samples, f)session['responses'] = [] # Initialize responses listsession['username'] = username # Store the username for later usesession['selected_samples'] = selected_samples # Store selected samples in sessionsession['method'] = method # Store the method in sessionsession['filename'] = filename # Store the filename in sessionlogger.info(f"Session data set: {session}") # Log session datareturn redirect(url_for('experiment', username=username, sample_index=0, seed=seed, filename=filename))except Exception as e:logger.exception(f"Error in index route: {e}")return "An error occurred", 500return render_template('index.html')@app.route('/experiment/<username>/<int:sample_index>/<seed>/<filename>', methods=['GET', 'POST'])def experiment(username, sample_index, seed, filename):try:selected_samples = session.get('selected_samples', [])method = session.get('method')logger.info(f"Experiment route - Session data: {session}") # Log session datalogger.info(f"Selected samples: {selected_samples}") # Log selected samplesif not selected_samples:logger.error("No samples in session. Redirecting to index.")return redirect(url_for('index'))if sample_index >= len(selected_samples):return redirect(url_for('completed', filename=filename))visualization_file = selected_samples[sample_index]if method == "Chain-of-Table":vis_dir = 'htmls_COT'13 unmodified linesstatement = "Please make a decision to Accept/Reject the AI prediction based on the explanation."# Render the template with the correct path for the iframereturn render_template('experiment.html',sample_id=sample_index,statement=statement,visualization=url_for('send_visualization', path=visualization_path),username=username,seed=seed,sample_index=sample_index,filename=filename)except Exception as e:logger.exception(f"An error occurred in the experiment route: {e}")return "An error occurred", 500@app.route('/feedback', methods=['POST'])def feedback():try:sample_id = request.form['sample_id']feedback = request.form['feedback']username = request.form['username']seed = request.form['seed']sample_index = int(request.form['sample_index'])filename = request.form['filename']selected_samples = session.get('selected_samples', [])responses = session.get('responses', [])# Store the feedbackresponses.append({'sample_id': sample_id,'feedback': feedback})session['responses'] = responses# Create the result directory if it doesn't existresult_dir = 'human_study'os.makedirs(result_dir, exist_ok=True)# Load existing data if the JSON file existsfilepath = os.path.join(result_dir, filename)if os.path.exists(filepath):with open(filepath, 'r') as f:data = json.load(f)else:data = {}# Update data with the current feedbackdata[sample_index] = {'Username': username,'Seed': seed,'Sample ID': sample_id,'Task': "Please make a decision to Accept/Reject the AI prediction based on the explanation.",'User Feedback': feedback}# Save updated data to the filewith open(filepath, 'w') as f:json.dump(data, f, indent=4)next_sample_index = sample_index + 1if next_sample_index >= len(selected_samples):return redirect(url_for('completed', filename=filename))return redirect(url_for('experiment', username=username, sample_index=next_sample_index, seed=seed, filename=filename))except Exception as e:logger.exception(f"Error in feedback route: {e}")return "An error occurred", 500@app.route('/completed/<filename>')def completed(filename):try:responses = session.get('responses', [])method = session.get('method')if method == "Chain-of-Table":json_file = 'Tabular_LLMs_human_study_vis_6_COT.json'10 unmodified linesfor response in responses:sample_id = response['sample_id']feedback = response['feedback']index = sample_id.split('-')[1].split('.')[0] # Extract index from filenameif feedback.upper() == "TRUE":accept_count += 13 unmodified lines4567896 unmodified lines16171819202110 unmodified lines323334353637383940414243444546474849505140 unmodified lines929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314413 unmodified lines15815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221310 unmodified lines2242252262272282292302313 unmodified linesimport osimport stringimport logging# Set up logginglogging.basicConfig(level=logging.INFO,6 unmodified linesapp = Flask(__name__)app.config['SECRET_KEY'] = 'supersecretkey' # Change this to a random secret key# Directories for visualizationsVISUALIZATION_DIRS_PLAN_OF_SQLS = {10 unmodified lines"FN": "htmls_COT/FN"}# Function to save session data to a filedef save_session_data(username, data):os.makedirs('session_data', exist_ok=True)with open(f'session_data/{username}_session.json', 'w') as f:json.dump(data, f)# Function to load session data from a filedef load_session_data(username):try:with open(f'session_data/{username}_session.json', 'r') as f:return json.load(f)except FileNotFoundError:return None# Load all sample files from the directories based on the selected methoddef load_samples(method):logger.info(f"Loading samples for method: {method}")40 unmodified linesreturn "Missing username, seed, or method", 400try:seed = int(seed)random.seed(seed)all_samples = load_samples(method)selected_samples = select_balanced_samples(all_samples)logger.info(f"Number of selected samples: {len(selected_samples)}")if len(selected_samples) == 0:logger.error("No samples were selected.")return "No samples were selected", 500filename = f'{username}_{seed}_{method}_{generate_random_string()}.json'logger.info(f"Generated filename: {filename}")# Save session datasession_data = {'responses': [],'username': username,'selected_samples': selected_samples,'method': method,'filename': filename,'current_index': 0}save_session_data(username, session_data)logger.info(f"Session data saved for user: {username}")return redirect(url_for('experiment', username=username))except Exception as e:logger.exception(f"Error in index route: {e}")return "An error occurred", 500return render_template('index.html')@app.route('/experiment/<username>', methods=['GET', 'POST'])def experiment(username):try:session_data = load_session_data(username)if not session_data:logger.error(f"No session data found for user: {username}")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', username=username))visualization_file = selected_samples[current_index]if method == "Chain-of-Table":vis_dir = 'htmls_COT'13 unmodified linesstatement = "Please make a decision to Accept/Reject the AI prediction based on the explanation."return render_template('experiment.html',sample_id=current_index,statement=statement,visualization=url_for('send_visualization', path=visualization_path),username=username)except Exception as e:logger.exception(f"An error occurred in the experiment route: {e}")return "An error occurred", 500@app.route('/feedback', methods=['POST'])def feedback():try:username = request.form['username']feedback = request.form['feedback']session_data = load_session_data(username)if not session_data:logger.error(f"No session data found for user: {username}")return redirect(url_for('index'))# Store the feedbacksession_data['responses'].append({'sample_id': session_data['current_index'],'feedback': feedback})# Move to the next samplesession_data['current_index'] += 1# Save updated session datasave_session_data(username, session_data)if session_data['current_index'] >= len(session_data['selected_samples']):return redirect(url_for('completed', username=username))return redirect(url_for('experiment', username=username))except Exception as e:logger.exception(f"Error in feedback route: {e}")return "An error occurred", 500@app.route('/completed/<username>')def completed(username):try:session_data = load_session_data(username)if not session_data:logger.error(f"No session data found for user: {username}")return redirect(url_for('index'))responses = session_data['responses']method = session_data['method']if method == "Chain-of-Table":json_file = 'Tabular_LLMs_human_study_vis_6_COT.json'10 unmodified linesfor response in responses:sample_id = response['sample_id']feedback = response['feedback']visualization_file = session_data['selected_samples'][sample_id]index = visualization_file.split('-')[1].split('.')[0] # Extract index from filenameif feedback.upper() == "TRUE":accept_count += 1
app.py+71-91