File size: 34,962 Bytes
f1427c2
 
 
 
 
 
 
 
 
 
 
 
 
39f25b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8d76df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdc2d24
 
 
be20a8c
 
e224c96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ab1b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6659f73
a5e25ce
e75a7af
 
 
 
 
 
 
 
 
6659f73
 
 
e75a7af
 
 
 
 
 
 
 
 
 
6659f73
e75a7af
 
 
 
 
 
 
 
 
 
 
 
 
6659f73
e75a7af
6659f73
e75a7af
 
 
80b0eee
 
 
 
 
 
 
 
 
 
e75a7af
80b0eee
e75a7af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80b0eee
e75a7af
 
 
 
 
 
 
6659f73
e75a7af
 
 
6659f73
e75a7af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6659f73
bee9831
ca9aa54
 
 
 
 
 
 
 
 
6659f73
ca9aa54
 
 
 
 
 
6659f73
ca9aa54
 
 
 
 
 
 
 
 
 
 
 
 
 
6659f73
ca9aa54
 
 
 
 
 
6659f73
ca9aa54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6659f73
ca9aa54
6659f73
ca9aa54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6659f73
ca9aa54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6659f73
ca9aa54
6659f73
ca9aa54
 
 
 
 
6659f73
ca9aa54
 
 
 
 
 
 
6659f73
 
ca9aa54
80b0eee
 
 
 
 
 
 
13ea9f9
dd79e85
8c184cc
ad444e5
80b0eee
8c184cc
80b0eee
 
 
6659f73
80b0eee
 
8c184cc
80b0eee
8c184cc
80b0eee
8c184cc
80b0eee
 
 
 
 
 
 
8c184cc
6659f73
 
80b0eee
8c184cc
 
80b0eee
8c184cc
 
 
 
80b0eee
8c184cc
80b0eee
 
8c184cc
80b0eee
 
 
 
 
8c184cc
80b0eee
 
f2ee8f0
8c184cc
f2ee8f0
 
 
 
 
6659f73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c184cc
f2ee8f0
 
6659f73
f2ee8f0
ca9aa54
f2ee8f0
 
8c184cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6659f73
8c184cc
 
 
 
6659f73
8c184cc
 
 
 
 
6659f73
 
8c184cc
6659f73
8c184cc
 
 
 
 
 
f2ee8f0
 
 
6659f73
f2ee8f0
8c184cc
6659f73
f2ee8f0
 
 
bee9831
 
6659f73
bee9831
 
6659f73
f2ee8f0
 
 
 
6659f73
 
 
388d8b4
0f9c95c
faa4b49
 
 
711eaf7
8c184cc
 
 
4ab1b42
b2769ed
b82a261
 
 
b2769ed
b82a261
b2769ed
b82a261
 
b2769ed
 
b82a261
 
 
 
 
b2769ed
b82a261
 
 
b2769ed
b82a261
b2769ed
b82a261
b2769ed
 
 
 
 
 
 
b82a261
b2769ed
 
 
 
 
 
63128f0
b2769ed
 
 
 
0bbc8fc
b2769ed
 
 
0bbc8fc
b2769ed
 
 
 
 
0bbc8fc
b2769ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bbc8fc
b2769ed
 
 
 
 
 
0bbc8fc
b2769ed
 
 
 
 
 
 
 
 
0bbc8fc
b2769ed
 
 
 
 
 
 
 
 
 
 
 
 
 
0bbc8fc
b2769ed
 
 
 
 
 
 
0bbc8fc
b2769ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bbc8fc
b2769ed
 
 
0bbc8fc
b2769ed
 
 
 
 
0bbc8fc
b2769ed
0bbc8fc
b2769ed
 
 
0bbc8fc
b2769ed
 
 
 
b4f1068
 
 
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
# import os
# import nltk
# import asyncio
# import torch
# import logging
# from nltk.tokenize import sent_tokenize
# from transformers import PegasusForConditionalGeneration, PegasusTokenizer
# from typing import List

# # Configure logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # Load optional secret key (e.g., for logging/monitoring access)
# API_KEY = os.getenv("API_KEY")
# if API_KEY:
#     logger.info("API_KEY loaded successfully.")
# else:
#     logger.warning("API_KEY not found. You may set it via Hugging Face secrets.")

# # NLTK setup
# nltk_data_path = os.getenv("NLTK_DATA", "/app/nltk_data")
# nltk.data.path.append(nltk_data_path)

# # Download required tokenizer
# try:
#     nltk.data.find("tokenizers/punkt")
# except LookupError:
#     nltk.download("punkt", download_dir=nltk_data_path)

# # Load Pegasus model and tokenizer
# try:
#     logger.info("Loading Pegasus model from /app/pegasus_model...")
#     pegasus_model = PegasusForConditionalGeneration.from_pretrained("/app/pegasus_model")
#     tokenizer = PegasusTokenizer.from_pretrained("/app/pegasus_model")
#     logger.info("Pegasus model loaded successfully.")
# except Exception as e:
#     logger.error(f"Error loading Pegasus model: {e}")
#     raise

# # Generation config
# MAX_TOKENS = 1024
# TEMPERATURE = 0.9
# TOP_K = 50
# TOP_P = 0.95
# NUM_BEAMS = 3

# def split_into_sentences(text: str) -> List[str]:
#     """Split text into sentences while preserving paragraph breaks."""
#     sentences = []
#     for paragraph in text.split('\n'):
#         if paragraph.strip():
#             sentences.extend(sent_tokenize(paragraph))
#         else:
#             sentences.append('')  # preserve empty lines
#     return sentences

# async def paraphrase_sentence(sentence: str) -> str:
#     """Paraphrase a single sentence using Pegasus."""
#     if not sentence.strip():
#         return sentence
#     try:
#         inputs = tokenizer(sentence, return_tensors="pt", truncation=True, padding=True)
#         outputs = pegasus_model.generate(
#             **inputs,
#             max_length=MAX_TOKENS,
#             num_beams=NUM_BEAMS,
#             early_stopping=True,
#             temperature=TEMPERATURE,
#             top_k=TOP_K,
#             top_p=TOP_P,
#             do_sample=True
#         )
#         paraphrased = tokenizer.decode(outputs[0], skip_special_tokens=True)

#         # Ensure meaning is preserved (not too short, not identical)
#         if paraphrased.lower() != sentence.lower() and len(paraphrased.split()) >= len(sentence.split()) * 0.7:
#             return paraphrased
#     except Exception as e:
#         logger.error(f"Failed to paraphrase sentence: {e}")
#     return sentence

# async def paraphrase_paragraph(paragraph: str) -> str:
#     """Paraphrase each sentence within a paragraph."""
#     if not paragraph.strip():
#         return paragraph
#     sentences = sent_tokenize(paragraph)
#     paraphrased_sentences = await asyncio.gather(*[paraphrase_sentence(s) for s in sentences])
#     return ' '.join(paraphrased_sentences)

# async def get_paraphrased_text(text: str) -> str:
#     """Main interface: paraphrase a long multi-paragraph text."""
#     if not text.strip():
#         return text
#     paragraphs = text.split('\n')
#     paraphrased_paragraphs = await asyncio.gather(*[paraphrase_paragraph(p) for p in paragraphs])
#     return '\n'.join(paraphrased_paragraphs)




###-------------- working properly! -----------------------

# import os
# import nltk
# import asyncio
# import torch
# import logging
# from nltk.tokenize import sent_tokenize
# from transformers import PegasusForConditionalGeneration, PegasusTokenizer
# from typing import List

# # Configure logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # Optional: Hugging Face secrets
# API_KEY = os.getenv("API_KEY")
# if API_KEY:
#     logger.info("API_KEY loaded successfully.")
# else:
#     logger.warning("API_KEY not found. You may set it via Hugging Face secrets.")

# # NLTK setup
# nltk_data_path = os.getenv("NLTK_DATA", "/app/nltk_data")
# nltk.data.path.append(nltk_data_path)

# try:
#     nltk.data.find("tokenizers/punkt")
# except LookupError:
#     nltk.download("punkt", download_dir=nltk_data_path)

# # Load model on CPU with optimizations
# torch_device = "cpu"
# model_name = "tuner007/pegasus_paraphrase"

# try:
#     logger.info(f"Loading Pegasus model '{model_name}' on CPU...")
#     tokenizer = PegasusTokenizer.from_pretrained(model_name)
#     pegasus_model = PegasusForConditionalGeneration.from_pretrained(
#         model_name,
#         torch_dtype=torch.float32,
#         low_cpu_mem_usage=True
#     ).to(torch_device).eval()
#     logger.info("Model loaded successfully.")
# except Exception as e:
#     logger.error(f"Error loading model: {e}")
#     raise

# # Generation config
# MAX_TOKENS = 1024
# NUM_BEAMS = 3
# TEMPERATURE = 1.0
# TOP_K = 50
# TOP_P = 0.95

# def split_into_sentences(text: str) -> List[str]:
#     """Split text into sentences while preserving paragraph breaks."""
#     sentences = []
#     for paragraph in text.split('\n'):
#         if paragraph.strip():
#             sentences.extend(sent_tokenize(paragraph))
#         else:
#             sentences.append('')  # preserve empty lines
#     return sentences

# async def paraphrase_sentence(sentence: str) -> str:
#     """Paraphrase a single sentence using Pegasus."""
#     if not sentence.strip():
#         return sentence
#     try:
#         inputs = tokenizer(sentence, return_tensors="pt", truncation=True, padding=True).to(torch_device)
#         outputs = pegasus_model.generate(
#             **inputs,
#             max_length=MAX_TOKENS,
#             num_beams=NUM_BEAMS,
#             early_stopping=True,
#             do_sample=False,
#             temperature=TEMPERATURE,
#             top_k=TOP_K,
#             top_p=TOP_P
#         )
#         paraphrased = tokenizer.decode(outputs[0], skip_special_tokens=True)

#         # Filter out poor-quality paraphrases
#         if paraphrased.lower() != sentence.lower() and len(paraphrased.split()) >= len(sentence.split()) * 0.7:
#             return paraphrased
#     except Exception as e:
#         logger.error(f"Failed to paraphrase sentence: {e}")
#     return sentence

# async def paraphrase_paragraph(paragraph: str) -> str:
#     """Paraphrase each sentence within a paragraph."""
#     if not paragraph.strip():
#         return paragraph
#     sentences = sent_tokenize(paragraph)
#     paraphrased_sentences = await asyncio.gather(*[paraphrase_sentence(s) for s in sentences])
#     return ' '.join(paraphrased_sentences)

# async def get_paraphrased_text(text: str) -> str:
#     """Main interface: paraphrase a long multi-paragraph text."""
#     if not text.strip():
#         return text
#     paragraphs = text.split('\n')
#     paraphrased_paragraphs = await asyncio.gather(*[paraphrase_paragraph(p) for p in paragraphs])
#     return '\n'.join(paraphrased_paragraphs)




##### update #####

# import os
# import nltk
# import asyncio
# import torch
# import logging
# from typing import List
# from nltk.tokenize import sent_tokenize
# from transformers import PegasusForConditionalGeneration, PegasusTokenizer

# # Setup logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # Load optional API key (for HF Spaces secrets if used)
# API_KEY = os.getenv("API_KEY")
# if API_KEY:
#     logger.info("API_KEY loaded successfully.")
# else:
#     logger.warning("API_KEY not found. Continuing without it.")

# # Ensure NLTK data is available
# nltk_data_path = os.getenv("NLTK_DATA", "/app/nltk_data")
# nltk.data.path.append(nltk_data_path)
# try:
#     nltk.data.find("tokenizers/punkt")
# except LookupError:
#     nltk.download("punkt", download_dir=nltk_data_path)

# # Model setup
# MAX_TOKENS = 128  # lower max length for faster response
# MAX_INPUT_LENGTH = 60
# NUM_BEAMS = 3
# torch_device = "cpu"
# model_name = "tuner007/pegasus_paraphrase"

# logger.info(f"Loading model '{model_name}'...")
# tokenizer = PegasusTokenizer.from_pretrained(model_name)
# model = PegasusForConditionalGeneration.from_pretrained(
#     model_name,
#     torch_dtype=torch.float32,
#     low_cpu_mem_usage=True
# ).to(torch_device).eval()

# # --- Utilities ---

# def split_into_sentences(text: str) -> List[str]:
#     """Preserve paragraph structure while splitting into sentences."""
#     sentences = []
#     for para in text.split('\n'):
#         if para.strip():
#             sentences.extend(sent_tokenize(para))
#         else:
#             sentences.append('')  # blank line = paragraph break
#     return sentences

# def chunk_sentence(sentence: str, max_words: int = 50) -> List[str]:
#     """Break long sentence into smaller chunks."""
#     words = sentence.split()
#     if len(words) <= max_words:
#         return [sentence]
#     return [' '.join(words[i:i+max_words]) for i in range(0, len(words), max_words)]

# # --- Paraphrasing ---

# async def paraphrase_sentence(sentence: str) -> str:
#     """Paraphrase a single sentence or chunk."""
#     if not sentence.strip():
#         return sentence

#     chunks = chunk_sentence(sentence)
#     rewritten_chunks = []

#     for chunk in chunks:
#         try:
#             inputs = tokenizer(chunk, return_tensors="pt", truncation=True, max_length=MAX_INPUT_LENGTH).to(torch_device)

#             if inputs.input_ids.shape[1] > MAX_INPUT_LENGTH:
#                 logger.warning("Chunk too long, skipping.")
#                 rewritten_chunks.append(chunk)
#                 continue

#             outputs = model.generate(
#                 **inputs,
#                 max_length=MAX_TOKENS,
#                 num_beams=NUM_BEAMS,
#                 early_stopping=True,
#                 do_sample=False,
#             )
#             result = tokenizer.decode(outputs[0], skip_special_tokens=True)

#             if result.lower() != chunk.lower() and len(result.split()) >= len(chunk.split()) * 0.7:
#                 rewritten_chunks.append(result)
#             else:
#                 rewritten_chunks.append(chunk)

#         except Exception as e:
#             logger.error(f"Error during paraphrase: {e}")
#             rewritten_chunks.append(chunk)

#     return ' '.join(rewritten_chunks)

# async def paraphrase_paragraph(paragraph: str) -> str:
#     """Process each sentence in a paragraph."""
#     if not paragraph.strip():
#         return paragraph
#     sentences = sent_tokenize(paragraph)
#     rewritten = await asyncio.gather(*(paraphrase_sentence(s) for s in sentences))
#     return ' '.join(rewritten)

# async def get_paraphrased_text(text: str) -> str:
#     """Main method to rewrite input while preserving structure."""
#     if not text.strip():
#         return text
#     paragraphs = text.split('\n')
#     rewritten = await asyncio.gather(*(paraphrase_paragraph(p) for p in paragraphs))
#     return '\n'.join(rewritten)



# import os
# import nltk
# import asyncio
# import torch
# import logging
# from typing import List
# from nltk.tokenize import sent_tokenize
# from transformers import PegasusForConditionalGeneration, PegasusTokenizer

# # Setup logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # Optional API key (e.g., for Hugging Face secrets)
# API_KEY = os.getenv("API_KEY")
# if API_KEY:
#     logger.info("API_KEY loaded successfully.")
# else:
#     logger.warning("API_KEY not found. Continuing without it.")

# # Ensure NLTK tokenizer is available
# nltk_data_path = os.getenv("NLTK_DATA", "/app/nltk_data")
# nltk.data.path.append(nltk_data_path)
# try:
#     nltk.data.find("tokenizers/punkt")
# except LookupError:
#     nltk.download("punkt", download_dir=nltk_data_path)

# # Model configuration
# MAX_TOKENS = 128  # Max output length
# MAX_INPUT_LENGTH = 60  # Max input token length per chunk
# NUM_BEAMS = 3
# torch_device = "cpu"
# model_name = "tuner007/pegasus_paraphrase"

# logger.info(f"Loading model '{model_name}'...")
# tokenizer = PegasusTokenizer.from_pretrained(model_name)
# model = PegasusForConditionalGeneration.from_pretrained(
#     model_name,
#     torch_dtype=torch.float32,
#     low_cpu_mem_usage=True
# ).to(torch_device).eval()


# # ----------- Utilities -----------

# def split_into_sentences(text: str) -> List[str]:
#     """Preserve paragraph breaks while tokenizing into sentences."""
#     sentences = []
#     for para in text.split('\n'):
#         if para.strip():
#             sentences.extend(sent_tokenize(para))
#         else:
#             sentences.append('')  # preserve paragraph spacing
#     return sentences

# def chunk_sentence(sentence: str, max_words: int = 50) -> List[str]:
#     """Split very long sentences into smaller word chunks."""
#     words = sentence.split()
#     if len(words) <= max_words:
#         return [sentence]
#     return [' '.join(words[i:i + max_words]) for i in range(0, len(words), max_words)]


# # ----------- Core Paraphrasing -----------

# async def paraphrase_sentence(sentence: str) -> str:
#     """Paraphrase a sentence or its smaller chunks if long."""
#     if not sentence.strip():
#         return sentence  # preserve blank lines

#     chunks = chunk_sentence(sentence)
#     rewritten_chunks = []

#     for chunk in chunks:
#         try:
#             inputs = tokenizer(
#                 chunk,
#                 return_tensors="pt",
#                 truncation=True,
#                 max_length=MAX_INPUT_LENGTH,
#             ).to(torch_device)

#             if inputs.input_ids.shape[1] > MAX_INPUT_LENGTH:
#                 logger.warning(f"Chunk too long, skipping: {chunk}")
#                 rewritten_chunks.append(chunk)
#                 continue

#             outputs = model.generate(
#                 **inputs,
#                 max_length=MAX_TOKENS,
#                 num_beams=NUM_BEAMS,
#                 early_stopping=True,
#                 do_sample=False,
#             )

#             result = tokenizer.decode(outputs[0], skip_special_tokens=True)

#             # Sanity check: avoid broken or poor rewrites
#             if (
#                 result.lower() != chunk.lower()
#                 and len(result.split()) >= max(3, int(len(chunk.split()) * 0.6))
#                 and not any(phrase in result.lower() for phrase in ["is a type of", "are 200", "the man is named"])
#             ):
#                 rewritten_chunks.append(result)
#             else:
#                 logger.warning(f"Low-quality rewrite or too similar: '{result}' <- '{chunk}'")
#                 rewritten_chunks.append(chunk)

#         except Exception as e:
#             logger.error(f"Error during paraphrasing: {e}")
#             rewritten_chunks.append(chunk)

#     return ' '.join(rewritten_chunks)


# async def paraphrase_paragraph(paragraph: str) -> str:
#     """Rewrite each sentence within a paragraph."""
#     if not paragraph.strip():
#         return paragraph
#     sentences = sent_tokenize(paragraph)
#     rewritten_sentences = await asyncio.gather(*[paraphrase_sentence(s) for s in sentences])
#     return ' '.join(rewritten_sentences)


# async def get_paraphrased_text(text: str) -> str:
#     """Rewrite full text input while preserving paragraph structure."""
#     if not text.strip():
#         return text
#     paragraphs = text.split('\n')
#     rewritten_paragraphs = await asyncio.gather(*[paraphrase_paragraph(p) for p in paragraphs])
#     return '\n'.join(rewritten_paragraphs)



#### --------------------------------- use the bitsandbytes INT8 quantization with transformers and accelerate  ------------------------------------

# import os
# import nltk
# import asyncio
# import torch
# import logging
# from typing import List
# from nltk.tokenize import sent_tokenize
# from transformers import PegasusForConditionalGeneration, PegasusTokenizer

# # Limit CPU threads for performance tuning (important in 2vCPU env)
# torch.set_num_threads(2)

# # Setup logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# API_KEY = os.getenv("API_KEY")
# if API_KEY:
#     logger.info("API_KEY loaded successfully.")
# else:
#     logger.warning("API_KEY not found. Continuing without it.")

# # Ensure punkt tokenizer is available
# nltk_data_path = os.getenv("NLTK_DATA", "/app/nltk_data")
# nltk.data.path.append(nltk_data_path)
# try:
#     nltk.data.find("tokenizers/punkt")
# except LookupError:
#     nltk.download("punkt", download_dir=nltk_data_path)

# MAX_TOKENS = 128
# MAX_INPUT_LENGTH = 60
# NUM_BEAMS = 3
# torch_device = "cpu"
# model_name = "tuner007/pegasus_paraphrase"

# logger.info(f"Loading Pegasus model '{model_name}' for CPU...")
# tokenizer = PegasusTokenizer.from_pretrained(model_name)
# model = PegasusForConditionalGeneration.from_pretrained(model_name).to(torch_device).eval()

# # ----------- Utilities -----------

# def split_into_sentences(text: str) -> List[str]:
#     """Preserve paragraph breaks while tokenizing into sentences."""
#     sentences = []
#     for para in text.split('\n'):
#         if para.strip():
#             sentences.extend(sent_tokenize(para))
#         else:
#             sentences.append('')  # preserve blank lines
#     return sentences

# def chunk_sentence(sentence: str, max_words: int = 50) -> List[str]:
#     """Split very long sentences into smaller word chunks."""
#     words = sentence.split()
#     if len(words) <= max_words:
#         return [sentence]
#     return [' '.join(words[i:i + max_words]) for i in range(0, len(words), max_words)]

# # ----------- Core Paraphrasing Logic -----------

# async def paraphrase_sentence(sentence: str) -> str:
#     if not sentence.strip():
#         return sentence  # preserve blank lines

#     chunks = chunk_sentence(sentence)
#     rewritten_chunks = []

#     for chunk in chunks:
#         try:
#             inputs = tokenizer(
#                 chunk,
#                 return_tensors="pt",
#                 truncation=True,
#                 max_length=MAX_INPUT_LENGTH,
#             ).to(torch_device)

#             outputs = model.generate(
#                 **inputs,
#                 max_length=MAX_TOKENS,
#                 num_beams=NUM_BEAMS,
#                 early_stopping=True,
#                 do_sample=False,
#             )

#             result = tokenizer.decode(outputs[0], skip_special_tokens=True)

#             # Quality checks
#             if (
#                 result.lower() != chunk.lower()
#                 and len(result.split()) >= max(3, int(len(chunk.split()) * 0.6))
#                 and not any(phrase in result.lower() for phrase in ["is a type of", "are 200", "the man is named"])
#             ):
#                 rewritten_chunks.append(result)
#             else:
#                 logger.warning(f"Low-quality rewrite: '{result}' <- '{chunk}'")
#                 rewritten_chunks.append(chunk)

#         except Exception as e:
#             logger.error(f"Paraphrasing error: {e}")
#             rewritten_chunks.append(chunk)

#     return ' '.join(rewritten_chunks)

# async def paraphrase_paragraph(paragraph: str) -> str:
#     if not paragraph.strip():
#         return paragraph
#     sentences = sent_tokenize(paragraph)
#     rewritten_sentences = await asyncio.gather(*[paraphrase_sentence(s) for s in sentences])
#     return ' '.join(rewritten_sentences)

# async def get_paraphrased_text(text: str) -> str:
#     if not text.strip():
#         return text
#     paragraphs = text.split('\n')
#     rewritten_paragraphs = await asyncio.gather(*[paraphrase_paragraph(p) for p in paragraphs])
#     return '\n'.join(rewritten_paragraphs)


############## update the above code ####################

# import os
# import nltk
# import asyncio
# import torch
# import logging
# from typing import List
# from nltk.tokenize import sent_tokenize
# from transformers import PegasusForConditionalGeneration, PegasusTokenizer

# # Limit CPU threads for performance tuning (especially in Hugging Face 2vCPU env)
# torch.set_num_threads(2)

# # Setup logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # Optional API key
# API_KEY = os.getenv("API_KEY")
# if API_KEY:
#     logger.info("API_KEY loaded successfully.")
# else:
#     logger.warning("API_KEY not found. Continuing without it.")

# # Ensure punkt tokenizer is available
# nltk_data_path = os.getenv("NLTK_DATA", "/app/nltk_data")
# nltk.data.path.append(nltk_data_path)
# try:
#     nltk.data.find("tokenizers/punkt")
# except LookupError:
#     nltk.download("punkt", download_dir=nltk_data_path)

# # Model config
# MAX_TOKENS = 128
# MAX_INPUT_LENGTH = 60
# NUM_BEAMS = 3
# torch_device = "cpu"
# model_name = "tuner007/pegasus_paraphrase"

# # Load tokenizer and model
# logger.info(f"Loading Pegasus model '{model_name}' for CPU...")
# tokenizer = PegasusTokenizer.from_pretrained(model_name)
# model = PegasusForConditionalGeneration.from_pretrained(model_name).to(torch_device).eval()

# # ----------- Utilities -----------

# def split_into_sentences(text: str) -> List[str]:
#     """Preserve paragraph breaks while tokenizing into sentences."""
#     sentences = []
#     for para in text.split('\n'):
#         if para.strip():
#             sentences.extend(sent_tokenize(para))
#         else:
#             sentences.append('')  # preserve blank lines
#     return sentences

# def chunk_sentence(sentence: str, max_words: int = 50) -> List[str]:
#     """Split very long sentences into smaller word chunks."""
#     words = sentence.split()
#     if len(words) <= max_words:
#         return [sentence]
#     return [' '.join(words[i:i + max_words]) for i in range(0, len(words), max_words)]

# # ----------- Core Paraphrasing Logic -----------

# async def paraphrase_sentence(sentence: str) -> str:
#     """Paraphrase a sentence or short chunk."""
#     if not sentence.strip():
#         return sentence  # Preserve blank lines

#     chunks = chunk_sentence(sentence)
#     rewritten_chunks = []

#     for chunk in chunks:
#         try:
#             inputs = tokenizer(
#                 chunk,
#                 return_tensors="pt",
#                 truncation=True,
#                 max_length=MAX_INPUT_LENGTH,
#             ).to(torch_device)

#             outputs = model.generate(
#                 **inputs,
#                 max_length=MAX_TOKENS,
#                 num_beams=NUM_BEAMS,
#                 early_stopping=True,
#                 do_sample=False,
#             )

#             result = tokenizer.decode(outputs[0], skip_special_tokens=True)

#             # Quality check
#             if (
#                 result.lower() != chunk.lower()
#                 and len(result.split()) >= max(3, int(len(chunk.split()) * 0.6))
#                 and not any(phrase in result.lower() for phrase in ["is a type of", "are 200", "the man is named"])
#             ):
#                 rewritten_chunks.append(result)
#             else:
#                 logger.warning(f"Low-quality rewrite: '{result}' <- '{chunk}'")
#                 rewritten_chunks.append(chunk)

#         except Exception as e:
#             logger.error(f"Paraphrasing error: {e}")
#             rewritten_chunks.append(chunk)

#     return ' '.join(rewritten_chunks)

# async def paraphrase_paragraph(paragraph: str) -> str:
#     """Paraphrase a paragraph by rewriting each sentence."""
#     if not paragraph.strip():
#         return paragraph  # Preserve blank lines
#     sentences = sent_tokenize(paragraph)
#     rewritten_sentences = await asyncio.gather(*[paraphrase_sentence(s) for s in sentences])
#     return ' '.join(rewritten_sentences)

# async def get_paraphrased_text(text: str) -> str:
#     """Main paraphrasing function to handle full texts with paragraph preservation."""
#     if not text.strip():
#         return text
#     paragraphs = text.split('\n')
#     rewritten_paragraphs = await asyncio.gather(*[paraphrase_paragraph(p) for p in paragraphs])
#     return '\n'.join(rewritten_paragraphs)


################# grammer logic add- improve them ##################


import os
import nltk
import asyncio
import torch
import logging
from typing import List
from nltk.tokenize import sent_tokenize
from transformers import PegasusForConditionalGeneration, PegasusTokenizer

# Limit CPU threads for performance tuning (especially in Hugging Face 2vCPU env)
torch.set_num_threads(2)

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Optional API key loading (if needed)
API_KEY = os.getenv("API_KEY")
if API_KEY:
    logger.info("API_KEY loaded successfully.")
else:
    logger.warning("API_KEY not found. Continuing without it.")

# Ensure punkt tokenizer is available
nltk_data_path = os.getenv("NLTK_DATA", "/app/nltk_data")
nltk.data.path.append(nltk_data_path)
try:
    nltk.data.find("tokenizers/punkt")
except LookupError:
    nltk.download("punkt", download_dir=nltk_data_path)

# Model config
MAX_TOKENS = 128          # Output max tokens
MAX_INPUT_LENGTH = 60     # Input max tokens per chunk (pegasus prefers shorter input chunks)
NUM_BEAMS = 3
torch_device = "cpu"
model_name = "tuner007/pegasus_paraphrase"

# Load tokenizer and model
logger.info(f"Loading Pegasus model '{model_name}' for CPU...")
tokenizer = PegasusTokenizer.from_pretrained(model_name)
model = PegasusForConditionalGeneration.from_pretrained(model_name).to(torch_device).eval()

# ----------- Utilities -----------

def split_into_sentences(text: str) -> List[str]:
    """Preserve paragraph breaks while tokenizing into sentences."""
    sentences = []
    for para in text.split('\n'):
        if para.strip():
            sentences.extend(sent_tokenize(para))
        else:
            sentences.append('')  # preserve blank lines
    return sentences

def chunk_sentence(sentence: str, max_words: int = 50) -> List[str]:
    """Split very long sentences into smaller word chunks."""
    words = sentence.split()
    if len(words) <= max_words:
        return [sentence]
    return [' '.join(words[i:i + max_words]) for i in range(0, len(words), max_words)]

def simple_grammar_fix(text: str) -> str:
    """
    Very lightweight grammar fixer to capitalize sentences and fix spacing.
    For production, consider integrating language models or grammar tools.
    """
    # Capitalize first letter of each sentence
    sentences = sent_tokenize(text)
    fixed_sentences = []
    for s in sentences:
        s = s.strip()
        if s:
            s = s[0].upper() + s[1:]
        fixed_sentences.append(s)
    return " ".join(fixed_sentences).replace(" ,", ",").replace(" .", ".").replace(" !", "!").replace(" ?", "?")

# ----------- Core Paraphrasing Logic -----------

async def paraphrase_sentence(sentence: str) -> str:
    """Paraphrase a sentence or short chunk asynchronously."""
    if not sentence.strip():
        return sentence  # Preserve blank lines

    chunks = chunk_sentence(sentence)
    rewritten_chunks = []

    for chunk in chunks:
        try:
            inputs = tokenizer(
                chunk,
                return_tensors="pt",
                truncation=True,
                max_length=MAX_INPUT_LENGTH,
            ).to(torch_device)

            outputs = model.generate(
                **inputs,
                max_length=MAX_TOKENS,
                num_beams=NUM_BEAMS,
                early_stopping=True,
                do_sample=False,
                no_repeat_ngram_size=2,
            )

            result = tokenizer.decode(outputs[0], skip_special_tokens=True)

            # Quality check to avoid bad paraphrases and preserve meaning & length
            if (
                result.lower() != chunk.lower()
                and len(result.split()) >= max(3, int(len(chunk.split()) * 0.6))
                and not any(phrase in result.lower() for phrase in ["is a type of", "are 200", "the man is named"])
            ):
                fixed_result = simple_grammar_fix(result)
                rewritten_chunks.append(fixed_result)
            else:
                logger.warning(f"Low-quality rewrite detected, using original chunk.\nOriginal: {chunk}\nResult: {result}")
                rewritten_chunks.append(chunk)

        except Exception as e:
            logger.error(f"Paraphrasing error: {e}")
            rewritten_chunks.append(chunk)

    return ' '.join(rewritten_chunks)

async def paraphrase_paragraph(paragraph: str) -> str:
    """Paraphrase a paragraph by rewriting each sentence asynchronously."""
    if not paragraph.strip():
        return paragraph  # Preserve blank lines

    sentences = sent_tokenize(paragraph)
    rewritten_sentences = await asyncio.gather(*[paraphrase_sentence(s) for s in sentences])
    return ' '.join(rewritten_sentences)

async def get_paraphrased_text(text: str) -> str:
    """Main paraphrasing function to handle full texts with paragraph preservation asynchronously."""
    if not text.strip():
        return text

    paragraphs = text.split('\n')
    rewritten_paragraphs = await asyncio.gather(*[paraphrase_paragraph(p) for p in paragraphs])
    return '\n'.join(rewritten_paragraphs)

# Example synchronous wrapper (if you want sync calls)
def paraphrase_text_sync(text: str) -> str:
    return asyncio.run(get_paraphrased_text(text))









######------------------------------- add minecraft terms ----------------------------------------------------------------------

# import os
# import nltk
# import torch
# import re
# import logging
# import asyncio
# from nltk.tokenize import sent_tokenize
# from transformers import PegasusForConditionalGeneration, PegasusTokenizer
# from concurrent.futures import ThreadPoolExecutor
# from typing import List, Tuple, Dict

# # Configure logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # NLTK Setup
# nltk_data_path = os.getenv("NLTK_DATA", "/app/nltk_data")
# nltk.data.path.append(nltk_data_path)
# try:
#     nltk.data.find('tokenizers/punkt')
# except LookupError:
#     nltk.download('punkt', download_dir=nltk_data_path)

# # Model Loading with CPU optimization
# pegasus_model = PegasusForConditionalGeneration.from_pretrained(
#     "/app/pegasus_model",
#     low_cpu_mem_usage=True,
#     torch_dtype=torch.float32
# ).eval()
# tokenizer = PegasusTokenizer.from_pretrained("/app/pegasus_model")

# # Configuration
# DYNAMIC_MAX_TOKENS = 768  # Base token length
# ABSOLUTE_MAX = 1024       # For technical descriptions
# NUM_BEAMS = 4             # Improved quality
# BATCH_SIZE = 3            # Optimal for 2vCPU
# MAX_WORKERS = 2           # Matches your 2vCPU
    
# # Dynamic Term Protection System
# def extract_protected_terms(text: str) -> set:
#     """Auto-detect terms to protect from the input text"""
#     protected = set()
    
#     # Extract ALL-CAPS terms and phrases in quotes
#     protected.update(re.findall(r'([A-Z][A-Z0-9_]+(?:\s[A-Z0-9_]+)*)', text))
#     protected.update(re.findall(r'\"([^\"]+)\"', text))
    
#     # Extract noun phrases with 2+ capital letters
#     protected.update(
#         phrase.strip() for phrase in re.findall(r'([A-Z][a-z]+(?:\s[A-Z][a-z]+)+)', text)
#         if len(phrase.split()) > 1
#     )
    
#     return {term.lower() for term in protected}

# # Format Protection Patterns
# FORMAT_PATTERNS = [
#     (r'\*\*(.*?)\*\*', 'BOLD'),          # **bold text**
#     (r'([A-Z]{2,}(?:\s[A-Z0-9_]+)*:)', 'HEADER'),  # HEADERS:
#     (r'\n- (.*?)(\n|$)', 'BULLET'),      # - bullet points
#     (r'`(.*?)`', 'CODE'),                # `code`
#     (r'\"(.*?)\"', 'QUOTE')              # "quoted text"
# ]

# def protect_content(text: str) -> Tuple[str, Dict[str, str]]:
#     """Dynamic content protection"""
#     protected_terms = extract_protected_terms(text)
#     restoration = {}
#     protected_text = text
    
#     # Protect formats
#     for pattern, tag in FORMAT_PATTERNS:
#         for match in re.finditer(pattern, protected_text):
#             placeholder = f"PROTECT_{tag}_{len(restoration)}"
#             protected_text = protected_text.replace(match.group(0), placeholder)
#             restoration[placeholder] = match.group(0)
    
#     # Protect terms (case-insensitive)
#     words = re.split(r'(\W+)', protected_text)
#     for i, word in enumerate(words):
#         lower_word = word.lower()
#         if lower_word in protected_terms:
#             placeholder = f"TERM_{abs(hash(lower_word))}"
#             words[i] = placeholder
#             restoration[placeholder] = word
#     protected_text = ''.join(words)
    
#     return protected_text, restoration

# def restore_content(text: str, restoration: Dict[str, str]) -> str:
#     """Restore protected content"""
#     for placeholder in sorted(restoration.keys(), key=len, reverse=True):
#         text = text.replace(placeholder, restoration[placeholder])
#     return text

# def paraphrase_batch(sentences: List[str]) -> List[str]:
#     """Quality-focused batch processing"""
#     max_len = max(
#         ABSOLUTE_MAX if len(s.split()) > 25 else DYNAMIC_MAX_TOKENS 
#         for s in sentences
#     )
    
#     inputs = tokenizer(
#         sentences,
#         return_tensors="pt",
#         padding=True,
#         truncation=True,
#         max_length=max_len
#     )
    
#     outputs = pegasus_model.generate(
#         **inputs,
#         max_length=max_len + 64,
#         num_beams=NUM_BEAMS,
#         early_stopping=True,
#         temperature=0.8,
#         top_p=0.9,
#         no_repeat_ngram_size=3,
#         length_penalty=1.0,
#         do_sample=False
#     )
#     return tokenizer.batch_decode(outputs, skip_special_tokens=True)

# async def process_paragraph(paragraph: str) -> str:
#     """Paragraph processing pipeline"""
#     if not paragraph.strip():
#         return paragraph
    
#     try:
#         protected, restoration = protect_content(paragraph)
#         sentences = sent_tokenize(protected)
        
#         with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
#             batches = [sentences[i:i+BATCH_SIZE] for i in range(0, len(sentences), BATCH_SIZE)]
#             results = []
#             for batch in batches:
#                 results.extend(paraphrase_batch(batch))
        
#         return restore_content(' '.join(results), restoration)
    
#     except Exception as e:
#         logger.error(f"Paragraph processing failed: {e}")
#         return paragraph

# async def get_paraphrased_text(text: str) -> str:
#     """Main processing function"""
#     paragraphs = [p for p in text.split('\n') if p.strip() or p == '']
#     processed = await asyncio.gather(*[process_paragraph(p) for p in paragraphs])
#     return '\n'.join(processed)