VeenaLim commited on
Commit
7f43b8b
·
verified ·
1 Parent(s): feb0875

Upload plumber_hf.R

Browse files
Files changed (1) hide show
  1. plumber_hf.R +176 -0
plumber_hf.R ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ library(dampack)
2
+ library(readr)
3
+ library(assertthat)
4
+ library(jsonlite)
5
+
6
+ #* @apiTitle DARTH Health Economic Model API
7
+ #*
8
+ #* @apiDescription This API runs a health economic Markov model (Sick-Sicker)
9
+ #* for probabilistic sensitivity analysis. Hosted on Hugging Face Spaces.
10
+ #* Users send their own parameter CSV data from their local machine.
11
+ #* Supports multiple CSV inputs (e.g., base parameters + clinical inputs) that get merged.
12
+
13
+ #* Welcome page - API info
14
+ #* @get /
15
+ function() {
16
+ list(
17
+ name = "DARTH Health Economic Model API",
18
+ version = "1.0",
19
+ status = "running",
20
+ endpoints = list(
21
+ "GET /" = "This welcome page",
22
+ "GET /health" = "Health check",
23
+ "POST /runDARTHmodel" = "Run the DARTH model with your CSV data"
24
+ )
25
+ )
26
+ }
27
+
28
+ #* Health check endpoint
29
+ #* @get /health
30
+ function() {
31
+ list(status = "healthy", timestamp = Sys.time())
32
+ }
33
+
34
+ #* Run the DARTH model
35
+ #* @serializer csv
36
+ #* @param psa_inputs_json JSON string containing the base parameter distributions data from client's local CSV
37
+ #* @param clinical_inputs_json JSON string containing clinical input parameters (optional, merged with psa_inputs)
38
+ #* @param param_updates JSON string with optional parameter overrides (applied after merging all inputs)
39
+ #* @post /runDARTHmodel
40
+ function(psa_inputs_json = NULL, clinical_inputs_json = NULL, param_updates = NULL) {
41
+
42
+ # Source the model functions from Hugging Face (local) or SharePoint
43
+ # Local path = inside Docker container on Hugging Face after deployment
44
+ model_functions_path <- "/app/model/darth_funcs.R"
45
+
46
+ # SharePoint URL for model code (EXPERIMENT - will show roadblocks)
47
+ # Original sharing link: https://symmetronltd.sharepoint.com/:u:/s/EJP_Sandbox/IQAjXsgb1eL1Q5T2uBMT2-VRAQ8wm3t8w4HJqUlf11C2N74?e=rTpGVD
48
+ sharepoint_url <- "https://symmetronltd.sharepoint.com/:u:/s/EJP_Sandbox/IQAjXsgb1eL1Q5T2uBMT2-VRAQ8wm3t8w4HJqUlf11C2N74?download=1"
49
+
50
+ model_loaded <- FALSE
51
+
52
+ # Option 1: Try local file on Hugging Face first (fastest, most reliable)
53
+ if (file.exists(model_functions_path)) {
54
+ source(model_functions_path)
55
+ model_loaded <- TRUE
56
+ message("Model loaded from Hugging Face local file")
57
+ }
58
+
59
+ # Option 2: Try SharePoint (ROADBLOCK - requires authentication!)
60
+ if (!model_loaded) {
61
+ tryCatch({
62
+ # This will FAIL because:
63
+ # 1. SharePoint requires Microsoft 365 authentication
64
+ # 2. source() cannot pass authentication headers
65
+ # 3. The URL redirects to a login page, not the raw R file
66
+ source(sharepoint_url)
67
+ model_loaded <- TRUE
68
+ message("Model loaded from SharePoint")
69
+ }, error = function(e) {
70
+ message("SharePoint source failed: ", e$message)
71
+ message("ROADBLOCK: SharePoint requires Azure AD authentication")
72
+ })
73
+ }
74
+
75
+ # No fallback - fail if model cannot be loaded
76
+ if (!model_loaded) {
77
+ stop("ERROR: Could not load model. Neither local file nor SharePoint source available.")
78
+ }
79
+
80
+ # Helper function to parse and validate CSV JSON input
81
+ parse_csv_json <- function(json_input, input_name) {
82
+ if (is.null(json_input) || json_input == "") {
83
+ return(NULL)
84
+ }
85
+
86
+ tryCatch({
87
+ df <- jsonlite::fromJSON(json_input)
88
+ df <- as.data.frame(df)
89
+
90
+ # Validate required columns exist
91
+ required_cols <- c("parameter", "distribution", "v1", "v2")
92
+ if (!all(required_cols %in% names(df))) {
93
+ stop(paste("Error:", input_name, "must contain columns:", paste(required_cols, collapse = ", ")))
94
+ }
95
+
96
+ # Ensure v1 and v2 are numeric (handle NULL/NA values)
97
+ df$v1 <- as.numeric(df$v1)
98
+ df$v2 <- as.numeric(df$v2)
99
+
100
+ # Replace NA with 0 for v2 (needed for 'fixed' distributions)
101
+ df$v2[is.na(df$v2)] <- 0
102
+
103
+ return(df)
104
+ }, error = function(e) {
105
+ stop(paste("Error parsing", input_name, "JSON:", e$message))
106
+ })
107
+ }
108
+
109
+ # Parse the base PSA inputs (required)
110
+ if (is.null(psa_inputs_json) || psa_inputs_json == "") {
111
+ stop("Error: psa_inputs_json is required. Please send your local CSV data.")
112
+ }
113
+
114
+ psa_inputs <- parse_csv_json(psa_inputs_json, "psa_inputs_json")
115
+
116
+ # Parse clinical inputs if provided (optional, merged with psa_inputs)
117
+ clinical_inputs <- parse_csv_json(clinical_inputs_json, "clinical_inputs_json")
118
+
119
+ if (!is.null(clinical_inputs)) {
120
+ # Merge clinical inputs with base inputs (clinical inputs are appended)
121
+ # If duplicate parameters exist, clinical inputs take precedence
122
+ existing_params <- psa_inputs$parameter
123
+ new_params <- clinical_inputs$parameter
124
+
125
+ # Remove any duplicate parameters from psa_inputs (clinical takes precedence)
126
+ duplicates <- existing_params %in% new_params
127
+ if (any(duplicates)) {
128
+ psa_inputs <- psa_inputs[!duplicates, ]
129
+ }
130
+
131
+ # Combine the data frames
132
+ psa_inputs <- rbind(psa_inputs, clinical_inputs)
133
+ }
134
+
135
+ # Parse param_updates if provided (for additional overrides)
136
+ if (!is.null(param_updates) && param_updates != "") {
137
+ # Handle both JSON string and data frame input
138
+ if (is.character(param_updates)) {
139
+ param_updates <- jsonlite::fromJSON(param_updates)
140
+ }
141
+
142
+ # Convert to data frame if needed
143
+ if (!is.data.frame(param_updates)) {
144
+ param_updates <- as.data.frame(param_updates)
145
+ }
146
+
147
+ # For each row of the data-frame containing the variables to be changed...
148
+ for(n in 1:nrow(param_updates)) {
149
+ # Update parameters from API input
150
+ psa_inputs <- overwrite_parameter_value(
151
+ existing_df = psa_inputs,
152
+ parameter = param_updates[n, "parameter"],
153
+ distribution = param_updates[n, "distribution"],
154
+ v1 = param_updates[n, "v1"],
155
+ v2 = param_updates[n, "v2"]
156
+ )
157
+ }
158
+ }
159
+
160
+ # Run the model using the single run-model function
161
+ results <- run_model(psa_inputs)
162
+
163
+ # Check that the model results being returned are the correct dimensions
164
+ assertthat::assert_that(
165
+ all(dim(x = results) == c(1000, 6)),
166
+ class(results) == "data.frame",
167
+ msg = "Dimensions or type of data are incorrect, please check the model code."
168
+ )
169
+
170
+ # Check that no sensitive data is included in the output
171
+ assertthat::assert_that(
172
+ all(psa_inputs[, 1] %in% as.character(unlist(x = results, recursive = TRUE)) == FALSE)
173
+ )
174
+
175
+ return(results)
176
+ }