File size: 11,087 Bytes
1041734 e7b4937 1041734 |
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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
"""
File Parser Tool - Multi-format file reading
Author: @mangubee
Date: 2026-01-02
Provides file parsing for:
- PDF files (.pdf) using PyPDF2
- Excel files (.xlsx, .xls) using openpyxl
- Word documents (.docx) using python-docx
- Text files (.txt, .csv) using built-in open()
All parsers include retry logic and error handling.
"""
import logging
from pathlib import Path
from typing import Dict, List, Optional
from tenacity import (
retry,
stop_after_attempt,
wait_exponential,
retry_if_exception_type,
)
# ============================================================================
# CONFIG
# ============================================================================
MAX_RETRIES = 3
RETRY_MIN_WAIT = 1 # seconds
RETRY_MAX_WAIT = 5 # seconds
SUPPORTED_EXTENSIONS = {
'.pdf': 'PDF',
'.xlsx': 'Excel',
'.xls': 'Excel',
'.docx': 'Word',
'.txt': 'Text',
'.csv': 'CSV',
}
# ============================================================================
# Logging Setup
# ============================================================================
logger = logging.getLogger(__name__)
# ============================================================================
# PDF Parser
# ============================================================================
@retry(
stop=stop_after_attempt(MAX_RETRIES),
wait=wait_exponential(multiplier=1, min=RETRY_MIN_WAIT, max=RETRY_MAX_WAIT),
retry=retry_if_exception_type((IOError, OSError)),
reraise=True,
)
def parse_pdf(file_path: str) -> Dict:
"""
Parse PDF file and extract text content.
Args:
file_path: Path to PDF file
Returns:
Dict with structure: {
"content": str, # Extracted text
"pages": int, # Number of pages
"file_type": "PDF",
"file_path": str
}
Raises:
FileNotFoundError: If file doesn't exist
ValueError: If file is corrupted or invalid
IOError: For file reading errors (triggers retry)
"""
try:
from PyPDF2 import PdfReader
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"PDF file not found: {file_path}")
logger.info(f"Parsing PDF: {file_path}")
reader = PdfReader(str(path))
num_pages = len(reader.pages)
# Extract text from all pages
content = []
for page_num, page in enumerate(reader.pages, 1):
text = page.extract_text()
if text.strip():
content.append(f"--- Page {page_num} ---\n{text}")
full_content = "\n\n".join(content)
logger.info(f"PDF parsed successfully: {num_pages} pages, {len(full_content)} chars")
return {
"content": full_content,
"pages": num_pages,
"file_type": "PDF",
"file_path": file_path,
}
except FileNotFoundError as e:
logger.error(f"PDF file not found: {e}")
raise
except (IOError, OSError) as e:
logger.warning(f"PDF IO error (will retry): {e}")
raise
except Exception as e:
logger.error(f"PDF parsing error: {e}")
raise ValueError(f"Failed to parse PDF: {str(e)}")
# ============================================================================
# Excel Parser
# ============================================================================
@retry(
stop=stop_after_attempt(MAX_RETRIES),
wait=wait_exponential(multiplier=1, min=RETRY_MIN_WAIT, max=RETRY_MAX_WAIT),
retry=retry_if_exception_type((IOError, OSError)),
reraise=True,
)
def parse_excel(file_path: str) -> Dict:
"""
Parse Excel file and extract data from all sheets.
Args:
file_path: Path to Excel file (.xlsx or .xls)
Returns:
Dict with structure: {
"content": str, # Formatted table data
"sheets": List[str], # Sheet names
"file_type": "Excel",
"file_path": str
}
Raises:
FileNotFoundError: If file doesn't exist
ValueError: If file is corrupted or invalid
IOError: For file reading errors (triggers retry)
"""
try:
from openpyxl import load_workbook
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"Excel file not found: {file_path}")
logger.info(f"Parsing Excel: {file_path}")
workbook = load_workbook(str(path), data_only=True)
sheet_names = workbook.sheetnames
# Extract data from all sheets
content_parts = []
for sheet_name in sheet_names:
sheet = workbook[sheet_name]
# Get all values
rows = []
for row in sheet.iter_rows(values_only=True):
# Filter out completely empty rows
if any(cell is not None for cell in row):
row_str = "\t".join(str(cell) if cell is not None else "" for cell in row)
rows.append(row_str)
if rows:
sheet_content = f"=== Sheet: {sheet_name} ===\n" + "\n".join(rows)
content_parts.append(sheet_content)
full_content = "\n\n".join(content_parts)
logger.info(f"Excel parsed successfully: {len(sheet_names)} sheets")
return {
"content": full_content,
"sheets": sheet_names,
"file_type": "Excel",
"file_path": file_path,
}
except FileNotFoundError as e:
logger.error(f"Excel file not found: {e}")
raise
except (IOError, OSError) as e:
logger.warning(f"Excel IO error (will retry): {e}")
raise
except Exception as e:
logger.error(f"Excel parsing error: {e}")
raise ValueError(f"Failed to parse Excel: {str(e)}")
# ============================================================================
# Word Document Parser
# ============================================================================
@retry(
stop=stop_after_attempt(MAX_RETRIES),
wait=wait_exponential(multiplier=1, min=RETRY_MIN_WAIT, max=RETRY_MAX_WAIT),
retry=retry_if_exception_type((IOError, OSError)),
reraise=True,
)
def parse_word(file_path: str) -> Dict:
"""
Parse Word document and extract text content.
Args:
file_path: Path to Word file (.docx)
Returns:
Dict with structure: {
"content": str, # Extracted text
"paragraphs": int, # Number of paragraphs
"file_type": "Word",
"file_path": str
}
Raises:
FileNotFoundError: If file doesn't exist
ValueError: If file is corrupted or invalid
IOError: For file reading errors (triggers retry)
"""
try:
from docx import Document
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"Word file not found: {file_path}")
logger.info(f"Parsing Word document: {file_path}")
doc = Document(str(path))
# Extract text from all paragraphs
paragraphs = [para.text for para in doc.paragraphs if para.text.strip()]
full_content = "\n\n".join(paragraphs)
logger.info(f"Word parsed successfully: {len(paragraphs)} paragraphs")
return {
"content": full_content,
"paragraphs": len(paragraphs),
"file_type": "Word",
"file_path": file_path,
}
except FileNotFoundError as e:
logger.error(f"Word file not found: {e}")
raise
except (IOError, OSError) as e:
logger.warning(f"Word IO error (will retry): {e}")
raise
except Exception as e:
logger.error(f"Word parsing error: {e}")
raise ValueError(f"Failed to parse Word document: {str(e)}")
# ============================================================================
# Text/CSV Parser
# ============================================================================
@retry(
stop=stop_after_attempt(MAX_RETRIES),
wait=wait_exponential(multiplier=1, min=RETRY_MIN_WAIT, max=RETRY_MAX_WAIT),
retry=retry_if_exception_type((IOError, OSError)),
reraise=True,
)
def parse_text(file_path: str) -> Dict:
"""
Parse plain text or CSV file.
Args:
file_path: Path to text file (.txt or .csv)
Returns:
Dict with structure: {
"content": str,
"lines": int,
"file_type": "Text" or "CSV",
"file_path": str
}
Raises:
FileNotFoundError: If file doesn't exist
IOError: For file reading errors (triggers retry)
"""
try:
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"Text file not found: {file_path}")
logger.info(f"Parsing text file: {file_path}")
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
lines = content.count('\n') + 1
file_type = "CSV" if path.suffix == '.csv' else "Text"
logger.info(f"{file_type} file parsed successfully: {lines} lines")
return {
"content": content,
"lines": lines,
"file_type": file_type,
"file_path": file_path,
}
except FileNotFoundError as e:
logger.error(f"Text file not found: {e}")
raise
except (IOError, OSError) as e:
logger.warning(f"Text file IO error (will retry): {e}")
raise
except UnicodeDecodeError as e:
logger.error(f"Text file encoding error: {e}")
raise ValueError(f"Failed to decode text file (try UTF-8): {str(e)}")
# ============================================================================
# Unified File Parser
# ============================================================================
def parse_file(file_path: str) -> Dict:
"""
Parse file based on extension, automatically selecting the right parser.
Args:
file_path: Path to file
Returns:
Dict with parsed content and metadata
Raises:
ValueError: If file type is not supported
FileNotFoundError: If file doesn't exist
Exception: For parsing errors
"""
path = Path(file_path)
extension = path.suffix.lower()
if extension not in SUPPORTED_EXTENSIONS:
raise ValueError(
f"Unsupported file type: {extension}. "
f"Supported: {', '.join(SUPPORTED_EXTENSIONS.keys())}"
)
logger.info(f"Dispatching parser for {SUPPORTED_EXTENSIONS[extension]} file: {file_path}")
# Dispatch to appropriate parser
if extension == '.pdf':
return parse_pdf(file_path)
elif extension in ['.xlsx', '.xls']:
return parse_excel(file_path)
elif extension == '.docx':
return parse_word(file_path)
elif extension in ['.txt', '.csv']:
return parse_text(file_path)
else:
# Should never reach here due to check above
raise ValueError(f"No parser for extension: {extension}")
|