Spaces:
Sleeping
Sleeping
File size: 9,179 Bytes
c94dde8 8e157b2 c94dde8 8e157b2 c94dde8 8e157b2 c94dde8 45b16c9 0e4f7b9 c94dde8 7f81b6d c94dde8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 |
# Import the required libraries
import gradio as gr
import cv2 # OpenCV, to read and manipulate images
import easyocr # EasyOCR, for OCR
import torch # PyTorch, for deep learning
import pymupdf # PDF manipulation
from transformers import pipeline # Hugging Face Transformers, for NER
import os # OS, for file operations
from glob import glob # Glob, to get file paths
##########################################################################################################
# Initiate the models
# Easyocr model
print("Initiating easyocr")
reader = easyocr.Reader(['en'], gpu=torch.cuda.is_available(), model_storage_directory='.')
# Use gpu if available
print("Using gpu if available")
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
print(f"Using device: {device}")
# Ner model
print("Initiating nlp pipeline")
nlp = pipeline("token-classification", model="dslim/distilbert-NER", device=device)
##########################################################################################################
## Functions
# Define img_format
img_format = "png"
# Convert pdf to set of images
def convert_to_images(pdf_file_path):
# Create a directory to store pdf images
pdf_images_dir = f'{pdf_file_path}_images'
os.makedirs(pdf_images_dir, exist_ok=True)
# DPI
dpi = 150
# Convert the PDF to images
print("Converting PDF to images...")
doc = pymupdf.open(pdf_file_path) # open document
for page in doc: # iterate through the pages
pix = page.get_pixmap(dpi=dpi) # render page to an image
pix.save(f"{pdf_images_dir}/page-{page.number}.{img_format}") # store image as a PNG
# Return the directory with the images
return pdf_images_dir
# Do the redaction
def redact_image(pdf_image_path, redaction_score_threshold):
# Loop through the images
print("Redacting sensitive information...")
print(f"Processing {pdf_image_path}...")
# Read the image
cv_image = cv2.imread(pdf_image_path)
# Read the text from the image
result = reader.readtext(cv_image, height_ths=0, width_ths=0, x_ths=0, y_ths=0)
# Get the text from the result
text = ' '.join([text for (bbox, text, prob) in result])
# Perform NER on the text
ner_results = nlp(text)
# Draw bounding boxes
for ((bbox, text, prob),ner_result) in zip(result, ner_results):
# Get the coordinates of the bounding box
(top_left, top_right, bottom_right, bottom_left) = bbox
top_left = tuple(map(int, top_left))
bottom_right = tuple(map(int, bottom_right))
# Calculate the centers of the top and bottom of the bounding box
# center_top = (int((top_left[0] + top_right[0]) / 2), int((top_left[1] + top_right[1]) / 2))
# center_bottom = (int((bottom_left[0] + bottom_right[0]) / 2), int((bottom_left[1] + bottom_right[1]) / 2))
# If the NER result is not empty, and the score is high
if len(ner_result) > 0 and ner_result['score'] > redaction_score_threshold:
# Get the entity and score
# entity = ner_result[0]['entity']
# score = str(ner_result[0]['score'])
# Apply a irreversible redaction
cv2.rectangle(cv_image, top_left, bottom_right, (0, 0, 0), -1)
# else:
# entity = 'O'
# score = '0'
# # Draw the bounding box
# cv2.rectangle(cv_image, top_left, bottom_right, (0, 255, 0), 1)
# # Draw the entity and score
# cv2.putText(cv_image, entity, center_top, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# cv2.putText(cv_image, score, center_bottom, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# Save the redacted image
print(f"Saving redacted {pdf_image_path}...")
redacted_image_path = pdf_image_path.replace(f'.{img_format}', f'_redacted.{img_format}')
# Save the redacted image in png format
cv2.imwrite(redacted_image_path, cv_image)
return redacted_image_path
# Convert the set of redacted images to a pdf
def stich_images_to_pdf(redacted_image_files, input_pdf_path):
# Sort the redacted images
redacted_image_files.sort()
# Convert the redacted images to a single PDF
print("Converting redacted images to PDF...")
redacted_pdf_path = input_pdf_path.replace('.pdf', '_redacted.pdf')
doc = pymupdf.open()
for redacted_image_file in redacted_image_files:
img = pymupdf.open(redacted_image_file) # open pic as document
rect = img[0].rect # pic dimension
pdfbytes = img.convert_to_pdf() # make a PDF stream
img.close() # no longer needed
imgPDF = pymupdf.open("pdf", pdfbytes) # open stream as PDF
page = doc.new_page(width = rect.width, # new page with ...
height = rect.height) # pic dimension
page.show_pdf_page(rect, imgPDF, 0) # image fills the page
doc.save(redacted_pdf_path)
# print(f"PDF saved as {redacted_pdf_path}")
return redacted_pdf_path
def cleanup(redacted_image_files, pdf_images, pdf_images_dir, original_pdf):
# Remove the directory with the images
print("Cleaning up...")
# Remove the redacted images
for file in redacted_image_files:
os.remove(file)
# Remove the pdf images
for file in pdf_images:
os.remove(file)
# Remove the pdf images directory
os.rmdir(pdf_images_dir)
# Remove original pdf
os.remove(original_pdf)
return None
# Func to control ui
def predict(input_pdf_path, sensitivity):
print("Setting threshold")
# Convert sensitivity to threshold
redaction_score_threshold = (100-sensitivity)/100
# Convert the PDF to images
print("Converting pdf to images")
pdf_images_dir = convert_to_images(input_pdf_path)
# Get the file paths of the images
print("Gathering converted images")
pdf_images = glob(f'{pdf_images_dir}/*.{img_format}', recursive=True)
pdf_images.sort()
# Redact images
print("Redacting images")
redacted_image_files = []
for pdf_image in pdf_images:
redacted_image_files.append(redact_image(pdf_image, redaction_score_threshold))
# Convert the redacted images to a single PDF
print("Stitching images to pdf")
redacted_pdf_path = stich_images_to_pdf(redacted_image_files, input_pdf_path)
print("Cleaning up")
cleanup(redacted_image_files, pdf_images, pdf_images_dir, input_pdf_path)
return redacted_pdf_path
##########################################################################################################
contact_text = """
# Contact Information
π€ [Mitanshu Sukhwani](https://www.linkedin.com/in/mitanshusukhwani/)
βοΈ mitanshu.sukhwani@gmail.com
π [mitanshu7](https://github.com/mitanshu7)
"""
##########################################################################################################
# Gradio interface
with gr.Blocks(theme=gr.themes.Soft()) as demo:
# Title and description
gr.Markdown("# RedactNLP: Redact your PDF!")
gr.Markdown("## How redaction happens:")
gr.Markdown("""
1. The PDF pages are converted to images using **[PyMuPDF](https://github.com/pymupdf/PyMuPDF)**.
2. **[EasyOCR](https://github.com/JaidedAI/EasyOCR)** is run on the converted images to extract text.
3. **[dslim/distilbert-NER](https://huggingface.co/dslim/distilbert-NER)** model does the token classification.
4. Non-recoverable mask is applied to identified elements using **[OpenCV](https://github.com/opencv/opencv)**.
5. The masked images are converted back to a PDF again using **[PyMuPDF](https://github.com/pymupdf/PyMuPDF)**.
""")
gr.Markdown("*Note: If you already have a ML setup, it is preferable that you download the [github repo](https://github.com/mitanshu7/RedactNLP) and use it offline. It offers better privacy and can use GPU for (much) faster computations while utilising a better model like **[FacebookAI/xlm-roberta-large-finetuned-conll03-english](https://huggingface.co/FacebookAI/xlm-roberta-large-finetuned-conll03-english)** or **[blaze999/Medical-NER](https://huggingface.co/blaze999/Medical-NER)***")
# Input Section
pdf_file_input = gr.File(file_count='single', file_types=['pdf'], label='Upload PDF', show_label=True, interactive=True)
# Slider for results count
slider_input = gr.Slider(
minimum=0, maximum=100, value=80, step=1,
label="Sensitivity to remove elements. Higher is more sensitive, hence will redact aggresively."
)
# Submission Button
submit_btn = gr.Button("Redact")
# Output section
output = gr.File(file_count='single', file_types=['pdf'], label='Download redacted PDF', show_label=True, interactive=False)
# Attribution
gr.Markdown(contact_text)
# Link button click to the prediction function
submit_btn.click(predict, [pdf_file_input, slider_input], output)
################################################################################
if __name__ == "__main__":
demo.launch()
|