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 Winklerd252a1dcda95
diff --cc Pipfileindex 8cb84f44b,ad60e0905..e9caaddd5--- a/Pipfile+++ b/Pipfile@@@ -9,35 -9,32 +9,35 @@@ verify_ssl = truname = "piwheels"[packages]- django = "~=3.1"- pillow = "*"- dateparser = "~=0.7"+ dateparser = "~=0.7.6"+ django = "~=3.1.3"django-cors-headers = "*"- djangorestframework = "~=3.12"- python-gnupg = "*"- python-dotenv = "*"- filemagic = "*"- pyocr = "~=0.7"+ django-extensions = "*"+ django-filter = "~=2.4.0"+ django-q = "~=1.3.4"+ djangorestframework = "~=3.12.2"+ fuzzywuzzy = "*"+ gunicorn = "*"+ imap-tools = "*"langdetect = "*"pdftotext = "*"- django-filter = "~=2.4"+ pathvalidate = "*"+ pillow = "*"+ pyocr = "~=0.7.2"+ python-gnupg = "*"+ python-dotenv = "*"python-dateutil = "*"- psycopg2-binary = "*"- scikit-learn="~=0.23"- whoosh="~=2.7"- gunicorn = "*"- whitenoise = "~=5.2"- fuzzywuzzy = "*"python-Levenshtein = "*"- django-extensions = "*"- watchdog = "*"- pathvalidate = "*"- django-q = "*"+ python-magic = "*"+ psycopg2-binary = "*"redis = "*"- imap-tools = "*"+ scikit-learn="~=0.23.2"+ whitenoise = "~=5.2.0"+ watchdog = "*"+ whoosh="~=2.7.4"+channels = "~=3.0"+channels-redis = "*"+daphne = "~=3.0"[dev-packages]coveralls = "*"diff --cc src-ui/src/app/app.component.tsindex 5809968e8,84c173a18..61df1e6eb--- a/src-ui/src/app/app.component.ts+++ b/src-ui/src/app/app.component.ts@@@ -7,37 -3,12 +7,37 @@@ import { Toast, ToastService } from './@Component({selector: 'app-root',templateUrl: './app.component.html',- styleUrls: ['./app.component.css']+ styleUrls: ['./app.component.scss']})-export class AppComponent {+export class AppComponent implements OnInit, OnDestroy {++ successSubscription: Subscription;+ failedSubscription: Subscription;- constructor () {+ constructor ( private consumerStatusService: ConsumerStatusService, private toastService: ToastService, private router: Router ) {+ }++ 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/components/dashboard/dashboard.component.htmlindex 1c51324a5,c24d633a9..68a8da2f5--- a/src-ui/src/app/components/dashboard/dashboard.component.html+++ b/src-ui/src/app/components/dashboard/dashboard.component.html@@@ -1,16 -1,25 +1,27 @@@-- <app-page-header title="Dashboard">+ <app-page-header title="Dashboard" subTitle="Welcome to paperless-ng!">+ <img src="assets/logo.svg" height="80" class="m-2 d-none d-md-block"></app-page-header>- <p>Welcome to paperless-ng!</p>-<div class='row'><div class="col-lg">- <app-saved-view-widget [viewConfig]="conf" *ngFor="let conf of savedViewConfigService.getDashboardConfigs()"></app-saved-view-widget>+ <app-widget-frame title="Saved views" *ngIf="savedViews.length == 0">+ <p class="card-text">This space is reserved to display your saved views. Go to your documents and save a view+ to have it displayed+ here!</p>+ </app-widget-frame>++ <ng-container *ngFor="let v of savedViews">+ <app-saved-view-widget [savedView]="v"></app-saved-view-widget>+ </ng-container>+</div><div class="col-lg">+<app-statistics-widget></app-statistics-widget>- <app-file-upload-widget></app-file-upload-widget>++ <app-upload-file-widget></app-upload-file-widget>++ <app-consumer-status-widget></app-consumer-status-widget>++</div>-</div>+</div>diff --cc src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.htmlindex 110464641,712e4dec7..870bf804b--- a/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html+++ b/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html@@@ -1,16 -1,18 +1,18 @@@- <h4>{{viewConfig.title}}</h4>+ <app-widget-frame [title]="savedView.title">- <table class="table table-sm table-hover table-borderless">- <thead>- <tr>- <th>Date created</th>- <th scope="col">Document</th>- </tr>- </thead>- <tbody>- <tr *ngFor="let doc of documents" routerLink="/documents/{{doc.id}}">- <td>{{doc.created | date}}</td>- <td>{{doc.title}}<app-tag [tag]="t" *ngFor="let t of doc.tags" class="ml-1"></app-tag>- </tr>- </tbody>- </table>+ <table class="table table-sm table-hover table-borderless">+ <thead>+ <tr>+ <th>Created</th>+ <th scope="col">Title</th>+ </tr>+ </thead>+ <tbody>+ <tr *ngFor="let doc of documents" routerLink="/documents/{{doc.id}}">+ <td>{{doc.created | date}}</td>+ <td>{{doc.title}}<app-tag [tag]="t" *ngFor="let t of doc.tags" class="ml-1"></app-tag>+ </tr>+ </tbody>+ </table>+-</app-widget-frame>++</app-widget-frame>diff --cc src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.tsindex eb2d53aee,9b124715f..405c82f7a--- 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@@@ -8,32 -6,19 +8,32 @@@ import { DocumentService } from 'src/ap@Component({selector: 'app-saved-view-widget',templateUrl: './saved-view-widget.component.html',- styleUrls: ['./saved-view-widget.component.css']+ styleUrls: ['./saved-view-widget.component.scss']})- export class SavedViewWidgetComponent implements OnInit, OnDestroy {+ export class SavedViewWidgetComponent implements OnInit {- constructor(private documentService: DocumentService) { }-+ constructor(private documentService: DocumentService, private consumerStatusService: ConsumerStatusService) { }+@Input()- viewConfig: SavedViewConfig+ savedView: SavedViewConfig- documents: PaperlessDocument[]+ documents: 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.viewConfig.sortField,this.viewConfig.sortDirection,this.viewConfig.filterRules).subscribe(result => {+ this.documentService.list(1,10,this.savedView.sortField,this.savedView.sortDirection,this.savedView.filterRules).subscribe(result => {this.documents = result.results})}diff --cc src-ui/src/app/components/dashboard/widgets/statistics-widget/statistics-widget.component.htmlindex 2f89a2b34,693935290..4e8049a69--- 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,3 -1,4 +1,4 @@@- <h4>Statistics</h4>- <p>Documents in inbox: {{statistics.documents_inbox}}</p>- <p>Total documents: {{statistics.documents_total}}</p>+ <app-widget-frame title="Statistics">+ <p class="card-text">Documents in inbox: {{statistics.documents_inbox}}</p>+ <p class="card-text">Total documents: {{statistics.documents_total}}</p>-</app-widget-frame>++</app-widget-frame>diff --cc src-ui/src/app/components/dashboard/widgets/statistics-widget/statistics-widget.component.tsindex 4efb03895,73eee698c..c3f45d63c--- a/src-ui/src/app/components/dashboard/widgets/statistics-widget/statistics-widget.component.ts+++ b/src-ui/src/app/components/dashboard/widgets/statistics-widget/statistics-widget.component.ts@@@ -19,6 -20,10 +20,10 @@@ export class StatisticsWidgetComponentstatistics: Statistics = {}+ getStatistics(): Observable<Statistics> {+ return this.http.get(`${environment.apiBaseUrl}statistics/`)+ }-++ngOnInit(): void {this.getStatistics().subscribe(statistics => {this.statistics = statisticsdiff --cc src/documents/consumer.pyindex 8edbb00a3,65febc937..8abee7918--- a/src/documents/consumer.py+++ b/src/documents/consumer.py@@@ -2,10 -2,8 +2,10 @@@ import datetimimport hashlibimport loggingimport os- import re+ import magic+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@@@ -156,16 -128,10 +153,16 @@@ class Consumer(LoggingMixin)# Parse the document. This may take some time.try:- self.log("debug", "Generating thumbnail for {}...".format(self.filename))+ self.log("debug", f"Generating thumbnail for {self.filename}...")+ self._send_progress(self.filename, 10, 100, 'WORKING',+ 'Generating thumbnail...')thumbnail = document_parser.get_optimised_thumbnail()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(self.filename, 80, 100, 'WORKING',+ 'Getting date from document...')date = document_parser.get_date()except ParseError as e:document_parser.cleanup()@@@ -234,12 -193,9 +232,12 @@@"Document {} consumption finished".format(document))+ self._send_progress(self.filename, 100, 100, 'SUCCESS',+ 'Finished.', document.id)+return document- def _store(self, text, date):+ def _store(self, text, date, mime_type):# If someone gave us the original filename, use it instead of doc.diff --cc src/documents/parsers.pyindex af4681d55,eb8ccf45e..81198868d--- a/src/documents/parsers.py+++ b/src/documents/parsers.py@@@ -112,8 -138,8 +138,9 @@@ class DocumentParser(LoggingMixin)super().__init__()self.logging_group = logging_groupself.document_path = path- self.tempdir = tempfile.mkdtemp(prefix="paperless-", dir=settings.SCRATCH_DIR)+ self.tempdir = tempfile.mkdtemp(+ prefix="paperless-", dir=settings.SCRATCH_DIR)+ self.progress_callback = progress_callbackdef get_thumbnail(self):"""diff --cc src/paperless/urls.pyindex 07d109587,dd5e6a379..f422729fa--- a/src/paperless/urls.py+++ b/src/paperless/urls.py@@@ -65,14 -78,8 +79,13 @@@ urlpatterns =# Root of the Frontentre_path(r".*", login_required(IndexView.as_view())),-]++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-ng'# Text at the end of each page's <title>.diff --cc src/paperless_tesseract/parsers.pyindex 11a6c8b37,b8320a4f0..5832a27dd--- a/src/paperless_tesseract/parsers.py+++ b/src/paperless_tesseract/parsers.py@@@ -99,27 -101,39 +102,41 @@@ class RasterisedDocumentParser(Documenttry:sample_page_index = int(len(images) / 2)- self.log("debug", "Attempting language detection on page {} of {}...".format(sample_page_index + 1, len(images)))+ self.log(+ "debug",+ f"Attempting language detection on page "+ f"{sample_page_index + 1} of {len(images)}...")-+ self.progress_callback(0.4, 1, "Language Detection.")- sample_page_text = self._ocr([images[sample_page_index]], settings.OCR_LANGUAGE)[0]+ 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.")- ocr_pages = self._complete_ocr_default_language(images, sample_page_index, sample_page_text)+ ocr_pages = self._complete_ocr_default_language(+ images, sample_page_index, sample_page_text)elif ISO639[guessed_language] == settings.OCR_LANGUAGE:- self.log("debug", "Detected language: {} (default language)".format(guessed_language))- ocr_pages = self._complete_ocr_default_language(images, sample_page_index, sample_page_text)-- elif not ISO639[guessed_language] in pyocr.get_available_tools()[0].get_available_languages():- self.log("warning", "Detected language {} is not available on this system.".format(guessed_language))- ocr_pages = self._complete_ocr_default_language(images, sample_page_index, sample_page_text)+ self.log(+ "debug",+ f"Detected language: {guessed_language} "+ f"(default language)")+ ocr_pages = self._complete_ocr_default_language(+ images, sample_page_index, sample_page_text)++ elif not ISO639[guessed_language] in pyocr.get_available_tools()[0].get_available_languages(): # NOQA: E501+ self.log(+ "warning",+ f"Detected language {guessed_language} is not available "+ f"on this system.")+ ocr_pages = self._complete_ocr_default_language(+ images, sample_page_index, sample_page_text)else:- self.log("debug", "Detected language: {}".format(guessed_language))- ocr_pages = self._ocr(images, ISO639[guessed_language], report_progress=True)+ self.log("debug", f"Detected language: {guessed_language}")- ocr_pages = self._ocr(images, ISO639[guessed_language])++ ocr_pages = self._ocr(++ images, ISO639[guessed_language], report_progress=True)self.log("debug", "OCR completed.")self._text = strip_excess_whitespace(" ".join(ocr_pages))@@@ -151,10 -174,8 +177,10 @@@if f.endswith(".pnm"):pnms.append(os.path.join(self.tempdir, f))- self.log("debug", "Running unpaper on {} pages...".format(len(pnms)))+ self.log("debug", f"Running unpaper on {len(pnms)} pages...")+ self.progress_callback(0.2,1, "Running unpaper on {} pages...".format(len(pnms)))+# Run unpaper in parallel on converted imageswith ThreadPool(processes=settings.THREADS_PER_WORKER) as pool:pnms = pool.map(run_unpaper, pnms)@@@ -166,32 -187,26 +192,32 @@@guess = langdetect.detect(text)return guessexcept Exception as e:- self.log('warning', "Language detection failed with: {}".format(e))+ self.log('warning', f"Language detection failed with: {e}")return None- def _ocr(self, imgs, lang):+ def _ocr(self, imgs, lang, report_progress=False):- self.log("debug", "Performing OCR on {} page(s) with language {}".format(len(imgs), lang))+ self.log(+ "debug",+ f"Performing OCR on {len(imgs)} page(s) with language {lang}")+ r = []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 r- def _complete_ocr_default_language(self, images, sample_page_index, sample_page):- """- Given a `middle` value and the text that middle page represents, we OCR- the remainder of the document and return the whole thing.- """- # text = self._ocr(imgs[:middle], settings.OCR_LANGUAGE) + text- # text += self._ocr(imgs[middle + 1:], settings.OCR_LANGUAGE)+ def _complete_ocr_default_language(self,+ images,+ sample_page_index,+ sample_page):images_copy = list(images)del images_copy[sample_page_index]if images_copy:- self.log('debug', 'Continuing ocr with default language.')- ocr_pages = self._ocr(images_copy, settings.OCR_LANGUAGE, report_progress=True)+ 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: