|
6 | 6 | import csv |
7 | 7 |
|
8 | 8 | from pathlib import Path |
| 9 | +import os |
| 10 | +import pandas as pd |
| 11 | +import traceback |
| 12 | +import re |
| 13 | +import requests |
9 | 14 | from flask import Flask, request, Response, send_file |
10 | 15 |
|
11 | 16 | # Local imports from app |
|
147 | 152 |
|
148 | 153 |
|
149 | 154 | def calib_results(): |
150 | | - """ |
151 | | - Generate calibration results. |
152 | | -
|
153 | | - This function generates calibration results based on the provided form data. |
154 | | - It saves the calibration points to a CSV file. Then, it uses the gaze_tracker module to predict the calibration results. |
155 | | -
|
156 | | - Returns: |
157 | | - Response: A JSON response containing the calibration results. |
158 | | -
|
159 | | - Raises: |
160 | | - IOError: If there is an error while writing to the CSV files. |
161 | | - """ |
162 | | - # Get form data from request |
163 | | - file_name = json.loads(request.form["file_name"]) |
164 | | - fixed_points = json.loads(request.form["fixed_circle_iris_points"]) |
165 | | - calib_points = json.loads(request.form["calib_circle_iris_points"]) |
166 | | - screen_height = json.loads(request.form["screen_height"]) |
167 | | - screen_width = json.loads(request.form["screen_width"]) |
168 | | - k = json.loads(request.form["k"]) |
169 | | - model = json.loads(request.form["model"]) |
| 155 | + from_ruxailab = json.loads(request.form['from_ruxailab']) |
| 156 | + file_name = json.loads(request.form['file_name']) |
| 157 | + fixed_points = json.loads(request.form['fixed_circle_iris_points']) |
| 158 | + calib_points = json.loads(request.form['calib_circle_iris_points']) |
| 159 | + screen_height = json.loads(request.form['screen_height']) |
| 160 | + screen_width = json.loads(request.form['screen_width']) |
| 161 | + model_X = json.loads(request.form.get('model', '"Linear Regression"')) |
| 162 | + model_Y = json.loads(request.form.get('model', '"Linear Regression"')) |
| 163 | + k = json.loads(request.form['k']) |
170 | 164 |
|
171 | 165 | # Generate csv dataset of calibration points |
172 | 166 | os.makedirs( |
@@ -219,14 +213,107 @@ def calib_results(): |
219 | 213 | except IOError: |
220 | 214 | print("I/O error") |
221 | 215 |
|
222 | | - # data = gaze_tracker.train_to_validate_calib(calib_csv_file, predict_csv_file) |
| 216 | + # Run prediction |
| 217 | + data = gaze_tracker.predict(calib_csv_file, k, model_X, model_Y) |
| 218 | + |
| 219 | + if from_ruxailab: |
| 220 | + try: |
| 221 | + payload = { |
| 222 | + "session_id": file_name, |
| 223 | + "model": data, |
| 224 | + "screen_height": screen_height, |
| 225 | + "screen_width": screen_width, |
| 226 | + "k": k |
| 227 | + } |
| 228 | + |
| 229 | + RUXAILAB_WEBHOOK_URL = "https://receivecalibration-ffptzpxikq-uc.a.run.app" |
223 | 230 |
|
224 | | - # Predict calibration results |
225 | | - data = gaze_tracker.predict(calib_csv_file, k, model_X=model, model_Y=model) |
| 231 | + print("file_name:", file_name) |
226 | 232 |
|
227 | | - # Return calibration results |
228 | | - return Response(json.dumps(data), status=200, mimetype="application/json") |
| 233 | + resp = requests.post(RUXAILAB_WEBHOOK_URL, json=payload) |
| 234 | + print("Enviado para RuxaiLab:", resp.status_code, resp.text) |
| 235 | + except Exception as e: |
| 236 | + print("Erro ao enviar para RuxaiLab:", e) |
229 | 237 |
|
| 238 | + return Response(json.dumps(data), status=200, mimetype='application/json') |
| 239 | + |
| 240 | +def batch_predict(): |
| 241 | + try: |
| 242 | + data = request.get_json() |
| 243 | + iris_data = data['iris_tracking_data'] |
| 244 | + k = data.get('k', 3) |
| 245 | + screen_height = data.get('screen_height') |
| 246 | + screen_width = data.get('screen_width') |
| 247 | + model_X = data.get('model_X', 'Linear Regression') |
| 248 | + model_Y = data.get('model_Y', 'Linear Regression') |
| 249 | + calib_id = data.get('calib_id') |
| 250 | + if not calib_id: |
| 251 | + return Response("Missing 'calib_id' in request", status=400) |
| 252 | + |
| 253 | + base_path = Path().absolute() / 'app/services/calib_validation/csv/data' |
| 254 | + calib_csv_path = base_path / f"{calib_id}_fixed_train_data.csv" |
| 255 | + predict_csv_path = base_path / 'temp_batch_predict.csv' |
| 256 | + |
| 257 | + print(f"Calib CSV Path: {calib_csv_path}") |
| 258 | + print(f"Predict CSV Path: {predict_csv_path}") |
| 259 | + print(f"Iris data sample (até 3): {iris_data[:3]}") |
| 260 | + |
| 261 | + # Gera CSV temporário com os dados de íris |
| 262 | + with open(predict_csv_path, 'w', newline='') as csvfile: |
| 263 | + writer = csv.DictWriter(csvfile, fieldnames=[ |
| 264 | + 'left_iris_x', 'left_iris_y', 'right_iris_x', 'right_iris_y' |
| 265 | + ]) |
| 266 | + writer.writeheader() |
| 267 | + for item in iris_data: |
| 268 | + writer.writerow({ |
| 269 | + 'left_iris_x': item['left_iris_x'], |
| 270 | + 'left_iris_y': item['left_iris_y'], |
| 271 | + 'right_iris_x': item['right_iris_x'], |
| 272 | + 'right_iris_y': item['right_iris_y'] |
| 273 | + }) |
| 274 | + |
| 275 | + # Chama a função de predição corretamente |
| 276 | + predictions_raw = gaze_tracker.predict_new_data( |
| 277 | + calib_csv_path, |
| 278 | + predict_csv_path, |
| 279 | + model_X, |
| 280 | + model_Y, |
| 281 | + k |
| 282 | + ) |
| 283 | + |
| 284 | + # Constrói uma resposta mais visual e direta |
| 285 | + result = [] |
| 286 | + if isinstance(predictions_raw, dict): |
| 287 | + # Percorre o dicionário retornado e transforma em lista plana |
| 288 | + for true_x, inner_dict in predictions_raw.items(): |
| 289 | + if true_x == "centroids": |
| 290 | + continue |
| 291 | + for true_y, info in inner_dict.items(): |
| 292 | + pred_x_list = info.get("predicted_x", []) |
| 293 | + pred_y_list = info.get("predicted_y", []) |
| 294 | + precision = info.get("PrecisionSD") |
| 295 | + accuracy = info.get("Accuracy") |
| 296 | + |
| 297 | + for i, (px, py) in enumerate(zip(pred_x_list, pred_y_list)): |
| 298 | + timestamp = iris_data[i].get("timestamp") if i < len(iris_data) else None |
| 299 | + result.append({ |
| 300 | + "timestamp": timestamp, |
| 301 | + "predicted_x": px, |
| 302 | + "predicted_y": py, |
| 303 | + "precision": precision, |
| 304 | + "accuracy": accuracy, |
| 305 | + "screen_width": screen_width, |
| 306 | + "screen_height": screen_height |
| 307 | + }) |
| 308 | + else: |
| 309 | + print("Retorno inesperado da função predict:", type(predictions_raw)) |
| 310 | + |
| 311 | + return Response(json.dumps(result), status=200, mimetype='application/json') |
| 312 | + |
| 313 | + except Exception as e: |
| 314 | + print("Erro na batch_predict:", e) |
| 315 | + traceback.print_exc() |
| 316 | + return Response("Erro interno na predição", status=500) |
230 | 317 |
|
231 | 318 | # def session_results(): |
232 | 319 | # session_id = request.args.__getitem__('id') |
|
0 commit comments