|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +import logging |
| 17 | +import pickle |
| 18 | +from typing import List |
| 19 | + |
| 20 | +log = logging.getLogger(__name__) |
| 21 | +MODEL_REGISTRY = { |
| 22 | + "SPAM": { |
| 23 | + "model_path": "nemoguardrails/library/xgb/model_artifacts/model.pkl", |
| 24 | + "vectorizer_path": "nemoguardrails/library/xgb/model_artifacts/vectorizer.pkl", |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | + |
| 29 | +def xgb_inference(text: str, enabled_detectors: List[str]): |
| 30 | + detections = [] |
| 31 | + for detector in enabled_detectors: |
| 32 | + model_info = MODEL_REGISTRY.get(detector) |
| 33 | + if not model_info: |
| 34 | + raise ValueError( |
| 35 | + f"XGB detector '{detector}' is not configured in the MODEL_REGISTRY." |
| 36 | + ) |
| 37 | + model_path = model_info["model_path"] |
| 38 | + vectorizer_path = model_info["vectorizer_path"] |
| 39 | + with open(model_path, "rb") as f: |
| 40 | + model = pickle.load(f) |
| 41 | + with open(vectorizer_path, "rb") as f: |
| 42 | + vectorizer = pickle.load(f) |
| 43 | + |
| 44 | + try: |
| 45 | + X_vec = vectorizer.transform([text]) |
| 46 | + prediction = model.predict(X_vec)[0] |
| 47 | + probability = model.predict_proba(X_vec)[0] |
| 48 | + |
| 49 | + is_safe = prediction == 0 |
| 50 | + confidence = max(probability) |
| 51 | + |
| 52 | + detections.append( |
| 53 | + { |
| 54 | + "allowed": bool(is_safe), |
| 55 | + "score": float(confidence), |
| 56 | + "prediction": "safe" if is_safe else detector, |
| 57 | + } |
| 58 | + ) |
| 59 | + |
| 60 | + except Exception as e: |
| 61 | + raise ValueError( |
| 62 | + f"Error during XGBoost inference for detector '{detector}': {e}" |
| 63 | + ) |
| 64 | + return detections |
0 commit comments