Spaces:
Sleeping
Sleeping
import streamlit as st | |
from docx import Document | |
import PyPDF2 | |
import pdfplumber | |
import pytesseract | |
import difflib | |
def read_pdf(file): | |
try: | |
pdf_reader = PyPDF2.PdfFileReader(file) | |
total_pages = pdf_reader.numPages | |
text = [] | |
for page_num in range(total_pages): | |
page = pdf_reader.getPage(page_num) | |
text.append(page.extract_text()) | |
return "\n".join(text) | |
except: | |
st.warning('Failed to directly read PDF, trying OCR...') | |
try: | |
with pdfplumber.open(file) as pdf: | |
text = "\n".join([page.extract_text() for page in pdf.pages]) | |
return text | |
except Exception as e: | |
st.error(f"Error in OCR: {str(e)}") | |
return None | |
def read_docx(file): | |
doc = Document(file) | |
return "\n".join([p.text for p in doc.paragraphs]) | |
def compare_texts(text1, text2): | |
d = difflib.Differ() | |
diff = d.compare(text1.splitlines(), text2.splitlines()) | |
return '\n'.join(diff) | |
st.title('PDF and DOCX Comparison Tool') | |
pdf_file = st.file_uploader('Upload a PDF file', type=['pdf']) | |
docx_file = st.file_uploader('Upload a DOCX file', type=['docx']) | |
if pdf_file and docx_file: | |
pdf_text = read_pdf(pdf_file) | |
docx_text = read_docx(docx_file) | |
if pdf_text and docx_text: | |
comparison_result = compare_texts(pdf_text, docx_text) | |
st.text(comparison_result) | |
else: | |
st.error('Failed to read text from one or both files.') |