File size: 16,616 Bytes
5374a2d |
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 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 |
from .tool import Tool,Toolkit
import os
import PyPDF2
from typing import Dict, Any, List, Optional
from ..core.logging import logger
from ..core.module import BaseModule
class FileBase(BaseModule):
"""
Base class containing shared file handling logic for different file types.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
# File type handlers for special file formats
self.file_handlers = {
'.pdf': {
'read': self._read_pdf,
'write': self._write_pdf,
'append': self._append_pdf
}
# Add more special file handlers here as needed
}
def get_file_handlers(self):
"""Returns file type handlers for special file formats"""
return self.file_handlers
def _read_pdf(self, file_path: str) -> Dict[str, Any]:
"""
Read content from a PDF file.
Args:
file_path (str): Path to the PDF file
Returns:
dict: A dictionary with the PDF content and metadata
"""
try:
with open(file_path, 'rb') as f:
pdf_reader = PyPDF2.PdfReader(f)
text = ""
for page_num in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_num]
text += page.extract_text() + "\n"
return {
"success": True,
"content": text,
"file_path": file_path,
"file_type": "pdf",
"pages": len(pdf_reader.pages)
}
except Exception as e:
logger.error(f"Error reading PDF {file_path}: {str(e)}")
return {"success": False, "error": str(e), "file_path": file_path}
def _write_pdf(self, file_path: str, content: str) -> Dict[str, Any]:
"""
Write content to a PDF file using reportlab.
Args:
file_path (str): Path to the PDF file
content (str): Content to write to the PDF
Returns:
dict: A dictionary with the operation status
"""
try:
# Use reportlab to create a proper PDF with text content
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
# Create PDF document
doc = SimpleDocTemplate(file_path, pagesize=letter)
styles = getSampleStyleSheet()
story = []
# Split content into paragraphs
paragraphs = content.split('\n')
for para_text in paragraphs:
if para_text.strip(): # Non-empty paragraph
# Create paragraph with normal style
para = Paragraph(para_text, styles['Normal'])
story.append(para)
story.append(Spacer(1, 12)) # Add space between paragraphs
else:
# Empty line - add space
story.append(Spacer(1, 12))
# Build the PDF
doc.build(story)
return {
"success": True,
"message": f"PDF created at {file_path} with text content using reportlab",
"file_path": file_path,
"content_length": len(content),
"paragraphs": len([p for p in paragraphs if p.strip()]),
"library_used": "reportlab"
}
except ImportError:
# Fallback: Create a basic PDF with PyPDF2 but inform user about limitation
pdf_writer = PyPDF2.PdfWriter()
pdf_writer.add_blank_page(width=612, height=792) # Standard letter size
with open(file_path, 'wb') as f:
pdf_writer.write(f)
return {
"success": True,
"message": f"Basic PDF created at {file_path} (blank page only - reportlab not available)",
"file_path": file_path,
"warning": "Text content not added - reportlab library not found",
"note": "Install reportlab for full PDF text support: pip install reportlab",
"library_used": "PyPDF2"
}
except Exception as e:
logger.error(f"Error writing PDF {file_path}: {str(e)}")
return {"success": False, "error": str(e), "file_path": file_path}
def _append_pdf(self, file_path: str, content: str) -> Dict[str, Any]:
"""
Append content to a PDF file by creating a new page.
Args:
file_path (str): Path to the PDF file
content (str): Content to append to the PDF
Returns:
dict: A dictionary with the operation status
"""
try:
if not os.path.exists(file_path):
return self._write_pdf(file_path, content)
try:
# Import required libraries
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
import tempfile
# Create a temporary PDF with the new content
with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as temp_file:
temp_pdf_path = temp_file.name
# Create the new page with content using reportlab
doc = SimpleDocTemplate(temp_pdf_path, pagesize=letter)
styles = getSampleStyleSheet()
story = []
# Split content into paragraphs
paragraphs = content.split('\n')
for para_text in paragraphs:
if para_text.strip(): # Non-empty paragraph
para = Paragraph(para_text, styles['Normal'])
story.append(para)
story.append(Spacer(1, 12))
else:
# Empty line - add space
story.append(Spacer(1, 12))
# Build the temporary PDF
doc.build(story)
# Now merge the existing PDF with the new page
pdf_writer = PyPDF2.PdfWriter()
# Add all pages from the existing PDF
with open(file_path, 'rb') as existing_file:
pdf_reader = PyPDF2.PdfReader(existing_file)
for page_num in range(len(pdf_reader.pages)):
pdf_writer.add_page(pdf_reader.pages[page_num])
# Add the new page(s) from the temporary PDF
with open(temp_pdf_path, 'rb') as temp_file:
temp_reader = PyPDF2.PdfReader(temp_file)
for page_num in range(len(temp_reader.pages)):
pdf_writer.add_page(temp_reader.pages[page_num])
# Write the merged PDF back to the original file
with open(file_path, 'wb') as output_file:
pdf_writer.write(output_file)
# Clean up temporary file
os.unlink(temp_pdf_path)
return {
"success": True,
"message": f"Content appended as new page(s) to PDF at {file_path}",
"file_path": file_path,
"operation": "append_new_page",
"appended_content_length": len(content),
"paragraphs_added": len([p for p in paragraphs if p.strip()]),
"library_used": "reportlab + PyPDF2"
}
except ImportError:
# Fallback: Basic PDF page append using only PyPDF2
pdf_writer = PyPDF2.PdfWriter()
# Add all pages from the existing PDF
with open(file_path, 'rb') as existing_file:
pdf_reader = PyPDF2.PdfReader(existing_file)
for page_num in range(len(pdf_reader.pages)):
pdf_writer.add_page(pdf_reader.pages[page_num])
# Add a blank page (since we can't add text without reportlab)
pdf_writer.add_blank_page(width=612, height=792)
# Write back to file
with open(file_path, 'wb') as output_file:
pdf_writer.write(output_file)
return {
"success": True,
"message": f"Blank page appended to PDF at {file_path} (reportlab not available for text)",
"file_path": file_path,
"operation": "append_blank_page",
"warning": "Text content not added - reportlab library not found",
"note": "Install reportlab for full PDF text support: pip install reportlab",
"library_used": "PyPDF2"
}
except Exception as e:
logger.error(f"Error appending to PDF {file_path}: {str(e)}")
return {"success": False, "error": str(e), "file_path": file_path}
class ReadFileTool(Tool):
name: str = "read_file"
description: str = "Read content from a file with special handling for different file types like PDFs"
inputs: Dict[str, Dict[str, str]] = {
"file_path": {
"type": "string",
"description": "Path to the file to read"
}
}
required: Optional[List[str]] = ["file_path"]
def __init__(self, file_base: FileBase = None):
super().__init__()
self.file_base = file_base
def __call__(self, file_path: str) -> Dict[str, Any]:
"""
Read content from a file with special handling for different file types.
Args:
file_path (str): Path to the file to read
Returns:
dict: A dictionary with the file content and metadata
"""
try:
if not os.path.exists(file_path):
return {"success": False, "error": f"File not found: {file_path}"}
file_ext = os.path.splitext(file_path)[1].lower()
# Use special handler if available for this file type
if self.file_base and file_ext in self.file_base.get_file_handlers():
file_handlers = self.file_base.get_file_handlers()
if 'read' in file_handlers[file_ext]:
return file_handlers[file_ext]['read'](file_path)
# Default file reading behavior
with open(file_path, 'r') as f:
content = f.read()
return {
"success": True,
"content": content,
"file_path": file_path,
"file_type": file_ext or "text"
}
except Exception as e:
logger.error(f"Error reading file {file_path}: {str(e)}")
return {"success": False, "error": str(e), "file_path": file_path}
class WriteFileTool(Tool):
name: str = "write_file"
description: str = "Write content to a file with special handling for different file types like PDFs"
inputs: Dict[str, Dict[str, str]] = {
"file_path": {
"type": "string",
"description": "Path to the file to write"
},
"content": {
"type": "string",
"description": "Content to write to the file"
}
}
required: Optional[List[str]] = ["file_path", "content"]
def __init__(self, file_base: FileBase = None):
super().__init__()
self.file_base = file_base
def __call__(self, file_path: str, content: str) -> Dict[str, Any]:
"""
Write content to a file with special handling for different file types.
Args:
file_path (str): Path to the file to write
content (str): Content to write to the file
Returns:
dict: A dictionary with the operation status
"""
try:
file_ext = os.path.splitext(file_path)[1].lower()
# Create directory if it doesn't exist
directory = os.path.dirname(file_path)
if directory:
os.makedirs(directory, exist_ok=True)
# Use special handler if available for this file type
if self.file_base and file_ext in self.file_base.get_file_handlers():
file_handlers = self.file_base.get_file_handlers()
if 'write' in file_handlers[file_ext]:
return file_handlers[file_ext]['write'](file_path, content)
# Default file writing behavior
with open(file_path, 'w') as f:
f.write(content)
return {
"success": True,
"message": f"Content written to {file_path}",
"file_path": file_path
}
except Exception as e:
logger.error(f"Error writing to file {file_path}: {str(e)}")
return {"success": False, "error": str(e), "file_path": file_path}
class AppendFileTool(Tool):
name: str = "append_file"
description: str = "Append content to a file with special handling for different file types like PDFs"
inputs: Dict[str, Dict[str, str]] = {
"file_path": {
"type": "string",
"description": "Path to the file to append to"
},
"content": {
"type": "string",
"description": "Content to append to the file"
}
}
required: Optional[List[str]] = ["file_path", "content"]
def __init__(self, file_base: FileBase = None):
super().__init__()
self.file_base = file_base
def __call__(self, file_path: str, content: str) -> Dict[str, Any]:
"""
Append content to a file with special handling for different file types.
Args:
file_path (str): Path to the file to append to
content (str): Content to append to the file
Returns:
dict: A dictionary with the operation status
"""
file_ext = os.path.splitext(file_path)[1].lower()
# Create directory if it doesn't exist
directory = os.path.dirname(file_path)
if directory:
os.makedirs(directory, exist_ok=True)
# Use special handler if available for this file type
if self.file_base and file_ext in self.file_base.get_file_handlers():
file_handlers = self.file_base.get_file_handlers()
if 'append' in file_handlers[file_ext]:
return file_handlers[file_ext]['append'](file_path, content)
# Default file appending behavior
try:
with open(file_path, 'a') as f:
f.write(content)
return {
"success": True,
"message": f"Content appended to {file_path}",
"file_path": file_path
}
except Exception as e:
logger.error(f"Error appending to file {file_path}: {str(e)}")
return {"success": False, "error": str(e), "file_path": file_path}
class FileToolkit(Toolkit):
def __init__(self, name: str = "FileToolkit"):
# Create the shared file base instance
file_base = FileBase()
# Create tools with the shared file base
tools = [
ReadFileTool(file_base=file_base),
WriteFileTool(file_base=file_base),
AppendFileTool(file_base=file_base)
]
# Initialize parent with tools
super().__init__(name=name, tools=tools)
# Store file_base as instance variable
self.file_base = file_base
|