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
| 4 |
+
from typing import List, Dict, Any, Tuple
|
| 5 |
+
import language_tool_python
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
def extract_pdf_text(file) -> str:
|
| 9 |
+
"""Extracts full text from a PDF file using PyMuPDF."""
|
| 10 |
+
try:
|
| 11 |
+
# Open the PDF file
|
| 12 |
+
doc = fitz.open(stream=file.read(), filetype="pdf") if not isinstance(file, str) else fitz.open(file)
|
| 13 |
+
full_text = ""
|
| 14 |
+
for page_num, page in enumerate(doc, start=1):
|
| 15 |
+
text = page.get_text("text")
|
| 16 |
+
full_text += text + "\n"
|
| 17 |
+
print(f"Extracted text from page {page_num}: {len(text)} characters.")
|
| 18 |
+
doc.close()
|
| 19 |
+
print(f"Total extracted text length: {len(full_text)} characters.")
|
| 20 |
+
return full_text
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"Error extracting text from PDF: {e}")
|
| 23 |
+
return ""
|
| 24 |
+
|
| 25 |
+
def check_language_issues(full_text: str) -> Dict[str, Any]:
|
| 26 |
+
"""Check for language issues using LanguageTool."""
|
| 27 |
+
try:
|
| 28 |
+
language_tool = language_tool_python.LanguageTool('en-US')
|
| 29 |
+
matches = language_tool.check(full_text)
|
| 30 |
+
issues = []
|
| 31 |
+
for match in matches:
|
| 32 |
+
issues.append({
|
| 33 |
+
"message": match.message,
|
| 34 |
+
"context": match.context.strip(),
|
| 35 |
+
"suggestions": match.replacements[:3] if match.replacements else [],
|
| 36 |
+
"category": match.category,
|
| 37 |
+
"rule_id": match.ruleId,
|
| 38 |
+
"offset": match.offset,
|
| 39 |
+
"length": match.errorLength
|
| 40 |
+
})
|
| 41 |
+
print(f"Total language issues found: {len(issues)}")
|
| 42 |
+
return {
|
| 43 |
+
"total_issues": len(issues),
|
| 44 |
+
"issues": issues
|
| 45 |
+
}
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"Error checking language issues: {e}")
|
| 48 |
+
return {"error": str(e)}
|
| 49 |
+
|
| 50 |
+
def highlight_issues_in_pdf(file, language_matches: List[Dict[str, Any]]) -> bytes:
|
| 51 |
+
"""
|
| 52 |
+
Highlights language issues in the PDF and returns the annotated PDF as bytes.
|
| 53 |
+
This function maps LanguageTool matches to specific words in the PDF
|
| 54 |
+
and highlights those words.
|
| 55 |
+
"""
|
| 56 |
+
try:
|
| 57 |
+
# Open the PDF
|
| 58 |
+
doc = fitz.open(stream=file.read(), filetype="pdf") if not isinstance(file, str) else fitz.open(file)
|
| 59 |
+
print(f"Opened PDF with {len(doc)} pages.")
|
| 60 |
+
|
| 61 |
+
# Extract words with positions from each page
|
| 62 |
+
word_list = [] # List of tuples: (page_number, word, x0, y0, x1, y1)
|
| 63 |
+
for page_number in range(len(doc)):
|
| 64 |
+
page = doc[page_number]
|
| 65 |
+
words = page.get_text("words") # List of tuples: (x0, y0, x1, y1, "word", block_no, line_no, word_no)
|
| 66 |
+
for w in words:
|
| 67 |
+
word_text = w[4]
|
| 68 |
+
# **Fix:** Insert a space before '[' to ensure "globally [2]" instead of "globally[2]"
|
| 69 |
+
if '[' in word_text:
|
| 70 |
+
word_text = word_text.replace('[', ' [')
|
| 71 |
+
word_list.append((page_number, word_text, w[0], w[1], w[2], w[3]))
|
| 72 |
+
print(f"Total words extracted: {len(word_list)}")
|
| 73 |
+
|
| 74 |
+
# Concatenate all words to form the full text
|
| 75 |
+
concatenated_text = " ".join([w[1] for w in word_list])
|
| 76 |
+
print(f"Concatenated text length: {len(concatenated_text)} characters.")
|
| 77 |
+
|
| 78 |
+
# Iterate over each language issue
|
| 79 |
+
for idx, issue in enumerate(language_matches, start=1):
|
| 80 |
+
offset = issue["offset"]
|
| 81 |
+
length = issue["length"]
|
| 82 |
+
error_text = concatenated_text[offset:offset+length]
|
| 83 |
+
print(f"\nIssue {idx}: '{error_text}' at offset {offset} with length {length}")
|
| 84 |
+
|
| 85 |
+
# Find the words that fall within the error span
|
| 86 |
+
current_pos = 0
|
| 87 |
+
target_words = []
|
| 88 |
+
for word in word_list:
|
| 89 |
+
word_text = word[1]
|
| 90 |
+
word_length = len(word_text) + 1 # +1 for the space
|
| 91 |
+
|
| 92 |
+
if current_pos + word_length > offset and current_pos < offset + length:
|
| 93 |
+
target_words.append(word)
|
| 94 |
+
current_pos += word_length
|
| 95 |
+
|
| 96 |
+
if not target_words:
|
| 97 |
+
print("No matching words found for this issue.")
|
| 98 |
+
continue
|
| 99 |
+
|
| 100 |
+
# Add highlight annotations to the target words
|
| 101 |
+
for target in target_words:
|
| 102 |
+
page_num, word_text, x0, y0, x1, y1 = target
|
| 103 |
+
page = doc[page_num]
|
| 104 |
+
# Define a rectangle around the word with some padding
|
| 105 |
+
rect = fitz.Rect(x0 - 1, y0 - 1, x1 + 1, y1 + 1)
|
| 106 |
+
# Add a highlight annotation
|
| 107 |
+
highlight = page.add_highlight_annot(rect)
|
| 108 |
+
highlight.set_colors(stroke=(1, 1, 0)) # Yellow color
|
| 109 |
+
highlight.update()
|
| 110 |
+
print(f"Highlighted '{word_text}' on page {page_num + 1} at position ({x0}, {y0}, {x1}, {y1})")
|
| 111 |
+
|
| 112 |
+
# Save annotated PDF to bytes
|
| 113 |
+
byte_stream = io.BytesIO()
|
| 114 |
+
doc.save(byte_stream)
|
| 115 |
+
annotated_pdf_bytes = byte_stream.getvalue()
|
| 116 |
+
doc.close()
|
| 117 |
+
|
| 118 |
+
# Save annotated PDF locally for verification
|
| 119 |
+
with open("annotated_temp.pdf", "wb") as f:
|
| 120 |
+
f.write(annotated_pdf_bytes)
|
| 121 |
+
print("Annotated PDF saved as 'annotated_temp.pdf' for manual verification.")
|
| 122 |
+
|
| 123 |
+
return annotated_pdf_bytes
|
| 124 |
+
except Exception as e:
|
| 125 |
+
print(f"Error in highlighting PDF: {e}")
|
| 126 |
+
return b""
|
| 127 |
+
|
| 128 |
+
def analyze_pdf(file) -> Tuple[Dict[str, Any], bytes]:
|
| 129 |
+
"""Analyzes the PDF for language issues and returns results and annotated PDF."""
|
| 130 |
+
try:
|
| 131 |
+
# Reset file pointer before reading
|
| 132 |
+
file.seek(0)
|
| 133 |
+
full_text = extract_pdf_text(file)
|
| 134 |
+
if not full_text:
|
| 135 |
+
return {"error": "Failed to extract text from PDF."}, None
|
| 136 |
+
|
| 137 |
+
language_issues = check_language_issues(full_text)
|
| 138 |
+
if "error" in language_issues:
|
| 139 |
+
return language_issues, None
|
| 140 |
+
|
| 141 |
+
issues = language_issues.get("issues", [])
|
| 142 |
+
# Reset file pointer before highlighting
|
| 143 |
+
file.seek(0)
|
| 144 |
+
annotated_pdf = highlight_issues_in_pdf(file, issues) if issues else None
|
| 145 |
+
return language_issues, annotated_pdf
|
| 146 |
+
except Exception as e:
|
| 147 |
+
return {"error": str(e)}, None
|