pdf / main.py
Suman2003's picture
Update main.py
bd97350 verified
Raw History Blame Contribute Delete
18.1 kB
from fastapi import FastAPI, File, UploadFile, HTTPException, Form
from fastapi.responses import FileResponse
from pdf2docx import Converter
from playwright.async_api import async_playwright
from pydantic import BaseModel
from pptx import Presentation
from pptx.util import Inches
from youtube_transcript_api import YouTubeTranscriptApi
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
import urllib.parse
import fitz
import tempfile
import os
import traceback
import subprocess
import pdfplumber
import pandas as pd
import json
import urllib.parse
app = FastAPI()
class URLRequest(BaseModel):
url: str
@app.post("/convert")
async def convert_pdf_to_docx(file: UploadFile = File(...)):
try:
# Safely write the uploaded PDF
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
temp_pdf.write(await file.read())
pdf_path = temp_pdf.name
docx_path = pdf_path.replace(".pdf", ".docx")
# Convert using pdf2docx
print(f"Starting conversion for: {file.filename}")
cv = Converter(pdf_path)
cv.convert(docx_path, start=0, end=None)
cv.close()
# Verify the file
if not os.path.exists(docx_path) or os.path.getsize(docx_path) == 0:
raise Exception("Conversion resulted in an empty or corrupted file.")
print(f"Successfully converted: {file.filename}")
return FileResponse(
docx_path,
media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document',
filename=file.filename.replace('.pdf', '.docx')
)
except Exception as e:
# Print the exact error to the Hugging Face console logs!
print("--- CONVERSION CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/word-to-pdf")
async def convert_word_to_pdf(file: UploadFile = File(...)):
try:
# 1. Safely write the uploaded DOCX
with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as temp_docx:
temp_docx.write(await file.read())
docx_path = temp_docx.name
output_dir = os.path.dirname(docx_path)
pdf_path = docx_path.replace(".docx", ".pdf")
# 2. Command LibreOffice to convert it without opening a graphical window
print(f"Starting DOCX to PDF for: {file.filename}")
process = subprocess.run([
"libreoffice", "--headless", "--convert-to", "pdf", docx_path, "--outdir", output_dir
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 3. Verify success
if not os.path.exists(pdf_path) or os.path.getsize(pdf_path) == 0:
print("LibreOffice Error:", process.stderr.decode())
raise Exception("Conversion failed. Check server logs.")
print(f"Successfully converted: {file.filename}")
# 4. Return the perfect PDF
return FileResponse(
pdf_path,
media_type='application/pdf',
filename=file.filename.replace('.docx', '.pdf')
)
except Exception as e:
print("--- CONVERSION CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/powerpoint-to-pdf")
async def convert_powerpoint_to_pdf(file: UploadFile = File(...)):
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as temp_ppt:
temp_ppt.write(await file.read())
ppt_path = temp_ppt.name
output_dir = os.path.dirname(ppt_path)
pdf_path = ppt_path.replace(".pptx", ".pdf")
print(f"Starting PPTX to PDF for: {file.filename}")
process = subprocess.run([
"libreoffice", "--headless", "--convert-to", "pdf", ppt_path, "--outdir", output_dir
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if not os.path.exists(pdf_path) or os.path.getsize(pdf_path) == 0:
raise Exception("Conversion failed. Check server logs.")
return FileResponse(
pdf_path,
media_type='application/pdf',
filename=file.filename.replace('.pptx', '.pdf').replace('.ppt', '.pdf')
)
except Exception as e:
print("--- PPTX CONVERSION CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/excel-to-pdf")
async def convert_excel_to_pdf(file: UploadFile = File(...)):
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as temp_excel:
temp_excel.write(await file.read())
excel_path = temp_excel.name
output_dir = os.path.dirname(excel_path)
pdf_path = excel_path.replace(".xlsx", ".pdf")
print(f"Starting XLSX to PDF for: {file.filename}")
process = subprocess.run([
"libreoffice", "--headless", "--convert-to", "pdf", excel_path, "--outdir", output_dir
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if not os.path.exists(pdf_path) or os.path.getsize(pdf_path) == 0:
raise Exception("Conversion failed. Check server logs.")
return FileResponse(
pdf_path,
media_type='application/pdf',
filename=file.filename.replace('.xlsx', '.pdf').replace('.xls', '.pdf')
)
except Exception as e:
print("--- XLSX CONVERSION CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/url-to-pdf")
async def convert_url_to_pdf(request: URLRequest):
try:
url = request.url
# Ensure the URL is properly formatted
if not url.startswith("http://") and not url.startswith("https://"):
url = "https://" + url
pdf_path = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
print(f"Starting URL to PDF for: {url}")
# Launch the invisible browser
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
# Wait until network is idle so JavaScript frameworks fully load
await page.goto(url, wait_until="networkidle")
# Print to PDF
await page.pdf(path=pdf_path, format="A4", print_background=True)
await browser.close()
print(f"Successfully converted URL: {url}")
return FileResponse(
pdf_path,
media_type='application/pdf',
filename='webpage.pdf'
)
except Exception as e:
print("--- URL TO PDF CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/pdf-to-powerpoint")
async def convert_pdf_to_pptx(file: UploadFile = File(...)):
try:
# 1. Safely write the uploaded PDF
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
temp_pdf.write(await file.read())
pdf_path = temp_pdf.name
pptx_path = pdf_path.replace(".pdf", ".pptx")
print(f"Starting PDF to PPTX for: {file.filename}")
# 2. Create a blank PowerPoint presentation
prs = Presentation()
blank_slide_layout = prs.slide_layouts[6] # 6 is the blank layout
# 3. Open the PDF
doc = fitz.open(pdf_path)
for page_num in range(len(doc)):
page = doc.load_page(page_num)
# Extract high-res image of the page
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
img_path = f"{pdf_path}_page_{page_num}.png"
pix.save(img_path)
# Adjust PowerPoint slide dimensions to match the PDF page (converted from points to EMU)
width = page.rect.width
height = page.rect.height
prs.slide_width = int(width / 72 * 914400)
prs.slide_height = int(height / 72 * 914400)
# Add the slide and insert the image
slide = prs.slides.add_slide(blank_slide_layout)
slide.shapes.add_picture(img_path, 0, 0, width=prs.slide_width, height=prs.slide_height)
# Cleanup the temporary image
os.remove(img_path)
# 4. Save and return the PPTX
prs.save(pptx_path)
print(f"Successfully converted to PPTX: {file.filename}")
return FileResponse(
pptx_path,
media_type='application/vnd.openxmlformats-officedocument.presentationml.presentation',
filename=file.filename.replace('.pdf', '.pptx')
)
except Exception as e:
print("--- PDF TO PPTX CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/pdf-to-excel")
async def convert_pdf_to_excel(file: UploadFile = File(...)):
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
temp_pdf.write(await file.read())
pdf_path = temp_pdf.name
excel_path = pdf_path.replace(".pdf", ".xlsx")
print(f"Starting PDF to Excel for: {file.filename}")
all_tables = []
# 1. Open the PDF and hunt for tables
with pdfplumber.open(pdf_path) as pdf:
for page in pdf.pages:
tables = page.extract_tables()
for table in tables:
# Append raw table data (list of lists)
all_tables.append(table)
# 2. Check if we actually found any data
if not all_tables:
raise Exception("No readable tables were found in this PDF.")
# 3. Create the Excel file using pandas
with pd.ExcelWriter(excel_path, engine='openpyxl') as writer:
for i, table_data in enumerate(all_tables):
# We load it without assuming column names, as PDF tables can be messy
df = pd.DataFrame(table_data)
df.to_excel(writer, sheet_name=f'Table_{i+1}', index=False, header=False)
print(f"Successfully converted to XLSX: {file.filename}")
# 4. Return the Excel file
return FileResponse(
excel_path,
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
filename=file.filename.replace('.pdf', '.xlsx')
)
except Exception as e:
print("--- PDF TO EXCEL CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/unlock-pdf")
async def unlock_pdf(file: UploadFile = File(...), password: str = Form("")):
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
temp_pdf.write(await file.read())
pdf_path = temp_pdf.name
output_path = pdf_path.replace(".pdf", "_unlocked.pdf")
print(f"Starting Unlock PDF for: {file.filename}")
doc = fitz.open(pdf_path)
# Check if the document actually has a lock
if not doc.is_encrypted:
raise Exception("This PDF is not locked or encrypted.")
# Attempt to unlock it using the provided password
auth_success = doc.authenticate(password)
# A return value of 0 means authentication failed
if not auth_success:
raise Exception("Incorrect password. Could not unlock the PDF.")
# Save the document. PyMuPDF automatically strips encryption when saving unless told otherwise!
doc.save(output_path)
doc.close()
print(f"Successfully unlocked: {file.filename}")
return FileResponse(
output_path,
media_type='application/pdf',
filename=file.filename.replace('.pdf', '_unlocked.pdf')
)
except Exception as e:
print("--- UNLOCK PDF CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/protect-pdf")
async def protect_pdf(file: UploadFile = File(...), password: str = Form(...)):
try:
# Require a password to be sent
if not password or len(password.strip()) == 0:
raise Exception("A password is required to protect the document.")
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
temp_pdf.write(await file.read())
pdf_path = temp_pdf.name
output_path = pdf_path.replace(".pdf", "_protected.pdf")
print(f"Starting Protect PDF for: {file.filename}")
doc = fitz.open(pdf_path)
# Save the document with AES-256 encryption
# We set both user_pw and owner_pw so the same password unlocks everything
doc.save(
output_path,
encryption=fitz.PDF_ENCRYPT_AES_256,
user_pw=password,
owner_pw=password
)
doc.close()
print(f"Successfully protected: {file.filename}")
return FileResponse(
output_path,
media_type='application/pdf',
filename=file.filename.replace('.pdf', '_protected.pdf')
)
except Exception as e:
print("--- PROTECT PDF CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/redact-pdf")
async def redact_pdf(file: UploadFile = File(...), redactions: str = Form(...)):
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
temp_pdf.write(await file.read())
pdf_path = temp_pdf.name
output_path = pdf_path.replace(".pdf", "_redacted.pdf")
print(f"Starting Redact PDF for: {file.filename}")
doc = fitz.open(pdf_path)
zones = json.loads(redactions)
# 1. Loop through all requested redactions
for zone in zones:
page_idx = zone["page"] - 1
if page_idx < 0 or page_idx >= len(doc):
continue
page = doc[page_idx]
rect = page.rect
# 2. Convert frontend percentages back into exact PDF coordinates
# PyMuPDF coordinate system starts at Top-Left (0,0)
x0 = (zone["x"] / 100.0) * rect.width
y0 = (zone["y"] / 100.0) * rect.height
x1 = x0 + (zone["w"] / 100.0) * rect.width
y1 = y0 + (zone["h"] / 100.0) * rect.height
# 3. Mark the area for redaction
page.add_redact_annot(fitz.Rect(x0, y0, x1, y1), fill=(0, 0, 0))
# 4. Physically destroy the underlying text/images and apply the black boxes
for page in doc:
page.apply_redactions()
# Save with garbage collection to completely purge unreferenced data
doc.save(output_path, garbage=3, deflate=True)
doc.close()
print(f"Successfully redacted: {file.filename}")
return FileResponse(
output_path,
media_type='application/pdf',
filename=file.filename.replace('.pdf', '_redacted.pdf')
)
except Exception as e:
print("--- REDACT PDF CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/youtube-to-pdf")
async def youtube_to_pdf(url: str = Form(...)):
try:
print(f"Starting YouTube to PDF for: {url}")
# 1. Extract the Video ID from the URL
parsed_url = urllib.parse.urlparse(url)
if "youtube.com" in parsed_url.netloc:
video_id = urllib.parse.parse_qs(parsed_url.query).get("v", [None])[0]
elif "youtu.be" in parsed_url.netloc:
video_id = parsed_url.path.lstrip("/")
else:
raise Exception("Invalid YouTube URL.")
if not video_id:
raise Exception("Could not extract Video ID.")
# 2. Fetch the Transcript (Using the NEW Object-Oriented syntax)
yt_api = YouTubeTranscriptApi()
try:
# Get the list of all available transcripts for this video
transcripts = yt_api.list(video_id)
# Grab the very first available transcript (works for any language!)
transcript = next(iter(transcripts))
transcript_data = transcript.fetch()
except Exception as e:
raise Exception("Transcripts are disabled or unavailable for this video.")
# Combine the text chunks into a single string
full_text = " ".join([item['text'] for item in transcript_data])
# 3. Create the PDF
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
pdf_path = temp_pdf.name
doc = SimpleDocTemplate(pdf_path, pagesize=letter)
styles = getSampleStyleSheet()
story = []
# Add Title
story.append(Paragraph(f"YouTube Transcript Notes", styles['Title']))
story.append(Spacer(1, 12))
# Add the text (breaking it into paragraphs for readability)
words = full_text.split()
chunk_size = 150 # Roughly 150 words per paragraph
for i in range(0, len(words), chunk_size):
paragraph_text = " ".join(words[i:i+chunk_size])
story.append(Paragraph(paragraph_text, styles['Normal']))
story.append(Spacer(1, 12))
doc.build(story)
print(f"Successfully generated PDF for video: {video_id}")
return FileResponse(
pdf_path,
media_type='application/pdf',
filename=f'YouTube_Notes_{video_id}.pdf'
)
except Exception as e:
print("--- YOUTUBE TO PDF CRASHED ---")
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))