Spaces:
Sleeping
Sleeping
Download api/preprocessing.py from CloudPulse/ML_classifier: direct link, hf CLI and curl.
- Browser
- Download file 2.26 kB
-
https://huggingface.co/spaces/CloudPulse/ML_classifier/resolve/main/api/preprocessing.py
- Command line
-
hf download hf://spaces/CloudPulse/ML_classifier/api/preprocessing.py
-
curl -L -o preprocessing.py https://huggingface.co/spaces/CloudPulse/ML_classifier/resolve/main/api/preprocessing.py
2.26 kB
| """ | |
| Preprocessing helpers used at inference time. | |
| Mirrors exactly what notebook 00 does to the training data, so a description | |
| arriving from the data engineer's pipeline is anonymised the same way the | |
| training corpus was. | |
| """ | |
| import re | |
| URL_PATTERN = re.compile(r"https?://\S+|www\.\S+", flags=re.IGNORECASE) | |
| # Same provider list as notebook 00. Kept here so the API can run standalone. | |
| PROVIDER_VARIANTS = sorted({ | |
| "amazon", "aws", "microsoft azure", "azure", "google cloud", "gcp", | |
| "cloudflare", "fastly", "datadog", "pagerduty", "twilio", "sendgrid", | |
| "stripe", "github", "gitlab", "atlassian", "jira", "confluent", "slack", | |
| "discord", "mongodb", "vercel", "hubspot", "circleci", "typeform", | |
| "zoom", "digitalocean", "new relic", "shopify", "openai", "intercom", | |
| "linear", "spotify", | |
| }, key=len, reverse=True) | |
| PROVIDER_PATTERN = re.compile( | |
| r"\b(" + "|".join(re.escape(p) for p in PROVIDER_VARIANTS) + r")\b", | |
| flags=re.IGNORECASE, | |
| ) | |
| def anonymise(text: str) -> str: | |
| """Replaces URLs and provider names with generic tokens. | |
| Identical to the training-time preprocessing in notebook 00. Any change here | |
| must be mirrored in notebook 00 or the model and inference will diverge. | |
| """ | |
| if not isinstance(text, str): | |
| return "" | |
| text = URL_PATTERN.sub("URL", text) | |
| text = PROVIDER_PATTERN.sub("PROVIDER", text) | |
| text = re.sub(r"\s+", " ", text).strip() | |
| return text | |
| def confidence_label(probability: float) -> str: | |
| """Bins a predicted probability into a confidence label for the dashboard.""" | |
| if probability >= 0.75: | |
| return "high" | |
| if probability >= 0.50: | |
| return "medium" | |
| return "low" | |
| def apply_escalation_rule( | |
| ml_prediction: str, | |
| original_impact: str | None, | |
| ) -> tuple[str, bool, str | None]: | |
| """The CloudPulse escalation rule. | |
| If the classifier predicts 'high' AND the upstream provider tagged the | |
| incident as 'critical', the final label is upgraded to 'critical'. | |
| Otherwise the model prediction stands. | |
| Returns (final_label, was_escalated, reason). | |
| """ | |
| if ml_prediction == "high" and original_impact == "critical": | |
| return "critical", True, "provider_marked_critical" | |
| return ml_prediction, False, None | |