lokesh341 commited on
Commit
5071de2
·
verified ·
1 Parent(s): 0960583

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fitz # PyMuPDF
2
+ from PIL import Image
3
+ import pytesseract
4
+ from fpdf import FPDF
5
+ import gradio as gr
6
+
7
+ # Step 1: Convert PDF Pages to Images
8
+ def pdf_to_images(pdf_path):
9
+ pdf_document = fitz.open(pdf_path)
10
+ images = []
11
+ for page_num in range(len(pdf_document)):
12
+ page = pdf_document[page_num]
13
+ pix = page.get_pixmap() # Render the page as an image
14
+ image_path = f"page_{page_num + 1}.png"
15
+ pix.save(image_path)
16
+ images.append(image_path)
17
+ return images
18
+
19
+ # Step 2: Extract Text Using Tesseract OCR
20
+ def extract_text(images):
21
+ text_pages = []
22
+ for image_path in images:
23
+ text = pytesseract.image_to_string(Image.open(image_path)) # Perform OCR
24
+ text_pages.append(text)
25
+ return text_pages
26
+
27
+ # Step 3: Replace Curved Text with Editable Text in a New PDF
28
+ def create_editable_pdf(images, text_pages, output_pdf_path):
29
+ pdf = FPDF()
30
+ pdf.set_auto_page_break(auto=True, margin=15)
31
+ for text in text_pages:
32
+ pdf.add_page()
33
+ pdf.set_font("Arial", size=12)
34
+ pdf.multi_cell(0, 10, text)
35
+ pdf.output(output_pdf_path)
36
+
37
+ # Main Function
38
+ def process_pdf(file):
39
+ input_pdf_path = file.name
40
+ output_pdf_path = "Editable_Output.pdf"
41
+
42
+ # Convert PDF to images and perform OCR
43
+ images = pdf_to_images(input_pdf_path)
44
+ text_pages = extract_text(images)
45
+
46
+ # Create a new editable PDF
47
+ create_editable_pdf(images, text_pages, output_pdf_path)
48
+ return output_pdf_path
49
+
50
+ # Gradio Interface
51
+ iface = gr.Interface(
52
+ fn=process_pdf,
53
+ inputs=gr.File(label="Upload PDF"),
54
+ outputs=gr.File(label="Download Editable PDF"),
55
+ title="OCR PDF to Editable Text",
56
+ description="Upload a PDF to extract and replace text while preserving shapes and layout.",
57
+ )
58
+
59
+ iface.launch()