Spaces:
Sleeping
Sleeping
V2 of the model.
Browse files
app.py
CHANGED
|
@@ -1,187 +1,582 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import logging
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
from
|
| 7 |
-
from
|
| 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 |
-
return
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
import io
|
| 4 |
+
import asyncio
|
| 5 |
+
import json
|
| 6 |
+
from typing import Optional, List
|
| 7 |
+
from enum import Enum
|
| 8 |
+
import torch
|
| 9 |
+
from fastapi import FastAPI, HTTPException, UploadFile, File
|
| 10 |
+
from fastapi.responses import StreamingResponse
|
| 11 |
+
from pydantic import BaseModel, Field, field_validator
|
| 12 |
+
from transformers import T5ForConditionalGeneration, T5Tokenizer
|
| 13 |
+
from docx import Document
|
| 14 |
+
from reportlab.lib.pagesizes import LETTER
|
| 15 |
+
from reportlab.pdfgen import canvas
|
| 16 |
+
|
| 17 |
+
# Configure logging
|
| 18 |
+
logging.basicConfig(
|
| 19 |
+
level=logging.INFO,
|
| 20 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 21 |
+
)
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
# FastAPI app
|
| 25 |
+
app = FastAPI(
|
| 26 |
+
title="T5 Paraphrasing API",
|
| 27 |
+
description="Production-ready paraphrasing service using T5 model",
|
| 28 |
+
version="1.0.0"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# Global model and tokenizer (loaded once on startup)
|
| 32 |
+
model: Optional[T5ForConditionalGeneration] = None
|
| 33 |
+
tokenizer: Optional[T5Tokenizer] = None
|
| 34 |
+
|
| 35 |
+
# Configuration constants
|
| 36 |
+
MIN_WORDS = 5
|
| 37 |
+
MAX_INPUT_LENGTH = 512 # Protect CPU from very long inputs
|
| 38 |
+
MAX_OUTPUT_LENGTH = 128
|
| 39 |
+
NUM_BEAMS = 4
|
| 40 |
+
NO_REPEAT_NGRAM_SIZE = 3
|
| 41 |
+
CHUNK_TOKEN_LIMIT = 400 # Safe chunking for long documents
|
| 42 |
+
MAX_DOC_CHUNKS = 50 # Free-tier protection
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ParaphraseStyle(str, Enum):
|
| 46 |
+
"""Paraphrasing styles for different use cases"""
|
| 47 |
+
neutral = "neutral"
|
| 48 |
+
formal = "formal"
|
| 49 |
+
ats = "ats"
|
| 50 |
+
bullets = "bullets"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def build_prompt(text: str, style: ParaphraseStyle) -> str:
|
| 54 |
+
"""Build style-specific prompts for T5 model"""
|
| 55 |
+
if style == ParaphraseStyle.formal:
|
| 56 |
+
return f"paraphrase formally: {text}"
|
| 57 |
+
elif style == ParaphraseStyle.ats:
|
| 58 |
+
return (
|
| 59 |
+
"paraphrase professionally for a resume, "
|
| 60 |
+
"use clear action verbs, concise language, "
|
| 61 |
+
f"and ATS-friendly wording: {text}"
|
| 62 |
+
)
|
| 63 |
+
elif style == ParaphraseStyle.bullets:
|
| 64 |
+
return (
|
| 65 |
+
"Rewrite the following text into concise, professional resume bullet points. "
|
| 66 |
+
"Use strong action verbs, quantify impact where possible, "
|
| 67 |
+
f"and keep each bullet ATS-friendly: {text}"
|
| 68 |
+
)
|
| 69 |
+
return f"paraphrase: {text}"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def chunk_text(text: str, tokenizer, max_tokens: int) -> List[str]:
|
| 73 |
+
"""Chunk text by sentences to stay within token limits"""
|
| 74 |
+
sentences = text.split('. ')
|
| 75 |
+
chunks = []
|
| 76 |
+
current_chunk = []
|
| 77 |
+
current_tokens = 0
|
| 78 |
+
|
| 79 |
+
for sentence in sentences:
|
| 80 |
+
sentence = sentence.strip()
|
| 81 |
+
if not sentence:
|
| 82 |
+
continue
|
| 83 |
+
|
| 84 |
+
# Add period back if it was removed
|
| 85 |
+
if not sentence.endswith('.'):
|
| 86 |
+
sentence += '.'
|
| 87 |
+
|
| 88 |
+
tokens = tokenizer.encode(sentence, add_special_tokens=False)
|
| 89 |
+
|
| 90 |
+
if current_tokens + len(tokens) > max_tokens:
|
| 91 |
+
if current_chunk:
|
| 92 |
+
chunks.append(' '.join(current_chunk))
|
| 93 |
+
current_chunk = [sentence]
|
| 94 |
+
current_tokens = len(tokens)
|
| 95 |
+
else:
|
| 96 |
+
# Single sentence too long, truncate
|
| 97 |
+
chunks.append(sentence[:max_tokens])
|
| 98 |
+
else:
|
| 99 |
+
current_chunk.append(sentence)
|
| 100 |
+
current_tokens += len(tokens)
|
| 101 |
+
|
| 102 |
+
if current_chunk:
|
| 103 |
+
chunks.append(' '.join(current_chunk))
|
| 104 |
+
|
| 105 |
+
return chunks
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def paragraph_chunks(text: str, tokenizer, max_tokens: int) -> List[str]:
|
| 109 |
+
"""Chunk text by paragraphs for bullet-point restructuring"""
|
| 110 |
+
paragraphs = [p.strip() for p in text.split("\n") if p.strip()]
|
| 111 |
+
chunks = []
|
| 112 |
+
current = []
|
| 113 |
+
tokens_count = 0
|
| 114 |
+
|
| 115 |
+
for p in paragraphs:
|
| 116 |
+
tokens = tokenizer.encode(p, add_special_tokens=False)
|
| 117 |
+
if tokens_count + len(tokens) > max_tokens:
|
| 118 |
+
if current:
|
| 119 |
+
chunks.append("\n".join(current))
|
| 120 |
+
current = [p]
|
| 121 |
+
tokens_count = len(tokens)
|
| 122 |
+
else:
|
| 123 |
+
# Single paragraph too long, use sentence chunking
|
| 124 |
+
sentence_chunks = chunk_text(p, tokenizer, max_tokens)
|
| 125 |
+
chunks.extend(sentence_chunks)
|
| 126 |
+
else:
|
| 127 |
+
current.append(p)
|
| 128 |
+
tokens_count += len(tokens)
|
| 129 |
+
|
| 130 |
+
if current:
|
| 131 |
+
chunks.append("\n".join(current))
|
| 132 |
+
|
| 133 |
+
return chunks
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def create_docx(text: str) -> bytes:
|
| 137 |
+
"""Create DOCX file from text"""
|
| 138 |
+
doc = Document()
|
| 139 |
+
|
| 140 |
+
for line in text.split("\n"):
|
| 141 |
+
if line.strip():
|
| 142 |
+
if line.strip().startswith("•") or line.strip().startswith("-"):
|
| 143 |
+
# Bullet point
|
| 144 |
+
doc.add_paragraph(line.strip(), style='List Bullet')
|
| 145 |
+
else:
|
| 146 |
+
# Regular paragraph
|
| 147 |
+
doc.add_paragraph(line.strip())
|
| 148 |
+
else:
|
| 149 |
+
# Empty line for spacing
|
| 150 |
+
doc.add_paragraph("")
|
| 151 |
+
|
| 152 |
+
buffer = io.BytesIO()
|
| 153 |
+
doc.save(buffer)
|
| 154 |
+
buffer.seek(0)
|
| 155 |
+
return buffer.read()
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def create_pdf(text: str) -> bytes:
|
| 159 |
+
"""Create PDF file from text"""
|
| 160 |
+
buffer = io.BytesIO()
|
| 161 |
+
c = canvas.Canvas(buffer, pagesize=LETTER)
|
| 162 |
+
width, height = LETTER
|
| 163 |
+
y = height - 40
|
| 164 |
+
|
| 165 |
+
for line in text.split("\n"):
|
| 166 |
+
if y < 40: # New page
|
| 167 |
+
c.showPage()
|
| 168 |
+
y = height - 40
|
| 169 |
+
|
| 170 |
+
# Handle long lines
|
| 171 |
+
line = line[:100] + "..." if len(line) > 100 else line
|
| 172 |
+
c.drawString(40, y, line)
|
| 173 |
+
y -= 14
|
| 174 |
+
|
| 175 |
+
c.save()
|
| 176 |
+
buffer.seek(0)
|
| 177 |
+
return buffer.read()
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class ParaphraseRequest(BaseModel):
|
| 181 |
+
"""Input schema for paraphrasing request"""
|
| 182 |
+
text: str = Field(..., min_length=1, description="Text to paraphrase")
|
| 183 |
+
style: ParaphraseStyle = Field(default=ParaphraseStyle.neutral, description="Paraphrasing style")
|
| 184 |
+
|
| 185 |
+
@field_validator('text')
|
| 186 |
+
@classmethod
|
| 187 |
+
def validate_text(cls, v: str) -> str:
|
| 188 |
+
"""Validate and clean input text"""
|
| 189 |
+
if not v or not v.strip():
|
| 190 |
+
raise ValueError("Text cannot be empty")
|
| 191 |
+
|
| 192 |
+
# Clean text lightly (remove extra whitespace, preserve punctuation)
|
| 193 |
+
cleaned = ' '.join(v.strip().split())
|
| 194 |
+
|
| 195 |
+
# Check word count
|
| 196 |
+
word_count = len(cleaned.split())
|
| 197 |
+
if word_count < MIN_WORDS:
|
| 198 |
+
raise ValueError(f"Text must contain at least {MIN_WORDS} words")
|
| 199 |
+
|
| 200 |
+
# For long documents, we'll chunk them
|
| 201 |
+
if len(cleaned) > MAX_INPUT_LENGTH * 3: # Allow longer text for chunking
|
| 202 |
+
logger.info(f"Long document detected: {len(cleaned)} characters")
|
| 203 |
+
|
| 204 |
+
return cleaned
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class DocumentRequest(BaseModel):
|
| 208 |
+
"""Input schema for document processing"""
|
| 209 |
+
style: ParaphraseStyle = Field(default=ParaphraseStyle.neutral, description="Paraphrasing style")
|
| 210 |
+
output_format: str = Field(default="json", description="Output format: json, docx, or pdf")
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class ParaphraseResponse(BaseModel):
|
| 214 |
+
"""Output schema for paraphrasing response"""
|
| 215 |
+
output: str = Field(..., description="Paraphrased text")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@app.on_event("startup")
|
| 219 |
+
async def load_model():
|
| 220 |
+
"""Load model and tokenizer once on startup"""
|
| 221 |
+
global model, tokenizer
|
| 222 |
+
|
| 223 |
+
model_name = "Vamsi/T5_Paraphrase_Paws"
|
| 224 |
+
logger.info(f"Loading model: {model_name}")
|
| 225 |
+
|
| 226 |
+
try:
|
| 227 |
+
# Load tokenizer
|
| 228 |
+
logger.info("Loading tokenizer...")
|
| 229 |
+
tokenizer = T5Tokenizer.from_pretrained(model_name)
|
| 230 |
+
|
| 231 |
+
# Load model
|
| 232 |
+
logger.info("Loading model...")
|
| 233 |
+
model = T5ForConditionalGeneration.from_pretrained(model_name)
|
| 234 |
+
|
| 235 |
+
# Set to evaluation mode
|
| 236 |
+
model.eval()
|
| 237 |
+
|
| 238 |
+
# Move to CPU (explicit for clarity)
|
| 239 |
+
device = torch.device("cpu")
|
| 240 |
+
model.to(device)
|
| 241 |
+
|
| 242 |
+
logger.info("Model loaded successfully on CPU")
|
| 243 |
+
|
| 244 |
+
except Exception as e:
|
| 245 |
+
logger.error(f"Failed to load model: {str(e)}")
|
| 246 |
+
raise
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
@app.get("/")
|
| 250 |
+
async def root():
|
| 251 |
+
"""Health check endpoint"""
|
| 252 |
+
return {
|
| 253 |
+
"status": "healthy",
|
| 254 |
+
"model_loaded": model is not None and tokenizer is not None
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@app.get("/health")
|
| 259 |
+
async def health():
|
| 260 |
+
"""Health check endpoint"""
|
| 261 |
+
return {
|
| 262 |
+
"status": "healthy",
|
| 263 |
+
"model_loaded": model is not None and tokenizer is not None
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
@app.post("/humanize", response_model=ParaphraseResponse)
|
| 268 |
+
async def humanize(request: ParaphraseRequest) -> ParaphraseResponse:
|
| 269 |
+
"""
|
| 270 |
+
Paraphrase input text using T5 model with style support.
|
| 271 |
+
|
| 272 |
+
Args:
|
| 273 |
+
request: ParaphraseRequest containing text and style
|
| 274 |
+
|
| 275 |
+
Returns:
|
| 276 |
+
ParaphraseResponse with paraphrased text
|
| 277 |
+
|
| 278 |
+
Raises:
|
| 279 |
+
HTTPException: If model is not loaded or inference fails
|
| 280 |
+
"""
|
| 281 |
+
if model is None or tokenizer is None:
|
| 282 |
+
logger.error("Model not loaded")
|
| 283 |
+
raise HTTPException(status_code=503, detail="Model not loaded")
|
| 284 |
+
|
| 285 |
+
input_text = request.text
|
| 286 |
+
style = request.style
|
| 287 |
+
logger.info(f"Received request: {len(input_text)} characters, {len(input_text.split())} words, style: {style}")
|
| 288 |
+
|
| 289 |
+
try:
|
| 290 |
+
# For short text, process directly
|
| 291 |
+
if len(input_text.split()) <= 100:
|
| 292 |
+
return await process_single_chunk(input_text, style)
|
| 293 |
+
|
| 294 |
+
# For long text, use chunking
|
| 295 |
+
return await process_long_text(input_text, style)
|
| 296 |
+
|
| 297 |
+
except Exception as e:
|
| 298 |
+
logger.error(f"Inference error: {str(e)}")
|
| 299 |
+
# Return original text on error (graceful degradation)
|
| 300 |
+
logger.warning("Returning original text due to inference error")
|
| 301 |
+
return ParaphraseResponse(output=input_text)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
async def process_single_chunk(text: str, style: ParaphraseStyle) -> ParaphraseResponse:
|
| 305 |
+
"""Process a single chunk of text"""
|
| 306 |
+
# Prepare input with style-specific prompt
|
| 307 |
+
input_text_prepared = build_prompt(text, style)
|
| 308 |
+
|
| 309 |
+
# Tokenize
|
| 310 |
+
input_ids = tokenizer.encode(
|
| 311 |
+
input_text_prepared,
|
| 312 |
+
return_tensors="pt",
|
| 313 |
+
max_length=MAX_INPUT_LENGTH,
|
| 314 |
+
truncation=True,
|
| 315 |
+
padding=True
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
# Inference with no_grad for efficiency
|
| 319 |
+
with torch.no_grad():
|
| 320 |
+
# Generate with beam search for accuracy
|
| 321 |
+
outputs = model.generate(
|
| 322 |
+
input_ids,
|
| 323 |
+
max_length=MAX_OUTPUT_LENGTH,
|
| 324 |
+
num_beams=NUM_BEAMS,
|
| 325 |
+
no_repeat_ngram_size=NO_REPEAT_NGRAM_SIZE,
|
| 326 |
+
early_stopping=True,
|
| 327 |
+
do_sample=False, # Deterministic, no randomness
|
| 328 |
+
temperature=None, # Not used when do_sample=False
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
# Decode output
|
| 332 |
+
paraphrased_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 333 |
+
|
| 334 |
+
# Clean output
|
| 335 |
+
paraphrased_text = paraphrased_text.strip()
|
| 336 |
+
|
| 337 |
+
# Fallback: if output is empty or too short, return original
|
| 338 |
+
if not paraphrased_text or len(paraphrased_text.split()) < MIN_WORDS:
|
| 339 |
+
logger.warning("Generated output too short, returning original text")
|
| 340 |
+
paraphrased_text = text
|
| 341 |
+
|
| 342 |
+
logger.info(f"Generated paraphrase: {len(paraphrased_text)} characters")
|
| 343 |
+
|
| 344 |
+
return ParaphraseResponse(output=paraphrased_text)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
async def process_long_text(text: str, style: ParaphraseStyle) -> ParaphraseResponse:
|
| 348 |
+
"""Process long text by chunking"""
|
| 349 |
+
# Choose chunking strategy based on style
|
| 350 |
+
if style == ParaphraseStyle.bullets:
|
| 351 |
+
chunks = paragraph_chunks(text, tokenizer, CHUNK_TOKEN_LIMIT)
|
| 352 |
+
else:
|
| 353 |
+
chunks = chunk_text(text, tokenizer, CHUNK_TOKEN_LIMIT)
|
| 354 |
+
|
| 355 |
+
if len(chunks) > MAX_DOC_CHUNKS:
|
| 356 |
+
raise HTTPException(status_code=413, detail="Document too large")
|
| 357 |
+
|
| 358 |
+
logger.info(f"Processing {len(chunks)} chunks")
|
| 359 |
+
|
| 360 |
+
results = []
|
| 361 |
+
for i, chunk in enumerate(chunks):
|
| 362 |
+
logger.info(f"Processing chunk {i+1}/{len(chunks)}")
|
| 363 |
+
|
| 364 |
+
# Process each chunk
|
| 365 |
+
prompt = build_prompt(chunk, style)
|
| 366 |
+
input_ids = tokenizer.encode(
|
| 367 |
+
prompt,
|
| 368 |
+
return_tensors="pt",
|
| 369 |
+
max_length=MAX_INPUT_LENGTH,
|
| 370 |
+
truncation=True
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
with torch.no_grad():
|
| 374 |
+
output = model.generate(
|
| 375 |
+
input_ids,
|
| 376 |
+
max_length=MAX_OUTPUT_LENGTH,
|
| 377 |
+
num_beams=NUM_BEAMS,
|
| 378 |
+
no_repeat_ngram_size=NO_REPEAT_NGRAM_SIZE,
|
| 379 |
+
early_stopping=True,
|
| 380 |
+
do_sample=False
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
chunk_result = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 384 |
+
results.append(chunk_result.strip())
|
| 385 |
+
|
| 386 |
+
# Small delay to prevent overwhelming the CPU
|
| 387 |
+
await asyncio.sleep(0.1)
|
| 388 |
+
|
| 389 |
+
# Join results appropriately based on style
|
| 390 |
+
if style == ParaphraseStyle.bullets:
|
| 391 |
+
final_output = "\n\n".join(results)
|
| 392 |
+
else:
|
| 393 |
+
final_output = " ".join(results)
|
| 394 |
+
|
| 395 |
+
logger.info(f"Completed long text processing: {len(final_output)} characters")
|
| 396 |
+
|
| 397 |
+
return ParaphraseResponse(output=final_output)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@app.post("/humanize-document")
|
| 401 |
+
async def humanize_document(
|
| 402 |
+
file: UploadFile = File(...),
|
| 403 |
+
style: ParaphraseStyle = ParaphraseStyle.neutral,
|
| 404 |
+
output_format: str = "json" # json | docx | pdf
|
| 405 |
+
):
|
| 406 |
+
"""
|
| 407 |
+
Process uploaded document with style-specific paraphrasing.
|
| 408 |
+
|
| 409 |
+
Args:
|
| 410 |
+
file: Uploaded document (txt, docx, etc.)
|
| 411 |
+
style: Paraphrasing style
|
| 412 |
+
output_format: Output format (json, docx, pdf)
|
| 413 |
+
|
| 414 |
+
Returns:
|
| 415 |
+
Processed document in requested format
|
| 416 |
+
"""
|
| 417 |
+
if model is None or tokenizer is None:
|
| 418 |
+
raise HTTPException(status_code=503, detail="Model not loaded")
|
| 419 |
+
|
| 420 |
+
# Read file content
|
| 421 |
+
content = await file.read()
|
| 422 |
+
filename = file.filename.lower() if file.filename else ""
|
| 423 |
+
|
| 424 |
+
# Extract text based on file type
|
| 425 |
+
try:
|
| 426 |
+
if filename.endswith(".txt"):
|
| 427 |
+
text = content.decode('utf-8')
|
| 428 |
+
elif filename.endswith(".docx"):
|
| 429 |
+
# For now, return error - DOCX parsing requires python-docx
|
| 430 |
+
raise HTTPException(
|
| 431 |
+
status_code=400,
|
| 432 |
+
detail="DOCX parsing not available in this version. Please convert to text first."
|
| 433 |
+
)
|
| 434 |
+
else:
|
| 435 |
+
# Try to decode as text
|
| 436 |
+
text = content.decode('utf-8')
|
| 437 |
+
except Exception as e:
|
| 438 |
+
raise HTTPException(status_code=400, detail=f"Could not process file: {str(e)}")
|
| 439 |
+
|
| 440 |
+
if not text or len(text.split()) < MIN_WORDS:
|
| 441 |
+
raise HTTPException(status_code=400, detail="Could not extract valid text")
|
| 442 |
+
|
| 443 |
+
# Process the text
|
| 444 |
+
logger.info(f"Processing document: {len(text)} characters, style: {style}")
|
| 445 |
+
|
| 446 |
+
# Use long text processing
|
| 447 |
+
result = await process_long_text(text, style)
|
| 448 |
+
paraphrased = result.output
|
| 449 |
+
|
| 450 |
+
# Return in requested format
|
| 451 |
+
if output_format == "json":
|
| 452 |
+
return {"output": paraphrased, "style": style}
|
| 453 |
+
|
| 454 |
+
elif output_format == "pdf":
|
| 455 |
+
pdf_bytes = create_pdf(paraphrased)
|
| 456 |
+
return StreamingResponse(
|
| 457 |
+
io.BytesIO(pdf_bytes),
|
| 458 |
+
media_type="application/pdf",
|
| 459 |
+
headers={"Content-Disposition": "attachment; filename=paraphrased.pdf"}
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
elif output_format == "docx":
|
| 463 |
+
docx_bytes = create_docx(paraphrased)
|
| 464 |
+
return StreamingResponse(
|
| 465 |
+
io.BytesIO(docx_bytes),
|
| 466 |
+
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
| 467 |
+
headers={"Content-Disposition": "attachment; filename=paraphrased.docx"}
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
else:
|
| 471 |
+
raise HTTPException(status_code=400, detail="Invalid output format")
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
@app.post("/humanize-document-stream")
|
| 475 |
+
async def humanize_document_stream(
|
| 476 |
+
file: UploadFile = File(...),
|
| 477 |
+
style: ParaphraseStyle = ParaphraseStyle.neutral
|
| 478 |
+
):
|
| 479 |
+
"""
|
| 480 |
+
Process document with streaming progress updates.
|
| 481 |
+
|
| 482 |
+
Args:
|
| 483 |
+
file: Uploaded document
|
| 484 |
+
style: Paraphrasing style
|
| 485 |
+
|
| 486 |
+
Returns:
|
| 487 |
+
Streaming JSON responses with progress updates
|
| 488 |
+
"""
|
| 489 |
+
if model is None or tokenizer is None:
|
| 490 |
+
raise HTTPException(status_code=503, detail="Model not loaded")
|
| 491 |
+
|
| 492 |
+
# Read and extract text
|
| 493 |
+
content = await file.read()
|
| 494 |
+
filename = file.filename.lower() if file.filename else ""
|
| 495 |
+
|
| 496 |
+
try:
|
| 497 |
+
if filename.endswith(".txt"):
|
| 498 |
+
text = content.decode('utf-8')
|
| 499 |
+
else:
|
| 500 |
+
text = content.decode('utf-8')
|
| 501 |
+
except Exception as e:
|
| 502 |
+
raise HTTPException(status_code=400, detail=f"Could not process file: {str(e)}")
|
| 503 |
+
|
| 504 |
+
if not text or len(text.split()) < MIN_WORDS:
|
| 505 |
+
raise HTTPException(status_code=400, detail="Could not extract valid text")
|
| 506 |
+
|
| 507 |
+
# Choose chunking strategy
|
| 508 |
+
if style == ParaphraseStyle.bullets:
|
| 509 |
+
chunks = paragraph_chunks(text, tokenizer, CHUNK_TOKEN_LIMIT)
|
| 510 |
+
else:
|
| 511 |
+
chunks = chunk_text(text, tokenizer, CHUNK_TOKEN_LIMIT)
|
| 512 |
+
|
| 513 |
+
if len(chunks) > MAX_DOC_CHUNKS:
|
| 514 |
+
raise HTTPException(status_code=413, detail="Document too large")
|
| 515 |
+
|
| 516 |
+
async def stream_processing():
|
| 517 |
+
"""Generator for streaming responses"""
|
| 518 |
+
total = len(chunks)
|
| 519 |
+
results = []
|
| 520 |
+
|
| 521 |
+
for idx, chunk in enumerate(chunks, start=1):
|
| 522 |
+
# Send progress update
|
| 523 |
+
yield json.dumps({
|
| 524 |
+
"type": "progress",
|
| 525 |
+
"current": idx,
|
| 526 |
+
"total": total,
|
| 527 |
+
"message": f"Processing chunk {idx} of {total}"
|
| 528 |
+
}) + "\n"
|
| 529 |
+
|
| 530 |
+
# Process chunk
|
| 531 |
+
prompt = build_prompt(chunk, style)
|
| 532 |
+
input_ids = tokenizer.encode(
|
| 533 |
+
prompt,
|
| 534 |
+
return_tensors="pt",
|
| 535 |
+
max_length=MAX_INPUT_LENGTH,
|
| 536 |
+
truncation=True
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
with torch.no_grad():
|
| 540 |
+
output = model.generate(
|
| 541 |
+
input_ids,
|
| 542 |
+
max_length=MAX_OUTPUT_LENGTH,
|
| 543 |
+
num_beams=NUM_BEAMS,
|
| 544 |
+
no_repeat_ngram_size=NO_REPEAT_NGRAM_SIZE,
|
| 545 |
+
early_stopping=True,
|
| 546 |
+
do_sample=False
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
chunk_result = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 550 |
+
results.append(chunk_result.strip())
|
| 551 |
+
|
| 552 |
+
# Send chunk result
|
| 553 |
+
yield json.dumps({
|
| 554 |
+
"type": "chunk",
|
| 555 |
+
"content": chunk_result.strip(),
|
| 556 |
+
"index": idx
|
| 557 |
+
}) + "\n"
|
| 558 |
+
|
| 559 |
+
await asyncio.sleep(0.1) # Allow event loop to process
|
| 560 |
+
|
| 561 |
+
# Send final result
|
| 562 |
+
if style == ParaphraseStyle.bullets:
|
| 563 |
+
final_output = "\n\n".join(results)
|
| 564 |
+
else:
|
| 565 |
+
final_output = " ".join(results)
|
| 566 |
+
|
| 567 |
+
yield json.dumps({
|
| 568 |
+
"type": "done",
|
| 569 |
+
"output": final_output,
|
| 570 |
+
"style": style
|
| 571 |
+
}) + "\n"
|
| 572 |
+
|
| 573 |
+
return StreamingResponse(
|
| 574 |
+
stream_processing(),
|
| 575 |
+
media_type="application/json"
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
if __name__ == "__main__":
|
| 580 |
+
import uvicorn
|
| 581 |
+
port = int(os.getenv("PORT", 7860))
|
| 582 |
+
uvicorn.run(app, host="0.0.0.0", port=port)
|