jcarve 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jcarve/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """jcarve -- reassemble fragmented JPEGs from raw disk images."""
2
+ __version__ = '0.1.0'
jcarve/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """`python -m jcarve` -- the same CLI as the `jcarve` command."""
2
+ from jcarve.carve import main
3
+
4
+ if __name__ == '__main__': # guarded: multiprocessing re-imports __main__
5
+ main()
jcarve/app.py ADDED
@@ -0,0 +1,445 @@
1
+ """
2
+ jcarve — Streamlit front end for fragmented-JPEG recovery.
3
+
4
+ Run with: jcarve-ui (installed)
5
+ streamlit run jcarve/app.py (source checkout)
6
+
7
+ Long jobs run as `python -m jcarve` subprocesses and report progress through a JSON
8
+ file, so the scan survives UI reruns and you can close and reopen the browser.
9
+ """
10
+ import datetime, io, json, os, re, signal, subprocess, sys, time
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import streamlit as st
15
+
16
+ # Streamlit runs this file as a script, not as part of the package, so relative
17
+ # imports are unavailable. An installed jcarve imports directly; a source
18
+ # checkout needs the repo root -- the package's parent -- on the path.
19
+ PKG_PARENT = str(Path(__file__).resolve().parent.parent)
20
+ try:
21
+ from jcarve import carve, geom # carve: default_jobs() only; jobs stay subprocesses
22
+ except ImportError:
23
+ sys.path.insert(0, PKG_PARENT)
24
+ from jcarve import carve, geom
25
+ from PIL import Image, ImageFile
26
+
27
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
28
+ JOB_LOG = '/tmp/jcarve_%s.log'
29
+
30
+ st.set_page_config(page_title='jcarve — fragmented JPEG recovery',
31
+ page_icon='🧩', layout='wide')
32
+
33
+ # ---------------------------------------------------------------- helpers
34
+
35
+ def sh(*args):
36
+ return [sys.executable, '-m', 'jcarve', *[str(a) for a in args]]
37
+
38
+
39
+ def job_env():
40
+ """Environment for a job subprocess: lets `-m jcarve` resolve from a
41
+ source checkout as well as from an install."""
42
+ env = dict(os.environ)
43
+ env['PYTHONPATH'] = os.pathsep.join(
44
+ p for p in (PKG_PARENT, env.get('PYTHONPATH')) if p)
45
+ return env
46
+
47
+
48
+ def launch(cmd, key):
49
+ """Start a long job as a subprocess.
50
+
51
+ Never give it a PIPE: nothing here drains one, so the child blocks forever
52
+ as soon as the 64 KiB pipe buffer fills. `index` emits a 61-byte progress
53
+ line per 16 MiB chunk, which fills it after ~1073 lines -- about 17 GiB
54
+ into the image, so this only ever bit on real-sized media. `recover` would
55
+ hit the same wall after ~700 photos. Progress comes from the JSON file;
56
+ this log exists only for a post-mortem if a job dies.
57
+ """
58
+ log = open(JOB_LOG % key, 'wb')
59
+ try:
60
+ st.session_state[key] = subprocess.Popen(
61
+ cmd, stdout=log, stderr=subprocess.STDOUT, env=job_env())
62
+ finally:
63
+ log.close() # the child holds its own dup of the descriptor
64
+
65
+
66
+ def exif_day(s):
67
+ """Calendar date out of an EXIF timestamp, or None if there wasn't one.
68
+
69
+ EXIF writes 'YYYY:MM:DD hh:mm:ss' -- colons, not dashes -- which is why the
70
+ substring box needs `2026:05:26` and silently matches nothing for
71
+ `2026-05-26`. The pickers exist so that trap never comes up.
72
+ """
73
+ try:
74
+ return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10]))
75
+ except (ValueError, TypeError, IndexError):
76
+ return None
77
+
78
+
79
+ def running(key):
80
+ p = st.session_state.get(key)
81
+ return p is not None and p.poll() is None
82
+
83
+
84
+ def read_json(path):
85
+ try:
86
+ with open(path) as fh:
87
+ return json.load(fh)
88
+ except Exception:
89
+ return None
90
+
91
+
92
+ def cluster_map(clean, headers, cluster, base_off, cols=900, rows=40):
93
+ """A strip like JpegDigger's entropy map: which clusters hold entropy data.
94
+
95
+ Always rendered at a fixed width so the strip stays thin regardless of how
96
+ many clusters the image actually has.
97
+ """
98
+ n = len(clean)
99
+ if n == 0:
100
+ return None
101
+ arr = (np.frombuffer(clean.encode(), dtype=np.uint8) - ord('0')).astype(np.float32)
102
+ if n >= cols: # downsample: local density
103
+ edges = np.linspace(0, n, cols + 1).astype(int)
104
+ dens = np.array([arr[a:b].mean() if b > a else 0.0
105
+ for a, b in zip(edges[:-1], edges[1:])], np.float32)
106
+ else: # upsample: nearest cluster
107
+ dens = arr[np.minimum((np.arange(cols) * n // cols), n - 1)]
108
+ img = np.zeros((rows, cols, 3), np.uint8)
109
+ img[..., 1] = (dens * 205).astype(np.uint8)[None, :] # green = entropy data
110
+ img[..., 2] = (dens * 85).astype(np.uint8)[None, :]
111
+ img[:5] = 22 # header gutter
112
+ for h in headers:
113
+ c = (h['offset'] - base_off) // cluster
114
+ if 0 <= c < n:
115
+ x = int(c / n * cols)
116
+ img[:5, max(0, x - 1):min(cols, x + 2)] = np.array([255, 170, 40], np.uint8)
117
+ return img
118
+
119
+
120
+ def human(n):
121
+ for u in ('B', 'KB', 'MB', 'GB', 'TB'):
122
+ if abs(n) < 1024:
123
+ return '%.1f %s' % (n, u)
124
+ n /= 1024
125
+ return '%.1f PB' % n
126
+
127
+
128
+ # ---------------------------------------------------------------- sidebar
129
+
130
+ st.sidebar.title('🧩 jcarve')
131
+ st.sidebar.caption('Reassembles JPEGs that ordinary carvers leave broken.')
132
+
133
+ image = st.sidebar.text_input('Disk image', value=st.session_state.get('image', ''),
134
+ placeholder='/Volumes/Backup/disk.img')
135
+ st.session_state['image'] = image
136
+
137
+ for k, v in (('cluster', 131072), ('data_off', 0)):
138
+ st.session_state.setdefault(k, v)
139
+
140
+ if image and os.path.exists(image):
141
+ st.sidebar.success(human(os.path.getsize(image)))
142
+ elif image:
143
+ st.sidebar.error('Not found')
144
+
145
+ with st.sidebar.expander('Geometry', expanded=True):
146
+ st.caption('Cluster size and where the data region begins. Everything the '
147
+ 'carver does is aligned to this grid, so it has to be right.')
148
+
149
+ det = st.session_state.get('detect_result')
150
+ ok = bool(image and os.path.exists(image))
151
+
152
+ if st.button('Detect', disabled=not ok, use_container_width=True,
153
+ help='Read the filesystem\'s own parameters from the boot sector'):
154
+ with st.spinner('Reading boot records...'):
155
+ st.session_state['detect_result'] = {'boot': geom.from_boot_records(image)}
156
+ st.rerun()
157
+
158
+ det = st.session_state.get('detect_result')
159
+ if det is not None and det.get('boot'):
160
+ st.success('Found %d boot record(s)' % len(det['boot']))
161
+ for i, bt in enumerate(det['boot']):
162
+ st.caption('**%s** · %s clusters · data @ %d \n_%s_'
163
+ % (bt['fs'], human(bt['cluster_size']), bt['data_offset'], bt['where']))
164
+ if st.button('Use this', key='usebt%d' % i, use_container_width=True):
165
+ st.session_state['cluster'] = int(bt['cluster_size'])
166
+ st.session_state['data_off'] = int(bt['data_offset'])
167
+ st.rerun()
168
+ elif det is not None:
169
+ st.warning('No readable boot record.')
170
+
171
+ if det is not None and not det.get('boot'):
172
+ st.caption('Infer it instead: files start on cluster boundaries, so all '
173
+ 'JPEG headers share one residue modulo the cluster size.')
174
+ gib = st.slider('Sample size (GiB)', 0.5, 32.0, 4.0, 0.5,
175
+ help='Bigger sample = more headers = more certainty. '
176
+ 'Reads scattered windows, not the whole image.')
177
+ if st.button('Scan for alignment', use_container_width=True):
178
+ bar = st.progress(0.0, text='sampling...')
179
+
180
+ def prog(i, n, found):
181
+ bar.progress(i / n, text='window %d/%d · %d headers' % (i, n, found))
182
+
183
+ res = geom.from_alignment(image, gib, progress=prog)
184
+ bar.empty()
185
+ st.session_state['align_result'] = res
186
+ if 'cluster_size' in res:
187
+ st.session_state['cluster'] = int(res['cluster_size'])
188
+ st.session_state['data_off'] = int(res['data_offset'])
189
+ st.rerun()
190
+
191
+ ar = st.session_state.get('align_result')
192
+ if ar:
193
+ if 'error' in ar:
194
+ st.error(ar['error'])
195
+ else:
196
+ st.success(ar['confidence'])
197
+ with st.expander('Evidence'):
198
+ st.caption('Share of sampled headers agreeing on one residue. '
199
+ 'Divisors of the true cluster size also score 1.00, '
200
+ 'so the answer is the largest size that still does.')
201
+ st.dataframe(
202
+ [{'cluster': human(r['cluster']), 'residue': r['residue'],
203
+ 'share': r['fraction']} for r in ar['ladder']],
204
+ hide_index=True, use_container_width=True, height=300)
205
+
206
+ st.divider()
207
+ cluster = st.number_input('Cluster size (bytes)', min_value=512, step=512, key='cluster')
208
+ data_off = st.number_input('Data region offset (bytes)', min_value=0, step=512, key='data_off')
209
+ st.caption('JpegDigger shows these as *blocksize* %d and *start* %d, in 512-byte sectors.'
210
+ % (cluster // 512, data_off // 512))
211
+
212
+ with st.sidebar.expander('Date filter'):
213
+ d_from = st.text_input('From (YYYY-MM-DD)', '')
214
+ d_to = st.text_input('To (YYYY-MM-DD)', '')
215
+
216
+ idx_path = (image + '.idx.json') if image else ''
217
+ idx = read_json(idx_path) if idx_path and os.path.exists(idx_path) else None
218
+
219
+ tab_scan, tab_photos, tab_recover, tab_method = st.tabs(
220
+ ['① Scan', '② Photos', '③ Recover', 'Method'])
221
+
222
+ # ---------------------------------------------------------------- scan tab
223
+
224
+ with tab_scan:
225
+ st.subheader('Index the image')
226
+ st.caption('One sequential pass: catalogues JPEG headers and marks clusters '
227
+ 'that plausibly hold compressed image data. Results are cached, so '
228
+ 'this runs once.')
229
+
230
+ c1, c2 = st.columns([1, 3])
231
+ with c1:
232
+ disabled = not (image and os.path.exists(image)) or running('scan')
233
+ if st.button('Start scan', type='primary', disabled=disabled):
234
+ cmd = sh('index', image, '--cluster', cluster, '--data-offset', data_off,
235
+ '--progress-file', '/tmp/jcarve_index.json')
236
+ if d_from:
237
+ cmd += ['--from', d_from]
238
+ if d_to:
239
+ cmd += ['--to', d_to]
240
+ try:
241
+ os.remove('/tmp/jcarve_index.json')
242
+ except OSError:
243
+ pass
244
+ launch(cmd, 'scan')
245
+ st.rerun()
246
+ if running('scan') and st.button('Cancel'):
247
+ st.session_state['scan'].terminate()
248
+ st.rerun()
249
+
250
+ prog = read_json('/tmp/jcarve_index.json')
251
+ if prog:
252
+ pct = prog.get('pct', 0)
253
+ st.progress(min(pct / 100, 1.0),
254
+ text='%.1f%% · %.1f of %.1f GiB' % (pct, prog.get('gib', 0), prog.get('total_gib', 0)))
255
+ m = st.columns(4)
256
+ m[0].metric('Read rate', '%.0f MiB/s' % prog.get('rate', 0))
257
+ m[1].metric('ETA', '%.0f min' % prog.get('eta_min', 0))
258
+ m[2].metric('Elapsed', '%.0f min' % (prog.get('elapsed', 0) / 60))
259
+ m[3].metric('JPEG headers', '%d' % prog.get('headers', 0))
260
+
261
+ if idx:
262
+ st.divider()
263
+ st.markdown('**Cluster map** — green is data that could be part of a JPEG; '
264
+ 'amber ticks along the top are file headers.')
265
+ img = cluster_map(idx['clean'], idx['headers'], idx['cluster'],
266
+ idx.get('data_offset', 0))
267
+ if img is not None:
268
+ st.image(img, use_container_width=True)
269
+ st.caption('%d headers indexed · %s clusters · data region @ %d'
270
+ % (len(idx['headers']), human(idx['cluster']), idx.get('data_offset', 0)))
271
+
272
+ if running('scan'):
273
+ time.sleep(1.5)
274
+ st.rerun()
275
+
276
+ # ---------------------------------------------------------------- photos tab
277
+
278
+ with tab_photos:
279
+ if not idx:
280
+ st.info('Run a scan first.')
281
+ else:
282
+ rows = []
283
+ for i, h in enumerate(idx['headers']):
284
+ rows.append({
285
+ 'id': i,
286
+ 'date': h.get('date', ''),
287
+ 'model': h.get('model', ''),
288
+ 'pixels': '%d×%d' % (h.get('width', 0), h.get('height', 0)),
289
+ 'megapixels': round(h.get('width', 0) * h.get('height', 0) / 1e6, 1),
290
+ 'declared size': h.get('total_size') or 0,
291
+ 'offset': h['offset'],
292
+ })
293
+ st.subheader('%d JPEG headers found' % len(rows))
294
+ span = sorted(d for d in (exif_day(r['date']) for r in rows) if d)
295
+
296
+ c1, c2, c3, c4 = st.columns([2, 1.5, 1.5, 2])
297
+ min_mp = c1.slider('Minimum megapixels', 0.0, 60.0, 0.0, 0.5,
298
+ help='Filters out thumbnails and video-derived previews.')
299
+ # Both bounds are inclusive and either may be left empty, so From alone
300
+ # means "this day onwards". Unlike the sidebar's scan-time filter these
301
+ # only narrow the view -- the index keeps every header.
302
+ lo = c2.date_input('From', value=None, format='YYYY-MM-DD',
303
+ min_value=span[0], max_value=span[-1],
304
+ help='Inclusive. Leave empty for no lower bound.') if span else None
305
+ hi = c3.date_input('To', value=None, format='YYYY-MM-DD',
306
+ min_value=span[0], max_value=span[-1],
307
+ help='Inclusive. Leave empty for no upper bound.') if span else None
308
+ q = c4.text_input('Filter by date or model contains', '',
309
+ help="Substring match. Dates are EXIF-formatted, so "
310
+ "`2026:05:26` -- use the pickers for ranges.")
311
+
312
+ view, undated = [], 0
313
+ for r in rows:
314
+ if r['megapixels'] < min_mp:
315
+ continue
316
+ if q and q.lower() not in (r['date'] + r['model']).lower():
317
+ continue
318
+ if lo or hi:
319
+ d = exif_day(r['date'])
320
+ if d is None: # can't be placed in time; don't guess
321
+ undated += 1
322
+ continue
323
+ if (lo and d < lo) or (hi and d > hi):
324
+ continue
325
+ view.append(r)
326
+
327
+ if lo and hi and lo > hi:
328
+ st.warning('From is after To — nothing can match.')
329
+
330
+ note = '%d shown' % len(view)
331
+ if undated:
332
+ note += ' · %d hidden for carrying no EXIF date' % undated
333
+ if span:
334
+ note += ' · index spans %s to %s' % (span[0], span[-1])
335
+ st.caption(note)
336
+ st.dataframe(view, use_container_width=True, hide_index=True,
337
+ height=min(460, 45 + 35 * max(len(view), 1)))
338
+ st.session_state['visible_ids'] = [r['id'] for r in view]
339
+
340
+ # ---------------------------------------------------------------- recover tab
341
+
342
+ with tab_recover:
343
+ if not idx:
344
+ st.info('Run a scan first.')
345
+ else:
346
+ st.subheader('Reassemble')
347
+ outdir = st.text_input('Output folder', value=os.path.join(
348
+ os.path.dirname(image) or '.', 'recovered'))
349
+ ids = st.session_state.get('visible_ids', list(range(len(idx['headers']))))
350
+ c1, c2, c3, c4 = st.columns([1, 1, 1, 2])
351
+ limit = c1.number_input('Max photos', 1, 100000, min(len(ids), 25))
352
+ window = c2.number_input('Search window (clusters)', 1000, 4000000, 200000,
353
+ help='How far past a fragment to look for its continuation.')
354
+ jobs = c3.number_input('Parallel jobs', 1, 64, carve.default_jobs(),
355
+ help='Photos are independent, so each runs in its own '
356
+ 'process. Defaults to one per performance core.')
357
+ with c4:
358
+ st.write('')
359
+ st.write('')
360
+ if st.button('Recover %d photo(s)' % min(limit, len(ids)),
361
+ type='primary', disabled=running('rec')):
362
+ try:
363
+ os.remove('/tmp/jcarve_rec.json')
364
+ except OSError:
365
+ pass
366
+ launch(sh('recover', image, outdir,
367
+ '--ids', ','.join(str(i) for i in ids[:int(limit)]),
368
+ '--window', window, '--jobs', jobs,
369
+ '--progress-file', '/tmp/jcarve_rec.json'), 'rec')
370
+ st.rerun()
371
+
372
+ rp = read_json('/tmp/jcarve_rec.json')
373
+ if rp:
374
+ done, total = rp.get('done', 0), rp.get('total', 1)
375
+ nj = rp.get('jobs')
376
+ st.progress(done / max(total, 1),
377
+ text='%d of %d%s' % (done, total,
378
+ ' · %d processes' % nj if nj and nj > 1 else ''))
379
+ res = rp.get('results', [])
380
+ if res:
381
+ full = [r for r in res if r['percent'] >= 99.5]
382
+ frag = [r for r in res if len(r['fragments']) > 1]
383
+ m = st.columns(3)
384
+ m[0].metric('Complete', '%d / %d' % (len(full), len(res)))
385
+ m[1].metric('Needed reassembly', '%d' % len(frag))
386
+ m[2].metric('Mean completeness', '%.1f%%' % (sum(r['percent'] for r in res) / len(res)))
387
+
388
+ st.divider()
389
+ cols = st.columns(4)
390
+ for n, r in enumerate(reversed(res[-24:])):
391
+ with cols[n % 4]:
392
+ try:
393
+ im = Image.open(r['file'])
394
+ im.thumbnail((400, 400))
395
+ st.image(im, use_container_width=True)
396
+ except Exception as e:
397
+ st.warning('no preview')
398
+ badge = '✅' if r['percent'] >= 99.5 else '⚠️'
399
+ st.caption('%s **%.1f%%** · %d fragment(s) \n`%s`'
400
+ % (badge, r['percent'], len(r['fragments']),
401
+ os.path.basename(r['file'])))
402
+ if r['steps']:
403
+ with st.expander('detail'):
404
+ for s in r['steps']:
405
+ st.code(s, language=None)
406
+ mpath = os.path.join(outdir, 'manifest.json')
407
+ if os.path.exists(mpath):
408
+ st.download_button('Download manifest.json', open(mpath, 'rb').read(),
409
+ file_name='manifest.json', mime='application/json')
410
+ if running('rec'):
411
+ time.sleep(1.5)
412
+ st.rerun()
413
+
414
+ # ---------------------------------------------------------------- method tab
415
+
416
+ with tab_method:
417
+ st.subheader('How it decides')
418
+ st.markdown("""
419
+ A carver finds `FFD8FF` and reads forward, assuming the file occupies one
420
+ unbroken run of clusters. When the filesystem scattered it, everything after
421
+ the first fragment belongs to other files — you get a correct top slice and
422
+ grey below.
423
+
424
+ The compressed part of a JPEG is one continuous bitstream, so candidate
425
+ clusters can be tested. Two filters, cheap first:
426
+
427
+ **1 · Bitstream validation** — walk the Huffman codes with no IDCT or colour
428
+ conversion. Reject on an invalid code, or on *quantisation-array overflow*
429
+ (a block holds exactly 64 coefficients; a symbol implying more is proof of
430
+ corruption). This is the DFRWS 2024 method.
431
+
432
+ **2 · Seam continuity** — the decisive test. Decode the candidate's MCUs and
433
+ correlate their DC coefficients against the MCUs *vertically above* them,
434
+ which came from known-good data. Only the genuine continuation lines up.
435
+
436
+ Why the second test is load-bearing: of 300 random wrong continuations on a
437
+ real Sony carve, **72% passed bitstream validation**, because the other photos
438
+ on the card were written by the same encoder with byte-identical Huffman
439
+ tables. Their data is genuinely legal under our decoder. Content is the only
440
+ thing that separates them.
441
+ """)
442
+ st.code("""true continuations : min 0.964 mean 0.983
443
+ wrong candidates : max 0.725 mean 0.148 -> threshold 0.85""", language=None)
444
+ st.caption('Verified end-to-end on a synthetic disk with a JPEG split into '
445
+ 'three fragments: recovered byte-identical, SHA-256 matching.')