samyak152002 commited on
Commit
4b93adb
1 Parent(s): 706a020

Create annotations.py

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