forked from icereed/paperless-gpt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.go
More file actions
281 lines (236 loc) · 8.24 KB
/
background.go
File metadata and controls
281 lines (236 loc) · 8.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package main
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"time"
)
// This is our interface, allowing us to enable proper testing
type BackgroundProcessor interface {
processAutoOcrTagDocuments(ctx context.Context) (int, error)
processAutoTagDocuments(ctx context.Context) (int, error)
isOcrEnabled() bool
}
// Start our background tasks in a goroutine
func StartBackgroundTasks(ctx context.Context, app BackgroundProcessor) {
go func() {
minBackoffDuration := 10 * time.Second
maxBackoffDuration := time.Hour
pollingInterval := 10 * time.Second
backoffDuration := minBackoffDuration
for {
select {
case <-ctx.Done():
log.Infoln("Background tasks shutting down")
return
default: // needed to make this non-blocking
}
processedCount, err := func() (count int, err error) {
count = 0
// If OCR is enabled, run OCR tagging first
if app.isOcrEnabled() {
ocrCount, err := app.processAutoOcrTagDocuments(ctx)
if err != nil {
return 0, fmt.Errorf("error in processAutoOcrTagDocuments: %w", err)
}
count += ocrCount
}
// Run auto-tagging after OCR
autoCount, err := app.processAutoTagDocuments(ctx)
if err != nil {
return 0, fmt.Errorf("error in processAutoTagDocuments: %w", err)
}
count += autoCount
return count, nil
}()
if err != nil {
log.Errorf("Error in background tagging: %v", err)
time.Sleep(backoffDuration)
// Exponential backoff logic
backoffDuration *= 2
if backoffDuration > maxBackoffDuration {
log.Warnf("Max backoff duration reached. Using %v", maxBackoffDuration)
backoffDuration = maxBackoffDuration
}
} else {
// Reset backoff when processing succeeds
backoffDuration = minBackoffDuration
}
// If nothing was processed, pause before next cycle
if processedCount == 0 {
time.Sleep(pollingInterval)
}
}
}()
}
// processAutoTagDocuments handles the background auto-tagging of documents
func (app *App) processAutoTagDocuments(ctx context.Context) (int, error) {
documents, err := app.Client.GetDocumentsByTags(ctx, []string{autoTag}, 25)
if err != nil {
return 0, fmt.Errorf("error fetching documents with autoTag: %w", err)
}
if len(documents) == 0 {
log.Debugf("No documents with tag %s found", autoTag)
return 0, nil // No documents to process
}
// Refresh the custom fields cache before processing, as we have documents
refreshCustomFieldsCache(app.Client)
log.Debugf("Found at least %d remaining documents with tag %s", len(documents), autoTag)
var errs []error
processedCount := 0
for _, docSummary := range documents {
// Get the full document details, including custom fields
document, err := app.Client.GetDocument(ctx, docSummary.ID)
if err != nil {
err = fmt.Errorf("error fetching full details for document %d: %w", docSummary.ID, err)
documentLogger(docSummary.ID).Error(err.Error())
errs = append(errs, err)
continue
}
// Skip documents that have the autoOcrTag
if slices.Contains(document.Tags, autoOcrTag) {
log.Debugf("Skipping document %d as it has the OCR tag %s", document.ID, autoOcrTag)
continue
}
docLogger := documentLogger(document.ID)
docLogger.Info("Processing document for auto-tagging")
suggestionRequest := GenerateSuggestionsRequest{
Documents: []Document{document},
GenerateTitles: strings.ToLower(autoGenerateTitle) != "false",
GenerateTags: strings.ToLower(autoGenerateTags) != "false",
GenerateCorrespondents: strings.ToLower(autoGenerateCorrespondents) != "false",
GenerateCreatedDate: strings.ToLower(autoGenerateCreatedDate) != "false",
GenerateCustomFields: settings.CustomFieldsEnable,
}
suggestions, err := app.generateDocumentSuggestions(ctx, suggestionRequest, docLogger)
if err != nil {
err = fmt.Errorf("error generating suggestions for document %d: %w", document.ID, err)
docLogger.Error(err.Error())
errs = append(errs, err)
continue
}
err = app.Client.UpdateDocuments(ctx, suggestions, app.Database, false)
if err != nil {
err = fmt.Errorf("error updating document %d: %w", document.ID, err)
docLogger.Error(err.Error())
errs = append(errs, err)
continue
}
docLogger.Info("Successfully processed document")
processedCount++
}
if len(errs) > 0 {
return processedCount, errors.Join(errs...)
}
return processedCount, nil
}
// processAutoOcrTagDocuments handles the background auto-tagging of OCR documents
func (app *App) processAutoOcrTagDocuments(ctx context.Context) (int, error) {
documents, err := app.Client.GetDocumentsByTags(ctx, []string{autoOcrTag}, 25)
if err != nil {
return 0, fmt.Errorf("error fetching documents with autoOcrTag: %w", err)
}
if len(documents) == 0 {
log.Debugf("No documents with tag %s found", autoOcrTag)
return 0, nil
}
log.Debugf("Found %d documents with tag %s", len(documents), autoOcrTag)
successCount := 0
var errs []error
for _, document := range documents {
docLogger := documentLogger(document.ID)
docLogger.Info("Processing document for OCR")
// Skip OCR if the document already has the OCR complete tag and tagging is enabled
if app.pdfOCRTagging {
hasCompleteTag := false
for _, tag := range document.Tags {
if tag == app.pdfOCRCompleteTag {
hasCompleteTag = true
break
}
}
if hasCompleteTag {
docLogger.Infof("Document already has OCR complete tag '%s', skipping OCR processing", app.pdfOCRCompleteTag)
// Remove only the autoOcrTag to take it out of the processing queue
// while preserving the OCR complete tag
err = app.Client.UpdateDocuments(ctx, []DocumentSuggestion{
{
ID: document.ID,
OriginalDocument: document,
RemoveTags: []string{autoOcrTag},
},
}, app.Database, false)
if err != nil {
docLogger.Errorf("Update to remove autoOcrTag failed: %v", err)
errs = append(errs, fmt.Errorf("document %d update error: %w", document.ID, err))
continue
}
docLogger.Info("Successfully removed auto OCR tag")
successCount++
continue
}
}
options := OCROptions{
UploadPDF: app.pdfUpload,
ReplaceOriginal: app.pdfReplace,
CopyMetadata: app.pdfCopyMetadata,
LimitPages: limitOcrPages,
ProcessMode: app.ocrProcessMode,
}
// Use the DocumentProcessor interface instead of calling the method directly
var processedDoc *ProcessedDocument
var err error
if app.docProcessor != nil {
// Use injected processor if available
processedDoc, err = app.docProcessor.ProcessDocumentOCR(ctx, document.ID, options, "")
} else {
// Use the app's own implementation if no processor is injected
processedDoc, err = app.ProcessDocumentOCR(ctx, document.ID, options, "")
}
if err != nil {
docLogger.Errorf("OCR processing failed: %v", err)
errs = append(errs, fmt.Errorf("document %d OCR error: %w", document.ID, err))
continue
}
if processedDoc == nil {
docLogger.Info("OCR processing skipped for document")
continue
}
docLogger.Debug("OCR processing completed")
documentSuggestion := DocumentSuggestion{
ID: document.ID,
OriginalDocument: document,
SuggestedContent: processedDoc.Text,
RemoveTags: []string{autoOcrTag},
// Add OCR complete tag if tagging is enabled and PDF wasn't uploaded (upload handles tagging)
AddTags: func() []string {
if app.pdfOCRTagging && !options.UploadPDF {
return []string{app.pdfOCRCompleteTag}
}
return nil
}(),
}
if (app.pdfOCRTagging) && app.pdfOCRCompleteTag != "" {
// Add the OCR complete tag if tagging is enabled
documentSuggestion.SuggestedTags = []string{app.pdfOCRCompleteTag}
documentSuggestion.KeepOriginalTags = true
docLogger.Infof("Adding OCR complete tag '%s'", app.pdfOCRCompleteTag)
}
err = app.Client.UpdateDocuments(ctx, []DocumentSuggestion{
documentSuggestion,
}, app.Database, false)
if err != nil {
docLogger.Errorf("Update after OCR failed: %v", err)
errs = append(errs, fmt.Errorf("document %d update error: %w", document.ID, err))
continue
}
docLogger.Info("Successfully processed document OCR")
successCount++
}
if len(errs) > 0 {
return successCount, fmt.Errorf("one or more errors occurred: %w", errors.Join(errs...))
}
return successCount, nil
}