Rammohan0504 commited on
Commit
1b9c6ad
·
verified ·
1 Parent(s): a93913b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fitz # PyMuPDF
2
+ import gradio as gr
3
+ from PIL import Image, ImageEnhance, ImageFilter
4
+ import io
5
+
6
+ # Step 1: Convert PDF to high-quality image
7
+ def pdf_to_image(pdf_file, dpi=600):
8
+ try:
9
+ print(f"Opening PDF: {pdf_file.name}")
10
+ pdf_document = fitz.open(pdf_file.name)
11
+ page = pdf_document.load_page(0) # Load the first page
12
+
13
+ # Render the page at high DPI
14
+ zoom = dpi / 72 # Scale factor based on DPI
15
+ mat = fitz.Matrix(zoom, zoom)
16
+ pix = page.get_pixmap(matrix=mat, alpha=False)
17
+
18
+ # Convert pixmap to image
19
+ image_bytes = io.BytesIO(pix.tobytes("png"))
20
+ img = Image.open(image_bytes)
21
+ return img
22
+ except Exception as e:
23
+ print(f"Error during PDF conversion: {str(e)}")
24
+ return None
25
+
26
+ # Helper: Convert inches to pixels
27
+ def inches_to_pixels(inches, dpi=600):
28
+ return int(inches * dpi)
29
+
30
+ # Step 2: Adjust image dimensions and brightness
31
+ def adjust_image(pdf_file, height_in, width_in, brightness):
32
+ img = pdf_to_image(pdf_file)
33
+ if img is None:
34
+ return "Unable to convert PDF to image."
35
+
36
+ try:
37
+ # Convert dimensions from inches to pixels
38
+ height_px = inches_to_pixels(height_in)
39
+ width_px = inches_to_pixels(width_in)
40
+
41
+ # Resize with high-quality resampling
42
+ img_resized = img.resize((width_px, height_px), Image.LANCZOS)
43
+
44
+ # Apply anti-aliasing filter for smooth edges
45
+ img_smoothed = img_resized.filter(ImageFilter.SMOOTH)
46
+
47
+ # Adjust brightness
48
+ enhancer = ImageEnhance.Brightness(img_smoothed)
49
+ img_bright = enhancer.enhance(brightness)
50
+
51
+ return img_bright
52
+ except Exception as e:
53
+ print(f"Error during image adjustment: {str(e)}")
54
+ return "Error adjusting the image."
55
+
56
+ # Gradio Interface
57
+ iface = gr.Interface(
58
+ fn=adjust_image,
59
+ inputs=[
60
+ gr.File(label="Upload PDF"),
61
+ gr.Number(label="Height (inches)", value=5.0),
62
+ gr.Number(label="Width (inches)", value=4.0),
63
+ gr.Slider(minimum=0.5, maximum=2, step=0.1, value=1.0, label="Brightness"),
64
+ ],
65
+ outputs="image",
66
+ title="Plate Design Creation - Convert & Adjust PDF Page",
67
+ description="Upload a PDF containing a technical diagram or nameplate. Adjust the dimensions and brightness for optimal clarity."
68
+ )
69
+
70
+ # Launch the interface
71
+ iface.launch()