samyak152002 commited on
Commit
d9a6b52
1 Parent(s): 9508bb0

Update annotations.py

Browse files
Files changed (1) hide show
  1. annotations.py +8 -16
annotations.py CHANGED
@@ -13,9 +13,7 @@ def extract_pdf_text(file) -> str:
13
  for page in doc:
14
  text = page.get_text("text")
15
  full_text += text + "\n"
16
- print(f"Extracted text from page {page.number + 1}: {len(text)} characters")
17
  doc.close()
18
- print(f"Total extracted text length: {len(full_text)} characters")
19
  return full_text
20
  except Exception as e:
21
  print(f"Error extracting text from PDF: {e}")
@@ -37,7 +35,6 @@ def check_language_issues(full_text: str) -> Dict[str, Any]:
37
  "offset": match.offset,
38
  "length": match.errorLength
39
  })
40
- print(f"Total language issues found: {len(issues)}")
41
  return {
42
  "total_issues": len(issues),
43
  "issues": issues
@@ -55,7 +52,6 @@ def highlight_issues_in_pdf(file, language_matches: List[Dict[str, Any]]) -> byt
55
  try:
56
  # Open the PDF
57
  doc = fitz.open(stream=file.read(), filetype="pdf") if not isinstance(file, str) else fitz.open(file)
58
- print(f"Opened PDF with {len(doc)} pages.")
59
 
60
  # Extract words with positions from each page
61
  word_list = [] # List of tuples: (page_number, word, x0, y0, x1, y1)
@@ -65,19 +61,16 @@ def highlight_issues_in_pdf(file, language_matches: List[Dict[str, Any]]) -> byt
65
  for w in words:
66
  word_text = w[4]
67
  word_list.append((page_number, word_text, w[0], w[1], w[2], w[3]))
68
- print(f"Page {page_number + 1}: Extracted {len(words)} words.")
69
 
70
  # Concatenate all words to form the full text
71
  concatenated_text = " ".join([w[1] for w in word_list])
72
- print(f"Concatenated text length: {len(concatenated_text)} characters.")
73
 
74
  # Iterate over each language issue
75
- for idx, issue in enumerate(language_matches, 1):
76
  offset = issue["offset"]
77
  length = issue["length"]
78
  error_text = concatenated_text[offset:offset+length]
79
- print(f"\nIssue {idx}: '{error_text}' at offset {offset} with length {length}")
80
-
81
  # Find the words that fall within the error span
82
  current_pos = 0
83
  target_words = []
@@ -89,10 +82,6 @@ def highlight_issues_in_pdf(file, language_matches: List[Dict[str, Any]]) -> byt
89
  target_words.append(word)
90
  current_pos += word_length
91
 
92
- if not target_words:
93
- print("No matching words found for this issue.")
94
- continue
95
-
96
  # Add highlight annotations to the target words
97
  for target in target_words:
98
  page_num, word_text, x0, y0, x1, y1 = target
@@ -103,14 +92,18 @@ def highlight_issues_in_pdf(file, language_matches: List[Dict[str, Any]]) -> byt
103
  highlight = page.add_highlight_annot(rect)
104
  highlight.set_colors(stroke=(1, 1, 0)) # Yellow color
105
  highlight.update()
106
- print(f"Highlighted '{word_text}' on page {page_num + 1} at position ({x0}, {y0}, {x1}, {y1})")
107
 
108
  # Save annotated PDF to bytes
109
  byte_stream = io.BytesIO()
110
  doc.save(byte_stream)
111
  annotated_pdf_bytes = byte_stream.getvalue()
112
  doc.close()
113
- print("Annotated PDF successfully created.")
 
 
 
 
 
114
  return annotated_pdf_bytes
115
  except Exception as e:
116
  print(f"Error in highlighting PDF: {e}")
@@ -131,5 +124,4 @@ def analyze_pdf(file) -> Tuple[Dict[str, Any], bytes]:
131
  annotated_pdf = highlight_issues_in_pdf(file, issues) if issues else None
132
  return language_issues, annotated_pdf
133
  except Exception as e:
134
- print(f"Error in analyze_pdf: {e}")
135
  return {"error": str(e)}, None
 
13
  for page in doc:
14
  text = page.get_text("text")
15
  full_text += text + "\n"
 
16
  doc.close()
 
17
  return full_text
18
  except Exception as e:
19
  print(f"Error extracting text from PDF: {e}")
 
35
  "offset": match.offset,
36
  "length": match.errorLength
37
  })
 
38
  return {
39
  "total_issues": len(issues),
40
  "issues": issues
 
52
  try:
53
  # Open the PDF
54
  doc = fitz.open(stream=file.read(), filetype="pdf") if not isinstance(file, str) else fitz.open(file)
 
55
 
56
  # Extract words with positions from each page
57
  word_list = [] # List of tuples: (page_number, word, x0, y0, x1, y1)
 
61
  for w in words:
62
  word_text = w[4]
63
  word_list.append((page_number, word_text, w[0], w[1], w[2], w[3]))
 
64
 
65
  # Concatenate all words to form the full text
66
  concatenated_text = " ".join([w[1] for w in word_list])
 
67
 
68
  # Iterate over each language issue
69
+ for issue in language_matches:
70
  offset = issue["offset"]
71
  length = issue["length"]
72
  error_text = concatenated_text[offset:offset+length]
73
+
 
74
  # Find the words that fall within the error span
75
  current_pos = 0
76
  target_words = []
 
82
  target_words.append(word)
83
  current_pos += word_length
84
 
 
 
 
 
85
  # Add highlight annotations to the target words
86
  for target in target_words:
87
  page_num, word_text, x0, y0, x1, y1 = target
 
92
  highlight = page.add_highlight_annot(rect)
93
  highlight.set_colors(stroke=(1, 1, 0)) # Yellow color
94
  highlight.update()
 
95
 
96
  # Save annotated PDF to bytes
97
  byte_stream = io.BytesIO()
98
  doc.save(byte_stream)
99
  annotated_pdf_bytes = byte_stream.getvalue()
100
  doc.close()
101
+
102
+ # Save annotated PDF locally for verification
103
+ with open("annotated_temp.pdf", "wb") as f:
104
+ f.write(annotated_pdf_bytes)
105
+ print("Annotated PDF saved as 'annotated_temp.pdf' for manual verification.")
106
+
107
  return annotated_pdf_bytes
108
  except Exception as e:
109
  print(f"Error in highlighting PDF: {e}")
 
124
  annotated_pdf = highlight_issues_in_pdf(file, issues) if issues else None
125
  return language_issues, annotated_pdf
126
  except Exception as e:
 
127
  return {"error": str(e)}, None