File size: 2,440 Bytes
c67261b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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()