A community-supported supercharged document management system: scan, index and archive all your documents
Python aiangulararchivingdjangodmsdocument-managementdocument-management-systemllmmachine-learningocroptical-character-recognitionpdf
Merge remote-tracking branch 'upstream/master'
Jonas Winkler766109ae4e25
diff --cc requirements.txtindex 84ec2e68b,d30cbf078..ea595335b--- a/requirements.txt+++ b/requirements.txt@@@ -1,54 -1,80 +1,83 @@@-i https://pypi.python.org/simple- apipkg==1.5; python_version != '3.3.*'- atomicwrites==1.2.1; python_version != '3.3.*'+ alabaster==0.7.12+ apipkg==1.5+ atomicwrites==1.2.1attrs==18.2.0- certifi==2018.8.24+ babel==2.6.0+ backcall==0.1.0+ certifi==2018.10.15chardet==3.0.4- coverage==4.5.1; python_version < '4'- coveralls==1.5.0+ coverage==4.5.1+ coveralls==1.5.1dateparser==0.7.0+ decorator==4.3.0django-cors-headers==2.4.0django-crispy-forms==1.7.2- django-extensions==2.1.2+ django-extensions==2.1.3django-filter==2.0.0- django==2.0.8- djangorestframework==3.8.2+ django==2.0.9+ djangorestframework==3.9.0docopt==0.6.2- execnet==1.5.0; python_version != '3.3.*'+ docutils==0.14+ execnet==1.5.0factory-boy==2.11.1- faker==0.9.0; python_version >= '2.7'+ faker==0.9.2+ filelock==3.0.10filemagic==1.6- fuzzywuzzy==0.15.0+ fuzzywuzzy[speedup]==0.15.0gunicorn==19.9.0idna==2.7+ imagesize==1.1.0inotify-simple==1.1.8+ ipython-genutils==0.2.0+ ipython==7.1.1+ jedi==0.13.1+ jinja2==2.10langdetect==1.0.7+ markupsafe==1.0more-itertools==4.3.0+numpy==1.15.1- pdftotext==2.1.0- pillow==5.2.0- pluggy==0.7.1; python_version != '3.3.*'- py==1.6.0; python_version != '3.3.*'+ packaging==18.0+ parso==0.3.1+ pdftotext==2.1.1+ pexpect==4.6.0+ pickleshare==0.7.5+ pillow==5.3.0+ pluggy==0.8.0+ psycopg2==2.7.6.1+ prompt-toolkit==2.0.7+ ptyprocess==0.6.0+ py==1.7.0pycodestyle==2.4.0+ pygments==2.2.0pyocr==0.5.3+ pyparsing==2.3.0pytest-cov==2.6.0- pytest-django==3.4.2+ pytest-django==3.4.3pytest-env==0.6.2- pytest-forked==0.2; python_version != '3.3.*'+ pytest-forked==0.2pytest-sugar==0.9.1- pytest-xdist==1.23.0- pytest==3.8.0- python-dateutil==2.7.3+ pytest-xdist==1.24.0+ pytest==3.9.3+ python-dateutil==2.7.5python-dotenv==0.9.1python-gnupg==0.4.3- python-levenshtein==0.12.0- pytz==2018.5- regex==2018.8.29- requests==2.19.1+ python-levenshtein==0.12.0 ; extra == 'speedup'+ pytz==2018.7+ regex==2018.11.2+ requests==2.20.0six==1.11.0+scikit-learn==0.19.2+scipy==1.1.0+ snowballstemmer==1.2.1+ sphinx==1.8.1+ sphinxcontrib-websupport==1.1.0termcolor==1.1.0text-unidecode==1.2+ toml==0.10.0+ tox==3.5.3+ traitlets==4.3.2tzlocal==1.5.1- urllib3==1.23; python_version != '3.3.*'+ urllib3==1.24.1+ virtualenv==16.1.0+ wcwidth==0.1.7diff --cc src/documents/admin.pyindex d739011d4,ff0365a53..555f5a55cmode 100755,100644..100755--- a/src/documents/admin.py+++ b/src/documents/admin.py@@@ -124,7 -121,10 +123,9 @@@ class CorrespondentAdmin(CommonAdmin)"document_count","last_correspondence")- list_editable = ("automatic_classification")- list_filter = ("matching_algorithm",)- list_editable = ("match", "matching_algorithm")++ list_editable = ("automatic_classification",)++ readonly_fields = ("slug",)def get_queryset(self, request):qs = super(CorrespondentAdmin, self).get_queryset(request)@@@ -145,10 -145,16 +146,15 @@@class TagAdmin(CommonAdmin):- list_display = (- "name", "colour", "match", "matching_algorithm", "document_count")- list_filter = ("colour", "matching_algorithm")- list_editable = ("colour", "match", "matching_algorithm")+ list_display = ("name", "colour", "automatic_classification", "document_count")+ list_filter = ("colour",)+ list_editable = ("colour", "automatic_classification")+ readonly_fields = ("slug",)++ class Media:+ js = ("js/colours.js",)+def get_queryset(self, request):qs = super(TagAdmin, self).get_queryset(request)qs = qs.annotate(document_count=models.Count("documents"))@@@ -159,21 -165,6 +165,23 @@@document_count.admin_order_field = "document_count"+class DocumentTypeAdmin(CommonAdmin):++ list_display = ("name", "automatic_classification", "document_count")+ list_editable = ("automatic_classification",)+++ readonly_fields = ("slug",)+++ def get_queryset(self, request):+ qs = super(DocumentTypeAdmin, self).get_queryset(request)+ qs = qs.annotate(document_count=models.Count("documents"))+ return qs++ def document_count(self, obj):+ return obj.document_count+ document_count.admin_order_field = "document_count"++class DocumentAdmin(CommonAdmin):class Media:@@@ -182,14 -173,12 +190,13 @@@}search_fields = ("correspondent__name", "title", "content", "tags__name")- readonly_fields = ("added",)+ readonly_fields = ("added", "file_type", "storage_type",)list_display = ("title", "created", "added", "thumbnail", "correspondent",- "tags_")+ "tags_", "archive_serial_number", "document_type")list_filter = (+ "document_type","tags",("correspondent", RecentCorrespondentFilter),- "correspondent",FinancialYearFilter)diff --cc src/documents/filters.pyindex ae0e0d22e,2b7c9cc9f..3e828e332mode 100755,100644..100755--- a/src/documents/filters.py+++ b/src/documents/filters.py@@@ -1,6 -1,6 +1,6 @@@- from django_filters.rest_framework import CharFilter, FilterSet, BooleanFilter, ModelChoiceFilter+ from django_filters.rest_framework import BooleanFilter, FilterSet-from .models import Correspondent, Document, Tag+from .models import Correspondent, Document, Tag, DocumentTypeCHAR_KWARGS = (diff --cc src/documents/migrations/0022_auto_20181007_1420.pyindex 000000000,937695bc8..2853f2093mode 000000,100644..100644--- a/src/documents/migrations/0022_auto_20181007_1420.py+++ b/src/documents/migrations/0022_auto_20181007_1420.py@@@ -1,0 -1,52 +1,52 @@@+ # Generated by Django 2.0.8 on 2018-10-07 14:20++ from django.db import migrations, models+ from django.utils.text import slugify+++ def re_slug_all_the_things(apps, schema_editor):+ """+ Rewrite all slug values to make sure they're actually slugs before we brand+ them as uneditable.+ """++ Tag = apps.get_model("documents", "Tag")- Correspondent = apps.get_model("documents", "Tag")++ Correspondent = apps.get_model("documents", "Correspondent")++ for klass in (Tag, Correspondent):+ for instance in klass.objects.all():+ klass.objects.filter(+ pk=instance.pk+ ).update(+ slug=slugify(instance.slug)+ )+++ class Migration(migrations.Migration):++ dependencies = [+ ('documents', '0021_document_storage_type'),+ ]++ operations = [+ migrations.AlterModelOptions(+ name='tag',+ options={'ordering': ('name',)},+ ),+ migrations.AlterField(+ model_name='correspondent',+ name='slug',+ field=models.SlugField(blank=True, editable=False),+ ),+ migrations.AlterField(+ model_name='document',+ name='file_type',+ field=models.CharField(choices=[('pdf', 'PDF'), ('png', 'PNG'), ('jpg', 'JPG'), ('gif', 'GIF'), ('tiff', 'TIFF'), ('txt', 'TXT'), ('csv', 'CSV'), ('md', 'MD')], editable=False, max_length=4),+ ),+ migrations.AlterField(+ model_name='tag',+ name='slug',+ field=models.SlugField(blank=True, editable=False),+ ),+ migrations.RunPython(re_slug_all_the_things, migrations.RunPython.noop)+ ]diff --cc src/documents/migrations/1001_workflow_improvements.pyindex cdaf4504c,000000000..11b1a9ebbmode 100644,000000..100644--- a/src/documents/migrations/1001_workflow_improvements.py+++ b/src/documents/migrations/1001_workflow_improvements.py@@@ -1,28 -1,0 +1,28 @@@+# Generated by Django 2.0.7 on 2018-07-12 09:52++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [- ('documents', '0021_document_storage_type'),++ ('documents', '0022_auto_20181007_1420'),+ ]++ operations = [+ migrations.AddField(+ model_name='document',+ name='archive_serial_number',+ field=models.IntegerField(blank=True, db_index=True, help_text='The position of this document in your physical document archive.', null=True, unique=True),+ ),+ migrations.AddField(+ model_name='tag',+ name='is_archived_tag',+ field=models.BooleanField(default=False, help_text='Marks this tag as an archive tag: All documents tagged with archive tags will never be modified automatically (i.e., modifying tags by matching rules)'),+ ),+ migrations.AddField(+ model_name='tag',+ name='is_inbox_tag',+ field=models.BooleanField(default=False, help_text='Marks this tag as an inbox tag: All newly consumed documents will be tagged with inbox tags.'),+ ),+ ]diff --cc src/documents/migrations/1002_auto_20180823_1155.pyindex e8d8098f4,000000000..1f5525a45mode 100644,000000..100644--- a/src/documents/migrations/1002_auto_20180823_1155.py+++ b/src/documents/migrations/1002_auto_20180823_1155.py@@@ -1,33 -1,0 +1,33 @@@+# Generated by Django 2.0.7 on 2018-08-23 11:55++from django.db import migrations, models+import django.db.models.deletion+++class Migration(migrations.Migration):++ dependencies = [- ('documents', '0022_workflow_improvements'),++ ('documents', '1001_workflow_improvements'),+ ]++ operations = [+ migrations.CreateModel(+ name='DocumentType',+ fields=[+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),+ ('name', models.CharField(max_length=128, unique=True)),+ ('slug', models.SlugField(blank=True)),+ ('match', models.CharField(blank=True, max_length=256)),+ ('matching_algorithm', models.PositiveIntegerField(choices=[(1, 'Any'), (2, 'All'), (3, 'Literal'), (4, 'Regular Expression'), (5, 'Fuzzy Match')], default=1, help_text='Which algorithm you want to use when matching text to the OCR\'d PDF. Here, "any" looks for any occurrence of any word provided in the PDF, while "all" requires that every word provided appear in the PDF, albeit not in the order provided. A "literal" match means that the text you enter must appear in the PDF exactly as you\'ve entered it, and "regular expression" uses a regex to match the PDF. (If you don\'t know what a regex is, you probably don\'t want this option.) Finally, a "fuzzy match" looks for words or phrases that are mostly—but not exactly—the same, which can be useful for matching against documents containg imperfections that foil accurate OCR.')),+ ('is_insensitive', models.BooleanField(default=True)),+ ],+ options={+ 'abstract': False,+ },+ ),+ migrations.AddField(+ model_name='document',+ name='document_type',+ field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='documents', to='documents.DocumentType'),+ ),+ ]diff --cc src/documents/migrations/1003_auto_20180904_1425.pyindex 07191d8cf,000000000..01691af7bmode 100644,000000..100644--- a/src/documents/migrations/1003_auto_20180904_1425.py+++ b/src/documents/migrations/1003_auto_20180904_1425.py@@@ -1,77 -1,0 +1,77 @@@+# Generated by Django 2.0.8 on 2018-09-04 14:25++from django.db import migrations, models+++def transfer_automatic_classification(apps, schema_editor):+ for model_name in ["Tag", "Correspondent", "DocumentType"]:+ model_class = apps.get_model("documents", model_name)+ for o in model_class.objects.all():+ o.automatic_classification = o.match is not None and len(o.match) > 0+ o.save()+++def reverse_automatic_classification(apps, schema_editor):+ pass+++class Migration(migrations.Migration):++ dependencies = [- ('documents', '0023_auto_20180823_1155'),++ ('documents', '1002_auto_20180823_1155'),+ ]++ operations = [+ migrations.AddField(+ model_name='correspondent',+ name='automatic_classification',+ field=models.BooleanField(default=False, help_text='Automatically assign to newly added documents based on current usage in your document collection.'),+ ),+ migrations.AddField(+ model_name='documenttype',+ name='automatic_classification',+ field=models.BooleanField(default=False, help_text='Automatically assign to newly added documents based on current usage in your document collection.'),+ ),+ migrations.AddField(+ model_name='tag',+ name='automatic_classification',+ field=models.BooleanField(default=False, help_text='Automatically assign to newly added documents based on current usage in your document collection.'),+ ),+ migrations.RunPython(transfer_automatic_classification, reverse_automatic_classification),+ migrations.RemoveField(+ model_name='correspondent',+ name='is_insensitive',+ ),+ migrations.RemoveField(+ model_name='correspondent',+ name='match',+ ),+ migrations.RemoveField(+ model_name='correspondent',+ name='matching_algorithm',+ ),+ migrations.RemoveField(+ model_name='documenttype',+ name='is_insensitive',+ ),+ migrations.RemoveField(+ model_name='documenttype',+ name='match',+ ),+ migrations.RemoveField(+ model_name='documenttype',+ name='matching_algorithm',+ ),+ migrations.RemoveField(+ model_name='tag',+ name='is_insensitive',+ ),+ migrations.RemoveField(+ model_name='tag',+ name='match',+ ),+ migrations.RemoveField(+ model_name='tag',+ name='matching_algorithm',+ ),+ ]diff --cc src/documents/migrations/1004_documenttype_slug.pyindex 000000000,000000000..557aa46d5new file mode 100644--- /dev/null+++ b/src/documents/migrations/1004_documenttype_slug.py@@@ -1,0 -1,0 +1,36 @@@++# Generated by Django 2.0.8 on 2018-10-07 14:20++++from django.db import migrations, models++from django.utils.text import slugify++++++def re_slug_all_the_things(apps, schema_editor):++ """++ Rewrite all slug values to make sure they're actually slugs before we brand++ them as uneditable.++ """++++ DocumentType = apps.get_model("documents", "DocumentType")++++ for instance in DocumentType.objects.all():++ DocumentType.objects.filter(++ pk=instance.pk++ ).update(++ slug=slugify(instance.slug)++ )++++++class Migration(migrations.Migration):++++ dependencies = [++ ('documents', '1003_auto_20180904_1425'),++ ]++++ operations = [++ migrations.AlterField(++ model_name='documenttype',++ name='slug',++ field=models.SlugField(blank=True, editable=False),++ ),++ migrations.RunPython(re_slug_all_the_things, migrations.RunPython.noop)++ ]diff --cc src/documents/models.pyindex ef2e8a862,37c1cfdbf..4c29fa4b8--- a/src/documents/models.py+++ b/src/documents/models.py@@@ -23,10 -24,42 +24,10 @@@ except ImportErrorclass MatchingModel(models.Model):- MATCH_ANY = 1- MATCH_ALL = 2- MATCH_LITERAL = 3- MATCH_REGEX = 4- MATCH_FUZZY = 5- MATCHING_ALGORITHMS = (- (MATCH_ANY, "Any"),- (MATCH_ALL, "All"),- (MATCH_LITERAL, "Literal"),- (MATCH_REGEX, "Regular Expression"),- (MATCH_FUZZY, "Fuzzy Match"),- )-name = models.CharField(max_length=128, unique=True)- slug = models.SlugField(blank=True)+ slug = models.SlugField(blank=True, editable=False)- match = models.CharField(max_length=256, blank=True)- matching_algorithm = models.PositiveIntegerField(- choices=MATCHING_ALGORITHMS,- default=MATCH_ANY,- help_text=(- "Which algorithm you want to use when matching text to the OCR'd "- "PDF. Here, \"any\" looks for any occurrence of any word "- "provided in the PDF, while \"all\" requires that every word "- "provided appear in the PDF, albeit not in the order provided. A "- "\"literal\" match means that the text you enter must appear in "- "the PDF exactly as you've entered it, and \"regular expression\" "- "uses a regex to match the PDF. (If you don't know what a regex "- "is, you probably don't want this option.) Finally, a \"fuzzy "- "match\" looks for words or phrases that are mostly—but not "- "exactly—the same, which can be useful for matching against "- "documents containg imperfections that foil accurate OCR."- )- )-- is_insensitive = models.BooleanField(default=True)+ automatic_classification = models.BooleanField(default=False, help_text='Automatically assign to newly added documents based on current usage in your document collection.')class Meta:abstract = True@@@ -35,10 -68,87 +36,9 @@@def __str__(self):return self.name- @property- def conditions(self):- return "{}: \"{}\" ({})".format(- self.name, self.match, self.get_matching_algorithm_display())-- @classmethod- def match_all(cls, text, tags=None):-- if tags is None:- tags = cls.objects.all()-- text = text.lower()- for tag in tags:- if tag.matches(text):- yield tag-- def matches(self, text):-- search_kwargs = {}-- # Check that match is not empty- if self.match.strip() == "":- return False-- if self.is_insensitive:- search_kwargs = {"flags": re.IGNORECASE}-- if self.matching_algorithm == self.MATCH_ALL:- for word in self._split_match():- search_result = re.search(- r"\b{}\b".format(word), text, **search_kwargs)- if not search_result:- return False- return True-- if self.matching_algorithm == self.MATCH_ANY:- for word in self._split_match():- if re.search(r"\b{}\b".format(word), text, **search_kwargs):- return True- return False-- if self.matching_algorithm == self.MATCH_LITERAL:- return bool(re.search(- r"\b{}\b".format(self.match), text, **search_kwargs))-- if self.matching_algorithm == self.MATCH_REGEX:- return bool(re.search(- re.compile(self.match, **search_kwargs), text))-- if self.matching_algorithm == self.MATCH_FUZZY:- match = re.sub(r'[^\w\s]', '', self.match)- text = re.sub(r'[^\w\s]', '', text)- if self.is_insensitive:- match = match.lower()- text = text.lower()-- return True if fuzz.partial_ratio(match, text) >= 90 else False-- raise NotImplementedError("Unsupported matching algorithm")-- def _split_match(self):- """- Splits the match to individual keywords, getting rid of unnecessary- spaces and grouping quoted words together.-- Example:- ' some random words "with quotes " and spaces'- ==>- ["some", "random", "words", "with+quotes", "and", "spaces"]- """- findterms = re.compile(r'"([^"]+)"|(\S+)').findall- normspace = re.compile(r"\s+").sub- return [- normspace(" ", (t[0] or t[1]).strip()).replace(" ", r"\s+")- for t in findterms(self.match)- ]-def save(self, *args, **kwargs):- if not self.slug:- self.slug = slugify(self.name)- self.match = self.match.lower()+ self.slug = slugify(self.name)models.Model.save(self, *args, **kwargs)diff --cc src/paperless/settings.pyindex b3725f4b6,d862837a1..21a00869amode 100755,100644..100755--- a/src/paperless/settings.py+++ b/src/paperless/settings.py@@@ -199,11 -203,16 +203,21 @@@ STATIC_URL = os.getenv("PAPERLESS_STATIMEDIA_URL = os.getenv("PAPERLESS_MEDIA_URL", "/media/")+ # Other++ # Disable Django's artificial limit on the number of form fields to submit at+ # once. This is a protection against overloading the server, but since this is+ # a self-hosted sort of gig, the benefits of being able to mass-delete a tonne+ # of log entries outweight the benefits of such a safeguard.++ DATA_UPLOAD_MAX_NUMBER_FIELDS = None+++# Document classification models location+MODEL_FILE = os.getenv(+ "PAPERLESS_MODEL_FILE", os.path.join(BASE_DIR, "..", "models", "model.pickle"))++# Paperless-specific stuff# You shouldn't have to edit any of these values. Rather, you can set these# values in /etc/paperless.conf instead.