jithenderchoudary commited on
Commit
c67261b
·
verified ·
1 Parent(s): 7e4decc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fitz # PyMuPDF
2
+ import gradio as gr
3
+ from PIL import Image, ImageEnhance
4
+ import io
5
+
6
+ # Step 1: Convert the entire PDF page to a high-quality image
7
+ def pdf_to_image(pdf_file, zoom=4): # Increased zoom for better quality
8
+ try:
9
+ print(f"Opening PDF: {pdf_file.name}")
10
+
11
+ # Open the PDF file
12
+ pdf_document = fitz.open(pdf_file.name)
13
+ print("PDF opened successfully.")
14
+
15
+ # Load the first page
16
+ page = pdf_document.load_page(0)
17
+ print("Loaded the first page of the PDF.")
18
+
19
+ # Render the page to an image with a higher zoom level for better quality
20
+ mat = fitz.Matrix(zoom, zoom) # Increase zoom for higher resolution
21
+ pix = page.get_pixmap(matrix=mat, alpha=False) # No transparency
22
+
23
+ # Save the pixmap to a PNG byte stream
24
+ image_bytes = io.BytesIO(pix.tobytes("png"))
25
+ img = Image.open(image_bytes)
26
+ return img
27
+ except Exception as e:
28
+ print(f"Error during PDF to image conversion: {str(e)}")
29
+ return None
30
+
31
+ # Step 2: Adjust image dimensions and brightness
32
+ def adjust_image(pdf_file, height, width, brightness):
33
+ print("Processing the uploaded PDF...")
34
+ img = pdf_to_image(pdf_file)
35
+
36
+ if img is None:
37
+ print("Failed to convert PDF to image.")
38
+ return "Unable to convert PDF to image."
39
+
40
+ try:
41
+ # Resize the image
42
+ img_resized = img.resize((int(width), int(height)), Image.LANCZOS) # High-quality resampling
43
+ print(f"Image resized to: {width}x{height}")
44
+
45
+ # Adjust brightness
46
+ enhancer = ImageEnhance.Brightness(img_resized)
47
+ img_bright = enhancer.enhance(brightness)
48
+ print(f"Brightness adjusted by factor: {brightness}")
49
+
50
+ return img_bright
51
+ except Exception as e:
52
+ print(f"Error during image adjustment: {str(e)}")
53
+ return "Error adjusting the image."
54
+
55
+ # Gradio Interface
56
+ iface = gr.Interface(
57
+ fn=adjust_image,
58
+ inputs=[
59
+ gr.File(label="Upload PDF"),
60
+ gr.Number(label="Height", value=1000),
61
+ gr.Number(label="Width", value=800),
62
+ gr.Slider(minimum=0.5, maximum=2, step=0.1, value=1.0, label="Brightness"),
63
+ ],
64
+ outputs="image",
65
+ title="Plate Design Creation - Convert & Adjust PDF Page",
66
+ description="Upload a PDF containing a technical diagram or nameplate. Convert the page to an image and adjust its dimensions and brightness."
67
+ )
68
+
69
+ # Launch the interface
70
+ iface.launch()