A community-supported supercharged document management system: scan, index and archive all your documents
Python aiangulararchivingdjangodmsdocument-managementdocument-management-systemllmmachine-learningocroptical-character-recognitionpdf
Merge branch 'dev' into celery-tasks
Jonas Winkler17430210a1a7
diff --cc Pipfileindex fdfe63595,66d60845b..8cb84f44b--- a/Pipfile+++ b/Pipfile@@@ -29,9 -34,7 +34,10 @@@ watchdog = "*pathvalidate = "*"django-q = "*"redis = "*"+ imap-tools = "*"+channels = "~=3.0"+channels-redis = "*"+daphne = "~=3.0"[dev-packages]coveralls = "*"diff --cc docker/supervisord.confindex ae2a77513,ebe0f005d..a643b1136--- a/docker/supervisord.conf+++ b/docker/supervisord.conf@@@ -5,9 -5,10 +5,10 @@@ pidfile=/var/run/supervisord/supervisorlogfile_maxbytes=50MB ; max main logfile bytes b4 rotation; default 50MBlogfile_backups=10 ; # of main logfile backups; 0 means none, default 10loglevel=info ; log level; default info; others: debug,warn,trace+ user=root-[program:gunicorn]-command=gunicorn -c /usr/src/paperless/gunicorn.conf.py -b 0.0.0.0:8000 paperless.wsgi+[program:daphne]+command=daphne -b 0.0.0.0 -p 8000 paperless.asgi:applicationuser=paperlessstdout_logfile=/dev/stdoutdiff --cc src-ui/src/app/app.module.tsindex 5a3cfde19,014279cc5..750ef1e6b--- a/src-ui/src/app/app.module.ts+++ b/src-ui/src/app/app.module.ts@@@ -39,10 -39,8 +39,12 @@@ import { InfiniteScrollModule } from 'nimport { DateTimeComponent } from './components/common/input/date-time/date-time.component';import { TagsComponent } from './components/common/input/tags/tags.component';import { SortableDirective } from './directives/sortable.directive';+ import { CookieService } from 'ngx-cookie-service';+ import { CsrfInterceptor } from './interceptors/csrf.interceptor';+import { SavedViewWidgetComponent } from './components/dashboard/widgets/saved-view-widget/saved-view-widget.component';+import { ConsumerStatusWidgetComponent } from './components/dashboard/widgets/consumer-status-widget/consumer-status-widget.component';+import { StatisticsWidgetComponent } from './components/dashboard/widgets/statistics-widget/statistics-widget.component';+import { FileUploadWidgetComponent } from './components/dashboard/widgets/file-upload-widget/file-upload-widget.component';@NgModule({declarations: [diff --cc src/documents/consumer.pyindex 3a73fc0cd,3cd57796e..973fff925--- a/src/documents/consumer.py+++ b/src/documents/consumer.py@@@ -3,10 -3,7 +3,9 @@@ import hashliimport loggingimport osimport re- import uuid+from asgiref.sync import async_to_sync+from channels.layers import get_channel_layerfrom django.conf import settingsfrom django.db import transactionfrom django.utils import timezone@@@ -25,168 -24,186 +26,226 @@@ class ConsumerError(Exception)pass- class Consumer:- """- Loop over every file found in CONSUMPTION_DIR and:- 1. Convert it to a greyscale pnm- 2. Use tesseract on the pnm- 3. Store the document in the MEDIA_ROOT with optional encryption- 4. Store the OCR'd text in the database- 5. Delete the document and image(s)- """+ class Consumer(LoggingMixin):- def _send_progress(self, filename, current_progress, max_progress, status, message, document_id=None):++ def _send_progress(self, filename, current_progress, max_progress, status,++ message, document_id=None):+ payload = {+ 'filename': os.path.basename(filename),+ 'current_progress': current_progress,+ 'max_progress': max_progress,+ 'status': status,+ 'message': message,+ 'document_id': document_id+ }- async_to_sync(self.channel_layer.group_send)("status_updates", {'type': 'status_update', 'data': payload})-- def __init__(self, consume=settings.CONSUMPTION_DIR,- scratch=settings.SCRATCH_DIR):-- self.logger = logging.getLogger(__name__)- self.logging_group = None-- self.consume = consume- self.scratch = scratch-- self.classifier = DocumentClassifier()++ async_to_sync(self.channel_layer.group_send)("status_updates",++ {'type': 'status_update',++ 'data': payload})+++ def __init__(self):+ super().__init__()+ self.path = None+ self.filename = None+ self.override_title = None+ self.override_correspondent_id = None+ self.override_tag_ids = None+ self.override_document_type_id = None+ self.channel_layer = get_channel_layer()+- os.makedirs(self.scratch, exist_ok=True)-- self.storage_type = Document.STORAGE_TYPE_UNENCRYPTED- if settings.PASSPHRASE:- self.storage_type = Document.STORAGE_TYPE_GPG+ def pre_check_file_exists(self):+ if not os.path.isfile(self.path):+ raise ConsumerError("Cannot consume {}: It is not a file".format(+ self.path))- if not self.consume:+ def pre_check_consumption_dir(self):+ if not settings.CONSUMPTION_DIR:raise ConsumerError("The CONSUMPTION_DIR settings variable does not appear to be "- "set."- )+ "set.")++ if not os.path.isdir(settings.CONSUMPTION_DIR):+ raise ConsumerError(+ "Consumption directory {} does not exist".format(+ settings.CONSUMPTION_DIR))- if not os.path.exists(self.consume):+ def pre_check_regex(self):+ if not re.match(FileInfo.REGEXES["title"], self.filename):raise ConsumerError(- "Consumption directory {} does not exist".format(self.consume))+ "Filename {} does not seem to be safe to "+ "consume".format(self.filename))- def log(self, level, message):- getattr(self.logger, level)(message, extra={- "group": self.logging_group- })+ def pre_check_duplicate(self):+ with open(self.path, "rb") as f:+ checksum = hashlib.md5(f.read()).hexdigest()+ if Document.objects.filter(checksum=checksum).exists():+ if settings.CONSUMER_DELETE_DUPLICATES:+ os.unlink(self.path)+ raise ConsumerError(+ "Not consuming {}: It is a duplicate.".format(self.filename)+ )- @transaction.atomic- def try_consume_file(self, file):+ def pre_check_directories(self):+ os.makedirs(settings.SCRATCH_DIR, exist_ok=True)+ os.makedirs(settings.THUMBNAIL_DIR, exist_ok=True)+ os.makedirs(settings.ORIGINALS_DIR, exist_ok=True)++ def try_consume_file(self,+ path,+ override_filename=None,+ override_title=None,+ override_correspondent_id=None,+ override_document_type_id=None,+ override_tag_ids=None):"""- Return True if file was consumed+ Return the document object if it was successfully created."""- self.logging_group = uuid.uuid4()+ self.path = path+ self.filename = override_filename or os.path.basename(path)+ self.override_title = override_title+ self.override_correspondent_id = override_correspondent_id+ self.override_document_type_id = override_document_type_id+ self.override_tag_ids = override_tag_ids- if not re.match(FileInfo.REGEXES["title"], file):- return False+ # this is for grouping logging entries for this particular file+ # together.- doc = file+ self.renew_logging_group()- if self._is_duplicate(doc):- self.log(- "warning",- "Skipping {} as it appears to be a duplicate".format(doc)- )- return False+ # Make sure that preconditions for consuming the file are met.++ self.pre_check_file_exists()+ self.pre_check_consumption_dir()+ self.pre_check_directories()+ self.pre_check_regex()+ self.pre_check_duplicate()- self.log("info", "Consuming {}".format(doc))+ self.log("info", "Consuming {}".format(self.filename))+ # Determine the parser class.- parser_class = get_parser_class(doc)+ parser_class = get_parser_class(self.filename)if not parser_class:- self.log(- "error", "No parsers could be found for {}".format(doc))- return False+ raise ConsumerError("No parsers abvailable for {}".format(self.filename))else:- self.log("info", "Parser: {}".format(parser_class.__name__))+ self.log("debug", "Parser: {}".format(parser_class.__name__))++ # Notify all listeners that we're going to do some work.- self._send_progress(file, 0, 100, 'WORKING', 'Consumption started')++ self._send_progress(self.filename, 0, 100, 'WORKING', 'Consumption started')+document_consumption_started.send(sender=self.__class__,- filename=doc,+ filename=self.path,logging_group=self.logging_group)+ def progress_callback(current_progress, max_progress, message):+ # recalculate progress to be within 20 and 80+ p = int((current_progress / max_progress) * 60 + 20)- self._send_progress(file, p, 100, "WORKING", message)++ self._send_progress(self.filename, p, 100, "WORKING", message)+++ # This doesn't parse the document yet, but gives us a parser.+- document_parser = parser_class(self.path, self.logging_group)++ document_parser = parser_class(self.path, self.logging_group, progress_callback)++ # However, this already created working directories which we have to+ # clean up.- document_parser = parser_class(doc, self.logging_group, progress_callback)+ # Parse the document. This may take some time.try:- self.log("info", "Generating thumbnail for {}...".format(doc))- self._send_progress(file, 10, 100, 'WORKING',+ self.log("debug", "Generating thumbnail for {}...".format(self.filename))++ self._send_progress(self.filename, 10, 100, 'WORKING',+ 'Generating thumbnail...')thumbnail = document_parser.get_optimised_thumbnail()- self._send_progress(file, 20, 100, 'WORKING',+ self.log("debug", "Parsing {}...".format(self.filename))++ self._send_progress(self.filename, 20, 100, 'WORKING',+ 'Getting text from document...')text = document_parser.get_text()- self._send_progress(file, 80, 100, 'WORKING',++ self._send_progress(self.filename, 80, 100, 'WORKING',+ 'Getting date from document...')date = document_parser.get_date()- self._send_progress(file, 85, 100, 'WORKING',- 'Storing the document...')- document = self._store(- text,- doc,- thumbnail,- date- )except ParseError as e:- self.log("fatal", "PARSE FAILURE for {}: {}".format(doc, e))- self._send_progress(file, 100, 100, 'FAILED',+ document_parser.cleanup()++ self._send_progress(self.filename, 100, 100, 'FAILED',+ "Failed: {}".format(e))+ raise ConsumerError(e)- document_parser.cleanup()- return False- else:- document_parser.cleanup()- self._cleanup_doc(doc)+ # Prepare the document classifier.- self.log(- "info",- "Document {} consumption finished".format(document)- )+ # TODO: I don't really like to do this here, but this way we avoid+ # reloading the classifier multiple times, since there are multiple+ # post-consume hooks that all require the classifier.+ try:+ classifier = DocumentClassifier()+ classifier.reload()+ except (FileNotFoundError, IncompatibleClassifierVersionError) as e:+ logging.getLogger(__name__).warning(+ "Cannot classify documents: {}.".format(e))classifier = None-++ self._send_progress(self.filename, 85, 100, 'WORKING',++ 'Storing the document...')+ # now that everything is done, we can start to store the document+ # in the system. This will be a transaction and reasonably fast.+ try:+ with transaction.atomic():++ # store the document.+ document = self._store(+ text=text,+ date=date+ )++ # If we get here, it was successful. Proceed with post-consume+ # hooks. If they fail, nothing will get changed.+++ self._send_progress(self.filename, 90, 100, 'WORKING',++ 'Performing post-consumption tasks...')+++ document_consumption_finished.send(+ sender=self.__class__,+ document=document,+ logging_group=self.logging_group,+ classifier=classifier+ )++ # After everything is in the database, copy the files into+ # place. If this fails, we'll also rollback the transaction.++ create_source_path_directory(document.source_path)+ self._write(document, self.path, document.source_path)+ self._write(document, thumbnail, document.thumbnail_path)++ # Delete the file only if it was successfully consumed+ self.log("debug", "Deleting file {}".format(self.path))+ os.unlink(self.path)+ except Exception as e:+ raise ConsumerError(e)++ self._send_progress(file, 100, 100, 'FAILED',++ "Failed: {}".format(e))+ finally:+ document_parser.cleanup()- try:- self.classifier.reload()- classifier = self.classifier- except (FileNotFoundError, IncompatibleClassifierVersionError) as e:- logging.getLogger(__name__).warning("Cannot classify documents: {}.".format(e))+ self.log(+ "info",+ "Document {} consumption finished".format(document)+ )- self._send_progress(file, 90, 100, 'WORKING',- 'Performing post-consumption tasks...')++ self._send_progress(file, 100, 100, 'SUCCESS',++ 'Finished.', document.id)+- document_consumption_finished.send(- sender=self.__class__,- document=document,- logging_group=self.logging_group,- classifier=classifier- )- self._send_progress(file, 100, 100, 'SUCCESS',- 'Finished.', document.id)- return True+ return document++ def _store(self, text, date):- def _store(self, text, doc, thumbnail, date):+ # If someone gave us the original filename, use it instead of doc.- file_info = FileInfo.from_path(doc)+ file_info = FileInfo.from_path(self.filename)- stats = os.stat(doc)+ stats = os.stat(self.path)self.log("debug", "Saving record to database")diff --cc src/documents/parsers.pyindex 7976f4739,496efa188..af4681d55--- a/src/documents/parsers.py+++ b/src/documents/parsers.py@@@ -106,12 -108,11 +108,12 @@@ class DocumentParser(LoggingMixin)`paperless_tesseract.parsers` for inspiration."""- def __init__(self, path, logging_group):+ def __init__(self, path, logging_group, progress_callback):+ super().__init__()+ self.logging_group = logging_groupself.document_path = pathself.tempdir = tempfile.mkdtemp(prefix="paperless-", dir=settings.SCRATCH_DIR)- self.logger = logging.getLogger(__name__)- self.logging_group = logging_group+ self.progress_callback = progress_callbackdef get_thumbnail(self):"""diff --cc src/paperless/settings.pyindex 491bc557f,06895e92f..cb115739b--- a/src/paperless/settings.py+++ b/src/paperless/settings.py@@@ -311,14 -370,6 +373,15 @@@ FILENAME_PARSE_TRANSFORMS = [for t in json.loads(os.getenv("PAPERLESS_FILENAME_PARSE_TRANSFORMS", "[]")):FILENAME_PARSE_TRANSFORMS.append((re.compile(t["pattern"]), t["repl"]))+ # TODO: this should not have a prefix.# Specify the filename format for out filesPAPERLESS_FILENAME_FORMAT = os.getenv("PAPERLESS_FILENAME_FORMAT")++CHANNEL_LAYERS = {+ "default": {+ "BACKEND": "channels_redis.core.RedisChannelLayer",+ "CONFIG": {+ "hosts": [("broker", 6379)],+ },+ },+}diff --cc src/paperless/urls.pyindex b8ff8facf,220e6402c..07d109587--- a/src/paperless/urls.py+++ b/src/paperless/urls.py@@@ -6,8 -6,6 +6,7 @@@ from django.views.decorators.csrf imporfrom django.views.generic import RedirectViewfrom rest_framework.routers import DefaultRouter+from paperless.consumers import StatusConsumer- from paperless.views import FaviconViewfrom documents.views import (CorrespondentViewSet,DocumentViewSet,@@@ -68,14 -67,9 +68,14 @@@ urlpatterns =]++websocket_urlpatterns = [+ re_path(r'ws/status/$', StatusConsumer.as_asgi()),+]+# Text in each page's <h1> (and above login form).- admin.site.site_header = 'Paperless'+ admin.site.site_header = 'Paperless-ng'# Text at the end of each page's <title>.- admin.site.site_title = 'Paperless'+ admin.site.site_title = 'Paperless-ng'# Text at the top of the admin index page.- admin.site.index_title = 'Paperless administration'+ admin.site.index_title = 'Paperless-ng administration'diff --cc src/paperless_tesseract/parsers.pyindex 535ee501c,73b2414d5..c3715c83a--- a/src/paperless_tesseract/parsers.py+++ b/src/paperless_tesseract/parsers.py@@@ -100,11 -98,9 +99,11 @@@ class RasterisedDocumentParser(Documenttry:sample_page_index = int(len(images) / 2)- self.log("info", "Attempting language detection on page {} of {}...".format(sample_page_index+1, len(images)))+ self.log("debug", "Attempting language detection on page {} of {}...".format(sample_page_index + 1, len(images)))+ self.progress_callback(0.4, 1, "Language Detection.")sample_page_text = self._ocr([images[sample_page_index]], settings.OCR_LANGUAGE)[0]guessed_language = self._guess_language(sample_page_text)+ self.progress_callback(0.6, 1, "OCR all the pages.")if not guessed_language or guessed_language not in ISO639:self.log("warning", "Language detection failed.")@@@ -119,10 -115,10 +118,10 @@@ocr_pages = self._complete_ocr_default_language(images, sample_page_index, sample_page_text)else:- self.log("info", "Detected language: {}".format(guessed_language))+ self.log("debug", "Detected language: {}".format(guessed_language))- ocr_pages = self._ocr(images, ISO639[guessed_language])+ ocr_pages = self._ocr(images, ISO639[guessed_language], report_progress=True)- self.log("info", "OCR completed.")+ self.log("debug", "OCR completed.")self._text = strip_excess_whitespace(" ".join(ocr_pages))return self._text@@@ -152,12 -148,10 +151,12 @@@if f.endswith(".pnm"):pnms.append(os.path.join(self.tempdir, f))- self.log("info", "Running unpaper on {} pages...".format(len(pnms)))+ self.log("debug", "Running unpaper on {} pages...".format(len(pnms)))+ self.progress_callback(0.2,1, "Running unpaper on {} pages...".format(len(pnms)))+# Run unpaper in parallel on converted images- with Pool(processes=settings.OCR_THREADS) as pool:+ with ThreadPool(processes=settings.THREADS_PER_WORKER) as pool:pnms = pool.map(run_unpaper, pnms)return sorted(filter(lambda __: os.path.isfile(__), pnms))@@@ -167,19 -161,14 +166,19 @@@guess = langdetect.detect(text)return guessexcept Exception as e:- self.log('debug', "Language detection failed with: {}".format(e))+ self.log('warning', "Language detection failed with: {}".format(e))return None- def _ocr(self, imgs, lang):+ def _ocr(self, imgs, lang, report_progress=False):- self.log("info", "Performing OCR on {} page(s) with language {}".format(len(imgs), lang))+ self.log("debug", "Performing OCR on {} page(s) with language {}".format(len(imgs), lang))+ r = []- with Pool(processes=settings.OCR_THREADS) as pool:+ with ThreadPool(processes=settings.THREADS_PER_WORKER) as pool:- r = pool.map(image_to_string, itertools.product(imgs, [lang]))- return r+ # r = pool.map(image_to_string, itertools.product(imgs, [lang]))+ for i, page in enumerate(pool.imap(image_to_string, itertools.product(imgs, [lang]))):+ if report_progress:+ self.progress_callback(0.6 + (i / len(imgs)) * 0.4, 1, "OCR'ed {} pages".format(i+1))+ r += [page]+ return rdef _complete_ocr_default_language(self, images, sample_page_index, sample_page):"""@@@ -191,8 -180,8 +190,8 @@@images_copy = list(images)del images_copy[sample_page_index]if images_copy:- self.log('info', 'Continuing ocr with default language.')+ self.log('debug', 'Continuing ocr with default language.')- ocr_pages = self._ocr(images_copy, settings.OCR_LANGUAGE)+ ocr_pages = self._ocr(images_copy, settings.OCR_LANGUAGE, report_progress=True)ocr_pages.insert(sample_page_index, sample_page)return ocr_pageselse: