2017-03-11 16:30:49 +00:00
|
|
|
import datetime
|
|
|
|
|
import hashlib
|
|
|
|
|
import logging
|
2016-11-27 15:06:45 +00:00
|
|
|
import os
|
|
|
|
|
import re
|
|
|
|
|
import uuid
|
2017-03-11 16:30:49 +00:00
|
|
|
|
2016-01-30 01:18:52 +00:00
|
|
|
from django.conf import settings
|
|
|
|
|
from django.utils import timezone
|
|
|
|
|
from paperless.db import GnuPG
|
|
|
|
|
|
2017-03-11 16:30:49 +00:00
|
|
|
from .models import Document, FileInfo, Tag
|
|
|
|
|
from .parsers import ParseError
|
2016-03-14 21:20:44 +00:00
|
|
|
from .signals import (
|
2017-03-11 16:30:49 +00:00
|
|
|
document_consumer_declaration,
|
|
|
|
|
document_consumption_finished,
|
|
|
|
|
document_consumption_started
|
2016-11-27 15:06:45 +00:00
|
|
|
)
|
2016-01-30 01:18:52 +00:00
|
|
|
|
|
|
|
|
|
2016-02-06 17:05:36 +00:00
|
|
|
class ConsumerError(Exception):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2018-02-18 15:55:55 +00:00
|
|
|
class Consumer:
|
2016-02-06 17:05:36 +00:00
|
|
|
"""
|
|
|
|
|
Loop over every file found in CONSUMPTION_DIR and:
|
2016-02-16 10:49:55 +01:00
|
|
|
1. Convert it to a greyscale pnm
|
|
|
|
|
2. Use tesseract on the pnm
|
2016-02-06 17:05:36 +00:00
|
|
|
3. Encrypt and store the document in the MEDIA_ROOT
|
|
|
|
|
4. Store the OCR'd text in the database
|
|
|
|
|
5. Delete the document and image(s)
|
|
|
|
|
"""
|
2016-01-30 01:18:52 +00:00
|
|
|
|
2018-02-25 19:20:51 +01:00
|
|
|
def __init__(self, consume=settings.CONSUMPTION_DIR,
|
|
|
|
|
scratch=settings.SCRATCH_DIR):
|
2016-01-30 01:18:52 +00:00
|
|
|
|
2016-02-27 20:18:50 +00:00
|
|
|
self.logger = logging.getLogger(__name__)
|
|
|
|
|
self.logging_group = None
|
2016-01-30 01:18:52 +00:00
|
|
|
|
2018-02-24 20:32:19 +01:00
|
|
|
self.stats = {}
|
|
|
|
|
self._ignore = []
|
|
|
|
|
self.consume = consume
|
|
|
|
|
self.scratch = scratch
|
|
|
|
|
|
2016-01-30 01:18:52 +00:00
|
|
|
try:
|
2018-02-24 20:32:19 +01:00
|
|
|
os.makedirs(self.scratch)
|
2016-01-30 01:18:52 +00:00
|
|
|
except FileExistsError:
|
|
|
|
|
pass
|
|
|
|
|
|
2018-02-04 13:14:47 +00:00
|
|
|
acceptable_storage_types = [_[0] for _ in Document.STORAGE_TYPES]
|
|
|
|
|
if settings.STORAGE_TYPE not in acceptable_storage_types:
|
|
|
|
|
raise ConsumerError(
|
|
|
|
|
'Invalid STORAGE_TYPE "{}" defined. It must be one of {}. '
|
|
|
|
|
'Exiting.'.format(
|
|
|
|
|
settings.STORAGE_TYPE,
|
|
|
|
|
", ".join(acceptable_storage_types)
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
self.stats = {}
|
|
|
|
|
self._ignore = []
|
|
|
|
|
|
2018-02-24 20:32:19 +01:00
|
|
|
if not self.consume:
|
2016-02-06 17:05:36 +00:00
|
|
|
raise ConsumerError(
|
|
|
|
|
"The CONSUMPTION_DIR settings variable does not appear to be "
|
|
|
|
|
"set."
|
|
|
|
|
)
|
|
|
|
|
|
2018-02-24 20:32:19 +01:00
|
|
|
if not os.path.exists(self.consume):
|
2016-02-06 17:05:36 +00:00
|
|
|
raise ConsumerError(
|
2018-02-24 20:32:19 +01:00
|
|
|
"Consumption directory {} does not exist".format(self.consume))
|
2016-02-06 17:05:36 +00:00
|
|
|
|
2017-03-11 16:30:49 +00:00
|
|
|
self.parsers = []
|
|
|
|
|
for response in document_consumer_declaration.send(self):
|
|
|
|
|
self.parsers.append(response[1])
|
|
|
|
|
|
|
|
|
|
if not self.parsers:
|
|
|
|
|
raise ConsumerError(
|
|
|
|
|
"No parsers could be found, not even the default. "
|
|
|
|
|
"This is a problem."
|
|
|
|
|
)
|
|
|
|
|
|
2016-02-27 20:18:50 +00:00
|
|
|
def log(self, level, message):
|
|
|
|
|
getattr(self.logger, level)(message, extra={
|
2016-03-28 11:11:15 +01:00
|
|
|
"group": self.logging_group
|
2016-02-27 20:18:50 +00:00
|
|
|
})
|
|
|
|
|
|
2018-02-24 20:32:19 +01:00
|
|
|
def run(self):
|
2016-02-06 17:05:36 +00:00
|
|
|
|
2018-02-24 20:32:19 +01:00
|
|
|
for doc in os.listdir(self.consume):
|
2016-02-06 17:05:36 +00:00
|
|
|
|
2018-02-24 20:32:19 +01:00
|
|
|
doc = os.path.join(self.consume, doc)
|
2016-02-06 17:05:36 +00:00
|
|
|
|
|
|
|
|
if not os.path.isfile(doc):
|
|
|
|
|
continue
|
|
|
|
|
|
2016-03-24 19:18:33 +00:00
|
|
|
if not re.match(FileInfo.REGEXES["title"], doc):
|
2016-02-06 17:05:36 +00:00
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
if doc in self._ignore:
|
|
|
|
|
continue
|
|
|
|
|
|
2016-06-26 10:18:58 +02:00
|
|
|
if not self._is_ready(doc):
|
2016-02-06 17:05:36 +00:00
|
|
|
continue
|
|
|
|
|
|
2016-04-03 18:44:00 +01:00
|
|
|
if self._is_duplicate(doc):
|
|
|
|
|
self.log(
|
|
|
|
|
"info",
|
|
|
|
|
"Skipping {} as it appears to be a duplicate".format(doc)
|
|
|
|
|
)
|
|
|
|
|
self._ignore.append(doc)
|
|
|
|
|
continue
|
|
|
|
|
|
2017-03-11 16:30:49 +00:00
|
|
|
parser_class = self._get_parser_class(doc)
|
|
|
|
|
if not parser_class:
|
|
|
|
|
self.log(
|
2017-03-28 21:01:50 +00:00
|
|
|
"error", "No parsers could be found for {}".format(doc))
|
2017-03-11 16:30:49 +00:00
|
|
|
self._ignore.append(doc)
|
|
|
|
|
continue
|
|
|
|
|
|
2016-02-27 20:18:50 +00:00
|
|
|
self.logging_group = uuid.uuid4()
|
|
|
|
|
|
|
|
|
|
self.log("info", "Consuming {}".format(doc))
|
2016-02-06 17:05:36 +00:00
|
|
|
|
2016-03-14 21:20:44 +00:00
|
|
|
document_consumption_started.send(
|
2016-03-28 11:11:15 +01:00
|
|
|
sender=self.__class__,
|
|
|
|
|
filename=doc,
|
|
|
|
|
logging_group=self.logging_group
|
|
|
|
|
)
|
2016-03-14 21:20:44 +00:00
|
|
|
|
2017-03-11 16:30:49 +00:00
|
|
|
parsed_document = parser_class(doc)
|
2016-02-06 17:05:36 +00:00
|
|
|
|
|
|
|
|
try:
|
2018-02-18 16:02:27 +00:00
|
|
|
thumbnail = parsed_document.get_thumbnail()
|
|
|
|
|
date = parsed_document.get_date()
|
2017-03-11 16:30:49 +00:00
|
|
|
document = self._store(
|
|
|
|
|
parsed_document.get_text(),
|
|
|
|
|
doc,
|
2018-01-28 19:09:52 +01:00
|
|
|
thumbnail,
|
|
|
|
|
date
|
2017-03-11 16:30:49 +00:00
|
|
|
)
|
|
|
|
|
except ParseError as e:
|
2016-03-14 21:20:44 +00:00
|
|
|
|
2016-02-06 17:05:36 +00:00
|
|
|
self._ignore.append(doc)
|
2017-03-11 16:30:49 +00:00
|
|
|
self.log("error", "PARSE FAILURE for {}: {}".format(doc, e))
|
|
|
|
|
parsed_document.cleanup()
|
2016-03-14 21:20:44 +00:00
|
|
|
|
2016-02-06 17:05:36 +00:00
|
|
|
continue
|
2016-03-14 21:20:44 +00:00
|
|
|
|
2016-02-20 22:30:01 +00:00
|
|
|
else:
|
2016-03-14 21:20:44 +00:00
|
|
|
|
2017-03-11 16:30:49 +00:00
|
|
|
parsed_document.cleanup()
|
2016-02-20 22:30:01 +00:00
|
|
|
self._cleanup_doc(doc)
|
2016-02-06 17:05:36 +00:00
|
|
|
|
2016-10-26 09:52:09 +00:00
|
|
|
self.log(
|
|
|
|
|
"info",
|
|
|
|
|
"Document {} consumption finished".format(document)
|
|
|
|
|
)
|
|
|
|
|
|
2016-03-14 21:20:44 +00:00
|
|
|
document_consumption_finished.send(
|
2016-03-28 11:11:15 +01:00
|
|
|
sender=self.__class__,
|
|
|
|
|
document=document,
|
|
|
|
|
logging_group=self.logging_group
|
|
|
|
|
)
|
2016-03-14 21:20:44 +00:00
|
|
|
|
2017-03-11 16:30:49 +00:00
|
|
|
def _get_parser_class(self, doc):
|
2016-02-14 17:13:48 +00:00
|
|
|
"""
|
2017-03-11 16:30:49 +00:00
|
|
|
Determine the appropriate parser class based on the file
|
2016-02-14 17:13:48 +00:00
|
|
|
"""
|
|
|
|
|
|
2017-03-11 16:30:49 +00:00
|
|
|
options = []
|
|
|
|
|
for parser in self.parsers:
|
|
|
|
|
result = parser(doc)
|
|
|
|
|
if result:
|
|
|
|
|
options.append(result)
|
2016-01-30 01:18:52 +00:00
|
|
|
|
2017-03-28 21:01:50 +00:00
|
|
|
self.log(
|
|
|
|
|
"info",
|
|
|
|
|
"Parsers available: {}".format(
|
|
|
|
|
", ".join([str(o["parser"].__name__) for o in options])
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if not options:
|
|
|
|
|
return None
|
|
|
|
|
|
2017-03-11 16:30:49 +00:00
|
|
|
# Return the parser with the highest weight.
|
|
|
|
|
return sorted(
|
|
|
|
|
options, key=lambda _: _["weight"], reverse=True)[0]["parser"]
|
2016-01-30 01:18:52 +00:00
|
|
|
|
2018-01-28 19:09:52 +01:00
|
|
|
def _store(self, text, doc, thumbnail, date):
|
2016-01-30 01:18:52 +00:00
|
|
|
|
2016-03-07 21:08:07 +02:00
|
|
|
file_info = FileInfo.from_path(doc)
|
2016-01-30 01:18:52 +00:00
|
|
|
|
|
|
|
|
stats = os.stat(doc)
|
|
|
|
|
|
2016-02-27 20:18:50 +00:00
|
|
|
self.log("debug", "Saving record to database")
|
2016-01-30 01:18:52 +00:00
|
|
|
|
2018-01-28 19:09:52 +01:00
|
|
|
created = file_info.created or date or timezone.make_aware(
|
2016-08-20 18:11:51 +01:00
|
|
|
datetime.datetime.fromtimestamp(stats.st_mtime))
|
|
|
|
|
|
2016-04-11 23:28:12 +01:00
|
|
|
with open(doc, "rb") as f:
|
|
|
|
|
document = Document.objects.create(
|
|
|
|
|
correspondent=file_info.correspondent,
|
|
|
|
|
title=file_info.title,
|
|
|
|
|
content=text,
|
|
|
|
|
file_type=file_info.extension,
|
|
|
|
|
checksum=hashlib.md5(f.read()).hexdigest(),
|
2016-08-20 18:11:51 +01:00
|
|
|
created=created,
|
2018-02-04 13:14:47 +00:00
|
|
|
modified=created,
|
|
|
|
|
storage_type=settings.STORAGE_TYPE
|
2016-04-11 23:28:12 +01:00
|
|
|
)
|
2016-01-30 01:18:52 +00:00
|
|
|
|
2016-03-28 11:11:15 +01:00
|
|
|
relevant_tags = set(list(Tag.match_all(text)) + list(file_info.tags))
|
2016-01-30 01:18:52 +00:00
|
|
|
if relevant_tags:
|
|
|
|
|
tag_names = ", ".join([t.slug for t in relevant_tags])
|
2016-02-27 20:18:50 +00:00
|
|
|
self.log("debug", "Tagging with {}".format(tag_names))
|
2016-01-30 01:18:52 +00:00
|
|
|
document.tags.add(*relevant_tags)
|
|
|
|
|
|
2018-02-04 13:14:47 +00:00
|
|
|
self._write(document, doc, document.source_path)
|
|
|
|
|
self._write(document, thumbnail, document.thumbnail_path)
|
2016-01-30 01:18:52 +00:00
|
|
|
|
2016-02-27 20:18:50 +00:00
|
|
|
self.log("info", "Completed")
|
|
|
|
|
|
2016-03-14 21:20:44 +00:00
|
|
|
return document
|
|
|
|
|
|
2018-02-04 13:14:47 +00:00
|
|
|
def _write(self, document, source, target):
|
|
|
|
|
with open(source, "rb") as read_file:
|
|
|
|
|
with open(target, "wb") as write_file:
|
|
|
|
|
if document.storage_type == Document.STORAGE_TYPE_UNENCRYPTED:
|
|
|
|
|
write_file.write(read_file.read())
|
|
|
|
|
return
|
|
|
|
|
self.log("debug", "Encrypting the thumbnail")
|
|
|
|
|
write_file.write(GnuPG.encrypted(read_file))
|
|
|
|
|
|
2016-02-27 20:18:50 +00:00
|
|
|
def _cleanup_doc(self, doc):
|
|
|
|
|
self.log("debug", "Deleting document {}".format(doc))
|
2016-02-14 17:40:37 +01:00
|
|
|
os.unlink(doc)
|
2016-01-30 01:18:52 +00:00
|
|
|
|
2016-02-06 17:05:36 +00:00
|
|
|
def _is_ready(self, doc):
|
|
|
|
|
"""
|
2018-03-03 18:42:27 +00:00
|
|
|
Detect whether ``doc`` is ready to consume or if it's still being
|
|
|
|
|
written to by the uploader.
|
2016-02-06 17:05:36 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
t = os.stat(doc).st_mtime
|
|
|
|
|
|
|
|
|
|
if self.stats.get(doc) == t:
|
|
|
|
|
del(self.stats[doc])
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
self.stats[doc] = t
|
|
|
|
|
|
|
|
|
|
return False
|
2016-02-27 20:18:50 +00:00
|
|
|
|
2016-04-03 18:44:00 +01:00
|
|
|
@staticmethod
|
|
|
|
|
def _is_duplicate(doc):
|
|
|
|
|
with open(doc, "rb") as f:
|
|
|
|
|
checksum = hashlib.md5(f.read()).hexdigest()
|
|
|
|
|
return Document.objects.filter(checksum=checksum).exists()
|