Spaces:
Sleeping

equil2-api / plumber.R
riki74's picture
Upload plumber.R
af7255e verified
Raw History Blame Contribute Delete
6.65 kB
library(plumber)
library(jsonlite)
library(readr)
library(dplyr)
# Source helper functions
source("helpers.R")
# Add CORS headers for web usage
#* @filter cors
cors <- function(req, res) {
res$setHeader("Access-Control-Allow-Origin", "*")
res$setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
res$setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,X-API-Key")
if (req$REQUEST_METHOD == "OPTIONS") {
res$status <- 200
return(list())
} else {
forward()
}
}
# API Key authentication (optional)
#* @filter auth
auth <- function(req, res) {
api_key <- Sys.getenv("API_KEY")
if (nchar(api_key) > 0) {
provided_key <- req$HTTP_X_API_KEY
if (is.null(provided_key) || provided_key != api_key) {
res$status <- 401
return(list(error = "Unauthorized: Invalid or missing API key"))
}
}
forward()
}
# Request logging
#* @filter logger
function(req) {
cat(paste0(
"[", Sys.time(), "] ",
req$REQUEST_METHOD, " ",
req$PATH_INFO, " - ",
req$REMOTE_ADDR, "\n"
))
forward()
}
#* Health check endpoint
#* @get /health
function() {
list(
status = "ok",
service = "equil2-api",
time = as.character(Sys.time()),
uptime = as.numeric(proc.time()[3])
)
}
#* Version information
#* @get /version
function() {
list(
service = "equil2-api",
version = "1.0.0",
r_version = R.version$version.string,
pkg_equil2 = as.character(utils::packageVersion("equil2")),
pkg_plumber = as.character(utils::packageVersion("plumber")),
license = "GPL-3 (equil2 package)"
)
}
#* Compute urinary supersaturation from JSON
#* @post /equil2/compute
#* @serializer json
function(req, res) {
tryCatch({
# Parse JSON body
body <- jsonlite::fromJSON(req$postBody, simplifyVector = TRUE)
if (!is.null(body$records)) {
# Process records array
df_in <- normalize_records_to_df(body$records)
} else if (!is.null(body$csv)) {
# Process inline CSV string
df_in <- readr::read_csv(I(body$csv), show_col_types = FALSE)
} else {
res$status <- 400
return(list(error = "Provide either 'records' array or 'csv' string"))
}
# Convert units and validate
df_conv <- convert_and_validate(df_in)
# Run EQUIL2 computation
result <- run_equil2_dataframe(df_conv)
return(result)
}, error = function(e) {
res$status <- 400
list(error = paste("Computation failed:", conditionMessage(e)))
})
}
#* Compute urinary supersaturation from CSV file upload
#* @post /equil2/compute_csv
#* @parser multi
#* @serializer json
function(req, res) {
tryCatch({
# Check for uploaded file
file <- req$files[["file"]]
if (is.null(file) || is.null(file$datapath)) {
res$status <- 400
return(list(error = "Missing file upload. Use 'file' as the form field name."))
}
# Read CSV file
df_in <- readr::read_csv(file$datapath, show_col_types = FALSE)
# Convert units and validate
df_conv <- convert_and_validate(df_in)
# Run EQUIL2 computation
result <- run_equil2_dataframe(df_conv)
return(result)
}, error = function(e) {
res$status <- 400
list(error = paste("CSV processing failed:", conditionMessage(e)))
})
}
#* Get example input format
#* @get /equil2/example
function() {
list(
description = "Example input format for EQUIL2 computation",
units = list(
concentrations = "mmol/L or mg/L (will be converted)",
pH = "logarithmic units (4-8.5 range expected)"
),
example_record = list(
Na_mmolL = 45,
K_mmolL = 55,
Ca_mgL = 150,
Mg_mgL = 150,
NH4_mmolL = 10,
Cl_mmolL = 75,
PO4_mgL = 1000,
SO4_mmolL = 20,
Ox_mgL = 100,
Citr_mgL = 4000,
Urate_mgL = 500,
pH = 5.5
),
alternative_units = list(
note = "You can also provide *_mmolL instead of *_mgL for any component",
example = "Ca_mmolL instead of Ca_mgL"
)
)
}
#* API limits and capabilities
#* @get /equil2/limits
function() {
list(
max_records_per_request = 1000,
timeout_seconds = 120,
supported_formats = c("JSON", "CSV"),
required_fields = c("Na_mmolL", "K_mmolL", "NH4_mmolL", "Cl_mmolL", "SO4_mmolL", "pH"),
optional_fields = c("Ca_mgL", "Mg_mgL", "PO4_mgL", "Ox_mgL", "Citr_mgL", "Urate_mgL"),
output_fields = c("SS_CaOx", "SS_Brushite", "SS_HAp", "SS_UricAcid", "DG_CaOx", "DG_Brushite", "DG_HAp", "DG_UricAcid")
)
}
#* Debug endpoint - Test input structure
#* @get /debug/test_input
function() {
# Simula esattamente quello che fa l'API
test_df <- tibble::tibble(
Na_mmolL = 50,
K_mmolL = 40,
Ca_mmolL = 3.74,
Mg_mmolL = 0.01,
NH4_mmolL = 10,
Cl_mmolL = 80,
PO4_mmolL = 4.74,
SO4_mmolL = 15,
Ox_mmolL = 0.28,
Citr_mmolL = 0.01,
Urate_mmolL = 0.01,
pH = 6.0
)
# Test estrazione con [[i]]
i <- 1
test_value <- test_df$Na_mmolL[[i]]
# Crea input per equil2
urine_input <- list(
Na = as.numeric(test_df$Na_mmolL[[i]]),
K = as.numeric(test_df$K_mmolL[[i]]),
Ca = as.numeric(test_df$Ca_mmolL[[i]]),
Mg = as.numeric(test_df$Mg_mmolL[[i]]),
NH4 = as.numeric(test_df$NH4_mmolL[[i]]),
Cl = as.numeric(test_df$Cl_mmolL[[i]]),
PO4 = as.numeric(test_df$PO4_mmolL[[i]]),
SO4 = as.numeric(test_df$SO4_mmolL[[i]]),
C2O4 = as.numeric(test_df$Ox_mmolL[[i]]),
Citrate = as.numeric(test_df$Citr_mmolL[[i]]),
Uric = as.numeric(test_df$Urate_mmolL[[i]]),
pH = as.numeric(test_df$pH[[i]])
)
# Verifica tipi
types_info <- lapply(urine_input, function(x) {
list(
class = class(x),
type = typeof(x),
length = length(x),
value = x
)
})
# Prova chiamata equil2
equil_result <- tryCatch({
res <- equil2::equil2(urine_input)
list(
status = "success",
SS_CaOx = as.numeric(res$RSS["CaOx"]),
message = "equil2 call succeeded"
)
}, error = function(e) {
list(
status = "error",
message = conditionMessage(e)
)
})
return(list(
test_extraction = list(
value = test_value,
class = class(test_value),
length = length(test_value)
),
input_types = types_info,
equil2_result = equil_result,
helpers_version = "2.0",
timestamp = as.character(Sys.time())
))
}