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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
#os.environ["PATH"] += os.pathsep + "/usr/bin" + os.pathsep + "/usr/local/bin" #Removed redundant path setting
|
| 3 |
+
print(f"Current PATH: {os.environ['PATH']}")
|
| 4 |
import streamlit as st
|
| 5 |
+
from PyPDF2 import PdfMerger
|
| 6 |
+
from google.cloud import vision
|
| 7 |
+
from google.oauth2 import service_account
|
| 8 |
+
import fitz
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
import tempfile
|
| 12 |
+
import json
|
| 13 |
+
from streamlit_sortables import sort_items
|
| 14 |
+
import subprocess
|
| 15 |
+
from tqdm import tqdm
|
| 16 |
+
|
| 17 |
+
# Check if /usr/bin/pdfinfo exists
|
| 18 |
+
if os.path.exists("/usr/bin/pdfinfo"):
|
| 19 |
+
print("pdfinfo exists at /usr/bin/pdfinfo")
|
| 20 |
+
# Check the file permissions
|
| 21 |
+
permissions = os.stat("/usr/bin/pdfinfo").st_mode
|
| 22 |
+
print(f"File permissions: {oct(permissions)}")
|
| 23 |
+
else:
|
| 24 |
+
print("pdfinfo does not exist at /usr/bin/pdfinfo")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Load Google Cloud Vision credentials from secret
|
| 28 |
+
credentials_json = os.getenv("GOOGLE_CREDENTIALS_JSON")
|
| 29 |
+
if credentials_json:
|
| 30 |
+
credentials_dict = json.loads(credentials_json)
|
| 31 |
+
credentials = service_account.Credentials.from_service_account_info(credentials_dict)
|
| 32 |
+
client = vision.ImageAnnotatorClient(credentials=credentials)
|
| 33 |
+
else:
|
| 34 |
+
client = None
|
| 35 |
+
|
| 36 |
+
# Function to extract text using Google Cloud Vision
|
| 37 |
+
def extract_text_with_google_vision(image_bytes):
|
| 38 |
+
"""Extracts text using Google Cloud Vision."""
|
| 39 |
+
image = vision.Image(content=image_bytes)
|
| 40 |
+
response = client.document_text_detection(image=image)
|
| 41 |
+
if response.error.message:
|
| 42 |
+
raise Exception(f"Google Cloud Vision API Error: {response.error.message}")
|
| 43 |
+
return response.full_text_annotation.text if response.full_text_annotation else ""
|
| 44 |
+
|
| 45 |
+
# Function to process PDF for transcription
|
| 46 |
+
def process_pdf(file):
|
| 47 |
+
"""Converts PDF pages to images and extracts text."""
|
| 48 |
+
text = ""
|
| 49 |
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_pdf:
|
| 50 |
+
temp_pdf.write(file.read())
|
| 51 |
+
temp_pdf_path = temp_pdf.name
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
doc = fitz.open(temp_pdf_path)
|
| 55 |
+
for i in tqdm(range(len(doc)), desc="Processing pages"):
|
| 56 |
+
page = doc.load_page(i)
|
| 57 |
+
pix = page.get_pixmap()
|
| 58 |
+
image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
| 59 |
+
image_bytes = BytesIO()
|
| 60 |
+
image.save(image_bytes, format="PNG")
|
| 61 |
+
image_bytes.seek(0)
|
| 62 |
+
try:
|
| 63 |
+
page_text = extract_text_with_google_vision(image_bytes.getvalue())
|
| 64 |
+
text += f"--- Page {i + 1} ---\n{page_text}\n\n"
|
| 65 |
+
except Exception as e:
|
| 66 |
+
st.error(f"Error on page {i + 1}: {e}")
|
| 67 |
+
finally:
|
| 68 |
+
os.remove(temp_pdf_path)
|
| 69 |
+
|
| 70 |
+
return text
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# Function to generate thumbnail from PDF
|
| 74 |
+
def get_pdf_thumbnail(uploaded_file):
|
| 75 |
+
"""Generates a thumbnail image of the first page of a PDF."""
|
| 76 |
+
uploaded_file.seek(0)
|
| 77 |
+
doc = fitz.open(stream=uploaded_file.read(), filetype="pdf")
|
| 78 |
+
page = doc.load_page(0)
|
| 79 |
+
pix = page.get_pixmap()
|
| 80 |
+
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
| 81 |
+
img.thumbnail((100, 140))
|
| 82 |
+
return img
|
| 83 |
+
|
| 84 |
+
# Function to merge PDFs
|
| 85 |
+
def merge_pdfs(reordered_files):
|
| 86 |
+
"""Merges multiple PDFs into one."""
|
| 87 |
+
merger = PdfMerger()
|
| 88 |
+
for file in reordered_files:
|
| 89 |
+
file.seek(0)
|
| 90 |
+
merger.append(file)
|
| 91 |
+
output_filename = "combined_document.pdf"
|
| 92 |
+
with open(output_filename, "wb") as output_file:
|
| 93 |
+
merger.write(output_file)
|
| 94 |
+
return output_filename
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def add_signature_to_pdf(pdf_file, signature_image, x, y):
|
| 98 |
+
"""Adds a signature image to the PDF at the given coordinates."""
|
| 99 |
+
|
| 100 |
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_pdf:
|
| 101 |
+
try:
|
| 102 |
+
temp_pdf.write(pdf_file.read())
|
| 103 |
+
temp_pdf_path = temp_pdf.name
|
| 104 |
+
print(f"temp file name: {temp_pdf_path}")
|
| 105 |
+
except Exception as e:
|
| 106 |
+
print(f"Error creating temp file: {e}")
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
try:
|
| 110 |
+
doc = fitz.open(temp_pdf_path)
|
| 111 |
+
page = doc[0] # Operate on the first page for simplicity
|
| 112 |
+
rect = fitz.Rect(x, y, x + 200, y + 100) # Size for the signature
|
| 113 |
+
|
| 114 |
+
img = Image.open(signature_image)
|
| 115 |
+
img_bytes = BytesIO()
|
| 116 |
+
img.save(img_bytes, format="PNG")
|
| 117 |
+
img_bytes.seek(0)
|
| 118 |
+
page.insert_image(rect, stream=img_bytes.read(), keep_proportion=True)
|
| 119 |
+
output_filename = "signed_document.pdf"
|
| 120 |
+
doc.save(output_filename)
|
| 121 |
+
os.remove(temp_pdf_path)
|
| 122 |
+
return output_filename
|
| 123 |
+
except Exception as e:
|
| 124 |
+
print(f"Error with pdf: {e}")
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
def pdf_signer_ui(pdf_file, signature_image):
|
| 128 |
+
"""Handles the UI and logic for PDF signing."""
|
| 129 |
+
if st.button("Preview PDF"):
|
| 130 |
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_pdf:
|
| 131 |
+
try:
|
| 132 |
+
temp_pdf.write(pdf_file.read())
|
| 133 |
+
temp_pdf_path = temp_pdf.name
|
| 134 |
+
print(f"temp file name: {temp_pdf_path}")
|
| 135 |
+
except Exception as e:
|
| 136 |
+
print(f"Error creating temporary file: {e}")
|
| 137 |
+
st.error("Could not create temporary file. Please make sure your uploaded file is valid")
|
| 138 |
+
return
|
| 139 |
+
|
| 140 |
+
try:
|
| 141 |
+
doc = fitz.open(temp_pdf_path)
|
| 142 |
+
page = doc[0]
|
| 143 |
+
pix = page.get_pixmap()
|
| 144 |
+
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
| 145 |
+
clicked = st.image(img, use_container_width=True)
|
| 146 |
+
if clicked:
|
| 147 |
+
x = clicked.x
|
| 148 |
+
y = clicked.y
|
| 149 |
+
if st.button("Add Signature"):
|
| 150 |
+
with st.spinner("Adding Signature..."):
|
| 151 |
+
if pdf_file and signature_image: # Check for file existence
|
| 152 |
+
output_file = add_signature_to_pdf(pdf_file, signature_image, x, y)
|
| 153 |
+
if output_file:
|
| 154 |
+
st.success("Signature added successfully")
|
| 155 |
+
with open(output_file, "rb") as f:
|
| 156 |
+
st.download_button("Download Signed PDF", f, file_name=output_file, mime="application/pdf")
|
| 157 |
+
os.remove(output_file)
|
| 158 |
+
else:
|
| 159 |
+
st.error("An Error occurred when creating the signed PDF")
|
| 160 |
+
else:
|
| 161 |
+
st.error("Please upload both a PDF file and a signature image")
|
| 162 |
+
|
| 163 |
+
os.remove(temp_pdf_path)
|
| 164 |
+
|
| 165 |
+
except Exception as e:
|
| 166 |
+
print(f"Error with pdf: {e}")
|
| 167 |
+
st.error(f"Could not open PDF file {e}")
|
| 168 |
+
os.remove(temp_pdf_path)
|
| 169 |
+
|
| 170 |
+
# Sidebar Navigation
|
| 171 |
+
st.sidebar.title("Tool Selector")
|
| 172 |
+
selection = st.sidebar.radio("Choose a tool:", ["PDF Combiner", "PDF Transcriber", "PDF Signer"])
|
| 173 |
+
|
| 174 |
+
# PDF Combiner with Preview and Reordering
|
| 175 |
+
if selection == "PDF Combiner":
|
| 176 |
+
st.title("PDF Combiner with Preview & Reordering")
|
| 177 |
+
st.write("Upload individual PDF pages, visualize them, reorder, and merge into a single PDF.")
|
| 178 |
+
|
| 179 |
+
uploaded_files = st.file_uploader("Upload PDF pages", type="pdf", accept_multiple_files=True)
|
| 180 |
+
|
| 181 |
+
if uploaded_files:
|
| 182 |
+
# Generate thumbnails and filenames for each uploaded PDF
|
| 183 |
+
thumbnails = []
|
| 184 |
+
filenames = []
|
| 185 |
+
|
| 186 |
+
for file in uploaded_files:
|
| 187 |
+
thumbnails.append(get_pdf_thumbnail(file))
|
| 188 |
+
filenames.append(file.name)
|
| 189 |
+
|
| 190 |
+
# Display thumbnails with filenames for reordering
|
| 191 |
+
st.write("**Drag and drop to reorder the PDFs:**")
|
| 192 |
+
reordered_filenames = sort_items(filenames)
|
| 193 |
+
|
| 194 |
+
# Map the filenames back to the corresponding files
|
| 195 |
+
reordered_files = [uploaded_files[filenames.index(name)] for name in reordered_filenames]
|
| 196 |
+
|
| 197 |
+
# Display the thumbnails in the new order
|
| 198 |
+
st.write("**Preview of selected order:**")
|
| 199 |
+
cols = st.columns(len(reordered_files))
|
| 200 |
+
for idx, file in enumerate(reordered_files):
|
| 201 |
+
with cols[idx]:
|
| 202 |
+
st.image(get_pdf_thumbnail(file), caption=file.name, use_container_width=True)
|
| 203 |
+
|
| 204 |
+
# Merge PDFs in the specified order
|
| 205 |
+
if st.button("Merge PDFs"):
|
| 206 |
+
output_file = merge_pdfs(reordered_files)
|
| 207 |
+
st.success("PDF pages combined successfully!")
|
| 208 |
+
with open(output_file, "rb") as f:
|
| 209 |
+
st.download_button("Download Combined PDF", f, file_name=output_file, mime="application/pdf")
|
| 210 |
+
os.remove(output_file)
|
| 211 |
+
|
| 212 |
+
# PDF Transcriber Tool
|
| 213 |
+
elif selection == "PDF Transcriber":
|
| 214 |
+
st.title("PDF Transcriber Tool")
|
| 215 |
+
st.write("Upload a scanned PDF to transcribe the text.")
|
| 216 |
+
if not client:
|
| 217 |
+
st.error("Google Cloud credentials are not set. Please configure the secret.")
|
| 218 |
+
uploaded_file = st.file_uploader("Upload a PDF", type=["pdf"])
|
| 219 |
+
if uploaded_file and st.button("Transcribe PDF"):
|
| 220 |
+
with st.spinner("Processing..."):
|
| 221 |
+
pdf_text = process_pdf(uploaded_file)
|
| 222 |
+
st.success("Text extraction complete!")
|
| 223 |
+
st.text_area("Extracted Text", pdf_text, height=400)
|
| 224 |
+
output_file_name = f"(T){os.path.splitext(uploaded_file.name)[0]}.txt"
|
| 225 |
+
st.download_button("Download Extracted Text", pdf_text, file_name=output_file_name)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
# PDF Signer Tool
|
| 229 |
+
elif selection == "PDF Signer":
|
| 230 |
+
st.title("PDF Signer")
|
| 231 |
+
st.write("Upload a PDF and place a signature on it by clicking the preview.")
|
| 232 |
+
|
| 233 |
+
pdf_file = st.file_uploader("Upload PDF", type=["pdf"])
|
| 234 |
+
signature_image = st.file_uploader("Upload Signature Image", type=["png", "jpg", "jpeg"])
|
| 235 |
+
if pdf_file and signature_image:
|
| 236 |
+
pdf_signer_ui(pdf_file, signature_image)
|