File size: 4,011 Bytes
1575c76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7ef481
 
 
1575c76
 
 
 
a7ef481
1575c76
 
 
 
 
 
a7ef481
1575c76
 
 
 
 
 
 
 
 
a7ef481
1575c76
a7ef481
1575c76
 
 
 
 
a7ef481
 
1575c76
 
 
 
 
 
 
a7ef481
1575c76
 
 
 
 
a7ef481
1575c76
 
 
 
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
import gradio as gr
import fitz  # PyMuPDF
import cv2
from pdf2image import convert_from_path
import numpy as np
import os
from fpdf import FPDF

# Convert PDFs to images
def convert_pdf_to_images(pdf_path, dpi=300):
    images = convert_from_path(pdf_path, dpi=dpi, poppler_path="/usr/bin")
    return [cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) for image in images]

# Align images
def align_images(img1, img2):
    gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    orb = cv2.ORB_create()
    kp1, des1 = orb.detectAndCompute(gray1, None)
    kp2, des2 = orb.detectAndCompute(gray2, None)
    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
    matches = bf.match(des1, des2)
    matches = sorted(matches, key=lambda x: x.distance)
    src_pts = np.float32([kp1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
    dst_pts = np.float32([kp2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
    matrix, _ = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

    # Validate if alignment is good enough
    if matrix is None or len(matches) < 10:  # Check if sufficient matches exist
        raise ValueError("Alignment failed. Insufficient matches between images.")

    aligned_img = cv2.warpPerspective(img2, matrix, (img1.shape[1], img1.shape[0]))
    return aligned_img

# Compare visual changes
def compare_visual_changes(orig_img, edit_img):
    diff = cv2.absdiff(orig_img, edit_img)
    gray_diff = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)

    # Apply Gaussian blur to reduce noise
    blurred_diff = cv2.GaussianBlur(gray_diff, (5, 5), 0)

    # Apply thresholding
    _, thresh = cv2.threshold(blurred_diff, 70, 255, cv2.THRESH_BINARY)

    # Morphological operations to clean noise
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    cleaned = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

    contours, _ = cv2.findContours(cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    overlay = edit_img.copy()

    for cnt in contours:
        if cv2.contourArea(cnt) > 100:  # Filter out small regions
            x, y, w, h = cv2.boundingRect(cnt)
            cv2.rectangle(overlay, (x, y), (x + w, y + h), (0, 0, 255), 2)  # Red bounding box

    return overlay

# Generate visual comparison report
def generate_visual_report(images, output_path):
    pdf = FPDF()
    for img in images:
        temp_path = "temp_image.png"
        cv2.imwrite(temp_path, img)
        pdf.add_page()
        pdf.image(temp_path, x=10, y=10, w=190)
        os.remove(temp_path)

    pdf.output(output_path)
    return output_path

# Perform only visual comparison
def generate_visual_comparison(original_pdf, edited_pdf):
    original_images = convert_pdf_to_images(original_pdf)
    edited_images = convert_pdf_to_images(edited_pdf)

    visual_combined_images = []
    for orig_img, edit_img in zip(original_images, edited_images):
        aligned_img = align_images(orig_img, edit_img)
        highlighted_img = compare_visual_changes(orig_img, aligned_img)
        visual_combined_images.append(np.hstack((orig_img, highlighted_img)))

    # Generate visual changes report
    visual_report_path = generate_visual_report(
        visual_combined_images, "outputs/visual_changes.pdf"
    )

    return visual_report_path

# Gradio interface function
def pdf_visual_comparison(original_pdf, edited_pdf):
    visual_path = generate_visual_comparison(original_pdf.name, edited_pdf.name)
    return visual_path

# Gradio interface
interface = gr.Interface(
    fn=pdf_visual_comparison,
    inputs=[
        gr.File(label="Upload Original PDF", file_types=[".pdf"]),
        gr.File(label="Upload Edited PDF", file_types=[".pdf"])
    ],
    outputs=[
        gr.File(label="Download Visual Changes Report")
    ],
    title="PDF Visual Comparison Tool",
    description="Upload two PDFs: the original and the edited version. The tool generates a visual changes report."
)

if __name__ == "__main__":
    interface.launch()