DSatishchandra commited on
Commit
fb15ef8
·
verified ·
1 Parent(s): fb81d3a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -49
app.py CHANGED
@@ -1,43 +1,40 @@
1
  import os
2
  import fitz # PyMuPDF for PDF handling
3
- import easyocr # OCR for text extraction
 
4
  import tempfile
5
  import streamlit as st
6
 
7
- # Disable GStreamer to prevent OpenCV-related errors
8
- os.environ["OPENCV_VIDEOIO_PRIORITY_GSTREAMER"] = "0"
9
-
10
- def extract_text_with_ocr(pdf_path):
11
  """
12
- Extract text with bounding box positions using OCR for both English and Arabic text.
13
  :param pdf_path: Path to the input PDF file.
14
  :return: List of dictionaries containing text and positions for each page.
15
  """
16
  extracted_data = []
17
  doc = fitz.open(pdf_path)
18
 
19
- # Convert each PDF page to an image for OCR processing
20
  for page_num in range(len(doc)):
21
  page = doc.load_page(page_num)
22
- pix = page.get_pixmap(dpi=300) # Convert PDF page to image
23
  image_path = f"temp_page_{page_num}.png"
24
  pix.save(image_path)
25
 
26
- # Perform OCR on the image
27
- reader = easyocr.Reader(['en']) # Supports English (add 'ar' for Arabic if needed)
28
- results = reader.readtext(image_path, detail=1) # detail=1 returns bounding box info
29
 
30
- # Extract text and positions
31
  page_data = []
32
- for (bbox, text, confidence) in results:
33
- (x0, y0), (x1, y1) = bbox[0], bbox[2]
34
- page_data.append({
35
- "text": text,
36
- "x0": x0,
37
- "y0": y1, # Adjust to bottom-left corner (PDF coordinates)
38
- "font_size": y1 - y0, # Approximate font size
39
- "confidence": confidence
40
- })
 
41
 
42
  extracted_data.append(page_data)
43
 
@@ -49,29 +46,26 @@ def extract_text_with_ocr(pdf_path):
49
 
50
  def overlay_text_with_fonts(pdf_path, extracted_data, output_pdf_path):
51
  """
52
- Overlay extracted text onto the original PDF using fonts from different font families.
53
  :param pdf_path: Path to the input PDF file.
54
- :param extracted_data: List of extracted text with positions.
55
  :param output_pdf_path: Path to save the output PDF file.
56
  """
57
  doc = fitz.open(pdf_path)
58
 
59
- # Define default font settings
60
- default_font = "Helvetica" # You can replace it with specific fonts like "Arial" or others.
61
 
62
  for page_num, page_data in enumerate(extracted_data):
63
  page = doc[page_num]
64
 
65
  for item in page_data:
66
- if item["confidence"] > 0.8: # Only overlay high-confidence text
67
- page.insert_text(
68
- (item["x0"], item["y0"]),
69
- item["text"],
70
- fontsize=item["font_size"],
71
- fontname=default_font,
72
- color=(0, 0, 0), # Black text
73
- render_mode=0 # Ensure text is not outlined
74
- )
75
 
76
  doc.save(output_pdf_path)
77
  print(f"PDF saved to: {output_pdf_path}")
@@ -79,29 +73,24 @@ def overlay_text_with_fonts(pdf_path, extracted_data, output_pdf_path):
79
 
80
  def process_pdf(uploaded_pdf, output_pdf_path):
81
  """
82
- Process the uploaded PDF to extract text using OCR and overlay it as editable text.
83
- :param uploaded_pdf: The uploaded PDF file.
84
  :param output_pdf_path: Path to save the output PDF file.
85
  """
86
  with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
87
  temp_pdf.write(uploaded_pdf.read())
88
  temp_pdf_path = temp_pdf.name
89
 
90
- # Step 1: Extract text using OCR
91
- extracted_data = extract_text_with_ocr(temp_pdf_path)
92
-
93
- # Step 2: Overlay extracted text onto the original PDF
94
  overlay_text_with_fonts(temp_pdf_path, extracted_data, output_pdf_path)
95
 
96
- # Cleanup temporary file
97
- if os.path.exists(temp_pdf_path):
98
- os.remove(temp_pdf_path)
99
 
100
 
101
  # Streamlit App
102
  def main():
103
- st.title("PDF Text Conversion Tool")
104
- st.write("Upload a PDF to convert vector text into regular, editable text.")
105
 
106
  uploaded_file = st.file_uploader("Upload PDF", type=["pdf"])
107
  if uploaded_file:
@@ -121,10 +110,8 @@ def main():
121
  mime="application/pdf"
122
  )
123
 
124
- # Cleanup the processed output PDF
125
- if os.path.exists(output_pdf_path):
126
- os.remove(output_pdf_path)
127
 
128
 
129
  if __name__ == "__main__":
130
- main()
 
1
  import os
2
  import fitz # PyMuPDF for PDF handling
3
+ import pytesseract # OCR for text extraction
4
+ from PIL import Image
5
  import tempfile
6
  import streamlit as st
7
 
8
+ def extract_text_with_tesseract(pdf_path):
 
 
 
9
  """
10
+ Extract text with bounding box positions using Tesseract OCR.
11
  :param pdf_path: Path to the input PDF file.
12
  :return: List of dictionaries containing text and positions for each page.
13
  """
14
  extracted_data = []
15
  doc = fitz.open(pdf_path)
16
 
 
17
  for page_num in range(len(doc)):
18
  page = doc.load_page(page_num)
19
+ pix = page.get_pixmap(dpi=300) # Convert PDF page to high-resolution image
20
  image_path = f"temp_page_{page_num}.png"
21
  pix.save(image_path)
22
 
23
+ # Perform OCR using Tesseract
24
+ img = Image.open(image_path)
25
+ ocr_result = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)
26
 
 
27
  page_data = []
28
+ for i in range(len(ocr_result["text"])):
29
+ if ocr_result["text"][i].strip(): # Ignore empty text
30
+ page_data.append({
31
+ "text": ocr_result["text"][i],
32
+ "x0": ocr_result["left"][i],
33
+ "y0": ocr_result["top"][i],
34
+ "x1": ocr_result["left"][i] + ocr_result["width"][i],
35
+ "y1": ocr_result["top"][i] + ocr_result["height"][i],
36
+ "font_size": ocr_result["height"][i]
37
+ })
38
 
39
  extracted_data.append(page_data)
40
 
 
46
 
47
  def overlay_text_with_fonts(pdf_path, extracted_data, output_pdf_path):
48
  """
49
+ Overlay extracted text onto the original PDF using PyMuPDF.
50
  :param pdf_path: Path to the input PDF file.
51
+ :param extracted_data: Extracted text and positions.
52
  :param output_pdf_path: Path to save the output PDF file.
53
  """
54
  doc = fitz.open(pdf_path)
55
 
56
+ default_font = "Helvetica"
 
57
 
58
  for page_num, page_data in enumerate(extracted_data):
59
  page = doc[page_num]
60
 
61
  for item in page_data:
62
+ page.insert_text(
63
+ (item["x0"], item["y0"]),
64
+ item["text"],
65
+ fontsize=item["font_size"] / 2, # Adjust font size for better scaling
66
+ fontname=default_font,
67
+ color=(0, 0, 0) # Black text
68
+ )
 
 
69
 
70
  doc.save(output_pdf_path)
71
  print(f"PDF saved to: {output_pdf_path}")
 
73
 
74
  def process_pdf(uploaded_pdf, output_pdf_path):
75
  """
76
+ Process the uploaded PDF to extract text using Tesseract and overlay it.
77
+ :param uploaded_pdf: Uploaded PDF file.
78
  :param output_pdf_path: Path to save the output PDF file.
79
  """
80
  with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
81
  temp_pdf.write(uploaded_pdf.read())
82
  temp_pdf_path = temp_pdf.name
83
 
84
+ extracted_data = extract_text_with_tesseract(temp_pdf_path)
 
 
 
85
  overlay_text_with_fonts(temp_pdf_path, extracted_data, output_pdf_path)
86
 
87
+ os.remove(temp_pdf_path)
 
 
88
 
89
 
90
  # Streamlit App
91
  def main():
92
+ st.title("PDF OCR and Text Conversion Tool")
93
+ st.write("Upload a PDF to extract and overlay text as editable layers.")
94
 
95
  uploaded_file = st.file_uploader("Upload PDF", type=["pdf"])
96
  if uploaded_file:
 
110
  mime="application/pdf"
111
  )
112
 
113
+ os.remove(output_pdf_path)
 
 
114
 
115
 
116
  if __name__ == "__main__":
117
+ main()