Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,6 +11,7 @@ import logging
|
|
| 11 |
import io
|
| 12 |
import asyncio
|
| 13 |
import json
|
|
|
|
| 14 |
from typing import Optional, List
|
| 15 |
from enum import Enum
|
| 16 |
from contextlib import asynccontextmanager
|
|
@@ -20,7 +21,11 @@ from fastapi.responses import StreamingResponse, Response
|
|
| 20 |
from pydantic import BaseModel, Field, field_validator
|
| 21 |
from transformers import T5ForConditionalGeneration, T5Tokenizer
|
| 22 |
from docx import Document
|
| 23 |
-
from reportlab.lib.pagesizes import LETTER
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
from reportlab.pdfgen import canvas
|
| 25 |
|
| 26 |
# Configure logging
|
|
@@ -30,6 +35,36 @@ logging.basicConfig(
|
|
| 30 |
)
|
| 31 |
logger = logging.getLogger(__name__)
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
# Global model and tokenizer (loaded once on startup)
|
| 34 |
model: Optional[T5ForConditionalGeneration] = None
|
| 35 |
tokenizer: Optional[T5Tokenizer] = None
|
|
@@ -87,6 +122,11 @@ async def lifespan(app: FastAPI):
|
|
| 87 |
"""Lifespan event handler for FastAPI"""
|
| 88 |
# Startup
|
| 89 |
logger.info("Starting up...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
await load_model()
|
| 91 |
logger.info("Startup complete")
|
| 92 |
|
|
@@ -191,106 +231,365 @@ def paragraph_chunks(text: str, tokenizer, max_tokens: int) -> List[str]:
|
|
| 191 |
|
| 192 |
|
| 193 |
def create_docx(text: str) -> bytes:
|
| 194 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 195 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
doc = Document()
|
| 197 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
# Split text into paragraphs
|
| 199 |
paragraphs = text.split('\n\n')
|
|
|
|
|
|
|
| 200 |
|
| 201 |
-
for
|
| 202 |
-
if not
|
| 203 |
continue
|
| 204 |
|
| 205 |
-
#
|
| 206 |
-
lines =
|
| 207 |
|
| 208 |
for line in lines:
|
| 209 |
line = line.strip()
|
| 210 |
if not line:
|
| 211 |
continue
|
| 212 |
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
elif line.isupper() and len(line.split()) <= 5:
|
| 217 |
-
|
| 218 |
-
|
|
|
|
| 219 |
else:
|
| 220 |
-
|
| 221 |
-
|
|
|
|
| 222 |
|
| 223 |
-
# Add spacing between sections
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
| 226 |
|
|
|
|
| 227 |
buffer = io.BytesIO()
|
| 228 |
doc.save(buffer)
|
| 229 |
buffer.seek(0)
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
except Exception as e:
|
| 232 |
-
logger.error(f"DOCX generation error: {str(e)}")
|
| 233 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
|
| 236 |
def create_pdf(text: str) -> bytes:
|
| 237 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 238 |
try:
|
|
|
|
|
|
|
|
|
|
| 239 |
buffer = io.BytesIO()
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
# Split text into paragraphs
|
| 248 |
paragraphs = text.split('\n\n')
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
-
for
|
| 251 |
-
if not
|
| 252 |
continue
|
| 253 |
|
| 254 |
-
#
|
| 255 |
-
|
| 256 |
-
lines = paragraph.split('\n')
|
| 257 |
-
else:
|
| 258 |
-
# Wrap long paragraphs
|
| 259 |
-
words = paragraph.split()
|
| 260 |
-
lines = []
|
| 261 |
-
current_line = ""
|
| 262 |
-
|
| 263 |
-
for word in words:
|
| 264 |
-
test_line = current_line + " " + word if current_line else word
|
| 265 |
-
# Rough character width estimation
|
| 266 |
-
if len(test_line) * 6 < max_width:
|
| 267 |
-
current_line = test_line
|
| 268 |
-
else:
|
| 269 |
-
if current_line:
|
| 270 |
-
lines.append(current_line)
|
| 271 |
-
current_line = word
|
| 272 |
-
|
| 273 |
-
if current_line:
|
| 274 |
-
lines.append(current_line)
|
| 275 |
|
| 276 |
-
# Draw lines
|
| 277 |
for line in lines:
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
|
| 283 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
|
| 285 |
-
# Add
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
-
|
| 289 |
buffer.seek(0)
|
| 290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
except Exception as e:
|
| 292 |
-
logger.error(f"PDF generation error: {str(e)}")
|
| 293 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
|
| 296 |
class ParaphraseRequest(BaseModel):
|
|
@@ -500,16 +799,24 @@ async def humanize_document(
|
|
| 500 |
Processed document in requested format
|
| 501 |
"""
|
| 502 |
if model is None or tokenizer is None:
|
|
|
|
| 503 |
raise HTTPException(status_code=503, detail="Model not loaded")
|
| 504 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 505 |
# Read file content
|
| 506 |
content = await file.read()
|
| 507 |
filename = file.filename.lower() if file.filename else ""
|
| 508 |
|
|
|
|
|
|
|
| 509 |
# Extract text based on file type
|
| 510 |
try:
|
| 511 |
if filename.endswith(".txt"):
|
| 512 |
text = content.decode('utf-8')
|
|
|
|
| 513 |
elif filename.endswith(".docx"):
|
| 514 |
# Parse DOCX file using python-docx
|
| 515 |
try:
|
|
@@ -518,54 +825,89 @@ async def humanize_document(
|
|
| 518 |
doc = Document(doc_file)
|
| 519 |
text = "\n".join([paragraph.text for paragraph in doc.paragraphs if paragraph.text.strip()])
|
| 520 |
if not text.strip():
|
|
|
|
| 521 |
raise HTTPException(status_code=400, detail="DOCX file appears to be empty")
|
|
|
|
|
|
|
| 522 |
except Exception as docx_error:
|
| 523 |
-
logger.error(f"DOCX parsing error: {str(docx_error)}")
|
| 524 |
raise HTTPException(status_code=400, detail=f"Could not parse DOCX file: {str(docx_error)}")
|
| 525 |
else:
|
| 526 |
# Try to decode as text
|
| 527 |
text = content.decode('utf-8')
|
|
|
|
| 528 |
except HTTPException:
|
| 529 |
# Re-raise HTTP exceptions
|
| 530 |
raise
|
| 531 |
except Exception as e:
|
|
|
|
| 532 |
raise HTTPException(status_code=400, detail=f"Could not process file: {str(e)}")
|
| 533 |
|
| 534 |
if not text or len(text.split()) < MIN_WORDS:
|
|
|
|
| 535 |
raise HTTPException(status_code=400, detail="Could not extract valid text")
|
| 536 |
|
| 537 |
# Process the text
|
| 538 |
-
|
|
|
|
| 539 |
|
| 540 |
# Use long text processing
|
|
|
|
| 541 |
result = await process_long_text(text, style)
|
| 542 |
paraphrased = result.output
|
|
|
|
|
|
|
|
|
|
|
|
|
| 543 |
|
| 544 |
# Return in requested format
|
| 545 |
if output_format == "json":
|
|
|
|
|
|
|
| 546 |
return {"output": paraphrased, "style": style}
|
| 547 |
|
| 548 |
elif output_format == "pdf":
|
| 549 |
-
logger.info(f"Generating PDF for {len(paraphrased)} characters")
|
|
|
|
| 550 |
pdf_bytes = create_pdf(paraphrased)
|
| 551 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
return Response(
|
| 553 |
content=pdf_bytes,
|
| 554 |
media_type="application/pdf",
|
| 555 |
-
headers={
|
|
|
|
|
|
|
|
|
|
|
|
|
| 556 |
)
|
| 557 |
|
| 558 |
elif output_format == "docx":
|
| 559 |
-
logger.info(f"Generating DOCX for {len(paraphrased)} characters")
|
|
|
|
| 560 |
docx_bytes = create_docx(paraphrased)
|
| 561 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 562 |
return Response(
|
| 563 |
content=docx_bytes,
|
| 564 |
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
| 565 |
-
headers={
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
)
|
| 567 |
|
| 568 |
else:
|
|
|
|
| 569 |
raise HTTPException(status_code=400, detail="Invalid output format")
|
| 570 |
|
| 571 |
|
|
|
|
| 11 |
import io
|
| 12 |
import asyncio
|
| 13 |
import json
|
| 14 |
+
import time
|
| 15 |
from typing import Optional, List
|
| 16 |
from enum import Enum
|
| 17 |
from contextlib import asynccontextmanager
|
|
|
|
| 21 |
from pydantic import BaseModel, Field, field_validator
|
| 22 |
from transformers import T5ForConditionalGeneration, T5Tokenizer
|
| 23 |
from docx import Document
|
| 24 |
+
from reportlab.lib.pagesizes import LETTER, letter
|
| 25 |
+
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 26 |
+
from reportlab.lib.units import inch
|
| 27 |
+
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
|
| 28 |
+
from reportlab.lib.enums import TA_LEFT, TA_JUSTIFY
|
| 29 |
from reportlab.pdfgen import canvas
|
| 30 |
|
| 31 |
# Configure logging
|
|
|
|
| 35 |
)
|
| 36 |
logger = logging.getLogger(__name__)
|
| 37 |
|
| 38 |
+
# Validate dependencies on startup
|
| 39 |
+
def validate_dependencies():
|
| 40 |
+
"""Validate that all required dependencies are available"""
|
| 41 |
+
try:
|
| 42 |
+
# Test ReportLab imports
|
| 43 |
+
from reportlab.lib.pagesizes import letter
|
| 44 |
+
from reportlab.lib.styles import getSampleStyleSheet
|
| 45 |
+
from reportlab.platypus import SimpleDocTemplate, Paragraph
|
| 46 |
+
logger.info("β
ReportLab dependencies validated")
|
| 47 |
+
|
| 48 |
+
# Test python-docx imports
|
| 49 |
+
from docx import Document
|
| 50 |
+
from docx.shared import Pt, Inches
|
| 51 |
+
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
| 52 |
+
logger.info("β
python-docx dependencies validated")
|
| 53 |
+
|
| 54 |
+
return True
|
| 55 |
+
except ImportError as e:
|
| 56 |
+
logger.error(f"β Missing dependency: {str(e)}")
|
| 57 |
+
raise HTTPException(
|
| 58 |
+
status_code=503,
|
| 59 |
+
detail=f"Required dependency missing: {str(e)}"
|
| 60 |
+
)
|
| 61 |
+
except Exception as e:
|
| 62 |
+
logger.error(f"β Dependency validation error: {str(e)}")
|
| 63 |
+
raise HTTPException(
|
| 64 |
+
status_code=503,
|
| 65 |
+
detail=f"Dependency validation failed: {str(e)}"
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
# Global model and tokenizer (loaded once on startup)
|
| 69 |
model: Optional[T5ForConditionalGeneration] = None
|
| 70 |
tokenizer: Optional[T5Tokenizer] = None
|
|
|
|
| 122 |
"""Lifespan event handler for FastAPI"""
|
| 123 |
# Startup
|
| 124 |
logger.info("Starting up...")
|
| 125 |
+
|
| 126 |
+
# Validate dependencies first
|
| 127 |
+
validate_dependencies()
|
| 128 |
+
|
| 129 |
+
# Then load model
|
| 130 |
await load_model()
|
| 131 |
logger.info("Startup complete")
|
| 132 |
|
|
|
|
| 231 |
|
| 232 |
|
| 233 |
def create_docx(text: str) -> bytes:
|
| 234 |
+
"""
|
| 235 |
+
Create DOCX file from text with proper formatting.
|
| 236 |
+
Handles paragraphs, bullet points, and headings.
|
| 237 |
+
"""
|
| 238 |
try:
|
| 239 |
+
from docx import Document
|
| 240 |
+
from docx.shared import Pt, RGBColor, Inches
|
| 241 |
+
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
| 242 |
+
|
| 243 |
+
logger.info(f"π Starting DOCX generation for {len(text)} characters")
|
| 244 |
+
start_time = time.time()
|
| 245 |
+
|
| 246 |
doc = Document()
|
| 247 |
|
| 248 |
+
# Set default styling
|
| 249 |
+
style = doc.styles['Normal']
|
| 250 |
+
font = style.font
|
| 251 |
+
font.name = 'Calibri'
|
| 252 |
+
font.size = Pt(11)
|
| 253 |
+
|
| 254 |
+
# Set page margins
|
| 255 |
+
sections = doc.sections
|
| 256 |
+
for section in sections:
|
| 257 |
+
section.top_margin = Inches(1)
|
| 258 |
+
section.bottom_margin = Inches(1)
|
| 259 |
+
section.left_margin = Inches(1)
|
| 260 |
+
section.right_margin = Inches(1)
|
| 261 |
+
|
| 262 |
# Split text into paragraphs
|
| 263 |
paragraphs = text.split('\n\n')
|
| 264 |
+
paragraph_count = 0
|
| 265 |
+
bullet_count = 0
|
| 266 |
|
| 267 |
+
for paragraph_text in paragraphs:
|
| 268 |
+
if not paragraph_text.strip():
|
| 269 |
continue
|
| 270 |
|
| 271 |
+
# Split by lines for bullet points
|
| 272 |
+
lines = paragraph_text.split('\n')
|
| 273 |
|
| 274 |
for line in lines:
|
| 275 |
line = line.strip()
|
| 276 |
if not line:
|
| 277 |
continue
|
| 278 |
|
| 279 |
+
# Handle bullet points
|
| 280 |
+
if line.startswith('β’') or line.startswith('-') or line.startswith('*'):
|
| 281 |
+
# Remove bullet character
|
| 282 |
+
clean_line = line[1:].strip()
|
| 283 |
+
doc.add_paragraph(clean_line, style='List Bullet')
|
| 284 |
+
bullet_count += 1
|
| 285 |
+
|
| 286 |
+
# Handle headings (all caps, short)
|
| 287 |
elif line.isupper() and len(line.split()) <= 5:
|
| 288 |
+
heading = doc.add_heading(line, level=2)
|
| 289 |
+
|
| 290 |
+
# Regular paragraph
|
| 291 |
else:
|
| 292 |
+
para = doc.add_paragraph(line)
|
| 293 |
+
para.alignment = WD_ALIGN_PARAGRAPH.LEFT
|
| 294 |
+
paragraph_count += 1
|
| 295 |
|
| 296 |
+
# Add spacing between sections (empty paragraph)
|
| 297 |
+
doc.add_paragraph()
|
| 298 |
+
|
| 299 |
+
# Remove last empty paragraph
|
| 300 |
+
if len(doc.paragraphs) > 0 and not doc.paragraphs[-1].text.strip():
|
| 301 |
+
doc._element.body.remove(doc.paragraphs[-1]._element)
|
| 302 |
|
| 303 |
+
# Save to buffer
|
| 304 |
buffer = io.BytesIO()
|
| 305 |
doc.save(buffer)
|
| 306 |
buffer.seek(0)
|
| 307 |
+
docx_bytes = buffer.read()
|
| 308 |
+
|
| 309 |
+
# Validate DOCX was created properly
|
| 310 |
+
validation_result = validate_docx_content(docx_bytes)
|
| 311 |
+
|
| 312 |
+
if not validation_result['valid']:
|
| 313 |
+
error_msg = validation_result.get('error', 'DOCX validation failed')
|
| 314 |
+
logger.error(f"β DOCX validation failed: {error_msg}")
|
| 315 |
+
raise ValueError(error_msg)
|
| 316 |
+
|
| 317 |
+
processing_time = time.time() - start_time
|
| 318 |
+
logger.info(f"β
DOCX created successfully: {len(docx_bytes)} bytes, "
|
| 319 |
+
f"{paragraph_count} paragraphs, {bullet_count} bullets, "
|
| 320 |
+
f"processed in {processing_time:.2f}s")
|
| 321 |
+
return docx_bytes
|
| 322 |
+
|
| 323 |
except Exception as e:
|
| 324 |
+
logger.error(f"β DOCX generation error: {str(e)}", exc_info=True)
|
| 325 |
+
raise HTTPException(
|
| 326 |
+
status_code=500,
|
| 327 |
+
detail=f"DOCX generation failed: {str(e)}"
|
| 328 |
+
)
|
| 329 |
|
| 330 |
|
| 331 |
def create_pdf(text: str) -> bytes:
|
| 332 |
+
"""
|
| 333 |
+
Create PDF file from text with proper formatting using ReportLab.
|
| 334 |
+
Uses SimpleDocTemplate for robust PDF generation.
|
| 335 |
+
"""
|
| 336 |
try:
|
| 337 |
+
logger.info(f"π Starting PDF generation for {len(text)} characters")
|
| 338 |
+
start_time = time.time()
|
| 339 |
+
|
| 340 |
buffer = io.BytesIO()
|
| 341 |
+
|
| 342 |
+
# Create PDF document with proper margins
|
| 343 |
+
doc = SimpleDocTemplate(
|
| 344 |
+
buffer,
|
| 345 |
+
pagesize=letter,
|
| 346 |
+
rightMargin=72,
|
| 347 |
+
leftMargin=72,
|
| 348 |
+
topMargin=72,
|
| 349 |
+
bottomMargin=18,
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
# Container for flowable objects
|
| 353 |
+
elements = []
|
| 354 |
+
|
| 355 |
+
# Get default styles
|
| 356 |
+
styles = getSampleStyleSheet()
|
| 357 |
+
style_normal = ParagraphStyle(
|
| 358 |
+
'CustomNormal',
|
| 359 |
+
parent=styles['Normal'],
|
| 360 |
+
fontSize=11,
|
| 361 |
+
leading=16,
|
| 362 |
+
alignment=TA_JUSTIFY,
|
| 363 |
+
spaceAfter=12,
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
style_bullet = ParagraphStyle(
|
| 367 |
+
'CustomBullet',
|
| 368 |
+
parent=styles['Normal'],
|
| 369 |
+
fontSize=11,
|
| 370 |
+
leading=16,
|
| 371 |
+
alignment=TA_LEFT,
|
| 372 |
+
leftIndent=20,
|
| 373 |
+
spaceAfter=8,
|
| 374 |
+
)
|
| 375 |
|
| 376 |
# Split text into paragraphs
|
| 377 |
paragraphs = text.split('\n\n')
|
| 378 |
+
paragraph_count = 0
|
| 379 |
+
bullet_count = 0
|
| 380 |
+
heading_count = 0
|
| 381 |
|
| 382 |
+
for para_text in paragraphs:
|
| 383 |
+
if not para_text.strip():
|
| 384 |
continue
|
| 385 |
|
| 386 |
+
# Check if this is a multi-line section with bullets
|
| 387 |
+
lines = para_text.split('\n')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
|
|
|
|
| 389 |
for line in lines:
|
| 390 |
+
line = line.strip()
|
| 391 |
+
if not line:
|
| 392 |
+
continue
|
| 393 |
+
|
| 394 |
+
# Escape XML special characters for ReportLab
|
| 395 |
+
line = (line
|
| 396 |
+
.replace('&', '&')
|
| 397 |
+
.replace('<', '<')
|
| 398 |
+
.replace('>', '>')
|
| 399 |
+
.replace('"', '"')
|
| 400 |
+
.replace("'", ''')
|
| 401 |
+
)
|
| 402 |
|
| 403 |
+
# Detect and format bullet points
|
| 404 |
+
if line.startswith('β’') or line.startswith('-') or line.startswith('*'):
|
| 405 |
+
# Remove bullet character and create bullet paragraph
|
| 406 |
+
clean_line = line[1:].strip()
|
| 407 |
+
bullet_text = f"β’ {clean_line}"
|
| 408 |
+
para = Paragraph(bullet_text, style_bullet)
|
| 409 |
+
elements.append(para)
|
| 410 |
+
bullet_count += 1
|
| 411 |
+
elif line.isupper() and len(line.split()) <= 5:
|
| 412 |
+
# Heading style
|
| 413 |
+
para = Paragraph(f"<b>{line}</b>", style_normal)
|
| 414 |
+
elements.append(para)
|
| 415 |
+
elements.append(Spacer(1, 0.15 * inch))
|
| 416 |
+
heading_count += 1
|
| 417 |
+
else:
|
| 418 |
+
# Regular paragraph
|
| 419 |
+
para = Paragraph(line, style_normal)
|
| 420 |
+
elements.append(para)
|
| 421 |
+
paragraph_count += 1
|
| 422 |
|
| 423 |
+
# Add spacing between sections
|
| 424 |
+
elements.append(Spacer(1, 0.2 * inch))
|
| 425 |
+
|
| 426 |
+
# Build PDF
|
| 427 |
+
doc.build(elements)
|
| 428 |
|
| 429 |
+
# Get PDF bytes
|
| 430 |
buffer.seek(0)
|
| 431 |
+
pdf_bytes = buffer.read()
|
| 432 |
+
|
| 433 |
+
# Validate PDF was created properly
|
| 434 |
+
validation_result = validate_pdf_content(pdf_bytes)
|
| 435 |
+
|
| 436 |
+
if not validation_result['valid']:
|
| 437 |
+
error_msg = validation_result.get('error', 'PDF validation failed')
|
| 438 |
+
logger.error(f"β PDF validation failed: {error_msg}")
|
| 439 |
+
raise ValueError(error_msg)
|
| 440 |
+
|
| 441 |
+
processing_time = time.time() - start_time
|
| 442 |
+
logger.info(f"β
PDF created successfully: {len(pdf_bytes)} bytes, "
|
| 443 |
+
f"{paragraph_count} paragraphs, {bullet_count} bullets, "
|
| 444 |
+
f"{heading_count} headings, processed in {processing_time:.2f}s")
|
| 445 |
+
return pdf_bytes
|
| 446 |
+
|
| 447 |
except Exception as e:
|
| 448 |
+
logger.error(f"β PDF generation error: {str(e)}", exc_info=True)
|
| 449 |
+
raise HTTPException(
|
| 450 |
+
status_code=500,
|
| 451 |
+
detail=f"PDF generation failed: {str(e)}"
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def validate_pdf_content(pdf_bytes: bytes) -> dict:
|
| 456 |
+
"""
|
| 457 |
+
Validate PDF file content and headers
|
| 458 |
+
|
| 459 |
+
Args:
|
| 460 |
+
pdf_bytes: The PDF file content as bytes
|
| 461 |
+
|
| 462 |
+
Returns:
|
| 463 |
+
dict: Validation result with status and details
|
| 464 |
+
"""
|
| 465 |
+
try:
|
| 466 |
+
# Check if content is empty
|
| 467 |
+
if len(pdf_bytes) == 0:
|
| 468 |
+
return {
|
| 469 |
+
'valid': False,
|
| 470 |
+
'error': 'PDF file is empty',
|
| 471 |
+
'size': 0,
|
| 472 |
+
'has_header': False
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
# Check PDF header
|
| 476 |
+
has_pdf_header = pdf_bytes.startswith(b'%PDF')
|
| 477 |
+
|
| 478 |
+
# Additional PDF structure validation
|
| 479 |
+
has_eof = b'%%EOF' in pdf_bytes
|
| 480 |
+
|
| 481 |
+
validation_result = {
|
| 482 |
+
'valid': has_pdf_header and len(pdf_bytes) > 0,
|
| 483 |
+
'size': len(pdf_bytes),
|
| 484 |
+
'has_header': has_pdf_header,
|
| 485 |
+
'has_eof': has_eof,
|
| 486 |
+
'content_type': 'application/pdf'
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
if not has_pdf_header:
|
| 490 |
+
validation_result['error'] = 'Invalid PDF header - file does not start with %PDF'
|
| 491 |
+
elif not has_eof:
|
| 492 |
+
validation_result['warning'] = 'PDF may be incomplete - missing %%EOF marker'
|
| 493 |
+
|
| 494 |
+
logger.info(f"PDF validation: {validation_result}")
|
| 495 |
+
return validation_result
|
| 496 |
+
|
| 497 |
+
except Exception as e:
|
| 498 |
+
logger.error(f"PDF validation error: {str(e)}")
|
| 499 |
+
return {
|
| 500 |
+
'valid': False,
|
| 501 |
+
'error': f'PDF validation failed: {str(e)}',
|
| 502 |
+
'size': len(pdf_bytes) if pdf_bytes else 0,
|
| 503 |
+
'has_header': False
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def validate_docx_content(docx_bytes: bytes) -> dict:
|
| 508 |
+
"""
|
| 509 |
+
Validate DOCX file content and headers
|
| 510 |
+
|
| 511 |
+
Args:
|
| 512 |
+
docx_bytes: The DOCX file content as bytes
|
| 513 |
+
|
| 514 |
+
Returns:
|
| 515 |
+
dict: Validation result with status and details
|
| 516 |
+
"""
|
| 517 |
+
try:
|
| 518 |
+
# Check if content is empty
|
| 519 |
+
if len(docx_bytes) == 0:
|
| 520 |
+
return {
|
| 521 |
+
'valid': False,
|
| 522 |
+
'error': 'DOCX file is empty',
|
| 523 |
+
'size': 0,
|
| 524 |
+
'has_header': False
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
# Check DOCX header (ZIP format)
|
| 528 |
+
has_zip_header = docx_bytes.startswith(b'PK')
|
| 529 |
+
|
| 530 |
+
# Additional DOCX structure validation
|
| 531 |
+
# DOCX files should contain specific XML files
|
| 532 |
+
has_content_types = b'[Content_Types].xml' in docx_bytes
|
| 533 |
+
has_word_document = b'word/document.xml' in docx_bytes
|
| 534 |
+
|
| 535 |
+
validation_result = {
|
| 536 |
+
'valid': has_zip_header and len(docx_bytes) > 0,
|
| 537 |
+
'size': len(docx_bytes),
|
| 538 |
+
'has_header': has_zip_header,
|
| 539 |
+
'has_content_types': has_content_types,
|
| 540 |
+
'has_word_document': has_word_document,
|
| 541 |
+
'content_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
if not has_zip_header:
|
| 545 |
+
validation_result['error'] = 'Invalid DOCX header - file does not start with PK (ZIP format)'
|
| 546 |
+
elif not has_content_types:
|
| 547 |
+
validation_result['warning'] = 'DOCX may be incomplete - missing Content_Types.xml'
|
| 548 |
+
elif not has_word_document:
|
| 549 |
+
validation_result['warning'] = 'DOCX may be incomplete - missing word/document.xml'
|
| 550 |
+
|
| 551 |
+
logger.info(f"DOCX validation: {validation_result}")
|
| 552 |
+
return validation_result
|
| 553 |
+
|
| 554 |
+
except Exception as e:
|
| 555 |
+
logger.error(f"DOCX validation error: {str(e)}")
|
| 556 |
+
return {
|
| 557 |
+
'valid': False,
|
| 558 |
+
'error': f'DOCX validation failed: {str(e)}',
|
| 559 |
+
'size': len(docx_bytes) if docx_bytes else 0,
|
| 560 |
+
'has_header': False
|
| 561 |
+
}
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def validate_file_content(file_bytes: bytes, expected_format: str) -> dict:
|
| 565 |
+
"""
|
| 566 |
+
Validate file content based on expected format
|
| 567 |
+
|
| 568 |
+
Args:
|
| 569 |
+
file_bytes: The file content as bytes
|
| 570 |
+
expected_format: Expected format ('pdf' or 'docx')
|
| 571 |
+
|
| 572 |
+
Returns:
|
| 573 |
+
dict: Validation result with status and details
|
| 574 |
+
"""
|
| 575 |
+
try:
|
| 576 |
+
if expected_format.lower() == 'pdf':
|
| 577 |
+
return validate_pdf_content(file_bytes)
|
| 578 |
+
elif expected_format.lower() == 'docx':
|
| 579 |
+
return validate_docx_content(file_bytes)
|
| 580 |
+
else:
|
| 581 |
+
return {
|
| 582 |
+
'valid': False,
|
| 583 |
+
'error': f'Unsupported format for validation: {expected_format}',
|
| 584 |
+
'size': len(file_bytes) if file_bytes else 0
|
| 585 |
+
}
|
| 586 |
+
except Exception as e:
|
| 587 |
+
logger.error(f"File validation error: {str(e)}")
|
| 588 |
+
return {
|
| 589 |
+
'valid': False,
|
| 590 |
+
'error': f'File validation failed: {str(e)}',
|
| 591 |
+
'size': len(file_bytes) if file_bytes else 0
|
| 592 |
+
}
|
| 593 |
|
| 594 |
|
| 595 |
class ParaphraseRequest(BaseModel):
|
|
|
|
| 799 |
Processed document in requested format
|
| 800 |
"""
|
| 801 |
if model is None or tokenizer is None:
|
| 802 |
+
logger.error("β Model not loaded for document processing")
|
| 803 |
raise HTTPException(status_code=503, detail="Model not loaded")
|
| 804 |
|
| 805 |
+
request_start_time = time.time()
|
| 806 |
+
logger.info(f"π Document processing request: file={file.filename}, "
|
| 807 |
+
f"style={style}, format={output_format}")
|
| 808 |
+
|
| 809 |
# Read file content
|
| 810 |
content = await file.read()
|
| 811 |
filename = file.filename.lower() if file.filename else ""
|
| 812 |
|
| 813 |
+
logger.info(f"π File uploaded: {file.filename} ({len(content)} bytes)")
|
| 814 |
+
|
| 815 |
# Extract text based on file type
|
| 816 |
try:
|
| 817 |
if filename.endswith(".txt"):
|
| 818 |
text = content.decode('utf-8')
|
| 819 |
+
logger.info(f"π Extracted text from TXT: {len(text)} characters")
|
| 820 |
elif filename.endswith(".docx"):
|
| 821 |
# Parse DOCX file using python-docx
|
| 822 |
try:
|
|
|
|
| 825 |
doc = Document(doc_file)
|
| 826 |
text = "\n".join([paragraph.text for paragraph in doc.paragraphs if paragraph.text.strip()])
|
| 827 |
if not text.strip():
|
| 828 |
+
logger.error("β DOCX file appears to be empty")
|
| 829 |
raise HTTPException(status_code=400, detail="DOCX file appears to be empty")
|
| 830 |
+
logger.info(f"π Extracted text from DOCX: {len(text)} characters, "
|
| 831 |
+
f"{len(doc.paragraphs)} paragraphs")
|
| 832 |
except Exception as docx_error:
|
| 833 |
+
logger.error(f"β DOCX parsing error: {str(docx_error)}", exc_info=True)
|
| 834 |
raise HTTPException(status_code=400, detail=f"Could not parse DOCX file: {str(docx_error)}")
|
| 835 |
else:
|
| 836 |
# Try to decode as text
|
| 837 |
text = content.decode('utf-8')
|
| 838 |
+
logger.info(f"π Extracted text from generic file: {len(text)} characters")
|
| 839 |
except HTTPException:
|
| 840 |
# Re-raise HTTP exceptions
|
| 841 |
raise
|
| 842 |
except Exception as e:
|
| 843 |
+
logger.error(f"β File processing error: {str(e)}", exc_info=True)
|
| 844 |
raise HTTPException(status_code=400, detail=f"Could not process file: {str(e)}")
|
| 845 |
|
| 846 |
if not text or len(text.split()) < MIN_WORDS:
|
| 847 |
+
logger.error(f"β Invalid text extracted: {len(text.split())} words (minimum: {MIN_WORDS})")
|
| 848 |
raise HTTPException(status_code=400, detail="Could not extract valid text")
|
| 849 |
|
| 850 |
# Process the text
|
| 851 |
+
word_count = len(text.split())
|
| 852 |
+
logger.info(f"π€ Processing document: {len(text)} characters, {word_count} words, style: {style}")
|
| 853 |
|
| 854 |
# Use long text processing
|
| 855 |
+
processing_start_time = time.time()
|
| 856 |
result = await process_long_text(text, style)
|
| 857 |
paraphrased = result.output
|
| 858 |
+
processing_time = time.time() - processing_start_time
|
| 859 |
+
|
| 860 |
+
logger.info(f"β
Text processing completed in {processing_time:.2f}s: "
|
| 861 |
+
f"{len(paraphrased)} characters output")
|
| 862 |
|
| 863 |
# Return in requested format
|
| 864 |
if output_format == "json":
|
| 865 |
+
total_time = time.time() - request_start_time
|
| 866 |
+
logger.info(f"π€ Returning JSON response (total time: {total_time:.2f}s)")
|
| 867 |
return {"output": paraphrased, "style": style}
|
| 868 |
|
| 869 |
elif output_format == "pdf":
|
| 870 |
+
logger.info(f"π Generating PDF for {len(paraphrased)} characters")
|
| 871 |
+
file_start_time = time.time()
|
| 872 |
pdf_bytes = create_pdf(paraphrased)
|
| 873 |
+
file_time = time.time() - file_start_time
|
| 874 |
+
total_time = time.time() - request_start_time
|
| 875 |
+
|
| 876 |
+
logger.info(f"π€ Returning PDF response: {len(pdf_bytes)} bytes "
|
| 877 |
+
f"(file generation: {file_time:.2f}s, total: {total_time:.2f}s)")
|
| 878 |
+
|
| 879 |
return Response(
|
| 880 |
content=pdf_bytes,
|
| 881 |
media_type="application/pdf",
|
| 882 |
+
headers={
|
| 883 |
+
"Content-Disposition": "attachment; filename=humanized.pdf",
|
| 884 |
+
"Content-Length": str(len(pdf_bytes)),
|
| 885 |
+
"Cache-Control": "no-cache, no-store, must-revalidate"
|
| 886 |
+
}
|
| 887 |
)
|
| 888 |
|
| 889 |
elif output_format == "docx":
|
| 890 |
+
logger.info(f"π Generating DOCX for {len(paraphrased)} characters")
|
| 891 |
+
file_start_time = time.time()
|
| 892 |
docx_bytes = create_docx(paraphrased)
|
| 893 |
+
file_time = time.time() - file_start_time
|
| 894 |
+
total_time = time.time() - request_start_time
|
| 895 |
+
|
| 896 |
+
logger.info(f"π€ Returning DOCX response: {len(docx_bytes)} bytes "
|
| 897 |
+
f"(file generation: {file_time:.2f}s, total: {total_time:.2f}s)")
|
| 898 |
+
|
| 899 |
return Response(
|
| 900 |
content=docx_bytes,
|
| 901 |
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
| 902 |
+
headers={
|
| 903 |
+
"Content-Disposition": "attachment; filename=humanized.docx",
|
| 904 |
+
"Content-Length": str(len(docx_bytes)),
|
| 905 |
+
"Cache-Control": "no-cache, no-store, must-revalidate"
|
| 906 |
+
}
|
| 907 |
)
|
| 908 |
|
| 909 |
else:
|
| 910 |
+
logger.error(f"β Invalid output format requested: {output_format}")
|
| 911 |
raise HTTPException(status_code=400, detail="Invalid output format")
|
| 912 |
|
| 913 |
|