SathvikGanta's picture
Create app.py
b2f518f verified
import fitz # PyMuPDF
import gradio as gr
from PIL import Image, ImageEnhance, ImageFilter
import io
# Step 1: Convert PDF to high-quality image
def pdf_to_image(pdf_file, dpi=600):
try:
print(f"Opening PDF: {pdf_file.name}")
pdf_document = fitz.open(pdf_file.name)
page = pdf_document.load_page(0) # Load the first page
# Render the page at high DPI
zoom = dpi / 72 # Scale factor based on DPI
mat = fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat, alpha=False)
# Convert pixmap to image
image_bytes = io.BytesIO(pix.tobytes("png"))
img = Image.open(image_bytes)
return img
except Exception as e:
print(f"Error during PDF conversion: {str(e)}")
return None
# Helper: Convert inches to pixels
def inches_to_pixels(inches, dpi=600):
return int(inches * dpi)
# Step 2: Adjust image dimensions and brightness
def adjust_image(pdf_file, height_in, width_in, brightness):
img = pdf_to_image(pdf_file)
if img is None:
return "Unable to convert PDF to image."
try:
# Convert dimensions from inches to pixels
height_px = inches_to_pixels(height_in)
width_px = inches_to_pixels(width_in)
# Resize with high-quality resampling
img_resized = img.resize((width_px, height_px), Image.LANCZOS)
# Apply anti-aliasing filter for smooth edges
img_smoothed = img_resized.filter(ImageFilter.SMOOTH)
# Adjust brightness
enhancer = ImageEnhance.Brightness(img_smoothed)
img_bright = enhancer.enhance(brightness)
return img_bright
except Exception as e:
print(f"Error during image adjustment: {str(e)}")
return "Error adjusting the image."
# Gradio Interface
iface = gr.Interface(
fn=adjust_image,
inputs=[
gr.File(label="Upload PDF"),
gr.Number(label="Height (inches)", value=5.0),
gr.Number(label="Width (inches)", value=4.0),
gr.Slider(minimum=0.5, maximum=2, step=0.1, value=1.0, label="Brightness"),
],
outputs="image",
title="Plate Design Creation - Convert & Adjust PDF Page",
description="Upload a PDF containing a technical diagram or nameplate. Adjust the dimensions and brightness for optimal clarity."
)
# Launch the interface
iface.launch()