Views
No views yet
1import torch
2from transformers import AutoTokenizer, AutoModelForTokenClassification
3import warnings
4warnings.filterwarnings("ignore")
5
6class IndianAddressNER:
7 def __init__(self):
8 model_name = "shiprocket-ai/open-indicbert-indian-address-ner"
9 self.tokenizer = AutoTokenizer.from_pretrained(model_name)
10 self.model = AutoModelForTokenClassification.from_pretrained(model_name)
11 self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12 self.model.to(self.device)
13 self.model.eval()
14
15 # Entity mappings
16 self.id2entity = {
17 "0": "O",
18 "1": "B-building_name",
19 "2": "I-building_name",
20 "3": "B-city",
21 "4": "I-city",
22 "5": "B-country",
23 "6": "I-country",
24 "7": "B-floor",
25 "8": "I-floor",
26 "9": "B-house_details",
27 "10": "I-house_details",
28 "11": "B-locality",
29 "12": "I-locality",
30 "13": "B-pincode",
31 "14": "I-pincode",
32 "15": "B-road",
33 "16": "I-road",
34 "17": "B-state",
35 "18": "I-state",
36 "19": "B-sub_locality",
37 "20": "I-sub_locality",
38 "21": "B-landmarks",
39 "22": "I-landmarks"
40}
41
42 def predict(self, address):
43 """Extract entities from an Indian address"""
44 if not address.strip():
45 return {}
46
47 # Tokenize
48 inputs = self.tokenizer(
49 address,
50 return_tensors="pt",
51 truncation=True,
52 padding=True,
53 max_length=128
54 )
55 inputs = {k: v.to(self.device) for k, v in inputs.items()}
56
57 # Predict
58 with torch.no_grad():
59 outputs = self.model(**inputs)
60 predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
61 predicted_ids = torch.argmax(predictions, dim=-1)
62 confidence_scores = torch.max(predictions, dim=-1)[0]
63
64 # Convert to tokens and labels
65 tokens = self.tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
66 predicted_labels = [self.id2entity.get(str(id.item()), "O") for id in predicted_ids[0]]
67 confidences = confidence_scores[0].cpu().numpy()
68
69 # Group entities
70 entities = self.group_entities(tokens, predicted_labels, confidences)
71 return entities
72
73 def group_entities(self, tokens, labels, confidences):
74 """Group B- and I- tags into complete entities"""
75 entities = {}
76 current_entity = None
77
78 for i, (token, label, conf) in enumerate(zip(tokens, labels, confidences)):
79 if token in ["[CLS]", "[SEP]", "[PAD]"]:
80 continue
81
82 if label.startswith("B-"):
83 # Save previous entity
84 if current_entity:
85 entity_type = current_entity["type"]
86 if entity_type not in entities:
87 entities[entity_type] = []
88 entities[entity_type].append({
89 "text": current_entity["text"].replace("##", ""),
90 "confidence": current_entity["confidence"]
91 })
92
93 # Start new entity
94 entity_type = label[2:] # Remove "B-"
95 current_entity = {
96 "type": entity_type,
97 "text": token,
98 "confidence": conf
99 }
100
101 elif label.startswith("I-") and current_entity:
102 # Continue current entity
103 entity_type = label[2:] # Remove "I-"
104 if entity_type == current_entity["type"]:
105 current_entity["text"] += token
106 current_entity["confidence"] = (current_entity["confidence"] + conf) / 2
107
108 elif label == "O" and current_entity:
109 # End current entity
110 entity_type = current_entity["type"]
111 if entity_type not in entities:
112 entities[entity_type] = []
113 entities[entity_type].append({
114 "text": current_entity["text"].replace("##", ""),
115 "confidence": current_entity["confidence"]
116 })
117 current_entity = None
118
119 # Add final entity if exists
120 if current_entity:
121 entity_type = current_entity["type"]
122 if entity_type not in entities:
123 entities[entity_type] = []
124 entities[entity_type].append({
125 "text": current_entity["text"].replace("##", ""),
126 "confidence": current_entity["confidence"]
127 })
128
129 return entities
130
131# Usage example
132ner = IndianAddressNER()
133
134# Test addresses
135test_addresses = [
136 "Shop No 123, Sunshine Apartments, Andheri West, Mumbai, 400058",
137 "DLF Cyber City, Sector 25, Gurgaon, Haryana",
138 "Flat 201, MG Road, Bangalore, Karnataka, 560001",
139 "Phoenix Mall, Kurla West, Mumbai"
140]
141
142print("🏠 INDIAN ADDRESS NER EXAMPLES")
143print("=" * 50)
144
145for address in test_addresses:
146 print(f"\n📍 Address: {address}")
147 entities = ner.predict(address)
148
149 if entities:
150 for entity_type, entity_list in sorted(entities.items()):
151 print(f"🏷️ {entity_type.replace('_', ' ').title()}:")
152 for entity in entity_list:
153 confidence = entity['confidence']
154 text = entity['text']
155 confidence_icon = "🟢" if confidence > 0.8 else "🟡" if confidence > 0.6 else "🔴"
156 print(f" {confidence_icon} {text} (confidence: {confidence:.3f})")
157 else:
158 print("❌ No entities found")
159 print("-" * 40)1{
2 "entity2id": {
3 "O": 0,
4 "B-building_name": 1,
5 "I-building_name": 2,
6 "B-city": 3,
7 "I-city": 4,
8 "B-country": 5,
9 "I-country": 6,
10 "B-floor": 7,
11 "I-floor": 8,
12 "B-house_details": 9,
13 "I-house_details": 10,
14 "B-locality": 11,
15 "I-locality": 12,
16 "B-pincode": 13,
17 "I-pincode": 14,
18 "B-road": 15,
19 "I-road": 16,
20 "B-state": 17,
21 "I-state": 18,
22 "B-sub_locality": 19,
23 "I-sub_locality": 20,
24 "B-landmarks": 21,
25 "I-landmarks": 22
26 },
27 "id2entity": {
28 "0": "O",
29 "1": "B-building_name",
30 "2": "I-building_name",
31 "3": "B-city",
32 "4": "I-city",
33 "5": "B-country",
34 "6": "I-country",
35 "7": "B-floor",
36 "8": "I-floor",
37 "9": "B-house_details",
38 "10": "I-house_details",
39 "11": "B-locality",
40 "12": "I-locality",
41 "13": "B-pincode",
42 "14": "I-pincode",
43 "15": "B-road",
44 "16": "I-road",
45 "17": "B-state",
46 "18": "I-state",
47 "19": "B-sub_locality",
48 "20": "I-sub_locality",
49 "21": "B-landmarks",
50 "22": "I-landmarks"
51 }
52}config.json: Model configuration and hyperparameterspytorch_model.bin / model.safetensors: Model weightstokenizer.json: Tokenizer configurationtokenizer_config.json: Tokenizer settingsvocab.txt: Vocabulary fileentity_mappings.json: Entity type mappings1@misc{open-indicbert-indian-address-ner,
2 title={IndicBERT Indian Address NER Model},
3 year={2025},
4 publisher={Hugging Face},
5 url={https://huggingface.co/shiprocket-ai/open-indicbert-indian-address-ner}
6}