VeenaLim commited on
Commit
6c1954b
·
verified ·
1 Parent(s): 66ca13f

Read from private github

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