forked from OCR-D/core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_workspace.py
More file actions
625 lines (475 loc) · 22.2 KB
/
test_workspace.py
File metadata and controls
625 lines (475 loc) · 22.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
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
# -*- coding: utf-8 -*-
from os import chdir, curdir, walk, stat, chmod, umask
import shutil
import logging
from stat import filemode
from os.path import join, exists, abspath, basename, dirname
from shutil import copyfile, copytree as copytree_, rmtree
from pathlib import Path
from gzip import open as gzip_open
from PIL import Image
import numpy as np
import pytest
from tests.base import (
assets,
main,
FIFOIO
)
from ocrd_models import (
OcrdFile,
OcrdMets
)
from ocrd_models.ocrd_page import parseString
from ocrd_models.ocrd_page import TextRegionType, CoordsType, AlternativeImageType
from ocrd_utils import polygon_mask, xywh_from_polygon, bbox_from_polygon, points_from_polygon
from ocrd_modelfactory import page_from_file
from ocrd.resolver import Resolver
from ocrd.workspace import Workspace
TMP_FOLDER = '/tmp/test-core-workspace'
SRC_METS = assets.path_to('kant_aufklaerung_1784/data/mets.xml')
SAMPLE_FILE_FILEGRP = 'OCR-D-IMG'
SAMPLE_FILE_ID = 'INPUT_0017'
SAMPLE_FILE_URL = join(SAMPLE_FILE_FILEGRP, '%s.tif' % SAMPLE_FILE_ID)
def copytree(src, dst, *args, **kwargs):
rmtree(dst)
copytree_(src, dst, *args, **kwargs)
def count_files(d): return sum(len(files) for _, _, files in walk(d))
@pytest.fixture(name='plain_workspace')
def _fixture_plain_workspace(tmp_path):
resolver = Resolver()
ws = resolver.workspace_from_nothing(directory=tmp_path)
prev_dir = abspath(curdir)
chdir(tmp_path)
yield ws
chdir(prev_dir)
def test_workspace_add_file(plain_workspace):
fpath = str(plain_workspace.directory / 'ID1.tif')
# act
plain_workspace.add_file(
'GRP',
ID='ID1',
mimetype='image/tiff',
content='CONTENT',
pageId=None,
local_filename=fpath
)
f = plain_workspace.mets.find_all_files()[0]
# assert
assert f.ID == 'ID1'
assert f.mimetype == 'image/tiff'
assert f.url == fpath
assert f.local_filename == fpath
assert exists(fpath)
def test_workspace_add_file_basename_no_content(plain_workspace):
plain_workspace.add_file('GRP', ID='ID1', mimetype='image/tiff', pageId=None)
f = next(plain_workspace.mets.find_files())
# assert
assert f.url == None
def test_workspace_add_file_binary_content(plain_workspace):
fpath = join(plain_workspace.directory, 'subdir', 'ID1.tif')
plain_workspace.add_file('GRP', ID='ID1', content=b'CONTENT', local_filename=fpath, url='http://foo/bar', pageId=None)
# assert
assert exists(fpath)
def test_workspacec_add_file_content_wo_local_filename(plain_workspace):
# act
with pytest.raises(Exception) as fn_exc:
plain_workspace.add_file('GRP', ID='ID1', content=b'CONTENT', pageId='foo1234')
assert "'content' was set but no 'local_filename'" in str(fn_exc.value)
def test_workspacec_add_file_content_wo_pageid(plain_workspace):
# act
with pytest.raises(ValueError) as val_err:
plain_workspace.add_file('GRP', ID='ID1', content=b'CONTENT', local_filename='foo')
assert "workspace.add_file must be passed a 'pageId' kwarg, even if it is None." in str(val_err.value)
def test_workspace_str(plain_workspace):
# act
plain_workspace.save_mets()
plain_workspace.reload_mets()
# assert
ws_dir = plain_workspace.directory
assert str(plain_workspace) == 'Workspace[directory=%s, baseurl=None, file_groups=[], files=[]]' % ws_dir
def test_workspace_backup(plain_workspace):
# act
plain_workspace.automatic_backup = True
plain_workspace.save_mets()
plain_workspace.reload_mets()
# TODO
# changed test semantics
assert exists(join(plain_workspace.directory, '.backup'))
def _url_to_file(the_path):
dummy_mets = OcrdMets.empty_mets()
dummy_url = abspath(the_path)
return dummy_mets.add_file('DEPRECATED', ID=Path(dummy_url).name, url=dummy_url)
def test_download_very_self_file(plain_workspace):
# arrange with some dummy stuff
the_file = _url_to_file(abspath(__file__))
# act
fn = plain_workspace.download_file(the_file)
# assert
assert fn, join('DEPRECATED', basename(__file__))
def test_download_url_without_baseurl_raises_exception(tmp_path):
# arrange
dst_mets = join(tmp_path, 'mets.xml')
copyfile(SRC_METS, dst_mets)
ws1 = Resolver().workspace_from_url(dst_mets)
the_file = _url_to_file(SAMPLE_FILE_URL)
# act
with pytest.raises(Exception) as exc:
ws1.download_file(the_file)
# assert exception message contents
assert "Already tried prepending baseurl '%s'" % str(tmp_path) in str(exc.value)
def test_download_url_with_baseurl(tmp_path):
# arrange
dst_mets = join(tmp_path, 'mets.xml')
copyfile(SRC_METS, dst_mets)
tif_dir = tmp_path / 'OCR-D-IMG'
tif_dir.mkdir()
dst_tif = join(tmp_path, SAMPLE_FILE_URL)
copyfile(join(dirname(SRC_METS), SAMPLE_FILE_URL), dst_tif)
ws1 = Resolver().workspace_from_url(dst_mets, src_baseurl=dirname(SRC_METS))
the_file = _url_to_file(dst_tif)
# act
# TODO
# semantics changed from .download_url to .download_file
# and from context path 'DEPRECATED' to 'OCR-D-IMG'
f = Path(ws1.download_file(the_file).local_filename)
# assert
assert str(f).endswith(join('OCR-D-IMG', '%s.tif' % SAMPLE_FILE_ID))
assert Path(ws1.directory, f).exists()
def test_from_url_dst_dir_download(plain_workspace):
"""
https://github.com/OCR-D/core/issues/319
"""
ws_dir = join(plain_workspace.directory, 'non-existing-for-good-measure')
# Create a relative path to trigger #319
src_path = str(Path(assets.path_to('kant_aufklaerung_1784/data/mets.xml')))
plain_workspace.resolver.workspace_from_url(src_path, dst_dir=ws_dir, download=True)
# assert
assert Path(ws_dir, 'mets.xml').exists() # sanity check, mets.xml must exist
assert Path(ws_dir, 'OCR-D-GT-PAGE/PAGE_0017_PAGE.xml').exists()
def test_superfluous_copies_in_ws_dir(tmp_path):
"""
https://github.com/OCR-D/core/issues/227
"""
# arrange
src_path = assets.path_to('SBB0000F29300010000/data/mets_one_file.xml')
dst_path = join(tmp_path, 'mets.xml')
copyfile(src_path, dst_path)
ws1 = Workspace(Resolver(), tmp_path)
# assert directory files
assert count_files(tmp_path) == 1
# act
for file in ws1.mets.find_all_files():
ws1.download_file(file)
# assert
assert count_files(tmp_path) == 2
assert exists(join(tmp_path, 'OCR-D-IMG/FILE_0005_IMAGE.tif'))
@pytest.fixture(name='sbb_data_tmp')
def _fixture_sbb_data_tmp(tmp_path):
copytree(assets.path_to('SBB0000F29300010000/data'), str(tmp_path))
yield str(tmp_path)
@pytest.fixture(name='sbb_data_workspace')
def _fixture_sbb_data(sbb_data_tmp):
resolver = Resolver()
workspace = Workspace(resolver, directory=sbb_data_tmp)
yield workspace
def test_remove_file_not_existing_raises_error(sbb_data_workspace):
# act
with pytest.raises(FileNotFoundError) as fnf_err:
sbb_data_workspace.remove_file('non-existing-id')
# assert
assert "not found" in str(fnf_err.value)
def test_remove_file_force(sbb_data_workspace):
"""Enforce removal of non-existing-id doesn't yield any error
but also returns no ocrd-file identifier"""
# TODO check semantics - can a non-existend thing be removed?
assert not sbb_data_workspace.remove_file('non-existing-id', force=True)
# should also succeed
sbb_data_workspace.overwrite_mode = True
assert not sbb_data_workspace.remove_file('non-existing-id', force=False)
def test_remove_file_remote_not_available_raises_exception(plain_workspace):
plain_workspace.add_file('IMG', ID='page1_img', mimetype='image/tiff', url='http://remote', pageId=None)
with pytest.raises(Exception) as not_avail_exc:
plain_workspace.remove_file('page1_img')
assert "not locally available" in str(not_avail_exc.value)
def test_remove_file_remote(plain_workspace):
# act
plain_workspace.add_file('IMG', ID='page1_img', mimetype='image/tiff', url='http://remote', pageId=None)
# must succeed because removal is enforced
assert plain_workspace.remove_file('page1_img', force=True)
# TODO check returned value
# should also "succeed", because overwrite_mode is set which also sets 'force' to 'True'
plain_workspace.overwrite_mode = True
assert not plain_workspace.remove_file('page1_img')
def test_rename_file_group(tmp_path):
# arrange
copytree(assets.path_to('kant_aufklaerung_1784-page-region-line-word_glyph/data'), str(tmp_path))
workspace = Workspace(Resolver(), directory=str(tmp_path))
# before act
# TODO clear semantics
# requires rather odd additional path-setting because root path from
# workspace is not propagated - works only if called inside workspace
# which can be achieved with pushd_popd functionalities
ocrd_file = next(workspace.mets.find_files(ID='OCR-D-GT-SEG-WORD_0001'))
relative_name = ocrd_file.local_filename
ocrd_file.local_filename = join(tmp_path, relative_name)
pcgts_before = page_from_file(ocrd_file)
# before assert
assert pcgts_before.get_Page().imageFilename == 'OCR-D-IMG/OCR-D-IMG_0001.tif'
# act
workspace.rename_file_group('OCR-D-IMG', 'FOOBAR')
next_ocrd_file = next(workspace.mets.find_files(ID='OCR-D-GT-SEG-WORD_0001'))
next_ocrd_file.local_filename = join(tmp_path, relative_name)
pcgts_after = page_from_file(next_ocrd_file)
# assert
assert pcgts_after.get_Page().imageFilename == 'FOOBAR/FOOBAR_0001.tif'
assert Path(tmp_path / 'FOOBAR/FOOBAR_0001.tif').exists()
assert not Path('OCR-D-IMG/OCR-D-IMG_0001.tif').exists()
assert workspace.mets.get_physical_pages(for_fileIds=['OCR-D-IMG_0001']) == [None]
assert workspace.mets.get_physical_pages(for_fileIds=['FOOBAR_0001']) == ['phys_0001']
def test_remove_file_group_invalid_raises_exception(sbb_data_workspace):
with pytest.raises(Exception) as no_fg_exc:
# should fail
sbb_data_workspace.remove_file_group('I DO NOT EXIST')
assert "No such fileGrp" in str(no_fg_exc.value)
def test_remove_file_group_force(sbb_data_workspace):
# TODO
# check function and tests semantics
# should succeed
assert not sbb_data_workspace.remove_file_group('I DO NOT EXIST', force=True)
# should also succeed
sbb_data_workspace.overwrite_mode = True
assert not sbb_data_workspace.remove_file_group('I DO NOT EXIST', force=False)
def test_remove_file_group_rmdir(sbb_data_tmp, sbb_data_workspace):
assert exists(join(sbb_data_tmp, 'OCR-D-IMG'))
sbb_data_workspace.remove_file_group('OCR-D-IMG', recursive=True)
assert not exists(join(sbb_data_tmp, 'OCR-D-IMG'))
def test_remove_file_group_flat(plain_workspace):
"""
https://github.com/OCR-D/core/issues/728
"""
# act
added_res = plain_workspace.add_file('FOO', ID='foo', mimetype='foo/bar', local_filename='file.ext', content='foo', pageId=None).url
# requires additional prepending of current path because not pushd_popd-magic at work
added_path = Path(join(plain_workspace.directory, added_res))
# assert
assert added_path.exists()
plain_workspace.remove_file_group('FOO', recursive=True)
@pytest.fixture(name='kant_complex_workspace')
def _fixture_kant_complex(tmp_path):
copytree(assets.path_to('kant_aufklaerung_1784-complex/data'), str(tmp_path))
yield Workspace(Resolver, directory=tmp_path)
def test_remove_file_page_recursive(kant_complex_workspace):
assert len(kant_complex_workspace.mets.find_all_files()) == 119
kant_complex_workspace.remove_file('OCR-D-OCR-OCRO-fraktur-SEG-LINE-tesseract-ocropy-DEWARP_0001', page_recursive=True, page_same_group=False, keep_file=True)
assert len(kant_complex_workspace.mets.find_all_files()) == 83
kant_complex_workspace.remove_file('PAGE_0017_ALTO', page_recursive=True)
def test_remove_file_page_recursive_keep_file(kant_complex_workspace):
before = count_files(kant_complex_workspace.directory)
kant_complex_workspace.remove_file('OCR-D-IMG-BINPAGE-sauvola_0001', page_recursive=True, page_same_group=False, force=True)
after = count_files(kant_complex_workspace.directory)
assert after == (before - 2), '2 files deleted'
def test_remove_file_page_recursive_same_group(kant_complex_workspace):
before = count_files(kant_complex_workspace.directory)
kant_complex_workspace.remove_file('OCR-D-IMG-BINPAGE-sauvola_0001', page_recursive=True, page_same_group=True, force=False)
after = count_files(kant_complex_workspace.directory)
assert after == before - 1, '1 file deleted'
def test_download_to_directory_from_workspace_download_file(plain_workspace):
"""
https://github.com/OCR-D/core/issues/342
"""
f1 = plain_workspace.add_file('IMG', ID='page1_img', mimetype='image/tiff', local_filename='test.tif', content='', pageId=None)
f2 = plain_workspace.add_file('GT', ID='page1_gt', mimetype='text/xml', local_filename='test.xml', content='', pageId=None)
assert f1.url == 'test.tif'
assert f2.url == 'test.xml'
# these should be no-ops
plain_workspace.download_file(f1)
plain_workspace.download_file(f2)
assert f1.url == 'test.tif'
assert f2.url == 'test.xml'
def test_save_image_file_invalid_mimetype_raises_exception(plain_workspace):
img = Image.new('RGB', (1000, 1000))
# act raise
with pytest.raises(KeyError) as key_exc:
plain_workspace.save_image_file(img, 'page1_img', 'IMG', 'page1', 'ceci/nest/pas/une/mimetype')
assert "'ceci/nest/pas/une/mimetype'" == str(key_exc.value)
def test_save_image_file(plain_workspace):
# arrange
img = Image.new('RGB', (1000, 1000))
# act
assert plain_workspace.save_image_file(img, 'page1_img', 'IMG', 'page1', 'image/jpeg')
assert exists(join(plain_workspace.directory, 'IMG', 'page1_img.jpg'))
# should succeed
assert plain_workspace.save_image_file(img, 'page1_img', 'IMG', 'page1', 'image/jpeg', force=True)
# should also succeed
plain_workspace.overwrite_mode = True
assert plain_workspace.save_image_file(img, 'page1_img', 'IMG', 'page1', 'image/jpeg')
@pytest.fixture(name='workspace_kant_aufklaerung')
def _fixture_workspace_kant_aufklaerung(tmp_path):
copytree(assets.path_to('kant_aufklaerung_1784/data/'), str(tmp_path))
resolver = Resolver()
ws = resolver.workspace_from_url(join(tmp_path, 'mets.xml'), src_baseurl=tmp_path)
prev_dir = abspath(curdir)
chdir(tmp_path)
yield ws
chdir(prev_dir)
def test_resolve_image_exif(workspace_kant_aufklaerung):
tif_path = 'OCR-D-IMG/INPUT_0017.tif'
# act
exif = workspace_kant_aufklaerung.resolve_image_exif(tif_path)
# assert
assert exif.compression == 'jpeg'
assert exif.width == 1457
def test_resolve_image_as_pil(workspace_kant_aufklaerung):
img = workspace_kant_aufklaerung._resolve_image_as_pil('OCR-D-IMG/INPUT_0017.tif')
assert img.width == 1457
img = workspace_kant_aufklaerung._resolve_image_as_pil('OCR-D-IMG/INPUT_0017.tif', coords=([100, 100], [50, 50]))
assert img.width == 50
@pytest.fixture(name='workspace_gutachten_data')
def _fixture_workspace_gutachten_data(tmp_path):
copytree(assets.path_to('gutachten/data'), str(tmp_path))
resolver = Resolver()
ws = resolver.workspace_from_url(join(str(tmp_path), 'mets.xml'))
prev_path = abspath(curdir)
chdir(tmp_path)
yield ws
chdir(prev_path)
def test_image_from_page_basic(workspace_gutachten_data):
# arrange
with open(assets.path_to('gutachten/data/TEMP1/PAGE_TEMP1.xml'), 'r') as f:
pcgts = parseString(f.read().encode('utf8'), silence=True)
# act + assert
_, info, _ = workspace_gutachten_data.image_from_page(pcgts.get_Page(), page_id='PHYS_0017', feature_selector='clipped', feature_filter='cropped')
assert info['features'] == 'binarized,clipped'
_, info, _ = workspace_gutachten_data.image_from_page(pcgts.get_Page(), page_id='PHYS_0017')
assert info['features'] == 'binarized,clipped'
@pytest.fixture(name='workspace_sample_features')
def _fixture_workspace_sample_features(tmp_path):
copytree('tests/data/sample-features', str(tmp_path))
resolver = Resolver()
ws = resolver.workspace_from_url(join(str(tmp_path), 'mets.xml'))
prev_path = abspath(curdir)
chdir(tmp_path)
yield ws
chdir(prev_path)
def test_image_feature_selectoro(workspace_sample_features):
# arrange
with open(join(str(workspace_sample_features.directory), 'image_features.page.xml'), 'r') as f:
pcgts = parseString(f.read().encode('utf8'))
# richest feature set is not last:
_, info, _ = workspace_sample_features.image_from_page(pcgts.get_Page(), page_id='page1', feature_selector='dewarped')
# recropped because foo4 contains cropped+deskewed but not recropped yet:
assert info['features'] == 'cropped,dewarped,binarized,despeckled,deskewed'
# richest feature set is also last:
_, info, _ = workspace_sample_features.image_from_page(pcgts.get_Page(), page_id='page1', feature_selector='dewarped', feature_filter='binarized')
# no deskewing here, thus no recropping:
assert info['features'] == 'cropped,dewarped,despeckled'
def test_deskewing(plain_workspace):
#from ocrd_utils import initLogging, setOverrideLogLevel
#setOverrideLogLevel('DEBUG')
size = (3000, 4000)
poly = [[1403, 2573], [1560, 2573], [1560, 2598], [2311, 2598], [2311, 2757],
[2220, 2757], [2220, 2798], [2311, 2798], [2311, 2908], [1403, 2908]]
xywh = xywh_from_polygon(poly)
bbox = bbox_from_polygon(poly)
skew = 4.625
image = Image.new('L', size)
image = polygon_mask(image, poly)
#image.show(title='image')
pixels = np.count_nonzero(np.array(image) > 0)
name = 'foo0'
assert plain_workspace.save_image_file(image, name, 'IMG')
pcgts = page_from_file(next(plain_workspace.mets.find_files(ID=name)))
page = pcgts.get_Page()
region = TextRegionType(id='nonrect',
Coords=CoordsType(points=points_from_polygon(poly)),
orientation=-skew)
page.add_TextRegion(region)
page_image, page_coords, _ = plain_workspace.image_from_page(page, '')
#page_image.show(title='page_image')
assert list(image.getdata()) == list(page_image.getdata())
assert np.all(page_coords['transform'] == np.eye(3))
reg_image, reg_coords = plain_workspace.image_from_segment(region, page_image, page_coords,
feature_filter='deskewed', fill=0)
assert list(image.crop(bbox).getdata()) == list(reg_image.getdata())
assert reg_image.width == xywh['w'] == 908
assert reg_image.height == xywh['h'] == 335
assert reg_coords['transform'][0, 2] == -xywh['x']
assert reg_coords['transform'][1, 2] == -xywh['y']
# same fg after cropping to minimal bbox
reg_pixels = np.count_nonzero(np.array(reg_image) > 0)
assert pixels == reg_pixels
# now with deskewing (test for size after recropping)
reg_image, reg_coords = plain_workspace.image_from_segment(region, page_image, page_coords, fill=0)
#reg_image.show(title='reg_image')
assert reg_image.width == 932 > xywh['w']
assert reg_image.height == 382 > xywh['h']
assert reg_coords['transform'][0, 1] != 0
assert reg_coords['transform'][1, 0] != 0
assert 'deskewed' in reg_coords['features']
# same fg after cropping to minimal bbox (roughly - due to aliasing)
reg_pixels = np.count_nonzero(np.array(reg_image) > 0)
assert np.abs(pixels - reg_pixels) / pixels < 0.005
reg_array = np.array(reg_image) > 0
# now via AlternativeImage
path = plain_workspace.save_image_file(reg_image, region.id + '_img', 'IMG')
region.add_AlternativeImage(AlternativeImageType(filename=path, comments=reg_coords['features']))
logger_capture = FIFOIO(256)
logger_handler = logging.StreamHandler(logger_capture)
#logger_handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_TIMEFMT))
logger = logging.getLogger('ocrd_utils.crop_image')
logger.addHandler(logger_handler)
reg_image2, reg_coords2 = plain_workspace.image_from_segment(region, page_image, page_coords, fill=0)
#reg_image2.show(title='reg_image2')
logger_output = logger_capture.getvalue()
logger_capture.close()
assert logger_output == ''
assert reg_image2.width == reg_image.width
assert reg_image2.height == reg_image.height
assert np.allclose(reg_coords2['transform'], reg_coords['transform'])
assert reg_coords2['features'] == reg_coords['features']
# same fg after cropping to minimal bbox (roughly - due to aliasing)
reg_pixels2 = np.count_nonzero(np.array(reg_image) > 0)
assert reg_pixels2 == reg_pixels
reg_array2 = np.array(reg_image2) > 0
assert 0.98 < np.sum(reg_array == reg_array2) / reg_array.size <= 1.0
def test_downsample_16bit_image(plain_workspace):
# arrange image
img_path = join(plain_workspace.directory, '16bit.tif')
with gzip_open(join(dirname(__file__), 'data/OCR-D-IMG_APBB_Mitteilungen_62.0002.tif.gz'), 'rb') as gzip_in:
with open(img_path, 'wb') as tif_out:
tif_out.write(gzip_in.read())
# act
plain_workspace.add_file('IMG', ID='foo', url=img_path, mimetype='image/tiff', pageId=None)
# assert
pil_before = Image.open(img_path)
assert pil_before.mode == 'I;16'
pil_after = plain_workspace._resolve_image_as_pil(img_path)
assert pil_after.mode == 'L'
def test_mets_permissions(plain_workspace):
plain_workspace.save_mets()
mets_path = join(plain_workspace.directory, 'mets.xml')
mask = umask(0)
umask(mask)
assert (stat(mets_path).st_mode) == 0o100664 & ~mask
chmod(mets_path, 0o777)
plain_workspace.save_mets()
assert filemode(stat(mets_path).st_mode) == '-rwxrwxrwx'
def test_merge(tmp_path):
# arrange
dst_path1 = tmp_path / 'kant_aufklaerung'
dst_path1.mkdir()
dst_path2 = tmp_path / 'sbb'
dst_path2.mkdir()
copytree(assets.path_to('kant_aufklaerung_1784/data'), dst_path1)
copytree(assets.path_to('SBB0000F29300010000/data'), dst_path2)
ws1 = Workspace(Resolver(), dst_path1)
ws2 = Workspace(Resolver(), dst_path2)
# assert number of files before
assert len(ws1.mets.find_all_files()) == 6
# act
ws1.merge(ws2)
# assert
assert len(ws1.mets.find_all_files()) == 41
assert exists(join(dst_path1, 'OCR-D-IMG/FILE_0001_IMAGE.tif'))
if __name__ == '__main__':
main(__file__)