1414# appropriate file permissions. In production, consider using safer serialization
1515# formats like joblib or JSON + model-specific loaders.
1616
17+
1718def safe_pickle_load (filepath : str ):
1819 """
1920 Load pickle file with basic safety checks.
@@ -30,6 +31,7 @@ def safe_pickle_load(filepath: str):
3031 with open (filepath , "rb" ) as f :
3132 return pickle .load (f )
3233
34+
3335# Load models with safety checks
3436try :
3537 bayes_model = safe_pickle_load ("src/bin/bayes_model_sk.pkl" )
@@ -41,7 +43,20 @@ def safe_pickle_load(filepath: str):
4143 # Fallback to old format directory (for backward compatibility)
4244 rnn_model_path = "src/bin/rnn"
4345
44- rnn_model = keras .models .load_model (rnn_model_path )
46+ # Load with safe_mode=True to prevent arbitrary code execution
47+ # Note: This only works with .keras files, not .h5/.hdf5
48+ try :
49+ rnn_model = keras .models .load_model (rnn_model_path , safe_mode = True )
50+ print ("RNN model loaded in safe mode" )
51+ except Exception as safe_mode_error :
52+ print (f"Safe mode loading failed: { safe_mode_error } " )
53+ # Fallback to unsafe loading only for trusted local models
54+ # In production, this should be removed or require explicit configuration
55+ if os .path .basename (rnn_model_path ) == "rnn.keras" or os .path .basename (rnn_model_path ) == "rnn" :
56+ print ("Loading model without safe_mode (trusted local model)" )
57+ rnn_model = keras .models .load_model (rnn_model_path , safe_mode = False )
58+ else :
59+ raise ValueError (f"Refusing to load untrusted model: { rnn_model_path } " )
4560except Exception as e :
4661 print (f"Error loading models: { e } " )
4762 raise
0 commit comments