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