-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeepstrip_api.py
More file actions
332 lines (289 loc) · 11.2 KB
/
deepstrip_api.py
File metadata and controls
332 lines (289 loc) · 11.2 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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
deepstrip_api.py - Dynamic version loader
Automatically finds and imports the latest deepstrip_*.py version
"""
from pathlib import Path
from typing import Dict, Any, List
import base64
import importlib.util
import sys
# ============================================================================
# DYNAMIC DEEPSTRIP VERSION LOADER
# ============================================================================
def load_latest_deepstrip():
"""Find and import the latest deepstrip_*.py file"""
deepstrip_files = sorted(
Path(".").glob("deepstrip_*.py"),
reverse=True # Gets highest version number first
)
if not deepstrip_files:
raise ImportError("No deepstrip_*.py file found in directory")
latest_file = deepstrip_files[0]
module_name = latest_file.stem
# Load module dynamically
spec = importlib.util.spec_from_file_location(module_name, latest_file)
if spec is None or spec.loader is None:
raise ImportError(f"Could not load {latest_file}")
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module, module_name
# Load the module
try:
deepstrip_module, version_name = load_latest_deepstrip()
# Import required classes/functions
ExtractionPipeline = deepstrip_module.ExtractionPipeline
Config = deepstrip_module.Config
HexDump = getattr(deepstrip_module, 'HexDump', None)
TokenEncoder = getattr(deepstrip_module, 'TokenEncoder', None)
FormatDetector = getattr(deepstrip_module, 'FormatDetector', None)
scan_unlinked_files = getattr(deepstrip_module, 'scan_unlinked_files', None)
generate_manifest = getattr(deepstrip_module, 'generate_manifest', None)
print(f"✓ Loaded DeepStrip module: {version_name}")
except Exception as e:
print(f"✗ Failed to load DeepStrip: {e}")
# Fallback stubs
class ExtractionPipeline:
def __init__(self, config): pass
def extract(self, data, output): return []
def stream_extract(self, url, max_files): return []
def analyze_file(self, data): return {}
class Config:
def __init__(self): pass
class HexDumpStub:
@staticmethod
def classic(data): return data.hex()
class TokenEncoderStub:
@staticmethod
def encode(data, mode): return data.hex()
@staticmethod
def decode(text, mode): return bytes.fromhex(text)
class FormatDetectorStub:
@staticmethod
def detect(data): return "unknown"
HexDump = HexDumpStub
TokenEncoder = TokenEncoderStub
FormatDetector = FormatDetectorStub
scan_unlinked_files = lambda url: []
generate_manifest = lambda url, results: ""
version_name = "FALLBACK"
# ============================================================================
# API HANDLERS
# ============================================================================
def handle_process(file_contents: bytes, filename: str) -> dict:
"""Process uploaded archive file"""
try:
pipeline = ExtractionPipeline(Config())
files = pipeline.extract(file_contents, Path("./output"))
return {
"status": "success",
"filename": filename,
"size": len(file_contents),
"extracted_files": [
{"name": str(f[0]), "size": len(f[1])} for f in files
]
}
except Exception as e:
return {
"status": "error",
"error": str(e)
}
def handle_extract(payload: Dict[str, Any]) -> dict:
"""Extract archive from URL or path"""
url = payload.get("url")
if not url:
return {"status": "error", "message": "Missing URL"}
try:
path = Path(url)
data = path.read_bytes() if path.exists() else b""
pipeline = ExtractionPipeline(Config())
files = pipeline.extract(data, Path("./output"))
return {
"status": "ok",
"files": [{"name": str(f[0]), "size": len(f[1])} for f in files]
}
except Exception as e:
return {"status": "error", "message": str(e)}
def handle_stream(payload: Dict[str, Any]) -> dict:
"""Stream-extract from remote URL"""
url = payload.get("url")
max_files = payload.get("maxFiles")
if not url:
return {"status": "error", "message": "Missing URL"}
try:
pipeline = ExtractionPipeline(Config())
files = pipeline.stream_extract(url, max_files)
return {
"status": "ok",
"files": [{"name": str(f[0]), "size": len(f[1])} for f in files]
}
except Exception as e:
return {"status": "error", "message": str(e)}
def handle_analyze(payload: Dict[str, Any]) -> dict:
"""Analyze a file or archive"""
url = payload.get("url")
if not url:
return {"status": "error", "message": "Missing URL"}
try:
path = Path(url)
data = path.read_bytes() if path.exists() else b""
pipeline = ExtractionPipeline(Config())
result = pipeline.analyze_file(data)
return {"status": "ok", **result}
except Exception as e:
return {"status": "error", "message": str(e)}
def handle_scan_unlinked(payload: Dict[str, Any]) -> dict:
"""Scan Internet Archive for unlinked files"""
base_url = payload.get("baseUrl")
max_files = payload.get("maxFiles")
if not base_url:
return {"status": "error", "message": "Missing baseUrl"}
try:
results = scan_unlinked_files(base_url)
if max_files:
results = results[:max_files]
manifest = generate_manifest(base_url, results)
return {
"status": "ok",
"totalFound": len(results),
"manifest": manifest,
"files": [
{"name": r[0], "url": r[1], "sha256": r[2]} for r in results
]
}
except Exception as e:
return {"status": "error", "message": str(e)}
def get_info() -> dict:
"""Return API info"""
return {
"version": version_name,
"python": "3.10+",
"containers": [
"zip","tar","gzip","bzip2","xz","7z","cab","arj",
"lzh","arc","is3","iscab","cfbf","zoo","pak"
],
"plugins": 0
}
def handle_hexdump(payload: Dict[str, Any]) -> dict:
"""Generate hexdump in various formats"""
url = payload.get("url")
mode = payload.get("mode", "hex")
spaced = payload.get("spaced", False)
if not url:
return {"status": "error", "message": "Missing URL"}
try:
path = Path(url)
data = path.read_bytes() if path.exists() else b""
if mode == "base64":
encoded = base64.b64encode(data).decode()
elif mode in ("tb256", "gemini"):
out = TokenEncoder.encode(data, "gemini")
encoded = " ".join(out) if spaced else out
elif mode == "braille":
out = TokenEncoder.encode(data, "braille")
encoded = " ".join(out) if spaced else out
elif mode == "hex" or mode == "binary":
h = data.hex()
encoded = " ".join(h[i:i+2] for i in range(0, len(h), 2)) if spaced else h
else:
encoded = HexDump.classic(data)
return {"status": "ok", "mode": mode, "content": encoded}
except Exception as e:
return {"status": "error", "message": str(e)}
def handle_save(payload: Dict[str, Any]) -> dict:
"""Save file (decode from encoding)"""
filename = payload.get("filename", "out.bin")
content = payload.get("content")
mode = payload.get("mode", "binary")
spaced = payload.get("spaced", False)
if content is None:
return {"status": "error", "message": "Missing content"}
try:
if mode in ("hex", "binary"):
raw = bytes.fromhex(content.replace(" ", "")) if spaced else bytes.fromhex(content)
elif mode == "base64":
raw = base64.b64decode(content)
elif mode in ("tb256", "gemini"):
raw = TokenEncoder.decode(content.replace(" ", ""), "gemini")
elif mode == "braille":
raw = TokenEncoder.decode(content.replace(" ", ""), "braille")
else:
return {"status": "error", "message": f"Unsupported mode {mode}"}
path = Path("./output") / filename
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(raw)
return {"status": "ok", "saved": str(path), "size": len(raw)}
except Exception as e:
return {"status": "error", "message": str(e)}
def handle_load(payload: Dict[str, Any]) -> dict:
"""Load file (encode to chosen format)"""
filename = payload.get("filename")
mode = payload.get("mode", "binary")
spaced = payload.get("spaced", False)
if not filename:
return {"status": "error", "message": "Missing filename"}
try:
path = Path("./output") / filename
data = path.read_bytes()
if mode == "base64":
encoded = base64.b64encode(data).decode()
elif mode in ("tb256", "gemini"):
out = TokenEncoder.encode(data, "gemini")
encoded = " ".join(out) if spaced else out
elif mode == "braille":
out = TokenEncoder.encode(data, "braille")
encoded = " ".join(out) if spaced else out
elif mode in ("hex", "binary"):
h = data.hex()
encoded = " ".join(h[i:i+2] for i in range(0, len(h), 2)) if spaced else h
else:
encoded = HexDump.classic(data)
return {"status": "ok", "filename": filename, "mode": mode, "content": encoded}
except Exception as e:
return {"status": "error", "message": str(e)}
def handle_orcad_index(file_contents: bytes, filename: str) -> dict:
"""Classify OrCAD file type (for upload handler)"""
try:
fmt = FormatDetector.detect(file_contents)
return {
"file": filename,
"type": fmt,
"orcad_format": fmt in ("dsn", "sch", "olb", "lib"),
"notes": "detected by FormatDetector"
}
except Exception as e:
return {
"file": filename,
"type": "unknown",
"orcad_format": False,
"notes": str(e)
}
def handle_orcad_index_batch(payload: Dict[str, Any]) -> dict:
"""Classify OrCAD files from paths (for JSON payload)"""
files: List[str] = payload.get("files", [])
if not files:
return {"classified": []}
classified = []
for f in files:
try:
data = Path(f).read_bytes()
fmt = FormatDetector.detect(data)
classified.append({
"file": f,
"type": fmt,
"orcad_format": fmt in ("dsn", "sch", "olb", "lib"),
"notes": "detected by FormatDetector"
})
except Exception as e:
classified.append({
"file": f,
"type": "unknown",
"orcad_format": False,
"notes": str(e)
})
return {"classified": classified}
def handle_deploy() -> dict:
"""Deploy stub"""
return {"status": "deploy triggered", "detail": "Triggered via API stub"}