File size: 12,578 Bytes
5d43a8b 7d5ea10 5d295a5 7d5ea10 352ad92 7d5ea10 a0113c0 85ac02c ee101e3 a0113c0 7d5ea10 352ad92 7d5ea10 352ad92 7d5ea10 a0113c0 7d5ea10 352ad92 7d5ea10 352ad92 7d5ea10 a0113c0 7d5ea10 352ad92 a0113c0 7d5ea10 5d295a5 a0113c0 5d295a5 a0113c0 5d295a5 a0113c0 5d295a5 a0113c0 5d295a5 5d43a8b 5d295a5 a0113c0 5d43a8b a0113c0 5d295a5 5d43a8b 5d295a5 a0113c0 5d295a5 a0113c0 cbaab47 a0113c0 7d5ea10 a0113c0 7d5ea10 5d295a5 7d5ea10 352ad92 5d295a5 352ad92 7d5ea10 352ad92 a0113c0 352ad92 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
# import os
# import logging
# import fitz # PyMuPDF
# import numpy as np
# from PIL import Image
# import cv2
# import re
# # OCR
# from paddleocr import PaddleOCR
# # Optional Mistral OCR
# try:
# from doctr.models import ocr_predictor
# from doctr.io import DocumentFile
# mistral_ocr = ocr_predictor(pretrained=True)
# use_mistral_ocr = True
# except ImportError:
# mistral_ocr = None
# use_mistral_ocr = False
# # Environment paths
# os.environ.setdefault("HOME", "/app")
# os.environ.setdefault("PADDLEOCR_HOME", "/app/.paddleocr")
# # Logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)
# # PaddleOCR
# ocr = PaddleOCR(use_angle_cls=True, lang='en')
# def clean_text(text):
# return re.sub(r'\s+', ' ', text).strip()
# def auto_rotate_image(pil_img):
# """Auto-rotate PIL image safely."""
# if pil_img.mode != "RGB":
# pil_img = pil_img.convert("RGB")
# img_cv = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2GRAY)
# coords = np.column_stack(np.where(img_cv > 0))
# if coords.size == 0:
# return pil_img # blank page
# angle = cv2.minAreaRect(coords)[-1]
# angle = -(90 + angle) if angle < -45 else -angle
# (h, w) = img_cv.shape[:2]
# M = cv2.getRotationMatrix2D((w // 2, h // 2), angle, 1.0)
# rotated = cv2.warpAffine(img_cv, M, (w, h),
# flags=cv2.INTER_CUBIC,
# borderMode=cv2.BORDER_REPLICATE)
# return Image.fromarray(cv2.cvtColor(rotated, cv2.COLOR_GRAY2RGB))
# def extract_images_with_fitz(pdf_path, start_page=1, end_page=None):
# images = []
# try:
# doc = fitz.open(pdf_path)
# total_pages = len(doc)
# end = min(end_page or total_pages, total_pages)
# for i in range(start_page - 1, end):
# try:
# page = doc[i]
# pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
# mode = "RGBA" if pix.alpha else "RGB"
# img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
# images.append((i + 1, img))
# except Exception as e:
# logger.error(f"Error rendering page {i + 1}: {e}")
# doc.close()
# except Exception as e:
# logger.error(f"Failed to open PDF file: {e}")
# return images
# def extract_text_from_file(file, start_page=None, end_page=None, filename=None):
# ext = os.path.splitext(filename or "")[-1].lower()
# result = []
# if ext == ".pdf":
# try:
# doc = fitz.open(file.name)
# except Exception as e:
# logger.error(f"Cannot open PDF {filename}: {e}")
# return "[Error opening PDF]"
# images = extract_images_with_fitz(file.name, start_page or 1, end_page)
# total_pages = len(doc)
# start = max(start_page or 1, 1)
# end = min(end_page or total_pages, total_pages)
# for i, page in enumerate(doc):
# page_num = i + 1
# if not (start <= page_num <= end):
# continue
# text = page.get_text()
# if text.strip():
# result.append(f"Page {page_num} (Extracted):\n{clean_text(text)}")
# else:
# if i < len(images):
# try:
# img = auto_rotate_image(images[i][1])
# img_np = np.array(img)
# ocr_text = ""
# # PaddleOCR
# try:
# ocr_result = ocr.ocr(img_np, cls=True)
# ocr_text = "\n".join([line[1][0] for line in ocr_result[0]]) if ocr_result else ""
# except Exception as e:
# logger.warning(f"PaddleOCR failed on page {page_num}: {e}")
# # Mistral OCR fallback
# if not ocr_text and use_mistral_ocr:
# try:
# doc_img = DocumentFile.from_images(img)
# ocr_text = mistral_ocr(doc_img).render()
# except Exception as e:
# logger.warning(f"Mistral OCR failed on page {page_num}: {e}")
# ocr_text = "[OCR Error]"
# result.append(f"Page {page_num} (OCR):\n{clean_text(ocr_text) or '[No OCR Text]'}")
# except Exception as e:
# logger.error(f"OCR processing failed for page {page_num}: {e}")
# result.append(f"Page {page_num}: [OCR Error]")
# else:
# result.append(f"Page {page_num}: [No text or image]")
# doc.close()
# return "\n\n".join(result)
# elif ext == ".docx":
# from docx.api import Document
# doc = Document(file.name)
# paras = [p.text for p in doc.paragraphs if p.text.strip()]
# page_texts = []
# page_size = 500
# for i in range(0, len(paras), page_size):
# page_texts.append("\n".join(paras[i:i + page_size]))
# selected_pages = page_texts
# if start_page and end_page:
# selected_pages = page_texts[start_page - 1:end_page]
# return clean_text("\n\n".join(selected_pages))
# elif ext == ".csv":
# import pandas as pd
# try:
# return pd.read_csv(file.name).to_string(index=False)
# except Exception as e:
# logger.error(f"CSV read error: {e}")
# return "[CSV Read Error]"
# elif ext in [".xls", ".xlsx"]:
# import pandas as pd
# try:
# xl = pd.ExcelFile(file.name)
# return "\n\n".join([
# f"Sheet: {s}\n{xl.parse(s).to_string(index=False)}"
# for s in xl.sheet_names
# ])
# except Exception as e:
# logger.error(f"Excel read error: {e}")
# return "[Excel Read Error]"
# else:
# return "[Unsupported file type]"
import os
import logging
import fitz # PyMuPDF
import numpy as np
from PIL import Image
import cv2
import re
# OCR
from paddleocr import PaddleOCR
# Optional Mistral OCR
try:
from doctr.models import ocr_predictor
from doctr.io import DocumentFile
mistral_ocr = ocr_predictor(pretrained=True)
use_mistral_ocr = True
except ImportError:
mistral_ocr = None
use_mistral_ocr = False
# Environment paths
os.environ.setdefault("HOME", "/app")
os.environ.setdefault("PADDLEOCR_HOME", "/app/.paddleocr")
# Logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize PaddleOCR correctly (no cls param at call time)
ocr = PaddleOCR(use_angle_cls=True, lang='en')
def clean_text(text: str) -> str:
return re.sub(r'\s+', ' ', text).strip()
def auto_rotate_image(pil_img):
"""Auto-rotate PIL image safely."""
if pil_img.mode != "RGB":
pil_img = pil_img.convert("RGB")
img_cv = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2GRAY)
coords = np.column_stack(np.where(img_cv > 0))
if coords.size == 0:
return pil_img # blank page
angle = cv2.minAreaRect(coords)[-1]
angle = -(90 + angle) if angle < -45 else -angle
(h, w) = img_cv.shape[:2]
M = cv2.getRotationMatrix2D((w // 2, h // 2), angle, 1.0)
rotated = cv2.warpAffine(img_cv, M, (w, h),
flags=cv2.INTER_CUBIC,
borderMode=cv2.BORDER_REPLICATE)
return Image.fromarray(cv2.cvtColor(rotated, cv2.COLOR_GRAY2RGB))
def extract_images_with_fitz(pdf_path, start_page=1, end_page=None):
images = []
try:
doc = fitz.open(pdf_path)
total_pages = len(doc)
end = min(end_page or total_pages, total_pages)
for i in range(start_page - 1, end):
try:
page = doc[i]
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
mode = "RGBA" if pix.alpha else "RGB"
img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
images.append((i + 1, img))
except Exception as e:
logger.error(f"Error rendering page {i + 1}: {e}")
doc.close()
except Exception as e:
logger.error(f"Failed to open PDF file: {e}")
return images
def extract_text_from_file(file, start_page=None, end_page=None, filename=None):
ext = os.path.splitext(filename or "")[-1].lower()
all_results = [] # Collect outputs from all methods
if ext == ".pdf":
try:
doc = fitz.open(file.name)
except Exception as e:
logger.error(f"Cannot open PDF {filename}: {e}")
return "[Error opening PDF]"
images = extract_images_with_fitz(file.name, start_page or 1, end_page)
total_pages = len(doc)
start = max(start_page or 1, 1)
end = min(end_page or total_pages, total_pages)
for i, page in enumerate(doc):
page_num = i + 1
if not (start <= page_num <= end):
continue
page_results = {}
# --- PyMuPDF ---
try:
text = page.get_text()
if text.strip():
page_results["PyMuPDF"] = f"Page {page_num}:\n{clean_text(text)}"
except Exception as e:
logger.warning(f"PyMuPDF failed on page {page_num}: {e}")
# --- PaddleOCR ---
paddle_text = ""
try:
if i < len(images):
img = auto_rotate_image(images[i][1])
img_np = np.array(img)
ocr_result = ocr.ocr(img_np) # ✅ FIXED (removed cls=True)
if ocr_result and len(ocr_result[0]) > 0:
paddle_text = "\n".join([line[1][0] for line in ocr_result[0]])
paddle_text = clean_text(paddle_text)
except Exception as e:
logger.warning(f"PaddleOCR failed on page {page_num}: {e}")
if paddle_text:
page_results["PaddleOCR"] = f"Page {page_num}:\n{paddle_text}"
# --- MistralOCR ---
mistral_text = ""
if use_mistral_ocr and i < len(images):
try:
doc_img = DocumentFile.from_images(images[i][1])
mistral_text = mistral_ocr(doc_img).render()
mistral_text = clean_text(mistral_text)
except Exception as e:
logger.warning(f"Mistral OCR failed on page {page_num}: {e}")
if mistral_text:
page_results["MistralOCR"] = f"Page {page_num}:\n{mistral_text}"
# Append collected method outputs for this page
combined_output = []
for method, out in page_results.items():
combined_output.append(f"===== Method: {method} =====\n{out}")
if combined_output:
all_results.append("\n".join(combined_output))
else:
all_results.append(f"Page {page_num}: [No text extracted by any method]")
doc.close()
return "\n\n".join(all_results)
elif ext == ".docx":
from docx.api import Document
doc = Document(file.name)
paras = [p.text for p in doc.paragraphs if p.text.strip()]
page_texts = []
page_size = 500
for i in range(0, len(paras), page_size):
page_texts.append("\n".join(paras[i:i + page_size]))
selected_pages = page_texts
if start_page and end_page:
selected_pages = page_texts[start_page - 1:end_page]
return clean_text("\n\n".join(selected_pages))
elif ext == ".csv":
import pandas as pd
try:
return pd.read_csv(file.name).to_string(index=False)
except Exception as e:
logger.error(f"CSV read error: {e}")
return "[CSV Read Error]"
elif ext in [".xls", ".xlsx"]:
import pandas as pd
try:
xl = pd.ExcelFile(file.name)
return "\n\n".join([
f"Sheet: {s}\n{xl.parse(s).to_string(index=False)}"
for s in xl.sheet_names
])
except Exception as e:
logger.error(f"Excel read error: {e}")
return "[Excel Read Error]"
else:
return "[Unsupported file type]"
|