File size: 30,526 Bytes
54fa0c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# from transformers import pipeline

# classifier = pipeline("token-classification", model = "bigcode/starpii", aggregation_strategy="simple")
# classifier("Hello I'm John and my IP address is 196.780.89.78")

# from transformers import AutoModelForTokenClassification, AutoTokenizer
# import torch

# # Load the pre-trained model and tokenizer
# model_name = "bigcode/starpii"
# model = AutoModelForTokenClassification.from_pretrained(model_name)
# tokenizer = AutoTokenizer.from_pretrained(model_name)

# # Prepare input text
# text = "from transformers import AutoModelForTokenClassification, AutoTokenizer import torch secretkey= cmVnrGtuOjAxOjE3MjEyODUwMjg6M0RrNjVMVGZEaGd6T0RiZ09FR3M5MEV5Tk0z ipadress= 10.83.73.87.84 email= [email protected]"
# inputs = tokenizer(text, return_tensors="pt")

# # Perform inference
# with torch.no_grad():
#     outputs = model(**inputs)

# # Get the predicted labels
# predicted_labels = torch.argmax(outputs.logits, dim=2)
# labels = [model.config.id2label[label_id] for label_id in predicted_labels[0].tolist()]

# # Print the labels
# print(labels)

# from transformers import AutoModelForTokenClassification, AutoTokenizer
# import torch

# # Load the pre-trained model and tokenizer
# model_name = "bigcode/starpii"
# model = AutoModelForTokenClassification.from_pretrained(model_name)
# tokenizer = AutoTokenizer.from_pretrained(model_name)

# # Prepare input text
# text = "from transformers import AutoModelForTokenClassification, AutoTokenizer import torch secretkey= cmVnrGtuOjAxOjE3MjEyODUwMjg6M0RrNjVMVGZEaGd6T0RiZ09FR3M5MEV5Tk0z ipadress= 10.83.73.87.84 email= [email protected]"
# inputs = tokenizer(text, return_tensors="pt")

# # Perform inference
# with torch.no_grad():
#     outputs = model(**inputs)

# # Get the predicted labels
# predicted_labels = torch.argmax(outputs.logits, dim=2)
# labels = [model.config.id2label[label_id] for label_id in predicted_labels[0].tolist()]

# # Replace IP address with the label or "IP_ADDRESS"
# output_text = text
# current_ip = ""
# for token, label in zip(inputs["input_ids"][0], labels):
#     token_text = tokenizer.decode(token).strip()
#     if label == "B-EMAIL":
#         current_ip += token_text
#     if label == "I-EMAIL":
#         current_ip += token_text
#     elif current_ip:
#         output_text = output_text.replace(current_ip, "EMAILID")
#         current_ip = ""

# print("output text",output_text)


## SAVED THE MODEL LOCALLY USING THIS CODE
## USING THIS CODE TEH HUGGINGFACE MODEL IS SAVED LOCALLY AND USED IN BELOW CODE 
## FOR TEXT AS WELL AS FILE DETECTION
# from transformers import AutoModelForTokenClassification, AutoTokenizer

# # Load the pre-trained model and tokenizer
# model_name = "bigcode/starpii"
# model = AutoModelForTokenClassification.from_pretrained(model_name)
# tokenizer = AutoTokenizer.from_pretrained(model_name)

# # Specify the directory where you want to save the model
# local_model_directory = "./nermodel"

# # Save the model and tokenizer to the local directory
# model.save_pretrained(local_model_directory)
# tokenizer.save_pretrained(local_model_directory)

# print(f"Model and tokenizer saved to {local_model_directory}")

## ABOVE COMMENTED CODE IS FOR REMOVAL!!!

# NER MODEL DETECTION FOR TEXT
from transformers import AutoModelForTokenClassification, AutoTokenizer
import torch
import os
import autopep8
import re
class code_detect_ner:
    # def textner(text):
    #     # Load the model and tokenizer from the local directory
    #     local_model_directory = "privacy/util/code_detect/ner/pii_inference/nermodel"
    #     model = AutoModelForTokenClassification.from_pretrained(local_model_directory)
    #     tokenizer = AutoTokenizer.from_pretrained(local_model_directory)

    #     # Prepare input text
    #     inputs = tokenizer(text, return_tensors="pt")

    #     # Perform inference
    #     with torch.no_grad():
    #         outputs = model(**inputs)

    #     # Get the predicted labels
    #     predicted_labels = torch.argmax(outputs.logits, dim=2)
    #     labels = [model.config.id2label[label_id] for label_id in predicted_labels[0].tolist()]

    #     # Define a mapping of entity types to placeholders
    #     entity_mapping = {
    #         "USERNAME": "<USERNAME>",
    #         "EMAIL": "<EMAIL>",
    #         "IP_ADDRESS": "<IP_ADDRESS>",
    #         "KEY": "<KEY>",
    #     }

    #     # Initialize variables
    #     redacted_text = ""
    #     current_entity = None
    #     last_token_was_special = False

    #     # Redact entities in the original text
    #     for token, label in zip(tokenizer.convert_ids_to_tokens(inputs["input_ids"][0]), labels):
    #         if token.startswith("Ġ"):
    #             last_token_was_special = True
    #             token = token[1:]  # Remove the leading "Ġ" character if present
    #         else:
    #             last_token_was_special = False

    #         if label.startswith("B-"):
    #             current_entity = label[2:]
    #             redacted_text += f" {entity_mapping.get(current_entity, current_entity)}"
    #         elif label.startswith("I-") and current_entity is not None:
    #             pass  # Skip intermediate tokens of the entity
    #         else:
    #             current_entity = None
    #             if last_token_was_special and not token.startswith("Ġ"):
    #                 redacted_text += " "
    #             redacted_text += token

    #     redacted_text = redacted_text.replace("Ġ", "")
    #     redacted_text = redacted_text.replace("č", "")
    #     redacted_text = redacted_text.replace("Ċ", "")
    #     # redacted_text = redacted_text.replace("Ċ", "")
        
        

    #     # Print the redacted text
    #     print("Redacted Text:", redacted_text.strip())
    #     return redacted_text.strip()


    def textner(text):
        # Load the model and tokenizer from the local directory
        local_model_directory = "privacy/util/code_detect/ner/pii_inference/nermodel"
        model = AutoModelForTokenClassification.from_pretrained(local_model_directory)
        tokenizer = AutoTokenizer.from_pretrained(local_model_directory)
        print("textNER", text)

        # Prepare input text
        inputs = tokenizer(text, return_tensors="pt")

        # Perform inference
        with torch.no_grad():
            outputs = model(**inputs)

        # Get the predicted labels
        predicted_labels = torch.argmax(outputs.logits, dim=2)
        labels = [model.config.id2label[label_id] for label_id in predicted_labels[0].tolist()]
        print(predicted_labels,"predicted_labels")
        print("labels",labels)
        # Define a mapping of entity types to placeholders
        entity_mapping = {
                "<USERNAME>": "<USERNAME>",
                "<EMAIL>": "<EMAIL>",
                "<IP_ADDRESS>": "<IP_ADDRESS>",
                "<KEY>": "<KEY>",
            }

       # Initialize variables
        redacted_text = ""
        current_entity = None
        last_token_was_special = False

        # Redact entities in the original text
        for token, label in zip(tokenizer.convert_ids_to_tokens(inputs["input_ids"][0]), labels):
            if token.startswith("Ġ"):
                last_token_was_special = True
                token = token[1:]  # Remove the leading "Ġ" character
            else:
                last_token_was_special = False

            if label.startswith("B-"):
                current_entity = label[2:]
                redacted_text += f"<{entity_mapping.get(current_entity, current_entity)}>"
            elif label.startswith("I-") and current_entity is not None:
                pass  # Skip intermediate tokens of the entity
            else:
                current_entity = None
                if last_token_was_special and not token.startswith("Ġ"):
                    redacted_text += " "
                redacted_text += token

        # Print the redacted text
        #code_detect_ner.filener("privacy/util/code_detect/ner/pii_inference/input_code.java")
        redacted_text = redacted_text.replace("Ġ", "")
        redacted_text = redacted_text.replace("č", "")
        redacted_text = redacted_text.replace("Ċ", "")
        print("Redacted Text:", redacted_text.strip())
        return redacted_text

    # def filener(input_code_file):
    #     ## NER DETECTION FROM FILE BUT FOR BIG CODE!!!!!!!!!!!!!!
    #     from transformers import AutoModelForTokenClassification, AutoTokenizer
    #     import torch

    #     # Load the model and tokenizer from the local directory
    #     local_model_directory = "privacy/util/code_detect/ner/pii_inference/nermodel"
    #     model = AutoModelForTokenClassification.from_pretrained(local_model_directory)
    #     tokenizer = AutoTokenizer.from_pretrained(local_model_directory, model_max_length=10000)

    #     # Specify the input code file
    #     #input_code_file = "input_code.java"
    #     # input_code_file = "input.py"

    #     # Read the code from the file
    #     with open(input_code_file, "r", encoding="utf-8") as file:
    #         code = file.read()
    #     #code = input_code_file.file.read()

    #     # Define a chunk size (adjust as needed)
    #     chunk_size = 1000

    #     # Initialize the redacted text
    #     redacted_text = ""
    #     current_entity = None
    #     last_token_was_special = False

    #     # Split the code into chunks
    #     code_chunks = [code[i:i + chunk_size] for i in range(0, len(code), chunk_size)]

    #     # Process each chunk
    #     for i, chunk in enumerate(code_chunks):
    #         # Prepare input text
    #         inputs = tokenizer(chunk, return_tensors="pt")

    #         # Perform inference
    #         with torch.no_grad():
    #             outputs = model(**inputs)

    #         # Get the predicted labels
    #         predicted_labels = torch.argmax(outputs.logits, dim=2)
    #         labels = [model.config.id2label[label_id] for label_id in predicted_labels[0].tolist()]

    #         # Define a mapping of entity types to placeholders
    #         entity_mapping = {
    #             "NAME": "<NAME>",
    #             "EMAIL": "<EMAIL>",
    #             "IP_ADDRESS": "<IP_ADDRESS>",
    #         }

    #         # Redact entities in the original text
    #         for token, label in zip(tokenizer.convert_ids_to_tokens(inputs["input_ids"][0]), labels):
    #             if token.startswith("Ġ"):
    #                 last_token_was_special = True
    #                 token = token[1:]  # Remove the leading "Ġ" character
    #             else:
    #                 last_token_was_special = False

    #             # Add space if the last token was a special token and the current token does not start with "<"
    #             if last_token_was_special and not token.startswith("<"):
    #                 redacted_text += " "

    #             if label.startswith("B-"):
    #                 current_entity = label[2:]
    #                 redacted_text += f"{entity_mapping.get(current_entity, current_entity)}"
    #             elif label.startswith("I-") and current_entity is not None:
    #                 pass  # Skip intermediate tokens of the entity
    #             else:
    #                 current_entity = None
    #                 redacted_text += token

    #     # Split the redacted text into lines and add indentation
    #     redacted_lines = redacted_text.split("Ċ")
    #     formatted_redacted_text = ""
    #     indentation = 0

    #     for line in redacted_lines:
    #         if "{" in line:
    #             formatted_redacted_text += "    " * indentation + line + "\n"
    #             indentation += 1
    #         elif "}" in line:
    #             indentation -= 1
    #             formatted_redacted_text += "    " * indentation + line + "\n"
    #         else:
    #             formatted_redacted_text += "    " * indentation + line + "\n"

    #     # Remove any remaining special characters
    #     formatted_redacted_text = formatted_redacted_text.replace("Ġ", "")

    #     # # Write the redacted code back to the file using UTF-8 encoding
    #     # output_code_file = "redacted_code.java"
    #     # with open(output_code_file, "a", encoding="utf-8") as file:
    #     #     file.write(formatted_redacted_text.strip())
    #     # Generate the output file name based on the input file name
    #     output_code_file = os.path.splitext(input_code_file)[0] + "_redacted" + os.path.splitext(input_code_file)[1]

    #     # Write the redacted code back to the file using UTF-8 encoding
    #     with open(output_code_file, "w", encoding="utf-8") as file:
    #         file.write(formatted_redacted_text.strip())
    #     # Delete the temporary input code file
    #     os.remove(input_code_file)
    #     # Print the final redacted text
    #     print("Redacted Text:", formatted_redacted_text.strip())
    #     return output_code_file





    # def filener(code_content, filename):
    #     # Load the model and tokenizer from the local directory
    #     local_model_directory = "privacy/util/code_detect/ner/pii_inference/nermodel"
    #     model = AutoModelForTokenClassification.from_pretrained(local_model_directory)
    #     tokenizer = AutoTokenizer.from_pretrained(local_model_directory, model_max_length=10000)

    #     # Define a chunk size (adjust as needed)
    #     chunk_size = 1000

    #     # Initialize the redacted text
    #     redacted_text = ""
    #     current_entity = None
    #     last_token_was_special = False

    #     # Split the code into chunks
    #     code_chunks = [code_content[i:i + chunk_size] for i in range(0, len(code_content), chunk_size)]

    #     # Process each chunk
    #     for i, chunk in enumerate(code_chunks):
    #         # Prepare input text
    #         chunk_str = chunk.decode("utf-8")
    #         inputs = tokenizer(chunk_str, return_tensors="pt")

    #         # Perform inference
    #         with torch.no_grad():
    #             outputs = model(**inputs)

    #         # Get the predicted labels
    #         predicted_labels = torch.argmax(outputs.logits, dim=2)
    #         labels = [model.config.id2label[label_id] for label_id in predicted_labels[0].tolist()]

    #         # Define a mapping of entity types to placeholders
    #         entity_mapping = {
    #             "NAME": "<NAME>",
    #             "EMAIL": "<EMAIL>",
    #             "IP_ADDRESS": "<IP_ADDRESS>",
    #         }

    #         # Redact entities in the original text
    #         for token, label in zip(tokenizer.convert_ids_to_tokens(inputs["input_ids"][0]), labels):
    #             if token.startswith("Ġ"):
    #                 last_token_was_special = True
    #                 token = token[1:]  # Remove the leading "Ġ" character
    #             else:
    #                 last_token_was_special = False

    #             # Add space if the last token was a special token and the current token does not start with "<"
    #             if last_token_was_special and not token.startswith("<"):
    #                 redacted_text += " "

    #             if label.startswith("B-"):
    #                 current_entity = label[2:]
    #                 redacted_text += f"{entity_mapping.get(current_entity, current_entity)}"
    #             elif label.startswith("I-") and current_entity is not None:
    #                 pass  # Skip intermediate tokens of the entity
    #             else:
    #                 current_entity = None
    #                 redacted_text += token

    #     # Split the redacted text into lines and add indentation
    #     redacted_lines = redacted_text.split("Ċ")
    #     formatted_redacted_text = ""
    #     indentation = 0
        
    #     for line in redacted_lines:
    #         if "{" in line:
    #             formatted_redacted_text += "    " * indentation + line + "\n"
    #             indentation += 1
    #         elif "}" in line:
    #             indentation -= 1
    #             formatted_redacted_text += "    " * indentation + line + "\n"
    #         else:
    #             formatted_redacted_text += "    " * indentation + line + "\n"

    #     # Remove any remaining special characters
    #     formatted_redacted_text = formatted_redacted_text.replace("Ġ", "")
    #     formatted_redacted_text = formatted_redacted_text.replace("č", "")
    #     print("formatted_redacted_text",formatted_redacted_text)
    #     # Generate the output file name based on the input file name
    #     output_code_file = os.path.splitext(filename)[0] + "_redacted" + os.path.splitext(filename)[1]

    #     # Write the redacted code back to the file using UTF-8 encoding
    #     with open(output_code_file, "w", encoding="utf-8") as file:
    #         file.write(formatted_redacted_text.strip())

    #     # Return the redacted text and the output code file name
    #     return formatted_redacted_text.strip().encode("utf-8"), output_code_file
    

    

    # def filener(code_content, filename):
    #     # Load the model and tokenizer from the local directory
    #     local_model_directory = "privacy/util/code_detect/ner/pii_inference/nermodel"
    #     model = AutoModelForTokenClassification.from_pretrained(local_model_directory)
    #     tokenizer = AutoTokenizer.from_pretrained(local_model_directory, model_max_length=10000)

    #     # Define a chunk size (adjust as needed)
    #     chunk_size = 1000

    #     # Initialize the redacted text
    #     redacted_text = ""
    #     current_entity = None
    #     last_token_was_special = False

    #     # Split the code into chunks
    #     code_chunks = [code_content[i:i + chunk_size] for i in range(0, len(code_content), chunk_size)]

    #     # Process each chunk
    #     for i, chunk in enumerate(code_chunks):
    #         # Prepare input text
    #         chunk_str = chunk.decode("utf-8")
    #         inputs = tokenizer(chunk_str, return_tensors="pt")

    #         # Perform inference
    #         with torch.no_grad():
    #             outputs = model(**inputs)

    #         # Get the predicted labels
    #         predicted_labels = torch.argmax(outputs.logits, dim=2)
    #         labels = [model.config.id2label[label_id] for label_id in predicted_labels[0].tolist()]

    #         # Define a mapping of entity types to placeholders
    #         entity_mapping = {
    #             "NAME": "<NAME>",
    #             "EMAIL": "<EMAIL>",
    #             "IP_ADDRESS": "<IP_ADDRESS>"
    #         }

    #         # Redact entities in the original text
    #         for token, label in zip(tokenizer.convert_ids_to_tokens(inputs["input_ids"][0]), labels):
    #             if token.startswith("Ġ"):
    #                 last_token_was_special = True
    #                 token = token[1:]  # Remove the leading "Ġ" character
    #             else:
    #                 last_token_was_special = False

    #             # Add space if the last token was a special token and the current token does not start with "<"
    #             if last_token_was_special and not token.startswith("<"):
    #                 redacted_text += " "

    #             if label.startswith("B-"):
    #                 current_entity = label[2:]
    #                 redacted_text += f"{entity_mapping.get(current_entity, current_entity)}"
    #             elif label.startswith("I-") and current_entity is not None:
    #                 pass  # Skip intermediate tokens of the entity
    #             else:
    #                 current_entity = None
    #                 redacted_text += token

    #     # Split the redacted text into lines and add indentation
    #     redacted_lines = redacted_text.split("Ċ")
    #     formatted_redacted_text = ""
    #     indentation = 0

    #     for line in redacted_lines:
    #         line = line.strip()

    #         if line.startswith(" "):
    #             formatted_line = "    " * indentation + line + "\n"
    #         elif line.startswith("#"):
    #             formatted_line = "    " * indentation + line + "\n"
    #         else:
    #             formatted_line = line + "\n"

    #         # Adjust indentation based on braces
    #         if "{" in line:
    #             indentation += 1
    #         elif "}" in line:
    #             indentation = max(0, indentation - 1)

    #         formatted_redacted_text += formatted_line

    #     # Remove any remaining special characters
    #     formatted_redacted_text = formatted_redacted_text.replace("Ġ", "")
    #     formatted_redacted_text = formatted_redacted_text.replace("č", "")

    #     # Generate the output file name based on the input file name
    #     output_code_file = os.path.splitext(filename)[0] + "_redacted" + os.path.splitext(filename)[1]

    #     # Write the formatted redacted code back to the file using UTF-8 encoding
    #     with open(output_code_file, "w", encoding="utf-8") as file:
    #         file.write(formatted_redacted_text.strip())

    #     # Use autopep8 to format the code in-place
    #     with open(output_code_file, "r", encoding="utf-8") as file:
    #         code_content = file.read()

    #     formatted_code = autopep8.fix_code(
    #         code_content,
    #         options={
    #             'aggressive': 1,
    #             'max_line_length': 120,  # Adjust this based on your desired line length
    #         }
    #     )

    #     # Write the formatted code back
    #     with open(output_code_file, "w", encoding="utf-8") as file:
    #         file.write(formatted_code)
            
    #     print("FORMCODE","\n",formatted_code)
    #     # Return the redacted text and the output code file name
    #     return formatted_code.encode("utf-8"), output_code_file
    
    def filener(code_content, filename,model,tokenizer):
        # Load the model and tokenizer from the local directory
        # local_model_directory = "privacy/util/code_detect/ner/pii_inference/nermodel"
        # model = AutoModelForTokenClassification.from_pretrained(local_model_directory)
        # tokenizer = AutoTokenizer.from_pretrained(local_model_directory, model_max_length=10000)

        # Define a chunk size (adjust as needed)
        chunk_size = 1000
        # Initialize the redacted text
        redacted_text = ""
        current_entity = None
        last_token_was_special = False

        # Split the code into chunks
        code_chunks = [code_content[i:i + chunk_size] for i in range(0, len(code_content), chunk_size)]

        # Process each chunk
        for i, chunk in enumerate(code_chunks):
            # Prepare input text
            chunk_str = chunk.decode("utf-8")
            inputs = tokenizer(chunk_str, return_tensors="pt")

            # Perform inference
            with torch.no_grad():
                outputs = model(**inputs)

            # Get the predicted labels
            predicted_labels = torch.argmax(outputs.logits, dim=2)
            labels = [model.config.id2label[label_id] for label_id in predicted_labels[0].tolist()]
            # Define a mapping of entity types to placeholders
            entity_mapping = {
                "USERNAME": "<USERNAME>",
                "EMAIL": "<EMAIL>",
                "IP_ADDRESS": "<IP_ADDRESS>",
                "KEY": "<KEY>",
                "NAME": "<NAME>"
            }

            # Redact entities in the original text
            for token, label in zip(tokenizer.convert_ids_to_tokens(inputs["input_ids"][0]), labels):
                if token.startswith("Ġ"):
                    last_token_was_special = True
                    token = token[1:]  # Remove the leading "Ġ" character
                else:
                    last_token_was_special = False

                # Add space if the last token was a special token and the current token does not start with "<"
                if last_token_was_special and not token.startswith("<"):
                    redacted_text += " "

                if label.startswith("B-"):
                    current_entity = label[2:]
                    redacted_text += f"{entity_mapping.get(current_entity, current_entity)}"
                elif label.startswith("I-") and current_entity is not None:
                    pass  # Skip intermediate tokens of the entity
                else:
                    current_entity = None
                    redacted_text += token

        # Split the redacted text into lines and add indentation
        redacted_lines = redacted_text.split("Ċ")
        formatted_redacted_text = ""
        indentation = 0

        for line in redacted_lines:
            print("line--",line +"\n")
            line = line.strip()

            if line.startswith(" "):
                formatted_line = "  " * indentation + line + "\n"
            elif line.startswith('Ġ'):
                formatted_line = " " + line + "\n"
            elif line.startswith('ĉ'):
                formatted_line = "        " + line + "\n"
            elif line.startswith("#"):
                formatted_line = "    " * indentation + line + "\n"    
            else:
                formatted_line = " " + line + "\n"
            print("--formatted line--",formatted_line)
            # Adjust indentation based on braces
            if "{" in line:
                indentation += 1
            elif "}" in line:
                indentation = max(0, indentation - 1)

            # Check if the line ends with a colon, indicating the start of a block
            if line.endswith(":"):
                indentation += 1

            formatted_redacted_text += formatted_line
        # Remove any remaining special characters
        
        formatted_redacted_text = formatted_redacted_text.replace("Ġ", " ")
        print("to be removed chars--",formatted_redacted_text)

        formatted_redacted_text = formatted_redacted_text.replace("č", " ")
        formatted_redacted_text = formatted_redacted_text.replace("ĉ", " ") 
        redacted_text = formatted_redacted_text.replace("Ċ", " ")
        #print("formatted text",formatted_redacted_text)
        # Generate the output file name based on the input file name
        output_code_file = os.path.splitext(filename)[0] + "_redacted" + os.path.splitext(filename)[1]

        # Write the formatted redacted code back to the file using UTF-8 encoding
        with open(output_code_file, "w", encoding="utf-8") as file:
            file.write(formatted_redacted_text.strip())

        # Use autopep8 to format the code in-place
        with open(output_code_file, "r", encoding="utf-8") as file:
            code_content = file.read()

        formatted_code = autopep8.fix_code(
            code_content,
            options={
                'aggressive': 1,
                'max_line_length': 120,  # Adjust this based on your desired line length
            }
        )

        # Write the formatted code back
        with open(output_code_file, "w", encoding="utf-8") as file:
            file.write(formatted_code)
        # print("FORMATTED CODE","\n", formatted_code)
        # Return the redacted text and the output code file name
        return formatted_code.encode("utf-8"), output_code_file




## FOR FILE WORKING
# from transformers import AutoModelForTokenClassification, AutoTokenizer
# import torch

# # Load the model and tokenizer from the local directory
# local_model_directory = "./nermodel"
# model = AutoModelForTokenClassification.from_pretrained(local_model_directory)
# tokenizer = AutoTokenizer.from_pretrained(local_model_directory,model_max_length=10000)

# # Specify the input code file
# input_code_file = "input_code.java"
# #input_code_file = "input.py"
# # Read the code from the file
# with open(input_code_file, "r", encoding="utf-8") as file:
#     code = file.read()

# # Prepare input text
# inputs = tokenizer(code, return_tensors="pt")
# # print("INPUT IDS",inputs["input_ids"].shape)
# # print("MODEL CONFIG",model.config)
# # print("TOKENIZER",tokenizer)
# # Perform inference
# with torch.no_grad():
#     outputs = model(**inputs)

# # Get the predicted labels
# predicted_labels = torch.argmax(outputs.logits, dim=2)
# labels = [model.config.id2label[label_id] for label_id in predicted_labels[0].tolist()]

# # Define a mapping of entity types to placeholders
# entity_mapping = {
#     "NAME": "<NAME>",
#     "EMAIL": "<EMAIL>",
#     "IP_ADDRESS": "<IP_ADDRESS>",
# }

# # Initialize variables
# redacted_text = ""
# current_entity = None
# last_token_was_special = False

# # Redact entities in the original text
# for token, label in zip(tokenizer.convert_ids_to_tokens(inputs["input_ids"][0]), labels):
#     if token.startswith("Ġ"):
#         last_token_was_special = True
#         token = token[1:]  # Remove the leading "Ġ" character
#     else:
#         last_token_was_special = False

#     # Add space if the last token was a special token and the current token does not start with "<"
#     if last_token_was_special and not token.startswith("<"):
#         redacted_text += " "

#     if label.startswith("B-"):
#         current_entity = label[2:]
#         redacted_text += f"{entity_mapping.get(current_entity, current_entity)}"
#     elif label.startswith("I-") and current_entity is not None:
#         pass  # Skip intermediate tokens of the entity
#     else:
#         current_entity = None
#         redacted_text += token


# # Split the redacted text into lines and add indentation
# redacted_lines = redacted_text.split("Ċ")
# formatted_redacted_text = ""
# indentation = 0

# for line in redacted_lines:
#     if "{" in line:
#         formatted_redacted_text += "    " * indentation + line + "\n"
#         indentation += 1
#     elif "}" in line:
#         indentation -= 1
#         formatted_redacted_text += "    " * indentation + line + "\n"
#     else:
#         formatted_redacted_text += "    " * indentation + line + "\n"

# # Remove any remaining special characters
# formatted_redacted_text = formatted_redacted_text.replace("Ġ", "")

# # Write the redacted code back to the file using UTF-8 encoding
# output_code_file = "redacted_code.java"
# #output_code_file = "x.py"
# with open(output_code_file, "w", encoding="utf-8") as file:
#     file.write(formatted_redacted_text.strip())

# # Print the redacted text
# print("Redacted Text:", formatted_redacted_text.strip())