Views
No views yet
[entity]label)[entity]labelpip install transformers torch1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3# Load model and tokenizer
4model_name = "naazimsnh02/qwen3-0.6b-pii-detector"
5tokenizer = AutoTokenizer.from_pretrained(model_name)
6model = AutoModelForCausalLM.from_pretrained(model_name)
7
8# Prepare input
9text = "My name is John Smith and my SSN is 123-45-6789. Contact me at john@email.com"
10
11messages = [
12 {
13 "role": "user",
14 "content": f"""Analyze the following text and identify all PII (Personally Identifiable Information) and PHI (Protected Health Information) entities.
15
16Text: {text}
17
18Provide the output with inline tags in the format: [entity]label"""
19 }
20]
21
22# Generate
23input_ids = tokenizer.apply_chat_template(
24 messages,
25 tokenize=True,
26 add_generation_prompt=True,
27 return_tensors="pt"
28)
29
30outputs = model.generate(
31 input_ids,
32 max_new_tokens=512,
33 temperature=0.1, # Lower for consistent tagging
34 top_p=0.9,
35)
36
37response = tokenizer.decode(outputs[0], skip_special_tokens=True)
38print(response)
39# Output: My name is [John Smith]name and my SSN is [123-45-6789]ssn. Contact me at [john@email.com]email1# Prepare input with context
2text = "Patient John Doe, MRN 12345, diagnosed with hypertension."
3domain = "healthcare"
4doc_type = "medical_record"
5locale = "us"
6
7messages = [
8 {
9 "role": "user",
10 "content": f"""Analyze the following {doc_type} from the {domain} domain ({locale.upper()} locale) and identify all PII (Personally Identifiable Information) and PHI (Protected Health Information) entities.
11
12Text: {text}
13
14Provide the output with inline tags in the format: [entity]label"""
15 }
16]
17
18# Generate as above
19input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt")
20outputs = model.generate(input_ids, max_new_tokens=512, temperature=0.1)
21response = tokenizer.decode(outputs[0], skip_special_tokens=True)
22print(response)1import re
2from typing import List, Dict
3
4class PIIExtractor:
5 """
6 Utility class to extract PII entities from text tagged by the model.
7
8 The model outputs text in the format: [entity]label
9 Example: "[John Smith]first_name works at [Acme Corp]organization"
10 """
11
12 def __init__(self):
13 # Pattern to match [entity]label format
14 self.pattern = re.compile(r'\[([^\]]+)\](\w+)')
15
16 def extract_entities(self, tagged_text: str) -> List[Dict[str, str]]:
17 """
18 Extract all PII entities from tagged text.
19
20 Returns:
21 List of dictionaries with 'text' and 'label' keys
22 """
23 matches = self.pattern.findall(tagged_text)
24 return [{"text": text, "label": label} for text, label in matches]
25
26 def extract_with_positions(self, tagged_text: str) -> List[Dict[str, any]]:
27 """Extract entities with their positions in the original text."""
28 entities = []
29 offset = 0
30
31 for match in self.pattern.finditer(tagged_text):
32 entity_text = match.group(1)
33 label = match.group(2)
34
35 start = match.start() - offset
36 end = start + len(entity_text)
37
38 entities.append({
39 "text": entity_text,
40 "label": label,
41 "start": start,
42 "end": end
43 })
44
45 # Update offset (length of tags removed)
46 offset += len(label) + 2 # +2 for ] and label
47
48 return entities
49
50 def get_clean_text(self, tagged_text: str) -> str:
51 """Remove all tags from text, leaving only the original content."""
52 # Remove labels and brackets
53 text = re.sub(r'\](\w+)', '', tagged_text)
54 text = text.replace('[', '')
55 return text
56
57 def group_by_label(self, tagged_text: str) -> Dict[str, List[str]]:
58 """Group extracted entities by their label type."""
59 entities = self.extract_entities(tagged_text)
60 grouped = {}
61 for entity in entities:
62 label = entity['label']
63 if label not in grouped:
64 grouped[label] = []
65 grouped[label].append(entity['text'])
66 return grouped
67
68# Example usage
69extractor = PIIExtractor()
70tagged_output = "[John Smith]first_name lives in [New York]city"
71
72entities = extractor.extract_entities(tagged_output)
73print(entities)
74# [{'text': 'John Smith', 'label': 'first_name'}, {'text': 'New York', 'label': 'city'}]
75
76clean_text = extractor.get_clean_text(tagged_output)
77print(clean_text)
78# "John Smith lives in New York"
79
80grouped = extractor.group_by_label(tagged_output)
81print(grouped)
82# {'first_name': ['John Smith'], 'city': ['New York']}[entity]labelI am applying for student financial aid. My name is Peggy and my SSN is 250-38-8116.I am applying for student financial aid. My name is [Peggy]first_name and my SSN is [250-38-8116]ssn.first_name, last_name, name, maiden_name, middle_namessn (Social Security Number)date_of_birth, agegender, race_ethnicity, religious_beliefdriver_license, passport, national_idemail, phone_number, fax_numberstreet_address, address, city, state, county, zip_code, countrypo_boxmedical_record_number (mrn), patient_idblood_type, diagnosis, medication, procedurehealth_plan_id, insurance_number, policy_numberhospital_name, doctor_namecredit_card_number, bank_account_numberrouting_number, account_number, ibantax_id, employer_id (ein)salary, incomeorganization, company_name, employerjob_title, employee_idusername, user_idip_address, mac_addressurl, domain_namedevice_id, imeistudent_id, school_name, universitydegree, gpacase_number, court_namelicense_plate, vin1@misc{qwen3-pii-detector,
2 author = {Syed Naazim Hussain},
3 title = {Qwen3 0.6B PII Detector},
4 year = {2025},
5 publisher = {HuggingFace},
6 url = {https://huggingface.co/naazimsnh02/qwen3-0.6b-pii-detector}
7}