cherry-studio/src/main/services/ocr/builtin/SystemOcrService.ts
beyondkmp 5ce7261678
refactor: Improve linux build for system-ocr (#9775)
* refactor(ocr): streamline OCR service registration and improve image preprocessing

- Simplified the registration of the system OCR service by removing the conditional check for Linux.
- Updated SystemOcrService to directly import necessary modules, enhancing clarity.
- Refactored image preprocessing to use a static import of the 'sharp' library for better performance.

* add patch for system-ocr

* add patch

* add patch again

* add patch

* delete setting

* delete i18n

* lint error

* add isLinux

* Revert "delete i18n"

This reverts commit 173e65bbd0.

* Revert "delete setting"

This reverts commit de39c76f83.

* fix: add system check for error message

---------

Co-authored-by: icarus <eurfelux@gmail.com>
2025-09-02 12:59:14 +08:00

40 lines
1.2 KiB
TypeScript

import { isLinux, isWin } from '@main/constant'
import { loadOcrImage } from '@main/utils/ocr'
import { OcrAccuracy, recognize } from '@napi-rs/system-ocr'
import {
ImageFileMetadata,
isImageFileMetadata as isImageFileMetadata,
OcrResult,
OcrSystemConfig,
SupportedOcrFile
} from '@types'
import { OcrBaseService } from './OcrBaseService'
// const logger = loggerService.withContext('SystemOcrService')
export class SystemOcrService extends OcrBaseService {
constructor() {
super()
}
private async ocrImage(file: ImageFileMetadata, options?: OcrSystemConfig): Promise<OcrResult> {
if (isLinux) {
return { text: '' }
}
const buffer = await loadOcrImage(file)
const langs = isWin ? options?.langs : undefined
const result = await recognize(buffer, OcrAccuracy.Accurate, langs)
return { text: result.text }
}
public ocr = async (file: SupportedOcrFile, options?: OcrSystemConfig): Promise<OcrResult> => {
if (isImageFileMetadata(file)) {
return this.ocrImage(file, options)
} else {
throw new Error('Unsupported file type, currently only image files are supported')
}
}
}
export const systemOcrService = new SystemOcrService()