CoolFace
Apppublic

Abhilashvj/compare-docs

sourceHugging Faceapache-2.0updated 3y agoView on Hugging Face
0likes
app.py69 linesDownload Raw Back to root
1import streamlit as st2from docx import Document3import PyPDF24import pdfplumber5import pytesseract6import difflib7import base648 9def read_pdf(file):10    try:11        pdf_reader = PyPDF2.PdfFileReader(file)12        total_pages = pdf_reader.numPages13        text = []14        for page_num in range(total_pages):15            page = pdf_reader.getPage(page_num)16            text.append(page.extract_text())17        return "\n".join(text)18    except:19        st.warning('Failed to directly read PDF, trying OCR...')20        try:21            with pdfplumber.open(file) as pdf:22                text = "\n".join([page.extract_text() for page in pdf.pages])23            return text24        except Exception as e:25            st.error(f"Error in OCR: {str(e)}")26            return None27 28def read_docx(file):29    doc = Document(file)30    return "\n".join([p.text for p in doc.paragraphs])31 32def compare_texts(text1, text2):33    d = difflib.Differ()34    diff = list(d.compare(text1.splitlines(), text2.splitlines()))35    36    result = []37    page_no = 138    for line in diff:39        if 'Page' in line:  # if a new page starts40            page_no += 141        elif line.startswith('+ '):  # text present in text2 but not in text142            result.append(f'Additional text detected on page {page_no}')43        elif line.startswith('- '):  # text present in text1 but not in text244            result.append(f'Less text detected on page {page_no}')45    46    return "\n".join(set(result))  # using set to remove duplicates47 48st.title('PDF and DOCX Comparison Tool')49 50pdf_file = st.file_uploader('Upload a PDF file', type=['pdf'])51docx_file = st.file_uploader('Upload a DOCX file', type=['docx'])52 53if pdf_file and docx_file:54    pdf_text = read_pdf(pdf_file)55    docx_text = read_docx(docx_file)56 57    b64_pdf = base64.b64encode(pdf_file.read()).decode()  # some strings <-> bytes conversions necessary here58    href = f'<a href="data:file/pdf;base64,{b64_pdf}" download="file.pdf">Download PDF File</a> (right-click and save as &lt;some_name&gt;.pdf)'59    st.markdown(href, unsafe_allow_html=True)60 61    st.markdown(f'<iframe src="data:application/pdf;base64,{b64_pdf}" width="50%" height="600px" type="application/pdf"></iframe>', unsafe_allow_html=True)62    st.markdown("### DOCX Content:")63    st.text(docx_text)64 65    if pdf_text and docx_text:66        comparison_result = compare_texts(pdf_text, docx_text)67        st.text(comparison_result)68    else:69        st.error('Failed to read text from one or both files.')