This repository has been archived by the owner on Dec 18, 2019. It is now read-only.
/
__init__.py
3563 lines (2989 loc) · 125 KB
/
__init__.py
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Paperwork - Using OCR to grep dead trees the easy way
# Copyright (C) 2012-2014 Jerome Flesch
# Copyright (C) 2012 Sebastien Maccagnoni-Munch
#
# Paperwork is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Paperwork is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Paperwork. If not, see <http://www.gnu.org/licenses/>.
import gc
import logging
import os
import sys
import threading
import gettext
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import GLib
from gi.repository import Gio
from gi.repository import GObject
from gi.repository import Gtk
import pillowfight
from paperwork_backend import docexport
from paperwork_backend import docimport
from paperwork_backend.common.page import BasicPage
from paperwork_backend.common.page import DummyPage
from paperwork_backend.docsearch import DocSearch
from paperwork_backend.docsearch import DummyDocSearch
from paperwork.frontend.aboutdialog import AboutDialog
from paperwork.frontend import activation
from paperwork.frontend.diag import DiagDialog
from paperwork.frontend.mainwindow.docs import DocList
from paperwork.frontend.mainwindow.docs import DocPropertiesPanel
from paperwork.frontend.mainwindow.docs import sort_documents_by_date
from paperwork.frontend.mainwindow.pages import PageDrawer
from paperwork.frontend.mainwindow.pages import PageDropHandler
from paperwork.frontend.mainwindow.pages import JobFactoryImgProcesser
from paperwork.frontend.mainwindow.pages import JobFactoryPageBoxesLoader
from paperwork.frontend.mainwindow.pages import JobFactoryPageImgLoader
from paperwork.frontend.mainwindow.pages import SimplePageDrawer
from paperwork.frontend.mainwindow.scan import ScanWorkflow
from paperwork.frontend.mainwindow.scan import MultiAnglesScanWorkflowDrawer
from paperwork.frontend.mainwindow.scan import SingleAngleScanWorkflowDrawer
from paperwork.frontend.multiscan import MultiscanDialog
from paperwork.frontend.searchdialog import SearchDialog
from paperwork.frontend.settingswindow import SettingsWindow
from paperwork.frontend.util import connect_actions
from paperwork.frontend.util import load_cssfile
from paperwork.frontend.util import load_image
from paperwork.frontend.util import load_uifile
from paperwork.frontend.util import sizeof_fmt
from paperwork.frontend.util.actions import SimpleAction
from paperwork.frontend.util.config import get_scanner
from paperwork.frontend.util.dialog import ask_confirmation
from paperwork.frontend.util.dialog import popup_no_scanner_found
from paperwork.frontend.util.canvas import Canvas
from paperwork.frontend.util.canvas.animations import SpinnerAnimation
from paperwork.frontend.util.canvas.drawers import Centerer
from paperwork.frontend.util.canvas.drawers import PillowImageDrawer
from paperwork.frontend.util.canvas.drawers import ProgressBarDrawer
from paperwork.frontend.util.canvas.drawers import TextDrawer
from paperwork.frontend.util.jobs import Job
from paperwork.frontend.util.jobs import JobFactory
from paperwork.frontend.util.jobs import JobScheduler
from paperwork.frontend.util import renderer
_ = gettext.gettext
logger = logging.getLogger(__name__)
__version__ = '1.0.6'
# during tests, we have multiple instatiations of MainWindow(), but we must
# not register the app again
g_must_init_app = True
def check_scanner(main_win, config):
if config['scanner_devid'].value is not None:
return True
main_win.actions['open_settings'][1].do()
return False
def set_widget_state(widgets, state, cond=lambda widget: True):
for widget in widgets:
if cond(widget):
if isinstance(widget, Gio.Action):
widget.set_enabled(state)
else:
widget.set_sensitive(state)
class JobIndexLoader(Job):
"""
Reload the doc index
"""
__gsignals__ = {
'index-loading-start': (GObject.SignalFlags.RUN_LAST, None, ()),
'index-loading-progression': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_FLOAT,
GObject.TYPE_STRING)),
'index-loading-end': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_PYOBJECT, )),
}
can_stop = True
priority = 100
def __init__(self, factory, job_id, config):
Job.__init__(self, factory, job_id)
self.__config = config
self.started = False
self.done = False
def __progress_cb(self, progression, total, step, doc=None):
"""
Update the main progress bar
"""
if not self.can_run:
raise StopIteration()
if progression % 50 != 0:
return
txt = None
if step == DocSearch.INDEX_STEP_LOADING:
txt = _('Loading ...')
else:
assert() # unknown progression type
txt = ""
if doc is not None:
txt += (" (%s)" % (doc.name))
self.emit('index-loading-progression', float(progression) / total, txt)
def do(self):
if self.done:
return
self.can_run = True
if not self.started:
self.emit('index-loading-start')
self.started = True
try:
if (self.__config.CURRENT_INDEX_VERSION !=
self.__config['index_version'].value):
logger.info("Index structure is obsolete."
" Must rebuild from scratch")
docsearch = DocSearch(self.__config['workdir'].value)
# we destroy the index to force its rebuilding
docsearch.destroy_index()
self.__config['index_version'].value = \
self.__config.CURRENT_INDEX_VERSION
self.__config.write()
if not self.can_run:
return
docsearch = DocSearch(self.__config['workdir'].value)
docsearch.set_language(self.__config['ocr_lang'].value)
docsearch.reload_index(progress_cb=self.__progress_cb)
if not self.can_run:
return
self.emit('index-loading-end', docsearch)
self.done = True
except StopIteration:
logger.info("Index loading interrupted")
def stop(self, will_resume=False):
if not will_resume and not self.done:
self.emit('index-loading-end', None)
self.done = True
self.can_run = False
GObject.type_register(JobIndexLoader)
class JobFactoryIndexLoader(JobFactory):
def __init__(self, main_window, config):
JobFactory.__init__(self, "IndexLoader")
self.__main_window = main_window
self.__config = config
def make(self):
job = JobIndexLoader(self, next(self.id_generator), self.__config)
job.connect('index-loading-start',
lambda job: GLib.idle_add(
self.__main_window.on_index_loading_start_cb, job))
job.connect('index-loading-progression',
lambda job, progression, txt:
GLib.idle_add(self.__main_window.set_progression,
job, progression, txt))
job.connect('index-loading-end',
lambda loader, docsearch: GLib.idle_add(
self.__main_window.on_index_loading_end_cb, loader,
docsearch
))
return job
class JobDocExaminer(Job):
"""
Look for modified documents
"""
__gsignals__ = {
'doc-examination-start': (GObject.SignalFlags.RUN_LAST, None, ()),
'doc-examination-progression': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_FLOAT,
GObject.TYPE_STRING)),
'doc-examination-end': (GObject.SignalFlags.RUN_LAST, None, ()),
}
can_stop = False
priority = 50
def __init__(self, factory, id, config, docsearch):
Job.__init__(self, factory, id)
self.__config = config
self.docsearch = docsearch
self.done = False
self.started = False
self.labels = set()
def __progress_cb(self, progression, total, step, doc=None):
"""
Update the main progress bar
"""
if not self.can_run:
raise StopIteration()
if progression % 10 != 0:
return
txt = None
if step == DocSearch.INDEX_STEP_CHECKING:
txt = _('Checking ...')
else:
assert() # unknown progression type
txt = ""
if doc is not None:
txt += (" (%s)" % (str(doc)))
self.emit('doc-examination-progression',
float(progression) / total, txt)
def do(self):
if self.done:
return
self.can_run = True
if not self.started:
self.emit('doc-examination-start')
self.started = True
self.new_docs = set() # documents
self.docs_changed = set() # documents
self.docs_missing = set() # document ids
try:
doc_examiner = self.docsearch.get_doc_examiner()
doc_examiner.examine_rootdir(
self.__on_new_doc,
self.__on_doc_changed,
self.__on_doc_missing,
self.__on_doc_unchanged,
self.__progress_cb)
self.emit('doc-examination-end')
self.done = True
except StopIteration:
logger.info("Document examination interrupted")
def stop(self, will_resume=False):
self.can_run = False
if not will_resume:
self.emit('doc-examination-end')
def __on_new_doc(self, doc):
self.new_docs.add(doc)
self.labels.update(doc.labels)
def __on_doc_changed(self, doc):
self.docs_changed.add(doc)
self.labels.update(doc.labels)
def __on_doc_missing(self, docid):
self.docs_missing.add(docid)
def __on_doc_unchanged(self, doc):
self.labels.update(doc.labels)
GObject.type_register(JobDocExaminer)
class JobFactoryDocExaminer(JobFactory):
def __init__(self, main_win, config):
JobFactory.__init__(self, "DocExaminer")
self.__main_win = main_win
self.__config = config
def make(self, docsearch):
job = JobDocExaminer(self, next(self.id_generator),
self.__config, docsearch)
job.connect(
'doc-examination-start',
lambda job: GLib.idle_add(
self.__main_win.on_doc_examination_start_cb, job))
job.connect(
'doc-examination-progression',
lambda job, progression, txt: GLib.idle_add(
self.__main_win.set_progression, job, progression, txt))
job.connect(
'doc-examination-end',
lambda job: GLib.idle_add(
self.__main_win.on_doc_examination_end_cb, job))
return job
class JobIndexUpdater(Job):
"""
Update the index
"""
__gsignals__ = {
'index-update-start': (GObject.SignalFlags.RUN_LAST, None, ()),
'index-update-progression': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_FLOAT,
GObject.TYPE_STRING)),
'index-update-interrupted': (GObject.SignalFlags.RUN_LAST, None, ()),
'index-update-write': (GObject.SignalFlags.RUN_LAST, None, ()),
'index-update-end': (GObject.SignalFlags.RUN_LAST, None, ()),
}
can_stop = True
priority = 15
def __init__(self, factory, id, config, docsearch,
new_docs=set(), upd_docs=set(), del_docs=set(),
optimize=True):
Job.__init__(self, factory, id)
self.__docsearch = docsearch
self.__config = config
self.__condition = threading.Condition()
self.new_docs = new_docs
self.upd_docs = upd_docs
self.del_docs = del_docs
self.update_only = len(new_docs) == 0 and len(del_docs) == 0
self.optimize = optimize
self.index_updater = None
self.total = (len(self.new_docs) + len(self.upd_docs) +
len(self.del_docs))
self.progression = float(0)
def __wakeup(self):
self.__condition.acquire()
self.__condition.notify_all()
self.__condition.release()
def __wait(self):
# HACK(Jflesch): Make sure the signal is actually taken care
# of before continuing. Otherwise, on slow computers, the
# progress bar may not be updated at all until the index
# update is finished
self.__condition.acquire()
GLib.idle_add(self.__wakeup)
self.__condition.wait()
self.__condition.release()
def do(self):
# keep in mind that we may have been interrupted and then called back
# later
self.can_run = True
total = len(self.new_docs) + len(self.upd_docs) + len(self.del_docs)
if total <= 0 and not self.optimize and self.index_updater is None:
return
if self.index_updater is None:
self.emit('index-update-start')
self.index_updater = self.__docsearch.get_index_updater(
optimize=self.optimize)
if not self.can_run:
self.emit('index-update-interrupted')
return
docs = [
(_("Indexing new document ..."), self.new_docs,
self.index_updater.add_doc),
(_("Reindexing modified document ..."), self.upd_docs,
self.index_updater.upd_doc),
(_("Removing deleted document from index ..."), self.del_docs,
self.index_updater.del_doc),
]
for (op_name, doc_bunch, op) in docs:
try:
while True:
if not self.can_run:
self.emit('index-update-interrupted')
return
doc = doc_bunch.pop()
self.emit('index-update-progression',
(self.progression * 0.75) / self.total,
"%s (%s)" % (op_name, str(doc)))
self.__wait()
op(doc)
self.progression += 1
except KeyError:
pass
if not self.can_run:
self.emit('index-update-interrupted')
return
self.emit('index-update-progression', 0.75,
_("Writing index ..."))
self.emit('index-update-write')
self.__wait()
self.index_updater.commit()
self.index_updater = None
self.optimize = False
self.emit('index-update-progression', 1.0, "")
self.emit('index-update-end')
def stop(self, will_resume=False):
self.can_run = False
if not will_resume:
self.connect('index-update-interrupted',
lambda job:
GLib.idle_add(self.index_updater.cancel))
GObject.type_register(JobIndexUpdater)
class JobFactoryIndexUpdater(JobFactory):
def __init__(self, main_win, config):
JobFactory.__init__(self, "IndexUpdater")
self.__main_win = main_win
self.__config = config
def make(self, docsearch,
new_docs=set(), upd_docs=set(), del_docs=set(),
optimize=True, reload_list=False):
job = JobIndexUpdater(self, next(self.id_generator), self.__config,
docsearch, new_docs, upd_docs, del_docs,
optimize)
job.connect('index-update-start',
lambda updater:
GLib.idle_add(self.__main_win.on_index_update_start_cb,
updater))
job.connect('index-update-progression',
lambda updater, progression, txt:
GLib.idle_add(self.__main_win.set_progression, updater,
progression, txt))
job.connect('index-update-write',
lambda updater:
GLib.idle_add(self.__main_win.on_index_update_write_cb,
updater))
job.connect('index-update-end',
lambda updater:
GLib.idle_add(self.__main_win.on_index_update_end_cb,
updater))
if reload_list:
job.connect('index-update-end',
lambda updater:
GLib.idle_add(self.__main_win.refresh_doc_list))
return job
class JobDocSearcher(Job):
"""
Search the documents
"""
__gsignals__ = {
'search-start': (GObject.SignalFlags.RUN_LAST, None, ()),
# user made a typo
'search-invalid': (GObject.SignalFlags.RUN_LAST, None, ()),
# array of documents
'search-results': (GObject.SignalFlags.RUN_LAST, None,
# XXX(Jflesch): TYPE_STRING would turn the Unicode
# object into a string object
(GObject.TYPE_PYOBJECT,
GObject.TYPE_PYOBJECT,)),
# array of suggestions
'search-suggestions': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_PYOBJECT,)),
}
can_stop = True
priority = 500
def __init__(self, factory, id, config, docsearch, sort_func,
search_type, search):
Job.__init__(self, factory, id)
self.search = search
self.__search_type = search_type
self.__docsearch = docsearch
self.__sort_func = sort_func
self.__config = config
def do(self):
self.can_run = True
self._wait(0.5)
if not self.can_run:
return
self.emit('search-start')
try:
logger.info("Searching: [%s]" % self.search)
documents = self.__docsearch.find_documents(
self.search,
search_type=self.__search_type)
except Exception as exc:
logger.error("Invalid search: [%s]" % self.search)
logger.error("Exception was: %s: %s" % (type(exc), str(exc)))
logger.exception(exc)
self.emit('search-invalid')
return
if not self.can_run:
return
if self.search == u"":
# when no specific search has been done, the sorting is always
# the same
sort_documents_by_date(documents)
else:
self.__sort_func(documents)
self.emit('search-results', self.search, documents)
if not self.can_run:
logger.info("Search cancelled. Won't look for suggestions")
return
suggestions = self.__docsearch.find_suggestions(self.search)
self.emit('search-suggestions', suggestions)
def stop(self, will_resume=False):
self.can_run = False
self._stop_wait()
GObject.type_register(JobDocSearcher)
class JobFactoryDocSearcher(JobFactory):
def __init__(self, main_win, config):
JobFactory.__init__(self, "Search")
self.__main_win = main_win
self.__config = config
def make(self, docsearch, sort_func, search_type, search):
job = JobDocSearcher(self, next(self.id_generator), self.__config,
docsearch, sort_func, search_type, search)
job.connect('search-start', lambda searcher:
GLib.idle_add(self.__main_win.on_search_start_cb))
job.connect('search-results',
lambda searcher, search, documents:
GLib.idle_add(self.__main_win.on_search_results_cb,
search, documents))
job.connect('search-invalid',
lambda searcher: GLib.idle_add(
self.__main_win.on_search_invalid_cb))
job.connect('search-suggestions',
lambda searcher, suggestions:
GLib.idle_add(self.__main_win.on_search_suggestions_cb,
suggestions))
return job
class JobLabelPredictor(Job):
"""
Predicts what labels should be on a document
"""
__gsignals__ = {
# array of labels (strings)
'predicted-labels': (GObject.SignalFlags.RUN_LAST, None,
(
GObject.TYPE_PYOBJECT, # doc
GObject.TYPE_PYOBJECT, # array of labels
)),
}
can_stop = True
priority = 10
def __init__(self, factory, id, docsearch, doc):
Job.__init__(self, factory, id)
self.__docsearch = docsearch
self.doc = doc
def _progress_cb(self, current, total):
if not self.can_run:
raise StopIteration()
def do(self):
self.can_run = True
try:
predicted_labels = self.__docsearch.guess_labels(self.doc)
logger.info("Predicted labels on document [%s]: [%s]"
% (self.doc.docid, predicted_labels))
self.emit('predicted-labels', self.doc, predicted_labels)
except StopIteration:
return
def stop(self, will_resume=False):
self.can_run = False
GObject.type_register(JobLabelPredictor)
class JobFactoryLabelPredictorOnNewDoc(JobFactory):
def __init__(self, main_win):
JobFactory.__init__(self, "Label predictor (on new doc)")
self.__main_win = main_win
def make(self, doc):
job = JobLabelPredictor(self, next(self.id_generator),
self.__main_win.docsearch, doc)
return job
class JobExportPreviewer(Job):
__gsignals__ = {
'export-preview-start': (GObject.SignalFlags.RUN_LAST, None, ()),
'export-preview-done': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_INT, GObject.TYPE_PYOBJECT,)),
}
can_stop = True
priority = 500
def __init__(self, factory, id, exporter):
Job.__init__(self, factory, id)
self.__exporter = exporter
def do(self):
self.can_run = True
self._wait(0.7)
if not self.can_run:
return
self.emit('export-preview-start')
size = self.__exporter.estimate_size()
if not self.can_run:
return
img = self.__exporter.get_img()
if not self.can_run:
return
drawer = PillowImageDrawer((0, 0), img)
if not self.can_run:
return
self.emit('export-preview-done', size, drawer)
def stop(self, will_resume=False):
self.can_run = False
self._stop_wait()
GObject.type_register(JobExportPreviewer)
class JobFactoryExportPreviewer(JobFactory):
def __init__(self, main_win):
JobFactory.__init__(self, "ExportPreviewer")
self.__main_win = main_win
def make(self, exporter):
job = JobExportPreviewer(self, next(self.id_generator), exporter)
job.connect('export-preview-start',
lambda job:
GLib.idle_add(self.__main_win.on_export_preview_start))
job.connect('export-preview-done',
lambda job, size, pixbuf:
GLib.idle_add(self.__main_win.on_export_preview_done,
size, pixbuf))
return job
class JobPageEditor(Job):
__gsignals__ = {
'page-editing-img-edit': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_PYOBJECT, )),
'page-editing-done': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_PYOBJECT, )),
}
can_stop = False
priority = 10
def __init__(self, factory, id, page, changes=[]):
Job.__init__(self, factory, id)
self.__page = page
self.__changes = changes[:]
def do(self):
self.emit('page-editing-img-edit', self.__page)
try:
img = self.__page.img
for change in self.__changes:
img = change.do(img, 1.0)
self.__page.img = img
finally:
self.emit('page-editing-done', self.__page)
GObject.type_register(JobPageEditor)
class JobPageImgRenderer(Job):
__gsignals__ = {
'rendered': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_INT, GObject.TYPE_INT,
GObject.TYPE_PYOBJECT, GObject.TYPE_PYOBJECT)),
'rendering-error': (GObject.SignalFlags.RUN_LAST, None, ()),
}
can_stop = False
priority = 100
def __init__(self, factory, id, page):
Job.__init__(self, factory, id)
self.page = page
def do(self):
try:
self.emit("rendered",
self.page.page_nb, self.page.doc.nb_pages,
self.page.img, self.page.boxes)
except:
# TODO(Jflesch)
# We get "MemoryError" sometimes ? oO
self.emit("rendering-error")
raise
class JobFactoryPageImgRenderer(JobFactory):
def __init__(self, main_win):
JobFactory.__init__(self, "PageImgRenderer")
self.__main_win = main_win
def make(self, page):
job = JobPageImgRenderer(self, next(self.id_generator), page)
job.connect("rendered",
lambda renderer, page_nb, total_pages, img, boxes:
GLib.idle_add(self.__main_win.on_page_img_rendered,
renderer, page_nb, total_pages))
job.connect("rendering-error",
lambda renderer: GLib.idle_add(
self.__main_win.on_page_img_rendering_error, renderer))
return job
class JobImporter(Job):
__gsignals__ = {
'import-error': (GObject.SignalFlags.RUN_LAST, None,
(GObject.TYPE_PYOBJECT, )),
'no-doc-imported': (GObject.SignalFlags.RUN_LAST, None, ()),
}
can_stop = False
priority = 150
def __init__(self, factory, id, main_win, config, importer, file_uri):
Job.__init__(self, factory, id)
self.__main_win = main_win
self.__config = config
self.importer = importer
self.file_uri = file_uri
class IndexAdder(object):
def __init__(self, main_win, page_iterator, must_add_labels=False):
self._main_win = main_win
self._page_iterator = page_iterator
self.must_add_labels = must_add_labels
self._docs_to_label_predict = set()
self._docs_to_upd = set()
def start(self):
self._ocr_next_page()
def _ocr_next_page(self):
try:
while True:
page = next(self._page_iterator)
logger.info("Examining page %s" % str(page))
if len(page.boxes) <= 0:
break
self._add_doc_to_checklists(page.doc)
self._main_win.on_page_img_rendered(
None, page.page_nb, page.doc.nb_pages
)
except StopIteration:
logger.info("OCR has been redone on all the target pages")
if len(self._docs_to_label_predict) > 0:
self._predict_labels()
else:
self._update_index()
return
# found a page where we need to run the OCR
renderer = self._main_win.job_factories['page_img_renderer']
renderer = renderer.make(page)
renderer.connect("rendered",
lambda _, page_nb, nb_pages, img, boxes:
GLib.idle_add(self._ocr,
page, img, boxes))
self._main_win.schedulers['main'].schedule(renderer)
def _ocr(self, page, page_img, boxes):
if len(boxes) <= 0:
logger.info("Doing OCR on %s" % str(page))
self._main_win.show_doc(page.doc)
scan_workflow = self._main_win.make_scan_workflow()
drawer = self._main_win.make_scan_workflow_drawer(
scan_workflow, single_angle=True, page=page)
self._main_win.add_scan_workflow(page.doc, drawer,
page_nb=page.page_nb)
scan_workflow.connect('process-done',
lambda scan_workflow, img, boxes:
GLib.idle_add(self._on_page_ocr_done,
scan_workflow, img,
boxes, page))
scan_workflow.ocr(page_img, angles=1)
else:
logger.info("Imported page %s already has text" % page)
self._add_doc_to_checklists(page.doc)
GLib.idle_add(self._ocr_next_page)
def _on_page_ocr_done(self, scan_workflow, img, boxes, page):
if page.can_edit:
page.img = img
page.boxes = boxes
logger.info("OCR done on %s" % str(page))
self._main_win.remove_scan_workflow(scan_workflow)
self._main_win.show_page(page, force_refresh=True)
self._add_doc_to_checklists(page.doc)
self._ocr_next_page()
def _add_doc_to_checklists(self, doc):
self._docs_to_upd.add(doc)
if self.must_add_labels:
self._docs_to_label_predict.add(doc)
def _predict_labels(self):
for doc in self._docs_to_label_predict:
logger.info("Predicting labels on doc %s"
% str(doc))
factory = self._main_win.job_factories[
'label_predictor_on_new_doc'
]
job = factory.make(doc)
job.connect("predicted-labels",
self._on_predicted_labels)
self._main_win.schedulers['main'].schedule(job)
def _on_predicted_labels(self, predictor, doc, predicted_labels):
GLib.idle_add(self._on_predicted_labels2, doc, predicted_labels)
def _on_predicted_labels2(self, doc, predicted_labels):
logger.info("Label predicted on doc %s" % str(doc))
for label in self._main_win.docsearch.label_list:
if label in predicted_labels:
self._main_win.docsearch.add_label(doc, label,
update_index=False)
self._docs_to_label_predict.remove(doc)
if len(self._docs_to_label_predict) <= 0:
self._update_index()
self._main_win.refresh_label_list()
def _update_index(self):
logger.info("Updating index for %d docs"
% len(self._docs_to_upd))
job = self._main_win.job_factories['index_updater'].make(
self._main_win.docsearch, new_docs=self._docs_to_upd,
optimize=False, reload_list=True)
self._main_win.schedulers['index'].schedule(job)
self._docs_to_upd = set()
def do(self):
self.__main_win.set_mouse_cursor("Busy")
try:
try:
(docs, page, must_add_labels) = self.importer.import_doc(
self.file_uri, self.__main_win.docsearch,
self.__main_win.doc
)
finally:
self.__main_win.set_mouse_cursor("Normal")
except Exception as exc:
self.emit('import-error', str(exc))
raise
if docs is None or len(docs) <= 0:
self.emit('no-doc-imported')
return
if page is not None:
nb_docs = 0
nb_pages = 1
else:
nb_docs = len(docs)
nb_pages = sum([doc.nb_pages for doc in docs])
logger.info("Importing %d docs and %d pages" % (nb_docs, nb_pages))
self.__main_win.show_doc(docs[-1], force_refresh=True)
if page is not None:
self.__main_win.show_page(page, force_refresh=True)
set_widget_state(self.__main_win.need_doc_widgets, True)
if page is not None:
self.IndexAdder(self.__main_win, iter([page]),
must_add_labels).start()
return
if nb_pages > 0:
pages = []
for doc in docs:
new_pages = [p for p in doc.pages]
pages += new_pages
self.IndexAdder(self.__main_win, iter(pages),
must_add_labels).start()
GObject.type_register(JobImporter)
class JobFactoryImporter(JobFactory):
def __init__(self, main_win, config):
JobFactory.__init__(self, "Importer")
self._main_win = main_win
self._config = config
def make(self, importer, file_uri):
return JobImporter(self, next(self.id_generator),
self._main_win, self._config,
importer, file_uri)
class ActionNewDocument(SimpleAction):
"""
Starts a new docume.
"""
def __init__(self, doclist, main_win):
SimpleAction.__init__(self, "New document")
self.__doclist = doclist
self.__main_win = main_win
def do(self):
SimpleAction.do(self)
self.__main_win.allow_multiselect = False
self.__doclist.open_new_doc()
self.__doclist.gui['scrollbars'].get_vadjustment().set_value(0)
class ActionUpdateSearchResults(SimpleAction):
"""
Update search results
"""
def __init__(self, main_window, refresh_pages=True):
SimpleAction.__init__(self, "Update search results")
self.__main_win = main_window
self.__refresh_pages = refresh_pages
def do(self):
SimpleAction.do(self)
self.__main_win.refresh_doc_list()
if self.__refresh_pages:
self.__main_win.refresh_boxes()