Spaces:
Build error
Build error
Commit
·
7b72076
1
Parent(s):
3bf9a69
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from docx import Document
|
| 3 |
+
import PyPDF2
|
| 4 |
+
import pdfplumber
|
| 5 |
+
import pytesseract
|
| 6 |
+
import difflib
|
| 7 |
+
|
| 8 |
+
def read_pdf(file):
|
| 9 |
+
try:
|
| 10 |
+
pdf_reader = PyPDF2.PdfFileReader(file)
|
| 11 |
+
total_pages = pdf_reader.numPages
|
| 12 |
+
text = []
|
| 13 |
+
for page_num in range(total_pages):
|
| 14 |
+
page = pdf_reader.getPage(page_num)
|
| 15 |
+
text.append(page.extract_text())
|
| 16 |
+
return "\n".join(text)
|
| 17 |
+
except:
|
| 18 |
+
st.warning('Failed to directly read PDF, trying OCR...')
|
| 19 |
+
try:
|
| 20 |
+
with pdfplumber.open(file) as pdf:
|
| 21 |
+
text = "\n".join([page.extract_text() for page in pdf.pages])
|
| 22 |
+
return text
|
| 23 |
+
except Exception as e:
|
| 24 |
+
st.error(f"Error in OCR: {str(e)}")
|
| 25 |
+
return None
|
| 26 |
+
|
| 27 |
+
def read_docx(file):
|
| 28 |
+
doc = Document(file)
|
| 29 |
+
return "\n".join([p.text for p in doc.paragraphs])
|
| 30 |
+
|
| 31 |
+
def compare_texts(text1, text2):
|
| 32 |
+
d = difflib.Differ()
|
| 33 |
+
diff = d.compare(text1.splitlines(), text2.splitlines())
|
| 34 |
+
return '\n'.join(diff)
|
| 35 |
+
|
| 36 |
+
st.title('PDF and DOCX Comparison Tool')
|
| 37 |
+
|
| 38 |
+
pdf_file = st.file_uploader('Upload a PDF file', type=['pdf'])
|
| 39 |
+
docx_file = st.file_uploader('Upload a DOCX file', type=['docx'])
|
| 40 |
+
|
| 41 |
+
if pdf_file and docx_file:
|
| 42 |
+
pdf_text = read_pdf(pdf_file)
|
| 43 |
+
docx_text = read_docx(docx_file)
|
| 44 |
+
|
| 45 |
+
if pdf_text and docx_text:
|
| 46 |
+
comparison_result = compare_texts(pdf_text, docx_text)
|
| 47 |
+
st.text(comparison_result)
|
| 48 |
+
else:
|
| 49 |
+
st.error('Failed to read text from one or both files.')
|