Spaces:
Running on Zero
Running on Zero
Download backend/iris_content_guard.py from reflection/iris: direct link, hf CLI and curl.
- Browser
- Download file 1.58 kB
-
https://huggingface.co/spaces/reflection/iris/resolve/refs%2Fpr%2F13/backend/iris_content_guard.py
- Command line
-
hf download hf://spaces/reflection/iris@refs/pr/13/backend/iris_content_guard.py
-
curl -L -o iris_content_guard.py https://huggingface.co/spaces/reflection/iris/resolve/refs%2Fpr%2F13/backend/iris_content_guard.py
1.58 kB
| """Run Iris Content Guard on ZeroGPU and return probabilities for the turn plots.""" | |
| import spaces | |
| import torch | |
| import transformers | |
| CATEGORIES = ( | |
| 'cyber', | |
| 'fraud', | |
| 'privacy', | |
| 'bio_weapons', | |
| 'chem_weapons', | |
| 'rn_weapons', | |
| 'child_safety_non_csae', | |
| 'violence', | |
| 'self_harm', | |
| 'grooming', | |
| 'sex_crimes', | |
| 'sex_content', | |
| 'illegal_activities', | |
| 'hate', | |
| ) | |
| type TurnScores = dict[str, dict[str, float] | None] | |
| classifier = transformers.pipeline( | |
| 'token-classification', | |
| model='reflection/Iris-Content-Guard', | |
| trust_remote_code=True, | |
| # ZeroGPU stages tensors placed on CUDA at startup. | |
| device='cuda', | |
| ) | |
| def _category_scores(side: dict[str, dict[str, float]]) -> dict[str, float]: | |
| probabilities = side['category_harm_probabilities'] | |
| scores = {category: probabilities[category] for category in CATEGORIES} | |
| if not all( | |
| type(value) in (float, int) and 0 <= value <= 1 for value in scores.values() | |
| ): | |
| raise ValueError('Invalid Iris Content Guard probabilities') | |
| return scores | |
| def score_conversation(messages: list[dict[str, str]]) -> TurnScores: | |
| """Score the latest user request and its visible reply in conversation context.""" | |
| with torch.inference_mode(): | |
| result = classifier(messages) | |
| reply = result['response'] | |
| if (reply is not None) != (messages[-1]['role'] == 'assistant'): | |
| raise ValueError('Iris Content Guard reply does not match the conversation') | |
| return { | |
| 'request': _category_scores(result['request']), | |
| 'response': _category_scores(reply) if reply is not None else None, | |
| } | |