We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[BUG] CONSUME_SUBDIRS_AS_TAGS not working when using CONSUMER_ENABLE_BARCODES
### Description

my scanner puts files into a specific subdirectory of the `CONSUMPTION_DIR`. However when `CONSUMER_ENABLE_BARCODES` is enabled and a barcode is detected the split documents don't have the expected tags.

It looks like this is caused by `save_to_dir()` in `src/documents/tasks.py` and the fact that it always stores the new documents into `CONSUMPTION_DIR`

### Steps to reproduce

1. enable CONSUMER_ENABLE_BARCODES and CONSUME_SUBDIRS_AS_TAGS 
2. put document with correct Barcode into <CONSUMPTION_DIR>/foo
3. wait for import
4. imported documents don't have the tag `foo`

### Webserver logs

_No response_

### Paperless-ngx version

1.7.1

### Host OS

Debian

### Installation method

Bare metal

### Browser

_No response_

### Configuration changes

_No response_

### Other

_No response_

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/documents/tasks.py`
Content:
```
1 import logging
2 import os
3 import shutil
4 from pathlib import Path
5 from typing import Type
6 
7 import tqdm
8 from asgiref.sync import async_to_sync
9 from channels.layers import get_channel_layer
10 from django.conf import settings
11 from django.core.exceptions import ObjectDoesNotExist
12 from django.db.models.signals import post_save
13 from documents import barcodes
14 from documents import index
15 from documents import sanity_checker
16 from documents.classifier import DocumentClassifier
17 from documents.classifier import load_classifier
18 from documents.consumer import Consumer
19 from documents.consumer import ConsumerError
20 from documents.models import Correspondent
21 from documents.models import Document
22 from documents.models import DocumentType
23 from documents.models import StoragePath
24 from documents.models import Tag
25 from documents.parsers import DocumentParser
26 from documents.parsers import get_parser_class_for_mime_type
27 from documents.parsers import ParseError
28 from documents.sanity_checker import SanityCheckFailedException
29 from whoosh.writing import AsyncWriter
30 
31 
32 logger = logging.getLogger("paperless.tasks")
33 
34 
35 def index_optimize():
36     ix = index.open_index()
37     writer = AsyncWriter(ix)
38     writer.commit(optimize=True)
39 
40 
41 def index_reindex(progress_bar_disable=False):
42     documents = Document.objects.all()
43 
44     ix = index.open_index(recreate=True)
45 
46     with AsyncWriter(ix) as writer:
47         for document in tqdm.tqdm(documents, disable=progress_bar_disable):
48             index.update_document(writer, document)
49 
50 
51 def train_classifier():
52     if (
53         not Tag.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()
54         and not DocumentType.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()
55         and not Correspondent.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()
56         and not StoragePath.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()
57     ):
58 
59         return
60 
61     classifier = load_classifier()
62 
63     if not classifier:
64         classifier = DocumentClassifier()
65 
66     try:
67         if classifier.train():
68             logger.info(
69                 f"Saving updated classifier model to {settings.MODEL_FILE}...",
70             )
71             classifier.save()
72         else:
73             logger.debug("Training data unchanged.")
74 
75     except Exception as e:
76         logger.warning("Classifier error: " + str(e))
77 
78 
79 def consume_file(
80     path,
81     override_filename=None,
82     override_title=None,
83     override_correspondent_id=None,
84     override_document_type_id=None,
85     override_tag_ids=None,
86     task_id=None,
87     override_created=None,
88 ):
89 
90     # check for separators in current document
91     if settings.CONSUMER_ENABLE_BARCODES:
92 
93         mime_type = barcodes.get_file_mime_type(path)
94 
95         if not barcodes.supported_file_type(mime_type):
96             # if not supported, skip this routine
97             logger.warning(
98                 f"Unsupported file format for barcode reader: {str(mime_type)}",
99             )
100         else:
101             separators = []
102             document_list = []
103 
104             if mime_type == "image/tiff":
105                 file_to_process = barcodes.convert_from_tiff_to_pdf(path)
106             else:
107                 file_to_process = path
108 
109             separators = barcodes.scan_file_for_separating_barcodes(file_to_process)
110 
111             if separators:
112                 logger.debug(
113                     f"Pages with separators found in: {str(path)}",
114                 )
115                 document_list = barcodes.separate_pages(file_to_process, separators)
116 
117             if document_list:
118                 for n, document in enumerate(document_list):
119                     # save to consumption dir
120                     # rename it to the original filename  with number prefix
121                     if override_filename:
122                         newname = f"{str(n)}_" + override_filename
123                     else:
124                         newname = None
125                     barcodes.save_to_dir(document, newname=newname)
126 
127                 # if we got here, the document was successfully split
128                 # and can safely be deleted
129                 if mime_type == "image/tiff":
130                     # Remove the TIFF converted to PDF file
131                     logger.debug(f"Deleting file {file_to_process}")
132                     os.unlink(file_to_process)
133                 # Remove the original file (new file is saved above)
134                 logger.debug(f"Deleting file {path}")
135                 os.unlink(path)
136 
137                 # notify the sender, otherwise the progress bar
138                 # in the UI stays stuck
139                 payload = {
140                     "filename": override_filename,
141                     "task_id": task_id,
142                     "current_progress": 100,
143                     "max_progress": 100,
144                     "status": "SUCCESS",
145                     "message": "finished",
146                 }
147                 try:
148                     async_to_sync(get_channel_layer().group_send)(
149                         "status_updates",
150                         {"type": "status_update", "data": payload},
151                     )
152                 except OSError as e:
153                     logger.warning(
154                         "OSError. It could be, the broker cannot be reached.",
155                     )
156                     logger.warning(str(e))
157                 # consuming stops here, since the original document with
158                 # the barcodes has been split and will be consumed separately
159                 return "File successfully split"
160 
161     # continue with consumption if no barcode was found
162     document = Consumer().try_consume_file(
163         path,
164         override_filename=override_filename,
165         override_title=override_title,
166         override_correspondent_id=override_correspondent_id,
167         override_document_type_id=override_document_type_id,
168         override_tag_ids=override_tag_ids,
169         task_id=task_id,
170         override_created=override_created,
171     )
172 
173     if document:
174         return f"Success. New document id {document.pk} created"
175     else:
176         raise ConsumerError(
177             "Unknown error: Returned document was null, but "
178             "no error message was given.",
179         )
180 
181 
182 def sanity_check():
183     messages = sanity_checker.check_sanity()
184 
185     messages.log_messages()
186 
187     if messages.has_error:
188         raise SanityCheckFailedException("Sanity check failed with errors. See log.")
189     elif messages.has_warning:
190         return "Sanity check exited with warnings. See log."
191     elif len(messages) > 0:
192         return "Sanity check exited with infos. See log."
193     else:
194         return "No issues detected."
195 
196 
197 def bulk_update_documents(document_ids):
198     documents = Document.objects.filter(id__in=document_ids)
199 
200     ix = index.open_index()
201 
202     for doc in documents:
203         post_save.send(Document, instance=doc, created=False)
204 
205     with AsyncWriter(ix) as writer:
206         for doc in documents:
207             index.update_document(writer, doc)
208 
209 
210 def redo_ocr(document_ids):
211     all_docs = Document.objects.all()
212 
213     for doc_pk in document_ids:
214         try:
215             logger.info(f"Parsing document {doc_pk}")
216             doc: Document = all_docs.get(pk=doc_pk)
217         except ObjectDoesNotExist:
218             logger.error(f"Document {doc_pk} does not exist")
219             continue
220 
221         # Get the correct parser for this mime type
222         parser_class: Type[DocumentParser] = get_parser_class_for_mime_type(
223             doc.mime_type,
224         )
225         document_parser: DocumentParser = parser_class(
226             "redo-ocr",
227         )
228 
229         # Create a file path to copy the original file to for working on
230         temp_file = (Path(document_parser.tempdir) / Path("new-ocr-file")).resolve()
231 
232         shutil.copy(doc.source_path, temp_file)
233 
234         try:
235             logger.info(
236                 f"Using {type(document_parser).__name__} for document",
237             )
238             # Try to re-parse the document into text
239             document_parser.parse(str(temp_file), doc.mime_type)
240 
241             doc.content = document_parser.get_text()
242             doc.save()
243             logger.info("Document OCR updated")
244 
245         except ParseError as e:
246             logger.error(f"Error parsing document: {e}")
247         finally:
248             # Remove the file path if it was created
249             if temp_file.exists() and temp_file.is_file():
250                 temp_file.unlink()
251
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/documents/tasks.py b/src/documents/tasks.py
--- a/src/documents/tasks.py
+++ b/src/documents/tasks.py
@@ -87,6 +87,8 @@
     override_created=None,
 ):
 
+    path = Path(path).resolve()
+
     # check for separators in current document
     if settings.CONSUMER_ENABLE_BARCODES:
 
@@ -122,7 +124,11 @@
                         newname = f"{str(n)}_" + override_filename
                     else:
                         newname = None
-                    barcodes.save_to_dir(document, newname=newname)
+                    barcodes.save_to_dir(
+                        document,
+                        newname=newname,
+                        target_dir=path.parent,
+                    )
 
                 # if we got here, the document was successfully split
                 # and can safely be deleted

{"golden_diff": "diff --git a/src/documents/tasks.py b/src/documents/tasks.py\n--- a/src/documents/tasks.py\n+++ b/src/documents/tasks.py\n@@ -87,6 +87,8 @@\n     override_created=None,\n ):\n \n+    path = Path(path).resolve()\n+\n     # check for separators in current document\n     if settings.CONSUMER_ENABLE_BARCODES:\n \n@@ -122,7 +124,11 @@\n                         newname = f\"{str(n)}_\" + override_filename\n                     else:\n                         newname = None\n-                    barcodes.save_to_dir(document, newname=newname)\n+                    barcodes.save_to_dir(\n+                        document,\n+                        newname=newname,\n+                        target_dir=path.parent,\n+                    )\n \n                 # if we got here, the document was successfully split\n                 # and can safely be deleted\n", "issue": "[BUG] CONSUME_SUBDIRS_AS_TAGS not working when using CONSUMER_ENABLE_BARCODES\n### Description\n\nmy scanner puts files into a specific subdirectory of the `CONSUMPTION_DIR`. However when `CONSUMER_ENABLE_BARCODES` is enabled and a barcode is detected the split documents don't have the expected tags.\r\n\r\nIt looks like this is caused by `save_to_dir()` in `src/documents/tasks.py` and the fact that it always stores the new documents into `CONSUMPTION_DIR`\n\n### Steps to reproduce\n\n1. enable CONSUMER_ENABLE_BARCODES and CONSUME_SUBDIRS_AS_TAGS \r\n2. put document with correct Barcode into <CONSUMPTION_DIR>/foo\r\n3. wait for import\r\n4. imported documents don't have the tag `foo`\n\n### Webserver logs\n\n_No response_\n\n### Paperless-ngx version\n\n1.7.1\n\n### Host OS\n\nDebian\n\n### Installation method\n\nBare metal\n\n### Browser\n\n_No response_\n\n### Configuration changes\n\n_No response_\n\n### Other\n\n_No response_\n", "before_files": [{"content": "import logging\nimport os\nimport shutil\nfrom pathlib import Path\nfrom typing import Type\n\nimport tqdm\nfrom asgiref.sync import async_to_sync\nfrom channels.layers import get_channel_layer\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db.models.signals import post_save\nfrom documents import barcodes\nfrom documents import index\nfrom documents import sanity_checker\nfrom documents.classifier import DocumentClassifier\nfrom documents.classifier import load_classifier\nfrom documents.consumer import Consumer\nfrom documents.consumer import ConsumerError\nfrom documents.models import Correspondent\nfrom documents.models import Document\nfrom documents.models import DocumentType\nfrom documents.models import StoragePath\nfrom documents.models import Tag\nfrom documents.parsers import DocumentParser\nfrom documents.parsers import get_parser_class_for_mime_type\nfrom documents.parsers import ParseError\nfrom documents.sanity_checker import SanityCheckFailedException\nfrom whoosh.writing import AsyncWriter\n\n\nlogger = logging.getLogger(\"paperless.tasks\")\n\n\ndef index_optimize():\n    ix = index.open_index()\n    writer = AsyncWriter(ix)\n    writer.commit(optimize=True)\n\n\ndef index_reindex(progress_bar_disable=False):\n    documents = Document.objects.all()\n\n    ix = index.open_index(recreate=True)\n\n    with AsyncWriter(ix) as writer:\n        for document in tqdm.tqdm(documents, disable=progress_bar_disable):\n            index.update_document(writer, document)\n\n\ndef train_classifier():\n    if (\n        not Tag.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()\n        and not DocumentType.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()\n        and not Correspondent.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()\n        and not StoragePath.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()\n    ):\n\n        return\n\n    classifier = load_classifier()\n\n    if not classifier:\n        classifier = DocumentClassifier()\n\n    try:\n        if classifier.train():\n            logger.info(\n                f\"Saving updated classifier model to {settings.MODEL_FILE}...\",\n            )\n            classifier.save()\n        else:\n            logger.debug(\"Training data unchanged.\")\n\n    except Exception as e:\n        logger.warning(\"Classifier error: \" + str(e))\n\n\ndef consume_file(\n    path,\n    override_filename=None,\n    override_title=None,\n    override_correspondent_id=None,\n    override_document_type_id=None,\n    override_tag_ids=None,\n    task_id=None,\n    override_created=None,\n):\n\n    # check for separators in current document\n    if settings.CONSUMER_ENABLE_BARCODES:\n\n        mime_type = barcodes.get_file_mime_type(path)\n\n        if not barcodes.supported_file_type(mime_type):\n            # if not supported, skip this routine\n            logger.warning(\n                f\"Unsupported file format for barcode reader: {str(mime_type)}\",\n            )\n        else:\n            separators = []\n            document_list = []\n\n            if mime_type == \"image/tiff\":\n                file_to_process = barcodes.convert_from_tiff_to_pdf(path)\n            else:\n                file_to_process = path\n\n            separators = barcodes.scan_file_for_separating_barcodes(file_to_process)\n\n            if separators:\n                logger.debug(\n                    f\"Pages with separators found in: {str(path)}\",\n                )\n                document_list = barcodes.separate_pages(file_to_process, separators)\n\n            if document_list:\n                for n, document in enumerate(document_list):\n                    # save to consumption dir\n                    # rename it to the original filename  with number prefix\n                    if override_filename:\n                        newname = f\"{str(n)}_\" + override_filename\n                    else:\n                        newname = None\n                    barcodes.save_to_dir(document, newname=newname)\n\n                # if we got here, the document was successfully split\n                # and can safely be deleted\n                if mime_type == \"image/tiff\":\n                    # Remove the TIFF converted to PDF file\n                    logger.debug(f\"Deleting file {file_to_process}\")\n                    os.unlink(file_to_process)\n                # Remove the original file (new file is saved above)\n                logger.debug(f\"Deleting file {path}\")\n                os.unlink(path)\n\n                # notify the sender, otherwise the progress bar\n                # in the UI stays stuck\n                payload = {\n                    \"filename\": override_filename,\n                    \"task_id\": task_id,\n                    \"current_progress\": 100,\n                    \"max_progress\": 100,\n                    \"status\": \"SUCCESS\",\n                    \"message\": \"finished\",\n                }\n                try:\n                    async_to_sync(get_channel_layer().group_send)(\n                        \"status_updates\",\n                        {\"type\": \"status_update\", \"data\": payload},\n                    )\n                except OSError as e:\n                    logger.warning(\n                        \"OSError. It could be, the broker cannot be reached.\",\n                    )\n                    logger.warning(str(e))\n                # consuming stops here, since the original document with\n                # the barcodes has been split and will be consumed separately\n                return \"File successfully split\"\n\n    # continue with consumption if no barcode was found\n    document = Consumer().try_consume_file(\n        path,\n        override_filename=override_filename,\n        override_title=override_title,\n        override_correspondent_id=override_correspondent_id,\n        override_document_type_id=override_document_type_id,\n        override_tag_ids=override_tag_ids,\n        task_id=task_id,\n        override_created=override_created,\n    )\n\n    if document:\n        return f\"Success. New document id {document.pk} created\"\n    else:\n        raise ConsumerError(\n            \"Unknown error: Returned document was null, but \"\n            \"no error message was given.\",\n        )\n\n\ndef sanity_check():\n    messages = sanity_checker.check_sanity()\n\n    messages.log_messages()\n\n    if messages.has_error:\n        raise SanityCheckFailedException(\"Sanity check failed with errors. See log.\")\n    elif messages.has_warning:\n        return \"Sanity check exited with warnings. See log.\"\n    elif len(messages) > 0:\n        return \"Sanity check exited with infos. See log.\"\n    else:\n        return \"No issues detected.\"\n\n\ndef bulk_update_documents(document_ids):\n    documents = Document.objects.filter(id__in=document_ids)\n\n    ix = index.open_index()\n\n    for doc in documents:\n        post_save.send(Document, instance=doc, created=False)\n\n    with AsyncWriter(ix) as writer:\n        for doc in documents:\n            index.update_document(writer, doc)\n\n\ndef redo_ocr(document_ids):\n    all_docs = Document.objects.all()\n\n    for doc_pk in document_ids:\n        try:\n            logger.info(f\"Parsing document {doc_pk}\")\n            doc: Document = all_docs.get(pk=doc_pk)\n        except ObjectDoesNotExist:\n            logger.error(f\"Document {doc_pk} does not exist\")\n            continue\n\n        # Get the correct parser for this mime type\n        parser_class: Type[DocumentParser] = get_parser_class_for_mime_type(\n            doc.mime_type,\n        )\n        document_parser: DocumentParser = parser_class(\n            \"redo-ocr\",\n        )\n\n        # Create a file path to copy the original file to for working on\n        temp_file = (Path(document_parser.tempdir) / Path(\"new-ocr-file\")).resolve()\n\n        shutil.copy(doc.source_path, temp_file)\n\n        try:\n            logger.info(\n                f\"Using {type(document_parser).__name__} for document\",\n            )\n            # Try to re-parse the document into text\n            document_parser.parse(str(temp_file), doc.mime_type)\n\n            doc.content = document_parser.get_text()\n            doc.save()\n            logger.info(\"Document OCR updated\")\n\n        except ParseError as e:\n            logger.error(f\"Error parsing document: {e}\")\n        finally:\n            # Remove the file path if it was created\n            if temp_file.exists() and temp_file.is_file():\n                temp_file.unlink()\n", "path": "src/documents/tasks.py"}], "after_files": [{"content": "import logging\nimport os\nimport shutil\nfrom pathlib import Path\nfrom typing import Type\n\nimport tqdm\nfrom asgiref.sync import async_to_sync\nfrom channels.layers import get_channel_layer\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db.models.signals import post_save\nfrom documents import barcodes\nfrom documents import index\nfrom documents import sanity_checker\nfrom documents.classifier import DocumentClassifier\nfrom documents.classifier import load_classifier\nfrom documents.consumer import Consumer\nfrom documents.consumer import ConsumerError\nfrom documents.models import Correspondent\nfrom documents.models import Document\nfrom documents.models import DocumentType\nfrom documents.models import StoragePath\nfrom documents.models import Tag\nfrom documents.parsers import DocumentParser\nfrom documents.parsers import get_parser_class_for_mime_type\nfrom documents.parsers import ParseError\nfrom documents.sanity_checker import SanityCheckFailedException\nfrom whoosh.writing import AsyncWriter\n\n\nlogger = logging.getLogger(\"paperless.tasks\")\n\n\ndef index_optimize():\n    ix = index.open_index()\n    writer = AsyncWriter(ix)\n    writer.commit(optimize=True)\n\n\ndef index_reindex(progress_bar_disable=False):\n    documents = Document.objects.all()\n\n    ix = index.open_index(recreate=True)\n\n    with AsyncWriter(ix) as writer:\n        for document in tqdm.tqdm(documents, disable=progress_bar_disable):\n            index.update_document(writer, document)\n\n\ndef train_classifier():\n    if (\n        not Tag.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()\n        and not DocumentType.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()\n        and not Correspondent.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()\n        and not StoragePath.objects.filter(matching_algorithm=Tag.MATCH_AUTO).exists()\n    ):\n\n        return\n\n    classifier = load_classifier()\n\n    if not classifier:\n        classifier = DocumentClassifier()\n\n    try:\n        if classifier.train():\n            logger.info(\n                f\"Saving updated classifier model to {settings.MODEL_FILE}...\",\n            )\n            classifier.save()\n        else:\n            logger.debug(\"Training data unchanged.\")\n\n    except Exception as e:\n        logger.warning(\"Classifier error: \" + str(e))\n\n\ndef consume_file(\n    path,\n    override_filename=None,\n    override_title=None,\n    override_correspondent_id=None,\n    override_document_type_id=None,\n    override_tag_ids=None,\n    task_id=None,\n    override_created=None,\n):\n\n    path = Path(path).resolve()\n\n    # check for separators in current document\n    if settings.CONSUMER_ENABLE_BARCODES:\n\n        mime_type = barcodes.get_file_mime_type(path)\n\n        if not barcodes.supported_file_type(mime_type):\n            # if not supported, skip this routine\n            logger.warning(\n                f\"Unsupported file format for barcode reader: {str(mime_type)}\",\n            )\n        else:\n            separators = []\n            document_list = []\n\n            if mime_type == \"image/tiff\":\n                file_to_process = barcodes.convert_from_tiff_to_pdf(path)\n            else:\n                file_to_process = path\n\n            separators = barcodes.scan_file_for_separating_barcodes(file_to_process)\n\n            if separators:\n                logger.debug(\n                    f\"Pages with separators found in: {str(path)}\",\n                )\n                document_list = barcodes.separate_pages(file_to_process, separators)\n\n            if document_list:\n                for n, document in enumerate(document_list):\n                    # save to consumption dir\n                    # rename it to the original filename  with number prefix\n                    if override_filename:\n                        newname = f\"{str(n)}_\" + override_filename\n                    else:\n                        newname = None\n                    barcodes.save_to_dir(\n                        document,\n                        newname=newname,\n                        target_dir=path.parent,\n                    )\n\n                # if we got here, the document was successfully split\n                # and can safely be deleted\n                if mime_type == \"image/tiff\":\n                    # Remove the TIFF converted to PDF file\n                    logger.debug(f\"Deleting file {file_to_process}\")\n                    os.unlink(file_to_process)\n                # Remove the original file (new file is saved above)\n                logger.debug(f\"Deleting file {path}\")\n                os.unlink(path)\n\n                # notify the sender, otherwise the progress bar\n                # in the UI stays stuck\n                payload = {\n                    \"filename\": override_filename,\n                    \"task_id\": task_id,\n                    \"current_progress\": 100,\n                    \"max_progress\": 100,\n                    \"status\": \"SUCCESS\",\n                    \"message\": \"finished\",\n                }\n                try:\n                    async_to_sync(get_channel_layer().group_send)(\n                        \"status_updates\",\n                        {\"type\": \"status_update\", \"data\": payload},\n                    )\n                except OSError as e:\n                    logger.warning(\n                        \"OSError. It could be, the broker cannot be reached.\",\n                    )\n                    logger.warning(str(e))\n                # consuming stops here, since the original document with\n                # the barcodes has been split and will be consumed separately\n                return \"File successfully split\"\n\n    # continue with consumption if no barcode was found\n    document = Consumer().try_consume_file(\n        path,\n        override_filename=override_filename,\n        override_title=override_title,\n        override_correspondent_id=override_correspondent_id,\n        override_document_type_id=override_document_type_id,\n        override_tag_ids=override_tag_ids,\n        task_id=task_id,\n        override_created=override_created,\n    )\n\n    if document:\n        return f\"Success. New document id {document.pk} created\"\n    else:\n        raise ConsumerError(\n            \"Unknown error: Returned document was null, but \"\n            \"no error message was given.\",\n        )\n\n\ndef sanity_check():\n    messages = sanity_checker.check_sanity()\n\n    messages.log_messages()\n\n    if messages.has_error:\n        raise SanityCheckFailedException(\"Sanity check failed with errors. See log.\")\n    elif messages.has_warning:\n        return \"Sanity check exited with warnings. See log.\"\n    elif len(messages) > 0:\n        return \"Sanity check exited with infos. See log.\"\n    else:\n        return \"No issues detected.\"\n\n\ndef bulk_update_documents(document_ids):\n    documents = Document.objects.filter(id__in=document_ids)\n\n    ix = index.open_index()\n\n    for doc in documents:\n        post_save.send(Document, instance=doc, created=False)\n\n    with AsyncWriter(ix) as writer:\n        for doc in documents:\n            index.update_document(writer, doc)\n\n\ndef redo_ocr(document_ids):\n    all_docs = Document.objects.all()\n\n    for doc_pk in document_ids:\n        try:\n            logger.info(f\"Parsing document {doc_pk}\")\n            doc: Document = all_docs.get(pk=doc_pk)\n        except ObjectDoesNotExist:\n            logger.error(f\"Document {doc_pk} does not exist\")\n            continue\n\n        # Get the correct parser for this mime type\n        parser_class: Type[DocumentParser] = get_parser_class_for_mime_type(\n            doc.mime_type,\n        )\n        document_parser: DocumentParser = parser_class(\n            \"redo-ocr\",\n        )\n\n        # Create a file path to copy the original file to for working on\n        temp_file = (Path(document_parser.tempdir) / Path(\"new-ocr-file\")).resolve()\n\n        shutil.copy(doc.source_path, temp_file)\n\n        try:\n            logger.info(\n                f\"Using {type(document_parser).__name__} for document\",\n            )\n            # Try to re-parse the document into text\n            document_parser.parse(str(temp_file), doc.mime_type)\n\n            doc.content = document_parser.get_text()\n            doc.save()\n            logger.info(\"Document OCR updated\")\n\n        except ParseError as e:\n            logger.error(f\"Error parsing document: {e}\")\n        finally:\n            # Remove the file path if it was created\n            if temp_file.exists() and temp_file.is_file():\n                temp_file.unlink()\n", "path": "src/documents/tasks.py"}]}