Update app.py
Browse files
app.py
CHANGED
|
@@ -25,183 +25,136 @@ app.add_middleware(
|
|
| 25 |
|
| 26 |
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 27 |
|
| 28 |
-
# =====
|
| 29 |
|
| 30 |
-
def
|
| 31 |
-
"""Create a
|
| 32 |
try:
|
| 33 |
from reportlab.pdfgen import canvas
|
| 34 |
-
from reportlab.lib.pagesizes import letter
|
| 35 |
-
from reportlab.lib.units import inch
|
| 36 |
-
from reportlab.lib.colors import Color, black, white, gray, navy, blue
|
| 37 |
from reportlab.pdfbase import pdfmetrics
|
| 38 |
from reportlab.pdfbase.ttfonts import TTFont
|
| 39 |
-
|
| 40 |
-
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak, Table, TableStyle
|
| 41 |
-
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT, TA_JUSTIFY
|
| 42 |
|
| 43 |
buffer = io.BytesIO()
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
#
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
leftMargin=72,
|
| 51 |
-
topMargin=72,
|
| 52 |
-
bottomMargin=72,
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
# Styles
|
| 56 |
-
styles = getSampleStyleSheet()
|
| 57 |
-
|
| 58 |
-
# Custom styles
|
| 59 |
-
title_style = ParagraphStyle(
|
| 60 |
-
'CustomTitle',
|
| 61 |
-
parent=styles['Title'],
|
| 62 |
-
fontSize=24,
|
| 63 |
-
fontName='Helvetica-Bold',
|
| 64 |
-
alignment=TA_CENTER,
|
| 65 |
-
spaceAfter=30,
|
| 66 |
-
textColor=navy
|
| 67 |
-
)
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
parent=styles['Heading2'],
|
| 72 |
-
fontSize=16,
|
| 73 |
-
fontName='Helvetica-Bold',
|
| 74 |
-
alignment=TA_LEFT,
|
| 75 |
-
spaceAfter=12,
|
| 76 |
-
spaceBefore=12,
|
| 77 |
-
textColor=blue
|
| 78 |
-
)
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
-
|
| 91 |
-
story = []
|
| 92 |
-
|
| 93 |
-
# Title
|
| 94 |
-
story.append(Paragraph(f"<b>{title}</b>", title_style))
|
| 95 |
-
story.append(Spacer(1, 0.5*inch))
|
| 96 |
-
|
| 97 |
-
# Add date
|
| 98 |
-
from datetime import datetime
|
| 99 |
-
date_style = ParagraphStyle(
|
| 100 |
-
'Date',
|
| 101 |
-
parent=styles['Normal'],
|
| 102 |
-
fontSize=10,
|
| 103 |
-
fontName='Helvetica',
|
| 104 |
-
alignment=TA_LEFT,
|
| 105 |
-
textColor=gray,
|
| 106 |
-
spaceAfter=20
|
| 107 |
-
)
|
| 108 |
-
story.append(Paragraph(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", date_style))
|
| 109 |
-
story.append(Spacer(1, 0.3*inch))
|
| 110 |
-
|
| 111 |
-
# Process content - split into paragraphs and wrap text
|
| 112 |
-
paragraphs = text_content.split('\n\n')
|
| 113 |
-
|
| 114 |
-
for para in paragraphs:
|
| 115 |
-
if para.strip():
|
| 116 |
-
# Clean and wrap text
|
| 117 |
-
cleaned = para.strip()
|
| 118 |
-
# Remove extra spaces
|
| 119 |
-
cleaned = ' '.join(cleaned.split())
|
| 120 |
-
# Create paragraph with word wrapping
|
| 121 |
-
story.append(Paragraph(cleaned, body_style))
|
| 122 |
-
story.append(Spacer(1, 0.1*inch))
|
| 123 |
-
|
| 124 |
-
# Build PDF
|
| 125 |
-
doc.build(story)
|
| 126 |
buffer.seek(0)
|
| 127 |
return buffer.getvalue()
|
| 128 |
|
| 129 |
except Exception as e:
|
| 130 |
print(f"PDF generation error: {e}")
|
| 131 |
-
# Fallback
|
| 132 |
-
return
|
| 133 |
|
| 134 |
-
def
|
| 135 |
-
"""
|
| 136 |
try:
|
| 137 |
from reportlab.pdfgen import canvas
|
| 138 |
from reportlab.lib.pagesizes import letter
|
| 139 |
from reportlab.lib.units import inch
|
|
|
|
| 140 |
|
| 141 |
buffer = io.BytesIO()
|
| 142 |
c = canvas.Canvas(buffer, pagesize=letter)
|
| 143 |
width, height = letter
|
| 144 |
|
| 145 |
-
#
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
from datetime import datetime
|
| 151 |
-
c.setFont("Helvetica", 10)
|
| 152 |
-
c.drawString(inch, height - 1.5*inch, f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 153 |
|
| 154 |
-
#
|
| 155 |
c.setFont("Helvetica", 11)
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
|
|
|
|
|
|
| 175 |
y -= 15
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
y -= 15
|
| 180 |
|
| 181 |
c.save()
|
| 182 |
buffer.seek(0)
|
| 183 |
return buffer.getvalue()
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
| 186 |
|
| 187 |
# ===== REAL CONVERSION FUNCTIONS =====
|
| 188 |
|
| 189 |
def convert_docx_to_pdf(docx_bytes):
|
| 190 |
-
"""Convert DOCX to PDF with
|
| 191 |
try:
|
| 192 |
from docx import Document
|
| 193 |
|
| 194 |
# Read the DOCX
|
| 195 |
doc = Document(io.BytesIO(docx_bytes))
|
| 196 |
|
| 197 |
-
# Extract all text
|
| 198 |
full_text = []
|
| 199 |
|
| 200 |
-
# Get document title
|
| 201 |
-
title = "Document"
|
| 202 |
-
if doc.core_properties.title:
|
| 203 |
-
title = doc.core_properties.title
|
| 204 |
-
|
| 205 |
# Extract paragraphs
|
| 206 |
for para in doc.paragraphs:
|
| 207 |
if para.text.strip():
|
|
@@ -219,27 +172,18 @@ def convert_docx_to_pdf(docx_bytes):
|
|
| 219 |
|
| 220 |
text_content = '\n\n'.join(full_text) if full_text else "No text content found in document."
|
| 221 |
|
| 222 |
-
# Create
|
| 223 |
-
return
|
| 224 |
|
| 225 |
except Exception as e:
|
| 226 |
print(f"DOCX to PDF error: {e}")
|
| 227 |
-
|
| 228 |
-
try:
|
| 229 |
-
from docx import Document
|
| 230 |
-
doc = Document(io.BytesIO(docx_bytes))
|
| 231 |
-
text = '\n'.join([p.text for p in doc.paragraphs if p.text.strip()])
|
| 232 |
-
return create_basic_pdf(text, "Converted Document")
|
| 233 |
-
except:
|
| 234 |
-
return docx_bytes
|
| 235 |
|
| 236 |
def convert_pdf_to_docx(pdf_bytes):
|
| 237 |
-
"""Convert PDF to DOCX - extract text
|
| 238 |
try:
|
| 239 |
from PyPDF2 import PdfReader
|
| 240 |
from docx import Document
|
| 241 |
-
from docx.shared import Inches, Pt
|
| 242 |
-
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
| 243 |
|
| 244 |
# Read PDF
|
| 245 |
pdf = PdfReader(io.BytesIO(pdf_bytes))
|
|
@@ -247,37 +191,16 @@ def convert_pdf_to_docx(pdf_bytes):
|
|
| 247 |
# Create DOCX
|
| 248 |
doc = Document()
|
| 249 |
|
| 250 |
-
# Add title
|
| 251 |
-
title = doc.add_heading('Converted from PDF', 0)
|
| 252 |
-
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 253 |
-
|
| 254 |
-
# Add date
|
| 255 |
-
from datetime import datetime
|
| 256 |
-
date_para = doc.add_paragraph(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 257 |
-
date_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 258 |
-
|
| 259 |
-
doc.add_paragraph()
|
| 260 |
-
|
| 261 |
# Extract text from each page
|
| 262 |
-
for
|
| 263 |
-
# Page header
|
| 264 |
-
header = doc.add_heading(f'Page {page_num}', 1)
|
| 265 |
-
|
| 266 |
text = page.extract_text()
|
| 267 |
if text and text.strip():
|
| 268 |
# Split into paragraphs
|
| 269 |
paragraphs = text.split('\n\n')
|
| 270 |
for para in paragraphs:
|
| 271 |
if para.strip():
|
| 272 |
-
# Clean up text
|
| 273 |
cleaned = ' '.join(para.split())
|
| 274 |
doc.add_paragraph(cleaned)
|
| 275 |
-
else:
|
| 276 |
-
doc.add_paragraph("[No text extracted from this page]")
|
| 277 |
-
|
| 278 |
-
# Page break between pages
|
| 279 |
-
if page_num < len(pdf.pages):
|
| 280 |
-
doc.add_page_break()
|
| 281 |
|
| 282 |
buffer = io.BytesIO()
|
| 283 |
doc.save(buffer)
|
|
@@ -292,52 +215,24 @@ def convert_pdf_to_excel(pdf_bytes):
|
|
| 292 |
"""Convert PDF to Excel - extract tables"""
|
| 293 |
try:
|
| 294 |
import openpyxl
|
| 295 |
-
from openpyxl.styles import Font, PatternFill, Alignment
|
| 296 |
from PyPDF2 import PdfReader
|
| 297 |
|
| 298 |
wb = openpyxl.Workbook()
|
| 299 |
ws = wb.active
|
| 300 |
ws.title = "Extracted Data"
|
| 301 |
|
| 302 |
-
# Style the header
|
| 303 |
-
header_font = Font(bold=True, color="FFFFFF")
|
| 304 |
-
header_fill = PatternFill(start_color="4F46E5", end_color="4F46E5", fill_type="solid")
|
| 305 |
-
|
| 306 |
pdf = PdfReader(io.BytesIO(pdf_bytes))
|
| 307 |
row = 1
|
| 308 |
|
| 309 |
-
|
| 310 |
-
ws.cell(row=row, column=1, value="Page")
|
| 311 |
-
ws.cell(row=row, column=2, value="Content")
|
| 312 |
-
ws.cell(row=row, column=1).font = header_font
|
| 313 |
-
ws.cell(row=row, column=1).fill = header_fill
|
| 314 |
-
ws.cell(row=row, column=2).font = header_font
|
| 315 |
-
ws.cell(row=row, column=2).fill = header_fill
|
| 316 |
-
row += 1
|
| 317 |
-
|
| 318 |
-
for page_num, page in enumerate(pdf.pages, 1):
|
| 319 |
text = page.extract_text()
|
| 320 |
if text:
|
| 321 |
lines = text.split('\n')
|
| 322 |
for line in lines:
|
| 323 |
if line.strip():
|
| 324 |
-
ws.cell(row=row, column=1, value=
|
| 325 |
-
ws.cell(row=row, column=2, value=line.strip()[:500])
|
| 326 |
row += 1
|
| 327 |
|
| 328 |
-
# Auto-adjust column widths
|
| 329 |
-
for column in ws.columns:
|
| 330 |
-
max_length = 0
|
| 331 |
-
column_letter = column[0].column_letter
|
| 332 |
-
for cell in column:
|
| 333 |
-
try:
|
| 334 |
-
if len(str(cell.value)) > max_length:
|
| 335 |
-
max_length = len(str(cell.value))
|
| 336 |
-
except:
|
| 337 |
-
pass
|
| 338 |
-
adjusted_width = min(max_length + 2, 50)
|
| 339 |
-
ws.column_dimensions[column_letter].width = adjusted_width
|
| 340 |
-
|
| 341 |
buffer = io.BytesIO()
|
| 342 |
wb.save(buffer)
|
| 343 |
buffer.seek(0)
|
|
@@ -348,41 +243,26 @@ def convert_pdf_to_excel(pdf_bytes):
|
|
| 348 |
return pdf_bytes
|
| 349 |
|
| 350 |
def convert_pdf_to_pptx(pdf_bytes):
|
| 351 |
-
"""Convert PDF to PPTX
|
| 352 |
try:
|
| 353 |
from pptx import Presentation
|
| 354 |
-
from pptx.util import Inches, Pt
|
| 355 |
from PyPDF2 import PdfReader
|
| 356 |
|
| 357 |
prs = Presentation()
|
| 358 |
-
|
| 359 |
-
# Set slide layout
|
| 360 |
-
title_slide_layout = prs.slide_layouts[0]
|
| 361 |
content_slide_layout = prs.slide_layouts[1]
|
| 362 |
|
| 363 |
-
# Add title slide
|
| 364 |
-
slide = prs.slides.add_slide(title_slide_layout)
|
| 365 |
-
title = slide.shapes.title
|
| 366 |
-
subtitle = slide.placeholders[1]
|
| 367 |
-
title.text = "PDF Converted to PowerPoint"
|
| 368 |
-
from datetime import datetime
|
| 369 |
-
subtitle.text = f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 370 |
-
|
| 371 |
-
# Read PDF
|
| 372 |
pdf = PdfReader(io.BytesIO(pdf_bytes))
|
| 373 |
|
| 374 |
-
for
|
| 375 |
slide = prs.slides.add_slide(content_slide_layout)
|
| 376 |
title = slide.shapes.title
|
| 377 |
content = slide.placeholders[1]
|
| 378 |
|
| 379 |
-
title.text = f"Page {i+1}"
|
| 380 |
text = page.extract_text()
|
| 381 |
if text and text.strip():
|
| 382 |
-
# Limit text length
|
| 383 |
content.text = text[:1000] + "..." if len(text) > 1000 else text
|
| 384 |
else:
|
| 385 |
-
content.text = "No text extracted
|
| 386 |
|
| 387 |
buffer = io.BytesIO()
|
| 388 |
prs.save(buffer)
|
|
@@ -397,49 +277,47 @@ def convert_excel_to_pdf(excel_bytes):
|
|
| 397 |
"""Convert Excel to PDF"""
|
| 398 |
try:
|
| 399 |
import openpyxl
|
| 400 |
-
from reportlab.
|
| 401 |
-
from reportlab.lib.pagesizes import
|
| 402 |
-
from reportlab.lib import colors
|
| 403 |
-
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 404 |
-
from reportlab.lib.enums import TA_CENTER, TA_LEFT
|
| 405 |
from reportlab.lib.units import inch
|
|
|
|
| 406 |
|
| 407 |
wb = openpyxl.load_workbook(io.BytesIO(excel_bytes))
|
| 408 |
ws = wb.active
|
| 409 |
|
| 410 |
buffer = io.BytesIO()
|
| 411 |
-
|
|
|
|
| 412 |
|
| 413 |
-
|
| 414 |
-
|
|
|
|
|
|
|
| 415 |
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
|
| 420 |
-
#
|
| 421 |
-
|
| 422 |
for row in ws.iter_rows(values=True):
|
| 423 |
-
|
| 424 |
-
if
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
(
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
story.append(t)
|
| 441 |
-
|
| 442 |
-
doc.build(story)
|
| 443 |
buffer.seek(0)
|
| 444 |
return buffer.getvalue()
|
| 445 |
|
|
@@ -451,39 +329,44 @@ def convert_ppt_to_pdf(pptx_bytes):
|
|
| 451 |
"""Convert PPTX to PDF"""
|
| 452 |
try:
|
| 453 |
from pptx import Presentation
|
| 454 |
-
from reportlab.
|
| 455 |
-
from reportlab.lib.pagesizes import
|
| 456 |
-
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 457 |
-
from reportlab.lib.enums import TA_CENTER, TA_LEFT
|
| 458 |
from reportlab.lib.units import inch
|
|
|
|
| 459 |
|
| 460 |
prs = Presentation(io.BytesIO(pptx_bytes))
|
| 461 |
|
| 462 |
buffer = io.BytesIO()
|
| 463 |
-
|
|
|
|
| 464 |
|
| 465 |
-
|
| 466 |
-
|
|
|
|
| 467 |
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
|
| 472 |
-
for
|
| 473 |
-
|
| 474 |
-
story.append(Spacer(1, 0.1*inch))
|
| 475 |
-
|
| 476 |
for shape in slide.shapes:
|
| 477 |
if hasattr(shape, "text") and shape.text:
|
| 478 |
-
|
| 479 |
-
if text:
|
| 480 |
-
story.append(Paragraph(text, styles['Normal']))
|
| 481 |
-
story.append(Spacer(1, 0.05*inch))
|
| 482 |
|
| 483 |
-
if
|
| 484 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
|
| 486 |
-
|
| 487 |
buffer.seek(0)
|
| 488 |
return buffer.getvalue()
|
| 489 |
|
|
@@ -523,7 +406,8 @@ async def root():
|
|
| 523 |
async def health_check():
|
| 524 |
return {
|
| 525 |
"status": "healthy",
|
| 526 |
-
"hf_token": "configured" if HF_TOKEN else "missing"
|
|
|
|
| 527 |
}
|
| 528 |
|
| 529 |
@app.post("/api/convert")
|
|
@@ -531,7 +415,7 @@ async def convert_file(
|
|
| 531 |
file: UploadFile = File(...),
|
| 532 |
target_format: str = Form("pdf")
|
| 533 |
):
|
| 534 |
-
"""Universal file converter
|
| 535 |
try:
|
| 536 |
content = await file.read()
|
| 537 |
filename = file.filename or "file"
|
|
|
|
| 25 |
|
| 26 |
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 27 |
|
| 28 |
+
# ===== CLEAN PDF GENERATION (NO METADATA) =====
|
| 29 |
|
| 30 |
+
def create_clean_pdf(text_content):
|
| 31 |
+
"""Create a clean PDF with just the content - NO extra metadata"""
|
| 32 |
try:
|
| 33 |
from reportlab.pdfgen import canvas
|
| 34 |
+
from reportlab.lib.pagesizes import letter
|
| 35 |
+
from reportlab.lib.units import inch
|
|
|
|
| 36 |
from reportlab.pdfbase import pdfmetrics
|
| 37 |
from reportlab.pdfbase.ttfonts import TTFont
|
| 38 |
+
import textwrap
|
|
|
|
|
|
|
| 39 |
|
| 40 |
buffer = io.BytesIO()
|
| 41 |
+
c = canvas.Canvas(buffer, pagesize=letter)
|
| 42 |
+
width, height = letter
|
| 43 |
|
| 44 |
+
# Set up margins
|
| 45 |
+
left_margin = 72 # 1 inch
|
| 46 |
+
right_margin = 72
|
| 47 |
+
top_margin = 72
|
| 48 |
+
bottom_margin = 72
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
# Set font
|
| 51 |
+
c.setFont("Helvetica", 11)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
# Start position
|
| 54 |
+
x = left_margin
|
| 55 |
+
y = height - top_margin
|
| 56 |
+
|
| 57 |
+
# Split content into lines and wrap
|
| 58 |
+
lines = []
|
| 59 |
+
for paragraph in text_content.split('\n\n'):
|
| 60 |
+
if paragraph.strip():
|
| 61 |
+
# Clean the paragraph
|
| 62 |
+
clean_para = ' '.join(paragraph.split())
|
| 63 |
+
# Wrap text
|
| 64 |
+
wrapped = textwrap.wrap(clean_para, width=80)
|
| 65 |
+
lines.extend(wrapped)
|
| 66 |
+
lines.append('') # Add blank line between paragraphs
|
| 67 |
+
|
| 68 |
+
# Draw each line
|
| 69 |
+
for line in lines:
|
| 70 |
+
if line == '':
|
| 71 |
+
y -= 12 # Blank line
|
| 72 |
+
else:
|
| 73 |
+
# Check if we need a new page
|
| 74 |
+
if y < bottom_margin:
|
| 75 |
+
c.showPage()
|
| 76 |
+
c.setFont("Helvetica", 11)
|
| 77 |
+
y = height - top_margin
|
| 78 |
+
|
| 79 |
+
c.drawString(x, y, line)
|
| 80 |
+
y -= 15 # Line spacing
|
| 81 |
|
| 82 |
+
c.save()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
buffer.seek(0)
|
| 84 |
return buffer.getvalue()
|
| 85 |
|
| 86 |
except Exception as e:
|
| 87 |
print(f"PDF generation error: {e}")
|
| 88 |
+
# Fallback: return plain text
|
| 89 |
+
return text_content.encode('utf-8')
|
| 90 |
|
| 91 |
+
def create_professional_pdf(text_content, title="Document"):
|
| 92 |
+
"""Create a professional PDF with proper formatting - minimal metadata"""
|
| 93 |
try:
|
| 94 |
from reportlab.pdfgen import canvas
|
| 95 |
from reportlab.lib.pagesizes import letter
|
| 96 |
from reportlab.lib.units import inch
|
| 97 |
+
import textwrap
|
| 98 |
|
| 99 |
buffer = io.BytesIO()
|
| 100 |
c = canvas.Canvas(buffer, pagesize=letter)
|
| 101 |
width, height = letter
|
| 102 |
|
| 103 |
+
# Set up margins
|
| 104 |
+
left_margin = 72
|
| 105 |
+
right_margin = 72
|
| 106 |
+
top_margin = 72
|
| 107 |
+
bottom_margin = 72
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
+
# Set font
|
| 110 |
c.setFont("Helvetica", 11)
|
| 111 |
+
|
| 112 |
+
# Start position
|
| 113 |
+
x = left_margin
|
| 114 |
+
y = height - top_margin
|
| 115 |
+
|
| 116 |
+
# Split content into paragraphs
|
| 117 |
+
paragraphs = text_content.split('\n\n') if '\n\n' in text_content else [text_content]
|
| 118 |
+
|
| 119 |
+
for paragraph in paragraphs:
|
| 120 |
+
if paragraph.strip():
|
| 121 |
+
# Clean the paragraph
|
| 122 |
+
clean_para = ' '.join(paragraph.split())
|
| 123 |
+
# Wrap text
|
| 124 |
+
wrapped = textwrap.wrap(clean_para, width=80)
|
| 125 |
+
|
| 126 |
+
for line in wrapped:
|
| 127 |
+
if y < bottom_margin:
|
| 128 |
+
c.showPage()
|
| 129 |
+
c.setFont("Helvetica", 11)
|
| 130 |
+
y = height - top_margin
|
| 131 |
+
c.drawString(x, y, line)
|
| 132 |
y -= 15
|
| 133 |
+
|
| 134 |
+
# Add space between paragraphs
|
| 135 |
+
y -= 10
|
|
|
|
| 136 |
|
| 137 |
c.save()
|
| 138 |
buffer.seek(0)
|
| 139 |
return buffer.getvalue()
|
| 140 |
+
|
| 141 |
+
except Exception as e:
|
| 142 |
+
print(f"PDF generation error: {e}")
|
| 143 |
+
return create_clean_pdf(text_content)
|
| 144 |
|
| 145 |
# ===== REAL CONVERSION FUNCTIONS =====
|
| 146 |
|
| 147 |
def convert_docx_to_pdf(docx_bytes):
|
| 148 |
+
"""Convert DOCX to PDF with clean content"""
|
| 149 |
try:
|
| 150 |
from docx import Document
|
| 151 |
|
| 152 |
# Read the DOCX
|
| 153 |
doc = Document(io.BytesIO(docx_bytes))
|
| 154 |
|
| 155 |
+
# Extract all text
|
| 156 |
full_text = []
|
| 157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
# Extract paragraphs
|
| 159 |
for para in doc.paragraphs:
|
| 160 |
if para.text.strip():
|
|
|
|
| 172 |
|
| 173 |
text_content = '\n\n'.join(full_text) if full_text else "No text content found in document."
|
| 174 |
|
| 175 |
+
# Create clean PDF
|
| 176 |
+
return create_clean_pdf(text_content)
|
| 177 |
|
| 178 |
except Exception as e:
|
| 179 |
print(f"DOCX to PDF error: {e}")
|
| 180 |
+
return docx_bytes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
def convert_pdf_to_docx(pdf_bytes):
|
| 183 |
+
"""Convert PDF to DOCX - extract text"""
|
| 184 |
try:
|
| 185 |
from PyPDF2 import PdfReader
|
| 186 |
from docx import Document
|
|
|
|
|
|
|
| 187 |
|
| 188 |
# Read PDF
|
| 189 |
pdf = PdfReader(io.BytesIO(pdf_bytes))
|
|
|
|
| 191 |
# Create DOCX
|
| 192 |
doc = Document()
|
| 193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
# Extract text from each page
|
| 195 |
+
for page in pdf.pages:
|
|
|
|
|
|
|
|
|
|
| 196 |
text = page.extract_text()
|
| 197 |
if text and text.strip():
|
| 198 |
# Split into paragraphs
|
| 199 |
paragraphs = text.split('\n\n')
|
| 200 |
for para in paragraphs:
|
| 201 |
if para.strip():
|
|
|
|
| 202 |
cleaned = ' '.join(para.split())
|
| 203 |
doc.add_paragraph(cleaned)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
buffer = io.BytesIO()
|
| 206 |
doc.save(buffer)
|
|
|
|
| 215 |
"""Convert PDF to Excel - extract tables"""
|
| 216 |
try:
|
| 217 |
import openpyxl
|
|
|
|
| 218 |
from PyPDF2 import PdfReader
|
| 219 |
|
| 220 |
wb = openpyxl.Workbook()
|
| 221 |
ws = wb.active
|
| 222 |
ws.title = "Extracted Data"
|
| 223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
pdf = PdfReader(io.BytesIO(pdf_bytes))
|
| 225 |
row = 1
|
| 226 |
|
| 227 |
+
for page in pdf.pages:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
text = page.extract_text()
|
| 229 |
if text:
|
| 230 |
lines = text.split('\n')
|
| 231 |
for line in lines:
|
| 232 |
if line.strip():
|
| 233 |
+
ws.cell(row=row, column=1, value=line.strip()[:500])
|
|
|
|
| 234 |
row += 1
|
| 235 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
buffer = io.BytesIO()
|
| 237 |
wb.save(buffer)
|
| 238 |
buffer.seek(0)
|
|
|
|
| 243 |
return pdf_bytes
|
| 244 |
|
| 245 |
def convert_pdf_to_pptx(pdf_bytes):
|
| 246 |
+
"""Convert PDF to PPTX"""
|
| 247 |
try:
|
| 248 |
from pptx import Presentation
|
|
|
|
| 249 |
from PyPDF2 import PdfReader
|
| 250 |
|
| 251 |
prs = Presentation()
|
|
|
|
|
|
|
|
|
|
| 252 |
content_slide_layout = prs.slide_layouts[1]
|
| 253 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
pdf = PdfReader(io.BytesIO(pdf_bytes))
|
| 255 |
|
| 256 |
+
for page in pdf.pages:
|
| 257 |
slide = prs.slides.add_slide(content_slide_layout)
|
| 258 |
title = slide.shapes.title
|
| 259 |
content = slide.placeholders[1]
|
| 260 |
|
|
|
|
| 261 |
text = page.extract_text()
|
| 262 |
if text and text.strip():
|
|
|
|
| 263 |
content.text = text[:1000] + "..." if len(text) > 1000 else text
|
| 264 |
else:
|
| 265 |
+
content.text = "No text extracted"
|
| 266 |
|
| 267 |
buffer = io.BytesIO()
|
| 268 |
prs.save(buffer)
|
|
|
|
| 277 |
"""Convert Excel to PDF"""
|
| 278 |
try:
|
| 279 |
import openpyxl
|
| 280 |
+
from reportlab.pdfgen import canvas
|
| 281 |
+
from reportlab.lib.pagesizes import letter
|
|
|
|
|
|
|
|
|
|
| 282 |
from reportlab.lib.units import inch
|
| 283 |
+
import textwrap
|
| 284 |
|
| 285 |
wb = openpyxl.load_workbook(io.BytesIO(excel_bytes))
|
| 286 |
ws = wb.active
|
| 287 |
|
| 288 |
buffer = io.BytesIO()
|
| 289 |
+
c = canvas.Canvas(buffer, pagesize=letter)
|
| 290 |
+
width, height = letter
|
| 291 |
|
| 292 |
+
# Set up margins
|
| 293 |
+
left_margin = 72
|
| 294 |
+
top_margin = 72
|
| 295 |
+
bottom_margin = 72
|
| 296 |
|
| 297 |
+
c.setFont("Helvetica", 10)
|
| 298 |
+
y = height - top_margin
|
| 299 |
+
x = left_margin
|
| 300 |
|
| 301 |
+
# Extract all cell values
|
| 302 |
+
cell_values = []
|
| 303 |
for row in ws.iter_rows(values=True):
|
| 304 |
+
row_text = ' | '.join([str(cell) for cell in row if cell])
|
| 305 |
+
if row_text:
|
| 306 |
+
cell_values.append(row_text)
|
| 307 |
+
|
| 308 |
+
# Write to PDF with word wrapping
|
| 309 |
+
for row_text in cell_values:
|
| 310 |
+
wrapped = textwrap.wrap(row_text, width=80)
|
| 311 |
+
for line in wrapped:
|
| 312 |
+
if y < bottom_margin:
|
| 313 |
+
c.showPage()
|
| 314 |
+
c.setFont("Helvetica", 10)
|
| 315 |
+
y = height - top_margin
|
| 316 |
+
c.drawString(x, y, line)
|
| 317 |
+
y -= 12
|
| 318 |
+
y -= 6 # Space between rows
|
| 319 |
+
|
| 320 |
+
c.save()
|
|
|
|
|
|
|
|
|
|
| 321 |
buffer.seek(0)
|
| 322 |
return buffer.getvalue()
|
| 323 |
|
|
|
|
| 329 |
"""Convert PPTX to PDF"""
|
| 330 |
try:
|
| 331 |
from pptx import Presentation
|
| 332 |
+
from reportlab.pdfgen import canvas
|
| 333 |
+
from reportlab.lib.pagesizes import letter
|
|
|
|
|
|
|
| 334 |
from reportlab.lib.units import inch
|
| 335 |
+
import textwrap
|
| 336 |
|
| 337 |
prs = Presentation(io.BytesIO(pptx_bytes))
|
| 338 |
|
| 339 |
buffer = io.BytesIO()
|
| 340 |
+
c = canvas.Canvas(buffer, pagesize=letter)
|
| 341 |
+
width, height = letter
|
| 342 |
|
| 343 |
+
left_margin = 72
|
| 344 |
+
top_margin = 72
|
| 345 |
+
bottom_margin = 72
|
| 346 |
|
| 347 |
+
c.setFont("Helvetica", 11)
|
| 348 |
+
y = height - top_margin
|
| 349 |
+
x = left_margin
|
| 350 |
|
| 351 |
+
for slide in prs.slides:
|
| 352 |
+
slide_text = []
|
|
|
|
|
|
|
| 353 |
for shape in slide.shapes:
|
| 354 |
if hasattr(shape, "text") and shape.text:
|
| 355 |
+
slide_text.append(shape.text.strip())
|
|
|
|
|
|
|
|
|
|
| 356 |
|
| 357 |
+
if slide_text:
|
| 358 |
+
text = '\n\n'.join(slide_text)
|
| 359 |
+
wrapped = textwrap.wrap(text, width=80)
|
| 360 |
+
for line in wrapped:
|
| 361 |
+
if y < bottom_margin:
|
| 362 |
+
c.showPage()
|
| 363 |
+
c.setFont("Helvetica", 11)
|
| 364 |
+
y = height - top_margin
|
| 365 |
+
c.drawString(x, y, line)
|
| 366 |
+
y -= 15
|
| 367 |
+
y -= 20 # Space between slides
|
| 368 |
|
| 369 |
+
c.save()
|
| 370 |
buffer.seek(0)
|
| 371 |
return buffer.getvalue()
|
| 372 |
|
|
|
|
| 406 |
async def health_check():
|
| 407 |
return {
|
| 408 |
"status": "healthy",
|
| 409 |
+
"hf_token": "configured" if HF_TOKEN else "missing",
|
| 410 |
+
"hf_token_length": len(HF_TOKEN) if HF_TOKEN else 0
|
| 411 |
}
|
| 412 |
|
| 413 |
@app.post("/api/convert")
|
|
|
|
| 415 |
file: UploadFile = File(...),
|
| 416 |
target_format: str = Form("pdf")
|
| 417 |
):
|
| 418 |
+
"""Universal file converter"""
|
| 419 |
try:
|
| 420 |
content = await file.read()
|
| 421 |
filename = file.filename or "file"
|