Update app.py
Browse files
app.py
CHANGED
@@ -19,109 +19,169 @@ plt.style.use('default')
|
|
19 |
sns.set_palette("husl")
|
20 |
|
21 |
class EnhancedAIvsRealGazeAnalyzer:
|
|
|
|
|
|
|
|
|
|
|
22 |
def __init__(self):
|
23 |
self.questions = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6']
|
24 |
self.correct_answers = {'Pair1': 'B', 'Pair2': 'B', 'Pair3': 'B', 'Pair4': 'B', 'Pair5': 'B', 'Pair6': 'B'}
|
25 |
self.combined_data = None
|
26 |
-
self.
|
27 |
-
self.
|
28 |
-
self.
|
|
|
|
|
|
|
29 |
|
30 |
def load_and_process_data(self, base_path, response_file):
|
|
|
31 |
print("Loading and processing data...")
|
32 |
self.response_data = pd.read_excel(response_file) if response_file.endswith('.xlsx') else pd.read_csv(response_file)
|
33 |
self.response_data.columns = self.response_data.columns.str.strip()
|
34 |
-
|
35 |
-
if pair in self.response_data.columns:
|
36 |
-
self.response_data[f'{pair}_Correct'] = (self.response_data[pair].astype(str).str.strip().str.upper() == correct_answer)
|
37 |
all_data = {}
|
38 |
for question in self.questions:
|
39 |
file_path = f"{base_path}/Filtered_GenAI_Metrics_cleaned_{question}.xlsx"
|
40 |
if os.path.exists(file_path):
|
41 |
xls = pd.ExcelFile(file_path)
|
42 |
all_data[question] = {sheet_name: pd.read_excel(xls, sheet_name) for sheet_name in xls.sheet_names}
|
|
|
43 |
all_dfs = [df.copy().assign(Question=q, Metric_Type=m) for q, qd in all_data.items() for m, df in qd.items()]
|
44 |
-
if not all_dfs: raise ValueError("No eye-tracking data files were found
|
|
|
45 |
self.combined_data = pd.concat(all_dfs, ignore_index=True)
|
46 |
self.combined_data.columns = self.combined_data.columns.str.strip()
|
47 |
-
|
48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
response_long = self.response_data.melt(id_vars=[resp_id_col], value_vars=self.correct_answers.keys(), var_name='Pair', value_name='Response')
|
50 |
correctness_long = self.response_data.melt(id_vars=[resp_id_col], value_vars=[f'{p}_Correct' for p in self.correct_answers.keys()], var_name='Pair_Correct_Col', value_name='Correct')
|
51 |
correctness_long['Pair'] = correctness_long['Pair_Correct_Col'].str.replace('_Correct', '')
|
52 |
response_long = response_long.merge(correctness_long[[resp_id_col, 'Pair', 'Correct']], on=[resp_id_col, 'Pair'])
|
|
|
53 |
q_to_pair = {f'Q{i+1}': f'Pair{i+1}' for i in range(6)}
|
54 |
self.combined_data['Pair'] = self.combined_data['Question'].map(q_to_pair)
|
55 |
-
self.combined_data = self.combined_data.merge(response_long, left_on=[et_id_col, 'Pair'], right_on=[resp_id_col, 'Pair'], how='left')
|
56 |
self.combined_data['Answer_Correctness'] = self.combined_data['Correct'].map({True: 'Correct', False: 'Incorrect'})
|
|
|
57 |
self.numeric_cols = self.combined_data.select_dtypes(include=np.number).columns.tolist()
|
58 |
self.time_metrics = [c for c in self.numeric_cols if any(k in c.lower() for k in ['time', 'duration', 'fixation'])]
|
|
|
|
|
|
|
|
|
59 |
print("Data loading complete.")
|
60 |
return self
|
61 |
|
62 |
def analyze_rq1_metric(self, metric):
|
63 |
-
|
|
|
64 |
correct = self.combined_data.loc[self.combined_data['Answer_Correctness'] == 'Correct', metric].dropna()
|
65 |
incorrect = self.combined_data.loc[self.combined_data['Answer_Correctness'] == 'Incorrect', metric].dropna()
|
66 |
t_stat, p_val = stats.ttest_ind(incorrect, correct, equal_var=False, nan_policy='omit')
|
67 |
-
fig, ax = plt.subplots(figsize=(8, 6))
|
68 |
-
|
69 |
-
ax.set_title(f'Comparison of "{metric}" by Answer Correctness', fontsize=14)
|
70 |
-
ax.set_xlabel("Answer Correctness")
|
71 |
-
ax.set_ylabel(metric)
|
72 |
-
plt.tight_layout()
|
73 |
-
summary = f"""### Analysis for: **{metric}**\n- **Mean (Correct Answers):** {correct.mean():.4f}\n- **Mean (Incorrect Answers):** {incorrect.mean():.4f}\n- **T-test p-value:** {p_val:.4f}\n\n**Conclusion:**\n- {'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).'}"""
|
74 |
return fig, summary
|
75 |
|
76 |
def run_prediction_model(self, test_size, n_estimators):
|
77 |
-
|
78 |
-
|
79 |
-
|
|
|
80 |
target = self.combined_data['Answer_Correctness'].map({'Correct': 1, 'Incorrect': 0})
|
81 |
valid_indices = target.notna()
|
82 |
features, target = features[valid_indices], target[valid_indices]
|
83 |
features = features.fillna(features.median()).fillna(0)
|
84 |
-
if len(target.unique()) < 2: return "Not enough classes to train.", None, None
|
85 |
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=test_size, random_state=42, stratify=target)
|
86 |
-
scaler = StandardScaler()
|
87 |
-
X_train_scaled, X_test_scaled = scaler.
|
88 |
-
model = RandomForestClassifier(n_estimators=n_estimators, random_state=42, class_weight='balanced')
|
89 |
-
model.
|
90 |
-
|
91 |
-
|
92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
-
|
95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
summary_md = f"""
|
97 |
-
###
|
98 |
-
- **
|
99 |
-
- **
|
100 |
"""
|
101 |
-
|
102 |
-
|
|
|
|
|
|
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
plt.tight_layout()
|
|
|
|
|
|
|
|
|
111 |
|
112 |
-
|
113 |
-
|
114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
|
116 |
-
# --- DATA SETUP ---
|
117 |
def setup_and_load_data():
|
|
|
118 |
repo_url = "https://github.com/RextonRZ/GenAIEyeTrackingCleanedDataset"
|
119 |
repo_dir = "GenAIEyeTrackingCleanedDataset"
|
120 |
if not os.path.exists(repo_dir):
|
121 |
print(f"Cloning data repository from {repo_url}...")
|
122 |
git.Repo.clone_from(repo_url, repo_dir)
|
123 |
else:
|
124 |
-
print("Data repository already. Skipping clone.")
|
125 |
base_path = repo_dir
|
126 |
response_file = os.path.join(repo_dir, "GenAI Response.xlsx")
|
127 |
analyzer = EnhancedAIvsRealGazeAnalyzer().load_and_process_data(base_path, response_file)
|
@@ -133,26 +193,26 @@ print("Application setup complete. Ready for interaction.")
|
|
133 |
|
134 |
# --- GRADIO INTERACTIVE FUNCTIONS ---
|
135 |
def update_rq1_visuals(metric_choice):
|
136 |
-
if not metric_choice: return None, "Please select a metric
|
137 |
plot, summary = analyzer.analyze_rq1_metric(metric_choice)
|
138 |
return plot, summary
|
139 |
|
140 |
def update_rq2_model(test_size, n_estimators):
|
141 |
n_estimators = int(n_estimators)
|
142 |
-
# The function now returns three items
|
143 |
summary, report_df, plot = analyzer.run_prediction_model(test_size, n_estimators)
|
144 |
return summary, report_df, plot
|
145 |
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
Explore the eye-tracking dataset by interacting with the controls below. The data is automatically loaded from the public GitHub repository.
|
150 |
-
"""
|
151 |
|
|
|
152 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
153 |
-
gr.Markdown(
|
|
|
154 |
with gr.Tabs():
|
155 |
-
|
|
|
156 |
with gr.Row():
|
157 |
with gr.Column(scale=1):
|
158 |
rq1_metric_dropdown = gr.Dropdown(choices=analyzer.time_metrics, label="Select a Time-Based Metric", value=analyzer.time_metrics[0] if analyzer.time_metrics else None)
|
@@ -160,34 +220,48 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
160 |
with gr.Column(scale=2):
|
161 |
rq1_plot_output = gr.Plot(label="Metric Comparison")
|
162 |
|
163 |
-
|
|
|
164 |
with gr.Row():
|
165 |
with gr.Column(scale=1):
|
166 |
gr.Markdown("#### Tune Model Hyperparameters")
|
167 |
rq2_test_size_slider = gr.Slider(minimum=0.1, maximum=0.5, step=0.05, value=0.3, label="Test Set Size")
|
168 |
rq2_estimators_slider = gr.Slider(minimum=10, maximum=200, step=10, value=100, label="Number of Trees (n_estimators)")
|
169 |
-
|
170 |
-
# --- THIS IS THE KEY UI FIX ---
|
171 |
with gr.Column(scale=2):
|
172 |
-
# 1. A Markdown component for the summary text.
|
173 |
rq2_summary_output = gr.Markdown(label="Model Performance Summary")
|
174 |
-
# 2. A Dataframe component for the table.
|
175 |
rq2_table_output = gr.Dataframe(label="Classification Report", interactive=False)
|
176 |
-
# 3. A Plot component for the chart.
|
177 |
rq2_plot_output = gr.Plot(label="Feature Importance")
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
183 |
|
|
|
|
|
|
|
|
|
|
|
184 |
rq1_metric_dropdown.change(fn=update_rq1_visuals, inputs=[rq1_metric_dropdown], outputs=[rq1_plot_output, rq1_summary_output])
|
|
|
|
|
185 |
rq2_test_size_slider.release(fn=update_rq2_model, inputs=[rq2_test_size_slider, rq2_estimators_slider], outputs=outputs_rq2)
|
186 |
rq2_estimators_slider.release(fn=update_rq2_model, inputs=[rq2_test_size_slider, rq2_estimators_slider], outputs=outputs_rq2)
|
187 |
|
|
|
|
|
|
|
|
|
|
|
188 |
demo.load(fn=update_rq1_visuals, inputs=[rq1_metric_dropdown], outputs=[rq1_plot_output, rq1_summary_output])
|
189 |
demo.load(fn=update_rq2_model, inputs=[rq2_test_size_slider, rq2_estimators_slider], outputs=outputs_rq2)
|
190 |
-
# --- END OF WIRING FIX ---
|
191 |
|
192 |
if __name__ == "__main__":
|
193 |
demo.launch()
|
|
|
19 |
sns.set_palette("husl")
|
20 |
|
21 |
class EnhancedAIvsRealGazeAnalyzer:
|
22 |
+
"""
|
23 |
+
A comprehensive class to load, process, and analyze eye-tracking data.
|
24 |
+
It supports statistical analysis (RQ1), predictive modeling (RQ2),
|
25 |
+
and deep-dive exploration of individual trials.
|
26 |
+
"""
|
27 |
def __init__(self):
|
28 |
self.questions = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6']
|
29 |
self.correct_answers = {'Pair1': 'B', 'Pair2': 'B', 'Pair3': 'B', 'Pair4': 'B', 'Pair5': 'B', 'Pair6': 'B'}
|
30 |
self.combined_data = None
|
31 |
+
self.participant_list = []
|
32 |
+
self.model = None
|
33 |
+
self.scaler = None
|
34 |
+
self.feature_names = []
|
35 |
+
self.group_means = None
|
36 |
+
self.et_id_col = 'Participant name' # Default participant ID column name
|
37 |
|
38 |
def load_and_process_data(self, base_path, response_file):
|
39 |
+
"""Loads all data from files and preprocesses it for analysis."""
|
40 |
print("Loading and processing data...")
|
41 |
self.response_data = pd.read_excel(response_file) if response_file.endswith('.xlsx') else pd.read_csv(response_file)
|
42 |
self.response_data.columns = self.response_data.columns.str.strip()
|
43 |
+
|
|
|
|
|
44 |
all_data = {}
|
45 |
for question in self.questions:
|
46 |
file_path = f"{base_path}/Filtered_GenAI_Metrics_cleaned_{question}.xlsx"
|
47 |
if os.path.exists(file_path):
|
48 |
xls = pd.ExcelFile(file_path)
|
49 |
all_data[question] = {sheet_name: pd.read_excel(xls, sheet_name) for sheet_name in xls.sheet_names}
|
50 |
+
|
51 |
all_dfs = [df.copy().assign(Question=q, Metric_Type=m) for q, qd in all_data.items() for m, df in qd.items()]
|
52 |
+
if not all_dfs: raise ValueError("No eye-tracking data files were found.")
|
53 |
+
|
54 |
self.combined_data = pd.concat(all_dfs, ignore_index=True)
|
55 |
self.combined_data.columns = self.combined_data.columns.str.strip()
|
56 |
+
|
57 |
+
# Dynamically find participant ID columns
|
58 |
+
self.et_id_col = next((c for c in self.combined_data.columns if 'participant' in c.lower()), 'Participant name')
|
59 |
+
resp_id_col = next((c for c in self.response_data.columns if 'participant' in c.lower()), 'Participant name')
|
60 |
+
|
61 |
+
for pair, correct_answer in self.correct_answers.items():
|
62 |
+
if pair in self.response_data.columns:
|
63 |
+
self.response_data[f'{pair}_Correct'] = (self.response_data[pair].astype(str).str.strip().str.upper() == correct_answer)
|
64 |
+
|
65 |
response_long = self.response_data.melt(id_vars=[resp_id_col], value_vars=self.correct_answers.keys(), var_name='Pair', value_name='Response')
|
66 |
correctness_long = self.response_data.melt(id_vars=[resp_id_col], value_vars=[f'{p}_Correct' for p in self.correct_answers.keys()], var_name='Pair_Correct_Col', value_name='Correct')
|
67 |
correctness_long['Pair'] = correctness_long['Pair_Correct_Col'].str.replace('_Correct', '')
|
68 |
response_long = response_long.merge(correctness_long[[resp_id_col, 'Pair', 'Correct']], on=[resp_id_col, 'Pair'])
|
69 |
+
|
70 |
q_to_pair = {f'Q{i+1}': f'Pair{i+1}' for i in range(6)}
|
71 |
self.combined_data['Pair'] = self.combined_data['Question'].map(q_to_pair)
|
72 |
+
self.combined_data = self.combined_data.merge(response_long, left_on=[self.et_id_col, 'Pair'], right_on=[resp_id_col, 'Pair'], how='left')
|
73 |
self.combined_data['Answer_Correctness'] = self.combined_data['Correct'].map({True: 'Correct', False: 'Incorrect'})
|
74 |
+
|
75 |
self.numeric_cols = self.combined_data.select_dtypes(include=np.number).columns.tolist()
|
76 |
self.time_metrics = [c for c in self.numeric_cols if any(k in c.lower() for k in ['time', 'duration', 'fixation'])]
|
77 |
+
self.participant_list = sorted(self.combined_data[self.et_id_col].unique().tolist())
|
78 |
+
|
79 |
+
# Pre-calculate group means for the explorer tab
|
80 |
+
self.group_means = self.combined_data.groupby('Answer_Correctness')[self.numeric_cols].mean()
|
81 |
print("Data loading complete.")
|
82 |
return self
|
83 |
|
84 |
def analyze_rq1_metric(self, metric):
|
85 |
+
"""Analyzes a single metric for RQ1."""
|
86 |
+
if not metric: return None, "Metric not found."
|
87 |
correct = self.combined_data.loc[self.combined_data['Answer_Correctness'] == 'Correct', metric].dropna()
|
88 |
incorrect = self.combined_data.loc[self.combined_data['Answer_Correctness'] == 'Incorrect', metric].dropna()
|
89 |
t_stat, p_val = stats.ttest_ind(incorrect, correct, equal_var=False, nan_policy='omit')
|
90 |
+
fig, ax = plt.subplots(figsize=(8, 6)); sns.boxplot(data=self.combined_data, x='Answer_Correctness', y=metric, ax=ax, palette=['#66b3ff','#ff9999']); ax.set_title(f'Comparison of "{metric}" by Answer Correctness', fontsize=14); ax.set_xlabel("Answer Correctness"); ax.set_ylabel(metric); plt.tight_layout()
|
91 |
+
summary = f"""### Analysis for: **{metric}**\n- **Mean (Correct Answers):** {correct.mean():.4f}\n- **Mean (Incorrect Answers):** {incorrect.mean():.4f}\n- **T-test p-value:** {p_val:.4f}\n\n**Conclusion:**\n- {'There is a **statistically significant** difference (p < 0.05).' if p_val < 0.05 else 'There is **no statistically significant** difference (p >= 0.05).'}"""
|
|
|
|
|
|
|
|
|
|
|
92 |
return fig, summary
|
93 |
|
94 |
def run_prediction_model(self, test_size, n_estimators):
|
95 |
+
"""Trains and evaluates the RandomForest model for RQ2."""
|
96 |
+
leaky_features = ['Total_Correct', 'Overall_Accuracy', 'Correct', self.et_id_col]
|
97 |
+
self.feature_names = [col for col in self.numeric_cols if col not in leaky_features and col in self.combined_data.columns]
|
98 |
+
features = self.combined_data[self.feature_names].copy()
|
99 |
target = self.combined_data['Answer_Correctness'].map({'Correct': 1, 'Incorrect': 0})
|
100 |
valid_indices = target.notna()
|
101 |
features, target = features[valid_indices], target[valid_indices]
|
102 |
features = features.fillna(features.median()).fillna(0)
|
|
|
103 |
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=test_size, random_state=42, stratify=target)
|
104 |
+
self.scaler = StandardScaler().fit(X_train)
|
105 |
+
X_train_scaled, X_test_scaled = self.scaler.transform(X_train), self.scaler.transform(X_test)
|
106 |
+
self.model = RandomForestClassifier(n_estimators=n_estimators, random_state=42, class_weight='balanced').fit(X_train_scaled, y_train)
|
107 |
+
report = classification_report(y_test, self.model.predict(X_test_scaled), target_names=['Incorrect', 'Correct'], output_dict=True)
|
108 |
+
auc_score = roc_auc_score(y_test, self.model.predict_proba(X_test_scaled)[:, 1])
|
109 |
+
summary_md = f"### Model Performance\n- **AUC Score:** **{auc_score:.4f}**\n- **Overall Accuracy:** {report['accuracy']:.3f}"
|
110 |
+
report_df = pd.DataFrame(report).transpose().round(3)
|
111 |
+
feature_importance = pd.DataFrame({'Feature': self.feature_names, 'Importance': self.model.feature_importances_}).sort_values('Importance', ascending=False).head(15)
|
112 |
+
fig, ax = plt.subplots(figsize=(10, 8)); sns.barplot(data=feature_importance, x='Importance', y='Feature', ax=ax, palette='viridis'); ax.set_title(f'Top 15 Predictive Features (n_estimators={n_estimators})', fontsize=14); plt.tight_layout()
|
113 |
+
return summary_md, report_df, fig
|
114 |
+
|
115 |
+
def analyze_individual_trial(self, participant, question):
|
116 |
+
"""Generates a detailed report for a single participant-question trial."""
|
117 |
+
if not participant or not question:
|
118 |
+
return "Please select a participant and a question.", None, None
|
119 |
+
|
120 |
+
trial_data = self.combined_data[(self.combined_data[self.et_id_col] == participant) & (self.combined_data['Question'] == question)]
|
121 |
+
if trial_data.empty:
|
122 |
+
return f"No data found for {participant} on {question}.", None, None
|
123 |
|
124 |
+
trial_data = trial_data.iloc[0]
|
125 |
+
actual_answer = trial_data['Answer_Correctness']
|
126 |
+
|
127 |
+
# Model Prediction for this specific trial
|
128 |
+
trial_features = trial_data[self.feature_names].values.reshape(1, -1)
|
129 |
+
trial_features_scaled = self.scaler.transform(trial_features)
|
130 |
+
prediction_prob = self.model.predict_proba(trial_features_scaled)[0]
|
131 |
+
predicted_answer = "Correct" if prediction_prob[1] > 0.5 else "Incorrect"
|
132 |
+
|
133 |
+
# Summary Text
|
134 |
summary_md = f"""
|
135 |
+
### Trial Breakdown: **{participant}** on **{question}**
|
136 |
+
- **Actual Answer:** `{actual_answer}`
|
137 |
+
- **Model Prediction:** `{predicted_answer}` (Confidence: {max(prediction_prob)*100:.1f}%)
|
138 |
"""
|
139 |
+
|
140 |
+
# A vs B Gaze Bias Plot
|
141 |
+
aoi_cols = [c for c in self.feature_names if ' A' in c or ' B' in c]
|
142 |
+
a_cols = sorted([c for c in aoi_cols if ' A' in c])
|
143 |
+
b_cols = sorted([c for c in aoi_cols if ' B' in c])
|
144 |
|
145 |
+
plot_data = []
|
146 |
+
for a_col, b_col in zip(a_cols, b_cols):
|
147 |
+
base_name = a_col.replace(' A', '')
|
148 |
+
plot_data.append({'AOI': base_name, 'Image': 'A', 'Value': trial_data[a_col]})
|
149 |
+
plot_data.append({'AOI': base_name, 'Image': 'B', 'Value': trial_data[b_col]})
|
150 |
+
|
151 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
152 |
+
if plot_data:
|
153 |
+
sns.barplot(data=pd.DataFrame(plot_data), x='Value', y='AOI', hue='Image', ax=ax, palette={'A': '#66b3ff', 'B': '#ff9999'})
|
154 |
+
ax.set_title(f'Gaze Bias: Image A vs. Image B for {question}')
|
155 |
+
else:
|
156 |
+
ax.text(0.5, 0.5, 'No A/B Area of Interest data for this question.', ha='center')
|
157 |
plt.tight_layout()
|
158 |
+
|
159 |
+
# Feature Report Card
|
160 |
+
top_features = self.model.feature_importances_.argsort()[-5:][::-1]
|
161 |
+
top_feature_names = [self.feature_names[i] for i in top_features]
|
162 |
|
163 |
+
report_card_data = []
|
164 |
+
for feature in top_feature_names:
|
165 |
+
report_card_data.append({
|
166 |
+
'Top Feature': feature,
|
167 |
+
'This Trial Value': f"{trial_data[feature]:.2f}",
|
168 |
+
'Avg (Correct)': f"{self.group_means.loc['Correct', feature]:.2f}",
|
169 |
+
'Avg (Incorrect)': f"{self.group_means.loc['Incorrect', feature]:.2f}"
|
170 |
+
})
|
171 |
+
report_card_df = pd.DataFrame(report_card_data)
|
172 |
+
|
173 |
+
return summary_md, fig, report_card_df
|
174 |
|
175 |
+
# --- DATA SETUP (RUNS ONCE AT STARTUP) ---
|
176 |
def setup_and_load_data():
|
177 |
+
"""Clones the repo if not present and loads data."""
|
178 |
repo_url = "https://github.com/RextonRZ/GenAIEyeTrackingCleanedDataset"
|
179 |
repo_dir = "GenAIEyeTrackingCleanedDataset"
|
180 |
if not os.path.exists(repo_dir):
|
181 |
print(f"Cloning data repository from {repo_url}...")
|
182 |
git.Repo.clone_from(repo_url, repo_dir)
|
183 |
else:
|
184 |
+
print("Data repository already exists. Skipping clone.")
|
185 |
base_path = repo_dir
|
186 |
response_file = os.path.join(repo_dir, "GenAI Response.xlsx")
|
187 |
analyzer = EnhancedAIvsRealGazeAnalyzer().load_and_process_data(base_path, response_file)
|
|
|
193 |
|
194 |
# --- GRADIO INTERACTIVE FUNCTIONS ---
|
195 |
def update_rq1_visuals(metric_choice):
|
196 |
+
if not metric_choice: return None, "Please select a metric."
|
197 |
plot, summary = analyzer.analyze_rq1_metric(metric_choice)
|
198 |
return plot, summary
|
199 |
|
200 |
def update_rq2_model(test_size, n_estimators):
|
201 |
n_estimators = int(n_estimators)
|
|
|
202 |
summary, report_df, plot = analyzer.run_prediction_model(test_size, n_estimators)
|
203 |
return summary, report_df, plot
|
204 |
|
205 |
+
def update_explorer_view(participant, question):
|
206 |
+
summary, plot, report_card = analyzer.analyze_individual_trial(participant, question)
|
207 |
+
return summary, plot, report_card
|
|
|
|
|
208 |
|
209 |
+
# --- GRADIO INTERFACE DEFINITION ---
|
210 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
211 |
+
gr.Markdown("# Interactive Dashboard: AI vs. Real Gaze Analysis\nExplore the eye-tracking dataset by interacting with the controls below. The data is automatically loaded from the public GitHub repository.")
|
212 |
+
|
213 |
with gr.Tabs():
|
214 |
+
# --- TAB 1: RQ1 ---
|
215 |
+
with gr.TabItem("π RQ1: Viewing Time vs. Correctness"):
|
216 |
with gr.Row():
|
217 |
with gr.Column(scale=1):
|
218 |
rq1_metric_dropdown = gr.Dropdown(choices=analyzer.time_metrics, label="Select a Time-Based Metric", value=analyzer.time_metrics[0] if analyzer.time_metrics else None)
|
|
|
220 |
with gr.Column(scale=2):
|
221 |
rq1_plot_output = gr.Plot(label="Metric Comparison")
|
222 |
|
223 |
+
# --- TAB 2: RQ2 ---
|
224 |
+
with gr.TabItem("π€ RQ2: Predicting Correctness from Gaze"):
|
225 |
with gr.Row():
|
226 |
with gr.Column(scale=1):
|
227 |
gr.Markdown("#### Tune Model Hyperparameters")
|
228 |
rq2_test_size_slider = gr.Slider(minimum=0.1, maximum=0.5, step=0.05, value=0.3, label="Test Set Size")
|
229 |
rq2_estimators_slider = gr.Slider(minimum=10, maximum=200, step=10, value=100, label="Number of Trees (n_estimators)")
|
|
|
|
|
230 |
with gr.Column(scale=2):
|
|
|
231 |
rq2_summary_output = gr.Markdown(label="Model Performance Summary")
|
|
|
232 |
rq2_table_output = gr.Dataframe(label="Classification Report", interactive=False)
|
|
|
233 |
rq2_plot_output = gr.Plot(label="Feature Importance")
|
234 |
+
|
235 |
+
# --- TAB 3: INNOVATIVE EXPLORER ---
|
236 |
+
with gr.TabItem("π¬ Individual Trial Explorer"):
|
237 |
+
gr.Markdown("### Deep Dive into a Single Trial\nSelect a participant and a question to see a detailed breakdown of their gaze behavior.")
|
238 |
+
with gr.Row():
|
239 |
+
with gr.Column(scale=1):
|
240 |
+
explorer_participant = gr.Dropdown(choices=analyzer.participant_list, label="Select Participant")
|
241 |
+
explorer_question = gr.Dropdown(choices=analyzer.questions, label="Select Question")
|
242 |
+
explorer_summary = gr.Markdown(label="Trial Summary")
|
243 |
+
explorer_report_card = gr.Dataframe(label="Feature Report Card", interactive=False)
|
244 |
+
with gr.Column(scale=2):
|
245 |
+
explorer_plot = gr.Plot(label="Gaze Bias (Image A vs. B)")
|
246 |
|
247 |
+
# --- WIRING FOR ALL TABS ---
|
248 |
+
outputs_rq2 = [rq2_summary_output, rq2_table_output, rq2_plot_output]
|
249 |
+
outputs_explorer = [explorer_summary, explorer_plot, explorer_report_card]
|
250 |
+
|
251 |
+
# Wiring for Tab 1
|
252 |
rq1_metric_dropdown.change(fn=update_rq1_visuals, inputs=[rq1_metric_dropdown], outputs=[rq1_plot_output, rq1_summary_output])
|
253 |
+
|
254 |
+
# Wiring for Tab 2
|
255 |
rq2_test_size_slider.release(fn=update_rq2_model, inputs=[rq2_test_size_slider, rq2_estimators_slider], outputs=outputs_rq2)
|
256 |
rq2_estimators_slider.release(fn=update_rq2_model, inputs=[rq2_test_size_slider, rq2_estimators_slider], outputs=outputs_rq2)
|
257 |
|
258 |
+
# Wiring for Tab 3
|
259 |
+
explorer_participant.change(fn=update_explorer_view, inputs=[explorer_participant, explorer_question], outputs=outputs_explorer)
|
260 |
+
explorer_question.change(fn=update_explorer_view, inputs=[explorer_participant, explorer_question], outputs=outputs_explorer)
|
261 |
+
|
262 |
+
# Load initial state for all tabs when the app starts
|
263 |
demo.load(fn=update_rq1_visuals, inputs=[rq1_metric_dropdown], outputs=[rq1_plot_output, rq1_summary_output])
|
264 |
demo.load(fn=update_rq2_model, inputs=[rq2_test_size_slider, rq2_estimators_slider], outputs=outputs_rq2)
|
|
|
265 |
|
266 |
if __name__ == "__main__":
|
267 |
demo.launch()
|