diff --git a/app/main.py b/app/main.py index b978c2f2..0635c724 100644 --- a/app/main.py +++ b/app/main.py @@ -70,6 +70,10 @@ def calib_validation(): """ if request.method == "POST": return session_route.calib_results() - return Response( - "Invalid request method for route", status=405, mimetype="application/json" - ) + return Response('Invalid request method for route', status=405, mimetype='application/json') + +@app.route('/api/session/batch_predict', methods=['POST']) +def batch_predict(): + if request.method == 'POST': + return session_route.batch_predict() + return Response('Invalid request method for route', status=405, mimetype='application/json') diff --git a/app/routes/session.py b/app/routes/session.py index 0872b1b8..54512d74 100644 --- a/app/routes/session.py +++ b/app/routes/session.py @@ -6,6 +6,10 @@ import csv from pathlib import Path +import os +import pandas as pd +import traceback +import re from flask import Flask, request, Response, send_file # Local imports from app @@ -220,13 +224,91 @@ def calib_results(): print("I/O error") # data = gaze_tracker.train_to_validate_calib(calib_csv_file, predict_csv_file) + try: + payload = { + "session_id": file_name, + "model": data, + "screen_height": screen_height, + "screen_width": screen_width, + "k": k + } - # Predict calibration results - data = gaze_tracker.predict(calib_csv_file, k, model_X=model, model_Y=model) + RUXAILAB_WEBHOOK_URL = "https://us-central1-ruxailab-prod.cloudfunctions.net/receiveCalibration" - # Return calibration results - return Response(json.dumps(data), status=200, mimetype="application/json") + resp = requests.post(RUXAILAB_WEBHOOK_URL, json=payload) + print("Enviado para RuxaiLab:", resp.status_code, resp.text) + except Exception as e: + print("Erro ao enviar para RuxaiLab:", e) + return Response(json.dumps(data), status=200, mimetype='application/json') + +def batch_predict(): + try: + data = request.get_json() + + iris_data = data['iris_tracking_data'] + k = data.get('k', 3) + screen_height = data.get('screen_height') + screen_width = data.get('screen_width') + + base_path = Path().absolute() / 'app/services/calib_validation/csv/data' + calib_csv_path = base_path / 'vcczxvzxcv_fixed_train_data.csv' + predict_csv_path = base_path / 'temp_batch_predict.csv' + + print(f"Calib CSV Path: {calib_csv_path}") + print(f"Predict CSV Path: {predict_csv_path}") + print(f"Iris data sample (até 3): {iris_data[:3]}") + + # Debug: colunas do CSV de calibração + df_calib = pd.read_csv(calib_csv_path) + print("Colunas do CSV de calibração:", df_calib.columns.tolist()) + + # Cria CSV temporário com dados de íris para predição + with open(predict_csv_path, 'w', newline='') as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=[ + 'left_iris_x', 'left_iris_y', 'right_iris_x', 'right_iris_y' + ]) + writer.writeheader() + for item in iris_data: + writer.writerow({ + 'left_iris_x': item['left_iris_x'], + 'left_iris_y': item['left_iris_y'], + 'right_iris_x': item['right_iris_x'], + 'right_iris_y': item['right_iris_y'] + }) + + # Chama a predição com os dois CSVs de calibração + predictions = gaze_tracker.predict( + calib_csv_path, + calib_csv_path, + k + ) + + # Verifica se o retorno é lista, dicionário ou outro + if isinstance(predictions, list): + # Se for lista, adiciona timestamp e metadados a cada item + for i in range(len(predictions)): + predictions[i]['timestamp'] = iris_data[i].get('timestamp') + if screen_height is not None: + predictions[i]['screen_height'] = screen_height + if screen_width is not None: + predictions[i]['screen_width'] = screen_width + elif isinstance(predictions, dict): + # Se for dicionário, anexa metadados gerais (exemplo) + if screen_height is not None: + predictions['screen_height'] = screen_height + if screen_width is not None: + predictions['screen_width'] = screen_width + # Timestamp pode não fazer sentido em dicionário com estrutura complexa + else: + print("Retorno da predição tem tipo inesperado:", type(predictions)) + + return Response(json.dumps(predictions), status=200, mimetype='application/json') + + except Exception as e: + print("Erro na batch_predict:", e) + traceback.print_exc() + return Response("Erro interno na predição", status=500) # def session_results(): # session_id = request.args.__getitem__('id') diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..91396f55 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "eye-tracker-api", + "lockfileVersion": 3, + "requires": true, + "packages": {} +}