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 feature-websockets-status
jonaswinkler9f9581e1f8aa
diff --cc Pipfileindex 0e89efd9f,f6301b98f..23c31f1f2--- a/Pipfile+++ b/Pipfile@@@ -40,9 -42,7 +42,10 @@@ whoosh="~=2.7.4inotifyrecursive = "~=0.3.4"ocrmypdf = "*"tqdm = "*"+ tika = "*"+channels = "~=3.0"+channels-redis = "*"+daphne = "~=3.0"[dev-packages]coveralls = "*"diff --cc src-ui/src/app/app.component.tsindex 61df1e6eb,73c5fc861..55c23b4de--- a/src-ui/src/app/app.component.ts+++ b/src-ui/src/app/app.component.ts@@@ -1,43 -1,17 +1,47 @@@-import { Component } from '@angular/core';+ import { SettingsService } from './services/settings.service';+import { Component, OnDestroy, OnInit } from '@angular/core';+import { Router } from '@angular/router';+import { Subscription } from 'rxjs';+import { ConsumerStatusService } from './services/consumer-status.service';+import { Toast, ToastService } from './services/toast.service';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss']})-export class AppComponent {+export class AppComponent implements OnInit, OnDestroy {- constructor (private settings: SettingsService) {+ successSubscription: Subscription;+ failedSubscription: Subscription;-- constructor ( private consumerStatusService: ConsumerStatusService, private toastService: ToastService, private router: Router ) {++++ constructor (private settings: SettingsService, private consumerStatusService: ConsumerStatusService, private toastService: ToastService, private router: Router) {+ let anyWindow = (window as any)+ anyWindow.pdfWorkerSrc = '/assets/js/pdf.worker.min.js';+ this.settings.updateDarkModeSettings()}+ ngOnDestroy(): void {+ this.consumerStatusService.disconnect()+ this.successSubscription.unsubscribe()+ this.failedSubscription.unsubscribe()+ }++ ngOnInit(): void {+ this.consumerStatusService.connect()++ this.successSubscription = this.consumerStatusService.onDocumentConsumptionFinished().subscribe(status => {+ this.toastService.showToast({title: "Document added", content: `Document ${status.filename} was added to paperless.`, actionName: "Open document", action: () => {+ this.router.navigate(['documents', status.document_id])+ }})+ })++ this.failedSubscription = this.consumerStatusService.onDocumentConsumptionFailed().subscribe(status => {+ this.toastService.showError(`Could not consume ${status.filename}: ${status.message}`)+ })++ }+-+++}diff --cc src-ui/src/app/app.module.tsindex f421e2cd6,8cd28b6fc..130c474a1--- a/src-ui/src/app/app.module.ts+++ b/src-ui/src/app/app.module.ts@@@ -45,8 -48,16 +48,17 @@@ import { SavedViewWidgetComponent } froimport { StatisticsWidgetComponent } from './components/dashboard/widgets/statistics-widget/statistics-widget.component';import { UploadFileWidgetComponent } from './components/dashboard/widgets/upload-file-widget/upload-file-widget.component';import { WidgetFrameComponent } from './components/dashboard/widgets/widget-frame/widget-frame.component';+ import { PdfViewerModule } from 'ng2-pdf-viewer';import { WelcomeWidgetComponent } from './components/dashboard/widgets/welcome-widget/welcome-widget.component';+ import { YesNoPipe } from './pipes/yes-no.pipe';+ import { FileSizePipe } from './pipes/file-size.pipe';+ import { FilterPipe } from './pipes/filter.pipe';+ import { DocumentTitlePipe } from './pipes/document-title.pipe';+ import { MetadataCollapseComponent } from './components/document-detail/metadata-collapse/metadata-collapse.component';+ import { SelectDialogComponent } from './components/common/select-dialog/select-dialog.component';+ import { NgSelectModule } from '@ng-select/ng-select';+ import { NumberComponent } from './components/common/input/number/number.component';+import { ConsumerStatusWidgetComponent } from './components/dashboard/widgets/consumer-status-widget/consumer-status-widget.component';@NgModule({declarations: [@@@ -86,7 -100,13 +101,14 @@@UploadFileWidgetComponent,WidgetFrameComponent,WelcomeWidgetComponent,+ YesNoPipe,+ FileSizePipe,+ FilterPipe,+ DocumentTitlePipe,+ MetadataCollapseComponent,+ SelectDialogComponent,- NumberComponent++ NumberComponent,+ ConsumerStatusWidgetComponent],imports: [BrowserModule,diff --cc src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.tsindex f53e3ebfc,f200d8db9..9039e7cec--- a/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.ts+++ b/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.ts@@@ -1,10 -1,8 +1,10 @@@-import { Component, Input, OnInit } from '@angular/core';+import { Component, Input, OnDestroy, OnInit } from '@angular/core';import { Router } from '@angular/router';+import { Subscription } from 'rxjs';import { PaperlessDocument } from 'src/app/data/paperless-document';- import { SavedViewConfig } from 'src/app/data/saved-view-config';+ import { PaperlessSavedView } from 'src/app/data/paperless-saved-view';import { DocumentListViewService } from 'src/app/services/document-list-view.service';+import { ConsumerStatusService } from 'src/app/services/consumer-status.service';import { DocumentService } from 'src/app/services/rest/document.service';@Component({@@@ -17,29 -15,15 +17,29 @@@ export class SavedViewWidgetComponent iconstructor(private documentService: DocumentService,private router: Router,- private list: DocumentListViewService) { }-+ private list: DocumentListViewService,+ private consumerStatusService: ConsumerStatusService) { }+@Input()- savedView: SavedViewConfig+ savedView: PaperlessSavedViewdocuments: PaperlessDocument[] = []+ subscription: Subscription+ngOnInit(): void {+ this.reload()+ this.subscription = this.consumerStatusService.onDocumentConsumptionFinished().subscribe(status => {+ this.reload()+ })+ }++ ngOnDestroy(): void {+ this.subscription.unsubscribe()+ }++ reload() {- this.documentService.list(1,10,this.savedView.sortField,this.savedView.sortDirection,this.savedView.filterRules).subscribe(result => {+ this.documentService.listFiltered(1,10,this.savedView.sort_field, this.savedView.sort_reverse, this.savedView.filter_rules).subscribe(result => {this.documents = result.results})}diff --cc src-ui/src/app/components/dashboard/widgets/statistics-widget/statistics-widget.component.htmlindex c8beb1d28,0ad0005ea..6ab996675--- a/src-ui/src/app/components/dashboard/widgets/statistics-widget/statistics-widget.component.html+++ b/src-ui/src/app/components/dashboard/widgets/statistics-widget/statistics-widget.component.html@@@ -1,6 -1,6 +1,6 @@@- <app-widget-frame title="Statistics">+ <app-widget-frame title="Statistics" i18n-title><ng-container content>- <p class="card-text">Documents in inbox: {{statistics.documents_inbox}}</p>- <p class="card-text">Total documents: {{statistics.documents_total}}</p>+ <p class="card-text" i18n>Documents in inbox: {{statistics.documents_inbox}}</p>+ <p class="card-text" i18n>Total documents: {{statistics.documents_total}}</p></ng-container>-</app-widget-frame>+</app-widget-frame>diff --cc src-ui/src/app/components/dashboard/widgets/upload-file-widget/upload-file-widget.component.tsindex 16a220229,2b14a571a..19d9909a9--- a/src-ui/src/app/components/dashboard/widgets/upload-file-widget/upload-file-widget.component.ts+++ b/src-ui/src/app/components/dashboard/widgets/upload-file-widget/upload-file-widget.component.ts@@@ -1,7 -2,13 +2,13 @@@ import { HttpEventType } from '@angularimport { Component, OnInit } from '@angular/core';import { FileSystemFileEntry, NgxFileDropEntry } from 'ngx-file-drop';import { DocumentService } from 'src/app/services/rest/document.service';- import { Toast, ToastService } from 'src/app/services/toast.service';+ import { ToastService } from 'src/app/services/toast.service';+++ interface UploadStatus {+ loaded: number- total: number++ total: number+ }@Component({selector: 'app-upload-file-widget',@@@ -24,16 -44,31 +44,31 @@@ export class UploadFileWidgetComponentpublic dropped(files: NgxFileDropEntry[]) {for (const droppedFile of files) {if (droppedFile.fileEntry.isFile) {- const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;+ let uploadStatusObject: UploadStatus = {loaded: 0, total: 1}+ this.uploadStatus.push(uploadStatusObject)+ this.uploadVisible = true++ const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;fileEntry.file((file: File) => {- const formData = new FormData()+ let formData = new FormData()formData.append('document', file, file.name)- this.documentService.uploadDocument(formData).subscribe(result => {- this.toastService.showInfo("The document has been uploaded and will be processed by the consumer shortly.")++ this.documentService.uploadDocument(formData).subscribe(event => {+ if (event.type == HttpEventType.UploadProgress) {+ uploadStatusObject.loaded = event.loaded+ uploadStatusObject.total = event.total+ } else if (event.type == HttpEventType.Response) {+ this.uploadStatus.splice(this.uploadStatus.indexOf(uploadStatusObject), 1)+ this.completedFiles += 1+ this.toastService.showInfo($localize`The document has been uploaded and will be processed by the consumer shortly.`)+ }-++}, error => {+ this.uploadStatus.splice(this.uploadStatus.indexOf(uploadStatusObject), 1)+ this.completedFiles += 1switch (error.status) {case 400: {- this.toastService.showError(`There was an error while uploading the document: ${error.error.document}`)+ this.toastService.showInfo($localize`There was an error while uploading the document: ${error.error.document}`)break;}default: {diff --cc src-ui/src/app/components/document-list/document-list.component.tsindex 4dc986d51,84daf7e22..db9fbb52e--- a/src-ui/src/app/components/document-list/document-list.component.ts+++ b/src-ui/src/app/components/document-list/document-list.component.ts@@@ -19,18 -20,25 +20,25 @@@ export class DocumentListComponent implconstructor(public list: DocumentListViewService,- public savedViewConfigService: SavedViewConfigService,+ public savedViewService: SavedViewService,public route: ActivatedRoute,+ private router: Router,private toastService: ToastService,- public modalService: NgbModal) { }+ private modalService: NgbModal) { }++ @ViewChild("filterEditor")+ private filterEditor: FilterEditorComponent++ @ViewChildren(SortableDirective) headers: QueryList<SortableDirective>;-+displayMode = 'smallCards' // largeCards, smallCards, details- filterRules: FilterRule[] = []- showFilter = false+ get isFiltered() {+ return this.list.filterRules?.length > 0+ }getTitle() {- return this.list.savedViewTitle || "Documents"+ return this.list.savedViewTitle || $localize`Documents`}getSortFields() {diff --cc src-ui/src/app/services/toast.service.tsindex d5781139e,86d66eee6..fc522e2df--- a/src-ui/src/app/services/toast.service.ts+++ b/src-ui/src/app/services/toast.service.ts@@@ -7,12 -7,8 +7,12 @@@ export interface Toastcontent: string- delay?: number+ delay: number+ action?: any++ actionName?: string+}@Injectable({diff --cc src-ui/src/environments/environment.tsindex c945a0364,29a8f3af6..da87c55e9--- a/src-ui/src/environments/environment.ts+++ b/src-ui/src/environments/environment.ts@@@ -5,7 -5,8 +5,9 @@@export const environment = {production: false,apiBaseUrl: "http://localhost:8000/api/",+ appTitle: "Paperless-ng",+ version: "DEVELOPMENT"+ wsBaseUrl: "ws://localhost:8000/ws/"};/*diff --cc src/documents/consumer.pyindex 30c57e6a0,134137e2f..1cd05d2be--- a/src/documents/consumer.py+++ b/src/documents/consumer.py@@@ -1,11 -1,9 +1,11 @@@import datetimeimport hashlib- import loggingimport os+ from subprocess import Popenimport magic+from asgiref.sync import async_to_sync+from channels.layers import get_channel_layerfrom django.conf import settingsfrom django.db import transactionfrom django.db.models import Q@@@ -57,11 -38,14 +59,15 @@@ class Consumer(LoggingMixin)self.override_tag_ids = Noneself.override_document_type_id = None+ self.channel_layer = get_channel_layer()+def pre_check_file_exists(self):if not os.path.isfile(self.path):+ self.log(+ "error",+ "Cannot consume {}: It is not a file.".format(self.path)+ )- raise ConsumerError("Cannot consume {}: It is not a file".format(- self.path))+ self._fail("File not found")def pre_check_duplicate(self):with open(self.path, "rb") as f:@@@ -69,7 -53,13 +75,11 @@@if Document.objects.filter(Q(checksum=checksum) | Q(archive_checksum=checksum)).exists(): # NOQA: E501if settings.CONSUMER_DELETE_DUPLICATES:os.unlink(self.path)+ self.log(+ "error",+ "Not consuming {}: It is a duplicate.".format(self.filename)+ )- raise ConsumerError(- "Not consuming {}: It is a duplicate.".format(self.filename)- )+ self._fail("Document is a duplicate")def pre_check_directories(self):os.makedirs(settings.SCRATCH_DIR, exist_ok=True)@@@ -115,13 -135,15 +158,14 @@@mime_type = magic.from_file(self.path, mime=True)+ self.log("debug", f"Detected mime type: {mime_type}")+parser_class = get_parser_class_for_mime_type(mime_type)if not parser_class:- self._fail("No parsers abvailable")- raise ConsumerError(- f"Unsupported mime type {mime_type} of file {self.filename}")++ self._fail(f"Unsupported mime type {mime_type}")else:self.log("debug",- f"Parser: {parser_class.__name__} "- f"based on mime type {mime_type}")+ f"Parser: {parser_class.__name__}")# Notify all listeners that we're going to do some work.@@@ -131,14 -153,11 +175,16 @@@logging_group=self.logging_group)+ self.run_pre_consume_script()++ def progress_callback(current_progress, max_progress, message):+ # recalculate progress to be within 20 and 80+ p = int((current_progress / max_progress) * 50 + 20)+ 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.logging_group)+ document_parser = parser_class(self.logging_group, progress_callback)# However, this already created working directories which we have to# clean up.@@@ -146,14 -165,10 +192,14 @@@# Parse the document. This may take some time.try:+ self._send_progress(self.filename, 20, 100, 'WORKING',+ 'Parsing document...')self.log("debug", "Parsing {}...".format(self.filename))- document_parser.parse(self.path, mime_type)+ document_parser.parse(self.path, mime_type, self.filename)self.log("debug", f"Generating thumbnail for {self.filename}...")+ self._send_progress(self.filename, 70, 100, 'WORKING',+ 'Generating thumbnail...')thumbnail = document_parser.get_optimised_thumbnail(self.path, mime_type)@@@ -181,12 -194,12 +227,13 @@@try:classifier = DocumentClassifier()classifier.reload()- except (FileNotFoundError, IncompatibleClassifierVersionError) as e:- logging.getLogger(__name__).warning(- "Cannot classify documents: {}.".format(e))+ except (OSError, EOFError, IncompatibleClassifierVersionError) as e:+ self.log(+ "warning",+ f"Cannot classify documents: {e}.")classifier = None-+ self._send_progress(self.filename, 95, 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:diff --cc src/documents/parsers.pyindex e525221dd,371a53c4b..75c69ce6c--- a/src/documents/parsers.py+++ b/src/documents/parsers.py@@@ -207,18 -254,21 +254,22 @@@ class DocumentParser(LoggingMixin)`paperless_tesseract.parsers` for inspiration."""- def __init__(self, logging_group):+ def __init__(self, logging_group, progress_callback):super().__init__()self.logging_group = logging_group+ os.makedirs(settings.SCRATCH_DIR, exist_ok=True)self.tempdir = tempfile.mkdtemp(prefix="paperless-", dir=settings.SCRATCH_DIR)self.archive_path = Noneself.text = Noneself.date = None+ self.progress_callback = progress_callback- def parse(self, document_path, mime_type):+ def extract_metadata(self, document_path, mime_type):+ return []++ def parse(self, document_path, mime_type, file_name=None):raise NotImplementedError()def get_archive_path(self):diff --cc src/paperless/settings.pyindex d8129970b,1fd54823f..9b0160c82--- a/src/paperless/settings.py+++ b/src/paperless/settings.py@@@ -91,9 -100,7 +100,9 @@@ INSTALLED_APPS ="django_q",+ "channels",+- ]+ ] + env_appsREST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES': [diff --cc src/paperless/urls.pyindex 2d75907a2,49e6e8b7a..5b58de454--- a/src/paperless/urls.py+++ b/src/paperless/urls.py@@@ -7,7 -7,8 +7,9 @@@ from django.views.generic import Redirefrom rest_framework.authtoken import viewsfrom rest_framework.routers import DefaultRouter+ from django.utils.translation import gettext_lazy as _++from paperless.consumers import StatusConsumerfrom documents.views import (CorrespondentViewSet,DocumentViewSet,