File size: 14,561 Bytes
9aa727e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273fb8f
9aa727e
 
782e7af
 
 
 
 
 
 
 
 
9aa727e
 
 
 
 
 
 
 
 
8ffbf70
9c5ef2c
 
 
 
 
 
 
9aa727e
 
 
 
782e7af
9aa727e
 
 
273fb8f
92bf86f
9aa727e
 
92bf86f
9aa727e
92bf86f
9aa727e
782e7af
 
9aa727e
 
 
 
 
 
 
 
273fb8f
 
 
9aa727e
 
 
 
273fb8f
9aa727e
 
 
 
 
 
 
18d08ed
9aa727e
 
18d08ed
9aa727e
 
 
 
 
 
 
 
 
 
 
18d08ed
9aa727e
18d08ed
 
9aa727e
18d08ed
 
9aa727e
 
 
9c5ef2c
18d08ed
 
9c5ef2c
18d08ed
 
 
9c5ef2c
18d08ed
b5cdbb3
593b070
18d08ed
 
 
 
9aa727e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
782e7af
 
9aa727e
 
 
 
 
 
 
 
782e7af
9aa727e
 
782e7af
9aa727e
 
 
 
782e7af
9aa727e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5cdbb3
 
 
9aa727e
 
 
 
b5cdbb3
 
9aa727e
 
 
 
4376446
 
9aa727e
 
 
 
5512ae5
 
9aa727e
4376446
 
 
 
 
 
 
85d7b7f
 
4376446
 
 
 
 
 
 
 
 
9aa727e
 
 
 
 
 
 
 
 
 
 
51a1e1a
f6449d5
9aa727e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5512ae5
 
 
 
 
 
 
 
 
 
9aa727e
 
 
 
 
 
 
 
 
 
5512ae5
9aa727e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ffbf70
 
9aa727e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, session
import json
import random
import os
import string
import logging
from datetime import datetime


import os
from huggingface_hub import login

# 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")

# 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__)

app = Flask(__name__)
app.config['SECRET_KEY'] = 'supersecretkey'  # Change this to a random secret key

# Directories for visualizations
VISUALIZATION_DIRS_PLAN_OF_SQLS = {
    "TP": "htmls_POS/TP",
    "TN": "htmls_POS/TN",
    "FP": "htmls_POS/FP",
    "FN": "htmls_POS/FN"
}

VISUALIZATION_DIRS_CHAIN_OF_TABLE = {
    "TP": "htmls_COT/TP",
    "TN": "htmls_COT/TN",
    "FP": "htmls_COT/FP",
    "FN": "htmls_COT/FN"
}

VISUALIZATION_DIRS_NO_XAI = {
    "TP": "htmls_NO_XAI/TP",
    "TN": "htmls_NO_XAI/TN",
    "FP": "htmls_NO_XAI/FP",
    "FN": "htmls_NO_XAI/FN"
}

VISUALIZATION_DIRS_DATER = {
    "TP": "htmls_DATER/TP",
    "TN": "htmls_DATER/TN",
    "FP": "htmls_DATER/FP",
    "FN": "htmls_DATER/FN"
}

import json
import os
from datetime import datetime

from huggingface_hub import HfApi
def save_session_data(username, data):
    try:
        # Extract seed and start_time from the data
        seed = data.get('seed', 'unknown')
        start_time = data.get('start_time', datetime.now().isoformat())

        # Create a filename with username, seed, and start_time
        file_name = f'{username}_seed{seed}_{start_time}_session.json'

        # Remove any characters that might not be safe for filenames
        file_name = "".join(c for c in file_name if c.isalnum() or c in ['_', '-', '.'])

        # Convert data to JSON string
        json_data = json.dumps(data, indent=4)

        # Create a temporary file
        temp_file_path = f"/tmp/{file_name}"
        with open(temp_file_path, 'w') as f:
            f.write(json_data)

        # Upload the file to the Hugging Face Space, overwriting if it exists
        api = HfApi()
        api.upload_file(
            path_or_fileobj=temp_file_path,
            path_in_repo=f"session_data_pref/{file_name}",
            repo_id="luulinh90s/Tabular-LLM-Study-Data",
            repo_type="space",
        )

        # Remove the temporary file
        os.remove(temp_file_path)

        logger.info(f"Session data saved for user {username} with seed {seed} and start time {start_time} in Hugging Face Data Space")
    except Exception as e:
        logger.exception(f"Error saving session data for user {username}: {e}")

from huggingface_hub import hf_hub_download, HfApi

def load_session_data(username):
    try:
        # List all files in the repo
        api = HfApi()
        files = api.list_repo_files(repo_id="luulinh90s/Tabular-LLM-Study-Data", repo_type="space")

        # Filter files for the user
        user_files = [f for f in files if f.startswith(f'session_data_pref/{username}_')]

        if not user_files:
            logger.warning(f"No session data found for user {username}")
            return None

        # Get the most recent file
        latest_file = sorted(user_files, reverse=True)[0]

        # Download the file from the data storage Space
        file_path = hf_hub_download(repo_id="luulinh90s/Tabular-LLM-Study-Data", repo_type="space",
                                    filename=latest_file)

        with open(file_path, 'r') as f:
            data = json.load(f)

        logger.info(f"Session data loaded for user {username} from Hugging Face Data Space")
        return data
    except Exception as e:
        logger.exception(f"Error loading session data for user {username}: {e}")
        return None

def load_samples(methods):
    logger.info(f"Loading samples for methods: {methods}")
    samples = set()  # Use a set to avoid duplicates
    categories = ["TP", "TN", "FP", "FN"]

    method_dirs = [get_method_dir(method) for method in methods]

    for category in categories:
        dir_a = f'htmls_{method_dirs[0].upper()}/{category}'
        dir_b = f'htmls_{method_dirs[1].upper()}/{category}'

        files_a = set(os.listdir(dir_a))
        files_b = set(os.listdir(dir_b))

        matching_files = files_a & files_b

        for file in matching_files:
            samples.add((category, file))

    # Convert set of tuples back to list of dictionaries
    samples = [{'category': category, 'file': file} for category, file in samples]

    logger.info(f"Loaded {len(samples)} unique samples across all categories")
    return samples

def select_balanced_samples(samples):
    try:
        # Ensure we have at least 10 unique samples
        unique_samples = list({(s['category'], s['file']) for s in samples})

        if len(unique_samples) < 10:
            logger.warning(f"Not enough unique samples. Only {len(unique_samples)} available.")
            selected_samples = unique_samples
        else:
            selected_samples = random.sample(unique_samples, 10)

        logger.info(f"Unique sampled samples:\n{selected_samples}")

        # Convert back to dictionary format
        selected_samples = [{'category': category, 'file': file} for category, file in selected_samples]

        logger.info(f"Selected {len(selected_samples)} unique samples")
        return selected_samples
    except Exception as e:
        logger.exception("Error selecting balanced samples")
        return []

def generate_random_string(length=8):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

@app.route('/', methods=['GET', 'POST'])
def index():
    logger.info("Rendering index page.")
    if request.method == 'POST':
        username = request.form.get('username')
        seed = request.form.get('seed')
        methods = request.form.get('method').split(',')

        if not username or not seed or len(methods) != 2:
            logger.error("Missing username, seed, or incorrect number of methods.")
            return "Please fill in all fields and select exactly two methods.", 400

        try:
            seed_int = int(seed)  # Convert to int for random.seed()
            random.seed(seed_int)
            all_samples = load_samples(methods)
            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", 500

            start_time = datetime.now().isoformat()
            session_data = {
                'username': username,
                'seed': seed,  # Store as string
                'methods': methods,
                'selected_samples': selected_samples,
                'current_index': 0,
                'responses': [],
                'start_time': start_time
            }
            save_session_data(username, session_data)
            logger.info(f"Session data initialized 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", 500
    return 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'))


        logger.info(f"Session data:\n{session_data}")

        selected_samples = session_data['selected_samples']
        methods = session_data['methods']
        current_index = session_data['current_index']

        logger.info(f"current_index:\n{current_index}")

        if current_index >= len(selected_samples):
            return redirect(url_for('completed', username=username))

        sample = selected_samples[current_index]
        logger.info(f"sample:\n{sample}")

        method_a, method_b = methods

        # Find matching files for both methods

        method_a_dir = get_method_dir(method_a)
        method_b_dir = get_method_dir(method_b)

        # for category in ['TP', 'TN', 'FP', 'FN']:
        category = sample['category']
        dir_a = f'htmls_{method_a_dir.upper()}/{category}'
        dir_b = f'htmls_{method_b_dir.upper()}/{category}'

        file_a = os.path.join(dir_a, sample['file'])
        file_b = os.path.join(dir_b, sample['file'])
        logger.info(f"file_a:\n{file_a}")
        logger.info(f"file_b:\n{file_a}")

            # files_a = os.listdir(dir_a)
            # files_b = os.listdir(dir_b)
            #
            # matching_files = set(files_a) & set(files_b)
            # if matching_files:
            #     file_a = os.path.join(dir_a, next(iter(matching_files)))
            #     file_b = os.path.join(dir_b, next(iter(matching_files)))
            #     break

        if not file_a or not file_b:
            logger.error(f"Missing files for comparison at index {current_index}")
            session_data['current_index'] += 1
            save_session_data(username, session_data)
            return redirect(url_for('experiment', username=username))

        visualization_a = url_for('send_visualization', filename=file_a)
        visualization_b = url_for('send_visualization', filename=file_b)

        statement = """
Please note that in select row function, starting index is 0 for Chain-of-Table 1 for Dater and Index * represents the selection of the whole Table.
You are now given two explanations that describe the reasoning process of the Table QA model. 
Please analyze the explanations and determine which one provides a clearer and more accurate reasoning process.
        """

        return render_template('experiment.html',
                               sample_id=current_index,
                               statement=statement,
                               visualization_a=visualization_a,
                               visualization_b=visualization_b,
                               method_a=method_a,
                               method_b=method_b,
                               username=username)
    except Exception as e:
        logger.exception(f"An error occurred in the experiment route: {e}")
        return "An error occurred", 500

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'

def get_visualization_dir(method):
    if method == "No-XAI":
        return 'htmls_NO_XAI'
    elif method == "Dater":
        return 'htmls_DATER'
    elif method == "Chain-of-Table":
        return 'htmls_COT'
    else:  # Plan-of-SQLs
        return 'htmls_POS'


@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 feedback
        session_data['responses'].append({
            'sample_id': session_data['current_index'],
            'preferred_method': feedback,
            'timestamp': datetime.now().isoformat()
        })

        # Move to the next sample
        session_data['current_index'] += 1

        # Save updated session data
        save_session_data(username, session_data)
        logger.info(f"Feedback saved for user {username}, sample {session_data['current_index'] - 1}")

        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'))

        session_data['end_time'] = datetime.now().isoformat()

        methods = session_data['methods']
        responses = session_data['responses']

        preferences = {method: 0 for method in methods}
        total_responses = len(responses)

        for response in responses:
            preferred_method = response['preferred_method']
            preferences[preferred_method] += 1

        for method in preferences:
            preferences[method] = round((preferences[method] / total_responses) * 100, 2)

        session_data['preferences'] = preferences

        # Save the final updated session data
        save_session_data(username, session_data)

        return render_template('completed.html', preferences=preferences)
    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}")
    # Ensure the path is safe and doesn't allow access to files outside the intended directory
    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)


if __name__ == "__main__":
    os.makedirs('session_data', exist_ok=True)  # Ensure the directory for session files exists
    app.run(host="0.0.0.0", port=7860, debug=True)