File size: 12,469 Bytes
fe52ef9 | 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 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | import base64
import json
from typing import Dict, Any
import PyPDF2
from docx import Document
import pandas as pd
import nbformat
class BaseProcessor:
"""Base class for all file processors"""
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
raise NotImplementedError("Subclasses must implement process method")
class PDFProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
pages = []
for n, page in enumerate(pdf_reader.pages):
pages.append({"page": n, "content": page.extract_text()})
return {
"content": pages,
"metadata": {
"total_pages": len(pages),
"file_type": "PDF"
}
}
class DocxProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
doc = Document(file_path)
paragraphs = []
for n, paragraph in enumerate(doc.paragraphs, 1):
if paragraph.text.strip():
paragraphs.append({
"paragraph": n,
"content": paragraph.text
})
return {
"content": paragraphs,
"metadata": {
"total_paragraphs": len(paragraphs),
"file_type": "DOCX"
}
}
class ImageProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
try:
with open(file_path, 'rb') as file:
content = base64.b64encode(file.read()).decode('ascii')
return {
"content": content,
"metadata": {
"file_type": "IMAGE",
"encoding": "base64"
}
}
except Exception as e:
raise Exception(f"Error processing image: {str(e)}")
class JSONProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
try:
data = json.load(file)
return {
"content": data,
"metadata": {
"file_type": "JSON",
"is_valid": True
}
}
except json.JSONDecodeError as e:
return {
"content": None,
"metadata": {
"file_type": "JSON",
"is_valid": False,
"error": str(e)
}
}
class TextProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
content = file.read()
return {
"content": content,
"metadata": {
"file_type": "TEXT",
"encoding": "utf-8"
}
}
class CSVProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
try:
df = pd.read_csv(file_path)
return {
"content": df.to_dict(orient='records'),
"metadata": {
"file_type": "CSV",
"rows": len(df),
"columns": len(df.columns),
"column_names": list(df.columns),
"summary": {
"first_few_rows": df.head().to_dict(orient='records'),
"statistics": df.describe().to_dict()
}
}
}
except Exception as e:
return {
"content": None,
"metadata": {
"file_type": "CSV",
"error": str(e)
}
}
class ExcelProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
try:
# Get sheet names first
xl = pd.ExcelFile(file_path)
sheets = xl.sheet_names
# Read the first sheet by default
df = pd.read_excel(file_path, sheet_name=sheets[0])
# Read all sheets
all_sheets = {}
for sheet in sheets:
all_sheets[sheet] = pd.read_excel(file_path, sheet_name=sheet).to_dict(orient='records')
return {
"content": all_sheets,
"metadata": {
"file_type": "EXCEL",
"sheets": sheets,
"current_sheet": {
"name": sheets[0],
"rows": len(df),
"columns": len(df.columns),
"column_names": list(df.columns),
"summary": {
"first_few_rows": df.head().to_dict(orient='records'),
"statistics": df.describe().to_dict()
}
}
}
}
except Exception as e:
return {
"content": None,
"metadata": {
"file_type": "EXCEL",
"error": str(e)
}
}
class PythonProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
content = file.read()
return {
"content": content,
"metadata": {
"file_type": "PYTHON",
"encoding": "utf-8"
}
}
class JupyterNotebookProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
try:
with open(file_path, 'r') as file:
nb = nbformat.read(file, as_version=4)
content = []
for cell in nb.cells:
cell_info = {
"type": cell.cell_type,
"content": cell.source
}
if cell.cell_type == "code" and cell.outputs:
cell_info["outputs"] = [str(output) for output in cell.outputs]
content.append(cell_info)
return {
"content": content,
"metadata": {
"file_type": "JUPYTER_NOTEBOOK",
"total_cells": len(content),
"cell_types": list(set(cell["type"] for cell in content))
}
}
except Exception as e:
return {
"content": None,
"metadata": {
"file_type": "JUPYTER_NOTEBOOK",
"error": str(e)
}
}
class SVGProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
try:
with open(file_path, 'r') as file:
return {
"content": file.read(),
"metadata": {
"file_type": "SVG",
"encoding": "utf-8"
}
}
except Exception as e:
return {
"content": None,
"metadata": {
"file_type": "SVG",
"error": str(e)
}
}
class JavaScriptProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
content = file.read()
return {
"content": content,
"metadata": {
"file_type": "JAVASCRIPT",
"encoding": "utf-8"
}
}
class HTMLProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
content = file.read()
return {
"content": content,
"metadata": {
"file_type": "HTML",
"encoding": "utf-8"
}
}
class CSSProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
content = file.read()
return {
"content": content,
"metadata": {
"file_type": "CSS",
"encoding": "utf-8"
}
}
class JavaProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
content = file.read()
return {
"content": content,
"metadata": {
"file_type": "JAVA",
"encoding": "utf-8"
}
}
class CppProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
content = file.read()
return {
"content": content,
"metadata": {
"file_type": "CPP",
"encoding": "utf-8"
}
}
class HeaderProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
content = file.read()
return {
"content": content,
"metadata": {
"file_type": "HEADER",
"encoding": "utf-8"
}
}
class ShellScriptProcessor(BaseProcessor):
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
content = file.read()
return {
"content": content,
"metadata": {
"file_type": "SHELL_SCRIPT",
"encoding": "utf-8"
}
}
class CodeFileProcessor(BaseProcessor):
"""Universal processor for code files that just need to be read as text"""
@classmethod
def process(cls, file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as file:
content = file.read()
ext = file_path[file_path.rfind('.'):].upper()[1:] # Remove the dot and capitalize
return {
"content": content,
"metadata": {
"file_type": ext,
"encoding": "utf-8"
}
}
class FileProcessorFactory:
"""Factory class to get the appropriate processor for a file type"""
_processors = {
'.pdf': PDFProcessor,
'.docx': DocxProcessor,
'.png': ImageProcessor,
'.jpg': ImageProcessor,
'.jpeg': ImageProcessor,
'.json': JSONProcessor,
'.txt': TextProcessor,
'.csv': CSVProcessor,
'.xlsx': ExcelProcessor,
'.xls': ExcelProcessor,
'.py': PythonProcessor,
'.ipynb': JupyterNotebookProcessor,
'.svg': SVGProcessor,
# Universal code file processor for various file types
'.js': CodeFileProcessor,
'.html': CodeFileProcessor,
'.htm': CodeFileProcessor,
'.css': CodeFileProcessor,
'.java': CodeFileProcessor,
'.cpp': CodeFileProcessor,
'.cc': CodeFileProcessor,
'.cxx': CodeFileProcessor,
'.h': CodeFileProcessor,
'.hpp': CodeFileProcessor,
'.sh': CodeFileProcessor,
'.bash': CodeFileProcessor
}
@classmethod
def get_processor(cls, file_path: str) -> BaseProcessor:
ext = file_path[file_path.rfind('.'):].lower()
processor = cls._processors.get(ext)
if not processor:
raise ValueError(f"Unsupported file type: {ext}")
return processor |