Spaces:
Sleeping
Sleeping
| import fitz # PyMuPDF | |
| import gradio as gr | |
| from PIL import Image, ImageEnhance | |
| import io | |
| # Step 1: Convert the entire PDF page to a high-quality image | |
| def pdf_to_image(pdf_file, zoom=4): # Increased zoom for better quality | |
| try: | |
| print(f"Opening PDF: {pdf_file.name}") | |
| # Open the PDF file | |
| pdf_document = fitz.open(pdf_file.name) | |
| print("PDF opened successfully.") | |
| # Load the first page | |
| page = pdf_document.load_page(0) | |
| print("Loaded the first page of the PDF.") | |
| # Render the page to an image with a higher zoom level for better quality | |
| mat = fitz.Matrix(zoom, zoom) # Increase zoom for higher resolution | |
| pix = page.get_pixmap(matrix=mat, alpha=False) # No transparency | |
| # Save the pixmap to a PNG byte stream | |
| image_bytes = io.BytesIO(pix.tobytes("png")) | |
| img = Image.open(image_bytes) | |
| return img | |
| except Exception as e: | |
| print(f"Error during PDF to image conversion: {str(e)}") | |
| return None | |
| # Step 2: Adjust image dimensions and brightness | |
| def adjust_image(pdf_file, height, width, brightness): | |
| print("Processing the uploaded PDF...") | |
| img = pdf_to_image(pdf_file) | |
| if img is None: | |
| print("Failed to convert PDF to image.") | |
| return "Unable to convert PDF to image." | |
| try: | |
| # Resize the image | |
| img_resized = img.resize((int(width), int(height)), Image.LANCZOS) # High-quality resampling | |
| print(f"Image resized to: {width}x{height}") | |
| # Adjust brightness | |
| enhancer = ImageEnhance.Brightness(img_resized) | |
| img_bright = enhancer.enhance(brightness) | |
| print(f"Brightness adjusted by factor: {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", value=1000), | |
| gr.Number(label="Width", value=800), | |
| 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. Convert the page to an image and adjust its dimensions and brightness." | |
| ) | |
| # Launch the interface | |
| iface.launch() |