Spaces:
Sleeping
Sleeping
Updated the download feature
Browse files
app.py
CHANGED
|
@@ -16,7 +16,7 @@ from enum import Enum
|
|
| 16 |
from contextlib import asynccontextmanager
|
| 17 |
import torch
|
| 18 |
from fastapi import FastAPI, HTTPException, UploadFile, File
|
| 19 |
-
from fastapi.responses import StreamingResponse
|
| 20 |
from pydantic import BaseModel, Field, field_validator
|
| 21 |
from transformers import T5ForConditionalGeneration, T5Tokenizer
|
| 22 |
from docx import Document
|
|
@@ -191,47 +191,106 @@ def paragraph_chunks(text: str, tokenizer, max_tokens: int) -> List[str]:
|
|
| 191 |
|
| 192 |
|
| 193 |
def create_docx(text: str) -> bytes:
|
| 194 |
-
"""Create DOCX file from text"""
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
|
| 215 |
def create_pdf(text: str) -> bytes:
|
| 216 |
-
"""Create PDF file from text"""
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
y = height - 40
|
| 226 |
|
| 227 |
-
#
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
|
| 237 |
class ParaphraseRequest(BaseModel):
|
|
@@ -487,17 +546,21 @@ async def humanize_document(
|
|
| 487 |
return {"output": paraphrased, "style": style}
|
| 488 |
|
| 489 |
elif output_format == "pdf":
|
|
|
|
| 490 |
pdf_bytes = create_pdf(paraphrased)
|
| 491 |
-
|
| 492 |
-
|
|
|
|
| 493 |
media_type="application/pdf",
|
| 494 |
headers={"Content-Disposition": "attachment; filename=paraphrased.pdf"}
|
| 495 |
)
|
| 496 |
|
| 497 |
elif output_format == "docx":
|
|
|
|
| 498 |
docx_bytes = create_docx(paraphrased)
|
| 499 |
-
|
| 500 |
-
|
|
|
|
| 501 |
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
| 502 |
headers={"Content-Disposition": "attachment; filename=paraphrased.docx"}
|
| 503 |
)
|
|
|
|
| 16 |
from contextlib import asynccontextmanager
|
| 17 |
import torch
|
| 18 |
from fastapi import FastAPI, HTTPException, UploadFile, File
|
| 19 |
+
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
|
|
|
|
| 191 |
|
| 192 |
|
| 193 |
def create_docx(text: str) -> bytes:
|
| 194 |
+
"""Create DOCX file from text with proper formatting"""
|
| 195 |
+
try:
|
| 196 |
+
doc = Document()
|
| 197 |
+
|
| 198 |
+
# Split text into paragraphs
|
| 199 |
+
paragraphs = text.split('\n\n')
|
| 200 |
+
|
| 201 |
+
for paragraph in paragraphs:
|
| 202 |
+
if not paragraph.strip():
|
| 203 |
+
continue
|
| 204 |
+
|
| 205 |
+
# Handle different paragraph types
|
| 206 |
+
lines = paragraph.split('\n')
|
| 207 |
+
|
| 208 |
+
for line in lines:
|
| 209 |
+
line = line.strip()
|
| 210 |
+
if not line:
|
| 211 |
+
continue
|
| 212 |
+
|
| 213 |
+
if line.startswith("•") or line.startswith("-"):
|
| 214 |
+
# Bullet point
|
| 215 |
+
doc.add_paragraph(line, style='List Bullet')
|
| 216 |
+
elif line.isupper() and len(line.split()) <= 5:
|
| 217 |
+
# Likely a heading
|
| 218 |
+
doc.add_heading(line, level=2)
|
| 219 |
+
else:
|
| 220 |
+
# Regular paragraph
|
| 221 |
+
doc.add_paragraph(line)
|
| 222 |
+
|
| 223 |
+
# Add spacing between sections
|
| 224 |
+
if paragraph != paragraphs[-1]: # Don't add space after last paragraph
|
| 225 |
+
doc.add_paragraph("")
|
| 226 |
+
|
| 227 |
+
buffer = io.BytesIO()
|
| 228 |
+
doc.save(buffer)
|
| 229 |
+
buffer.seek(0)
|
| 230 |
+
return buffer.read()
|
| 231 |
+
except Exception as e:
|
| 232 |
+
logger.error(f"DOCX generation error: {str(e)}")
|
| 233 |
+
raise HTTPException(status_code=500, detail=f"DOCX generation failed: {str(e)}")
|
| 234 |
|
| 235 |
|
| 236 |
def create_pdf(text: str) -> bytes:
|
| 237 |
+
"""Create PDF file from text with proper formatting"""
|
| 238 |
+
try:
|
| 239 |
+
buffer = io.BytesIO()
|
| 240 |
+
c = canvas.Canvas(buffer, pagesize=LETTER)
|
| 241 |
+
width, height = LETTER
|
| 242 |
+
y = height - 50 # Start from top with margin
|
| 243 |
+
line_height = 14
|
| 244 |
+
margin = 50
|
| 245 |
+
max_width = width - 2 * margin
|
|
|
|
| 246 |
|
| 247 |
+
# Split text into paragraphs
|
| 248 |
+
paragraphs = text.split('\n\n')
|
| 249 |
+
|
| 250 |
+
for paragraph in paragraphs:
|
| 251 |
+
if not paragraph.strip():
|
| 252 |
+
continue
|
| 253 |
+
|
| 254 |
+
# Handle bullet points
|
| 255 |
+
if paragraph.strip().startswith('•') or paragraph.strip().startswith('-'):
|
| 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 |
+
if y < 50: # New page if near bottom
|
| 279 |
+
c.showPage()
|
| 280 |
+
y = height - 50
|
| 281 |
+
|
| 282 |
+
c.drawString(margin, y, line.strip())
|
| 283 |
+
y -= line_height
|
| 284 |
+
|
| 285 |
+
# Add space between paragraphs
|
| 286 |
+
y -= line_height
|
| 287 |
+
|
| 288 |
+
c.save()
|
| 289 |
+
buffer.seek(0)
|
| 290 |
+
return buffer.read()
|
| 291 |
+
except Exception as e:
|
| 292 |
+
logger.error(f"PDF generation error: {str(e)}")
|
| 293 |
+
raise HTTPException(status_code=500, detail=f"PDF generation failed: {str(e)}")
|
| 294 |
|
| 295 |
|
| 296 |
class ParaphraseRequest(BaseModel):
|
|
|
|
| 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 |
+
logger.info(f"Generated PDF: {len(pdf_bytes)} bytes")
|
| 552 |
+
return Response(
|
| 553 |
+
content=pdf_bytes,
|
| 554 |
media_type="application/pdf",
|
| 555 |
headers={"Content-Disposition": "attachment; filename=paraphrased.pdf"}
|
| 556 |
)
|
| 557 |
|
| 558 |
elif output_format == "docx":
|
| 559 |
+
logger.info(f"Generating DOCX for {len(paraphrased)} characters")
|
| 560 |
docx_bytes = create_docx(paraphrased)
|
| 561 |
+
logger.info(f"Generated DOCX: {len(docx_bytes)} bytes")
|
| 562 |
+
return Response(
|
| 563 |
+
content=docx_bytes,
|
| 564 |
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
| 565 |
headers={"Content-Disposition": "attachment; filename=paraphrased.docx"}
|
| 566 |
)
|