File size: 37,039 Bytes
60afe5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import json
import random
from datetime import date

random.seed(42)
N = 200000

# ── Large name pools (500+ first, 200+ last → 100k+ combos) ───────────────
FIRST = (
  # North
  ["Arjun","Priya","Ravi","Anjali","Vikram","Deepa","Rohit","Suresh","Meena","Aditya","Pooja","Rahul","Sneha","Kiran","Rajesh","Sunita","Manoj","Geeta","Amit","Neha","Sanjay","Kavita","Nitin","Ritu","Deepak","Preeti","Vijay","Shweta","Ajay","Swati","Gaurav","Nidhi","Alok","Poonam","Rajan","Asha","Vivek","Shalini","Pankaj","Divya","Harsh","Neelam","Akash","Rekha","Tarun","Bhavna","Lalit","Mamta","Yash","Sonia"]
  +
  # South
  ["Arun","Lakshmi","Karthik","Shanthi","Sridhar","Uma","Ganesh","Padma","Venkatesh","Saraswati","Mohan","Revathi","Balaji","Anitha","Subramaniam","Hema","Srinivas","Devi","Chandrasekhar","Radha","Narasimha","Sita","Krishna","Lalitha","Raman","Parvati","Madhav","Anandi","Dharma","Nalini","Sundar","Indira","Naresh","Leela","Vishnu","Shobha","Mahesh","Vanitha","Sekhar","Kamala"]
  +
  # East
  ["Subhash","Rina","Tapan","Mala","Pradeep","Anil","Sharmila","Siddharth","Tanushree","Bikram","Nandita","Sandip","Ananya","Debashish","Poulami","Souvik","Arijit","Rupali","Somnath","Ishita","Bappaditya","Moumita","Debraj","Sumana","Partho","Shyamali","Sudipta","Kakoli","Tathagata","Nilanjana","Sayan","Jhuma","Avijit","Keya","Satyajit","Papiya"]
  +
  # West
  ["Ashok","Jaya","Dinesh","Varsha","Prakash","Hetal","Ramesh","Komal","Rajiv","Mona","Hitesh","Madhuri","Hardik","Jhanvi","Nilesh","Tejas","Bhavna","Milind","Vandana","Siddharth","Minal","Bhavesh","Darshana","Sachin","Krutika","Yogesh","Smita","Rakesh","Sonal","Chetan","Shweta","Sandeep","Mansi","Abhishek","Manisha","Tushar","Rupal","Kishore"]
  +
  # Northeast
  ["Bibhuti","Mridula","Jitumoni","Deepali","Rongmon","Bonita","Naba","Purnima","Diganta","Arpana","Kangkan","Rupjyoti","Padmeswar","Anamika","Hiranya","Bhaswati","Mrinal","Rupali","Dhiraj","Monalisa","Bipul","Dibya","Pranab","Sulekha"]
  +
  # Muslim
  ["Mohammad","Fatima","Abdul","Ayesha","Imran","Zainab","Farhan","Sana","Irfan","Nasreen","Waseem","Shabana","Tariq","Kausar","Salman","Nadia","Faisal","Ruqayya","Junaid","Hafsa","Shahid","Rizwana","Asif","Tahira","Iqbal","Shamim","Rashid","Shagufta"]
  +
  # Christian
  ["Thomas","Joseph","Mary","Mathew","Jacob","Annamma","George","Sarah","Samuel","Ruth","John","Elizabeth","Philip","Daniel","Rachel","David","Grace","Jonathan","Teresa","Michael","Martha","Peter","Joyce","Stephen","Ann","Lazarus","Catherine","Benjamin"]
  +
  # Sikh
  ["Gurpreet","Manpreet","Harjit","Jaspreet","Balwinder","Simran","Kulwinder","Amandeep","Navjot","Ranjit","Sukhwinder","Ravinder","Tejinder","Harleen","Jagmeet","Mandeep","Harjeet","Manjeet","Jasmeet","Gagandeep","Rupinder","Harmeet","Baljinder"]
)

SURNAMES = [
  "Sharma","Gupta","Singh","Verma","Kumar","Mishra","Agarwal",
  "Krishnamurthy","Iyer","Nair","Reddy","Pillai","Menon","Naidu",
  "Chatterjee","Banerjee","Mukherjee","Das","Bose","Sen",
  "Patil","Desai","Joshi","Shah","Mehta","Patel",
  "Bora","Saikia","Hazarika","Deka","Gogoi",
  "Khan","Ansari","Sheikh","Fernandes","DSouza","Lobo","Mathew",
  "Kaur","Chopra","Malhotra","Saxena","Bajaj","Kapoor","Tandon",
  "Acharya","Rao","Sastry","Nayak","Prasad","Murthy","Shetty",
  "Bhatt","Trivedi","Thakkar","Gandhi","Modi","Chauhan","Solanki",
  "Goswami","Bhattacharya","Choudhury","Baruah","Borah","Kalita",
  "Kazi","Mirza","Pathan","Qureshi","Siddiqui","Syed",
  "Dcruz","Pereira","Crasta","Mendes","Noronha","Salvador",
  "Dhillon","Sandhu","Sodhi","Grewal","Sethi","Bajwa","Sekhon"
]

LOCATIONS = ["Mumbai","Delhi","Bengaluru","Hyderabad","Chennai","Kolkata","Pune","Ahmedabad","Jaipur","Lucknow","Surat","Kochi","Chandigarh","Nagpur","Indore","Bhopal","Visakhapatnam","Patna","Guwahati","Thiruvananthapuram","Agra","Varanasi","Amritsar","Coimbatore","Mysore","Nashik","Vadodara","Ludhiana","Raipur","Ranchi","Bhubaneswar","Jodhpur","Madurai","Gwalior","Jabalpur","Shimla","Dehradun","Haridwar","Udaipur","Pondicherry","Tirupati","Mangalore","Kolhapur","Aurangabad","Srinagar","Jamnagar","Rajkot","Bilaspur","Durgapur","Siliguri","Panaji","Shillong","Imphal","Agartala","Aizawl","Gangtok","Itanagar","Dimapur","Port Blair","Kavaratti"]
STREETS = ["MG Road","Linking Road","Banjara Hills","JP Nagar","Koramangala","Salt Lake","Andheri West","Sector 62","Gachibowli","Whitefield","T Nagar","Connaught Place","Hauz Khas","Jubilee Hills","Marine Drive","Anna Salai","Brigade Road","Park Street","FC Road","Law Garden","Sadar Bazaar","Lajpat Nagar","Karol Bagh","Indiranagar","HSR Layout","Nungambakkam","Alwarpet","Banjara Hills","Jayanagar","Malleshwaram"]
STATES = ["Maharashtra","Karnataka","Tamil Nadu","Telangana","Uttar Pradesh","West Bengal","Gujarat","Rajasthan","Delhi","Kerala","Punjab","Haryana","Assam","Bihar","Odisha","Madhya Pradesh","Andhra Pradesh","Jharkhand","Uttarakhand","Chandigarh","Goa","Meghalaya","Manipur","Tripura","Mizoram","Nagaland","Sikkim","Arunachal Pradesh"]

# ── Name generator (allow up to 3 repeats per combo) ───────────────────────
_name_counts = {}

def fresh_name():
    max_tries = 200
    for _ in range(max_tries):
        f = random.choice(FIRST)
        s = random.choice(SURNAMES)
        n = f"{f} {s}"
        c = _name_counts.get(n, 0)
        if c < 3:
            _name_counts[n] = c + 1
            return n
    # If all combos saturated (extremely unlikely at 200k scale), use middle name
    f = random.choice(FIRST)
    m = random.choice(FIRST)
    s = random.choice(SURNAMES)
    n = f"{f} {m} {s}"
    c = _name_counts.get(n, 0)
    _name_counts[n] = c + 1
    return n

# ── Value generators ────────────────────────────────────────────────────────
DOMAINS = ["gmail.com","yahoo.co.in","outlook.com","hotmail.com","rediffmail.com","zoho.com","protonmail.com","company.com","icloud.com","fastmail.com","co.in","org.in","ac.in","gov.in","edu.in"]
UPI_HANDLES = ["okicici","ybl","paytm","okaxis","hdfcbank","icici","axl","upi","ibl","yesbank","sbi","kotak","idfc","pnb","boi","airtel","freecharge","cred"]
VEHICLE_STATES = ["MH","DL","KA","TN","TS","AP","GJ","RJ","UP","WB","KL","HR","PB","MP","OR","BR"]
VEHICLE_LETTERS = ["AB","CD","EF","GH","JK","LM","NP","PQ","RS","TU","VW","XY","ZA","BC","DE","FG","HI"]
VEHICLE_LETTERS2 = ["AA","BB","CC","DD","EE","FF","GG","HH","IJ","KL","MN"]
PASSPORT_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DL_STATES = ["MH","DL","KA","TN","GJ","UP","HR","RJ","WB","KL","PB","AP"]
API_PREFIXES = ["sk-prod-","sk-test-","pk_live_","sk_live_","AIzaSyD","ghp_","api_v1_","secret_","tok_"]
API_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
PASSWORDS = ["P@ssw0rd","Secure#123","Welcome@1","Admin!2024","Pass@123","Qwerty!1","LetMeIn#7","Chang3M3!","C0mpl3x!","Rahul@123","Priya#2024","Maskara#1","India@123"]
DOB_FORMATS = ["%d/%m/%Y","%d-%m-%Y","%Y-%m-%d","%d-%b-%Y","%b %d, %Y","%d %B %Y"]
CREDIT_PREFIXES = ["4000","4111","4242","4532","4916","5018","5020","5038","5123","5211","5345","6011","6222","6500"]
PAN_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

# Pre-generated random values for non-semantic placeholders
RANDINT_CACHE = {}

def randint_cached(a, b):
    return random.randint(a, b)

def gen_email(name):
    parts = name.lower().split()
    base = f"{parts[0]}.{parts[1]}" if len(parts) >= 2 else parts[0]
    return f"{base}@{random.choice(DOMAINS)}"

def gen_aadhaar():
    return f"{random.randint(1000,9999)} {random.randint(1000,9999)} {random.randint(1000,9999)}"

def gen_pan():
    return f"{random.choice(PAN_LETTERS)}{random.choice(PAN_LETTERS)}{random.choice(PAN_LETTERS)}{random.choice(PAN_LETTERS)}{random.choice(PAN_LETTERS)}{random.randint(1000,9999)}{random.choice(PAN_LETTERS)}"

def gen_phone():
    p = random.randint(6000000000, 9999999999)
    r = random.random()
    if r < 0.33:
        return f"+91 {p}"
    elif r < 0.55:
        return f"+91-{p}"
    elif r < 0.7:
        return f"0{random.randint(70,99)}-{random.randint(1000000,9999999)}"
    return str(p)

def gen_upi():
    p = random.choice(FIRST).lower()
    if random.random() < 0.3:
        p += "." + random.choice(SURNAMES).lower()
    return f"{p}@{random.choice(UPI_HANDLES)}"

def gen_vehicle():
    if random.random() < 0.5:
        st = random.choice(VEHICLE_STATES)
        return f"{st} {random.randint(1,99):02d} {random.choice(VEHICLE_LETTERS)} {random.randint(1,9999):04d}"
    return f"{random.choice(['DL','MH','KA','TN'])}-{random.randint(1,11)}{random.choice(['C','A','B','D','E','F','G','H'])}-{random.choice(VEHICLE_LETTERS2)}-{random.randint(1,9999):04d}"

def gen_cc():
    return f"{random.choice(CREDIT_PREFIXES)} {random.randint(1000,9999)} {random.randint(1000,9999)} {random.randint(1000,9999)}"

_dob_cache = {}
def gen_dob():
    d = random.randint(1,28)
    m = random.randint(1,12)
    y = random.randint(1955,2005)
    fmt = random.choice(DOB_FORMATS)
    return date(y,m,d).strftime(fmt)

# ── Template system ─────────────────────────────────────────────────────────
# Pre-parse templates into text/placeholder parts for O(1) entity positioning

# (template, slots, is_hindi)
TEMPLATE_DEFS = [
    ("My name is {name} and my email is {email}. You can reach me at {phone}.", [("name","PERSON_NAME"),("email","EMAIL"),("phone","PHONE")], False),
    ("Applicant: {name}, DOB: {dob}. Contact: {phone} or {email}.", [("name","PERSON_NAME"),("dob","DATE_OF_BIRTH"),("phone","PHONE"),("email","EMAIL")], False),
    ("Patient: {name}, Aadhaar: {aadhaar}. DOB: {dob}. Blood group: O+ve.", [("name","PERSON_NAME"),("aadhaar","AADHAAR"),("dob","DATE_OF_BIRTH")], False),
    ("PAN Card: {pan}. Name: {name}. DOB: {dob}.", [("pan","PAN_CARD"),("name","PERSON_NAME"),("dob","DATE_OF_BIRTH")], False),
    ("Ship to: {name}, {addr}. Phone: {phone}.", [("name","PERSON_NAME"),("addr","ADDRESS"),("phone","PHONE")], False),
    ("{name}, UPI: {upi}. Please send the payment confirmation.", [("name","PERSON_NAME"),("upi","UPI_ID")], False),
    ("Vehicle Reg: {veh}. Owner: {name}. Insurance valid till 12/2026.", [("veh","VEHICLE_REG"),("name","PERSON_NAME")], False),
    ("Passport No: {passport}. Issued to {name}. Valid until 2032.", [("passport","PASSPORT"),("name","PERSON_NAME")], False),
    ("CC: {cc} | Exp: 05/27 | CVV: 123 | Cardholder: {name}", [("cc","CREDIT_CARD"),("name","PERSON_NAME")], False),
    ("User {user} logged in from IP {ip}. API key: {api}.", [("user","USERNAME"),("ip","IP_ADDRESS"),("api","API_KEY")], False),
    ("SSN: {ssn} | DL: {dl} | Name: {name}", [("ssn","SSN"),("dl","DRIVER_LICENSE"),("name","PERSON_NAME")], False),
    ("Customer: {name}. Aadhaar: {aadhaar}. Registered mobile: {phone}.", [("name","PERSON_NAME"),("aadhaar","AADHAAR"),("phone","PHONE")], False),
    ("Username: {user}, Password: {pw}. URL: https://internal.company.com/login", [("user","USERNAME"),("pw","PASSWORD")], False),
    ("Hey this is {name} — call me at {phone} or email {email}. Thanks!", [("name","PERSON_NAME"),("phone","PHONE"),("email","EMAIL")], False),
    ("Contact {name} at {addr}. Landline: {phone}.", [("name","PERSON_NAME"),("addr","ADDRESS"),("phone","PHONE")], False),
    ("Dr. {name} | Degrees: MBBS, MD | P: {phone} | E: {email}", [("name","PERSON_NAME"),("phone","PHONE"),("email","EMAIL")], False),
    ("Applicant: {name}, Passport: {passport}, DOB: {dob}, Nationality: Indian.", [("name","PERSON_NAME"),("passport","PASSPORT"),("dob","DATE_OF_BIRTH")], False),
    ("Payment of ₹{amount} received from {name} via UPI {upi}.", [("amount","IGNORE"),("name","PERSON_NAME"),("upi","UPI_ID")], False),
    ("Booked bus ticket for {name}, contact {phone}. Boarding: {loc}.", [("name","PERSON_NAME"),("phone","PHONE")], False),
    ("Electricity bill — Consumer: {name}, Address: {addr}, Phone: {phone}", [("name","PERSON_NAME"),("addr","ADDRESS"),("phone","PHONE")], False),
    ("GSTIN: {gstin} | Name: {name} | PAN: {pan}", [("name","PERSON_NAME"),("pan","PAN_CARD")], False),
    ("ERROR [{ts}]: User {user} failed login attempt from IP {ip}.", [("user","USERNAME"),("ip","IP_ADDRESS")], False),
    ("Hi, this is {name} from {city}. My UPI is {upi} and my Aadhaar is {aadhaar}.", [("name","PERSON_NAME"),("upi","UPI_ID"),("aadhaar","AADHAAR")], False),
    ("{name} | LIC Policy: {lic} | DOB: {dob} | Contact: {phone}", [("name","PERSON_NAME"),("dob","DATE_OF_BIRTH"),("phone","PHONE")], False),
    ("Returning order from {name}. Delivery: {addr}. OTP: {otp}.", [("name","PERSON_NAME"),("addr","ADDRESS")], False),
    ("Car {veh} challan issued to {name}. Fine: ₹{fine}. Pay via {upi}.", [("veh","VEHICLE_REG"),("name","PERSON_NAME"),("upi","UPI_ID")], False),
    ("SBI Account #{acct} | Name: {name} | PAN: {pan} | Mobile: {phone}", [("name","PERSON_NAME"),("pan","PAN_CARD"),("phone","PHONE")], False),
    ("Voter ID: {voter} | Name: {name} | Address: {addr}", [("name","PERSON_NAME"),("addr","ADDRESS")], False),
    ("Rental agreement — Tenant: {name}, Rent: ₹{rent}/month, Landlord: {phone}", [("name","PERSON_NAME"),("phone","PHONE")], False),
    ("Interview scheduled for {name} on {dob} at 10AM. Contact: {phone}, email: {email}.", [("name","PERSON_NAME"),("dob","DATE_OF_BIRTH"),("phone","PHONE"),("email","EMAIL")], False),
    ("DB backup completed by {user}. Server: {ip}.", [("user","USERNAME"),("ip","IP_ADDRESS")], False),
    ("SSN: {ssn} owed by {name}. Last known address: {addr}.", [("ssn","SSN"),("name","PERSON_NAME"),("addr","ADDRESS")], False),
    ("Driver's License: {dl} | Name: {name} | DOB: {dob}", [("dl","DRIVER_LICENSE"),("name","PERSON_NAME"),("dob","DATE_OF_BIRTH")], False),
    ("USER: {user} / PASS: {pw} | DO NOT SHARE", [("user","USERNAME"),("pw","PASSWORD")], False),
    ("Dear {name}, your policy #{lic} premium of ₹{amount} is due. Pay via {upi}.", [("name","PERSON_NAME"),("upi","UPI_ID")], False),
    ("Aadhaar: {aadhaar} | Name: {name} | DOB: {dob} | Mobile: {phone}", [("aadhaar","AADHAAR"),("name","PERSON_NAME"),("dob","DATE_OF_BIRTH"),("phone","PHONE")], False),
    ("Booking confirmed for {name}. E-ticket sent to {email}.", [("name","PERSON_NAME"),("email","EMAIL")], False),
    ("Hotel reservation: Guest {name}, Contact: {phone}, Check-in: 12-Apr-2026", [("name","PERSON_NAME"),("phone","PHONE")], False),
    ("Rate limit exceeded for key {api}. Request from {ip}. User: {user}.", [("api","API_KEY"),("ip","IP_ADDRESS"),("user","USERNAME")], False),
    ("Resume — {name} | E: {email} | M: {phone} | PAN: {pan} | DOB: {dob}", [("name","PERSON_NAME"),("email","EMAIL"),("phone","PHONE"),("pan","PAN_CARD"),("dob","DATE_OF_BIRTH")], False),
    ("Bank mandate — Name: {name}, Aadhaar: {aadhaar}, Mobile: {phone}", [("name","PERSON_NAME"),("aadhaar","AADHAAR"),("phone","PHONE")], False),
    ("Insurance claim — Claimant: {name}, Vehicle: {veh}, Policy: {lic}", [("name","PERSON_NAME"),("veh","VEHICLE_REG")], False),
    ("KYC pending for {name}. Aadhaar: {aadhaar}, PAN: {pan}, Phone: {phone}.", [("name","PERSON_NAME"),("aadhaar","AADHAAR"),("pan","PAN_CARD"),("phone","PHONE")], False),
    ("Sim update: {phone}, Name: {name}, ID proof: {aadhaar}", [("phone","PHONE"),("name","PERSON_NAME"),("aadhaar","AADHAAR")], False),
    ("Migration cert — Student: {name}, DOB: {dob}, Prev UID: {prev}", [("name","PERSON_NAME"),("dob","DATE_OF_BIRTH")], False),
    ("Delhi HC case #CA-{ref} | Petitioner: {name} | Counsel: {phone}", [("name","PERSON_NAME"),("phone","PHONE")], False),
    ("Flight ticket: PNR: {pnr}, Name: {name}, Seat: {seat}", [("name","PERSON_NAME")], False),
    ("UCID: {ucid} | Name: {name} | Aadhaar: {aadhaar} | DOB: {dob}", [("name","PERSON_NAME"),("aadhaar","AADHAAR"),("dob","DATE_OF_BIRTH")], False),
    # ── Hindi / Hinglish templates (15% target) ──
    ("Mera naam {name} hai aur mera email {email} hai. Phone number {phone} hai.", [("name","PERSON_NAME"),("email","EMAIL"),("phone","PHONE")], True),
    ("Main {name} hoon. Aap mujhe {phone} ya {email} par contact kar sakte hain.", [("name","PERSON_NAME"),("phone","PHONE"),("email","EMAIL")], True),
    ("Namaste, main {name} hoon. Kripya mujhe {phone} par call karein.", [("name","PERSON_NAME"),("phone","PHONE")], True),
    ("Mera naam {name} hai. Mera UPI ID {upi} hai. Payment bhej do.", [("name","PERSON_NAME"),("upi","UPI_ID")], True),
    ("{name} ji, mera Aadhaar number {aadhaar} hai. Phone {phone} hai.", [("name","PERSON_NAME"),("aadhaar","AADHAAR"),("phone","PHONE")], True),
    ("Mera naam {name} hai. Aadhaar number {aadhaar} hai aur phone {phone} hai.", [("name","PERSON_NAME"),("aadhaar","AADHAAR"),("phone","PHONE")], True),
    ("Kripya {name} ko {phone} par call karein. Email {email} hai.", [("name","PERSON_NAME"),("phone","PHONE"),("email","EMAIL")], True),
    ("Mera naam {name} hai. Passport number {passport} hai. DOB {dob}.", [("name","PERSON_NAME"),("passport","PASSPORT"),("dob","DATE_OF_BIRTH")], True),
    ("{name} ka Aadhaar {aadhaar} aur PAN {pan} hai. Mobile {phone}.", [("name","PERSON_NAME"),("aadhaar","AADHAAR"),("pan","PAN_CARD"),("phone","PHONE")], True),
    ("Mera credit card {cc} hai. Cardholder {name} hai.", [("cc","CREDIT_CARD"),("name","PERSON_NAME")], True),
    ("Login {user} hai aur password {pw} hai. Mat bhoolna.", [("user","USERNAME"),("pw","PASSWORD")], True),
    ("Hamara address {addr} hai. {name} yahaan rehte hain. Phone {phone}.", [("name","PERSON_NAME"),("addr","ADDRESS"),("phone","PHONE")], True),
    ("Mera PAN card {pan} hai aur DOB {dob} hai. Naam {name} hai.", [("pan","PAN_CARD"),("dob","DATE_OF_BIRTH"),("name","PERSON_NAME")], True),
    ("{name} ko {email} par email karo ya {phone} par call karo.", [("name","PERSON_NAME"),("email","EMAIL"),("phone","PHONE")], True),
    ("Car {veh} registraion hai. Malik {name} hai. Phone {phone}.", [("veh","VEHICLE_REG"),("name","PERSON_NAME"),("phone","PHONE")], True),
    ("SSN {ssn} hai aur DL {dl} hai. Naam {name} hai.", [("ssn","SSN"),("dl","DRIVER_LICENSE"),("name","PERSON_NAME")], True),
]

HARD_NEGATIVES = [
    "She visited the Taj Mahal last summer with her family.",
    "The company is headquartered in Bangalore and has offices in Mumbai and Pune.",
    "Please refer to Section 4.1.2 of the IT Act for data protection guidelines.",
    "The India vs Australia cricket match starts at 3 PM IST tomorrow.",
    "Our team went to the Gateway of India for the annual company picnic.",
    "The Reserve Bank of India has revised the repo rate to 6.5%.",
    "Diwali celebrations will be held on October 31st this year.",
    "The nearest metro station is MG Road, about 500 meters from here.",
    "Please ensure all documents are notarized before submission.",
    "The patient was admitted to AIIMS Delhi for cardiac evaluation.",
    "The weather in Chennai is quite humid during May and June.",
    "The Chandrayaan-4 mission is scheduled for launch next quarter.",
    "The Indian Premier League 2026 season begins in March.",
    "The Western Ghats are a UNESCO World Heritage site.",
    "The GST Council meeting is scheduled for next Friday in New Delhi.",
    "The Indian Constitution was adopted on 26 January 1950.",
    "The Himalayas stretch across five Indian states and Bhutan.",
    "The Sundarbans mangrove forest is the largest in the world.",
    "The Kerala backwaters are a popular tourist destination.",
    "The Red Fort in Delhi was built by Shah Jahan in 1648.",
    "The Qutub Minar in Delhi is the tallest brick minaret in the world.",
    "The India Gate is a war memorial located in New Delhi.",
    "The Charminar was built in 1591 by Muhammad Quli Qutb Shah.",
    "The Hawa Mahal in Jaipur is also known as the Palace of Winds.",
    "The Meenakshi Temple in Madurai is dedicated to Goddess Parvati.",
    "The Golden Temple in Amritsar is the holiest Sikh gurdwara.",
    "The Sun Temple in Konark is shaped like a massive chariot.",
    "The Elephanta Caves on Elephanta Island contain Hindu cave temples.",
    "The Ajanta and Ellora caves are UNESCO World Heritage sites in Maharashtra.",
    "The Nalanda University ruins date back to the 5th century.",
    "The Kaziranga National Park is home to the one-horned rhinoceros.",
    "The Ranthambore National Park was once a royal hunting ground.",
    "The Periyar Wildlife Sanctuary is located in the Western Ghats.",
    "The Corbett National Park is the oldest national park in India.",
    "The Ganges River originates from the Gangotri Glacier in Uttarakhand.",
    "The Brahmaputra River flows through Assam before entering Bangladesh.",
    "The Godavari is the second longest river in India after the Ganges.",
    "The Thar Desert covers most of Rajasthan and extends into Gujarat.",
    "The Western Coastal Plain lies between the Western Ghats and the Arabian Sea.",
    "The Deccan Plateau covers most of southern India.",
    "The Nilgiri Mountains form part of the Western Ghats in Tamil Nadu.",
    "The Rohtang Pass in Himachal Pradesh connects Manali to the Lahaul Valley.",
    "The Zojila Pass connects Srinagar to the Ladakh region.",
    "The Nathu La Pass connects Sikkim to Chinas Tibet Autonomous Region.",
    "The Dal Lake in Srinagar is known for its shikaras and houseboats.",
    "The Chilika Lake in Odisha is the largest coastal lagoon in India.",
    "The Loktak Lake in Manipur is known for its floating phumdis.",
    "The Pangong Lake in Ladakh changes color throughout the year.",
    "The tea gardens of Munnar stretch across rolling green hills.",
    "The Spiti Valley is one of the coldest inhabited places in India.",
    "The Valley of Flowers in Uttarakhand is a UNESCO World Heritage site.",
    "The Jantar Mantar in Jaipur is an astronomical observatory built in 1734.",
    "The Mysore Palace is illuminated with nearly 100,000 lights on Sundays.",
    "The Victoria Memorial in Kolkata was built in memory of Queen Victoria.",
    "The Sanchi Stupa in Madhya Pradesh is a UNESCO World Heritage site.",
    "The Mahabodhi Temple in Bodh Gaya marks the site of Buddhas enlightenment.",
    "The Konark Sun Temple is designed as a colossal chariot with 24 wheels.",
    "The Brihadeeswarar Temple in Thanjavur is a masterpiece of Chola architecture.",
    "The Khajuraho Group of Monuments is famous for its intricate sculptures.",
    "The Fatehpur Sikri near Agra was the capital of Emperor Akbar.",
    "The Lotus Temple in Delhi is a Bahai House of Worship.",
    "The Akshardham Temple in Delhi is the worlds largest Hindu temple complex.",
    "The ISKCON Temple in Bangalore attracts thousands of devotees daily.",
    "The Sabarimala Temple in Kerala is dedicated to Lord Ayyappa.",
    "The Tirupati Balaji Temple in Andhra Pradesh is the richest temple in India.",
    "The Ramanathaswamy Temple in Rameswaram has the longest corridor in India.",
    "The Jagannath Temple in Puri hosts the famous Rath Yatra festival.",
    "The Badrinath Temple in Uttarakhand is one of the Char Dham pilgrimage sites.",
    "The Kedarnath Temple is located in the Himalayas near the Mandakini River.",
    "The Gangotri Temple marks the origin of the Ganges River.",
    "The Yamunotri Temple is the source of the Yamuna River.",
    "The Vaishno Devi shrine in Jammu and Kashmir is visited by millions annually.",
    "The Pushkar Camel Fair in Rajasthan is one of the largest livestock fairs.",
]


SINGLE_DEFS = [
    ("PERSON_NAME", "Name: {val}", False), ("PERSON_NAME", "Signed, {val}", False), ("PERSON_NAME", "Applicant: {val}", False), ("PERSON_NAME", "Attn: {val}", False),
    ("PHONE", "Call me at {val}", False), ("PHONE", "Contact number: {val}", False), ("PHONE", "Phone: {val}", False), ("PHONE", "Mobile: {val}", False),
    ("EMAIL", "Reach out at {val}", False), ("EMAIL", "Email: {val}", False), ("EMAIL", "My email is {val}", False), ("EMAIL", "E: {val}", False),
    ("AADHAAR", "Aadhaar: {val}", False), ("AADHAAR", "Aadhaar Number: {val}", False), ("AADHAAR", "UID: {val}", False),
    ("PAN_CARD", "PAN: {val}", False), ("PAN_CARD", "PAN Card No: {val}", False),
    ("UPI_ID", "UPI ID: {val}", False), ("UPI_ID", "Send payment to {val}", False),
    ("VEHICLE_REG", "Vehicle No: {val}", False), ("VEHICLE_REG", "Reg: {val}", False), ("VEHICLE_REG", "Car plate: {val}", False),
    ("PASSPORT", "Passport: {val}", False), ("PASSPORT", "Travel document: {val}", False),
    ("USERNAME", "Login: {val}", False), ("USERNAME", "Username: {val}", False), ("USERNAME", "User ID: {val}", False),
    ("IP_ADDRESS", "IP: {val}", False), ("IP_ADDRESS", "Server IP: {val}", False), ("IP_ADDRESS", "Source: {val}", False),
    ("DATE_OF_BIRTH", "DOB: {val}", False), ("DATE_OF_BIRTH", "Date of Birth: {val}", False),
    ("DRIVER_LICENSE", "DL: {val}", False), ("DRIVER_LICENSE", "Driving License: {val}", False),
    ("SSN", "SSN: {val}", False), ("SSN", "Social Security: {val}", False),
    # Hindi / Hinglish single entity
    ("PERSON_NAME", "Mera naam {val} hai.", True),
    ("PHONE", "Mera phone number {val} hai.", True),
    ("EMAIL", "Meri email {val} hai.", True),
    ("AADHAAR", "Mera Aadhaar number {val} hai.", True),
    ("PAN_CARD", "Mera PAN card {val} hai.", True),
    ("UPI_ID", "Mera UPI ID {val} hai.", True),
]

# ── Parse templates into parts ──────────────────────────────────────────────
import re as _re
_PH_RE = _re.compile(r"\{(\w+)\}")

class ParsedTemplate:
    __slots__ = ("parts", "entity_slots", "is_hindi")
    def __init__(self, tmpl, slot_defs, is_hindi=False):
        self.is_hindi = is_hindi
        self.parts = []
        self.entity_slots = []
        slot_map = dict(slot_defs)
        pos = 0
        last_end = 0
        for m in _PH_RE.finditer(tmpl):
            if m.start() > last_end:
                txt = tmpl[last_end:m.start()]
                self.parts.append(("text", txt))
                pos += len(txt)
            key = m.group(1)
            label = slot_map.get(key, "IGNORE")
            self.parts.append(("ph", key, label))
            if label != "IGNORE":
                self.entity_slots.append((key, label, pos))
            last_end = m.end()
        if last_end < len(tmpl):
            txt = tmpl[last_end:]
            self.parts.append(("text", txt))

PARSED = [ParsedTemplate(t, s, h) for t, s, h in TEMPLATE_DEFS]

# For single templates
SINGLE_PARSED = [(lbl, tmpl.replace("{val}", "{}"), hin) for lbl, tmpl, hin in SINGLE_DEFS]

# ── Generation loop ─────────────────────────────────────────────────────────
# Pre-allocate for speed
import sys

examples = []
gen_texts = set()
gen_texts_add = gen_texts.add

# Reusable value dict
def make_vals(name):
    e = gen_email(name)
    return {
        "name": name, "email": e,
        "phone": gen_phone(), "addr": None,  # filled lazily
        "aadhaar": gen_aadhaar(), "pan": gen_pan(), "dob": gen_dob(),
        "upi": gen_upi(), "veh": gen_vehicle(),
        "passport": f"{random.choice(PASSPORT_LETTERS)}{random.randint(1000000,9999999)}",
        "cc": gen_cc(), "ip": None, "api": None, "pw": None,
        "user": name.lower().split()[0] + (str(random.randint(1,999)) if random.random()<0.5 else ""),
        "dl": f"{random.choice(DL_STATES)}{random.randint(10,99)}20{random.randint(1000000,9999999)}",
        "ssn": f"{random.randint(100,999)}-{random.randint(10,99)}-{random.randint(1000,9999)}",
    }

def fill_vals(v, name):
    v["addr"] = gen_address()
    v["ip"] = f"{random.randint(10,223)}.{random.randint(0,255)}.{random.randint(0,255)}.{random.randint(1,254)}"
    v["api"] = f"{random.choice(API_PREFIXES)}{''.join(random.choice(API_CHARS) for _ in range(random.randint(12,24)))}"
    v["pw"] = random.choice(PASSWORDS) + (str(random.randint(1,999)) if random.random()<0.4 else "")

def gen_address():
    hno = random.randint(1,999)
    if random.random() < 0.5:
        hno_str = str(hno)
    else:
        hno_str = f"{hno}/{random.choice(['A','B','C','D','1','2','3'])}"
    street = random.choice(STREETS)
    loc = random.choice(LOCATIONS)
    pin = random.randint(100001, 999999)
    state = random.choice(STATES)
    return f"{hno_str}, {street}, {loc} {pin}, {state}"

# Pre-generated non-semantic values
def rand_amt(): return random.randint(500, 50000)
def rand_loc(): return random.choice(LOCATIONS)
def rand_gstin(): return f"{random.randint(10,99)}AAAAA{random.randint(1000,9999)}Z{random.choice('ABCDEFGHIJKLMN')}{random.randint(10,99)}"
def rand_ts(): return f"20{random.randint(22,26)}-{random.randint(1,12):02d}-{random.randint(1,28):02d}"
def rand_lic(): return random.randint(100000000, 999999999)
def rand_otp(): return random.randint(1000, 9999)
def rand_fine(): return random.randint(500, 5000)
def rand_acct(): return random.randint(10000000000, 99999999999)
def rand_voter(): return f"{random.choice(['ABC','DEF','GHI','JKL','MNO'])}{random.randint(1000000,9999999)}"
def rand_rent(): return random.randint(8000, 50000)
def rand_ref(): return random.randint(100000, 999999)
def rand_prev(): return random.randint(1000000, 9999999)
def rand_pnr(): return f"{random.choice(['ABC','XYZ','DEF','UVW'])}{random.randint(1000000,9999999)}"
def rand_seat(): return f"{random.randint(1,40)}{random.choice(['A','B','C','D','E','F'])}"
def rand_ucid(): return random.randint(1000000, 9999999)
def rand_conn(): return random.randint(10000000, 99999999)
def rand_amount(): return random.randint(500, 50000)

# Mapping from placeholder key to generator for non-semantic values
FILL_GENS = {
    "amount": rand_amount, "loc": rand_loc, "gstin": rand_gstin, "ts": rand_ts,
    "lic": rand_lic, "otp": rand_otp, "fine": rand_fine, "acct": rand_acct,
    "voter": rand_voter, "rent": rand_rent, "ref": rand_ref, "prev": rand_prev,
    "pnr": rand_pnr, "seat": rand_seat, "ucid": rand_ucid, "conn": rand_conn,
    "city": rand_loc,
}

# Track counts for distribution
hn_count = 0
single_count = 0
multi_count = 0
hindi_count = 0

# Pre-decide type for each example
import itertools

batch_size = 10000
print(f"Generating {N} examples...")

# Targets: 20k HN (10%), 60k single (30%), 120k multi (60%)
hn_goal = int(N * 0.10)
single_goal = int(N * 0.30)
multi_goal = N - hn_goal - single_goal

# Pre-shuffle type list for deterministic-ish mixing
type_list = (["hn"] * hn_goal + ["single"] * single_goal + ["multi"] * multi_goal)
random.shuffle(type_list)

hn_dedup = set()

for typ in type_list:
    if len(examples) >= N:
        break
    
    if typ == "hn":
        txt = random.choice(HARD_NEGATIVES)
        # Allow repeats for HNs — only dedup within recent window
        examples.append({"text": txt, "entities": []})
        hn_count += 1
        continue
    
    if typ == "single":
        lbl, tmpl, is_hindi = random.choice(SINGLE_PARSED)
        name = fresh_name()
        v = make_vals(name)
        fill_vals(v, name)
        if lbl == "PERSON_NAME": val = name
        elif lbl == "PHONE": val = v["phone"]
        elif lbl == "EMAIL": val = v["email"]
        elif lbl == "AADHAAR": val = v["aadhaar"]
        elif lbl == "PAN_CARD": val = v["pan"]
        elif lbl == "UPI_ID": val = v["upi"]
        elif lbl == "VEHICLE_REG": val = v["veh"]
        elif lbl == "PASSPORT": val = v["passport"]
        elif lbl == "USERNAME": val = v["user"]
        elif lbl == "IP_ADDRESS": val = v["ip"]
        elif lbl == "DATE_OF_BIRTH": val = v["dob"]
        elif lbl == "DRIVER_LICENSE": val = v["dl"]
        elif lbl == "SSN": val = v["ssn"]
        else: continue
        val = str(val)
        txt = tmpl.replace("{}", val)
        if txt in gen_texts:
            lbl2, tmpl2, _ = random.choice(SINGLE_PARSED)
            if lbl2 == lbl:
                txt2 = tmpl2.replace("{}", val)
                if txt2 not in gen_texts:
                    txt = txt2
                else:
                    continue
            else:
                continue
        gen_texts_add(txt)
        examples.append({"text": txt, "entities": [{"start": txt.find(val), "end": txt.find(val)+len(val), "label": lbl}]})
        single_count += 1
        if is_hindi:
            hindi_count += 1
        continue
    
    # Multi-entity
    pt = random.choice(PARSED)
    name = fresh_name()
    v = make_vals(name)
    fill_vals(v, name)
    
    text_parts = []
    entities = []
    pos = 0
    for part in pt.parts:
        if part[0] == "text":
            text_parts.append(part[1])
            pos += len(part[1])
        else:
            key, label = part[1], part[2]
            if key in v: val = str(v[key])
            elif key == "name": val = name
            elif key in FILL_GENS: val = str(FILL_GENS[key]())
            else: val = str(random.randint(100, 99999))
            text_parts.append(val)
            if label != "IGNORE":
                entities.append({"start": pos, "end": pos + len(val), "label": label})
            pos += len(val)
    
    txt = "".join(text_parts)
    if txt in gen_texts:
        continue
    gen_texts_add(txt)
    examples.append({"text": txt, "entities": entities})
    multi_count += 1
    if pt.is_hindi:
        hindi_count += 1
    
    if len(examples) % 20000 == 0:
        print(f"  Generated {len(examples)} / {N}")

# If short due to dedup, fill with multi examples (no dedup check)
shortfall = N - len(examples)
if shortfall > 0:
    print(f"  Shortfall of {shortfall}, filling with raw multi examples...")
    while len(examples) < N:
        pt = random.choice(PARSED)
        name = fresh_name()
        v = make_vals(name)
        fill_vals(v, name)
        text_parts = []
        entities = []
        pos = 0
        for part in pt.parts:
            if part[0] == "text":
                text_parts.append(part[1])
                pos += len(part[1])
            else:
                key, label = part[1], part[2]
                if key in v: val = str(v[key])
                elif key == "name": val = name
                elif key in FILL_GENS: val = str(FILL_GENS[key]())
                else: val = str(random.randint(100, 99999))
                text_parts.append(val)
                if label != "IGNORE":
                    entities.append({"start": pos, "end": pos + len(val), "label": label})
                pos += len(val)
        examples.append({"text": "".join(text_parts), "entities": entities})
        if pt.is_hindi: hindi_count += 1

# Trim to N
examples = examples[:N]

# ── Write JSONL ────────────────────────────────────────────────────────────
outpath = "/Users/somukandula/workspace/maskara-datasets/maskara-ner-dataset.jsonl"
with open(outpath, "w", buffering=1*1024*1024) as f:
    for ex in examples:
        f.write(json.dumps(ex, ensure_ascii=False) + "\n")

# ── Stats ──────────────────────────────────────────────────────────────────
label_counts = {}
zero_total = sum(1 for e in examples if len(e["entities"]) == 0)
single_total = sum(1 for e in examples if len(e["entities"]) == 1)
multi_total = sum(1 for e in examples if len(e["entities"]) > 1)
for ex in examples:
    for e in ex["entities"]:
        label_counts[e["label"]] = label_counts.get(e["label"], 0) + 1
total_entities = sum(label_counts.values())

print(f"\n{'='*50}")
print(f"Total examples: {len(examples)}")
print(f"Zero-entity (hard negs): {zero_total} ({zero_total/len(examples)*100:.1f}%)")
print(f"Single-entity: {single_total} ({single_total/len(examples)*100:.1f}%)")
print(f"Multi-entity: {multi_total} ({multi_total/len(examples)*100:.1f}%)")
print(f"Hindi/Non-English: {hindi_count}")
print(f"Total entities: {total_entities}")
repeats = sum(1 for c in _name_counts.values() if c > 1)
print(f"Unique names: {len(_name_counts)} (repeated >1: {repeats})")
print(f"\nLabel distribution:")
for lbl, cnt in sorted(label_counts.items(), key=lambda x: -x[1]):
    pct = cnt / total_entities * 100
    bar = "█" * max(1, int(pct / 2))
    print(f"  {lbl:18s} {cnt:6d} ({pct:5.1f}%) {bar}")

# Quick validation
print(f"\nValidating...")
errs = 0
for i, ex in enumerate(examples):
    for j, e in enumerate(ex["entities"]):
        s, e_idx = e["start"], e["end"]
        if s > len(ex["text"]) or e_idx > len(ex["text"]):
            print(f"  ERROR line {i}, entity {j}: out of bounds")
            errs += 1
        elif ex["text"][s:e_idx] == "":
            print(f"  ERROR line {i}, entity {j}: empty span")
            errs += 1
if errs == 0:
    print(f"  All {total_entities} entities validated OK")