karthikmn commited on
Commit
7c64ce7
·
verified ·
1 Parent(s): 04ccc8d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -31
app.py CHANGED
@@ -3,13 +3,14 @@ import datetime
3
  from PIL import Image
4
  from fpdf import FPDF
5
  import gradio as gr
 
6
 
7
  # Folder paths
8
  INPUT_FOLDER = "./input/"
9
  OUTPUT_FOLDER = "./output/"
10
  LOG_FOLDER = "./logs/"
11
  PROCESSED_IMAGE = os.path.join(OUTPUT_FOLDER, "processed_image.png")
12
- OUTPUT_PDF = os.path.join(OUTPUT_FOLDER, "processed_image.pdf")
13
  LOG_FILE = os.path.join(LOG_FOLDER, "conversion_log.txt")
14
 
15
  # Ensure required folders exist
@@ -18,56 +19,74 @@ os.makedirs(OUTPUT_FOLDER, exist_ok=True)
18
  os.makedirs(LOG_FOLDER, exist_ok=True)
19
 
20
  # Function to log conversion steps
21
- def log_conversion(status, input_image, output_file):
22
  with open(LOG_FILE, "a") as log_file:
23
  log_file.write(f"{datetime.datetime.now()} - Status: {status}\n")
24
- log_file.write(f"Input Image: {input_image}\n")
25
  log_file.write(f"Output File: {output_file}\n\n")
26
 
27
- # Processing function
28
- def process_image(uploaded_image, width_inches, height_inches, dpi=300):
29
  try:
30
- # Save the uploaded image temporarily
31
- input_image_path = os.path.join(INPUT_FOLDER, "uploaded_image.png")
32
- uploaded_image.save(input_image_path)
33
-
34
- # Convert inches to pixels (1 inch = dpi pixels)
35
- width_pixels = int(width_inches * dpi)
36
- height_pixels = int(height_inches * dpi)
37
-
38
- # Open and process the image
39
- with Image.open(input_image_path) as img:
40
- grayscale_image = img.convert("L") # Convert to grayscale
41
- resized_image = grayscale_image.resize((width_pixels, height_pixels)) # Resize
42
- resized_image.save(PROCESSED_IMAGE)
43
-
44
- # Convert the processed image to PDF
45
- pdf = FPDF(unit="in", format=(width_inches, height_inches))
46
- pdf.add_page()
47
- pdf.image(PROCESSED_IMAGE, x=0, y=0, w=width_inches, h=height_inches)
48
- pdf.output(OUTPUT_PDF)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  # Log success
51
- log_conversion("Success", input_image_path, OUTPUT_PDF)
52
 
53
  # Return processed PDF and log file
54
  return OUTPUT_PDF, LOG_FILE
 
55
  except Exception as e:
56
- log_conversion("Failed", "Uploaded Image", "Processing Error")
57
  return None, f"Error: {str(e)}"
58
 
59
  # Gradio Interface
60
  def gradio_app():
61
  with gr.Blocks() as demo:
62
- gr.Markdown("# Image Grayscale Converter and Resizer (Inches to PDF)")
63
 
64
  with gr.Row():
65
- image_input = gr.Image(type="pil", label="Upload Image")
66
  with gr.Column():
67
  width_input = gr.Number(value=8.5, label="Width (in inches)")
68
  height_input = gr.Number(value=11.0, label="Height (in inches)")
69
 
70
- process_button = gr.Button("Process Image to PDF")
71
 
72
  with gr.Row():
73
  pdf_output = gr.File(label="Download Processed PDF")
@@ -75,8 +94,8 @@ def gradio_app():
75
 
76
  # Define the button click functionality
77
  process_button.click(
78
- process_image,
79
- inputs=[image_input, width_input, height_input],
80
  outputs=[pdf_output, log_file_output],
81
  )
82
 
 
3
  from PIL import Image
4
  from fpdf import FPDF
5
  import gradio as gr
6
+ from PyPDF2 import PdfReader, PdfWriter
7
 
8
  # Folder paths
9
  INPUT_FOLDER = "./input/"
10
  OUTPUT_FOLDER = "./output/"
11
  LOG_FOLDER = "./logs/"
12
  PROCESSED_IMAGE = os.path.join(OUTPUT_FOLDER, "processed_image.png")
13
+ OUTPUT_PDF = os.path.join(OUTPUT_FOLDER, "processed_file.pdf")
14
  LOG_FILE = os.path.join(LOG_FOLDER, "conversion_log.txt")
15
 
16
  # Ensure required folders exist
 
19
  os.makedirs(LOG_FOLDER, exist_ok=True)
20
 
21
  # Function to log conversion steps
22
+ def log_conversion(status, input_file, output_file):
23
  with open(LOG_FILE, "a") as log_file:
24
  log_file.write(f"{datetime.datetime.now()} - Status: {status}\n")
25
+ log_file.write(f"Input File: {input_file}\n")
26
  log_file.write(f"Output File: {output_file}\n\n")
27
 
28
+ # Processing function for PDF
29
+ def process_pdf(uploaded_pdf, width_inches, height_inches, dpi=300):
30
  try:
31
+ # Save the uploaded PDF temporarily
32
+ input_pdf_path = os.path.join(INPUT_FOLDER, "uploaded_file.pdf")
33
+ with open(input_pdf_path, "wb") as f:
34
+ f.write(uploaded_pdf.read())
35
+
36
+ # Read the PDF
37
+ reader = PdfReader(input_pdf_path)
38
+ writer = PdfWriter()
39
+
40
+ for page_num, page in enumerate(reader.pages):
41
+ # Extract the image from the PDF page
42
+ if "/XObject" in page["/Resources"]:
43
+ xObject = page["/Resources"]["/XObject"].get_object()
44
+ for obj in xObject:
45
+ if xObject[obj]["/Subtype"] == "/Image":
46
+ size = (xObject[obj]["/Width"], xObject[obj]["/Height"])
47
+ data = xObject[obj].get_data()
48
+ img = Image.frombytes("RGB", size, data)
49
+
50
+ # Convert the image to grayscale and resize
51
+ grayscale_image = img.convert("L")
52
+ width_pixels = int(width_inches * dpi)
53
+ height_pixels = int(height_inches * dpi)
54
+ resized_image = grayscale_image.resize((width_pixels, height_pixels))
55
+
56
+ # Save processed image temporarily
57
+ processed_image_path = os.path.join(OUTPUT_FOLDER, f"processed_page_{page_num + 1}.png")
58
+ resized_image.save(processed_image_path)
59
+
60
+ # Add the processed image to the new PDF
61
+ pdf = FPDF(unit="in", format=(width_inches, height_inches))
62
+ pdf.add_page()
63
+ pdf.image(processed_image_path, x=0, y=0, w=width_inches, h=height_inches)
64
+
65
+ # Save the final PDF
66
+ pdf.output(OUTPUT_PDF)
67
 
68
  # Log success
69
+ log_conversion("Success", input_pdf_path, OUTPUT_PDF)
70
 
71
  # Return processed PDF and log file
72
  return OUTPUT_PDF, LOG_FILE
73
+
74
  except Exception as e:
75
+ log_conversion("Failed", "Uploaded PDF", "Processing Error")
76
  return None, f"Error: {str(e)}"
77
 
78
  # Gradio Interface
79
  def gradio_app():
80
  with gr.Blocks() as demo:
81
+ gr.Markdown("# PDF Grayscale Converter and Resizer")
82
 
83
  with gr.Row():
84
+ pdf_input = gr.File(type="file", label="Upload PDF File")
85
  with gr.Column():
86
  width_input = gr.Number(value=8.5, label="Width (in inches)")
87
  height_input = gr.Number(value=11.0, label="Height (in inches)")
88
 
89
+ process_button = gr.Button("Process PDF")
90
 
91
  with gr.Row():
92
  pdf_output = gr.File(label="Download Processed PDF")
 
94
 
95
  # Define the button click functionality
96
  process_button.click(
97
+ process_pdf,
98
+ inputs=[pdf_input, width_input, height_input],
99
  outputs=[pdf_output, log_file_output],
100
  )
101