code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
#include <stdint.h> #include <stddef.h> #include <stdlib.h> #include "../../../include/libbase64.h" #include "../../tables/tables.h" #include "../../codecs.h" #include "config.h" #include "../../env.h" #if HAVE_SSE41 #include <smmintrin.h> // Only enable inline assembly on supported compilers and on 64-bit CPUs. #ifndef BASE64_SSE41_USE_ASM # if (defined(__GNUC__) || defined(__clang__)) && BASE64_WORDSIZE == 64 # define BASE64_SSE41_USE_ASM 1 # else # define BASE64_SSE41_USE_ASM 0 # endif #endif #include "../ssse3/dec_reshuffle.c" #include "../ssse3/dec_loop.c" #if BASE64_SSE41_USE_ASM # include "../ssse3/enc_loop_asm.c" #else # include "../ssse3/enc_translate.c" # include "../ssse3/enc_reshuffle.c" # include "../ssse3/enc_loop.c" #endif #endif // HAVE_SSE41 void base64_stream_encode_sse41 BASE64_ENC_PARAMS { #if HAVE_SSE41 #include "../generic/enc_head.c" enc_loop_ssse3(&s, &slen, &o, &olen); #include "../generic/enc_tail.c" #else base64_enc_stub(state, src, srclen, out, outlen); #endif } int base64_stream_decode_sse41 BASE64_DEC_PARAMS { #if HAVE_SSE41 #include "../generic/dec_head.c" dec_loop_ssse3(&s, &slen, &o, &olen); #include "../generic/dec_tail.c" #else return base64_dec_stub(state, src, srclen, out, outlen); #endif }
2301_81045437/base64
lib/arch/sse41/codec.c
C
bsd
1,265
#include <stdint.h> #include <stddef.h> #include <stdlib.h> #include "../../../include/libbase64.h" #include "../../tables/tables.h" #include "../../codecs.h" #include "config.h" #include "../../env.h" #if HAVE_SSE42 #include <nmmintrin.h> // Only enable inline assembly on supported compilers and on 64-bit CPUs. #ifndef BASE64_SSE42_USE_ASM # if (defined(__GNUC__) || defined(__clang__)) && BASE64_WORDSIZE == 64 # define BASE64_SSE42_USE_ASM 1 # else # define BASE64_SSE42_USE_ASM 0 # endif #endif #include "../ssse3/dec_reshuffle.c" #include "../ssse3/dec_loop.c" #if BASE64_SSE42_USE_ASM # include "../ssse3/enc_loop_asm.c" #else # include "../ssse3/enc_translate.c" # include "../ssse3/enc_reshuffle.c" # include "../ssse3/enc_loop.c" #endif #endif // HAVE_SSE42 void base64_stream_encode_sse42 BASE64_ENC_PARAMS { #if HAVE_SSE42 #include "../generic/enc_head.c" enc_loop_ssse3(&s, &slen, &o, &olen); #include "../generic/enc_tail.c" #else base64_enc_stub(state, src, srclen, out, outlen); #endif } int base64_stream_decode_sse42 BASE64_DEC_PARAMS { #if HAVE_SSE42 #include "../generic/dec_head.c" dec_loop_ssse3(&s, &slen, &o, &olen); #include "../generic/dec_tail.c" #else return base64_dec_stub(state, src, srclen, out, outlen); #endif }
2301_81045437/base64
lib/arch/sse42/codec.c
C
bsd
1,265
#include <stdint.h> #include <stddef.h> #include <stdlib.h> #include "../../../include/libbase64.h" #include "../../tables/tables.h" #include "../../codecs.h" #include "config.h" #include "../../env.h" #if HAVE_SSSE3 #include <tmmintrin.h> // Only enable inline assembly on supported compilers and on 64-bit CPUs. // 32-bit CPUs with SSSE3 support, such as low-end Atoms, only have eight XMM // registers, which is not enough to run the inline assembly. #ifndef BASE64_SSSE3_USE_ASM # if (defined(__GNUC__) || defined(__clang__)) && BASE64_WORDSIZE == 64 # define BASE64_SSSE3_USE_ASM 1 # else # define BASE64_SSSE3_USE_ASM 0 # endif #endif #include "dec_reshuffle.c" #include "dec_loop.c" #if BASE64_SSSE3_USE_ASM # include "enc_loop_asm.c" #else # include "enc_reshuffle.c" # include "enc_translate.c" # include "enc_loop.c" #endif #endif // HAVE_SSSE3 void base64_stream_encode_ssse3 BASE64_ENC_PARAMS { #if HAVE_SSSE3 #include "../generic/enc_head.c" enc_loop_ssse3(&s, &slen, &o, &olen); #include "../generic/enc_tail.c" #else base64_enc_stub(state, src, srclen, out, outlen); #endif } int base64_stream_decode_ssse3 BASE64_DEC_PARAMS { #if HAVE_SSSE3 #include "../generic/dec_head.c" dec_loop_ssse3(&s, &slen, &o, &olen); #include "../generic/dec_tail.c" #else return base64_dec_stub(state, src, srclen, out, outlen); #endif }
2301_81045437/base64
lib/arch/ssse3/codec.c
C
bsd
1,351
// The input consists of six character sets in the Base64 alphabet, which we // need to map back to the 6-bit values they represent. There are three ranges, // two singles, and then there's the rest. // // # From To Add Characters // 1 [43] [62] +19 + // 2 [47] [63] +16 / // 3 [48..57] [52..61] +4 0..9 // 4 [65..90] [0..25] -65 A..Z // 5 [97..122] [26..51] -71 a..z // (6) Everything else => invalid input // // We will use lookup tables for character validation and offset computation. // Remember that 0x2X and 0x0X are the same index for _mm_shuffle_epi8, this // allows to mask with 0x2F instead of 0x0F and thus save one constant // declaration (register and/or memory access). // // For offsets: // Perfect hash for lut = ((src >> 4) & 0x2F) + ((src == 0x2F) ? 0xFF : 0x00) // 0000 = garbage // 0001 = / // 0010 = + // 0011 = 0-9 // 0100 = A-Z // 0101 = A-Z // 0110 = a-z // 0111 = a-z // 1000 >= garbage // // For validation, here's the table. // A character is valid if and only if the AND of the 2 lookups equals 0: // // hi \ lo 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 // LUT 0x15 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x13 0x1A 0x1B 0x1B 0x1B 0x1A // // 0000 0x10 char NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI // andlut 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 // // 0001 0x10 char DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US // andlut 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 // // 0010 0x01 char ! " # $ % & ' ( ) * + , - . / // andlut 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x00 0x01 0x01 0x01 0x00 // // 0011 0x02 char 0 1 2 3 4 5 6 7 8 9 : ; < = > ? // andlut 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x02 0x02 0x02 0x02 0x02 0x02 // // 0100 0x04 char @ A B C D E F G H I J K L M N O // andlut 0x04 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 // // 0101 0x08 char P Q R S T U V W X Y Z [ \ ] ^ _ // andlut 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x08 0x08 0x08 0x08 0x08 // // 0110 0x04 char ` a b c d e f g h i j k l m n o // andlut 0x04 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 // 0111 0x08 char p q r s t u v w x y z { | } ~ // andlut 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x08 0x08 0x08 0x08 0x08 // // 1000 0x10 andlut 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 // 1001 0x10 andlut 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 // 1010 0x10 andlut 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 // 1011 0x10 andlut 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 // 1100 0x10 andlut 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 // 1101 0x10 andlut 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 // 1110 0x10 andlut 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 // 1111 0x10 andlut 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 static BASE64_FORCE_INLINE int dec_loop_ssse3_inner (const uint8_t **s, uint8_t **o, size_t *rounds) { const __m128i lut_lo = _mm_setr_epi8( 0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x13, 0x1A, 0x1B, 0x1B, 0x1B, 0x1A); const __m128i lut_hi = _mm_setr_epi8( 0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10); const __m128i lut_roll = _mm_setr_epi8( 0, 16, 19, 4, -65, -65, -71, -71, 0, 0, 0, 0, 0, 0, 0, 0); const __m128i mask_2F = _mm_set1_epi8(0x2F); // Load input: __m128i str = _mm_loadu_si128((__m128i *) *s); // Table lookups: const __m128i hi_nibbles = _mm_and_si128(_mm_srli_epi32(str, 4), mask_2F); const __m128i lo_nibbles = _mm_and_si128(str, mask_2F); const __m128i hi = _mm_shuffle_epi8(lut_hi, hi_nibbles); const __m128i lo = _mm_shuffle_epi8(lut_lo, lo_nibbles); // Check for invalid input: if any "and" values from lo and hi are not // zero, fall back on bytewise code to do error checking and reporting: if (_mm_movemask_epi8(_mm_cmpgt_epi8(_mm_and_si128(lo, hi), _mm_setzero_si128())) != 0) { return 0; } const __m128i eq_2F = _mm_cmpeq_epi8(str, mask_2F); const __m128i roll = _mm_shuffle_epi8(lut_roll, _mm_add_epi8(eq_2F, hi_nibbles)); // Now simply add the delta values to the input: str = _mm_add_epi8(str, roll); // Reshuffle the input to packed 12-byte output format: str = dec_reshuffle(str); // Store the output: _mm_storeu_si128((__m128i *) *o, str); *s += 16; *o += 12; *rounds -= 1; return 1; } static inline void dec_loop_ssse3 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { if (*slen < 24) { return; } // Process blocks of 16 bytes per round. Because 4 extra zero bytes are // written after the output, ensure that there will be at least 8 bytes // of input data left to cover the gap. (6 data bytes and up to two // end-of-string markers.) size_t rounds = (*slen - 8) / 16; *slen -= rounds * 16; // 16 bytes consumed per round *olen += rounds * 12; // 12 bytes produced per round do { if (rounds >= 8) { if (dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds)) { continue; } break; } if (rounds >= 4) { if (dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds)) { continue; } break; } if (rounds >= 2) { if (dec_loop_ssse3_inner(s, o, &rounds) && dec_loop_ssse3_inner(s, o, &rounds)) { continue; } break; } dec_loop_ssse3_inner(s, o, &rounds); break; } while (rounds > 0); // Adjust for any rounds that were skipped: *slen += rounds * 16; *olen -= rounds * 12; }
2301_81045437/base64
lib/arch/ssse3/dec_loop.c
C
bsd
6,891
static BASE64_FORCE_INLINE __m128i dec_reshuffle (const __m128i in) { // in, bits, upper case are most significant bits, lower case are least significant bits // 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ // 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG // 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD // 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA const __m128i merge_ab_and_bc = _mm_maddubs_epi16(in, _mm_set1_epi32(0x01400140)); // 0000kkkk LLllllll 0000JJJJ JJjjKKKK // 0000hhhh IIiiiiii 0000GGGG GGggHHHH // 0000eeee FFffffff 0000DDDD DDddEEEE // 0000bbbb CCcccccc 0000AAAA AAaaBBBB const __m128i out = _mm_madd_epi16(merge_ab_and_bc, _mm_set1_epi32(0x00011000)); // 00000000 JJJJJJjj KKKKkkkk LLllllll // 00000000 GGGGGGgg HHHHhhhh IIiiiiii // 00000000 DDDDDDdd EEEEeeee FFffffff // 00000000 AAAAAAaa BBBBbbbb CCcccccc // Pack bytes together: return _mm_shuffle_epi8(out, _mm_setr_epi8( 2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1)); // 00000000 00000000 00000000 00000000 // LLllllll KKKKkkkk JJJJJJjj IIiiiiii // HHHHhhhh GGGGGGgg FFffffff EEEEeeee // DDDDDDdd CCcccccc BBBBbbbb AAAAAAaa }
2301_81045437/base64
lib/arch/ssse3/dec_reshuffle.c
C
bsd
1,118
static BASE64_FORCE_INLINE void enc_loop_ssse3_inner (const uint8_t **s, uint8_t **o) { // Load input: __m128i str = _mm_loadu_si128((__m128i *) *s); // Reshuffle: str = enc_reshuffle(str); // Translate reshuffled bytes to the Base64 alphabet: str = enc_translate(str); // Store: _mm_storeu_si128((__m128i *) *o, str); *s += 12; *o += 16; } static inline void enc_loop_ssse3 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { if (*slen < 16) { return; } // Process blocks of 12 bytes at a time. Because blocks are loaded 16 // bytes at a time, ensure that there will be at least 4 remaining // bytes after the last round, so that the final read will not pass // beyond the bounds of the input buffer: size_t rounds = (*slen - 4) / 12; *slen -= rounds * 12; // 12 bytes consumed per round *olen += rounds * 16; // 16 bytes produced per round do { if (rounds >= 8) { enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); rounds -= 8; continue; } if (rounds >= 4) { enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); rounds -= 4; continue; } if (rounds >= 2) { enc_loop_ssse3_inner(s, o); enc_loop_ssse3_inner(s, o); rounds -= 2; continue; } enc_loop_ssse3_inner(s, o); break; } while (rounds > 0); }
2301_81045437/base64
lib/arch/ssse3/enc_loop.c
C
bsd
1,549
// Apologies in advance for combining the preprocessor with inline assembly, // two notoriously gnarly parts of C, but it was necessary to avoid a lot of // code repetition. The preprocessor is used to template large sections of // inline assembly that differ only in the registers used. If the code was // written out by hand, it would become very large and hard to audit. // Generate a block of inline assembly that loads register R0 from memory. The // offset at which the register is loaded is set by the given round. #define LOAD(R0, ROUND) \ "lddqu ("#ROUND" * 12)(%[src]), %["R0"] \n\t" // Generate a block of inline assembly that deinterleaves and shuffles register // R0 using preloaded constants. Outputs in R0 and R1. #define SHUF(R0, R1) \ "pshufb %[lut0], %["R0"] \n\t" \ "movdqa %["R0"], %["R1"] \n\t" \ "pand %[msk0], %["R0"] \n\t" \ "pand %[msk2], %["R1"] \n\t" \ "pmulhuw %[msk1], %["R0"] \n\t" \ "pmullw %[msk3], %["R1"] \n\t" \ "por %["R1"], %["R0"] \n\t" // Generate a block of inline assembly that takes R0 and R1 and translates // their contents to the base64 alphabet, using preloaded constants. #define TRAN(R0, R1, R2) \ "movdqa %["R0"], %["R1"] \n\t" \ "movdqa %["R0"], %["R2"] \n\t" \ "psubusb %[n51], %["R1"] \n\t" \ "pcmpgtb %[n25], %["R2"] \n\t" \ "psubb %["R2"], %["R1"] \n\t" \ "movdqa %[lut1], %["R2"] \n\t" \ "pshufb %["R1"], %["R2"] \n\t" \ "paddb %["R2"], %["R0"] \n\t" // Generate a block of inline assembly that stores the given register R0 at an // offset set by the given round. #define STOR(R0, ROUND) \ "movdqu %["R0"], ("#ROUND" * 16)(%[dst]) \n\t" // Generate a block of inline assembly that generates a single self-contained // encoder round: fetch the data, process it, and store the result. Then update // the source and destination pointers. #define ROUND() \ LOAD("a", 0) \ SHUF("a", "b") \ TRAN("a", "b", "c") \ STOR("a", 0) \ "add $12, %[src] \n\t" \ "add $16, %[dst] \n\t" // Define a macro that initiates a three-way interleaved encoding round by // preloading registers a, b and c from memory. // The register graph shows which registers are in use during each step, and // is a visual aid for choosing registers for that step. Symbol index: // // + indicates that a register is loaded by that step. // | indicates that a register is in use and must not be touched. // - indicates that a register is decommissioned by that step. // x indicates that a register is used as a temporary by that step. // V indicates that a register is an input or output to the macro. // #define ROUND_3_INIT() /* a b c d e f */ \ LOAD("a", 0) /* + */ \ SHUF("a", "d") /* | + */ \ LOAD("b", 1) /* | + | */ \ TRAN("a", "d", "e") /* | | - x */ \ LOAD("c", 2) /* V V V */ // Define a macro that translates, shuffles and stores the input registers A, B // and C, and preloads registers D, E and F for the next round. // This macro can be arbitrarily daisy-chained by feeding output registers D, E // and F back into the next round as input registers A, B and C. The macro // carefully interleaves memory operations with data operations for optimal // pipelined performance. #define ROUND_3(ROUND, A,B,C,D,E,F) /* A B C D E F */ \ LOAD(D, (ROUND + 3)) /* V V V + */ \ SHUF(B, E) /* | | | | + */ \ STOR(A, (ROUND + 0)) /* - | | | | */ \ TRAN(B, E, F) /* | | | - x */ \ LOAD(E, (ROUND + 4)) /* | | | + */ \ SHUF(C, A) /* + | | | | */ \ STOR(B, (ROUND + 1)) /* | - | | | */ \ TRAN(C, A, F) /* - | | | x */ \ LOAD(F, (ROUND + 5)) /* | | | + */ \ SHUF(D, A) /* + | | | | */ \ STOR(C, (ROUND + 2)) /* | - | | | */ \ TRAN(D, A, B) /* - x V V V */ // Define a macro that terminates a ROUND_3 macro by taking pre-loaded // registers D, E and F, and translating, shuffling and storing them. #define ROUND_3_END(ROUND, A,B,C,D,E,F) /* A B C D E F */ \ SHUF(E, A) /* + V V V */ \ STOR(D, (ROUND + 3)) /* | - | | */ \ TRAN(E, A, B) /* - x | | */ \ SHUF(F, C) /* + | | */ \ STOR(E, (ROUND + 4)) /* | - | */ \ TRAN(F, C, D) /* - x | */ \ STOR(F, (ROUND + 5)) /* - */ // Define a type A round. Inputs are a, b, and c, outputs are d, e, and f. #define ROUND_3_A(ROUND) \ ROUND_3(ROUND, "a", "b", "c", "d", "e", "f") // Define a type B round. Inputs and outputs are swapped with regard to type A. #define ROUND_3_B(ROUND) \ ROUND_3(ROUND, "d", "e", "f", "a", "b", "c") // Terminating macro for a type A round. #define ROUND_3_A_LAST(ROUND) \ ROUND_3_A(ROUND) \ ROUND_3_END(ROUND, "a", "b", "c", "d", "e", "f") // Terminating macro for a type B round. #define ROUND_3_B_LAST(ROUND) \ ROUND_3_B(ROUND) \ ROUND_3_END(ROUND, "d", "e", "f", "a", "b", "c") // Suppress clang's warning that the literal string in the asm statement is // overlong (longer than the ISO-mandated minimum size of 4095 bytes for C99 // compilers). It may be true, but the goal here is not C99 portability. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverlength-strings" static inline void enc_loop_ssse3 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen) { // For a clearer explanation of the algorithm used by this function, // please refer to the plain (not inline assembly) implementation. This // function follows the same basic logic. if (*slen < 16) { return; } // Process blocks of 12 bytes at a time. Input is read in blocks of 16 // bytes, so "reserve" four bytes from the input buffer to ensure that // we never read beyond the end of the input buffer. size_t rounds = (*slen - 4) / 12; *slen -= rounds * 12; // 12 bytes consumed per round *olen += rounds * 16; // 16 bytes produced per round // Number of times to go through the 36x loop. size_t loops = rounds / 36; // Number of rounds remaining after the 36x loop. rounds %= 36; // Lookup tables. const __m128i lut0 = _mm_set_epi8( 10, 11, 9, 10, 7, 8, 6, 7, 4, 5, 3, 4, 1, 2, 0, 1); const __m128i lut1 = _mm_setr_epi8( 65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0); // Temporary registers. __m128i a, b, c, d, e, f; __asm__ volatile ( // If there are 36 rounds or more, enter a 36x unrolled loop of // interleaved encoding rounds. The rounds interleave memory // operations (load/store) with data operations (table lookups, // etc) to maximize pipeline throughput. " test %[loops], %[loops] \n\t" " jz 18f \n\t" " jmp 36f \n\t" " \n\t" ".balign 64 \n\t" "36: " ROUND_3_INIT() " " ROUND_3_A( 0) " " ROUND_3_B( 3) " " ROUND_3_A( 6) " " ROUND_3_B( 9) " " ROUND_3_A(12) " " ROUND_3_B(15) " " ROUND_3_A(18) " " ROUND_3_B(21) " " ROUND_3_A(24) " " ROUND_3_B(27) " " ROUND_3_A_LAST(30) " add $(12 * 36), %[src] \n\t" " add $(16 * 36), %[dst] \n\t" " dec %[loops] \n\t" " jnz 36b \n\t" // Enter an 18x unrolled loop for rounds of 18 or more. "18: cmp $18, %[rounds] \n\t" " jl 9f \n\t" " " ROUND_3_INIT() " " ROUND_3_A(0) " " ROUND_3_B(3) " " ROUND_3_A(6) " " ROUND_3_B(9) " " ROUND_3_A_LAST(12) " sub $18, %[rounds] \n\t" " add $(12 * 18), %[src] \n\t" " add $(16 * 18), %[dst] \n\t" // Enter a 9x unrolled loop for rounds of 9 or more. "9: cmp $9, %[rounds] \n\t" " jl 6f \n\t" " " ROUND_3_INIT() " " ROUND_3_A(0) " " ROUND_3_B_LAST(3) " sub $9, %[rounds] \n\t" " add $(12 * 9), %[src] \n\t" " add $(16 * 9), %[dst] \n\t" // Enter a 6x unrolled loop for rounds of 6 or more. "6: cmp $6, %[rounds] \n\t" " jl 55f \n\t" " " ROUND_3_INIT() " " ROUND_3_A_LAST(0) " sub $6, %[rounds] \n\t" " add $(12 * 6), %[src] \n\t" " add $(16 * 6), %[dst] \n\t" // Dispatch the remaining rounds 0..5. "55: cmp $3, %[rounds] \n\t" " jg 45f \n\t" " je 3f \n\t" " cmp $1, %[rounds] \n\t" " jg 2f \n\t" " je 1f \n\t" " jmp 0f \n\t" "45: cmp $4, %[rounds] \n\t" " je 4f \n\t" // Block of non-interlaced encoding rounds, which can each // individually be jumped to. Rounds fall through to the next. "5: " ROUND() "4: " ROUND() "3: " ROUND() "2: " ROUND() "1: " ROUND() "0: \n\t" // Outputs (modified). : [rounds] "+r" (rounds), [loops] "+r" (loops), [src] "+r" (*s), [dst] "+r" (*o), [a] "=&x" (a), [b] "=&x" (b), [c] "=&x" (c), [d] "=&x" (d), [e] "=&x" (e), [f] "=&x" (f) // Inputs (not modified). : [lut0] "x" (lut0), [lut1] "x" (lut1), [msk0] "x" (_mm_set1_epi32(0x0FC0FC00)), [msk1] "x" (_mm_set1_epi32(0x04000040)), [msk2] "x" (_mm_set1_epi32(0x003F03F0)), [msk3] "x" (_mm_set1_epi32(0x01000010)), [n51] "x" (_mm_set1_epi8(51)), [n25] "x" (_mm_set1_epi8(25)) // Clobbers. : "cc", "memory" ); } #pragma GCC diagnostic pop
2301_81045437/base64
lib/arch/ssse3/enc_loop_asm.c
C
bsd
9,310
static BASE64_FORCE_INLINE __m128i enc_reshuffle (__m128i in) { // Input, bytes MSB to LSB: // 0 0 0 0 l k j i h g f e d c b a in = _mm_shuffle_epi8(in, _mm_set_epi8( 10, 11, 9, 10, 7, 8, 6, 7, 4, 5, 3, 4, 1, 2, 0, 1)); // in, bytes MSB to LSB: // k l j k // h i g h // e f d e // b c a b const __m128i t0 = _mm_and_si128(in, _mm_set1_epi32(0x0FC0FC00)); // bits, upper case are most significant bits, lower case are least significant bits // 0000kkkk LL000000 JJJJJJ00 00000000 // 0000hhhh II000000 GGGGGG00 00000000 // 0000eeee FF000000 DDDDDD00 00000000 // 0000bbbb CC000000 AAAAAA00 00000000 const __m128i t1 = _mm_mulhi_epu16(t0, _mm_set1_epi32(0x04000040)); // 00000000 00kkkkLL 00000000 00JJJJJJ // 00000000 00hhhhII 00000000 00GGGGGG // 00000000 00eeeeFF 00000000 00DDDDDD // 00000000 00bbbbCC 00000000 00AAAAAA const __m128i t2 = _mm_and_si128(in, _mm_set1_epi32(0x003F03F0)); // 00000000 00llllll 000000jj KKKK0000 // 00000000 00iiiiii 000000gg HHHH0000 // 00000000 00ffffff 000000dd EEEE0000 // 00000000 00cccccc 000000aa BBBB0000 const __m128i t3 = _mm_mullo_epi16(t2, _mm_set1_epi32(0x01000010)); // 00llllll 00000000 00jjKKKK 00000000 // 00iiiiii 00000000 00ggHHHH 00000000 // 00ffffff 00000000 00ddEEEE 00000000 // 00cccccc 00000000 00aaBBBB 00000000 return _mm_or_si128(t1, t3); // 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ // 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG // 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD // 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA }
2301_81045437/base64
lib/arch/ssse3/enc_reshuffle.c
C
bsd
1,514
static BASE64_FORCE_INLINE __m128i enc_translate (const __m128i in) { // A lookup table containing the absolute offsets for all ranges: const __m128i lut = _mm_setr_epi8( 65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0 ); // Translate values 0..63 to the Base64 alphabet. There are five sets: // # From To Abs Index Characters // 0 [0..25] [65..90] +65 0 ABCDEFGHIJKLMNOPQRSTUVWXYZ // 1 [26..51] [97..122] +71 1 abcdefghijklmnopqrstuvwxyz // 2 [52..61] [48..57] -4 [2..11] 0123456789 // 3 [62] [43] -19 12 + // 4 [63] [47] -16 13 / // Create LUT indices from the input. The index for range #0 is right, // others are 1 less than expected: __m128i indices = _mm_subs_epu8(in, _mm_set1_epi8(51)); // mask is 0xFF (-1) for range #[1..4] and 0x00 for range #0: __m128i mask = _mm_cmpgt_epi8(in, _mm_set1_epi8(25)); // Subtract -1, so add 1 to indices for range #[1..4]. All indices are // now correct: indices = _mm_sub_epi8(indices, mask); // Add offsets to input values: return _mm_add_epi8(in, _mm_shuffle_epi8(lut, indices)); }
2301_81045437/base64
lib/arch/ssse3/enc_translate.c
C
bsd
1,171
#include <stdbool.h> #include <stdint.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include "../include/libbase64.h" #include "codecs.h" #include "config.h" #include "env.h" #if (__x86_64__ || __i386__ || _M_X86 || _M_X64) #define BASE64_X86 #if (HAVE_SSSE3 || HAVE_SSE41 || HAVE_SSE42 || HAVE_AVX || HAVE_AVX2 || HAVE_AVX512) #define BASE64_X86_SIMD #endif #endif #ifdef BASE64_X86 #ifdef _MSC_VER #include <intrin.h> #define __cpuid_count(__level, __count, __eax, __ebx, __ecx, __edx) \ { \ int info[4]; \ __cpuidex(info, __level, __count); \ __eax = info[0]; \ __ebx = info[1]; \ __ecx = info[2]; \ __edx = info[3]; \ } #define __cpuid(__level, __eax, __ebx, __ecx, __edx) \ __cpuid_count(__level, 0, __eax, __ebx, __ecx, __edx) #else #include <cpuid.h> #if HAVE_AVX512 || HAVE_AVX2 || HAVE_AVX #if ((__GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 2) || (__clang_major__ >= 3)) static inline uint64_t _xgetbv (uint32_t index) { uint32_t eax, edx; __asm__ __volatile__("xgetbv" : "=a"(eax), "=d"(edx) : "c"(index)); return ((uint64_t)edx << 32) | eax; } #else #error "Platform not supported" #endif #endif #endif #ifndef bit_AVX512vl #define bit_AVX512vl (1 << 31) #endif #ifndef bit_AVX512vbmi #define bit_AVX512vbmi (1 << 1) #endif #ifndef bit_AVX2 #define bit_AVX2 (1 << 5) #endif #ifndef bit_SSSE3 #define bit_SSSE3 (1 << 9) #endif #ifndef bit_SSE41 #define bit_SSE41 (1 << 19) #endif #ifndef bit_SSE42 #define bit_SSE42 (1 << 20) #endif #ifndef bit_AVX #define bit_AVX (1 << 28) #endif #define bit_XSAVE_XRSTORE (1 << 27) #ifndef _XCR_XFEATURE_ENABLED_MASK #define _XCR_XFEATURE_ENABLED_MASK 0 #endif #define bit_XMM (1 << 1) #define bit_YMM (1 << 2) #define bit_OPMASK (1 << 5) #define bit_ZMM (1 << 6) #define bit_HIGH_ZMM (1 << 7) #define _XCR_XMM_AND_YMM_STATE_ENABLED_BY_OS (bit_XMM | bit_YMM) #define _AVX_512_ENABLED_BY_OS (bit_XMM | bit_YMM | bit_OPMASK | bit_ZMM | bit bit_HIGH_ZMM) #endif // Function declarations: #define BASE64_CODEC_FUNCS(arch) \ extern void base64_stream_encode_ ## arch BASE64_ENC_PARAMS; \ extern int base64_stream_decode_ ## arch BASE64_DEC_PARAMS; BASE64_CODEC_FUNCS(avx512) BASE64_CODEC_FUNCS(avx2) BASE64_CODEC_FUNCS(neon32) BASE64_CODEC_FUNCS(neon64) BASE64_CODEC_FUNCS(plain) BASE64_CODEC_FUNCS(ssse3) BASE64_CODEC_FUNCS(sse41) BASE64_CODEC_FUNCS(sse42) BASE64_CODEC_FUNCS(avx) static bool codec_choose_forced (struct codec *codec, int flags) { // If the user wants to use a certain codec, // always allow it, even if the codec is a no-op. // For testing purposes. if (!(flags & 0xFFFF)) { return false; } if (flags & BASE64_FORCE_AVX2) { codec->enc = base64_stream_encode_avx2; codec->dec = base64_stream_decode_avx2; return true; } if (flags & BASE64_FORCE_NEON32) { codec->enc = base64_stream_encode_neon32; codec->dec = base64_stream_decode_neon32; return true; } if (flags & BASE64_FORCE_NEON64) { codec->enc = base64_stream_encode_neon64; codec->dec = base64_stream_decode_neon64; return true; } if (flags & BASE64_FORCE_PLAIN) { codec->enc = base64_stream_encode_plain; codec->dec = base64_stream_decode_plain; return true; } if (flags & BASE64_FORCE_SSSE3) { codec->enc = base64_stream_encode_ssse3; codec->dec = base64_stream_decode_ssse3; return true; } if (flags & BASE64_FORCE_SSE41) { codec->enc = base64_stream_encode_sse41; codec->dec = base64_stream_decode_sse41; return true; } if (flags & BASE64_FORCE_SSE42) { codec->enc = base64_stream_encode_sse42; codec->dec = base64_stream_decode_sse42; return true; } if (flags & BASE64_FORCE_AVX) { codec->enc = base64_stream_encode_avx; codec->dec = base64_stream_decode_avx; return true; } if (flags & BASE64_FORCE_AVX512) { codec->enc = base64_stream_encode_avx512; codec->dec = base64_stream_decode_avx512; return true; } return false; } static bool codec_choose_arm (struct codec *codec) { #if (defined(__ARM_NEON__) || defined(__ARM_NEON)) && ((defined(__aarch64__) && HAVE_NEON64) || HAVE_NEON32) // Unfortunately there is no portable way to check for NEON // support at runtime from userland in the same way that x86 // has cpuid, so just stick to the compile-time configuration: #if defined(__aarch64__) && HAVE_NEON64 codec->enc = base64_stream_encode_neon64; codec->dec = base64_stream_decode_neon64; #else codec->enc = base64_stream_encode_neon32; codec->dec = base64_stream_decode_neon32; #endif return true; #else (void)codec; return false; #endif } static bool codec_choose_x86 (struct codec *codec) { #ifdef BASE64_X86_SIMD unsigned int eax, ebx = 0, ecx = 0, edx; unsigned int max_level; #ifdef _MSC_VER int info[4]; __cpuidex(info, 0, 0); max_level = info[0]; #else max_level = __get_cpuid_max(0, NULL); #endif #if HAVE_AVX512 || HAVE_AVX2 || HAVE_AVX // Check for AVX/AVX2/AVX512 support: // Checking for AVX requires 3 things: // 1) CPUID indicates that the OS uses XSAVE and XRSTORE instructions // (allowing saving YMM registers on context switch) // 2) CPUID indicates support for AVX // 3) XGETBV indicates the AVX registers will be saved and restored on // context switch // // Note that XGETBV is only available on 686 or later CPUs, so the // instruction needs to be conditionally run. if (max_level >= 1) { __cpuid_count(1, 0, eax, ebx, ecx, edx); if (ecx & bit_XSAVE_XRSTORE) { uint64_t xcr_mask; xcr_mask = _xgetbv(_XCR_XFEATURE_ENABLED_MASK); if ((xcr_mask & _XCR_XMM_AND_YMM_STATE_ENABLED_BY_OS) == _XCR_XMM_AND_YMM_STATE_ENABLED_BY_OS) { // check multiple bits at once #if HAVE_AVX512 if (max_level >= 7 && ((xcr_mask & _AVX_512_ENABLED_BY_OS) == _AVX_512_ENABLED_BY_OS)) { __cpuid_count(7, 0, eax, ebx, ecx, edx); if ((ebx & bit_AVX512vl) && (ecx & bit_AVX512vbmi)) { codec->enc = base64_stream_encode_avx512; codec->dec = base64_stream_decode_avx512; return true; } } #endif #if HAVE_AVX2 if (max_level >= 7) { __cpuid_count(7, 0, eax, ebx, ecx, edx); if (ebx & bit_AVX2) { codec->enc = base64_stream_encode_avx2; codec->dec = base64_stream_decode_avx2; return true; } } #endif #if HAVE_AVX __cpuid_count(1, 0, eax, ebx, ecx, edx); if (ecx & bit_AVX) { codec->enc = base64_stream_encode_avx; codec->dec = base64_stream_decode_avx; return true; } #endif } } } #endif #if HAVE_SSE42 // Check for SSE42 support: if (max_level >= 1) { __cpuid(1, eax, ebx, ecx, edx); if (ecx & bit_SSE42) { codec->enc = base64_stream_encode_sse42; codec->dec = base64_stream_decode_sse42; return true; } } #endif #if HAVE_SSE41 // Check for SSE41 support: if (max_level >= 1) { __cpuid(1, eax, ebx, ecx, edx); if (ecx & bit_SSE41) { codec->enc = base64_stream_encode_sse41; codec->dec = base64_stream_decode_sse41; return true; } } #endif #if HAVE_SSSE3 // Check for SSSE3 support: if (max_level >= 1) { __cpuid(1, eax, ebx, ecx, edx); if (ecx & bit_SSSE3) { codec->enc = base64_stream_encode_ssse3; codec->dec = base64_stream_decode_ssse3; return true; } } #endif #else (void)codec; #endif return false; } void codec_choose (struct codec *codec, int flags) { // User forced a codec: if (codec_choose_forced(codec, flags)) { return; } // Runtime feature detection: if (codec_choose_arm(codec)) { return; } if (codec_choose_x86(codec)) { return; } codec->enc = base64_stream_encode_plain; codec->dec = base64_stream_decode_plain; }
2301_81045437/base64
lib/codec_choose.c
C
bsd
7,655
#include "../include/libbase64.h" // Function parameters for encoding functions: #define BASE64_ENC_PARAMS \ ( struct base64_state *state \ , const char *src \ , size_t srclen \ , char *out \ , size_t *outlen \ ) // Function parameters for decoding functions: #define BASE64_DEC_PARAMS \ ( struct base64_state *state \ , const char *src \ , size_t srclen \ , char *out \ , size_t *outlen \ ) // This function is used as a stub when a certain encoder is not compiled in. // It discards the inputs and returns zero output bytes. static inline void base64_enc_stub BASE64_ENC_PARAMS { (void) state; (void) src; (void) srclen; (void) out; *outlen = 0; } // This function is used as a stub when a certain decoder is not compiled in. // It discards the inputs and returns an invalid decoding result. static inline int base64_dec_stub BASE64_DEC_PARAMS { (void) state; (void) src; (void) srclen; (void) out; (void) outlen; return -1; } typedef void (* base64_enc_fn) BASE64_ENC_PARAMS; typedef int (* base64_dec_fn) BASE64_DEC_PARAMS; struct codec { base64_enc_fn enc; base64_dec_fn dec; }; extern void codec_choose (struct codec *, int flags);
2301_81045437/base64
lib/codecs.h
C
bsd
1,199
#ifndef BASE64_ENV_H #define BASE64_ENV_H #include <stdint.h> // This header file contains macro definitions that describe certain aspects of // the compile-time environment. Compatibility and portability macros go here. // Define machine endianness. This is for GCC: #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) # define BASE64_LITTLE_ENDIAN 1 #else # define BASE64_LITTLE_ENDIAN 0 #endif // This is for Clang: #ifdef __LITTLE_ENDIAN__ # define BASE64_LITTLE_ENDIAN 1 #endif #ifdef __BIG_ENDIAN__ # define BASE64_LITTLE_ENDIAN 0 #endif // MSVC++ needs intrin.h for _byteswap_uint64 (issue #68): #if BASE64_LITTLE_ENDIAN && defined(_MSC_VER) # include <intrin.h> #endif // Endian conversion functions: #if BASE64_LITTLE_ENDIAN # ifdef _MSC_VER // Microsoft Visual C++: # define BASE64_HTOBE32(x) _byteswap_ulong(x) # define BASE64_HTOBE64(x) _byteswap_uint64(x) # else // GCC and Clang: # define BASE64_HTOBE32(x) __builtin_bswap32(x) # define BASE64_HTOBE64(x) __builtin_bswap64(x) # endif #else // No conversion needed: # define BASE64_HTOBE32(x) (x) # define BASE64_HTOBE64(x) (x) #endif // Detect word size: #if defined (__x86_64__) // This also works for the x32 ABI, which has a 64-bit word size. # define BASE64_WORDSIZE 64 #elif SIZE_MAX == UINT32_MAX # define BASE64_WORDSIZE 32 #elif SIZE_MAX == UINT64_MAX # define BASE64_WORDSIZE 64 #else # error BASE64_WORDSIZE_NOT_DEFINED #endif // End-of-file definitions. // Almost end-of-file when waiting for the last '=' character: #define BASE64_AEOF 1 // End-of-file when stream end has been reached or invalid input provided: #define BASE64_EOF 2 // GCC 7 defaults to issuing a warning for fallthrough in switch statements, // unless the fallthrough cases are marked with an attribute. As we use // fallthrough deliberately, define an alias for the attribute: #if __GNUC__ >= 7 # define BASE64_FALLTHROUGH __attribute__((fallthrough)); #else # define BASE64_FALLTHROUGH #endif // Declare macros to ensure that functions that are intended to be inlined, are // actually inlined, even when no optimization is applied. A lot of inner loop // code is factored into separate functions for reasons of readability, but // that code should always be inlined (and optimized) in the main loop. #ifdef _MSC_VER # define BASE64_FORCE_INLINE __forceinline #else # define BASE64_FORCE_INLINE inline __attribute__((always_inline)) #endif #endif // BASE64_ENV_H
2301_81045437/base64
lib/env.h
C
bsd
2,453
#include <stdint.h> #include <stddef.h> #ifdef _OPENMP #include <omp.h> #endif #include "../include/libbase64.h" #include "tables/tables.h" #include "codecs.h" #include "env.h" // These static function pointers are initialized once when the library is // first used, and remain in use for the remaining lifetime of the program. // The idea being that CPU features don't change at runtime. static struct codec codec = { NULL, NULL }; void base64_stream_encode_init (struct base64_state *state, int flags) { // If any of the codec flags are set, redo choice: if (codec.enc == NULL || flags & 0xFF) { codec_choose(&codec, flags); } state->eof = 0; state->bytes = 0; state->carry = 0; state->flags = flags; } void base64_stream_encode ( struct base64_state *state , const char *src , size_t srclen , char *out , size_t *outlen ) { codec.enc(state, src, srclen, out, outlen); } void base64_stream_encode_final ( struct base64_state *state , char *out , size_t *outlen ) { uint8_t *o = (uint8_t *)out; if (state->bytes == 1) { *o++ = base64_table_enc_6bit[state->carry]; *o++ = '='; *o++ = '='; *outlen = 3; return; } if (state->bytes == 2) { *o++ = base64_table_enc_6bit[state->carry]; *o++ = '='; *outlen = 2; return; } *outlen = 0; } void base64_stream_decode_init (struct base64_state *state, int flags) { // If any of the codec flags are set, redo choice: if (codec.dec == NULL || flags & 0xFFFF) { codec_choose(&codec, flags); } state->eof = 0; state->bytes = 0; state->carry = 0; state->flags = flags; } int base64_stream_decode ( struct base64_state *state , const char *src , size_t srclen , char *out , size_t *outlen ) { return codec.dec(state, src, srclen, out, outlen); } #ifdef _OPENMP // Due to the overhead of initializing OpenMP and creating a team of // threads, we require the data length to be larger than a threshold: #define OMP_THRESHOLD 20000 // Conditionally include OpenMP-accelerated codec implementations: #include "lib_openmp.c" #endif void base64_encode ( const char *src , size_t srclen , char *out , size_t *outlen , int flags ) { size_t s; size_t t; struct base64_state state; #ifdef _OPENMP if (srclen >= OMP_THRESHOLD) { base64_encode_openmp(src, srclen, out, outlen, flags); return; } #endif // Init the stream reader: base64_stream_encode_init(&state, flags); // Feed the whole string to the stream reader: base64_stream_encode(&state, src, srclen, out, &s); // Finalize the stream by writing trailer if any: base64_stream_encode_final(&state, out + s, &t); // Final output length is stream length plus tail: *outlen = s + t; } int base64_decode ( const char *src , size_t srclen , char *out , size_t *outlen , int flags ) { int ret; struct base64_state state; #ifdef _OPENMP if (srclen >= OMP_THRESHOLD) { return base64_decode_openmp(src, srclen, out, outlen, flags); } #endif // Init the stream reader: base64_stream_decode_init(&state, flags); // Feed the whole string to the stream reader: ret = base64_stream_decode(&state, src, srclen, out, outlen); // If when decoding a whole block, we're still waiting for input then fail: if (ret && (state.bytes == 0)) { return ret; } return 0; }
2301_81045437/base64
lib/lib.c
C
bsd
3,281
// This code makes some assumptions on the implementation of // base64_stream_encode_init(), base64_stream_encode() and base64_stream_decode(). // Basically these assumptions boil down to that when breaking the src into // parts, out parts can be written without side effects. // This is met when: // 1) base64_stream_encode() and base64_stream_decode() don't use globals; // 2) the shared variables src and out are not read or written outside of the // bounds of their parts, i.e. when base64_stream_encode() reads a multiple // of 3 bytes, it must write no more then a multiple of 4 bytes, not even // temporarily; // 3) the state flag can be discarded after base64_stream_encode() and // base64_stream_decode() on the parts. static inline void base64_encode_openmp ( const char *src , size_t srclen , char *out , size_t *outlen , int flags ) { size_t s; size_t t; size_t sum = 0, len, last_len; struct base64_state state, initial_state; int num_threads, i; // Request a number of threads but not necessarily get them: #pragma omp parallel { // Get the number of threads used from one thread only, // as num_threads is a shared var: #pragma omp single { num_threads = omp_get_num_threads(); // Split the input string into num_threads parts, each // part a multiple of 3 bytes. The remaining bytes will // be done later: len = srclen / (num_threads * 3); len *= 3; last_len = srclen - num_threads * len; // Init the stream reader: base64_stream_encode_init(&state, flags); initial_state = state; } // Single has an implicit barrier for all threads to wait here // for the above to complete: #pragma omp for firstprivate(state) private(s) reduction(+:sum) schedule(static,1) for (i = 0; i < num_threads; i++) { // Feed each part of the string to the stream reader: base64_stream_encode(&state, src + i * len, len, out + i * len * 4 / 3, &s); sum += s; } } // As encoding should never fail and we encode an exact multiple // of 3 bytes, we can discard state: state = initial_state; // Encode the remaining bytes: base64_stream_encode(&state, src + num_threads * len, last_len, out + num_threads * len * 4 / 3, &s); // Finalize the stream by writing trailer if any: base64_stream_encode_final(&state, out + num_threads * len * 4 / 3 + s, &t); // Final output length is stream length plus tail: sum += s + t; *outlen = sum; } static inline int base64_decode_openmp ( const char *src , size_t srclen , char *out , size_t *outlen , int flags ) { int num_threads, result = 0, i; size_t sum = 0, len, last_len, s; struct base64_state state, initial_state; // Request a number of threads but not necessarily get them: #pragma omp parallel { // Get the number of threads used from one thread only, // as num_threads is a shared var: #pragma omp single { num_threads = omp_get_num_threads(); // Split the input string into num_threads parts, each // part a multiple of 4 bytes. The remaining bytes will // be done later: len = srclen / (num_threads * 4); len *= 4; last_len = srclen - num_threads * len; // Init the stream reader: base64_stream_decode_init(&state, flags); initial_state = state; } // Single has an implicit barrier to wait here for the above to // complete: #pragma omp for firstprivate(state) private(s) reduction(+:sum, result) schedule(static,1) for (i = 0; i < num_threads; i++) { int this_result; // Feed each part of the string to the stream reader: this_result = base64_stream_decode(&state, src + i * len, len, out + i * len * 3 / 4, &s); sum += s; result += this_result; } } // If `result' equals `-num_threads', then all threads returned -1, // indicating that the requested codec is not available: if (result == -num_threads) { return -1; } // If `result' does not equal `num_threads', then at least one of the // threads hit a decode error: if (result != num_threads) { return 0; } // So far so good, now decode whatever remains in the buffer. Reuse the // initial state, since we are at a 4-byte boundary: state = initial_state; result = base64_stream_decode(&state, src + num_threads * len, last_len, out + num_threads * len * 3 / 4, &s); sum += s; *outlen = sum; // If when decoding a whole block, we're still waiting for input then fail: if (result && (state.bytes == 0)) { return result; } return 0; }
2301_81045437/base64
lib/lib_openmp.c
C
bsd
4,457
.PHONY: all clean TARGETS := table_dec_32bit.h table_enc_12bit.h table_generator all: $(TARGETS) clean: $(RM) $(TARGETS) table_dec_32bit.h: table_generator ./$^ > $@ table_enc_12bit.h: table_enc_12bit.py ./$^ > $@ table_generator: table_generator.c $(CC) $(CFLAGS) -o $@ $^
2301_81045437/base64
lib/tables/Makefile
Makefile
bsd
284
#include <stdint.h> #define CHAR62 '+' #define CHAR63 '/' #define CHARPAD '=' #if BASE64_LITTLE_ENDIAN /* SPECIAL DECODE TABLES FOR LITTLE ENDIAN (INTEL) CPUS */ const uint32_t base64_table_dec_32bit_d0[256] = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x000000f8, 0xffffffff, 0xffffffff, 0xffffffff, 0x000000fc, 0x000000d0, 0x000000d4, 0x000000d8, 0x000000dc, 0x000000e0, 0x000000e4, 0x000000e8, 0x000000ec, 0x000000f0, 0x000000f4, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000004, 0x00000008, 0x0000000c, 0x00000010, 0x00000014, 0x00000018, 0x0000001c, 0x00000020, 0x00000024, 0x00000028, 0x0000002c, 0x00000030, 0x00000034, 0x00000038, 0x0000003c, 0x00000040, 0x00000044, 0x00000048, 0x0000004c, 0x00000050, 0x00000054, 0x00000058, 0x0000005c, 0x00000060, 0x00000064, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000068, 0x0000006c, 0x00000070, 0x00000074, 0x00000078, 0x0000007c, 0x00000080, 0x00000084, 0x00000088, 0x0000008c, 0x00000090, 0x00000094, 0x00000098, 0x0000009c, 0x000000a0, 0x000000a4, 0x000000a8, 0x000000ac, 0x000000b0, 0x000000b4, 0x000000b8, 0x000000bc, 0x000000c0, 0x000000c4, 0x000000c8, 0x000000cc, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff }; const uint32_t base64_table_dec_32bit_d1[256] = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x0000e003, 0xffffffff, 0xffffffff, 0xffffffff, 0x0000f003, 0x00004003, 0x00005003, 0x00006003, 0x00007003, 0x00008003, 0x00009003, 0x0000a003, 0x0000b003, 0x0000c003, 0x0000d003, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00001000, 0x00002000, 0x00003000, 0x00004000, 0x00005000, 0x00006000, 0x00007000, 0x00008000, 0x00009000, 0x0000a000, 0x0000b000, 0x0000c000, 0x0000d000, 0x0000e000, 0x0000f000, 0x00000001, 0x00001001, 0x00002001, 0x00003001, 0x00004001, 0x00005001, 0x00006001, 0x00007001, 0x00008001, 0x00009001, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x0000a001, 0x0000b001, 0x0000c001, 0x0000d001, 0x0000e001, 0x0000f001, 0x00000002, 0x00001002, 0x00002002, 0x00003002, 0x00004002, 0x00005002, 0x00006002, 0x00007002, 0x00008002, 0x00009002, 0x0000a002, 0x0000b002, 0x0000c002, 0x0000d002, 0x0000e002, 0x0000f002, 0x00000003, 0x00001003, 0x00002003, 0x00003003, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff }; const uint32_t base64_table_dec_32bit_d2[256] = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00800f00, 0xffffffff, 0xffffffff, 0xffffffff, 0x00c00f00, 0x00000d00, 0x00400d00, 0x00800d00, 0x00c00d00, 0x00000e00, 0x00400e00, 0x00800e00, 0x00c00e00, 0x00000f00, 0x00400f00, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00400000, 0x00800000, 0x00c00000, 0x00000100, 0x00400100, 0x00800100, 0x00c00100, 0x00000200, 0x00400200, 0x00800200, 0x00c00200, 0x00000300, 0x00400300, 0x00800300, 0x00c00300, 0x00000400, 0x00400400, 0x00800400, 0x00c00400, 0x00000500, 0x00400500, 0x00800500, 0x00c00500, 0x00000600, 0x00400600, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00800600, 0x00c00600, 0x00000700, 0x00400700, 0x00800700, 0x00c00700, 0x00000800, 0x00400800, 0x00800800, 0x00c00800, 0x00000900, 0x00400900, 0x00800900, 0x00c00900, 0x00000a00, 0x00400a00, 0x00800a00, 0x00c00a00, 0x00000b00, 0x00400b00, 0x00800b00, 0x00c00b00, 0x00000c00, 0x00400c00, 0x00800c00, 0x00c00c00, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff }; const uint32_t base64_table_dec_32bit_d3[256] = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x003e0000, 0xffffffff, 0xffffffff, 0xffffffff, 0x003f0000, 0x00340000, 0x00350000, 0x00360000, 0x00370000, 0x00380000, 0x00390000, 0x003a0000, 0x003b0000, 0x003c0000, 0x003d0000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00010000, 0x00020000, 0x00030000, 0x00040000, 0x00050000, 0x00060000, 0x00070000, 0x00080000, 0x00090000, 0x000a0000, 0x000b0000, 0x000c0000, 0x000d0000, 0x000e0000, 0x000f0000, 0x00100000, 0x00110000, 0x00120000, 0x00130000, 0x00140000, 0x00150000, 0x00160000, 0x00170000, 0x00180000, 0x00190000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x001a0000, 0x001b0000, 0x001c0000, 0x001d0000, 0x001e0000, 0x001f0000, 0x00200000, 0x00210000, 0x00220000, 0x00230000, 0x00240000, 0x00250000, 0x00260000, 0x00270000, 0x00280000, 0x00290000, 0x002a0000, 0x002b0000, 0x002c0000, 0x002d0000, 0x002e0000, 0x002f0000, 0x00300000, 0x00310000, 0x00320000, 0x00330000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff }; #else /* SPECIAL DECODE TABLES FOR BIG ENDIAN (IBM/MOTOROLA/SUN) CPUS */ const uint32_t base64_table_dec_32bit_d0[256] = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xf8000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xfc000000, 0xd0000000, 0xd4000000, 0xd8000000, 0xdc000000, 0xe0000000, 0xe4000000, 0xe8000000, 0xec000000, 0xf0000000, 0xf4000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x04000000, 0x08000000, 0x0c000000, 0x10000000, 0x14000000, 0x18000000, 0x1c000000, 0x20000000, 0x24000000, 0x28000000, 0x2c000000, 0x30000000, 0x34000000, 0x38000000, 0x3c000000, 0x40000000, 0x44000000, 0x48000000, 0x4c000000, 0x50000000, 0x54000000, 0x58000000, 0x5c000000, 0x60000000, 0x64000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x68000000, 0x6c000000, 0x70000000, 0x74000000, 0x78000000, 0x7c000000, 0x80000000, 0x84000000, 0x88000000, 0x8c000000, 0x90000000, 0x94000000, 0x98000000, 0x9c000000, 0xa0000000, 0xa4000000, 0xa8000000, 0xac000000, 0xb0000000, 0xb4000000, 0xb8000000, 0xbc000000, 0xc0000000, 0xc4000000, 0xc8000000, 0xcc000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff }; const uint32_t base64_table_dec_32bit_d1[256] = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x03e00000, 0xffffffff, 0xffffffff, 0xffffffff, 0x03f00000, 0x03400000, 0x03500000, 0x03600000, 0x03700000, 0x03800000, 0x03900000, 0x03a00000, 0x03b00000, 0x03c00000, 0x03d00000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00100000, 0x00200000, 0x00300000, 0x00400000, 0x00500000, 0x00600000, 0x00700000, 0x00800000, 0x00900000, 0x00a00000, 0x00b00000, 0x00c00000, 0x00d00000, 0x00e00000, 0x00f00000, 0x01000000, 0x01100000, 0x01200000, 0x01300000, 0x01400000, 0x01500000, 0x01600000, 0x01700000, 0x01800000, 0x01900000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x01a00000, 0x01b00000, 0x01c00000, 0x01d00000, 0x01e00000, 0x01f00000, 0x02000000, 0x02100000, 0x02200000, 0x02300000, 0x02400000, 0x02500000, 0x02600000, 0x02700000, 0x02800000, 0x02900000, 0x02a00000, 0x02b00000, 0x02c00000, 0x02d00000, 0x02e00000, 0x02f00000, 0x03000000, 0x03100000, 0x03200000, 0x03300000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff }; const uint32_t base64_table_dec_32bit_d2[256] = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x000f8000, 0xffffffff, 0xffffffff, 0xffffffff, 0x000fc000, 0x000d0000, 0x000d4000, 0x000d8000, 0x000dc000, 0x000e0000, 0x000e4000, 0x000e8000, 0x000ec000, 0x000f0000, 0x000f4000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00004000, 0x00008000, 0x0000c000, 0x00010000, 0x00014000, 0x00018000, 0x0001c000, 0x00020000, 0x00024000, 0x00028000, 0x0002c000, 0x00030000, 0x00034000, 0x00038000, 0x0003c000, 0x00040000, 0x00044000, 0x00048000, 0x0004c000, 0x00050000, 0x00054000, 0x00058000, 0x0005c000, 0x00060000, 0x00064000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00068000, 0x0006c000, 0x00070000, 0x00074000, 0x00078000, 0x0007c000, 0x00080000, 0x00084000, 0x00088000, 0x0008c000, 0x00090000, 0x00094000, 0x00098000, 0x0009c000, 0x000a0000, 0x000a4000, 0x000a8000, 0x000ac000, 0x000b0000, 0x000b4000, 0x000b8000, 0x000bc000, 0x000c0000, 0x000c4000, 0x000c8000, 0x000cc000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff }; const uint32_t base64_table_dec_32bit_d3[256] = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00003e00, 0xffffffff, 0xffffffff, 0xffffffff, 0x00003f00, 0x00003400, 0x00003500, 0x00003600, 0x00003700, 0x00003800, 0x00003900, 0x00003a00, 0x00003b00, 0x00003c00, 0x00003d00, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000100, 0x00000200, 0x00000300, 0x00000400, 0x00000500, 0x00000600, 0x00000700, 0x00000800, 0x00000900, 0x00000a00, 0x00000b00, 0x00000c00, 0x00000d00, 0x00000e00, 0x00000f00, 0x00001000, 0x00001100, 0x00001200, 0x00001300, 0x00001400, 0x00001500, 0x00001600, 0x00001700, 0x00001800, 0x00001900, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00001a00, 0x00001b00, 0x00001c00, 0x00001d00, 0x00001e00, 0x00001f00, 0x00002000, 0x00002100, 0x00002200, 0x00002300, 0x00002400, 0x00002500, 0x00002600, 0x00002700, 0x00002800, 0x00002900, 0x00002a00, 0x00002b00, 0x00002c00, 0x00002d00, 0x00002e00, 0x00002f00, 0x00003000, 0x00003100, 0x00003200, 0x00003300, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff }; #endif
2301_81045437/base64
lib/tables/table_dec_32bit.h
C
bsd
25,258
#include <stdint.h> const uint16_t base64_table_enc_12bit[] = { #if BASE64_LITTLE_ENDIAN 0x4141U, 0x4241U, 0x4341U, 0x4441U, 0x4541U, 0x4641U, 0x4741U, 0x4841U, 0x4941U, 0x4A41U, 0x4B41U, 0x4C41U, 0x4D41U, 0x4E41U, 0x4F41U, 0x5041U, 0x5141U, 0x5241U, 0x5341U, 0x5441U, 0x5541U, 0x5641U, 0x5741U, 0x5841U, 0x5941U, 0x5A41U, 0x6141U, 0x6241U, 0x6341U, 0x6441U, 0x6541U, 0x6641U, 0x6741U, 0x6841U, 0x6941U, 0x6A41U, 0x6B41U, 0x6C41U, 0x6D41U, 0x6E41U, 0x6F41U, 0x7041U, 0x7141U, 0x7241U, 0x7341U, 0x7441U, 0x7541U, 0x7641U, 0x7741U, 0x7841U, 0x7941U, 0x7A41U, 0x3041U, 0x3141U, 0x3241U, 0x3341U, 0x3441U, 0x3541U, 0x3641U, 0x3741U, 0x3841U, 0x3941U, 0x2B41U, 0x2F41U, 0x4142U, 0x4242U, 0x4342U, 0x4442U, 0x4542U, 0x4642U, 0x4742U, 0x4842U, 0x4942U, 0x4A42U, 0x4B42U, 0x4C42U, 0x4D42U, 0x4E42U, 0x4F42U, 0x5042U, 0x5142U, 0x5242U, 0x5342U, 0x5442U, 0x5542U, 0x5642U, 0x5742U, 0x5842U, 0x5942U, 0x5A42U, 0x6142U, 0x6242U, 0x6342U, 0x6442U, 0x6542U, 0x6642U, 0x6742U, 0x6842U, 0x6942U, 0x6A42U, 0x6B42U, 0x6C42U, 0x6D42U, 0x6E42U, 0x6F42U, 0x7042U, 0x7142U, 0x7242U, 0x7342U, 0x7442U, 0x7542U, 0x7642U, 0x7742U, 0x7842U, 0x7942U, 0x7A42U, 0x3042U, 0x3142U, 0x3242U, 0x3342U, 0x3442U, 0x3542U, 0x3642U, 0x3742U, 0x3842U, 0x3942U, 0x2B42U, 0x2F42U, 0x4143U, 0x4243U, 0x4343U, 0x4443U, 0x4543U, 0x4643U, 0x4743U, 0x4843U, 0x4943U, 0x4A43U, 0x4B43U, 0x4C43U, 0x4D43U, 0x4E43U, 0x4F43U, 0x5043U, 0x5143U, 0x5243U, 0x5343U, 0x5443U, 0x5543U, 0x5643U, 0x5743U, 0x5843U, 0x5943U, 0x5A43U, 0x6143U, 0x6243U, 0x6343U, 0x6443U, 0x6543U, 0x6643U, 0x6743U, 0x6843U, 0x6943U, 0x6A43U, 0x6B43U, 0x6C43U, 0x6D43U, 0x6E43U, 0x6F43U, 0x7043U, 0x7143U, 0x7243U, 0x7343U, 0x7443U, 0x7543U, 0x7643U, 0x7743U, 0x7843U, 0x7943U, 0x7A43U, 0x3043U, 0x3143U, 0x3243U, 0x3343U, 0x3443U, 0x3543U, 0x3643U, 0x3743U, 0x3843U, 0x3943U, 0x2B43U, 0x2F43U, 0x4144U, 0x4244U, 0x4344U, 0x4444U, 0x4544U, 0x4644U, 0x4744U, 0x4844U, 0x4944U, 0x4A44U, 0x4B44U, 0x4C44U, 0x4D44U, 0x4E44U, 0x4F44U, 0x5044U, 0x5144U, 0x5244U, 0x5344U, 0x5444U, 0x5544U, 0x5644U, 0x5744U, 0x5844U, 0x5944U, 0x5A44U, 0x6144U, 0x6244U, 0x6344U, 0x6444U, 0x6544U, 0x6644U, 0x6744U, 0x6844U, 0x6944U, 0x6A44U, 0x6B44U, 0x6C44U, 0x6D44U, 0x6E44U, 0x6F44U, 0x7044U, 0x7144U, 0x7244U, 0x7344U, 0x7444U, 0x7544U, 0x7644U, 0x7744U, 0x7844U, 0x7944U, 0x7A44U, 0x3044U, 0x3144U, 0x3244U, 0x3344U, 0x3444U, 0x3544U, 0x3644U, 0x3744U, 0x3844U, 0x3944U, 0x2B44U, 0x2F44U, 0x4145U, 0x4245U, 0x4345U, 0x4445U, 0x4545U, 0x4645U, 0x4745U, 0x4845U, 0x4945U, 0x4A45U, 0x4B45U, 0x4C45U, 0x4D45U, 0x4E45U, 0x4F45U, 0x5045U, 0x5145U, 0x5245U, 0x5345U, 0x5445U, 0x5545U, 0x5645U, 0x5745U, 0x5845U, 0x5945U, 0x5A45U, 0x6145U, 0x6245U, 0x6345U, 0x6445U, 0x6545U, 0x6645U, 0x6745U, 0x6845U, 0x6945U, 0x6A45U, 0x6B45U, 0x6C45U, 0x6D45U, 0x6E45U, 0x6F45U, 0x7045U, 0x7145U, 0x7245U, 0x7345U, 0x7445U, 0x7545U, 0x7645U, 0x7745U, 0x7845U, 0x7945U, 0x7A45U, 0x3045U, 0x3145U, 0x3245U, 0x3345U, 0x3445U, 0x3545U, 0x3645U, 0x3745U, 0x3845U, 0x3945U, 0x2B45U, 0x2F45U, 0x4146U, 0x4246U, 0x4346U, 0x4446U, 0x4546U, 0x4646U, 0x4746U, 0x4846U, 0x4946U, 0x4A46U, 0x4B46U, 0x4C46U, 0x4D46U, 0x4E46U, 0x4F46U, 0x5046U, 0x5146U, 0x5246U, 0x5346U, 0x5446U, 0x5546U, 0x5646U, 0x5746U, 0x5846U, 0x5946U, 0x5A46U, 0x6146U, 0x6246U, 0x6346U, 0x6446U, 0x6546U, 0x6646U, 0x6746U, 0x6846U, 0x6946U, 0x6A46U, 0x6B46U, 0x6C46U, 0x6D46U, 0x6E46U, 0x6F46U, 0x7046U, 0x7146U, 0x7246U, 0x7346U, 0x7446U, 0x7546U, 0x7646U, 0x7746U, 0x7846U, 0x7946U, 0x7A46U, 0x3046U, 0x3146U, 0x3246U, 0x3346U, 0x3446U, 0x3546U, 0x3646U, 0x3746U, 0x3846U, 0x3946U, 0x2B46U, 0x2F46U, 0x4147U, 0x4247U, 0x4347U, 0x4447U, 0x4547U, 0x4647U, 0x4747U, 0x4847U, 0x4947U, 0x4A47U, 0x4B47U, 0x4C47U, 0x4D47U, 0x4E47U, 0x4F47U, 0x5047U, 0x5147U, 0x5247U, 0x5347U, 0x5447U, 0x5547U, 0x5647U, 0x5747U, 0x5847U, 0x5947U, 0x5A47U, 0x6147U, 0x6247U, 0x6347U, 0x6447U, 0x6547U, 0x6647U, 0x6747U, 0x6847U, 0x6947U, 0x6A47U, 0x6B47U, 0x6C47U, 0x6D47U, 0x6E47U, 0x6F47U, 0x7047U, 0x7147U, 0x7247U, 0x7347U, 0x7447U, 0x7547U, 0x7647U, 0x7747U, 0x7847U, 0x7947U, 0x7A47U, 0x3047U, 0x3147U, 0x3247U, 0x3347U, 0x3447U, 0x3547U, 0x3647U, 0x3747U, 0x3847U, 0x3947U, 0x2B47U, 0x2F47U, 0x4148U, 0x4248U, 0x4348U, 0x4448U, 0x4548U, 0x4648U, 0x4748U, 0x4848U, 0x4948U, 0x4A48U, 0x4B48U, 0x4C48U, 0x4D48U, 0x4E48U, 0x4F48U, 0x5048U, 0x5148U, 0x5248U, 0x5348U, 0x5448U, 0x5548U, 0x5648U, 0x5748U, 0x5848U, 0x5948U, 0x5A48U, 0x6148U, 0x6248U, 0x6348U, 0x6448U, 0x6548U, 0x6648U, 0x6748U, 0x6848U, 0x6948U, 0x6A48U, 0x6B48U, 0x6C48U, 0x6D48U, 0x6E48U, 0x6F48U, 0x7048U, 0x7148U, 0x7248U, 0x7348U, 0x7448U, 0x7548U, 0x7648U, 0x7748U, 0x7848U, 0x7948U, 0x7A48U, 0x3048U, 0x3148U, 0x3248U, 0x3348U, 0x3448U, 0x3548U, 0x3648U, 0x3748U, 0x3848U, 0x3948U, 0x2B48U, 0x2F48U, 0x4149U, 0x4249U, 0x4349U, 0x4449U, 0x4549U, 0x4649U, 0x4749U, 0x4849U, 0x4949U, 0x4A49U, 0x4B49U, 0x4C49U, 0x4D49U, 0x4E49U, 0x4F49U, 0x5049U, 0x5149U, 0x5249U, 0x5349U, 0x5449U, 0x5549U, 0x5649U, 0x5749U, 0x5849U, 0x5949U, 0x5A49U, 0x6149U, 0x6249U, 0x6349U, 0x6449U, 0x6549U, 0x6649U, 0x6749U, 0x6849U, 0x6949U, 0x6A49U, 0x6B49U, 0x6C49U, 0x6D49U, 0x6E49U, 0x6F49U, 0x7049U, 0x7149U, 0x7249U, 0x7349U, 0x7449U, 0x7549U, 0x7649U, 0x7749U, 0x7849U, 0x7949U, 0x7A49U, 0x3049U, 0x3149U, 0x3249U, 0x3349U, 0x3449U, 0x3549U, 0x3649U, 0x3749U, 0x3849U, 0x3949U, 0x2B49U, 0x2F49U, 0x414AU, 0x424AU, 0x434AU, 0x444AU, 0x454AU, 0x464AU, 0x474AU, 0x484AU, 0x494AU, 0x4A4AU, 0x4B4AU, 0x4C4AU, 0x4D4AU, 0x4E4AU, 0x4F4AU, 0x504AU, 0x514AU, 0x524AU, 0x534AU, 0x544AU, 0x554AU, 0x564AU, 0x574AU, 0x584AU, 0x594AU, 0x5A4AU, 0x614AU, 0x624AU, 0x634AU, 0x644AU, 0x654AU, 0x664AU, 0x674AU, 0x684AU, 0x694AU, 0x6A4AU, 0x6B4AU, 0x6C4AU, 0x6D4AU, 0x6E4AU, 0x6F4AU, 0x704AU, 0x714AU, 0x724AU, 0x734AU, 0x744AU, 0x754AU, 0x764AU, 0x774AU, 0x784AU, 0x794AU, 0x7A4AU, 0x304AU, 0x314AU, 0x324AU, 0x334AU, 0x344AU, 0x354AU, 0x364AU, 0x374AU, 0x384AU, 0x394AU, 0x2B4AU, 0x2F4AU, 0x414BU, 0x424BU, 0x434BU, 0x444BU, 0x454BU, 0x464BU, 0x474BU, 0x484BU, 0x494BU, 0x4A4BU, 0x4B4BU, 0x4C4BU, 0x4D4BU, 0x4E4BU, 0x4F4BU, 0x504BU, 0x514BU, 0x524BU, 0x534BU, 0x544BU, 0x554BU, 0x564BU, 0x574BU, 0x584BU, 0x594BU, 0x5A4BU, 0x614BU, 0x624BU, 0x634BU, 0x644BU, 0x654BU, 0x664BU, 0x674BU, 0x684BU, 0x694BU, 0x6A4BU, 0x6B4BU, 0x6C4BU, 0x6D4BU, 0x6E4BU, 0x6F4BU, 0x704BU, 0x714BU, 0x724BU, 0x734BU, 0x744BU, 0x754BU, 0x764BU, 0x774BU, 0x784BU, 0x794BU, 0x7A4BU, 0x304BU, 0x314BU, 0x324BU, 0x334BU, 0x344BU, 0x354BU, 0x364BU, 0x374BU, 0x384BU, 0x394BU, 0x2B4BU, 0x2F4BU, 0x414CU, 0x424CU, 0x434CU, 0x444CU, 0x454CU, 0x464CU, 0x474CU, 0x484CU, 0x494CU, 0x4A4CU, 0x4B4CU, 0x4C4CU, 0x4D4CU, 0x4E4CU, 0x4F4CU, 0x504CU, 0x514CU, 0x524CU, 0x534CU, 0x544CU, 0x554CU, 0x564CU, 0x574CU, 0x584CU, 0x594CU, 0x5A4CU, 0x614CU, 0x624CU, 0x634CU, 0x644CU, 0x654CU, 0x664CU, 0x674CU, 0x684CU, 0x694CU, 0x6A4CU, 0x6B4CU, 0x6C4CU, 0x6D4CU, 0x6E4CU, 0x6F4CU, 0x704CU, 0x714CU, 0x724CU, 0x734CU, 0x744CU, 0x754CU, 0x764CU, 0x774CU, 0x784CU, 0x794CU, 0x7A4CU, 0x304CU, 0x314CU, 0x324CU, 0x334CU, 0x344CU, 0x354CU, 0x364CU, 0x374CU, 0x384CU, 0x394CU, 0x2B4CU, 0x2F4CU, 0x414DU, 0x424DU, 0x434DU, 0x444DU, 0x454DU, 0x464DU, 0x474DU, 0x484DU, 0x494DU, 0x4A4DU, 0x4B4DU, 0x4C4DU, 0x4D4DU, 0x4E4DU, 0x4F4DU, 0x504DU, 0x514DU, 0x524DU, 0x534DU, 0x544DU, 0x554DU, 0x564DU, 0x574DU, 0x584DU, 0x594DU, 0x5A4DU, 0x614DU, 0x624DU, 0x634DU, 0x644DU, 0x654DU, 0x664DU, 0x674DU, 0x684DU, 0x694DU, 0x6A4DU, 0x6B4DU, 0x6C4DU, 0x6D4DU, 0x6E4DU, 0x6F4DU, 0x704DU, 0x714DU, 0x724DU, 0x734DU, 0x744DU, 0x754DU, 0x764DU, 0x774DU, 0x784DU, 0x794DU, 0x7A4DU, 0x304DU, 0x314DU, 0x324DU, 0x334DU, 0x344DU, 0x354DU, 0x364DU, 0x374DU, 0x384DU, 0x394DU, 0x2B4DU, 0x2F4DU, 0x414EU, 0x424EU, 0x434EU, 0x444EU, 0x454EU, 0x464EU, 0x474EU, 0x484EU, 0x494EU, 0x4A4EU, 0x4B4EU, 0x4C4EU, 0x4D4EU, 0x4E4EU, 0x4F4EU, 0x504EU, 0x514EU, 0x524EU, 0x534EU, 0x544EU, 0x554EU, 0x564EU, 0x574EU, 0x584EU, 0x594EU, 0x5A4EU, 0x614EU, 0x624EU, 0x634EU, 0x644EU, 0x654EU, 0x664EU, 0x674EU, 0x684EU, 0x694EU, 0x6A4EU, 0x6B4EU, 0x6C4EU, 0x6D4EU, 0x6E4EU, 0x6F4EU, 0x704EU, 0x714EU, 0x724EU, 0x734EU, 0x744EU, 0x754EU, 0x764EU, 0x774EU, 0x784EU, 0x794EU, 0x7A4EU, 0x304EU, 0x314EU, 0x324EU, 0x334EU, 0x344EU, 0x354EU, 0x364EU, 0x374EU, 0x384EU, 0x394EU, 0x2B4EU, 0x2F4EU, 0x414FU, 0x424FU, 0x434FU, 0x444FU, 0x454FU, 0x464FU, 0x474FU, 0x484FU, 0x494FU, 0x4A4FU, 0x4B4FU, 0x4C4FU, 0x4D4FU, 0x4E4FU, 0x4F4FU, 0x504FU, 0x514FU, 0x524FU, 0x534FU, 0x544FU, 0x554FU, 0x564FU, 0x574FU, 0x584FU, 0x594FU, 0x5A4FU, 0x614FU, 0x624FU, 0x634FU, 0x644FU, 0x654FU, 0x664FU, 0x674FU, 0x684FU, 0x694FU, 0x6A4FU, 0x6B4FU, 0x6C4FU, 0x6D4FU, 0x6E4FU, 0x6F4FU, 0x704FU, 0x714FU, 0x724FU, 0x734FU, 0x744FU, 0x754FU, 0x764FU, 0x774FU, 0x784FU, 0x794FU, 0x7A4FU, 0x304FU, 0x314FU, 0x324FU, 0x334FU, 0x344FU, 0x354FU, 0x364FU, 0x374FU, 0x384FU, 0x394FU, 0x2B4FU, 0x2F4FU, 0x4150U, 0x4250U, 0x4350U, 0x4450U, 0x4550U, 0x4650U, 0x4750U, 0x4850U, 0x4950U, 0x4A50U, 0x4B50U, 0x4C50U, 0x4D50U, 0x4E50U, 0x4F50U, 0x5050U, 0x5150U, 0x5250U, 0x5350U, 0x5450U, 0x5550U, 0x5650U, 0x5750U, 0x5850U, 0x5950U, 0x5A50U, 0x6150U, 0x6250U, 0x6350U, 0x6450U, 0x6550U, 0x6650U, 0x6750U, 0x6850U, 0x6950U, 0x6A50U, 0x6B50U, 0x6C50U, 0x6D50U, 0x6E50U, 0x6F50U, 0x7050U, 0x7150U, 0x7250U, 0x7350U, 0x7450U, 0x7550U, 0x7650U, 0x7750U, 0x7850U, 0x7950U, 0x7A50U, 0x3050U, 0x3150U, 0x3250U, 0x3350U, 0x3450U, 0x3550U, 0x3650U, 0x3750U, 0x3850U, 0x3950U, 0x2B50U, 0x2F50U, 0x4151U, 0x4251U, 0x4351U, 0x4451U, 0x4551U, 0x4651U, 0x4751U, 0x4851U, 0x4951U, 0x4A51U, 0x4B51U, 0x4C51U, 0x4D51U, 0x4E51U, 0x4F51U, 0x5051U, 0x5151U, 0x5251U, 0x5351U, 0x5451U, 0x5551U, 0x5651U, 0x5751U, 0x5851U, 0x5951U, 0x5A51U, 0x6151U, 0x6251U, 0x6351U, 0x6451U, 0x6551U, 0x6651U, 0x6751U, 0x6851U, 0x6951U, 0x6A51U, 0x6B51U, 0x6C51U, 0x6D51U, 0x6E51U, 0x6F51U, 0x7051U, 0x7151U, 0x7251U, 0x7351U, 0x7451U, 0x7551U, 0x7651U, 0x7751U, 0x7851U, 0x7951U, 0x7A51U, 0x3051U, 0x3151U, 0x3251U, 0x3351U, 0x3451U, 0x3551U, 0x3651U, 0x3751U, 0x3851U, 0x3951U, 0x2B51U, 0x2F51U, 0x4152U, 0x4252U, 0x4352U, 0x4452U, 0x4552U, 0x4652U, 0x4752U, 0x4852U, 0x4952U, 0x4A52U, 0x4B52U, 0x4C52U, 0x4D52U, 0x4E52U, 0x4F52U, 0x5052U, 0x5152U, 0x5252U, 0x5352U, 0x5452U, 0x5552U, 0x5652U, 0x5752U, 0x5852U, 0x5952U, 0x5A52U, 0x6152U, 0x6252U, 0x6352U, 0x6452U, 0x6552U, 0x6652U, 0x6752U, 0x6852U, 0x6952U, 0x6A52U, 0x6B52U, 0x6C52U, 0x6D52U, 0x6E52U, 0x6F52U, 0x7052U, 0x7152U, 0x7252U, 0x7352U, 0x7452U, 0x7552U, 0x7652U, 0x7752U, 0x7852U, 0x7952U, 0x7A52U, 0x3052U, 0x3152U, 0x3252U, 0x3352U, 0x3452U, 0x3552U, 0x3652U, 0x3752U, 0x3852U, 0x3952U, 0x2B52U, 0x2F52U, 0x4153U, 0x4253U, 0x4353U, 0x4453U, 0x4553U, 0x4653U, 0x4753U, 0x4853U, 0x4953U, 0x4A53U, 0x4B53U, 0x4C53U, 0x4D53U, 0x4E53U, 0x4F53U, 0x5053U, 0x5153U, 0x5253U, 0x5353U, 0x5453U, 0x5553U, 0x5653U, 0x5753U, 0x5853U, 0x5953U, 0x5A53U, 0x6153U, 0x6253U, 0x6353U, 0x6453U, 0x6553U, 0x6653U, 0x6753U, 0x6853U, 0x6953U, 0x6A53U, 0x6B53U, 0x6C53U, 0x6D53U, 0x6E53U, 0x6F53U, 0x7053U, 0x7153U, 0x7253U, 0x7353U, 0x7453U, 0x7553U, 0x7653U, 0x7753U, 0x7853U, 0x7953U, 0x7A53U, 0x3053U, 0x3153U, 0x3253U, 0x3353U, 0x3453U, 0x3553U, 0x3653U, 0x3753U, 0x3853U, 0x3953U, 0x2B53U, 0x2F53U, 0x4154U, 0x4254U, 0x4354U, 0x4454U, 0x4554U, 0x4654U, 0x4754U, 0x4854U, 0x4954U, 0x4A54U, 0x4B54U, 0x4C54U, 0x4D54U, 0x4E54U, 0x4F54U, 0x5054U, 0x5154U, 0x5254U, 0x5354U, 0x5454U, 0x5554U, 0x5654U, 0x5754U, 0x5854U, 0x5954U, 0x5A54U, 0x6154U, 0x6254U, 0x6354U, 0x6454U, 0x6554U, 0x6654U, 0x6754U, 0x6854U, 0x6954U, 0x6A54U, 0x6B54U, 0x6C54U, 0x6D54U, 0x6E54U, 0x6F54U, 0x7054U, 0x7154U, 0x7254U, 0x7354U, 0x7454U, 0x7554U, 0x7654U, 0x7754U, 0x7854U, 0x7954U, 0x7A54U, 0x3054U, 0x3154U, 0x3254U, 0x3354U, 0x3454U, 0x3554U, 0x3654U, 0x3754U, 0x3854U, 0x3954U, 0x2B54U, 0x2F54U, 0x4155U, 0x4255U, 0x4355U, 0x4455U, 0x4555U, 0x4655U, 0x4755U, 0x4855U, 0x4955U, 0x4A55U, 0x4B55U, 0x4C55U, 0x4D55U, 0x4E55U, 0x4F55U, 0x5055U, 0x5155U, 0x5255U, 0x5355U, 0x5455U, 0x5555U, 0x5655U, 0x5755U, 0x5855U, 0x5955U, 0x5A55U, 0x6155U, 0x6255U, 0x6355U, 0x6455U, 0x6555U, 0x6655U, 0x6755U, 0x6855U, 0x6955U, 0x6A55U, 0x6B55U, 0x6C55U, 0x6D55U, 0x6E55U, 0x6F55U, 0x7055U, 0x7155U, 0x7255U, 0x7355U, 0x7455U, 0x7555U, 0x7655U, 0x7755U, 0x7855U, 0x7955U, 0x7A55U, 0x3055U, 0x3155U, 0x3255U, 0x3355U, 0x3455U, 0x3555U, 0x3655U, 0x3755U, 0x3855U, 0x3955U, 0x2B55U, 0x2F55U, 0x4156U, 0x4256U, 0x4356U, 0x4456U, 0x4556U, 0x4656U, 0x4756U, 0x4856U, 0x4956U, 0x4A56U, 0x4B56U, 0x4C56U, 0x4D56U, 0x4E56U, 0x4F56U, 0x5056U, 0x5156U, 0x5256U, 0x5356U, 0x5456U, 0x5556U, 0x5656U, 0x5756U, 0x5856U, 0x5956U, 0x5A56U, 0x6156U, 0x6256U, 0x6356U, 0x6456U, 0x6556U, 0x6656U, 0x6756U, 0x6856U, 0x6956U, 0x6A56U, 0x6B56U, 0x6C56U, 0x6D56U, 0x6E56U, 0x6F56U, 0x7056U, 0x7156U, 0x7256U, 0x7356U, 0x7456U, 0x7556U, 0x7656U, 0x7756U, 0x7856U, 0x7956U, 0x7A56U, 0x3056U, 0x3156U, 0x3256U, 0x3356U, 0x3456U, 0x3556U, 0x3656U, 0x3756U, 0x3856U, 0x3956U, 0x2B56U, 0x2F56U, 0x4157U, 0x4257U, 0x4357U, 0x4457U, 0x4557U, 0x4657U, 0x4757U, 0x4857U, 0x4957U, 0x4A57U, 0x4B57U, 0x4C57U, 0x4D57U, 0x4E57U, 0x4F57U, 0x5057U, 0x5157U, 0x5257U, 0x5357U, 0x5457U, 0x5557U, 0x5657U, 0x5757U, 0x5857U, 0x5957U, 0x5A57U, 0x6157U, 0x6257U, 0x6357U, 0x6457U, 0x6557U, 0x6657U, 0x6757U, 0x6857U, 0x6957U, 0x6A57U, 0x6B57U, 0x6C57U, 0x6D57U, 0x6E57U, 0x6F57U, 0x7057U, 0x7157U, 0x7257U, 0x7357U, 0x7457U, 0x7557U, 0x7657U, 0x7757U, 0x7857U, 0x7957U, 0x7A57U, 0x3057U, 0x3157U, 0x3257U, 0x3357U, 0x3457U, 0x3557U, 0x3657U, 0x3757U, 0x3857U, 0x3957U, 0x2B57U, 0x2F57U, 0x4158U, 0x4258U, 0x4358U, 0x4458U, 0x4558U, 0x4658U, 0x4758U, 0x4858U, 0x4958U, 0x4A58U, 0x4B58U, 0x4C58U, 0x4D58U, 0x4E58U, 0x4F58U, 0x5058U, 0x5158U, 0x5258U, 0x5358U, 0x5458U, 0x5558U, 0x5658U, 0x5758U, 0x5858U, 0x5958U, 0x5A58U, 0x6158U, 0x6258U, 0x6358U, 0x6458U, 0x6558U, 0x6658U, 0x6758U, 0x6858U, 0x6958U, 0x6A58U, 0x6B58U, 0x6C58U, 0x6D58U, 0x6E58U, 0x6F58U, 0x7058U, 0x7158U, 0x7258U, 0x7358U, 0x7458U, 0x7558U, 0x7658U, 0x7758U, 0x7858U, 0x7958U, 0x7A58U, 0x3058U, 0x3158U, 0x3258U, 0x3358U, 0x3458U, 0x3558U, 0x3658U, 0x3758U, 0x3858U, 0x3958U, 0x2B58U, 0x2F58U, 0x4159U, 0x4259U, 0x4359U, 0x4459U, 0x4559U, 0x4659U, 0x4759U, 0x4859U, 0x4959U, 0x4A59U, 0x4B59U, 0x4C59U, 0x4D59U, 0x4E59U, 0x4F59U, 0x5059U, 0x5159U, 0x5259U, 0x5359U, 0x5459U, 0x5559U, 0x5659U, 0x5759U, 0x5859U, 0x5959U, 0x5A59U, 0x6159U, 0x6259U, 0x6359U, 0x6459U, 0x6559U, 0x6659U, 0x6759U, 0x6859U, 0x6959U, 0x6A59U, 0x6B59U, 0x6C59U, 0x6D59U, 0x6E59U, 0x6F59U, 0x7059U, 0x7159U, 0x7259U, 0x7359U, 0x7459U, 0x7559U, 0x7659U, 0x7759U, 0x7859U, 0x7959U, 0x7A59U, 0x3059U, 0x3159U, 0x3259U, 0x3359U, 0x3459U, 0x3559U, 0x3659U, 0x3759U, 0x3859U, 0x3959U, 0x2B59U, 0x2F59U, 0x415AU, 0x425AU, 0x435AU, 0x445AU, 0x455AU, 0x465AU, 0x475AU, 0x485AU, 0x495AU, 0x4A5AU, 0x4B5AU, 0x4C5AU, 0x4D5AU, 0x4E5AU, 0x4F5AU, 0x505AU, 0x515AU, 0x525AU, 0x535AU, 0x545AU, 0x555AU, 0x565AU, 0x575AU, 0x585AU, 0x595AU, 0x5A5AU, 0x615AU, 0x625AU, 0x635AU, 0x645AU, 0x655AU, 0x665AU, 0x675AU, 0x685AU, 0x695AU, 0x6A5AU, 0x6B5AU, 0x6C5AU, 0x6D5AU, 0x6E5AU, 0x6F5AU, 0x705AU, 0x715AU, 0x725AU, 0x735AU, 0x745AU, 0x755AU, 0x765AU, 0x775AU, 0x785AU, 0x795AU, 0x7A5AU, 0x305AU, 0x315AU, 0x325AU, 0x335AU, 0x345AU, 0x355AU, 0x365AU, 0x375AU, 0x385AU, 0x395AU, 0x2B5AU, 0x2F5AU, 0x4161U, 0x4261U, 0x4361U, 0x4461U, 0x4561U, 0x4661U, 0x4761U, 0x4861U, 0x4961U, 0x4A61U, 0x4B61U, 0x4C61U, 0x4D61U, 0x4E61U, 0x4F61U, 0x5061U, 0x5161U, 0x5261U, 0x5361U, 0x5461U, 0x5561U, 0x5661U, 0x5761U, 0x5861U, 0x5961U, 0x5A61U, 0x6161U, 0x6261U, 0x6361U, 0x6461U, 0x6561U, 0x6661U, 0x6761U, 0x6861U, 0x6961U, 0x6A61U, 0x6B61U, 0x6C61U, 0x6D61U, 0x6E61U, 0x6F61U, 0x7061U, 0x7161U, 0x7261U, 0x7361U, 0x7461U, 0x7561U, 0x7661U, 0x7761U, 0x7861U, 0x7961U, 0x7A61U, 0x3061U, 0x3161U, 0x3261U, 0x3361U, 0x3461U, 0x3561U, 0x3661U, 0x3761U, 0x3861U, 0x3961U, 0x2B61U, 0x2F61U, 0x4162U, 0x4262U, 0x4362U, 0x4462U, 0x4562U, 0x4662U, 0x4762U, 0x4862U, 0x4962U, 0x4A62U, 0x4B62U, 0x4C62U, 0x4D62U, 0x4E62U, 0x4F62U, 0x5062U, 0x5162U, 0x5262U, 0x5362U, 0x5462U, 0x5562U, 0x5662U, 0x5762U, 0x5862U, 0x5962U, 0x5A62U, 0x6162U, 0x6262U, 0x6362U, 0x6462U, 0x6562U, 0x6662U, 0x6762U, 0x6862U, 0x6962U, 0x6A62U, 0x6B62U, 0x6C62U, 0x6D62U, 0x6E62U, 0x6F62U, 0x7062U, 0x7162U, 0x7262U, 0x7362U, 0x7462U, 0x7562U, 0x7662U, 0x7762U, 0x7862U, 0x7962U, 0x7A62U, 0x3062U, 0x3162U, 0x3262U, 0x3362U, 0x3462U, 0x3562U, 0x3662U, 0x3762U, 0x3862U, 0x3962U, 0x2B62U, 0x2F62U, 0x4163U, 0x4263U, 0x4363U, 0x4463U, 0x4563U, 0x4663U, 0x4763U, 0x4863U, 0x4963U, 0x4A63U, 0x4B63U, 0x4C63U, 0x4D63U, 0x4E63U, 0x4F63U, 0x5063U, 0x5163U, 0x5263U, 0x5363U, 0x5463U, 0x5563U, 0x5663U, 0x5763U, 0x5863U, 0x5963U, 0x5A63U, 0x6163U, 0x6263U, 0x6363U, 0x6463U, 0x6563U, 0x6663U, 0x6763U, 0x6863U, 0x6963U, 0x6A63U, 0x6B63U, 0x6C63U, 0x6D63U, 0x6E63U, 0x6F63U, 0x7063U, 0x7163U, 0x7263U, 0x7363U, 0x7463U, 0x7563U, 0x7663U, 0x7763U, 0x7863U, 0x7963U, 0x7A63U, 0x3063U, 0x3163U, 0x3263U, 0x3363U, 0x3463U, 0x3563U, 0x3663U, 0x3763U, 0x3863U, 0x3963U, 0x2B63U, 0x2F63U, 0x4164U, 0x4264U, 0x4364U, 0x4464U, 0x4564U, 0x4664U, 0x4764U, 0x4864U, 0x4964U, 0x4A64U, 0x4B64U, 0x4C64U, 0x4D64U, 0x4E64U, 0x4F64U, 0x5064U, 0x5164U, 0x5264U, 0x5364U, 0x5464U, 0x5564U, 0x5664U, 0x5764U, 0x5864U, 0x5964U, 0x5A64U, 0x6164U, 0x6264U, 0x6364U, 0x6464U, 0x6564U, 0x6664U, 0x6764U, 0x6864U, 0x6964U, 0x6A64U, 0x6B64U, 0x6C64U, 0x6D64U, 0x6E64U, 0x6F64U, 0x7064U, 0x7164U, 0x7264U, 0x7364U, 0x7464U, 0x7564U, 0x7664U, 0x7764U, 0x7864U, 0x7964U, 0x7A64U, 0x3064U, 0x3164U, 0x3264U, 0x3364U, 0x3464U, 0x3564U, 0x3664U, 0x3764U, 0x3864U, 0x3964U, 0x2B64U, 0x2F64U, 0x4165U, 0x4265U, 0x4365U, 0x4465U, 0x4565U, 0x4665U, 0x4765U, 0x4865U, 0x4965U, 0x4A65U, 0x4B65U, 0x4C65U, 0x4D65U, 0x4E65U, 0x4F65U, 0x5065U, 0x5165U, 0x5265U, 0x5365U, 0x5465U, 0x5565U, 0x5665U, 0x5765U, 0x5865U, 0x5965U, 0x5A65U, 0x6165U, 0x6265U, 0x6365U, 0x6465U, 0x6565U, 0x6665U, 0x6765U, 0x6865U, 0x6965U, 0x6A65U, 0x6B65U, 0x6C65U, 0x6D65U, 0x6E65U, 0x6F65U, 0x7065U, 0x7165U, 0x7265U, 0x7365U, 0x7465U, 0x7565U, 0x7665U, 0x7765U, 0x7865U, 0x7965U, 0x7A65U, 0x3065U, 0x3165U, 0x3265U, 0x3365U, 0x3465U, 0x3565U, 0x3665U, 0x3765U, 0x3865U, 0x3965U, 0x2B65U, 0x2F65U, 0x4166U, 0x4266U, 0x4366U, 0x4466U, 0x4566U, 0x4666U, 0x4766U, 0x4866U, 0x4966U, 0x4A66U, 0x4B66U, 0x4C66U, 0x4D66U, 0x4E66U, 0x4F66U, 0x5066U, 0x5166U, 0x5266U, 0x5366U, 0x5466U, 0x5566U, 0x5666U, 0x5766U, 0x5866U, 0x5966U, 0x5A66U, 0x6166U, 0x6266U, 0x6366U, 0x6466U, 0x6566U, 0x6666U, 0x6766U, 0x6866U, 0x6966U, 0x6A66U, 0x6B66U, 0x6C66U, 0x6D66U, 0x6E66U, 0x6F66U, 0x7066U, 0x7166U, 0x7266U, 0x7366U, 0x7466U, 0x7566U, 0x7666U, 0x7766U, 0x7866U, 0x7966U, 0x7A66U, 0x3066U, 0x3166U, 0x3266U, 0x3366U, 0x3466U, 0x3566U, 0x3666U, 0x3766U, 0x3866U, 0x3966U, 0x2B66U, 0x2F66U, 0x4167U, 0x4267U, 0x4367U, 0x4467U, 0x4567U, 0x4667U, 0x4767U, 0x4867U, 0x4967U, 0x4A67U, 0x4B67U, 0x4C67U, 0x4D67U, 0x4E67U, 0x4F67U, 0x5067U, 0x5167U, 0x5267U, 0x5367U, 0x5467U, 0x5567U, 0x5667U, 0x5767U, 0x5867U, 0x5967U, 0x5A67U, 0x6167U, 0x6267U, 0x6367U, 0x6467U, 0x6567U, 0x6667U, 0x6767U, 0x6867U, 0x6967U, 0x6A67U, 0x6B67U, 0x6C67U, 0x6D67U, 0x6E67U, 0x6F67U, 0x7067U, 0x7167U, 0x7267U, 0x7367U, 0x7467U, 0x7567U, 0x7667U, 0x7767U, 0x7867U, 0x7967U, 0x7A67U, 0x3067U, 0x3167U, 0x3267U, 0x3367U, 0x3467U, 0x3567U, 0x3667U, 0x3767U, 0x3867U, 0x3967U, 0x2B67U, 0x2F67U, 0x4168U, 0x4268U, 0x4368U, 0x4468U, 0x4568U, 0x4668U, 0x4768U, 0x4868U, 0x4968U, 0x4A68U, 0x4B68U, 0x4C68U, 0x4D68U, 0x4E68U, 0x4F68U, 0x5068U, 0x5168U, 0x5268U, 0x5368U, 0x5468U, 0x5568U, 0x5668U, 0x5768U, 0x5868U, 0x5968U, 0x5A68U, 0x6168U, 0x6268U, 0x6368U, 0x6468U, 0x6568U, 0x6668U, 0x6768U, 0x6868U, 0x6968U, 0x6A68U, 0x6B68U, 0x6C68U, 0x6D68U, 0x6E68U, 0x6F68U, 0x7068U, 0x7168U, 0x7268U, 0x7368U, 0x7468U, 0x7568U, 0x7668U, 0x7768U, 0x7868U, 0x7968U, 0x7A68U, 0x3068U, 0x3168U, 0x3268U, 0x3368U, 0x3468U, 0x3568U, 0x3668U, 0x3768U, 0x3868U, 0x3968U, 0x2B68U, 0x2F68U, 0x4169U, 0x4269U, 0x4369U, 0x4469U, 0x4569U, 0x4669U, 0x4769U, 0x4869U, 0x4969U, 0x4A69U, 0x4B69U, 0x4C69U, 0x4D69U, 0x4E69U, 0x4F69U, 0x5069U, 0x5169U, 0x5269U, 0x5369U, 0x5469U, 0x5569U, 0x5669U, 0x5769U, 0x5869U, 0x5969U, 0x5A69U, 0x6169U, 0x6269U, 0x6369U, 0x6469U, 0x6569U, 0x6669U, 0x6769U, 0x6869U, 0x6969U, 0x6A69U, 0x6B69U, 0x6C69U, 0x6D69U, 0x6E69U, 0x6F69U, 0x7069U, 0x7169U, 0x7269U, 0x7369U, 0x7469U, 0x7569U, 0x7669U, 0x7769U, 0x7869U, 0x7969U, 0x7A69U, 0x3069U, 0x3169U, 0x3269U, 0x3369U, 0x3469U, 0x3569U, 0x3669U, 0x3769U, 0x3869U, 0x3969U, 0x2B69U, 0x2F69U, 0x416AU, 0x426AU, 0x436AU, 0x446AU, 0x456AU, 0x466AU, 0x476AU, 0x486AU, 0x496AU, 0x4A6AU, 0x4B6AU, 0x4C6AU, 0x4D6AU, 0x4E6AU, 0x4F6AU, 0x506AU, 0x516AU, 0x526AU, 0x536AU, 0x546AU, 0x556AU, 0x566AU, 0x576AU, 0x586AU, 0x596AU, 0x5A6AU, 0x616AU, 0x626AU, 0x636AU, 0x646AU, 0x656AU, 0x666AU, 0x676AU, 0x686AU, 0x696AU, 0x6A6AU, 0x6B6AU, 0x6C6AU, 0x6D6AU, 0x6E6AU, 0x6F6AU, 0x706AU, 0x716AU, 0x726AU, 0x736AU, 0x746AU, 0x756AU, 0x766AU, 0x776AU, 0x786AU, 0x796AU, 0x7A6AU, 0x306AU, 0x316AU, 0x326AU, 0x336AU, 0x346AU, 0x356AU, 0x366AU, 0x376AU, 0x386AU, 0x396AU, 0x2B6AU, 0x2F6AU, 0x416BU, 0x426BU, 0x436BU, 0x446BU, 0x456BU, 0x466BU, 0x476BU, 0x486BU, 0x496BU, 0x4A6BU, 0x4B6BU, 0x4C6BU, 0x4D6BU, 0x4E6BU, 0x4F6BU, 0x506BU, 0x516BU, 0x526BU, 0x536BU, 0x546BU, 0x556BU, 0x566BU, 0x576BU, 0x586BU, 0x596BU, 0x5A6BU, 0x616BU, 0x626BU, 0x636BU, 0x646BU, 0x656BU, 0x666BU, 0x676BU, 0x686BU, 0x696BU, 0x6A6BU, 0x6B6BU, 0x6C6BU, 0x6D6BU, 0x6E6BU, 0x6F6BU, 0x706BU, 0x716BU, 0x726BU, 0x736BU, 0x746BU, 0x756BU, 0x766BU, 0x776BU, 0x786BU, 0x796BU, 0x7A6BU, 0x306BU, 0x316BU, 0x326BU, 0x336BU, 0x346BU, 0x356BU, 0x366BU, 0x376BU, 0x386BU, 0x396BU, 0x2B6BU, 0x2F6BU, 0x416CU, 0x426CU, 0x436CU, 0x446CU, 0x456CU, 0x466CU, 0x476CU, 0x486CU, 0x496CU, 0x4A6CU, 0x4B6CU, 0x4C6CU, 0x4D6CU, 0x4E6CU, 0x4F6CU, 0x506CU, 0x516CU, 0x526CU, 0x536CU, 0x546CU, 0x556CU, 0x566CU, 0x576CU, 0x586CU, 0x596CU, 0x5A6CU, 0x616CU, 0x626CU, 0x636CU, 0x646CU, 0x656CU, 0x666CU, 0x676CU, 0x686CU, 0x696CU, 0x6A6CU, 0x6B6CU, 0x6C6CU, 0x6D6CU, 0x6E6CU, 0x6F6CU, 0x706CU, 0x716CU, 0x726CU, 0x736CU, 0x746CU, 0x756CU, 0x766CU, 0x776CU, 0x786CU, 0x796CU, 0x7A6CU, 0x306CU, 0x316CU, 0x326CU, 0x336CU, 0x346CU, 0x356CU, 0x366CU, 0x376CU, 0x386CU, 0x396CU, 0x2B6CU, 0x2F6CU, 0x416DU, 0x426DU, 0x436DU, 0x446DU, 0x456DU, 0x466DU, 0x476DU, 0x486DU, 0x496DU, 0x4A6DU, 0x4B6DU, 0x4C6DU, 0x4D6DU, 0x4E6DU, 0x4F6DU, 0x506DU, 0x516DU, 0x526DU, 0x536DU, 0x546DU, 0x556DU, 0x566DU, 0x576DU, 0x586DU, 0x596DU, 0x5A6DU, 0x616DU, 0x626DU, 0x636DU, 0x646DU, 0x656DU, 0x666DU, 0x676DU, 0x686DU, 0x696DU, 0x6A6DU, 0x6B6DU, 0x6C6DU, 0x6D6DU, 0x6E6DU, 0x6F6DU, 0x706DU, 0x716DU, 0x726DU, 0x736DU, 0x746DU, 0x756DU, 0x766DU, 0x776DU, 0x786DU, 0x796DU, 0x7A6DU, 0x306DU, 0x316DU, 0x326DU, 0x336DU, 0x346DU, 0x356DU, 0x366DU, 0x376DU, 0x386DU, 0x396DU, 0x2B6DU, 0x2F6DU, 0x416EU, 0x426EU, 0x436EU, 0x446EU, 0x456EU, 0x466EU, 0x476EU, 0x486EU, 0x496EU, 0x4A6EU, 0x4B6EU, 0x4C6EU, 0x4D6EU, 0x4E6EU, 0x4F6EU, 0x506EU, 0x516EU, 0x526EU, 0x536EU, 0x546EU, 0x556EU, 0x566EU, 0x576EU, 0x586EU, 0x596EU, 0x5A6EU, 0x616EU, 0x626EU, 0x636EU, 0x646EU, 0x656EU, 0x666EU, 0x676EU, 0x686EU, 0x696EU, 0x6A6EU, 0x6B6EU, 0x6C6EU, 0x6D6EU, 0x6E6EU, 0x6F6EU, 0x706EU, 0x716EU, 0x726EU, 0x736EU, 0x746EU, 0x756EU, 0x766EU, 0x776EU, 0x786EU, 0x796EU, 0x7A6EU, 0x306EU, 0x316EU, 0x326EU, 0x336EU, 0x346EU, 0x356EU, 0x366EU, 0x376EU, 0x386EU, 0x396EU, 0x2B6EU, 0x2F6EU, 0x416FU, 0x426FU, 0x436FU, 0x446FU, 0x456FU, 0x466FU, 0x476FU, 0x486FU, 0x496FU, 0x4A6FU, 0x4B6FU, 0x4C6FU, 0x4D6FU, 0x4E6FU, 0x4F6FU, 0x506FU, 0x516FU, 0x526FU, 0x536FU, 0x546FU, 0x556FU, 0x566FU, 0x576FU, 0x586FU, 0x596FU, 0x5A6FU, 0x616FU, 0x626FU, 0x636FU, 0x646FU, 0x656FU, 0x666FU, 0x676FU, 0x686FU, 0x696FU, 0x6A6FU, 0x6B6FU, 0x6C6FU, 0x6D6FU, 0x6E6FU, 0x6F6FU, 0x706FU, 0x716FU, 0x726FU, 0x736FU, 0x746FU, 0x756FU, 0x766FU, 0x776FU, 0x786FU, 0x796FU, 0x7A6FU, 0x306FU, 0x316FU, 0x326FU, 0x336FU, 0x346FU, 0x356FU, 0x366FU, 0x376FU, 0x386FU, 0x396FU, 0x2B6FU, 0x2F6FU, 0x4170U, 0x4270U, 0x4370U, 0x4470U, 0x4570U, 0x4670U, 0x4770U, 0x4870U, 0x4970U, 0x4A70U, 0x4B70U, 0x4C70U, 0x4D70U, 0x4E70U, 0x4F70U, 0x5070U, 0x5170U, 0x5270U, 0x5370U, 0x5470U, 0x5570U, 0x5670U, 0x5770U, 0x5870U, 0x5970U, 0x5A70U, 0x6170U, 0x6270U, 0x6370U, 0x6470U, 0x6570U, 0x6670U, 0x6770U, 0x6870U, 0x6970U, 0x6A70U, 0x6B70U, 0x6C70U, 0x6D70U, 0x6E70U, 0x6F70U, 0x7070U, 0x7170U, 0x7270U, 0x7370U, 0x7470U, 0x7570U, 0x7670U, 0x7770U, 0x7870U, 0x7970U, 0x7A70U, 0x3070U, 0x3170U, 0x3270U, 0x3370U, 0x3470U, 0x3570U, 0x3670U, 0x3770U, 0x3870U, 0x3970U, 0x2B70U, 0x2F70U, 0x4171U, 0x4271U, 0x4371U, 0x4471U, 0x4571U, 0x4671U, 0x4771U, 0x4871U, 0x4971U, 0x4A71U, 0x4B71U, 0x4C71U, 0x4D71U, 0x4E71U, 0x4F71U, 0x5071U, 0x5171U, 0x5271U, 0x5371U, 0x5471U, 0x5571U, 0x5671U, 0x5771U, 0x5871U, 0x5971U, 0x5A71U, 0x6171U, 0x6271U, 0x6371U, 0x6471U, 0x6571U, 0x6671U, 0x6771U, 0x6871U, 0x6971U, 0x6A71U, 0x6B71U, 0x6C71U, 0x6D71U, 0x6E71U, 0x6F71U, 0x7071U, 0x7171U, 0x7271U, 0x7371U, 0x7471U, 0x7571U, 0x7671U, 0x7771U, 0x7871U, 0x7971U, 0x7A71U, 0x3071U, 0x3171U, 0x3271U, 0x3371U, 0x3471U, 0x3571U, 0x3671U, 0x3771U, 0x3871U, 0x3971U, 0x2B71U, 0x2F71U, 0x4172U, 0x4272U, 0x4372U, 0x4472U, 0x4572U, 0x4672U, 0x4772U, 0x4872U, 0x4972U, 0x4A72U, 0x4B72U, 0x4C72U, 0x4D72U, 0x4E72U, 0x4F72U, 0x5072U, 0x5172U, 0x5272U, 0x5372U, 0x5472U, 0x5572U, 0x5672U, 0x5772U, 0x5872U, 0x5972U, 0x5A72U, 0x6172U, 0x6272U, 0x6372U, 0x6472U, 0x6572U, 0x6672U, 0x6772U, 0x6872U, 0x6972U, 0x6A72U, 0x6B72U, 0x6C72U, 0x6D72U, 0x6E72U, 0x6F72U, 0x7072U, 0x7172U, 0x7272U, 0x7372U, 0x7472U, 0x7572U, 0x7672U, 0x7772U, 0x7872U, 0x7972U, 0x7A72U, 0x3072U, 0x3172U, 0x3272U, 0x3372U, 0x3472U, 0x3572U, 0x3672U, 0x3772U, 0x3872U, 0x3972U, 0x2B72U, 0x2F72U, 0x4173U, 0x4273U, 0x4373U, 0x4473U, 0x4573U, 0x4673U, 0x4773U, 0x4873U, 0x4973U, 0x4A73U, 0x4B73U, 0x4C73U, 0x4D73U, 0x4E73U, 0x4F73U, 0x5073U, 0x5173U, 0x5273U, 0x5373U, 0x5473U, 0x5573U, 0x5673U, 0x5773U, 0x5873U, 0x5973U, 0x5A73U, 0x6173U, 0x6273U, 0x6373U, 0x6473U, 0x6573U, 0x6673U, 0x6773U, 0x6873U, 0x6973U, 0x6A73U, 0x6B73U, 0x6C73U, 0x6D73U, 0x6E73U, 0x6F73U, 0x7073U, 0x7173U, 0x7273U, 0x7373U, 0x7473U, 0x7573U, 0x7673U, 0x7773U, 0x7873U, 0x7973U, 0x7A73U, 0x3073U, 0x3173U, 0x3273U, 0x3373U, 0x3473U, 0x3573U, 0x3673U, 0x3773U, 0x3873U, 0x3973U, 0x2B73U, 0x2F73U, 0x4174U, 0x4274U, 0x4374U, 0x4474U, 0x4574U, 0x4674U, 0x4774U, 0x4874U, 0x4974U, 0x4A74U, 0x4B74U, 0x4C74U, 0x4D74U, 0x4E74U, 0x4F74U, 0x5074U, 0x5174U, 0x5274U, 0x5374U, 0x5474U, 0x5574U, 0x5674U, 0x5774U, 0x5874U, 0x5974U, 0x5A74U, 0x6174U, 0x6274U, 0x6374U, 0x6474U, 0x6574U, 0x6674U, 0x6774U, 0x6874U, 0x6974U, 0x6A74U, 0x6B74U, 0x6C74U, 0x6D74U, 0x6E74U, 0x6F74U, 0x7074U, 0x7174U, 0x7274U, 0x7374U, 0x7474U, 0x7574U, 0x7674U, 0x7774U, 0x7874U, 0x7974U, 0x7A74U, 0x3074U, 0x3174U, 0x3274U, 0x3374U, 0x3474U, 0x3574U, 0x3674U, 0x3774U, 0x3874U, 0x3974U, 0x2B74U, 0x2F74U, 0x4175U, 0x4275U, 0x4375U, 0x4475U, 0x4575U, 0x4675U, 0x4775U, 0x4875U, 0x4975U, 0x4A75U, 0x4B75U, 0x4C75U, 0x4D75U, 0x4E75U, 0x4F75U, 0x5075U, 0x5175U, 0x5275U, 0x5375U, 0x5475U, 0x5575U, 0x5675U, 0x5775U, 0x5875U, 0x5975U, 0x5A75U, 0x6175U, 0x6275U, 0x6375U, 0x6475U, 0x6575U, 0x6675U, 0x6775U, 0x6875U, 0x6975U, 0x6A75U, 0x6B75U, 0x6C75U, 0x6D75U, 0x6E75U, 0x6F75U, 0x7075U, 0x7175U, 0x7275U, 0x7375U, 0x7475U, 0x7575U, 0x7675U, 0x7775U, 0x7875U, 0x7975U, 0x7A75U, 0x3075U, 0x3175U, 0x3275U, 0x3375U, 0x3475U, 0x3575U, 0x3675U, 0x3775U, 0x3875U, 0x3975U, 0x2B75U, 0x2F75U, 0x4176U, 0x4276U, 0x4376U, 0x4476U, 0x4576U, 0x4676U, 0x4776U, 0x4876U, 0x4976U, 0x4A76U, 0x4B76U, 0x4C76U, 0x4D76U, 0x4E76U, 0x4F76U, 0x5076U, 0x5176U, 0x5276U, 0x5376U, 0x5476U, 0x5576U, 0x5676U, 0x5776U, 0x5876U, 0x5976U, 0x5A76U, 0x6176U, 0x6276U, 0x6376U, 0x6476U, 0x6576U, 0x6676U, 0x6776U, 0x6876U, 0x6976U, 0x6A76U, 0x6B76U, 0x6C76U, 0x6D76U, 0x6E76U, 0x6F76U, 0x7076U, 0x7176U, 0x7276U, 0x7376U, 0x7476U, 0x7576U, 0x7676U, 0x7776U, 0x7876U, 0x7976U, 0x7A76U, 0x3076U, 0x3176U, 0x3276U, 0x3376U, 0x3476U, 0x3576U, 0x3676U, 0x3776U, 0x3876U, 0x3976U, 0x2B76U, 0x2F76U, 0x4177U, 0x4277U, 0x4377U, 0x4477U, 0x4577U, 0x4677U, 0x4777U, 0x4877U, 0x4977U, 0x4A77U, 0x4B77U, 0x4C77U, 0x4D77U, 0x4E77U, 0x4F77U, 0x5077U, 0x5177U, 0x5277U, 0x5377U, 0x5477U, 0x5577U, 0x5677U, 0x5777U, 0x5877U, 0x5977U, 0x5A77U, 0x6177U, 0x6277U, 0x6377U, 0x6477U, 0x6577U, 0x6677U, 0x6777U, 0x6877U, 0x6977U, 0x6A77U, 0x6B77U, 0x6C77U, 0x6D77U, 0x6E77U, 0x6F77U, 0x7077U, 0x7177U, 0x7277U, 0x7377U, 0x7477U, 0x7577U, 0x7677U, 0x7777U, 0x7877U, 0x7977U, 0x7A77U, 0x3077U, 0x3177U, 0x3277U, 0x3377U, 0x3477U, 0x3577U, 0x3677U, 0x3777U, 0x3877U, 0x3977U, 0x2B77U, 0x2F77U, 0x4178U, 0x4278U, 0x4378U, 0x4478U, 0x4578U, 0x4678U, 0x4778U, 0x4878U, 0x4978U, 0x4A78U, 0x4B78U, 0x4C78U, 0x4D78U, 0x4E78U, 0x4F78U, 0x5078U, 0x5178U, 0x5278U, 0x5378U, 0x5478U, 0x5578U, 0x5678U, 0x5778U, 0x5878U, 0x5978U, 0x5A78U, 0x6178U, 0x6278U, 0x6378U, 0x6478U, 0x6578U, 0x6678U, 0x6778U, 0x6878U, 0x6978U, 0x6A78U, 0x6B78U, 0x6C78U, 0x6D78U, 0x6E78U, 0x6F78U, 0x7078U, 0x7178U, 0x7278U, 0x7378U, 0x7478U, 0x7578U, 0x7678U, 0x7778U, 0x7878U, 0x7978U, 0x7A78U, 0x3078U, 0x3178U, 0x3278U, 0x3378U, 0x3478U, 0x3578U, 0x3678U, 0x3778U, 0x3878U, 0x3978U, 0x2B78U, 0x2F78U, 0x4179U, 0x4279U, 0x4379U, 0x4479U, 0x4579U, 0x4679U, 0x4779U, 0x4879U, 0x4979U, 0x4A79U, 0x4B79U, 0x4C79U, 0x4D79U, 0x4E79U, 0x4F79U, 0x5079U, 0x5179U, 0x5279U, 0x5379U, 0x5479U, 0x5579U, 0x5679U, 0x5779U, 0x5879U, 0x5979U, 0x5A79U, 0x6179U, 0x6279U, 0x6379U, 0x6479U, 0x6579U, 0x6679U, 0x6779U, 0x6879U, 0x6979U, 0x6A79U, 0x6B79U, 0x6C79U, 0x6D79U, 0x6E79U, 0x6F79U, 0x7079U, 0x7179U, 0x7279U, 0x7379U, 0x7479U, 0x7579U, 0x7679U, 0x7779U, 0x7879U, 0x7979U, 0x7A79U, 0x3079U, 0x3179U, 0x3279U, 0x3379U, 0x3479U, 0x3579U, 0x3679U, 0x3779U, 0x3879U, 0x3979U, 0x2B79U, 0x2F79U, 0x417AU, 0x427AU, 0x437AU, 0x447AU, 0x457AU, 0x467AU, 0x477AU, 0x487AU, 0x497AU, 0x4A7AU, 0x4B7AU, 0x4C7AU, 0x4D7AU, 0x4E7AU, 0x4F7AU, 0x507AU, 0x517AU, 0x527AU, 0x537AU, 0x547AU, 0x557AU, 0x567AU, 0x577AU, 0x587AU, 0x597AU, 0x5A7AU, 0x617AU, 0x627AU, 0x637AU, 0x647AU, 0x657AU, 0x667AU, 0x677AU, 0x687AU, 0x697AU, 0x6A7AU, 0x6B7AU, 0x6C7AU, 0x6D7AU, 0x6E7AU, 0x6F7AU, 0x707AU, 0x717AU, 0x727AU, 0x737AU, 0x747AU, 0x757AU, 0x767AU, 0x777AU, 0x787AU, 0x797AU, 0x7A7AU, 0x307AU, 0x317AU, 0x327AU, 0x337AU, 0x347AU, 0x357AU, 0x367AU, 0x377AU, 0x387AU, 0x397AU, 0x2B7AU, 0x2F7AU, 0x4130U, 0x4230U, 0x4330U, 0x4430U, 0x4530U, 0x4630U, 0x4730U, 0x4830U, 0x4930U, 0x4A30U, 0x4B30U, 0x4C30U, 0x4D30U, 0x4E30U, 0x4F30U, 0x5030U, 0x5130U, 0x5230U, 0x5330U, 0x5430U, 0x5530U, 0x5630U, 0x5730U, 0x5830U, 0x5930U, 0x5A30U, 0x6130U, 0x6230U, 0x6330U, 0x6430U, 0x6530U, 0x6630U, 0x6730U, 0x6830U, 0x6930U, 0x6A30U, 0x6B30U, 0x6C30U, 0x6D30U, 0x6E30U, 0x6F30U, 0x7030U, 0x7130U, 0x7230U, 0x7330U, 0x7430U, 0x7530U, 0x7630U, 0x7730U, 0x7830U, 0x7930U, 0x7A30U, 0x3030U, 0x3130U, 0x3230U, 0x3330U, 0x3430U, 0x3530U, 0x3630U, 0x3730U, 0x3830U, 0x3930U, 0x2B30U, 0x2F30U, 0x4131U, 0x4231U, 0x4331U, 0x4431U, 0x4531U, 0x4631U, 0x4731U, 0x4831U, 0x4931U, 0x4A31U, 0x4B31U, 0x4C31U, 0x4D31U, 0x4E31U, 0x4F31U, 0x5031U, 0x5131U, 0x5231U, 0x5331U, 0x5431U, 0x5531U, 0x5631U, 0x5731U, 0x5831U, 0x5931U, 0x5A31U, 0x6131U, 0x6231U, 0x6331U, 0x6431U, 0x6531U, 0x6631U, 0x6731U, 0x6831U, 0x6931U, 0x6A31U, 0x6B31U, 0x6C31U, 0x6D31U, 0x6E31U, 0x6F31U, 0x7031U, 0x7131U, 0x7231U, 0x7331U, 0x7431U, 0x7531U, 0x7631U, 0x7731U, 0x7831U, 0x7931U, 0x7A31U, 0x3031U, 0x3131U, 0x3231U, 0x3331U, 0x3431U, 0x3531U, 0x3631U, 0x3731U, 0x3831U, 0x3931U, 0x2B31U, 0x2F31U, 0x4132U, 0x4232U, 0x4332U, 0x4432U, 0x4532U, 0x4632U, 0x4732U, 0x4832U, 0x4932U, 0x4A32U, 0x4B32U, 0x4C32U, 0x4D32U, 0x4E32U, 0x4F32U, 0x5032U, 0x5132U, 0x5232U, 0x5332U, 0x5432U, 0x5532U, 0x5632U, 0x5732U, 0x5832U, 0x5932U, 0x5A32U, 0x6132U, 0x6232U, 0x6332U, 0x6432U, 0x6532U, 0x6632U, 0x6732U, 0x6832U, 0x6932U, 0x6A32U, 0x6B32U, 0x6C32U, 0x6D32U, 0x6E32U, 0x6F32U, 0x7032U, 0x7132U, 0x7232U, 0x7332U, 0x7432U, 0x7532U, 0x7632U, 0x7732U, 0x7832U, 0x7932U, 0x7A32U, 0x3032U, 0x3132U, 0x3232U, 0x3332U, 0x3432U, 0x3532U, 0x3632U, 0x3732U, 0x3832U, 0x3932U, 0x2B32U, 0x2F32U, 0x4133U, 0x4233U, 0x4333U, 0x4433U, 0x4533U, 0x4633U, 0x4733U, 0x4833U, 0x4933U, 0x4A33U, 0x4B33U, 0x4C33U, 0x4D33U, 0x4E33U, 0x4F33U, 0x5033U, 0x5133U, 0x5233U, 0x5333U, 0x5433U, 0x5533U, 0x5633U, 0x5733U, 0x5833U, 0x5933U, 0x5A33U, 0x6133U, 0x6233U, 0x6333U, 0x6433U, 0x6533U, 0x6633U, 0x6733U, 0x6833U, 0x6933U, 0x6A33U, 0x6B33U, 0x6C33U, 0x6D33U, 0x6E33U, 0x6F33U, 0x7033U, 0x7133U, 0x7233U, 0x7333U, 0x7433U, 0x7533U, 0x7633U, 0x7733U, 0x7833U, 0x7933U, 0x7A33U, 0x3033U, 0x3133U, 0x3233U, 0x3333U, 0x3433U, 0x3533U, 0x3633U, 0x3733U, 0x3833U, 0x3933U, 0x2B33U, 0x2F33U, 0x4134U, 0x4234U, 0x4334U, 0x4434U, 0x4534U, 0x4634U, 0x4734U, 0x4834U, 0x4934U, 0x4A34U, 0x4B34U, 0x4C34U, 0x4D34U, 0x4E34U, 0x4F34U, 0x5034U, 0x5134U, 0x5234U, 0x5334U, 0x5434U, 0x5534U, 0x5634U, 0x5734U, 0x5834U, 0x5934U, 0x5A34U, 0x6134U, 0x6234U, 0x6334U, 0x6434U, 0x6534U, 0x6634U, 0x6734U, 0x6834U, 0x6934U, 0x6A34U, 0x6B34U, 0x6C34U, 0x6D34U, 0x6E34U, 0x6F34U, 0x7034U, 0x7134U, 0x7234U, 0x7334U, 0x7434U, 0x7534U, 0x7634U, 0x7734U, 0x7834U, 0x7934U, 0x7A34U, 0x3034U, 0x3134U, 0x3234U, 0x3334U, 0x3434U, 0x3534U, 0x3634U, 0x3734U, 0x3834U, 0x3934U, 0x2B34U, 0x2F34U, 0x4135U, 0x4235U, 0x4335U, 0x4435U, 0x4535U, 0x4635U, 0x4735U, 0x4835U, 0x4935U, 0x4A35U, 0x4B35U, 0x4C35U, 0x4D35U, 0x4E35U, 0x4F35U, 0x5035U, 0x5135U, 0x5235U, 0x5335U, 0x5435U, 0x5535U, 0x5635U, 0x5735U, 0x5835U, 0x5935U, 0x5A35U, 0x6135U, 0x6235U, 0x6335U, 0x6435U, 0x6535U, 0x6635U, 0x6735U, 0x6835U, 0x6935U, 0x6A35U, 0x6B35U, 0x6C35U, 0x6D35U, 0x6E35U, 0x6F35U, 0x7035U, 0x7135U, 0x7235U, 0x7335U, 0x7435U, 0x7535U, 0x7635U, 0x7735U, 0x7835U, 0x7935U, 0x7A35U, 0x3035U, 0x3135U, 0x3235U, 0x3335U, 0x3435U, 0x3535U, 0x3635U, 0x3735U, 0x3835U, 0x3935U, 0x2B35U, 0x2F35U, 0x4136U, 0x4236U, 0x4336U, 0x4436U, 0x4536U, 0x4636U, 0x4736U, 0x4836U, 0x4936U, 0x4A36U, 0x4B36U, 0x4C36U, 0x4D36U, 0x4E36U, 0x4F36U, 0x5036U, 0x5136U, 0x5236U, 0x5336U, 0x5436U, 0x5536U, 0x5636U, 0x5736U, 0x5836U, 0x5936U, 0x5A36U, 0x6136U, 0x6236U, 0x6336U, 0x6436U, 0x6536U, 0x6636U, 0x6736U, 0x6836U, 0x6936U, 0x6A36U, 0x6B36U, 0x6C36U, 0x6D36U, 0x6E36U, 0x6F36U, 0x7036U, 0x7136U, 0x7236U, 0x7336U, 0x7436U, 0x7536U, 0x7636U, 0x7736U, 0x7836U, 0x7936U, 0x7A36U, 0x3036U, 0x3136U, 0x3236U, 0x3336U, 0x3436U, 0x3536U, 0x3636U, 0x3736U, 0x3836U, 0x3936U, 0x2B36U, 0x2F36U, 0x4137U, 0x4237U, 0x4337U, 0x4437U, 0x4537U, 0x4637U, 0x4737U, 0x4837U, 0x4937U, 0x4A37U, 0x4B37U, 0x4C37U, 0x4D37U, 0x4E37U, 0x4F37U, 0x5037U, 0x5137U, 0x5237U, 0x5337U, 0x5437U, 0x5537U, 0x5637U, 0x5737U, 0x5837U, 0x5937U, 0x5A37U, 0x6137U, 0x6237U, 0x6337U, 0x6437U, 0x6537U, 0x6637U, 0x6737U, 0x6837U, 0x6937U, 0x6A37U, 0x6B37U, 0x6C37U, 0x6D37U, 0x6E37U, 0x6F37U, 0x7037U, 0x7137U, 0x7237U, 0x7337U, 0x7437U, 0x7537U, 0x7637U, 0x7737U, 0x7837U, 0x7937U, 0x7A37U, 0x3037U, 0x3137U, 0x3237U, 0x3337U, 0x3437U, 0x3537U, 0x3637U, 0x3737U, 0x3837U, 0x3937U, 0x2B37U, 0x2F37U, 0x4138U, 0x4238U, 0x4338U, 0x4438U, 0x4538U, 0x4638U, 0x4738U, 0x4838U, 0x4938U, 0x4A38U, 0x4B38U, 0x4C38U, 0x4D38U, 0x4E38U, 0x4F38U, 0x5038U, 0x5138U, 0x5238U, 0x5338U, 0x5438U, 0x5538U, 0x5638U, 0x5738U, 0x5838U, 0x5938U, 0x5A38U, 0x6138U, 0x6238U, 0x6338U, 0x6438U, 0x6538U, 0x6638U, 0x6738U, 0x6838U, 0x6938U, 0x6A38U, 0x6B38U, 0x6C38U, 0x6D38U, 0x6E38U, 0x6F38U, 0x7038U, 0x7138U, 0x7238U, 0x7338U, 0x7438U, 0x7538U, 0x7638U, 0x7738U, 0x7838U, 0x7938U, 0x7A38U, 0x3038U, 0x3138U, 0x3238U, 0x3338U, 0x3438U, 0x3538U, 0x3638U, 0x3738U, 0x3838U, 0x3938U, 0x2B38U, 0x2F38U, 0x4139U, 0x4239U, 0x4339U, 0x4439U, 0x4539U, 0x4639U, 0x4739U, 0x4839U, 0x4939U, 0x4A39U, 0x4B39U, 0x4C39U, 0x4D39U, 0x4E39U, 0x4F39U, 0x5039U, 0x5139U, 0x5239U, 0x5339U, 0x5439U, 0x5539U, 0x5639U, 0x5739U, 0x5839U, 0x5939U, 0x5A39U, 0x6139U, 0x6239U, 0x6339U, 0x6439U, 0x6539U, 0x6639U, 0x6739U, 0x6839U, 0x6939U, 0x6A39U, 0x6B39U, 0x6C39U, 0x6D39U, 0x6E39U, 0x6F39U, 0x7039U, 0x7139U, 0x7239U, 0x7339U, 0x7439U, 0x7539U, 0x7639U, 0x7739U, 0x7839U, 0x7939U, 0x7A39U, 0x3039U, 0x3139U, 0x3239U, 0x3339U, 0x3439U, 0x3539U, 0x3639U, 0x3739U, 0x3839U, 0x3939U, 0x2B39U, 0x2F39U, 0x412BU, 0x422BU, 0x432BU, 0x442BU, 0x452BU, 0x462BU, 0x472BU, 0x482BU, 0x492BU, 0x4A2BU, 0x4B2BU, 0x4C2BU, 0x4D2BU, 0x4E2BU, 0x4F2BU, 0x502BU, 0x512BU, 0x522BU, 0x532BU, 0x542BU, 0x552BU, 0x562BU, 0x572BU, 0x582BU, 0x592BU, 0x5A2BU, 0x612BU, 0x622BU, 0x632BU, 0x642BU, 0x652BU, 0x662BU, 0x672BU, 0x682BU, 0x692BU, 0x6A2BU, 0x6B2BU, 0x6C2BU, 0x6D2BU, 0x6E2BU, 0x6F2BU, 0x702BU, 0x712BU, 0x722BU, 0x732BU, 0x742BU, 0x752BU, 0x762BU, 0x772BU, 0x782BU, 0x792BU, 0x7A2BU, 0x302BU, 0x312BU, 0x322BU, 0x332BU, 0x342BU, 0x352BU, 0x362BU, 0x372BU, 0x382BU, 0x392BU, 0x2B2BU, 0x2F2BU, 0x412FU, 0x422FU, 0x432FU, 0x442FU, 0x452FU, 0x462FU, 0x472FU, 0x482FU, 0x492FU, 0x4A2FU, 0x4B2FU, 0x4C2FU, 0x4D2FU, 0x4E2FU, 0x4F2FU, 0x502FU, 0x512FU, 0x522FU, 0x532FU, 0x542FU, 0x552FU, 0x562FU, 0x572FU, 0x582FU, 0x592FU, 0x5A2FU, 0x612FU, 0x622FU, 0x632FU, 0x642FU, 0x652FU, 0x662FU, 0x672FU, 0x682FU, 0x692FU, 0x6A2FU, 0x6B2FU, 0x6C2FU, 0x6D2FU, 0x6E2FU, 0x6F2FU, 0x702FU, 0x712FU, 0x722FU, 0x732FU, 0x742FU, 0x752FU, 0x762FU, 0x772FU, 0x782FU, 0x792FU, 0x7A2FU, 0x302FU, 0x312FU, 0x322FU, 0x332FU, 0x342FU, 0x352FU, 0x362FU, 0x372FU, 0x382FU, 0x392FU, 0x2B2FU, 0x2F2FU, #else 0x4141U, 0x4142U, 0x4143U, 0x4144U, 0x4145U, 0x4146U, 0x4147U, 0x4148U, 0x4149U, 0x414AU, 0x414BU, 0x414CU, 0x414DU, 0x414EU, 0x414FU, 0x4150U, 0x4151U, 0x4152U, 0x4153U, 0x4154U, 0x4155U, 0x4156U, 0x4157U, 0x4158U, 0x4159U, 0x415AU, 0x4161U, 0x4162U, 0x4163U, 0x4164U, 0x4165U, 0x4166U, 0x4167U, 0x4168U, 0x4169U, 0x416AU, 0x416BU, 0x416CU, 0x416DU, 0x416EU, 0x416FU, 0x4170U, 0x4171U, 0x4172U, 0x4173U, 0x4174U, 0x4175U, 0x4176U, 0x4177U, 0x4178U, 0x4179U, 0x417AU, 0x4130U, 0x4131U, 0x4132U, 0x4133U, 0x4134U, 0x4135U, 0x4136U, 0x4137U, 0x4138U, 0x4139U, 0x412BU, 0x412FU, 0x4241U, 0x4242U, 0x4243U, 0x4244U, 0x4245U, 0x4246U, 0x4247U, 0x4248U, 0x4249U, 0x424AU, 0x424BU, 0x424CU, 0x424DU, 0x424EU, 0x424FU, 0x4250U, 0x4251U, 0x4252U, 0x4253U, 0x4254U, 0x4255U, 0x4256U, 0x4257U, 0x4258U, 0x4259U, 0x425AU, 0x4261U, 0x4262U, 0x4263U, 0x4264U, 0x4265U, 0x4266U, 0x4267U, 0x4268U, 0x4269U, 0x426AU, 0x426BU, 0x426CU, 0x426DU, 0x426EU, 0x426FU, 0x4270U, 0x4271U, 0x4272U, 0x4273U, 0x4274U, 0x4275U, 0x4276U, 0x4277U, 0x4278U, 0x4279U, 0x427AU, 0x4230U, 0x4231U, 0x4232U, 0x4233U, 0x4234U, 0x4235U, 0x4236U, 0x4237U, 0x4238U, 0x4239U, 0x422BU, 0x422FU, 0x4341U, 0x4342U, 0x4343U, 0x4344U, 0x4345U, 0x4346U, 0x4347U, 0x4348U, 0x4349U, 0x434AU, 0x434BU, 0x434CU, 0x434DU, 0x434EU, 0x434FU, 0x4350U, 0x4351U, 0x4352U, 0x4353U, 0x4354U, 0x4355U, 0x4356U, 0x4357U, 0x4358U, 0x4359U, 0x435AU, 0x4361U, 0x4362U, 0x4363U, 0x4364U, 0x4365U, 0x4366U, 0x4367U, 0x4368U, 0x4369U, 0x436AU, 0x436BU, 0x436CU, 0x436DU, 0x436EU, 0x436FU, 0x4370U, 0x4371U, 0x4372U, 0x4373U, 0x4374U, 0x4375U, 0x4376U, 0x4377U, 0x4378U, 0x4379U, 0x437AU, 0x4330U, 0x4331U, 0x4332U, 0x4333U, 0x4334U, 0x4335U, 0x4336U, 0x4337U, 0x4338U, 0x4339U, 0x432BU, 0x432FU, 0x4441U, 0x4442U, 0x4443U, 0x4444U, 0x4445U, 0x4446U, 0x4447U, 0x4448U, 0x4449U, 0x444AU, 0x444BU, 0x444CU, 0x444DU, 0x444EU, 0x444FU, 0x4450U, 0x4451U, 0x4452U, 0x4453U, 0x4454U, 0x4455U, 0x4456U, 0x4457U, 0x4458U, 0x4459U, 0x445AU, 0x4461U, 0x4462U, 0x4463U, 0x4464U, 0x4465U, 0x4466U, 0x4467U, 0x4468U, 0x4469U, 0x446AU, 0x446BU, 0x446CU, 0x446DU, 0x446EU, 0x446FU, 0x4470U, 0x4471U, 0x4472U, 0x4473U, 0x4474U, 0x4475U, 0x4476U, 0x4477U, 0x4478U, 0x4479U, 0x447AU, 0x4430U, 0x4431U, 0x4432U, 0x4433U, 0x4434U, 0x4435U, 0x4436U, 0x4437U, 0x4438U, 0x4439U, 0x442BU, 0x442FU, 0x4541U, 0x4542U, 0x4543U, 0x4544U, 0x4545U, 0x4546U, 0x4547U, 0x4548U, 0x4549U, 0x454AU, 0x454BU, 0x454CU, 0x454DU, 0x454EU, 0x454FU, 0x4550U, 0x4551U, 0x4552U, 0x4553U, 0x4554U, 0x4555U, 0x4556U, 0x4557U, 0x4558U, 0x4559U, 0x455AU, 0x4561U, 0x4562U, 0x4563U, 0x4564U, 0x4565U, 0x4566U, 0x4567U, 0x4568U, 0x4569U, 0x456AU, 0x456BU, 0x456CU, 0x456DU, 0x456EU, 0x456FU, 0x4570U, 0x4571U, 0x4572U, 0x4573U, 0x4574U, 0x4575U, 0x4576U, 0x4577U, 0x4578U, 0x4579U, 0x457AU, 0x4530U, 0x4531U, 0x4532U, 0x4533U, 0x4534U, 0x4535U, 0x4536U, 0x4537U, 0x4538U, 0x4539U, 0x452BU, 0x452FU, 0x4641U, 0x4642U, 0x4643U, 0x4644U, 0x4645U, 0x4646U, 0x4647U, 0x4648U, 0x4649U, 0x464AU, 0x464BU, 0x464CU, 0x464DU, 0x464EU, 0x464FU, 0x4650U, 0x4651U, 0x4652U, 0x4653U, 0x4654U, 0x4655U, 0x4656U, 0x4657U, 0x4658U, 0x4659U, 0x465AU, 0x4661U, 0x4662U, 0x4663U, 0x4664U, 0x4665U, 0x4666U, 0x4667U, 0x4668U, 0x4669U, 0x466AU, 0x466BU, 0x466CU, 0x466DU, 0x466EU, 0x466FU, 0x4670U, 0x4671U, 0x4672U, 0x4673U, 0x4674U, 0x4675U, 0x4676U, 0x4677U, 0x4678U, 0x4679U, 0x467AU, 0x4630U, 0x4631U, 0x4632U, 0x4633U, 0x4634U, 0x4635U, 0x4636U, 0x4637U, 0x4638U, 0x4639U, 0x462BU, 0x462FU, 0x4741U, 0x4742U, 0x4743U, 0x4744U, 0x4745U, 0x4746U, 0x4747U, 0x4748U, 0x4749U, 0x474AU, 0x474BU, 0x474CU, 0x474DU, 0x474EU, 0x474FU, 0x4750U, 0x4751U, 0x4752U, 0x4753U, 0x4754U, 0x4755U, 0x4756U, 0x4757U, 0x4758U, 0x4759U, 0x475AU, 0x4761U, 0x4762U, 0x4763U, 0x4764U, 0x4765U, 0x4766U, 0x4767U, 0x4768U, 0x4769U, 0x476AU, 0x476BU, 0x476CU, 0x476DU, 0x476EU, 0x476FU, 0x4770U, 0x4771U, 0x4772U, 0x4773U, 0x4774U, 0x4775U, 0x4776U, 0x4777U, 0x4778U, 0x4779U, 0x477AU, 0x4730U, 0x4731U, 0x4732U, 0x4733U, 0x4734U, 0x4735U, 0x4736U, 0x4737U, 0x4738U, 0x4739U, 0x472BU, 0x472FU, 0x4841U, 0x4842U, 0x4843U, 0x4844U, 0x4845U, 0x4846U, 0x4847U, 0x4848U, 0x4849U, 0x484AU, 0x484BU, 0x484CU, 0x484DU, 0x484EU, 0x484FU, 0x4850U, 0x4851U, 0x4852U, 0x4853U, 0x4854U, 0x4855U, 0x4856U, 0x4857U, 0x4858U, 0x4859U, 0x485AU, 0x4861U, 0x4862U, 0x4863U, 0x4864U, 0x4865U, 0x4866U, 0x4867U, 0x4868U, 0x4869U, 0x486AU, 0x486BU, 0x486CU, 0x486DU, 0x486EU, 0x486FU, 0x4870U, 0x4871U, 0x4872U, 0x4873U, 0x4874U, 0x4875U, 0x4876U, 0x4877U, 0x4878U, 0x4879U, 0x487AU, 0x4830U, 0x4831U, 0x4832U, 0x4833U, 0x4834U, 0x4835U, 0x4836U, 0x4837U, 0x4838U, 0x4839U, 0x482BU, 0x482FU, 0x4941U, 0x4942U, 0x4943U, 0x4944U, 0x4945U, 0x4946U, 0x4947U, 0x4948U, 0x4949U, 0x494AU, 0x494BU, 0x494CU, 0x494DU, 0x494EU, 0x494FU, 0x4950U, 0x4951U, 0x4952U, 0x4953U, 0x4954U, 0x4955U, 0x4956U, 0x4957U, 0x4958U, 0x4959U, 0x495AU, 0x4961U, 0x4962U, 0x4963U, 0x4964U, 0x4965U, 0x4966U, 0x4967U, 0x4968U, 0x4969U, 0x496AU, 0x496BU, 0x496CU, 0x496DU, 0x496EU, 0x496FU, 0x4970U, 0x4971U, 0x4972U, 0x4973U, 0x4974U, 0x4975U, 0x4976U, 0x4977U, 0x4978U, 0x4979U, 0x497AU, 0x4930U, 0x4931U, 0x4932U, 0x4933U, 0x4934U, 0x4935U, 0x4936U, 0x4937U, 0x4938U, 0x4939U, 0x492BU, 0x492FU, 0x4A41U, 0x4A42U, 0x4A43U, 0x4A44U, 0x4A45U, 0x4A46U, 0x4A47U, 0x4A48U, 0x4A49U, 0x4A4AU, 0x4A4BU, 0x4A4CU, 0x4A4DU, 0x4A4EU, 0x4A4FU, 0x4A50U, 0x4A51U, 0x4A52U, 0x4A53U, 0x4A54U, 0x4A55U, 0x4A56U, 0x4A57U, 0x4A58U, 0x4A59U, 0x4A5AU, 0x4A61U, 0x4A62U, 0x4A63U, 0x4A64U, 0x4A65U, 0x4A66U, 0x4A67U, 0x4A68U, 0x4A69U, 0x4A6AU, 0x4A6BU, 0x4A6CU, 0x4A6DU, 0x4A6EU, 0x4A6FU, 0x4A70U, 0x4A71U, 0x4A72U, 0x4A73U, 0x4A74U, 0x4A75U, 0x4A76U, 0x4A77U, 0x4A78U, 0x4A79U, 0x4A7AU, 0x4A30U, 0x4A31U, 0x4A32U, 0x4A33U, 0x4A34U, 0x4A35U, 0x4A36U, 0x4A37U, 0x4A38U, 0x4A39U, 0x4A2BU, 0x4A2FU, 0x4B41U, 0x4B42U, 0x4B43U, 0x4B44U, 0x4B45U, 0x4B46U, 0x4B47U, 0x4B48U, 0x4B49U, 0x4B4AU, 0x4B4BU, 0x4B4CU, 0x4B4DU, 0x4B4EU, 0x4B4FU, 0x4B50U, 0x4B51U, 0x4B52U, 0x4B53U, 0x4B54U, 0x4B55U, 0x4B56U, 0x4B57U, 0x4B58U, 0x4B59U, 0x4B5AU, 0x4B61U, 0x4B62U, 0x4B63U, 0x4B64U, 0x4B65U, 0x4B66U, 0x4B67U, 0x4B68U, 0x4B69U, 0x4B6AU, 0x4B6BU, 0x4B6CU, 0x4B6DU, 0x4B6EU, 0x4B6FU, 0x4B70U, 0x4B71U, 0x4B72U, 0x4B73U, 0x4B74U, 0x4B75U, 0x4B76U, 0x4B77U, 0x4B78U, 0x4B79U, 0x4B7AU, 0x4B30U, 0x4B31U, 0x4B32U, 0x4B33U, 0x4B34U, 0x4B35U, 0x4B36U, 0x4B37U, 0x4B38U, 0x4B39U, 0x4B2BU, 0x4B2FU, 0x4C41U, 0x4C42U, 0x4C43U, 0x4C44U, 0x4C45U, 0x4C46U, 0x4C47U, 0x4C48U, 0x4C49U, 0x4C4AU, 0x4C4BU, 0x4C4CU, 0x4C4DU, 0x4C4EU, 0x4C4FU, 0x4C50U, 0x4C51U, 0x4C52U, 0x4C53U, 0x4C54U, 0x4C55U, 0x4C56U, 0x4C57U, 0x4C58U, 0x4C59U, 0x4C5AU, 0x4C61U, 0x4C62U, 0x4C63U, 0x4C64U, 0x4C65U, 0x4C66U, 0x4C67U, 0x4C68U, 0x4C69U, 0x4C6AU, 0x4C6BU, 0x4C6CU, 0x4C6DU, 0x4C6EU, 0x4C6FU, 0x4C70U, 0x4C71U, 0x4C72U, 0x4C73U, 0x4C74U, 0x4C75U, 0x4C76U, 0x4C77U, 0x4C78U, 0x4C79U, 0x4C7AU, 0x4C30U, 0x4C31U, 0x4C32U, 0x4C33U, 0x4C34U, 0x4C35U, 0x4C36U, 0x4C37U, 0x4C38U, 0x4C39U, 0x4C2BU, 0x4C2FU, 0x4D41U, 0x4D42U, 0x4D43U, 0x4D44U, 0x4D45U, 0x4D46U, 0x4D47U, 0x4D48U, 0x4D49U, 0x4D4AU, 0x4D4BU, 0x4D4CU, 0x4D4DU, 0x4D4EU, 0x4D4FU, 0x4D50U, 0x4D51U, 0x4D52U, 0x4D53U, 0x4D54U, 0x4D55U, 0x4D56U, 0x4D57U, 0x4D58U, 0x4D59U, 0x4D5AU, 0x4D61U, 0x4D62U, 0x4D63U, 0x4D64U, 0x4D65U, 0x4D66U, 0x4D67U, 0x4D68U, 0x4D69U, 0x4D6AU, 0x4D6BU, 0x4D6CU, 0x4D6DU, 0x4D6EU, 0x4D6FU, 0x4D70U, 0x4D71U, 0x4D72U, 0x4D73U, 0x4D74U, 0x4D75U, 0x4D76U, 0x4D77U, 0x4D78U, 0x4D79U, 0x4D7AU, 0x4D30U, 0x4D31U, 0x4D32U, 0x4D33U, 0x4D34U, 0x4D35U, 0x4D36U, 0x4D37U, 0x4D38U, 0x4D39U, 0x4D2BU, 0x4D2FU, 0x4E41U, 0x4E42U, 0x4E43U, 0x4E44U, 0x4E45U, 0x4E46U, 0x4E47U, 0x4E48U, 0x4E49U, 0x4E4AU, 0x4E4BU, 0x4E4CU, 0x4E4DU, 0x4E4EU, 0x4E4FU, 0x4E50U, 0x4E51U, 0x4E52U, 0x4E53U, 0x4E54U, 0x4E55U, 0x4E56U, 0x4E57U, 0x4E58U, 0x4E59U, 0x4E5AU, 0x4E61U, 0x4E62U, 0x4E63U, 0x4E64U, 0x4E65U, 0x4E66U, 0x4E67U, 0x4E68U, 0x4E69U, 0x4E6AU, 0x4E6BU, 0x4E6CU, 0x4E6DU, 0x4E6EU, 0x4E6FU, 0x4E70U, 0x4E71U, 0x4E72U, 0x4E73U, 0x4E74U, 0x4E75U, 0x4E76U, 0x4E77U, 0x4E78U, 0x4E79U, 0x4E7AU, 0x4E30U, 0x4E31U, 0x4E32U, 0x4E33U, 0x4E34U, 0x4E35U, 0x4E36U, 0x4E37U, 0x4E38U, 0x4E39U, 0x4E2BU, 0x4E2FU, 0x4F41U, 0x4F42U, 0x4F43U, 0x4F44U, 0x4F45U, 0x4F46U, 0x4F47U, 0x4F48U, 0x4F49U, 0x4F4AU, 0x4F4BU, 0x4F4CU, 0x4F4DU, 0x4F4EU, 0x4F4FU, 0x4F50U, 0x4F51U, 0x4F52U, 0x4F53U, 0x4F54U, 0x4F55U, 0x4F56U, 0x4F57U, 0x4F58U, 0x4F59U, 0x4F5AU, 0x4F61U, 0x4F62U, 0x4F63U, 0x4F64U, 0x4F65U, 0x4F66U, 0x4F67U, 0x4F68U, 0x4F69U, 0x4F6AU, 0x4F6BU, 0x4F6CU, 0x4F6DU, 0x4F6EU, 0x4F6FU, 0x4F70U, 0x4F71U, 0x4F72U, 0x4F73U, 0x4F74U, 0x4F75U, 0x4F76U, 0x4F77U, 0x4F78U, 0x4F79U, 0x4F7AU, 0x4F30U, 0x4F31U, 0x4F32U, 0x4F33U, 0x4F34U, 0x4F35U, 0x4F36U, 0x4F37U, 0x4F38U, 0x4F39U, 0x4F2BU, 0x4F2FU, 0x5041U, 0x5042U, 0x5043U, 0x5044U, 0x5045U, 0x5046U, 0x5047U, 0x5048U, 0x5049U, 0x504AU, 0x504BU, 0x504CU, 0x504DU, 0x504EU, 0x504FU, 0x5050U, 0x5051U, 0x5052U, 0x5053U, 0x5054U, 0x5055U, 0x5056U, 0x5057U, 0x5058U, 0x5059U, 0x505AU, 0x5061U, 0x5062U, 0x5063U, 0x5064U, 0x5065U, 0x5066U, 0x5067U, 0x5068U, 0x5069U, 0x506AU, 0x506BU, 0x506CU, 0x506DU, 0x506EU, 0x506FU, 0x5070U, 0x5071U, 0x5072U, 0x5073U, 0x5074U, 0x5075U, 0x5076U, 0x5077U, 0x5078U, 0x5079U, 0x507AU, 0x5030U, 0x5031U, 0x5032U, 0x5033U, 0x5034U, 0x5035U, 0x5036U, 0x5037U, 0x5038U, 0x5039U, 0x502BU, 0x502FU, 0x5141U, 0x5142U, 0x5143U, 0x5144U, 0x5145U, 0x5146U, 0x5147U, 0x5148U, 0x5149U, 0x514AU, 0x514BU, 0x514CU, 0x514DU, 0x514EU, 0x514FU, 0x5150U, 0x5151U, 0x5152U, 0x5153U, 0x5154U, 0x5155U, 0x5156U, 0x5157U, 0x5158U, 0x5159U, 0x515AU, 0x5161U, 0x5162U, 0x5163U, 0x5164U, 0x5165U, 0x5166U, 0x5167U, 0x5168U, 0x5169U, 0x516AU, 0x516BU, 0x516CU, 0x516DU, 0x516EU, 0x516FU, 0x5170U, 0x5171U, 0x5172U, 0x5173U, 0x5174U, 0x5175U, 0x5176U, 0x5177U, 0x5178U, 0x5179U, 0x517AU, 0x5130U, 0x5131U, 0x5132U, 0x5133U, 0x5134U, 0x5135U, 0x5136U, 0x5137U, 0x5138U, 0x5139U, 0x512BU, 0x512FU, 0x5241U, 0x5242U, 0x5243U, 0x5244U, 0x5245U, 0x5246U, 0x5247U, 0x5248U, 0x5249U, 0x524AU, 0x524BU, 0x524CU, 0x524DU, 0x524EU, 0x524FU, 0x5250U, 0x5251U, 0x5252U, 0x5253U, 0x5254U, 0x5255U, 0x5256U, 0x5257U, 0x5258U, 0x5259U, 0x525AU, 0x5261U, 0x5262U, 0x5263U, 0x5264U, 0x5265U, 0x5266U, 0x5267U, 0x5268U, 0x5269U, 0x526AU, 0x526BU, 0x526CU, 0x526DU, 0x526EU, 0x526FU, 0x5270U, 0x5271U, 0x5272U, 0x5273U, 0x5274U, 0x5275U, 0x5276U, 0x5277U, 0x5278U, 0x5279U, 0x527AU, 0x5230U, 0x5231U, 0x5232U, 0x5233U, 0x5234U, 0x5235U, 0x5236U, 0x5237U, 0x5238U, 0x5239U, 0x522BU, 0x522FU, 0x5341U, 0x5342U, 0x5343U, 0x5344U, 0x5345U, 0x5346U, 0x5347U, 0x5348U, 0x5349U, 0x534AU, 0x534BU, 0x534CU, 0x534DU, 0x534EU, 0x534FU, 0x5350U, 0x5351U, 0x5352U, 0x5353U, 0x5354U, 0x5355U, 0x5356U, 0x5357U, 0x5358U, 0x5359U, 0x535AU, 0x5361U, 0x5362U, 0x5363U, 0x5364U, 0x5365U, 0x5366U, 0x5367U, 0x5368U, 0x5369U, 0x536AU, 0x536BU, 0x536CU, 0x536DU, 0x536EU, 0x536FU, 0x5370U, 0x5371U, 0x5372U, 0x5373U, 0x5374U, 0x5375U, 0x5376U, 0x5377U, 0x5378U, 0x5379U, 0x537AU, 0x5330U, 0x5331U, 0x5332U, 0x5333U, 0x5334U, 0x5335U, 0x5336U, 0x5337U, 0x5338U, 0x5339U, 0x532BU, 0x532FU, 0x5441U, 0x5442U, 0x5443U, 0x5444U, 0x5445U, 0x5446U, 0x5447U, 0x5448U, 0x5449U, 0x544AU, 0x544BU, 0x544CU, 0x544DU, 0x544EU, 0x544FU, 0x5450U, 0x5451U, 0x5452U, 0x5453U, 0x5454U, 0x5455U, 0x5456U, 0x5457U, 0x5458U, 0x5459U, 0x545AU, 0x5461U, 0x5462U, 0x5463U, 0x5464U, 0x5465U, 0x5466U, 0x5467U, 0x5468U, 0x5469U, 0x546AU, 0x546BU, 0x546CU, 0x546DU, 0x546EU, 0x546FU, 0x5470U, 0x5471U, 0x5472U, 0x5473U, 0x5474U, 0x5475U, 0x5476U, 0x5477U, 0x5478U, 0x5479U, 0x547AU, 0x5430U, 0x5431U, 0x5432U, 0x5433U, 0x5434U, 0x5435U, 0x5436U, 0x5437U, 0x5438U, 0x5439U, 0x542BU, 0x542FU, 0x5541U, 0x5542U, 0x5543U, 0x5544U, 0x5545U, 0x5546U, 0x5547U, 0x5548U, 0x5549U, 0x554AU, 0x554BU, 0x554CU, 0x554DU, 0x554EU, 0x554FU, 0x5550U, 0x5551U, 0x5552U, 0x5553U, 0x5554U, 0x5555U, 0x5556U, 0x5557U, 0x5558U, 0x5559U, 0x555AU, 0x5561U, 0x5562U, 0x5563U, 0x5564U, 0x5565U, 0x5566U, 0x5567U, 0x5568U, 0x5569U, 0x556AU, 0x556BU, 0x556CU, 0x556DU, 0x556EU, 0x556FU, 0x5570U, 0x5571U, 0x5572U, 0x5573U, 0x5574U, 0x5575U, 0x5576U, 0x5577U, 0x5578U, 0x5579U, 0x557AU, 0x5530U, 0x5531U, 0x5532U, 0x5533U, 0x5534U, 0x5535U, 0x5536U, 0x5537U, 0x5538U, 0x5539U, 0x552BU, 0x552FU, 0x5641U, 0x5642U, 0x5643U, 0x5644U, 0x5645U, 0x5646U, 0x5647U, 0x5648U, 0x5649U, 0x564AU, 0x564BU, 0x564CU, 0x564DU, 0x564EU, 0x564FU, 0x5650U, 0x5651U, 0x5652U, 0x5653U, 0x5654U, 0x5655U, 0x5656U, 0x5657U, 0x5658U, 0x5659U, 0x565AU, 0x5661U, 0x5662U, 0x5663U, 0x5664U, 0x5665U, 0x5666U, 0x5667U, 0x5668U, 0x5669U, 0x566AU, 0x566BU, 0x566CU, 0x566DU, 0x566EU, 0x566FU, 0x5670U, 0x5671U, 0x5672U, 0x5673U, 0x5674U, 0x5675U, 0x5676U, 0x5677U, 0x5678U, 0x5679U, 0x567AU, 0x5630U, 0x5631U, 0x5632U, 0x5633U, 0x5634U, 0x5635U, 0x5636U, 0x5637U, 0x5638U, 0x5639U, 0x562BU, 0x562FU, 0x5741U, 0x5742U, 0x5743U, 0x5744U, 0x5745U, 0x5746U, 0x5747U, 0x5748U, 0x5749U, 0x574AU, 0x574BU, 0x574CU, 0x574DU, 0x574EU, 0x574FU, 0x5750U, 0x5751U, 0x5752U, 0x5753U, 0x5754U, 0x5755U, 0x5756U, 0x5757U, 0x5758U, 0x5759U, 0x575AU, 0x5761U, 0x5762U, 0x5763U, 0x5764U, 0x5765U, 0x5766U, 0x5767U, 0x5768U, 0x5769U, 0x576AU, 0x576BU, 0x576CU, 0x576DU, 0x576EU, 0x576FU, 0x5770U, 0x5771U, 0x5772U, 0x5773U, 0x5774U, 0x5775U, 0x5776U, 0x5777U, 0x5778U, 0x5779U, 0x577AU, 0x5730U, 0x5731U, 0x5732U, 0x5733U, 0x5734U, 0x5735U, 0x5736U, 0x5737U, 0x5738U, 0x5739U, 0x572BU, 0x572FU, 0x5841U, 0x5842U, 0x5843U, 0x5844U, 0x5845U, 0x5846U, 0x5847U, 0x5848U, 0x5849U, 0x584AU, 0x584BU, 0x584CU, 0x584DU, 0x584EU, 0x584FU, 0x5850U, 0x5851U, 0x5852U, 0x5853U, 0x5854U, 0x5855U, 0x5856U, 0x5857U, 0x5858U, 0x5859U, 0x585AU, 0x5861U, 0x5862U, 0x5863U, 0x5864U, 0x5865U, 0x5866U, 0x5867U, 0x5868U, 0x5869U, 0x586AU, 0x586BU, 0x586CU, 0x586DU, 0x586EU, 0x586FU, 0x5870U, 0x5871U, 0x5872U, 0x5873U, 0x5874U, 0x5875U, 0x5876U, 0x5877U, 0x5878U, 0x5879U, 0x587AU, 0x5830U, 0x5831U, 0x5832U, 0x5833U, 0x5834U, 0x5835U, 0x5836U, 0x5837U, 0x5838U, 0x5839U, 0x582BU, 0x582FU, 0x5941U, 0x5942U, 0x5943U, 0x5944U, 0x5945U, 0x5946U, 0x5947U, 0x5948U, 0x5949U, 0x594AU, 0x594BU, 0x594CU, 0x594DU, 0x594EU, 0x594FU, 0x5950U, 0x5951U, 0x5952U, 0x5953U, 0x5954U, 0x5955U, 0x5956U, 0x5957U, 0x5958U, 0x5959U, 0x595AU, 0x5961U, 0x5962U, 0x5963U, 0x5964U, 0x5965U, 0x5966U, 0x5967U, 0x5968U, 0x5969U, 0x596AU, 0x596BU, 0x596CU, 0x596DU, 0x596EU, 0x596FU, 0x5970U, 0x5971U, 0x5972U, 0x5973U, 0x5974U, 0x5975U, 0x5976U, 0x5977U, 0x5978U, 0x5979U, 0x597AU, 0x5930U, 0x5931U, 0x5932U, 0x5933U, 0x5934U, 0x5935U, 0x5936U, 0x5937U, 0x5938U, 0x5939U, 0x592BU, 0x592FU, 0x5A41U, 0x5A42U, 0x5A43U, 0x5A44U, 0x5A45U, 0x5A46U, 0x5A47U, 0x5A48U, 0x5A49U, 0x5A4AU, 0x5A4BU, 0x5A4CU, 0x5A4DU, 0x5A4EU, 0x5A4FU, 0x5A50U, 0x5A51U, 0x5A52U, 0x5A53U, 0x5A54U, 0x5A55U, 0x5A56U, 0x5A57U, 0x5A58U, 0x5A59U, 0x5A5AU, 0x5A61U, 0x5A62U, 0x5A63U, 0x5A64U, 0x5A65U, 0x5A66U, 0x5A67U, 0x5A68U, 0x5A69U, 0x5A6AU, 0x5A6BU, 0x5A6CU, 0x5A6DU, 0x5A6EU, 0x5A6FU, 0x5A70U, 0x5A71U, 0x5A72U, 0x5A73U, 0x5A74U, 0x5A75U, 0x5A76U, 0x5A77U, 0x5A78U, 0x5A79U, 0x5A7AU, 0x5A30U, 0x5A31U, 0x5A32U, 0x5A33U, 0x5A34U, 0x5A35U, 0x5A36U, 0x5A37U, 0x5A38U, 0x5A39U, 0x5A2BU, 0x5A2FU, 0x6141U, 0x6142U, 0x6143U, 0x6144U, 0x6145U, 0x6146U, 0x6147U, 0x6148U, 0x6149U, 0x614AU, 0x614BU, 0x614CU, 0x614DU, 0x614EU, 0x614FU, 0x6150U, 0x6151U, 0x6152U, 0x6153U, 0x6154U, 0x6155U, 0x6156U, 0x6157U, 0x6158U, 0x6159U, 0x615AU, 0x6161U, 0x6162U, 0x6163U, 0x6164U, 0x6165U, 0x6166U, 0x6167U, 0x6168U, 0x6169U, 0x616AU, 0x616BU, 0x616CU, 0x616DU, 0x616EU, 0x616FU, 0x6170U, 0x6171U, 0x6172U, 0x6173U, 0x6174U, 0x6175U, 0x6176U, 0x6177U, 0x6178U, 0x6179U, 0x617AU, 0x6130U, 0x6131U, 0x6132U, 0x6133U, 0x6134U, 0x6135U, 0x6136U, 0x6137U, 0x6138U, 0x6139U, 0x612BU, 0x612FU, 0x6241U, 0x6242U, 0x6243U, 0x6244U, 0x6245U, 0x6246U, 0x6247U, 0x6248U, 0x6249U, 0x624AU, 0x624BU, 0x624CU, 0x624DU, 0x624EU, 0x624FU, 0x6250U, 0x6251U, 0x6252U, 0x6253U, 0x6254U, 0x6255U, 0x6256U, 0x6257U, 0x6258U, 0x6259U, 0x625AU, 0x6261U, 0x6262U, 0x6263U, 0x6264U, 0x6265U, 0x6266U, 0x6267U, 0x6268U, 0x6269U, 0x626AU, 0x626BU, 0x626CU, 0x626DU, 0x626EU, 0x626FU, 0x6270U, 0x6271U, 0x6272U, 0x6273U, 0x6274U, 0x6275U, 0x6276U, 0x6277U, 0x6278U, 0x6279U, 0x627AU, 0x6230U, 0x6231U, 0x6232U, 0x6233U, 0x6234U, 0x6235U, 0x6236U, 0x6237U, 0x6238U, 0x6239U, 0x622BU, 0x622FU, 0x6341U, 0x6342U, 0x6343U, 0x6344U, 0x6345U, 0x6346U, 0x6347U, 0x6348U, 0x6349U, 0x634AU, 0x634BU, 0x634CU, 0x634DU, 0x634EU, 0x634FU, 0x6350U, 0x6351U, 0x6352U, 0x6353U, 0x6354U, 0x6355U, 0x6356U, 0x6357U, 0x6358U, 0x6359U, 0x635AU, 0x6361U, 0x6362U, 0x6363U, 0x6364U, 0x6365U, 0x6366U, 0x6367U, 0x6368U, 0x6369U, 0x636AU, 0x636BU, 0x636CU, 0x636DU, 0x636EU, 0x636FU, 0x6370U, 0x6371U, 0x6372U, 0x6373U, 0x6374U, 0x6375U, 0x6376U, 0x6377U, 0x6378U, 0x6379U, 0x637AU, 0x6330U, 0x6331U, 0x6332U, 0x6333U, 0x6334U, 0x6335U, 0x6336U, 0x6337U, 0x6338U, 0x6339U, 0x632BU, 0x632FU, 0x6441U, 0x6442U, 0x6443U, 0x6444U, 0x6445U, 0x6446U, 0x6447U, 0x6448U, 0x6449U, 0x644AU, 0x644BU, 0x644CU, 0x644DU, 0x644EU, 0x644FU, 0x6450U, 0x6451U, 0x6452U, 0x6453U, 0x6454U, 0x6455U, 0x6456U, 0x6457U, 0x6458U, 0x6459U, 0x645AU, 0x6461U, 0x6462U, 0x6463U, 0x6464U, 0x6465U, 0x6466U, 0x6467U, 0x6468U, 0x6469U, 0x646AU, 0x646BU, 0x646CU, 0x646DU, 0x646EU, 0x646FU, 0x6470U, 0x6471U, 0x6472U, 0x6473U, 0x6474U, 0x6475U, 0x6476U, 0x6477U, 0x6478U, 0x6479U, 0x647AU, 0x6430U, 0x6431U, 0x6432U, 0x6433U, 0x6434U, 0x6435U, 0x6436U, 0x6437U, 0x6438U, 0x6439U, 0x642BU, 0x642FU, 0x6541U, 0x6542U, 0x6543U, 0x6544U, 0x6545U, 0x6546U, 0x6547U, 0x6548U, 0x6549U, 0x654AU, 0x654BU, 0x654CU, 0x654DU, 0x654EU, 0x654FU, 0x6550U, 0x6551U, 0x6552U, 0x6553U, 0x6554U, 0x6555U, 0x6556U, 0x6557U, 0x6558U, 0x6559U, 0x655AU, 0x6561U, 0x6562U, 0x6563U, 0x6564U, 0x6565U, 0x6566U, 0x6567U, 0x6568U, 0x6569U, 0x656AU, 0x656BU, 0x656CU, 0x656DU, 0x656EU, 0x656FU, 0x6570U, 0x6571U, 0x6572U, 0x6573U, 0x6574U, 0x6575U, 0x6576U, 0x6577U, 0x6578U, 0x6579U, 0x657AU, 0x6530U, 0x6531U, 0x6532U, 0x6533U, 0x6534U, 0x6535U, 0x6536U, 0x6537U, 0x6538U, 0x6539U, 0x652BU, 0x652FU, 0x6641U, 0x6642U, 0x6643U, 0x6644U, 0x6645U, 0x6646U, 0x6647U, 0x6648U, 0x6649U, 0x664AU, 0x664BU, 0x664CU, 0x664DU, 0x664EU, 0x664FU, 0x6650U, 0x6651U, 0x6652U, 0x6653U, 0x6654U, 0x6655U, 0x6656U, 0x6657U, 0x6658U, 0x6659U, 0x665AU, 0x6661U, 0x6662U, 0x6663U, 0x6664U, 0x6665U, 0x6666U, 0x6667U, 0x6668U, 0x6669U, 0x666AU, 0x666BU, 0x666CU, 0x666DU, 0x666EU, 0x666FU, 0x6670U, 0x6671U, 0x6672U, 0x6673U, 0x6674U, 0x6675U, 0x6676U, 0x6677U, 0x6678U, 0x6679U, 0x667AU, 0x6630U, 0x6631U, 0x6632U, 0x6633U, 0x6634U, 0x6635U, 0x6636U, 0x6637U, 0x6638U, 0x6639U, 0x662BU, 0x662FU, 0x6741U, 0x6742U, 0x6743U, 0x6744U, 0x6745U, 0x6746U, 0x6747U, 0x6748U, 0x6749U, 0x674AU, 0x674BU, 0x674CU, 0x674DU, 0x674EU, 0x674FU, 0x6750U, 0x6751U, 0x6752U, 0x6753U, 0x6754U, 0x6755U, 0x6756U, 0x6757U, 0x6758U, 0x6759U, 0x675AU, 0x6761U, 0x6762U, 0x6763U, 0x6764U, 0x6765U, 0x6766U, 0x6767U, 0x6768U, 0x6769U, 0x676AU, 0x676BU, 0x676CU, 0x676DU, 0x676EU, 0x676FU, 0x6770U, 0x6771U, 0x6772U, 0x6773U, 0x6774U, 0x6775U, 0x6776U, 0x6777U, 0x6778U, 0x6779U, 0x677AU, 0x6730U, 0x6731U, 0x6732U, 0x6733U, 0x6734U, 0x6735U, 0x6736U, 0x6737U, 0x6738U, 0x6739U, 0x672BU, 0x672FU, 0x6841U, 0x6842U, 0x6843U, 0x6844U, 0x6845U, 0x6846U, 0x6847U, 0x6848U, 0x6849U, 0x684AU, 0x684BU, 0x684CU, 0x684DU, 0x684EU, 0x684FU, 0x6850U, 0x6851U, 0x6852U, 0x6853U, 0x6854U, 0x6855U, 0x6856U, 0x6857U, 0x6858U, 0x6859U, 0x685AU, 0x6861U, 0x6862U, 0x6863U, 0x6864U, 0x6865U, 0x6866U, 0x6867U, 0x6868U, 0x6869U, 0x686AU, 0x686BU, 0x686CU, 0x686DU, 0x686EU, 0x686FU, 0x6870U, 0x6871U, 0x6872U, 0x6873U, 0x6874U, 0x6875U, 0x6876U, 0x6877U, 0x6878U, 0x6879U, 0x687AU, 0x6830U, 0x6831U, 0x6832U, 0x6833U, 0x6834U, 0x6835U, 0x6836U, 0x6837U, 0x6838U, 0x6839U, 0x682BU, 0x682FU, 0x6941U, 0x6942U, 0x6943U, 0x6944U, 0x6945U, 0x6946U, 0x6947U, 0x6948U, 0x6949U, 0x694AU, 0x694BU, 0x694CU, 0x694DU, 0x694EU, 0x694FU, 0x6950U, 0x6951U, 0x6952U, 0x6953U, 0x6954U, 0x6955U, 0x6956U, 0x6957U, 0x6958U, 0x6959U, 0x695AU, 0x6961U, 0x6962U, 0x6963U, 0x6964U, 0x6965U, 0x6966U, 0x6967U, 0x6968U, 0x6969U, 0x696AU, 0x696BU, 0x696CU, 0x696DU, 0x696EU, 0x696FU, 0x6970U, 0x6971U, 0x6972U, 0x6973U, 0x6974U, 0x6975U, 0x6976U, 0x6977U, 0x6978U, 0x6979U, 0x697AU, 0x6930U, 0x6931U, 0x6932U, 0x6933U, 0x6934U, 0x6935U, 0x6936U, 0x6937U, 0x6938U, 0x6939U, 0x692BU, 0x692FU, 0x6A41U, 0x6A42U, 0x6A43U, 0x6A44U, 0x6A45U, 0x6A46U, 0x6A47U, 0x6A48U, 0x6A49U, 0x6A4AU, 0x6A4BU, 0x6A4CU, 0x6A4DU, 0x6A4EU, 0x6A4FU, 0x6A50U, 0x6A51U, 0x6A52U, 0x6A53U, 0x6A54U, 0x6A55U, 0x6A56U, 0x6A57U, 0x6A58U, 0x6A59U, 0x6A5AU, 0x6A61U, 0x6A62U, 0x6A63U, 0x6A64U, 0x6A65U, 0x6A66U, 0x6A67U, 0x6A68U, 0x6A69U, 0x6A6AU, 0x6A6BU, 0x6A6CU, 0x6A6DU, 0x6A6EU, 0x6A6FU, 0x6A70U, 0x6A71U, 0x6A72U, 0x6A73U, 0x6A74U, 0x6A75U, 0x6A76U, 0x6A77U, 0x6A78U, 0x6A79U, 0x6A7AU, 0x6A30U, 0x6A31U, 0x6A32U, 0x6A33U, 0x6A34U, 0x6A35U, 0x6A36U, 0x6A37U, 0x6A38U, 0x6A39U, 0x6A2BU, 0x6A2FU, 0x6B41U, 0x6B42U, 0x6B43U, 0x6B44U, 0x6B45U, 0x6B46U, 0x6B47U, 0x6B48U, 0x6B49U, 0x6B4AU, 0x6B4BU, 0x6B4CU, 0x6B4DU, 0x6B4EU, 0x6B4FU, 0x6B50U, 0x6B51U, 0x6B52U, 0x6B53U, 0x6B54U, 0x6B55U, 0x6B56U, 0x6B57U, 0x6B58U, 0x6B59U, 0x6B5AU, 0x6B61U, 0x6B62U, 0x6B63U, 0x6B64U, 0x6B65U, 0x6B66U, 0x6B67U, 0x6B68U, 0x6B69U, 0x6B6AU, 0x6B6BU, 0x6B6CU, 0x6B6DU, 0x6B6EU, 0x6B6FU, 0x6B70U, 0x6B71U, 0x6B72U, 0x6B73U, 0x6B74U, 0x6B75U, 0x6B76U, 0x6B77U, 0x6B78U, 0x6B79U, 0x6B7AU, 0x6B30U, 0x6B31U, 0x6B32U, 0x6B33U, 0x6B34U, 0x6B35U, 0x6B36U, 0x6B37U, 0x6B38U, 0x6B39U, 0x6B2BU, 0x6B2FU, 0x6C41U, 0x6C42U, 0x6C43U, 0x6C44U, 0x6C45U, 0x6C46U, 0x6C47U, 0x6C48U, 0x6C49U, 0x6C4AU, 0x6C4BU, 0x6C4CU, 0x6C4DU, 0x6C4EU, 0x6C4FU, 0x6C50U, 0x6C51U, 0x6C52U, 0x6C53U, 0x6C54U, 0x6C55U, 0x6C56U, 0x6C57U, 0x6C58U, 0x6C59U, 0x6C5AU, 0x6C61U, 0x6C62U, 0x6C63U, 0x6C64U, 0x6C65U, 0x6C66U, 0x6C67U, 0x6C68U, 0x6C69U, 0x6C6AU, 0x6C6BU, 0x6C6CU, 0x6C6DU, 0x6C6EU, 0x6C6FU, 0x6C70U, 0x6C71U, 0x6C72U, 0x6C73U, 0x6C74U, 0x6C75U, 0x6C76U, 0x6C77U, 0x6C78U, 0x6C79U, 0x6C7AU, 0x6C30U, 0x6C31U, 0x6C32U, 0x6C33U, 0x6C34U, 0x6C35U, 0x6C36U, 0x6C37U, 0x6C38U, 0x6C39U, 0x6C2BU, 0x6C2FU, 0x6D41U, 0x6D42U, 0x6D43U, 0x6D44U, 0x6D45U, 0x6D46U, 0x6D47U, 0x6D48U, 0x6D49U, 0x6D4AU, 0x6D4BU, 0x6D4CU, 0x6D4DU, 0x6D4EU, 0x6D4FU, 0x6D50U, 0x6D51U, 0x6D52U, 0x6D53U, 0x6D54U, 0x6D55U, 0x6D56U, 0x6D57U, 0x6D58U, 0x6D59U, 0x6D5AU, 0x6D61U, 0x6D62U, 0x6D63U, 0x6D64U, 0x6D65U, 0x6D66U, 0x6D67U, 0x6D68U, 0x6D69U, 0x6D6AU, 0x6D6BU, 0x6D6CU, 0x6D6DU, 0x6D6EU, 0x6D6FU, 0x6D70U, 0x6D71U, 0x6D72U, 0x6D73U, 0x6D74U, 0x6D75U, 0x6D76U, 0x6D77U, 0x6D78U, 0x6D79U, 0x6D7AU, 0x6D30U, 0x6D31U, 0x6D32U, 0x6D33U, 0x6D34U, 0x6D35U, 0x6D36U, 0x6D37U, 0x6D38U, 0x6D39U, 0x6D2BU, 0x6D2FU, 0x6E41U, 0x6E42U, 0x6E43U, 0x6E44U, 0x6E45U, 0x6E46U, 0x6E47U, 0x6E48U, 0x6E49U, 0x6E4AU, 0x6E4BU, 0x6E4CU, 0x6E4DU, 0x6E4EU, 0x6E4FU, 0x6E50U, 0x6E51U, 0x6E52U, 0x6E53U, 0x6E54U, 0x6E55U, 0x6E56U, 0x6E57U, 0x6E58U, 0x6E59U, 0x6E5AU, 0x6E61U, 0x6E62U, 0x6E63U, 0x6E64U, 0x6E65U, 0x6E66U, 0x6E67U, 0x6E68U, 0x6E69U, 0x6E6AU, 0x6E6BU, 0x6E6CU, 0x6E6DU, 0x6E6EU, 0x6E6FU, 0x6E70U, 0x6E71U, 0x6E72U, 0x6E73U, 0x6E74U, 0x6E75U, 0x6E76U, 0x6E77U, 0x6E78U, 0x6E79U, 0x6E7AU, 0x6E30U, 0x6E31U, 0x6E32U, 0x6E33U, 0x6E34U, 0x6E35U, 0x6E36U, 0x6E37U, 0x6E38U, 0x6E39U, 0x6E2BU, 0x6E2FU, 0x6F41U, 0x6F42U, 0x6F43U, 0x6F44U, 0x6F45U, 0x6F46U, 0x6F47U, 0x6F48U, 0x6F49U, 0x6F4AU, 0x6F4BU, 0x6F4CU, 0x6F4DU, 0x6F4EU, 0x6F4FU, 0x6F50U, 0x6F51U, 0x6F52U, 0x6F53U, 0x6F54U, 0x6F55U, 0x6F56U, 0x6F57U, 0x6F58U, 0x6F59U, 0x6F5AU, 0x6F61U, 0x6F62U, 0x6F63U, 0x6F64U, 0x6F65U, 0x6F66U, 0x6F67U, 0x6F68U, 0x6F69U, 0x6F6AU, 0x6F6BU, 0x6F6CU, 0x6F6DU, 0x6F6EU, 0x6F6FU, 0x6F70U, 0x6F71U, 0x6F72U, 0x6F73U, 0x6F74U, 0x6F75U, 0x6F76U, 0x6F77U, 0x6F78U, 0x6F79U, 0x6F7AU, 0x6F30U, 0x6F31U, 0x6F32U, 0x6F33U, 0x6F34U, 0x6F35U, 0x6F36U, 0x6F37U, 0x6F38U, 0x6F39U, 0x6F2BU, 0x6F2FU, 0x7041U, 0x7042U, 0x7043U, 0x7044U, 0x7045U, 0x7046U, 0x7047U, 0x7048U, 0x7049U, 0x704AU, 0x704BU, 0x704CU, 0x704DU, 0x704EU, 0x704FU, 0x7050U, 0x7051U, 0x7052U, 0x7053U, 0x7054U, 0x7055U, 0x7056U, 0x7057U, 0x7058U, 0x7059U, 0x705AU, 0x7061U, 0x7062U, 0x7063U, 0x7064U, 0x7065U, 0x7066U, 0x7067U, 0x7068U, 0x7069U, 0x706AU, 0x706BU, 0x706CU, 0x706DU, 0x706EU, 0x706FU, 0x7070U, 0x7071U, 0x7072U, 0x7073U, 0x7074U, 0x7075U, 0x7076U, 0x7077U, 0x7078U, 0x7079U, 0x707AU, 0x7030U, 0x7031U, 0x7032U, 0x7033U, 0x7034U, 0x7035U, 0x7036U, 0x7037U, 0x7038U, 0x7039U, 0x702BU, 0x702FU, 0x7141U, 0x7142U, 0x7143U, 0x7144U, 0x7145U, 0x7146U, 0x7147U, 0x7148U, 0x7149U, 0x714AU, 0x714BU, 0x714CU, 0x714DU, 0x714EU, 0x714FU, 0x7150U, 0x7151U, 0x7152U, 0x7153U, 0x7154U, 0x7155U, 0x7156U, 0x7157U, 0x7158U, 0x7159U, 0x715AU, 0x7161U, 0x7162U, 0x7163U, 0x7164U, 0x7165U, 0x7166U, 0x7167U, 0x7168U, 0x7169U, 0x716AU, 0x716BU, 0x716CU, 0x716DU, 0x716EU, 0x716FU, 0x7170U, 0x7171U, 0x7172U, 0x7173U, 0x7174U, 0x7175U, 0x7176U, 0x7177U, 0x7178U, 0x7179U, 0x717AU, 0x7130U, 0x7131U, 0x7132U, 0x7133U, 0x7134U, 0x7135U, 0x7136U, 0x7137U, 0x7138U, 0x7139U, 0x712BU, 0x712FU, 0x7241U, 0x7242U, 0x7243U, 0x7244U, 0x7245U, 0x7246U, 0x7247U, 0x7248U, 0x7249U, 0x724AU, 0x724BU, 0x724CU, 0x724DU, 0x724EU, 0x724FU, 0x7250U, 0x7251U, 0x7252U, 0x7253U, 0x7254U, 0x7255U, 0x7256U, 0x7257U, 0x7258U, 0x7259U, 0x725AU, 0x7261U, 0x7262U, 0x7263U, 0x7264U, 0x7265U, 0x7266U, 0x7267U, 0x7268U, 0x7269U, 0x726AU, 0x726BU, 0x726CU, 0x726DU, 0x726EU, 0x726FU, 0x7270U, 0x7271U, 0x7272U, 0x7273U, 0x7274U, 0x7275U, 0x7276U, 0x7277U, 0x7278U, 0x7279U, 0x727AU, 0x7230U, 0x7231U, 0x7232U, 0x7233U, 0x7234U, 0x7235U, 0x7236U, 0x7237U, 0x7238U, 0x7239U, 0x722BU, 0x722FU, 0x7341U, 0x7342U, 0x7343U, 0x7344U, 0x7345U, 0x7346U, 0x7347U, 0x7348U, 0x7349U, 0x734AU, 0x734BU, 0x734CU, 0x734DU, 0x734EU, 0x734FU, 0x7350U, 0x7351U, 0x7352U, 0x7353U, 0x7354U, 0x7355U, 0x7356U, 0x7357U, 0x7358U, 0x7359U, 0x735AU, 0x7361U, 0x7362U, 0x7363U, 0x7364U, 0x7365U, 0x7366U, 0x7367U, 0x7368U, 0x7369U, 0x736AU, 0x736BU, 0x736CU, 0x736DU, 0x736EU, 0x736FU, 0x7370U, 0x7371U, 0x7372U, 0x7373U, 0x7374U, 0x7375U, 0x7376U, 0x7377U, 0x7378U, 0x7379U, 0x737AU, 0x7330U, 0x7331U, 0x7332U, 0x7333U, 0x7334U, 0x7335U, 0x7336U, 0x7337U, 0x7338U, 0x7339U, 0x732BU, 0x732FU, 0x7441U, 0x7442U, 0x7443U, 0x7444U, 0x7445U, 0x7446U, 0x7447U, 0x7448U, 0x7449U, 0x744AU, 0x744BU, 0x744CU, 0x744DU, 0x744EU, 0x744FU, 0x7450U, 0x7451U, 0x7452U, 0x7453U, 0x7454U, 0x7455U, 0x7456U, 0x7457U, 0x7458U, 0x7459U, 0x745AU, 0x7461U, 0x7462U, 0x7463U, 0x7464U, 0x7465U, 0x7466U, 0x7467U, 0x7468U, 0x7469U, 0x746AU, 0x746BU, 0x746CU, 0x746DU, 0x746EU, 0x746FU, 0x7470U, 0x7471U, 0x7472U, 0x7473U, 0x7474U, 0x7475U, 0x7476U, 0x7477U, 0x7478U, 0x7479U, 0x747AU, 0x7430U, 0x7431U, 0x7432U, 0x7433U, 0x7434U, 0x7435U, 0x7436U, 0x7437U, 0x7438U, 0x7439U, 0x742BU, 0x742FU, 0x7541U, 0x7542U, 0x7543U, 0x7544U, 0x7545U, 0x7546U, 0x7547U, 0x7548U, 0x7549U, 0x754AU, 0x754BU, 0x754CU, 0x754DU, 0x754EU, 0x754FU, 0x7550U, 0x7551U, 0x7552U, 0x7553U, 0x7554U, 0x7555U, 0x7556U, 0x7557U, 0x7558U, 0x7559U, 0x755AU, 0x7561U, 0x7562U, 0x7563U, 0x7564U, 0x7565U, 0x7566U, 0x7567U, 0x7568U, 0x7569U, 0x756AU, 0x756BU, 0x756CU, 0x756DU, 0x756EU, 0x756FU, 0x7570U, 0x7571U, 0x7572U, 0x7573U, 0x7574U, 0x7575U, 0x7576U, 0x7577U, 0x7578U, 0x7579U, 0x757AU, 0x7530U, 0x7531U, 0x7532U, 0x7533U, 0x7534U, 0x7535U, 0x7536U, 0x7537U, 0x7538U, 0x7539U, 0x752BU, 0x752FU, 0x7641U, 0x7642U, 0x7643U, 0x7644U, 0x7645U, 0x7646U, 0x7647U, 0x7648U, 0x7649U, 0x764AU, 0x764BU, 0x764CU, 0x764DU, 0x764EU, 0x764FU, 0x7650U, 0x7651U, 0x7652U, 0x7653U, 0x7654U, 0x7655U, 0x7656U, 0x7657U, 0x7658U, 0x7659U, 0x765AU, 0x7661U, 0x7662U, 0x7663U, 0x7664U, 0x7665U, 0x7666U, 0x7667U, 0x7668U, 0x7669U, 0x766AU, 0x766BU, 0x766CU, 0x766DU, 0x766EU, 0x766FU, 0x7670U, 0x7671U, 0x7672U, 0x7673U, 0x7674U, 0x7675U, 0x7676U, 0x7677U, 0x7678U, 0x7679U, 0x767AU, 0x7630U, 0x7631U, 0x7632U, 0x7633U, 0x7634U, 0x7635U, 0x7636U, 0x7637U, 0x7638U, 0x7639U, 0x762BU, 0x762FU, 0x7741U, 0x7742U, 0x7743U, 0x7744U, 0x7745U, 0x7746U, 0x7747U, 0x7748U, 0x7749U, 0x774AU, 0x774BU, 0x774CU, 0x774DU, 0x774EU, 0x774FU, 0x7750U, 0x7751U, 0x7752U, 0x7753U, 0x7754U, 0x7755U, 0x7756U, 0x7757U, 0x7758U, 0x7759U, 0x775AU, 0x7761U, 0x7762U, 0x7763U, 0x7764U, 0x7765U, 0x7766U, 0x7767U, 0x7768U, 0x7769U, 0x776AU, 0x776BU, 0x776CU, 0x776DU, 0x776EU, 0x776FU, 0x7770U, 0x7771U, 0x7772U, 0x7773U, 0x7774U, 0x7775U, 0x7776U, 0x7777U, 0x7778U, 0x7779U, 0x777AU, 0x7730U, 0x7731U, 0x7732U, 0x7733U, 0x7734U, 0x7735U, 0x7736U, 0x7737U, 0x7738U, 0x7739U, 0x772BU, 0x772FU, 0x7841U, 0x7842U, 0x7843U, 0x7844U, 0x7845U, 0x7846U, 0x7847U, 0x7848U, 0x7849U, 0x784AU, 0x784BU, 0x784CU, 0x784DU, 0x784EU, 0x784FU, 0x7850U, 0x7851U, 0x7852U, 0x7853U, 0x7854U, 0x7855U, 0x7856U, 0x7857U, 0x7858U, 0x7859U, 0x785AU, 0x7861U, 0x7862U, 0x7863U, 0x7864U, 0x7865U, 0x7866U, 0x7867U, 0x7868U, 0x7869U, 0x786AU, 0x786BU, 0x786CU, 0x786DU, 0x786EU, 0x786FU, 0x7870U, 0x7871U, 0x7872U, 0x7873U, 0x7874U, 0x7875U, 0x7876U, 0x7877U, 0x7878U, 0x7879U, 0x787AU, 0x7830U, 0x7831U, 0x7832U, 0x7833U, 0x7834U, 0x7835U, 0x7836U, 0x7837U, 0x7838U, 0x7839U, 0x782BU, 0x782FU, 0x7941U, 0x7942U, 0x7943U, 0x7944U, 0x7945U, 0x7946U, 0x7947U, 0x7948U, 0x7949U, 0x794AU, 0x794BU, 0x794CU, 0x794DU, 0x794EU, 0x794FU, 0x7950U, 0x7951U, 0x7952U, 0x7953U, 0x7954U, 0x7955U, 0x7956U, 0x7957U, 0x7958U, 0x7959U, 0x795AU, 0x7961U, 0x7962U, 0x7963U, 0x7964U, 0x7965U, 0x7966U, 0x7967U, 0x7968U, 0x7969U, 0x796AU, 0x796BU, 0x796CU, 0x796DU, 0x796EU, 0x796FU, 0x7970U, 0x7971U, 0x7972U, 0x7973U, 0x7974U, 0x7975U, 0x7976U, 0x7977U, 0x7978U, 0x7979U, 0x797AU, 0x7930U, 0x7931U, 0x7932U, 0x7933U, 0x7934U, 0x7935U, 0x7936U, 0x7937U, 0x7938U, 0x7939U, 0x792BU, 0x792FU, 0x7A41U, 0x7A42U, 0x7A43U, 0x7A44U, 0x7A45U, 0x7A46U, 0x7A47U, 0x7A48U, 0x7A49U, 0x7A4AU, 0x7A4BU, 0x7A4CU, 0x7A4DU, 0x7A4EU, 0x7A4FU, 0x7A50U, 0x7A51U, 0x7A52U, 0x7A53U, 0x7A54U, 0x7A55U, 0x7A56U, 0x7A57U, 0x7A58U, 0x7A59U, 0x7A5AU, 0x7A61U, 0x7A62U, 0x7A63U, 0x7A64U, 0x7A65U, 0x7A66U, 0x7A67U, 0x7A68U, 0x7A69U, 0x7A6AU, 0x7A6BU, 0x7A6CU, 0x7A6DU, 0x7A6EU, 0x7A6FU, 0x7A70U, 0x7A71U, 0x7A72U, 0x7A73U, 0x7A74U, 0x7A75U, 0x7A76U, 0x7A77U, 0x7A78U, 0x7A79U, 0x7A7AU, 0x7A30U, 0x7A31U, 0x7A32U, 0x7A33U, 0x7A34U, 0x7A35U, 0x7A36U, 0x7A37U, 0x7A38U, 0x7A39U, 0x7A2BU, 0x7A2FU, 0x3041U, 0x3042U, 0x3043U, 0x3044U, 0x3045U, 0x3046U, 0x3047U, 0x3048U, 0x3049U, 0x304AU, 0x304BU, 0x304CU, 0x304DU, 0x304EU, 0x304FU, 0x3050U, 0x3051U, 0x3052U, 0x3053U, 0x3054U, 0x3055U, 0x3056U, 0x3057U, 0x3058U, 0x3059U, 0x305AU, 0x3061U, 0x3062U, 0x3063U, 0x3064U, 0x3065U, 0x3066U, 0x3067U, 0x3068U, 0x3069U, 0x306AU, 0x306BU, 0x306CU, 0x306DU, 0x306EU, 0x306FU, 0x3070U, 0x3071U, 0x3072U, 0x3073U, 0x3074U, 0x3075U, 0x3076U, 0x3077U, 0x3078U, 0x3079U, 0x307AU, 0x3030U, 0x3031U, 0x3032U, 0x3033U, 0x3034U, 0x3035U, 0x3036U, 0x3037U, 0x3038U, 0x3039U, 0x302BU, 0x302FU, 0x3141U, 0x3142U, 0x3143U, 0x3144U, 0x3145U, 0x3146U, 0x3147U, 0x3148U, 0x3149U, 0x314AU, 0x314BU, 0x314CU, 0x314DU, 0x314EU, 0x314FU, 0x3150U, 0x3151U, 0x3152U, 0x3153U, 0x3154U, 0x3155U, 0x3156U, 0x3157U, 0x3158U, 0x3159U, 0x315AU, 0x3161U, 0x3162U, 0x3163U, 0x3164U, 0x3165U, 0x3166U, 0x3167U, 0x3168U, 0x3169U, 0x316AU, 0x316BU, 0x316CU, 0x316DU, 0x316EU, 0x316FU, 0x3170U, 0x3171U, 0x3172U, 0x3173U, 0x3174U, 0x3175U, 0x3176U, 0x3177U, 0x3178U, 0x3179U, 0x317AU, 0x3130U, 0x3131U, 0x3132U, 0x3133U, 0x3134U, 0x3135U, 0x3136U, 0x3137U, 0x3138U, 0x3139U, 0x312BU, 0x312FU, 0x3241U, 0x3242U, 0x3243U, 0x3244U, 0x3245U, 0x3246U, 0x3247U, 0x3248U, 0x3249U, 0x324AU, 0x324BU, 0x324CU, 0x324DU, 0x324EU, 0x324FU, 0x3250U, 0x3251U, 0x3252U, 0x3253U, 0x3254U, 0x3255U, 0x3256U, 0x3257U, 0x3258U, 0x3259U, 0x325AU, 0x3261U, 0x3262U, 0x3263U, 0x3264U, 0x3265U, 0x3266U, 0x3267U, 0x3268U, 0x3269U, 0x326AU, 0x326BU, 0x326CU, 0x326DU, 0x326EU, 0x326FU, 0x3270U, 0x3271U, 0x3272U, 0x3273U, 0x3274U, 0x3275U, 0x3276U, 0x3277U, 0x3278U, 0x3279U, 0x327AU, 0x3230U, 0x3231U, 0x3232U, 0x3233U, 0x3234U, 0x3235U, 0x3236U, 0x3237U, 0x3238U, 0x3239U, 0x322BU, 0x322FU, 0x3341U, 0x3342U, 0x3343U, 0x3344U, 0x3345U, 0x3346U, 0x3347U, 0x3348U, 0x3349U, 0x334AU, 0x334BU, 0x334CU, 0x334DU, 0x334EU, 0x334FU, 0x3350U, 0x3351U, 0x3352U, 0x3353U, 0x3354U, 0x3355U, 0x3356U, 0x3357U, 0x3358U, 0x3359U, 0x335AU, 0x3361U, 0x3362U, 0x3363U, 0x3364U, 0x3365U, 0x3366U, 0x3367U, 0x3368U, 0x3369U, 0x336AU, 0x336BU, 0x336CU, 0x336DU, 0x336EU, 0x336FU, 0x3370U, 0x3371U, 0x3372U, 0x3373U, 0x3374U, 0x3375U, 0x3376U, 0x3377U, 0x3378U, 0x3379U, 0x337AU, 0x3330U, 0x3331U, 0x3332U, 0x3333U, 0x3334U, 0x3335U, 0x3336U, 0x3337U, 0x3338U, 0x3339U, 0x332BU, 0x332FU, 0x3441U, 0x3442U, 0x3443U, 0x3444U, 0x3445U, 0x3446U, 0x3447U, 0x3448U, 0x3449U, 0x344AU, 0x344BU, 0x344CU, 0x344DU, 0x344EU, 0x344FU, 0x3450U, 0x3451U, 0x3452U, 0x3453U, 0x3454U, 0x3455U, 0x3456U, 0x3457U, 0x3458U, 0x3459U, 0x345AU, 0x3461U, 0x3462U, 0x3463U, 0x3464U, 0x3465U, 0x3466U, 0x3467U, 0x3468U, 0x3469U, 0x346AU, 0x346BU, 0x346CU, 0x346DU, 0x346EU, 0x346FU, 0x3470U, 0x3471U, 0x3472U, 0x3473U, 0x3474U, 0x3475U, 0x3476U, 0x3477U, 0x3478U, 0x3479U, 0x347AU, 0x3430U, 0x3431U, 0x3432U, 0x3433U, 0x3434U, 0x3435U, 0x3436U, 0x3437U, 0x3438U, 0x3439U, 0x342BU, 0x342FU, 0x3541U, 0x3542U, 0x3543U, 0x3544U, 0x3545U, 0x3546U, 0x3547U, 0x3548U, 0x3549U, 0x354AU, 0x354BU, 0x354CU, 0x354DU, 0x354EU, 0x354FU, 0x3550U, 0x3551U, 0x3552U, 0x3553U, 0x3554U, 0x3555U, 0x3556U, 0x3557U, 0x3558U, 0x3559U, 0x355AU, 0x3561U, 0x3562U, 0x3563U, 0x3564U, 0x3565U, 0x3566U, 0x3567U, 0x3568U, 0x3569U, 0x356AU, 0x356BU, 0x356CU, 0x356DU, 0x356EU, 0x356FU, 0x3570U, 0x3571U, 0x3572U, 0x3573U, 0x3574U, 0x3575U, 0x3576U, 0x3577U, 0x3578U, 0x3579U, 0x357AU, 0x3530U, 0x3531U, 0x3532U, 0x3533U, 0x3534U, 0x3535U, 0x3536U, 0x3537U, 0x3538U, 0x3539U, 0x352BU, 0x352FU, 0x3641U, 0x3642U, 0x3643U, 0x3644U, 0x3645U, 0x3646U, 0x3647U, 0x3648U, 0x3649U, 0x364AU, 0x364BU, 0x364CU, 0x364DU, 0x364EU, 0x364FU, 0x3650U, 0x3651U, 0x3652U, 0x3653U, 0x3654U, 0x3655U, 0x3656U, 0x3657U, 0x3658U, 0x3659U, 0x365AU, 0x3661U, 0x3662U, 0x3663U, 0x3664U, 0x3665U, 0x3666U, 0x3667U, 0x3668U, 0x3669U, 0x366AU, 0x366BU, 0x366CU, 0x366DU, 0x366EU, 0x366FU, 0x3670U, 0x3671U, 0x3672U, 0x3673U, 0x3674U, 0x3675U, 0x3676U, 0x3677U, 0x3678U, 0x3679U, 0x367AU, 0x3630U, 0x3631U, 0x3632U, 0x3633U, 0x3634U, 0x3635U, 0x3636U, 0x3637U, 0x3638U, 0x3639U, 0x362BU, 0x362FU, 0x3741U, 0x3742U, 0x3743U, 0x3744U, 0x3745U, 0x3746U, 0x3747U, 0x3748U, 0x3749U, 0x374AU, 0x374BU, 0x374CU, 0x374DU, 0x374EU, 0x374FU, 0x3750U, 0x3751U, 0x3752U, 0x3753U, 0x3754U, 0x3755U, 0x3756U, 0x3757U, 0x3758U, 0x3759U, 0x375AU, 0x3761U, 0x3762U, 0x3763U, 0x3764U, 0x3765U, 0x3766U, 0x3767U, 0x3768U, 0x3769U, 0x376AU, 0x376BU, 0x376CU, 0x376DU, 0x376EU, 0x376FU, 0x3770U, 0x3771U, 0x3772U, 0x3773U, 0x3774U, 0x3775U, 0x3776U, 0x3777U, 0x3778U, 0x3779U, 0x377AU, 0x3730U, 0x3731U, 0x3732U, 0x3733U, 0x3734U, 0x3735U, 0x3736U, 0x3737U, 0x3738U, 0x3739U, 0x372BU, 0x372FU, 0x3841U, 0x3842U, 0x3843U, 0x3844U, 0x3845U, 0x3846U, 0x3847U, 0x3848U, 0x3849U, 0x384AU, 0x384BU, 0x384CU, 0x384DU, 0x384EU, 0x384FU, 0x3850U, 0x3851U, 0x3852U, 0x3853U, 0x3854U, 0x3855U, 0x3856U, 0x3857U, 0x3858U, 0x3859U, 0x385AU, 0x3861U, 0x3862U, 0x3863U, 0x3864U, 0x3865U, 0x3866U, 0x3867U, 0x3868U, 0x3869U, 0x386AU, 0x386BU, 0x386CU, 0x386DU, 0x386EU, 0x386FU, 0x3870U, 0x3871U, 0x3872U, 0x3873U, 0x3874U, 0x3875U, 0x3876U, 0x3877U, 0x3878U, 0x3879U, 0x387AU, 0x3830U, 0x3831U, 0x3832U, 0x3833U, 0x3834U, 0x3835U, 0x3836U, 0x3837U, 0x3838U, 0x3839U, 0x382BU, 0x382FU, 0x3941U, 0x3942U, 0x3943U, 0x3944U, 0x3945U, 0x3946U, 0x3947U, 0x3948U, 0x3949U, 0x394AU, 0x394BU, 0x394CU, 0x394DU, 0x394EU, 0x394FU, 0x3950U, 0x3951U, 0x3952U, 0x3953U, 0x3954U, 0x3955U, 0x3956U, 0x3957U, 0x3958U, 0x3959U, 0x395AU, 0x3961U, 0x3962U, 0x3963U, 0x3964U, 0x3965U, 0x3966U, 0x3967U, 0x3968U, 0x3969U, 0x396AU, 0x396BU, 0x396CU, 0x396DU, 0x396EU, 0x396FU, 0x3970U, 0x3971U, 0x3972U, 0x3973U, 0x3974U, 0x3975U, 0x3976U, 0x3977U, 0x3978U, 0x3979U, 0x397AU, 0x3930U, 0x3931U, 0x3932U, 0x3933U, 0x3934U, 0x3935U, 0x3936U, 0x3937U, 0x3938U, 0x3939U, 0x392BU, 0x392FU, 0x2B41U, 0x2B42U, 0x2B43U, 0x2B44U, 0x2B45U, 0x2B46U, 0x2B47U, 0x2B48U, 0x2B49U, 0x2B4AU, 0x2B4BU, 0x2B4CU, 0x2B4DU, 0x2B4EU, 0x2B4FU, 0x2B50U, 0x2B51U, 0x2B52U, 0x2B53U, 0x2B54U, 0x2B55U, 0x2B56U, 0x2B57U, 0x2B58U, 0x2B59U, 0x2B5AU, 0x2B61U, 0x2B62U, 0x2B63U, 0x2B64U, 0x2B65U, 0x2B66U, 0x2B67U, 0x2B68U, 0x2B69U, 0x2B6AU, 0x2B6BU, 0x2B6CU, 0x2B6DU, 0x2B6EU, 0x2B6FU, 0x2B70U, 0x2B71U, 0x2B72U, 0x2B73U, 0x2B74U, 0x2B75U, 0x2B76U, 0x2B77U, 0x2B78U, 0x2B79U, 0x2B7AU, 0x2B30U, 0x2B31U, 0x2B32U, 0x2B33U, 0x2B34U, 0x2B35U, 0x2B36U, 0x2B37U, 0x2B38U, 0x2B39U, 0x2B2BU, 0x2B2FU, 0x2F41U, 0x2F42U, 0x2F43U, 0x2F44U, 0x2F45U, 0x2F46U, 0x2F47U, 0x2F48U, 0x2F49U, 0x2F4AU, 0x2F4BU, 0x2F4CU, 0x2F4DU, 0x2F4EU, 0x2F4FU, 0x2F50U, 0x2F51U, 0x2F52U, 0x2F53U, 0x2F54U, 0x2F55U, 0x2F56U, 0x2F57U, 0x2F58U, 0x2F59U, 0x2F5AU, 0x2F61U, 0x2F62U, 0x2F63U, 0x2F64U, 0x2F65U, 0x2F66U, 0x2F67U, 0x2F68U, 0x2F69U, 0x2F6AU, 0x2F6BU, 0x2F6CU, 0x2F6DU, 0x2F6EU, 0x2F6FU, 0x2F70U, 0x2F71U, 0x2F72U, 0x2F73U, 0x2F74U, 0x2F75U, 0x2F76U, 0x2F77U, 0x2F78U, 0x2F79U, 0x2F7AU, 0x2F30U, 0x2F31U, 0x2F32U, 0x2F33U, 0x2F34U, 0x2F35U, 0x2F36U, 0x2F37U, 0x2F38U, 0x2F39U, 0x2F2BU, 0x2F2FU, #endif };
2301_81045437/base64
lib/tables/table_enc_12bit.h
C
bsd
74,858
#!/usr/bin/python3 def tr(x): """Translate a 6-bit value to the Base64 alphabet.""" s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ + 'abcdefghijklmnopqrstuvwxyz' \ + '0123456789' \ + '+/' return ord(s[x]) def table(fn): """Generate a 12-bit lookup table.""" ret = [] for n in range(0, 2**12): pre = "\n\t" if n % 8 == 0 else " " pre = "\t" if n == 0 else pre ret.append("{}0x{:04X}U,".format(pre, fn(n))) return "".join(ret) def table_be(): """Generate a 12-bit big-endian lookup table.""" return table(lambda n: (tr(n & 0x3F) << 0) | (tr(n >> 6) << 8)) def table_le(): """Generate a 12-bit little-endian lookup table.""" return table(lambda n: (tr(n >> 6) << 0) | (tr(n & 0x3F) << 8)) def main(): """Entry point.""" lines = [ "#include <stdint.h>", "", "const uint16_t base64_table_enc_12bit[] = {", "#if BASE64_LITTLE_ENDIAN", table_le(), "#else", table_be(), "#endif", "};" ] for line in lines: print(line) if __name__ == "__main__": main()
2301_81045437/base64
lib/tables/table_enc_12bit.py
Python
bsd
1,124
/** * * Copyright 2005, 2006 Nick Galbreath -- nickg [at] modp [dot] com * Copyright 2017 Matthieu Darbois * All rights reserved. * * http://modp.com/release/base64 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /****************************/ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> static uint8_t b64chars[64] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; static uint8_t padchar = '='; static void printStart(void) { printf("#include <stdint.h>\n"); printf("#define CHAR62 '%c'\n", b64chars[62]); printf("#define CHAR63 '%c'\n", b64chars[63]); printf("#define CHARPAD '%c'\n", padchar); } static void clearDecodeTable(uint32_t* ary) { int i = 0; for (i = 0; i < 256; ++i) { ary[i] = 0xFFFFFFFF; } } /* dump uint32_t as hex digits */ void uint32_array_to_c_hex(const uint32_t* ary, size_t sz, const char* name) { size_t i = 0; printf("const uint32_t %s[%d] = {\n", name, (int)sz); for (;;) { printf("0x%08" PRIx32, ary[i]); ++i; if (i == sz) break; if (i % 6 == 0) { printf(",\n"); } else { printf(", "); } } printf("\n};\n"); } int main(int argc, char** argv) { uint32_t x; uint32_t i = 0; uint32_t ary[256]; /* over-ride standard alphabet */ if (argc == 2) { uint8_t* replacements = (uint8_t*)argv[1]; if (strlen((char*)replacements) != 3) { fprintf(stderr, "input must be a string of 3 characters '-', '.' or '_'\n"); exit(1); } fprintf(stderr, "fusing '%s' as replacements in base64 encoding\n", replacements); b64chars[62] = replacements[0]; b64chars[63] = replacements[1]; padchar = replacements[2]; } printStart(); printf("\n\n#if BASE64_LITTLE_ENDIAN\n"); printf("\n\n/* SPECIAL DECODE TABLES FOR LITTLE ENDIAN (INTEL) CPUS */\n\n"); clearDecodeTable(ary); for (i = 0; i < 64; ++i) { x = b64chars[i]; ary[x] = i << 2; } uint32_array_to_c_hex(ary, sizeof(ary) / sizeof(uint32_t), "base64_table_dec_32bit_d0"); printf("\n\n"); clearDecodeTable(ary); for (i = 0; i < 64; ++i) { x = b64chars[i]; ary[x] = ((i & 0x30) >> 4) | ((i & 0x0F) << 12); } uint32_array_to_c_hex(ary, sizeof(ary) / sizeof(uint32_t), "base64_table_dec_32bit_d1"); printf("\n\n"); clearDecodeTable(ary); for (i = 0; i < 64; ++i) { x = b64chars[i]; ary[x] = ((i & 0x03) << 22) | ((i & 0x3c) << 6); } uint32_array_to_c_hex(ary, sizeof(ary) / sizeof(uint32_t), "base64_table_dec_32bit_d2"); printf("\n\n"); clearDecodeTable(ary); for (i = 0; i < 64; ++i) { x = b64chars[i]; ary[x] = i << 16; } uint32_array_to_c_hex(ary, sizeof(ary) / sizeof(uint32_t), "base64_table_dec_32bit_d3"); printf("\n\n"); printf("#else\n"); printf("\n\n/* SPECIAL DECODE TABLES FOR BIG ENDIAN (IBM/MOTOROLA/SUN) CPUS */\n\n"); clearDecodeTable(ary); for (i = 0; i < 64; ++i) { x = b64chars[i]; ary[x] = i << 26; } uint32_array_to_c_hex(ary, sizeof(ary) / sizeof(uint32_t), "base64_table_dec_32bit_d0"); printf("\n\n"); clearDecodeTable(ary); for (i = 0; i < 64; ++i) { x = b64chars[i]; ary[x] = i << 20; } uint32_array_to_c_hex(ary, sizeof(ary) / sizeof(uint32_t), "base64_table_dec_32bit_d1"); printf("\n\n"); clearDecodeTable(ary); for (i = 0; i < 64; ++i) { x = b64chars[i]; ary[x] = i << 14; } uint32_array_to_c_hex(ary, sizeof(ary) / sizeof(uint32_t), "base64_table_dec_32bit_d2"); printf("\n\n"); clearDecodeTable(ary); for (i = 0; i < 64; ++i) { x = b64chars[i]; ary[x] = i << 8; } uint32_array_to_c_hex(ary, sizeof(ary) / sizeof(uint32_t), "base64_table_dec_32bit_d3"); printf("\n\n"); printf("#endif\n"); return 0; }
2301_81045437/base64
lib/tables/table_generator.c
C
bsd
5,158
#include "tables.h" const uint8_t base64_table_enc_6bit[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "+/"; // In the lookup table below, note that the value for '=' (character 61) is // 254, not 255. This character is used for in-band signaling of the end of // the datastream, and we will use that later. The characters A-Z, a-z, 0-9 // and + / are mapped to their "decoded" values. The other bytes all map to // the value 255, which flags them as "invalid input". const uint8_t base64_table_dec_8bit[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 0..15 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 16..31 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, // 32..47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 254, 255, 255, // 48..63 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 64..79 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, // 80..95 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 96..111 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255, // 112..127 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 128..143 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, }; #if BASE64_WORDSIZE >= 32 # include "table_dec_32bit.h" # include "table_enc_12bit.h" #endif
2301_81045437/base64
lib/tables/tables.c
C
bsd
2,051
#ifndef BASE64_TABLES_H #define BASE64_TABLES_H #include <stdint.h> #include "../env.h" // These tables are used by all codecs for fallback plain encoding/decoding: extern const uint8_t base64_table_enc_6bit[]; extern const uint8_t base64_table_dec_8bit[]; // These tables are used for the 32-bit and 64-bit generic decoders: #if BASE64_WORDSIZE >= 32 extern const uint32_t base64_table_dec_32bit_d0[]; extern const uint32_t base64_table_dec_32bit_d1[]; extern const uint32_t base64_table_dec_32bit_d2[]; extern const uint32_t base64_table_dec_32bit_d3[]; // This table is used by the 32 and 64-bit generic encoders: extern const uint16_t base64_table_enc_12bit[]; #endif #endif // BASE64_TABLES_H
2301_81045437/base64
lib/tables/tables.h
C
bsd
704
# Written in 2016 by Henrik Steffen Gaßmann henrik@gassmann.onl # # To the extent possible under law, the author(s) have dedicated all # copyright and related and neighboring rights to this software to the # public domain worldwide. This software is distributed without any warranty. # # You should have received a copy of the CC0 Public Domain Dedication # along with this software. If not, see # # http://creativecommons.org/publicdomain/zero/1.0/ # ######################################################################## function(add_base64_test TEST_NAME) unset(SRC_FILE) foreach(SRC_FILE ${ARGN}) list(APPEND SRC_FILES "${SRC_FILE}") endforeach() add_executable(${TEST_NAME} ${SRC_FILES}) target_link_libraries(${TEST_NAME} PRIVATE base64) add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME} ) install(TARGETS ${TEST_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR}) endfunction() add_base64_test(test_base64 codec_supported.c test_base64.c ) add_base64_test(benchmark codec_supported.c benchmark.c ) if(CMAKE_SYSTEM_NAME STREQUAL "Linux") target_link_libraries(benchmark PRIVATE rt) endif()
2301_81045437/base64
test/CMakeLists.txt
CMake
bsd
1,168
CFLAGS += -std=c99 -O3 -Wall -Wextra -pedantic -DBASE64_STATIC_DEFINE ifdef OPENMP CFLAGS += -fopenmp endif TARGET := $(shell $(CC) -dumpmachine) ifneq (, $(findstring darwin, $(TARGET))) BENCH_LDFLAGS= else ifneq (, $(findstring mingw, $(TARGET))) BENCH_LDFLAGS= else # default to linux, -lrt needed BENCH_LDFLAGS=-lrt endif .PHONY: clean test valgrind test: clean test_base64 benchmark ./test_base64 ./benchmark valgrind: clean test_base64 valgrind --error-exitcode=2 ./test_base64 test_base64: test_base64.c codec_supported.o ../lib/libbase64.o $(CC) $(CFLAGS) -o $@ $^ benchmark: benchmark.c codec_supported.o ../lib/libbase64.o $(CC) $(CFLAGS) -o $@ $^ $(BENCH_LDFLAGS) ../%: make -C .. $* %.o: %.c $(CC) $(CFLAGS) -o $@ -c $< clean: rm -f benchmark test_base64 *.o
2301_81045437/base64
test/Makefile
Makefile
bsd
798
// For clock_gettime(2): #ifndef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 199309L #endif // For CLOCK_REALTIME on FreeBSD: #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE 600 #endif // Standard cross-platform includes. #include <stdbool.h> #include <stdlib.h> #include <stdio.h> // Platform-specific includes. #if defined(_WIN32) || defined(_WIN64) # include <windows.h> # include <wincrypt.h> #else # include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> # include <unistd.h> # include <time.h> #endif #if defined(__MACH__) # include <mach/mach_time.h> #endif #include "../include/libbase64.h" #include "codec_supported.h" #define KB 1024 #define MB (1024 * KB) #define RANDOMDEV "/dev/urandom" struct buffers { char *reg; char *enc; size_t regsz; size_t encsz; }; // Define buffer sizes to test with: static struct bufsize { char *label; size_t len; int repeat; int batch; } sizes[] = { { "10 MB", MB * 10, 10, 1 }, { "1 MB", MB * 1, 10, 10 }, { "100 KB", KB * 100, 10, 100 }, { "10 KB", KB * 10, 100, 100 }, { "1 KB", KB * 1, 100, 1000 }, }; static inline float bytes_to_mb (size_t bytes) { return bytes / (float) MB; } static bool get_random_data (struct buffers *b, char **errmsg) { #if defined(_WIN32) || defined(_WIN64) HCRYPTPROV hProvider = 0; if (!CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { *errmsg = "Error: CryptAcquireContext"; return false; } if (!CryptGenRandom(hProvider, b->regsz, b->reg)) { CryptReleaseContext(hProvider, 0); *errmsg = "Error: CryptGenRandom"; return false; } if (!CryptReleaseContext(hProvider, 0)) { *errmsg = "Error: CryptReleaseContext"; return false; } return true; #else int fd; ssize_t nread; size_t total_read = 0; // Open random device for semi-random data: if ((fd = open(RANDOMDEV, O_RDONLY)) < 0) { *errmsg = "Cannot open " RANDOMDEV; return false; } printf("Filling buffer with %.1f MB of random data...\n", bytes_to_mb(b->regsz)); while (total_read < b->regsz) { if ((nread = read(fd, b->reg + total_read, b->regsz - total_read)) < 0) { *errmsg = "Read error"; close(fd); return false; } total_read += nread; } close(fd); return true; #endif } #if defined(__MACH__) typedef uint64_t base64_timespec; static void base64_gettime (base64_timespec *t) { *t = mach_absolute_time(); } static float timediff_sec (base64_timespec *start, base64_timespec *end) { uint64_t diff = *end - *start; mach_timebase_info_data_t tb = { 0, 0 }; mach_timebase_info(&tb); return (float)((diff * tb.numer) / tb.denom) / 1e9f; } #elif defined(_WIN32) || defined(_WIN64) typedef ULARGE_INTEGER base64_timespec; static void base64_gettime (base64_timespec *t) { FILETIME current_time_ft; GetSystemTimePreciseAsFileTime(&current_time_ft); t->LowPart = current_time_ft.dwLowDateTime; t->HighPart = current_time_ft.dwHighDateTime; } static float timediff_sec (base64_timespec *start, base64_timespec *end) { // Timer resolution is 100 nanoseconds (10^-7 sec). return (end->QuadPart - start->QuadPart) / 1e7f; } #else typedef struct timespec base64_timespec; static void base64_gettime (base64_timespec *t) { clock_gettime(CLOCK_REALTIME, t); } static float timediff_sec (base64_timespec *start, base64_timespec *end) { return (end->tv_sec - start->tv_sec) + (end->tv_nsec - start->tv_nsec) / 1e9f; } #endif static void codec_bench_enc (struct buffers *b, const struct bufsize *bs, const char *name, unsigned int flags) { float timediff, fastest = -1.0f; base64_timespec start, end; // Reset buffer size: b->regsz = bs->len; // Repeat benchmark a number of times for a fair test: for (int i = bs->repeat; i; i--) { // Timing loop, use batches to increase timer resolution: base64_gettime(&start); for (int j = bs->batch; j; j--) base64_encode(b->reg, b->regsz, b->enc, &b->encsz, flags); base64_gettime(&end); // Calculate average time of batch: timediff = timediff_sec(&start, &end) / bs->batch; // Update fastest time seen: if (fastest < 0.0f || timediff < fastest) fastest = timediff; } printf("%s\tencode\t%.02f MB/sec\n", name, bytes_to_mb(b->regsz) / fastest); } static void codec_bench_dec (struct buffers *b, const struct bufsize *bs, const char *name, unsigned int flags) { float timediff, fastest = -1.0f; base64_timespec start, end; // Reset buffer size: b->encsz = bs->len; // Repeat benchmark a number of times for a fair test: for (int i = bs->repeat; i; i--) { // Timing loop, use batches to increase timer resolution: base64_gettime(&start); for (int j = bs->batch; j; j--) base64_decode(b->enc, b->encsz, b->reg, &b->regsz, flags); base64_gettime(&end); // Calculate average time of batch: timediff = timediff_sec(&start, &end) / bs->batch; // Update fastest time seen: if (fastest < 0.0f || timediff < fastest) fastest = timediff; } printf("%s\tdecode\t%.02f MB/sec\n", name, bytes_to_mb(b->encsz) / fastest); } static void codec_bench (struct buffers *b, const struct bufsize *bs, const char *name, unsigned int flags) { codec_bench_enc(b, bs, name, flags); codec_bench_dec(b, bs, name, flags); } int main () { int ret = 0; char *errmsg = NULL; struct buffers b; // Set buffer sizes to largest buffer length: b.regsz = sizes[0].len; b.encsz = sizes[0].len * 5 / 3; // Allocate space for megabytes of random data: if ((b.reg = malloc(b.regsz)) == NULL) { errmsg = "Out of memory"; ret = 1; goto err0; } // Allocate space for encoded output: if ((b.enc = malloc(b.encsz)) == NULL) { errmsg = "Out of memory"; ret = 1; goto err1; } // Fill buffer with random data: if (get_random_data(&b, &errmsg) == false) { ret = 1; goto err2; } // Loop over all buffer sizes: for (size_t i = 0; i < sizeof(sizes) / sizeof(sizes[0]); i++) { printf("Testing with buffer size %s, fastest of %d * %d\n", sizes[i].label, sizes[i].repeat, sizes[i].batch); // Loop over all codecs: for (size_t j = 0; codecs[j]; j++) if (codec_supported(1 << j)) codec_bench(&b, &sizes[i], codecs[j], 1 << j); }; // Free memory: err2: free(b.enc); err1: free(b.reg); err0: if (errmsg) fputs(errmsg, stderr); return ret; }
2301_81045437/base64
test/benchmark.c
C
bsd
6,241
#!/bin/bash set -ve MACHINE=$(uname -m) export CC=gcc uname -a clang --version # make analyse ${CC} --version # make -C test valgrind for USE_ASSEMBLY in 0 1; do if [ "${MACHINE}" == "x86_64" ]; then export SSSE3_CFLAGS="-mssse3 -DBASE64_SSSE3_USE_ASM=${USE_ASSEMBLY}" export SSE41_CFLAGS="-msse4.1 -DBASE64_SSE41_USE_ASM=${USE_ASSEMBLY}" export SSE42_CFLAGS="-msse4.2 -DBASE64_SSE42_USE_ASM=${USE_ASSEMBLY}" export AVX_CFLAGS="-mavx -DBASE64_AVX_USE_ASM=${USE_ASSEMBLY}" export AVX2_CFLAGS="-mavx2 -DBASE64_AVX2_USE_ASM=${USE_ASSEMBLY}" # Temporarily disable AVX512; it is not available in CI yet. # export AVX512_CFLAGS="-mavx512vl -mavx512vbmi" elif [ "${MACHINE}" == "aarch64" ]; then export NEON64_CFLAGS="-march=armv8-a" elif [ "${MACHINE}" == "armv7l" ]; then export NEON32_CFLAGS="-march=armv7-a -mfloat-abi=hard -mfpu=neon" fi if [ ${USE_ASSEMBLY} -eq 0 ]; then echo "::group::analyze" make analyze echo "::endgroup::" fi echo "::group::valgrind (USE_ASSEMBLY=${USE_ASSEMBLY})" make clean make make -C test valgrind echo "::endgroup::" done
2301_81045437/base64
test/ci/analysis.sh
Shell
bsd
1,092
#!/bin/bash set -ve MACHINE=$(uname -m) if [ "${MACHINE}" == "x86_64" ]; then export SSSE3_CFLAGS=-mssse3 export SSE41_CFLAGS=-msse4.1 export SSE42_CFLAGS=-msse4.2 export AVX_CFLAGS=-mavx # no AVX2 or AVX512 on GHA macOS if [ "$(uname -s)" != "Darwin" ]; then export AVX2_CFLAGS=-mavx2 # Temporarily disable AVX512; it is not available in CI yet. # export AVX512_CFLAGS="-mavx512vl -mavx512vbmi" fi elif [ "${MACHINE}" == "aarch64" ]; then export NEON64_CFLAGS="-march=armv8-a" elif [ "${MACHINE}" == "armv7l" ]; then export NEON32_CFLAGS="-march=armv7-a -mfloat-abi=hard -mfpu=neon" fi if [ "${OPENMP:-}" == "0" ]; then unset OPENMP fi uname -a ${CC} --version make make -C test
2301_81045437/base64
test/ci/test.sh
Shell
bsd
700
#include <string.h> #include "../include/libbase64.h" static char *_codecs[] = { "AVX2" , "NEON32" , "NEON64" , "plain" , "SSSE3" , "SSE41" , "SSE42" , "AVX" , "AVX512" , NULL } ; char **codecs = _codecs; int codec_supported (int flags) { // Check if given codec is supported by trying to decode a test string: char *a = "aGVsbG8="; char b[10]; size_t outlen; return (base64_decode(a, strlen(a), b, &outlen, flags) != -1); }
2301_81045437/base64
test/codec_supported.c
C
bsd
435
extern char **codecs; int codec_supported (int flags);
2301_81045437/base64
test/codec_supported.h
C
bsd
56
static const char *moby_dick_plain = "Call me Ishmael. Some years ago--never mind how long precisely--having\n" "little or no money in my purse, and nothing particular to interest me on\n" "shore, I thought I would sail about a little and see the watery part of\n" "the world. It is a way I have of driving off the spleen and regulating\n" "the circulation. Whenever I find myself growing grim about the mouth;\n" "whenever it is a damp, drizzly November in my soul; whenever I find\n" "myself involuntarily pausing before coffin warehouses, and bringing up\n" "the rear of every funeral I meet; and especially whenever my hypos get\n" "such an upper hand of me, that it requires a strong moral principle to\n" "prevent me from deliberately stepping into the street, and methodically\n" "knocking people's hats off--then, I account it high time to get to sea\n" "as soon as I can. This is my substitute for pistol and ball. With a\n" "philosophical flourish Cato throws himself upon his sword; I quietly\n" "take to the ship. There is nothing surprising in this. If they but knew\n" "it, almost all men in their degree, some time or other, cherish very\n" "nearly the same feelings towards the ocean with me.\n"; static const char *moby_dick_base64 = "Q2FsbCBtZSBJc2htYWVsLiBTb21lIHllYXJzIGFnby0tbmV2ZXIgbWluZCBob3cgbG9uZ" "yBwcmVjaXNlbHktLWhhdmluZwpsaXR0bGUgb3Igbm8gbW9uZXkgaW4gbXkgcHVyc2UsIG" "FuZCBub3RoaW5nIHBhcnRpY3VsYXIgdG8gaW50ZXJlc3QgbWUgb24Kc2hvcmUsIEkgdGh" "vdWdodCBJIHdvdWxkIHNhaWwgYWJvdXQgYSBsaXR0bGUgYW5kIHNlZSB0aGUgd2F0ZXJ5" "IHBhcnQgb2YKdGhlIHdvcmxkLiBJdCBpcyBhIHdheSBJIGhhdmUgb2YgZHJpdmluZyBvZ" "mYgdGhlIHNwbGVlbiBhbmQgcmVndWxhdGluZwp0aGUgY2lyY3VsYXRpb24uIFdoZW5ldm" "VyIEkgZmluZCBteXNlbGYgZ3Jvd2luZyBncmltIGFib3V0IHRoZSBtb3V0aDsKd2hlbmV" "2ZXIgaXQgaXMgYSBkYW1wLCBkcml6emx5IE5vdmVtYmVyIGluIG15IHNvdWw7IHdoZW5l" "dmVyIEkgZmluZApteXNlbGYgaW52b2x1bnRhcmlseSBwYXVzaW5nIGJlZm9yZSBjb2Zma" "W4gd2FyZWhvdXNlcywgYW5kIGJyaW5naW5nIHVwCnRoZSByZWFyIG9mIGV2ZXJ5IGZ1bm" "VyYWwgSSBtZWV0OyBhbmQgZXNwZWNpYWxseSB3aGVuZXZlciBteSBoeXBvcyBnZXQKc3V" "jaCBhbiB1cHBlciBoYW5kIG9mIG1lLCB0aGF0IGl0IHJlcXVpcmVzIGEgc3Ryb25nIG1v" "cmFsIHByaW5jaXBsZSB0bwpwcmV2ZW50IG1lIGZyb20gZGVsaWJlcmF0ZWx5IHN0ZXBwa" "W5nIGludG8gdGhlIHN0cmVldCwgYW5kIG1ldGhvZGljYWxseQprbm9ja2luZyBwZW9wbG" "UncyBoYXRzIG9mZi0tdGhlbiwgSSBhY2NvdW50IGl0IGhpZ2ggdGltZSB0byBnZXQgdG8" "gc2VhCmFzIHNvb24gYXMgSSBjYW4uIFRoaXMgaXMgbXkgc3Vic3RpdHV0ZSBmb3IgcGlz" "dG9sIGFuZCBiYWxsLiBXaXRoIGEKcGhpbG9zb3BoaWNhbCBmbG91cmlzaCBDYXRvIHRoc" "m93cyBoaW1zZWxmIHVwb24gaGlzIHN3b3JkOyBJIHF1aWV0bHkKdGFrZSB0byB0aGUgc2" "hpcC4gVGhlcmUgaXMgbm90aGluZyBzdXJwcmlzaW5nIGluIHRoaXMuIElmIHRoZXkgYnV" "0IGtuZXcKaXQsIGFsbW9zdCBhbGwgbWVuIGluIHRoZWlyIGRlZ3JlZSwgc29tZSB0aW1l" "IG9yIG90aGVyLCBjaGVyaXNoIHZlcnkKbmVhcmx5IHRoZSBzYW1lIGZlZWxpbmdzIHRvd" "2FyZHMgdGhlIG9jZWFuIHdpdGggbWUuCg==";
2301_81045437/base64
test/moby_dick.h
C
bsd
2,841
#include <stdbool.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include "../include/libbase64.h" #include "codec_supported.h" #include "moby_dick.h" static char out[2000]; static size_t outlen; static bool assert_enc (int flags, const char *src, const char *dst) { size_t srclen = strlen(src); size_t dstlen = strlen(dst); base64_encode(src, srclen, out, &outlen, flags); if (outlen != dstlen) { printf("FAIL: encoding of '%s': length expected %lu, got %lu\n", src, (unsigned long)dstlen, (unsigned long)outlen ); return true; } if (strncmp(dst, out, outlen) != 0) { out[outlen] = '\0'; printf("FAIL: encoding of '%s': expected output '%s', got '%s'\n", src, dst, out); return true; } return false; } static bool assert_dec (int flags, const char *src, const char *dst) { size_t srclen = strlen(src); size_t dstlen = strlen(dst); if (!base64_decode(src, srclen, out, &outlen, flags)) { printf("FAIL: decoding of '%s': decoding error\n", src); return true; } if (outlen != dstlen) { printf("FAIL: encoding of '%s': " "length expected %lu, got %lu\n", src, (unsigned long)dstlen, (unsigned long)outlen ); return true; } if (strncmp(dst, out, outlen) != 0) { out[outlen] = '\0'; printf("FAIL: decoding of '%s': expected output '%s', got '%s'\n", src, dst, out); return true; } return false; } static int assert_roundtrip (int flags, const char *src) { char tmp[1500]; size_t tmplen; size_t srclen = strlen(src); // Encode the input into global buffer: base64_encode(src, srclen, out, &outlen, flags); // Decode the global buffer into local temp buffer: if (!base64_decode(out, outlen, tmp, &tmplen, flags)) { printf("FAIL: decoding of '%s': decoding error\n", out); return true; } // Check that 'src' is identical to 'tmp': if (srclen != tmplen) { printf("FAIL: roundtrip of '%s': " "length expected %lu, got %lu\n", src, (unsigned long)srclen, (unsigned long)tmplen ); return true; } if (strncmp(src, tmp, tmplen) != 0) { tmp[tmplen] = '\0'; printf("FAIL: roundtrip of '%s': got '%s'\n", src, tmp); return true; } return false; } static int test_char_table (int flags, bool use_malloc) { bool fail = false; char chr[256]; char enc[400], dec[400]; size_t enclen, declen; // Fill array with all characters 0..255: for (int i = 0; i < 256; i++) chr[i] = (unsigned char)i; // Loop, using each char as a starting position to increase test coverage: for (int i = 0; i < 256; i++) { size_t chrlen = 256 - i; char* src = &chr[i]; if (use_malloc) { src = malloc(chrlen); /* malloc/copy this so valgrind can find out-of-bound access */ if (src == NULL) { printf( "FAIL: encoding @ %d: allocation of %lu bytes failed\n", i, (unsigned long)chrlen ); fail = true; continue; } memcpy(src, &chr[i], chrlen); } base64_encode(src, chrlen, enc, &enclen, flags); if (use_malloc) { free(src); } if (!base64_decode(enc, enclen, dec, &declen, flags)) { printf("FAIL: decoding @ %d: decoding error\n", i); fail = true; continue; } if (declen != chrlen) { printf("FAIL: roundtrip @ %d: " "length expected %lu, got %lu\n", i, (unsigned long)chrlen, (unsigned long)declen ); fail = true; continue; } if (strncmp(&chr[i], dec, declen) != 0) { printf("FAIL: roundtrip @ %d: decoded output not same as input\n", i); fail = true; } } return fail; } static int test_streaming (int flags) { bool fail = false; char chr[256]; char ref[400], enc[400]; size_t reflen; struct base64_state state; // Fill array with all characters 0..255: for (int i = 0; i < 256; i++) chr[i] = (unsigned char)i; // Create reference base64 encoding: base64_encode(chr, 256, ref, &reflen, BASE64_FORCE_PLAIN); // Encode the table with various block sizes and compare to reference: for (size_t bs = 1; bs < 255; bs++) { size_t inpos = 0; size_t partlen = 0; size_t enclen = 0; base64_stream_encode_init(&state, flags); memset(enc, 0, 400); for (;;) { base64_stream_encode(&state, &chr[inpos], (inpos + bs > 256) ? 256 - inpos : bs, &enc[enclen], &partlen); enclen += partlen; if (inpos + bs > 256) { break; } inpos += bs; } base64_stream_encode_final(&state, &enc[enclen], &partlen); enclen += partlen; if (enclen != reflen) { printf("FAIL: stream encoding gave incorrect size: " "%lu instead of %lu\n", (unsigned long)enclen, (unsigned long)reflen ); fail = true; } if (strncmp(ref, enc, reflen) != 0) { printf("FAIL: stream encoding with blocksize %lu failed\n", (unsigned long)bs ); fail = true; } } // Decode the reference encoding with various block sizes and // compare to input char table: for (size_t bs = 1; bs < 255; bs++) { size_t inpos = 0; size_t partlen = 0; size_t enclen = 0; base64_stream_decode_init(&state, flags); memset(enc, 0, 400); while (base64_stream_decode(&state, &ref[inpos], (inpos + bs > reflen) ? reflen - inpos : bs, &enc[enclen], &partlen)) { enclen += partlen; inpos += bs; // Has the entire buffer been consumed? if (inpos >= 400) { break; } } if (enclen != 256) { printf("FAIL: stream decoding gave incorrect size: " "%lu instead of 255\n", (unsigned long)enclen ); fail = true; } if (strncmp(chr, enc, 256) != 0) { printf("FAIL: stream decoding with blocksize %lu failed\n", (unsigned long)bs ); fail = true; } } return fail; } static int test_invalid_dec_input (int flags) { // Subset of invalid characters to cover all ranges static const char invalid_set[] = { '\0', -1, '!', '-', ';', '_', '|' }; static const char* invalid_strings[] = { "Zm9vYg=", "Zm9vYg", "Zm9vY", "Zm9vYmF=Zm9v" }; bool fail = false; char chr[256]; char enc[400], dec[400]; size_t enclen, declen; // Fill array with all characters 0..255: for (int i = 0; i < 256; i++) chr[i] = (unsigned char)i; // Create reference base64 encoding: base64_encode(chr, 256, enc, &enclen, BASE64_FORCE_PLAIN); // Test invalid strings returns error. for (size_t i = 0U; i < sizeof(invalid_strings) / sizeof(invalid_strings[0]); ++i) { if (base64_decode(invalid_strings[i], strlen(invalid_strings[i]), dec, &declen, flags)) { printf("FAIL: decoding invalid input \"%s\": no decoding error\n", invalid_strings[i]); fail = true; } } // Loop, corrupting each char to increase test coverage: for (size_t c = 0U; c < sizeof(invalid_set); ++c) { for (size_t i = 0U; i < enclen; i++) { char backup = enc[i]; enc[i] = invalid_set[c]; if (base64_decode(enc, enclen, dec, &declen, flags)) { printf("FAIL: decoding invalid input @ %d: no decoding error\n", (int)i); fail = true; enc[i] = backup; continue; } enc[i] = backup; } } // Loop, corrupting two chars to increase test coverage: for (size_t c = 0U; c < sizeof(invalid_set); ++c) { for (size_t i = 0U; i < enclen - 2U; i++) { char backup = enc[i+0]; char backup2 = enc[i+2]; enc[i+0] = invalid_set[c]; enc[i+2] = invalid_set[c]; if (base64_decode(enc, enclen, dec, &declen, flags)) { printf("FAIL: decoding invalid input @ %d: no decoding error\n", (int)i); fail = true; enc[i+0] = backup; enc[i+2] = backup2; continue; } enc[i+0] = backup; enc[i+2] = backup2; } } return fail; } static int test_one_codec (const char *codec, int flags) { bool fail = false; printf("Codec %s:\n", codec); // Skip if this codec is not supported: if (!codec_supported(flags)) { puts(" skipping"); return false; } // Test vectors: struct { const char *in; const char *out; } vec[] = { // These are the test vectors from RFC4648: { "", "" }, { "f", "Zg==" }, { "fo", "Zm8=" }, { "foo", "Zm9v" }, { "foob", "Zm9vYg==" }, { "fooba", "Zm9vYmE=" }, { "foobar", "Zm9vYmFy" }, // The first paragraph from Moby Dick, // to test the SIMD codecs with larger blocksize: { moby_dick_plain, moby_dick_base64 }, }; for (size_t i = 0; i < sizeof(vec) / sizeof(vec[0]); i++) { // Encode plain string, check against output: fail |= assert_enc(flags, vec[i].in, vec[i].out); // Decode the output string, check if we get the input: fail |= assert_dec(flags, vec[i].out, vec[i].in); // Do a roundtrip on the inputs and the outputs: fail |= assert_roundtrip(flags, vec[i].in); fail |= assert_roundtrip(flags, vec[i].out); } fail |= test_char_table(flags, false); /* test with unaligned input buffer */ fail |= test_char_table(flags, true); /* test for out-of-bound input read */ fail |= test_streaming(flags); fail |= test_invalid_dec_input(flags); if (!fail) puts(" all tests passed."); return fail; } int main () { bool fail = false; // Loop over all codecs: for (size_t i = 0; codecs[i]; i++) { // Flags to invoke this codec: int codec_flags = (1 << i); // Test this codec, merge the results: fail |= test_one_codec(codecs[i], codec_flags); } return (fail) ? 1 : 0; }
2301_81045437/base64
test/test_base64.c
C
bsd
9,105
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Helper math functions to make my Verilog coding life easier. This // must be included INSIDE in the module/endmodule region, not // before. This has something to do with global function defintions in // the standard. // A Xilinx implementation of the base 2 logarithm. This is very // useful when assigning port widths based on parameters. function integer lg; input integer value; reg [31:0] shifted; integer res; begin if (value < 2) lg = value; else begin shifted = value-1; for (res=0; shifted>0; res=res+1) shifted = shifted>>1; lg = res; end end endfunction // Function to convert a fixed point number to a real function real fixed_to_real; input x, binary_point; real fixed_to_real; fixed_to_real = $itor(f)/2**binary_point; endfunction // Macro to pack a 2D array into a 1D vector based on some number of // items each with a specified width. // u_src: unpacked source // p_dst: packed destination (obviously must be a wire) // width: the width of one unpacked item // num_items: the number of items to be packed `define PACK(u_src, p_dest, width, num_items) \ generate\ for (genvar __pack_i = 0; __pack_i < (num_items); __pack_i = __pack_i + 1) begin\ assign p_dest[(width)*(__pack_i+1)-1:(width)*__pack_i] = u_src[__pack_i]; end\ endgenerate // Macro to unpack a 1D vector into a 2D array based on some number of // items wach with a specified width. // p_src: packed source // u_dst: unpacked destination (a wire) // width: the width of one unpacked item // num_items: the number of items to be unpacked `define UNPACK(p_src, u_dest, width, num_items) \ generate\ for (genvar __unpack_i = 0; __unpack_i < (num_items); __unpack_i = __unpack_i + 1) begin\ assign u_dest[__unpack_i] = p_src[(width)*(__unpack_i+1)-1:(width)*__unpack_i]; end\ endgenerate // Macro to generate a random variable of some width using the $random // function. This is obviously only suitable for testbenches... // f: register you want to assign a random value to every clock cycle // width: width of f // period: how often to change the random variable genvar __random_width_i; `define RANDOM_WIDTH(f, width, period) \ generate\ for (__random_width_i = 0; __random_width_i < width>>5; __random_width_i = __random_width_i + 1)\ always #period f[32*(__random_width_i+1)-1:32*__random_width_i] = $random;\ always #period f[width-1:32*(width>>5)] = $random;\ endgenerate // Macro to generate a random varible of some width that changes with // some delay after a clock using the $random function. This is // intended to be used to create variable input data that does not // violate setup/hold times (i.e. you want data that changes HOLD_TIME // after clock rising edge). // f: output // width: width of f // clk: clock // delay: time after clk posedge when f changes genvar __random_width_clk_i; `define RANDOM_WIDTH_OFFSET(f, width, clk, delay) \ generate\ for (__random_width_clk_i = 0; __random_width_clk_i < width >> 5; __random_width_clk_i = __random_width_clk_i + 1)\ always @ (posedge clk)\ #delay f[32*(__random_width_clk_i+1)-1:32*__random_width_clk_i] = $random;\ always @ (posedge clk)\ #delay f[width-1:32*(width>>5)] = $random;\ endgenerate
2301_81045437/verilog
include/verilog_math.vh
SystemVerilog
apache-2.0
3,923
vlib work vlog -vlog01compat +incdir+../src+../include t_sqrt_generic.v vsim -voptargs=+acc work.t_sqrt_generic run -all
2301_81045437/verilog
sim/sqrt_generic.do
Stata
apache-2.0
121
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. `timescale 1ns / 1ps module t_button_debounce(); parameter CLK_FREQUENCY = 10_000_000, DEBOUNCE_HZ = 2; reg clk, reset_n, button; wire debounce; button_debounce #( .CLK_FREQUENCY(CLK_FREQUENCY), .DEBOUNCE_HZ(DEBOUNCE_HZ) ) button_debounce ( .clk(clk), .reset_n(reset_n), .button(button), .debounce(debounce) ); initial begin clk = 1'bx; reset_n = 1'bx; button = 1'bx; #10 reset_n = 1; #10 reset_n = 0; clk = 0; #10 reset_n = 1; #10 button = 0; end always #5 clk = ~clk; always begin #100 button = ~button; #0.1 button = ~button; #0.1 button = ~button; #0.1 button = ~button; #0.1 button = ~button; #0.1 button = ~button; #0.1 button = ~button; #0.1 button = ~button; #0.1 button = ~button; end endmodule
2301_81045437/verilog
sim/t_button_debounce.v
Verilog
apache-2.0
1,473
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. `timescale 1ns/1ps `include "pipeline_registers_set.v" module t_pipeline_registers_set(); `define PERIOD_TARGET 3 `define SLACK 0 `define PERIOD (`PERIOD_TARGET-(`SLACK)) `define HALF_PERIOD (`PERIOD/2) `define CQ_DELAY 0.100 `include "verilog_math.vh" localparam BIT_WIDTH = 8, NUMBER_OF_STAGES = 4; reg clk, reset_n, set; reg [BIT_WIDTH-1:0] pipe_in; reg [BIT_WIDTH-1:0] set_data_unpacked [NUMBER_OF_STAGES-1:0]; wire [BIT_WIDTH*NUMBER_OF_STAGES-1:0] set_data; wire [BIT_WIDTH-1:0] pipe_out; `PACK(set_data_unpacked, set_data, BIT_WIDTH, NUMBER_OF_STAGES) pipeline_registers_set #( .BIT_WIDTH(BIT_WIDTH), .NUMBER_OF_STAGES(NUMBER_OF_STAGES) ) u_pipeline_registers_set ( .clk(clk), .reset_n(reset_n), .set(set), .set_data(set_data), .pipe_in(pipe_out), .pipe_out(pipe_out) ); always #`HALF_PERIOD clk = ~clk; initial begin $display("---------------------------------------- starting simulation"); $display("Period is %0.3fns (%0.0fMHz)", `PERIOD, 1/(`PERIOD)*10**3); set_data_unpacked[0] = 8'h01; set_data_unpacked[1] = 8'h23; set_data_unpacked[2] = 8'h45; set_data_unpacked[3] = 8'h67; #5 clk = 0; reset_n = 0; #10 reset_n = 1; #10 set = 1; #10 set = 0; end endmodule
2301_81045437/verilog
sim/t_pipeline_registers_set.v
Verilog
apache-2.0
1,994
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. `timescale 1ns/1ps `include "sqrt_generic.v" module t_sqrt_generic(); localparam WIDTH_INPUT = 16, WIDTH_OUTPUT = WIDTH_INPUT / 2 + WIDTH_INPUT % 2; reg clk, rst_n, valid_in; wire valid_out; reg [WIDTH_INPUT-1:0] radicand; wire [WIDTH_INPUT-1:0] radicand_d; wire [WIDTH_OUTPUT-1:0] root; sqrt_generic #(.WIDTH_INPUT(WIDTH_INPUT), .WIDTH_OUTPUT(WIDTH_OUTPUT)) u_sqrt_generic (.clk(clk), .rst_n(rst_n), .valid_in(valid_in), .radicand(radicand), .valid_out(valid_out), .root(root)); pipeline_registers #(.BIT_WIDTH(WIDTH_INPUT), .NUMBER_OF_STAGES(WIDTH_OUTPUT)) u_pipe_radicand (.clk(clk), .reset_n(rst_n), .pipe_in(radicand), .pipe_out(radicand_d)); always #1 clk = ~clk; initial begin clk = 0; rst_n = 0; #5 rst_n = 1; end always @(posedge clk) begin radicand <= radicand + 1; valid_in <= 1; if (valid_out) begin if ($itor(root) - $floor($itor(radicand_d)) > 0) $error("Bad square root value:\n sqrt(%0d) = %0d (correct: %0.0f)", radicand_d, root, $floor($itor(radicand_d))); // $display("%8d %8d", root, radicand_d); end if (radicand_d >= (1 << WIDTH_INPUT) - 1) begin $stop; end // Reset case if (!rst_n) begin radicand <= '0; valid_in <= 0; end end endmodule
2301_81045437/verilog
sim/t_sqrt_generic.v
Verilog
apache-2.0
1,976
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. `timescale 1ns / 1ps module t_sqrt_pipelined(); parameter INPUT_BITS = 4; localparam OUTPUT_BITS = INPUT_BITS / 2 + INPUT_BITS % 2; reg [INPUT_BITS-1:0] radicand; reg clk, start, reset_n; wire [OUTPUT_BITS-1:0] root; wire data_valid; // wire [7:0] root_good; sqrt_pipelined #( .INPUT_BITS(INPUT_BITS) ) sqrt_pipelined ( .clk(clk), .reset_n(reset_n), .start(start), .radicand(radicand), .data_valid(data_valid), .root(root) ); initial begin radicand = 16'bx; clk = 1'bx; start = 1'bx; reset_n = 1'bx;; #10 reset_n = 0; clk = 0; #50 reset_n = 1; radicand = 0; // #40 radicand = 81; start = 1; // #10 radicand = 16'bx; start = 0; #10000 $finish; end always #5 clk = ~clk; always begin #10 radicand = radicand + 1; start = 1; #10 start = 0; end // always begin // #80 start = 1; // #10 start = 0; // end endmodule
2301_81045437/verilog
sim/t_sqrt_pipelined.v
Verilog
apache-2.0
1,617
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. `timescale 1ns / 1ps module button_debounce #( parameter CLK_FREQUENCY = 10_000_000, DEBOUNCE_HZ = 2 // These parameters are specified such that you can choose any power // of 2 frequency for a debouncer between 1 Hz and // CLK_FREQUENCY. Note, that this will throw errors if you choose a // non power of 2 frequency (i.e. count_value evaluates to some // number / 3 which isn't interpreted as a logical right shift). I'm // assuming this will not work for DEBOUNCE_HZ values less than 1, // however, I'm uncertain of the value of a debouncer for fractional // hertz button presses. ) ( input clk, // clock input reset_n, // asynchronous reset input button, // bouncy button output reg debounce // debounced 1-cycle signal ); localparam COUNT_VALUE = CLK_FREQUENCY / DEBOUNCE_HZ, WAIT = 0, FIRE = 1, COUNT = 2; reg [1:0] state, next_state; reg [25:0] count; always @ (posedge clk or negedge reset_n) state <= (!reset_n) ? WAIT : next_state; always @ (posedge clk or negedge reset_n) begin if (!reset_n) begin debounce <= 0; count <= 0; end else begin debounce <= 0; count <= 0; case (state) WAIT: begin end FIRE: begin debounce <= 1; end COUNT: begin count <= count + 1; end endcase end end always @ * begin case (state) WAIT: next_state = (button) ? FIRE : state; FIRE: next_state = COUNT; COUNT: next_state = (count > COUNT_VALUE - 1) ? WAIT : state; default: next_state = WAIT; endcase end endmodule
2301_81045437/verilog
src/button_debounce.v
Verilog
apache-2.0
2,341
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Description: // Pipelined implementation of the CORDIC vector rotation algorithm in circular // mode. The input is selected through an input "func" select line. Currently // implemented functions are: // func select | function // 0 | sine // 1 | cosine // Format is two's complement fixed point with 11 bits before the // binary point and 12 bits after e.g.: // [ sign ][ 11 bits ].[ 12 bits ] `timescale 1ns/1ps `include "pipeline_registers.v" module cordic_cir #( parameter W = 12 // input/output width ) ( input clk, rst_n, start, input func, // function to perform (see above) input signed [W*2-1:0] a, b, // function inputs output valid, // output data valid output reg [W-1:0] f // function output ); localparam COS = 1'd0, SIN = 1'd1; localparam ROT = 1'd0, VEC = 1'd1; localparam INV_GAIN_32 = 32'h4DBA76D4, // 0.60725293500888133000 PI_DIV_TWO = 32'sh6487ED51, // 1.57079632679489660000 TWO_DIV_PI = 32'sh28BE60DC; // 0.63661977236758138000 reg func_pp, inv_pp; reg [31:0] atan_table [31:0]; reg [W-1:0] sigma, mode; reg [W-1:0] x_neg [W:0]; reg [W-1:0] y_neg [W:0]; reg signed [W-1:0] x [W:0]; reg signed [W-1:0] y [W:0]; reg signed [W-1:0] z [W:0]; reg signed [W-1:0] x_round [W:0]; reg signed [W-1:0] y_round [W:0]; wire func_out, inv_out; wire signed [W*2-1:0] inv_gain, pi_div_two, two_div_pi; wire signed [W*4-1:0] q; wire [W*4-1:0] d; initial begin // this is overkill, how to improve? atan_table[0] = 32'hC90FDAA2; // 0.78539816339744828000 atan_table[1] = 32'h76B19C16; // 0.46364760900080609000 atan_table[2] = 32'h3EB6EBF2; // 0.24497866312686414000 atan_table[3] = 32'h1FD5BA9B; // 0.12435499454676144000 atan_table[4] = 32'h0FFAADDC; // 0.06241880999595735000 atan_table[5] = 32'h07FF556F; // 0.03123983343026827700 atan_table[6] = 32'h03FFEAAB; // 0.01562372862047683100 atan_table[7] = 32'h01FFFD55; // 0.00781234106010111110 atan_table[8] = 32'h00FFFFAB; // 0.00390623013196697180 atan_table[9] = 32'h007FFFF5; // 0.00195312251647881880 atan_table[10] = 32'h003FFFFF; // 0.00097656218955931946 atan_table[11] = 32'h00200000; // 0.00048828121119489829 atan_table[12] = 32'h00100000; // 0.00024414062014936177 atan_table[13] = 32'h00080000; // 0.00012207031189367021 atan_table[14] = 32'h00040000; // 0.00006103515617420877 atan_table[15] = 32'h00020000; // 0.00003051757811552610 atan_table[16] = 32'h00010000; // 0.00001525878906131576 atan_table[17] = 32'h00008000; // 0.00000762939453110197 atan_table[18] = 32'h00004000; // 0.00000381469726560650 atan_table[19] = 32'h00002000; // 0.00000190734863281019 atan_table[20] = 32'h00001000; // 0.00000095367431640596 atan_table[21] = 32'h00000800; // 0.00000047683715820309 atan_table[22] = 32'h00000400; // 0.00000023841857910156 atan_table[23] = 32'h00000200; // 0.00000011920928955078 atan_table[24] = 32'h00000100; // 0.00000005960464477539 atan_table[25] = 32'h00000080; // 0.00000002980232238770 atan_table[26] = 32'h00000040; // 0.00000001490116119385 atan_table[27] = 32'h00000020; // 0.00000000745058059692 atan_table[28] = 32'h00000010; // 0.00000000372529029846 atan_table[29] = 32'h00000008; // 0.00000000186264514923 atan_table[30] = 32'h00000004; // 0.00000000093132257462 atan_table[31] = 32'h00000002; // 0.00000000046566128731 end assign inv_gain = (INV_GAIN_32 >>> (32-W+1)) + INV_GAIN_32[32-W]; assign pi_div_two = (PI_DIV_TWO >>> (32-W*2)) + PI_DIV_TWO[32-W*2+1]; assign two_div_pi = (TWO_DIV_PI >>> (32-W*2)) + TWO_DIV_PI[32-W*2+1]; assign q = a * two_div_pi; assign d = (q[33:10]+q[9]) * pi_div_two; always @ * begin case (func) COS: begin case (q[35:34]) 2'd0: begin func_pp = COS; inv_pp = 0; end 2'd1: begin func_pp = SIN; inv_pp = 1; end 2'd2: begin func_pp = COS; inv_pp = 1; end 2'd3: begin func_pp = SIN; inv_pp = 0; end endcase end SIN: begin case (q[35:34]) 2'd0: begin func_pp = SIN; inv_pp = 0; end 2'd1: begin func_pp = COS; inv_pp = 0; end 2'd2: begin func_pp = SIN; inv_pp = 1; end 2'd3: begin func_pp = COS; inv_pp = 1; end endcase end endcase end always @ (posedge clk or negedge rst_n) begin//function pre-processing if (!rst_n) begin x[0] <= 0; y[0] <= 0; z[0] <= 0; mode[0] <= 0; end else begin case (func_pp) COS: begin x[0] <= inv_gain; y[0] <= 0; z[0] <= {1'b0,d[W*4-2:W*4-2-10]}; mode[0] <= ROT; end SIN: begin x[0] <= inv_gain; y[0] <= 0; z[0] <= {1'b0,d[W*4-2:W*4-2-10]}; mode[0] <= ROT; end default: begin x[0] <= 32'bx; y[0] <= 32'bx; z[0] <= 32'bx; mode[0] <= 1'bx; end endcase end end generate genvar i; for (i = 0; i < W; i = i + 1) begin : gen_stages always @ * begin x_neg[i] = ~x[i] + 1; y_neg[i] = ~y[i] + 1; if (i==0) begin x_round[i] = x[i]; y_round[i] = y[i]; end else begin x_round[i] = (x[i][W-1]) ? ~(x_neg[i] + (x_neg[i][i-1] << i)+1) + 1 : x[i] + (x[i][i-1] << i); y_round[i] = (y[i][W-1]) ? ~(y_neg[i] + (y_neg[i][i-1] << i)+1) + 1 : y[i] + (y[i][i-1] << i); end end always @ * begin case (mode[0]) ROT: sigma[i] = ~z[i][W-1];//z>=0 VEC: sigma[i] = y[i][W-1];//y<0 default: sigma[i] = 1'd0; endcase end always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin x[i+1] <= 0; y[i+1] <= 0; z[i+1] <= 0; end else begin x[i+1] <= (sigma[i]) ? x[i] - (y_round[i] >>> i) : x[i] + (y_round[i] >>> i); y[i+1] <= (sigma[i]) ? y[i] + (x_round[i] >>> i) : y[i] - (x_round[i] >>> i); z[i+1] <= (sigma[i]) ? z[i] - {2'b0, (atan_table[i][31:31-W+3]+atan_table[i][31-W+3-1])} : z[i] + {2'b0, atan_table[i][31:31-W+3]+atan_table[i][31-W+3-1]}; end end end endgenerate always @ (posedge clk or negedge rst_n) begin//function post-processing if (!rst_n) f <= 0; else begin case (func_out) COS: f <= (inv_out) ? ~x[W] + 1 : x[W]; SIN: f <= (inv_out) ? ~y[W] + 1 : y[W]; endcase end end pipeline_registers #( .BIT_WIDTH(3), .NUMBER_OF_STAGES(W+1) ) pipe_valid ( .clk(clk), .rst_n(rst_n), .pipe_in({func_pp,start,inv_pp}), .pipe_out({func_out,valid,inv_out}) ); endmodule
2301_81045437/verilog
src/cordic_cir.v
Verilog
apache-2.0
7,987
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Pipelined implementation of the CORDIC vector rotation algorithm in // hyperbolic mode. // // functions (governed by input func): // 1'd0: exp // 1'd1: ln // // The formats for inputs and outputs are as follows: // -------------------------------------------- // | function | input | output | // -------------------------------------------- // | exp | s0.9876543210 | s10.876543210 | // | ln | s3210.6543210 | [s][.876543210 | // -------------------------------------------- // >>>>> actually: [sign][11 bits].[12 bits] `include "pipeline_registers.v" `include "sign_extender.v" module cordic_hyp #( parameter W = 12 // input/output width/# stages ) ( input clk, rst_n, start, input func, // function to perform (see above) input signed [W*2-1:0] a, b, // function inputs output valid, // output data valid output reg [W*2-1:0] f // function output ); localparam EXP = 1'd0, LN = 1'd1; localparam ROT = 1'd0, VEC = 1'd1; localparam INV_GAIN_32 = 32'sh9A8F4390, // 1.20749706776307210000 LN_2 = 32'sh2C5C85FE, // 0.69314718055994529000 LN_2_INV = 32'sh5C551D95; // 1.44269504088896340000 localparam // account for repeated stages STAGES = W+(W>=4)+(W>=13)+(W>=40)+(W>=121)+(W>=364)+(W>=1093); reg [4:0] first_bit; reg [STAGES:0] mode; reg [31:0] atanh_table [31:0]; reg [STAGES-1:0] sigma; reg [W-1:0] x_neg [STAGES:0]; reg [W-1:0] y_neg [STAGES:0]; reg signed [W-1:0] x [STAGES:0]; reg signed [W-1:0] y [STAGES:0]; reg signed [W-1:0] z [STAGES:0]; reg signed [W-1:0] x_round [STAGES:0]; reg signed [W-1:0] y_round [STAGES:0]; wire func_out; wire [W-1:0] inv_gain, e_exp, e_exp_out; wire [W*2-1:0] m, d; wire [W*3-1:0] q; wire signed [4:0] e, e_out; wire signed [W-1:0] ln_2, ln_2_inv; wire signed [W+5-1:0] e_out_mul_ln_2; wire signed [W*2-1:0] z_se, e_out_mul_ln_2_se; initial begin // this is overkill, how to improve? atanh_table[0] = 32'h8C9F53D5; // 0.54930614433405478000 atanh_table[1] = 32'h4162BBEA; // 0.25541281188299536000 atanh_table[2] = 32'h202B1239; // 0.12565721414045303000 atanh_table[3] = 32'h1005588B; // 0.06258157147700300900 atanh_table[4] = 32'h0800AAC4; // 0.03126017849066699300 atanh_table[5] = 32'h04001556; // 0.01562627175205220900 atanh_table[6] = 32'h020002AB; // 0.00781265895154042120 atanh_table[7] = 32'h01000055; // 0.00390626986839682620 atanh_table[8] = 32'h0080000B; // 0.00195312748353254980 atanh_table[9] = 32'h00400001; // 0.00097656281044103594 atanh_table[10] = 32'h00200000; // 0.00048828128880511277 atanh_table[11] = 32'h00100000; // 0.00024414062985063861 atanh_table[12] = 32'h00080000; // 0.00012207031310632982 atanh_table[13] = 32'h00040000; // 0.00006103515632579122 atanh_table[14] = 32'h00020000; // 0.00003051757813447390 atanh_table[15] = 32'h00010000; // 0.00001525878906368424 atanh_table[16] = 32'h00008000; // 0.00000762939453139803 atanh_table[17] = 32'h00004000; // 0.00000381469726564350 atanh_table[18] = 32'h00002000; // 0.00000190734863281481 atanh_table[19] = 32'h00001000; // 0.00000095367431640654 atanh_table[20] = 32'h00000800; // 0.00000047683715820316 atanh_table[21] = 32'h00000400; // 0.00000023841857910157 atanh_table[22] = 32'h00000200; // 0.00000011920928955078 atanh_table[23] = 32'h00000100; // 0.00000005960464477539 atanh_table[24] = 32'h00000080; // 0.00000002980232238770 atanh_table[25] = 32'h00000040; // 0.00000001490116119385 atanh_table[26] = 32'h00000020; // 0.00000000745058059692 atanh_table[27] = 32'h00000010; // 0.00000000372529029846 atanh_table[28] = 32'h00000008; // 0.00000000186264514923 atanh_table[29] = 32'h00000004; // 0.00000000093132257462 atanh_table[30] = 32'h00000002; // 0.00000000046566128731 atanh_table[31] = 32'h00000001; // 0.00000000023283064365 end assign ln_2 = (LN_2[31:31-W+1] + LN_2[31-W]); assign ln_2_inv = (LN_2_INV[31:31-W+1] + LN_2_INV[31-W]); assign inv_gain = (INV_GAIN_32 >> (32-W+1)) + INV_GAIN_32[32-W]; assign m = (first_bit > 11) ? a >> (first_bit-11) : a << (11-first_bit); assign e = first_bit - 11; assign e_out_mul_ln_2 = e_out * ln_2; assign q = a * ln_2_inv; assign d = (q[21:21-W+1]+q[21-W]) * ln_2; assign e_exp = q[W*3-3:W*2-2]; always @ * begin casex(a) 24'b1_xxxxxxxxxxx_xxxxxxxxxxxx: first_bit = 23; 24'b0_1xxxxxxxxxx_xxxxxxxxxxxx: first_bit = 22; 24'b0_01xxxxxxxxx_xxxxxxxxxxxx: first_bit = 21; 24'b0_001xxxxxxxx_xxxxxxxxxxxx: first_bit = 20; 24'b0_0001xxxxxxx_xxxxxxxxxxxx: first_bit = 19; 24'b0_00001xxxxxx_xxxxxxxxxxxx: first_bit = 18; 24'b0_000001xxxxx_xxxxxxxxxxxx: first_bit = 17; 24'b0_0000001xxxx_xxxxxxxxxxxx: first_bit = 16; 24'b0_00000001xxx_xxxxxxxxxxxx: first_bit = 15; 24'b0_000000001xx_xxxxxxxxxxxx: first_bit = 14; 24'b0_0000000001x_xxxxxxxxxxxx: first_bit = 13; 24'b0_00000000001_xxxxxxxxxxxx: first_bit = 12; 24'b0_00000000000_1xxxxxxxxxxx: first_bit = 11; 24'b0_00000000000_01xxxxxxxxxx: first_bit = 10; 24'b0_00000000000_001xxxxxxxxx: first_bit = 9; 24'b0_00000000000_0001xxxxxxxx: first_bit = 8; 24'b0_00000000000_00001xxxxxxx: first_bit = 7; 24'b0_00000000000_000001xxxxxx: first_bit = 6; 24'b0_00000000000_0000001xxxxx: first_bit = 5; 24'b0_00000000000_00000001xxxx: first_bit = 4; 24'b0_00000000000_000000001xxx: first_bit = 3; 24'b0_00000000000_0000000001xx: first_bit = 2; 24'b0_00000000000_00000000001x: first_bit = 1; 24'b0_00000000000_000000000001: first_bit = 0; default: first_bit = 0; endcase end always @ (posedge clk or negedge rst_n) begin//function pre-processing if (!rst_n) begin x[0] <= 0; y[0] <= 0; z[0] <= 0; mode[0] <= ROT; end else begin case (func) EXP: begin x[0] <= inv_gain; y[0] <= 0; z[0] <= d[W*2-1:W]; mode[0] <= ROT; end LN: begin x[0] <= {2'b0,m[11:2]} + 12'b0100_0000_0000;//not rounded y[0] <= {2'b0,m[11:2]} - 12'b0100_0000_0000;//not rounded z[0] <= 0; mode[0] <= VEC; end default: begin x[0] <= 32'bx; y[0] <= 32'bx; z[0] <= 32'bx; mode[0] <= ROT; end endcase end end generate genvar i; for (i = 0; i < STAGES; i = i + 1) begin : gen_stages always @ * begin x_neg[i] = ~x[i] + 1; y_neg[i] = ~y[i] + 1; if (i==0) begin x_round[i] = x[i]; y_round[i] = y[i]; end else begin x_round[i] = (x[i][W-1]) ? ~(x_neg[i] + (x_neg[i][i-1] << i)+1) + 1 : x[i] + (x[i][i-1] << i); y_round[i] = (y[i][W-1]) ? ~(y_neg[i] + (y_neg[i][i-1] << i)+1) + 1 : y[i] + (y[i][i-1] << i); end end always @ * begin case (mode[i]) ROT: sigma[i] = ~z[i][W-1];//z>=0 VEC: sigma[i] = y[i][W-1];//y<0 default: sigma[i] = 1'd0; endcase end always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin x[i+1] <= 0; y[i+1] <= 0; z[i+1] <= 0; mode[i+1] <= 0; end else begin x[i+1] <= (sigma[i]) ? x[i] + (y_round[i] >>> i+1-(i>4)-(i>13)-(i>40)-(i>121)-(i>364)-(i>1093)) : x[i] - (y_round[i] >>> i+1-(i>4)-(i>13)-(i>40)-(i>121)-(i>364)-(i>1093)); y[i+1] <= (sigma[i]) ? y[i] + (x_round[i] >>> i+1-(i>4)-(i>13)-(i>40)-(i>121)-(i>364)-(i>1093)) : y[i] - (x_round[i] >>> i+1-(i>4)-(i>13)-(i>40)-(i>121)-(i>364)-(i>1093)); z[i+1] <= (sigma[i]) ? z[i] - {2'b0,(atanh_table[i-(i>4)-(i>13)-(i>40)-(i>121)- (i>364)-(i>1093)][31:31-W+3] + atanh_table[i-(i>4)-(i>13)-(i>40)-(i>121)- (i>364)-(i>1093)][31-W+3-1])} : z[i] + {2'b0,(atanh_table[i-(i>4)-(i>13)-(i>40)-(i>121)- (i>364)-(i>1093)][31:31-W+3] + atanh_table[i-(i>4)-(i>13)-(i>40)-(i>121)-(i>364)- (i>1093)][31-W+3-1])}; mode[i+1] <= mode[i]; end end end endgenerate always @ (posedge clk or negedge rst_n) begin//function post-processing if (!rst_n) f <= 0; else begin case (func_out) EXP: f <= (e_exp_out[W-1]) ? (x[STAGES] + y[STAGES]) >> (~e_exp_out+12'b1) : (x[STAGES] + y[STAGES]) << e_exp_out; LN: f <= (z_se * 2 + e_out_mul_ln_2_se) * 4; endcase end end sign_extender #( .INPUT_WIDTH(W), .OUTPUT_WIDTH(W*2) ) sign_extender_z ( .original(z[STAGES]), .sign_extended_original(z_se) ); sign_extender #( .INPUT_WIDTH(W+5), .OUTPUT_WIDTH(W*2) ) sign_extender_e_out_mul_LN_2 ( .original(e_out_mul_ln_2), .sign_extended_original(e_out_mul_ln_2_se) ); pipeline_registers #( .BIT_WIDTH(1), .NUMBER_OF_STAGES(W+3) ) pipe_valid ( .clk(clk), .rst_n(rst_n), .pipe_in(start), .pipe_out(valid) ); pipeline_registers #( .BIT_WIDTH(1+5+12), .NUMBER_OF_STAGES(W+2) ) pipe_func_e_exp ( .clk(clk), .rst_n(rst_n), .pipe_in({func,e,e_exp}), .pipe_out({func_out,e_out,e_exp_out}) ); endmodule
2301_81045437/verilog
src/cordic_hyp.v
Verilog
apache-2.0
10,904
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Implements a fixed-point parameterized pipelined division // operation. Outputs are expected to be on range [-1,1), techincally // [-1,2^(BITS-1)-1/2^(BITS-1)]. There is no convergent rounding. // // [TODO] Implement optional convergent rounding and some form of // variable output binary point placement. There are arguments in // these changes that make sense (specifically, adding an additional // bit results in a gain of one value when all the other 2^6 values // greater than 1 aren't used). Other improvements that are needed: 1) // quotient_gen is getting smaller by one bit in every stage, it would // make more sense to generate this as such, 2) there's some weird // initial behavior after rst_n is deasserted, you get weird output on // the quotient line for a number of cycles. // // [TODO] This doesn't exactly behave as expected if you specify // different BITS and STAGES parameters (which for a functional // module, should be implemented). Note, that this technically works, // but needs more investigation to fully understand its properties. `timescale 1ns / 1ps module div_pipelined ( input clk, input rst_n, input start, input [BITS-1:0] dividend, input [BITS-1:0] divisor, output reg data_valid, output reg div_by_zero, output reg [STAGES-1:0] quotient // output reg [7:0] quotient_correct ); // WARNING!!! THESE PARAMETERS ARE INTENDED TO BE MODIFIED IN A TOP // LEVEL MODULE. LOCAL CHANGES HERE WILL, MOST LIKELY, BE // OVERWRITTEN! parameter BITS = 8, STAGES = BITS; // y = a/bQ reg [STAGES-1:0] start_gen, negative_quotient_gen, div_by_zero_gen; reg [BITS*2*(STAGES-1)-1:0] dividend_gen, divisor_gen, quotient_gen; wire [BITS-1:0] pad_dividend; wire [BITS-2:0] pad_divisor; assign pad_dividend = 0; assign pad_divisor = 0; // sign conversion stage always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero_gen[0] <= 0; start_gen[0] <=0; negative_quotient_gen[0] <= 0; dividend_gen[BITS*2-1:0] <= 0; divisor_gen[BITS*2-1:0] <= 0; end else begin div_by_zero_gen[0] <= (divisor == 0); start_gen[0] <= start; negative_quotient_gen[0] <= dividend[BITS-1] ^ divisor[BITS-1]; dividend_gen[BITS*2-1:0] <= (dividend[BITS-1]) ? ~{dividend,pad_dividend} + 1 : {dividend,pad_dividend}; divisor_gen[BITS*2-1:0] <= (divisor [BITS-1]) ? ~{1'b1,divisor, pad_divisor} + 1 : {1'b0,divisor, pad_divisor}; end end // first computation stage always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero_gen[1] <= 0; start_gen[1] <= 0; negative_quotient_gen[1] <= 0; divisor_gen[BITS*2*2-1:BITS*2] <= 0; quotient_gen[BITS*2-1:0] <= 0; dividend_gen[BITS*2*2-1:BITS*2] <= 0; end else begin div_by_zero_gen[1] <= div_by_zero_gen[0]; start_gen[1] <= start_gen[0]; negative_quotient_gen[1] <= negative_quotient_gen[0]; divisor_gen[BITS*2*2-1:BITS*2] <= divisor_gen[BITS*2-1:0] >> 1; if ( dividend_gen[BITS*2-1:0] >= divisor_gen[BITS*2-1:0]) begin quotient_gen[BITS*2-1:0] <= 1 << STAGES - 2; dividend_gen[BITS*2*2-1:BITS*2] <= dividend_gen[BITS*2-1:0] - divisor_gen[BITS*2-1:0]; end else begin quotient_gen[BITS*2-1:0] <= 0; dividend_gen[BITS*2*2-1:BITS*2] <= dividend_gen[BITS*2-1:0]; end end // else: !if(!rst_n) end // always @ (posedge clk) generate genvar i; for (i = 1; i < STAGES - 2; i = i + 1) begin : pipeline always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero_gen[i+1] <= 0; start_gen[i+1] <= 0; negative_quotient_gen[i+1] <= 0; divisor_gen[BITS*2*(i+2)-1:BITS*2*(i+1)] <= 0; quotient_gen[BITS*2*(i+1)-1:BITS*2*i] <= 0; dividend_gen[BITS*2*(i+2)-1:BITS*2*(i+1)] <= 0; end else begin div_by_zero_gen[i+1] <= div_by_zero_gen[i]; start_gen[i+1] <= start_gen[i]; negative_quotient_gen[i+1] <= negative_quotient_gen[i]; divisor_gen[BITS*2*(i+2)-1:BITS*2*(i+1)] <= divisor_gen[BITS*2*(i+1)-1:BITS*2*i] >> 1; if (dividend_gen[BITS*2*(i+1)-1:BITS*2*i] >= divisor_gen[BITS*2*(i+1)-1:BITS*2*i]) begin quotient_gen[BITS*2*(i+1)-1:BITS*2*i] <= quotient_gen[BITS*2*i-1:BITS*2*(i-1)] | (1 << (STAGES-2-i)); dividend_gen[BITS*2*(i+2)-1:BITS*2*(i+1)] <= dividend_gen[BITS*2*(i+1)-1:BITS*2*i] - divisor_gen[BITS*2*(i+1)-1:BITS*2*i]; end else begin quotient_gen[BITS*2*(i+1)-1:BITS*2*i] <= quotient_gen[BITS*2*i-1:BITS*2*(i-1)]; dividend_gen[BITS*2*(i+2)-1:BITS*2*(i+1)] <= dividend_gen[BITS*2*(i+1)-1:BITS*2*i]; end end // else: !if(!rst_n) end // always @ (posedge clk or negedge rst_n) end // block: pipeline endgenerate // last computation stage always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero_gen[STAGES-1] <= 0; start_gen[STAGES-1] <= 0; negative_quotient_gen[STAGES-1] <= 0; quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] <= 0; end else begin div_by_zero_gen[STAGES-1] <= div_by_zero_gen[STAGES-2]; start_gen[STAGES-1] <= start_gen[STAGES-2]; negative_quotient_gen[STAGES-1] <= negative_quotient_gen[STAGES-2]; if ( dividend_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] >= divisor_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] ) quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] <= quotient_gen[BITS*2*(STAGES-2)-1:BITS*2*(STAGES-3)] | 1; else quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] <= quotient_gen[BITS*2*(STAGES-2)-1:BITS*2*(STAGES-3)]; end // else: !if(!rst_n) end // always @ (posedge clk) // sign conversion stage always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero <= 0; data_valid <= 0; quotient <= 0; end else begin div_by_zero <= div_by_zero_gen[STAGES-1]; data_valid <= start_gen[STAGES-1]; quotient <= (negative_quotient_gen[STAGES-1]) ? ~quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] + 1 : quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)]; end end endmodule
2301_81045437/verilog
src/div_pipelined.v
Verilog
apache-2.0
7,386
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Implements a series of pipeline registers specified by the input // parameters BIT_WIDTH and NUMBER_OF_STAGES. BIT_WIDTH determines the // size of the signal passed through each of the pipeline // registers. NUMBER_OF_STAGES is the number of pipeline registers // generated. This accepts values of 0 (yes, it just passes data from // input to output...) up to however many stages specified. `timescale 1ns / 1ps module pipeline_registers #( parameter BIT_WIDTH = 10, NUMBER_OF_STAGES = 5 ) ( input clk, input reset_n, input [BIT_WIDTH-1:0] pipe_in, output reg [BIT_WIDTH-1:0] pipe_out ); // Main generate function for conditional hardware instantiation generate genvar i; // Pass-through case for the odd event that no pipeline stages are // specified. if (NUMBER_OF_STAGES == 0) begin always @ * pipe_out = pipe_in; end // Single flop case for a single stage pipeline else if (NUMBER_OF_STAGES == 1) begin always @ (posedge clk or negedge reset_n) pipe_out <= (!reset_n) ? 0 : pipe_in; end // Case for 2 or more pipeline stages else begin // Create the necessary regs reg [BIT_WIDTH*(NUMBER_OF_STAGES-1)-1:0] pipe_gen; // Create logic for the initial and final pipeline registers always @ (posedge clk or negedge reset_n) begin if (!reset_n) begin pipe_gen[BIT_WIDTH-1:0] <= 0; pipe_out <= 0; end else begin pipe_gen[BIT_WIDTH-1:0] <= pipe_in; pipe_out <= pipe_gen[BIT_WIDTH*(NUMBER_OF_STAGES-1)-1:BIT_WIDTH*(NUMBER_OF_STAGES-2)]; end end // Create the intermediate pipeline registers if there are 3 or // more pipeline stages for (i = 1; i < NUMBER_OF_STAGES-1; i = i + 1) begin : pipeline always @ (posedge clk or negedge reset_n) pipe_gen[BIT_WIDTH*(i+1)-1:BIT_WIDTH*i] <= (!reset_n) ? 0 : pipe_gen[BIT_WIDTH*i-1:BIT_WIDTH*(i-1)]; end end endgenerate endmodule
2301_81045437/verilog
src/pipeline_registers.v
Verilog
apache-2.0
2,741
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Extension of original pipeline_registers.v that allows for a // synchronous set of all the internal registers. `timescale 1ns / 1ps module pipeline_registers_set #( parameter BIT_WIDTH = 10, NUMBER_OF_STAGES = 5 ) ( input clk, input reset_n, input set, input [BIT_WIDTH*NUMBER_OF_STAGES-1:0] set_data, input [BIT_WIDTH-1:0] pipe_in, output reg [BIT_WIDTH-1:0] pipe_out ); // Main generate function for conditional hardware instantiation generate genvar i; // Pass-through case for the odd event that no pipeline stages are // specified. if (NUMBER_OF_STAGES == 0) begin always @ * pipe_out = pipe_in; end // Single flop case for a single stage pipeline else if (NUMBER_OF_STAGES == 1) begin always @ (posedge clk or negedge reset_n) pipe_out <= (!reset_n) ? 0 : (set) ? set_data : pipe_in; end // Case for 2 or more pipeline stages else begin // Create the necessary regs reg [BIT_WIDTH*(NUMBER_OF_STAGES-1)-1:0] pipe_gen; // Create logic for the initial and final pipeline registers always @ (posedge clk or negedge reset_n) begin if (!reset_n) begin pipe_gen[BIT_WIDTH-1:0] <= 0; pipe_out <= 0; end else if (set) begin pipe_gen[BIT_WIDTH-1:0] <= set_data[BIT_WIDTH-1:0]; pipe_out <= set_data[BIT_WIDTH*NUMBER_OF_STAGES-1:BIT_WIDTH*(NUMBER_OF_STAGES-1)]; end else begin pipe_gen[BIT_WIDTH-1:0] <= pipe_in; pipe_out <= pipe_gen[BIT_WIDTH*(NUMBER_OF_STAGES-1)-1:BIT_WIDTH*(NUMBER_OF_STAGES-2)]; end end // Create the intermediate pipeline registers if there are 3 or // more pipeline stages for (i = 1; i < NUMBER_OF_STAGES-1; i = i + 1) begin : pipeline always @ (posedge clk or negedge reset_n) pipe_gen[BIT_WIDTH*(i+1)-1:BIT_WIDTH*i] <= (!reset_n) ? 0 : (set) ? set_data[BIT_WIDTH*(i+1)-1:BIT_WIDTH*i] : pipe_gen[BIT_WIDTH*i-1:BIT_WIDTH*(i-1)]; end end endgenerate endmodule
2301_81045437/verilog
src/pipeline_registers_set.v
Verilog
apache-2.0
2,891
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Infers parameterized block RAM from behavioral syntax. Based off an // example by Eric Johnson and Prof. Derek Chiou at UT Austin (see // http://users.ece.utexas.edu/~derek/code/BRAM.v). Tested by // inspection of simulated RTL schematic as this successfully infers // block RAM. `timescale 1ns/1ps module ram_infer #( parameter WIDTH = 8, DEPTH = 64, LG_DEPTH = 6, INIT_VAL = 8'd0 ) ( input clka, clkb, wea, web, ena, enb, input [LG_DEPTH-1:0] addra, addrb, input [WIDTH-1:0] dina, dinb, output reg [WIDTH-1:0] douta, doutb ); reg [WIDTH-1:0] ram [DEPTH-1:0]; reg [WIDTH-1:0] doa, dob; genvar i; generate for (i=0; i<DEPTH; i=i+1) begin: gen_init initial begin ram[i] = INIT_VAL; end end endgenerate always @(posedge clka) begin if (ena) begin if (wea) ram[addra] <= dina; douta <= ram[addra]; end end always @(posedge clkb) begin if (enb) begin if (web) ram[addrb] <= dinb; doutb <= ram[addrb]; end end endmodule
2301_81045437/verilog
src/ram_infer.v
Verilog
apache-2.0
1,723
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Implements a "good" reset signal that is asserted asynchronously // and deasserted synchronously. See Cliff Cummings work for the // reasoning behind this: // Cummings, C. and Milis, D. "Synchronous Resets? Asynchronous // resets? I am so confused! How will I ever know which to use?" // Synopsys Users Group Conference, 2002. // Cummings, C., Millis, D., and Golson, S. "Asynchronous & // synchronous reset design techniques-part deux." Synopsys Users // Group Conference, 2003. `include "pipeline_registers.v" module reset ( input clk, // input clock input rst_n_in, // asynchronous reset from userland output rst_n_out // asynchronous assert/synchronous deassert chip broadcast ); // You have two DFFs in series (a two stage pipe) with the input to // the first DFF tied to 1. When the input active low reset is // deasserted this asynchronously resets the DFFs. This causes the // second DFF to broadcast an asynchronous reset out to the whole // chip. However, when the input rest is asserted, the flip flops // are enabled, and you get a synchronous assert of the active low // reset to the entire chip. pipeline_registers #( .BIT_WIDTH(1), .NUMBER_OF_STAGES(2) ) reset_flops ( .clk(clk), // input clk .reset_n(rst_n_in), // convert to active low .pipe_in(1'b1), // input is always 1 .pipe_out(rst_n_out) // asynchronous reset output ); endmodule
2301_81045437/verilog
src/reset.v
Verilog
apache-2.0
2,081
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generic sign extension module `timescale 1ns/1ps module sign_extender #( parameter INPUT_WIDTH = 8, OUTPUT_WIDTH = 16 ) ( input [INPUT_WIDTH-1:0] original, output reg [OUTPUT_WIDTH-1:0] sign_extended_original ); wire [OUTPUT_WIDTH-INPUT_WIDTH-1:0] sign_extend; generate genvar i; for (i = 0; i < OUTPUT_WIDTH-INPUT_WIDTH; i = i + 1) begin : gen_sign_extend assign sign_extend[i] = (original[INPUT_WIDTH-1]) ? 1'b1 : 1'b0; end endgenerate always @ * begin sign_extended_original = {sign_extend,original}; end endmodule
2301_81045437/verilog
src/sign_extender.v
Verilog
apache-2.0
1,210
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. `timescale 1ns/1ps `include "pipeline_registers.v" module sqrt_generic #(parameter WIDTH_INPUT = 16, WIDTH_OUTPUT = WIDTH_INPUT / 2 + WIDTH_INPUT % 2, FLAG_PIPELINE = 1 // Currently unused ) ( input clk, // clock input rst_n, // asynchronous reset input valid_in, // optional start signal input [WIDTH_INPUT-1:0] radicand, // unsigned radicand output valid_out, // optional data valid signal output [WIDTH_OUTPUT-1:0] root // unsigned root ); // Pass-though pipe that sends the input valid signal to the // output valid signal pipeline_registers #(.BIT_WIDTH(1), .NUMBER_OF_STAGES(WIDTH_OUTPUT)) pipe_valid (.clk(clk), .reset_n(rst_n), .pipe_in(valid_in), .pipe_out(valid_out) ); reg [WIDTH_INPUT-1:0] root_gen [WIDTH_OUTPUT-1:0]; reg [WIDTH_INPUT-1:0] radicand_gen [WIDTH_OUTPUT-1:0]; wire [WIDTH_INPUT-1:0] mask_gen [WIDTH_OUTPUT-1:0]; generate genvar i; // Generate all the masks for (i = 0; i < WIDTH_OUTPUT; i = i + 1) begin: mask if (i % 2) assign mask_gen[WIDTH_OUTPUT-i-1] = 4 << 4 * (i/2); else assign mask_gen[WIDTH_OUTPUT-i-1] = 1 << 4 * (i/2); end // Handle the operations of each pipeline stage for (i = 0; i < WIDTH_OUTPUT; i = i + 1) begin: pipe_sqrt always @ (posedge clk or negedge rst_n) begin: pipe_stage // Reset condition if (!rst_n) begin radicand_gen[i] <= 0; root_gen[i] <= 0; end else begin // Logic for any stage which is not the first stage if (i > 0) begin if (root_gen[i-1] + mask_gen[i] <= radicand_gen[i-1]) begin radicand_gen[i] <= radicand_gen[i-1] - mask_gen[i] - root_gen[i-1]; root_gen[i] <= (root_gen[i-1] >> 1) + mask_gen[i]; end else begin radicand_gen[i] <= radicand_gen[i-1]; root_gen[i] <= root_gen[i-1] >> 1; end end // Logic specific to the first stage if (i == 0) begin if (mask_gen[i] <= radicand) begin radicand_gen[i] <= radicand - mask_gen[i]; root_gen[i] <= mask_gen[i]; end else begin radicand_gen[i] <= radicand; root_gen[i] <= 0; end end end end end endgenerate assign root = root_gen[WIDTH_OUTPUT-1]; endmodule
2301_81045437/verilog
src/sqrt_generic.v
Verilog
apache-2.0
3,163
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Implements a fixed-point parameterized pipelined square root // operation on an unsigned input of any bit length. The number of // stages in the pipeline is equal to the number of output bits in the // computation. This pipelien sustains a throughput of one computation // per clock cycle. `timescale 1ns / 1ps module sqrt_pipelined #( parameter INPUT_BITS = 16, // number of input bits (any integer) OUTPUT_BITS = INPUT_BITS / 2 + INPUT_BITS % 2 // number of output bits ) ( input clk, // clock input reset_n, // asynchronous reset input start, // optional start signal input [INPUT_BITS-1:0] radicand, // unsigned radicand output reg data_valid, // optional data valid signal output reg [OUTPUT_BITS-1:0] root // unsigned root ); reg [OUTPUT_BITS-1:0] start_gen; // valid data propagation reg [OUTPUT_BITS*INPUT_BITS-1:0] root_gen; // root values reg [OUTPUT_BITS*INPUT_BITS-1:0] radicand_gen; // radicand values wire [OUTPUT_BITS*INPUT_BITS-1:0] mask_gen; // mask values // This is the first stage of the pipeline. always @ (posedge clk or negedge reset_n) begin if (!reset_n) begin start_gen[0] <= 0; radicand_gen[INPUT_BITS-1:0] <= 0; root_gen[INPUT_BITS-1:0] <= 0; end else begin start_gen[0] <= start; if ( mask_gen[INPUT_BITS-1:0] <= radicand ) begin radicand_gen[INPUT_BITS-1:0] <= radicand - mask_gen[INPUT_BITS-1:0]; root_gen[INPUT_BITS-1:0] <= mask_gen[INPUT_BITS-1:0]; end else begin radicand_gen[INPUT_BITS-1:0] <= radicand; root_gen[INPUT_BITS-1:0] <= 0; end end end // Main generate loop to create the masks and pipeline stages. generate genvar i; // Generate all the mask values. These are built up in the // following fashion: // LAST MASK: 0x00...001 // 0x00...004 Increasing # OUTPUT_BITS // 0x00...010 | // 0x00...040 v // ... // FIRST MASK: 0x10...000 # masks == # OUTPUT_BITS // // Note that the first mask used can either be of the 0x1... or // 0x4... variety. This is purely determined by the number of // computation stages. However, the last mask used will always be // 0x1 and the second to last mask used will always be 0x4. for (i = 0; i < OUTPUT_BITS; i = i + 1) begin: mask_4 if (i % 2) // i is odd, this is a 4 mask assign mask_gen[INPUT_BITS*(OUTPUT_BITS-i)-1:INPUT_BITS*(OUTPUT_BITS-i-1)] = 4 << 4 * (i/2); else // i is even, this is a 1 mask assign mask_gen[INPUT_BITS*(OUTPUT_BITS-i)-1:INPUT_BITS*(OUTPUT_BITS-i-1)] = 1 << 4 * (i/2); end // Generate all the pipeline stages to compute the square root of // the input radicand stream. The general approach is to compare // the current values of the root plus the mask to the // radicand. If root/mask sum is greater than the radicand, // subtract the mask and the root from the radicand and store the // radicand for the next stage. Additionally, the root is // increased by the value of the mask and stored for the next // stage. If this test fails, then the radicand and the root // retain their value through to the next stage. The one weird // thing is that the mask indices appear to be incremented by one // additional position. This is not the case, however, because the // first mask is used in the first stage (always block after the // generate statement). for (i = 0; i < OUTPUT_BITS - 1; i = i + 1) begin: pipeline always @ (posedge clk or negedge reset_n) begin : pipeline_stage if (!reset_n) begin start_gen[i+1] <= 0; radicand_gen[INPUT_BITS*(i+2)-1:INPUT_BITS*(i+1)] <= 0; root_gen[INPUT_BITS*(i+2)-1:INPUT_BITS*(i+1)] <= 0; end else begin start_gen[i+1] <= start_gen[i]; if ((root_gen[INPUT_BITS*(i+1)-1:INPUT_BITS*i] + mask_gen[INPUT_BITS*(i+2)-1:INPUT_BITS*(i+1)]) <= radicand_gen[INPUT_BITS*(i+1)-1:INPUT_BITS*i]) begin radicand_gen[INPUT_BITS*(i+2)-1:INPUT_BITS*(i+1)] <= radicand_gen[INPUT_BITS*(i+1)-1:INPUT_BITS*i] - mask_gen[INPUT_BITS*(i+2)-1:INPUT_BITS*(i+1)] - root_gen[INPUT_BITS*(i+1)-1:INPUT_BITS*i]; root_gen[INPUT_BITS*(i+2)-1:INPUT_BITS*(i+1)] <= (root_gen[INPUT_BITS*(i+1)-1:INPUT_BITS*i] >> 1) + mask_gen[INPUT_BITS*(i+2)-1:INPUT_BITS*(i+1)]; end else begin radicand_gen[INPUT_BITS*(i+2)-1:INPUT_BITS*(i+1)] <= radicand_gen[INPUT_BITS*(i+1)-1:INPUT_BITS*i]; root_gen[INPUT_BITS*(i+2)-1:INPUT_BITS*(i+1)] <= root_gen[INPUT_BITS*(i+1)-1:INPUT_BITS*i] >> 1; end end end end endgenerate // This is the final stage which just implements a rounding // operation. This stage could be tacked on as a combinational logic // stage, but who cares about latency, anyway? This is NOT a true // rounding stage. In order to add convergent rounding, you need to // increase the input bit width by 2 (increase the number of // pipeline stages by 1) and implement rounding in the module that // instantiates this one. always @ (posedge clk or negedge reset_n) begin if (!reset_n) begin data_valid <= 0; root <= 0; end else begin data_valid <= start_gen[OUTPUT_BITS-1]; if (root_gen[OUTPUT_BITS*INPUT_BITS-1:OUTPUT_BITS*INPUT_BITS-INPUT_BITS] > root_gen[OUTPUT_BITS*INPUT_BITS-1:OUTPUT_BITS*INPUT_BITS-INPUT_BITS]) root <= root_gen[OUTPUT_BITS*INPUT_BITS-1:OUTPUT_BITS*INPUT_BITS-INPUT_BITS] + 1; else root <= root_gen[OUTPUT_BITS*INPUT_BITS-1:OUTPUT_BITS*INPUT_BITS-INPUT_BITS]; end end endmodule
2301_81045437/verilog
src/sqrt_pipelined.v
Verilog
apache-2.0
6,717
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Uart receiver module. Reads data from a serial UART line (rx) and // outputs it over a parallel bus (data) based on the clock frequency // of the FPGA and the anticipated UART frequency. //`define PARITY // enable parity bit (not implemented) module uart_rx #( parameter CLK_FREQUENCY = 66_000_000, // fpga clock frequency UART_FREQUENCY = 921_600 // UART clock frequency ) ( input clk, rst_n, rx, // 1-bit inputs output reg valid, // signals that data is valid output reg [7:0] data // output parallel data ); reg [2:0] state, next_state; // state/next state variables reg [3:0] bit_count; // remembers the bit that we're on reg [7:0] data_tmp; // stores intermediate values for data reg [14:0] tick_count; // used to know when to read rx line localparam TICKS_PER_BIT = CLK_FREQUENCY / UART_FREQUENCY, HALF_TICKS_PER_BIT = TICKS_PER_BIT / 2, NUM_BITS = 4'd8; localparam IDLE = 3'd0, // wait for a transmission to come in START = 3'd1, // start bit DATA = 3'd2, // data bits // PARITY = 3'd3, // parity bit (not implemented) VALID = 3'd4, // output valid data STOP = 3'd5; // stop bit always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin tick_count <= 15'b0; bit_count <= 4'b0; end else begin case (state) START: begin tick_count <= (tick_count==HALF_TICKS_PER_BIT) ? 15'b0 : tick_count + 15'b1; bit_count <= 4'b0; end DATA: begin tick_count <= (tick_count==TICKS_PER_BIT-1) ? 15'b0 : tick_count + 15'b1; bit_count <= (tick_count==TICKS_PER_BIT-1) ? bit_count + 1 : bit_count; end VALID: begin tick_count <= tick_count + 15'b1; end STOP: begin tick_count <= (tick_count==TICKS_PER_BIT-1) ? 15'b0 : tick_count + 15'b1; end default: begin tick_count <= 15'b0; bit_count <= 4'b0; end endcase end end always @ (posedge clk or negedge rst_n) state <= (!rst_n) ? IDLE : next_state; always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin data <= 8'b0; data_tmp <= 8'b0; valid <= 1'b0; end else begin data <= 8'bx; data_tmp <= data_tmp; valid <= 0; case (state) IDLE: data_tmp <= 8'bx; START: data_tmp <= 8'bx; DATA: if (tick_count == TICKS_PER_BIT-1) data_tmp[bit_count] <= rx; VALID: begin data <= data_tmp; valid <= 1'b1; end STOP: data_tmp <= 8'bx; endcase end end always @ * begin case (state) IDLE: next_state = (!rx) ? START : state; START: next_state = (tick_count==HALF_TICKS_PER_BIT) ? DATA : state; DATA: next_state = ((tick_count==TICKS_PER_BIT - 1) & (bit_count==NUM_BITS - 1))?VALID:state; // PARITY: next_state = () ? : state; VALID: next_state = STOP; STOP: next_state = (tick_count==TICKS_PER_BIT-1) ? IDLE : state; default: next_state = IDLE; endcase end endmodule
2301_81045437/verilog
src/uart_rx.v
Verilog
apache-2.0
4,176
// Copyright 2018 Schuyler Eldridge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module uart_tx #( parameter CLK_FREQUENCY = 66_000_000, // fpga clock frequency UART_FREQUENCY = 921_600 // UART clock frequency ) ( input user_clk, // 66 MHz input rst_n, input start_tx, input [7:0] data, output reg tx_bit, output reg ready, output reg chipscope_clk ); localparam TICKS_PER_BIT = CLK_FREQUENCY / UART_FREQUENCY; localparam IDLE = 2'd0, INIT = 2'd1, TX = 2'd2, DONE = 2'd3; reg [ 1:0] state, next_state; reg [ 2:0] bit_count; reg [ 7:0] data_buf; reg [11:0] clk_count; always @ (posedge user_clk or negedge rst_n) begin if (!rst_n) chipscope_clk <= 0; else if ((clk_count == TICKS_PER_BIT-1) | (clk_count == TICKS_PER_BIT>>1)) chipscope_clk <= ~chipscope_clk; else chipscope_clk <= chipscope_clk; end always @ (posedge user_clk or negedge rst_n) begin state <= (!rst_n) ? IDLE : next_state; end always @ (posedge user_clk or negedge rst_n) begin if (!rst_n) begin tx_bit <= 1; // should be pulled up on reset ready <= 1; data_buf <= 0; bit_count <= 0; clk_count <= 0; end else begin case (state) IDLE: begin tx_bit <= 1; ready <= 1; data_buf <= data; bit_count <= 0; clk_count <= 0; end INIT: begin tx_bit <= 0; ready <= 0; data_buf <= data_buf; bit_count <= 0; clk_count <= (clk_count == TICKS_PER_BIT-1) ? 12'b0 : clk_count + 12'b1; end TX: begin tx_bit <= data_buf[bit_count]; ready <= 0; data_buf <= data_buf; bit_count <= (clk_count == TICKS_PER_BIT-1) ? bit_count+3'b1 : bit_count; clk_count <= (clk_count == TICKS_PER_BIT-1) ? 12'b0 : clk_count + 12'b1; end DONE: begin tx_bit <= 1; ready <= 0; data_buf <= data_buf; bit_count <= 0; clk_count <= (clk_count == TICKS_PER_BIT-1) ? 12'b0 : clk_count + 12'b1; end default: begin tx_bit <= 1'bx; ready <= 1'bx; data_buf <= 8'bx; bit_count <= 3'bx; clk_count <= 12'bx; end endcase end end always @ * begin case (state) IDLE: next_state <= (start_tx) ? INIT : state; INIT: next_state <= (clk_count == TICKS_PER_BIT-1) ? TX : state; TX: next_state <= ((bit_count == 7) & (clk_count == TICKS_PER_BIT-1)) ? DONE : state; DONE: next_state <= (clk_count == TICKS_PER_BIT-1) ? IDLE : state; default: next_state <= IDLE; endcase end endmodule
2301_81045437/verilog
src/uart_tx.v
Verilog
apache-2.0
3,520
import os import streamlit as st import time from dotenv import load_dotenv import random from langchain_community.document_loaders import TextLoader from langchain_text_splitters import CharacterTextSplitter from langchain_community.vectorstores import Chroma from langchain_community.embeddings import QianfanEmbeddingsEndpoint from langchain_community.chat_models import QianfanChatEndpoint from langchain.chains import RetrievalQA from langchain.prompts import PromptTemplate # 加载环境变量 load_dotenv() # 从环境变量读取秘钥 os.environ["QIANFAN_ACCESS_KEY"] = os.getenv("QIANFAN_ACCESS_KEY") os.environ["QIANFAN_SECRET_KEY"] = os.getenv("QIANFAN_SECRET_KEY") st.set_page_config(page_title="文心·慧眼:基于竞品数据的电商差异化营销大脑", page_icon="🌌", layout="wide") # 注入自定义 CSS 进行极大美化 def local_css(): st.markdown(""" <style> /* 全局字体与背景 */ .stApp { background: linear-gradient(to bottom right, #f8f9fa, #e9ecef); font-family: 'PingFang SC', 'Helvetica Neue', sans-serif; } /* 侧边栏美化 */ section[data-testid="stSidebar"] { background-color: #ffffff; box-shadow: 2px 0 10px rgba(0,0,0,0.05); } /* 标题样式 */ h1, h2, h3 { color: #2c3e50; font-weight: 700; } h1 { background: -webkit-linear-gradient(45deg, #4e54c8, #8f94fb); -webkit-background-clip: text; -webkit-text-fill-color: transparent; padding-bottom: 10px; } /* 按钮美化 */ div.stButton > button { background: linear-gradient(90deg, #4e54c8 0%, #8f94fb 100%); color: white; border: none; border-radius: 8px; padding: 0.6rem 1.2rem; font-weight: 600; transition: all 0.3s ease; box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08); } div.stButton > button:hover { transform: translateY(-2px); box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08); background: linear-gradient(90deg, #3f44a5 0%, #7d82e8 100%); } /* 消息卡片样式 */ .chat-card { padding: 20px; border-radius: 12px; margin-bottom: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); background-color: white; border-left: 5px solid #4e54c8; } /* 耗时徽章 */ .time-badge { display: inline-block; background-color: #e3f2fd; color: #1565c0; padding: 2px 8px; border-radius: 12px; font-size: 0.8em; font-weight: bold; margin-top: 5px; } </style> """, unsafe_allow_html=True) local_css() # ========================================== # 2. 核心逻辑:文件处理 # ========================================== @st.cache_resource def process_uploaded_file(file_content, file_name): """读取用户上传的产品资料 -> 存入向量数据库""" if not os.path.exists("./temp_data"): os.makedirs("./temp_data") file_path = os.path.join("./temp_data", file_name) with open(file_path, "wb") as f: f.write(file_content) loader = TextLoader(file_path, encoding='utf-8') documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=400, chunk_overlap=50) docs = text_splitter.split_documents(documents) embeddings = QianfanEmbeddingsEndpoint() db = Chroma.from_documents(docs, embeddings) return db def process_custom_style_files(uploaded_files): """处理用户上传的自定义风格参考文件""" combined_text = "" for uploaded_file in uploaded_files: # 读取文本内容 content = str(uploaded_file.read(), encoding="utf-8") # 简单截取前1000字作为风格样本,避免Token溢出 combined_text += f"\n【参考范文片段】:\n{content[:800]}...\n" return combined_text # ========================================== # 3. 核心逻辑:Prompt 策略 (包含新增逻辑) # ========================================== def get_prompt_template(style, custom_style_content=None): # 通用营销大脑:教 AI 怎么把参数变成卖点 marketing_brain = """ 你是一个金牌电商营销专家。请阅读这份【产品资料】,并基于资料回答用户需求。 【思维链(你要怎么思考)】: 1. 看到"参数",联想"痛点"。 (如:看到298g -> 联想"轻盈手感") 2. 严格遵守资料里的"品牌调性"和"违禁词"。 3. 🔥 **核心卖点深挖(Deep Dive)**:找出产品最核心的1-2个卖点,绝不能一笔带过!必须使用"显微镜式"描写——通过排比、场景构建、感官描述(视觉/触觉/听觉)将这部分的篇幅拉长,使其在文中占据绝对的视觉重心,体现技术应用的深度。 """ # 基础模板 templates = { "小红书种草": marketing_brain + """ 【请模仿以下范文的语气】: 1.范文一: 标题:[产品名称]杀到!这波配置直接把我香晕了🤩 正文: 家人们![产品名称]的爆料也太炸了吧!作为一个资深[品牌]粉,看完这些信息我已经坐不住了!😤 首先说外观,[核心设计部位]要搞大事情!新增 [具体配置A] + [具体配置B],外观走 [设计风格形容词] 的路子,辨识度直接拉满!✨ 屏幕方面更绝,[型号A] 和 [型号B] 是[xx党]狂喜的设计,不管你爱哪种,都能选到心头好~❤️ 性能这块更是王炸!全系搭载 [核心技术/系统],搭配传说中的 [核心处理器/马达/引擎],流畅度和功耗控制想想就激动!🚀 [其他功能] 这些咱先不说,就这外观和性能的升级,已经让我开始疯狂期待了![品牌名称] 这波操作,是要把 [产品品类] 的天花板再抬高一截啊!📈 2.范文二: 标题:对 [特定人群/来源] 的 [产品品类] 真香了![核心卖点] 被我挖到了! 正文: 之前总觉得 [产品品类] 是智商税 🧠 直到 [朋友/同事] 给我试了这支 说是从 [可靠来源] 那安利到的 现在 [周围圈子] 都在用!✌🏻 [型号/颜色A] 上手是 [效果形容词A] ✌︎' ֊' 另一款 [型号/颜色B] 是 [效果形容词B] 就像 [理想状态形容词] [使用场景] 瞬间 [核心功效] [急救场景(如早八/加班)] 来不及 [复杂动作] 用它直接冲 [目的地] 😎 成分安心到离谱! [核心成分A] + [核心成分B] 不仅 [基础功效],还能 [进阶功效] 🥰 最近连 [隔壁人群] 都来问链接 果然好东西藏不住! 3.范文三: 标题:被 [亲密关系称呼] 强行安排的 [产品名称] 初体验…结果真香了!!😭 正文: 来对 [产品品类] 一直是观望状态,总觉得 [刻板印象/顾虑点] 🤔 结果某 [亲密关系称呼] 非说"[推荐理由/诱导话术]",硬拉着我 [购买/体验] 了一套… [使用/上手] 的瞬间真的有被惊到!😳 [核心参数/design] 意外 [体验感受/解决痛点]!!✨ 以前总觉得这种 [风格/产品] 离自己很远,没想到尝试之后居然有点上头…💘 果然 [感叹句/总结句]! 你们的 [产品名称] 初体验也是这样吗?🙈 4.范文四: 标题:大型真香现场!🥹我居然爱上了 [长辈称呼] 同款 [产品品类] 正文: 以前每次 [接触/使用] 我爸的 [旧款产品] 都偷偷吐槽 "这也太中年老干部风了吧" 🤣 直到刷到 [新产品型号] —— 直接被狠狠戳中!💘 这还是我认识的 [品牌/品类] 吗?! 颜值暴击💥 [核心气质] 拉满! [外观设计A] + [外观设计B],像 [比喻对象] 一样酷! 再配上 [专属配置],好几次被路人问 "这是新款 [高级品类] 吗"? 完全打破 "[产品品类] = [刻板印象]" 的魔咒好吗! 现在轮到我调侃老爸了 😎 每次 [使用场景] 的时候,都故意在我爸面前晃 🤪 "爸,你那老 [旧款产品] 该更新换代啦,你看我的比你还潮!" 我爸嘴上不服气,却偷偷 [偷窥/体验] 了好几回我的 [产品核心部位] 😉hhh 谁能想到啊!曾经嫌弃的 [产品品类],现在成了我出门必炫耀的心头好 🥳 果然选 [产品品类] 不能凭刻板印象,[新产品型号] 真的太懂年轻人了!😍 5.范文五: 标题:种草 [产品名称]!用了它之后,我的 [使用场景] 变得超 [积极形容词] 了! 正文: 最近入手了 [产品名称],真的是太惊喜了!✨ 作为一个 [用户身份/背景],我对 [产品品类] 的要求还是挺高的。 但是这款 [产品名称] 完全超出了我的预期!😍 首先,它的 [核心卖点A] 让我在 [使用场景] 时感到非常 [积极形容词A]。以前我总觉得 [使用场景] 是一件麻烦事,但有了它,一切都变得轻松多了!💪 其次,它的 [核心卖点B] 也让我爱不释手。在 [使用场景B] 的时候,我能明显感觉到它带来的便利和舒适感。真的让我对 [产品品类] 有了全新的认识!🌟 最后,我还要说的是它的 [核心卖点C]。这让我在 [使用场景C] 时,体验感提升了一个档次!简直是为我们这些 [用户身份/背景] 量身定做的啊!🎯 总之,种草 [产品名称] 绝对没错!如果你和我一样是个 [用户身份/背景],强烈推荐你也试试这款神器!相信我,你会爱上它的!😍🔥 【现在轮到你了】: 产品资料:{context} 用户需求:{question} 【生成要求 - 加强版】: 1. 智能匹配:根据【产品资料】特性,从上方 5 个范文中选择最贴切的一个进行深度模仿。 2. 🔥 **语气强制**:必须使用极其情绪化的"网络黑话"! - 强制使用词库:绝绝子、yyds、家人们、真香、拿捏、翘楚、天花板、救命、暴风吸入(如果适用)。 - 禁止使用:虽然但是、总的来说、综上所述(太书面了)。 3. 🔥 **Emoji 密度**:每两句话必须带一个 Emoji (✨🔥😭🥺😎),这一条非常重要! 4. 🛑 防幻觉指令:语气可以夸张,但**具体参数(价格、配置、型号)必须严格来自【产品资料】,严禁编造资料里没有的数据!** 5. 结尾必须带 5 个以上的话题标签(Hashtag)。 6. 🔥 **(新增) 核心卖点扩写**:请从产品中挑出 1 个最强痛点(例如技术参数或功效),用"痛点描述 + 夸张的解决效果 + 个人主观感受"的三层逻辑详细展开,这一段的字数要比其他段落多一倍,把它吹爆! """, "抖音直播脚本": marketing_brain + """ 【请模仿以下范文的语气】: 1.范文一: 主播:来!所有女生!看这里!👀 主播:(展示动作) 大家看这个细节,是不是薄如蝉翼?✨ 主播:外面专柜要卖多少?5999!今天在我直播间,把价格打下来!只要2999!🔥 主播:库存只有最后50单,3!2!1!上链接!🔗 2.范文二: 主播:Oh my god!所有女生!你们的魔鬼来咯!🔔 主播:(展示特写) 你们看这个 [产品核心细节],简直是把"高级"两个字写在了脸上!✨ 主播:老板娘在吗?原价 [原价] 我真的不敢看!今天李老头给你们炸到 [现价]!买一送一!💥 主播:美眉们,全中国只有最后2000组,手慢无!买它!买它!买它!❗️ 3.范文三: 主播:兄弟们!别眨眼!给我上才艺!🤜 主播:(进行暴力测试动作) 看到没有?怎么 [破坏性动作] 都不坏!这就是质量!这就是硬货!🧱 主播:品牌方今天不想过了是吧?[原价] 不要!给我改成 [现价]!直接上车!🚑 主播:有没有?没抢到的扣1!后台再加500单!手速要快!给兄弟们炸!⚡️ 4.范文四: 主播:听听!都给我听听!别去买外面那些智商税了!😒 主播:(傲娇展示) 看看这 [产品质感],K总什么时候骗过你们?这带出去多有面子?💅 主播:今天这价格,我是真没赚钱,纯粹给姐姐们谋福利![现价]!闭眼冲!🤐 主播:只有这一波啊,抢不到别来私信我哭!去拍!链接在左下角!🛍️ 【现在轮到你了】: 产品资料:{context} 用户需求:{question} 【生成要求 - 加强版】: 1. 智能匹配:根据产品属性,选择最合适的一个主播风格。 2. 🔥 **节奏强制**:必须是"短句"+"感叹号"!不要长篇大论! 3. 🔥 **互动感**:必须包含与弹幕的互动,例如:"没抢到的扣1"、"觉得贵的把'贵'打在公屏上"、"后台运营别睡了赶紧上库存"。 4. 🛑 防幻觉指令:范文里的"2999"是假数据,不要抄!**请务必去【产品资料】里找真实的价格和库存!**如果资料没写价格,就说"价格炸裂"或者"给到骨折价"。 5. ⏱️ **专业时间轴规划**:请务必按照直播带货的黄金节奏,为脚本加上明确的**粗体时间标记**。请严格参考以下结构: - **【0-30秒】痛点引入**:不要直接卖货!先讲生活中遇到的麻烦,引发共鸣,留住观众。 - **【30-60秒】产品介绍**:亮出产品,展示核心卖点(对应解决痛点)。 - **【60-90秒】高潮演示**:进行暴力测试、上脸实测或特写展示,证明效果。 - **【90-120秒】逼单时刻**:强调价格优势、赠品和库存紧张,引导下单。 6. 🔥 **(新增) 卖点高光时刻**:在【30-60秒】或【60-90秒】区间,对于最核心的技术/卖点,必须使用连续 3 个感叹句或反问句进行高强度强调(如:"这就是X技术!懂行的兄弟们打个懂!还有谁能做到?"),增加语气的爆发力。 """, "京东详情页": marketing_brain + """ 【请模仿以下五篇范文的语气】: 【范文1:核心技术解析】搭载行业领先的第V代数字引擎,效率提升30%。这意味着,它能从源头上解决卡顿痛点。 【范文2:工艺美学】机身采用航空级铝合金材质,经由CNC精密雕刻,触感细腻冷冽。 【范文3:生物黑科技风(适合美妆/护肤)】 【核心成分解析】蕴含高浓度 [核心成分名称],深入肌底,从源头激活 [细胞/胶原] 再生。 【夜间修护科技】搭载独家 [技术名称] 科技,精准捕捉受损因子,在 [时间段] 释放修护能量。 【范文4:人体工学风(适合椅子/鞋服)】 【仿生脊椎设计】依据 [人体工学原理],打造 [结构名称] 支撑系统。它能自动贴合您的 [身体部位] 曲线,提供动态支撑。 【专利网面科技】采用 [材质名称] 材质,具有独特的 [材质特性],均匀分散身体压力。 【范文5:精密机械风(适合咖啡机/电器)】 【恒温萃取系统】配备 [加热技术名称],精准控制水温在 [温度范围]°C 黄金萃取区间,完美释放 [原料] 的原有风味。 【研磨工艺】内置 [磨盘材质] 锥形磨豆器,支持 [数值] 档研磨粗细调节。 【现在轮到你了】: 产品资料:{context} 用户需求:{question} 【生成要求 - 严格遵守】: 1. 智能匹配:请根据【产品资料】的类型,自动选择上面 5 个范文中**最贴切的一种风格**进行模仿。 2. 语气要求:专业、严谨、客观、数据支撑。多用"搭载"、"配备"、"源于"、"甄选"等高级词汇。 3. 🛑 防幻觉指令:范文里的具体参数(如"30%"、"CNC")仅供参考句式!**所有参数必须严格来自【产品资料】,严禁编造资料里没有的数据!** 4. 🔥 **(新增) 技术深度解析**:针对 1-2 个核心技术参数,不能只列数据!必须采用"原理+数据+体验"的深度写法(例如:不仅说搭载了X引擎,还要解释X引擎是如何工作的,以及它让用户的使用感受提升了多少),体现专业壁垒。 """ } # 4. 🔥 【新增】自定义风格逻辑 if style == "✨ 自定义风格 (Custom)" and custom_style_content: # 修复:使用字符串替换而不是 f-string 或 .format() custom_template = marketing_brain + """ 【你收到了一些参考资料(论文/爆文),请严格模仿其语感】: {custom_style_content} 【现在轮到你了】: 产品资料:{context} 用户需求:{question} 【生成要求 - 严格遵守】: 1. 🔥 **风格迁移**:请分析上述【参考范文片段】的句式结构、用词专业度、情感色彩,并完全模仿这种风格来撰写本次的文案。 2. 🛑 **严禁数据混淆**:参考范文中的任何具体数据(如价格、参数、型号、实验数据)**一律不准使用**!你只能使用【产品资料】里的数据。 3. 🔥 **核心卖点深挖**:如上所述,对核心卖点进行显微镜式扩写,字数加倍。 """ # 直接替换占位符 custom_template = custom_template.replace("{custom_style_content}", custom_style_content) return custom_template return templates.get(style, templates["小红书种草"]) # ========================================== # 4. 辅助功能函数 # ========================================== def competitor_analysis(product_context, llm): """🔍 竞争情报分析系统""" start_time = time.time() # ⏱️ 计时开始 analysis_prompt = f""" 基于以下产品资料,请进行简短的【竞争情报分析】: 产品资料摘要:{product_context[:500]}... 请输出以下JSON格式信息(不要输出Markdown,直接输出文本): 1. 【竞品对标】:列出市面上可能的2个竞争对手类型。 2. 【差异化优势】:该产品打败竞品的1个核心杀手锏是什么? 3. 【营销切入点】:建议从什么刁钻的角度进行宣传? """ try: response = llm.invoke(analysis_prompt) end_time = time.time() # ⏱️ 计时结束 return response.content, end_time - start_time except: return "无法连接竞争情报数据库...", 0 def virtual_review_board(generated_content, llm, style): """👥 虚拟评审团 (自适应风格)""" start_time = time.time() # ⏱️ 计时开始 review_criteria = { "小红书种草": { "intro": "你现在是【小红书爆文鉴赏团】。专注于:颜值、种草力、情绪价值。", "roles": "**💅 颜值博主**:[点评美感]\n**🗣️ 互动运营**:[点评互动引导]\n**⚖️ 合规专家**:[检查违禁词]", }, "抖音直播脚本": { "intro": "你现在是【抖音直播间操盘手】。专注于:黄金三秒、节奏感、逼单话术。", "roles": "**🎬 直播导演**:[点评节奏]\n**💰 投流专家**:[点评转化潜力]\n**⚖️ 合规专家**:[检查虚假宣传]", }, "京东详情页": { "intro": "你现在是【京东电商产品经理】。专注于:专业度、参数准确性、信任背书。", "roles": "**👨‍🔬 产品经理**:[点评逻辑]\n**📉 转化专家**:[点评信任感]\n**⚖️ 合规专家**:[检查广告法]", }, "✨ 自定义风格 (Custom)": { "intro": "你现在是【高级内容审核主编】。专注于:风格一致性、逻辑自洽性。", "roles": "**📝 主编**:[点评风格还原度]\n**🕵️ 事实核查员**:[检查是否混淆了参考资料的数据]", } } # 默认为小红书,防止KeyError current = review_criteria.get(style, review_criteria["小红书种草"]) review_prompt = f""" {current['intro']} 文案:{generated_content} 请输出评审结果(仅输出专家会诊部分,保持客观): ### 👥 专家会诊 {current['roles']} (请针对文案进行打分和简评,不要直接重写文案) """ response = llm.invoke(review_prompt) end_time = time.time() # ⏱️ 计时结束 return response.content, end_time - start_time def rewrite_content(original_content, review_feedback, llm): """(新增功能) 🔧 一键优化""" start_time = time.time() # ⏱️ 计时开始 rewrite_prompt = f""" 你是一个精益求精的文案大师。请根据【评审团意见】修改【原始文案】。 【原始文案】: {original_content} 【评审团意见(参考诊断)】: {review_feedback} 【修改要求】: 1. 必须根据诊断意见优化痛点。 2. 保持原有的平台风格。 3. 🔥 **重点**:对被专家表扬或指出的核心卖点,请进一步增加细节描述,强化技术应用的深度。 4. 直接输出修改后的完整文案,不要废话。 """ response = llm.invoke(rewrite_prompt) end_time = time.time() # ⏱️ 计时结束 return response.content, end_time - start_time # ========================================== # 5. 前端界面 (Streamlit) # ========================================== st.title("🌌 文心·慧眼:基于竞品数据的电商差异化营销大脑") st.markdown("**🚀 融合 竞争情报分析 + RAG生成 + 虚拟评审 (v2.0 Pro)**") # 初始化Session if "db" not in st.session_state: st.session_state.db = None if "messages" not in st.session_state: st.session_state.messages = [{"role": "assistant", "content": "👋 您好!我是您的智能营销助手。请上传产品资料,我将为您生成全案策略。"}] if "last_review" not in st.session_state: st.session_state.last_review = "" if "raw_text" not in st.session_state: st.session_state.raw_text = "" if "custom_style_data" not in st.session_state: st.session_state.custom_style_data = None # --- 侧边栏 --- with st.sidebar: st.image("https://cdn-icons-png.flaticon.com/512/4712/4712035.png", width=80) st.header("📂 资料中心") with st.expander("📝 第一步:产品资料 (必须)", expanded=True): uploaded_file = st.file_uploader("上传产品说明书 (TXT)", type=['txt']) if uploaded_file and st.session_state.db is None: with st.spinner("🔄 正在构建向量索引..."): st.session_state.db = process_uploaded_file(uploaded_file.getvalue(), uploaded_file.name) st.session_state.raw_text = str(uploaded_file.getvalue(), encoding='utf-8') st.success(f"✅ 已就绪:{uploaded_file.name}") st.divider() st.header("⚙️ 策略控制台") # 增加自定义风格选项 style = st.selectbox("目标风格", ["小红书种草", "抖音直播脚本", "京东详情页", "✨ 自定义风格 (Custom)"]) # 📂 自定义风格上传区 if style == "✨ 自定义风格 (Custom)": with st.expander("📂 上传风格参考 (论文/爆文)", expanded=True): style_files = st.file_uploader( "请上传 1-10 个参考文件 (TXT/MD)", type=['txt', 'md'], accept_multiple_files=True ) if style_files: if len(style_files) > 10: st.warning("⚠️ 最多支持10个文件,将仅使用前10个。") style_files = style_files[:10] st.session_state.custom_style_data = process_custom_style_files(style_files) st.info(f"✅ 已提取 {len(style_files)} 份文档的风格特征") else: st.session_state.custom_style_data = None st.warning("请上传参考文件以激活自定义风格!") model_name = st.selectbox("模型引擎", ["ERNIE-4.0-8K", "ERNIE-3.5-8K", "ERNIE-Speed-128K"]) col_t1, col_t2 = st.columns(2) with col_t1: enable_competitor = st.toggle("🔍 竞争情报", value=True) with col_t2: enable_review = st.toggle("👥 虚拟评审", value=True) st.divider() if st.button("🔄 重置系统"): st.cache_resource.clear() st.session_state.clear() st.rerun() # --- 主界面 --- # 历史消息渲染 for msg in st.session_state.messages: # 使用自定义CSS类包裹消息 st.markdown(f'<div class="chat-card">', unsafe_allow_html=True) with st.chat_message(msg["role"]): # 检测是否是子内容(竞争情报 或 虚拟评审),如果是则折叠显示 if "### 🔍 竞争情报分析" in msg["content"]: with st.expander("🔍 竞争情报分析 (点击展开)"): st.markdown(msg["content"]) # 提取耗时(如果有) if "cost_time" in msg: st.markdown(f'<div class="time-badge">⏱️ 耗时: {msg["cost_time"]:.2f}s</div>', unsafe_allow_html=True) elif "### 👥 虚拟评审团" in msg["content"]: with st.expander("👥 虚拟评审团意见 (点击展开)"): st.markdown(msg["content"]) if "cost_time" in msg: st.markdown(f'<div class="time-badge">⏱️ 耗时: {msg["cost_time"]:.2f}s</div>', unsafe_allow_html=True) else: # 正常显示主文案 st.markdown(msg["content"]) if "cost_time" in msg: st.markdown(f'<div class="time-badge">⏱️ 耗时: {msg["cost_time"]:.2f}s</div>', unsafe_allow_html=True) st.markdown('</div>', unsafe_allow_html=True) # --- 输入逻辑 --- prompt = st.chat_input("💡 输入需求(例如:帮我写个种草文案,核心卖点是续航)") if prompt: # 检查自定义风格是否就绪 if style == "✨ 自定义风格 (Custom)" and not st.session_state.custom_style_data: st.error("❌ 请先在左侧上传【自定义风格】参考文件!") elif st.session_state.db is None: st.error("❌ 请先在左侧上传【产品资料】文件!") else: st.session_state.messages.append({"role": "user", "content": prompt}) # 立即渲染用户提问,不等待 with st.chat_message("user"): st.markdown(prompt) try: llm = QianfanChatEndpoint(model=model_name, temperature=0.7) # 1. 文案生成 (核心内容) # 传入自定义风格内容(如果有) current_template = get_prompt_template(style, st.session_state.custom_style_data) PROMPT = PromptTemplate(template=current_template, input_variables=["context", "question"]) qa_chain = RetrievalQA.from_chain_type( llm=llm, retriever=st.session_state.db.as_retriever(search_kwargs={"k": 2}), chain_type_kwargs={"prompt": PROMPT} ) with st.chat_message("assistant"): # A. 生成主文案 start_gen = time.time() # ⏱️ with st.spinner(f"✍️ AI ({model_name}) 正在创作..."): response = qa_chain.invoke({"query": prompt}) generated_text = response['result'] gen_time = time.time() - start_gen # ⏱️ st.markdown(f"## 📝 生成内容\n\n{generated_text}") st.markdown(f'<div class="time-badge">⏱️ 耗时: {gen_time:.2f}s</div>', unsafe_allow_html=True) st.session_state.messages.append({ "role": "assistant", "content": f"## 📝 生成内容\n\n{generated_text}", "cost_time": gen_time }) # B. 生成竞争情报 if enable_competitor and st.session_state.raw_text: with st.status("🔍 正在分析市场数据...", expanded=False) as status: insight, comp_time = competitor_analysis(st.session_state.raw_text, llm) st.session_state.messages.append({ "role": "assistant", "content": f"### 🔍 竞争情报分析\n\n{insight}", "cost_time": comp_time }) status.update(label=f"✅ 竞争情报已生成 ({comp_time:.2f}s)", state="complete") # C. 生成虚拟评审 if enable_review: with st.status("👥 专家评审团正在会诊...", expanded=False) as status: review_result, review_time = virtual_review_board(generated_text, llm, style) st.session_state.last_review = review_result st.session_state.messages.append({ "role": "assistant", "content": f"### 👥 虚拟评审团\n\n{review_result}", "cost_time": review_time }) status.update(label=f"✅ 专家评审已完成 ({review_time:.2f}s)", state="complete") st.rerun() except Exception as e: st.error(f"系统错误: {e}") # --- 底部功能区 --- if (st.session_state.messages and st.session_state.messages[-1]["role"] == "assistant"): st.divider() col1, col2 = st.columns([1, 4]) with col1: if st.session_state.get("last_review"): if st.button("🔧 一键优化 (Auto-Refine)", type="primary", help="根据评审团意见自动重写"): with st.spinner("⚡️ AI 正在根据专家意见重写文案..."): llm = QianfanChatEndpoint(model=model_name, temperature=0.7) # 寻找最近的生成内容 original_msg = None for i in range(len(st.session_state.messages)-1, -1, -1): if "生成内容" in st.session_state.messages[i]["content"]: original_msg = st.session_state.messages[i] break if original_msg: original_content = original_msg["content"].replace("## 📝 生成内容\n\n", "") review = st.session_state.last_review new_version, rewrite_time = rewrite_content(original_content, review, llm) st.session_state.messages.append({ "role": "assistant", "content": f"## ✅ 优化版本\n\n{new_version}", "cost_time": rewrite_time }) st.session_state.last_review = "" st.rerun() else: st.button("🔧 一键优化", disabled=True)
2301_81173397/wenxin-huiyan
main.py
Python
unknown
32,684
@inproceedings{TableDetect, author = {Faisal Shafait and Ray Smith}, booktitle = {Document Analysis Systems}, editor = {David S. Doermann and Venu Govindaraju and Daniel P. Lopresti and Premkumar Natarajan}, pages = {65--72}, publisher = {ACM}, series = {ACM International Conference Proceeding Series}, title = {Table detection in heterogeneous documents.}, url = {http://dblp.uni-trier.de/db/conf/das/das2010.html#ShafaitS10}, year = 2010, isbn = {978-1-60558-773-8}, date = {2010-07-07} } @inproceedings{Multilingual, author = {Ray Smith and Daria Antonova and Dar-Shyang Lee}, booktitle = {MOCR '09: Proceedings of the International Workshop on Multilingual OCR}, editor = {Venu Govindaraju and Premkumar Natarajan and Santanu Chaudhury and Daniel P. Lopresti}, pages = {1--8}, publisher = {ACM}, series = {ACM International Conference Proceeding Series}, title = {Adapting the Tesseract Open Source OCR Engine for Multilingual OCR.}, url = {https://storage.googleapis.com/pub-tools-public-publication-data/pdf/35248.pdf}, year = 2009, isbn = {978-1-60558-698-4}, date = {2009-07-25}, doi = {http://doi.acm.org/10/1145/1577802.1577804}, location = {Barcelona, Spain}, } @inproceedings{ScriptDetect, author = {Ranjith Unnikrishnan and Ray Smith}, title = {Combined Orientation and Script Detection using the Tesseract OCR Engine}, booktitle = {MOCR '09: Proceedings of the International Workshop on Multilingual OCR}, editor = {Venu Govindaraju and Premkumar Natarajan and Santanu Chaudhury and Daniel P. Lopresti}, url = {https://storage.googleapis.com/pub-tools-public-publication-data/pdf/35506.pdf}, year = {2009}, isbn = {978-1-60558-698-4}, pages = {1--7}, location = {Barcelona, Spain}, doi = {http://doi.acm.org/10.1145/1577802.1577809}, publisher = {ACM}, address = {New York, NY, USA}, } @inproceedings{PageLayout, author = {Ray Smith}, title = {Hybrid Page Layout Analysis via Tab-Stop Detection}, booktitle = {ICDAR '09: Proceedings of the 2009 10th International Conference on Document Analysis and Recognition}, url = {https://storage.googleapis.com/pub-tools-public-publication-data/pdf/35094.pdf}, year = {2009}, isbn = {978-0-7695-3725-2}, pages = {241--245}, doi = {http://dx.doi.org/10.1109/ICDAR.2009.257}, publisher = {IEEE Computer Society}, address = {Washington, DC, USA}, } @inproceedings{TessOverview, author = {Ray Smith}, title = {An Overview of the Tesseract OCR Engine}, booktitle = {ICDAR '07: Proceedings of the Ninth International Conference on Document Analysis and Recognition}, url = {https://storage.googleapis.com/pub-tools-public-publication-data/pdf/33418.pdf}, year = {2007}, isbn = {0-7695-2822-8}, pages = {629--633}, publisher = {IEEE Computer Society}, address = {Washington, DC, USA}, }
2301_81045437/tesseract
CITATIONS.bib
BibTeX
apache-2.0
2,851
# # tesseract # # ############################################################################## # # cmake settings # # ############################################################################## cmake_minimum_required(VERSION 3.10 FATAL_ERROR) # In-source builds are disabled. if("${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}") message( FATAL_ERROR "CMake generation is not possible within the source directory!" "\n Remove the CMakeCache.txt file and try again from another folder, " "e.g.:\n " "\n rm CMakeCache.txt" "\n mkdir build" "\n cd build" "\n cmake ..") endif() set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH};${CMAKE_CURRENT_SOURCE_DIR}/cmake") set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}") # Use solution folders. set_property(GLOBAL PROPERTY USE_FOLDERS ON) set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER "CMake Targets") if(NOT ${CMAKE_VERSION} VERSION_LESS "3.15.0") if(WIN32) cmake_policy(SET CMP0091 NEW) message(STATUS "Setting policy CMP0091 to NEW") endif() endif() # ############################################################################## # # project settings # # ############################################################################## project(tesseract C CXX) # Get version with components from VERSION file. file(STRINGS "VERSION" VERSION_PLAIN) string(REGEX REPLACE "^([^.]*)\\..*" "\\1" VERSION_MAJOR ${VERSION_PLAIN}) string(REGEX REPLACE "^[^.]*\\.([^.]*)\\..*" "\\1" VERSION_MINOR ${VERSION_PLAIN}) string(REGEX REPLACE "^[^.]*\\.[^.]*\\.([0-9]*).*" "\\1" VERSION_PATCH ${VERSION_PLAIN}) if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git) execute_process(COMMAND git --git-dir ${CMAKE_CURRENT_SOURCE_DIR}/.git describe --abbrev=4 OUTPUT_VARIABLE GIT_REV) string(REGEX REPLACE "\n$" "" PACKAGE_VERSION "${GIT_REV}") endif() if(NOT PACKAGE_VERSION) set(PACKAGE_VERSION ${VERSION_PLAIN}) endif() # Provide also same macro names as autoconf (see configure.ac). set(GENERIC_MAJOR_VERSION ${VERSION_MAJOR}) set(GENERIC_MINOR_VERSION ${VERSION_MINOR}) set(GENERIC_MICRO_VERSION ${VERSION_PATCH}) set(MINIMUM_LEPTONICA_VERSION 1.74) # ############################################################################## # # options # # ############################################################################## message(STATUS "Configuring tesseract version ${PACKAGE_VERSION}...") if(WIN32) option(SW_BUILD "Build with sw" ON) else() option(SW_BUILD "Build with sw" OFF) endif() option(OPENMP_BUILD "Build with openmp support" OFF) # see issue #1662 option(GRAPHICS_DISABLED "Disable disable graphics (ScrollView)" OFF) option(DISABLED_LEGACY_ENGINE "Disable the legacy OCR engine" OFF) option(ENABLE_LTO "Enable link-time optimization" OFF) option(FAST_FLOAT "Enable float for LSTM" ON) option(ENABLE_NATIVE "Enable optimization for host CPU (could break HW compatibility)" OFF) # see # https://stackoverflow.com/questions/52653025/why-is-march-native-used-so-rarely option(BUILD_TRAINING_TOOLS "Build training tools" ON) option(BUILD_TESTS "Build tests" OFF) option(USE_SYSTEM_ICU "Use system ICU" OFF) option(DISABLE_TIFF "Disable build with libtiff (if available)" OFF) option(DISABLE_ARCHIVE "Disable build with libarchive (if available)" OFF) option(DISABLE_CURL "Disable build with libcurl (if available)" OFF) option(INSTALL_CONFIGS "Install tesseract configs" ON) if(NOT ${CMAKE_VERSION} VERSION_LESS "3.15.0") if(WIN32 AND MSVC) option(WIN32_MT_BUILD "Build with MT flag for MSVC" OFF) endif() endif() # ############################################################################## # # compiler and linker # # ############################################################################## if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") set(CLANG 1) endif() if(NOT CMAKE_BUILD_TYPE) message(STATUS "Setting build type to 'Release' as none was specified.") set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release") endif() include(CheckCXXCompilerFlag) set(CMAKE_CXX_STANDARD 17) if("cxx_std_20" IN_LIST CMAKE_CXX_COMPILE_FEATURES) set(CMAKE_CXX_STANDARD 20) endif() set(CMAKE_CXX_STANDARD_REQUIRED ON) if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU") # cygwin gnu c++ needs to use -std=gnu++17 instead of -std=c++17 set(CMAKE_CXX_EXTENSIONS OFF) endif() if(BUILD_SHARED_LIBS) set(CMAKE_CXX_VISIBILITY_PRESET hidden) endif() # LTO cmake_policy(SET CMP0069 NEW) include(CheckIPOSupported) check_ipo_supported(RESULT LTO_SUPPORTED OUTPUT error) if(LTO_SUPPORTED) message(STATUS "IPO / LTO supported") else() message(STATUS "IPO / LTO not supported: <${error}>") endif() set(MARCH_NATIVE_OPT OFF) if(ENABLE_NATIVE) check_cxx_compiler_flag("-march=native" COMPILER_SUPPORTS_MARCH_NATIVE) if(COMPILER_SUPPORTS_MARCH_NATIVE) set(DOTPRODUCT_FLAGS "${DOTPRODUCT_FLAGS} -march=native") if(NOT CLANG AND MSVC) # clang-cl does not know this argument set(DOTPRODUCT_FLAGS "${DOTPRODUCT_FLAGS} -mtune=native") endif() set(MARCH_NATIVE_OPT ON) endif(COMPILER_SUPPORTS_MARCH_NATIVE) endif(ENABLE_NATIVE) message(STATUS "CMAKE_SYSTEM_PROCESSOR=<${CMAKE_SYSTEM_PROCESSOR}>") if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86|x86_64|AMD64|amd64|i386|i686") set(HAVE_NEON FALSE) if(MSVC) set(HAVE_AVX ON) set(AVX_COMPILE_FLAGS "/arch:AVX") add_definitions("-DHAVE_AVX") set(HAVE_AVX2 ON) set(AVX2_COMPILE_FLAGS "/arch:AVX2") add_definitions("-DHAVE_AVX2") set(HAVE_AVX512F ON) set(AVX512F_COMPILE_FLAGS "/arch:AVX512") add_definitions("-DHAVE_AVX512F") set(HAVE_FMA ON) set(FMA_COMPILE_FLAGS "-D__FMA__") add_definitions("-DHAVE_FMA") set(HAVE_SSE4_1 ON) set(SSE4_1_COMPILE_FLAGS "-D__SSE4_1__") add_definitions("-DHAVE_SSE4_1") set(DOTPRODUCT_FLAGS "${DOTPRODUCT_FLAGS} -openmp:experimental") add_definitions("-DOPENMP_SIMD") # clang with MSVC compatibility if(CLANG) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-microsoft-unqualified-friend") if(HAVE_FMA) set(FMA_COMPILE_FLAGS "-mfma ${FMA_COMPILE_FLAGS}") endif(HAVE_FMA) if(HAVE_SSE4_1) set(SSE4_1_COMPILE_FLAGS "-msse4.1 ${SSE4_1_COMPILE_FLAGS}") endif(HAVE_SSE4_1) endif(CLANG) else() # if not MSVC check_cxx_compiler_flag("-mavx" HAVE_AVX) if(HAVE_AVX) set(AVX_COMPILE_FLAGS "-mavx") add_definitions("-DHAVE_AVX") endif(HAVE_AVX) check_cxx_compiler_flag("-mavx2" HAVE_AVX2) if(HAVE_AVX2) set(AVX2_COMPILE_FLAGS "-mavx2") add_definitions("-DHAVE_AVX2") endif() check_cxx_compiler_flag("-mavx512f" HAVE_AVX512F) if(HAVE_AVX512F) set(AVX512F_COMPILE_FLAGS "-mavx512f") add_definitions("-DHAVE_AVX512F") endif() check_cxx_compiler_flag("-mfma" HAVE_FMA) if(HAVE_FMA) set(FMA_COMPILE_FLAGS "-mfma") add_definitions("-DHAVE_FMA") endif() check_cxx_compiler_flag("-msse4.1" HAVE_SSE4_1) if(HAVE_SSE4_1) set(SSE4_1_COMPILE_FLAGS "-msse4.1") add_definitions("-DHAVE_SSE4_1") endif() check_cxx_compiler_flag("-fopenmp-simd" OPENMP_SIMD) if(OPENMP_SIMD) set(DOTPRODUCT_FLAGS "${DOTPRODUCT_FLAGS} -fopenmp-simd") add_definitions("-DOPENMP_SIMD") endif(OPENMP_SIMD) endif(MSVC) elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "arm64|aarch64.*|AARCH64.*") set(HAVE_AVX FALSE) set(HAVE_AVX2 FALSE) set(HAVE_AVX512F FALSE) set(HAVE_FMA FALSE) set(HAVE_SSE4_1 FALSE) set(HAVE_NEON TRUE) elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "arm.*") set(HAVE_AVX FALSE) set(HAVE_AVX2 FALSE) set(HAVE_AVX512F FALSE) set(HAVE_FMA FALSE) set(HAVE_SSE4_1 FALSE) check_cxx_compiler_flag("-mfpu=neon" HAVE_NEON) if(HAVE_NEON) set(NEON_COMPILE_FLAGS "-mfpu=neon") endif(HAVE_NEON) else() set(HAVE_AVX FALSE) set(HAVE_AVX2 FALSE) set(HAVE_AVX512F FALSE) set(HAVE_FMA FALSE) set(HAVE_NEON FALSE) set(HAVE_SSE4_1 FALSE) endif(CMAKE_SYSTEM_PROCESSOR MATCHES "x86|x86_64|AMD64|amd64|i386|i686") if(HAVE_NEON) message(STATUS "LTO build is not supported on arm/RBPi.") set(ENABLE_LTO FALSE) # enable LTO cause fatal error on arm/RBPi endif() # Compiler specific environment if(CMAKE_COMPILER_IS_GNUCXX OR MINGW) set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -DDEBUG -pedantic -Og") elseif(MSVC) add_definitions(-D_CRT_SECURE_NO_WARNINGS) add_definitions(-D_CRT_NONSTDC_NO_DEPRECATE) # strdup set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /utf-8") if(NOT CLANG) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP") endif() # Hide some warnings for release target wd4244 'argument': conversion from # 'uint64_t' to 'unsigned int', possible loss of data wd4251 needs to have # dll-interface wd4267 return': conversion from 'size_t' to 'int', possible # loss of data wd4275 non dll-interface class wd4305 ...truncation from # 'double' to 'float' set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /wd4244 /wd4305 /wd4267 /wd4251 /wd4275 /wd4005" ) set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /wd4068") # Don't use /Wall because it generates too many warnings. set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /W0 /bigobj") # MT flag if(WIN32_MT_BUILD) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") message(STATUS "Building with static CRT.") endif() endif() if(CLANG) # clang all platforms set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wno-unused-command-line-argument") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -DDEBUG -pedantic -O0") endif() if(OPENMP_BUILD AND MSVC AND "${MSVC_VERSION}" LESS 1929) set(OPENMP_BUILD OFF) endif() if(OPENMP_BUILD) find_package(OpenMP QUIET) # https://stackoverflow.com/questions/12399422 # how-to-set-linker-flags-for-openmp-in-cmakes-try-compile-function if(NOT OpenMP_FOUND AND CLANG AND WIN32) # workaround because find_package(OpenMP) does not work for clang-cl # https://gitlab.kitware.com/cmake/cmake/issues/19404 check_include_file_cxx(omp.h HAVE_OMP_H_INCLUDE) find_library(OpenMP_LIBRARY NAMES omp libomp.lib) message(">> OpenMP_LIBRARY: ${OpenMP_LIBRARY}") if(MSVC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /openmp") else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp") endif() set(OpenMP_FOUND 1) # OpenMP 3.1 is fully supported from Clang 3.8.0 add_definitions(-D_OPENMP=201107) endif() if(MSVC) # Note: -openmp:llvm is available for X64 from MSVC 16.9 from MSVC 16.10 # Preview 2 there is support also for x86 and arm64 # https://devblogs.microsoft.com/cppblog/openmp-updates-and-fixes-for-cpp-in-visual-studio-2019-16-10/ if("${OpenMP_CXX_FLAGS}" STREQUAL "-openmp") set(OpenMP_CXX_FLAGS "-openmp:llvm") endif() endif() if(OpenMP_FOUND) message(">> OpenMP_FOUND ${OpenMP_FOUND} version: ${OpenMP_CXX_VERSION}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") if(NOT TARGET OpenMP::OpenMP_CXX) add_library(OpenMP::OpenMP_CXX IMPORTED INTERFACE) endif() endif() endif() if(CYGWIN) add_definitions(-D__CYGWIN__) elseif(UNIX) if(NOT ANDROID) set(LIB_pthread pthread) endif() elseif(WIN32) set(LIB_Ws2_32 Ws2_32) endif() add_definitions("-DCMAKE_BUILD") # ############################################################################## # # packages # # ############################################################################## include(CheckFunctions) if(SW_BUILD) find_package(SW REQUIRED) if(BUILD_SHARED_LIBS) set(SW_BUILD_SHARED_LIBS 1) else() set(SW_BUILD_SHARED_LIBS 0) endif() sw_add_package(org.sw.demo.danbloomberg.leptonica org.sw.demo.libarchive.libarchive) if(BUILD_TRAINING_TOOLS) sw_add_package(org.sw.demo.gnome.pango.pangocairo org.sw.demo.unicode.icu.i18n) endif() sw_execute() else() find_package(PkgConfig) # Check for required library. option -DLeptonica_DIR=path => cmake hint where # to find leptonica find_package(Leptonica ${MINIMUM_LEPTONICA_VERSION} CONFIG) if(NOT Leptonica_FOUND AND PKG_CONFIG_EXECUTABLE) pkg_check_modules(Leptonica lept>=${MINIMUM_LEPTONICA_VERSION}) link_directories(${Leptonica_LIBRARY_DIRS}) endif() if(NOT Leptonica_FOUND) message(FATAL_ERROR "Cannot find required library Leptonica. Quitting!") else() message(STATUS "Found leptonica version: ${Leptonica_VERSION}") endif(NOT Leptonica_FOUND) include_directories(${Leptonica_INCLUDE_DIRS}) check_leptonica_tiff_support() if ((NOT LEPT_TIFF_RESULT EQUAL 0) AND LEPT_TIFF_COMPILE_SUCCESS) message(NOTICE "Leptonica was build without TIFF support! Disabling TIFF support...") set(DISABLE_TIFF ON) elseif(NOT ${CMAKE_VERSION} VERSION_LESS "3.25") message(STATUS "Leptonica was build with TIFF support.") endif() # Check for optional libraries. if(DISABLE_TIFF) set(HAVE_TIFFIO_H OFF) message(STATUS "TIFF support disabled.") else(DISABLE_TIFF) find_package(TIFF) # for tesseract if(NOT TIFF_FOUND AND PKG_CONFIG_EXECUTABLE) # try PKG_CONFIG to find libtiff if cmake failed pkg_check_modules(TIFF libtiff-4) endif() if(TIFF_FOUND) set(HAVE_TIFFIO_H ON) include_directories(${TIFF_INCLUDE_DIRS}) endif(TIFF_FOUND) endif(DISABLE_TIFF) if(DISABLE_ARCHIVE) set(HAVE_LIBARCHIVE OFF) message(STATUS "LibArchive support disabled.") else(DISABLE_ARCHIVE) find_package(LibArchive) if(NOT LibArchive_FOUND AND PKG_CONFIG_EXECUTABLE) # try PKG_CONFIG to find libarchive if cmake failed pkg_check_modules(LibArchive libarchive) endif() if(LibArchive_FOUND) set(HAVE_LIBARCHIVE ON) include_directories(${LibArchive_INCLUDE_DIRS}) endif(LibArchive_FOUND) endif(DISABLE_ARCHIVE) if(DISABLE_CURL) set(HAVE_LIBCURL OFF) message(STATUS "CURL support disabled.") else(DISABLE_CURL) find_package(CURL) if(NOT CURL_FOUND AND PKG_CONFIG_EXECUTABLE) # try PKG_CONFIG to find libcurl if cmake failed pkg_check_modules(CURL libcurl) endif() if(CURL_FOUND) set(HAVE_LIBCURL ON) include_directories(${CURL_INCLUDE_DIRS}) endif(CURL_FOUND) endif(DISABLE_CURL) endif() # ############################################################################## # # configure # # ############################################################################## if(MSVC) set(DOTPRODUCT_FLAGS "${DOTPRODUCT_FLAGS} /fp:fast") else() set(DOTPRODUCT_FLAGS "${DOTPRODUCT_FLAGS} -O3 -ffast-math") endif() include (GNUInstallDirs) set(AUTOCONFIG_SRC ${CMAKE_CURRENT_BINARY_DIR}/config_auto.h.in) set(AUTOCONFIG ${CMAKE_CURRENT_BINARY_DIR}/config_auto.h) add_definitions(-DHAVE_CONFIG_H) if(GRAPHICS_DISABLED) message("ScrollView debugging disabled.") endif() set(CMAKE_REQUIRED_INCLUDES ${CMAKE_REQUIRED_INCLUDES} "${CMAKE_PREFIX_PATH}/include" ${CMAKE_INSTALL_INCLUDEDIR}) include(Configure) configure_file(${AUTOCONFIG_SRC} ${AUTOCONFIG} @ONLY) set(INCLUDE_DIR ${CMAKE_INSTALL_INCLUDEDIR}) set(LIBRARY_DIRS ${CMAKE_INSTALL_LIBDIR}) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/include/tesseract/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/include/tesseract/version.h @ONLY) include(CMakePackageConfigHelpers) include(GenerateExportHeader) # show summary of configuration if(${CMAKE_BUILD_TYPE} MATCHES Debug) set(COMPILER_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG}") elseif(${CMAKE_BUILD_TYPE} MATCHES Release) set(COMPILER_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE}") if(LTO_SUPPORTED AND ENABLE_LTO) set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE) else() set(CMAKE_INTERPROCEDURAL_OPTIMIZATION FALSE) endif() # LTO_SUPPORTED endif() if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(BUILD_ARCH "64 bits") elseif(CMAKE_SIZEOF_VOID_P EQUAL 4) set(BUILD_ARCH "32 bits") endif() message(STATUS) message(STATUS "General configuration for Tesseract ${PACKAGE_VERSION}") message(STATUS "--------------------------------------------------------") message(STATUS "Build type: ${CMAKE_BUILD_TYPE} ${BUILD_ARCH}") message(STATUS "Compiler: ${CMAKE_CXX_COMPILER_ID}") message(STATUS "Used standard: C++${CMAKE_CXX_STANDARD}") message(STATUS "CXX compiler options: ${COMPILER_FLAGS}") get_directory_property(DirCompDefs COMPILE_DEFINITIONS) message(STATUS "Compile definitions = ${DirCompDefs}") message(STATUS "Linker options: ${CMAKE_EXE_LINKER_FLAGS} " "${CMAKE_EXE_LINKER_FLAGS_${CMAKE_BUILD_TYPE_UP}}") message(STATUS "Install directory: ${CMAKE_INSTALL_PREFIX}") message(STATUS "HAVE_AVX: ${HAVE_AVX}") message(STATUS "HAVE_AVX2: ${HAVE_AVX2}") message(STATUS "HAVE_AVX512F: ${HAVE_AVX512F}") message(STATUS "HAVE_FMA: ${HAVE_FMA}") message(STATUS "HAVE_SSE4_1: ${HAVE_SSE4_1}") message(STATUS "MARCH_NATIVE_OPT: ${MARCH_NATIVE_OPT}") message(STATUS "HAVE_NEON: ${HAVE_NEON}") message(STATUS "Link-time optimization: ${CMAKE_INTERPROCEDURAL_OPTIMIZATION}") message(STATUS "--------------------------------------------------------") message(STATUS "Build with sw [SW_BUILD]: ${SW_BUILD}") message(STATUS "Build with openmp support [OPENMP_BUILD]: ${OPENMP_BUILD}") message(STATUS "Build with libarchive support [HAVE_LIBARCHIVE]: " "${HAVE_LIBARCHIVE}") message(STATUS "Build with libcurl support [HAVE_LIBCURL]: ${HAVE_LIBCURL}") message(STATUS "Enable float for LSTM [FAST_FLOAT]: ${FAST_FLOAT}") message(STATUS "Enable optimization for host CPU (could break HW compatibility)" " [ENABLE_NATIVE]: ${ENABLE_NATIVE}") message(STATUS "Disable disable graphics (ScrollView) [GRAPHICS_DISABLED]: " "${GRAPHICS_DISABLED}") message(STATUS "Disable the legacy OCR engine [DISABLED_LEGACY_ENGINE]: " "${DISABLED_LEGACY_ENGINE}") message(STATUS "Build training tools [BUILD_TRAINING_TOOLS]: " "${BUILD_TRAINING_TOOLS}") message(STATUS "Build tests [BUILD_TESTS]: ${BUILD_TESTS}") message(STATUS "Use system ICU Library [USE_SYSTEM_ICU]: ${USE_SYSTEM_ICU}") message( STATUS "Install tesseract configs [INSTALL_CONFIGS]: ${INSTALL_CONFIGS}") message(STATUS "--------------------------------------------------------") message(STATUS) # ############################################################################## # # build # # ############################################################################## include(BuildFunctions) include(SourceGroups) add_definitions(-D_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1) include_directories(${CMAKE_CURRENT_BINARY_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}/include) if(ANDROID_TOOLCHAIN) include_directories(${ANDROID_TOOLCHAIN}/sysroot/usr/include) add_compile_definitions(__ANDROID_API_FUTURE__) endif() # ############################################################################## # LIBRARY tesseract # ############################################################################## file( GLOB TESSERACT_SRC src/ccmain/*.cpp src/ccstruct/*.cpp src/ccutil/*.cpp src/classify/*.cpp src/cutil/*.cpp src/dict/*.cpp src/lstm/*.cpp src/textord/*.cpp src/viewer/*.cpp src/wordrec/*.cpp) if(DISABLED_LEGACY_ENGINE) # prepend path to list of source files function(prepend_path srcs path) set(tmp, "") foreach(src IN LISTS ${srcs}) list(APPEND tmp ${path}/${src}) endforeach(src ${srcs}) set(${srcs} ${tmp} PARENT_SCOPE) endfunction() set(TESSERACT_SRC_LEGACY src/ccmain/adaptions.cpp src/ccmain/docqual.cpp src/ccmain/equationdetect.cpp src/ccmain/fixspace.cpp src/ccmain/fixxht.cpp src/ccmain/osdetect.cpp src/ccmain/par_control.cpp src/ccmain/recogtraining.cpp src/ccmain/superscript.cpp src/ccmain/tessbox.cpp src/ccmain/tfacepp.cpp src/ccstruct/fontinfo.cpp src/ccstruct/params_training_featdef.cpp src/ccutil/ambigs.cpp src/ccutil/bitvector.cpp src/ccutil/indexmapbidi.cpp src/classify/adaptive.cpp src/classify/adaptmatch.cpp src/classify/blobclass.cpp src/classify/cluster.cpp src/classify/clusttool.cpp src/classify/cutoffs.cpp src/classify/featdefs.cpp src/classify/float2int.cpp src/classify/fpoint.cpp src/classify/intfeaturespace.cpp src/classify/intfx.cpp src/classify/intmatcher.cpp src/classify/intproto.cpp src/classify/kdtree.cpp src/classify/mf.cpp src/classify/mfoutline.cpp src/classify/mfx.cpp src/classify/normfeat.cpp src/classify/normmatch.cpp src/classify/ocrfeatures.cpp src/classify/outfeat.cpp src/classify/picofeat.cpp src/classify/protos.cpp src/classify/shapeclassifier.cpp src/classify/shapetable.cpp src/classify/tessclassifier.cpp src/classify/trainingsample.cpp src/dict/permdawg.cpp src/dict/hyphen.cpp src/wordrec/associate.cpp src/wordrec/chop.cpp src/wordrec/chopper.cpp src/wordrec/drawfx.cpp src/wordrec/findseam.cpp src/wordrec/gradechop.cpp src/wordrec/language_model.cpp src/wordrec/lm_consistency.cpp src/wordrec/lm_pain_points.cpp src/wordrec/lm_state.cpp src/wordrec/outlines.cpp src/wordrec/params_model.cpp src/wordrec/pieces.cpp src/wordrec/plotedges.cpp src/wordrec/render.cpp src/wordrec/segsearch.cpp src/wordrec/wordclass.cpp) prepend_path(TESSERACT_SRC_LEGACY "${CMAKE_CURRENT_SOURCE_DIR}") list(REMOVE_ITEM TESSERACT_SRC ${TESSERACT_SRC_LEGACY}) endif(DISABLED_LEGACY_ENGINE) list(APPEND arch_files src/arch/dotproduct.cpp src/arch/simddetect.cpp src/arch/intsimdmatrix.cpp) if(DOTPRODUCT_FLAGS) set_source_files_properties(src/arch/dotproduct.cpp PROPERTIES COMPILE_FLAGS ${DOTPRODUCT_FLAGS}) endif(DOTPRODUCT_FLAGS) if(HAVE_AVX) list(APPEND arch_files_opt src/arch/dotproductavx.cpp) set_source_files_properties(src/arch/dotproductavx.cpp PROPERTIES COMPILE_FLAGS ${AVX_COMPILE_FLAGS}) endif(HAVE_AVX) if(HAVE_AVX2) list(APPEND arch_files_opt src/arch/intsimdmatrixavx2.cpp src/arch/dotproductavx.cpp) set_source_files_properties(src/arch/intsimdmatrixavx2.cpp PROPERTIES COMPILE_FLAGS ${AVX2_COMPILE_FLAGS}) endif(HAVE_AVX2) if(HAVE_AVX512F) list(APPEND arch_files_opt src/arch/dotproductavx512.cpp) set_source_files_properties(src/arch/dotproductavx512.cpp PROPERTIES COMPILE_FLAGS ${AVX512F_COMPILE_FLAGS}) endif(HAVE_AVX512F) if(HAVE_FMA) list(APPEND arch_files_opt src/arch/dotproductfma.cpp) set_source_files_properties(src/arch/dotproductfma.cpp PROPERTIES COMPILE_FLAGS ${FMA_COMPILE_FLAGS}) endif(HAVE_FMA) if(HAVE_SSE4_1) list(APPEND arch_files_opt src/arch/dotproductsse.cpp src/arch/intsimdmatrixsse.cpp) set_source_files_properties( src/arch/dotproductsse.cpp src/arch/intsimdmatrixsse.cpp PROPERTIES COMPILE_FLAGS ${SSE4_1_COMPILE_FLAGS}) endif(HAVE_SSE4_1) if(HAVE_NEON) list(APPEND arch_files_opt src/arch/dotproductneon.cpp src/arch/intsimdmatrixneon.cpp) if(NEON_COMPILE_FLAGS) set_source_files_properties( src/arch/dotproductneon.cpp src/arch/intsimdmatrixneon.cpp PROPERTIES COMPILE_FLAGS ${NEON_COMPILE_FLAGS}) endif() endif(HAVE_NEON) file( GLOB_RECURSE TESSERACT_HDR include/* src/arch/*.h src/ccmain/*.h src/ccstruct/*.h src/ccutil/*.h src/classify/*.h src/cutil/*.h src/dict/*.h src/lstm/*.h src/textord/*.h src/viewer/*.h src/wordrec/*.h) set(TESSERACT_SRC ${TESSERACT_SRC} src/api/baseapi.cpp src/api/capi.cpp src/api/renderer.cpp src/api/altorenderer.cpp src/api/pagerenderer.cpp src/api/hocrrenderer.cpp src/api/lstmboxrenderer.cpp src/api/pdfrenderer.cpp src/api/wordstrboxrenderer.cpp) set(TESSERACT_CONFIGS tessdata/configs/alto tessdata/configs/ambigs.train tessdata/configs/api_config tessdata/configs/bazaar tessdata/configs/bigram tessdata/configs/box.train tessdata/configs/box.train.stderr tessdata/configs/digits tessdata/configs/get.images tessdata/configs/hocr tessdata/configs/inter tessdata/configs/kannada tessdata/configs/linebox tessdata/configs/logfile tessdata/configs/lstm.train tessdata/configs/lstmbox tessdata/configs/lstmdebug tessdata/configs/makebox tessdata/configs/page tessdata/configs/pdf tessdata/configs/quiet tessdata/configs/rebox tessdata/configs/strokewidth tessdata/configs/tsv tessdata/configs/txt tessdata/configs/unlv tessdata/configs/wordstrbox) set(TESSERACT_TESSCONFIGS tessdata/tessconfigs/batch tessdata/tessconfigs/batch.nochop tessdata/tessconfigs/matdemo tessdata/tessconfigs/msdemo tessdata/tessconfigs/nobatch tessdata/tessconfigs/segdemo) set(LIBTESSFILES ${TESSERACT_SRC} ${arch_files} ${arch_files_opt} ${TESSERACT_HDR}) source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${LIBTESSFILES}) add_library(libtesseract ${LIBTESSFILES}) target_include_directories( libtesseract BEFORE PRIVATE src PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/arch> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/ccmain> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/ccstruct> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/ccutil> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/classify> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/cutil> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/dict> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/lstm> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/textord> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/viewer> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/wordrec> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/training>) if(BUILD_SHARED_LIBS) target_compile_definitions( libtesseract PRIVATE -DTESS_EXPORTS INTERFACE -DTESS_IMPORTS) # generate_export_header (libtesseract EXPORT_MACRO_NAME TESS_API) endif() target_link_libraries(libtesseract PRIVATE ${LIB_Ws2_32} ${LIB_pthread}) if(OpenMP_CXX_FOUND) target_link_libraries(libtesseract PUBLIC OpenMP::OpenMP_CXX) endif() if(LibArchive_FOUND) target_link_libraries(libtesseract PUBLIC ${LibArchive_LIBRARIES}) endif(LibArchive_FOUND) if(CURL_FOUND) if(NOT CURL_LIBRARIES) target_link_libraries(libtesseract PUBLIC CURL::libcurl) else() target_link_libraries(libtesseract PUBLIC ${CURL_LIBRARIES}) endif() endif(CURL_FOUND) set_target_properties( libtesseract PROPERTIES VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}) set_target_properties( libtesseract PROPERTIES SOVERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}) set_target_properties( libtesseract PROPERTIES OUTPUT_NAME tesseract$<$<BOOL:${WIN32}>:${VERSION_MAJOR}${VERSION_MINOR}$<$<CONFIG:DEBUG>:d>> ) if(SW_BUILD) target_link_libraries(libtesseract PUBLIC org.sw.demo.danbloomberg.leptonica org.sw.demo.libarchive.libarchive) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/TesseractTargets.cmake "include(${CMAKE_CURRENT_BINARY_DIR}/cppan.cmake)\n") export( TARGETS libtesseract APPEND FILE ${CMAKE_CURRENT_BINARY_DIR}/TesseractTargets.cmake NAMESPACE Tesseract::) else() target_link_libraries(libtesseract PUBLIC ${Leptonica_LIBRARIES}) export( TARGETS libtesseract FILE ${CMAKE_CURRENT_BINARY_DIR}/TesseractTargets.cmake NAMESPACE Tesseract::) endif() if(WIN32 AND CLANG AND OPENMP_BUILD) # Workaround for "libomp.lib is not automatically added on Windows" see: # http://lists.llvm.org/pipermail/openmp-dev/2015-August/000857.html target_link_libraries(libtesseract PRIVATE ${OpenMP_LIBRARY}) endif() if(ANDROID) add_definitions(-DANDROID) find_package(CpuFeaturesNdkCompat REQUIRED) target_include_directories( libtesseract PRIVATE "${CpuFeaturesNdkCompat_DIR}/../../../include/ndk_compat") target_link_libraries(libtesseract PRIVATE CpuFeatures::ndk_compat) endif() # ############################################################################## # EXECUTABLE tesseract # ############################################################################## add_executable(tesseract src/tesseract.cpp) target_link_libraries(tesseract libtesseract) if(HAVE_TIFFIO_H AND WIN32) target_link_libraries(tesseract ${TIFF_LIBRARIES}) endif() if(OPENMP_BUILD AND UNIX) target_link_libraries(tesseract pthread) endif() # ############################################################################## if(BUILD_TESTS AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/unittest/third_party/googletest/CMakeLists.txt ) add_subdirectory(unittest/third_party/googletest) endif() if(BUILD_TRAINING_TOOLS) add_subdirectory(src/training) endif() get_target_property(tesseract_NAME libtesseract NAME) get_target_property(tesseract_VERSION libtesseract VERSION) get_target_property(tesseract_OUTPUT_NAME libtesseract OUTPUT_NAME) configure_file(tesseract.pc.cmake ${CMAKE_CURRENT_BINARY_DIR}/tesseract.pc.in @ONLY) # to resolve generator expression in OUTPUT_NAME file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/tesseract_$<CONFIG>.pc INPUT ${CMAKE_CURRENT_BINARY_DIR}/tesseract.pc.in) configure_package_config_file( cmake/templates/TesseractConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/tesseract/TesseractConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/tesseract PATH_VARS INCLUDE_DIR LIBRARY_DIRS) write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/cmake/tesseract/TesseractConfigVersion.cmake VERSION ${PACKAGE_VERSION} COMPATIBILITY SameMajorVersion) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/tesseract_$<CONFIG>.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig RENAME tesseract.pc) install(TARGETS tesseract DESTINATION bin) if (MSVC) install(FILES $<TARGET_PDB_FILE:${PROJECT_NAME}> DESTINATION bin OPTIONAL) endif() install( TARGETS libtesseract EXPORT TesseractTargets RUNTIME DESTINATION bin RUNTIME DESTINATION bin LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) if (MSVC AND BUILD_SHARED_LIBS) install(FILES $<TARGET_PDB_FILE:libtesseract> DESTINATION bin OPTIONAL) endif() install( EXPORT TesseractTargets NAMESPACE Tesseract:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/tesseract) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}) install( FILES include/tesseract/baseapi.h include/tesseract/capi.h include/tesseract/renderer.h ${CMAKE_CURRENT_BINARY_DIR}/include/tesseract/version.h include/tesseract/ltrresultiterator.h include/tesseract/pageiterator.h include/tesseract/resultiterator.h include/tesseract/osdetect.h include/tesseract/publictypes.h include/tesseract/ocrclass.h include/tesseract/export.h include/tesseract/unichar.h # ${CMAKE_CURRENT_BINARY_DIR}/src/endianness.h DESTINATION include/tesseract) if(INSTALL_CONFIGS) install(FILES ${TESSERACT_CONFIGS} DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/tessdata/configs) install(FILES ${TESSERACT_TESSCONFIGS} DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/tessdata/tessconfigs) endif() # ############################################################################## # uninstall target # ############################################################################## if(NOT TARGET uninstall) configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/cmake/templates/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target( uninstall COMMENT "Uninstall installed files" COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) endif() # ##############################################################################
2301_81045437/tesseract
CMakeLists.txt
CMake
apache-2.0
32,724
## run autogen.sh to create Makefile.in from this file ACLOCAL_AMFLAGS = -I m4 .PHONY: doc html install-langs ScrollView.jar install-jars pdf training CLEANFILES = SUBDIRS = . tessdata EXTRA_DIST = README.md LICENSE EXTRA_DIST += aclocal.m4 config configure.ac autogen.sh EXTRA_DIST += tesseract.pc.in doc if !GRAPHICS_DISABLED EXTRA_DIST += java endif EXTRA_DIST += CMakeLists.txt tesseract.pc.cmake cmake VERSION DIST_SUBDIRS = $(SUBDIRS) EXTRA_PROGRAMS = uninstall-hook: rm -rf $(DESTDIR)$(pkgincludedir) dist-hook: # Need to remove .svn directories from directories # added using EXTRA_DIST. $(distdir)/tessdata would in # theory suffice. rm -rf `find $(distdir) -name .deps -type d` -rm -f $(distdir)/*/Makefile $(distdir)/*/*/Makefile rm -f `find $(distdir) -name '*~'` rm -rf $(distdir)/doc/html/* $(distdir)/doc/*.log if !GRAPHICS_DISABLED ScrollView.jar: @cd "$(top_builddir)/java" && $(MAKE) $@ install-jars: @cd "$(top_builddir)/java" && $(MAKE) $@ endif doc: -srcdir="$(top_srcdir)" builddir="$(top_builddir)" \ version="@PACKAGE_VERSION@" name="@PACKAGE_NAME@" \ doxygen $(top_srcdir)/doc/Doxyfile doc-pack: doc -chmod a+r $(top_builddir)/doc/html/* @tar --create --directory=$(top_builddir)/doc/html --verbose --file=- . | gzip -c -9 > $(top_builddir)/@PACKAGE_NAME@-@PACKAGE_VERSION@-doc-html.tar.gz; doc-clean: rm -rf $(top_builddir)/doc/html/* pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = tesseract.pc pkginclude_HEADERS = $(top_builddir)/include/tesseract/version.h pkginclude_HEADERS += include/tesseract/baseapi.h pkginclude_HEADERS += include/tesseract/capi.h pkginclude_HEADERS += include/tesseract/export.h pkginclude_HEADERS += include/tesseract/ltrresultiterator.h pkginclude_HEADERS += include/tesseract/ocrclass.h pkginclude_HEADERS += include/tesseract/osdetect.h pkginclude_HEADERS += include/tesseract/pageiterator.h pkginclude_HEADERS += include/tesseract/publictypes.h pkginclude_HEADERS += include/tesseract/renderer.h pkginclude_HEADERS += include/tesseract/resultiterator.h pkginclude_HEADERS += include/tesseract/unichar.h # Rules for all subdirectories. noinst_HEADERS = noinst_LTLIBRARIES = AM_CPPFLAGS += -I$(top_srcdir)/include AM_CPPFLAGS += -I$(top_builddir)/include if VISIBILITY AM_CPPFLAGS += -DTESS_EXPORTS AM_CPPFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden -fPIC endif AM_CXXFLAGS = $(OPENMP_CXXFLAGS) # Rules for src/api. libtesseract_la_CPPFLAGS = $(AM_CPPFLAGS) libtesseract_la_CPPFLAGS += -DTESS_COMMON_TRAINING_API= libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/arch libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/ccmain libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/ccstruct libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/ccutil libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/classify libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/cutil libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/dict libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/lstm libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/textord libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/training/common libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/viewer libtesseract_la_CPPFLAGS += -I$(top_srcdir)/src/wordrec libtesseract_la_CPPFLAGS += $(libcurl_CFLAGS) lib_LTLIBRARIES = libtesseract.la libtesseract_la_LDFLAGS = $(LEPTONICA_LIBS) libtesseract_la_LDFLAGS += $(libarchive_LIBS) libtesseract_la_LDFLAGS += $(libcurl_LIBS) libtesseract_la_LDFLAGS += $(TENSORFLOW_LIBS) if T_WIN libtesseract_la_LDFLAGS += -no-undefined -lws2_32 else libtesseract_la_LDFLAGS += $(NOUNDEFINED) endif libtesseract_la_LDFLAGS += -version-info $(GENERIC_LIBRARY_VERSION) libtesseract_la_SOURCES = src/api/baseapi.cpp libtesseract_la_SOURCES += src/api/altorenderer.cpp libtesseract_la_SOURCES += src/api/pagerenderer.cpp libtesseract_la_SOURCES += src/api/capi.cpp libtesseract_la_SOURCES += src/api/hocrrenderer.cpp libtesseract_la_SOURCES += src/api/lstmboxrenderer.cpp libtesseract_la_SOURCES += src/api/pdfrenderer.cpp libtesseract_la_SOURCES += src/api/renderer.cpp libtesseract_la_SOURCES += src/api/wordstrboxrenderer.cpp libtesseract_la_LIBADD = libtesseract_ccutil.la libtesseract_la_LIBADD += libtesseract_lstm.la libtesseract_la_LIBADD += libtesseract_native.la # Rules for src/arch. noinst_HEADERS += src/arch/dotproduct.h noinst_HEADERS += src/arch/intsimdmatrix.h noinst_HEADERS += src/arch/simddetect.h noinst_LTLIBRARIES += libtesseract_native.la libtesseract_native_la_CXXFLAGS = -O3 -ffast-math if OPENMP_SIMD libtesseract_native_la_CXXFLAGS += -fopenmp-simd -DOPENMP_SIMD endif libtesseract_native_la_CXXFLAGS += -I$(top_srcdir)/src/ccutil libtesseract_native_la_SOURCES = src/arch/dotproduct.cpp if HAVE_AVX libtesseract_avx_la_CXXFLAGS = -mavx libtesseract_avx_la_CXXFLAGS += -I$(top_srcdir)/src/ccutil libtesseract_avx_la_SOURCES = src/arch/dotproductavx.cpp libtesseract_la_LIBADD += libtesseract_avx.la noinst_LTLIBRARIES += libtesseract_avx.la endif if HAVE_AVX2 libtesseract_avx2_la_CXXFLAGS = -mavx2 libtesseract_avx2_la_CXXFLAGS += -I$(top_srcdir)/src/ccutil libtesseract_avx2_la_SOURCES = src/arch/intsimdmatrixavx2.cpp libtesseract_la_LIBADD += libtesseract_avx2.la noinst_LTLIBRARIES += libtesseract_avx2.la endif if HAVE_AVX512F libtesseract_avx512_la_CXXFLAGS = -mavx512f libtesseract_avx512_la_CXXFLAGS += -I$(top_srcdir)/src/ccutil libtesseract_avx512_la_SOURCES = src/arch/dotproductavx512.cpp libtesseract_la_LIBADD += libtesseract_avx512.la noinst_LTLIBRARIES += libtesseract_avx512.la endif if HAVE_FMA libtesseract_fma_la_CXXFLAGS = -mfma libtesseract_fma_la_CXXFLAGS += -I$(top_srcdir)/src/ccutil libtesseract_fma_la_SOURCES = src/arch/dotproductfma.cpp libtesseract_la_LIBADD += libtesseract_fma.la noinst_LTLIBRARIES += libtesseract_fma.la endif if HAVE_SSE4_1 libtesseract_sse_la_CXXFLAGS = -msse4.1 libtesseract_sse_la_CXXFLAGS += -I$(top_srcdir)/src/ccutil libtesseract_sse_la_SOURCES = src/arch/dotproductsse.cpp src/arch/intsimdmatrixsse.cpp libtesseract_la_LIBADD += libtesseract_sse.la noinst_LTLIBRARIES += libtesseract_sse.la endif if HAVE_NEON libtesseract_neon_la_CXXFLAGS = $(NEON_CXXFLAGS) libtesseract_neon_la_CXXFLAGS += -O3 if OPENMP_SIMD libtesseract_neon_la_CXXFLAGS += -fopenmp-simd -DOPENMP_SIMD endif libtesseract_neon_la_CXXFLAGS += -I$(top_srcdir)/src/ccutil libtesseract_neon_la_SOURCES = src/arch/intsimdmatrixneon.cpp libtesseract_neon_la_SOURCES += src/arch/dotproductneon.cpp libtesseract_la_LIBADD += libtesseract_neon.la noinst_LTLIBRARIES += libtesseract_neon.la endif libtesseract_la_SOURCES += src/arch/intsimdmatrix.cpp libtesseract_la_SOURCES += src/arch/simddetect.cpp # Rules for src/ccmain. noinst_HEADERS += src/ccmain/control.h noinst_HEADERS += src/ccmain/mutableiterator.h noinst_HEADERS += src/ccmain/output.h noinst_HEADERS += src/ccmain/paragraphs.h noinst_HEADERS += src/ccmain/paragraphs_internal.h noinst_HEADERS += src/ccmain/paramsd.h noinst_HEADERS += src/ccmain/pgedit.h noinst_HEADERS += src/ccmain/tesseractclass.h noinst_HEADERS += src/ccmain/tessvars.h noinst_HEADERS += src/ccmain/thresholder.h noinst_HEADERS += src/ccmain/werdit.h if !DISABLED_LEGACY_ENGINE noinst_HEADERS += src/ccmain/docqual.h noinst_HEADERS += src/ccmain/equationdetect.h noinst_HEADERS += src/ccmain/fixspace.h noinst_HEADERS += src/ccmain/reject.h endif libtesseract_la_SOURCES += src/ccmain/applybox.cpp libtesseract_la_SOURCES += src/ccmain/control.cpp libtesseract_la_SOURCES += src/ccmain/linerec.cpp libtesseract_la_SOURCES += src/ccmain/ltrresultiterator.cpp libtesseract_la_SOURCES += src/ccmain/mutableiterator.cpp libtesseract_la_SOURCES += src/ccmain/output.cpp libtesseract_la_SOURCES += src/ccmain/pageiterator.cpp libtesseract_la_SOURCES += src/ccmain/pagesegmain.cpp libtesseract_la_SOURCES += src/ccmain/pagewalk.cpp libtesseract_la_SOURCES += src/ccmain/paragraphs.cpp if !GRAPHICS_DISABLED libtesseract_la_SOURCES += src/ccmain/paramsd.cpp libtesseract_la_SOURCES += src/ccmain/pgedit.cpp endif libtesseract_la_SOURCES += src/ccmain/reject.cpp libtesseract_la_SOURCES += src/ccmain/resultiterator.cpp libtesseract_la_SOURCES += src/ccmain/tessedit.cpp libtesseract_la_SOURCES += src/ccmain/tesseractclass.cpp libtesseract_la_SOURCES += src/ccmain/tessvars.cpp libtesseract_la_SOURCES += src/ccmain/thresholder.cpp libtesseract_la_SOURCES += src/ccmain/werdit.cpp if !DISABLED_LEGACY_ENGINE libtesseract_la_SOURCES += src/ccmain/adaptions.cpp libtesseract_la_SOURCES += src/ccmain/docqual.cpp libtesseract_la_SOURCES += src/ccmain/equationdetect.cpp libtesseract_la_SOURCES += src/ccmain/fixspace.cpp libtesseract_la_SOURCES += src/ccmain/fixxht.cpp libtesseract_la_SOURCES += src/ccmain/osdetect.cpp libtesseract_la_SOURCES += src/ccmain/par_control.cpp libtesseract_la_SOURCES += src/ccmain/recogtraining.cpp libtesseract_la_SOURCES += src/ccmain/superscript.cpp libtesseract_la_SOURCES += src/ccmain/tessbox.cpp libtesseract_la_SOURCES += src/ccmain/tfacepp.cpp endif # Rules for src/ccstruct. noinst_HEADERS += src/ccstruct/blamer.h noinst_HEADERS += src/ccstruct/blobbox.h noinst_HEADERS += src/ccstruct/blobs.h noinst_HEADERS += src/ccstruct/blread.h noinst_HEADERS += src/ccstruct/boxread.h noinst_HEADERS += src/ccstruct/boxword.h noinst_HEADERS += src/ccstruct/ccstruct.h noinst_HEADERS += src/ccstruct/coutln.h noinst_HEADERS += src/ccstruct/crakedge.h noinst_HEADERS += src/ccstruct/debugpixa.h noinst_HEADERS += src/ccstruct/detlinefit.h noinst_HEADERS += src/ccstruct/dppoint.h noinst_HEADERS += src/ccstruct/image.h noinst_HEADERS += src/ccstruct/imagedata.h noinst_HEADERS += src/ccstruct/linlsq.h noinst_HEADERS += src/ccstruct/matrix.h noinst_HEADERS += src/ccstruct/mod128.h noinst_HEADERS += src/ccstruct/normalis.h noinst_HEADERS += src/ccstruct/ocrblock.h noinst_HEADERS += src/ccstruct/ocrpara.h noinst_HEADERS += src/ccstruct/ocrrow.h noinst_HEADERS += src/ccstruct/otsuthr.h noinst_HEADERS += src/ccstruct/pageres.h noinst_HEADERS += src/ccstruct/pdblock.h noinst_HEADERS += src/ccstruct/points.h noinst_HEADERS += src/ccstruct/polyaprx.h noinst_HEADERS += src/ccstruct/polyblk.h noinst_HEADERS += src/ccstruct/quadlsq.h noinst_HEADERS += src/ccstruct/quadratc.h noinst_HEADERS += src/ccstruct/quspline.h noinst_HEADERS += src/ccstruct/ratngs.h noinst_HEADERS += src/ccstruct/rect.h noinst_HEADERS += src/ccstruct/rejctmap.h noinst_HEADERS += src/ccstruct/seam.h noinst_HEADERS += src/ccstruct/split.h noinst_HEADERS += src/ccstruct/statistc.h noinst_HEADERS += src/ccstruct/stepblob.h noinst_HEADERS += src/ccstruct/werd.h if !DISABLED_LEGACY_ENGINE noinst_HEADERS += src/ccstruct/fontinfo.h noinst_HEADERS += src/ccstruct/params_training_featdef.h endif libtesseract_la_SOURCES += src/ccstruct/blamer.cpp libtesseract_la_SOURCES += src/ccstruct/blobbox.cpp libtesseract_la_SOURCES += src/ccstruct/blobs.cpp libtesseract_la_SOURCES += src/ccstruct/blread.cpp libtesseract_la_SOURCES += src/ccstruct/boxread.cpp libtesseract_la_SOURCES += src/ccstruct/boxword.cpp libtesseract_la_SOURCES += src/ccstruct/ccstruct.cpp libtesseract_la_SOURCES += src/ccstruct/coutln.cpp libtesseract_la_SOURCES += src/ccstruct/detlinefit.cpp libtesseract_la_SOURCES += src/ccstruct/dppoint.cpp libtesseract_la_SOURCES += src/ccstruct/image.cpp libtesseract_la_SOURCES += src/ccstruct/imagedata.cpp libtesseract_la_SOURCES += src/ccstruct/linlsq.cpp libtesseract_la_SOURCES += src/ccstruct/matrix.cpp libtesseract_la_SOURCES += src/ccstruct/mod128.cpp libtesseract_la_SOURCES += src/ccstruct/normalis.cpp libtesseract_la_SOURCES += src/ccstruct/ocrblock.cpp libtesseract_la_SOURCES += src/ccstruct/ocrpara.cpp libtesseract_la_SOURCES += src/ccstruct/ocrrow.cpp libtesseract_la_SOURCES += src/ccstruct/otsuthr.cpp libtesseract_la_SOURCES += src/ccstruct/pageres.cpp libtesseract_la_SOURCES += src/ccstruct/pdblock.cpp libtesseract_la_SOURCES += src/ccstruct/points.cpp libtesseract_la_SOURCES += src/ccstruct/polyaprx.cpp libtesseract_la_SOURCES += src/ccstruct/polyblk.cpp libtesseract_la_SOURCES += src/ccstruct/quadlsq.cpp libtesseract_la_SOURCES += src/ccstruct/quspline.cpp libtesseract_la_SOURCES += src/ccstruct/ratngs.cpp libtesseract_la_SOURCES += src/ccstruct/rect.cpp libtesseract_la_SOURCES += src/ccstruct/rejctmap.cpp libtesseract_la_SOURCES += src/ccstruct/seam.cpp libtesseract_la_SOURCES += src/ccstruct/split.cpp libtesseract_la_SOURCES += src/ccstruct/statistc.cpp libtesseract_la_SOURCES += src/ccstruct/stepblob.cpp libtesseract_la_SOURCES += src/ccstruct/werd.cpp if !DISABLED_LEGACY_ENGINE libtesseract_la_SOURCES += src/ccstruct/fontinfo.cpp libtesseract_la_SOURCES += src/ccstruct/params_training_featdef.cpp endif # Rules for src/ccutil libtesseract_ccutil_la_CPPFLAGS = $(AM_CPPFLAGS) libtesseract_ccutil_la_CPPFLAGS += $(libarchive_CFLAGS) if !NO_TESSDATA_PREFIX libtesseract_ccutil_la_CPPFLAGS += -DTESSDATA_PREFIX='"@datadir@"' endif noinst_HEADERS += src/ccutil/ccutil.h noinst_HEADERS += src/ccutil/clst.h noinst_HEADERS += src/ccutil/elst2.h noinst_HEADERS += src/ccutil/elst.h noinst_HEADERS += src/ccutil/errcode.h noinst_HEADERS += src/ccutil/fileerr.h noinst_HEADERS += src/ccutil/genericheap.h noinst_HEADERS += src/ccutil/genericvector.h noinst_HEADERS += src/ccutil/helpers.h noinst_HEADERS += src/ccutil/host.h noinst_HEADERS += src/ccutil/kdpair.h noinst_HEADERS += src/ccutil/lsterr.h noinst_HEADERS += src/ccutil/object_cache.h noinst_HEADERS += src/ccutil/params.h noinst_HEADERS += src/ccutil/qrsequence.h noinst_HEADERS += src/ccutil/sorthelper.h noinst_HEADERS += src/ccutil/scanutils.h noinst_HEADERS += src/ccutil/serialis.h noinst_HEADERS += src/ccutil/tessdatamanager.h noinst_HEADERS += src/ccutil/tprintf.h noinst_HEADERS += src/ccutil/unicharcompress.h noinst_HEADERS += src/ccutil/unicharmap.h noinst_HEADERS += src/ccutil/unicharset.h noinst_HEADERS += src/ccutil/unicity_table.h if !DISABLED_LEGACY_ENGINE noinst_HEADERS += src/ccutil/ambigs.h noinst_HEADERS += src/ccutil/bitvector.h noinst_HEADERS += src/ccutil/indexmapbidi.h noinst_HEADERS += src/ccutil/universalambigs.h endif noinst_LTLIBRARIES += libtesseract_ccutil.la libtesseract_ccutil_la_SOURCES = src/ccutil/ccutil.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/clst.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/elst2.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/elst.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/errcode.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/serialis.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/scanutils.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/tessdatamanager.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/tprintf.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/unichar.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/unicharcompress.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/unicharmap.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/unicharset.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/params.cpp if !DISABLED_LEGACY_ENGINE libtesseract_ccutil_la_SOURCES += src/ccutil/ambigs.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/bitvector.cpp libtesseract_ccutil_la_SOURCES += src/ccutil/indexmapbidi.cpp endif # Rules for src/classify. noinst_HEADERS += src/classify/classify.h if !DISABLED_LEGACY_ENGINE noinst_HEADERS += src/classify/adaptive.h noinst_HEADERS += src/classify/cluster.h noinst_HEADERS += src/classify/clusttool.h noinst_HEADERS += src/classify/featdefs.h noinst_HEADERS += src/classify/float2int.h noinst_HEADERS += src/classify/fpoint.h noinst_HEADERS += src/classify/intfeaturespace.h noinst_HEADERS += src/classify/intfx.h noinst_HEADERS += src/classify/intmatcher.h noinst_HEADERS += src/classify/intproto.h noinst_HEADERS += src/classify/kdtree.h noinst_HEADERS += src/classify/mf.h noinst_HEADERS += src/classify/mfdefs.h noinst_HEADERS += src/classify/mfoutline.h noinst_HEADERS += src/classify/mfx.h noinst_HEADERS += src/classify/normfeat.h noinst_HEADERS += src/classify/normmatch.h noinst_HEADERS += src/classify/ocrfeatures.h noinst_HEADERS += src/classify/outfeat.h noinst_HEADERS += src/classify/picofeat.h noinst_HEADERS += src/classify/protos.h noinst_HEADERS += src/classify/shapeclassifier.h noinst_HEADERS += src/classify/shapetable.h noinst_HEADERS += src/classify/tessclassifier.h noinst_HEADERS += src/classify/trainingsample.h endif libtesseract_la_SOURCES += src/classify/classify.cpp if !DISABLED_LEGACY_ENGINE libtesseract_la_SOURCES += src/classify/adaptive.cpp libtesseract_la_SOURCES += src/classify/adaptmatch.cpp libtesseract_la_SOURCES += src/classify/blobclass.cpp libtesseract_la_SOURCES += src/classify/cluster.cpp libtesseract_la_SOURCES += src/classify/clusttool.cpp libtesseract_la_SOURCES += src/classify/cutoffs.cpp libtesseract_la_SOURCES += src/classify/featdefs.cpp libtesseract_la_SOURCES += src/classify/float2int.cpp libtesseract_la_SOURCES += src/classify/fpoint.cpp libtesseract_la_SOURCES += src/classify/intfeaturespace.cpp libtesseract_la_SOURCES += src/classify/intfx.cpp libtesseract_la_SOURCES += src/classify/intmatcher.cpp libtesseract_la_SOURCES += src/classify/intproto.cpp libtesseract_la_SOURCES += src/classify/kdtree.cpp libtesseract_la_SOURCES += src/classify/mf.cpp libtesseract_la_SOURCES += src/classify/mfoutline.cpp libtesseract_la_SOURCES += src/classify/mfx.cpp libtesseract_la_SOURCES += src/classify/normfeat.cpp libtesseract_la_SOURCES += src/classify/normmatch.cpp libtesseract_la_SOURCES += src/classify/ocrfeatures.cpp libtesseract_la_SOURCES += src/classify/outfeat.cpp libtesseract_la_SOURCES += src/classify/picofeat.cpp libtesseract_la_SOURCES += src/classify/protos.cpp libtesseract_la_SOURCES += src/classify/shapeclassifier.cpp libtesseract_la_SOURCES += src/classify/shapetable.cpp libtesseract_la_SOURCES += src/classify/tessclassifier.cpp libtesseract_la_SOURCES += src/classify/trainingsample.cpp endif # Rules for src/cutil. if !DISABLED_LEGACY_ENGINE noinst_HEADERS += src/cutil/bitvec.h noinst_HEADERS += src/cutil/oldlist.h endif if !DISABLED_LEGACY_ENGINE libtesseract_la_SOURCES += src/cutil/oldlist.cpp endif # Rules for src/dict. noinst_HEADERS += src/dict/dawg.h noinst_HEADERS += src/dict/dawg_cache.h noinst_HEADERS += src/dict/dict.h noinst_HEADERS += src/dict/matchdefs.h noinst_HEADERS += src/dict/stopper.h noinst_HEADERS += src/dict/trie.h libtesseract_la_SOURCES += src/dict/context.cpp libtesseract_la_SOURCES += src/dict/dawg.cpp libtesseract_la_SOURCES += src/dict/dawg_cache.cpp libtesseract_la_SOURCES += src/dict/dict.cpp libtesseract_la_SOURCES += src/dict/stopper.cpp libtesseract_la_SOURCES += src/dict/trie.cpp if !DISABLED_LEGACY_ENGINE libtesseract_la_SOURCES += src/dict/hyphen.cpp libtesseract_la_SOURCES += src/dict/permdawg.cpp endif # Rules for src/lstm. libtesseract_lstm_la_CPPFLAGS = $(AM_CPPFLAGS) libtesseract_lstm_la_CPPFLAGS += -I$(top_srcdir)/src/arch libtesseract_lstm_la_CPPFLAGS += -I$(top_srcdir)/src/ccstruct libtesseract_lstm_la_CPPFLAGS += -I$(top_srcdir)/src/ccutil libtesseract_lstm_la_CPPFLAGS += -I$(top_srcdir)/src/classify libtesseract_lstm_la_CPPFLAGS += -I$(top_srcdir)/src/cutil libtesseract_lstm_la_CPPFLAGS += -I$(top_srcdir)/src/dict libtesseract_lstm_la_CPPFLAGS += -I$(top_srcdir)/src/lstm libtesseract_lstm_la_CPPFLAGS += -I$(top_srcdir)/src/viewer if TENSORFLOW libtesseract_lstm_la_CPPFLAGS += -DINCLUDE_TENSORFLOW libtesseract_lstm_la_CPPFLAGS += -I/usr/include/tensorflow endif if !NO_TESSDATA_PREFIX libtesseract_lstm_la_CPPFLAGS += -DTESSDATA_PREFIX='"@datadir@"' endif noinst_HEADERS += src/lstm/convolve.h noinst_HEADERS += src/lstm/fullyconnected.h noinst_HEADERS += src/lstm/functions.h noinst_HEADERS += src/lstm/input.h noinst_HEADERS += src/lstm/lstm.h noinst_HEADERS += src/lstm/lstmrecognizer.h noinst_HEADERS += src/lstm/maxpool.h noinst_HEADERS += src/lstm/network.h noinst_HEADERS += src/lstm/networkio.h noinst_HEADERS += src/lstm/networkscratch.h noinst_HEADERS += src/lstm/parallel.h noinst_HEADERS += src/lstm/plumbing.h noinst_HEADERS += src/lstm/recodebeam.h noinst_HEADERS += src/lstm/reconfig.h noinst_HEADERS += src/lstm/reversed.h noinst_HEADERS += src/lstm/series.h noinst_HEADERS += src/lstm/static_shape.h noinst_HEADERS += src/lstm/stridemap.h noinst_HEADERS += src/lstm/tfnetwork.h noinst_HEADERS += src/lstm/weightmatrix.h noinst_LTLIBRARIES += libtesseract_lstm.la libtesseract_lstm_la_SOURCES = src/lstm/convolve.cpp libtesseract_lstm_la_SOURCES += src/lstm/fullyconnected.cpp libtesseract_lstm_la_SOURCES += src/lstm/functions.cpp libtesseract_lstm_la_SOURCES += src/lstm/input.cpp libtesseract_lstm_la_SOURCES += src/lstm/lstm.cpp libtesseract_lstm_la_SOURCES += src/lstm/lstmrecognizer.cpp libtesseract_lstm_la_SOURCES += src/lstm/maxpool.cpp libtesseract_lstm_la_SOURCES += src/lstm/network.cpp libtesseract_lstm_la_SOURCES += src/lstm/networkio.cpp libtesseract_lstm_la_SOURCES += src/lstm/parallel.cpp libtesseract_lstm_la_SOURCES += src/lstm/plumbing.cpp libtesseract_lstm_la_SOURCES += src/lstm/recodebeam.cpp libtesseract_lstm_la_SOURCES += src/lstm/reconfig.cpp libtesseract_lstm_la_SOURCES += src/lstm/reversed.cpp libtesseract_lstm_la_SOURCES += src/lstm/series.cpp libtesseract_lstm_la_SOURCES += src/lstm/stridemap.cpp libtesseract_lstm_la_SOURCES += src/lstm/tfnetwork.cpp libtesseract_lstm_la_SOURCES += src/lstm/weightmatrix.cpp if TENSORFLOW libtesseract_lstm_la_SOURCES += src/lstm/tfnetwork.pb.cc endif # Rules for src/textord. noinst_HEADERS += src/textord/alignedblob.h noinst_HEADERS += src/textord/baselinedetect.h noinst_HEADERS += src/textord/bbgrid.h noinst_HEADERS += src/textord/blkocc.h noinst_HEADERS += src/textord/blobgrid.h noinst_HEADERS += src/textord/ccnontextdetect.h noinst_HEADERS += src/textord/cjkpitch.h noinst_HEADERS += src/textord/colfind.h noinst_HEADERS += src/textord/colpartition.h noinst_HEADERS += src/textord/colpartitionset.h noinst_HEADERS += src/textord/colpartitiongrid.h noinst_HEADERS += src/textord/devanagari_processing.h noinst_HEADERS += src/textord/drawtord.h noinst_HEADERS += src/textord/edgblob.h noinst_HEADERS += src/textord/edgloop.h noinst_HEADERS += src/textord/fpchop.h noinst_HEADERS += src/textord/gap_map.h noinst_HEADERS += src/textord/imagefind.h noinst_HEADERS += src/textord/linefind.h noinst_HEADERS += src/textord/makerow.h noinst_HEADERS += src/textord/oldbasel.h noinst_HEADERS += src/textord/pithsync.h noinst_HEADERS += src/textord/pitsync1.h noinst_HEADERS += src/textord/scanedg.h noinst_HEADERS += src/textord/sortflts.h noinst_HEADERS += src/textord/strokewidth.h noinst_HEADERS += src/textord/tabfind.h noinst_HEADERS += src/textord/tablefind.h noinst_HEADERS += src/textord/tabvector.h noinst_HEADERS += src/textord/tablerecog.h noinst_HEADERS += src/textord/textlineprojection.h noinst_HEADERS += src/textord/textord.h noinst_HEADERS += src/textord/topitch.h noinst_HEADERS += src/textord/tordmain.h noinst_HEADERS += src/textord/tovars.h noinst_HEADERS += src/textord/underlin.h noinst_HEADERS += src/textord/wordseg.h noinst_HEADERS += src/textord/workingpartset.h if !DISABLED_LEGACY_ENGINE noinst_HEADERS += src/textord/equationdetectbase.h endif libtesseract_la_SOURCES += src/textord/alignedblob.cpp libtesseract_la_SOURCES += src/textord/baselinedetect.cpp libtesseract_la_SOURCES += src/textord/bbgrid.cpp libtesseract_la_SOURCES += src/textord/blkocc.cpp libtesseract_la_SOURCES += src/textord/blobgrid.cpp libtesseract_la_SOURCES += src/textord/ccnontextdetect.cpp libtesseract_la_SOURCES += src/textord/cjkpitch.cpp libtesseract_la_SOURCES += src/textord/colfind.cpp libtesseract_la_SOURCES += src/textord/colpartition.cpp libtesseract_la_SOURCES += src/textord/colpartitionset.cpp libtesseract_la_SOURCES += src/textord/colpartitiongrid.cpp libtesseract_la_SOURCES += src/textord/devanagari_processing.cpp libtesseract_la_SOURCES += src/textord/drawtord.cpp libtesseract_la_SOURCES += src/textord/edgblob.cpp libtesseract_la_SOURCES += src/textord/edgloop.cpp libtesseract_la_SOURCES += src/textord/fpchop.cpp libtesseract_la_SOURCES += src/textord/gap_map.cpp libtesseract_la_SOURCES += src/textord/imagefind.cpp libtesseract_la_SOURCES += src/textord/linefind.cpp libtesseract_la_SOURCES += src/textord/makerow.cpp libtesseract_la_SOURCES += src/textord/oldbasel.cpp libtesseract_la_SOURCES += src/textord/pithsync.cpp libtesseract_la_SOURCES += src/textord/pitsync1.cpp libtesseract_la_SOURCES += src/textord/scanedg.cpp libtesseract_la_SOURCES += src/textord/sortflts.cpp libtesseract_la_SOURCES += src/textord/strokewidth.cpp libtesseract_la_SOURCES += src/textord/tabfind.cpp libtesseract_la_SOURCES += src/textord/tablefind.cpp libtesseract_la_SOURCES += src/textord/tabvector.cpp libtesseract_la_SOURCES += src/textord/tablerecog.cpp libtesseract_la_SOURCES += src/textord/textlineprojection.cpp libtesseract_la_SOURCES += src/textord/textord.cpp libtesseract_la_SOURCES += src/textord/topitch.cpp libtesseract_la_SOURCES += src/textord/tordmain.cpp libtesseract_la_SOURCES += src/textord/tospace.cpp libtesseract_la_SOURCES += src/textord/tovars.cpp libtesseract_la_SOURCES += src/textord/underlin.cpp libtesseract_la_SOURCES += src/textord/wordseg.cpp libtesseract_la_SOURCES += src/textord/workingpartset.cpp if !DISABLED_LEGACY_ENGINE libtesseract_la_SOURCES += src/textord/equationdetectbase.cpp endif # Rules for src/viewer. if !GRAPHICS_DISABLED noinst_HEADERS += src/viewer/scrollview.h noinst_HEADERS += src/viewer/svmnode.h noinst_HEADERS += src/viewer/svutil.h libtesseract_la_SOURCES += src/viewer/scrollview.cpp libtesseract_la_SOURCES += src/viewer/svmnode.cpp libtesseract_la_SOURCES += src/viewer/svutil.cpp EXTRA_PROGRAMS += svpaint svpaint_CPPFLAGS = $(AM_CPPFLAGS) svpaint_CPPFLAGS += -I$(top_srcdir)/src/ccstruct svpaint_CPPFLAGS += -I$(top_srcdir)/src/viewer svpaint_SOURCES = src/svpaint.cpp svpaint_LDADD = libtesseract.la endif # Rules for src/wordrec. noinst_HEADERS += src/wordrec/wordrec.h if !DISABLED_LEGACY_ENGINE noinst_HEADERS += src/wordrec/associate.h noinst_HEADERS += src/wordrec/chop.h noinst_HEADERS += src/wordrec/drawfx.h noinst_HEADERS += src/wordrec/findseam.h noinst_HEADERS += src/wordrec/language_model.h noinst_HEADERS += src/wordrec/lm_consistency.h noinst_HEADERS += src/wordrec/lm_pain_points.h noinst_HEADERS += src/wordrec/lm_state.h noinst_HEADERS += src/wordrec/outlines.h noinst_HEADERS += src/wordrec/params_model.h noinst_HEADERS += src/wordrec/plotedges.h noinst_HEADERS += src/wordrec/render.h endif libtesseract_la_SOURCES += src/wordrec/tface.cpp libtesseract_la_SOURCES += src/wordrec/wordrec.cpp if !DISABLED_LEGACY_ENGINE libtesseract_la_SOURCES += src/wordrec/associate.cpp libtesseract_la_SOURCES += src/wordrec/chop.cpp libtesseract_la_SOURCES += src/wordrec/chopper.cpp libtesseract_la_SOURCES += src/wordrec/drawfx.cpp libtesseract_la_SOURCES += src/wordrec/findseam.cpp libtesseract_la_SOURCES += src/wordrec/gradechop.cpp libtesseract_la_SOURCES += src/wordrec/language_model.cpp libtesseract_la_SOURCES += src/wordrec/lm_consistency.cpp libtesseract_la_SOURCES += src/wordrec/lm_pain_points.cpp libtesseract_la_SOURCES += src/wordrec/lm_state.cpp libtesseract_la_SOURCES += src/wordrec/outlines.cpp libtesseract_la_SOURCES += src/wordrec/params_model.cpp libtesseract_la_SOURCES += src/wordrec/pieces.cpp if !GRAPHICS_DISABLED libtesseract_la_SOURCES += src/wordrec/plotedges.cpp endif libtesseract_la_SOURCES += src/wordrec/render.cpp libtesseract_la_SOURCES += src/wordrec/segsearch.cpp libtesseract_la_SOURCES += src/wordrec/wordclass.cpp endif # Rules for tesseract executable. bin_PROGRAMS = tesseract tesseract_SOURCES = src/tesseract.cpp tesseract_CPPFLAGS = $(AM_CPPFLAGS) tesseract_CPPFLAGS += -I$(top_srcdir)/src/arch tesseract_CPPFLAGS += -I$(top_srcdir)/src/ccmain tesseract_CPPFLAGS += -I$(top_srcdir)/src/ccstruct tesseract_CPPFLAGS += -I$(top_srcdir)/src/ccutil tesseract_CPPFLAGS += -I$(top_srcdir)/src/classify tesseract_CPPFLAGS += -I$(top_srcdir)/src/cutil tesseract_CPPFLAGS += -I$(top_srcdir)/src/dict tesseract_CPPFLAGS += -I$(top_srcdir)/src/textord tesseract_CPPFLAGS += -I$(top_srcdir)/src/viewer tesseract_CPPFLAGS += -I$(top_srcdir)/src/wordrec tesseract_LDFLAGS = $(OPENMP_CXXFLAGS) tesseract_LDADD = libtesseract.la tesseract_LDADD += $(LEPTONICA_LIBS) tesseract_LDADD += $(TENSORFLOW_LIBS) tesseract_LDADD += $(libarchive_LIBS) tesseract_LDADD += $(libcurl_LIBS) if T_WIN tesseract_LDADD += -ltiff tesseract_LDADD += -lws2_32 endif if ADD_RT tesseract_LDADD += -lrt endif # Rules for training tools. if ENABLE_TRAINING training: $(trainingtools) | $(PROGRAMS) training-install: $(trainingtools) mkdir -p $(DESTDIR)$(bindir) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install \ $(INSTALL) $(INSTALL_STRIP_FLAG) $(trainingtools) $(DESTDIR)$(bindir) training-uninstall: # Some unit tests use code from training. check: libtesseract_training.la # dawg_test runs dawg2wordlist and wordlist2dawg. check: dawg2wordlist wordlist2dawg else training: @echo "Need to reconfigure project, so there are no errors" endif CLEANFILES += $(EXTRA_PROGRAMS) training_CPPFLAGS = $(AM_CPPFLAGS) training_CPPFLAGS += -DPANGO_ENABLE_ENGINE training_CPPFLAGS += -DTESS_COMMON_TRAINING_API= training_CPPFLAGS += -DTESS_PANGO_TRAINING_API= training_CPPFLAGS += -DTESS_UNICHARSET_TRAINING_API= training_CPPFLAGS += -I$(top_srcdir)/src/training training_CPPFLAGS += -I$(top_srcdir)/src/training/common training_CPPFLAGS += -I$(top_srcdir)/src/training/pango training_CPPFLAGS += -I$(top_srcdir)/src/training/unicharset training_CPPFLAGS += -I$(top_srcdir)/src/api training_CPPFLAGS += -I$(top_srcdir)/src/ccmain training_CPPFLAGS += -I$(top_srcdir)/src/ccutil training_CPPFLAGS += -I$(top_srcdir)/src/ccstruct training_CPPFLAGS += -I$(top_srcdir)/src/lstm training_CPPFLAGS += -I$(top_srcdir)/src/arch training_CPPFLAGS += -I$(top_srcdir)/src/viewer training_CPPFLAGS += -I$(top_srcdir)/src/textord training_CPPFLAGS += -I$(top_srcdir)/src/dict training_CPPFLAGS += -I$(top_srcdir)/src/classify training_CPPFLAGS += -I$(top_srcdir)/src/wordrec training_CPPFLAGS += -I$(top_srcdir)/src/cutil training_CPPFLAGS += $(ICU_UC_CFLAGS) $(ICU_I18N_CFLAGS) training_CPPFLAGS += $(pango_CFLAGS) training_CPPFLAGS += $(cairo_CFLAGS) if DISABLED_LEGACY_ENGINE training_CPPFLAGS += -DDISABLED_LEGACY_ENGINE endif # TODO: training programs cannot be linked to shared library created # with -fvisibility if VISIBILITY AM_LDFLAGS += -all-static endif noinst_HEADERS += src/training/pango/boxchar.h noinst_HEADERS += src/training/common/commandlineflags.h noinst_HEADERS += src/training/common/commontraining.h noinst_HEADERS += src/training/common/ctc.h noinst_HEADERS += src/training/common/networkbuilder.h noinst_HEADERS += src/training/degradeimage.h noinst_HEADERS += src/training/pango/ligature_table.h noinst_HEADERS += src/training/pango/pango_font_info.h noinst_HEADERS += src/training/pango/stringrenderer.h noinst_HEADERS += src/training/pango/tlog.h noinst_HEADERS += src/training/unicharset/icuerrorcode.h noinst_HEADERS += src/training/unicharset/fileio.h noinst_HEADERS += src/training/unicharset/lang_model_helpers.h noinst_HEADERS += src/training/unicharset/lstmtester.h noinst_HEADERS += src/training/unicharset/lstmtrainer.h noinst_HEADERS += src/training/unicharset/normstrngs.h noinst_HEADERS += src/training/unicharset/unicharset_training_utils.h noinst_HEADERS += src/training/unicharset/validate_grapheme.h noinst_HEADERS += src/training/unicharset/validate_indic.h noinst_HEADERS += src/training/unicharset/validate_javanese.h noinst_HEADERS += src/training/unicharset/validate_khmer.h noinst_HEADERS += src/training/unicharset/validate_myanmar.h noinst_HEADERS += src/training/unicharset/validator.h if !DISABLED_LEGACY_ENGINE noinst_HEADERS += src/training/common/errorcounter.h noinst_HEADERS += src/training/common/intfeaturedist.h noinst_HEADERS += src/training/common/intfeaturemap.h noinst_HEADERS += src/training/common/mastertrainer.h noinst_HEADERS += src/training/common/sampleiterator.h noinst_HEADERS += src/training/common/trainingsampleset.h noinst_HEADERS += src/training/mergenf.h endif CLEANFILES += libtesseract_training.la EXTRA_LTLIBRARIES = libtesseract_training.la libtesseract_training_la_CPPFLAGS = $(training_CPPFLAGS) libtesseract_training_la_SOURCES = src/training/pango/boxchar.cpp libtesseract_training_la_SOURCES += src/training/common/commandlineflags.cpp libtesseract_training_la_SOURCES += src/training/common/commontraining.cpp libtesseract_training_la_SOURCES += src/training/common/ctc.cpp libtesseract_training_la_SOURCES += src/training/common/networkbuilder.cpp libtesseract_training_la_SOURCES += src/training/degradeimage.cpp libtesseract_training_la_SOURCES += src/training/pango/ligature_table.cpp libtesseract_training_la_SOURCES += src/training/pango/pango_font_info.cpp libtesseract_training_la_SOURCES += src/training/pango/stringrenderer.cpp libtesseract_training_la_SOURCES += src/training/pango/tlog.cpp libtesseract_training_la_SOURCES += src/training/unicharset/icuerrorcode.cpp libtesseract_training_la_SOURCES += src/training/unicharset/fileio.cpp libtesseract_training_la_SOURCES += src/training/unicharset/lang_model_helpers.cpp libtesseract_training_la_SOURCES += src/training/unicharset/lstmtester.cpp libtesseract_training_la_SOURCES += src/training/unicharset/lstmtrainer.cpp libtesseract_training_la_SOURCES += src/training/unicharset/normstrngs.cpp libtesseract_training_la_SOURCES += src/training/unicharset/unicharset_training_utils.cpp libtesseract_training_la_SOURCES += src/training/unicharset/validate_grapheme.cpp libtesseract_training_la_SOURCES += src/training/unicharset/validate_indic.cpp libtesseract_training_la_SOURCES += src/training/unicharset/validate_javanese.cpp libtesseract_training_la_SOURCES += src/training/unicharset/validate_khmer.cpp libtesseract_training_la_SOURCES += src/training/unicharset/validate_myanmar.cpp libtesseract_training_la_SOURCES += src/training/unicharset/validator.cpp if !DISABLED_LEGACY_ENGINE libtesseract_training_la_SOURCES += src/training/common/errorcounter.cpp libtesseract_training_la_SOURCES += src/training/common/intfeaturedist.cpp libtesseract_training_la_SOURCES += src/training/common/intfeaturemap.cpp libtesseract_training_la_SOURCES += src/training/common/mastertrainer.cpp libtesseract_training_la_SOURCES += src/training/common/sampleiterator.cpp libtesseract_training_la_SOURCES += src/training/common/trainingsampleset.cpp endif trainingtools = combine_lang_model$(EXEEXT) trainingtools += combine_tessdata$(EXEEXT) trainingtools += dawg2wordlist$(EXEEXT) trainingtools += lstmeval$(EXEEXT) trainingtools += lstmtraining$(EXEEXT) trainingtools += merge_unicharsets$(EXEEXT) trainingtools += set_unicharset_properties$(EXEEXT) trainingtools += text2image$(EXEEXT) trainingtools += unicharset_extractor$(EXEEXT) trainingtools += wordlist2dawg$(EXEEXT) if !DISABLED_LEGACY_ENGINE trainingtools += ambiguous_words$(EXEEXT) trainingtools += classifier_tester$(EXEEXT) trainingtools += cntraining$(EXEEXT) trainingtools += mftraining$(EXEEXT) trainingtools += shapeclustering$(EXEEXT) endif $(trainingtools): libtesseract.la EXTRA_PROGRAMS += $(trainingtools) extralib = libtesseract.la extralib += $(libarchive_LIBS) extralib += $(LEPTONICA_LIBS) extralib += $(TENSORFLOW_LIBS) if T_WIN extralib += -lws2_32 endif if !DISABLED_LEGACY_ENGINE ambiguous_words_CPPFLAGS = $(training_CPPFLAGS) ambiguous_words_SOURCES = src/training/ambiguous_words.cpp ambiguous_words_LDADD = libtesseract_training.la ambiguous_words_LDADD += $(extralib) classifier_tester_CPPFLAGS = $(training_CPPFLAGS) classifier_tester_SOURCES = src/training/classifier_tester.cpp classifier_tester_LDADD = libtesseract_training.la classifier_tester_LDADD += $(extralib) cntraining_CPPFLAGS = $(training_CPPFLAGS) cntraining_SOURCES = src/training/cntraining.cpp cntraining_LDADD = libtesseract_training.la cntraining_LDADD += $(extralib) mftraining_CPPFLAGS = $(training_CPPFLAGS) mftraining_SOURCES = src/training/mftraining.cpp src/training/mergenf.cpp mftraining_LDADD = libtesseract_training.la mftraining_LDADD += $(ICU_UC_LIBS) mftraining_LDADD += $(extralib) shapeclustering_CPPFLAGS = $(training_CPPFLAGS) shapeclustering_SOURCES = src/training/shapeclustering.cpp shapeclustering_LDADD = libtesseract_training.la shapeclustering_LDADD += $(extralib) endif combine_lang_model_CPPFLAGS = $(training_CPPFLAGS) combine_lang_model_SOURCES = src/training/combine_lang_model.cpp combine_lang_model_LDADD = libtesseract_training.la combine_lang_model_LDADD += $(ICU_I18N_LIBS) $(ICU_UC_LIBS) combine_lang_model_LDADD += $(extralib) combine_tessdata_CPPFLAGS = $(training_CPPFLAGS) combine_tessdata_SOURCES = src/training/combine_tessdata.cpp combine_tessdata_LDADD = $(extralib) dawg2wordlist_CPPFLAGS = $(training_CPPFLAGS) dawg2wordlist_SOURCES = src/training/dawg2wordlist.cpp dawg2wordlist_LDADD = $(extralib) lstmeval_CPPFLAGS = $(training_CPPFLAGS) lstmeval_SOURCES = src/training/lstmeval.cpp lstmeval_LDADD = libtesseract_training.la lstmeval_LDADD += $(ICU_UC_LIBS) lstmeval_LDADD += $(extralib) lstmtraining_CPPFLAGS = $(training_CPPFLAGS) lstmtraining_SOURCES = src/training/lstmtraining.cpp lstmtraining_LDADD = libtesseract_training.la lstmtraining_LDADD += $(ICU_I18N_LIBS) $(ICU_UC_LIBS) lstmtraining_LDADD += $(extralib) merge_unicharsets_CPPFLAGS = $(training_CPPFLAGS) merge_unicharsets_SOURCES = src/training/merge_unicharsets.cpp merge_unicharsets_LDADD = $(extralib) set_unicharset_properties_CPPFLAGS = $(training_CPPFLAGS) set_unicharset_properties_SOURCES = src/training/set_unicharset_properties.cpp set_unicharset_properties_LDADD = libtesseract_training.la set_unicharset_properties_LDADD += $(ICU_I18N_LIBS) $(ICU_UC_LIBS) set_unicharset_properties_LDADD += $(extralib) text2image_CPPFLAGS = $(training_CPPFLAGS) text2image_SOURCES = src/training/text2image.cpp text2image_LDADD = libtesseract_training.la text2image_LDADD += $(ICU_I18N_LIBS) $(ICU_UC_LIBS) text2image_LDADD += $(extralib) text2image_LDADD += $(ICU_UC_LIBS) $(cairo_LIBS) text2image_LDADD += $(pango_LIBS) $(pangocairo_LIBS) $(pangoft2_LIBS) unicharset_extractor_CPPFLAGS = $(training_CPPFLAGS) unicharset_extractor_SOURCES = src/training/unicharset_extractor.cpp unicharset_extractor_LDADD = libtesseract_training.la unicharset_extractor_LDADD += $(ICU_I18N_LIBS) $(ICU_UC_LIBS) unicharset_extractor_LDADD += $(extralib) wordlist2dawg_CPPFLAGS = $(training_CPPFLAGS) wordlist2dawg_SOURCES = src/training/wordlist2dawg.cpp wordlist2dawg_LDADD = $(extralib) # fuzzer-api is used for fuzzing tests. # They are run by OSS-Fuzz https://oss-fuzz.com/, but can also be run locally. # Note: -fsanitize=fuzzer currently requires the clang++ compiler. # LIB_FUZZING_ENGINE can be overridden by the caller. # This is used by OSS-Fuzz. LIB_FUZZING_ENGINE ?= -fsanitize=fuzzer fuzzer-api: libtesseract.la fuzzer-api: unittest/fuzzers/fuzzer-api.cpp $(CXX) $(CXXFLAGS) -g $(LIB_FUZZING_ENGINE) \ -I $(top_srcdir)/include \ -I $(builddir)/include \ -I $(top_srcdir)/src/ccmain \ -I $(top_srcdir)/src/ccstruct \ -I $(top_srcdir)/src/ccutil \ $(LEPTONICA_CFLAGS) \ $(OPENMP_CXXFLAGS) \ $< \ $(builddir)/.libs/libtesseract.a \ $(LEPTONICA_LIBS) \ $(TENSORFLOW_LIBS) \ $(libarchive_LIBS) \ $(libcurl_LIBS) \ -o $@ fuzzer-api-512x256: libtesseract.la fuzzer-api-512x256: unittest/fuzzers/fuzzer-api.cpp $(CXX) $(CXXFLAGS) -g $(LIB_FUZZING_ENGINE) \ -DTESSERACT_FUZZER_WIDTH=512 \ -DTESSERACT_FUZZER_HEIGHT=256 \ -I $(top_srcdir)/include \ -I $(builddir)/include \ -I $(top_srcdir)/src/ccmain \ -I $(top_srcdir)/src/ccstruct \ -I $(top_srcdir)/src/ccutil \ $(LEPTONICA_CFLAGS) \ $(OPENMP_CXXFLAGS) \ $< \ $(builddir)/.libs/libtesseract.a \ $(LEPTONICA_LIBS) \ $(TENSORFLOW_LIBS) \ $(libarchive_LIBS) \ $(libcurl_LIBS) \ -o $@ CLEANFILES += fuzzer-api fuzzer-api-512x256 if ASCIIDOC man_MANS = doc/combine_lang_model.1 man_MANS += doc/combine_tessdata.1 man_MANS += doc/dawg2wordlist.1 man_MANS += doc/lstmeval.1 man_MANS += doc/lstmtraining.1 man_MANS += doc/merge_unicharsets.1 man_MANS += doc/set_unicharset_properties.1 man_MANS += doc/tesseract.1 man_MANS += doc/text2image.1 man_MANS += doc/unicharset.5 man_MANS += doc/unicharset_extractor.1 man_MANS += doc/wordlist2dawg.1 if !DISABLED_LEGACY_ENGINE man_MANS += doc/ambiguous_words.1 man_MANS += doc/classifier_tester.1 man_MANS += doc/cntraining.1 man_MANS += doc/mftraining.1 man_MANS += doc/shapeclustering.1 man_MANS += doc/unicharambigs.5 endif man_xslt = http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl EXTRA_DIST += $(man_MANS) doc/Doxyfile html: ${man_MANS:%=%.html} pdf: ${man_MANS:%=%.pdf} SUFFIXES = .asc .html .pdf .asc: if HAVE_XML_CATALOG_FILES asciidoc -b docbook -d manpage -o - $< | \ XML_CATALOG_FILES=$(XML_CATALOG_FILES) xsltproc --nonet -o $@ $(man_xslt) - else asciidoc -b docbook -d manpage -o - $< | \ xsltproc --nonet -o $@ $(man_xslt) - endif .asc.html: asciidoc -b html5 -o $@ $< .asc.pdf: asciidoc -b docbook -d manpage -o $*.dbk $< docbook2pdf -o doc $*.dbk MAINTAINERCLEANFILES = $(man_MANS) Doxyfile endif # Absolute path of directory 'langdata'. LANGDATA_DIR=$(shell cd $(top_srcdir) && cd .. && pwd)/langdata_lstm # Absolute path of directory 'tessdata' with traineddata files # (must be on same level as top source directory). TESSDATA_DIR=$(shell cd $(top_srcdir) && cd .. && pwd)/tessdata # Absolute path of directory 'testing' with test images and ground truth texts # (using submodule test). TESTING_DIR=$(shell cd $(top_srcdir) && pwd)/test/testing # Absolute path of directory 'testdata' with test unicharset etc. # (using submodule test). TESTDATA_DIR=$(shell cd $(top_srcdir) && pwd)/test/testdata # Suppress some memory leaks reported by LeakSanitizer. export LSAN_OPTIONS=suppressions=$(top_srcdir)/unittest/tesseract_leaksanitizer.supp unittest_CPPFLAGS = $(AM_CPPFLAGS) unittest_CPPFLAGS += -DTESSBIN_DIR="\"$(abs_top_builddir)\"" unittest_CPPFLAGS += -DLANGDATA_DIR="\"$(LANGDATA_DIR)\"" unittest_CPPFLAGS += -DTESSDATA_DIR="\"$(TESSDATA_DIR)\"" unittest_CPPFLAGS += -DTESTING_DIR="\"$(TESTING_DIR)\"" unittest_CPPFLAGS += -DTESTDATA_DIR="\"$(TESTDATA_DIR)\"" unittest_CPPFLAGS += -DPANGO_ENABLE_ENGINE if DISABLED_LEGACY_ENGINE unittest_CPPFLAGS += -DDISABLED_LEGACY_ENGINE endif # DISABLED_LEGACY_ENGINE unittest_CPPFLAGS += -DTESS_COMMON_TRAINING_API= unittest_CPPFLAGS += -DTESS_PANGO_TRAINING_API= unittest_CPPFLAGS += -DTESS_UNICHARSET_TRAINING_API= unittest_CPPFLAGS += -I$(top_srcdir)/src/arch unittest_CPPFLAGS += -I$(top_srcdir)/src/ccmain unittest_CPPFLAGS += -I$(top_srcdir)/src/ccstruct unittest_CPPFLAGS += -I$(top_srcdir)/src/ccutil unittest_CPPFLAGS += -I$(top_srcdir)/src/classify unittest_CPPFLAGS += -I$(top_srcdir)/src/cutil unittest_CPPFLAGS += -I$(top_srcdir)/src/dict unittest_CPPFLAGS += -I$(top_srcdir)/src/display unittest_CPPFLAGS += -I$(top_srcdir)/src/lstm unittest_CPPFLAGS += -I$(top_srcdir)/src/textord unittest_CPPFLAGS += -I$(top_srcdir)/unittest/base unittest_CPPFLAGS += -I$(top_srcdir)/unittest/util unittest_CPPFLAGS += $(LEPTONICA_CFLAGS) if ENABLE_TRAINING unittest_CPPFLAGS += -I$(top_srcdir)/src/training unittest_CPPFLAGS += -I$(top_srcdir)/src/training/common unittest_CPPFLAGS += -I$(top_srcdir)/src/training/pango unittest_CPPFLAGS += -I$(top_srcdir)/src/training/unicharset unittest_CPPFLAGS += $(pangocairo_CFLAGS) endif # ENABLE_TRAINING unittest_CPPFLAGS += -I$(top_srcdir)/src/viewer unittest_CPPFLAGS += -I$(top_srcdir)/src/wordrec unittest_CPPFLAGS += -I$(top_srcdir)/unittest if TENSORFLOW unittest_CPPFLAGS += -DINCLUDE_TENSORFLOW unittest_CPPFLAGS += -I/usr/include/tensorflow endif # TENSORFLOW # Build googletest: check_LTLIBRARIES = libgtest.la libgtest_main.la libgmock.la libgmock_main.la libgtest_la_SOURCES = unittest/third_party/googletest/googletest/src/gtest-all.cc libgtest_la_CPPFLAGS = -I$(top_srcdir)/unittest/third_party/googletest/googletest/include libgtest_la_CPPFLAGS += -I$(top_srcdir)/unittest/third_party/googletest/googletest libgtest_la_CPPFLAGS += -pthread libgtest_main_la_SOURCES = unittest/third_party/googletest/googletest/src/gtest_main.cc libgtest_main_la_CPPFLAGS = $(libgtest_la_CPPFLAGS) GMOCK_INCLUDES = -I$(top_srcdir)/unittest/third_party/googletest/googlemock/include \ -I$(top_srcdir)/unittest/third_party/googletest/googlemock \ -I$(top_srcdir)/unittest/third_party/googletest/googletest/include \ -I$(top_srcdir)/unittest/third_party/googletest/googletest libgmock_la_SOURCES = unittest/third_party/googletest/googlemock/src/gmock-all.cc libgmock_la_CPPFLAGS = $(GMOCK_INCLUDES) \ -pthread libgmock_main_la_SOURCES = unittest/third_party/googletest/googlemock/src/gmock_main.cc libgmock_main_la_CPPFLAGS = $(GMOCK_INCLUDES) \ -pthread # Build unittests GTEST_LIBS = libgtest.la libgtest_main.la -lpthread GMOCK_LIBS = libgmock.la libgmock_main.la TESS_LIBS = $(GTEST_LIBS) TESS_LIBS += libtesseract.la $(libarchive_LIBS) TESS_LIBS += $(TENSORFLOW_LIBS) TRAINING_LIBS = libtesseract_training.la TRAINING_LIBS += $(TESS_LIBS) unittest_CPPFLAGS += -isystem $(top_srcdir)/unittest/third_party/googletest/googletest/include unittest_CPPFLAGS += -isystem $(top_srcdir)/unittest/third_party/googletest/googlemock/include check_PROGRAMS = apiexample_test if ENABLE_TRAINING if !DISABLED_LEGACY_ENGINE check_PROGRAMS += applybox_test endif # !DISABLED_LEGACY_ENGINE check_PROGRAMS += baseapi_test check_PROGRAMS += baseapi_thread_test if !DISABLED_LEGACY_ENGINE check_PROGRAMS += bitvector_test endif # !DISABLED_LEGACY_ENGINE endif # ENABLE_TRAINING check_PROGRAMS += cleanapi_test check_PROGRAMS += colpartition_test if ENABLE_TRAINING check_PROGRAMS += commandlineflags_test check_PROGRAMS += dawg_test endif # ENABLE_TRAINING check_PROGRAMS += denorm_test if !DISABLED_LEGACY_ENGINE check_PROGRAMS += equationdetect_test endif # !DISABLED_LEGACY_ENGINE check_PROGRAMS += fileio_test check_PROGRAMS += heap_test check_PROGRAMS += imagedata_test if !DISABLED_LEGACY_ENGINE check_PROGRAMS += indexmapbidi_test check_PROGRAMS += intfeaturemap_test endif # !DISABLED_LEGACY_ENGINE check_PROGRAMS += intsimdmatrix_test check_PROGRAMS += lang_model_test check_PROGRAMS += layout_test check_PROGRAMS += ligature_table_test check_PROGRAMS += linlsq_test check_PROGRAMS += list_test if ENABLE_TRAINING check_PROGRAMS += lstm_recode_test check_PROGRAMS += lstm_squashed_test check_PROGRAMS += lstm_test check_PROGRAMS += lstmtrainer_test endif # ENABLE_TRAINING check_PROGRAMS += loadlang_test if !DISABLED_LEGACY_ENGINE check_PROGRAMS += mastertrainer_test endif # !DISABLED_LEGACY_ENGINE check_PROGRAMS += matrix_test check_PROGRAMS += networkio_test if ENABLE_TRAINING check_PROGRAMS += normstrngs_test endif # ENABLE_TRAINING check_PROGRAMS += nthitem_test if !DISABLED_LEGACY_ENGINE check_PROGRAMS += osd_test endif # !DISABLED_LEGACY_ENGINE check_PROGRAMS += pagesegmode_test if ENABLE_TRAINING check_PROGRAMS += pango_font_info_test endif # ENABLE_TRAINING check_PROGRAMS += paragraphs_test if !DISABLED_LEGACY_ENGINE check_PROGRAMS += params_model_test endif # !DISABLED_LEGACY_ENGINE check_PROGRAMS += progress_test check_PROGRAMS += qrsequence_test check_PROGRAMS += recodebeam_test check_PROGRAMS += rect_test check_PROGRAMS += resultiterator_test check_PROGRAMS += scanutils_test if !DISABLED_LEGACY_ENGINE check_PROGRAMS += shapetable_test endif # !DISABLED_LEGACY_ENGINE check_PROGRAMS += stats_test check_PROGRAMS += stridemap_test check_PROGRAMS += stringrenderer_test check_PROGRAMS += tablefind_test check_PROGRAMS += tablerecog_test check_PROGRAMS += tabvector_test check_PROGRAMS += tatweel_test if !DISABLED_LEGACY_ENGINE check_PROGRAMS += textlineprojection_test endif # !DISABLED_LEGACY_ENGINE check_PROGRAMS += tfile_test if ENABLE_TRAINING check_PROGRAMS += unichar_test check_PROGRAMS += unicharcompress_test check_PROGRAMS += unicharset_test check_PROGRAMS += validate_grapheme_test check_PROGRAMS += validate_indic_test check_PROGRAMS += validate_khmer_test check_PROGRAMS += validate_myanmar_test check_PROGRAMS += validator_test endif # ENABLE_TRAINING check_PROGRAMS: libtesseract.la libtesseract_training.la TESTS = $(check_PROGRAMS) # List of source files needed to build the executable: apiexample_test_SOURCES = unittest/apiexample_test.cc apiexample_test_CPPFLAGS = $(unittest_CPPFLAGS) apiexample_test_LDFLAGS = $(LEPTONICA_LIBS) apiexample_test_LDADD = $(TESS_LIBS) $(LEPTONICA_LIBS) if !DISABLED_LEGACY_ENGINE applybox_test_SOURCES = unittest/applybox_test.cc applybox_test_CPPFLAGS = $(unittest_CPPFLAGS) applybox_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS) endif # !DISABLED_LEGACY_ENGINE baseapi_test_SOURCES = unittest/baseapi_test.cc baseapi_test_CPPFLAGS = $(unittest_CPPFLAGS) baseapi_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS) baseapi_thread_test_SOURCES = unittest/baseapi_thread_test.cc baseapi_thread_test_CPPFLAGS = $(unittest_CPPFLAGS) baseapi_thread_test_LDADD = $(TESS_LIBS) $(LEPTONICA_LIBS) if !DISABLED_LEGACY_ENGINE bitvector_test_SOURCES = unittest/bitvector_test.cc bitvector_test_CPPFLAGS = $(unittest_CPPFLAGS) bitvector_test_LDADD = $(TRAINING_LIBS) endif # !DISABLED_LEGACY_ENGINE cleanapi_test_SOURCES = unittest/cleanapi_test.cc cleanapi_test_CPPFLAGS = $(unittest_CPPFLAGS) cleanapi_test_LDADD = $(TESS_LIBS) colpartition_test_SOURCES = unittest/colpartition_test.cc colpartition_test_CPPFLAGS = $(unittest_CPPFLAGS) colpartition_test_LDADD = $(TESS_LIBS) commandlineflags_test_SOURCES = unittest/commandlineflags_test.cc commandlineflags_test_CPPFLAGS = $(unittest_CPPFLAGS) commandlineflags_test_LDADD = $(TRAINING_LIBS) $(ICU_UC_LIBS) dawg_test_SOURCES = unittest/dawg_test.cc dawg_test_CPPFLAGS = $(unittest_CPPFLAGS) dawg_test_LDADD = $(TRAINING_LIBS) denorm_test_SOURCES = unittest/denorm_test.cc denorm_test_CPPFLAGS = $(unittest_CPPFLAGS) denorm_test_LDADD = $(TESS_LIBS) if !DISABLED_LEGACY_ENGINE equationdetect_test_SOURCES = unittest/equationdetect_test.cc equationdetect_test_CPPFLAGS = $(unittest_CPPFLAGS) equationdetect_test_LDADD = $(TESS_LIBS) $(LEPTONICA_LIBS) endif # !DISABLED_LEGACY_ENGINE fileio_test_SOURCES = unittest/fileio_test.cc fileio_test_CPPFLAGS = $(unittest_CPPFLAGS) fileio_test_LDADD = $(TRAINING_LIBS) heap_test_SOURCES = unittest/heap_test.cc heap_test_CPPFLAGS = $(unittest_CPPFLAGS) heap_test_LDADD = $(TESS_LIBS) imagedata_test_SOURCES = unittest/imagedata_test.cc imagedata_test_CPPFLAGS = $(unittest_CPPFLAGS) imagedata_test_LDADD = $(TRAINING_LIBS) if !DISABLED_LEGACY_ENGINE indexmapbidi_test_SOURCES = unittest/indexmapbidi_test.cc indexmapbidi_test_CPPFLAGS = $(unittest_CPPFLAGS) indexmapbidi_test_LDADD = $(TRAINING_LIBS) endif # !DISABLED_LEGACY_ENGINE if !DISABLED_LEGACY_ENGINE intfeaturemap_test_SOURCES = unittest/intfeaturemap_test.cc intfeaturemap_test_CPPFLAGS = $(unittest_CPPFLAGS) intfeaturemap_test_LDADD = $(TRAINING_LIBS) endif # !DISABLED_LEGACY_ENGINE intsimdmatrix_test_SOURCES = unittest/intsimdmatrix_test.cc intsimdmatrix_test_CPPFLAGS = $(unittest_CPPFLAGS) if HAVE_AVX2 intsimdmatrix_test_CPPFLAGS += -DHAVE_AVX2 endif if HAVE_SSE4_1 intsimdmatrix_test_CPPFLAGS += -DHAVE_SSE4_1 endif intsimdmatrix_test_LDADD = $(TESS_LIBS) lang_model_test_SOURCES = unittest/lang_model_test.cc lang_model_test_CPPFLAGS = $(unittest_CPPFLAGS) lang_model_test_LDADD = $(TRAINING_LIBS) $(ICU_I18N_LIBS) $(ICU_UC_LIBS) layout_test_SOURCES = unittest/layout_test.cc layout_test_CPPFLAGS = $(unittest_CPPFLAGS) layout_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS) ligature_table_test_SOURCES = unittest/ligature_table_test.cc ligature_table_test_CPPFLAGS = $(unittest_CPPFLAGS) ligature_table_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS) ligature_table_test_LDADD += $(ICU_I18N_LIBS) $(ICU_UC_LIBS) ligature_table_test_LDADD += $(pangocairo_LIBS) $(pangoft2_LIBS) ligature_table_test_LDADD += $(cairo_LIBS) $(pango_LIBS) linlsq_test_SOURCES = unittest/linlsq_test.cc linlsq_test_CPPFLAGS = $(unittest_CPPFLAGS) linlsq_test_LDADD = $(TESS_LIBS) list_test_SOURCES = unittest/list_test.cc list_test_CPPFLAGS = $(unittest_CPPFLAGS) list_test_LDADD = $(TESS_LIBS) loadlang_test_SOURCES = unittest/loadlang_test.cc loadlang_test_CPPFLAGS = $(unittest_CPPFLAGS) loadlang_test_LDADD = $(TESS_LIBS) $(LEPTONICA_LIBS) lstm_recode_test_SOURCES = unittest/lstm_recode_test.cc lstm_recode_test_CPPFLAGS = $(unittest_CPPFLAGS) lstm_recode_test_LDADD = $(TRAINING_LIBS) lstm_squashed_test_SOURCES = unittest/lstm_squashed_test.cc lstm_squashed_test_CPPFLAGS = $(unittest_CPPFLAGS) lstm_squashed_test_LDADD = $(TRAINING_LIBS) lstm_test_SOURCES = unittest/lstm_test.cc lstm_test_CPPFLAGS = $(unittest_CPPFLAGS) lstm_test_LDADD = $(TRAINING_LIBS) lstmtrainer_test_SOURCES = unittest/lstmtrainer_test.cc lstmtrainer_test_CPPFLAGS = $(unittest_CPPFLAGS) lstmtrainer_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS) if !DISABLED_LEGACY_ENGINE mastertrainer_test_SOURCES = unittest/mastertrainer_test.cc mastertrainer_test_CPPFLAGS = $(unittest_CPPFLAGS) mastertrainer_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS) endif # !DISABLED_LEGACY_ENGINE matrix_test_SOURCES = unittest/matrix_test.cc matrix_test_CPPFLAGS = $(unittest_CPPFLAGS) matrix_test_LDADD = $(TESS_LIBS) networkio_test_SOURCES = unittest/networkio_test.cc networkio_test_CPPFLAGS = $(unittest_CPPFLAGS) networkio_test_LDADD = $(TESS_LIBS) normstrngs_test_SOURCES = unittest/normstrngs_test.cc if TENSORFLOW normstrngs_test_SOURCES += unittest/third_party/utf/rune.c normstrngs_test_SOURCES += unittest/util/utf8/unilib.cc endif # TENSORFLOW normstrngs_test_CPPFLAGS = $(unittest_CPPFLAGS) normstrngs_test_LDADD = $(TRAINING_LIBS) $(ICU_I18N_LIBS) $(ICU_UC_LIBS) nthitem_test_SOURCES = unittest/nthitem_test.cc nthitem_test_CPPFLAGS = $(unittest_CPPFLAGS) nthitem_test_LDADD = $(TESS_LIBS) if !DISABLED_LEGACY_ENGINE osd_test_SOURCES = unittest/osd_test.cc osd_test_CPPFLAGS = $(unittest_CPPFLAGS) osd_test_LDADD = $(TESS_LIBS) $(LEPTONICA_LIBS) endif # !DISABLED_LEGACY_ENGINE pagesegmode_test_SOURCES = unittest/pagesegmode_test.cc pagesegmode_test_CPPFLAGS = $(unittest_CPPFLAGS) pagesegmode_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS) pango_font_info_test_SOURCES = unittest/pango_font_info_test.cc if TENSORFLOW pango_font_info_test_SOURCES += unittest/third_party/utf/rune.c pango_font_info_test_SOURCES += unittest/util/utf8/unicodetext.cc pango_font_info_test_SOURCES += unittest/util/utf8/unilib.cc endif # TENSORFLOW pango_font_info_test_CPPFLAGS = $(unittest_CPPFLAGS) pango_font_info_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS) pango_font_info_test_LDADD += $(ICU_I18N_LIBS) pango_font_info_test_LDADD += $(pangocairo_LIBS) pango_font_info_test_LDADD += $(pangoft2_LIBS) paragraphs_test_SOURCES = unittest/paragraphs_test.cc paragraphs_test_CPPFLAGS = $(unittest_CPPFLAGS) paragraphs_test_LDADD = $(TESS_LIBS) if !DISABLED_LEGACY_ENGINE params_model_test_SOURCES = unittest/params_model_test.cc params_model_test_CPPFLAGS = $(unittest_CPPFLAGS) params_model_test_LDADD = $(TRAINING_LIBS) endif # !DISABLED_LEGACY_ENGINE progress_test_SOURCES = unittest/progress_test.cc progress_test_CPPFLAGS = $(unittest_CPPFLAGS) progress_test_LDFLAGS = $(LEPTONICA_LIBS) progress_test_LDADD = $(GTEST_LIBS) $(GMOCK_LIBS) $(TESS_LIBS) $(LEPTONICA_LIBS) qrsequence_test_SOURCES = unittest/qrsequence_test.cc qrsequence_test_CPPFLAGS = $(unittest_CPPFLAGS) qrsequence_test_LDADD = $(TESS_LIBS) recodebeam_test_SOURCES = unittest/recodebeam_test.cc recodebeam_test_CPPFLAGS = $(unittest_CPPFLAGS) recodebeam_test_LDADD = $(TRAINING_LIBS) $(ICU_I18N_LIBS) $(ICU_UC_LIBS) rect_test_SOURCES = unittest/rect_test.cc rect_test_CPPFLAGS = $(unittest_CPPFLAGS) rect_test_LDADD = $(TESS_LIBS) resultiterator_test_SOURCES = unittest/resultiterator_test.cc resultiterator_test_CPPFLAGS = $(unittest_CPPFLAGS) resultiterator_test_LDADD = $(TRAINING_LIBS) resultiterator_test_LDADD += $(LEPTONICA_LIBS) $(ICU_I18N_LIBS) $(ICU_UC_LIBS) scanutils_test_SOURCES = unittest/scanutils_test.cc scanutils_test_CPPFLAGS = $(unittest_CPPFLAGS) scanutils_test_LDADD = $(TRAINING_LIBS) if !DISABLED_LEGACY_ENGINE shapetable_test_SOURCES = unittest/shapetable_test.cc shapetable_test_CPPFLAGS = $(unittest_CPPFLAGS) shapetable_test_LDADD = $(TRAINING_LIBS) endif # !DISABLED_LEGACY_ENGINE stats_test_SOURCES = unittest/stats_test.cc stats_test_CPPFLAGS = $(unittest_CPPFLAGS) stats_test_LDADD = $(TESS_LIBS) stridemap_test_SOURCES = unittest/stridemap_test.cc stridemap_test_CPPFLAGS = $(unittest_CPPFLAGS) stridemap_test_LDADD = $(TESS_LIBS) stringrenderer_test_SOURCES = unittest/stringrenderer_test.cc stringrenderer_test_CPPFLAGS = $(unittest_CPPFLAGS) stringrenderer_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS) stringrenderer_test_LDADD += $(ICU_I18N_LIBS) $(ICU_UC_LIBS) stringrenderer_test_LDADD += $(pangocairo_LIBS) $(pangoft2_LIBS) stringrenderer_test_LDADD += $(cairo_LIBS) $(pango_LIBS) tablefind_test_SOURCES = unittest/tablefind_test.cc tablefind_test_CPPFLAGS = $(unittest_CPPFLAGS) tablefind_test_LDADD = $(TESS_LIBS) tablerecog_test_SOURCES = unittest/tablerecog_test.cc tablerecog_test_CPPFLAGS = $(unittest_CPPFLAGS) tablerecog_test_LDADD = $(TESS_LIBS) tabvector_test_SOURCES = unittest/tabvector_test.cc tabvector_test_CPPFLAGS = $(unittest_CPPFLAGS) tabvector_test_LDADD = $(TESS_LIBS) tatweel_test_SOURCES = unittest/tatweel_test.cc tatweel_test_SOURCES += unittest/third_party/utf/rune.c tatweel_test_SOURCES += unittest/util/utf8/unicodetext.cc tatweel_test_SOURCES += unittest/util/utf8/unilib.cc tatweel_test_CPPFLAGS = $(unittest_CPPFLAGS) tatweel_test_LDADD = $(TRAINING_LIBS) textlineprojection_test_SOURCES = unittest/textlineprojection_test.cc textlineprojection_test_CPPFLAGS = $(unittest_CPPFLAGS) textlineprojection_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS) tfile_test_SOURCES = unittest/tfile_test.cc tfile_test_CPPFLAGS = $(unittest_CPPFLAGS) tfile_test_LDADD = $(TESS_LIBS) unichar_test_SOURCES = unittest/unichar_test.cc unichar_test_CPPFLAGS = $(unittest_CPPFLAGS) unichar_test_LDADD = $(TRAINING_LIBS) $(ICU_UC_LIBS) unicharcompress_test_SOURCES = unittest/unicharcompress_test.cc unicharcompress_test_CPPFLAGS = $(unittest_CPPFLAGS) unicharcompress_test_LDADD = $(TRAINING_LIBS) $(ICU_UC_LIBS) unicharset_test_SOURCES = unittest/unicharset_test.cc unicharset_test_CPPFLAGS = $(unittest_CPPFLAGS) unicharset_test_LDADD = $(TRAINING_LIBS) $(ICU_UC_LIBS) validate_grapheme_test_SOURCES = unittest/validate_grapheme_test.cc validate_grapheme_test_CPPFLAGS = $(unittest_CPPFLAGS) validate_grapheme_test_LDADD = $(TRAINING_LIBS) $(ICU_I18N_LIBS) $(ICU_UC_LIBS) validate_indic_test_SOURCES = unittest/validate_indic_test.cc validate_indic_test_CPPFLAGS = $(unittest_CPPFLAGS) validate_indic_test_LDADD = $(TRAINING_LIBS) $(ICU_I18N_LIBS) $(ICU_UC_LIBS) validate_khmer_test_SOURCES = unittest/validate_khmer_test.cc validate_khmer_test_CPPFLAGS = $(unittest_CPPFLAGS) validate_khmer_test_LDADD = $(TRAINING_LIBS) $(ICU_I18N_LIBS) $(ICU_UC_LIBS) validate_myanmar_test_SOURCES = unittest/validate_myanmar_test.cc validate_myanmar_test_CPPFLAGS = $(unittest_CPPFLAGS) validate_myanmar_test_LDADD = $(TRAINING_LIBS) $(ICU_I18N_LIBS) $(ICU_UC_LIBS) validator_test_SOURCES = unittest/validator_test.cc validator_test_CPPFLAGS = $(unittest_CPPFLAGS) validator_test_LDADD = $(TRAINING_LIBS) $(ICU_UC_LIBS) # for windows if T_WIN apiexample_test_LDADD += -lws2_32 intsimdmatrix_test_LDADD += -lws2_32 matrix_test_LDADD += -lws2_32 if !DISABLED_LEGACY_ENGINE osd_test_LDADD += -lws2_32 endif # !DISABLED_LEGACY_ENGINE loadlang_test_LDADD += -lws2_32 endif EXTRA_apiexample_test_DEPENDENCIES = $(abs_top_builddir)/test/testing/phototest.tif EXTRA_apiexample_test_DEPENDENCIES += $(abs_top_builddir)/test/testing/phototest.txt $(abs_top_builddir)/test/testing/phototest.tif: mkdir -p $(top_builddir)/test/testing ln -s $(TESTING_DIR)/phototest.tif $(top_builddir)/test/testing/phototest.tif $(abs_top_builddir)/test/testing/phototest.txt: mkdir -p $(top_builddir)/test/testing ln -s $(TESTING_DIR)/phototest.txt $(top_builddir)/test/testing/phototest.txt # Some tests require a local tmp directory. $(check_PROGRAMS): | tmp tmp: mkdir -p tmp # Some tests require a well defined set of the following font files. fonts = ae_Arab.ttf fonts += Arial_Bold_Italic.ttf fonts += DejaVuSans-ExtraLight.ttf fonts += Lohit-Hindi.ttf fonts += Times_New_Roman.ttf fonts += UnBatang.ttf fonts += Verdana.ttf # These tests depend on installed model files and fonts: # # apiexample_test baseapi_test lang_model_test layout_test # ligature_table_test loadlang_test lstm_recode_test lstm_squashed_test # lstm_test lstmtrainer_test mastertrainer_test osd_test # pagesegmode_test pango_font_info_test progress_test # recodebeam_test resultiterator_test stringrenderer_test # textlineprojection_test unicharcompress_test # # Instead of fine-tuned dependencies the following lines # simply require those dependencies for all tests. # That can be improved if necessary. $(check_PROGRAMS): | $(LANGDATA_DIR) $(check_PROGRAMS): | $(TESSDATA_DIR) $(check_PROGRAMS): | $(TESSDATA_BEST_DIR) $(check_PROGRAMS): | $(TESSDATA_FAST_DIR) $(check_PROGRAMS): | $(fonts:%=$(TESTING_DIR)/%) $(LANGDATA_DIR) $(TESSDATA_DIR) $(TESSDATA_BEST_DIR) $(TESSDATA_FAST_DIR): @echo "Some unit tests require $@." @echo "It can be installed manually by running this command:" @echo " git clone https://github.com/tesseract-ocr/$$(basename $@).git $@" @exit 1 $(TESTING_DIR)/Arial_Bold_Italic.ttf: curl -sSL -o Arial.exe https://sourceforge.net/projects/corefonts/files/the%20fonts/final/arial32.exe/download cabextract -F Arialbi.TTF -q Arial.exe rm Arial.exe mv Arialbi.TTF $@ $(TESTING_DIR)/DejaVuSans-ExtraLight.ttf: curl -sSL http://sourceforge.net/projects/dejavu/files/dejavu/2.37/dejavu-fonts-ttf-2.37.tar.bz2 | \ tar -xjO dejavu-fonts-ttf-2.37/ttf/DejaVuSans-ExtraLight.ttf >$@ $(TESTING_DIR)/Lohit-Hindi.ttf: curl -sSL https://releases.pagure.org/lohit/lohit-hindi-ttf-2.4.3.tar.gz | \ tar -xzO lohit-hindi-ttf-2.4.3/Lohit-Hindi.ttf >$@ $(TESTING_DIR)/Times_New_Roman.ttf: curl -sSL -o Times.exe https://sourceforge.net/projects/corefonts/files/the%20fonts/final/times32.exe/download cabextract -F Times.TTF -q Times.exe rm Times.exe mv Times.TTF $@ $(TESTING_DIR)/UnBatang.ttf: curl -sSL -o $@ https://salsa.debian.org/fonts-team/fonts-unfonts-core/-/raw/master/UnBatang.ttf $(TESTING_DIR)/Verdana.ttf: curl -sSL -o Verdana.exe https://sourceforge.net/projects/corefonts/files/the%20fonts/final/verdan32.exe/download cabextract -F Verdana.TTF -q Verdana.exe rm Verdana.exe mv Verdana.TTF $@ $(TESTING_DIR)/ae_Arab.ttf: curl -sSL -o $@ https://salsa.debian.org/fonts-team/fonts-arabeyes/-/raw/master/ae_Arab.ttf
2301_81045437/tesseract
Makefile.am
Makefile
apache-2.0
63,142
#!/bin/sh # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This is a simple script which is meant to help developers # better deal with the GNU autotools, specifically: # # aclocal # libtoolize # autoconf # autoheader # automake # # The whole thing is quite complex... # # The idea is to run this collection of tools on a single platform, # typically the main development platform, running a recent version of # autoconf. In theory, if we had these tools on each platform where we # ever expected to port the software, we would never need to checkin # more than a few autotools configuration files. However, the whole # idea is to generate a configure script and associated files in a way # that is portable across platforms, so we *have* to check in a whole # bunch of files generated by all these tools. # The real source files are: # # acinclude.m4 (used by aclocal) # configure.ac (main autoconf file) # Makefile.am, */Makefile.am (automake config files) # # All the rest is auto-generated. if [ "$1" = "clean" ]; then echo "Cleaning..." rm configure aclocal.m4 rm m4/l* rm config/* rmdir config find . -iname "Makefile.in" -type f -exec rm '{}' + fi bail_out() { echo echo " Something went wrong, bailing out!" echo exit 1 } # Prevent any errors that might result from failing to properly invoke # `libtoolize` or `glibtoolize,` whichever is present on your system, # from occurring by testing for its existence and capturing the absolute path to # its location for caching purposes prior to using it later on in 'Step 2:' if command -v libtoolize >/dev/null 2>&1; then LIBTOOLIZE="$(command -v libtoolize)" elif command -v glibtoolize >/dev/null 2>&1; then LIBTOOLIZE="$(command -v glibtoolize)" else echo "Unable to find a valid copy of libtoolize or glibtoolize in your PATH!" bail_out fi # --- Step 1: Generate aclocal.m4 from: # . acinclude.m4 # . config/*.m4 (these files are referenced in acinclude.m4) mkdir -p config echo "Running aclocal" aclocal -I config || bail_out # --- Step 2: echo "Running $LIBTOOLIZE" $LIBTOOLIZE -f -c || bail_out $LIBTOOLIZE --automake || bail_out # Run aclocal a 2nd time because glibtoolize created additional m4 files. echo "Running aclocal" aclocal -I config || bail_out # --- Step 3: Generate configure and include/miaconfig.h from: # . configure.ac # echo "Running autoconf" autoconf || bail_out if grep -q PKG_CHECK_MODULES configure; then # The generated configure is invalid because pkg-config is unavailable. rm configure echo "Missing pkg-config. Check the build requirements." bail_out fi # --- Step 4: Generate config.h.in from: # . configure.ac (look for AM_CONFIG_HEADER tag or AC_CONFIG_HEADER tag) echo "Running autoheader" autoheader -f || bail_out # --- Step 5: Generate Makefile.in, src/Makefile.in, and a whole bunch of # files in config (config.guess, config.sub, depcomp, # install-sh, missing, mkinstalldirs) plus COPYING and # INSTALL from: # . Makefile.am # . src/Makefile.am # # Using --add-missing --copy makes sure that, if these files are missing, # they are copied from the system so they can be used in a distribution. echo "Running automake --add-missing --copy" automake --add-missing --copy --warnings=all || bail_out echo "" echo "All done." echo "To build the software now, do something like:" echo "" echo "$ ./configure [--enable-debug] [...other options]"
2301_81045437/tesseract
autogen.sh
Shell
apache-2.0
4,021
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ # # macros and functions # ################################################################################ ######################################## # FUNCTION project_group ######################################## function(project_group target name) set_target_properties(${target} PROPERTIES FOLDER ${name}) endfunction(project_group) ################################################################################
2301_81045437/tesseract
cmake/BuildFunctions.cmake
CMake
apache-2.0
1,041
# Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by # applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the specific language # governing permissions and limitations under the License. # ############################################################################## # # macros and functions # # ############################################################################## # ############################################################################## # FUNCTION check_leptonica_tiff_support # ############################################################################## function(check_leptonica_tiff_support) # check if leptonica was build with tiff support set result to # LEPT_TIFF_RESULT set(TIFF_TEST "#include \"leptonica/allheaders.h\"\n" "int main() {\n" " l_uint8 *data = NULL;\n" " size_t size = 0;\n" " PIX* pix = pixCreate(3, 3, 4);\n" " l_int32 ret_val = pixWriteMemTiff(&data, &size, pix, IFF_TIFF_G3);\n" " pixDestroy(&pix);\n" " lept_free(data);\n" " return ret_val;}\n") if(${CMAKE_VERSION} VERSION_LESS "3.25") message(STATUS "Testing TIFF support in Leptonica is available with CMake >= 3.25 (you have ${CMAKE_VERSION}))") else() set(CMAKE_TRY_COMPILE_CONFIGURATION ${CMAKE_BUILD_TYPE}) try_run( LEPT_TIFF_RESULT LEPT_TIFF_COMPILE_SUCCESS SOURCE_FROM_CONTENT tiff_test.cpp "${TIFF_TEST}" CMAKE_FLAGS "-DINCLUDE_DIRECTORIES=${Leptonica_INCLUDE_DIRS}" LINK_LIBRARIES ${Leptonica_LIBRARIES} COMPILE_OUTPUT_VARIABLE COMPILE_OUTPUT) if(NOT LEPT_TIFF_COMPILE_SUCCESS) message(STATUS "COMPILE_OUTPUT: ${COMPILE_OUTPUT}") message(STATUS "Leptonica_INCLUDE_DIRS: ${Leptonica_INCLUDE_DIRS}") message(STATUS "Leptonica_LIBRARIES: ${Leptonica_LIBRARIES}") message(STATUS "LEPT_TIFF_RESULT: ${LEPT_TIFF_RESULT}") message(STATUS "LEPT_TIFF_COMPILE: ${LEPT_TIFF_COMPILE}") message(WARNING "Failed to compile test") endif() endif() endfunction(check_leptonica_tiff_support) # ##############################################################################
2301_81045437/tesseract
cmake/CheckFunctions.cmake
CMake
apache-2.0
2,447
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ # # configure # ################################################################################ ######################################## # FUNCTION check_includes ######################################## function(check_includes files) foreach(F ${${files}}) set(name ${F}) string(REPLACE "-" "_" name ${name}) string(REPLACE "." "_" name ${name}) string(REPLACE "/" "_" name ${name}) string(TOUPPER ${name} name) check_include_files(${F} HAVE_${name}) file(APPEND ${AUTOCONFIG_SRC} "/* Define to 1 if you have the <${F}> header file. */\n") file(APPEND ${AUTOCONFIG_SRC} "#cmakedefine HAVE_${name} 1\n") file(APPEND ${AUTOCONFIG_SRC} "\n") endforeach() endfunction(check_includes) ######################################## # FUNCTION check_functions ######################################## function(check_functions functions) foreach(F ${${functions}}) set(name ${F}) string(TOUPPER ${name} name) check_function_exists(${F} HAVE_${name}) file(APPEND ${AUTOCONFIG_SRC} "/* Define to 1 if you have the `${F}' function. */\n") file(APPEND ${AUTOCONFIG_SRC} "#cmakedefine HAVE_${name} 1\n") file(APPEND ${AUTOCONFIG_SRC} "\n") endforeach() endfunction(check_functions) ######################################## # FUNCTION check_types ######################################## function(check_types types) foreach(T ${${types}}) set(name ${T}) string(REPLACE " " "_" name ${name}) string(REPLACE "-" "_" name ${name}) string(REPLACE "." "_" name ${name}) string(REPLACE "/" "_" name ${name}) string(TOUPPER ${name} name) check_type_size(${T} HAVE_${name}) file(APPEND ${AUTOCONFIG_SRC} "/* Define to 1 if the system has the type `${T}'. */\n") file(APPEND ${AUTOCONFIG_SRC} "#cmakedefine HAVE_${name} 1\n") file(APPEND ${AUTOCONFIG_SRC} "\n") endforeach() endfunction(check_types) ######################################## file(WRITE ${AUTOCONFIG_SRC}) include(CheckCSourceCompiles) include(CheckCSourceRuns) include(CheckCXXSourceCompiles) include(CheckCXXSourceRuns) include(CheckFunctionExists) include(CheckIncludeFiles) include(CheckLibraryExists) include(CheckPrototypeDefinition) include(CheckStructHasMember) include(CheckSymbolExists) include(CheckTypeSize) include(TestBigEndian) set(include_files_list dlfcn.h inttypes.h memory.h stdint.h stdlib.h string.h sys/stat.h sys/types.h unistd.h cairo/cairo-version.h pango-1.0/pango/pango-features.h unicode/uchar.h ) # check_includes(include_files_list) set(types_list "long long int" wchar_t ) # check_types(types_list) list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE) list(APPEND CMAKE_REQUIRED_LIBRARIES -lm) set(functions_list feenableexcept ) check_functions(functions_list) file(APPEND ${AUTOCONFIG_SRC} " /* Version number */ #cmakedefine PACKAGE_VERSION \"${PACKAGE_VERSION}\" #cmakedefine GRAPHICS_DISABLED ${GRAPHICS_DISABLED} #cmakedefine FAST_FLOAT ${FAST_FLOAT} #cmakedefine DISABLED_LEGACY_ENGINE ${DISABLED_LEGACY_ENGINE} #cmakedefine HAVE_TIFFIO_H ${HAVE_TIFFIO_H} #cmakedefine HAVE_NEON ${HAVE_NEON} #cmakedefine HAVE_LIBARCHIVE ${HAVE_LIBARCHIVE} #cmakedefine HAVE_LIBCURL ${HAVE_LIBCURL} ") if(TESSDATA_PREFIX) file(APPEND ${AUTOCONFIG_SRC} " #cmakedefine TESSDATA_PREFIX \"${TESSDATA_PREFIX}\" ") endif() ######################################## ################################################################################
2301_81045437/tesseract
cmake/Configure.cmake
CMake
apache-2.0
4,216
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #include(SourceGroups) set(SSRC ${CMAKE_SOURCE_DIR}) set(BSRC ${CMAKE_BINARY_DIR}) set(_CPP ".*\\.cpp") set(CPP "${_CPP}$") set(_H ".*\\.h") set(H "${_H}$") set(H_CPP "(${H}|${CPP})") source_group("Resource files" ".*\\.(rc|ico)") source_group("api" "${SSRC}/api/${H_CPP}") source_group("arch" "${SSRC}/arch/${H_CPP}") source_group("ccmain" "${SSRC}/ccmain/${H_CPP}") source_group("ccstruct" "${SSRC}/ccstruct/${H_CPP}") source_group("ccutil" "${SSRC}/ccutil/${H_CPP}") source_group("classify" "${SSRC}/classify/${H_CPP}") source_group("cutil" "${SSRC}/cutil/${H_CPP}") source_group("dict" "${SSRC}/dict/${H_CPP}") source_group("lstm" "${SSRC}/lstm/${H_CPP}") source_group("textord" "${SSRC}/textord/${H_CPP}") source_group("viewer" "${SSRC}/viewer/${H_CPP}") source_group("wordrec" "${SSRC}/wordrec/${H_CPP}")
2301_81045437/tesseract
cmake/SourceGroups.cmake
CMake
apache-2.0
1,429
# =================================================================================== # The Tesseract CMake configuration file # # ** File generated automatically, do not modify ** # # Usage from an external project: # In your CMakeLists.txt, add these lines: # # find_package(Tesseract REQUIRED) # target_link_libraries(MY_TARGET_NAME Tesseract::libtesseract) # # This file will define the following variables: # - Tesseract_LIBRARIES : The list of all imported targets. # - Tesseract_INCLUDE_DIRS : The Tesseract include directories. # - Tesseract_LIBRARY_DIRS : The Tesseract library directories. # - Tesseract_VERSION : The version of this Tesseract build: "@VERSION_PLAIN@" # - Tesseract_VERSION_MAJOR : Major version part of Tesseract_VERSION: "@VERSION_MAJOR@" # - Tesseract_VERSION_MINOR : Minor version part of Tesseract_VERSION: "@VERSION_MINOR@" # - Tesseract_VERSION_PATCH : Patch version part of Tesseract_VERSION: "@VERSION_PATCH@" # # =================================================================================== include(CMakeFindDependencyMacro) find_dependency(Leptonica) include(${CMAKE_CURRENT_LIST_DIR}/TesseractTargets.cmake) @PACKAGE_INIT@ SET(Tesseract_VERSION @VERSION_PLAIN@) SET(Tesseract_VERSION_MAJOR @VERSION_MAJOR@) SET(Tesseract_VERSION_MINOR @VERSION_MINOR@) SET(Tesseract_VERSION_PATCH @VERSION_PATCH@) set_and_check(Tesseract_INCLUDE_DIRS "@PACKAGE_INCLUDE_DIR@") set_and_check(Tesseract_LIBRARY_DIRS "@PACKAGE_LIBRARY_DIRS@") set(Tesseract_LIBRARIES @tesseract_OUTPUT_NAME@) check_required_components(Tesseract)
2301_81045437/tesseract
cmake/templates/TesseractConfig.cmake.in
CMake
apache-2.0
1,710
# https://gitlab.kitware.com/cmake/community/wikis/FAQ#can-i-do-make-uninstall-with-cmake if(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") message(FATAL_ERROR "Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt") endif(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") file(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files) string(REGEX REPLACE "\n" ";" files "${files}") foreach(file ${files}) message(STATUS "Uninstalling $ENV{DESTDIR}${file}") if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") exec_program( "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\"" OUTPUT_VARIABLE rm_out RETURN_VALUE rm_retval ) if(NOT "${rm_retval}" STREQUAL 0) message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}") endif(NOT "${rm_retval}" STREQUAL 0) else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") message(STATUS "File $ENV{DESTDIR}${file} does not exist.") endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") endforeach(file)
2301_81045437/tesseract
cmake/templates/cmake_uninstall.cmake.in
CMake
apache-2.0
1,093
# -*-Shell-script-*- # # Copyright (c) Luc Vincent # ---------------------------------------- # Initialization # ---------------------------------------- AC_PREREQ([2.69]) AC_INIT([tesseract], [m4_esyscmd_s([test -d .git && git describe --abbrev=4 2>/dev/null || cat VERSION])], [https://github.com/tesseract-ocr/tesseract/issues],, [https://github.com/tesseract-ocr/tesseract/]) # Store command like options for CXXFLAGS OLD_CXXFLAGS=$CXXFLAGS AC_PROG_CXX([g++ clang++]) # reset compiler flags to initial flags AC_LANG([C++]) AC_LANG_COMPILER_REQUIRE CXXFLAGS=${CXXFLAGS:-""} AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_AUX_DIR([config]) AC_CONFIG_SRCDIR([src/tesseract.cpp]) AC_PREFIX_DEFAULT([/usr/local]) # Automake configuration. Do not require README file (we use README.md). AM_INIT_AUTOMAKE([foreign subdir-objects nostdinc]) # Define date of package, etc. Could be useful in auto-generated # documentation. PACKAGE_YEAR=2024 PACKAGE_DATE="06/11" abs_top_srcdir=`AS_DIRNAME([$0])` AC_DEFINE_UNQUOTED([PACKAGE_NAME], ["${PACKAGE_NAME}"], [Name of package]) AC_DEFINE_UNQUOTED([PACKAGE_VERSION], ["${PACKAGE_VERSION}"], [Version number]) AC_DEFINE_UNQUOTED([PACKAGE_YEAR], ["$PACKAGE_YEAR"], [Official year for this release]) AC_DEFINE_UNQUOTED([PACKAGE_DATE], ["$PACKAGE_DATE"], [Official date of release]) AC_SUBST([PACKAGE_NAME]) AC_SUBST([PACKAGE_VERSION]) AC_SUBST([PACKAGE_YEAR]) AC_SUBST([PACKAGE_DATE]) GENERIC_LIBRARY_NAME=tesseract # Release versioning. Get versions from PACKAGE_VERSION. AX_SPLIT_VERSION GENERIC_MAJOR_VERSION=$(echo "$AX_MAJOR_VERSION" | $SED 's/^[[^0-9]]*//') GENERIC_MINOR_VERSION=$AX_MINOR_VERSION GENERIC_MICRO_VERSION=`echo "$AX_POINT_VERSION" | $SED 's/^\([[0-9]][[0-9]]*\).*/\1/'` # API version (often = GENERIC_MAJOR_VERSION.GENERIC_MINOR_VERSION) GENERIC_API_VERSION=$GENERIC_MAJOR_VERSION.$GENERIC_MINOR_VERSION GENERIC_LIBRARY_VERSION=$GENERIC_MAJOR_VERSION:$GENERIC_MINOR_VERSION AC_SUBST([GENERIC_API_VERSION]) AC_SUBST([GENERIC_MAJOR_VERSION]) AC_SUBST([GENERIC_MINOR_VERSION]) AC_SUBST([GENERIC_MICRO_VERSION]) AC_SUBST([GENERIC_LIBRARY_VERSION]) PACKAGE=$GENERIC_LIBRARY_NAME AC_SUBST([GENERIC_LIBRARY_NAME]) GENERIC_VERSION=$GENERIC_MAJOR_VERSION.$GENERIC_MINOR_VERSION.$GENERIC_MICRO_VERSION GENERIC_RELEASE=$GENERIC_MAJOR_VERSION.$GENERIC_MINOR_VERSION AC_SUBST([GENERIC_RELEASE]) AC_SUBST([GENERIC_VERSION]) AC_CONFIG_HEADERS([include/config_auto.h:config/config.h.in]) # default conditional AM_CONDITIONAL([T_WIN], false) AM_CONDITIONAL([GRAPHICS_DISABLED], false) AC_SUBST([AM_CPPFLAGS]) # Be less noisy by default. # Can be overridden with `configure --disable-silent-rules` or with `make V=1`. AM_SILENT_RULES([yes]) ############################# # # Platform specific setup # ############################# AC_CANONICAL_HOST case "${host_os}" in mingw*) AM_CONDITIONAL([T_WIN], true) AM_CONDITIONAL([ADD_RT], false) AC_SUBST([AM_LDFLAGS], ['-no-undefined']) ;; cygwin*) AM_CONDITIONAL([ADD_RT], false) AC_SUBST([NOUNDEFINED], ['-no-undefined']) ;; solaris*) LIBS="$LIBS -lsocket -lnsl -lrt -lxnet" AM_CONDITIONAL([ADD_RT], true) ;; *darwin*) AM_CONDITIONAL([ADD_RT], false) ;; *android*|openbsd*) AM_CONDITIONAL([ADD_RT], false) ;; powerpc-*-darwin*) ;; *) # default AM_CONDITIONAL([ADD_RT], true) ;; esac WERROR=-Werror # The test code used by AX_CHECK_COMPILE_FLAG uses an empty statement # and unused macros which must not raise a compiler error, but it must # be an error if flags like -avx are ignored on ARM and other # architectures because they are unsupported. AX_CHECK_COMPILE_FLAG([-Werror=unused-command-line-argument], [WERROR=-Werror=unused-command-line-argument]) ## Checks for supported compiler options. AM_CONDITIONAL([HAVE_AVX], false) AM_CONDITIONAL([HAVE_AVX2], false) AM_CONDITIONAL([HAVE_AVX512F], false) AM_CONDITIONAL([HAVE_FMA], false) AM_CONDITIONAL([HAVE_SSE4_1], false) AM_CONDITIONAL([HAVE_NEON], false) case "${host_cpu}" in amd64|*86*) AX_CHECK_COMPILE_FLAG([-mavx], [avx=true], [avx=false], [$WERROR]) AM_CONDITIONAL([HAVE_AVX], ${avx}) if $avx; then AC_DEFINE([HAVE_AVX], [1], [Enable AVX instructions]) fi AX_CHECK_COMPILE_FLAG([-mavx2], [avx2=true], [avx2=false], [$WERROR]) AM_CONDITIONAL([HAVE_AVX2], $avx2) if $avx2; then AC_DEFINE([HAVE_AVX2], [1], [Enable AVX2 instructions]) fi AX_CHECK_COMPILE_FLAG([-mavx512f], [avx512f=true], [avx512f=false], [$WERROR]) AM_CONDITIONAL([HAVE_AVX512F], $avx512f) if $avx512f; then AC_DEFINE([HAVE_AVX512F], [1], [Enable AVX512F instructions]) fi AX_CHECK_COMPILE_FLAG([-mfma], [fma=true], [fma=false], [$WERROR]) AM_CONDITIONAL([HAVE_FMA], $fma) if $fma; then AC_DEFINE([HAVE_FMA], [1], [Enable FMA instructions]) fi AX_CHECK_COMPILE_FLAG([-msse4.1], [sse41=true], [sse41=false], [$WERROR]) AM_CONDITIONAL([HAVE_SSE4_1], $sse41) if $sse41; then AC_DEFINE([HAVE_SSE4_1], [1], [Enable SSE 4.1 instructions]) fi ;; aarch64*|arm64) # ARMv8 always has NEON and does not need special compiler flags. AM_CONDITIONAL([HAVE_NEON], true) AC_DEFINE([HAVE_NEON], [1], [Enable NEON instructions]) ;; arm*) AX_CHECK_COMPILE_FLAG([-mfpu=neon], [neon=true], [neon=false], [$WERROR]) AM_CONDITIONAL([HAVE_NEON], $neon) if $neon; then AC_DEFINE([HAVE_NEON], [1], [Enable NEON instructions]) NEON_CXXFLAGS="-mfpu=neon" AC_SUBST([NEON_CXXFLAGS]) check_for_neon=1 fi ;; *) AC_MSG_WARN([No compiler options for $host_cpu]) esac # check whether feenableexcept is supported. some C libraries (e.g. uclibc) don't. AC_CHECK_FUNCS([feenableexcept]) # additional checks for NEON targets if test x$check_for_neon = x1; then AC_MSG_NOTICE([checking how to detect NEON availability]) AC_CHECK_FUNCS([getauxval elf_aux_info android_getCpuFamily]) if test $ac_cv_func_getauxval = no && test $ac_cv_func_elf_aux_info = no && test $ac_cv_func_android_getCpuFamily = no; then AC_MSG_WARN([NEON is available, but we don't know how to check for it. Will not be able to use NEON.]) fi fi AX_CHECK_COMPILE_FLAG([-fopenmp-simd], [openmp_simd=true], [openmp_simd=false], [$WERROR]) AM_CONDITIONAL([OPENMP_SIMD], $openmp_simd) AC_ARG_WITH([extra-includes], [AS_HELP_STRING([--with-extra-includes=DIR], [Define an additional directory for include files])], [if test -d "$withval" ; then CFLAGS="$CFLAGS -I$withval" else AC_MSG_ERROR([Cannot stat directory $withval]) fi]) AC_ARG_WITH([extra-libraries], [AS_HELP_STRING([--with-extra-libraries=DIR], [Define an additional directory for library files])], [if test -d "$withval" ; then LDFLAGS="$LDFLAGS -L$withval" else AC_MSG_ERROR([Cannot stat directory $withval]) fi]) AC_MSG_CHECKING([--enable-float32 argument]) AC_ARG_ENABLE([float32], AS_HELP_STRING([--disable-float32], [disable float and enable double for LSTM])) AC_MSG_RESULT([$enable_float32]) if test "$enable_float32" != "no"; then AC_DEFINE([FAST_FLOAT], [1], [Enable float for LSTM]) fi AC_MSG_CHECKING([--enable-graphics argument]) AC_ARG_ENABLE([graphics], AS_HELP_STRING([--disable-graphics], [disable graphics (ScrollView)])) AC_MSG_RESULT([$enable_graphics]) if test "$enable_graphics" = "no"; then AC_DEFINE([GRAPHICS_DISABLED], [], [Disable graphics]) AM_CONDITIONAL([GRAPHICS_DISABLED], true) fi AC_MSG_CHECKING([--enable-legacy argument]) AC_ARG_ENABLE([legacy], AS_HELP_STRING([--disable-legacy], [disable the legacy OCR engine])) AC_MSG_RESULT([$enable_legacy]) AM_CONDITIONAL([DISABLED_LEGACY_ENGINE], test "$enable_legacy" = "no") if test "$enable_legacy" = "no"; then AC_DEFINE([DISABLED_LEGACY_ENGINE], [1], [Disable legacy OCR engine]) fi # check whether to build OpenMP support AC_OPENMP have_tiff=false # Note that the first usage of AC_CHECK_HEADERS must be unconditional. AC_CHECK_HEADERS([tiffio.h], [have_tiff=true], [have_tiff=false]) # Configure arguments which allow disabling some optional libraries. AC_ARG_WITH([archive], AS_HELP_STRING([--with-archive], [Build with libarchive which supports compressed model files @<:@default=check@:>@]), [], [with_archive=check]) AC_ARG_WITH([curl], AS_HELP_STRING([--with-curl], [Build with libcurl which supports processing an image URL @<:@default=check@:>@]), [], [with_curl=check]) AC_ARG_WITH([tensorflow], AS_HELP_STRING([--with-tensorflow], [support TensorFlow @<:@default=check@:>@]), [], [with_tensorflow=check]) # Check whether to build with support for TensorFlow. AM_CONDITIONAL([TENSORFLOW], false) TENSORFLOW_LIBS= AS_IF([test "x$with_tensorflow" != xno], [AC_CHECK_HEADERS([tensorflow/core/framework/graph.pb.h], [AC_SUBST([TENSORFLOW_LIBS], ["-lprotobuf -ltensorflow_cc"]) AM_CONDITIONAL([TENSORFLOW], true) ], [if test "x$with_tensorflow" != xcheck; then AC_MSG_FAILURE( [--with-tensorflow was given, but test for libtensorflow-dev failed]) fi ]) ]) # https://lists.apple.com/archives/unix-porting/2009/Jan/msg00026.html m4_define([MY_CHECK_FRAMEWORK], [AC_CACHE_CHECK([if -framework $1 works],[my_cv_framework_$1], [save_LIBS="$LIBS" LIBS="$LIBS -framework $1" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [my_cv_framework_$1=yes], [my_cv_framework_$1=no]) LIBS="$save_LIBS" ]) if test "$my_cv_framework_$1"="yes"; then AC_DEFINE(AS_TR_CPP([HAVE_FRAMEWORK_$1]), 1, [Define if you have the $1 framework]) AS_TR_CPP([FRAMEWORK_$1])="-framework $1" AC_SUBST(AS_TR_CPP([FRAMEWORK_$1])) fi] ) case "${host_os}" in *darwin* | *-macos10*) MY_CHECK_FRAMEWORK([Accelerate]) if test $my_cv_framework_Accelerate = yes; then AM_CPPFLAGS="-DHAVE_FRAMEWORK_ACCELERATE $AM_CPPFLAGS" AM_LDFLAGS="$AM_LDFLAGS -framework Accelerate" fi ;; *) # default ;; esac # check whether to build tesseract with -fvisibility=hidden -fvisibility-inlines-hidden # http://gcc.gnu.org/wiki/Visibility # https://groups.google.com/g/tesseract-dev/c/l2ZFrpgYkSc/m/_cdYSRDSXuUJ AC_MSG_CHECKING([--enable-visibility argument]) AC_ARG_ENABLE([visibility], AS_HELP_STRING([--enable-visibility], [enable experimental build with -fvisibility [default=no]])) AC_MSG_RESULT([$enable_visibility]) AM_CONDITIONAL([VISIBILITY], [test "$enable_visibility" = "yes"]) # Check if tessdata-prefix is disabled AC_MSG_CHECKING([whether to use tessdata-prefix]) AC_ARG_ENABLE([tessdata-prefix], [AS_HELP_STRING([--disable-tessdata-prefix], [don't set TESSDATA-PREFIX during compile])], [tessdata_prefix="no"], [tessdata_prefix="yes"]) AC_MSG_RESULT([$tessdata_prefix]) AM_CONDITIONAL([NO_TESSDATA_PREFIX], [test "$tessdata_prefix" = "no"]) # Detect Clang compiler AC_MSG_CHECKING([if compiling with clang]) AC_COMPILE_IFELSE( [AC_LANG_PROGRAM([], [[ #ifndef __clang__ not clang #endif ]])], [CLANG=yes], [CLANG=no]) AC_MSG_RESULT([$CLANG]) # Check whether to enable debugging AC_MSG_CHECKING([whether to enable debugging]) AC_ARG_ENABLE([debug], AS_HELP_STRING([--enable-debug], [turn on debugging [default=no]])) AC_MSG_RESULT([$enable_debug]) if test x"$enable_debug" = x"yes"; then CXXFLAGS=${CXXFLAGS:-"-O2"} AM_CPPFLAGS="$AM_CPPFLAGS -g -Wall -DDEBUG -pedantic" AM_CXXFLAGS="$AM_CXXFLAGS -g -Wall -DDEBUG -pedantic" if test "x$CLANG" = "xyes"; then # https://clang.llvm.org/docs/CommandGuide/clang.html # clang treats -Og as -O1 AM_CPPFLAGS="$AM_CPPFLAGS -O0" AM_CXXFLAGS="$AM_CXXFLAGS -O0" else AM_CPPFLAGS="$AM_CPPFLAGS -Og" AM_CXXFLAGS="$AM_CXXFLAGS -Og" fi else AM_CXXFLAGS="$AM_CXXFLAGS -O2 -DNDEBUG" AM_CPPFLAGS="$AM_CPPFLAGS -O2 -DNDEBUG" fi # ---------------------------------------- # Init libtool # ---------------------------------------- LT_INIT # ---------------------------------------- # C++ related options # ---------------------------------------- dnl ********************** dnl Turn on C++17 or newer dnl ********************** CPLUSPLUS= AX_CHECK_COMPILE_FLAG([-std=c++17], [CPLUSPLUS=17], [], [$WERROR]) AX_CHECK_COMPILE_FLAG([-std=c++20], [CPLUSPLUS=20], [], [$WERROR]) if test -z "$CPLUSPLUS"; then AC_MSG_ERROR([Your compiler does not have the necessary C++17 support! Cannot proceed.]) fi # Set C++17 or newer support based on platform/compiler case "${host_os}" in cygwin*) CXXFLAGS="$CXXFLAGS -std=gnu++$CPLUSPLUS" ;; *-darwin* | *-macos10*) CXXFLAGS="$CXXFLAGS -std=c++$CPLUSPLUS" if test "x$CLANG" = "xyes"; then LDFLAGS="$LDFLAGS -stdlib=libc++" fi ;; *) # default CXXFLAGS="$CXXFLAGS -std=c++$CPLUSPLUS" ;; esac # ---------------------------------------- # Check for libraries # ---------------------------------------- AC_SEARCH_LIBS([pthread_create], [pthread]) # Set PKG_CONFIG_PATH for macOS with Homebrew unless it is already set. AC_CHECK_PROG([have_brew], brew, true, false) if $have_brew; then brew_prefix=$(brew --prefix) if test -z "$PKG_CONFIG_PATH"; then PKG_CONFIG_PATH=$brew_prefix/opt/icu4c/lib/pkgconfig:$brew_prefix/opt/libarchive/lib/pkgconfig export PKG_CONFIG_PATH fi fi # ---------------------------------------- # Check for programs needed to build documentation. # ---------------------------------------- AM_CONDITIONAL([ASCIIDOC], false) AM_CONDITIONAL([HAVE_XML_CATALOG_FILES], false) AC_ARG_ENABLE([doc], AS_HELP_STRING([--disable-doc], [disable build of documentation]) [], [: m4_divert_text([DEFAULTS], [enable_doc=check])]) AS_IF([test "$enable_doc" != "no"], [ AC_CHECK_PROG([have_asciidoc], asciidoc, true, false) AC_CHECK_PROG([have_xsltproc], xsltproc, true, false) # macOS with Homebrew requires the environment variable # XML_CATALOG_FILES for xsltproc. if $have_asciidoc && $have_xsltproc; then AM_CONDITIONAL([ASCIIDOC], true) XML_CATALOG_FILES= if $have_brew; then catalog_file=$brew_prefix/etc/xml/catalog if test -f $catalog_file; then AM_CONDITIONAL([HAVE_XML_CATALOG_FILES], true) XML_CATALOG_FILES=file:$catalog_file else AC_MSG_WARN([Missing file $catalog_file.]) fi fi AC_SUBST([XML_CATALOG_FILES]) else AS_IF([test "x$enable_doc" != xcheck], [ AC_MSG_FAILURE( [--enable-doc was given, but test for asciidoc and xsltproc failed]) ]) fi ]) # ---------------------------------------- # Checks for typedefs, structures, and compiler characteristics. # ---------------------------------------- AC_CHECK_TYPES([wchar_t],,, [#include "wchar.h"]) AC_CHECK_TYPES([long long int]) # ---------------------------------------- # Test auxiliary packages # ---------------------------------------- AM_CONDITIONAL([HAVE_LIBCURL], false) AS_IF([test "x$with_curl" != xno], [ PKG_CHECK_MODULES([libcurl], [libcurl], [have_libcurl=true], [have_libcurl=false]) AM_CONDITIONAL([HAVE_LIBCURL], $have_libcurl) if $have_libcurl; then AC_DEFINE([HAVE_LIBCURL], [1], [Enable libcurl]) else AS_IF([test "x$with_curl" != xcheck], [ AC_MSG_FAILURE( [--with-curl was given, but test for libcurl failed]) ]) fi ]) PKG_CHECK_MODULES([LEPTONICA], [lept >= 1.74], [have_lept=true], [have_lept=false]) if $have_lept; then CPPFLAGS="$CPPFLAGS $LEPTONICA_CFLAGS" else AC_MSG_ERROR([Leptonica 1.74 or higher is required. Try to install libleptonica-dev package.]) fi AM_CONDITIONAL([HAVE_LIBARCHIVE], false) AS_IF([test "x$with_archive" != xno], [ PKG_CHECK_MODULES([libarchive], [libarchive], [have_libarchive=true], [have_libarchive=false]) AM_CONDITIONAL([HAVE_LIBARCHIVE], [$have_libarchive]) if $have_libarchive; then AC_DEFINE([HAVE_LIBARCHIVE], [1], [Enable libarchive]) CPPFLAGS="$CPPFLAGS $libarchive_CFLAGS" else AS_IF([test "x$with_archive" != xcheck], [ AC_MSG_FAILURE( [--with-archive was given, but test for libarchive failed]) ]) fi ]) AM_CONDITIONAL([ENABLE_TRAINING], true) # Check availability of ICU packages. PKG_CHECK_MODULES([ICU_UC], [icu-uc >= 52.1], [have_icu_uc=true], [have_icu_uc=false]) PKG_CHECK_MODULES([ICU_I18N], [icu-i18n >= 52.1], [have_icu_i18n=true], [have_icu_i18n=false]) if !($have_icu_uc && $have_icu_i18n); then AC_MSG_WARN([icu 52.1 or higher is required, but was not found.]) AC_MSG_WARN([Training tools WILL NOT be built.]) AC_MSG_WARN([Try to install libicu-dev package.]) AM_CONDITIONAL([ENABLE_TRAINING], false) fi # Check location of pango headers PKG_CHECK_MODULES([pango], [pango >= 1.38.0], [have_pango=true], [have_pango=false]) if !($have_pango); then AC_MSG_WARN([pango 1.38.0 or higher is required, but was not found.]) AC_MSG_WARN([Training tools WILL NOT be built.]) AC_MSG_WARN([Try to install libpango1.0-dev package.]) AM_CONDITIONAL([ENABLE_TRAINING], false) fi # Check location of cairo headers PKG_CHECK_MODULES([cairo], [cairo], [have_cairo=true], [have_cairo=false]) if !($have_cairo); then AC_MSG_WARN([Training tools WILL NOT be built because of missing cairo library.]) AC_MSG_WARN([Try to install libcairo-dev?? package.]) AM_CONDITIONAL([ENABLE_TRAINING], false) fi PKG_CHECK_MODULES([pangocairo], [pangocairo], [], [false]) PKG_CHECK_MODULES([pangoft2], [pangoft2], [], [false]) # ---------------------------------------- # Final Tasks and Output # ---------------------------------------- # Output files AC_CONFIG_FILES([include/tesseract/version.h]) AC_CONFIG_FILES([Makefile tesseract.pc]) AC_CONFIG_FILES([tessdata/Makefile]) AC_CONFIG_FILES([tessdata/configs/Makefile]) AC_CONFIG_FILES([tessdata/tessconfigs/Makefile]) AC_CONFIG_FILES([java/Makefile]) AC_CONFIG_FILES([java/com/Makefile]) AC_CONFIG_FILES([java/com/google/Makefile]) AC_CONFIG_FILES([java/com/google/scrollview/Makefile]) AC_CONFIG_FILES([java/com/google/scrollview/events/Makefile]) AC_CONFIG_FILES([java/com/google/scrollview/ui/Makefile]) AC_OUTPUT # Final message echo "" echo "Configuration is done." echo "You can now build and install $PACKAGE_NAME by running:" echo "" echo "$ make" echo "$ sudo make install" echo "$ sudo ldconfig" echo "" AM_COND_IF([ASCIIDOC], [ echo "This will also build the documentation." ], [ AS_IF([test "$enable_doc" = "no"], [ echo "Documentation will not be built because it was disabled." ], [ echo "Documentation will not be built because asciidoc or xsltproc is missing." ]) ]) # echo "$ sudo make install LANGS=\"eng ara deu\"" # echo " Or:" # echo "$ sudo make install-langs" echo "" AM_COND_IF([ENABLE_TRAINING], [ echo "Training tools can be built and installed with:" echo "" echo "$ make training" echo "$ sudo make training-install" echo ""], [ echo "You cannot build training tools because of missing dependency." echo "Check configure output for details." echo ""] ) # ---------------------------------------- # CONFIG Template # ---------------------------------------- # Fence added in configuration file AH_TOP([ #ifndef CONFIG_AUTO_H #define CONFIG_AUTO_H /* config_auto.h: begin */ ]) # Stuff added at bottom of file AH_BOTTOM([ /* Miscellaneous defines */ #define AUTOCONF 1 /* Not used yet #ifndef NO_GETTEXT #define USING_GETTEXT #endif */ /* config_auto.h: end */ #endif ])
2301_81045437/tesseract
configure.ac
Shell
apache-2.0
19,873
#!/bin/bash # # File: generate_manpages.sh # Description: Converts .asc files into man pages, etc. for Tesseract. # Author: eger@google.com (David Eger) # Created: 9 Feb 2012 # # (C) Copyright 2012 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. man_xslt=http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl asciidoc=$(which asciidoc) xsltproc=$(which xsltproc) if [[ -z "${asciidoc}" ]] || [[ -z "${xsltproc}" ]]; then echo "Please make sure asciidoc and xsltproc are installed." exit 1 else for src in *.asc; do pagename=${src/.asc/} (${asciidoc} -d manpage "${src}" && ${asciidoc} -d manpage -b docbook "${src}" && ${xsltproc} --nonet ${man_xslt} "${pagename}".xml) || echo "Error generating ${pagename}" done fi exit 0
2301_81045437/tesseract
doc/generate_manpages.sh
Shell
apache-2.0
1,298
// SPDX-License-Identifier: Apache-2.0 // File: baseapi.h // Description: Simple API for calling tesseract. // Author: Ray Smith // // (C) Copyright 2006, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TESSERACT_API_BASEAPI_H_ #define TESSERACT_API_BASEAPI_H_ #ifdef HAVE_CONFIG_H # include "config_auto.h" // DISABLED_LEGACY_ENGINE #endif #include "export.h" #include "pageiterator.h" #include "publictypes.h" #include "resultiterator.h" #include "unichar.h" #include <tesseract/version.h> #include <cstdio> #include <vector> // for std::vector struct Pix; struct Pixa; struct Boxa; namespace tesseract { class PAGE_RES; class ParagraphModel; class BLOCK_LIST; class ETEXT_DESC; struct OSResults; class UNICHARSET; class Dawg; class Dict; class EquationDetect; class PageIterator; class ImageThresholder; class LTRResultIterator; class ResultIterator; class MutableIterator; class TessResultRenderer; class Tesseract; // Function to read a std::vector<char> from a whole file. // Returns false on failure. using FileReader = bool (*)(const char *filename, std::vector<char> *data); using DictFunc = int (Dict::*)(void *, const UNICHARSET &, UNICHAR_ID, bool) const; using ProbabilityInContextFunc = double (Dict::*)(const char *, const char *, int, const char *, int); /** * Base class for all tesseract APIs. * Specific classes can add ability to work on different inputs or produce * different outputs. * This class is mostly an interface layer on top of the Tesseract instance * class to hide the data types so that users of this class don't have to * include any other Tesseract headers. */ class TESS_API TessBaseAPI { public: TessBaseAPI(); virtual ~TessBaseAPI(); // Copy constructor and assignment operator are currently unsupported. TessBaseAPI(TessBaseAPI const &) = delete; TessBaseAPI &operator=(TessBaseAPI const &) = delete; /** * Returns the version identifier as a static string. Do not delete. */ static const char *Version(); /** * Set the name of the input file. Needed for training and * reading a UNLV zone file, and for searchable PDF output. */ void SetInputName(const char *name); /** * These functions are required for searchable PDF output. * We need our hands on the input file so that we can include * it in the PDF without transcoding. If that is not possible, * we need the original image. Finally, resolution metadata * is stored in the PDF so we need that as well. */ const char *GetInputName(); // Takes ownership of the input pix. void SetInputImage(Pix *pix); Pix *GetInputImage(); int GetSourceYResolution(); const char *GetDatapath(); /** Set the name of the bonus output files. Needed only for debugging. */ void SetOutputName(const char *name); /** * Set the value of an internal "parameter." * Supply the name of the parameter and the value as a string, just as * you would in a config file. * Returns false if the name lookup failed. * Eg SetVariable("tessedit_char_blacklist", "xyz"); to ignore x, y and z. * Or SetVariable("classify_bln_numeric_mode", "1"); to set numeric-only mode. * SetVariable may be used before Init, but settings will revert to * defaults on End(). * * Note: Must be called after Init(). Only works for non-init variables * (init variables should be passed to Init()). */ bool SetVariable(const char *name, const char *value); bool SetDebugVariable(const char *name, const char *value); /** * Returns true if the parameter was found among Tesseract parameters. * Fills in value with the value of the parameter. */ bool GetIntVariable(const char *name, int *value) const; bool GetBoolVariable(const char *name, bool *value) const; bool GetDoubleVariable(const char *name, double *value) const; /** * Returns the pointer to the string that represents the value of the * parameter if it was found among Tesseract parameters. */ const char *GetStringVariable(const char *name) const; #ifndef DISABLED_LEGACY_ENGINE /** * Print Tesseract fonts table to the given file. */ void PrintFontsTable(FILE *fp) const; #endif /** * Print Tesseract parameters to the given file. */ void PrintVariables(FILE *fp) const; /** * Get value of named variable as a string, if it exists. */ bool GetVariableAsString(const char *name, std::string *val) const; /** * Instances are now mostly thread-safe and totally independent, * but some global parameters remain. Basically it is safe to use multiple * TessBaseAPIs in different threads in parallel, UNLESS: * you use SetVariable on some of the Params in classify and textord. * If you do, then the effect will be to change it for all your instances. * * Start tesseract. Returns zero on success and -1 on failure. * NOTE that the only members that may be called before Init are those * listed above here in the class definition. * * The datapath must be the name of the tessdata directory. * The language is (usually) an ISO 639-3 string or nullptr will default to * eng. It is entirely safe (and eventually will be efficient too) to call * Init multiple times on the same instance to change language, or just * to reset the classifier. * The language may be a string of the form [~]<lang>[+[~]<lang>]* indicating * that multiple languages are to be loaded. Eg hin+eng will load Hindi and * English. Languages may specify internally that they want to be loaded * with one or more other languages, so the ~ sign is available to override * that. Eg if hin were set to load eng by default, then hin+~eng would force * loading only hin. The number of loaded languages is limited only by * memory, with the caveat that loading additional languages will impact * both speed and accuracy, as there is more work to do to decide on the * applicable language, and there is more chance of hallucinating incorrect * words. * WARNING: On changing languages, all Tesseract parameters are reset * back to their default values. (Which may vary between languages.) * If you have a rare need to set a Variable that controls * initialization for a second call to Init you should explicitly * call End() and then use SetVariable before Init. This is only a very * rare use case, since there are very few uses that require any parameters * to be set before Init. * * If set_only_non_debug_params is true, only params that do not contain * "debug" in the name will be set. */ int Init(const char *datapath, const char *language, OcrEngineMode mode, char **configs, int configs_size, const std::vector<std::string> *vars_vec, const std::vector<std::string> *vars_values, bool set_only_non_debug_params); int Init(const char *datapath, const char *language, OcrEngineMode oem) { return Init(datapath, language, oem, nullptr, 0, nullptr, nullptr, false); } int Init(const char *datapath, const char *language) { return Init(datapath, language, OEM_DEFAULT, nullptr, 0, nullptr, nullptr, false); } // In-memory version reads the traineddata file directly from the given // data[data_size] array, and/or reads data via a FileReader. int Init(const char *data, int data_size, const char *language, OcrEngineMode mode, char **configs, int configs_size, const std::vector<std::string> *vars_vec, const std::vector<std::string> *vars_values, bool set_only_non_debug_params, FileReader reader); /** * Returns the languages string used in the last valid initialization. * If the last initialization specified "deu+hin" then that will be * returned. If hin loaded eng automatically as well, then that will * not be included in this list. To find the languages actually * loaded use GetLoadedLanguagesAsVector. * The returned string should NOT be deleted. */ const char *GetInitLanguagesAsString() const; /** * Returns the loaded languages in the vector of std::string. * Includes all languages loaded by the last Init, including those loaded * as dependencies of other loaded languages. */ void GetLoadedLanguagesAsVector(std::vector<std::string> *langs) const; /** * Returns the available languages in the sorted vector of std::string. */ void GetAvailableLanguagesAsVector(std::vector<std::string> *langs) const; /** * Init only for page layout analysis. Use only for calls to SetImage and * AnalysePage. Calls that attempt recognition will generate an error. */ void InitForAnalysePage(); /** * Read a "config" file containing a set of param, value pairs. * Searches the standard places: tessdata/configs, tessdata/tessconfigs * and also accepts a relative or absolute path name. * Note: only non-init params will be set (init params are set by Init()). */ void ReadConfigFile(const char *filename); /** Same as above, but only set debug params from the given config file. */ void ReadDebugConfigFile(const char *filename); /** * Set the current page segmentation mode. Defaults to PSM_SINGLE_BLOCK. * The mode is stored as an IntParam so it can also be modified by * ReadConfigFile or SetVariable("tessedit_pageseg_mode", mode as string). */ void SetPageSegMode(PageSegMode mode); /** Return the current page segmentation mode. */ PageSegMode GetPageSegMode() const; /** * Recognize a rectangle from an image and return the result as a string. * May be called many times for a single Init. * Currently has no error checking. * Greyscale of 8 and color of 24 or 32 bits per pixel may be given. * Palette color images will not work properly and must be converted to * 24 bit. * Binary images of 1 bit per pixel may also be given but they must be * byte packed with the MSB of the first byte being the first pixel, and a * 1 represents WHITE. For binary images set bytes_per_pixel=0. * The recognized text is returned as a char* which is coded * as UTF8 and must be freed with the delete [] operator. * * Note that TesseractRect is the simplified convenience interface. * For advanced uses, use SetImage, (optionally) SetRectangle, Recognize, * and one or more of the Get*Text functions below. */ char *TesseractRect(const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height); /** * Call between pages or documents etc to free up memory and forget * adaptive data. */ void ClearAdaptiveClassifier(); /** * @defgroup AdvancedAPI Advanced API * The following methods break TesseractRect into pieces, so you can * get hold of the thresholded image, get the text in different formats, * get bounding boxes, confidences etc. */ /* @{ */ /** * Provide an image for Tesseract to recognize. Format is as * TesseractRect above. Copies the image buffer and converts to Pix. * SetImage clears all recognition results, and sets the rectangle to the * full image, so it may be followed immediately by a GetUTF8Text, and it * will automatically perform recognition. */ void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line); /** * Provide an image for Tesseract to recognize. As with SetImage above, * Tesseract takes its own copy of the image, so it need not persist until * after Recognize. * Pix vs raw, which to use? * Use Pix where possible. Tesseract uses Pix as its internal representation * and it is therefore more efficient to provide a Pix directly. */ void SetImage(Pix *pix); /** * Set the resolution of the source image in pixels per inch so font size * information can be calculated in results. Call this after SetImage(). */ void SetSourceResolution(int ppi); /** * Restrict recognition to a sub-rectangle of the image. Call after SetImage. * Each SetRectangle clears the recogntion results so multiple rectangles * can be recognized with the same image. */ void SetRectangle(int left, int top, int width, int height); /** * Get a copy of the internal thresholded image from Tesseract. * Caller takes ownership of the Pix and must pixDestroy it. * May be called any time after SetImage, or after TesseractRect. */ Pix *GetThresholdedImage(); /** * Return average gradient of lines on page. */ float GetGradient(); /** * Get the result of page layout analysis as a leptonica-style * Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. */ Boxa *GetRegions(Pixa **pixa); /** * Get the textlines as a leptonica-style * Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. * If raw_image is true, then extract from the original image instead of the * thresholded image and pad by raw_padding pixels. * If blockids is not nullptr, the block-id of each line is also returned as * an array of one element per line. delete [] after use. If paraids is not * nullptr, the paragraph-id of each line within its block is also returned as * an array of one element per line. delete [] after use. */ Boxa *GetTextlines(bool raw_image, int raw_padding, Pixa **pixa, int **blockids, int **paraids); /* Helper method to extract from the thresholded image. (most common usage) */ Boxa *GetTextlines(Pixa **pixa, int **blockids) { return GetTextlines(false, 0, pixa, blockids, nullptr); } /** * Get textlines and strips of image regions as a leptonica-style Boxa, Pixa * pair, in reading order. Enables downstream handling of non-rectangular * regions. * Can be called before or after Recognize. * If blockids is not nullptr, the block-id of each line is also returned as * an array of one element per line. delete [] after use. */ Boxa *GetStrips(Pixa **pixa, int **blockids); /** * Get the words as a leptonica-style * Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. */ Boxa *GetWords(Pixa **pixa); /** * Gets the individual connected (text) components (created * after pages segmentation step, but before recognition) * as a leptonica-style Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. * Note: the caller is responsible for calling boxaDestroy() * on the returned Boxa array and pixaDestroy() on cc array. */ Boxa *GetConnectedComponents(Pixa **cc); /** * Get the given level kind of components (block, textline, word etc.) as a * leptonica-style Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. * If blockids is not nullptr, the block-id of each component is also returned * as an array of one element per component. delete [] after use. * If blockids is not nullptr, the paragraph-id of each component with its * block is also returned as an array of one element per component. delete [] * after use. If raw_image is true, then portions of the original image are * extracted instead of the thresholded image and padded with raw_padding. If * text_only is true, then only text components are returned. */ Boxa *GetComponentImages(PageIteratorLevel level, bool text_only, bool raw_image, int raw_padding, Pixa **pixa, int **blockids, int **paraids); // Helper function to get binary images with no padding (most common usage). Boxa *GetComponentImages(const PageIteratorLevel level, const bool text_only, Pixa **pixa, int **blockids) { return GetComponentImages(level, text_only, false, 0, pixa, blockids, nullptr); } /** * Returns the scale factor of the thresholded image that would be returned by * GetThresholdedImage() and the various GetX() methods that call * GetComponentImages(). * Returns 0 if no thresholder has been set. */ int GetThresholdedImageScaleFactor() const; /** * Runs page layout analysis in the mode set by SetPageSegMode. * May optionally be called prior to Recognize to get access to just * the page layout results. Returns an iterator to the results. * If merge_similar_words is true, words are combined where suitable for use * with a line recognizer. Use if you want to use AnalyseLayout to find the * textlines, and then want to process textline fragments with an external * line recognizer. * Returns nullptr on error or an empty page. * The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ PageIterator *AnalyseLayout(); PageIterator *AnalyseLayout(bool merge_similar_words); /** * Recognize the image from SetAndThresholdImage, generating Tesseract * internal structures. Returns 0 on success. * Optional. The Get*Text functions below will call Recognize if needed. * After Recognize, the output is kept internally until the next SetImage. */ int Recognize(ETEXT_DESC *monitor); /** * Methods to retrieve information after SetAndThresholdImage(), * Recognize() or TesseractRect(). (Recognize is called implicitly if needed.) */ /** * Turns images into symbolic text. * * filename can point to a single image, a multi-page TIFF, * or a plain text list of image filenames. * * retry_config is useful for debugging. If not nullptr, you can fall * back to an alternate configuration if a page fails for some * reason. * * timeout_millisec terminates processing if any single page * takes too long. Set to 0 for unlimited time. * * renderer is responsible for creating the output. For example, * use the TessTextRenderer if you want plaintext output, or * the TessPDFRender to produce searchable PDF. * * If tessedit_page_number is non-negative, will only process that * single page. Works for multi-page tiff file, or filelist. * * Returns true if successful, false on error. */ bool ProcessPages(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer); // Does the real work of ProcessPages. bool ProcessPagesInternal(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer); /** * Turn a single image into symbolic text. * * The pix is the image processed. filename and page_index are * metadata used by side-effect processes, such as reading a box * file or formatting as hOCR. * * See ProcessPages for descriptions of other parameters. */ bool ProcessPage(Pix *pix, int page_index, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer); /** * Get a reading-order iterator to the results of LayoutAnalysis and/or * Recognize. The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ ResultIterator *GetIterator(); /** * Get a mutable iterator to the results of LayoutAnalysis and/or Recognize. * The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ MutableIterator *GetMutableIterator(); /** * The recognized text is returned as a char* which is coded * as UTF8 and must be freed with the delete [] operator. */ char *GetUTF8Text(); /** * Make a HTML-formatted string with hOCR markup from the internal * data structures. * page_number is 0-based but will appear in the output as 1-based. * monitor can be used to * cancel the recognition * receive progress callbacks * Returned string must be freed with the delete [] operator. */ char *GetHOCRText(ETEXT_DESC *monitor, int page_number); /** * Make a HTML-formatted string with hOCR markup from the internal * data structures. * page_number is 0-based but will appear in the output as 1-based. * Returned string must be freed with the delete [] operator. */ char *GetHOCRText(int page_number); /** * Make an XML-formatted string with Alto markup from the internal * data structures. */ char *GetAltoText(ETEXT_DESC *monitor, int page_number); /** * Make an XML-formatted string with Alto markup from the internal * data structures. */ char *GetAltoText(int page_number); /** * Make an XML-formatted string with PAGE markup from the internal * data structures. */ char *GetPAGEText(ETEXT_DESC *monitor, int page_number); /** * Make an XML-formatted string with PAGE markup from the internal * data structures. */ char *GetPAGEText(int page_number); /** * Make a TSV-formatted string from the internal data structures. * page_number is 0-based but will appear in the output as 1-based. * Returned string must be freed with the delete [] operator. */ char *GetTSVText(int page_number); /** * Make a box file for LSTM training from the internal data structures. * Constructs coordinates in the original image - not just the rectangle. * page_number is a 0-based page index that will appear in the box file. * Returned string must be freed with the delete [] operator. */ char *GetLSTMBoxText(int page_number); /** * The recognized text is returned as a char* which is coded in the same * format as a box file used in training. * Constructs coordinates in the original image - not just the rectangle. * page_number is a 0-based page index that will appear in the box file. * Returned string must be freed with the delete [] operator. */ char *GetBoxText(int page_number); /** * The recognized text is returned as a char* which is coded in the same * format as a WordStr box file used in training. * page_number is a 0-based page index that will appear in the box file. * Returned string must be freed with the delete [] operator. */ char *GetWordStrBoxText(int page_number); /** * The recognized text is returned as a char* which is coded * as UNLV format Latin-1 with specific reject and suspect codes. * Returned string must be freed with the delete [] operator. */ char *GetUNLVText(); /** * Detect the orientation of the input image and apparent script (alphabet). * orient_deg is the detected clockwise rotation of the input image in degrees * (0, 90, 180, 270) * orient_conf is the confidence (15.0 is reasonably confident) * script_name is an ASCII string, the name of the script, e.g. "Latin" * script_conf is confidence level in the script * Returns true on success and writes values to each parameter as an output */ bool DetectOrientationScript(int *orient_deg, float *orient_conf, const char **script_name, float *script_conf); /** * The recognized text is returned as a char* which is coded * as UTF8 and must be freed with the delete [] operator. * page_number is a 0-based page index that will appear in the osd file. */ char *GetOsdText(int page_number); /** Returns the (average) confidence value between 0 and 100. */ int MeanTextConf(); /** * Returns all word confidences (between 0 and 100) in an array, terminated * by -1. The calling function must delete [] after use. * The number of confidences should correspond to the number of space- * delimited words in GetUTF8Text. */ int *AllWordConfidences(); #ifndef DISABLED_LEGACY_ENGINE /** * Applies the given word to the adaptive classifier if possible. * The word must be SPACE-DELIMITED UTF-8 - l i k e t h i s , so it can * tell the boundaries of the graphemes. * Assumes that SetImage/SetRectangle have been used to set the image * to the given word. The mode arg should be PSM_SINGLE_WORD or * PSM_CIRCLE_WORD, as that will be used to control layout analysis. * The currently set PageSegMode is preserved. * Returns false if adaption was not possible for some reason. */ bool AdaptToWordStr(PageSegMode mode, const char *wordstr); #endif // ndef DISABLED_LEGACY_ENGINE /** * Free up recognition results and any stored image data, without actually * freeing any recognition data that would be time-consuming to reload. * Afterwards, you must call SetImage or TesseractRect before doing * any Recognize or Get* operation. */ void Clear(); /** * Close down tesseract and free up all memory. End() is equivalent to * destructing and reconstructing your TessBaseAPI. * Once End() has been used, none of the other API functions may be used * other than Init and anything declared above it in the class definition. */ void End(); /** * Clear any library-level memory caches. * There are a variety of expensive-to-load constant data structures (mostly * language dictionaries) that are cached globally -- surviving the Init() * and End() of individual TessBaseAPI's. This function allows the clearing * of these caches. **/ static void ClearPersistentCache(); /** * Check whether a word is valid according to Tesseract's language model * @return 0 if the word is invalid, non-zero if valid. * @warning temporary! This function will be removed from here and placed * in a separate API at some future time. */ int IsValidWord(const char *word) const; // Returns true if utf8_character is defined in the UniCharset. bool IsValidCharacter(const char *utf8_character) const; bool GetTextDirection(int *out_offset, float *out_slope); /** Sets Dict::letter_is_okay_ function to point to the given function. */ void SetDictFunc(DictFunc f); /** Sets Dict::probability_in_context_ function to point to the given * function. */ void SetProbabilityInContextFunc(ProbabilityInContextFunc f); /** * Estimates the Orientation And Script of the image. * @return true if the image was processed successfully. */ bool DetectOS(OSResults *); /** * Return text orientation of each block as determined by an earlier run * of layout analysis. */ void GetBlockTextOrientations(int **block_orientation, bool **vertical_writing); /** This method returns the string form of the specified unichar. */ const char *GetUnichar(int unichar_id) const; /** Return the pointer to the i-th dawg loaded into tesseract_ object. */ const Dawg *GetDawg(int i) const; /** Return the number of dawgs loaded into tesseract_ object. */ int NumDawgs() const; Tesseract *tesseract() const { return tesseract_; } OcrEngineMode oem() const { return last_oem_requested_; } void set_min_orientation_margin(double margin); /* @} */ protected: /** Common code for setting the image. Returns true if Init has been called. */ bool InternalSetImage(); /** * Run the thresholder to make the thresholded image. If pix is not nullptr, * the source is thresholded to pix instead of the internal IMAGE. */ virtual bool Threshold(Pix **pix); /** * Find lines from the image making the BLOCK_LIST. * @return 0 on success. */ int FindLines(); /** Delete the pageres and block list ready for a new page. */ void ClearResults(); /** * Return an LTR Result Iterator -- used only for training, as we really want * to ignore all BiDi smarts at that point. * delete once you're done with it. */ LTRResultIterator *GetLTRIterator(); /** * Return the length of the output text string, as UTF8, assuming * one newline per line and one per block, with a terminator, * and assuming a single character reject marker for each rejected character. * Also return the number of recognized blobs in blob_count. */ int TextLength(int *blob_count) const; //// paragraphs.cpp //////////////////////////////////////////////////// void DetectParagraphs(bool after_text_recognition); const PAGE_RES *GetPageRes() const { return page_res_; } protected: Tesseract *tesseract_; ///< The underlying data object. Tesseract *osd_tesseract_; ///< For orientation & script detection. EquationDetect *equ_detect_; ///< The equation detector. FileReader reader_; ///< Reads files from any filesystem. ImageThresholder *thresholder_; ///< Image thresholding module. std::vector<ParagraphModel *> *paragraph_models_; BLOCK_LIST *block_list_; ///< The page layout. PAGE_RES *page_res_; ///< The page-level data. std::string input_file_; ///< Name used by training code. std::string output_file_; ///< Name used by debug code. std::string datapath_; ///< Current location of tessdata. std::string language_; ///< Last initialized language. OcrEngineMode last_oem_requested_; ///< Last ocr language mode requested. bool recognition_done_; ///< page_res_ contains recognition data. /** * @defgroup ThresholderParams Thresholder Parameters * Parameters saved from the Thresholder. Needed to rebuild coordinates. */ /* @{ */ int rect_left_; int rect_top_; int rect_width_; int rect_height_; int image_width_; int image_height_; /* @} */ private: // A list of image filenames gets special consideration bool ProcessPagesFileList(FILE *fp, std::string *buf, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer, int tessedit_page_number); // TIFF supports multipage so gets special consideration. bool ProcessPagesMultipageTiff(const unsigned char *data, size_t size, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer, int tessedit_page_number); }; // class TessBaseAPI. /** Escape a char string - replace &<>"' with HTML codes. */ std::string HOcrEscape(const char *text); } // namespace tesseract #endif // TESSERACT_API_BASEAPI_H_
2301_81045437/tesseract
include/tesseract/baseapi.h
C++
apache-2.0
31,766
// SPDX-License-Identifier: Apache-2.0 // File: capi.h // Description: C-API TessBaseAPI // // (C) Copyright 2012, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef API_CAPI_H_ #define API_CAPI_H_ #include "export.h" #ifdef __cplusplus # include <tesseract/baseapi.h> # include <tesseract/ocrclass.h> # include <tesseract/pageiterator.h> # include <tesseract/renderer.h> # include <tesseract/resultiterator.h> #endif #include <stdbool.h> #include <stdio.h> #ifdef __cplusplus extern "C" { #endif #ifndef BOOL # define BOOL int # define TRUE 1 # define FALSE 0 #endif #ifdef __cplusplus typedef tesseract::TessResultRenderer TessResultRenderer; typedef tesseract::TessBaseAPI TessBaseAPI; typedef tesseract::PageIterator TessPageIterator; typedef tesseract::ResultIterator TessResultIterator; typedef tesseract::MutableIterator TessMutableIterator; typedef tesseract::ChoiceIterator TessChoiceIterator; typedef tesseract::OcrEngineMode TessOcrEngineMode; typedef tesseract::PageSegMode TessPageSegMode; typedef tesseract::PageIteratorLevel TessPageIteratorLevel; typedef tesseract::Orientation TessOrientation; typedef tesseract::ParagraphJustification TessParagraphJustification; typedef tesseract::WritingDirection TessWritingDirection; typedef tesseract::TextlineOrder TessTextlineOrder; typedef tesseract::PolyBlockType TessPolyBlockType; typedef tesseract::ETEXT_DESC ETEXT_DESC; #else typedef struct TessResultRenderer TessResultRenderer; typedef struct TessBaseAPI TessBaseAPI; typedef struct TessPageIterator TessPageIterator; typedef struct TessResultIterator TessResultIterator; typedef struct TessMutableIterator TessMutableIterator; typedef struct TessChoiceIterator TessChoiceIterator; typedef enum TessOcrEngineMode { OEM_TESSERACT_ONLY, OEM_LSTM_ONLY, OEM_TESSERACT_LSTM_COMBINED, OEM_DEFAULT } TessOcrEngineMode; typedef enum TessPageSegMode { PSM_OSD_ONLY, PSM_AUTO_OSD, PSM_AUTO_ONLY, PSM_AUTO, PSM_SINGLE_COLUMN, PSM_SINGLE_BLOCK_VERT_TEXT, PSM_SINGLE_BLOCK, PSM_SINGLE_LINE, PSM_SINGLE_WORD, PSM_CIRCLE_WORD, PSM_SINGLE_CHAR, PSM_SPARSE_TEXT, PSM_SPARSE_TEXT_OSD, PSM_RAW_LINE, PSM_COUNT } TessPageSegMode; typedef enum TessPageIteratorLevel { RIL_BLOCK, RIL_PARA, RIL_TEXTLINE, RIL_WORD, RIL_SYMBOL } TessPageIteratorLevel; typedef enum TessPolyBlockType { PT_UNKNOWN, PT_FLOWING_TEXT, PT_HEADING_TEXT, PT_PULLOUT_TEXT, PT_EQUATION, PT_INLINE_EQUATION, PT_TABLE, PT_VERTICAL_TEXT, PT_CAPTION_TEXT, PT_FLOWING_IMAGE, PT_HEADING_IMAGE, PT_PULLOUT_IMAGE, PT_HORZ_LINE, PT_VERT_LINE, PT_NOISE, PT_COUNT } TessPolyBlockType; typedef enum TessOrientation { ORIENTATION_PAGE_UP, ORIENTATION_PAGE_RIGHT, ORIENTATION_PAGE_DOWN, ORIENTATION_PAGE_LEFT } TessOrientation; typedef enum TessParagraphJustification { JUSTIFICATION_UNKNOWN, JUSTIFICATION_LEFT, JUSTIFICATION_CENTER, JUSTIFICATION_RIGHT } TessParagraphJustification; typedef enum TessWritingDirection { WRITING_DIRECTION_LEFT_TO_RIGHT, WRITING_DIRECTION_RIGHT_TO_LEFT, WRITING_DIRECTION_TOP_TO_BOTTOM } TessWritingDirection; typedef enum TessTextlineOrder { TEXTLINE_ORDER_LEFT_TO_RIGHT, TEXTLINE_ORDER_RIGHT_TO_LEFT, TEXTLINE_ORDER_TOP_TO_BOTTOM } TessTextlineOrder; typedef struct ETEXT_DESC ETEXT_DESC; #endif typedef bool (*TessCancelFunc)(void *cancel_this, int words); typedef bool (*TessProgressFunc)(ETEXT_DESC *ths, int left, int right, int top, int bottom); struct Pix; struct Boxa; struct Pixa; /* General free functions */ TESS_API const char *TessVersion(); TESS_API void TessDeleteText(const char *text); TESS_API void TessDeleteTextArray(char **arr); TESS_API void TessDeleteIntArray(const int *arr); /* Renderer API */ TESS_API TessResultRenderer *TessTextRendererCreate(const char *outputbase); TESS_API TessResultRenderer *TessHOcrRendererCreate(const char *outputbase); TESS_API TessResultRenderer *TessHOcrRendererCreate2(const char *outputbase, BOOL font_info); TESS_API TessResultRenderer *TessAltoRendererCreate(const char *outputbase); TESS_API TessResultRenderer *TessPAGERendererCreate(const char *outputbase); TESS_API TessResultRenderer *TessTsvRendererCreate(const char *outputbase); TESS_API TessResultRenderer *TessPDFRendererCreate(const char *outputbase, const char *datadir, BOOL textonly); TESS_API TessResultRenderer *TessUnlvRendererCreate(const char *outputbase); TESS_API TessResultRenderer *TessBoxTextRendererCreate(const char *outputbase); TESS_API TessResultRenderer *TessLSTMBoxRendererCreate(const char *outputbase); TESS_API TessResultRenderer *TessWordStrBoxRendererCreate( const char *outputbase); TESS_API void TessDeleteResultRenderer(TessResultRenderer *renderer); TESS_API void TessResultRendererInsert(TessResultRenderer *renderer, TessResultRenderer *next); TESS_API TessResultRenderer *TessResultRendererNext( TessResultRenderer *renderer); TESS_API BOOL TessResultRendererBeginDocument(TessResultRenderer *renderer, const char *title); TESS_API BOOL TessResultRendererAddImage(TessResultRenderer *renderer, TessBaseAPI *api); TESS_API BOOL TessResultRendererEndDocument(TessResultRenderer *renderer); TESS_API const char *TessResultRendererExtention(TessResultRenderer *renderer); TESS_API const char *TessResultRendererTitle(TessResultRenderer *renderer); TESS_API int TessResultRendererImageNum(TessResultRenderer *renderer); /* Base API */ TESS_API TessBaseAPI *TessBaseAPICreate(); TESS_API void TessBaseAPIDelete(TessBaseAPI *handle); TESS_API void TessBaseAPISetInputName(TessBaseAPI *handle, const char *name); TESS_API const char *TessBaseAPIGetInputName(TessBaseAPI *handle); TESS_API void TessBaseAPISetInputImage(TessBaseAPI *handle, struct Pix *pix); TESS_API struct Pix *TessBaseAPIGetInputImage(TessBaseAPI *handle); TESS_API int TessBaseAPIGetSourceYResolution(TessBaseAPI *handle); TESS_API const char *TessBaseAPIGetDatapath(TessBaseAPI *handle); TESS_API void TessBaseAPISetOutputName(TessBaseAPI *handle, const char *name); TESS_API BOOL TessBaseAPISetVariable(TessBaseAPI *handle, const char *name, const char *value); TESS_API BOOL TessBaseAPISetDebugVariable(TessBaseAPI *handle, const char *name, const char *value); TESS_API BOOL TessBaseAPIGetIntVariable(const TessBaseAPI *handle, const char *name, int *value); TESS_API BOOL TessBaseAPIGetBoolVariable(const TessBaseAPI *handle, const char *name, BOOL *value); TESS_API BOOL TessBaseAPIGetDoubleVariable(const TessBaseAPI *handle, const char *name, double *value); TESS_API const char *TessBaseAPIGetStringVariable(const TessBaseAPI *handle, const char *name); TESS_API void TessBaseAPIPrintVariables(const TessBaseAPI *handle, FILE *fp); TESS_API BOOL TessBaseAPIPrintVariablesToFile(const TessBaseAPI *handle, const char *filename); TESS_API int TessBaseAPIInit1(TessBaseAPI *handle, const char *datapath, const char *language, TessOcrEngineMode oem, char **configs, int configs_size); TESS_API int TessBaseAPIInit2(TessBaseAPI *handle, const char *datapath, const char *language, TessOcrEngineMode oem); TESS_API int TessBaseAPIInit3(TessBaseAPI *handle, const char *datapath, const char *language); TESS_API int TessBaseAPIInit4(TessBaseAPI *handle, const char *datapath, const char *language, TessOcrEngineMode mode, char **configs, int configs_size, char **vars_vec, char **vars_values, size_t vars_vec_size, BOOL set_only_non_debug_params); TESS_API int TessBaseAPIInit5(TessBaseAPI *handle, const char *data, int data_size, const char *language, TessOcrEngineMode mode, char **configs, int configs_size, char **vars_vec, char **vars_values, size_t vars_vec_size, BOOL set_only_non_debug_params); TESS_API const char *TessBaseAPIGetInitLanguagesAsString( const TessBaseAPI *handle); TESS_API char **TessBaseAPIGetLoadedLanguagesAsVector( const TessBaseAPI *handle); TESS_API char **TessBaseAPIGetAvailableLanguagesAsVector( const TessBaseAPI *handle); TESS_API void TessBaseAPIInitForAnalysePage(TessBaseAPI *handle); TESS_API void TessBaseAPIReadConfigFile(TessBaseAPI *handle, const char *filename); TESS_API void TessBaseAPIReadDebugConfigFile(TessBaseAPI *handle, const char *filename); TESS_API void TessBaseAPISetPageSegMode(TessBaseAPI *handle, TessPageSegMode mode); TESS_API TessPageSegMode TessBaseAPIGetPageSegMode(const TessBaseAPI *handle); TESS_API char *TessBaseAPIRect(TessBaseAPI *handle, const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height); TESS_API void TessBaseAPIClearAdaptiveClassifier(TessBaseAPI *handle); TESS_API void TessBaseAPISetImage(TessBaseAPI *handle, const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line); TESS_API void TessBaseAPISetImage2(TessBaseAPI *handle, struct Pix *pix); TESS_API void TessBaseAPISetSourceResolution(TessBaseAPI *handle, int ppi); TESS_API void TessBaseAPISetRectangle(TessBaseAPI *handle, int left, int top, int width, int height); TESS_API struct Pix *TessBaseAPIGetThresholdedImage(TessBaseAPI *handle); TESS_API float TessBaseAPIGetGradient(TessBaseAPI *handle); TESS_API struct Boxa *TessBaseAPIGetRegions(TessBaseAPI *handle, struct Pixa **pixa); TESS_API struct Boxa *TessBaseAPIGetTextlines(TessBaseAPI *handle, struct Pixa **pixa, int **blockids); TESS_API struct Boxa *TessBaseAPIGetTextlines1(TessBaseAPI *handle, BOOL raw_image, int raw_padding, struct Pixa **pixa, int **blockids, int **paraids); TESS_API struct Boxa *TessBaseAPIGetStrips(TessBaseAPI *handle, struct Pixa **pixa, int **blockids); TESS_API struct Boxa *TessBaseAPIGetWords(TessBaseAPI *handle, struct Pixa **pixa); TESS_API struct Boxa *TessBaseAPIGetConnectedComponents(TessBaseAPI *handle, struct Pixa **cc); TESS_API struct Boxa *TessBaseAPIGetComponentImages(TessBaseAPI *handle, TessPageIteratorLevel level, BOOL text_only, struct Pixa **pixa, int **blockids); TESS_API struct Boxa *TessBaseAPIGetComponentImages1( TessBaseAPI *handle, TessPageIteratorLevel level, BOOL text_only, BOOL raw_image, int raw_padding, struct Pixa **pixa, int **blockids, int **paraids); TESS_API int TessBaseAPIGetThresholdedImageScaleFactor( const TessBaseAPI *handle); TESS_API TessPageIterator *TessBaseAPIAnalyseLayout(TessBaseAPI *handle); TESS_API int TessBaseAPIRecognize(TessBaseAPI *handle, ETEXT_DESC *monitor); TESS_API BOOL TessBaseAPIProcessPages(TessBaseAPI *handle, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer); TESS_API BOOL TessBaseAPIProcessPage(TessBaseAPI *handle, struct Pix *pix, int page_index, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer); TESS_API TessResultIterator *TessBaseAPIGetIterator(TessBaseAPI *handle); TESS_API TessMutableIterator *TessBaseAPIGetMutableIterator( TessBaseAPI *handle); TESS_API char *TessBaseAPIGetUTF8Text(TessBaseAPI *handle); TESS_API char *TessBaseAPIGetHOCRText(TessBaseAPI *handle, int page_number); TESS_API char *TessBaseAPIGetAltoText(TessBaseAPI *handle, int page_number); TESS_API char *TessBaseAPIGetPAGEText(TessBaseAPI *handle, int page_number); TESS_API char *TessBaseAPIGetTsvText(TessBaseAPI *handle, int page_number); TESS_API char *TessBaseAPIGetBoxText(TessBaseAPI *handle, int page_number); TESS_API char *TessBaseAPIGetLSTMBoxText(TessBaseAPI *handle, int page_number); TESS_API char *TessBaseAPIGetWordStrBoxText(TessBaseAPI *handle, int page_number); TESS_API char *TessBaseAPIGetUNLVText(TessBaseAPI *handle); TESS_API int TessBaseAPIMeanTextConf(TessBaseAPI *handle); TESS_API int *TessBaseAPIAllWordConfidences(TessBaseAPI *handle); #ifndef DISABLED_LEGACY_ENGINE TESS_API BOOL TessBaseAPIAdaptToWordStr(TessBaseAPI *handle, TessPageSegMode mode, const char *wordstr); #endif // #ifndef DISABLED_LEGACY_ENGINE TESS_API void TessBaseAPIClear(TessBaseAPI *handle); TESS_API void TessBaseAPIEnd(TessBaseAPI *handle); TESS_API int TessBaseAPIIsValidWord(TessBaseAPI *handle, const char *word); TESS_API BOOL TessBaseAPIGetTextDirection(TessBaseAPI *handle, int *out_offset, float *out_slope); TESS_API const char *TessBaseAPIGetUnichar(TessBaseAPI *handle, int unichar_id); TESS_API void TessBaseAPIClearPersistentCache(TessBaseAPI *handle); #ifndef DISABLED_LEGACY_ENGINE // Call TessDeleteText(*best_script_name) to free memory allocated by this // function TESS_API BOOL TessBaseAPIDetectOrientationScript(TessBaseAPI *handle, int *orient_deg, float *orient_conf, const char **script_name, float *script_conf); #endif // #ifndef DISABLED_LEGACY_ENGINE TESS_API void TessBaseAPISetMinOrientationMargin(TessBaseAPI *handle, double margin); TESS_API int TessBaseAPINumDawgs(const TessBaseAPI *handle); TESS_API TessOcrEngineMode TessBaseAPIOem(const TessBaseAPI *handle); TESS_API void TessBaseGetBlockTextOrientations(TessBaseAPI *handle, int **block_orientation, bool **vertical_writing); /* Page iterator */ TESS_API void TessPageIteratorDelete(TessPageIterator *handle); TESS_API TessPageIterator *TessPageIteratorCopy(const TessPageIterator *handle); TESS_API void TessPageIteratorBegin(TessPageIterator *handle); TESS_API BOOL TessPageIteratorNext(TessPageIterator *handle, TessPageIteratorLevel level); TESS_API BOOL TessPageIteratorIsAtBeginningOf(const TessPageIterator *handle, TessPageIteratorLevel level); TESS_API BOOL TessPageIteratorIsAtFinalElement(const TessPageIterator *handle, TessPageIteratorLevel level, TessPageIteratorLevel element); TESS_API BOOL TessPageIteratorBoundingBox(const TessPageIterator *handle, TessPageIteratorLevel level, int *left, int *top, int *right, int *bottom); TESS_API TessPolyBlockType TessPageIteratorBlockType(const TessPageIterator *handle); TESS_API struct Pix *TessPageIteratorGetBinaryImage( const TessPageIterator *handle, TessPageIteratorLevel level); TESS_API struct Pix *TessPageIteratorGetImage(const TessPageIterator *handle, TessPageIteratorLevel level, int padding, struct Pix *original_image, int *left, int *top); TESS_API BOOL TessPageIteratorBaseline(const TessPageIterator *handle, TessPageIteratorLevel level, int *x1, int *y1, int *x2, int *y2); TESS_API void TessPageIteratorOrientation( TessPageIterator *handle, TessOrientation *orientation, TessWritingDirection *writing_direction, TessTextlineOrder *textline_order, float *deskew_angle); TESS_API void TessPageIteratorParagraphInfo( TessPageIterator *handle, TessParagraphJustification *justification, BOOL *is_list_item, BOOL *is_crown, int *first_line_indent); /* Result iterator */ TESS_API void TessResultIteratorDelete(TessResultIterator *handle); TESS_API TessResultIterator *TessResultIteratorCopy( const TessResultIterator *handle); TESS_API TessPageIterator *TessResultIteratorGetPageIterator( TessResultIterator *handle); TESS_API const TessPageIterator *TessResultIteratorGetPageIteratorConst( const TessResultIterator *handle); TESS_API TessChoiceIterator *TessResultIteratorGetChoiceIterator( const TessResultIterator *handle); TESS_API BOOL TessResultIteratorNext(TessResultIterator *handle, TessPageIteratorLevel level); TESS_API char *TessResultIteratorGetUTF8Text(const TessResultIterator *handle, TessPageIteratorLevel level); TESS_API float TessResultIteratorConfidence(const TessResultIterator *handle, TessPageIteratorLevel level); TESS_API const char *TessResultIteratorWordRecognitionLanguage( const TessResultIterator *handle); TESS_API const char *TessResultIteratorWordFontAttributes( const TessResultIterator *handle, BOOL *is_bold, BOOL *is_italic, BOOL *is_underlined, BOOL *is_monospace, BOOL *is_serif, BOOL *is_smallcaps, int *pointsize, int *font_id); TESS_API BOOL TessResultIteratorWordIsFromDictionary(const TessResultIterator *handle); TESS_API BOOL TessResultIteratorWordIsNumeric(const TessResultIterator *handle); TESS_API BOOL TessResultIteratorSymbolIsSuperscript(const TessResultIterator *handle); TESS_API BOOL TessResultIteratorSymbolIsSubscript(const TessResultIterator *handle); TESS_API BOOL TessResultIteratorSymbolIsDropcap(const TessResultIterator *handle); TESS_API void TessChoiceIteratorDelete(TessChoiceIterator *handle); TESS_API BOOL TessChoiceIteratorNext(TessChoiceIterator *handle); TESS_API const char *TessChoiceIteratorGetUTF8Text( const TessChoiceIterator *handle); TESS_API float TessChoiceIteratorConfidence(const TessChoiceIterator *handle); /* Progress monitor */ TESS_API ETEXT_DESC *TessMonitorCreate(); TESS_API void TessMonitorDelete(ETEXT_DESC *monitor); TESS_API void TessMonitorSetCancelFunc(ETEXT_DESC *monitor, TessCancelFunc cancelFunc); TESS_API void TessMonitorSetCancelThis(ETEXT_DESC *monitor, void *cancelThis); TESS_API void *TessMonitorGetCancelThis(ETEXT_DESC *monitor); TESS_API void TessMonitorSetProgressFunc(ETEXT_DESC *monitor, TessProgressFunc progressFunc); TESS_API int TessMonitorGetProgress(ETEXT_DESC *monitor); TESS_API void TessMonitorSetDeadlineMSecs(ETEXT_DESC *monitor, int deadline); #ifdef __cplusplus } #endif #endif // API_CAPI_H_
2301_81045437/tesseract
include/tesseract/capi.h
C
apache-2.0
21,096
// SPDX-License-Identifier: Apache-2.0 // File: export.h // Description: Place holder // // (C) Copyright 2006, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TESSERACT_PLATFORM_H_ #define TESSERACT_PLATFORM_H_ #ifndef TESS_API # if defined(_WIN32) || defined(__CYGWIN__) # if defined(TESS_EXPORTS) # define TESS_API __declspec(dllexport) # elif defined(TESS_IMPORTS) # define TESS_API __declspec(dllimport) # else # define TESS_API # endif # else # if defined(TESS_EXPORTS) || defined(TESS_IMPORTS) # define TESS_API __attribute__((visibility("default"))) # else # define TESS_API # endif # endif #endif #endif // TESSERACT_PLATFORM_H_
2301_81045437/tesseract
include/tesseract/export.h
C
apache-2.0
1,214
// SPDX-License-Identifier: Apache-2.0 // File: ltrresultiterator.h // Description: Iterator for tesseract results in strict left-to-right // order that avoids using tesseract internal data structures. // Author: Ray Smith // // (C) Copyright 2010, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H_ #define TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H_ #include "export.h" // for TESS_API #include "pageiterator.h" // for PageIterator #include "publictypes.h" // for PageIteratorLevel #include "unichar.h" // for StrongScriptDirection namespace tesseract { class BLOB_CHOICE_IT; class PAGE_RES; class WERD_RES; class Tesseract; // Class to iterate over tesseract results, providing access to all levels // of the page hierarchy, without including any tesseract headers or having // to handle any tesseract structures. // WARNING! This class points to data held within the TessBaseAPI class, and // therefore can only be used while the TessBaseAPI class still exists and // has not been subjected to a call of Init, SetImage, Recognize, Clear, End // DetectOS, or anything else that changes the internal PAGE_RES. // See tesseract/publictypes.h for the definition of PageIteratorLevel. // See also base class PageIterator, which contains the bulk of the interface. // LTRResultIterator adds text-specific methods for access to OCR output. class TESS_API LTRResultIterator : public PageIterator { friend class ChoiceIterator; public: // page_res and tesseract come directly from the BaseAPI. // The rectangle parameters are copied indirectly from the Thresholder, // via the BaseAPI. They represent the coordinates of some rectangle in an // original image (in top-left-origin coordinates) and therefore the top-left // needs to be added to any output boxes in order to specify coordinates // in the original image. See TessBaseAPI::SetRectangle. // The scale and scaled_yres are in case the Thresholder scaled the image // rectangle prior to thresholding. Any coordinates in tesseract's image // must be divided by scale before adding (rect_left, rect_top). // The scaled_yres indicates the effective resolution of the binary image // that tesseract has been given by the Thresholder. // After the constructor, Begin has already been called. LTRResultIterator(PAGE_RES *page_res, Tesseract *tesseract, int scale, int scaled_yres, int rect_left, int rect_top, int rect_width, int rect_height); ~LTRResultIterator() override; // LTRResultIterators may be copied! This makes it possible to iterate over // all the objects at a lower level, while maintaining an iterator to // objects at a higher level. These constructors DO NOT CALL Begin, so // iterations will continue from the location of src. // TODO: For now the copy constructor and operator= only need the base class // versions, but if new data members are added, don't forget to add them! // ============= Moving around within the page ============. // See PageIterator. // ============= Accessing data ==============. // Returns the null terminated UTF-8 encoded text string for the current // object at the given level. Use delete [] to free after use. char *GetUTF8Text(PageIteratorLevel level) const; // Set the string inserted at the end of each text line. "\n" by default. void SetLineSeparator(const char *new_line); // Set the string inserted at the end of each paragraph. "\n" by default. void SetParagraphSeparator(const char *new_para); // Returns the mean confidence of the current object at the given level. // The number should be interpreted as a percent probability. (0.0f-100.0f) float Confidence(PageIteratorLevel level) const; // ============= Functions that refer to words only ============. // Returns the font attributes of the current word. If iterating at a higher // level object than words, eg textlines, then this will return the // attributes of the first word in that textline. // The actual return value is a string representing a font name. It points // to an internal table and SHOULD NOT BE DELETED. Lifespan is the same as // the iterator itself, ie rendered invalid by various members of // TessBaseAPI, including Init, SetImage, End or deleting the TessBaseAPI. // Pointsize is returned in printers points (1/72 inch.) const char *WordFontAttributes(bool *is_bold, bool *is_italic, bool *is_underlined, bool *is_monospace, bool *is_serif, bool *is_smallcaps, int *pointsize, int *font_id) const; // Return the name of the language used to recognize this word. // On error, nullptr. Do not delete this pointer. const char *WordRecognitionLanguage() const; // Return the overall directionality of this word. StrongScriptDirection WordDirection() const; // Returns true if the current word was found in a dictionary. bool WordIsFromDictionary() const; // Returns the number of blanks before the current word. int BlanksBeforeWord() const; // Returns true if the current word is numeric. bool WordIsNumeric() const; // Returns true if the word contains blamer information. bool HasBlamerInfo() const; // Returns the pointer to ParamsTrainingBundle stored in the BlamerBundle // of the current word. const void *GetParamsTrainingBundle() const; // Returns a pointer to the string with blamer information for this word. // Assumes that the word's blamer_bundle is not nullptr. const char *GetBlamerDebug() const; // Returns a pointer to the string with misadaption information for this word. // Assumes that the word's blamer_bundle is not nullptr. const char *GetBlamerMisadaptionDebug() const; // Returns true if a truth string was recorded for the current word. bool HasTruthString() const; // Returns true if the given string is equivalent to the truth string for // the current word. bool EquivalentToTruth(const char *str) const; // Returns a null terminated UTF-8 encoded truth string for the current word. // Use delete [] to free after use. char *WordTruthUTF8Text() const; // Returns a null terminated UTF-8 encoded normalized OCR string for the // current word. Use delete [] to free after use. char *WordNormedUTF8Text() const; // Returns a pointer to serialized choice lattice. // Fills lattice_size with the number of bytes in lattice data. const char *WordLattice(int *lattice_size) const; // ============= Functions that refer to symbols only ============. // Returns true if the current symbol is a superscript. // If iterating at a higher level object than symbols, eg words, then // this will return the attributes of the first symbol in that word. bool SymbolIsSuperscript() const; // Returns true if the current symbol is a subscript. // If iterating at a higher level object than symbols, eg words, then // this will return the attributes of the first symbol in that word. bool SymbolIsSubscript() const; // Returns true if the current symbol is a dropcap. // If iterating at a higher level object than symbols, eg words, then // this will return the attributes of the first symbol in that word. bool SymbolIsDropcap() const; protected: const char *line_separator_; const char *paragraph_separator_; }; // Class to iterate over the classifier choices for a single RIL_SYMBOL. class TESS_API ChoiceIterator { public: // Construction is from a LTRResultIterator that points to the symbol of // interest. The ChoiceIterator allows a one-shot iteration over the // choices for this symbol and after that it is useless. explicit ChoiceIterator(const LTRResultIterator &result_it); ~ChoiceIterator(); // Moves to the next choice for the symbol and returns false if there // are none left. bool Next(); // ============= Accessing data ==============. // Returns the null terminated UTF-8 encoded text string for the current // choice. // NOTE: Unlike LTRResultIterator::GetUTF8Text, the return points to an // internal structure and should NOT be delete[]ed to free after use. const char *GetUTF8Text() const; // Returns the confidence of the current choice depending on the used language // data. If only LSTM traineddata is used the value range is 0.0f - 1.0f. All // choices for one symbol should roughly add up to 1.0f. // If only traineddata of the legacy engine is used, the number should be // interpreted as a percent probability. (0.0f-100.0f) In this case // probabilities won't add up to 100. Each one stands on its own. float Confidence() const; // Returns a vector containing all timesteps, which belong to the currently // selected symbol. A timestep is a vector containing pairs of symbols and // floating point numbers. The number states the probability for the // corresponding symbol. std::vector<std::vector<std::pair<const char *, float>>> *Timesteps() const; private: // clears the remaining spaces out of the results and adapt the probabilities void filterSpaces(); // Pointer to the WERD_RES object owned by the API. WERD_RES *word_res_; // Iterator over the blob choices. BLOB_CHOICE_IT *choice_it_; std::vector<std::pair<const char *, float>> *LSTM_choices_ = nullptr; std::vector<std::pair<const char *, float>>::iterator LSTM_choice_it_; const int *tstep_index_; // regulates the rating granularity double rating_coefficient_; // leading blanks int blanks_before_word_; // true when there is lstm engine related trained data bool oemLSTM_; }; } // namespace tesseract. #endif // TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H_
2301_81045437/tesseract
include/tesseract/ltrresultiterator.h
C++
apache-2.0
10,291
// SPDX-License-Identifier: Apache-2.0 /********************************************************************** * File: ocrclass.h * Description: Class definitions and constants for the OCR API. * Author: Hewlett-Packard Co * * (C) Copyright 1996, Hewlett-Packard Co. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ /********************************************************************** * This file contains typedefs for all the structures used by * the HP OCR interface. * The structures are designed to allow them to be used with any * structure alignment up to 8. **********************************************************************/ #ifndef CCUTIL_OCRCLASS_H_ #define CCUTIL_OCRCLASS_H_ #include <chrono> #include <ctime> namespace tesseract { /********************************************************************** * EANYCODE_CHAR * Description of a single character. The character code is defined by * the character set of the current font. * Output text is sent as an array of these structures. * Spaces and line endings in the output are represented in the * structures of the surrounding characters. They are not directly * represented as characters. * The first character in a word has a positive value of blanks. * Missing information should be set to the defaults in the comments. * If word bounds are known, but not character bounds, then the top and * bottom of each character should be those of the word. The left of the * first and right of the last char in each word should be set. All other * lefts and rights should be set to -1. * If set, the values of right and bottom are left+width and top+height. * Most of the members come directly from the parameters to ocr_append_char. * The formatting member uses the enhancement parameter and combines the * line direction stuff into the top 3 bits. * The coding is 0=RL char, 1=LR char, 2=DR NL, 3=UL NL, 4=DR Para, * 5=UL Para, 6=TB char, 7=BT char. API users do not need to know what * the coding is, only that it is backwards compatible with the previous * version. **********************************************************************/ struct EANYCODE_CHAR { /*single character */ // It should be noted that the format for char_code for version 2.0 and beyond // is UTF8 which means that ASCII characters will come out as one structure // but other characters will be returned in two or more instances of this // structure with a single byte of the UTF8 code in each, but each will have // the same bounding box. Programs which want to handle languages with // different characters sets will need to handle extended characters // appropriately, but *all* code needs to be prepared to receive UTF8 coded // characters for characters such as bullet and fancy quotes. uint16_t char_code; /*character itself */ int16_t left; /*of char (-1) */ int16_t right; /*of char (-1) */ int16_t top; /*of char (-1) */ int16_t bottom; /*of char (-1) */ int16_t font_index; /*what font (0) */ uint8_t confidence; /*0=perfect, 100=reject (0/100) */ uint8_t point_size; /*of char, 72=i inch, (10) */ int8_t blanks; /*no of spaces before this char (1) */ uint8_t formatting; /*char formatting (0) */ }; /********************************************************************** * ETEXT_DESC * Description of the output of the OCR engine. * This structure is used as both a progress monitor and the final * output header, since it needs to be a valid progress monitor while * the OCR engine is storing its output to shared memory. * During progress, all the buffer info is -1. * Progress starts at 0 and increases to 100 during OCR. No other constraint. * Additionally the progress callback contains the bounding box of the word that * is currently being processed. * Every progress callback, the OCR engine must set ocr_alive to 1. * The HP side will set ocr_alive to 0. Repeated failure to reset * to 1 indicates that the OCR engine is dead. * If the cancel function is not null then it is called with the number of * user words found. If it returns true then operation is cancelled. **********************************************************************/ class ETEXT_DESC; using CANCEL_FUNC = bool (*)(void *, int); using PROGRESS_FUNC = bool (*)(int, int, int, int, int); using PROGRESS_FUNC2 = bool (*)(ETEXT_DESC *, int, int, int, int); class ETEXT_DESC { // output header public: int16_t count{0}; /// chars in this buffer(0) int16_t progress{0}; /// percent complete increasing (0-100) /** Progress monitor covers word recognition and it does not cover layout * analysis. * See Ray comment in https://github.com/tesseract-ocr/tesseract/pull/27 */ int8_t more_to_come{0}; /// true if not last volatile int8_t ocr_alive{0}; /// ocr sets to 1, HP 0 int8_t err_code{0}; /// for errcode use CANCEL_FUNC cancel{nullptr}; /// returns true to cancel PROGRESS_FUNC progress_callback{ nullptr}; /// called whenever progress increases PROGRESS_FUNC2 progress_callback2; /// monitor-aware progress callback void *cancel_this{nullptr}; /// this or other data for cancel std::chrono::steady_clock::time_point end_time; /// Time to stop. Expected to be set only /// by call to set_deadline_msecs(). EANYCODE_CHAR text[1]{}; /// character data ETEXT_DESC() : progress_callback2(&default_progress_func) { end_time = std::chrono::time_point<std::chrono::steady_clock, std::chrono::milliseconds>(); } // Sets the end time to be deadline_msecs milliseconds from now. void set_deadline_msecs(int32_t deadline_msecs) { if (deadline_msecs > 0) { end_time = std::chrono::steady_clock::now() + std::chrono::milliseconds(deadline_msecs); } } // Returns false if we've not passed the end_time, or have not set a deadline. bool deadline_exceeded() const { if (end_time.time_since_epoch() == std::chrono::steady_clock::duration::zero()) { return false; } auto now = std::chrono::steady_clock::now(); return (now > end_time); } private: static bool default_progress_func(ETEXT_DESC *ths, int left, int right, int top, int bottom) { if (ths->progress_callback != nullptr) { return (*(ths->progress_callback))(ths->progress, left, right, top, bottom); } return true; } }; } // namespace tesseract #endif // CCUTIL_OCRCLASS_H_
2301_81045437/tesseract
include/tesseract/ocrclass.h
C++
apache-2.0
7,176
// SPDX-License-Identifier: Apache-2.0 // File: osdetect.h // Description: Orientation and script detection. // Author: Samuel Charron // Ranjith Unnikrishnan // // (C) Copyright 2008, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TESSERACT_CCMAIN_OSDETECT_H_ #define TESSERACT_CCMAIN_OSDETECT_H_ #include "export.h" // for TESS_API #include <vector> // for std::vector namespace tesseract { class BLOBNBOX; class BLOBNBOX_CLIST; class BLOB_CHOICE_LIST; class TO_BLOCK_LIST; class UNICHARSET; class Tesseract; // Max number of scripts in ICU + "NULL" + Japanese and Korean + Fraktur const int kMaxNumberOfScripts = 116 + 1 + 2 + 1; struct OSBestResult { OSBestResult() : orientation_id(0), script_id(0), sconfidence(0.0), oconfidence(0.0) {} int orientation_id; int script_id; float sconfidence; float oconfidence; }; struct OSResults { OSResults() : unicharset(nullptr) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < kMaxNumberOfScripts; ++j) { scripts_na[i][j] = 0; } orientations[i] = 0; } } void update_best_orientation(); // Set the estimate of the orientation to the given id. void set_best_orientation(int orientation_id); // Update/Compute the best estimate of the script assuming the given // orientation id. void update_best_script(int orientation_id); // Return the index of the script with the highest score for this orientation. TESS_API int get_best_script(int orientation_id) const; // Accumulate scores with given OSResults instance and update the best script. void accumulate(const OSResults &osr); // Print statistics. void print_scores(void) const; void print_scores(int orientation_id) const; // Array holding scores for each orientation id [0,3]. // Orientation ids [0..3] map to [0, 270, 180, 90] degree orientations of the // page respectively, where the values refer to the amount of clockwise // rotation to be applied to the page for the text to be upright and readable. float orientations[4]; // Script confidence scores for each of 4 possible orientations. float scripts_na[4][kMaxNumberOfScripts]; UNICHARSET *unicharset; OSBestResult best_result; }; class OrientationDetector { public: OrientationDetector(const std::vector<int> *allowed_scripts, OSResults *results); bool detect_blob(BLOB_CHOICE_LIST *scores); int get_orientation(); private: OSResults *osr_; const std::vector<int> *allowed_scripts_; }; class ScriptDetector { public: ScriptDetector(const std::vector<int> *allowed_scripts, OSResults *osr, tesseract::Tesseract *tess); void detect_blob(BLOB_CHOICE_LIST *scores); bool must_stop(int orientation) const; private: OSResults *osr_; static const char *korean_script_; static const char *japanese_script_; static const char *fraktur_script_; int korean_id_; int japanese_id_; int katakana_id_; int hiragana_id_; int han_id_; int hangul_id_; int latin_id_; int fraktur_id_; tesseract::Tesseract *tess_; const std::vector<int> *allowed_scripts_; }; int orientation_and_script_detection(const char *filename, OSResults *, tesseract::Tesseract *); int os_detect(TO_BLOCK_LIST *port_blocks, OSResults *osr, tesseract::Tesseract *tess); int os_detect_blobs(const std::vector<int> *allowed_scripts, BLOBNBOX_CLIST *blob_list, OSResults *osr, tesseract::Tesseract *tess); bool os_detect_blob(BLOBNBOX *bbox, OrientationDetector *o, ScriptDetector *s, OSResults *, tesseract::Tesseract *tess); // Helper method to convert an orientation index to its value in degrees. // The value represents the amount of clockwise rotation in degrees that must be // applied for the text to be upright (readable). TESS_API int OrientationIdToValue(const int &id); } // namespace tesseract #endif // TESSERACT_CCMAIN_OSDETECT_H_
2301_81045437/tesseract
include/tesseract/osdetect.h
C++
apache-2.0
4,511
// SPDX-License-Identifier: Apache-2.0 // File: pageiterator.h // Description: Iterator for tesseract page structure that avoids using // tesseract internal data structures. // Author: Ray Smith // // (C) Copyright 2010, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TESSERACT_CCMAIN_PAGEITERATOR_H_ #define TESSERACT_CCMAIN_PAGEITERATOR_H_ #include "export.h" #include "publictypes.h" struct Pix; struct Pta; namespace tesseract { struct BlamerBundle; class C_BLOB_IT; class PAGE_RES; class PAGE_RES_IT; class WERD; class Tesseract; /** * Class to iterate over tesseract page structure, providing access to all * levels of the page hierarchy, without including any tesseract headers or * having to handle any tesseract structures. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. * See tesseract/publictypes.h for the definition of PageIteratorLevel. * See also ResultIterator, derived from PageIterator, which adds in the * ability to access OCR output with text-specific methods. */ class TESS_API PageIterator { public: /** * page_res and tesseract come directly from the BaseAPI. * The rectangle parameters are copied indirectly from the Thresholder, * via the BaseAPI. They represent the coordinates of some rectangle in an * original image (in top-left-origin coordinates) and therefore the top-left * needs to be added to any output boxes in order to specify coordinates * in the original image. See TessBaseAPI::SetRectangle. * The scale and scaled_yres are in case the Thresholder scaled the image * rectangle prior to thresholding. Any coordinates in tesseract's image * must be divided by scale before adding (rect_left, rect_top). * The scaled_yres indicates the effective resolution of the binary image * that tesseract has been given by the Thresholder. * After the constructor, Begin has already been called. */ PageIterator(PAGE_RES *page_res, Tesseract *tesseract, int scale, int scaled_yres, int rect_left, int rect_top, int rect_width, int rect_height); virtual ~PageIterator(); /** * Page/ResultIterators may be copied! This makes it possible to iterate over * all the objects at a lower level, while maintaining an iterator to * objects at a higher level. These constructors DO NOT CALL Begin, so * iterations will continue from the location of src. */ PageIterator(const PageIterator &src); const PageIterator &operator=(const PageIterator &src); /** Are we positioned at the same location as other? */ bool PositionedAtSameWord(const PAGE_RES_IT *other) const; // ============= Moving around within the page ============. /** * Moves the iterator to point to the start of the page to begin an * iteration. */ virtual void Begin(); /** * Moves the iterator to the beginning of the paragraph. * This class implements this functionality by moving it to the zero indexed * blob of the first (leftmost) word on the first row of the paragraph. */ virtual void RestartParagraph(); /** * Return whether this iterator points anywhere in the first textline of a * paragraph. */ bool IsWithinFirstTextlineOfParagraph() const; /** * Moves the iterator to the beginning of the text line. * This class implements this functionality by moving it to the zero indexed * blob of the first (leftmost) word of the row. */ virtual void RestartRow(); /** * Moves to the start of the next object at the given level in the * page hierarchy, and returns false if the end of the page was reached. * NOTE that RIL_SYMBOL will skip non-text blocks, but all other * PageIteratorLevel level values will visit each non-text block once. * Think of non text blocks as containing a single para, with a single line, * with a single imaginary word. * Calls to Next with different levels may be freely intermixed. * This function iterates words in right-to-left scripts correctly, if * the appropriate language has been loaded into Tesseract. */ virtual bool Next(PageIteratorLevel level); /** * Returns true if the iterator is at the start of an object at the given * level. * * For instance, suppose an iterator it is pointed to the first symbol of the * first word of the third line of the second paragraph of the first block in * a page, then: * it.IsAtBeginningOf(RIL_BLOCK) = false * it.IsAtBeginningOf(RIL_PARA) = false * it.IsAtBeginningOf(RIL_TEXTLINE) = true * it.IsAtBeginningOf(RIL_WORD) = true * it.IsAtBeginningOf(RIL_SYMBOL) = true */ virtual bool IsAtBeginningOf(PageIteratorLevel level) const; /** * Returns whether the iterator is positioned at the last element in a * given level. (e.g. the last word in a line, the last line in a block) * * Here's some two-paragraph example * text. It starts off innocuously * enough but quickly turns bizarre. * The author inserts a cornucopia * of words to guard against confused * references. * * Now take an iterator it pointed to the start of "bizarre." * it.IsAtFinalElement(RIL_PARA, RIL_SYMBOL) = false * it.IsAtFinalElement(RIL_PARA, RIL_WORD) = true * it.IsAtFinalElement(RIL_BLOCK, RIL_WORD) = false */ virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const; /** * Returns whether this iterator is positioned * before other: -1 * equal to other: 0 * after other: 1 */ int Cmp(const PageIterator &other) const; // ============= Accessing data ==============. // Coordinate system: // Integer coordinates are at the cracks between the pixels. // The top-left corner of the top-left pixel in the image is at (0,0). // The bottom-right corner of the bottom-right pixel in the image is at // (width, height). // Every bounding box goes from the top-left of the top-left contained // pixel to the bottom-right of the bottom-right contained pixel, so // the bounding box of the single top-left pixel in the image is: // (0,0)->(1,1). // If an image rectangle has been set in the API, then returned coordinates // relate to the original (full) image, rather than the rectangle. /** * Controls what to include in a bounding box. Bounding boxes of all levels * between RIL_WORD and RIL_BLOCK can include or exclude potential diacritics. * Between layout analysis and recognition, it isn't known where all * diacritics belong, so this control is used to include or exclude some * diacritics that are above or below the main body of the word. In most cases * where the placement is obvious, and after recognition, it doesn't make as * much difference, as the diacritics will already be included in the word. */ void SetBoundingBoxComponents(bool include_upper_dots, bool include_lower_dots) { include_upper_dots_ = include_upper_dots; include_lower_dots_ = include_lower_dots; } /** * Returns the bounding rectangle of the current object at the given level. * See comment on coordinate system above. * Returns false if there is no such object at the current position. * The returned bounding box is guaranteed to match the size and position * of the image returned by GetBinaryImage, but may clip foreground pixels * from a grey image. The padding argument to GetImage can be used to expand * the image to include more foreground pixels. See GetImage below. */ bool BoundingBox(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const; bool BoundingBox(PageIteratorLevel level, int padding, int *left, int *top, int *right, int *bottom) const; /** * Returns the bounding rectangle of the object in a coordinate system of the * working image rectangle having its origin at (rect_left_, rect_top_) with * respect to the original image and is scaled by a factor scale_. */ bool BoundingBoxInternal(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const; /** Returns whether there is no object of a given level. */ bool Empty(PageIteratorLevel level) const; /** * Returns the type of the current block. * See tesseract/publictypes.h for PolyBlockType. */ PolyBlockType BlockType() const; /** * Returns the polygon outline of the current block. The returned Pta must * be ptaDestroy-ed after use. Note that the returned Pta lists the vertices * of the polygon, and the last edge is the line segment between the last * point and the first point. nullptr will be returned if the iterator is * at the end of the document or layout analysis was not used. */ Pta *BlockPolygon() const; /** * Returns a binary image of the current object at the given level. * The position and size match the return from BoundingBoxInternal, and so * this could be upscaled with respect to the original input image. * Use pixDestroy to delete the image after use. */ Pix *GetBinaryImage(PageIteratorLevel level) const; /** * Returns an image of the current object at the given level in greyscale * if available in the input. To guarantee a binary image use BinaryImage. * NOTE that in order to give the best possible image, the bounds are * expanded slightly over the binary connected component, by the supplied * padding, so the top-left position of the returned image is returned * in (left,top). These will most likely not match the coordinates * returned by BoundingBox. * If you do not supply an original image, you will get a binary one. * Use pixDestroy to delete the image after use. */ Pix *GetImage(PageIteratorLevel level, int padding, Pix *original_img, int *left, int *top) const; /** * Returns the baseline of the current object at the given level. * The baseline is the line that passes through (x1, y1) and (x2, y2). * WARNING: with vertical text, baselines may be vertical! * Returns false if there is no baseline at the current position. */ bool Baseline(PageIteratorLevel level, int *x1, int *y1, int *x2, int *y2) const; // Returns the attributes of the current row. void RowAttributes(float *row_height, float *descenders, float *ascenders) const; /** * Returns orientation for the block the iterator points to. * orientation, writing_direction, textline_order: see publictypes.h * deskew_angle: after rotating the block so the text orientation is * upright, how many radians does one have to rotate the * block anti-clockwise for it to be level? * -Pi/4 <= deskew_angle <= Pi/4 */ void Orientation(tesseract::Orientation *orientation, tesseract::WritingDirection *writing_direction, tesseract::TextlineOrder *textline_order, float *deskew_angle) const; /** * Returns information about the current paragraph, if available. * * justification - * LEFT if ragged right, or fully justified and script is left-to-right. * RIGHT if ragged left, or fully justified and script is right-to-left. * unknown if it looks like source code or we have very few lines. * is_list_item - * true if we believe this is a member of an ordered or unordered list. * is_crown - * true if the first line of the paragraph is aligned with the other * lines of the paragraph even though subsequent paragraphs have first * line indents. This typically indicates that this is the continuation * of a previous paragraph or that it is the very first paragraph in * the chapter. * first_line_indent - * For LEFT aligned paragraphs, the first text line of paragraphs of * this kind are indented this many pixels from the left edge of the * rest of the paragraph. * for RIGHT aligned paragraphs, the first text line of paragraphs of * this kind are indented this many pixels from the right edge of the * rest of the paragraph. * NOTE 1: This value may be negative. * NOTE 2: if *is_crown == true, the first line of this paragraph is * actually flush, and first_line_indent is set to the "common" * first_line_indent for subsequent paragraphs in this block * of text. */ void ParagraphInfo(tesseract::ParagraphJustification *justification, bool *is_list_item, bool *is_crown, int *first_line_indent) const; // If the current WERD_RES (it_->word()) is not nullptr, sets the BlamerBundle // of the current word to the given pointer (takes ownership of the pointer) // and returns true. // Can only be used when iterating on the word level. bool SetWordBlamerBundle(BlamerBundle *blamer_bundle); protected: /** * Sets up the internal data for iterating the blobs of a new word, then * moves the iterator to the given offset. */ void BeginWord(int offset); /** Pointer to the page_res owned by the API. */ PAGE_RES *page_res_; /** Pointer to the Tesseract object owned by the API. */ Tesseract *tesseract_; /** * The iterator to the page_res_. Owned by this ResultIterator. * A pointer just to avoid dragging in Tesseract includes. */ PAGE_RES_IT *it_; /** * The current input WERD being iterated. If there is an output from OCR, * then word_ is nullptr. Owned by the API */ WERD *word_; /** The length of the current word_. */ int word_length_; /** The current blob index within the word. */ int blob_index_; /** * Iterator to the blobs within the word. If nullptr, then we are iterating * OCR results in the box_word. * Owned by this ResultIterator. */ C_BLOB_IT *cblob_it_; /** Control over what to include in bounding boxes. */ bool include_upper_dots_; bool include_lower_dots_; /** Parameters saved from the Thresholder. Needed to rebuild coordinates.*/ int scale_; int scaled_yres_; int rect_left_; int rect_top_; int rect_width_; int rect_height_; }; } // namespace tesseract. #endif // TESSERACT_CCMAIN_PAGEITERATOR_H_
2301_81045437/tesseract
include/tesseract/pageiterator.h
C++
apache-2.0
15,156
// SPDX-License-Identifier: Apache-2.0 // File: publictypes.h // Description: Types used in both the API and internally // Author: Ray Smith // // (C) Copyright 2010, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TESSERACT_CCSTRUCT_PUBLICTYPES_H_ #define TESSERACT_CCSTRUCT_PUBLICTYPES_H_ namespace tesseract { // This file contains types that are used both by the API and internally // to Tesseract. In order to decouple the API from Tesseract and prevent cyclic // dependencies, THIS FILE SHOULD NOT DEPEND ON ANY OTHER PART OF TESSERACT. // Restated: It is OK for low-level Tesseract files to include publictypes.h, // but not for the low-level tesseract code to include top-level API code. // This file should not use other Tesseract types, as that would drag // their includes into the API-level. /** Number of printers' points in an inch. The unit of the pointsize return. */ constexpr int kPointsPerInch = 72; /** * Minimum believable resolution. Used as a default if there is no other * information, as it is safer to under-estimate than over-estimate. */ constexpr int kMinCredibleResolution = 70; /** Maximum believable resolution. */ constexpr int kMaxCredibleResolution = 2400; /** * Ratio between median blob size and likely resolution. Used to estimate * resolution when none is provided. This is basically 1/usual text size in * inches. */ constexpr int kResolutionEstimationFactor = 10; /** * Possible types for a POLY_BLOCK or ColPartition. * Must be kept in sync with kPBColors in polyblk.cpp and PTIs*Type functions * below, as well as kPolyBlockNames in layout_test.cc. * Used extensively by ColPartition, and POLY_BLOCK. */ enum PolyBlockType { PT_UNKNOWN, // Type is not yet known. Keep as the first element. PT_FLOWING_TEXT, // Text that lives inside a column. PT_HEADING_TEXT, // Text that spans more than one column. PT_PULLOUT_TEXT, // Text that is in a cross-column pull-out region. PT_EQUATION, // Partition belonging to an equation region. PT_INLINE_EQUATION, // Partition has inline equation. PT_TABLE, // Partition belonging to a table region. PT_VERTICAL_TEXT, // Text-line runs vertically. PT_CAPTION_TEXT, // Text that belongs to an image. PT_FLOWING_IMAGE, // Image that lives inside a column. PT_HEADING_IMAGE, // Image that spans more than one column. PT_PULLOUT_IMAGE, // Image that is in a cross-column pull-out region. PT_HORZ_LINE, // Horizontal Line. PT_VERT_LINE, // Vertical Line. PT_NOISE, // Lies outside of any column. PT_COUNT }; /** Returns true if PolyBlockType is of line type */ inline bool PTIsLineType(PolyBlockType type) { return type == PT_HORZ_LINE || type == PT_VERT_LINE; } /** Returns true if PolyBlockType is of image type */ inline bool PTIsImageType(PolyBlockType type) { return type == PT_FLOWING_IMAGE || type == PT_HEADING_IMAGE || type == PT_PULLOUT_IMAGE; } /** Returns true if PolyBlockType is of text type */ inline bool PTIsTextType(PolyBlockType type) { return type == PT_FLOWING_TEXT || type == PT_HEADING_TEXT || type == PT_PULLOUT_TEXT || type == PT_TABLE || type == PT_VERTICAL_TEXT || type == PT_CAPTION_TEXT || type == PT_INLINE_EQUATION; } // Returns true if PolyBlockType is of pullout(inter-column) type inline bool PTIsPulloutType(PolyBlockType type) { return type == PT_PULLOUT_IMAGE || type == PT_PULLOUT_TEXT; } /** * +------------------+ Orientation Example: * | 1 Aaaa Aaaa Aaaa | ==================== * | Aaa aa aaa aa | To left is a diagram of some (1) English and * | aaaaaa A aa aaa. | (2) Chinese text and a (3) photo credit. * | 2 | * | ####### c c C | Upright Latin characters are represented as A and a. * | ####### c c c | '<' represents a latin character rotated * | < ####### c c c | anti-clockwise 90 degrees. * | < ####### c c | * | < ####### . c | Upright Chinese characters are represented C and c. * | 3 ####### c | * +------------------+ NOTA BENE: enum values here should match goodoc.proto * If you orient your head so that "up" aligns with Orientation, * then the characters will appear "right side up" and readable. * * In the example above, both the English and Chinese paragraphs are oriented * so their "up" is the top of the page (page up). The photo credit is read * with one's head turned leftward ("up" is to page left). * * The values of this enum match the convention of Tesseract's osdetect.h */ enum Orientation { ORIENTATION_PAGE_UP = 0, ORIENTATION_PAGE_RIGHT = 1, ORIENTATION_PAGE_DOWN = 2, ORIENTATION_PAGE_LEFT = 3, }; /** * The grapheme clusters within a line of text are laid out logically * in this direction, judged when looking at the text line rotated so that * its Orientation is "page up". * * For English text, the writing direction is left-to-right. For the * Chinese text in the above example, the writing direction is top-to-bottom. */ enum WritingDirection { WRITING_DIRECTION_LEFT_TO_RIGHT = 0, WRITING_DIRECTION_RIGHT_TO_LEFT = 1, WRITING_DIRECTION_TOP_TO_BOTTOM = 2, }; /** * The text lines are read in the given sequence. * * In English, the order is top-to-bottom. * In Chinese, vertical text lines are read right-to-left. Mongolian is * written in vertical columns top to bottom like Chinese, but the lines * order left-to right. * * Note that only some combinations make sense. For example, * WRITING_DIRECTION_LEFT_TO_RIGHT implies TEXTLINE_ORDER_TOP_TO_BOTTOM */ enum TextlineOrder { TEXTLINE_ORDER_LEFT_TO_RIGHT = 0, TEXTLINE_ORDER_RIGHT_TO_LEFT = 1, TEXTLINE_ORDER_TOP_TO_BOTTOM = 2, }; /** * Possible modes for page layout analysis. These *must* be kept in order * of decreasing amount of layout analysis to be done, except for OSD_ONLY, * so that the inequality test macros below work. */ enum PageSegMode { PSM_OSD_ONLY = 0, ///< Orientation and script detection only. PSM_AUTO_OSD = 1, ///< Automatic page segmentation with orientation and ///< script detection. (OSD) PSM_AUTO_ONLY = 2, ///< Automatic page segmentation, but no OSD, or OCR. PSM_AUTO = 3, ///< Fully automatic page segmentation, but no OSD. PSM_SINGLE_COLUMN = 4, ///< Assume a single column of text of variable sizes. PSM_SINGLE_BLOCK_VERT_TEXT = 5, ///< Assume a single uniform block of ///< vertically aligned text. PSM_SINGLE_BLOCK = 6, ///< Assume a single uniform block of text. (Default.) PSM_SINGLE_LINE = 7, ///< Treat the image as a single text line. PSM_SINGLE_WORD = 8, ///< Treat the image as a single word. PSM_CIRCLE_WORD = 9, ///< Treat the image as a single word in a circle. PSM_SINGLE_CHAR = 10, ///< Treat the image as a single character. PSM_SPARSE_TEXT = 11, ///< Find as much text as possible in no particular order. PSM_SPARSE_TEXT_OSD = 12, ///< Sparse text with orientation and script det. PSM_RAW_LINE = 13, ///< Treat the image as a single text line, bypassing ///< hacks that are Tesseract-specific. PSM_COUNT ///< Number of enum entries. }; /** * Inline functions that act on a PageSegMode to determine whether components of * layout analysis are enabled. * *Depend critically on the order of elements of PageSegMode.* * NOTE that arg is an int for compatibility with INT_PARAM. */ inline bool PSM_OSD_ENABLED(int pageseg_mode) { return pageseg_mode <= PSM_AUTO_OSD || pageseg_mode == PSM_SPARSE_TEXT_OSD; } inline bool PSM_ORIENTATION_ENABLED(int pageseg_mode) { return pageseg_mode <= PSM_AUTO || pageseg_mode == PSM_SPARSE_TEXT_OSD; } inline bool PSM_COL_FIND_ENABLED(int pageseg_mode) { return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_AUTO; } inline bool PSM_SPARSE(int pageseg_mode) { return pageseg_mode == PSM_SPARSE_TEXT || pageseg_mode == PSM_SPARSE_TEXT_OSD; } inline bool PSM_BLOCK_FIND_ENABLED(int pageseg_mode) { return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_COLUMN; } inline bool PSM_LINE_FIND_ENABLED(int pageseg_mode) { return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_BLOCK; } inline bool PSM_WORD_FIND_ENABLED(int pageseg_mode) { return (pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_LINE) || pageseg_mode == PSM_SPARSE_TEXT || pageseg_mode == PSM_SPARSE_TEXT_OSD; } /** * enum of the elements of the page hierarchy, used in ResultIterator * to provide functions that operate on each level without having to * have 5x as many functions. */ enum PageIteratorLevel { RIL_BLOCK, // Block of text/image/separator line. RIL_PARA, // Paragraph within a block. RIL_TEXTLINE, // Line within a paragraph. RIL_WORD, // Word within a textline. RIL_SYMBOL // Symbol/character within a word. }; /** * JUSTIFICATION_UNKNOWN * The alignment is not clearly one of the other options. This could happen * for example if there are only one or two lines of text or the text looks * like source code or poetry. * * NOTA BENE: Fully justified paragraphs (text aligned to both left and right * margins) are marked by Tesseract with JUSTIFICATION_LEFT if their text * is written with a left-to-right script and with JUSTIFICATION_RIGHT if * their text is written in a right-to-left script. * * Interpretation for text read in vertical lines: * "Left" is wherever the starting reading position is. * * JUSTIFICATION_LEFT * Each line, except possibly the first, is flush to the same left tab stop. * * JUSTIFICATION_CENTER * The text lines of the paragraph are centered about a line going * down through their middle of the text lines. * * JUSTIFICATION_RIGHT * Each line, except possibly the first, is flush to the same right tab stop. */ enum ParagraphJustification { JUSTIFICATION_UNKNOWN, JUSTIFICATION_LEFT, JUSTIFICATION_CENTER, JUSTIFICATION_RIGHT, }; /** * When Tesseract/Cube is initialized we can choose to instantiate/load/run * only the Tesseract part, only the Cube part or both along with the combiner. * The preference of which engine to use is stored in tessedit_ocr_engine_mode. * * ATTENTION: When modifying this enum, please make sure to make the * appropriate changes to all the enums mirroring it (e.g. OCREngine in * cityblock/workflow/detection/detection_storage.proto). Such enums will * mention the connection to OcrEngineMode in the comments. */ enum OcrEngineMode { OEM_TESSERACT_ONLY, // Run Tesseract only - fastest; deprecated OEM_LSTM_ONLY, // Run just the LSTM line recognizer. OEM_TESSERACT_LSTM_COMBINED, // Run the LSTM recognizer, but allow fallback // to Tesseract when things get difficult. // deprecated OEM_DEFAULT, // Specify this mode when calling init_*(), // to indicate that any of the above modes // should be automatically inferred from the // variables in the language-specific config, // command-line configs, or if not specified // in any of the above should be set to the // default OEM_TESSERACT_ONLY. OEM_COUNT // Number of OEMs }; } // namespace tesseract. #endif // TESSERACT_CCSTRUCT_PUBLICTYPES_H_
2301_81045437/tesseract
include/tesseract/publictypes.h
C++
apache-2.0
12,068
// SPDX-License-Identifier: Apache-2.0 // File: renderer.h // Description: Rendering interface to inject into TessBaseAPI // // (C) Copyright 2011, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TESSERACT_API_RENDERER_H_ #define TESSERACT_API_RENDERER_H_ #include "export.h" // To avoid collision with other typenames include the ABSOLUTE MINIMUM // complexity of includes here. Use forward declarations wherever possible // and hide includes of complex types in baseapi.cpp. #include <cstdint> #include <string> // for std::string #include <vector> // for std::vector struct Pix; namespace tesseract { class TessBaseAPI; /** * Interface for rendering tesseract results into a document, such as text, * HOCR or pdf. This class is abstract. Specific classes handle individual * formats. This interface is then used to inject the renderer class into * tesseract when processing images. * * For simplicity implementing this with tesseract version 3.01, * the renderer contains document state that is cleared from document * to document just as the TessBaseAPI is. This way the base API can just * delegate its rendering functionality to injected renderers, and the * renderers can manage the associated state needed for the specific formats * in addition to the heuristics for producing it. */ class TESS_API TessResultRenderer { public: virtual ~TessResultRenderer(); // Takes ownership of pointer so must be new'd instance. // Renderers aren't ordered, but appends the sequences of next parameter // and existing next(). The renderers should be unique across both lists. void insert(TessResultRenderer *next); // Returns the next renderer or nullptr. TessResultRenderer *next() { return next_; } /** * Starts a new document with the given title. * This clears the contents of the output data. * Title should use UTF-8 encoding. */ bool BeginDocument(const char *title); /** * Adds the recognized text from the source image to the current document. * Invalid if BeginDocument not yet called. * * Note that this API is a bit weird but is designed to fit into the * current TessBaseAPI implementation where the api has lots of state * information that we might want to add in. */ bool AddImage(TessBaseAPI *api); /** * Finishes the document and finalizes the output data * Invalid if BeginDocument not yet called. */ bool EndDocument(); const char *file_extension() const { return file_extension_; } const char *title() const { return title_.c_str(); } // Is everything fine? Otherwise something went wrong. bool happy() const { return happy_; } /** * Returns the index of the last image given to AddImage * (i.e. images are incremented whether the image succeeded or not) * * This is always defined. It means either the number of the * current image, the last image ended, or in the completed document * depending on when in the document lifecycle you are looking at it. * Will return -1 if a document was never started. */ int imagenum() const { return imagenum_; } protected: /** * Called by concrete classes. * * outputbase is the name of the output file excluding * extension. For example, "/path/to/chocolate-chip-cookie-recipe" * * extension indicates the file extension to be used for output * files. For example "pdf" will produce a .pdf file, and "hocr" * will produce .hocr files. */ TessResultRenderer(const char *outputbase, const char *extension); // Hook for specialized handling in BeginDocument() virtual bool BeginDocumentHandler(); // This must be overridden to render the OCR'd results virtual bool AddImageHandler(TessBaseAPI *api) = 0; // Hook for specialized handling in EndDocument() virtual bool EndDocumentHandler(); // Renderers can call this to append '\0' terminated strings into // the output string returned by GetOutput. // This method will grow the output buffer if needed. void AppendString(const char *s); // Renderers can call this to append binary byte sequences into // the output string returned by GetOutput. Note that s is not necessarily // '\0' terminated (and can contain '\0' within it). // This method will grow the output buffer if needed. void AppendData(const char *s, int len); template <typename T> auto AppendData(T &&d) { AppendData(d.data(), d.size()); return d.size(); } private: TessResultRenderer *next_; // Can link multiple renderers together FILE *fout_; // output file pointer const char *file_extension_; // standard extension for generated output std::string title_; // title of document being rendered int imagenum_; // index of last image added bool happy_; // I get grumpy when the disk fills up, etc. }; /** * Renders tesseract output into a plain UTF-8 text string */ class TESS_API TessTextRenderer : public TessResultRenderer { public: explicit TessTextRenderer(const char *outputbase); protected: bool AddImageHandler(TessBaseAPI *api) override; }; /** * Renders tesseract output into an hocr text string */ class TESS_API TessHOcrRenderer : public TessResultRenderer { public: explicit TessHOcrRenderer(const char *outputbase, bool font_info); explicit TessHOcrRenderer(const char *outputbase); protected: bool BeginDocumentHandler() override; bool AddImageHandler(TessBaseAPI *api) override; bool EndDocumentHandler() override; private: bool font_info_; // whether to print font information }; /** * Renders tesseract output into an alto text string */ class TESS_API TessAltoRenderer : public TessResultRenderer { public: explicit TessAltoRenderer(const char *outputbase); protected: bool BeginDocumentHandler() override; bool AddImageHandler(TessBaseAPI *api) override; bool EndDocumentHandler() override; private: bool begin_document; }; /** * Renders Tesseract output into a PAGE XML text string */ class TESS_API TessPAGERenderer : public TessResultRenderer { public: explicit TessPAGERenderer(const char *outputbase); protected: bool BeginDocumentHandler() override; bool AddImageHandler(TessBaseAPI *api) override; bool EndDocumentHandler() override; private: bool begin_document; }; /** * Renders Tesseract output into a TSV string */ class TESS_API TessTsvRenderer : public TessResultRenderer { public: explicit TessTsvRenderer(const char *outputbase, bool font_info); explicit TessTsvRenderer(const char *outputbase); protected: bool BeginDocumentHandler() override; bool AddImageHandler(TessBaseAPI *api) override; bool EndDocumentHandler() override; private: bool font_info_; // whether to print font information }; /** * Renders tesseract output into searchable PDF */ class TESS_API TessPDFRenderer : public TessResultRenderer { public: // datadir is the location of the TESSDATA. We need it because // we load a custom PDF font from this location. TessPDFRenderer(const char *outputbase, const char *datadir, bool textonly = false); protected: bool BeginDocumentHandler() override; bool AddImageHandler(TessBaseAPI *api) override; bool EndDocumentHandler() override; private: // We don't want to have every image in memory at once, // so we store some metadata as we go along producing // PDFs one page at a time. At the end, that metadata is // used to make everything that isn't easily handled in a // streaming fashion. long int obj_; // counter for PDF objects std::vector<uint64_t> offsets_; // offset of every PDF object in bytes std::vector<long int> pages_; // object number for every /Page object std::string datadir_; // where to find the custom font bool textonly_; // skip images if set // Bookkeeping only. DIY = Do It Yourself. void AppendPDFObjectDIY(size_t objectsize); // Bookkeeping + emit data. void AppendPDFObject(const char *data); // Create the /Contents object for an entire page. char *GetPDFTextObjects(TessBaseAPI *api, double width, double height); // Turn an image into a PDF object. Only transcode if we have to. static bool imageToPDFObj(Pix *pix, const char *filename, long int objnum, char **pdf_object, long int *pdf_object_size, int jpg_quality); }; /** * Renders tesseract output into a plain UTF-8 text string */ class TESS_API TessUnlvRenderer : public TessResultRenderer { public: explicit TessUnlvRenderer(const char *outputbase); protected: bool AddImageHandler(TessBaseAPI *api) override; }; /** * Renders tesseract output into a plain UTF-8 text string for LSTMBox */ class TESS_API TessLSTMBoxRenderer : public TessResultRenderer { public: explicit TessLSTMBoxRenderer(const char *outputbase); protected: bool AddImageHandler(TessBaseAPI *api) override; }; /** * Renders tesseract output into a plain UTF-8 text string */ class TESS_API TessBoxTextRenderer : public TessResultRenderer { public: explicit TessBoxTextRenderer(const char *outputbase); protected: bool AddImageHandler(TessBaseAPI *api) override; }; /** * Renders tesseract output into a plain UTF-8 text string in WordStr format */ class TESS_API TessWordStrBoxRenderer : public TessResultRenderer { public: explicit TessWordStrBoxRenderer(const char *outputbase); protected: bool AddImageHandler(TessBaseAPI *api) override; }; #ifndef DISABLED_LEGACY_ENGINE /** * Renders tesseract output into an osd text string */ class TESS_API TessOsdRenderer : public TessResultRenderer { public: explicit TessOsdRenderer(const char *outputbase); protected: bool AddImageHandler(TessBaseAPI *api) override; }; #endif // ndef DISABLED_LEGACY_ENGINE } // namespace tesseract. #endif // TESSERACT_API_RENDERER_H_
2301_81045437/tesseract
include/tesseract/renderer.h
C++
apache-2.0
10,417
// SPDX-License-Identifier: Apache-2.0 // File: resultiterator.h // Description: Iterator for tesseract results that is capable of // iterating in proper reading order over Bi Directional // (e.g. mixed Hebrew and English) text. // Author: David Eger // // (C) Copyright 2011, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TESSERACT_CCMAIN_RESULT_ITERATOR_H_ #define TESSERACT_CCMAIN_RESULT_ITERATOR_H_ #include "export.h" // for TESS_API, TESS_LOCAL #include "ltrresultiterator.h" // for LTRResultIterator #include "publictypes.h" // for PageIteratorLevel #include "unichar.h" // for StrongScriptDirection #include <set> // for std::pair #include <vector> // for std::vector namespace tesseract { class TESS_API ResultIterator : public LTRResultIterator { public: static ResultIterator *StartOfParagraph(const LTRResultIterator &resit); /** * ResultIterator is copy constructible! * The default copy constructor works just fine for us. */ ~ResultIterator() override = default; // ============= Moving around within the page ============. /** * Moves the iterator to point to the start of the page to begin * an iteration. */ void Begin() override; /** * Moves to the start of the next object at the given level in the * page hierarchy in the appropriate reading order and returns false if * the end of the page was reached. * NOTE that RIL_SYMBOL will skip non-text blocks, but all other * PageIteratorLevel level values will visit each non-text block once. * Think of non text blocks as containing a single para, with a single line, * with a single imaginary word. * Calls to Next with different levels may be freely intermixed. * This function iterates words in right-to-left scripts correctly, if * the appropriate language has been loaded into Tesseract. */ bool Next(PageIteratorLevel level) override; /** * IsAtBeginningOf() returns whether we're at the logical beginning of the * given level. (as opposed to ResultIterator's left-to-right top-to-bottom * order). Otherwise, this acts the same as PageIterator::IsAtBeginningOf(). * For a full description, see pageiterator.h */ bool IsAtBeginningOf(PageIteratorLevel level) const override; /** * Implement PageIterator's IsAtFinalElement correctly in a BiDi context. * For instance, IsAtFinalElement(RIL_PARA, RIL_WORD) returns whether we * point at the last word in a paragraph. See PageIterator for full comment. */ bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const override; // ============= Functions that refer to words only ============. // Returns the number of blanks before the current word. int BlanksBeforeWord() const; // ============= Accessing data ==============. /** * Returns the null terminated UTF-8 encoded text string for the current * object at the given level. Use delete [] to free after use. */ virtual char *GetUTF8Text(PageIteratorLevel level) const; /** * Returns the LSTM choices for every LSTM timestep for the current word. */ virtual std::vector<std::vector<std::vector<std::pair<const char *, float>>>> *GetRawLSTMTimesteps() const; virtual std::vector<std::vector<std::pair<const char *, float>>> *GetBestLSTMSymbolChoices() const; /** * Return whether the current paragraph's dominant reading direction * is left-to-right (as opposed to right-to-left). */ bool ParagraphIsLtr() const; // ============= Exposed only for testing =============. /** * Yields the reading order as a sequence of indices and (optional) * meta-marks for a set of words (given left-to-right). * The meta marks are passed as negative values: * kMinorRunStart Start of minor direction text. * kMinorRunEnd End of minor direction text. * kComplexWord The next indexed word contains both left-to-right and * right-to-left characters and was treated as neutral. * * For example, suppose we have five words in a text line, * indexed [0,1,2,3,4] from the leftmost side of the text line. * The following are all believable reading_orders: * * Left-to-Right (in ltr paragraph): * { 0, 1, 2, 3, 4 } * Left-to-Right (in rtl paragraph): * { kMinorRunStart, 0, 1, 2, 3, 4, kMinorRunEnd } * Right-to-Left (in rtl paragraph): * { 4, 3, 2, 1, 0 } * Left-to-Right except for an RTL phrase in words 2, 3 in an ltr paragraph: * { 0, 1, kMinorRunStart, 3, 2, kMinorRunEnd, 4 } */ static void CalculateTextlineOrder( bool paragraph_is_ltr, const std::vector<StrongScriptDirection> &word_dirs, std::vector<int> *reading_order); static const int kMinorRunStart; static const int kMinorRunEnd; static const int kComplexWord; protected: /** * We presume the data associated with the given iterator will outlive us. * NB: This is private because it does something that is non-obvious: * it resets to the beginning of the paragraph instead of staying wherever * resit might have pointed. */ explicit ResultIterator(const LTRResultIterator &resit); private: /** * Calculates the current paragraph's dominant writing direction. * Typically, members should use current_paragraph_ltr_ instead. */ bool CurrentParagraphIsLtr() const; /** * Returns word indices as measured from resit->RestartRow() = index 0 * for the reading order of words within a textline given an iterator * into the middle of the text line. * In addition to non-negative word indices, the following negative values * may be inserted: * kMinorRunStart Start of minor direction text. * kMinorRunEnd End of minor direction text. * kComplexWord The previous word contains both left-to-right and * right-to-left characters and was treated as neutral. */ void CalculateTextlineOrder(bool paragraph_is_ltr, const LTRResultIterator &resit, std::vector<int> *indices) const; /** Same as above, but the caller's ssd gets filled in if ssd != nullptr. */ void CalculateTextlineOrder(bool paragraph_is_ltr, const LTRResultIterator &resit, std::vector<StrongScriptDirection> *ssd, std::vector<int> *indices) const; /** * What is the index of the current word in a strict left-to-right reading * of the row? */ int LTRWordIndex() const; /** * Given an iterator pointing at a word, returns the logical reading order * of blob indices for the word. */ void CalculateBlobOrder(std::vector<int> *blob_indices) const; /** Precondition: current_paragraph_is_ltr_ is set. */ void MoveToLogicalStartOfTextline(); /** * Precondition: current_paragraph_is_ltr_ and in_minor_direction_ * are set. */ void MoveToLogicalStartOfWord(); /** Are we pointing at the final (reading order) symbol of the word? */ bool IsAtFinalSymbolOfWord() const; /** Are we pointing at the first (reading order) symbol of the word? */ bool IsAtFirstSymbolOfWord() const; /** * Append any extra marks that should be appended to this word when printed. * Mostly, these are Unicode BiDi control characters. */ void AppendSuffixMarks(std::string *text) const; /** Appends the current word in reading order to the given buffer.*/ void AppendUTF8WordText(std::string *text) const; /** * Appends the text of the current text line, *assuming this iterator is * positioned at the beginning of the text line* This function * updates the iterator to point to the first position past the text line. * Each textline is terminated in a single newline character. * If the textline ends a paragraph, it gets a second terminal newline. */ void IterateAndAppendUTF8TextlineText(std::string *text); /** * Appends the text of the current paragraph in reading order * to the given buffer. * Each textline is terminated in a single newline character, and the * paragraph gets an extra newline at the end. */ void AppendUTF8ParagraphText(std::string *text) const; /** Returns whether the bidi_debug flag is set to at least min_level. */ bool BidiDebug(int min_level) const; bool current_paragraph_is_ltr_; /** * Is the currently pointed-at character at the beginning of * a minor-direction run? */ bool at_beginning_of_minor_run_; /** Is the currently pointed-at character in a minor-direction sequence? */ bool in_minor_direction_; /** * Should detected inter-word spaces be preserved, or "compressed" to a single * space character (default behavior). */ bool preserve_interword_spaces_; }; } // namespace tesseract. #endif // TESSERACT_CCMAIN_RESULT_ITERATOR_H_
2301_81045437/tesseract
include/tesseract/resultiterator.h
C++
apache-2.0
9,484
// SPDX-License-Identifier: Apache-2.0 // File: unichar.h // Description: Unicode character/ligature class. // Author: Ray Smith // // (C) Copyright 2006, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TESSERACT_CCUTIL_UNICHAR_H_ #define TESSERACT_CCUTIL_UNICHAR_H_ #include "export.h" #include <memory.h> #include <cstring> #include <string> #include <vector> namespace tesseract { // Maximum number of characters that can be stored in a UNICHAR. Must be // at least 4. Must not exceed 31 without changing the coding of length. #define UNICHAR_LEN 30 // A UNICHAR_ID is the unique id of a unichar. using UNICHAR_ID = int; // A variable to indicate an invalid or uninitialized unichar id. static const int INVALID_UNICHAR_ID = -1; // A special unichar that corresponds to INVALID_UNICHAR_ID. static const char INVALID_UNICHAR[] = "__INVALID_UNICHAR__"; enum StrongScriptDirection { DIR_NEUTRAL = 0, // Text contains only neutral characters. DIR_LEFT_TO_RIGHT = 1, // Text contains no Right-to-Left characters. DIR_RIGHT_TO_LEFT = 2, // Text contains no Left-to-Right characters. DIR_MIX = 3, // Text contains a mixture of left-to-right // and right-to-left characters. }; using char32 = signed int; // The UNICHAR class holds a single classification result. This may be // a single Unicode character (stored as between 1 and 4 utf8 bytes) or // multiple Unicode characters representing the NFKC expansion of a ligature // such as fi, ffl etc. These are also stored as utf8. class TESS_API UNICHAR { public: UNICHAR() { memset(chars, 0, UNICHAR_LEN); } // Construct from a utf8 string. If len<0 then the string is null terminated. // If the string is too long to fit in the UNICHAR then it takes only what // will fit. UNICHAR(const char *utf8_str, int len); // Construct from a single UCS4 character. explicit UNICHAR(int unicode); // Default copy constructor and operator= are OK. // Get the first character as UCS-4. int first_uni() const; // Get the length of the UTF8 string. int utf8_len() const { int len = chars[UNICHAR_LEN - 1]; return len >= 0 && len < UNICHAR_LEN ? len : UNICHAR_LEN; } // Get a UTF8 string, but NOT nullptr terminated. const char *utf8() const { return chars; } // Get a terminated UTF8 string: Must delete[] it after use. char *utf8_str() const; // Get the number of bytes in the first character of the given utf8 string. static int utf8_step(const char *utf8_str); // A class to simplify iterating over and accessing elements of a UTF8 // string. Note that unlike the UNICHAR class, const_iterator does NOT COPY or // take ownership of the underlying byte array. It also does not permit // modification of the array (as the name suggests). // // Example: // for (UNICHAR::const_iterator it = UNICHAR::begin(str, str_len); // it != UNICHAR::end(str, len); // ++it) { // printf("UCS-4 symbol code = %d\n", *it); // char buf[5]; // int char_len = it.get_utf8(buf); buf[char_len] = '\0'; // printf("Char = %s\n", buf); // } class TESS_API const_iterator { using CI = const_iterator; public: // Step to the next UTF8 character. // If the current position is at an illegal UTF8 character, then print an // error message and step by one byte. If the current position is at a // nullptr value, don't step past it. const_iterator &operator++(); // Return the UCS-4 value at the current position. // If the current position is at an illegal UTF8 value, return a single // space character. int operator*() const; // Store the UTF-8 encoding of the current codepoint into buf, which must be // at least 4 bytes long. Return the number of bytes written. // If the current position is at an illegal UTF8 value, writes a single // space character and returns 1. // Note that this method does not null-terminate the buffer. int get_utf8(char *buf) const; // Returns the number of bytes of the current codepoint. Returns 1 if the // current position is at an illegal UTF8 value. int utf8_len() const; // Returns true if the UTF-8 encoding at the current position is legal. bool is_legal() const; // Return the pointer into the string at the current position. const char *utf8_data() const { return it_; } // Iterator equality operators. friend bool operator==(const CI &lhs, const CI &rhs) { return lhs.it_ == rhs.it_; } friend bool operator!=(const CI &lhs, const CI &rhs) { return !(lhs == rhs); } private: friend class UNICHAR; explicit const_iterator(const char *it) : it_(it) {} const char *it_; // Pointer into the string. }; // Create a start/end iterator pointing to a string. Note that these methods // are static and do NOT create a copy or take ownership of the underlying // array. static const_iterator begin(const char *utf8_str, int byte_length); static const_iterator end(const char *utf8_str, int byte_length); // Converts a utf-8 string to a vector of unicodes. // Returns an empty vector if the input contains invalid UTF-8. static std::vector<char32> UTF8ToUTF32(const char *utf8_str); // Converts a vector of unicodes to a utf8 string. // Returns an empty string if the input contains an invalid unicode. static std::string UTF32ToUTF8(const std::vector<char32> &str32); private: // A UTF-8 representation of 1 or more Unicode characters. // The last element (chars[UNICHAR_LEN - 1]) is a length if // its value < UNICHAR_LEN, otherwise it is a genuine character. char chars[UNICHAR_LEN]{}; }; } // namespace tesseract #endif // TESSERACT_CCUTIL_UNICHAR_H_
2301_81045437/tesseract
include/tesseract/unichar.h
C++
apache-2.0
6,305
SUBDIRS = com scrollview_path = @datadir@/tessdata JAVAC = javac JAR = jar if !GRAPHICS_DISABLED SCROLLVIEW_FILES = \ $(srcdir)/com/google/scrollview/ui/SVAbstractMenuItem.java \ $(srcdir)/com/google/scrollview/ui/SVCheckboxMenuItem.java \ $(srcdir)/com/google/scrollview/ui/SVEmptyMenuItem.java \ $(srcdir)/com/google/scrollview/events/SVEvent.java \ $(srcdir)/com/google/scrollview/events/SVEventHandler.java \ $(srcdir)/com/google/scrollview/events/SVEventType.java \ $(srcdir)/com/google/scrollview/ui/SVImageHandler.java \ $(srcdir)/com/google/scrollview/ui/SVMenuBar.java \ $(srcdir)/com/google/scrollview/ui/SVMenuItem.java \ $(srcdir)/com/google/scrollview/ui/SVPopupMenu.java \ $(srcdir)/com/google/scrollview/ui/SVSubMenuItem.java \ $(srcdir)/com/google/scrollview/ui/SVWindow.java \ $(srcdir)/com/google/scrollview/ScrollView.java SCROLLVIEW_CLASSES = \ com/google/scrollview/ui/SVAbstractMenuItem.class \ com/google/scrollview/ui/SVCheckboxMenuItem.class \ com/google/scrollview/ui/SVEmptyMenuItem.class \ com/google/scrollview/events/SVEvent.class \ com/google/scrollview/events/SVEventHandler.class \ com/google/scrollview/events/SVEventType.class \ com/google/scrollview/ui/SVImageHandler.class \ com/google/scrollview/ui/SVMenuBar.class \ com/google/scrollview/ui/SVMenuItem.class \ com/google/scrollview/ui/SVPopupMenu.class \ com/google/scrollview/ui/SVSubMenuItem.class \ com/google/scrollview/ui/SVWindow.class \ com/google/scrollview/ScrollView.class SCROLLVIEW_LIBS = \ piccolo2d-core-3.0.1.jar \ piccolo2d-extras-3.0.1.jar \ jaxb-api-2.3.1.jar CLASSPATH = piccolo2d-core-3.0.1.jar:piccolo2d-extras-3.0.1.jar:jaxb-api-2.3.1.jar ScrollView.jar : $(SCROLLVIEW_CLASSES) $(JAR) cfm $@ $(srcdir)/Manifest.txt com/google/scrollview/*.class \ com/google/scrollview/events/*.class com/google/scrollview/ui/*.class $(SCROLLVIEW_CLASSES) : $(SCROLLVIEW_FILES) $(SCROLLVIEW_LIBS) $(JAVAC) -encoding UTF8 -sourcepath $(srcdir) -classpath $(CLASSPATH) $(SCROLLVIEW_FILES) -d $(builddir) .PHONY: fetch-jars fetch-jars $(SCROLLVIEW_LIBS): curl -s -S -L -O https://search.maven.org/remotecontent?filepath=org/piccolo2d/piccolo2d-core/3.0.1/piccolo2d-core-3.0.1.jar curl -s -S -L -O https://search.maven.org/remotecontent?filepath=org/piccolo2d/piccolo2d-extras/3.0.1/piccolo2d-extras-3.0.1.jar curl -s -S -L -O https://search.maven.org/remotecontent?filepath=javax/xml/bind/jaxb-api/2.3.1/jaxb-api-2.3.1.jar .PHONY: install-jars install-jars : ScrollView.jar @if [ ! -d $(scrollview_path) ]; then mkdir -p $(scrollview_path); fi; $(INSTALL) -m 644 $(SCROLLVIEW_LIBS) $(scrollview_path); $(INSTALL) -m 644 ScrollView.jar $(scrollview_path); @echo "Don't forget to set environment variable SCROLLVIEW_PATH to $(scrollview_path)"; uninstall: rm -f $(scrollview_path)/*.jar endif clean-local: rm -f ScrollView.jar $(SCROLLVIEW_CLASSES) # all-am does nothing, to make the java part optional. all all-am install :
2301_81045437/tesseract
java/Makefile.am
Makefile
apache-2.0
2,978
SUBDIRS = google
2301_81045437/tesseract
java/com/Makefile.am
Makefile
apache-2.0
17
SUBDIRS = scrollview
2301_81045437/tesseract
java/com/google/Makefile.am
Makefile
apache-2.0
21
SUBDIRS = events ui EXTRA_DIST = \ ScrollView.java
2301_81045437/tesseract
java/com/google/scrollview/Makefile.am
Makefile
apache-2.0
56
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview; import com.google.scrollview.events.SVEvent; import com.google.scrollview.ui.SVImageHandler; import com.google.scrollview.ui.SVWindow; import org.piccolo2d.nodes.PImage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.regex.Pattern; /** * The ScrollView class is the main class which gets started from the command * line. It sets up LUA and handles the network processing. * @author wanke@google.com */ public class ScrollView { /** The port our server listens at. */ public static int SERVER_PORT = 8461; /** * All SVWindow objects share the same connection stream. The socket is needed * to detect when the connection got closed, in/out are used to send and * receive messages. */ private static Socket socket; private static PrintStream out; public static BufferedReader in; public static float polylineXCoords[]; // The coords being received. public static float polylineYCoords[]; // The coords being received. public static int polylineSize; // The size of the coords arrays. public static int polylineScanned; // The size read so far. private static ArrayList<SVWindow> windows; // The id to SVWindow map. private static Pattern intPattern; // For checking integer arguments. private static Pattern floatPattern; // For checking float arguments. /** Keeps track of the number of messages received. */ static int nrInputLines = 0; /** Prints all received messages to the console if true. */ static boolean debugViewNetworkTraffic = false; /** Add a new message to the outgoing queue. */ public static void addMessage(SVEvent e) { if (debugViewNetworkTraffic) { System.out.println("(S->c) " + e.toString()); } String str = e.toString(); // Send the whole thing as UTF8. try { byte [] utf8 = str.getBytes("UTF8"); out.write(utf8, 0, utf8.length); } catch (java.io.UnsupportedEncodingException ex) { System.out.println("Oops... can't encode to UTF8... Exiting"); System.exit(0); } out.println(); // Flush the output and check for errors. boolean error = out.checkError(); if (error) { System.out.println("Connection error. Quitting ScrollView Server..."); System.exit(0); } } /** Read one message from client (assuming there are any). */ public static String receiveMessage() throws IOException { return in.readLine(); } /** * The main program loop. Basically loops through receiving messages and * processing them and then sending messages (if there are any). */ private static void IOLoop() { String inputLine; try { while (!socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown() && socket.isConnected() && socket.isBound()) { inputLine = receiveMessage(); if (inputLine == null) { // End of stream reached. break; } nrInputLines++; if (debugViewNetworkTraffic) { System.out.println("(c->S," + nrInputLines + ")" + inputLine); } if (polylineSize > polylineScanned) { // We are processing a polyline. // Read pairs of coordinates separated by commas. boolean first = true; for (String coordStr : inputLine.split(",")) { int coord = Integer.parseInt(coordStr); if (first) { polylineXCoords[polylineScanned] = coord; } else { polylineYCoords[polylineScanned++] = coord; } first = !first; } assert first; } else { // Process this normally. processInput(inputLine); } } } // Some connection error catch (IOException e) { System.out.println("Connection error. Quitting ScrollView Server..."); } System.exit(0); } // Parse a comma-separated list of arguments into ArrayLists of the // possible types. Each type is stored in order, but the order // distinction between types is lost. // Note that the format is highly constrained to what the client used // to send to LUA: // Quoted string -> String. // true or false -> Boolean. // %f format number -> Float (no %e allowed) // Sequence of digits -> Integer // Nothing else allowed. private static void parseArguments(String argList, ArrayList<Integer> intList, ArrayList<Float> floatList, ArrayList<String> stringList, ArrayList<Boolean> boolList) { // str is only non-null if an argument starts with a single or double // quote. str is set back to null on completion of the string with a // matching quote. If the string contains a comma then str will stay // non-null across multiple argStr values until a matching closing quote. // Backslash escaped quotes do not count as terminating the string. String str = null; for (String argStr : argList.split(",")) { if (str != null) { // Last string was incomplete. Append argStr to it and restore comma. // Execute str += "," + argStr in Java. int length = str.length() + 1 + argStr.length(); StringBuilder appended = new StringBuilder(length); appended.append(str); appended.append(","); appended.append(argStr); str = appended.toString(); } else if (argStr.length() == 0) { continue; } else { char quote = argStr.charAt(0); // If it begins with a quote then it is a string, but may not // end this time if it contained a comma. if (quote == '\'' || quote == '"') { str = argStr; } } if (str != null) { // It began with a quote. Check that it still does. assert str.charAt(0) == '\'' || str.charAt(0) == '"'; int len = str.length(); if (len > 1 && str.charAt(len - 1) == str.charAt(0)) { // We have an ending quote of the right type. Now check that // it is not escaped. Must have an even number of slashes before. int slash = len - 1; while (slash > 0 && str.charAt(slash - 1) == '\\') --slash; if ((len - 1 - slash) % 2 == 0) { // It is now complete. Chop off the quotes and save. // TODO(rays) remove the first backslash of each pair. stringList.add(str.substring(1, len - 1)); str = null; } } // If str is not null here, then we have a string with a comma in it. // Append, and the next argument at the next iteration, but check // that str is null after the loop terminates in case it was an // unterminated string. } else if (floatPattern.matcher(argStr).matches()) { // It is a float. floatList.add(Float.parseFloat(argStr)); } else if (argStr.equals("true")) { boolList.add(true); } else if (argStr.equals("false")) { boolList.add(false); } else if (intPattern.matcher(argStr).matches()) { // Only contains digits so must be an int. intList.add(Integer.parseInt(argStr)); } // else ignore all incompatible arguments for forward compatibility. } // All strings must have been terminated. assert str == null; } /** Executes the LUA command parsed as parameter. */ private static void processInput(String inputLine) { if (inputLine == null) { return; } // Execute a function encoded as a LUA statement! Yuk! if (inputLine.charAt(0) == 'w') { // This is a method call on a window. Parse it. String noWLine = inputLine.substring(1); String[] idStrs = noWLine.split("[ :]", 2); int windowID = Integer.parseInt(idStrs[0]); // Find the parentheses. int start = inputLine.indexOf('('); int end = inputLine.lastIndexOf(')'); // Parse the args. ArrayList<Integer> intList = new ArrayList<Integer>(4); ArrayList<Float> floatList = new ArrayList<Float>(2); ArrayList<String> stringList = new ArrayList<String>(4); ArrayList<Boolean> boolList = new ArrayList<Boolean>(3); parseArguments(inputLine.substring(start + 1, end), intList, floatList, stringList, boolList); int colon = inputLine.indexOf(':'); if (colon > 1 && colon < start) { // This is a regular function call. Look for the name and call it. String func = inputLine.substring(colon + 1, start); if (func.equals("drawLine")) { windows.get(windowID).drawLine(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("createPolyline")) { windows.get(windowID).createPolyline(intList.get(0)); } else if (func.equals("drawPolyline")) { windows.get(windowID).drawPolyline(); } else if (func.equals("drawRectangle")) { windows.get(windowID).drawRectangle(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("setVisible")) { windows.get(windowID).setVisible(boolList.get(0)); } else if (func.equals("setAlwaysOnTop")) { windows.get(windowID).setAlwaysOnTop(boolList.get(0)); } else if (func.equals("addMessage")) { windows.get(windowID).addMessage(stringList.get(0)); } else if (func.equals("addMessageBox")) { windows.get(windowID).addMessageBox(); } else if (func.equals("clear")) { windows.get(windowID).clear(); } else if (func.equals("setStrokeWidth")) { windows.get(windowID).setStrokeWidth(floatList.get(0)); } else if (func.equals("drawEllipse")) { windows.get(windowID).drawEllipse(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("pen")) { if (intList.size() == 4) { windows.get(windowID).pen(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else { windows.get(windowID).pen(intList.get(0), intList.get(1), intList.get(2)); } } else if (func.equals("brush")) { if (intList.size() == 4) { windows.get(windowID).brush(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else { windows.get(windowID).brush(intList.get(0), intList.get(1), intList.get(2)); } } else if (func.equals("textAttributes")) { windows.get(windowID).textAttributes(stringList.get(0), intList.get(0), boolList.get(0), boolList.get(1), boolList.get(2)); } else if (func.equals("drawText")) { windows.get(windowID).drawText(intList.get(0), intList.get(1), stringList.get(0)); } else if (func.equals("addMenuBarItem")) { if (boolList.size() > 0) { windows.get(windowID).addMenuBarItem(stringList.get(0), stringList.get(1), intList.get(0), boolList.get(0)); } else if (intList.size() > 0) { windows.get(windowID).addMenuBarItem(stringList.get(0), stringList.get(1), intList.get(0)); } else { windows.get(windowID).addMenuBarItem(stringList.get(0), stringList.get(1)); } } else if (func.equals("addPopupMenuItem")) { if (stringList.size() == 4) { windows.get(windowID).addPopupMenuItem(stringList.get(0), stringList.get(1), intList.get(0), stringList.get(2), stringList.get(3)); } else { windows.get(windowID).addPopupMenuItem(stringList.get(0), stringList.get(1)); } } else if (func.equals("update")) { windows.get(windowID).update(); } else if (func.equals("showInputDialog")) { windows.get(windowID).showInputDialog(stringList.get(0)); } else if (func.equals("showYesNoDialog")) { windows.get(windowID).showYesNoDialog(stringList.get(0)); } else if (func.equals("zoomRectangle")) { windows.get(windowID).zoomRectangle(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("readImage")) { PImage image = SVImageHandler.readImage(intList.get(2), in); windows.get(windowID).drawImage(image, intList.get(0), intList.get(1)); } else if (func.equals("drawImage")) { PImage image = new PImage(stringList.get(0)); windows.get(windowID).drawImage(image, intList.get(0), intList.get(1)); } else if (func.equals("destroy")) { windows.get(windowID).destroy(); } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } else { // No colon. Check for create window. if (idStrs[1].startsWith("= luajava.newInstance")) { while (windows.size() <= windowID) { windows.add(null); } windows.set(windowID, new SVWindow(stringList.get(1), intList.get(0), intList.get(1), intList.get(2), intList.get(3), intList.get(4), intList.get(5), intList.get(6))); } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } } else if (inputLine.startsWith("svmain")) { // Startup or end. Startup is a lua bind, which is now a no-op. if (inputLine.startsWith("svmain:exit")) { exit(); } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } /** Called from the client to make the server exit. */ public static void exit() { System.exit(0); } /** * The main function. Sets up LUA and the server connection and then calls the * IOLoop. */ public static void main(String[] args) { if (args.length > 0) { SERVER_PORT = Integer.parseInt(args[0]); } windows = new ArrayList<SVWindow>(100); intPattern = Pattern.compile("[0-9-][0-9]*"); floatPattern = Pattern.compile("[0-9-][0-9]*\\.[0-9]*"); // Open a socket to listen on. try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT)) { System.out.println("Socket started on port " + SERVER_PORT); // Wait (blocking) for an incoming connection socket = serverSocket.accept(); System.out.println("Client connected"); // Setup the streams out = new PrintStream(socket.getOutputStream(), true, "UTF-8"); in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8")); } catch (IOException e) { // Something went wrong and we were unable to set up a connection. This is // pretty much a fatal error. // Note: The server does not get restarted automatically if this happens. e.printStackTrace(); System.exit(1); } // Enter the main program loop. IOLoop(); } }
2301_81045437/tesseract
java/com/google/scrollview/ScrollView.java
Java
apache-2.0
17,167
SUBDIRS = EXTRA_DIST = \ SVEvent.java SVEventHandler.java \ SVEventType.java
2301_81045437/tesseract
java/com/google/scrollview/events/Makefile.am
Makefile
apache-2.0
86
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.events; import com.google.scrollview.ui.SVWindow; /** * The SVEvent is a structure which holds the actual values of a message to be * transmitted. It corresponds to the client structure defined in scrollview.h * * @author wanke@google.com */ public class SVEvent { SVEventType type; // What kind of event. SVWindow window; // Window event relates to. int x; // Coords of click or selection. int y; int xSize; // Size of selection. int ySize; int commandId; String parameter; // Any string that might have been passed as argument. /** * A "normal" SVEvent. * * @param t The type of the event as specified in SVEventType (e.g. * SVET_CLICK) * @param w The window the event corresponds to * @param x1 X position of the mouse at the time of the event * @param y1 Y position of the mouse at the time of the event * @param x2 X selection size at the time of the event * @param y2 Y selection size at the time of the event * @param p A parameter associated with the event (e.g. keyboard input) */ public SVEvent(SVEventType t, SVWindow w, int x1, int y1, int x2, int y2, String p) { type = t; window = w; x = x1; y = y1; xSize = x2; ySize = y2; commandId = 0; parameter = p; } /** * An event which issues a command (like clicking on an item in the menubar). * * @param eventtype The type of the event as specified in SVEventType * (usually SVET_MENU or SVET_POPUP) * @param svWindow The window the event corresponds to * @param commandid The associated id with the command (given by the client * on construction of the item) * @param value A parameter associated with the event (e.g. keyboard input) */ public SVEvent(SVEventType eventtype, SVWindow svWindow, int commandid, String value) { type = eventtype; window = svWindow; parameter = value; x = 0; y = 0; xSize = 0; ySize = 0; commandId = commandid; } /** * This is the string representation of the message, which is what will * actually be transferred over the network. */ @Override public String toString() { return (window.hash + "," + type.ordinal() + "," + x + "," + y + "," + xSize + "," + ySize + "," + commandId + "," + parameter); } }
2301_81045437/tesseract
java/com/google/scrollview/events/SVEvent.java
Java
apache-2.0
2,942
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.events; import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVWindow; import org.piccolo2d.PCamera; import org.piccolo2d.PNode; import org.piccolo2d.event.PBasicInputEventHandler; import org.piccolo2d.event.PInputEvent; import org.piccolo2d.nodes.PPath; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.awt.Window; import javax.swing.Timer; /** * The ScrollViewEventHandler takes care of any events which might happen on the * canvas and converts them to an according SVEvent, which is (using the * processEvent method) then added to a message queue. All events from the * message queue get sent gradually. * * @author wanke@google.com */ public class SVEventHandler extends PBasicInputEventHandler implements ActionListener, KeyListener, WindowListener { /** Necessary to wait for a defined period of time (for SVET_HOVER). */ public Timer timer; /** The window which the event corresponds to. */ private SVWindow svWindow; /** These are used to determine a selection size (for SVET_SELECTION). */ private int lastX = 0; private int lastY = 0; /** * These are used in case we want to transmit our position, but do not get it * because it was no MouseEvent, in particular SVET_HOVER and SVET_INPUT. */ private int lastXMove = 0; private int lastYMove = 0; /** For Drawing a rubber-band rectangle for selection. */ private int startX = 0; private int startY = 0; private float rubberBandTransparency = 0.5f; private PNode selection = null; /** The string entered since the last enter. Since the client * end eats all newlines, we can't use the newline * character, so use ! for now, as it cannot be entered * directly anyway and therefore can never show up for real. */ private String keyStr = "!"; /** Setup the timer. */ public SVEventHandler(SVWindow wdw) { timer = new Timer(1000, this); svWindow = wdw; } /** * Store the newest x,y values, add the message to the queue and restart the * timer. */ private void processEvent(SVEvent e) { lastXMove = e.x; lastYMove = e.y; ScrollView.addMessage(e); timer.restart(); } /** Show the associated popup menu at (x,y) (relative position of the window). */ private void showPopup(PInputEvent e) { double x = e.getCanvasPosition().getX(); double y = e.getCanvasPosition().getY(); if (svWindow.svPuMenu != null) { svWindow.svPuMenu.show(svWindow, (int) x, (int) y); } } /** The mouse is clicked - create an SVET_CLICK event. */ @Override public void mouseClicked(PInputEvent e) { if (e.isPopupTrigger()) { showPopup(e); } else { processEvent(new SVEvent(SVEventType.SVET_CLICK, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), 0, 0, null)); } } /** * The mouse key is pressed (and keeps getting pressed). * Depending on the OS, show a popup menu (if the button pressed is associated * with popup menus, like the RMB under windows&linux) or otherwise save the * position (in case it is a selection). */ @Override public void mousePressed(PInputEvent e) { if (e.isPopupTrigger()) { showPopup(e); } else { lastX = (int) e.getPosition().getX(); lastY = (int) e.getPosition().getY(); timer.restart(); } } /** The mouse is getting dragged - create an SVET_MOUSE event. */ @Override public void mouseDragged(PInputEvent e) { processEvent(new SVEvent(SVEventType.SVET_MOUSE, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), (int) e .getPosition().getX() - lastX, (int) e.getPosition().getY() - lastY, null)); // Paint a selection rectangle. if (selection == null) { startX = (int) e.getPosition().getX(); startY = (int) e.getPosition().getY(); selection = PPath.createRectangle(startX, startY, 1, 1); selection.setTransparency(rubberBandTransparency); svWindow.canvas.getLayer().addChild(selection); } else { int right = Math.max(startX, (int) e.getPosition().getX()); int left = Math.min(startX, (int) e.getPosition().getX()); int bottom = Math.max(startY, (int) e.getPosition().getY()); int top = Math.min(startY, (int) e.getPosition().getY()); svWindow.canvas.getLayer().removeChild(selection); selection = PPath.createRectangle(left, top, right - left, bottom - top); selection.setPaint(Color.YELLOW); selection.setTransparency(rubberBandTransparency); svWindow.canvas.getLayer().addChild(selection); } } /** * The mouse was released. * Depending on the OS, show a popup menu (if the button pressed is associated * with popup menus, like the RMB under windows&linux) or otherwise create an * SVET_SELECTION event. */ @Override public void mouseReleased(PInputEvent e) { if (e.isPopupTrigger()) { showPopup(e); } else { processEvent(new SVEvent(SVEventType.SVET_SELECTION, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), (int) e .getPosition().getX() - lastX, (int) e.getPosition().getY() - lastY, null)); } if (selection != null) { svWindow.canvas.getLayer().removeChild(selection); selection = null; } } /** * The mouse wheel is used to zoom in and out of the viewport and center on * the (x,y) position the mouse is currently on. */ @Override public void mouseWheelRotated(PInputEvent e) { PCamera lc = svWindow.canvas.getCamera(); double sf = SVWindow.SCALING_FACTOR; if (e.getWheelRotation() < 0) { sf = 1 / sf; } lc.scaleViewAboutPoint(lc.getScale() / sf, e.getPosition().getX(), e .getPosition().getY()); } /** * The mouse was moved - create an SVET_MOTION event. NOTE: This obviously * creates a lot of traffic and, depending on the type of application, could * quite possibly be disabled. */ @Override public void mouseMoved(PInputEvent e) { processEvent(new SVEvent(SVEventType.SVET_MOTION, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), 0, 0, null)); } /** * The mouse entered the window. * Start the timer, which will then emit SVET_HOVER events every X ms. */ @Override public void mouseEntered(PInputEvent e) { timer.restart(); } /** * The mouse exited the window * Stop the timer, so no more SVET_HOVER events will emit. */ @Override public void mouseExited(PInputEvent e) { timer.stop(); } /** * The only associated object with this is the timer, so we use it to send a * SVET_HOVER event. */ public void actionPerformed(ActionEvent e) { processEvent(new SVEvent(SVEventType.SVET_HOVER, svWindow, lastXMove, lastYMove, 0, 0, null)); } /** * A key was pressed - create an SVET_INPUT event. * * NOTE: Might be useful to specify hotkeys. * * Implementation note: The keyListener provided by Piccolo seems to be * broken, so we use the AWT listener directly. * There are never any keyTyped events received either so we are * stuck with physical keys, which is very ugly. */ public void keyPressed(KeyEvent e) { char keyCh = e.getKeyChar(); if (keyCh == '\r' || keyCh == '\n' || keyCh == '\0' || keyCh == '?') { processEvent(new SVEvent(SVEventType.SVET_INPUT, svWindow, lastXMove, lastYMove, 0, 0, keyStr)); // Send newline characters as '!' as '!' can never be a keypressed // and the client eats all newline characters. keyStr = "!"; } else { processEvent(new SVEvent(SVEventType.SVET_INPUT, svWindow, lastXMove, lastYMove, 0, 0, String.valueOf(keyCh))); keyStr += keyCh; } } /** * A window is closed (by the 'x') - create an SVET_DESTROY event. If it was * the last open Window, also send an SVET_EXIT event (but do not exit unless * the client says so). */ public void windowClosing(WindowEvent e) { processEvent(new SVEvent(SVEventType.SVET_DESTROY, svWindow, lastXMove, lastYMove, 0, 0, null)); Window w = e.getWindow(); if (w != null) { w.dispose(); } SVWindow.nrWindows--; if (SVWindow.nrWindows == 0) { processEvent(new SVEvent(SVEventType.SVET_EXIT, svWindow, lastXMove, lastYMove, 0, 0, null)); } } /** These are all events we do not care about and throw away. */ public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } }
2301_81045437/tesseract
java/com/google/scrollview/events/SVEventHandler.java
Java
apache-2.0
9,825
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.events; /** * These are the defined events which can happen in ScrollView and be * transferred to the client. They are same events as on the client side part of * ScrollView (defined in ScrollView.h). * * @author wanke@google.com */ public enum SVEventType { SVET_DESTROY, // Window has been destroyed by user. SVET_EXIT, // User has destroyed the last window by clicking on the 'X' SVET_CLICK, // Any button pressed that is not a popup trigger. SVET_SELECTION, // Left button selection. SVET_INPUT, // Any kind of input SVET_MOUSE, // The mouse has moved with a button pressed. SVET_MOTION, // The mouse has moved with no button pressed. SVET_HOVER, // The mouse has stayed still for a second. SVET_POPUP, // A command selected through a popup menu SVET_MENU; // A command selected through the menubar }
2301_81045437/tesseract
java/com/google/scrollview/events/SVEventType.java
Java
apache-2.0
1,456
SUBDIRS = EXTRA_DIST = \ SVAbstractMenuItem.java \ SVCheckboxMenuItem.java SVEmptyMenuItem.java \ SVImageHandler.java SVMenuBar.java \ SVMenuItem.java SVPopupMenu.java SVSubMenuItem.java SVWindow.java
2301_81045437/tesseract
java/com/google/scrollview/ui/Makefile.am
Makefile
apache-2.0
218
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.events.SVEventType; import javax.swing.JMenu; import javax.swing.JMenuItem; abstract class SVAbstractMenuItem { JMenuItem mi; public String name; public int id; /** * Sets the basic attributes for name, id and the corresponding swing item */ SVAbstractMenuItem(int id, String name, JMenuItem jmi) { this.mi = jmi; this.name = name; this.id = id; } /** Returns the actual value of the MenuListItem. */ public String getValue() { return null; } /** Adds a child entry to the submenu. */ public void add(SVAbstractMenuItem mli) { } /** Adds a child menu to the submenu (or root node). */ public void add(JMenu jli) { } /** * What to do when user clicks on this item. * @param window The window the event happened. * @param eventType What kind of event will be associated * (usually SVET_POPUP or SVET_MENU). */ public void performAction(SVWindow window, SVEventType eventType) {} }
2301_81045437/tesseract
java/com/google/scrollview/ui/SVAbstractMenuItem.java
Java
apache-2.0
1,935
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventType; import javax.swing.JCheckBoxMenuItem; /** * Constructs a new menulistitem which possesses a flag that can be toggled. */ class SVCheckboxMenuItem extends SVAbstractMenuItem { public boolean bvalue; SVCheckboxMenuItem(int id, String name, boolean val) { super(id, name, new JCheckBoxMenuItem(name, val)); bvalue = val; } /** What to do when user clicks on this item. */ @Override public void performAction(SVWindow window, SVEventType eventType) { // Checkbox entry - trigger and send event. if (bvalue) { bvalue = false; } else { bvalue = true; } SVEvent svme = new SVEvent(eventType, window, id, getValue()); ScrollView.addMessage(svme); } /** Returns the actual value of the MenuListItem. */ @Override public String getValue() { return Boolean.toString(bvalue); } }
2301_81045437/tesseract
java/com/google/scrollview/ui/SVCheckboxMenuItem.java
Java
apache-2.0
1,939
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventType; import javax.swing.JMenuItem; /** * Constructs a new menulistitem which just has an ID and a name attached to * it. In this case, we will have to ask for the value of the item and its * description if it gets called. */ class SVEmptyMenuItem extends SVAbstractMenuItem { SVEmptyMenuItem(int id, String name) { super(id, name, new JMenuItem(name)); } /** What to do when user clicks on this item. */ @Override public void performAction(SVWindow window, SVEventType eventType) { // Send an event indicating that someone clicked on an entry. // Value will be null here. SVEvent svme = new SVEvent(eventType, window, id, getValue()); ScrollView.addMessage(svme); } }
2301_81045437/tesseract
java/com/google/scrollview/ui/SVEmptyMenuItem.java
Java
apache-2.0
1,799
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; import org.piccolo2d.nodes.PImage; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.xml.bind.DatatypeConverter; /** * The ScrollViewImageHandler is a helper class which takes care of image * processing. It is used to construct an Image from the message-stream and * basically consists of a number of utility functions to process the input * stream. * * @author wanke@google.com */ public class SVImageHandler { /* All methods are static, so we forbid to construct SVImageHandler objects. */ private SVImageHandler() { } /** * Reads size bytes from the stream in and interprets it as an image file, * encoded as png, and then text-encoded as base 64, returning the decoded * bitmap. * * @param size The size of the image file. * @param in The input stream from which to read the bytes. */ public static PImage readImage(int size, BufferedReader in) { char[] charbuffer = new char[size]; int numRead = 0; while (numRead < size) { int newRead = -1; try { newRead = in.read(charbuffer, numRead, size - numRead); } catch (IOException e) { System.out.println("Failed to read image data from socket:" + e.getMessage()); return null; } if (newRead < 0) { return null; } numRead += newRead; } if (numRead != size) { System.out.println("Failed to read image data from socket"); return null; } // Convert the character data to binary. byte[] binarydata = DatatypeConverter.parseBase64Binary(new String(charbuffer)); // Convert the binary data to a byte stream and parse to image. ByteArrayInputStream byteStream = new ByteArrayInputStream(binarydata); try { PImage img = new PImage(ImageIO.read(byteStream)); return img; } catch (IOException e) { System.out.println("Failed to decode image data from socket" + e.getMessage()); } return null; } }
2301_81045437/tesseract
java/com/google/scrollview/ui/SVImageHandler.java
Java
apache-2.0
2,659
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVWindow; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import javax.swing.JMenu; import javax.swing.JMenuBar; /** * The SVMenuBar class provides the functionality to add a menubar to * ScrollView. Each menubar item gets associated with a (client-defined) * command-id, which SVMenuBar will return upon clicking it. * * @author wanke@google.com * */ public class SVMenuBar implements ActionListener { /** The root entry to add items to. */ private JMenuBar root; /** Contains a map of item name to its actual entry. */ private HashMap<String, SVAbstractMenuItem> items; /** The window the menubar belongs to. */ private SVWindow svWindow; /** * Create a new SVMenuBar and place it at the top of the ScrollView window. * * @param scrollView The window our menubar belongs to. */ public SVMenuBar(SVWindow scrollView) { root = new JMenuBar(); svWindow = scrollView; items = new HashMap<String, SVAbstractMenuItem>(); svWindow.setJMenuBar(root); } /** * A click on one of the items in our menubar has occurred. Forward it * to the item itself to let it decide what happens. */ public void actionPerformed(ActionEvent e) { // Get the corresponding menuitem. SVAbstractMenuItem svm = items.get(e.getActionCommand()); svm.performAction(svWindow, SVEventType.SVET_MENU); } /** * Add a new entry to the menubar. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level) * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. */ public void add(String parent, String name, int id) { // A duplicate entry - we just throw it away, since its already in. if (items.get(name) != null) { return; } // A new submenu at the top-level if (parent.equals("")) { JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); root.add(jli); } // A new sub-submenu else if (id == -1) { SVAbstractMenuItem jmi = items.get(parent); JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); jmi.add(jli); } // A new child entry. Add to appropriate parent. else { SVAbstractMenuItem jmi = items.get(parent); if (jmi == null) { System.out.println("ERROR: Unknown parent " + parent); System.exit(1); } SVAbstractMenuItem mli = new SVEmptyMenuItem(id, name); mli.mi.addActionListener(this); items.put(name, mli); jmi.add(mli); } } /** * Add a new checkbox entry to the menubar. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level) * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. * @param b Whether the entry is initially flagged. * */ public void add(String parent, String name, int id, boolean b) { SVAbstractMenuItem jmi = items.get(parent); if (jmi == null) { System.out.println("ERROR: Unknown parent " + parent); System.exit(1); } SVAbstractMenuItem mli = new SVCheckboxMenuItem(id, name, b); mli.mi.addActionListener(this); items.put(name, mli); jmi.add(mli); } }
2301_81045437/tesseract
java/com/google/scrollview/ui/SVMenuBar.java
Java
apache-2.0
4,362
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.events.SVEventType; import javax.swing.JMenuItem; /** * Constructs a new menulistitem which also has a value and a description. For * these, we will not have to ask the server what the value is when the user * wants to change it, but can just call the client with the new value. */ class SVMenuItem extends SVAbstractMenuItem { public String value = null; public String desc = null; SVMenuItem(int id, String name, String v, String d) { super(id, name, new JMenuItem(name)); value = v; desc = d; } /** * Ask the user for new input for a variable and send it. * Depending on whether there is a description given for the entry, show * the description in the dialog or just show the name. */ @Override public void performAction(SVWindow window, SVEventType eventType) { if (desc != null) { window.showInputDialog(desc, value, id, eventType); } else { window.showInputDialog(name, value, id, eventType); } } /** Returns the actual value of the MenuListItem. */ @Override public String getValue() { return value; } }
2301_81045437/tesseract
java/com/google/scrollview/ui/SVMenuItem.java
Java
apache-2.0
2,085
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVMenuItem; import com.google.scrollview.ui.SVWindow; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import javax.swing.JMenu; import javax.swing.JPopupMenu; /** * The SVPopupMenu class provides the functionality to add a popup menu to * ScrollView. Each popup menu item gets associated with a (client-defined) * command-id, which SVPopupMenu will return upon clicking it. * * @author wanke@google.com * */ public class SVPopupMenu implements ActionListener { /** The root entry to add items to. */ private JPopupMenu root; /** Contains a map of item name to its actual entry. */ private HashMap<String, SVAbstractMenuItem> items; /** The window the menubar belongs to. */ private SVWindow svWindow; /** * Create a new SVPopupMenu and associate it with a ScrollView window. * * @param sv The window our popup menu belongs to. */ SVPopupMenu(SVWindow sv) { root = new JPopupMenu(); svWindow = sv; items = new HashMap<String, SVAbstractMenuItem>(); } /** * Add a new entry to the menubar. For these items, the server will poll the * client to ask what to do. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level). * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. */ public void add(String parent, String name, int id) { // A duplicate entry - we just throw it away, since its already in. if (items.get(name) != null) { return; } // A new submenu at the top-level. if (parent.equals("")) { JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); root.add(jli); } // A new sub-submenu. else if (id == -1) { SVAbstractMenuItem jmi = items.get(parent); JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); jmi.add(jli); } // A new child entry. Add to appropriate parent. else { SVAbstractMenuItem jmi = items.get(parent); if (jmi == null) { System.out.println("ERROR: Unknown parent " + parent); System.exit(1); } SVAbstractMenuItem mli = new SVEmptyMenuItem(id, name); mli.mi.addActionListener(this); items.put(name, mli); jmi.add(mli); } } /** * Add a new entry to the menubar. In this case, we also know its value and * possibly even have a description. For these items, the server will not poll * the client to ask what to do, but just show an input dialog and send a * message with the new value. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level). * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. * @param value The value of the new entry. * @param desc The description of the new entry. */ public void add(String parent, String name, int id, String value, String desc) { SVAbstractMenuItem jmi = items.get(parent); SVMenuItem mli = new SVMenuItem(id, name, value, desc); mli.mi.addActionListener(this); items.put(name, mli); if (jmi == null) { // add to root root.add(mli.mi); } else { // add to parent jmi.add(mli); } } /** * A click on one of the items in our menubar has occurred. Forward it * to the item itself to let it decide what happens. */ public void actionPerformed(ActionEvent e) { // Get the corresponding menuitem SVAbstractMenuItem svm = items.get(e.getActionCommand()); svm.performAction(svWindow, SVEventType.SVET_POPUP); } /** * Gets called by the SVEventHandler of the window to actually show the * content of the popup menu. */ public void show(Component Invoker, int x, int y) { root.show(Invoker, x, y); } }
2301_81045437/tesseract
java/com/google/scrollview/ui/SVPopupMenu.java
Java
apache-2.0
4,930
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import javax.swing.JMenu; /** Constructs a new submenu which can hold other entries. */ class SVSubMenuItem extends SVAbstractMenuItem { public SVSubMenuItem(String name, JMenu jli) { super(-1, name, jli); } /** Adds a child entry to the submenu. */ @Override public void add(SVAbstractMenuItem mli) { mi.add(mli.mi); } /** Adds a child menu to the submenu (or root node). */ @Override public void add(JMenu jli) { mi.add(jli); } }
2301_81045437/tesseract
java/com/google/scrollview/ui/SVSubMenuItem.java
Java
apache-2.0
1,424
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventHandler; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVMenuBar; import com.google.scrollview.ui.SVPopupMenu; import org.piccolo2d.PCamera; import org.piccolo2d.PCanvas; import org.piccolo2d.PLayer; import org.piccolo2d.extras.swing.PScrollPane; import org.piccolo2d.nodes.PImage; import org.piccolo2d.nodes.PPath; import org.piccolo2d.nodes.PText; import org.piccolo2d.util.PPaintContext; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.TextArea; import java.awt.geom.IllegalPathStateException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; /** * The SVWindow is the top-level ui class. It should get instantiated whenever * the user intends to create a new window. It contains helper functions to draw * on the canvas, add new menu items, show modal dialogs etc. * * @author wanke@google.com */ public class SVWindow extends JFrame { /** * Constants defining the maximum initial size of the window. */ private static final int MAX_WINDOW_X = 1000; private static final int MAX_WINDOW_Y = 800; /* Constant defining the (approx) height of the default message box*/ private static final int DEF_MESSAGEBOX_HEIGHT = 200; /** Constant defining the "speed" at which to zoom in and out. */ public static final double SCALING_FACTOR = 2; /** The top level layer we add our PNodes to (root node). */ PLayer layer; /** The current color of the pen. It is used to draw edges, text, etc. */ Color currentPenColor; /** * The current color of the brush. It is used to draw the interior of * primitives. */ Color currentBrushColor; /** The system name of the current font we are using (e.g. * "Times New Roman"). */ Font currentFont; /** The stroke width to be used. */ // This really needs to be a fixed width stroke as the basic stroke is // anti-aliased and gets too faint, but the piccolo fixed width stroke // is too buggy and generates missing initial moveto in path definition // errors with an IllegalPathStateException that cannot be caught because // it is in the automatic repaint function. If we can fix the exceptions // in piccolo, then we can use the following instead of BasicStroke: // import edu.umd.cs.piccolox.util.PFixedWidthStroke; // PFixedWidthStroke stroke = new PFixedWidthStroke(0.5f); // Instead we use the BasicStroke and turn off anti-aliasing. BasicStroke stroke = new BasicStroke(0.5f); /** * A unique representation for the window, also known by the client. It is * used when sending messages from server to client to identify him. */ public int hash; /** * The total number of created Windows. If this ever reaches 0 (apart from the * beginning), quit the server. */ public static int nrWindows = 0; /** * The Canvas, MessageBox, EventHandler, Menubar and Popupmenu associated with * this window. */ private SVEventHandler svEventHandler = null; private SVMenuBar svMenuBar = null; private TextArea ta = null; public SVPopupMenu svPuMenu = null; public PCanvas canvas; private int winSizeX; private int winSizeY; /** Set the brush to an RGB color */ public void brush(int red, int green, int blue) { brush(red, green, blue, 255); } /** Set the brush to an RGBA color */ public void brush(int red, int green, int blue, int alpha) { // If alpha is zero, use a null brush to save rendering time. if (alpha == 0) { currentBrushColor = null; } else { currentBrushColor = new Color(red, green, blue, alpha); } } /** Erase all content from the window, but do not destroy it. */ public void clear() { // Manipulation of Piccolo's scene graph should be done from Swings // event dispatch thread since Piccolo is not thread safe. This code calls // removeAllChildren() from that thread and releases the latch. final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); SwingUtilities.invokeLater(new Runnable() { public void run() { layer.removeAllChildren(); repaint(); latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { } } /** * Start setting up a new polyline. The server will now expect * polyline data until the polyline is complete. * * @param length number of coordinate pairs */ public void createPolyline(int length) { ScrollView.polylineXCoords = new float[length]; ScrollView.polylineYCoords = new float[length]; ScrollView.polylineSize = length; ScrollView.polylineScanned = 0; } /** * Draw the now complete polyline. */ public void drawPolyline() { int numCoords = ScrollView.polylineXCoords.length; if (numCoords < 2) { return; } PPath pn = PPath.createLine(ScrollView.polylineXCoords[0], ScrollView.polylineYCoords[0], ScrollView.polylineXCoords[1], ScrollView.polylineYCoords[1]); pn.reset(); pn.moveTo(ScrollView.polylineXCoords[0], ScrollView.polylineYCoords[0]); for (int p = 1; p < numCoords; ++p) { pn.lineTo(ScrollView.polylineXCoords[p], ScrollView.polylineYCoords[p]); } pn.closePath(); ScrollView.polylineSize = 0; pn.setStrokePaint(currentPenColor); pn.setPaint(null); // Don't fill the polygon - this is just a polyline. pn.setStroke(stroke); layer.addChild(pn); } /** * Construct a new SVWindow and set it visible. * * @param name Title of the window. * @param hash Unique internal representation. This has to be the same as * defined by the client, as they use this to refer to the windows. * @param posX X position of where to draw the window (upper left). * @param posY Y position of where to draw the window (upper left). * @param sizeX The width of the window. * @param sizeY The height of the window. * @param canvasSizeX The canvas width of the window. * @param canvasSizeY The canvas height of the window. */ public SVWindow(String name, int hash, int posX, int posY, int sizeX, int sizeY, int canvasSizeX, int canvasSizeY) { super(name); // Provide defaults for sizes. if (sizeX <= 0) sizeX = canvasSizeX; if (sizeY <= 0) sizeY = canvasSizeY; if (canvasSizeX <= 0) canvasSizeX = sizeX; if (canvasSizeY <= 0) canvasSizeY = sizeY; // Avoid later division by zero. if (sizeX <= 0) { sizeX = 1; canvasSizeX = sizeX; } if (sizeY <= 0) { sizeY = 1; canvasSizeY = sizeY; } // Initialize variables nrWindows++; this.hash = hash; this.svEventHandler = new SVEventHandler(this); this.currentPenColor = Color.BLACK; this.currentBrushColor = Color.BLACK; this.currentFont = new Font("Times New Roman", Font.PLAIN, 12); // Determine the initial size and zoom factor of the window. // If the window is too big, rescale it and zoom out. int shrinkfactor = 1; if (sizeX > MAX_WINDOW_X) { shrinkfactor = (sizeX + MAX_WINDOW_X - 1) / MAX_WINDOW_X; } if (sizeY / shrinkfactor > MAX_WINDOW_Y) { shrinkfactor = (sizeY + MAX_WINDOW_Y - 1) / MAX_WINDOW_Y; } winSizeX = sizeX / shrinkfactor; winSizeY = sizeY / shrinkfactor; double initialScalingfactor = 1.0 / shrinkfactor; if (winSizeX > canvasSizeX || winSizeY > canvasSizeY) { initialScalingfactor = Math.min(1.0 * winSizeX / canvasSizeX, 1.0 * winSizeY / canvasSizeY); } // Setup the actual window (its size, camera, title, etc.) if (canvas == null) { canvas = new PCanvas(); getContentPane().add(canvas, BorderLayout.CENTER); } layer = canvas.getLayer(); canvas.setBackground(Color.BLACK); // Disable antialiasing to make the lines more visible. canvas.setDefaultRenderQuality(PPaintContext.LOW_QUALITY_RENDERING); setLayout(new BorderLayout()); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); validate(); canvas.requestFocus(); // Manipulation of Piccolo's scene graph should be done from Swings // event dispatch thread since Piccolo is not thread safe. This code calls // initialize() from that thread once the PFrame is initialized, so you are // safe to start working with Piccolo in the initialize() method. SwingUtilities.invokeLater(new Runnable() { public void run() { repaint(); } }); setSize(winSizeX, winSizeY); setLocation(posX, posY); setTitle(name); // Add a Scrollpane to be able to scroll within the canvas PScrollPane scrollPane = new PScrollPane(canvas); getContentPane().add(scrollPane); scrollPane.setWheelScrollingEnabled(false); PCamera lc = canvas.getCamera(); lc.scaleViewAboutPoint(initialScalingfactor, 0, 0); // Disable the default event handlers and add our own. addWindowListener(svEventHandler); canvas.removeInputEventListener(canvas.getPanEventHandler()); canvas.removeInputEventListener(canvas.getZoomEventHandler()); canvas.addInputEventListener(svEventHandler); canvas.addKeyListener(svEventHandler); // Make the window visible. validate(); setVisible(true); } /** * Convenience function to add a message box to the window which can be used * to output debug information. */ public void addMessageBox() { if (ta == null) { ta = new TextArea(); ta.setEditable(false); getContentPane().add(ta, BorderLayout.SOUTH); } // We need to make the window bigger to accommodate the message box. winSizeY += DEF_MESSAGEBOX_HEIGHT; setSize(winSizeX, winSizeY); } /** * Allows you to specify the thickness with which to draw lines, recantgles * and ellipses. * @param width The new thickness. */ public void setStrokeWidth(float width) { // If this worked we wouldn't need the antialiased rendering off. // stroke = new PFixedWidthStroke(width); stroke = new BasicStroke(width); } /** * Draw an ellipse at (x,y) with given width and height, using the * current stroke, the current brush color to fill it and the * current pen color for the outline. */ public void drawEllipse(int x, int y, int width, int height) { PPath pn = PPath.createEllipse(x, y, width, height); pn.setStrokePaint(currentPenColor); pn.setStroke(stroke); pn.setPaint(currentBrushColor); layer.addChild(pn); } /** * Draw the image with the given name at (x,y). Any image loaded stays in * memory, so if you intend to redraw an image, you do not have to use * createImage again. */ public void drawImage(PImage img, int xPos, int yPos) { img.setX(xPos); img.setY(yPos); layer.addChild(img); } /** * Draw a line from (x1,y1) to (x2,y2) using the current pen color and stroke. */ public void drawLine(int x1, int y1, int x2, int y2) { PPath pn = PPath.createLine(x1, y1, x2, y2); pn.setStrokePaint(currentPenColor); pn.setPaint(null); // Null paint may render faster than the default. pn.setStroke(stroke); pn.moveTo(x1, y1); pn.lineTo(x2, y2); layer.addChild(pn); } /** * Draw a rectangle given the two points (x1,y1) and (x2,y2) using the current * stroke, pen color for the border and the brush to fill the * interior. */ public void drawRectangle(int x1, int y1, int x2, int y2) { if (x1 > x2) { int t = x1; x1 = x2; x2 = t; } if (y1 > y2) { int t = y1; y1 = y2; y2 = t; } PPath pn = PPath.createRectangle(x1, y1, x2 - x1, y2 - y1); pn.setStrokePaint(currentPenColor); pn.setStroke(stroke); pn.setPaint(currentBrushColor); layer.addChild(pn); } /** * Draw some text at (x,y) using the current pen color and text attributes. If * the current font does NOT support at least one character, it tries to find * a font which is capable of displaying it and use that to render the text. * Note: If the font says it can render a glyph, but in reality it turns out * to be crap, there is nothing we can do about it. */ public void drawText(int x, int y, String text) { int unreadableCharAt = -1; char[] chars = text.toCharArray(); PText pt = new PText(text); pt.setTextPaint(currentPenColor); pt.setFont(currentFont); // Check to see if every character can be displayed by the current font. for (int i = 0; i < chars.length; i++) { if (!currentFont.canDisplay(chars[i])) { // Set to the first not displayable character. unreadableCharAt = i; break; } } // Have to find some working font and use it for this text entry. if (unreadableCharAt != -1) { Font[] allfonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); for (int j = 0; j < allfonts.length; j++) { if (allfonts[j].canDisplay(chars[unreadableCharAt])) { Font tempFont = new Font(allfonts[j].getFontName(), currentFont.getStyle(), currentFont.getSize()); pt.setFont(tempFont); break; } } } pt.setX(x); pt.setY(y); layer.addChild(pt); } /** Set the pen color to an RGB value */ public void pen(int red, int green, int blue) { pen(red, green, blue, 255); } /** Set the pen color to an RGBA value */ public void pen(int red, int green, int blue, int alpha) { currentPenColor = new Color(red, green, blue, alpha); } /** * Define how to display text. Note: underlined is not currently not supported */ public void textAttributes(String font, int pixelSize, boolean bold, boolean italic, boolean underlined) { // For legacy reasons convert "Times" to "Times New Roman" if (font.equals("Times")) { font = "Times New Roman"; } int style = Font.PLAIN; if (bold) { style += Font.BOLD; } if (italic) { style += Font.ITALIC; } currentFont = new Font(font, style, pixelSize); } /** * Zoom the window to the rectangle given the two points (x1,y1) * and (x2,y2), which must be greater than (x1,y1). */ public void zoomRectangle(int x1, int y1, int x2, int y2) { if (x2 > x1 && y2 > y1) { winSizeX = getWidth(); winSizeY = getHeight(); int width = x2 - x1; int height = y2 - y1; // Since piccolo doesn't do this well either, pad with a margin // all the way around. int wmargin = width / 2; int hmargin = height / 2; double scalefactor = Math.min(winSizeX / (2.0 * wmargin + width), winSizeY / (2.0 * hmargin + height)); PCamera lc = canvas.getCamera(); lc.scaleView(scalefactor / lc.getViewScale()); lc.animateViewToPanToBounds(new Rectangle(x1 - hmargin, y1 - hmargin, 2 * wmargin + width, 2 * hmargin + height), 0); } } /** * Flush buffers and update display. * * Only actually reacts if there are no more messages in the stack, to prevent * the canvas from flickering. */ public void update() { // TODO(rays) fix bugs in piccolo or use something else. // The repaint function generates many // exceptions for no good reason. We catch and ignore as many as we // can here, but most of them are generated by the system repaints // caused by resizing/exposing parts of the window etc, and they // generate unwanted stack traces that have to be piped to /dev/null // (on linux). try { repaint(); } catch (NullPointerException e) { // Do nothing so the output isn't full of stack traces. } catch (IllegalPathStateException e) { // Do nothing so the output isn't full of stack traces. } } /** Adds a checkbox entry to the menubar, c.f. SVMenubar.add(...) */ public void addMenuBarItem(String parent, String name, int id, boolean checked) { svMenuBar.add(parent, name, id, checked); } /** Adds a submenu to the menubar, c.f. SVMenubar.add(...) */ public void addMenuBarItem(String parent, String name) { addMenuBarItem(parent, name, -1); } /** Adds a new entry to the menubar, c.f. SVMenubar.add(...) */ public void addMenuBarItem(String parent, String name, int id) { if (svMenuBar == null) { svMenuBar = new SVMenuBar(this); } svMenuBar.add(parent, name, id); } /** Add a message to the message box. */ public void addMessage(String message) { if (ta != null) { ta.append(message + "\n"); } else { System.out.println(message + "\n"); } } /** * This method converts a string which might contain hexadecimal values to a * string which contains the respective unicode counterparts. * * For example, Hall0x0094chen returns Hall<o umlaut>chen * encoded as utf8. * * @param input The original string, containing 0x values * @return The converted string which has the replaced unicode symbols */ private static String convertIntegerStringToUnicodeString(String input) { StringBuffer sb = new StringBuffer(input); Pattern numbers = Pattern.compile("0x[0-9a-fA-F]{4}"); Matcher matcher = numbers.matcher(sb); while (matcher.find()) { // Find the next match which resembles a hexadecimal value and convert it // to // its char value char a = (char) (Integer.decode(matcher.group()).intValue()); // Replace the original with the new character sb.replace(matcher.start(), matcher.end(), String.valueOf(a)); // Start again, since our positions have switched matcher.reset(); } return sb.toString(); } /** * Show a modal input dialog. The answer by the dialog is then send to the * client, together with the associated menu id, as SVET_POPUP * * @param msg The text that is displayed in the dialog. * @param def The default value of the dialog. * @param id The associated commandId * @param evtype The event this is associated with (usually SVET_MENU * or SVET_POPUP) */ public void showInputDialog(String msg, String def, int id, SVEventType evtype) { svEventHandler.timer.stop(); String tmp = (String) JOptionPane.showInputDialog(this, msg, "", JOptionPane.QUESTION_MESSAGE, null, null, def); if (tmp != null) { tmp = convertIntegerStringToUnicodeString(tmp); SVEvent res = new SVEvent(evtype, this, id, tmp); ScrollView.addMessage(res); } svEventHandler.timer.restart(); } /** * Shows a modal input dialog to the user. The return value is automatically * sent to the client as SVET_INPUT event (with command id -1). * * @param msg The text of the dialog. */ public void showInputDialog(String msg) { showInputDialog(msg, null, -1, SVEventType.SVET_INPUT); } /** * Shows a dialog presenting "Yes" and "No" as answers and returns either a * "y" or "n" to the client. * * Closing the dialog without answering is handled like "No". * * @param msg The text that is displayed in the dialog. */ public void showYesNoDialog(String msg) { // res returns 0 on yes, 1 on no. Seems to be a bit counterintuitive int res = JOptionPane.showOptionDialog(this, msg, "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); SVEvent e = new SVEvent(SVEventType.SVET_INPUT, this, 0, 0, 0, 0, res == 0 ? "y" : "n"); ScrollView.addMessage(e); } /** Adds a submenu to the popup menu, c.f. SVPopupMenu.add(...) */ public void addPopupMenuItem(String parent, String name) { if (svPuMenu == null) { svPuMenu = new SVPopupMenu(this); } svPuMenu.add(parent, name, -1); } /** Adds a new menu entry to the popup menu, c.f. SVPopupMenu.add(...) */ public void addPopupMenuItem(String parent, String name, int cmdEvent, String value, String desc) { if (svPuMenu == null) { svPuMenu = new SVPopupMenu(this); } svPuMenu.add(parent, name, cmdEvent, value, desc); } /** Destroys a window. */ public void destroy() { ScrollView.addMessage(new SVEvent(SVEventType.SVET_DESTROY, this, 0, "SVET_DESTROY")); setVisible(false); // dispose(); } }
2301_81045437/tesseract
java/com/google/scrollview/ui/SVWindow.java
Java
apache-2.0
21,613
# =========================================================================== # https://www.gnu.org/software/autoconf-archive/ax_check_compile_flag.html # =========================================================================== # # SYNOPSIS # # AX_CHECK_COMPILE_FLAG(FLAG, [ACTION-SUCCESS], [ACTION-FAILURE], [EXTRA-FLAGS], [INPUT]) # # DESCRIPTION # # Check whether the given FLAG works with the current language's compiler # or gives an error. (Warnings, however, are ignored) # # ACTION-SUCCESS/ACTION-FAILURE are shell commands to execute on # success/failure. # # If EXTRA-FLAGS is defined, it is added to the current language's default # flags (e.g. CFLAGS) when the check is done. The check is thus made with # the flags: "CFLAGS EXTRA-FLAGS FLAG". This can for example be used to # force the compiler to issue an error when a bad flag is given. # # INPUT gives an alternative input source to AC_COMPILE_IFELSE. # # NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. Please keep this # macro in sync with AX_CHECK_{PREPROC,LINK}_FLAG. # # LICENSE # # Copyright (c) 2008 Guido U. Draheim <guidod@gmx.de> # Copyright (c) 2011 Maarten Bosmans <mkbosmans@gmail.com> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 6 AC_DEFUN([AX_CHECK_COMPILE_FLAG], [AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_[]_AC_LANG_ABBREV[]flags_$4_$1])dnl AC_CACHE_CHECK([whether _AC_LANG compiler accepts $1], CACHEVAR, [ ax_check_save_flags=$[]_AC_LANG_PREFIX[]FLAGS _AC_LANG_PREFIX[]FLAGS="$[]_AC_LANG_PREFIX[]FLAGS $4 $1" AC_COMPILE_IFELSE([m4_default([$5],[AC_LANG_PROGRAM()])], [AS_VAR_SET(CACHEVAR,[yes])], [AS_VAR_SET(CACHEVAR,[no])]) _AC_LANG_PREFIX[]FLAGS=$ax_check_save_flags]) AS_VAR_IF(CACHEVAR,yes, [m4_default([$2], :)], [m4_default([$3], :)]) AS_VAR_POPDEF([CACHEVAR])dnl ])dnl AX_CHECK_COMPILE_FLAGS
2301_81045437/tesseract
m4/ax_check_compile_flag.m4
M4Sugar
apache-2.0
2,104
# =========================================================================== # https://www.gnu.org/software/autoconf-archive/ax_split_version.html # =========================================================================== # # SYNOPSIS # # AX_SPLIT_VERSION # # DESCRIPTION # # Splits a version number in the format MAJOR.MINOR.POINT into its # separate components. # # Sets the variables. # # LICENSE # # Copyright (c) 2008 Tom Howard <tomhoward@users.sf.net> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 10 AC_DEFUN([AX_SPLIT_VERSION],[ AC_REQUIRE([AC_PROG_SED]) AX_MAJOR_VERSION=`echo "$VERSION" | $SED 's/\([[^.]][[^.]]*\).*/\1/'` AX_MINOR_VERSION=`echo "$VERSION" | $SED 's/[[^.]][[^.]]*.\([[^.]][[^.]]*\).*/\1/'` AX_POINT_VERSION=`echo "$VERSION" | $SED 's/[[^.]][[^.]]*.[[^.]][[^.]]*.\(.*\)/\1/'` AC_MSG_CHECKING([Major version]) AC_MSG_RESULT([$AX_MAJOR_VERSION]) AC_MSG_CHECKING([Minor version]) AC_MSG_RESULT([$AX_MINOR_VERSION]) AC_MSG_CHECKING([Point version]) AC_MSG_RESULT([$AX_POINT_VERSION]) ])
2301_81045437/tesseract
m4/ax_split_version.m4
M4Sugar
apache-2.0
1,274
// File: altorenderer.cpp // Description: ALTO rendering interface // Author: Jake Sebright // (C) Copyright 2018 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "errcode.h" // for ASSERT_HOST #include "helpers.h" // for copy_string #ifdef _WIN32 # include "host.h" // windows.h for MultiByteToWideChar, ... #endif #include "tprintf.h" // for tprintf #include <tesseract/baseapi.h> #include <tesseract/renderer.h> #include <memory> #include <sstream> // for std::stringstream namespace tesseract { /// Add coordinates to specified TextBlock, TextLine or String bounding box. /// Add word confidence if adding to a String bounding box. /// static void AddBoxToAlto(const ResultIterator *it, PageIteratorLevel level, std::stringstream &alto_str) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); int hpos = left; int vpos = top; int height = bottom - top; int width = right - left; alto_str << " HPOS=\"" << hpos << "\""; alto_str << " VPOS=\"" << vpos << "\""; alto_str << " WIDTH=\"" << width << "\""; alto_str << " HEIGHT=\"" << height << "\""; if (level == RIL_WORD) { int wc = it->Confidence(RIL_WORD); alto_str << " WC=\"0." << wc << "\""; } else { alto_str << ">"; } } /// /// Append the ALTO XML for the beginning of the document /// bool TessAltoRenderer::BeginDocumentHandler() { // Delay the XML output because we need the name of the image file. begin_document = true; return true; } /// /// Append the ALTO XML for the layout of the image /// bool TessAltoRenderer::AddImageHandler(TessBaseAPI *api) { if (begin_document) { AppendString( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<alto xmlns=\"http://www.loc.gov/standards/alto/ns-v3#\" " "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " "xsi:schemaLocation=\"http://www.loc.gov/standards/alto/ns-v3# " "http://www.loc.gov/alto/v3/alto-3-0.xsd\">\n" "\t<Description>\n" "\t\t<MeasurementUnit>pixel</MeasurementUnit>\n" "\t\t<sourceImageInformation>\n" "\t\t\t<fileName>"); AppendString(api->GetInputName()); AppendString( "</fileName>\n" "\t\t</sourceImageInformation>\n" "\t\t<OCRProcessing ID=\"OCR_0\">\n" "\t\t\t<ocrProcessingStep>\n" "\t\t\t\t<processingSoftware>\n" "\t\t\t\t\t<softwareName>tesseract "); AppendString(TessBaseAPI::Version()); AppendString( "</softwareName>\n" "\t\t\t\t</processingSoftware>\n" "\t\t\t</ocrProcessingStep>\n" "\t\t</OCRProcessing>\n" "\t</Description>\n" "\t<Layout>\n"); begin_document = false; } const std::unique_ptr<const char[]> text(api->GetAltoText(imagenum())); if (text == nullptr) { return false; } AppendString(text.get()); return true; } /// /// Append the ALTO XML for the end of the document /// bool TessAltoRenderer::EndDocumentHandler() { AppendString("\t</Layout>\n</alto>\n"); return true; } TessAltoRenderer::TessAltoRenderer(const char *outputbase) : TessResultRenderer(outputbase, "xml"), begin_document(false) {} /// /// Make an XML-formatted string with ALTO markup from the internal /// data structures. /// char *TessBaseAPI::GetAltoText(int page_number) { return GetAltoText(nullptr, page_number); } /// /// Make an XML-formatted string with ALTO markup from the internal /// data structures. /// char *TessBaseAPI::GetAltoText(ETEXT_DESC *monitor, int page_number) { if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(monitor) < 0)) { return nullptr; } int lcnt = 0, tcnt = 0, bcnt = 0, wcnt = 0; if (input_file_.empty()) { SetInputName(nullptr); } #ifdef _WIN32 // convert input name from ANSI encoding to utf-8 int str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_.c_str(), -1, nullptr, 0); wchar_t *uni16_str = new WCHAR[str16_len]; str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_.c_str(), -1, uni16_str, str16_len); int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, nullptr, 0, nullptr, nullptr); char *utf8_str = new char[utf8_len]; WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str, utf8_len, nullptr, nullptr); input_file_ = utf8_str; delete[] uni16_str; delete[] utf8_str; #endif std::stringstream alto_str; // Use "C" locale (needed for int values larger than 999). alto_str.imbue(std::locale::classic()); alto_str << "\t\t<Page WIDTH=\"" << rect_width_ << "\" HEIGHT=\"" << rect_height_ << "\" PHYSICAL_IMG_NR=\"" << page_number << "\"" << " ID=\"page_" << page_number << "\">\n" << "\t\t\t<PrintSpace HPOS=\"0\" VPOS=\"0\"" << " WIDTH=\"" << rect_width_ << "\"" << " HEIGHT=\"" << rect_height_ << "\">\n"; ResultIterator *res_it = GetIterator(); while (!res_it->Empty(RIL_BLOCK)) { if (res_it->Empty(RIL_WORD)) { res_it->Next(RIL_WORD); continue; } int left, top, right, bottom; auto block_type = res_it->BlockType(); switch (block_type) { case PT_FLOWING_IMAGE: case PT_HEADING_IMAGE: case PT_PULLOUT_IMAGE: { // Handle all kinds of images. // TODO: optionally add TYPE, for example TYPE="photo". alto_str << "\t\t\t\t<Illustration ID=\"cblock_" << bcnt++ << "\""; AddBoxToAlto(res_it, RIL_BLOCK, alto_str); alto_str << "</Illustration>\n"; res_it->Next(RIL_BLOCK); continue; } case PT_HORZ_LINE: case PT_VERT_LINE: // Handle horizontal and vertical lines. alto_str << "\t\t\t\t<GraphicalElement ID=\"cblock_" << bcnt++ << "\""; AddBoxToAlto(res_it, RIL_BLOCK, alto_str); alto_str << "</GraphicalElement >\n"; res_it->Next(RIL_BLOCK); continue; case PT_NOISE: tprintf("TODO: Please report image which triggers the noise case.\n"); ASSERT_HOST(false); default: break; } if (res_it->IsAtBeginningOf(RIL_BLOCK)) { alto_str << "\t\t\t\t<ComposedBlock ID=\"cblock_" << bcnt << "\""; AddBoxToAlto(res_it, RIL_BLOCK, alto_str); alto_str << "\n"; } if (res_it->IsAtBeginningOf(RIL_PARA)) { alto_str << "\t\t\t\t\t<TextBlock ID=\"block_" << tcnt << "\""; AddBoxToAlto(res_it, RIL_PARA, alto_str); alto_str << "\n"; } if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { alto_str << "\t\t\t\t\t\t<TextLine ID=\"line_" << lcnt << "\""; AddBoxToAlto(res_it, RIL_TEXTLINE, alto_str); alto_str << "\n"; } alto_str << "\t\t\t\t\t\t\t<String ID=\"string_" << wcnt << "\""; AddBoxToAlto(res_it, RIL_WORD, alto_str); alto_str << " CONTENT=\""; bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD); bool last_word_in_tblock = res_it->IsAtFinalElement(RIL_PARA, RIL_WORD); bool last_word_in_cblock = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD); res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom); do { const std::unique_ptr<const char[]> grapheme(res_it->GetUTF8Text(RIL_SYMBOL)); if (grapheme && grapheme[0] != 0) { alto_str << HOcrEscape(grapheme.get()).c_str(); } res_it->Next(RIL_SYMBOL); } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD)); alto_str << "\"/>"; wcnt++; if (last_word_in_line) { alto_str << "\n\t\t\t\t\t\t</TextLine>\n"; lcnt++; } else { int hpos = right; int vpos = top; res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom); int width = left - hpos; alto_str << "<SP WIDTH=\"" << width << "\" VPOS=\"" << vpos << "\" HPOS=\"" << hpos << "\"/>\n"; } if (last_word_in_tblock) { alto_str << "\t\t\t\t\t</TextBlock>\n"; tcnt++; } if (last_word_in_cblock) { alto_str << "\t\t\t\t</ComposedBlock>\n"; bcnt++; } } alto_str << "\t\t\t</PrintSpace>\n" << "\t\t</Page>\n"; delete res_it; return copy_string(alto_str.str()); } } // namespace tesseract
2301_81045437/tesseract
src/api/altorenderer.cpp
C++
apache-2.0
8,666
/********************************************************************** * File: baseapi.cpp * Description: Simple API for calling tesseract. * Author: Ray Smith * * (C) Copyright 2006, Google Inc. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #define _USE_MATH_DEFINES // for M_PI // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H # include "config_auto.h" #endif #include "boxword.h" // for BoxWord #include "coutln.h" // for C_OUTLINE_IT, C_OUTLINE_LIST #include "dawg_cache.h" // for DawgCache #include "dict.h" // for Dict #include "elst.h" // for ELIST_ITERATOR, ELISTIZE, ELISTIZEH #include "environ.h" // for l_uint8 #ifndef DISABLED_LEGACY_ENGINE #include "equationdetect.h" // for EquationDetect, destructor of equ_detect_ #endif // ndef DISABLED_LEGACY_ENGINE #include "errcode.h" // for ASSERT_HOST #include "helpers.h" // for IntCastRounded, chomp_string, copy_string #include "host.h" // for MAX_PATH #include "imageio.h" // for IFF_TIFF_G4, IFF_TIFF, IFF_TIFF_G3, ... #ifndef DISABLED_LEGACY_ENGINE # include "intfx.h" // for INT_FX_RESULT_STRUCT #endif #include "mutableiterator.h" // for MutableIterator #include "normalis.h" // for kBlnBaselineOffset, kBlnXHeight #include "pageres.h" // for PAGE_RES_IT, WERD_RES, PAGE_RES, CR_DE... #include "paragraphs.h" // for DetectParagraphs #include "params.h" // for BoolParam, IntParam, DoubleParam, Stri... #include "pdblock.h" // for PDBLK #include "points.h" // for FCOORD #include "polyblk.h" // for POLY_BLOCK #include "rect.h" // for TBOX #include "stepblob.h" // for C_BLOB_IT, C_BLOB, C_BLOB_LIST #include "tessdatamanager.h" // for TessdataManager, kTrainedDataSuffix #include "tesseractclass.h" // for Tesseract #include "tprintf.h" // for tprintf #include "werd.h" // for WERD, WERD_IT, W_FUZZY_NON, W_FUZZY_SP #include "thresholder.h" // for ImageThresholder #include <tesseract/baseapi.h> #include <tesseract/ocrclass.h> // for ETEXT_DESC #include <tesseract/osdetect.h> // for OSResults, OSBestResult, OrientationId... #include <tesseract/renderer.h> // for TessResultRenderer #include <tesseract/resultiterator.h> // for ResultIterator #include <cmath> // for round, M_PI #include <cstdint> // for int32_t #include <cstring> // for strcmp, strcpy #include <fstream> // for size_t #include <iostream> // for std::cin #include <locale> // for std::locale::classic #include <memory> // for std::unique_ptr #include <set> // for std::pair #include <sstream> // for std::stringstream #include <vector> // for std::vector #include <allheaders.h> // for pixDestroy, boxCreate, boxaAddBox, box... #ifdef HAVE_LIBCURL # include <curl/curl.h> #endif #ifdef __linux__ # include <csignal> // for sigaction, SA_RESETHAND, SIGBUS, SIGFPE #endif #if defined(_WIN32) # include <fcntl.h> # include <io.h> #else # include <dirent.h> // for closedir, opendir, readdir, DIR, dirent # include <libgen.h> # include <sys/stat.h> // for stat, S_IFDIR # include <sys/types.h> # include <unistd.h> #endif // _WIN32 namespace tesseract { static BOOL_VAR(stream_filelist, false, "Stream a filelist from stdin"); static STRING_VAR(document_title, "", "Title of output document (used for hOCR and PDF output)"); #ifdef HAVE_LIBCURL static INT_VAR(curl_timeout, 0, "Timeout for curl in seconds"); static STRING_VAR(curl_cookiefile, "", "File with cookie data for curl"); #endif /** Minimum sensible image size to be worth running Tesseract. */ const int kMinRectSize = 10; /** Character returned when Tesseract couldn't recognize as anything. */ const char kTesseractReject = '~'; /** Character used by UNLV error counter as a reject. */ const char kUNLVReject = '~'; /** Character used by UNLV as a suspect marker. */ const char kUNLVSuspect = '^'; /** * Temp file used for storing current parameters before applying retry values. */ static const char *kOldVarsFile = "failed_vars.txt"; #ifndef DISABLED_LEGACY_ENGINE /** * Filename used for input image file, from which to derive a name to search * for a possible UNLV zone file, if none is specified by SetInputName. */ static const char *kInputFile = "noname.tif"; static const char kUnknownFontName[] = "UnknownFont"; static STRING_VAR(classify_font_name, kUnknownFontName, "Default font name to be used in training"); // Finds the name of the training font and returns it in fontname, by cutting // it out based on the expectation that the filename is of the form: // /path/to/dir/[lang].[fontname].exp[num] // The [lang], [fontname] and [num] fields should not have '.' characters. // If the global parameter classify_font_name is set, its value is used instead. static void ExtractFontName(const char* filename, std::string* fontname) { *fontname = classify_font_name; if (*fontname == kUnknownFontName) { // filename is expected to be of the form [lang].[fontname].exp[num] // The [lang], [fontname] and [num] fields should not have '.' characters. const char *basename = strrchr(filename, '/'); const char *firstdot = strchr(basename ? basename : filename, '.'); const char *lastdot = strrchr(filename, '.'); if (firstdot != lastdot && firstdot != nullptr && lastdot != nullptr) { ++firstdot; *fontname = firstdot; fontname->resize(lastdot - firstdot); } } } #endif /* Add all available languages recursively. */ static void addAvailableLanguages(const std::string &datadir, const std::string &base, std::vector<std::string> *langs) { auto base2 = base; if (!base2.empty()) { base2 += "/"; } const size_t extlen = sizeof(kTrainedDataSuffix); #ifdef _WIN32 WIN32_FIND_DATA data; HANDLE handle = FindFirstFile((datadir + base2 + "*").c_str(), &data); if (handle != INVALID_HANDLE_VALUE) { BOOL result = TRUE; for (; result;) { char *name = data.cFileName; // Skip '.', '..', and hidden files if (name[0] != '.') { if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) { addAvailableLanguages(datadir, base2 + name, langs); } else { size_t len = strlen(name); if (len > extlen && name[len - extlen] == '.' && strcmp(&name[len - extlen + 1], kTrainedDataSuffix) == 0) { name[len - extlen] = '\0'; langs->push_back(base2 + name); } } } result = FindNextFile(handle, &data); } FindClose(handle); } #else // _WIN32 DIR *dir = opendir((datadir + base).c_str()); if (dir != nullptr) { dirent *de; while ((de = readdir(dir))) { char *name = de->d_name; // Skip '.', '..', and hidden files if (name[0] != '.') { struct stat st; if (stat((datadir + base2 + name).c_str(), &st) == 0 && (st.st_mode & S_IFDIR) == S_IFDIR) { addAvailableLanguages(datadir, base2 + name, langs); } else { size_t len = strlen(name); if (len > extlen && name[len - extlen] == '.' && strcmp(&name[len - extlen + 1], kTrainedDataSuffix) == 0) { name[len - extlen] = '\0'; langs->push_back(base2 + name); } } } } closedir(dir); } #endif } TessBaseAPI::TessBaseAPI() : tesseract_(nullptr) , osd_tesseract_(nullptr) , equ_detect_(nullptr) , reader_(nullptr) , // thresholder_ is initialized to nullptr here, but will be set before use // by: A constructor of a derived API or created // implicitly when used in InternalSetImage. thresholder_(nullptr) , paragraph_models_(nullptr) , block_list_(nullptr) , page_res_(nullptr) , last_oem_requested_(OEM_DEFAULT) , recognition_done_(false) , rect_left_(0) , rect_top_(0) , rect_width_(0) , rect_height_(0) , image_width_(0) , image_height_(0) { } TessBaseAPI::~TessBaseAPI() { End(); } /** * Returns the version identifier as a static string. Do not delete. */ const char *TessBaseAPI::Version() { return TESSERACT_VERSION_STR; } /** * Set the name of the input file. Needed only for training and * loading a UNLV zone file. */ void TessBaseAPI::SetInputName(const char *name) { input_file_ = name ? name : ""; } /** Set the name of the output files. Needed only for debugging. */ void TessBaseAPI::SetOutputName(const char *name) { output_file_ = name ? name : ""; } bool TessBaseAPI::SetVariable(const char *name, const char *value) { if (tesseract_ == nullptr) { tesseract_ = new Tesseract; } return ParamUtils::SetParam(name, value, SET_PARAM_CONSTRAINT_NON_INIT_ONLY, tesseract_->params()); } bool TessBaseAPI::SetDebugVariable(const char *name, const char *value) { if (tesseract_ == nullptr) { tesseract_ = new Tesseract; } return ParamUtils::SetParam(name, value, SET_PARAM_CONSTRAINT_DEBUG_ONLY, tesseract_->params()); } bool TessBaseAPI::GetIntVariable(const char *name, int *value) const { auto *p = ParamUtils::FindParam<IntParam>(name, GlobalParams()->int_params, tesseract_->params()->int_params); if (p == nullptr) { return false; } *value = (int32_t)(*p); return true; } bool TessBaseAPI::GetBoolVariable(const char *name, bool *value) const { auto *p = ParamUtils::FindParam<BoolParam>(name, GlobalParams()->bool_params, tesseract_->params()->bool_params); if (p == nullptr) { return false; } *value = bool(*p); return true; } const char *TessBaseAPI::GetStringVariable(const char *name) const { auto *p = ParamUtils::FindParam<StringParam>(name, GlobalParams()->string_params, tesseract_->params()->string_params); return (p != nullptr) ? p->c_str() : nullptr; } bool TessBaseAPI::GetDoubleVariable(const char *name, double *value) const { auto *p = ParamUtils::FindParam<DoubleParam>(name, GlobalParams()->double_params, tesseract_->params()->double_params); if (p == nullptr) { return false; } *value = (double)(*p); return true; } /** Get value of named variable as a string, if it exists. */ bool TessBaseAPI::GetVariableAsString(const char *name, std::string *val) const { return ParamUtils::GetParamAsString(name, tesseract_->params(), val); } #ifndef DISABLED_LEGACY_ENGINE /** Print Tesseract fonts table to the given file. */ void TessBaseAPI::PrintFontsTable(FILE *fp) const { const int fontinfo_size = tesseract_->get_fontinfo_table().size(); for (int font_index = 1; font_index < fontinfo_size; ++font_index) { FontInfo font = tesseract_->get_fontinfo_table().at(font_index); fprintf(fp, "ID=%3d: %s is_italic=%s is_bold=%s" " is_fixed_pitch=%s is_serif=%s is_fraktur=%s\n", font_index, font.name, font.is_italic() ? "true" : "false", font.is_bold() ? "true" : "false", font.is_fixed_pitch() ? "true" : "false", font.is_serif() ? "true" : "false", font.is_fraktur() ? "true" : "false"); } } #endif /** Print Tesseract parameters to the given file. */ void TessBaseAPI::PrintVariables(FILE *fp) const { ParamUtils::PrintParams(fp, tesseract_->params()); } /** * The datapath must be the name of the data directory or * some other file in which the data directory resides (for instance argv[0].) * The language is (usually) an ISO 639-3 string or nullptr will default to eng. * If numeric_mode is true, then only digits and Roman numerals will * be returned. * @return: 0 on success and -1 on initialization failure. */ int TessBaseAPI::Init(const char *datapath, const char *language, OcrEngineMode oem, char **configs, int configs_size, const std::vector<std::string> *vars_vec, const std::vector<std::string> *vars_values, bool set_only_non_debug_params) { return Init(datapath, 0, language, oem, configs, configs_size, vars_vec, vars_values, set_only_non_debug_params, nullptr); } // In-memory version reads the traineddata file directly from the given // data[data_size] array. Also implements the version with a datapath in data, // flagged by data_size = 0. int TessBaseAPI::Init(const char *data, int data_size, const char *language, OcrEngineMode oem, char **configs, int configs_size, const std::vector<std::string> *vars_vec, const std::vector<std::string> *vars_values, bool set_only_non_debug_params, FileReader reader) { if (language == nullptr) { language = ""; } if (data == nullptr) { data = ""; } std::string datapath = data_size == 0 ? data : language; // If the datapath, OcrEngineMode or the language have changed - start again. // Note that the language_ field stores the last requested language that was // initialized successfully, while tesseract_->lang stores the language // actually used. They differ only if the requested language was nullptr, in // which case tesseract_->lang is set to the Tesseract default ("eng"). if (tesseract_ != nullptr && (datapath_.empty() || language_.empty() || datapath_ != datapath || last_oem_requested_ != oem || (language_ != language && tesseract_->lang != language))) { delete tesseract_; tesseract_ = nullptr; } bool reset_classifier = true; if (tesseract_ == nullptr) { reset_classifier = false; tesseract_ = new Tesseract; if (reader != nullptr) { reader_ = reader; } TessdataManager mgr(reader_); if (data_size != 0) { mgr.LoadMemBuffer(language, data, data_size); } if (tesseract_->init_tesseract(datapath, output_file_, language, oem, configs, configs_size, vars_vec, vars_values, set_only_non_debug_params, &mgr) != 0) { return -1; } } // Update datapath and language requested for the last valid initialization. datapath_ = std::move(datapath); if (datapath_.empty() && !tesseract_->datadir.empty()) { datapath_ = tesseract_->datadir; } language_ = language; last_oem_requested_ = oem; #ifndef DISABLED_LEGACY_ENGINE // For same language and datapath, just reset the adaptive classifier. if (reset_classifier) { tesseract_->ResetAdaptiveClassifier(); } #endif // ndef DISABLED_LEGACY_ENGINE return 0; } /** * Returns the languages string used in the last valid initialization. * If the last initialization specified "deu+hin" then that will be * returned. If hin loaded eng automatically as well, then that will * not be included in this list. To find the languages actually * loaded use GetLoadedLanguagesAsVector. * The returned string should NOT be deleted. */ const char *TessBaseAPI::GetInitLanguagesAsString() const { return language_.c_str(); } /** * Returns the loaded languages in the vector of std::string. * Includes all languages loaded by the last Init, including those loaded * as dependencies of other loaded languages. */ void TessBaseAPI::GetLoadedLanguagesAsVector(std::vector<std::string> *langs) const { langs->clear(); if (tesseract_ != nullptr) { langs->push_back(tesseract_->lang); int num_subs = tesseract_->num_sub_langs(); for (int i = 0; i < num_subs; ++i) { langs->push_back(tesseract_->get_sub_lang(i)->lang); } } } /** * Returns the available languages in the sorted vector of std::string. */ void TessBaseAPI::GetAvailableLanguagesAsVector(std::vector<std::string> *langs) const { langs->clear(); if (tesseract_ != nullptr) { addAvailableLanguages(tesseract_->datadir, "", langs); std::sort(langs->begin(), langs->end()); } } /** * Init only for page layout analysis. Use only for calls to SetImage and * AnalysePage. Calls that attempt recognition will generate an error. */ void TessBaseAPI::InitForAnalysePage() { if (tesseract_ == nullptr) { tesseract_ = new Tesseract; #ifndef DISABLED_LEGACY_ENGINE tesseract_->InitAdaptiveClassifier(nullptr); #endif } } /** * Read a "config" file containing a set of parameter name, value pairs. * Searches the standard places: tessdata/configs, tessdata/tessconfigs * and also accepts a relative or absolute path name. */ void TessBaseAPI::ReadConfigFile(const char *filename) { tesseract_->read_config_file(filename, SET_PARAM_CONSTRAINT_NON_INIT_ONLY); } /** Same as above, but only set debug params from the given config file. */ void TessBaseAPI::ReadDebugConfigFile(const char *filename) { tesseract_->read_config_file(filename, SET_PARAM_CONSTRAINT_DEBUG_ONLY); } /** * Set the current page segmentation mode. Defaults to PSM_AUTO. * The mode is stored as an IntParam so it can also be modified by * ReadConfigFile or SetVariable("tessedit_pageseg_mode", mode as string). */ void TessBaseAPI::SetPageSegMode(PageSegMode mode) { if (tesseract_ == nullptr) { tesseract_ = new Tesseract; } tesseract_->tessedit_pageseg_mode.set_value(mode); } /** Return the current page segmentation mode. */ PageSegMode TessBaseAPI::GetPageSegMode() const { if (tesseract_ == nullptr) { return PSM_SINGLE_BLOCK; } return static_cast<PageSegMode>(static_cast<int>(tesseract_->tessedit_pageseg_mode)); } /** * Recognize a rectangle from an image and return the result as a string. * May be called many times for a single Init. * Currently has no error checking. * Greyscale of 8 and color of 24 or 32 bits per pixel may be given. * Palette color images will not work properly and must be converted to * 24 bit. * Binary images of 1 bit per pixel may also be given but they must be * byte packed with the MSB of the first byte being the first pixel, and a * one pixel is WHITE. For binary images set bytes_per_pixel=0. * The recognized text is returned as a char* which is coded * as UTF8 and must be freed with the delete [] operator. */ char *TessBaseAPI::TesseractRect(const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height) { if (tesseract_ == nullptr || width < kMinRectSize || height < kMinRectSize) { return nullptr; // Nothing worth doing. } // Since this original api didn't give the exact size of the image, // we have to invent a reasonable value. int bits_per_pixel = bytes_per_pixel == 0 ? 1 : bytes_per_pixel * 8; SetImage(imagedata, bytes_per_line * 8 / bits_per_pixel, height + top, bytes_per_pixel, bytes_per_line); SetRectangle(left, top, width, height); return GetUTF8Text(); } #ifndef DISABLED_LEGACY_ENGINE /** * Call between pages or documents etc to free up memory and forget * adaptive data. */ void TessBaseAPI::ClearAdaptiveClassifier() { if (tesseract_ == nullptr) { return; } tesseract_->ResetAdaptiveClassifier(); tesseract_->ResetDocumentDictionary(); } #endif // ndef DISABLED_LEGACY_ENGINE /** * Provide an image for Tesseract to recognize. Format is as * TesseractRect above. Copies the image buffer and converts to Pix. * SetImage clears all recognition results, and sets the rectangle to the * full image, so it may be followed immediately by a GetUTF8Text, and it * will automatically perform recognition. */ void TessBaseAPI::SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line) { if (InternalSetImage()) { thresholder_->SetImage(imagedata, width, height, bytes_per_pixel, bytes_per_line); SetInputImage(thresholder_->GetPixRect()); } } void TessBaseAPI::SetSourceResolution(int ppi) { if (thresholder_) { thresholder_->SetSourceYResolution(ppi); } else { tprintf("Please call SetImage before SetSourceResolution.\n"); } } /** * Provide an image for Tesseract to recognize. As with SetImage above, * Tesseract takes its own copy of the image, so it need not persist until * after Recognize. * Pix vs raw, which to use? * Use Pix where possible. Tesseract uses Pix as its internal representation * and it is therefore more efficient to provide a Pix directly. */ void TessBaseAPI::SetImage(Pix *pix) { if (InternalSetImage()) { if (pixGetSpp(pix) == 4 && pixGetInputFormat(pix) == IFF_PNG) { // remove alpha channel from png Pix *p1 = pixRemoveAlpha(pix); pixSetSpp(p1, 3); (void)pixCopy(pix, p1); pixDestroy(&p1); } thresholder_->SetImage(pix); SetInputImage(thresholder_->GetPixRect()); } } /** * Restrict recognition to a sub-rectangle of the image. Call after SetImage. * Each SetRectangle clears the recognition results so multiple rectangles * can be recognized with the same image. */ void TessBaseAPI::SetRectangle(int left, int top, int width, int height) { if (thresholder_ == nullptr) { return; } thresholder_->SetRectangle(left, top, width, height); ClearResults(); } /** * ONLY available after SetImage if you have Leptonica installed. * Get a copy of the internal thresholded image from Tesseract. */ Pix *TessBaseAPI::GetThresholdedImage() { if (tesseract_ == nullptr || thresholder_ == nullptr) { return nullptr; } if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) { return nullptr; } return tesseract_->pix_binary().clone(); } /** * Get the result of page layout analysis as a leptonica-style * Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. */ Boxa *TessBaseAPI::GetRegions(Pixa **pixa) { return GetComponentImages(RIL_BLOCK, false, pixa, nullptr); } /** * Get the textlines as a leptonica-style Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. * If blockids is not nullptr, the block-id of each line is also returned as an * array of one element per line. delete [] after use. * If paraids is not nullptr, the paragraph-id of each line within its block is * also returned as an array of one element per line. delete [] after use. */ Boxa *TessBaseAPI::GetTextlines(const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids) { return GetComponentImages(RIL_TEXTLINE, true, raw_image, raw_padding, pixa, blockids, paraids); } /** * Get textlines and strips of image regions as a leptonica-style Boxa, Pixa * pair, in reading order. Enables downstream handling of non-rectangular * regions. * Can be called before or after Recognize. * If blockids is not nullptr, the block-id of each line is also returned as an * array of one element per line. delete [] after use. */ Boxa *TessBaseAPI::GetStrips(Pixa **pixa, int **blockids) { return GetComponentImages(RIL_TEXTLINE, false, pixa, blockids); } /** * Get the words as a leptonica-style * Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. */ Boxa *TessBaseAPI::GetWords(Pixa **pixa) { return GetComponentImages(RIL_WORD, true, pixa, nullptr); } /** * Gets the individual connected (text) components (created * after pages segmentation step, but before recognition) * as a leptonica-style Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. */ Boxa *TessBaseAPI::GetConnectedComponents(Pixa **pixa) { return GetComponentImages(RIL_SYMBOL, true, pixa, nullptr); } /** * Get the given level kind of components (block, textline, word etc.) as a * leptonica-style Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. * If blockids is not nullptr, the block-id of each component is also returned * as an array of one element per component. delete [] after use. * If text_only is true, then only text components are returned. */ Boxa *TessBaseAPI::GetComponentImages(PageIteratorLevel level, bool text_only, bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids) { /*non-const*/ std::unique_ptr</*non-const*/ PageIterator> page_it(GetIterator()); if (page_it == nullptr) { page_it.reset(AnalyseLayout()); } if (page_it == nullptr) { return nullptr; // Failed. } // Count the components to get a size for the arrays. int component_count = 0; int left, top, right, bottom; if (raw_image) { // Get bounding box in original raw image with padding. do { if (page_it->BoundingBox(level, raw_padding, &left, &top, &right, &bottom) && (!text_only || PTIsTextType(page_it->BlockType()))) { ++component_count; } } while (page_it->Next(level)); } else { // Get bounding box from binarized imaged. Note that this could be // differently scaled from the original image. do { if (page_it->BoundingBoxInternal(level, &left, &top, &right, &bottom) && (!text_only || PTIsTextType(page_it->BlockType()))) { ++component_count; } } while (page_it->Next(level)); } Boxa *boxa = boxaCreate(component_count); if (pixa != nullptr) { *pixa = pixaCreate(component_count); } if (blockids != nullptr) { *blockids = new int[component_count]; } if (paraids != nullptr) { *paraids = new int[component_count]; } int blockid = 0; int paraid = 0; int component_index = 0; page_it->Begin(); do { bool got_bounding_box; if (raw_image) { got_bounding_box = page_it->BoundingBox(level, raw_padding, &left, &top, &right, &bottom); } else { got_bounding_box = page_it->BoundingBoxInternal(level, &left, &top, &right, &bottom); } if (got_bounding_box && (!text_only || PTIsTextType(page_it->BlockType()))) { Box *lbox = boxCreate(left, top, right - left, bottom - top); boxaAddBox(boxa, lbox, L_INSERT); if (pixa != nullptr) { Pix *pix = nullptr; if (raw_image) { pix = page_it->GetImage(level, raw_padding, GetInputImage(), &left, &top); } else { pix = page_it->GetBinaryImage(level); } pixaAddPix(*pixa, pix, L_INSERT); pixaAddBox(*pixa, lbox, L_CLONE); } if (paraids != nullptr) { (*paraids)[component_index] = paraid; if (page_it->IsAtFinalElement(RIL_PARA, level)) { ++paraid; } } if (blockids != nullptr) { (*blockids)[component_index] = blockid; if (page_it->IsAtFinalElement(RIL_BLOCK, level)) { ++blockid; paraid = 0; } } ++component_index; } } while (page_it->Next(level)); return boxa; } int TessBaseAPI::GetThresholdedImageScaleFactor() const { if (thresholder_ == nullptr) { return 0; } return thresholder_->GetScaleFactor(); } /** * Runs page layout analysis in the mode set by SetPageSegMode. * May optionally be called prior to Recognize to get access to just * the page layout results. Returns an iterator to the results. * If merge_similar_words is true, words are combined where suitable for use * with a line recognizer. Use if you want to use AnalyseLayout to find the * textlines, and then want to process textline fragments with an external * line recognizer. * Returns nullptr on error or an empty page. * The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ PageIterator *TessBaseAPI::AnalyseLayout() { return AnalyseLayout(false); } PageIterator *TessBaseAPI::AnalyseLayout(bool merge_similar_words) { if (FindLines() == 0) { if (block_list_->empty()) { return nullptr; // The page was empty. } page_res_ = new PAGE_RES(merge_similar_words, block_list_, nullptr); DetectParagraphs(false); return new PageIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } return nullptr; } /** * Recognize the tesseract global image and return the result as Tesseract * internal structures. */ int TessBaseAPI::Recognize(ETEXT_DESC *monitor) { if (tesseract_ == nullptr) { return -1; } if (FindLines() != 0) { return -1; } delete page_res_; if (block_list_->empty()) { page_res_ = new PAGE_RES(false, block_list_, &tesseract_->prev_word_best_choice_); return 0; // Empty page. } tesseract_->SetBlackAndWhitelist(); recognition_done_ = true; #ifndef DISABLED_LEGACY_ENGINE if (tesseract_->tessedit_resegment_from_line_boxes) { page_res_ = tesseract_->ApplyBoxes(input_file_.c_str(), true, block_list_); } else if (tesseract_->tessedit_resegment_from_boxes) { page_res_ = tesseract_->ApplyBoxes(input_file_.c_str(), false, block_list_); } else #endif // ndef DISABLED_LEGACY_ENGINE { page_res_ = new PAGE_RES(tesseract_->AnyLSTMLang(), block_list_, &tesseract_->prev_word_best_choice_); } if (page_res_ == nullptr) { return -1; } if (tesseract_->tessedit_train_line_recognizer) { if (!tesseract_->TrainLineRecognizer(input_file_.c_str(), output_file_, block_list_)) { return -1; } tesseract_->CorrectClassifyWords(page_res_); return 0; } #ifndef DISABLED_LEGACY_ENGINE if (tesseract_->tessedit_make_boxes_from_boxes) { tesseract_->CorrectClassifyWords(page_res_); return 0; } #endif // ndef DISABLED_LEGACY_ENGINE int result = 0; if (tesseract_->interactive_display_mode) { #ifndef GRAPHICS_DISABLED tesseract_->pgeditor_main(rect_width_, rect_height_, page_res_); #endif // !GRAPHICS_DISABLED // The page_res is invalid after an interactive session, so cleanup // in a way that lets us continue to the next page without crashing. delete page_res_; page_res_ = nullptr; return -1; #ifndef DISABLED_LEGACY_ENGINE } else if (tesseract_->tessedit_train_from_boxes) { std::string fontname; ExtractFontName(output_file_.c_str(), &fontname); tesseract_->ApplyBoxTraining(fontname, page_res_); } else if (tesseract_->tessedit_ambigs_training) { FILE *training_output_file = tesseract_->init_recog_training(input_file_.c_str()); // OCR the page segmented into words by tesseract. tesseract_->recog_training_segmented(input_file_.c_str(), page_res_, monitor, training_output_file); fclose(training_output_file); #endif // ndef DISABLED_LEGACY_ENGINE } else { // Now run the main recognition. bool wait_for_text = true; GetBoolVariable("paragraph_text_based", &wait_for_text); if (!wait_for_text) { DetectParagraphs(false); } if (tesseract_->recog_all_words(page_res_, monitor, nullptr, nullptr, 0)) { if (wait_for_text) { DetectParagraphs(true); } } else { result = -1; } } return result; } // Takes ownership of the input pix. void TessBaseAPI::SetInputImage(Pix *pix) { tesseract_->set_pix_original(pix); } Pix *TessBaseAPI::GetInputImage() { return tesseract_->pix_original(); } const char *TessBaseAPI::GetInputName() { if (!input_file_.empty()) { return input_file_.c_str(); } return nullptr; } const char *TessBaseAPI::GetDatapath() { return tesseract_->datadir.c_str(); } int TessBaseAPI::GetSourceYResolution() { if (thresholder_ == nullptr) return -1; return thresholder_->GetSourceYResolution(); } // If flist exists, get data from there. Otherwise get data from buf. // Seems convoluted, but is the easiest way I know of to meet multiple // goals. Support streaming from stdin, and also work on platforms // lacking fmemopen. // TODO: check different logic for flist/buf and simplify. bool TessBaseAPI::ProcessPagesFileList(FILE *flist, std::string *buf, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer, int tessedit_page_number) { if (!flist && !buf) { return false; } unsigned page = (tessedit_page_number >= 0) ? tessedit_page_number : 0; char pagename[MAX_PATH]; std::vector<std::string> lines; if (!flist) { std::string line; for (const auto ch : *buf) { if (ch == '\n') { lines.push_back(line); line.clear(); } else { line.push_back(ch); } } if (!line.empty()) { // Add last line without terminating LF. lines.push_back(line); } if (lines.empty()) { return false; } } // Skip to the requested page number. for (unsigned i = 0; i < page; i++) { if (flist) { if (fgets(pagename, sizeof(pagename), flist) == nullptr) { break; } } } // Begin producing output if (renderer && !renderer->BeginDocument(document_title.c_str())) { return false; } // Loop over all pages - or just the requested one while (true) { if (flist) { if (fgets(pagename, sizeof(pagename), flist) == nullptr) { break; } } else { if (page >= lines.size()) { break; } snprintf(pagename, sizeof(pagename), "%s", lines[page].c_str()); } chomp_string(pagename); Pix *pix = pixRead(pagename); if (pix == nullptr) { tprintf("Image file %s cannot be read!\n", pagename); return false; } tprintf("Page %u : %s\n", page, pagename); bool r = ProcessPage(pix, page, pagename, retry_config, timeout_millisec, renderer); pixDestroy(&pix); if (!r) { return false; } if (tessedit_page_number >= 0) { break; } ++page; } // Finish producing output if (renderer && !renderer->EndDocument()) { return false; } return true; } bool TessBaseAPI::ProcessPagesMultipageTiff(const l_uint8 *data, size_t size, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer, int tessedit_page_number) { Pix *pix = nullptr; int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0; size_t offset = 0; for (;; ++page) { if (tessedit_page_number >= 0) { page = tessedit_page_number; pix = (data) ? pixReadMemTiff(data, size, page) : pixReadTiff(filename, page); } else { pix = (data) ? pixReadMemFromMultipageTiff(data, size, &offset) : pixReadFromMultipageTiff(filename, &offset); } if (pix == nullptr) { break; } if (offset || page > 0) { // Only print page number for multipage TIFF file. tprintf("Page %d\n", page + 1); } auto page_string = std::to_string(page); SetVariable("applybox_page", page_string.c_str()); bool r = ProcessPage(pix, page, filename, retry_config, timeout_millisec, renderer); pixDestroy(&pix); if (!r) { return false; } if (tessedit_page_number >= 0) { break; } if (!offset) { break; } } return true; } // Master ProcessPages calls ProcessPagesInternal and then does any post- // processing required due to being in a training mode. bool TessBaseAPI::ProcessPages(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer) { bool result = ProcessPagesInternal(filename, retry_config, timeout_millisec, renderer); #ifndef DISABLED_LEGACY_ENGINE if (result) { if (tesseract_->tessedit_train_from_boxes && !tesseract_->WriteTRFile(output_file_.c_str())) { tprintf("Write of TR file failed: %s\n", output_file_.c_str()); return false; } } #endif // ndef DISABLED_LEGACY_ENGINE return result; } #ifdef HAVE_LIBCURL static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size = size * nmemb; auto *buf = reinterpret_cast<std::string *>(userp); buf->append(reinterpret_cast<const char *>(contents), size); return size; } #endif // In the ideal scenario, Tesseract will start working on data as soon // as it can. For example, if you stream a filelist through stdin, we // should start the OCR process as soon as the first filename is // available. This is particularly useful when hooking Tesseract up to // slow hardware such as a book scanning machine. // // Unfortunately there are tradeoffs. You can't seek on stdin. That // makes automatic detection of datatype (TIFF? filelist? PNG?) // impractical. So we support a command line flag to explicitly // identify the scenario that really matters: filelists on // stdin. We'll still do our best if the user likes pipes. bool TessBaseAPI::ProcessPagesInternal(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer) { bool stdInput = !strcmp(filename, "stdin") || !strcmp(filename, "-"); if (stdInput) { #ifdef WIN32 if (_setmode(_fileno(stdin), _O_BINARY) == -1) tprintf("ERROR: cin to binary: %s", strerror(errno)); #endif // WIN32 } if (stream_filelist) { return ProcessPagesFileList(stdin, nullptr, retry_config, timeout_millisec, renderer, tesseract_->tessedit_page_number); } // At this point we are officially in autodection territory. // That means any data in stdin must be buffered, to make it // seekable. std::string buf; const l_uint8 *data = nullptr; if (stdInput) { buf.assign((std::istreambuf_iterator<char>(std::cin)), (std::istreambuf_iterator<char>())); data = reinterpret_cast<const l_uint8 *>(buf.data()); } else if (strstr(filename, "://") != nullptr) { // Get image or image list by URL. #ifdef HAVE_LIBCURL CURL *curl = curl_easy_init(); if (curl == nullptr) { fprintf(stderr, "Error, curl_easy_init failed\n"); return false; } else { CURLcode curlcode; auto error = [curl, &curlcode](const char *function) { fprintf(stderr, "Error, %s failed with error %s\n", function, curl_easy_strerror(curlcode)); curl_easy_cleanup(curl); return false; }; curlcode = curl_easy_setopt(curl, CURLOPT_URL, filename); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } // Follow HTTP, HTTPS, FTP and FTPS redirects. curlcode = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } // Allow no more than 8 redirections to prevent endless loops. curlcode = curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 8); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } int timeout = curl_timeout; if (timeout > 0) { curlcode = curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } } std::string cookiefile = curl_cookiefile; if (!cookiefile.empty()) { curlcode = curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookiefile.c_str()); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } } curlcode = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_setopt(curl, CURLOPT_USERAGENT, "Tesseract OCR"); if (curlcode != CURLE_OK) { return error("curl_easy_setopt"); } curlcode = curl_easy_perform(curl); if (curlcode != CURLE_OK) { return error("curl_easy_perform"); } curl_easy_cleanup(curl); data = reinterpret_cast<const l_uint8 *>(buf.data()); } #else fprintf(stderr, "Error, this tesseract has no URL support\n"); return false; #endif } else { // Check whether the input file can be read. if (FILE *file = fopen(filename, "rb")) { fclose(file); } else { fprintf(stderr, "Error, cannot read input file %s: %s\n", filename, strerror(errno)); return false; } } // Here is our autodetection int format; int r = (data != nullptr) ? findFileFormatBuffer(data, &format) : findFileFormat(filename, &format); // Maybe we have a filelist if (r != 0 || format == IFF_UNKNOWN) { std::string s; if (data != nullptr) { s = buf.c_str(); } else { std::ifstream t(filename); std::string u((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); s = u.c_str(); } return ProcessPagesFileList(nullptr, &s, retry_config, timeout_millisec, renderer, tesseract_->tessedit_page_number); } // Maybe we have a TIFF which is potentially multipage bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS || format == IFF_TIFF_RLE || format == IFF_TIFF_G3 || format == IFF_TIFF_G4 || format == IFF_TIFF_LZW || #if LIBLEPT_MAJOR_VERSION > 1 || LIBLEPT_MINOR_VERSION > 76 format == IFF_TIFF_JPEG || #endif format == IFF_TIFF_ZIP); // Fail early if we can, before producing any output Pix *pix = nullptr; if (!tiff) { pix = (data != nullptr) ? pixReadMem(data, buf.size()) : pixRead(filename); if (pix == nullptr) { return false; } } // Begin the output if (renderer && !renderer->BeginDocument(document_title.c_str())) { pixDestroy(&pix); return false; } // Produce output r = (tiff) ? ProcessPagesMultipageTiff(data, buf.size(), filename, retry_config, timeout_millisec, renderer, tesseract_->tessedit_page_number) : ProcessPage(pix, 0, filename, retry_config, timeout_millisec, renderer); // Clean up memory as needed pixDestroy(&pix); // End the output if (!r || (renderer && !renderer->EndDocument())) { return false; } return true; } bool TessBaseAPI::ProcessPage(Pix *pix, int page_index, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer) { SetInputName(filename); SetImage(pix); bool failed = false; if (tesseract_->tessedit_pageseg_mode == PSM_AUTO_ONLY) { // Disabled character recognition if (! std::unique_ptr<const PageIterator>(AnalyseLayout())) { failed = true; } } else if (tesseract_->tessedit_pageseg_mode == PSM_OSD_ONLY) { failed = FindLines() != 0; } else if (timeout_millisec > 0) { // Running with a timeout. ETEXT_DESC monitor; monitor.cancel = nullptr; monitor.cancel_this = nullptr; monitor.set_deadline_msecs(timeout_millisec); // Now run the main recognition. failed = Recognize(&monitor) < 0; } else { // Normal layout and character recognition with no timeout. failed = Recognize(nullptr) < 0; } if (tesseract_->tessedit_write_images) { Pix *page_pix = GetThresholdedImage(); std::string output_filename = output_file_ + ".processed"; if (page_index > 0) { output_filename += std::to_string(page_index); } output_filename += ".tif"; pixWrite(output_filename.c_str(), page_pix, IFF_TIFF_G4); pixDestroy(&page_pix); } if (failed && retry_config != nullptr && retry_config[0] != '\0') { // Save current config variables before switching modes. FILE *fp = fopen(kOldVarsFile, "wb"); if (fp == nullptr) { tprintf("Error, failed to open file \"%s\"\n", kOldVarsFile); } else { PrintVariables(fp); fclose(fp); } // Switch to alternate mode for retry. ReadConfigFile(retry_config); SetImage(pix); Recognize(nullptr); // Restore saved config variables. ReadConfigFile(kOldVarsFile); } if (renderer && !failed) { failed = !renderer->AddImage(this); } return !failed; } /** * Get a left-to-right iterator to the results of LayoutAnalysis and/or * Recognize. The returned iterator must be deleted after use. */ LTRResultIterator *TessBaseAPI::GetLTRIterator() { if (tesseract_ == nullptr || page_res_ == nullptr) { return nullptr; } return new LTRResultIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } /** * Get a reading-order iterator to the results of LayoutAnalysis and/or * Recognize. The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ ResultIterator *TessBaseAPI::GetIterator() { if (tesseract_ == nullptr || page_res_ == nullptr) { return nullptr; } return ResultIterator::StartOfParagraph(LTRResultIterator( page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_)); } /** * Get a mutable iterator to the results of LayoutAnalysis and/or Recognize. * The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ MutableIterator *TessBaseAPI::GetMutableIterator() { if (tesseract_ == nullptr || page_res_ == nullptr) { return nullptr; } return new MutableIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } /** Make a text string from the internal data structures. */ char *TessBaseAPI::GetUTF8Text() { if (tesseract_ == nullptr || (!recognition_done_ && Recognize(nullptr) < 0)) { return nullptr; } std::string text(""); const std::unique_ptr</*non-const*/ ResultIterator> it(GetIterator()); do { if (it->Empty(RIL_PARA)) { continue; } auto block_type = it->BlockType(); switch (block_type) { case PT_FLOWING_IMAGE: case PT_HEADING_IMAGE: case PT_PULLOUT_IMAGE: case PT_HORZ_LINE: case PT_VERT_LINE: // Ignore images and lines for text output. continue; case PT_NOISE: tprintf("TODO: Please report image which triggers the noise case.\n"); ASSERT_HOST(false); default: break; } const std::unique_ptr<const char[]> para_text(it->GetUTF8Text(RIL_PARA)); text += para_text.get(); } while (it->Next(RIL_PARA)); return copy_string(text); } static void AddBoxToTSV(const PageIterator *it, PageIteratorLevel level, std::string &text) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); text += "\t" + std::to_string(left); text += "\t" + std::to_string(top); text += "\t" + std::to_string(right - left); text += "\t" + std::to_string(bottom - top); } /** * Make a TSV-formatted string from the internal data structures. * page_number is 0-based but will appear in the output as 1-based. * Returned string must be freed with the delete [] operator. */ char *TessBaseAPI::GetTSVText(int page_number) { if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(nullptr) < 0)) { return nullptr; } #if !defined(NDEBUG) int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1; #endif int page_id = page_number + 1; // we use 1-based page numbers. int page_num = page_id; int block_num = 0; int par_num = 0; int line_num = 0; int word_num = 0; std::string tsv_str; tsv_str += "1\t" + std::to_string(page_num); // level 1 - page tsv_str += "\t" + std::to_string(block_num); tsv_str += "\t" + std::to_string(par_num); tsv_str += "\t" + std::to_string(line_num); tsv_str += "\t" + std::to_string(word_num); tsv_str += "\t" + std::to_string(rect_left_); tsv_str += "\t" + std::to_string(rect_top_); tsv_str += "\t" + std::to_string(rect_width_); tsv_str += "\t" + std::to_string(rect_height_); tsv_str += "\t-1\t\n"; const std::unique_ptr</*non-const*/ ResultIterator> res_it(GetIterator()); while (!res_it->Empty(RIL_BLOCK)) { if (res_it->Empty(RIL_WORD)) { res_it->Next(RIL_WORD); continue; } // Add rows for any new block/paragraph/textline. if (res_it->IsAtBeginningOf(RIL_BLOCK)) { block_num++; par_num = 0; line_num = 0; word_num = 0; tsv_str += "2\t" + std::to_string(page_num); // level 2 - block tsv_str += "\t" + std::to_string(block_num); tsv_str += "\t" + std::to_string(par_num); tsv_str += "\t" + std::to_string(line_num); tsv_str += "\t" + std::to_string(word_num); AddBoxToTSV(res_it.get(), RIL_BLOCK, tsv_str); tsv_str += "\t-1\t\n"; // end of row for block } if (res_it->IsAtBeginningOf(RIL_PARA)) { par_num++; line_num = 0; word_num = 0; tsv_str += "3\t" + std::to_string(page_num); // level 3 - paragraph tsv_str += "\t" + std::to_string(block_num); tsv_str += "\t" + std::to_string(par_num); tsv_str += "\t" + std::to_string(line_num); tsv_str += "\t" + std::to_string(word_num); AddBoxToTSV(res_it.get(), RIL_PARA, tsv_str); tsv_str += "\t-1\t\n"; // end of row for para } if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { line_num++; word_num = 0; tsv_str += "4\t" + std::to_string(page_num); // level 4 - line tsv_str += "\t" + std::to_string(block_num); tsv_str += "\t" + std::to_string(par_num); tsv_str += "\t" + std::to_string(line_num); tsv_str += "\t" + std::to_string(word_num); AddBoxToTSV(res_it.get(), RIL_TEXTLINE, tsv_str); tsv_str += "\t-1\t\n"; // end of row for line } // Now, process the word... int left, top, right, bottom; res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom); word_num++; tsv_str += "5\t" + std::to_string(page_num); // level 5 - word tsv_str += "\t" + std::to_string(block_num); tsv_str += "\t" + std::to_string(par_num); tsv_str += "\t" + std::to_string(line_num); tsv_str += "\t" + std::to_string(word_num); tsv_str += "\t" + std::to_string(left); tsv_str += "\t" + std::to_string(top); tsv_str += "\t" + std::to_string(right - left); tsv_str += "\t" + std::to_string(bottom - top); tsv_str += "\t" + std::to_string(res_it->Confidence(RIL_WORD)); tsv_str += "\t"; #if !defined(NDEBUG) // Increment counts if at end of block/paragraph/textline. if (res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD)) { lcnt++; } if (res_it->IsAtFinalElement(RIL_PARA, RIL_WORD)) { pcnt++; } if (res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD)) { bcnt++; } #endif do { tsv_str += std::unique_ptr<const char[]>(res_it->GetUTF8Text(RIL_SYMBOL)).get(); res_it->Next(RIL_SYMBOL); } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD)); tsv_str += "\n"; // end of row #if !defined(NDEBUG) wcnt++; #endif } return copy_string(tsv_str); } /** The 5 numbers output for each box (the usual 4 and a page number.) */ const int kNumbersPerBlob = 5; /** * The number of bytes taken by each number. Since we use int16_t for ICOORD, * assume only 5 digits max. */ const int kBytesPerNumber = 5; /** * Multiplier for max expected textlength assumes (kBytesPerNumber + space) * * kNumbersPerBlob plus the newline. Add to this the * original UTF8 characters, and one kMaxBytesPerLine for safety. */ const int kBytesPerBoxFileLine = (kBytesPerNumber + 1) * kNumbersPerBlob + 1; /** Max bytes in the decimal representation of int64_t. */ const int kBytesPer64BitNumber = 20; /** * A maximal single box could occupy kNumbersPerBlob numbers at * kBytesPer64BitNumber digits (if someone sneaks in a 64 bit value) and a * space plus the newline and the maximum length of a UNICHAR. * Test against this on each iteration for safety. */ const int kMaxBytesPerLine = kNumbersPerBlob * (kBytesPer64BitNumber + 1) + 1 + UNICHAR_LEN; /** * The recognized text is returned as a char* which is coded * as a UTF8 box file. * page_number is a 0-base page index that will appear in the box file. * Returned string must be freed with the delete [] operator. */ char *TessBaseAPI::GetBoxText(int page_number) { if (tesseract_ == nullptr || (!recognition_done_ && Recognize(nullptr) < 0)) { return nullptr; } int blob_count; int utf8_length = TextLength(&blob_count); int total_length = blob_count * kBytesPerBoxFileLine + utf8_length + kMaxBytesPerLine; char *result = new char[total_length]; result[0] = '\0'; int output_length = 0; LTRResultIterator *it = GetLTRIterator(); do { int left, top, right, bottom; if (it->BoundingBox(RIL_SYMBOL, &left, &top, &right, &bottom)) { const std::unique_ptr</*non-const*/ char[]> text(it->GetUTF8Text(RIL_SYMBOL)); // Tesseract uses space for recognition failure. Fix to a reject // character, kTesseractReject so we don't create illegal box files. for (int i = 0; text[i] != '\0'; ++i) { if (text[i] == ' ') { text[i] = kTesseractReject; } } snprintf(result + output_length, total_length - output_length, "%s %d %d %d %d %d\n", text.get(), left, image_height_ - bottom, right, image_height_ - top, page_number); output_length += strlen(result + output_length); // Just in case... if (output_length + kMaxBytesPerLine > total_length) { break; } } } while (it->Next(RIL_SYMBOL)); delete it; return result; } /** * Conversion table for non-latin characters. * Maps characters out of the latin set into the latin set. * TODO(rays) incorporate this translation into unicharset. */ const int kUniChs[] = {0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0}; /** Latin chars corresponding to the unicode chars above. */ const int kLatinChs[] = {0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0}; /** * The recognized text is returned as a char* which is coded * as UNLV format Latin-1 with specific reject and suspect codes. * Returned string must be freed with the delete [] operator. */ char *TessBaseAPI::GetUNLVText() { if (tesseract_ == nullptr || (!recognition_done_ && Recognize(nullptr) < 0)) { return nullptr; } bool tilde_crunch_written = false; bool last_char_was_newline = true; bool last_char_was_tilde = false; int total_length = TextLength(nullptr); PAGE_RES_IT page_res_it(page_res_); char *result = new char[total_length]; char *ptr = result; for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) { WERD_RES *word = page_res_it.word(); // Process the current word. if (word->unlv_crunch_mode != CR_NONE) { if (word->unlv_crunch_mode != CR_DELETE && (!tilde_crunch_written || (word->unlv_crunch_mode == CR_KEEP_SPACE && word->word->space() > 0 && !word->word->flag(W_FUZZY_NON) && !word->word->flag(W_FUZZY_SP)))) { if (!word->word->flag(W_BOL) && word->word->space() > 0 && !word->word->flag(W_FUZZY_NON) && !word->word->flag(W_FUZZY_SP)) { /* Write a space to separate from preceding good text */ *ptr++ = ' '; last_char_was_tilde = false; } if (!last_char_was_tilde) { // Write a reject char. last_char_was_tilde = true; *ptr++ = kUNLVReject; tilde_crunch_written = true; last_char_was_newline = false; } } } else { // NORMAL PROCESSING of non tilde crunched words. tilde_crunch_written = false; tesseract_->set_unlv_suspects(word); const char *wordstr = word->best_choice->unichar_string().c_str(); const auto &lengths = word->best_choice->unichar_lengths(); int length = lengths.length(); int i = 0; int offset = 0; if (last_char_was_tilde && word->word->space() == 0 && wordstr[offset] == ' ') { // Prevent adjacent tilde across words - we know that adjacent tildes // within words have been removed. // Skip the first character. offset = lengths[i++]; } if (i < length && wordstr[offset] != 0) { if (!last_char_was_newline) { *ptr++ = ' '; } else { last_char_was_newline = false; } for (; i < length; offset += lengths[i++]) { if (wordstr[offset] == ' ' || wordstr[offset] == kTesseractReject) { *ptr++ = kUNLVReject; last_char_was_tilde = true; } else { if (word->reject_map[i].rejected()) { *ptr++ = kUNLVSuspect; } UNICHAR ch(wordstr + offset, lengths[i]); int uni_ch = ch.first_uni(); for (int j = 0; kUniChs[j] != 0; ++j) { if (kUniChs[j] == uni_ch) { uni_ch = kLatinChs[j]; break; } } if (uni_ch <= 0xff) { *ptr++ = static_cast<char>(uni_ch); last_char_was_tilde = false; } else { *ptr++ = kUNLVReject; last_char_was_tilde = true; } } } } } if (word->word->flag(W_EOL) && !last_char_was_newline) { /* Add a new line output */ *ptr++ = '\n'; tilde_crunch_written = false; last_char_was_newline = true; last_char_was_tilde = false; } } *ptr++ = '\n'; *ptr = '\0'; return result; } #ifndef DISABLED_LEGACY_ENGINE /** * Detect the orientation of the input image and apparent script (alphabet). * orient_deg is the detected clockwise rotation of the input image in degrees * (0, 90, 180, 270) * orient_conf is the confidence (15.0 is reasonably confident) * script_name is an ASCII string, the name of the script, e.g. "Latin" * script_conf is confidence level in the script * Returns true on success and writes values to each parameter as an output */ bool TessBaseAPI::DetectOrientationScript(int *orient_deg, float *orient_conf, const char **script_name, float *script_conf) { OSResults osr; bool osd = DetectOS(&osr); if (!osd) { return false; } int orient_id = osr.best_result.orientation_id; int script_id = osr.get_best_script(orient_id); if (orient_conf) { *orient_conf = osr.best_result.oconfidence; } if (orient_deg) { *orient_deg = orient_id * 90; // convert quadrant to degrees } if (script_name) { const char *script = osr.unicharset->get_script_from_script_id(script_id); *script_name = script; } if (script_conf) { *script_conf = osr.best_result.sconfidence; } return true; } /** * The recognized text is returned as a char* which is coded * as UTF8 and must be freed with the delete [] operator. * page_number is a 0-based page index that will appear in the osd file. */ char *TessBaseAPI::GetOsdText(int page_number) { int orient_deg; float orient_conf; const char *script_name; float script_conf; if (!DetectOrientationScript(&orient_deg, &orient_conf, &script_name, &script_conf)) { return nullptr; } // clockwise rotation needed to make the page upright int rotate = OrientationIdToValue(orient_deg / 90); std::stringstream stream; // Use "C" locale (needed for float values orient_conf and script_conf). stream.imbue(std::locale::classic()); // Use fixed notation with 2 digits after the decimal point for float values. stream.precision(2); stream << std::fixed << "Page number: " << page_number << "\n" << "Orientation in degrees: " << orient_deg << "\n" << "Rotate: " << rotate << "\n" << "Orientation confidence: " << orient_conf << "\n" << "Script: " << script_name << "\n" << "Script confidence: " << script_conf << "\n"; return copy_string(stream.str()); } #endif // ndef DISABLED_LEGACY_ENGINE /** Returns the average word confidence for Tesseract page result. */ int TessBaseAPI::MeanTextConf() { int *conf = AllWordConfidences(); if (!conf) { return 0; } int sum = 0; int *pt = conf; while (*pt >= 0) { sum += *pt++; } if (pt != conf) { sum /= pt - conf; } delete[] conf; return sum; } /** Returns an array of all word confidences, terminated by -1. */ int *TessBaseAPI::AllWordConfidences() { if (tesseract_ == nullptr || (!recognition_done_ && Recognize(nullptr) < 0)) { return nullptr; } int n_word = 0; PAGE_RES_IT res_it(page_res_); for (res_it.restart_page(); res_it.word() != nullptr; res_it.forward()) { n_word++; } int *conf = new int[n_word + 1]; n_word = 0; for (res_it.restart_page(); res_it.word() != nullptr; res_it.forward()) { WERD_RES *word = res_it.word(); WERD_CHOICE *choice = word->best_choice; int w_conf = static_cast<int>(100 + 5 * choice->certainty()); // This is the eq for converting Tesseract confidence to 1..100 if (w_conf < 0) { w_conf = 0; } if (w_conf > 100) { w_conf = 100; } conf[n_word++] = w_conf; } conf[n_word] = -1; return conf; } #ifndef DISABLED_LEGACY_ENGINE /** * Applies the given word to the adaptive classifier if possible. * The word must be SPACE-DELIMITED UTF-8 - l i k e t h i s , so it can * tell the boundaries of the graphemes. * Assumes that SetImage/SetRectangle have been used to set the image * to the given word. The mode arg should be PSM_SINGLE_WORD or * PSM_CIRCLE_WORD, as that will be used to control layout analysis. * The currently set PageSegMode is preserved. * Returns false if adaption was not possible for some reason. */ bool TessBaseAPI::AdaptToWordStr(PageSegMode mode, const char *wordstr) { int debug = 0; GetIntVariable("applybox_debug", &debug); bool success = true; PageSegMode current_psm = GetPageSegMode(); SetPageSegMode(mode); SetVariable("classify_enable_learning", "0"); const std::unique_ptr<const char[]> text(GetUTF8Text()); if (debug) { tprintf("Trying to adapt \"%s\" to \"%s\"\n", text.get(), wordstr); } if (text != nullptr) { PAGE_RES_IT it(page_res_); WERD_RES *word_res = it.word(); if (word_res != nullptr) { word_res->word->set_text(wordstr); // Check to see if text matches wordstr. int w = 0; int t; for (t = 0; text[t] != '\0'; ++t) { if (text[t] == '\n' || text[t] == ' ') { continue; } while (wordstr[w] == ' ') { ++w; } if (text[t] != wordstr[w]) { break; } ++w; } if (text[t] != '\0' || wordstr[w] != '\0') { // No match. delete page_res_; std::vector<TBOX> boxes; page_res_ = tesseract_->SetupApplyBoxes(boxes, block_list_); tesseract_->ReSegmentByClassification(page_res_); tesseract_->TidyUp(page_res_); PAGE_RES_IT pr_it(page_res_); if (pr_it.word() == nullptr) { success = false; } else { word_res = pr_it.word(); } } else { word_res->BestChoiceToCorrectText(); } if (success) { tesseract_->EnableLearning = true; tesseract_->LearnWord(nullptr, word_res); } } else { success = false; } } else { success = false; } SetPageSegMode(current_psm); return success; } #endif // ndef DISABLED_LEGACY_ENGINE /** * Free up recognition results and any stored image data, without actually * freeing any recognition data that would be time-consuming to reload. * Afterwards, you must call SetImage or TesseractRect before doing * any Recognize or Get* operation. */ void TessBaseAPI::Clear() { if (thresholder_ != nullptr) { thresholder_->Clear(); } ClearResults(); if (tesseract_ != nullptr) { SetInputImage(nullptr); } } /** * Close down tesseract and free up all memory. End() is equivalent to * destructing and reconstructing your TessBaseAPI. * Once End() has been used, none of the other API functions may be used * other than Init and anything declared above it in the class definition. */ void TessBaseAPI::End() { Clear(); delete thresholder_; thresholder_ = nullptr; delete page_res_; page_res_ = nullptr; delete block_list_; block_list_ = nullptr; if (paragraph_models_ != nullptr) { for (auto model : *paragraph_models_) { delete model; } delete paragraph_models_; paragraph_models_ = nullptr; } #ifndef DISABLED_LEGACY_ENGINE if (osd_tesseract_ == tesseract_) { osd_tesseract_ = nullptr; } delete osd_tesseract_; osd_tesseract_ = nullptr; delete equ_detect_; equ_detect_ = nullptr; #endif // ndef DISABLED_LEGACY_ENGINE delete tesseract_; tesseract_ = nullptr; input_file_.clear(); output_file_.clear(); datapath_.clear(); language_.clear(); } // Clear any library-level memory caches. // There are a variety of expensive-to-load constant data structures (mostly // language dictionaries) that are cached globally -- surviving the Init() // and End() of individual TessBaseAPI's. This function allows the clearing // of these caches. void TessBaseAPI::ClearPersistentCache() { Dict::GlobalDawgCache()->DeleteUnusedDawgs(); } /** * Check whether a word is valid according to Tesseract's language model * returns 0 if the word is invalid, non-zero if valid */ int TessBaseAPI::IsValidWord(const char *word) const { return tesseract_->getDict().valid_word(word); } // Returns true if utf8_character is defined in the UniCharset. bool TessBaseAPI::IsValidCharacter(const char *utf8_character) const { return tesseract_->unicharset.contains_unichar(utf8_character); } // TODO(rays) Obsolete this function and replace with a more aptly named // function that returns image coordinates rather than tesseract coordinates. bool TessBaseAPI::GetTextDirection(int *out_offset, float *out_slope) { const std::unique_ptr<const PageIterator> it(AnalyseLayout()); if (it == nullptr) { return false; } int x1, x2, y1, y2; it->Baseline(RIL_TEXTLINE, &x1, &y1, &x2, &y2); // Calculate offset and slope (NOTE: Kind of ugly) if (x2 <= x1) { x2 = x1 + 1; } // Convert the point pair to slope/offset of the baseline (in image coords.) *out_slope = static_cast<float>(y2 - y1) / (x2 - x1); *out_offset = static_cast<int>(y1 - *out_slope * x1); // Get the y-coord of the baseline at the left and right edges of the // textline's bounding box. int left, top, right, bottom; if (!it->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom)) { return false; } int left_y = IntCastRounded(*out_slope * left + *out_offset); int right_y = IntCastRounded(*out_slope * right + *out_offset); // Shift the baseline down so it passes through the nearest bottom-corner // of the textline's bounding box. This is the difference between the y // at the lowest (max) edge of the box and the actual box bottom. *out_offset += bottom - std::max(left_y, right_y); // Switch back to bottom-up tesseract coordinates. Requires negation of // the slope and height - offset for the offset. *out_slope = -*out_slope; *out_offset = rect_height_ - *out_offset; return true; } /** Sets Dict::letter_is_okay_ function to point to the given function. */ void TessBaseAPI::SetDictFunc(DictFunc f) { if (tesseract_ != nullptr) { tesseract_->getDict().letter_is_okay_ = f; } } /** * Sets Dict::probability_in_context_ function to point to the given * function. * * @param f A single function that returns the probability of the current * "character" (in general a utf-8 string), given the context of a previous * utf-8 string. */ void TessBaseAPI::SetProbabilityInContextFunc(ProbabilityInContextFunc f) { if (tesseract_ != nullptr) { tesseract_->getDict().probability_in_context_ = f; // Set it for the sublangs too. int num_subs = tesseract_->num_sub_langs(); for (int i = 0; i < num_subs; ++i) { tesseract_->get_sub_lang(i)->getDict().probability_in_context_ = f; } } } /** Common code for setting the image. */ bool TessBaseAPI::InternalSetImage() { if (tesseract_ == nullptr) { tprintf("Please call Init before attempting to set an image.\n"); return false; } if (thresholder_ == nullptr) { thresholder_ = new ImageThresholder; } ClearResults(); return true; } /** * Run the thresholder to make the thresholded image, returned in pix, * which must not be nullptr. *pix must be initialized to nullptr, or point * to an existing pixDestroyable Pix. * The usual argument to Threshold is Tesseract::mutable_pix_binary(). */ bool TessBaseAPI::Threshold(Pix **pix) { ASSERT_HOST(pix != nullptr); if (*pix != nullptr) { pixDestroy(pix); } // Zero resolution messes up the algorithms, so make sure it is credible. int user_dpi = 0; GetIntVariable("user_defined_dpi", &user_dpi); int y_res = thresholder_->GetScaledYResolution(); if (user_dpi && (user_dpi < kMinCredibleResolution || user_dpi > kMaxCredibleResolution)) { tprintf( "Warning: User defined image dpi is outside of expected range " "(%d - %d)!\n", kMinCredibleResolution, kMaxCredibleResolution); } // Always use user defined dpi if (user_dpi) { thresholder_->SetSourceYResolution(user_dpi); } else if (y_res < kMinCredibleResolution || y_res > kMaxCredibleResolution) { if (y_res != 0) { // Show warning only if a resolution was given. tprintf("Warning: Invalid resolution %d dpi. Using %d instead.\n", y_res, kMinCredibleResolution); } thresholder_->SetSourceYResolution(kMinCredibleResolution); } auto thresholding_method = static_cast<ThresholdMethod>(static_cast<int>(tesseract_->thresholding_method)); if (thresholding_method == ThresholdMethod::Otsu) { Image pix_binary(*pix); if (!thresholder_->ThresholdToPix(&pix_binary)) { return false; } *pix = pix_binary; if (!thresholder_->IsBinary()) { tesseract_->set_pix_thresholds(thresholder_->GetPixRectThresholds()); tesseract_->set_pix_grey(thresholder_->GetPixRectGrey()); } else { tesseract_->set_pix_thresholds(nullptr); tesseract_->set_pix_grey(nullptr); } } else { auto [ok, pix_grey, pix_binary, pix_thresholds] = thresholder_->Threshold(this, thresholding_method); if (!ok) { return false; } *pix = pix_binary; tesseract_->set_pix_thresholds(pix_thresholds); tesseract_->set_pix_grey(pix_grey); } thresholder_->GetImageSizes(&rect_left_, &rect_top_, &rect_width_, &rect_height_, &image_width_, &image_height_); // Set the internal resolution that is used for layout parameters from the // estimated resolution, rather than the image resolution, which may be // fabricated, but we will use the image resolution, if there is one, to // report output point sizes. int estimated_res = ClipToRange(thresholder_->GetScaledEstimatedResolution(), kMinCredibleResolution, kMaxCredibleResolution); if (estimated_res != thresholder_->GetScaledEstimatedResolution()) { tprintf( "Estimated internal resolution %d out of range! " "Corrected to %d.\n", thresholder_->GetScaledEstimatedResolution(), estimated_res); } tesseract_->set_source_resolution(estimated_res); return true; } /** Find lines from the image making the BLOCK_LIST. */ int TessBaseAPI::FindLines() { if (thresholder_ == nullptr || thresholder_->IsEmpty()) { tprintf("Please call SetImage before attempting recognition.\n"); return -1; } if (recognition_done_) { ClearResults(); } if (!block_list_->empty()) { return 0; } if (tesseract_ == nullptr) { tesseract_ = new Tesseract; #ifndef DISABLED_LEGACY_ENGINE tesseract_->InitAdaptiveClassifier(nullptr); #endif } if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) { return -1; } tesseract_->PrepareForPageseg(); #ifndef DISABLED_LEGACY_ENGINE if (tesseract_->textord_equation_detect) { if (equ_detect_ == nullptr && !datapath_.empty()) { equ_detect_ = new EquationDetect(datapath_.c_str(), nullptr); } if (equ_detect_ == nullptr) { tprintf("Warning: Could not set equation detector\n"); } else { tesseract_->SetEquationDetect(equ_detect_); } } #endif // ndef DISABLED_LEGACY_ENGINE Tesseract *osd_tess = osd_tesseract_; OSResults osr; #ifndef DISABLED_LEGACY_ENGINE if (PSM_OSD_ENABLED(tesseract_->tessedit_pageseg_mode) && osd_tess == nullptr) { if (strcmp(language_.c_str(), "osd") == 0) { osd_tess = tesseract_; } else { osd_tesseract_ = new Tesseract; TessdataManager mgr(reader_); if (datapath_.empty()) { tprintf( "Warning: Auto orientation and script detection requested," " but data path is undefined\n"); delete osd_tesseract_; osd_tesseract_ = nullptr; } else if (osd_tesseract_->init_tesseract(datapath_, "", "osd", OEM_TESSERACT_ONLY, nullptr, 0, nullptr, nullptr, false, &mgr) == 0) { osd_tess = osd_tesseract_; osd_tesseract_->set_source_resolution(thresholder_->GetSourceYResolution()); } else { tprintf( "Warning: Auto orientation and script detection requested," " but osd language failed to load\n"); delete osd_tesseract_; osd_tesseract_ = nullptr; } } } #endif // ndef DISABLED_LEGACY_ENGINE if (tesseract_->SegmentPage(input_file_.c_str(), block_list_, osd_tess, &osr) < 0) { return -1; } // If Devanagari is being recognized, we use different images for page seg // and for OCR. tesseract_->PrepareForTessOCR(block_list_, osd_tess, &osr); return 0; } /** * Return average gradient of lines on page. */ float TessBaseAPI::GetGradient() { return tesseract_->gradient(); } /** Delete the pageres and clear the block list ready for a new page. */ void TessBaseAPI::ClearResults() { if (tesseract_ != nullptr) { tesseract_->Clear(); } delete page_res_; page_res_ = nullptr; recognition_done_ = false; if (block_list_ == nullptr) { block_list_ = new BLOCK_LIST; } else { block_list_->clear(); } if (paragraph_models_ != nullptr) { for (auto model : *paragraph_models_) { delete model; } delete paragraph_models_; paragraph_models_ = nullptr; } } /** * Return the length of the output text string, as UTF8, assuming * liberally two spacing marks after each word (as paragraphs end with two * newlines), and assuming a single character reject marker for each rejected * character. * Also return the number of recognized blobs in blob_count. */ int TessBaseAPI::TextLength(int *blob_count) const { if (tesseract_ == nullptr || page_res_ == nullptr) { return 0; } PAGE_RES_IT page_res_it(page_res_); int total_length = 2; int total_blobs = 0; // Iterate over the data structures to extract the recognition result. for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) { WERD_RES *word = page_res_it.word(); WERD_CHOICE *choice = word->best_choice; if (choice != nullptr) { total_blobs += choice->length() + 2; total_length += choice->unichar_string().length() + 2; for (int i = 0; i < word->reject_map.length(); ++i) { if (word->reject_map[i].rejected()) { ++total_length; } } } } if (blob_count != nullptr) { *blob_count = total_blobs; } return total_length; } #ifndef DISABLED_LEGACY_ENGINE /** * Estimates the Orientation And Script of the image. * Returns true if the image was processed successfully. */ bool TessBaseAPI::DetectOS(OSResults *osr) { if (tesseract_ == nullptr) { return false; } ClearResults(); if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) { return false; } if (input_file_.empty()) { input_file_ = kInputFile; } return orientation_and_script_detection(input_file_.c_str(), osr, tesseract_) > 0; } #endif // #ifndef DISABLED_LEGACY_ENGINE void TessBaseAPI::set_min_orientation_margin(double margin) { tesseract_->min_orientation_margin.set_value(margin); } /** * Return text orientation of each block as determined in an earlier page layout * analysis operation. Orientation is returned as the number of ccw 90-degree * rotations (in [0..3]) required to make the text in the block upright * (readable). Note that this may not necessary be the block orientation * preferred for recognition (such as the case of vertical CJK text). * * Also returns whether the text in the block is believed to have vertical * writing direction (when in an upright page orientation). * * The returned array is of length equal to the number of text blocks, which may * be less than the total number of blocks. The ordering is intended to be * consistent with GetTextLines(). */ void TessBaseAPI::GetBlockTextOrientations(int **block_orientation, bool **vertical_writing) { delete[] * block_orientation; *block_orientation = nullptr; delete[] * vertical_writing; *vertical_writing = nullptr; BLOCK_IT block_it(block_list_); block_it.move_to_first(); int num_blocks = 0; for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) { if (!block_it.data()->pdblk.poly_block()->IsText()) { continue; } ++num_blocks; } if (!num_blocks) { tprintf("WARNING: Found no blocks\n"); return; } *block_orientation = new int[num_blocks]; *vertical_writing = new bool[num_blocks]; block_it.move_to_first(); int i = 0; for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) { if (!block_it.data()->pdblk.poly_block()->IsText()) { continue; } FCOORD re_rotation = block_it.data()->re_rotation(); float re_theta = re_rotation.angle(); FCOORD classify_rotation = block_it.data()->classify_rotation(); float classify_theta = classify_rotation.angle(); double rot_theta = -(re_theta - classify_theta) * 2.0 / M_PI; if (rot_theta < 0) { rot_theta += 4; } int num_rotations = static_cast<int>(rot_theta + 0.5); (*block_orientation)[i] = num_rotations; // The classify_rotation is non-zero only if the text has vertical // writing direction. (*vertical_writing)[i] = classify_rotation.y() != 0.0f; ++i; } } void TessBaseAPI::DetectParagraphs(bool after_text_recognition) { int debug_level = 0; GetIntVariable("paragraph_debug_level", &debug_level); if (paragraph_models_ == nullptr) { paragraph_models_ = new std::vector<ParagraphModel *>; } MutableIterator *result_it = GetMutableIterator(); do { // Detect paragraphs for this block std::vector<ParagraphModel *> models; ::tesseract::DetectParagraphs(debug_level, after_text_recognition, result_it, &models); paragraph_models_->insert(paragraph_models_->end(), models.begin(), models.end()); } while (result_it->Next(RIL_BLOCK)); delete result_it; } /** This method returns the string form of the specified unichar. */ const char *TessBaseAPI::GetUnichar(int unichar_id) const { return tesseract_->unicharset.id_to_unichar(unichar_id); } /** Return the pointer to the i-th dawg loaded into tesseract_ object. */ const Dawg *TessBaseAPI::GetDawg(int i) const { if (tesseract_ == nullptr || i >= NumDawgs()) { return nullptr; } return tesseract_->getDict().GetDawg(i); } /** Return the number of dawgs loaded into tesseract_ object. */ int TessBaseAPI::NumDawgs() const { return tesseract_ == nullptr ? 0 : tesseract_->getDict().NumDawgs(); } /** Escape a char string - replace <>&"' with HTML codes. */ std::string HOcrEscape(const char *text) { std::string ret; const char *ptr; for (ptr = text; *ptr; ptr++) { switch (*ptr) { case '<': ret += "&lt;"; break; case '>': ret += "&gt;"; break; case '&': ret += "&amp;"; break; case '"': ret += "&quot;"; break; case '\'': ret += "&#39;"; break; default: ret += *ptr; } } return ret; } } // namespace tesseract
2301_81045437/tesseract
src/api/baseapi.cpp
C++
apache-2.0
82,412
/////////////////////////////////////////////////////////////////////// // File: capi.cpp // Description: C-API TessBaseAPI // // (C) Copyright 2012, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include <tesseract/capi.h> const char *TessVersion() { return TessBaseAPI::Version(); } static char *MakeText(const std::string& srcText) { auto *text = new char[srcText.size() + 1]; srcText.copy(text, srcText.size()); text[srcText.size()] = 0; return text; } void TessDeleteText(const char *text) { delete[] text; } static char **MakeTextArray(const std::vector<std::string>& srcArr) { auto **arr = new char *[srcArr.size() + 1]; for (size_t i = 0; i < srcArr.size(); ++i) { arr[i] = MakeText(srcArr[i]); } arr[srcArr.size()] = nullptr; return arr; } void TessDeleteTextArray(char **arr) { for (char **pos = arr; *pos != nullptr; ++pos) { delete[] * pos; } delete[] arr; } void TessDeleteIntArray(const int *arr) { delete[] arr; } TessResultRenderer *TessTextRendererCreate(const char *outputbase) { return new tesseract::TessTextRenderer(outputbase); } TessResultRenderer *TessHOcrRendererCreate(const char *outputbase) { return new tesseract::TessHOcrRenderer(outputbase); } TessResultRenderer *TessHOcrRendererCreate2(const char *outputbase, BOOL font_info) { return new tesseract::TessHOcrRenderer(outputbase, font_info != 0); } TessResultRenderer *TessAltoRendererCreate(const char *outputbase) { return new tesseract::TessAltoRenderer(outputbase); } TessResultRenderer *TessPAGERendererCreate(const char *outputbase) { return new tesseract::TessPAGERenderer(outputbase); } TessResultRenderer *TessTsvRendererCreate(const char *outputbase) { return new tesseract::TessTsvRenderer(outputbase); } TessResultRenderer *TessPDFRendererCreate(const char *outputbase, const char *datadir, BOOL textonly) { return new tesseract::TessPDFRenderer(outputbase, datadir, textonly != 0); } TessResultRenderer *TessUnlvRendererCreate(const char *outputbase) { return new tesseract::TessUnlvRenderer(outputbase); } TessResultRenderer *TessBoxTextRendererCreate(const char *outputbase) { return new tesseract::TessBoxTextRenderer(outputbase); } TessResultRenderer *TessWordStrBoxRendererCreate(const char *outputbase) { return new tesseract::TessWordStrBoxRenderer(outputbase); } TessResultRenderer *TessLSTMBoxRendererCreate(const char *outputbase) { return new tesseract::TessLSTMBoxRenderer(outputbase); } void TessDeleteResultRenderer(TessResultRenderer *renderer) { delete renderer; } void TessResultRendererInsert(TessResultRenderer *renderer, TessResultRenderer *next) { renderer->insert(next); } TessResultRenderer *TessResultRendererNext(TessResultRenderer *renderer) { return renderer->next(); } BOOL TessResultRendererBeginDocument(TessResultRenderer *renderer, const char *title) { return static_cast<int>(renderer->BeginDocument(title)); } BOOL TessResultRendererAddImage(TessResultRenderer *renderer, TessBaseAPI *api) { return static_cast<int>(renderer->AddImage(api)); } BOOL TessResultRendererEndDocument(TessResultRenderer *renderer) { return static_cast<int>(renderer->EndDocument()); } const char *TessResultRendererExtention(TessResultRenderer *renderer) { return renderer->file_extension(); } const char *TessResultRendererTitle(TessResultRenderer *renderer) { return renderer->title(); } int TessResultRendererImageNum(TessResultRenderer *renderer) { return renderer->imagenum(); } TessBaseAPI *TessBaseAPICreate() { return new TessBaseAPI; } void TessBaseAPIDelete(TessBaseAPI *handle) { delete handle; } void TessBaseAPISetInputName(TessBaseAPI *handle, const char *name) { handle->SetInputName(name); } const char *TessBaseAPIGetInputName(TessBaseAPI *handle) { return handle->GetInputName(); } void TessBaseAPISetInputImage(TessBaseAPI *handle, Pix *pix) { handle->SetInputImage(pix); } Pix *TessBaseAPIGetInputImage(TessBaseAPI *handle) { return handle->GetInputImage(); } int TessBaseAPIGetSourceYResolution(TessBaseAPI *handle) { return handle->GetSourceYResolution(); } const char *TessBaseAPIGetDatapath(TessBaseAPI *handle) { return handle->GetDatapath(); } void TessBaseAPISetOutputName(TessBaseAPI *handle, const char *name) { handle->SetOutputName(name); } BOOL TessBaseAPISetVariable(TessBaseAPI *handle, const char *name, const char *value) { return static_cast<int>(handle->SetVariable(name, value)); } BOOL TessBaseAPISetDebugVariable(TessBaseAPI *handle, const char *name, const char *value) { return static_cast<int>(handle->SetDebugVariable(name, value)); } BOOL TessBaseAPIGetIntVariable(const TessBaseAPI *handle, const char *name, int *value) { return static_cast<int>(handle->GetIntVariable(name, value)); } BOOL TessBaseAPIGetBoolVariable(const TessBaseAPI *handle, const char *name, BOOL *value) { bool boolValue; bool result = handle->GetBoolVariable(name, &boolValue); if (result) { *value = static_cast<int>(boolValue); } return static_cast<int>(result); } BOOL TessBaseAPIGetDoubleVariable(const TessBaseAPI *handle, const char *name, double *value) { return static_cast<int>(handle->GetDoubleVariable(name, value)); } const char *TessBaseAPIGetStringVariable(const TessBaseAPI *handle, const char *name) { return handle->GetStringVariable(name); } void TessBaseAPIPrintVariables(const TessBaseAPI *handle, FILE *fp) { handle->PrintVariables(fp); } BOOL TessBaseAPIPrintVariablesToFile(const TessBaseAPI *handle, const char *filename) { FILE *fp = fopen(filename, "w"); if (fp != nullptr) { handle->PrintVariables(fp); fclose(fp); return TRUE; } return FALSE; } int TessBaseAPIInit4(TessBaseAPI *handle, const char *datapath, const char *language, TessOcrEngineMode mode, char **configs, int configs_size, char **vars_vec, char **vars_values, size_t vars_vec_size, BOOL set_only_non_debug_params) { std::vector<std::string> varNames; std::vector<std::string> varValues; if (vars_vec != nullptr && vars_values != nullptr) { for (size_t i = 0; i < vars_vec_size; i++) { varNames.emplace_back(vars_vec[i]); varValues.emplace_back(vars_values[i]); } } return handle->Init(datapath, language, mode, configs, configs_size, &varNames, &varValues, set_only_non_debug_params != 0); } int TessBaseAPIInit1(TessBaseAPI *handle, const char *datapath, const char *language, TessOcrEngineMode oem, char **configs, int configs_size) { return handle->Init(datapath, language, oem, configs, configs_size, nullptr, nullptr, false); } int TessBaseAPIInit2(TessBaseAPI *handle, const char *datapath, const char *language, TessOcrEngineMode oem) { return handle->Init(datapath, language, oem); } int TessBaseAPIInit3(TessBaseAPI *handle, const char *datapath, const char *language) { return handle->Init(datapath, language); } int TessBaseAPIInit5(TessBaseAPI *handle, const char *data, int data_size, const char *language, TessOcrEngineMode mode, char **configs, int configs_size, char **vars_vec, char **vars_values, size_t vars_vec_size, BOOL set_only_non_debug_params) { std::vector<std::string> varNames; std::vector<std::string> varValues; if (vars_vec != nullptr && vars_values != nullptr) { for (size_t i = 0; i < vars_vec_size; i++) { varNames.emplace_back(vars_vec[i]); varValues.emplace_back(vars_values[i]); } } return handle->Init(data, data_size, language, mode, configs, configs_size, &varNames, &varValues, set_only_non_debug_params != 0, nullptr); } const char *TessBaseAPIGetInitLanguagesAsString(const TessBaseAPI *handle) { return handle->GetInitLanguagesAsString(); } char **TessBaseAPIGetLoadedLanguagesAsVector(const TessBaseAPI *handle) { std::vector<std::string> languages; handle->GetLoadedLanguagesAsVector(&languages); return MakeTextArray(languages); } char **TessBaseAPIGetAvailableLanguagesAsVector(const TessBaseAPI *handle) { std::vector<std::string> languages; handle->GetAvailableLanguagesAsVector(&languages); return MakeTextArray(languages); } void TessBaseAPIInitForAnalysePage(TessBaseAPI *handle) { handle->InitForAnalysePage(); } void TessBaseAPIReadConfigFile(TessBaseAPI *handle, const char *filename) { handle->ReadConfigFile(filename); } void TessBaseAPIReadDebugConfigFile(TessBaseAPI *handle, const char *filename) { handle->ReadDebugConfigFile(filename); } void TessBaseAPISetPageSegMode(TessBaseAPI *handle, TessPageSegMode mode) { handle->SetPageSegMode(mode); } TessPageSegMode TessBaseAPIGetPageSegMode(const TessBaseAPI *handle) { return handle->GetPageSegMode(); } char *TessBaseAPIRect(TessBaseAPI *handle, const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height) { return handle->TesseractRect(imagedata, bytes_per_pixel, bytes_per_line, left, top, width, height); } #ifndef DISABLED_LEGACY_ENGINE void TessBaseAPIClearAdaptiveClassifier(TessBaseAPI *handle) { handle->ClearAdaptiveClassifier(); } #endif void TessBaseAPISetImage(TessBaseAPI *handle, const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line) { handle->SetImage(imagedata, width, height, bytes_per_pixel, bytes_per_line); } void TessBaseAPISetImage2(TessBaseAPI *handle, struct Pix *pix) { return handle->SetImage(pix); } void TessBaseAPISetSourceResolution(TessBaseAPI *handle, int ppi) { handle->SetSourceResolution(ppi); } void TessBaseAPISetRectangle(TessBaseAPI *handle, int left, int top, int width, int height) { handle->SetRectangle(left, top, width, height); } struct Pix *TessBaseAPIGetThresholdedImage(TessBaseAPI *handle) { return handle->GetThresholdedImage(); } float TessBaseAPIGetGradient(TessBaseAPI *handle) { return handle->GetGradient(); } void TessBaseAPIClearPersistentCache(TessBaseAPI * /*handle*/) { TessBaseAPI::ClearPersistentCache(); } #ifndef DISABLED_LEGACY_ENGINE BOOL TessBaseAPIDetectOrientationScript(TessBaseAPI *handle, int *orient_deg, float *orient_conf, const char **script_name, float *script_conf) { auto success = handle->DetectOrientationScript(orient_deg, orient_conf, script_name, script_conf); return static_cast<BOOL>(success); } #endif struct Boxa *TessBaseAPIGetRegions(TessBaseAPI *handle, struct Pixa **pixa) { return handle->GetRegions(pixa); } struct Boxa *TessBaseAPIGetTextlines(TessBaseAPI *handle, struct Pixa **pixa, int **blockids) { return handle->GetTextlines(pixa, blockids); } struct Boxa *TessBaseAPIGetTextlines1(TessBaseAPI *handle, const BOOL raw_image, const int raw_padding, struct Pixa **pixa, int **blockids, int **paraids) { return handle->GetTextlines(raw_image != 0, raw_padding, pixa, blockids, paraids); } struct Boxa *TessBaseAPIGetStrips(TessBaseAPI *handle, struct Pixa **pixa, int **blockids) { return handle->GetStrips(pixa, blockids); } struct Boxa *TessBaseAPIGetWords(TessBaseAPI *handle, struct Pixa **pixa) { return handle->GetWords(pixa); } struct Boxa *TessBaseAPIGetConnectedComponents(TessBaseAPI *handle, struct Pixa **cc) { return handle->GetConnectedComponents(cc); } struct Boxa *TessBaseAPIGetComponentImages(TessBaseAPI *handle, TessPageIteratorLevel level, BOOL text_only, struct Pixa **pixa, int **blockids) { return handle->GetComponentImages(level, static_cast<bool>(text_only), pixa, blockids); } struct Boxa *TessBaseAPIGetComponentImages1(TessBaseAPI *handle, const TessPageIteratorLevel level, const BOOL text_only, const BOOL raw_image, const int raw_padding, struct Pixa **pixa, int **blockids, int **paraids) { return handle->GetComponentImages(level, static_cast<bool>(text_only), raw_image != 0, raw_padding, pixa, blockids, paraids); } int TessBaseAPIGetThresholdedImageScaleFactor(const TessBaseAPI *handle) { return handle->GetThresholdedImageScaleFactor(); } TessPageIterator *TessBaseAPIAnalyseLayout(TessBaseAPI *handle) { return handle->AnalyseLayout(); } int TessBaseAPIRecognize(TessBaseAPI *handle, ETEXT_DESC *monitor) { return handle->Recognize(monitor); } BOOL TessBaseAPIProcessPages(TessBaseAPI *handle, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer) { return static_cast<int>(handle->ProcessPages(filename, retry_config, timeout_millisec, renderer)); } BOOL TessBaseAPIProcessPage(TessBaseAPI *handle, struct Pix *pix, int page_index, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer) { return static_cast<int>( handle->ProcessPage(pix, page_index, filename, retry_config, timeout_millisec, renderer)); } TessResultIterator *TessBaseAPIGetIterator(TessBaseAPI *handle) { return handle->GetIterator(); } TessMutableIterator *TessBaseAPIGetMutableIterator(TessBaseAPI *handle) { return handle->GetMutableIterator(); } char *TessBaseAPIGetUTF8Text(TessBaseAPI *handle) { return handle->GetUTF8Text(); } char *TessBaseAPIGetHOCRText(TessBaseAPI *handle, int page_number) { return handle->GetHOCRText(nullptr, page_number); } char *TessBaseAPIGetAltoText(TessBaseAPI *handle, int page_number) { return handle->GetAltoText(page_number); } char *TessBaseAPIGetPAGEText(TessBaseAPI *handle, int page_number) { return handle->GetPAGEText(page_number); } char *TessBaseAPIGetTsvText(TessBaseAPI *handle, int page_number) { return handle->GetTSVText(page_number); } char *TessBaseAPIGetBoxText(TessBaseAPI *handle, int page_number) { return handle->GetBoxText(page_number); } char *TessBaseAPIGetWordStrBoxText(TessBaseAPI *handle, int page_number) { return handle->GetWordStrBoxText(page_number); } char *TessBaseAPIGetLSTMBoxText(TessBaseAPI *handle, int page_number) { return handle->GetLSTMBoxText(page_number); } char *TessBaseAPIGetUNLVText(TessBaseAPI *handle) { return handle->GetUNLVText(); } int TessBaseAPIMeanTextConf(TessBaseAPI *handle) { return handle->MeanTextConf(); } int *TessBaseAPIAllWordConfidences(TessBaseAPI *handle) { return handle->AllWordConfidences(); } #ifndef DISABLED_LEGACY_ENGINE BOOL TessBaseAPIAdaptToWordStr(TessBaseAPI *handle, TessPageSegMode mode, const char *wordstr) { return static_cast<int>(handle->AdaptToWordStr(mode, wordstr)); } #endif void TessBaseAPIClear(TessBaseAPI *handle) { handle->Clear(); } void TessBaseAPIEnd(TessBaseAPI *handle) { handle->End(); } int TessBaseAPIIsValidWord(TessBaseAPI *handle, const char *word) { return handle->IsValidWord(word); } BOOL TessBaseAPIGetTextDirection(TessBaseAPI *handle, int *out_offset, float *out_slope) { return static_cast<int>(handle->GetTextDirection(out_offset, out_slope)); } const char *TessBaseAPIGetUnichar(TessBaseAPI *handle, int unichar_id) { return handle->GetUnichar(unichar_id); } void TessBaseAPISetMinOrientationMargin(TessBaseAPI *handle, double margin) { handle->set_min_orientation_margin(margin); } int TessBaseAPINumDawgs(const TessBaseAPI *handle) { return handle->NumDawgs(); } TessOcrEngineMode TessBaseAPIOem(const TessBaseAPI *handle) { return handle->oem(); } void TessBaseGetBlockTextOrientations(TessBaseAPI *handle, int **block_orientation, bool **vertical_writing) { handle->GetBlockTextOrientations(block_orientation, vertical_writing); } void TessPageIteratorDelete(TessPageIterator *handle) { delete handle; } TessPageIterator *TessPageIteratorCopy(const TessPageIterator *handle) { return new TessPageIterator(*handle); } void TessPageIteratorBegin(TessPageIterator *handle) { handle->Begin(); } BOOL TessPageIteratorNext(TessPageIterator *handle, TessPageIteratorLevel level) { return static_cast<int>(handle->Next(level)); } BOOL TessPageIteratorIsAtBeginningOf(const TessPageIterator *handle, TessPageIteratorLevel level) { return static_cast<int>(handle->IsAtBeginningOf(level)); } BOOL TessPageIteratorIsAtFinalElement(const TessPageIterator *handle, TessPageIteratorLevel level, TessPageIteratorLevel element) { return static_cast<int>(handle->IsAtFinalElement(level, element)); } BOOL TessPageIteratorBoundingBox(const TessPageIterator *handle, TessPageIteratorLevel level, int *left, int *top, int *right, int *bottom) { return static_cast<int>(handle->BoundingBox(level, left, top, right, bottom)); } TessPolyBlockType TessPageIteratorBlockType(const TessPageIterator *handle) { return handle->BlockType(); } struct Pix *TessPageIteratorGetBinaryImage(const TessPageIterator *handle, TessPageIteratorLevel level) { return handle->GetBinaryImage(level); } struct Pix *TessPageIteratorGetImage(const TessPageIterator *handle, TessPageIteratorLevel level, int padding, struct Pix *original_image, int *left, int *top) { return handle->GetImage(level, padding, original_image, left, top); } BOOL TessPageIteratorBaseline(const TessPageIterator *handle, TessPageIteratorLevel level, int *x1, int *y1, int *x2, int *y2) { return static_cast<int>(handle->Baseline(level, x1, y1, x2, y2)); } void TessPageIteratorOrientation(TessPageIterator *handle, TessOrientation *orientation, TessWritingDirection *writing_direction, TessTextlineOrder *textline_order, float *deskew_angle) { handle->Orientation(orientation, writing_direction, textline_order, deskew_angle); } void TessPageIteratorParagraphInfo(TessPageIterator *handle, TessParagraphJustification *justification, BOOL *is_list_item, BOOL *is_crown, int *first_line_indent) { bool bool_is_list_item; bool bool_is_crown; handle->ParagraphInfo(justification, &bool_is_list_item, &bool_is_crown, first_line_indent); if (is_list_item != nullptr) { *is_list_item = static_cast<int>(bool_is_list_item); } if (is_crown != nullptr) { *is_crown = static_cast<int>(bool_is_crown); } } void TessResultIteratorDelete(TessResultIterator *handle) { delete handle; } TessResultIterator *TessResultIteratorCopy(const TessResultIterator *handle) { return new TessResultIterator(*handle); } TessPageIterator *TessResultIteratorGetPageIterator(TessResultIterator *handle) { return handle; } const TessPageIterator *TessResultIteratorGetPageIteratorConst(const TessResultIterator *handle) { return handle; } TessChoiceIterator *TessResultIteratorGetChoiceIterator(const TessResultIterator *handle) { return new TessChoiceIterator(*handle); } BOOL TessResultIteratorNext(TessResultIterator *handle, TessPageIteratorLevel level) { return static_cast<int>(handle->Next(level)); } char *TessResultIteratorGetUTF8Text(const TessResultIterator *handle, TessPageIteratorLevel level) { return handle->GetUTF8Text(level); } float TessResultIteratorConfidence(const TessResultIterator *handle, TessPageIteratorLevel level) { return handle->Confidence(level); } const char *TessResultIteratorWordRecognitionLanguage(const TessResultIterator *handle) { return handle->WordRecognitionLanguage(); } const char *TessResultIteratorWordFontAttributes(const TessResultIterator *handle, BOOL *is_bold, BOOL *is_italic, BOOL *is_underlined, BOOL *is_monospace, BOOL *is_serif, BOOL *is_smallcaps, int *pointsize, int *font_id) { bool bool_is_bold; bool bool_is_italic; bool bool_is_underlined; bool bool_is_monospace; bool bool_is_serif; bool bool_is_smallcaps; const char *ret = handle->WordFontAttributes(&bool_is_bold, &bool_is_italic, &bool_is_underlined, &bool_is_monospace, &bool_is_serif, &bool_is_smallcaps, pointsize, font_id); if (is_bold != nullptr) { *is_bold = static_cast<int>(bool_is_bold); } if (is_italic != nullptr) { *is_italic = static_cast<int>(bool_is_italic); } if (is_underlined != nullptr) { *is_underlined = static_cast<int>(bool_is_underlined); } if (is_monospace != nullptr) { *is_monospace = static_cast<int>(bool_is_monospace); } if (is_serif != nullptr) { *is_serif = static_cast<int>(bool_is_serif); } if (is_smallcaps != nullptr) { *is_smallcaps = static_cast<int>(bool_is_smallcaps); } return ret; } BOOL TessResultIteratorWordIsFromDictionary(const TessResultIterator *handle) { return static_cast<int>(handle->WordIsFromDictionary()); } BOOL TessResultIteratorWordIsNumeric(const TessResultIterator *handle) { return static_cast<int>(handle->WordIsNumeric()); } BOOL TessResultIteratorSymbolIsSuperscript(const TessResultIterator *handle) { return static_cast<int>(handle->SymbolIsSuperscript()); } BOOL TessResultIteratorSymbolIsSubscript(const TessResultIterator *handle) { return static_cast<int>(handle->SymbolIsSubscript()); } BOOL TessResultIteratorSymbolIsDropcap(const TessResultIterator *handle) { return static_cast<int>(handle->SymbolIsDropcap()); } void TessChoiceIteratorDelete(TessChoiceIterator *handle) { delete handle; } BOOL TessChoiceIteratorNext(TessChoiceIterator *handle) { return static_cast<int>(handle->Next()); } const char *TessChoiceIteratorGetUTF8Text(const TessChoiceIterator *handle) { return handle->GetUTF8Text(); } float TessChoiceIteratorConfidence(const TessChoiceIterator *handle) { return handle->Confidence(); } ETEXT_DESC *TessMonitorCreate() { return new ETEXT_DESC(); } void TessMonitorDelete(ETEXT_DESC *monitor) { delete monitor; } void TessMonitorSetCancelFunc(ETEXT_DESC *monitor, TessCancelFunc cancelFunc) { monitor->cancel = cancelFunc; } void TessMonitorSetCancelThis(ETEXT_DESC *monitor, void *cancelThis) { monitor->cancel_this = cancelThis; } void *TessMonitorGetCancelThis(ETEXT_DESC *monitor) { return monitor->cancel_this; } void TessMonitorSetProgressFunc(ETEXT_DESC *monitor, TessProgressFunc progressFunc) { monitor->progress_callback2 = progressFunc; } int TessMonitorGetProgress(ETEXT_DESC *monitor) { return monitor->progress; } void TessMonitorSetDeadlineMSecs(ETEXT_DESC *monitor, int deadline) { monitor->set_deadline_msecs(deadline); }
2301_81045437/tesseract
src/api/capi.cpp
C++
apache-2.0
23,672
/********************************************************************** * File: hocrrenderer.cpp * Description: Simple API for calling tesseract. * Author: Ray Smith (original code from baseapi.cpp) * Author: Stefan Weil (moved to separate file and cleaned code) * * (C) Copyright 2006, Google Inc. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <tesseract/baseapi.h> // for TessBaseAPI #include <locale> // for std::locale::classic #include <memory> // for std::unique_ptr #include <sstream> // for std::stringstream #ifdef _WIN32 # include "host.h" // windows.h for MultiByteToWideChar, ... #endif #include <tesseract/renderer.h> #include "helpers.h" // for copy_string #include "tesseractclass.h" // for Tesseract namespace tesseract { /** * Gets the block orientation at the current iterator position. */ static tesseract::Orientation GetBlockTextOrientation(const PageIterator *it) { tesseract::Orientation orientation; tesseract::WritingDirection writing_direction; tesseract::TextlineOrder textline_order; float deskew_angle; it->Orientation(&orientation, &writing_direction, &textline_order, &deskew_angle); return orientation; } /** * Fits a line to the baseline at the given level, and appends its coefficients * to the hOCR string. * NOTE: The hOCR spec is unclear on how to specify baseline coefficients for * rotated textlines. For this reason, on textlines that are not upright, this * method currently only inserts a 'textangle' property to indicate the rotation * direction and does not add any baseline information to the hocr string. */ static void AddBaselineCoordsTohOCR(const PageIterator *it, PageIteratorLevel level, std::stringstream &hocr_str) { tesseract::Orientation orientation = GetBlockTextOrientation(it); if (orientation != ORIENTATION_PAGE_UP) { hocr_str << "; textangle " << 360 - orientation * 90; return; } int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); // Try to get the baseline coordinates at this level. int x1, y1, x2, y2; if (!it->Baseline(level, &x1, &y1, &x2, &y2)) { return; } // Following the description of this field of the hOCR spec, we convert the // baseline coordinates so that "the bottom left of the bounding box is the // origin". x1 -= left; x2 -= left; y1 -= bottom; y2 -= bottom; // Now fit a line through the points so we can extract coefficients for the // equation: y = p1 x + p0 if (x1 == x2) { // Problem computing the polynomial coefficients. return; } double p1 = (y2 - y1) / static_cast<double>(x2 - x1); double p0 = y1 - p1 * x1; hocr_str << "; baseline " << round(p1 * 1000.0) / 1000.0 << " " << round(p0 * 1000.0) / 1000.0; } static void AddBoxTohOCR(const ResultIterator *it, PageIteratorLevel level, std::stringstream &hocr_str) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); // This is the only place we use double quotes instead of single quotes, // but it may too late to change for consistency hocr_str << " title=\"bbox " << left << " " << top << " " << right << " " << bottom; // Add baseline coordinates & heights for textlines only. if (level == RIL_TEXTLINE) { AddBaselineCoordsTohOCR(it, level, hocr_str); // add custom height measures float row_height, descenders, ascenders; // row attributes it->RowAttributes(&row_height, &descenders, &ascenders); // TODO(rays): Do we want to limit these to a single decimal place? hocr_str << "; x_size " << row_height << "; x_descenders " << -descenders << "; x_ascenders " << ascenders; } hocr_str << "\">"; } /** * Make a HTML-formatted string with hOCR markup from the internal * data structures. * page_number is 0-based but will appear in the output as 1-based. * Image name/input_file_ can be set by SetInputName before calling * GetHOCRText * STL removed from original patch submission and refactored by rays. * Returned string must be freed with the delete [] operator. */ char *TessBaseAPI::GetHOCRText(int page_number) { return GetHOCRText(nullptr, page_number); } /** * Make a HTML-formatted string with hOCR markup from the internal * data structures. * page_number is 0-based but will appear in the output as 1-based. * Image name/input_file_ can be set by SetInputName before calling * GetHOCRText * STL removed from original patch submission and refactored by rays. * Returned string must be freed with the delete [] operator. */ char *TessBaseAPI::GetHOCRText(ETEXT_DESC *monitor, int page_number) { if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(monitor) < 0)) { return nullptr; } int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1, scnt = 1, tcnt = 1, ccnt = 1; int page_id = page_number + 1; // hOCR uses 1-based page numbers. bool para_is_ltr = true; // Default direction is LTR const char *paragraph_lang = nullptr; bool font_info = false; bool hocr_boxes = false; GetBoolVariable("hocr_font_info", &font_info); GetBoolVariable("hocr_char_boxes", &hocr_boxes); if (input_file_.empty()) { SetInputName(nullptr); } #ifdef _WIN32 // convert input name from ANSI encoding to utf-8 int str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_.c_str(), -1, nullptr, 0); wchar_t *uni16_str = new WCHAR[str16_len]; str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_.c_str(), -1, uni16_str, str16_len); int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, nullptr, 0, nullptr, nullptr); char *utf8_str = new char[utf8_len]; WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str, utf8_len, nullptr, nullptr); input_file_ = utf8_str; delete[] uni16_str; delete[] utf8_str; #endif std::stringstream hocr_str; // Use "C" locale (needed for double values x_size and x_descenders). hocr_str.imbue(std::locale::classic()); // Use 8 digits for double values. hocr_str.precision(8); hocr_str << " <div class='ocr_page'" << " id='" << "page_" << page_id << "'" << " title='image \""; if (!input_file_.empty()) { hocr_str << HOcrEscape(input_file_.c_str()); } else { hocr_str << "unknown"; } hocr_str << "\"; bbox " << rect_left_ << " " << rect_top_ << " " << rect_width_ << " " << rect_height_ << "; ppageno " << page_number << "; scan_res " << GetSourceYResolution() << " " << GetSourceYResolution() << "'>\n"; std::unique_ptr<ResultIterator> res_it(GetIterator()); while (!res_it->Empty(RIL_BLOCK)) { int left, top, right, bottom; auto block_type = res_it->BlockType(); switch (block_type) { case PT_FLOWING_IMAGE: case PT_HEADING_IMAGE: case PT_PULLOUT_IMAGE: { // Handle all kinds of images. res_it.get()->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom); hocr_str << " <div class='ocr_photo' id='block_" << page_id << '_' << bcnt++ << "' title=\"bbox " << left << " " << top << " " << right << " " << bottom << "\"></div>\n"; res_it->Next(RIL_BLOCK); continue; } case PT_HORZ_LINE: case PT_VERT_LINE: // Handle horizontal and vertical lines. res_it.get()->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom); hocr_str << " <div class='ocr_separator' id='block_" << page_id << '_' << bcnt++ << "' title=\"bbox " << left << " " << top << " " << right << " " << bottom << "\"></div>\n"; res_it->Next(RIL_BLOCK); continue; case PT_NOISE: tprintf("TODO: Please report image which triggers the noise case.\n"); ASSERT_HOST(false); default: break; } if (res_it->Empty(RIL_WORD)) { res_it->Next(RIL_WORD); continue; } // Open any new block/paragraph/textline. if (res_it->IsAtBeginningOf(RIL_BLOCK)) { para_is_ltr = true; // reset to default direction hocr_str << " <div class='ocr_carea'" << " id='" << "block_" << page_id << "_" << bcnt << "'"; AddBoxTohOCR(res_it.get(), RIL_BLOCK, hocr_str); } if (res_it->IsAtBeginningOf(RIL_PARA)) { hocr_str << "\n <p class='ocr_par'"; para_is_ltr = res_it->ParagraphIsLtr(); if (!para_is_ltr) { hocr_str << " dir='rtl'"; } hocr_str << " id='" << "par_" << page_id << "_" << pcnt << "'"; paragraph_lang = res_it->WordRecognitionLanguage(); if (paragraph_lang) { hocr_str << " lang='" << paragraph_lang << "'"; } AddBoxTohOCR(res_it.get(), RIL_PARA, hocr_str); } if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { hocr_str << "\n <span class='"; switch (block_type) { case PT_HEADING_TEXT: hocr_str << "ocr_header"; break; case PT_PULLOUT_TEXT: hocr_str << "ocr_textfloat"; break; case PT_CAPTION_TEXT: hocr_str << "ocr_caption"; break; case PT_FLOWING_IMAGE: case PT_HEADING_IMAGE: case PT_PULLOUT_IMAGE: ASSERT_HOST(false); break; default: hocr_str << "ocr_line"; } hocr_str << "' id='" << "line_" << page_id << "_" << lcnt << "'"; AddBoxTohOCR(res_it.get(), RIL_TEXTLINE, hocr_str); } // Now, process the word... int32_t lstm_choice_mode = tesseract_->lstm_choice_mode; std::vector<std::vector<std::vector<std::pair<const char *, float>>>> *rawTimestepMap = nullptr; std::vector<std::vector<std::pair<const char *, float>>> *CTCMap = nullptr; if (lstm_choice_mode) { CTCMap = res_it->GetBestLSTMSymbolChoices(); rawTimestepMap = res_it->GetRawLSTMTimesteps(); } hocr_str << "\n <span class='ocrx_word'" << " id='" << "word_" << page_id << "_" << wcnt << "'"; bool bold, italic, underlined, monospace, serif, smallcaps; int pointsize, font_id; res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom); const char *font_name = res_it->WordFontAttributes(&bold, &italic, &underlined, &monospace, &serif, &smallcaps, &pointsize, &font_id); hocr_str << " title='bbox " << left << " " << top << " " << right << " " << bottom << "; x_wconf " << static_cast<int>(res_it->Confidence(RIL_WORD)); if (font_info) { if (font_name) { hocr_str << "; x_font " << HOcrEscape(font_name).c_str(); } hocr_str << "; x_fsize " << pointsize; } hocr_str << "'"; const char *lang = res_it->WordRecognitionLanguage(); if (lang && (!paragraph_lang || strcmp(lang, paragraph_lang))) { hocr_str << " lang='" << lang << "'"; } switch (res_it->WordDirection()) { // Only emit direction if different from current paragraph direction case DIR_LEFT_TO_RIGHT: if (!para_is_ltr) { hocr_str << " dir='ltr'"; } break; case DIR_RIGHT_TO_LEFT: if (para_is_ltr) { hocr_str << " dir='rtl'"; } break; case DIR_MIX: case DIR_NEUTRAL: default: // Do nothing. break; } hocr_str << ">"; bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD); bool last_word_in_para = res_it->IsAtFinalElement(RIL_PARA, RIL_WORD); bool last_word_in_block = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD); if (bold) { hocr_str << "<strong>"; } if (italic) { hocr_str << "<em>"; } do { const std::unique_ptr<const char[]> grapheme( res_it->GetUTF8Text(RIL_SYMBOL)); if (grapheme && grapheme[0] != 0) { if (hocr_boxes) { res_it->BoundingBox(RIL_SYMBOL, &left, &top, &right, &bottom); hocr_str << "\n <span class='ocrx_cinfo' title='x_bboxes " << left << " " << top << " " << right << " " << bottom << "; x_conf " << res_it->Confidence(RIL_SYMBOL) << "'>"; } hocr_str << HOcrEscape(grapheme.get()).c_str(); if (hocr_boxes) { hocr_str << "</span>"; tesseract::ChoiceIterator ci(*res_it); if (lstm_choice_mode == 1 && ci.Timesteps() != nullptr) { std::vector<std::vector<std::pair<const char *, float>>> *symbol = ci.Timesteps(); hocr_str << "\n <span class='ocr_symbol'" << " id='" << "symbol_" << page_id << "_" << wcnt << "_" << scnt << "'>"; for (const auto &timestep : *symbol) { hocr_str << "\n <span class='ocrx_cinfo'" << " id='" << "timestep" << page_id << "_" << wcnt << "_" << tcnt << "'>"; for (auto conf : timestep) { hocr_str << "\n <span class='ocrx_cinfo'" << " id='" << "choice_" << page_id << "_" << wcnt << "_" << ccnt << "'" << " title='x_confs " << int(conf.second * 100) << "'>" << HOcrEscape(conf.first).c_str() << "</span>"; ++ccnt; } hocr_str << "</span>"; ++tcnt; } hocr_str << "\n </span>"; ++scnt; } else if (lstm_choice_mode == 2) { hocr_str << "\n <span class='ocrx_cinfo'" << " id='" << "lstm_choices_" << page_id << "_" << wcnt << "_" << tcnt << "'>"; do { const char *choice = ci.GetUTF8Text(); float choiceconf = ci.Confidence(); if (choice != nullptr) { hocr_str << "\n <span class='ocrx_cinfo'" << " id='" << "choice_" << page_id << "_" << wcnt << "_" << ccnt << "'" << " title='x_confs " << choiceconf << "'>" << HOcrEscape(choice).c_str() << "</span>"; ccnt++; } } while (ci.Next()); hocr_str << "\n </span>"; tcnt++; } } } res_it->Next(RIL_SYMBOL); } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD)); if (italic) { hocr_str << "</em>"; } if (bold) { hocr_str << "</strong>"; } // If the lstm choice mode is required it is added here if (lstm_choice_mode == 1 && !hocr_boxes && rawTimestepMap != nullptr) { for (const auto &symbol : *rawTimestepMap) { hocr_str << "\n <span class='ocr_symbol'" << " id='" << "symbol_" << page_id << "_" << wcnt << "_" << scnt << "'>"; for (const auto &timestep : symbol) { hocr_str << "\n <span class='ocrx_cinfo'" << " id='" << "timestep" << page_id << "_" << wcnt << "_" << tcnt << "'>"; for (auto &&conf : timestep) { hocr_str << "\n <span class='ocrx_cinfo'" << " id='" << "choice_" << page_id << "_" << wcnt << "_" << ccnt << "'" << " title='x_confs " << int(conf.second * 100) << "'>" << HOcrEscape(conf.first).c_str() << "</span>"; ++ccnt; } hocr_str << "</span>"; ++tcnt; } hocr_str << "</span>"; ++scnt; } } else if (lstm_choice_mode == 2 && !hocr_boxes && CTCMap != nullptr) { for (const auto &timestep : *CTCMap) { if (timestep.size() > 0) { hocr_str << "\n <span class='ocrx_cinfo'" << " id='" << "lstm_choices_" << page_id << "_" << wcnt << "_" << tcnt << "'>"; for (auto &j : timestep) { float conf = 100 - tesseract_->lstm_rating_coefficient * j.second; if (conf < 0.0f) { conf = 0.0f; } if (conf > 100.0f) { conf = 100.0f; } hocr_str << "\n <span class='ocrx_cinfo'" << " id='" << "choice_" << page_id << "_" << wcnt << "_" << ccnt << "'" << " title='x_confs " << conf << "'>" << HOcrEscape(j.first).c_str() << "</span>"; ccnt++; } hocr_str << "</span>"; tcnt++; } } } // Close ocrx_word. if (hocr_boxes || lstm_choice_mode > 0) { hocr_str << "\n "; } hocr_str << "</span>"; tcnt = 1; ccnt = 1; wcnt++; // Close any ending block/paragraph/textline. if (last_word_in_line) { hocr_str << "\n </span>"; lcnt++; } if (last_word_in_para) { hocr_str << "\n </p>\n"; pcnt++; para_is_ltr = true; // back to default direction } if (last_word_in_block) { hocr_str << " </div>\n"; bcnt++; } } hocr_str << " </div>\n"; return copy_string(hocr_str.str()); } /********************************************************************** * HOcr Text Renderer interface implementation **********************************************************************/ TessHOcrRenderer::TessHOcrRenderer(const char *outputbase) : TessResultRenderer(outputbase, "hocr") { font_info_ = false; } TessHOcrRenderer::TessHOcrRenderer(const char *outputbase, bool font_info) : TessResultRenderer(outputbase, "hocr") { font_info_ = font_info; } bool TessHOcrRenderer::BeginDocumentHandler() { AppendString( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n" " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" " "lang=\"en\">\n <head>\n <title>"); AppendString(title()); AppendString( "</title>\n" " <meta http-equiv=\"Content-Type\" content=\"text/html;" "charset=utf-8\"/>\n" " <meta name='ocr-system' content='tesseract " TESSERACT_VERSION_STR "' />\n" " <meta name='ocr-capabilities' content='ocr_page ocr_carea ocr_par" " ocr_line ocrx_word ocrp_wconf"); if (font_info_) { AppendString(" ocrp_lang ocrp_dir ocrp_font ocrp_fsize"); } AppendString( "'/>\n" " </head>\n" " <body>\n"); return true; } bool TessHOcrRenderer::EndDocumentHandler() { AppendString(" </body>\n</html>\n"); return true; } bool TessHOcrRenderer::AddImageHandler(TessBaseAPI *api) { const std::unique_ptr<const char[]> hocr(api->GetHOCRText(imagenum())); if (hocr == nullptr) { return false; } AppendString(hocr.get()); return true; } } // namespace tesseract
2301_81045437/tesseract
src/api/hocrrenderer.cpp
C++
apache-2.0
20,092
/********************************************************************** * File: lstmboxrenderer.cpp * Description: Renderer for creating box file for LSTM training. * based on the tsv renderer. * * (C) Copyright 2019, Google Inc. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <tesseract/baseapi.h> // for TessBaseAPI #include <tesseract/renderer.h> #include "helpers.h" // for copy_string #include "tesseractclass.h" // for Tesseract namespace tesseract { /** * Create a UTF8 box file for LSTM training from the internal data structures. * page_number is a 0-base page index that will appear in the box file. * Returned string must be freed with the delete [] operator. */ static void AddBoxToLSTM(int right, int bottom, int top, int image_height, int page_num, std::string &text) { text += " " + std::to_string(image_height - bottom); text += " " + std::to_string(right + 5); text += " " + std::to_string(image_height - top); text += " " + std::to_string(page_num); } char *TessBaseAPI::GetLSTMBoxText(int page_number = 0) { if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(nullptr) < 0)) { return nullptr; } std::string lstm_box_str; bool first_word = true; int left = 0, top = 0, right = 0, bottom = 0; LTRResultIterator *res_it = GetLTRIterator(); while (!res_it->Empty(RIL_BLOCK)) { if (res_it->Empty(RIL_SYMBOL)) { res_it->Next(RIL_SYMBOL); continue; } if (!first_word) { if (!(res_it->IsAtBeginningOf(RIL_TEXTLINE))) { if (res_it->IsAtBeginningOf(RIL_WORD)) { lstm_box_str += " " + std::to_string(left); AddBoxToLSTM(right, bottom, top, image_height_, page_number, lstm_box_str); lstm_box_str += "\n"; // end of row for word } // word } else { if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { lstm_box_str += "\t " + std::to_string(left); AddBoxToLSTM(right, bottom, top, image_height_, page_number, lstm_box_str); lstm_box_str += "\n"; // end of row for line } // line } } // not first word first_word = false; // Use bounding box for whole line for everything res_it->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom); do { lstm_box_str += std::unique_ptr<const char[]>(res_it->GetUTF8Text(RIL_SYMBOL)).get(); res_it->Next(RIL_SYMBOL); } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_SYMBOL)); lstm_box_str += " " + std::to_string(left); AddBoxToLSTM(right, bottom, top, image_height_, page_number, lstm_box_str); lstm_box_str += "\n"; // end of row for symbol } if (!first_word) { // if first_word is true => empty page lstm_box_str += "\t " + std::to_string(left); AddBoxToLSTM(right, bottom, top, image_height_, page_number, lstm_box_str); lstm_box_str += "\n"; // end of PAGE } delete res_it; return copy_string(lstm_box_str); } /********************************************************************** * LSTMBox Renderer interface implementation **********************************************************************/ TessLSTMBoxRenderer::TessLSTMBoxRenderer(const char *outputbase) : TessResultRenderer(outputbase, "box") {} bool TessLSTMBoxRenderer::AddImageHandler(TessBaseAPI *api) { const std::unique_ptr<const char[]> lstmbox(api->GetLSTMBoxText(imagenum())); if (lstmbox == nullptr) { return false; } AppendString(lstmbox.get()); return true; } } // namespace tesseract.
2301_81045437/tesseract
src/api/lstmboxrenderer.cpp
C++
apache-2.0
4,187
// File: pagerenderer.cpp // Description: PAGE XML rendering interface // Author: Jan Kamlah // (C) Copyright 2021 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "errcode.h" // for ASSERT_HOST #include "helpers.h" // for copy_string #ifdef _WIN32 # include "host.h" // windows.h for MultiByteToWideChar, ... #endif #include "tprintf.h" // for tprintf #include <tesseract/baseapi.h> #include <tesseract/renderer.h> #include <ctime> #include <iomanip> #include <memory> #include <regex> #include <sstream> // for std::stringstream #include <unordered_set> #include <allheaders.h> #if (LIBLEPT_MAJOR_VERSION == 1 && LIBLEPT_MINOR_VERSION >= 83) || \ LIBLEPT_MAJOR_VERSION > 1 # include <array_internal.h> # include <pix_internal.h> #endif namespace tesseract { /// /// Slope and offset between two points /// static void GetSlopeAndOffset(float x0, float y0, float x1, float y1, float *m, float *b) { float slope; slope = ((y1 - y0) / (x1 - x0)); *m = slope; *b = y0 - slope * x0; } /// /// Write coordinates in the form of a points to a stream /// static void AddPointsToPAGE(Pta *pts, std::stringstream &str) { int num_pts; str << "<Coords points=\""; num_pts = ptaGetCount(pts); for (int p = 0; p < num_pts; ++p) { int x, y; ptaGetIPt(pts, p, &x, &y); if (p != 0) { str << " "; } str << std::to_string(x) << "," << std::to_string(y); } str << "\"/>\n"; } /// /// Convert bbox information to top and bottom polygon /// static void AddPointToWordPolygon( const ResultIterator *res_it, PageIteratorLevel level, Pta *word_top_pts, Pta *word_bottom_pts, tesseract::WritingDirection writing_direction) { int left, top, right, bottom; res_it->BoundingBox(level, &left, &top, &right, &bottom); if (writing_direction != WRITING_DIRECTION_TOP_TO_BOTTOM) { ptaAddPt(word_top_pts, left, top); ptaAddPt(word_top_pts, right, top); ptaAddPt(word_bottom_pts, left, bottom); ptaAddPt(word_bottom_pts, right, bottom); } else { // Transform from ttb to ltr ptaAddPt(word_top_pts, top, right); ptaAddPt(word_top_pts, bottom, right); ptaAddPt(word_bottom_pts, top, left); ptaAddPt(word_bottom_pts, bottom, left); } } /// /// Transpose polygonline, destroy old and return new pts /// Pta *TransposePolygonline(Pta *pts) { Pta *pts_transposed; pts_transposed = ptaTranspose(pts); ptaDestroy(&pts); return pts_transposed; } /// /// Reverse polygonline, destroy old and return new pts /// Pta *ReversePolygonline(Pta *pts, int type) { Pta *pts_reversed; pts_reversed = ptaReverse(pts, type); ptaDestroy(&pts); return pts_reversed; } /// /// Destroy old and create new pts /// Pta *DestroyAndCreatePta(Pta *pts) { ptaDestroy(&pts); return ptaCreate(0); } /// /// Recalculate linepolygon /// Create a hull for overlapping areas /// Pta *RecalcPolygonline(Pta *pts, bool upper) { int num_pts, num_bin, index = 0; int y, x0, y0, x1, y1; float x_min, y_min, x_max, y_max; NUMA *bin_line; Pta *pts_recalc; ptaGetMinMax(pts, &x_min, &y_min, &x_max, &y_max); num_bin = x_max - x_min; bin_line = numaCreate(num_bin + 1); for (int p = 0; p <= num_bin; ++p) { bin_line->array[p] = -1.; } num_pts = ptaGetCount(pts); if (num_pts == 2) { pts_recalc = ptaCopy(pts); ptaDestroy(&pts); return pts_recalc; } do { ptaGetIPt(pts, index, &x0, &y0); ptaGetIPt(pts, index + 1, &x1, &y1); for (int p = x0 - x_min; p <= x1 - x_min; ++p) { if (!upper) { if (bin_line->array[p] == -1. || y0 > bin_line->array[p]) { bin_line->array[p] = y0; } } else { if (bin_line->array[p] == -1. || y0 < bin_line->array[p]) { bin_line->array[p] = y0; } } } index += 2; } while (index < num_pts - 1); pts_recalc = ptaCreate(0); for (int p = 0; p <= num_bin; ++p) { if (p == 0) { y = bin_line->array[p]; ptaAddPt(pts_recalc, x_min + p, y); } else if (p == num_bin) { ptaAddPt(pts_recalc, x_min + p, y); break; } else if (y != bin_line->array[p]) { if (y != -1.) { ptaAddPt(pts_recalc, x_min + p, y); } y = bin_line->array[p]; if (y != -1.) { ptaAddPt(pts_recalc, x_min + p, y); } } } ptaDestroy(&pts); return pts_recalc; } /// /// Create a rectangle hull around a single line /// Pta *PolygonToBoxCoords(Pta *pts) { Pta *pts_box; float x_min, y_min, x_max, y_max; pts_box = ptaCreate(0); ptaGetMinMax(pts, &x_min, &y_min, &x_max, &y_max); ptaAddPt(pts_box, x_min, y_min); ptaAddPt(pts_box, x_max, y_min); ptaAddPt(pts_box, x_max, y_max); ptaAddPt(pts_box, x_min, y_max); ptaDestroy(&pts); return pts_box; } /// /// Create a rectangle polygon round the existing multiple lines /// static void UpdateBlockPoints(Pta *block_top_pts, Pta *block_bottom_pts, Pta *line_top_pts, Pta *line_bottom_pts, int lcnt, int last_word_in_cblock) { int num_pts; int x, y; // Create a hull around all lines if (lcnt == 0 && last_word_in_cblock) { ptaJoin(block_top_pts, line_top_pts, 0, -1); ptaJoin(block_bottom_pts, line_bottom_pts, 0, -1); } else if (lcnt == 0) { ptaJoin(block_top_pts, line_top_pts, 0, -1); num_pts = ptaGetCount(line_bottom_pts); ptaGetIPt(line_bottom_pts, num_pts - 1, &x, &y); ptaAddPt(block_top_pts, x, y); ptaGetIPt(line_bottom_pts, 0, &x, &y); ptaAddPt(block_bottom_pts, x, y); } else if (last_word_in_cblock) { ptaGetIPt(line_top_pts, 0, &x, &y); ptaAddPt(block_bottom_pts, x, y); ptaJoin(block_bottom_pts, line_bottom_pts, 0, -1); num_pts = ptaGetCount(line_top_pts); ptaGetIPt(line_top_pts, num_pts - 1, &x, &y); ptaAddPt(block_top_pts, x, y); } else { ptaGetIPt(line_top_pts, 0, &x, &y); ptaAddPt(block_bottom_pts, x, y); ptaGetIPt(line_bottom_pts, 0, &x, &y); ptaAddPt(block_bottom_pts, x, y); num_pts = ptaGetCount(line_top_pts); ptaGetIPt(line_top_pts, num_pts - 1, &x, &y); ptaAddPt(block_top_pts, x, y); num_pts = ptaGetCount(line_bottom_pts); ptaGetIPt(line_bottom_pts, num_pts - 1, &x, &y); ptaAddPt(block_top_pts, x, y); }; } /// /// Simplify polygonlines (only expanding not shrinking) (Due to recalculation /// currently not necessary) /// static void SimplifyLinePolygon(Pta *polyline, int tolerance, bool upper) { int x0, y0, x1, y1, x2, y2, x3, y3, index = 1; float m, b, y_min, y_max; while (index <= polyline->n - 2) { ptaGetIPt(polyline, index - 1, &x0, &y0); ptaGetIPt(polyline, index, &x1, &y1); ptaGetIPt(polyline, index + 1, &x2, &y2); if (index + 2 < polyline->n) { // Delete two point indentations ptaGetIPt(polyline, index + 2, &x3, &y3); if (abs(x3 - x0) <= tolerance * 2) { GetSlopeAndOffset(x0, y0, x3, y3, &m, &b); if (upper && (m * x1 + b) < y1 && (m * x2 + b) < y2) { ptaRemovePt(polyline, index + 1); ptaRemovePt(polyline, index); continue; } else if (!upper && (m * x1 + b) > y1 && (m * x2 + b) > y2) { ptaRemovePt(polyline, index + 1); ptaRemovePt(polyline, index); continue; } } } // Delete one point indentations if (abs(y0 - y1) <= tolerance && abs(y1 - y2) <= tolerance) { GetSlopeAndOffset(x0, y0, x2, y2, &m, &b); if (upper && (m * x1 + b) <= y1) { ptaRemovePt(polyline, index); continue; } else if (!upper && (m * x1 + b) >= y1) { ptaRemovePt(polyline, index); continue; } } // Delete near by points if (x1 != x0 && abs(y1 - y0) < 4 && abs(x1 - x0) <= tolerance) { if (upper) { y_min = std::min(y0, y1); GetSlopeAndOffset(x0, y_min, x2, y2, &m, &b); if ((m * x1 + b) <= y1) { polyline->y[index - 1] = std::min(y0, y1); ptaRemovePt(polyline, index); continue; } } else { y_max = std::max(y0, y1); GetSlopeAndOffset(x0, y_max, x2, y2, &m, &b); if ((m * x1 + b) >= y1) { polyline->y[index - 1] = y_max; ptaRemovePt(polyline, index); continue; } } } index++; } } /// /// Directly write bounding box information as coordinates a stream /// static void AddBoxToPAGE(const ResultIterator *it, PageIteratorLevel level, std::stringstream &page_str) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); page_str << "<Coords points=\"" << left << "," << top << " " << right << "," << top << " " << right << "," << bottom << " " << left << "," << bottom << "\"/>\n"; } /// /// Join ltr and rtl polygon information /// static void AppendLinePolygon(Pta *pts_ltr, Pta *pts_rtl, Pta *ptss, tesseract::WritingDirection writing_direction) { // If writing direction is NOT right-to-left, handle the left-to-right case. if (writing_direction != WRITING_DIRECTION_RIGHT_TO_LEFT) { if (ptaGetCount(pts_rtl) != 0) { ptaJoin(pts_ltr, pts_rtl, 0, -1); DestroyAndCreatePta(pts_rtl); } ptaJoin(pts_ltr, ptss, 0, -1); } else { // For right-to-left, work with a copy of ptss initially. PTA *ptsd = ptaCopy(ptss); if (ptaGetCount(pts_rtl) != 0) { ptaJoin(ptsd, pts_rtl, 0, -1); } ptaDestroy(&pts_rtl); ptaCopy(ptsd); } } /// /// Convert baseline to points and add to polygon /// static void AddBaselineToPTA(const ResultIterator *it, PageIteratorLevel level, Pta *baseline_pts) { int x1, y1, x2, y2; it->Baseline(level, &x1, &y1, &x2, &y2); ptaAddPt(baseline_pts, x1, y1); ptaAddPt(baseline_pts, x2, y2); } /// /// Directly write baseline information as baseline points a stream /// static void AddBaselinePtsToPAGE(Pta *baseline_pts, std::stringstream &str) { int x, y, num_pts = baseline_pts->n; str << "<Baseline points=\""; for (int p = 0; p < num_pts; ++p) { ptaGetIPt(baseline_pts, p, &x, &y); if (p != 0) { str << " "; } str << std::to_string(x) << "," << std::to_string(y); } str << "\"/>\n"; } /// /// Sort baseline points ascending and deleting duplicates /// Pta *SortBaseline(Pta *baseline_pts, tesseract::WritingDirection writing_direction) { int num_pts, index = 0; float x0, y0, x1, y1; Pta *sorted_baseline_pts; sorted_baseline_pts = ptaSort(baseline_pts, L_SORT_BY_X, L_SORT_INCREASING, nullptr); do { ptaGetPt(sorted_baseline_pts, index, &x0, &y0); ptaGetPt(sorted_baseline_pts, index + 1, &x1, &y1); if (x0 >= x1) { sorted_baseline_pts->y[index] = std::min(y0, y1); ptaRemovePt(sorted_baseline_pts, index + 1); } else { index++; } num_pts = ptaGetCount(sorted_baseline_pts); } while (index < num_pts - 1); ptaDestroy(&baseline_pts); return sorted_baseline_pts; } /// /// Clip baseline to range of the exsitings polygon and simplifies the baseline /// linepolygon /// Pta *ClipAndSimplifyBaseline(Pta *bottom_pts, Pta *baseline_pts, tesseract::WritingDirection writing_direction) { int num_pts; float m, b, x0, y0, x1, y1; float x_min, y_min, x_max, y_max; Pta *baseline_clipped_pts; ptaGetMinMax(bottom_pts, &x_min, &y_min, &x_max, &y_max); num_pts = ptaGetCount(baseline_pts); baseline_clipped_pts = ptaCreate(0); // Clip Baseline for (int p = 0; p < num_pts; ++p) { ptaGetPt(baseline_pts, p, &x0, &y0); if (x0 < x_min) { if (p + 1 < num_pts) { ptaGetPt(baseline_pts, p + 1, &x1, &y1); if (x1 < x_min) { continue; } else { GetSlopeAndOffset(x0, y0, x1, y1, &m, &b); y0 = int(x_min * m + b); x0 = x_min; } } } else if (x0 > x_max) { if (ptaGetCount(baseline_clipped_pts) > 0 && p > 0) { ptaGetPt(baseline_pts, p - 1, &x1, &y1); // See comment above GetSlopeAndOffset(x1, y1, x0, y0, &m, &b); y0 = int(x_max * m + b); x0 = x_max; ptaAddPt(baseline_clipped_pts, x0, y0); break; } } ptaAddPt(baseline_clipped_pts, x0, y0); } if (writing_direction == WRITING_DIRECTION_TOP_TO_BOTTOM) { SimplifyLinePolygon(baseline_clipped_pts, 3, 0); } else { SimplifyLinePolygon(baseline_clipped_pts, 3, 1); } SimplifyLinePolygon( baseline_clipped_pts, 3, writing_direction == WRITING_DIRECTION_TOP_TO_BOTTOM ? 0 : 1); // Check the number of points in baseline_clipped_pts after processing int clipped_pts_count = ptaGetCount(baseline_clipped_pts); if (clipped_pts_count < 2) { // If there's only one point in baseline_clipped_pts, duplicate it ptaDestroy(&baseline_clipped_pts); // Clean up the created but unused Pta baseline_clipped_pts = ptaCreate(0); ptaAddPt(baseline_clipped_pts, x_min, y_min); ptaAddPt(baseline_clipped_pts, x_max, y_min); } return baseline_clipped_pts; } /// /// Fit the baseline points into the existings polygon /// Pta *FitBaselineIntoLinePolygon(Pta *bottom_pts, Pta *baseline_pts, tesseract::WritingDirection writing_direction) { int num_pts, num_bin, x0, y0, x1, y1; float m, b; float x_min, y_min, x_max, y_max; float delta_median, delta_median_Q1, delta_median_Q3; NUMA *bin_line, *poly_bl_delta; Pta *baseline_recalc_pts, *baseline_clipped_pts; ptaGetMinMax(bottom_pts, &x_min, &y_min, &x_max, &y_max); num_bin = x_max - x_min; bin_line = numaCreate(num_bin + 1); for (int p = 0; p < num_bin + 1; ++p) { bin_line->array[p] = -1.; } num_pts = ptaGetCount(bottom_pts); // Create a interpolated polygon with stepsize 1 for (int index = 0; index < num_pts - 1; ++index) { ptaGetIPt(bottom_pts, index, &x0, &y0); ptaGetIPt(bottom_pts, index + 1, &x1, &y1); if (x0 >= x1) { continue; } if (y0 == y1) { for (int p = x0 - x_min; p < x1 - x_min + 1; ++p) { if (bin_line->array[p] == -1. || y0 > bin_line->array[p]) { bin_line->array[p] = y0; } } } else { GetSlopeAndOffset(x0, y0, x1, y1, &m, &b); for (int p = x0 - x_min; p < x1 - x_min + 1; ++p) { if (bin_line->array[p] == -1. || ((p + x_min) * m + b) > bin_line->array[p]) { bin_line->array[p] = ((p + x_min) * m + b); } } } } num_pts = ptaGetCount(baseline_pts); baseline_clipped_pts = ptaCreate(0); poly_bl_delta = numaCreate(0); // Clip Baseline and create a set of deltas between baseline and polygon for (int p = 0; p < num_pts; ++p) { ptaGetIPt(baseline_pts, p, &x0, &y0); if (x0 < x_min) { ptaGetIPt(baseline_pts, p + 1, &x1, &y1); if (x1 < x_min) { continue; } else { GetSlopeAndOffset(x0, y0, x1, y1, &m, &b); y0 = int(x_min * m + b); x0 = x_min; } } else if (x0 > x_max) { if (ptaGetCount(baseline_clipped_pts) > 0) { ptaGetIPt(baseline_pts, p - 1, &x1, &y1); GetSlopeAndOffset(x1, y1, x0, y0, &m, &b); y0 = int(x_max * m + b); x0 = x_max; int x_val = x0 - x_min; numaAddNumber(poly_bl_delta, abs(bin_line->array[x_val] - y0)); ptaAddPt(baseline_clipped_pts, x0, y0); break; } } int x_val = x0 - x_min; numaAddNumber(poly_bl_delta, abs(bin_line->array[x_val] - y0)); ptaAddPt(baseline_clipped_pts, x0, y0); } ptaDestroy(&baseline_pts); // Calculate quartiles to find outliers numaGetMedian(poly_bl_delta, &delta_median); numaGetRankValue(poly_bl_delta, 0.25, nullptr, 0, &delta_median_Q1); numaGetRankValue(poly_bl_delta, 0.75, nullptr, 0, &delta_median_Q3); // Fit baseline into the polygon // Todo: Needs maybe some adjustments to suppress fitting to superscript // glyphs baseline_recalc_pts = ptaCreate(0); num_pts = ptaGetCount(baseline_clipped_pts); for (int p = 0; p < num_pts; ++p) { ptaGetIPt(baseline_clipped_pts, p, &x0, &y0); int x_val = x0 - x_min; // Delete outliers with IQR if (abs(y0 - bin_line->array[x_val]) > 1.5 * delta_median_Q3 + delta_median && p != 0 && p != num_pts - 1) { continue; } if (writing_direction == WRITING_DIRECTION_TOP_TO_BOTTOM) { if (y0 < bin_line->array[x_val]) { ptaAddPt(baseline_recalc_pts, x0, bin_line->array[x_val]); } else { ptaAddPt(baseline_recalc_pts, x0, y0); } } else { if (y0 > bin_line->array[x_val]) { ptaAddPt(baseline_recalc_pts, x0, bin_line->array[x_val]); } else { ptaAddPt(baseline_recalc_pts, x0, y0); } } } // Return recalculated baseline if this fails return the bottom line as // baseline ptaDestroy(&baseline_clipped_pts); if (ptaGetCount(baseline_recalc_pts) < 2) { ptaDestroy(&baseline_recalc_pts); return ptaCopy(bottom_pts); } else { return baseline_recalc_pts; } } /// Convert writing direction to string representation const char *WritingDirectionToStr(int wd) { switch (wd) { case 0: return "left-to-right"; case 1: return "right-to-left"; case 2: return "top-to-bottom"; default: return "bottom-to-top"; } } /// /// Append the PAGE XML for the beginning of the document /// bool TessPAGERenderer::BeginDocumentHandler() { // Delay the XML output because we need the name of the image file. begin_document = true; return true; } /// /// Append the PAGE XML for the layout of the image /// bool TessPAGERenderer::AddImageHandler(TessBaseAPI *api) { if (begin_document) { AppendString( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" "<PcGts " "xmlns=\"http://schema.primaresearch.org/PAGE/gts/pagecontent/" "2019-07-15\" " "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " "xsi:schemaLocation=\"http://schema.primaresearch.org/PAGE/gts/" "pagecontent/2019-07-15 " "http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15/" "pagecontent.xsd\">\n" "\t<Metadata"); // If a URL is used to recognize a image add it as <Metadata // externalRef="url"> if (std::regex_search(api->GetInputName(), std::regex("^(https?|ftp|ssh):"))) { AppendString(" externalRef=\""); AppendString(api->GetInputName()); AppendString("\" "); } AppendString( ">\n" "\t\t<Creator>Tesseract - "); AppendString(TESSERACT_VERSION_STR); // If gmtime conversion is problematic maybe l_getFormattedDate can be used // here // char *datestr = l_getFormattedDate(); std::time_t now = std::time(nullptr); std::tm *now_tm = std::gmtime(&now); char mbstr[100]; std::strftime(mbstr, sizeof(mbstr), "%Y-%m-%dT%H:%M:%S", now_tm); AppendString( "</Creator>\n" "\t\t<Created>"); AppendString(mbstr); AppendString("</Created>\n"); AppendString("\t\t<LastChange>"); AppendString(mbstr); AppendString( "</LastChange>\n" "\t</Metadata>\n"); begin_document = false; } const std::unique_ptr<const char[]> text(api->GetPAGEText(imagenum())); if (text == nullptr) { return false; } AppendString(text.get()); return true; } /// /// Append the PAGE XML for the end of the document /// bool TessPAGERenderer::EndDocumentHandler() { AppendString("\t\t</Page>\n</PcGts>\n"); return true; } TessPAGERenderer::TessPAGERenderer(const char *outputbase) : TessResultRenderer(outputbase, "page.xml"), begin_document(false) {} /// /// Make an XML-formatted string with PAGE markup from the internal /// data structures. /// char *TessBaseAPI::GetPAGEText(int page_number) { return GetPAGEText(nullptr, page_number); } /// /// Make an XML-formatted string with PAGE markup from the internal /// data structures. /// char *TessBaseAPI::GetPAGEText(ETEXT_DESC *monitor, int page_number) { if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(monitor) < 0)) { return nullptr; } int rcnt = 0, lcnt = 0, wcnt = 0; if (input_file_.empty()) { SetInputName(nullptr); } #ifdef _WIN32 // convert input name from ANSI encoding to utf-8 int str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_.c_str(), -1, nullptr, 0); wchar_t *uni16_str = new WCHAR[str16_len]; str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_.c_str(), -1, uni16_str, str16_len); int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, nullptr, 0, nullptr, nullptr); char *utf8_str = new char[utf8_len]; WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str, utf8_len, nullptr, nullptr); input_file_ = utf8_str; delete[] uni16_str; delete[] utf8_str; #endif // Used variables std::stringstream reading_order_str; std::stringstream region_content; std::stringstream line_content; std::stringstream word_content; std::stringstream line_str; std::stringstream line_inter_str; std::stringstream word_str; std::stringstream page_str; float x1, y1, x2, y2; tesseract::Orientation orientation_block = ORIENTATION_PAGE_UP; tesseract::WritingDirection writing_direction_block = WRITING_DIRECTION_LEFT_TO_RIGHT; tesseract::TextlineOrder textline_order_block; Pta *block_top_pts = ptaCreate(0); Pta *block_bottom_pts = ptaCreate(0); Pta *line_top_ltr_pts = ptaCreate(0); Pta *line_bottom_ltr_pts = ptaCreate(0); Pta *line_top_rtl_pts = ptaCreate(0); Pta *line_bottom_rtl_pts = ptaCreate(0); Pta *word_top_pts = ptaCreate(0); Pta *word_bottom_pts = ptaCreate(0); Pta *word_baseline_pts = ptaCreate(0); Pta *line_baseline_rtl_pts = ptaCreate(0); Pta *line_baseline_ltr_pts = ptaCreate(0); Pta *line_baseline_pts = ptaCreate(0); bool POLYGONFLAG; GetBoolVariable("page_xml_polygon", &POLYGONFLAG); int LEVELFLAG; GetIntVariable("page_xml_level", &LEVELFLAG); if (LEVELFLAG != 0 && LEVELFLAG != 1) { tprintf( "For now, only line level and word level are available, and the level " "is reset to line level.\n"); LEVELFLAG = 0; } // Use "C" locale (needed for int values larger than 999). page_str.imbue(std::locale::classic()); reading_order_str << "\t<Page " << "imageFilename=\"" << GetInputName(); // AppendString(api->GetInputName()); reading_order_str << "\" " << "imageWidth=\"" << rect_width_ << "\" " << "imageHeight=\"" << rect_height_ << "\">\n"; std::size_t ro_id = std::hash<std::string>{}(GetInputName()); reading_order_str << "\t\t<ReadingOrder>\n" << "\t\t\t<OrderedGroup id=\"ro" << ro_id << "\" caption=\"Regions reading order\">\n"; ResultIterator *res_it = GetIterator(); while (!res_it->Empty(RIL_BLOCK)) { if (res_it->Empty(RIL_WORD)) { res_it->Next(RIL_WORD); continue; } auto block_type = res_it->BlockType(); switch (block_type) { case PT_FLOWING_IMAGE: case PT_HEADING_IMAGE: case PT_PULLOUT_IMAGE: { // Handle all kinds of images. page_str << "\t\t<GraphicRegion id=\"r" << rcnt++ << "\">\n"; page_str << "\t\t\t"; AddBoxToPAGE(res_it, RIL_BLOCK, page_str); page_str << "\t\t</GraphicRegion>\n"; res_it->Next(RIL_BLOCK); continue; } case PT_HORZ_LINE: case PT_VERT_LINE: // Handle horizontal and vertical lines. page_str << "\t\t<SeparatorRegion id=\"r" << rcnt++ << "\">\n"; page_str << "\t\t\t"; AddBoxToPAGE(res_it, RIL_BLOCK, page_str); page_str << "\t\t</SeparatorRegion>\n"; res_it->Next(RIL_BLOCK); continue; case PT_NOISE: tprintf("TODO: Please report image which triggers the noise case.\n"); ASSERT_HOST(false); default: break; } float block_conf = 0; if (res_it->IsAtBeginningOf(RIL_BLOCK)) { // Add Block to reading order reading_order_str << "\t\t\t\t<RegionRefIndexed " << "index=\"" << rcnt << "\" " << "regionRef=\"r" << rcnt << "\"/>\n"; float deskew_angle; res_it->Orientation(&orientation_block, &writing_direction_block, &textline_order_block, &deskew_angle); block_conf = ((res_it->Confidence(RIL_BLOCK)) / 100.); page_str << "\t\t<TextRegion id=\"r" << rcnt << "\" " << "custom=\"" << "readingOrder {index:" << rcnt << ";} "; if (writing_direction_block != WRITING_DIRECTION_LEFT_TO_RIGHT) { page_str << "readingDirection {" << WritingDirectionToStr(writing_direction_block) << ";} "; } page_str << "orientation {" << orientation_block << ";}\">\n"; page_str << "\t\t\t"; if ((!POLYGONFLAG || (orientation_block != ORIENTATION_PAGE_UP && orientation_block != ORIENTATION_PAGE_DOWN)) && LEVELFLAG == 0) { AddBoxToPAGE(res_it, RIL_BLOCK, page_str); } } // Writing direction changes at a per-word granularity // tesseract::WritingDirection writing_direction_before; auto writing_direction = writing_direction_block; if (writing_direction_block != WRITING_DIRECTION_TOP_TO_BOTTOM) { switch (res_it->WordDirection()) { case DIR_LEFT_TO_RIGHT: writing_direction = WRITING_DIRECTION_LEFT_TO_RIGHT; break; case DIR_RIGHT_TO_LEFT: writing_direction = WRITING_DIRECTION_RIGHT_TO_LEFT; break; default: break; } } bool ttb_flag = (writing_direction == WRITING_DIRECTION_TOP_TO_BOTTOM); // TODO: Rework polygon handling if line is skewed (90 or 180 degress), // for now using LinePts bool skewed_flag = (orientation_block != ORIENTATION_PAGE_UP && orientation_block != ORIENTATION_PAGE_DOWN); float line_conf = 0; if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { // writing_direction_before = writing_direction; line_conf = ((res_it->Confidence(RIL_TEXTLINE)) / 100.); std::string textline = res_it->GetUTF8Text(RIL_TEXTLINE); if (textline.back() == '\n') { textline.erase(textline.length() - 1); } line_content << HOcrEscape(textline.c_str()); line_str << "\t\t\t<TextLine id=\"r" << rcnt << "l" << lcnt << "\" "; if (writing_direction != WRITING_DIRECTION_LEFT_TO_RIGHT && writing_direction != writing_direction_block) { line_str << "readingDirection=\"" << WritingDirectionToStr(writing_direction) << "\" "; } line_str << "custom=\"" << "readingOrder {index:" << lcnt << ";}\">\n"; // If level is linebased, get the line polygon and baseline if (LEVELFLAG == 0 && (!POLYGONFLAG || skewed_flag)) { AddPointToWordPolygon(res_it, RIL_TEXTLINE, line_top_ltr_pts, line_bottom_ltr_pts, writing_direction); AddBaselineToPTA(res_it, RIL_TEXTLINE, line_baseline_pts); if (ttb_flag) { line_baseline_pts = TransposePolygonline(line_baseline_pts); } } } // Get information if word is last in line and if its last in the region bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD); bool last_word_in_cblock = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD); float word_conf = ((res_it->Confidence(RIL_WORD)) / 100.); // Create word stream if word level output is active if (LEVELFLAG > 0) { word_str << "\t\t\t\t<Word id=\"r" << rcnt << "l" << lcnt << "w" << wcnt << "\" readingDirection=\"" << WritingDirectionToStr(writing_direction) << "\" " << "custom=\"" << "readingOrder {index:" << wcnt << ";}\">\n"; if ((!POLYGONFLAG || skewed_flag) || ttb_flag) { AddPointToWordPolygon(res_it, RIL_WORD, word_top_pts, word_bottom_pts, writing_direction); } } if (POLYGONFLAG && !skewed_flag && ttb_flag && LEVELFLAG == 0) { AddPointToWordPolygon(res_it, RIL_WORD, word_top_pts, word_bottom_pts, writing_direction); } // Get the word baseline information AddBaselineToPTA(res_it, RIL_WORD, word_baseline_pts); // Get the word text content and polygon do { const std::unique_ptr<const char[]> grapheme( res_it->GetUTF8Text(RIL_SYMBOL)); if (grapheme && grapheme[0] != 0) { word_content << HOcrEscape(grapheme.get()).c_str(); if (POLYGONFLAG && !skewed_flag && !ttb_flag) { AddPointToWordPolygon(res_it, RIL_SYMBOL, word_top_pts, word_bottom_pts, writing_direction); } } res_it->Next(RIL_SYMBOL); } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD)); if (LEVELFLAG > 0 || (POLYGONFLAG && !skewed_flag)) { // Sort wordpolygons word_top_pts = RecalcPolygonline(word_top_pts, 1 - ttb_flag); word_bottom_pts = RecalcPolygonline(word_bottom_pts, 0 + ttb_flag); // AppendLinePolygon AppendLinePolygon(line_top_ltr_pts, line_top_rtl_pts, word_top_pts, writing_direction); AppendLinePolygon(line_bottom_ltr_pts, line_bottom_rtl_pts, word_bottom_pts, writing_direction); // Word level polygon word_bottom_pts = ReversePolygonline(word_bottom_pts, 1); ptaJoin(word_top_pts, word_bottom_pts, 0, -1); } // Reverse the word baseline direction for rtl if (writing_direction == WRITING_DIRECTION_RIGHT_TO_LEFT) { word_baseline_pts = ReversePolygonline(word_baseline_pts, 1); } // Write word information to the output if (LEVELFLAG > 0) { word_str << "\t\t\t\t\t"; if (ttb_flag) { word_top_pts = TransposePolygonline(word_top_pts); } AddPointsToPAGE(word_top_pts, word_str); word_str << "\t\t\t\t\t"; AddBaselinePtsToPAGE(word_baseline_pts, word_str); word_str << "\t\t\t\t\t<TextEquiv index=\"1\" conf=\"" << std::setprecision(4) << word_conf << "\">\n" << "\t\t\t\t\t\t<Unicode>" << word_content.str() << "</Unicode>\n" << "\t\t\t\t\t</TextEquiv>\n" << "\t\t\t\t</Word>\n"; } if (LEVELFLAG > 0 || (POLYGONFLAG && !skewed_flag)) { // Add wordbaseline to linebaseline if (ttb_flag) { word_baseline_pts = TransposePolygonline(word_baseline_pts); } ptaJoin(line_baseline_pts, word_baseline_pts, 0, -1); } word_baseline_pts = DestroyAndCreatePta(word_baseline_pts); // Reset word pts arrays word_top_pts = DestroyAndCreatePta(word_top_pts); word_bottom_pts = DestroyAndCreatePta(word_bottom_pts); // Check why this combination of words is not working as expected! // Write the word contents to the line #if 0 if (!last_word_in_line && writing_direction_before != writing_direction && writing_direction < 2 && writing_direction_before < 2 && res_it->WordDirection()) { if (writing_direction_before == WRITING_DIRECTION_LEFT_TO_RIGHT) { // line_content << "‏" << word_content.str(); } else { // line_content << "‎" << word_content.str(); } } else { // line_content << word_content.str(); } // Check if WordIsNeutral if (res_it->WordDirection()) { writing_direction_before = writing_direction; } #endif word_content.str(""); wcnt++; // Write line information to the output if (last_word_in_line) { // Combine ltr and rtl lines if (ptaGetCount(line_top_rtl_pts) != 0) { ptaJoin(line_top_ltr_pts, line_top_rtl_pts, 0, -1); line_top_rtl_pts = DestroyAndCreatePta(line_top_rtl_pts); } if (ptaGetCount(line_bottom_rtl_pts) != 0) { ptaJoin(line_bottom_ltr_pts, line_bottom_rtl_pts, 0, -1); line_bottom_rtl_pts = DestroyAndCreatePta(line_bottom_rtl_pts); } if ((POLYGONFLAG && !skewed_flag) || LEVELFLAG > 0) { // Recalc Polygonlines line_top_ltr_pts = RecalcPolygonline(line_top_ltr_pts, 1 - ttb_flag); line_bottom_ltr_pts = RecalcPolygonline(line_bottom_ltr_pts, 0 + ttb_flag); // Smooth the polygonline SimplifyLinePolygon(line_top_ltr_pts, 5, 1 - ttb_flag); SimplifyLinePolygon(line_bottom_ltr_pts, 5, 0 + ttb_flag); // Fit linepolygon matching the baselinepoints line_baseline_pts = SortBaseline(line_baseline_pts, writing_direction); // Fitting baseline into polygon is currently deactivated // it tends to push the baseline directly under superscritpts // but the baseline is always inside the polygon maybe it will be useful // for something line_baseline_pts = // FitBaselineIntoLinePolygon(line_bottom_ltr_pts, line_baseline_pts, // writing_direction); and it only cut it to the length and simplifies // the linepolyon line_baseline_pts = ClipAndSimplifyBaseline( line_bottom_ltr_pts, line_baseline_pts, writing_direction); // Update polygon of the block UpdateBlockPoints(block_top_pts, block_bottom_pts, line_top_ltr_pts, line_bottom_ltr_pts, lcnt, last_word_in_cblock); } // Line level polygon line_bottom_ltr_pts = ReversePolygonline(line_bottom_ltr_pts, 1); ptaJoin(line_top_ltr_pts, line_bottom_ltr_pts, 0, -1); line_bottom_ltr_pts = DestroyAndCreatePta(line_bottom_ltr_pts); if (LEVELFLAG > 0 && !(POLYGONFLAG && !skewed_flag)) { line_top_ltr_pts = PolygonToBoxCoords(line_top_ltr_pts); } // Write level points line_str << "\t\t\t\t"; if (ttb_flag) { line_top_ltr_pts = TransposePolygonline(line_top_ltr_pts); } AddPointsToPAGE(line_top_ltr_pts, line_str); line_top_ltr_pts = DestroyAndCreatePta(line_top_ltr_pts); // Write Baseline line_str << "\t\t\t\t"; if (ttb_flag) { line_baseline_pts = TransposePolygonline(line_baseline_pts); } AddBaselinePtsToPAGE(line_baseline_pts, line_str); line_baseline_pts = DestroyAndCreatePta(line_baseline_pts); // Add word information if word level output is active line_str << word_str.str(); word_str.str(""); // Write Line TextEquiv line_str << "\t\t\t\t<TextEquiv index=\"1\" conf=\"" << std::setprecision(4) << line_conf << "\">\n" << "\t\t\t\t\t<Unicode>" << line_content.str() << "</Unicode>\n" << "\t\t\t\t</TextEquiv>\n"; line_str << "\t\t\t</TextLine>\n"; region_content << line_content.str(); line_content.str(""); if (!last_word_in_cblock) { region_content << '\n'; } lcnt++; wcnt = 0; } // Write region information to the output if (last_word_in_cblock) { if ((POLYGONFLAG && !skewed_flag) || LEVELFLAG > 0) { page_str << "<Coords points=\""; block_bottom_pts = ReversePolygonline(block_bottom_pts, 1); ptaJoin(block_top_pts, block_bottom_pts, 0, -1); if (ttb_flag) { block_top_pts = TransposePolygonline(block_top_pts); } ptaGetMinMax(block_top_pts, &x1, &y1, &x2, &y2); page_str << (l_uint32)x1 << "," << (l_uint32)y1; page_str << " " << (l_uint32)x2 << "," << (l_uint32)y1; page_str << " " << (l_uint32)x2 << "," << (l_uint32)y2; page_str << " " << (l_uint32)x1 << "," << (l_uint32)y2; page_str << "\"/>\n"; block_top_pts = DestroyAndCreatePta(block_top_pts); block_bottom_pts = DestroyAndCreatePta(block_bottom_pts); } page_str << line_str.str(); line_str.str(""); page_str << "\t\t\t<TextEquiv index=\"1\" conf=\"" << std::setprecision(4) << block_conf << "\">\n" << "\t\t\t\t<Unicode>" << region_content.str() << "</Unicode>\n" << "\t\t\t</TextEquiv>\n"; page_str << "\t\t</TextRegion>\n"; region_content.str(""); rcnt++; lcnt = 0; } } // Destroy all point information ptaDestroy(&block_top_pts); ptaDestroy(&block_bottom_pts); ptaDestroy(&line_top_ltr_pts); ptaDestroy(&line_bottom_ltr_pts); ptaDestroy(&line_top_rtl_pts); ptaDestroy(&line_bottom_rtl_pts); ptaDestroy(&word_top_pts); ptaDestroy(&word_bottom_pts); ptaDestroy(&word_baseline_pts); ptaDestroy(&line_baseline_rtl_pts); ptaDestroy(&line_baseline_ltr_pts); ptaDestroy(&line_baseline_pts); reading_order_str << "\t\t\t</OrderedGroup>\n" << "\t\t</ReadingOrder>\n"; reading_order_str << page_str.str(); page_str.str(""); const std::string &text = reading_order_str.str(); reading_order_str.str(""); delete res_it; return copy_string(text); } } // namespace tesseract
2301_81045437/tesseract
src/api/pagerenderer.cpp
C++
apache-2.0
37,803