From 17a0405e580b30d1d20bb8716b93afbbfc00845b Mon Sep 17 00:00:00 2001 From: jvJUCA Date: Thu, 17 Jul 2025 19:29:21 -0300 Subject: [PATCH] feat: new predict endpoint --- app/main.py | 6 +++ app/routes/session.py | 85 +++++++++++++++++++++++++++++++++++++++++++ package-lock.json | 6 +++ 3 files changed, 97 insertions(+) create mode 100644 package-lock.json diff --git a/app/main.py b/app/main.py index f46bb31e..1b0f6dba 100644 --- a/app/main.py +++ b/app/main.py @@ -59,3 +59,9 @@ def calib_validation(): if request.method == 'POST': return session_route.calib_results() 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') \ No newline at end of file diff --git a/app/routes/session.py b/app/routes/session.py index e6c69076..ab3fc01f 100644 --- a/app/routes/session.py +++ b/app/routes/session.py @@ -8,6 +8,8 @@ import csv from pathlib import Path import os +import pandas as pd +import traceback import re ALLOWED_EXTENSIONS = {'txt', 'webm'} @@ -181,8 +183,91 @@ def calib_results(): # data = gaze_tracker.train_to_validate_calib(calib_csv_file, predict_csv_file) data = gaze_tracker.predict(calib_csv_file, calib_csv_file, k) + try: + payload = { + "session_id": file_name, + "model": data, + "screen_height": screen_height, + "screen_width": screen_width, + "k": k + } + + RUXAILAB_WEBHOOK_URL = "https://us-central1-ruxailab-prod.cloudfunctions.net/receiveCalibration" + + 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": {} +}