-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvocr.m
1076 lines (921 loc) · 29 KB
/
vocr.m
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
vocr.m - perform optical character recognition on an image or a PDF
using Apple's Vision framework
Inspired by: https://turbozen.com/sourceCode/ocrImage/
https://nemecek.be/blog/38/how-to-implement-ocr-with-vision-framework-in-ios-13
History:
v. 0.1.0 (04/19/2022) - Initial version
v. 0.2.0 (04/24/2022) - print text as soon as it has been recognized,
default to quiet mode
v. 0.3.0 (04/25/2022) - add language support
v. 0.3.1 (04/24/2022) - move printSupportedLangs to separate file
v. 0.4.0 (07/10/2022) - switch to PDFKit
v. 0.4.1 (10/28/2022) - updates for Monterey (MacOSX 12.x)
Copyright (c) 2022 Sriranga R. Veeraraghavan <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#import <AppKit/AppKit.h>
#import <Vision/Vision.h>
#import <PDFKit/PDFKit.h>
/*
use UTT, if available
see: https://stackoverflow.com/questions/70512722
*/
#ifdef HAVE_UTT
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#endif
#import <stdio.h>
#import <stdarg.h>
#import <unistd.h>
#import <string.h>
#import <math.h>
/* globals */
static NSString *gIndentStr = @" ";
static const char *gPgmName = "vocr";
#ifdef VOCR_IMG2TXT
static const NSUInteger
gBufSize = 1024;
#endif /* VOCR_IMG2TXT */
#ifndef HAVE_UTT
static NSString *gUTIPDF = @"com.adobe.pdf";
static NSString *gUTIIMG = @"public.image";
#endif
/*
command line options:
-a - set the ocr [a]lgorithm
'fast' - uses the fast algorithm
'accurate' - uses the accurate algorithm
-f - force ocr
-h - print usage / [h]elp
-i [mode] - set the [i]ndent mode:
'no' - disables indenting
'tab' - indents with tabs (default is to use 4 spaces)
-l - specify the [l]anguage to use for recognition
-p - add a page break / [l]ine feed between pages
-v - be [v]erbose
*/
enum
{
gPgmOptAlgorithm = 'a',
gPgmOptForce = 'f',
gPgmOptHelp = 'h',
gPgmOptIndent = 'i',
gPgmOptLang = 'l',
gPgmOptPageBreak = 'p',
gPgmOptVerbose = 'v',
};
enum
{
gLangGerman = 'd', /* de-DE */
gLangEnglish = 'e', /* en-US */
gLangFrench = 'f', /* fr-FR */
gLangItalian = 'i', /* it-IT */
gLangPortuguese = 'p', /* pt-BR */
gLangSpanish = 's', /* es-ES */
gLangChinese = 'z', /* zh-Hans and zh-Hant */
};
static const char *gPgmOpts = "fhpva:i:l:";
static const char *gPgmAlgorithmAccurate = "accurate";
static const char *gPgmAlgorithmFast = "fast";
static const char *gPgmIndentNo = "no";
static const char *gPgmIndentTab = "tab";
static BOOL gQuiet = YES;
static const char *gPgmLangGerman = "de";
static const char *gPgmLangEnglish = "en";
static const char *gPgmLangFrench = "fr";
static const char *gPgmLangItalian = "it";
static const char *gPgmLangPortuguese = "pt";
static const char *gPgmLangSpanish = "es";
static const char *gPgmLangChinese = "zh";
/* ocr options */
typedef struct
{
BOOL addPageBreak;
BOOL fast;
BOOL indent;
BOOL indentWithTabs;
BOOL forceOCR;
int lang;
} ocrOpts_t;
/* prototypes */
static void printUsage(void);
static void printError(const char *format, ...);
static void printInfo(const char *format, ...);
static BOOL ocrFile(const char *file,
#ifdef VOCR_IMG2TXT
NSMutableString *text,
#endif /* VOCR_IMG2TXT */
ocrOpts_t *opts);
static BOOL ocrImage(CGImageRef cgImage,
#ifdef VOCR_IMG2TXT
NSMutableString *text,
#endif /* VOCR_IMG2TXT */
ocrOpts_t *opts);
/* private functions */
/* printUsage - print the usage message */
static void printUsage(void)
{
fprintf(stderr,
"Usage: %s [-%c] [-%c [%s|%s]] [-%c] [-%c] [-%c [%s|%s]] [-%c [lang]] [files]\n",
gPgmName,
gPgmOptVerbose,
gPgmOptAlgorithm,
gPgmAlgorithmAccurate,
gPgmAlgorithmFast,
gPgmOptForce,
gPgmOptPageBreak,
gPgmOptIndent,
gPgmIndentNo,
gPgmIndentTab,
gPgmOptLang);
}
/* printError - print an error message */
static void printError(const char *format, ...)
{
va_list args;
if (gQuiet == YES)
{
return;
}
va_start(args, format);
fprintf(stderr,"ERROR: ");
vfprintf(stderr, format, args);
va_end(args);
}
/* printInfo - print an informational message */
static void printInfo(const char *format, ...)
{
va_list args;
if (gQuiet == YES)
{
return;
}
va_start(args, format);
fprintf(stderr,"INFO: ");
vfprintf(stderr, format, args);
va_end(args);
}
/* ocrImage - try to ocr the specified image */
static BOOL ocrImage(CGImageRef cgImage,
#ifdef VOCR_IMG2TXT
NSMutableString *text,
#endif /* VOCR_IMG2TXT */
ocrOpts_t *opts)
{
NSArray *results;
NSUInteger numResults = 0, j = 0;
VNImageRequestHandler *requestHandler = nil;
VNRecognizeTextRequest *request = nil;
VNRecognizedTextObservation *rawText = nil;
NSArray<VNRecognizedText *> *recognizedText;
NSString *tmp1 = nil, *tmp2 = nil;
#ifdef VOCR_IMG2TXT
NSMutableString *ocrText = nil;
#endif /* VOCR_IMG2TXT */
NSMutableArray<VNRecognizedTextObservation *> *textPieces;
unsigned int indentLevel = 0, k = 0;
double prevStart = 0.0, prevEnd = 0.0;
double curStart = 0.0, curEnd = 0.0;
BOOL indent = YES, fast = NO, langCorrect = YES;
NSString *indentStr = gIndentStr;
NSArray<NSString *> *langs = nil;
#ifdef VOCR_IMG2TXT
if (text == nil)
{
printError("Text buffer is NULL!\n");
return NO;
}
#endif /* VOCR_IMG2TXT */
if (opts != NULL)
{
/* is fast mode requested? */
fast = opts->fast;
/* desired indent */
indent = opts->indent;
if (opts->indentWithTabs)
{
indentStr = @"\t";
}
/*
on BigSur (10.16) and newer, try to set the
recognition language
*/
if (@available(macos 10.16, *))
{
switch(opts->lang)
{
case gLangGerman:
langs = [NSArray arrayWithObjects: @"de-DE", nil];
break;
case gLangEnglish:
break;
case gLangFrench:
langs = [NSArray arrayWithObjects: @"fr-FR", nil];
break;
case gLangItalian:
langs = [NSArray arrayWithObjects: @"it-IT", nil];
break;
case gLangPortuguese:
langs = [NSArray arrayWithObjects: @"pt-BR", nil];
break;
case gLangSpanish:
langs = [NSArray arrayWithObjects: @"es-ES", nil];
break;
case gLangChinese:
langs = [NSArray arrayWithObjects: @"zh-Hans",
@"zh-Hant",
@"en-US",
nil];
/*
disable language correction, fast mode
for Chinese, see:
https://developer.apple.com/documentation/vision/recognizing_text_in_images
*/
langCorrect = NO;
fast = NO;
break;
default:
langs = nil;
break;
}
}
}
#ifdef VOCR_IMG2TXT
ocrText = [[NSMutableString alloc] initWithCapacity: gBufSize];
if (ocrText == nil)
{
printError("Cannot allocate mutable string.\n");
return NO;
}
#endif /* VOCR_IMG2TXT */
textPieces = [NSMutableArray array];
if (textPieces == nil)
{
printError("Cannot allocate mutable array.\n");
return NO;
}
/*
create a OCR request, based on:
https://developer.apple.com/documentation/vision/recognizing_text_in_images?language=objc#overview
https://developer.apple.com/documentation/vision/vnimagerequesthandler?language=objc
https://developer.apple.com/documentation/vision/vnrecognizetextrequest?language=objc
https://bendodson.com/weblog/2019/06/11/detecting-text-with-vnrecognizetextrequest-in-ios-13/
https://chris-mash.medium.com/ios-13-optical-character-recognition-d1bb8b710db1
*/
requestHandler =
[[VNImageRequestHandler alloc] initWithCGImage: cgImage
options: @{}];
if (requestHandler == nil)
{
printError("Could not create OCR request handler.\n");
return NO;
}
request = [[VNRecognizeTextRequest alloc] init];
if (request == nil)
{
printError("Could not create OCR request for.\n");
return NO;
}
/*
enable fast/accurate recognition and language correction
https://developer.apple.com/documentation/vision/vnrequesttextrecognitionlevel?language=objc
https://developer.apple.com/documentation/vision/vnrecognizetextrequest/3166773-useslanguagecorrection?language=objc
*/
if (fast)
{
[request setRecognitionLevel:
VNRequestTextRecognitionLevelFast];
}
else
{
[request setRecognitionLevel:
VNRequestTextRecognitionLevelAccurate];
}
[request setUsesLanguageCorrection: langCorrect];
/*
use the version 2 algorithm on MacOSX 10.16+ (BigSur or newer),
which support multiple languages, and, if an alternate language
is requested set that as well:
https://developer.apple.com/documentation/vision/vnrecognizetextrequestrevision2?language=objc
https://stackoverflow.com/questions/63813709
*/
if (@available(macos 10.16, *))
{
[request setRevision: VNRecognizeTextRequestRevision2];
if (langs != nil)
{
[request setRecognitionLanguages: langs];
}
}
else
{
[request setRevision: VNRecognizeTextRequestRevision1];
}
if ([requestHandler performRequests: @[request]
error: NULL] == NO)
{
printError("OCR failed.\n");
return NO;
}
results = [request results];
if (results == nil)
{
printInfo("No text found.\n");
return NO;
}
numResults = [results count];
if (numResults == 0)
{
printInfo("No text found.\n");
return NO;
}
/* possibly found some text */
for (j = 0; j < numResults; j++)
{
/* skip any result that isn't a VNRecognizedTextObservation */
if (results[j] == nil ||
![results[j] isKindOfClass:
[VNRecognizedTextObservation class]])
{
continue;
}
rawText = (VNRecognizedTextObservation *)results[j];
recognizedText = [rawText topCandidates:1];
if (recognizedText == nil)
{
continue;
}
/* get the top recognition candidate */
tmp1 = [[recognizedText firstObject] string];
if (tmp1 == nil)
{
continue;
}
/*
eliminate any leading or trailing whitespace:
https://stackoverflow.com/questions/5689288/
*/
tmp2 = [tmp1 stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (tmp2 == nil)
{
continue;
}
/*
use the botton X position as a proxy for the starting
and ending position of the current line
*/
curStart = round(10.0 * rawText.bottomLeft.x);
curEnd = round(10.0 * rawText.bottomRight.x);
/* first line */
if (j == 0)
{
prevStart = curStart;
prevEnd = curEnd;
#ifdef VOCR_IMG2TXT
[ocrText appendString: tmp2];
#else
fprintf(stdout,
"%s",
[tmp2 cStringUsingEncoding: NSUTF8StringEncoding]);
#endif /* VOCR_IMG2TXT */
continue;
}
/*
if the starting position of the current line is greater
than that of the previous line and this line ends before
the prior line, this line is probably not part of the
same paragraph as the prior line, so add a new line
*/
if (curStart > prevStart && curEnd < prevEnd)
{
#ifdef VOCR_IMG2TXT
[ocrText appendString: @"\n"];
#else
fprintf(stdout, "\n");
#endif /* VOCR_IMG2TXT */
}
/*
if the starting position of the current line is greater than
that of the previous line, add a newline and increase the
the indent level
if the starting position of the current line is less than of
the previous line, add a new line and reduce the indent level
*/
if (curStart > prevStart)
{
indentLevel++;
#ifdef VOCR_IMG2TXT
[ocrText appendString: @"\n"];
#else
fprintf(stdout, "\n");
#endif /* VOCR_IMG2TXT */
}
else if (curStart < prevStart)
{
if (indentLevel > 1)
{
indentLevel--;
#ifdef VOCR_IMG2TXT
[ocrText appendString: @"\n"];
#else
fprintf(stdout, "\n");
#endif /* VOCR_IMG2TXT */
}
}
if (curStart >= prevStart)
{
if (indent && indentLevel > 0)
{
for (k = 0; k < indentLevel; k++)
{
#ifdef VOCR_IMG2TXT
[ocrText appendString: indentStr];
#else
fprintf(stdout,
"%s",
[indentStr cStringUsingEncoding: NSUTF8StringEncoding]);
#endif /* VOCR_IMG2TXT */
}
}
prevStart = curStart;
}
/* add the current line to the OCR'ed text */
#ifdef VOCR_IMG2TXT
[ocrText appendFormat: @"%@ ", tmp2];
#else
fprintf(stdout,
"%s",
[tmp2 cStringUsingEncoding: NSUTF8StringEncoding]);
#endif /* VOCR_IMG2TXT */
/*
if this line ends before the end of the prior line,
add a new line
*/
if (curEnd < prevEnd)
{
#ifdef VOCR_IMG2TXT
[ocrText appendString: @"\n"];
#else
fprintf(stdout, "\n");
#endif /* VOCR_IMG2TXT */
}
prevEnd = curEnd;
}
#ifdef VOCR_IMG2TXT
[text setString: ocrText];
#endif /* VOCR_IMG2TXT */
return YES;
}
/* ocrFile - try to ocr the specified file */
static BOOL ocrFile(const char *file,
#ifdef VOCR_IMG2TXT
NSMutableString *text,
#endif /* VOCR_IMG2TXT */
ocrOpts_t *opts)
{
NSFileManager *fm = nil;
NSWorkspace *workspace = nil;
NSString *path = nil;
NSURL *fURL = nil;
NSString *type = nil, *pageText = nil;
NSError *error = nil;
NSImage *image = nil;
NSRect imageRect;
CGImageRef cgImage;
NSData *pdfData = nil;
NSPDFImageRep *pdfImageRep = nil;
PDFDocument *pdfDoc = nil;
PDFPage *pdfPage = nil;
NSUInteger pdfPages = 0, i = 0;
#ifdef VOCR_IMG2TXT
NSMutableString *pdfText = nil;
#endif /* VOCR_IMG2TXT */
#ifdef HAVE_UTT
UTType *utt = nil;
#endif
if (file == NULL || file[0] == '\0')
{
printError("Filename is NULL!\n");
return NO;
}
#ifdef VOCR_IMG2TXT
if (text == nil)
{
printError("Text buffer is NULL!\n");
return NO;
}
#endif /* VOCR_IMG2TXT */
fm = [NSFileManager defaultManager];
if (fm == nil)
{
printError("Cannot get NSFileManager!\n");
return NO;
}
workspace = [NSWorkspace sharedWorkspace];
if (workspace == nil)
{
printError("Cannot get NSWorkspace!\n");
return NO;
}
path = [fm stringWithFileSystemRepresentation: file
length: strlen(file)];
if (path == nil)
{
printError("Cannot get full path for '%s'.\n", file);
return NO;
}
fURL = [NSURL fileURLWithPath: path];
if (fURL == nil)
{
printError("Cannot get create URL for '%s'.\n", file);
return NO;
}
/*
determine if the file is of a type we support, based on:
https://stackoverflow.com/questions/12503376
*/
if (![fURL getResourceValue: &type
forKey: NSURLTypeIdentifierKey
error: &error])
{
printError("Cannot determine file type for '%s'.\n", file);
return NO;
}
/* ocr a PDF */
#ifdef HAVE_UTT
utt = [UTType typeWithIdentifier: type];
if ([utt conformsToType: UTTypePDF])
#else
if ([workspace type: type conformsToType: gUTIPDF])
#endif
{
#ifdef VOCR_IMG2TXT
pdfText = [[NSMutableString alloc] initWithCapacity: gBufSize];
if (pdfText == nil)
{
printError("Cannot allocate buffer for PDF text.\n");
return NO;
}
#endif /* VOCR_IMG2TXT */
/*
convert each page of a PDF to an image and then OCR it,
based on:
https://stackoverflow.com/questions/23643961
*/
/* get the PDF data for the file */
pdfDoc = [[PDFDocument alloc] initWithURL: fURL];
if (pdfDoc == nil)
{
printError("Not a valid PDF: '%s'.\n", file);
return NO;
}
/* get the page count and make sure we have at least 1 page */
pdfPages = [pdfDoc pageCount];
if (pdfPages < 1)
{
printError("PDF has no pages: '%s'.\n", file);
return NO;
}
/* ocr each page */
for(i = 0 ; i < pdfPages ; i++)
{
pdfPage = [pdfDoc pageAtIndex: i];
if (pdfPage == NULL)
{
printError("Could not get p.%ld of '%s'.\n",
i+1, file);
continue;
}
/* if ocr isn't being forced, see if we can just use
the existing text representation for this page */
if (opts->forceOCR == NO)
{
pageText = [[pdfPage string] stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (pageText != nil && [pageText length] > 0)
{
fprintf(stdout,
"%s\n",
[pageText cStringUsingEncoding: NSUTF8StringEncoding]);
continue;
}
}
pdfData = [pdfPage dataRepresentation];
if (pdfData == NULL)
{
printError("Could not get contents of p.%ld of '%s'.\n",
i+1, file);
}
pdfImageRep = [NSPDFImageRep imageRepWithData: pdfData];
if (pdfData == nil)
{
printError("Cannot convert PDF to image: '%s'.\n",
file);
return NO;
}
[pdfImageRep setCurrentPage: 0];
/* create an image for the current page */
/*
TODO, get the orientation:
https://stackoverflow.com/questions/6321772
TODO: create a stacked, searchable PDF:
https://teabyte.dev/blog/2021-03-29-from-uiimage-to-searchable-pdf-part-3
*/
image =
[NSImage imageWithSize: pdfImageRep.size
flipped: NO
drawingHandler: ^BOOL(NSRect dstRect)
{
[pdfImageRep drawInRect: dstRect];
return YES;
}];
if (image == nil)
{
printError("Could not make an image for p.%ld of '%s'.\n",
i, file);
continue;
}
/*
convert the NSImage we have to a CGImage for
VisionRequestHandler:
https://stackoverflow.com/questions/2548059/
*/
imageRect =
NSMakeRect(0, 0, image.size.width, image.size.height);
cgImage = [image CGImageForProposedRect: &imageRect
context: NULL
hints: nil];
#ifdef VOCR_IMG2TXT
if (ocrImage(cgImage, pdfText, opts) != YES)
#else
if (ocrImage(cgImage, opts) != YES)
#endif /* VOCR_IMG2TXT */
{
continue;
}
printInfo("OCR'ed p. %ld of '%s'.\n", i+1, file);
#ifdef VOCR_IMG2TXT
[text appendFormat: @"%@\n", pdfText];
#endif /* VOCR_IMG2TXT */
if (opts != NULL && opts->addPageBreak)
{
#ifdef VOCR_IMG2TXT
[text appendFormat: @"\f"];
#else
fprintf(stdout, "\f");
#endif /* VOCR_IMG2TXT */
}
}
return YES;
}
/* ocr an image */
#ifdef HAVE_UTT
utt = [UTType typeWithIdentifier: type];
if ([utt conformsToType: UTTypeImage])
#else
if ([workspace type: type conformsToType: gUTIIMG])
#endif
{
image = [[NSImage alloc] initWithContentsOfURL: fURL];
if (image == nil)
{
printError("Not an valid image: '%s'.\n", file);
return NO;
}
/*
convert the NSImage we have to a CGImage for
VisionRequestHandler:
https://stackoverflow.com/questions/2548059/
*/
imageRect =
NSMakeRect(0, 0, image.size.width, image.size.height);
cgImage = [image CGImageForProposedRect: &imageRect
context: NULL
hints: nil];
#ifdef VOCR_IMG2TXT
return ocrImage(cgImage, text, opts);
#else
return ocrImage(cgImage, opts);
#endif /* VOCR_IMG2TXT */
}
/* unsupported file type */
printError("'%s' not a supported image or a PDF.\n", file);
return NO;
}
/* main */
int main(int argc, char * const argv[])
{
int i = 0, err = 0, ch = 0;
BOOL optHelp = NO;
#ifdef VOCR_IMG2TXT
NSMutableString *text = nil;
#endif /* VOCR_IMG2TXT */
ocrOpts_t options;
/*
create an autorelease pool:
https://developer.apple.com/documentation/foundation/nsautoreleasepool
*/
@autoreleasepool
{
/*
check for MacOSX 10.15 or newer, because we need
VNRecognizeTextRequest, which was first available
on MacOSX 10.15:
https://developer.apple.com/documentation/vision/vnrecognizetextrequest
*/
if (@available(macOS 10.15, *))
{
}
else
{
printError("%s requires MacOSX 10.15 or newer\n", gPgmName);
return 1;
}
if (argc <= 1)
{
printUsage();
return 1;
}
options.fast = NO;
options.addPageBreak = NO;
options.indent = YES;
options.indentWithTabs = NO;
options.lang = gLangEnglish;
options.forceOCR = NO;
while ((ch = getopt(argc, argv, gPgmOpts)) != -1)
{
switch(ch)
{
case gPgmOptHelp:
optHelp = YES;
break;
case gPgmOptAlgorithm:
if (strcmp(optarg, gPgmAlgorithmAccurate) == 0)
{
options.fast = NO;
}
else if (strcmp(optarg, gPgmAlgorithmFast) == 0)
{
options.fast = YES;
}
else
{
printError("Unsupported algorithm: '%s'\n", optarg);
err++;
}
break;
case gPgmOptForce:
options.forceOCR = YES;
break;
case gPgmOptPageBreak:
options.addPageBreak = YES;
break;
case gPgmOptIndent:
if (strcmp(optarg, gPgmIndentNo) == 0)
{
options.indent = NO;
options.indentWithTabs = NO;
}
else if (strcmp(optarg, gPgmIndentTab) == 0)
{
options.indent = YES;
options.indentWithTabs = YES;
}
else
{
printError("Unsupported indent type: '%s'\n", optarg);
err++;
}
break;
case gPgmOptLang:
if (@available(macos 11, *))
{
if (strcmp(optarg, gPgmLangGerman) == 0)
{
options.lang = gLangGerman;
}
else if (strcmp(optarg, gPgmLangEnglish) == 0)
{
options.lang = gLangEnglish;
}
else if (strcmp(optarg, gPgmLangFrench) == 0)
{
options.lang = gLangFrench;
}
else if (strcmp(optarg, gPgmLangItalian) == 0)
{
options.lang = gLangItalian;
}
else if (strcmp(optarg, gPgmLangPortuguese) == 0)
{
options.lang = gLangPortuguese;
}
else if (strcmp(optarg, gPgmLangSpanish) == 0)
{
options.lang = gLangSpanish;
}
else if (strcmp(optarg, gPgmLangChinese) == 0)
{
options.lang = gLangChinese;
}
else
{
printError("Unsupported language: '%s'\n", optarg);
err++;
}
}
else
{
/* before 11.x, only english is supported */
if (strcmp(optarg, gPgmLangEnglish) == 0)
{
options.lang = gLangEnglish;
}
else
{
printError("Unsupported language: '%s'\n", optarg);
err++;
}
}
break;
case gPgmOptVerbose: