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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
import seaborn as sns
|
6 |
+
from scipy import stats
|
7 |
+
from sklearn.preprocessing import StandardScaler
|
8 |
+
from sklearn.ensemble import RandomForestClassifier
|
9 |
+
from sklearn.model_selection import train_test_split
|
10 |
+
from sklearn.metrics import classification_report, roc_auc_score
|
11 |
+
from tabulate import tabulate
|
12 |
+
import warnings
|
13 |
+
import traceback
|
14 |
+
import gradio as gr
|
15 |
+
import os
|
16 |
+
import git
|
17 |
+
|
18 |
+
# --- Main Class (Slightly Refactored for Interactivity) ---
|
19 |
+
# The core logic remains, but we separate data loading from analysis functions.
|
20 |
+
warnings.filterwarnings('ignore')
|
21 |
+
plt.style.use('default')
|
22 |
+
sns.set_palette("husl")
|
23 |
+
|
24 |
+
|
25 |
+
class EnhancedAIvsRealGazeAnalyzer:
|
26 |
+
def __init__(self):
|
27 |
+
self.questions = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6']
|
28 |
+
self.correct_answers = {'Pair1': 'B', 'Pair2': 'B', 'Pair3': 'B', 'Pair4': 'B', 'Pair5': 'B', 'Pair6': 'B'}
|
29 |
+
self.combined_data = None
|
30 |
+
self.response_data = None
|
31 |
+
self.numeric_cols = []
|
32 |
+
self.time_metrics = []
|
33 |
+
|
34 |
+
def load_and_process_data(self, base_path, response_file):
|
35 |
+
"""Loads all data and preprocesses it once."""
|
36 |
+
print("Loading and processing data...")
|
37 |
+
# Load response data
|
38 |
+
self.response_data = pd.read_excel(response_file) if response_file.endswith('.xlsx') else pd.read_csv(
|
39 |
+
response_file)
|
40 |
+
self.response_data.columns = self.response_data.columns.str.strip()
|
41 |
+
for pair, correct_answer in self.correct_answers.items():
|
42 |
+
if pair in self.response_data.columns:
|
43 |
+
self.response_data[f'{pair}_Correct'] = (
|
44 |
+
self.response_data[pair].astype(str).str.strip().str.upper() == correct_answer)
|
45 |
+
|
46 |
+
# Load eye-tracking data
|
47 |
+
all_data = {}
|
48 |
+
for question in self.questions:
|
49 |
+
file_path = f"{base_path}/Filtered_GenAI_Metrics_cleaned_{question}.xlsx"
|
50 |
+
if os.path.exists(file_path):
|
51 |
+
xls = pd.ExcelFile(file_path)
|
52 |
+
all_data[question] = {sheet_name: pd.read_excel(xls, sheet_name) for sheet_name in xls.sheet_names}
|
53 |
+
|
54 |
+
# Combine and merge
|
55 |
+
all_dfs = [df.copy().assign(Question=q, Metric_Type=m) for q, qd in all_data.items() for m, df in qd.items()]
|
56 |
+
if not all_dfs:
|
57 |
+
raise ValueError("No eye-tracking data files were found or loaded.")
|
58 |
+
|
59 |
+
self.combined_data = pd.concat(all_dfs, ignore_index=True)
|
60 |
+
self.combined_data.columns = self.combined_data.columns.str.strip()
|
61 |
+
|
62 |
+
# Merge with responses
|
63 |
+
et_id_col = next((c for c in self.combined_data.columns if 'participant' in c.lower()), None)
|
64 |
+
resp_id_col = next((c for c in self.response_data.columns if 'participant' in c.lower()), None)
|
65 |
+
|
66 |
+
response_long = self.response_data.melt(id_vars=[resp_id_col], value_vars=self.correct_answers.keys(),
|
67 |
+
var_name='Pair', value_name='Response')
|
68 |
+
correctness_long = self.response_data.melt(id_vars=[resp_id_col],
|
69 |
+
value_vars=[f'{p}_Correct' for p in self.correct_answers.keys()],
|
70 |
+
var_name='Pair_Correct_Col', value_name='Correct')
|
71 |
+
correctness_long['Pair'] = correctness_long['Pair_Correct_Col'].str.replace('_Correct', '')
|
72 |
+
response_long = response_long.merge(correctness_long[[resp_id_col, 'Pair', 'Correct']],
|
73 |
+
on=[resp_id_col, 'Pair'])
|
74 |
+
|
75 |
+
q_to_pair = {f'Q{i + 1}': f'Pair{i + 1}' for i in range(6)}
|
76 |
+
self.combined_data['Pair'] = self.combined_data['Question'].map(q_to_pair)
|
77 |
+
self.combined_data = self.combined_data.merge(response_long, left_on=[et_id_col, 'Pair'],
|
78 |
+
right_on=[resp_id_col, 'Pair'], how='left')
|
79 |
+
self.combined_data['Answer_Correctness'] = self.combined_data['Correct'].map(
|
80 |
+
{True: 'Correct', False: 'Incorrect'})
|
81 |
+
|
82 |
+
# Identify numeric and time columns for later use
|
83 |
+
self.numeric_cols = self.combined_data.select_dtypes(include=np.number).columns.tolist()
|
84 |
+
self.time_metrics = [c for c in self.numeric_cols if
|
85 |
+
any(k in c.lower() for k in ['time', 'duration', 'fixation'])]
|
86 |
+
print("Data loading complete.")
|
87 |
+
return self # Return self for chaining
|
88 |
+
|
89 |
+
def analyze_rq1_metric(self, metric):
|
90 |
+
"""Analyzes a single metric for RQ1."""
|
91 |
+
if metric not in self.combined_data.columns:
|
92 |
+
return None, "Metric not found."
|
93 |
+
|
94 |
+
correct = self.combined_data.loc[self.combined_data['Answer_Correctness'] == 'Correct', metric].dropna()
|
95 |
+
incorrect = self.combined_data.loc[self.combined_data['Answer_Correctness'] == 'Incorrect', metric].dropna()
|
96 |
+
|
97 |
+
# Perform t-test
|
98 |
+
t_stat, p_val = stats.ttest_ind(incorrect, correct, equal_var=False, nan_policy='omit')
|
99 |
+
|
100 |
+
# Create plot
|
101 |
+
fig, ax = plt.subplots(figsize=(8, 6))
|
102 |
+
sns.boxplot(data=self.combined_data, x='Answer_Correctness', y=metric, ax=ax, palette=['#66b3ff', '#ff9999'])
|
103 |
+
ax.set_title(f'Comparison of "{metric}" by Answer Correctness', fontsize=14)
|
104 |
+
ax.set_xlabel("Answer Correctness")
|
105 |
+
ax.set_ylabel(metric)
|
106 |
+
plt.tight_layout()
|
107 |
+
|
108 |
+
# Create summary text
|
109 |
+
summary = f"""
|
110 |
+
### Analysis for: **{metric}**
|
111 |
+
- **Mean (Correct Answers):** {correct.mean():.4f}
|
112 |
+
- **Mean (Incorrect Answers):** {incorrect.mean():.4f}
|
113 |
+
- **T-test p-value:** {p_val:.4f}
|
114 |
+
|
115 |
+
**Conclusion:**
|
116 |
+
- {'There is a **statistically significant** difference between the groups (p < 0.05).' if p_val < 0.05 else 'There is **no statistically significant** difference between the groups (p >= 0.05).'}
|
117 |
+
"""
|
118 |
+
return fig, summary
|
119 |
+
|
120 |
+
def run_prediction_model(self, test_size, n_estimators):
|
121 |
+
"""Runs the RandomForest model with given parameters for RQ2."""
|
122 |
+
leaky_features = ['Total_Correct', 'Overall_Accuracy', 'Correct']
|
123 |
+
features_to_use = [col for col in self.numeric_cols if col not in leaky_features]
|
124 |
+
|
125 |
+
features = self.combined_data[features_to_use].copy()
|
126 |
+
target = self.combined_data['Answer_Correctness'].map({'Correct': 1, 'Incorrect': 0})
|
127 |
+
|
128 |
+
valid_indices = target.notna()
|
129 |
+
features, target = features[valid_indices], target[valid_indices]
|
130 |
+
features = features.fillna(features.median()).fillna(0)
|
131 |
+
|
132 |
+
if len(target.unique()) < 2:
|
133 |
+
return "Not enough classes to train the model.", None
|
134 |
+
|
135 |
+
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=test_size, random_state=42,
|
136 |
+
stratify=target)
|
137 |
+
scaler = StandardScaler()
|
138 |
+
X_train_scaled, X_test_scaled = scaler.fit_transform(X_train), scaler.transform(X_test)
|
139 |
+
|
140 |
+
model = RandomForestClassifier(n_estimators=n_estimators, random_state=42, class_weight='balanced')
|
141 |
+
model.fit(X_train_scaled, y_train)
|
142 |
+
y_pred_proba = model.predict_proba(X_test_scaled)[:, 1]
|
143 |
+
y_pred = model.predict(X_test_scaled)
|
144 |
+
|
145 |
+
# Generate results
|
146 |
+
report = classification_report(y_test, y_pred, target_names=['Incorrect', 'Correct'], output_dict=True)
|
147 |
+
auc_score = roc_auc_score(y_test, y_pred_proba)
|
148 |
+
|
149 |
+
report_df = pd.DataFrame(report).transpose().round(3)
|
150 |
+
report_md = f"""
|
151 |
+
### Model Performance
|
152 |
+
- **AUC Score:** **{auc_score:.4f}**
|
153 |
+
- **Overall Accuracy:** {report['accuracy']:.3f}
|
154 |
+
|
155 |
+
**Classification Report:**
|
156 |
+
{report_df.to_markdown()}
|
157 |
+
"""
|
158 |
+
|
159 |
+
# Feature importance plot
|
160 |
+
feature_importance = pd.DataFrame({'Feature': features.columns, 'Importance': model.feature_importances_})
|
161 |
+
feature_importance = feature_importance.sort_values('Importance', ascending=False).head(15)
|
162 |
+
|
163 |
+
fig, ax = plt.subplots(figsize=(10, 8))
|
164 |
+
sns.barplot(data=feature_importance, x='Importance', y='Feature', ax=ax, palette='viridis')
|
165 |
+
ax.set_title(f'Top 15 Predictive Features (n_estimators={n_estimators})', fontsize=14)
|
166 |
+
plt.tight_layout()
|
167 |
+
|
168 |
+
return report_md, fig
|
169 |
+
|
170 |
+
|
171 |
+
# --- DATA SETUP (RUNS ONCE AT STARTUP) ---
|
172 |
+
def setup_and_load_data():
|
173 |
+
"""Clones the repo if not present and loads data."""
|
174 |
+
repo_url = "https://github.com/RextonRZ/GenAIEyeTrackingCleanedDataset"
|
175 |
+
repo_dir = "GenAIEyeTrackingCleanedDataset"
|
176 |
+
|
177 |
+
if not os.path.exists(repo_dir):
|
178 |
+
print(f"Cloning data repository from {repo_url}...")
|
179 |
+
git.Repo.clone_from(repo_url, repo_dir)
|
180 |
+
else:
|
181 |
+
print("Data repository already exists.")
|
182 |
+
|
183 |
+
base_path = os.path.join(repo_dir, "cleaned_dataset")
|
184 |
+
response_file = os.path.join(repo_dir, "response_sheet", "GenAI_Response_Sheet.xlsx")
|
185 |
+
|
186 |
+
analyzer = EnhancedAIvsRealGazeAnalyzer().load_and_process_data(base_path, response_file)
|
187 |
+
return analyzer
|
188 |
+
|
189 |
+
|
190 |
+
print("Starting application setup...")
|
191 |
+
analyzer = setup_and_load_data()
|
192 |
+
print("Application setup complete. Ready for interaction.")
|
193 |
+
|
194 |
+
|
195 |
+
# --- GRADIO INTERACTIVE FUNCTIONS ---
|
196 |
+
def update_rq1_visuals(metric_choice):
|
197 |
+
"""Called by Gradio when the dropdown for RQ1 changes."""
|
198 |
+
if not metric_choice:
|
199 |
+
return None, "Please select a metric from the dropdown."
|
200 |
+
plot, summary = analyzer.analyze_rq1_metric(metric_choice)
|
201 |
+
return plot, summary
|
202 |
+
|
203 |
+
|
204 |
+
def update_rq2_model(test_size, n_estimators):
|
205 |
+
"""Called by Gradio when sliders for RQ2 change."""
|
206 |
+
n_estimators = int(n_estimators) # Ensure it's an integer
|
207 |
+
report, plot = analyzer.run_prediction_model(test_size, n_estimators)
|
208 |
+
return report, plot
|
209 |
+
|
210 |
+
|
211 |
+
# --- GRADIO INTERFACE DEFINITION ---
|
212 |
+
description = """
|
213 |
+
# Interactive Dashboard: AI vs. Real Gaze Analysis
|
214 |
+
Explore the eye-tracking dataset by interacting with the controls below. The data is automatically loaded from the public GitHub repository.
|
215 |
+
"""
|
216 |
+
|
217 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
218 |
+
gr.Markdown(description)
|
219 |
+
|
220 |
+
with gr.Tabs():
|
221 |
+
with gr.TabItem("RQ1: Viewing Time vs. Correctness"):
|
222 |
+
gr.Markdown("### Does viewing time differ based on whether a participant's answer was correct?")
|
223 |
+
with gr.Row():
|
224 |
+
with gr.Column(scale=1):
|
225 |
+
rq1_metric_dropdown = gr.Dropdown(
|
226 |
+
choices=analyzer.time_metrics,
|
227 |
+
label="Select a Time-Based Metric to Analyze",
|
228 |
+
value=analyzer.time_metrics[0] if analyzer.time_metrics else None
|
229 |
+
)
|
230 |
+
rq1_summary_output = gr.Markdown(label="Statistical Summary")
|
231 |
+
with gr.Column(scale=2):
|
232 |
+
rq1_plot_output = gr.Plot(label="Metric Comparison")
|
233 |
+
|
234 |
+
with gr.TabItem("RQ2: Predicting Correctness from Gaze"):
|
235 |
+
gr.Markdown("### Can we build a model to predict answer correctness from gaze patterns?")
|
236 |
+
with gr.Row():
|
237 |
+
with gr.Column(scale=1):
|
238 |
+
gr.Markdown("#### Tune Model Hyperparameters")
|
239 |
+
rq2_test_size_slider = gr.Slider(
|
240 |
+
minimum=0.1, maximum=0.5, step=0.05, value=0.3, label="Test Set Size"
|
241 |
+
)
|
242 |
+
rq2_estimators_slider = gr.Slider(
|
243 |
+
minimum=10, maximum=200, step=10, value=100, label="Number of Trees (n_estimators)"
|
244 |
+
)
|
245 |
+
rq2_report_output = gr.Markdown(label="Model Performance Report")
|
246 |
+
with gr.Column(scale=2):
|
247 |
+
rq2_plot_output = gr.Plot(label="Feature Importance")
|
248 |
+
|
249 |
+
# Wire up the interactive components
|
250 |
+
rq1_metric_dropdown.change(
|
251 |
+
fn=update_rq1_visuals,
|
252 |
+
inputs=[rq1_metric_dropdown],
|
253 |
+
outputs=[rq1_plot_output, rq1_summary_output]
|
254 |
+
)
|
255 |
+
|
256 |
+
# Use .release to only update when the user lets go of the slider
|
257 |
+
rq2_test_size_slider.release(
|
258 |
+
fn=update_rq2_model,
|
259 |
+
inputs=[rq2_test_size_slider, rq2_estimators_slider],
|
260 |
+
outputs=[rq2_report_output, rq2_plot_output]
|
261 |
+
)
|
262 |
+
rq2_estimators_slider.release(
|
263 |
+
fn=update_rq2_model,
|
264 |
+
inputs=[rq2_test_size_slider, rq2_estimators_slider],
|
265 |
+
outputs=[rq2_report_output, rq2_plot_output]
|
266 |
+
)
|
267 |
+
|
268 |
+
# Load initial state
|
269 |
+
demo.load(
|
270 |
+
fn=update_rq1_visuals,
|
271 |
+
inputs=[rq1_metric_dropdown],
|
272 |
+
outputs=[rq1_plot_output, rq1_summary_output]
|
273 |
+
)
|
274 |
+
demo.load(
|
275 |
+
fn=update_rq2_model,
|
276 |
+
inputs=[rq2_test_size_slider, rq2_estimators_slider],
|
277 |
+
outputs=[rq2_report_output, rq2_plot_output]
|
278 |
+
)
|
279 |
+
|
280 |
+
if __name__ == "__main__":
|
281 |
+
demo.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
pandas
|
2 |
+
numpy
|
3 |
+
matplotlib
|
4 |
+
seaborn
|
5 |
+
scipy
|
6 |
+
scikit-learn
|
7 |
+
gradio
|
8 |
+
openpyxl
|
9 |
+
GitPython
|