from fastapi import FastAPI from pydantic import BaseModel import pickle import numpy as np from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import RedirectResponse # Cargar el modelo desde el archivo .pkl with open("miarbolcancer.pkl", "rb") as f: model = pickle.load(f) # Definir el modelo de datos con Pydantic (sin ca_cervix como entrada) class PredictionInput(BaseModel): behavior_sexualRisk: float behavior_eating: float behavior_personalHygine: float intention_aggregation: float intention_commitment: float attitude_consistency: float attitude_spontaneity: float norm_significantPerson: float norm_fulfillment: float perception_vulnerability: float perception_severity: float motivation_strength: float motivation_willingness: float socialSupport_emotionality: float socialSupport_appreciation: float socialSupport_instrumental: float empowerment_knowledge: float empowerment_abilities: float empowerment_desires: float # Crear la aplicación FastAPI app = FastAPI() # CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Redirigir de "/" a "/docs" @app.get("/") def redirect_to_docs(): return RedirectResponse(url="/docs") # Definir el endpoint de predicción @app.post("/predict/") def predict(input_data: PredictionInput): # Convertir los datos de entrada en un array numpy input_array = np.array([[input_data.behavior_sexualRisk, input_data.behavior_eating, input_data.behavior_personalHygine, input_data.intention_aggregation, input_data.intention_commitment, input_data.attitude_consistency, input_data.attitude_spontaneity, input_data.norm_significantPerson, input_data.norm_fulfillment, input_data.perception_vulnerability, input_data.perception_severity, input_data.motivation_strength, input_data.motivation_willingness, input_data.socialSupport_emotionality, input_data.socialSupport_appreciation, input_data.socialSupport_instrumental, input_data.empowerment_knowledge, input_data.empowerment_abilities, input_data.empowerment_desires]]) # Realizar la predicción (el modelo debe predecir ca_cervix) prediction = model.predict(input_array) # Convertir la predicción a tipo nativo Python (int o float) prediction_value = prediction[0] if isinstance(prediction[0], (int, float)) else prediction[0].item() # Retornar la predicción (ca_cervix) return {"ca_cervix_prediction": prediction_value}