DSatishchandra commited on
Commit
2d1a10e
·
verified ·
1 Parent(s): 43cec96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -38
app.py CHANGED
@@ -1,17 +1,22 @@
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)):
@@ -20,52 +25,40 @@ def extract_text_with_tesseract(pdf_path):
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
 
41
  # Cleanup temporary image
42
  os.remove(image_path)
43
 
44
- return extracted_data
45
 
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,7 +66,7 @@ def overlay_text_with_fonts(pdf_path, extracted_data, 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
  """
@@ -81,7 +74,7 @@ def process_pdf(uploaded_pdf, output_pdf_path):
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)
@@ -89,8 +82,8 @@ def process_pdf(uploaded_pdf, output_pdf_path):
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:
 
1
  import os
2
  import fitz # PyMuPDF for PDF handling
3
+ from transformers import DonutProcessor, VisionEncoderDecoderModel
4
  from PIL import Image
5
  import tempfile
6
  import streamlit as st
7
 
8
+
9
+ def extract_text_with_donut(pdf_path):
10
  """
11
+ Extract text using Hugging Face Donut model for OCR.
12
  :param pdf_path: Path to the input PDF file.
13
+ :return: List of extracted text for each page.
14
  """
15
+ # Load the model and processor
16
+ processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base")
17
+ model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base")
18
+
19
+ extracted_text = []
20
  doc = fitz.open(pdf_path)
21
 
22
  for page_num in range(len(doc)):
 
25
  image_path = f"temp_page_{page_num}.png"
26
  pix.save(image_path)
27
 
28
+ # Perform OCR using Donut
29
+ image = Image.open(image_path).convert("RGB")
30
+ inputs = processor(images=image, return_tensors="pt")
31
+ outputs = model.generate(**inputs)
32
 
33
+ page_text = processor.batch_decode(outputs, skip_special_tokens=True)[0]
34
+ extracted_text.append({"page_num": page_num, "text": page_text})
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  # Cleanup temporary image
37
  os.remove(image_path)
38
 
39
+ return extracted_text
40
 
41
 
42
  def overlay_text_with_fonts(pdf_path, extracted_data, output_pdf_path):
43
  """
44
+ Overlay extracted text onto the original PDF.
45
  :param pdf_path: Path to the input PDF file.
46
+ :param extracted_data: Extracted text for each page.
47
  :param output_pdf_path: Path to save the output PDF file.
48
  """
49
  doc = fitz.open(pdf_path)
50
 
51
+ for item in extracted_data:
52
+ page_num = item["page_num"]
53
+ text = item["text"]
54
 
 
55
  page = doc[page_num]
56
 
57
+ # Add extracted text to the page
58
+ y = 50 # Starting position
59
+ for line in text.split("\n"):
60
+ page.insert_text((50, y), line, fontsize=10, fontname="Helvetica", color=(0, 0, 0))
61
+ y += 12 # Line spacing
 
 
 
62
 
63
  doc.save(output_pdf_path)
64
  print(f"PDF saved to: {output_pdf_path}")
 
66
 
67
  def process_pdf(uploaded_pdf, output_pdf_path):
68
  """
69
+ Process the uploaded PDF to extract text using Hugging Face Donut and overlay it.
70
  :param uploaded_pdf: Uploaded PDF file.
71
  :param output_pdf_path: Path to save the output PDF file.
72
  """
 
74
  temp_pdf.write(uploaded_pdf.read())
75
  temp_pdf_path = temp_pdf.name
76
 
77
+ extracted_data = extract_text_with_donut(temp_pdf_path)
78
  overlay_text_with_fonts(temp_pdf_path, extracted_data, output_pdf_path)
79
 
80
  os.remove(temp_pdf_path)
 
82
 
83
  # Streamlit App
84
  def main():
85
+ st.title("Hugging Face OCR Text Extraction Tool")
86
+ st.write("Upload a PDF to extract and overlay text using Hugging Face Donut.")
87
 
88
  uploaded_file = st.file_uploader("Upload PDF", type=["pdf"])
89
  if uploaded_file: