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7eb
03155c5
 
 
c83da3c
eefc7eb
 
 
03155c5
c83da3c
03155c5
 
 
c83da3c
03155c5
 
 
c83da3c
 
03155c5
 
c83da3c
03155c5
 
c83da3c
 
 
 
03155c5
 
 
c83da3c
 
03155c5
 
 
c83da3c
 
03155c5
c83da3c
 
 
 
 
 
d9ca4b2
 
03155c5
c83da3c
 
 
 
 
03155c5
 
 
c83da3c
 
03155c5
c83da3c
 
 
 
 
 
d9ca4b2
 
03155c5
c83da3c
 
 
 
 
03155c5
 
 
c83da3c
03155c5
 
 
 
 
 
330a102
03155c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
"""
AquaHumanizer Pro - AI Text Enhancement API
Copyright (c) 2026 AquilaStudios
Licensed under the MIT License

Production-ready paraphrasing service using T5 model with document processing capabilities.
"""

import os
import logging
import io
import asyncio
import json
import time
from typing import Optional, List
from enum import Enum
from contextlib import asynccontextmanager
import torch
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
from fastapi.responses import StreamingResponse, Response
from pydantic import BaseModel, Field, field_validator
from transformers import T5ForConditionalGeneration, T5Tokenizer
from docx import Document
from reportlab.lib.pagesizes import LETTER, letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.enums import TA_LEFT, TA_JUSTIFY
from reportlab.pdfgen import canvas

# Configure enhanced logging with structured format
import uuid
from datetime import datetime

class StructuredFormatter(logging.Formatter):
    """Custom formatter for structured logging"""
    
    def format(self, record):
        # Create structured log entry
        log_entry = {
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "level": record.levelname,
            "component": record.name,
            "message": record.getMessage(),
        }
        
        # Add request ID if available
        if hasattr(record, 'request_id'):
            log_entry["request_id"] = record.request_id
        
        # Add extra context if available
        if hasattr(record, 'context'):
            log_entry["context"] = record.context
        
        # Add error details if it's an error
        if record.levelno >= logging.ERROR and record.exc_info:
            log_entry["error_type"] = record.exc_info[0].__name__ if record.exc_info[0] else None
            log_entry["stack_trace"] = self.formatException(record.exc_info) if record.exc_info else None
        
        return json.dumps(log_entry)

# Configure logging with structured format
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# Create structured logger for API requests
structured_handler = logging.StreamHandler()
structured_handler.setFormatter(StructuredFormatter())
api_logger = logging.getLogger("api_requests")
api_logger.addHandler(structured_handler)
api_logger.setLevel(logging.INFO)

logger = logging.getLogger(__name__)

# Error tracking utilities
class ErrorTracker:
    """Track and log errors with context"""
    
    @staticmethod
    def log_request(request_data: dict, request_id: str = None) -> str:
        """Log incoming request with unique ID"""
        if not request_id:
            request_id = str(uuid.uuid4())[:8]
        
        api_logger.info(
            "Incoming request",
            extra={
                "request_id": request_id,
                "context": {
                    "endpoint": request_data.get("endpoint"),
                    "method": request_data.get("method"),
                    "content_length": request_data.get("content_length", 0),
                    "user_agent": request_data.get("user_agent", "unknown")
                }
            }
        )
        return request_id
    
    @staticmethod
    def log_processing_stage(stage: str, data: dict, request_id: str = None):
        """Log processing stage with timing and context"""
        api_logger.info(
            f"Processing stage: {stage}",
            extra={
                "request_id": request_id,
                "context": {
                    "stage": stage,
                    **data
                }
            }
        )
    
    @staticmethod
    def capture_error(error: Exception, context: dict, request_id: str = None) -> str:
        """Capture error with full context"""
        error_id = str(uuid.uuid4())[:8]
        
        api_logger.error(
            f"Error occurred: {str(error)}",
            exc_info=True,
            extra={
                "request_id": request_id,
                "context": {
                    "error_id": error_id,
                    "error_type": type(error).__name__,
                    "error_message": str(error),
                    **context
                }
            }
        )
        return error_id

error_tracker = ErrorTracker()

# Validate dependencies on startup
def validate_dependencies():
    """Validate that all required dependencies are available"""
    try:
        # Test ReportLab imports
        from reportlab.lib.pagesizes import letter
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.platypus import SimpleDocTemplate, Paragraph
        logger.info("βœ… ReportLab dependencies validated")
        
        # Test python-docx imports
        from docx import Document
        from docx.shared import Pt, Inches
        from docx.enum.text import WD_ALIGN_PARAGRAPH
        logger.info("βœ… python-docx dependencies validated")
        
        return True
    except ImportError as e:
        logger.error(f"❌ Missing dependency: {str(e)}")
        raise HTTPException(
            status_code=503, 
            detail=f"Required dependency missing: {str(e)}"
        )
    except Exception as e:
        logger.error(f"❌ Dependency validation error: {str(e)}")
        raise HTTPException(
            status_code=503,
            detail=f"Dependency validation failed: {str(e)}"
        )

# Global model and tokenizer (loaded once on startup)
model: Optional[T5ForConditionalGeneration] = None
tokenizer: Optional[T5Tokenizer] = None

# Configuration constants
MIN_WORDS = 5
MAX_INPUT_LENGTH = 512  # Protect CPU from very long inputs
MAX_OUTPUT_LENGTH = 128
NUM_BEAMS = 4
NO_REPEAT_NGRAM_SIZE = 3
CHUNK_TOKEN_LIMIT = 400  # Safe chunking for long documents
MAX_DOC_CHUNKS = 50  # Free-tier protection


class ParaphraseStyle(str, Enum):
    """Paraphrasing styles for different use cases"""
    neutral = "neutral"
    formal = "formal"
    ats = "ats"
    bullets = "bullets"


async def load_model():
    """Load model and tokenizer once on startup"""
    global model, tokenizer
    
    model_name = "Vamsi/T5_Paraphrase_Paws"
    logger.info(f"Loading model: {model_name}")
    
    try:
        # Load tokenizer
        logger.info("Loading tokenizer...")
        tokenizer = T5Tokenizer.from_pretrained(model_name)
        
        # Load model
        logger.info("Loading model...")
        model = T5ForConditionalGeneration.from_pretrained(model_name)
        
        # Set to evaluation mode
        model.eval()
        
        # Move to CPU (explicit for clarity)
        device = torch.device("cpu")
        model.to(device)
        
        logger.info("Model loaded successfully on CPU")
        
    except Exception as e:
        logger.error(f"Failed to load model: {str(e)}")
        raise


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Lifespan event handler for FastAPI"""
    # Startup
    logger.info("Starting up...")
    
    # Validate dependencies first
    validate_dependencies()
    
    # Then load model
    await load_model()
    logger.info("Startup complete")
    
    yield
    
    # Shutdown
    logger.info("Shutting down...")
    # Clean up resources if needed
    logger.info("Shutdown complete")


# FastAPI app with lifespan
app = FastAPI(
    title="T5 Paraphrasing API",
    description="Production-ready paraphrasing service using T5 model",
    version="2.0.0",
    lifespan=lifespan
)


def build_prompt(text: str, style: ParaphraseStyle) -> str:
    """Build style-specific prompts for T5 model"""
    if style == ParaphraseStyle.formal:
        return f"paraphrase formally: {text}"
    elif style == ParaphraseStyle.ats:
        return (
            "paraphrase professionally for a resume, "
            "use clear action verbs, concise language, "
            f"and ATS-friendly wording: {text}"
        )
    elif style == ParaphraseStyle.bullets:
        return (
            "Rewrite the following text into concise, professional resume bullet points. "
            "Use strong action verbs, quantify impact where possible, "
            f"and keep each bullet ATS-friendly: {text}"
        )
    return f"paraphrase: {text}"


def chunk_text(text: str, tokenizer, max_tokens: int) -> List[str]:
    """Chunk text by sentences to stay within token limits"""
    sentences = text.split('. ')
    chunks = []
    current_chunk = []
    current_tokens = 0
    
    for sentence in sentences:
        sentence = sentence.strip()
        if not sentence:
            continue
            
        # Add period back if it was removed
        if not sentence.endswith('.'):
            sentence += '.'
            
        tokens = tokenizer.encode(sentence, add_special_tokens=False)
        
        if current_tokens + len(tokens) > max_tokens:
            if current_chunk:
                chunks.append(' '.join(current_chunk))
                current_chunk = [sentence]
                current_tokens = len(tokens)
            else:
                # Single sentence too long, truncate
                chunks.append(sentence[:max_tokens])
        else:
            current_chunk.append(sentence)
            current_tokens += len(tokens)
    
    if current_chunk:
        chunks.append(' '.join(current_chunk))
    
    return chunks


def paragraph_chunks(text: str, tokenizer, max_tokens: int) -> List[str]:
    """Chunk text by paragraphs for bullet-point restructuring"""
    paragraphs = [p.strip() for p in text.split("\n") if p.strip()]
    chunks = []
    current = []
    tokens_count = 0
    
    for p in paragraphs:
        tokens = tokenizer.encode(p, add_special_tokens=False)
        if tokens_count + len(tokens) > max_tokens:
            if current:
                chunks.append("\n".join(current))
                current = [p]
                tokens_count = len(tokens)
            else:
                # Single paragraph too long, use sentence chunking
                sentence_chunks = chunk_text(p, tokenizer, max_tokens)
                chunks.extend(sentence_chunks)
        else:
            current.append(p)
            tokens_count += len(tokens)
    
    if current:
        chunks.append("\n".join(current))
    
    return chunks


def create_docx(text: str) -> bytes:
    """
    Create DOCX file from text with proper formatting.
    Handles paragraphs, bullet points, and headings.
    """
    try:
        from docx import Document
        from docx.shared import Pt, RGBColor, Inches
        from docx.enum.text import WD_ALIGN_PARAGRAPH
        
        logger.info(f"πŸ“„ Starting DOCX generation for {len(text)} characters")
        start_time = time.time()
        
        doc = Document()
        
        # Set default styling
        style = doc.styles['Normal']
        font = style.font
        font.name = 'Calibri'
        font.size = Pt(11)
        
        # Set page margins
        sections = doc.sections
        for section in sections:
            section.top_margin = Inches(1)
            section.bottom_margin = Inches(1)
            section.left_margin = Inches(1)
            section.right_margin = Inches(1)
        
        # Split text into paragraphs
        paragraphs = text.split('\n\n')
        paragraph_count = 0
        bullet_count = 0
        
        for paragraph_text in paragraphs:
            if not paragraph_text.strip():
                continue
                
            # Split by lines for bullet points
            lines = paragraph_text.split('\n')
            
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                    
                # Handle bullet points
                if line.startswith('β€’') or line.startswith('-') or line.startswith('*'):
                    # Remove bullet character
                    clean_line = line[1:].strip()
                    doc.add_paragraph(clean_line, style='List Bullet')
                    bullet_count += 1
                    
                # Handle headings (all caps, short)
                elif line.isupper() and len(line.split()) <= 5:
                    heading = doc.add_heading(line, level=2)
                    
                # Regular paragraph
                else:
                    para = doc.add_paragraph(line)
                    para.alignment = WD_ALIGN_PARAGRAPH.LEFT
                    paragraph_count += 1
            
            # Add spacing between sections (empty paragraph)
            doc.add_paragraph()
        
        # Remove last empty paragraph
        if len(doc.paragraphs) > 0 and not doc.paragraphs[-1].text.strip():
            doc._element.body.remove(doc.paragraphs[-1]._element)
        
        # Save to buffer
        buffer = io.BytesIO()
        doc.save(buffer)
        buffer.seek(0)
        docx_bytes = buffer.read()
        
        # Validate DOCX was created properly
        validation_result = validate_docx_content(docx_bytes)
        
        if not validation_result['valid']:
            error_msg = validation_result.get('error', 'DOCX validation failed')
            logger.error(f"❌ DOCX validation failed: {error_msg}")
            raise ValueError(error_msg)
        
        processing_time = time.time() - start_time
        logger.info(f"βœ… DOCX created successfully: {len(docx_bytes)} bytes, "
                   f"{paragraph_count} paragraphs, {bullet_count} bullets, "
                   f"processed in {processing_time:.2f}s")
        return docx_bytes
        
    except Exception as e:
        logger.error(f"❌ DOCX generation error: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=500,
            detail=f"DOCX generation failed: {str(e)}"
        )


def create_pdf(text: str) -> bytes:
    """
    Create PDF file from text with proper formatting using ReportLab.
    Uses SimpleDocTemplate for robust PDF generation.
    """
    try:
        logger.info(f"πŸ“‘ Starting PDF generation for {len(text)} characters")
        start_time = time.time()
        
        buffer = io.BytesIO()
        
        # Create PDF document with proper margins
        doc = SimpleDocTemplate(
            buffer,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=18,
        )
        
        # Container for flowable objects
        elements = []
        
        # Get default styles
        styles = getSampleStyleSheet()
        style_normal = ParagraphStyle(
            'CustomNormal',
            parent=styles['Normal'],
            fontSize=11,
            leading=16,
            alignment=TA_JUSTIFY,
            spaceAfter=12,
        )
        
        style_bullet = ParagraphStyle(
            'CustomBullet',
            parent=styles['Normal'],
            fontSize=11,
            leading=16,
            alignment=TA_LEFT,
            leftIndent=20,
            spaceAfter=8,
        )
        
        # Split text into paragraphs
        paragraphs = text.split('\n\n')
        paragraph_count = 0
        bullet_count = 0
        heading_count = 0
        
        for para_text in paragraphs:
            if not para_text.strip():
                continue
                
            # Check if this is a multi-line section with bullets
            lines = para_text.split('\n')
            
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                    
                # Escape XML special characters for ReportLab
                line = (line
                    .replace('&', '&amp;')
                    .replace('<', '&lt;')
                    .replace('>', '&gt;')
                    .replace('"', '&quot;')
                    .replace("'", '&apos;')
                )
                
                # Detect and format bullet points
                if line.startswith('β€’') or line.startswith('-') or line.startswith('*'):
                    # Remove bullet character and create bullet paragraph
                    clean_line = line[1:].strip()
                    bullet_text = f"β€’ {clean_line}"
                    para = Paragraph(bullet_text, style_bullet)
                    elements.append(para)
                    bullet_count += 1
                elif line.isupper() and len(line.split()) <= 5:
                    # Heading style
                    para = Paragraph(f"<b>{line}</b>", style_normal)
                    elements.append(para)
                    elements.append(Spacer(1, 0.15 * inch))
                    heading_count += 1
                else:
                    # Regular paragraph
                    para = Paragraph(line, style_normal)
                    elements.append(para)
                    paragraph_count += 1
            
            # Add spacing between sections
            elements.append(Spacer(1, 0.2 * inch))
        
        # Build PDF
        doc.build(elements)
        
        # Get PDF bytes
        buffer.seek(0)
        pdf_bytes = buffer.read()
        
        # Validate PDF was created properly
        validation_result = validate_pdf_content(pdf_bytes)
        
        if not validation_result['valid']:
            error_msg = validation_result.get('error', 'PDF validation failed')
            logger.error(f"❌ PDF validation failed: {error_msg}")
            raise ValueError(error_msg)
        
        processing_time = time.time() - start_time
        logger.info(f"βœ… PDF created successfully: {len(pdf_bytes)} bytes, "
                   f"{paragraph_count} paragraphs, {bullet_count} bullets, "
                   f"{heading_count} headings, processed in {processing_time:.2f}s")
        return pdf_bytes
        
    except Exception as e:
        logger.error(f"❌ PDF generation error: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=500, 
            detail=f"PDF generation failed: {str(e)}"
        )


def validate_pdf_content(pdf_bytes: bytes) -> dict:
    """
    Validate PDF file content and headers
    
    Args:
        pdf_bytes: The PDF file content as bytes
        
    Returns:
        dict: Validation result with status and details
    """
    try:
        # Check if content is empty
        if len(pdf_bytes) == 0:
            return {
                'valid': False,
                'error': 'PDF file is empty',
                'size': 0,
                'has_header': False
            }
        
        # Check PDF header
        has_pdf_header = pdf_bytes.startswith(b'%PDF')
        
        # Additional PDF structure validation
        has_eof = b'%%EOF' in pdf_bytes
        
        validation_result = {
            'valid': has_pdf_header and len(pdf_bytes) > 0,
            'size': len(pdf_bytes),
            'has_header': has_pdf_header,
            'has_eof': has_eof,
            'content_type': 'application/pdf'
        }
        
        if not has_pdf_header:
            validation_result['error'] = 'Invalid PDF header - file does not start with %PDF'
        elif not has_eof:
            validation_result['warning'] = 'PDF may be incomplete - missing %%EOF marker'
        
        logger.info(f"PDF validation: {validation_result}")
        return validation_result
        
    except Exception as e:
        logger.error(f"PDF validation error: {str(e)}")
        return {
            'valid': False,
            'error': f'PDF validation failed: {str(e)}',
            'size': len(pdf_bytes) if pdf_bytes else 0,
            'has_header': False
        }


def validate_docx_content(docx_bytes: bytes) -> dict:
    """
    Validate DOCX file content and headers
    
    Args:
        docx_bytes: The DOCX file content as bytes
        
    Returns:
        dict: Validation result with status and details
    """
    try:
        # Check if content is empty
        if len(docx_bytes) == 0:
            return {
                'valid': False,
                'error': 'DOCX file is empty',
                'size': 0,
                'has_header': False
            }
        
        # Check DOCX header (ZIP format)
        has_zip_header = docx_bytes.startswith(b'PK')
        
        # Additional DOCX structure validation
        # DOCX files should contain specific XML files
        has_content_types = b'[Content_Types].xml' in docx_bytes
        has_word_document = b'word/document.xml' in docx_bytes
        
        validation_result = {
            'valid': has_zip_header and len(docx_bytes) > 0,
            'size': len(docx_bytes),
            'has_header': has_zip_header,
            'has_content_types': has_content_types,
            'has_word_document': has_word_document,
            'content_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        }
        
        if not has_zip_header:
            validation_result['error'] = 'Invalid DOCX header - file does not start with PK (ZIP format)'
        elif not has_content_types:
            validation_result['warning'] = 'DOCX may be incomplete - missing Content_Types.xml'
        elif not has_word_document:
            validation_result['warning'] = 'DOCX may be incomplete - missing word/document.xml'
        
        logger.info(f"DOCX validation: {validation_result}")
        return validation_result
        
    except Exception as e:
        logger.error(f"DOCX validation error: {str(e)}")
        return {
            'valid': False,
            'error': f'DOCX validation failed: {str(e)}',
            'size': len(docx_bytes) if docx_bytes else 0,
            'has_header': False
        }


def validate_file_content(file_bytes: bytes, expected_format: str) -> dict:
    """
    Validate file content based on expected format
    
    Args:
        file_bytes: The file content as bytes
        expected_format: Expected format ('pdf' or 'docx')
        
    Returns:
        dict: Validation result with status and details
    """
    try:
        if expected_format.lower() == 'pdf':
            return validate_pdf_content(file_bytes)
        elif expected_format.lower() == 'docx':
            return validate_docx_content(file_bytes)
        else:
            return {
                'valid': False,
                'error': f'Unsupported format for validation: {expected_format}',
                'size': len(file_bytes) if file_bytes else 0
            }
    except Exception as e:
        logger.error(f"File validation error: {str(e)}")
        return {
            'valid': False,
            'error': f'File validation failed: {str(e)}',
            'size': len(file_bytes) if file_bytes else 0
        }


class ParaphraseRequest(BaseModel):
    """Input schema for paraphrasing request"""
    text: str = Field(..., min_length=1, description="Text to paraphrase")
    style: ParaphraseStyle = Field(default=ParaphraseStyle.neutral, description="Paraphrasing style")

    @field_validator('text')
    @classmethod
    def validate_text(cls, v: str) -> str:
        """Validate and clean input text"""
        if not v or not v.strip():
            raise ValueError("Text cannot be empty")
        
        # Clean text lightly (remove extra whitespace, preserve punctuation)
        cleaned = ' '.join(v.strip().split())
        
        # Check word count
        word_count = len(cleaned.split())
        if word_count < MIN_WORDS:
            raise ValueError(f"Text must contain at least {MIN_WORDS} words")
        
        # For long documents, we'll chunk them
        if len(cleaned) > MAX_INPUT_LENGTH * 3:  # Allow longer text for chunking
            logger.info(f"Long document detected: {len(cleaned)} characters")
        
        return cleaned


class DocumentRequest(BaseModel):
    """Input schema for document processing"""
    style: ParaphraseStyle = Field(default=ParaphraseStyle.neutral, description="Paraphrasing style")
    output_format: str = Field(default="json", description="Output format: json, docx, or pdf")


class ParaphraseResponse(BaseModel):
    """Output schema for paraphrasing response"""
    output: str = Field(..., description="Paraphrased text")


@app.get("/")
async def root():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "model_loaded": model is not None and tokenizer is not None
    }


@app.get("/health")
async def health():
    """Enhanced health check endpoint with comprehensive system status"""
    import psutil
    import sys
    
    try:
        # Basic model status
        model_loaded = model is not None and tokenizer is not None
        
        # System information
        memory_info = psutil.virtual_memory()
        cpu_percent = psutil.cpu_percent(interval=1)
        
        # Test model inference if loaded
        inference_working = False
        inference_time = None
        if model_loaded:
            try:
                start_time = time.time()
                test_result = await process_single_chunk("Test sentence for health check.", ParaphraseStyle.neutral)
                inference_time = time.time() - start_time
                inference_working = len(test_result.output) > 0
            except Exception as e:
                logger.warning(f"Health check inference failed: {e}")
                inference_working = False
        
        # Determine overall status
        if model_loaded and inference_working:
            overall_status = "healthy"
        elif model_loaded:
            overall_status = "degraded"
        else:
            overall_status = "unhealthy"
        
        health_data = {
            "status": overall_status,
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "model_status": {
                "loaded": model_loaded,
                "inference_working": inference_working,
                "inference_time_ms": round(inference_time * 1000, 2) if inference_time else None
            },
            "system_info": {
                "python_version": sys.version.split()[0],
                "memory_usage_mb": round(memory_info.used / 1024 / 1024, 2),
                "memory_available_mb": round(memory_info.available / 1024 / 1024, 2),
                "memory_percent": memory_info.percent,
                "cpu_percent": cpu_percent
            },
            "dependencies": {
                "torch_version": torch.__version__,
                "transformers_available": True,  # If we got here, transformers is available
                "reportlab_available": True,     # If we got here, reportlab is available
                "docx_available": True           # If we got here, python-docx is available
            }
        }
        
        # Log health check
        logger.info(f"Health check completed: {overall_status}")
        
        return health_data
        
    except Exception as e:
        error_id = error_tracker.capture_error(e, {"endpoint": "/health"})
        return {
            "status": "unhealthy",
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "error": f"Health check failed: {str(e)}",
            "error_id": error_id
        }

@app.get("/model-status")
async def model_status():
    """Detailed model status endpoint"""
    try:
        model_loaded = model is not None and tokenizer is not None
        
        if not model_loaded:
            return {
                "loaded": False,
                "error": "Model or tokenizer not loaded",
                "timestamp": datetime.utcnow().isoformat() + "Z"
            }
        
        # Test inference with timing
        test_texts = [
            "Short test.",
            "This is a medium length test sentence for model verification.",
            "This is a longer test sentence that will help us understand how the model performs with more substantial input text for comprehensive testing."
        ]
        
        inference_results = []
        for i, text in enumerate(test_texts):
            try:
                start_time = time.time()
                result = await process_single_chunk(text, ParaphraseStyle.neutral)
                inference_time = time.time() - start_time
                
                inference_results.append({
                    "test_case": i + 1,
                    "input_length": len(text),
                    "output_length": len(result.output),
                    "inference_time_ms": round(inference_time * 1000, 2),
                    "success": True
                })
            except Exception as e:
                inference_results.append({
                    "test_case": i + 1,
                    "input_length": len(text),
                    "success": False,
                    "error": str(e)
                })
        
        return {
            "loaded": True,
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "model_info": {
                "model_name": "Vamsi/T5_Paraphrase_Paws",
                "device": "cpu"
            },
            "inference_tests": inference_results,
            "performance_summary": {
                "successful_tests": sum(1 for r in inference_results if r["success"]),
                "total_tests": len(inference_results),
                "avg_inference_time_ms": round(
                    sum(r.get("inference_time_ms", 0) for r in inference_results if r["success"]) / 
                    max(1, sum(1 for r in inference_results if r["success"])), 2
                )
            }
        }
        
    except Exception as e:
        error_id = error_tracker.capture_error(e, {"endpoint": "/model-status"})
        return {
            "loaded": False,
            "error": str(e),
            "error_id": error_id,
            "timestamp": datetime.utcnow().isoformat() + "Z"
        }

@app.get("/environment")
async def environment_info():
    """System environment information endpoint"""
    try:
        import psutil
        import sys
        import platform
        
        # Get package versions
        package_versions = {}
        try:
            import torch
            package_versions["torch"] = torch.__version__
        except ImportError:
            package_versions["torch"] = "not_installed"
        
        try:
            import transformers
            package_versions["transformers"] = transformers.__version__
        except ImportError:
            package_versions["transformers"] = "not_installed"
        
        try:
            import reportlab
            package_versions["reportlab"] = reportlab.Version
        except ImportError:
            package_versions["reportlab"] = "not_installed"
        
        try:
            import docx
            package_versions["python-docx"] = "installed"  # python-docx doesn't have __version__
        except ImportError:
            package_versions["python-docx"] = "not_installed"
        
        # System information
        memory_info = psutil.virtual_memory()
        disk_info = psutil.disk_usage('/')
        
        return {
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "system": {
                "platform": platform.platform(),
                "python_version": sys.version,
                "architecture": platform.architecture()[0],
                "processor": platform.processor() or "unknown"
            },
            "memory": {
                "total_gb": round(memory_info.total / 1024 / 1024 / 1024, 2),
                "available_gb": round(memory_info.available / 1024 / 1024 / 1024, 2),
                "used_gb": round(memory_info.used / 1024 / 1024 / 1024, 2),
                "percent_used": memory_info.percent
            },
            "disk": {
                "total_gb": round(disk_info.total / 1024 / 1024 / 1024, 2),
                "free_gb": round(disk_info.free / 1024 / 1024 / 1024, 2),
                "used_gb": round(disk_info.used / 1024 / 1024 / 1024, 2),
                "percent_used": round((disk_info.used / disk_info.total) * 100, 2)
            },
            "packages": package_versions,
            "environment_variables": {
                "PORT": os.getenv("PORT", "not_set"),
                "PYTHONPATH": os.getenv("PYTHONPATH", "not_set")
            }
        }
        
    except Exception as e:
        error_id = error_tracker.capture_error(e, {"endpoint": "/environment"})
        return {
            "error": str(e),
            "error_id": error_id,
            "timestamp": datetime.utcnow().isoformat() + "Z"
        }


@app.post("/humanize", response_model=ParaphraseResponse)
async def humanize(request: ParaphraseRequest) -> ParaphraseResponse:
    """
    Paraphrase input text using T5 model with style support.
    
    Args:
        request: ParaphraseRequest containing text and style
        
    Returns:
        ParaphraseResponse with paraphrased text
        
    Raises:
        HTTPException: If model is not loaded or inference fails
    """
    if model is None or tokenizer is None:
        logger.error("Model not loaded")
        raise HTTPException(status_code=503, detail="Model not loaded")
    
    input_text = request.text
    style = request.style
    logger.info(f"Received request: {len(input_text)} characters, {len(input_text.split())} words, style: {style}")
    
    try:
        # For short text, process directly
        if len(input_text.split()) <= 100:
            return await process_single_chunk(input_text, style)
        
        # For long text, use chunking
        return await process_long_text(input_text, style)
        
    except Exception as e:
        logger.error(f"Inference error: {str(e)}")
        # Return original text on error (graceful degradation)
        logger.warning("Returning original text due to inference error")
        return ParaphraseResponse(output=input_text)


async def process_single_chunk(text: str, style: ParaphraseStyle) -> ParaphraseResponse:
    """Process a single chunk of text"""
    # Prepare input with style-specific prompt
    input_text_prepared = build_prompt(text, style)
    
    # Tokenize
    input_ids = tokenizer.encode(
        input_text_prepared,
        return_tensors="pt",
        max_length=MAX_INPUT_LENGTH,
        truncation=True,
        padding=True
    )
    
    # Inference with no_grad for efficiency
    with torch.no_grad():
        # Generate with beam search for accuracy
        outputs = model.generate(
            input_ids,
            max_length=MAX_OUTPUT_LENGTH,
            num_beams=NUM_BEAMS,
            no_repeat_ngram_size=NO_REPEAT_NGRAM_SIZE,
            early_stopping=True,
            do_sample=False,  # Deterministic, no randomness
            temperature=None,  # Not used when do_sample=False
        )
    
    # Decode output
    paraphrased_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
    
    # Clean output
    paraphrased_text = paraphrased_text.strip()
    
    # Fallback: if output is empty or too short, return original
    if not paraphrased_text or len(paraphrased_text.split()) < MIN_WORDS:
        logger.warning("Generated output too short, returning original text")
        paraphrased_text = text
    
    logger.info(f"Generated paraphrase: {len(paraphrased_text)} characters")
    
    return ParaphraseResponse(output=paraphrased_text)


async def process_long_text(text: str, style: ParaphraseStyle) -> ParaphraseResponse:
    """Process long text by chunking"""
    # Choose chunking strategy based on style
    if style == ParaphraseStyle.bullets:
        chunks = paragraph_chunks(text, tokenizer, CHUNK_TOKEN_LIMIT)
    else:
        chunks = chunk_text(text, tokenizer, CHUNK_TOKEN_LIMIT)
    
    if len(chunks) > MAX_DOC_CHUNKS:
        raise HTTPException(status_code=413, detail="Document too large")
    
    logger.info(f"Processing {len(chunks)} chunks")
    
    results = []
    for i, chunk in enumerate(chunks):
        logger.info(f"Processing chunk {i+1}/{len(chunks)}")
        
        # Process each chunk
        prompt = build_prompt(chunk, style)
        input_ids = tokenizer.encode(
            prompt,
            return_tensors="pt",
            max_length=MAX_INPUT_LENGTH,
            truncation=True
        )
        
        with torch.no_grad():
            output = model.generate(
                input_ids,
                max_length=MAX_OUTPUT_LENGTH,
                num_beams=NUM_BEAMS,
                no_repeat_ngram_size=NO_REPEAT_NGRAM_SIZE,
                early_stopping=True,
                do_sample=False
            )
        
        chunk_result = tokenizer.decode(output[0], skip_special_tokens=True)
        results.append(chunk_result.strip())
        
        # Small delay to prevent overwhelming the CPU
        await asyncio.sleep(0.1)
    
    # Join results appropriately based on style
    if style == ParaphraseStyle.bullets:
        final_output = "\n\n".join(results)
    else:
        final_output = " ".join(results)
    
    logger.info(f"Completed long text processing: {len(final_output)} characters")
    
    return ParaphraseResponse(output=final_output)


@app.post("/humanize-document")
async def humanize_document(
    file: UploadFile = File(...),
    style: ParaphraseStyle = Form(ParaphraseStyle.neutral),
    output_format: str = Form("json")  # json | docx | pdf
):
    """
    Process uploaded document with style-specific paraphrasing.
    
    Args:
        file: Uploaded document (txt, docx, etc.)
        style: Paraphrasing style
        output_format: Output format (json, docx, pdf)
        
    Returns:
        Processed document in requested format
    """
    # Generate request ID for tracking
    request_id = error_tracker.log_request({
        "endpoint": "/humanize-document",
        "method": "POST",
        "filename": file.filename,
        "content_type": file.content_type,
        "style": style,
        "output_format": output_format
    })
    
    request_start_time = time.time()
    
    try:
        # Check model availability
        if model is None or tokenizer is None:
            error_tracker.capture_error(
                Exception("Model not loaded"), 
                {"stage": "model_check", "request_id": request_id}
            )
            raise HTTPException(status_code=503, detail="Model not loaded")
        
        error_tracker.log_processing_stage("file_upload", {
            "filename": file.filename,
            "content_type": file.content_type,
            "style": style,
            "output_format": output_format
        }, request_id)
        
        # Read file content
        content = await file.read()
        filename = file.filename.lower() if file.filename else ""
        
        error_tracker.log_processing_stage("file_read", {
            "file_size_bytes": len(content),
            "filename": filename
        }, request_id)
        
        # Extract text based on file type
        text_extraction_start = time.time()
        try:
            if filename.endswith(".txt"):
                text = content.decode('utf-8')
                error_tracker.log_processing_stage("text_extraction", {
                    "file_type": "txt",
                    "extracted_length": len(text),
                    "extraction_time_ms": round((time.time() - text_extraction_start) * 1000, 2)
                }, request_id)
            elif filename.endswith(".docx"):
                # Parse DOCX file using python-docx
                try:
                    from docx import Document
                    doc_file = io.BytesIO(content)
                    doc = Document(doc_file)
                    text = "\n".join([paragraph.text for paragraph in doc.paragraphs if paragraph.text.strip()])
                    if not text.strip():
                        error_tracker.capture_error(
                            ValueError("DOCX file appears to be empty"),
                            {"stage": "docx_parsing", "filename": filename},
                            request_id
                        )
                        raise HTTPException(status_code=400, detail="DOCX file appears to be empty")
                    
                    error_tracker.log_processing_stage("text_extraction", {
                        "file_type": "docx",
                        "extracted_length": len(text),
                        "paragraph_count": len(doc.paragraphs),
                        "extraction_time_ms": round((time.time() - text_extraction_start) * 1000, 2)
                    }, request_id)
                except Exception as docx_error:
                    error_tracker.capture_error(docx_error, {
                        "stage": "docx_parsing",
                        "filename": filename,
                        "file_size": len(content)
                    }, request_id)
                    raise HTTPException(status_code=400, detail=f"Could not parse DOCX file: {str(docx_error)}")
            else:
                # Try to decode as text
                text = content.decode('utf-8')
                error_tracker.log_processing_stage("text_extraction", {
                    "file_type": "generic",
                    "extracted_length": len(text),
                    "extraction_time_ms": round((time.time() - text_extraction_start) * 1000, 2)
                }, request_id)
        except HTTPException:
            # Re-raise HTTP exceptions
            raise
        except Exception as e:
            error_tracker.capture_error(e, {
                "stage": "text_extraction",
                "filename": filename,
                "file_size": len(content)
            }, request_id)
            raise HTTPException(status_code=400, detail=f"Could not process file: {str(e)}")
        
        # Validate extracted text
        word_count = len(text.split())
        if not text or word_count < MIN_WORDS:
            error_tracker.capture_error(
                ValueError(f"Invalid text extracted: {word_count} words (minimum: {MIN_WORDS})"),
                {"stage": "text_validation", "word_count": word_count, "text_length": len(text)},
                request_id
            )
            raise HTTPException(status_code=400, detail="Could not extract valid text")
        
        error_tracker.log_processing_stage("text_validation", {
            "text_length": len(text),
            "word_count": word_count,
            "validation_passed": True
        }, request_id)
        
        # Process the text
        processing_start_time = time.time()
        error_tracker.log_processing_stage("text_processing_start", {
            "input_length": len(text),
            "word_count": word_count,
            "style": style
        }, request_id)
        
        result = await process_long_text(text, style)
        paraphrased = result.output
        processing_time = time.time() - processing_start_time
        
        error_tracker.log_processing_stage("text_processing_complete", {
            "output_length": len(paraphrased),
            "processing_time_ms": round(processing_time * 1000, 2)
        }, request_id)
        
        # Return in requested format
        if output_format == "json":
            total_time = time.time() - request_start_time
            error_tracker.log_processing_stage("response_json", {
                "total_time_ms": round(total_time * 1000, 2)
            }, request_id)
            return {"output": paraphrased, "style": style}
        
        elif output_format == "pdf":
            file_start_time = time.time()
            error_tracker.log_processing_stage("pdf_generation_start", {
                "input_length": len(paraphrased)
            }, request_id)
            
            pdf_bytes = create_pdf(paraphrased)
            file_time = time.time() - file_start_time
            total_time = time.time() - request_start_time
            
            error_tracker.log_processing_stage("pdf_generation_complete", {
                "pdf_size_bytes": len(pdf_bytes),
                "generation_time_ms": round(file_time * 1000, 2),
                "total_time_ms": round(total_time * 1000, 2)
            }, request_id)
            
            return Response(
                content=pdf_bytes,
                media_type="application/pdf",
                headers={
                    "Content-Disposition": "attachment; filename=humanized.pdf",
                    "Content-Length": str(len(pdf_bytes)),
                    "Cache-Control": "no-cache, no-store, must-revalidate"
                }
            )
        
        elif output_format == "docx":
            file_start_time = time.time()
            error_tracker.log_processing_stage("docx_generation_start", {
                "input_length": len(paraphrased)
            }, request_id)
            
            docx_bytes = create_docx(paraphrased)
            file_time = time.time() - file_start_time
            total_time = time.time() - request_start_time
            
            error_tracker.log_processing_stage("docx_generation_complete", {
                "docx_size_bytes": len(docx_bytes),
                "generation_time_ms": round(file_time * 1000, 2),
                "total_time_ms": round(total_time * 1000, 2)
            }, request_id)
            
            return Response(
                content=docx_bytes,
                media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                headers={
                    "Content-Disposition": "attachment; filename=humanized.docx",
                    "Content-Length": str(len(docx_bytes)),
                    "Cache-Control": "no-cache, no-store, must-revalidate"
                }
            )
        
        else:
            error_tracker.capture_error(
                ValueError(f"Invalid output format: {output_format}"),
                {"stage": "format_validation", "output_format": output_format},
                request_id
            )
            raise HTTPException(status_code=400, detail="Invalid output format")
    
    except HTTPException:
        # Re-raise HTTP exceptions (they're already logged)
        raise
    except Exception as e:
        # Capture any unexpected errors
        error_id = error_tracker.capture_error(e, {
            "stage": "unexpected_error",
            "request_id": request_id,
            "total_time_ms": round((time.time() - request_start_time) * 1000, 2)
        }, request_id)
        raise HTTPException(status_code=500, detail=f"Internal server error (ID: {error_id})")
    try:
        if filename.endswith(".txt"):
            text = content.decode('utf-8')
            logger.info(f"πŸ“ Extracted text from TXT: {len(text)} characters")
        elif filename.endswith(".docx"):
            # Parse DOCX file using python-docx
            try:
                from docx import Document
                doc_file = io.BytesIO(content)
                doc = Document(doc_file)
                text = "\n".join([paragraph.text for paragraph in doc.paragraphs if paragraph.text.strip()])
                if not text.strip():
                    logger.error("❌ DOCX file appears to be empty")
                    raise HTTPException(status_code=400, detail="DOCX file appears to be empty")
                logger.info(f"πŸ“„ Extracted text from DOCX: {len(text)} characters, "
                           f"{len(doc.paragraphs)} paragraphs")
            except Exception as docx_error:
                logger.error(f"❌ DOCX parsing error: {str(docx_error)}", exc_info=True)
                raise HTTPException(status_code=400, detail=f"Could not parse DOCX file: {str(docx_error)}")
        else:
            # Try to decode as text
            text = content.decode('utf-8')
            logger.info(f"πŸ“ Extracted text from generic file: {len(text)} characters")
    except HTTPException:
        # Re-raise HTTP exceptions
        raise
    except Exception as e:
        logger.error(f"❌ File processing error: {str(e)}", exc_info=True)
        raise HTTPException(status_code=400, detail=f"Could not process file: {str(e)}")
    
    if not text or len(text.split()) < MIN_WORDS:
        logger.error(f"❌ Invalid text extracted: {len(text.split())} words (minimum: {MIN_WORDS})")
        raise HTTPException(status_code=400, detail="Could not extract valid text")
    
    # Process the text
    word_count = len(text.split())
    logger.info(f"πŸ€– Processing document: {len(text)} characters, {word_count} words, style: {style}")
    
    # Use long text processing
    processing_start_time = time.time()
    result = await process_long_text(text, style)
    paraphrased = result.output
    processing_time = time.time() - processing_start_time
    
    logger.info(f"βœ… Text processing completed in {processing_time:.2f}s: "
               f"{len(paraphrased)} characters output")
    
    # Return in requested format
    if output_format == "json":
        total_time = time.time() - request_start_time
        logger.info(f"πŸ“€ Returning JSON response (total time: {total_time:.2f}s)")
        return {"output": paraphrased, "style": style}
    
    elif output_format == "pdf":
        logger.info(f"πŸ“‘ Generating PDF for {len(paraphrased)} characters")
        file_start_time = time.time()
        pdf_bytes = create_pdf(paraphrased)
        file_time = time.time() - file_start_time
        total_time = time.time() - request_start_time
        
        logger.info(f"πŸ“€ Returning PDF response: {len(pdf_bytes)} bytes "
                   f"(file generation: {file_time:.2f}s, total: {total_time:.2f}s)")
        
        return Response(
            content=pdf_bytes,
            media_type="application/pdf",
            headers={
                "Content-Disposition": "attachment; filename=humanized.pdf",
                "Content-Length": str(len(pdf_bytes)),
                "Cache-Control": "no-cache, no-store, must-revalidate"
            }
        )
    
    elif output_format == "docx":
        logger.info(f"πŸ“„ Generating DOCX for {len(paraphrased)} characters")
        file_start_time = time.time()
        docx_bytes = create_docx(paraphrased)
        file_time = time.time() - file_start_time
        total_time = time.time() - request_start_time
        
        logger.info(f"πŸ“€ Returning DOCX response: {len(docx_bytes)} bytes "
                   f"(file generation: {file_time:.2f}s, total: {total_time:.2f}s)")
        
        return Response(
            content=docx_bytes,
            media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            headers={
                "Content-Disposition": "attachment; filename=humanized.docx",
                "Content-Length": str(len(docx_bytes)),
                "Cache-Control": "no-cache, no-store, must-revalidate"
            }
        )
    
    else:
        logger.error(f"❌ Invalid output format requested: {output_format}")
        raise HTTPException(status_code=400, detail="Invalid output format")


@app.post("/humanize-document-stream")
async def humanize_document_stream(
    file: UploadFile = File(...),
    style: ParaphraseStyle = Form(ParaphraseStyle.neutral)
):
    """
    Process document with streaming progress updates.
    
    Args:
        file: Uploaded document
        style: Paraphrasing style
        
    Returns:
        Streaming JSON responses with progress updates
    """
    if model is None or tokenizer is None:
        raise HTTPException(status_code=503, detail="Model not loaded")
    
    # Read and extract text
    content = await file.read()
    filename = file.filename.lower() if file.filename else ""
    
    try:
        if filename.endswith(".txt"):
            text = content.decode('utf-8')
        else:
            text = content.decode('utf-8')
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Could not process file: {str(e)}")
    
    if not text or len(text.split()) < MIN_WORDS:
        raise HTTPException(status_code=400, detail="Could not extract valid text")
    
    # Choose chunking strategy
    if style == ParaphraseStyle.bullets:
        chunks = paragraph_chunks(text, tokenizer, CHUNK_TOKEN_LIMIT)
    else:
        chunks = chunk_text(text, tokenizer, CHUNK_TOKEN_LIMIT)
    
    if len(chunks) > MAX_DOC_CHUNKS:
        raise HTTPException(status_code=413, detail="Document too large")
    
    async def stream_processing():
        """Generator for streaming responses"""
        total = len(chunks)
        results = []
        
        for idx, chunk in enumerate(chunks, start=1):
            # Send progress update
            yield json.dumps({
                "type": "progress",
                "current": idx,
                "total": total,
                "message": f"Processing chunk {idx} of {total}"
            }) + "\n"
            
            # Process chunk
            prompt = build_prompt(chunk, style)
            input_ids = tokenizer.encode(
                prompt,
                return_tensors="pt",
                max_length=MAX_INPUT_LENGTH,
                truncation=True
            )
            
            with torch.no_grad():
                output = model.generate(
                    input_ids,
                    max_length=MAX_OUTPUT_LENGTH,
                    num_beams=NUM_BEAMS,
                    no_repeat_ngram_size=NO_REPEAT_NGRAM_SIZE,
                    early_stopping=True,
                    do_sample=False
                )
            
            chunk_result = tokenizer.decode(output[0], skip_special_tokens=True)
            results.append(chunk_result.strip())
            
            # Send chunk result
            yield json.dumps({
                "type": "chunk",
                "content": chunk_result.strip(),
                "index": idx
            }) + "\n"
            
            await asyncio.sleep(0.1)  # Allow event loop to process
        
        # Send final result
        if style == ParaphraseStyle.bullets:
            final_output = "\n\n".join(results)
        else:
            final_output = " ".join(results)
        
        yield json.dumps({
            "type": "done",
            "output": final_output,
            "style": style
        }) + "\n"
    
    return StreamingResponse(
        stream_processing(),
        media_type="application/json"
    )


if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", 7860))
    uvicorn.run(app, host="0.0.0.0", port=port)