-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_preprocessor.py
More file actions
296 lines (231 loc) · 9.22 KB
/
file_preprocessor.py
File metadata and controls
296 lines (231 loc) · 9.22 KB
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
import os
import json
import base64
import hashlib
import logging
from pathlib import Path
from typing import Dict, List, Tuple, Optional
from utils import get_sandbox_path
logger = logging.getLogger(__name__)
def get_file_hash(file_path: str) -> str:
"""Calculate SHA256 hash of a file."""
sha256_hash = hashlib.sha256()
try:
with open(file_path, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
except Exception as e:
logger.error(f"Error hashing file {file_path}: {e}")
return ""
def check_git_diff(sandbox_path: str, file_path: str) -> bool:
"""
Check if a file has changed since last git commit using dulwich.
Returns:
True if file has changed or is new, False if unchanged
"""
try:
from dulwich.repo import Repo
from dulwich.errors import NotGitRepository
# Check if git repo exists
try:
repo = Repo(sandbox_path)
except (NotGitRepository, FileNotFoundError):
return True # No git repo, treat as new
# Get relative path from sandbox
rel_path = os.path.relpath(file_path, sandbox_path)
# Convert to bytes for dulwich (uses bytes for paths)
rel_path_bytes = rel_path.encode('utf-8')
# Check if file is tracked in the index
index = repo.open_index()
if rel_path_bytes not in index:
# File is not tracked, it's new
return True
# Check if file has uncommitted changes
# Get HEAD tree
try:
head = repo[b'HEAD']
tree = repo[head.tree]
except KeyError:
# No HEAD commit yet (empty repo)
return True
# Get the file content from HEAD
try:
# Navigate through tree structure to find the file
parts = rel_path.split(os.sep)
current_tree = tree
for i, part in enumerate(parts[:-1]):
# Navigate through directories
part_bytes = part.encode('utf-8')
mode, sha = current_tree[part_bytes]
current_tree = repo[sha]
# Get the file blob from the tree
filename_bytes = parts[-1].encode('utf-8')
mode, blob_sha = current_tree[filename_bytes]
blob = repo[blob_sha]
head_content = blob.data
except (KeyError, IndexError):
# File doesn't exist in HEAD, it's new
return True
# Compare with working tree file
try:
with open(file_path, 'rb') as f:
working_content = f.read()
# Compare content
return head_content != working_content
except Exception as e:
logger.error(f"Error reading working file {file_path}: {e}")
return True
except Exception as e:
logger.error(f"Error checking git diff for {file_path}: {e}")
return True # On error, assume file changed
def convert_pdf_to_text(file_path: str, model_name: str = None) -> Tuple[str, str]:
"""
Convert PDF to text or images based on model capabilities.
Args:
file_path: Path to PDF file
model_name: Name of the model (to check if it supports vision)
Returns:
Tuple of (converted_content, format_type)
format_type is either 'text' or 'image'
"""
try:
import fitz # PyMuPDF
from utils import is_vlm
doc = fitz.open(file_path)
# Check if model supports vision
if is_vlm(model_name):
# Convert to images
images = []
for page in doc:
pix = page.get_pixmap()
img_data = pix.tobytes("png")
b64_img = base64.b64encode(img_data).decode("utf-8")
images.append(b64_img)
doc.close()
# Return as JSON for image format
content = json.dumps({"__type__": "image", "images": images})
return content, "image"
else:
# Convert to text
text_content = []
for i, page in enumerate(doc):
text = page.get_text()
text_content.append(f"--- Page {i+1} ---\n{text}")
doc.close()
content = "\n".join(text_content) if text_content else "PDF is empty or contains no extractable text."
return content, "text"
except Exception as e:
error_msg = f"Error converting PDF {file_path}: {e}"
logger.error(error_msg)
return error_msg, "error"
def get_converted_file_path(original_path: str, format_type: str) -> str:
"""
Get path for converted file.
Args:
original_path: Path to original file
format_type: 'text' or 'image'
Returns:
Path where converted content should be stored
"""
# Create .converted directory in same location as original
dir_name = os.path.dirname(original_path)
base_name = os.path.basename(original_path)
name_without_ext = os.path.splitext(base_name)[0]
converted_dir = os.path.join(dir_name, '.converted')
os.makedirs(converted_dir, exist_ok=True)
if format_type == "text":
return os.path.join(converted_dir, f"{name_without_ext}.txt")
elif format_type == "image":
return os.path.join(converted_dir, f"{name_without_ext}.json")
else:
return os.path.join(converted_dir, f"{name_without_ext}.converted")
def should_convert_file(file_path: str, converted_path: str, sandbox_path: str) -> bool:
"""
Determine if file needs conversion.
Returns:
True if conversion is needed, False if cached version is valid
"""
# If converted file doesn't exist, convert
if not os.path.exists(converted_path):
return True
# Check if original file has changed via git
has_changed = check_git_diff(sandbox_path, file_path)
if has_changed:
return True
# Check file modification times as fallback
original_mtime = os.path.getmtime(file_path)
converted_mtime = os.path.getmtime(converted_path)
if original_mtime > converted_mtime:
return True
return False
def preprocess_file(file_path: str, sandbox_path: str, model_name: str = None) -> Optional[str]:
"""
Preprocess a file by converting non-text formats to text.
Args:
file_path: Absolute path to file
sandbox_path: Path to sandbox
model_name: Model name for vision capability check
Returns:
Path to converted file if conversion happened, None if no conversion needed
"""
# Check if file needs conversion
file_ext = os.path.splitext(file_path)[1].lower()
if file_ext == '.pdf':
# Determine format type
from utils import is_vlm
format_type = "image" if is_vlm(model_name) else "text"
# Get converted file path
converted_path = get_converted_file_path(file_path, format_type)
# Check if conversion is needed
if not should_convert_file(file_path, converted_path, sandbox_path):
logger.info(f"Using cached conversion for {file_path}")
return converted_path
# Convert PDF
logger.info(f"Converting PDF {file_path} to {format_type}")
content, actual_format = convert_pdf_to_text(file_path, model_name)
if actual_format == "error":
logger.error(f"Failed to convert {file_path}")
return None
# Save converted content
try:
with open(converted_path, 'w', encoding='utf-8') as f:
f.write(content)
logger.info(f"Saved converted content to {converted_path}")
return converted_path
except Exception as e:
logger.error(f"Error saving converted file {converted_path}: {e}")
return None
# Add more file type conversions here (e.g., .docx, .xlsx, etc.)
# elif file_ext == '.docx':
# ...
return None
def preprocess_sandbox_files(sandbox_id: str, model_name: str = None) -> Dict[str, str]:
"""
Preprocess all files in sandbox that need conversion.
Args:
sandbox_id: ID of the sandbox
model_name: Model name for vision capability check
Returns:
Dictionary mapping original file paths to converted file paths
"""
sandbox_path = get_sandbox_path(sandbox_id)
conversions = {}
if not os.path.exists(sandbox_path):
return conversions
# Walk through sandbox files
for root, dirs, files in os.walk(sandbox_path):
# Skip .git and .converted directories
dirs[:] = [d for d in dirs if d not in ['.git', '.converted']]
for file in files:
file_path = os.path.join(root, file)
# Try to preprocess
converted_path = preprocess_file(file_path, sandbox_path, model_name)
if converted_path:
# Store relative paths for easier handling
rel_original = os.path.relpath(file_path, sandbox_path)
rel_converted = os.path.relpath(converted_path, sandbox_path)
conversions[rel_original] = rel_converted
if conversions:
logger.info(f"Preprocessed {len(conversions)} files in sandbox {sandbox_id}")
return conversions