Views
No views yet
thomas-sounack/BioClinical-ModernBERT-large to identify current and future treatment plans, medication decisions, and therapeutic interventions while preserving patient privacy.O: Outside treatment informationB-TREATMENT: Beginning of treatment entityI-TREATMENT: Inside treatment entity1from transformers import AutoTokenizer, AutoModelForTokenClassification
2import torch
3
4# Load model and tokenizer
5model_name = "Lekhansh/bioclinical-treatment-detector"
6tokenizer = AutoTokenizer.from_pretrained(model_name)
7model = AutoModelForTokenClassification.from_pretrained(model_name)
8
9# Example clinical text
10text = """
11Treatment Plan:
121. Start Tablet Buprenorphine 8mg twice daily
132. Continue counseling sessions weekly
143. Follow up in outpatient clinic after 2 weeks
15"""
16
17# Tokenize and predict
18inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512,
19 return_offsets_mapping=True)
20outputs = model(**{k: v for k, v in inputs.items() if k != 'offset_mapping'})
21
22# Get predictions
23predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
24predicted_labels = torch.argmax(predictions, dim=-1)[0]
25
26# Map predictions to text spans
27id2label = {0: "O", 1: "B-TREATMENT", 2: "I-TREATMENT"}
28offset_mapping = inputs["offset_mapping"][0]
29
30treatment_spans = []
31current_span = None
32
33for i, (label_id, (start, end)) in enumerate(zip(predicted_labels, offset_mapping)):
34 if start == 0 and end == 0: # Skip special tokens
35 continue
36
37 label = id2label[label_id.item()]
38
39 if label == "B-TREATMENT":
40 if current_span:
41 treatment_spans.append(current_span)
42 current_span = {"start": start.item(), "end": end.item()}
43 elif label == "I-TREATMENT" and current_span:
44 current_span["end"] = end.item()
45 else:
46 if current_span:
47 treatment_spans.append(current_span)
48 current_span = None
49
50if current_span:
51 treatment_spans.append(current_span)
52
53# Extract treatment text
54for span in treatment_spans:
55 treatment_text = text[span["start"]:span["end"]]
56 print(f"Treatment detected: '{treatment_text}'")1import torch
2import numpy as np
3from transformers import AutoTokenizer, AutoModelForTokenClassification
4
5class TreatmentDetector:
6 def __init__(self, model_name):
7 self.tokenizer = AutoTokenizer.from_pretrained(model_name)
8 self.model = AutoModelForTokenClassification.from_pretrained(model_name)
9 self.model.eval()
10 self.id2label = {0: "O", 1: "B-TREATMENT", 2: "I-TREATMENT"}
11
12 def detect_treatments(self, text, confidence_threshold=0.5):
13 encoding = self.tokenizer(
14 text, return_tensors="pt", truncation=True, max_length=8192,
15 return_offsets_mapping=True, padding=True
16 )
17
18 with torch.no_grad():
19 outputs = self.model(**{k: v for k, v in encoding.items() if k != 'offset_mapping'})
20 predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
21 predicted_labels = torch.argmax(predictions, dim=-1)[0]
22 confidence_scores = torch.max(predictions, dim=-1)[0][0]
23
24 treatment_spans = []
25 current_span = None
26
27 for i, (label_id, confidence, (start, end)) in enumerate(
28 zip(predicted_labels, confidence_scores, encoding["offset_mapping"][0])
29 ):
30 if start == 0 and end == 0:
31 continue
32
33 label = self.id2label[label_id.item()]
34 conf = confidence.item()
35
36 if label == "B-TREATMENT" and conf > confidence_threshold:
37 if current_span:
38 treatment_spans.append(current_span)
39 current_span = {
40 "start": start.item(), "end": end.item(),
41 "confidence": conf
42 }
43 elif label == "I-TREATMENT" and current_span and conf > confidence_threshold:
44 current_span["end"] = end.item()
45 current_span["confidence"] = (current_span["confidence"] + conf) / 2
46 else:
47 if current_span:
48 treatment_spans.append(current_span)
49 current_span = None
50
51 if current_span:
52 treatment_spans.append(current_span)
53
54 # Add text content
55 for span in treatment_spans:
56 span["text"] = text[span["start"]:span["end"]]
57
58 return treatment_spans
59
60# Usage
61detector = TreatmentDetector("Lekhansh/bioclinical-treatment-detector")
62treatments = detector.detect_treatments(clinical_text)1@misc{bioclinical-treatment-detector,
2 title={Addiction Medicine Treatment Information Detector for Clinical AI},
3 author={[Lekhansh S, Prakrithi SN]},
4 year={2025},
5 publisher={Hugging Face},
6 howpublished={\url{https://huggingface.co/Lekhansh/bioclinical-treatment-detector}}
7}