paperless-gpt/ocr.go

51 lines
1.5 KiB
Go
Raw Permalink Normal View History

2025-01-06 16:03:41 -06:00
package main
import (
"context"
"fmt"
"os"
"strings"
)
// ProcessDocumentOCR processes a document through OCR and returns the combined text
func (app *App) ProcessDocumentOCR(ctx context.Context, documentID int) (string, error) {
2025-01-13 00:52:40 -06:00
docLogger := documentLogger(documentID)
docLogger.Info("Starting OCR processing")
imagePaths, err := app.Client.DownloadDocumentAsImages(ctx, documentID, limitOcrPages)
2025-01-06 16:03:41 -06:00
defer func() {
for _, imagePath := range imagePaths {
2025-01-13 00:52:40 -06:00
if err := os.Remove(imagePath); err != nil {
docLogger.WithError(err).WithField("image_path", imagePath).Warn("Failed to remove temporary image file")
}
2025-01-06 16:03:41 -06:00
}
}()
if err != nil {
2025-01-13 00:52:40 -06:00
return "", fmt.Errorf("error downloading document images for document %d: %w", documentID, err)
2025-01-06 16:03:41 -06:00
}
2025-01-13 00:52:40 -06:00
docLogger.WithField("page_count", len(imagePaths)).Debug("Downloaded document images")
2025-01-06 16:03:41 -06:00
var ocrTexts []string
2025-01-13 00:52:40 -06:00
for i, imagePath := range imagePaths {
pageLogger := docLogger.WithField("page", i+1)
pageLogger.Debug("Processing page")
2025-01-06 16:03:41 -06:00
imageContent, err := os.ReadFile(imagePath)
if err != nil {
2025-01-13 00:52:40 -06:00
return "", fmt.Errorf("error reading image file for document %d, page %d: %w", documentID, i+1, err)
2025-01-06 16:03:41 -06:00
}
2025-01-13 00:52:40 -06:00
ocrText, err := app.doOCRViaLLM(ctx, imageContent, pageLogger)
2025-01-06 16:03:41 -06:00
if err != nil {
2025-01-13 00:52:40 -06:00
return "", fmt.Errorf("error performing OCR for document %d, page %d: %w", documentID, i+1, err)
2025-01-06 16:03:41 -06:00
}
2025-01-13 00:52:40 -06:00
pageLogger.Debug("OCR completed for page")
2025-01-06 16:03:41 -06:00
ocrTexts = append(ocrTexts, ocrText)
}
2025-01-13 00:52:40 -06:00
docLogger.Info("OCR processing completed successfully")
2025-01-06 16:03:41 -06:00
return strings.Join(ocrTexts, "\n\n"), nil
}