|
import os |
|
from PIL import Image, ImageOps, ImageChops |
|
import io |
|
import fitz |
|
from docx import Document |
|
from rembg import remove |
|
import gradio as gr |
|
import os |
|
|
|
|
|
os.makedirs("static", exist_ok=True) |
|
def trim_whitespace(image): |
|
gray_image = ImageOps.grayscale(image) |
|
inverted_image = ImageChops.invert(gray_image) |
|
bbox = inverted_image.getbbox() |
|
trimmed_image = image.crop(bbox) |
|
return trimmed_image |
|
|
|
def convert_pdf_to_images(pdf_path, zoom=2): |
|
pdf_document = fitz.open(pdf_path) |
|
images = [] |
|
for page_num in range(len(pdf_document)): |
|
page = pdf_document.load_page(page_num) |
|
matrix = fitz.Matrix(zoom, zoom) |
|
pix = page.get_pixmap(matrix=matrix) |
|
image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) |
|
trimmed_image = trim_whitespace(image) |
|
images.append(trimmed_image) |
|
return images |
|
|
|
def convert_docx_to_images(docx_path): |
|
document = Document(docx_path) |
|
images = [] |
|
for image_shape in document.inline_shapes: |
|
image_stream = image_shape.image.blob |
|
image = Image.open(io.BytesIO(image_stream)) |
|
images.append(image) |
|
return images |
|
|
|
def remove_background_from_image(image): |
|
return remove(image) |
|
|
|
|
|
|
|
|
|
|
|
def process_file(input_file): |
|
file_extension = os.path.splitext(input_file.name)[1].lower() |
|
|
|
if file_extension in ['.png', '.jpeg', '.jpg', '.bmp', '.gif']: |
|
image = Image.open(input_file) |
|
image = image.convert('RGB') |
|
output_image = remove_background_from_image(image) |
|
return output_image |
|
elif file_extension == '.pdf': |
|
images = convert_pdf_to_images(input_file.name) |
|
return [remove_background_from_image(image) for image in images] |
|
elif file_extension in ['.docx', '.doc']: |
|
images = convert_docx_to_images(input_file.name) |
|
return [remove_background_from_image(image) for image in images] |
|
else: |
|
return "File format not supported." |
|
|
|
def gradio_interface(input_file): |
|
return process_file(input_file) |
|
|
|
iface = gr.Interface( |
|
fn=gradio_interface, |
|
inputs=gr.File(label="Upload Word, PDF, or Image"), |
|
outputs=gr.outputs.Image(type="file", label="Processed Image(s)"), |
|
title="Document to Image Converter with Background Removal" |
|
) |
|
|
|
if __name__ == "__main__": |
|
iface.launch() |