An accounting document automatic generation method based on template matching

CN122987882APending Publication Date: 2026-10-27HUNAN INST OF INFORMATION TECH
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611167850.X
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-03
Publication Date
2026-10-27

AI Technical Summary

Technical Problem

然而,现有人工智能应用在会计凭证生成中仍面临数据异构、字段缺失、模板微差异等问题,难以在多行业、多账套、多格式场景下保证生成凭证的准确性和合规性

Benefits of technology

[0048]1、本发明提供的一种基于模板匹配的会计凭证自动生成方法,采用结构特征与语义特征融合的多阶段匹配机制,通过字段结构向量构建、语义相似度建模以及Sinkhorn距离算法进行正则化传输优化,实现了对原始单据与标准凭证模板之间的高精度匹配。该方法有效解决了传统规则匹配方式在字段位置偏移、命名不一致及非标准格式场景下匹配失败或误判的问题,显著提高了凭证生成过程中的准确性与稳定性,具备较强的容错能力和泛化能力。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122987882A_ABST
    Figure CN122987882A_ABST
Patent Text Reader

Abstract

The application discloses an accounting document automatic generation method based on template matching and concretely relates to the technical field of accounting automation; standard accounting document template is collected and field structure features are extracted; original document images are preprocessed and subjected to optical character recognition, and a preliminary field set is constructed; a matching score is calculated based on structural similarity and semantic similarity, and candidate templates are screened; a Sinkhorn distance algorithm is used to perform regularized transmission calculation on field residuals, and an optimal matching template is selected; a preliminary accounting document structure is generated according to a field mapping rule, and logical checking and compliance correction are performed through a business rule expression, and finally, an accounting document meeting accounting requirements is output; the method improves the accuracy, automation degree and system compatibility of document generation and is suitable for intelligent accounting processing in a multi-source document and multi-template scenario.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of accounting automation technology, specifically to a method for automatically generating accounting vouchers based on template matching. Background Technology

[0002] Accounting vouchers are the basic accounting documents used to record economic transactions in a company's daily financial activities. They are important bases for financial accounting, auditing, and financial analysis. Traditional accounting voucher generation mainly relies on manual filling or semi-automatic filling modes based on rule engines. These methods generally suffer from problems such as cumbersome operation, accuracy depending on personnel experience, and poor adaptability to different business scenarios. Especially in small and medium-sized enterprises and financial systems with multiple sets of accounts and multiple industries, existing systems often cannot accurately match templates when faced with non-standardized original document styles, resulting in high voucher generation error rates, frequent manual intervention, and a heavy workload for financial personnel.

[0003] Some intelligent financial systems have attempted to introduce automatic data entry strategies based on OCR recognition and business rules. However, these methods still rely on fixed field positions and preset business logic, making it difficult to adapt to multi-source heterogeneous data and original documents with inconsistent formats. Especially when there are documents of the same business type but with slightly different templates (such as different date positions or inconsistent summary field naming), the system cannot accurately determine the template to which it belongs, leading to matching failures or the generation of incorrect vouchers, which in turn affects the accuracy of subsequent accounting processing and reports.

[0004] In recent years, with the development of artificial intelligence (AI) technology, especially the widespread application of deep learning, natural language processing, and image recognition technologies, new solutions have been provided for the intelligent generation of accounting vouchers. AI-based OCR technology can perform high-precision text recognition on complex and non-standardized documents; natural language processing technology can semantically understand field naming and summary information; and deep learning models can automatically learn the structure and features of document templates through training, achieving adaptive matching across templates and formats. However, existing AI applications in accounting voucher generation still face problems such as data heterogeneity, missing fields, and minor template differences, making it difficult to guarantee the accuracy and compliance of generated vouchers in multi-industry, multi-account, and multi-format scenarios. Summary of the Invention

[0005] The purpose of this invention is to provide a method for automatically generating accounting vouchers based on template matching, so as to overcome the shortcomings of the prior art.

[0006] To achieve the above objectives, the present invention provides the following technical solution: a method for automatically generating accounting vouchers based on template matching, comprising:

[0007] S100: Collect multiple standard accounting document templates from the preset template library and extract the structured field feature set T1 from each template; where T1 includes field position, field name and field relative hierarchy;

[0008] S200: Collect images of the original accounting documents to be processed, use OCR to recognize them and construct their preliminary field set T2;

[0009] S300: Based on the structural similarity between T2 and each T1 in the template library, the similarity weight is calculated by combining the semantic matching algorithm to establish a matching candidate set M;

[0010] S400, further perform feature residual analysis on each candidate template in M, extract the field position offset matrix ΔP and the naming semantic similarity matrix ΔS, and calculate the weighted matching score W;

[0011] S500: Select the candidate template T* with the highest matching score from the weighted matching scores W, and use it as the matching template for the current original document.

[0012] S600, based on the field mapping rules in the candidate template T*, map the field content in the original document to the accounting voucher template to generate the preliminary accounting voucher structure V0;

[0013] S700 calls the business rules engine to perform logical verification and compliance correction on the key fields in V0, and obtains the final accounting voucher V;

[0014] S800, output the accounting voucher V and store it in the accounting system.

[0015] Preferably, the step of using OCR to identify and construct its initial field set T2 includes:

[0016] Obtain image data from the original accounting documents and perform image preprocessing on them;

[0017] A deep learning-based optical character recognition model is used to perform text recognition on the preprocessed document image, and an initial dataset containing field text and its position in the image is extracted.

[0018] The initial dataset is subjected to layout analysis, and candidate regions for fields are constructed based on the relative positional relationships of text blocks and the layout structure.

[0019] Based on the text content of the candidate field region, semantic matching is performed with the preset key field dictionary to identify the corresponding structured fields and form a preliminary field set T2.

[0020] Preferably, the step of calculating similarity weights using a semantic matching algorithm and establishing a matching candidate set M includes:

[0021] For each field in the initial field set T2 and each template field set T1, a field structure vector is constructed. The field structure vector includes the field's position coordinates in the image, the field length, and the relative distance between adjacent fields.

[0022] Normalized Euclidean distance is used to calculate the field-level structural similarity between T2 and the structural vectors in each T1, and the structural similarity score is obtained.

[0023] The naming of fields in T2 and T1 is semantically encoded using a word vector model, and the semantic similarity score is obtained by calculating the cosine similarity between word vectors.

[0024] The overall matching score is calculated based on the weighted result of structural similarity and semantic similarity, and templates with scores higher than a set threshold are added to the matching candidate set M.

[0025] Preferably, the step of further performing feature residual analysis on each candidate template in M ​​includes:

[0026] Based on the field position coordinates of the initial field set T2 and the candidate template field set T1, construct the field position offset matrix ΔP;

[0027] Based on the field names of the initial field set T2 and the candidate template field set T1, a pre-trained word vector model is used for semantic encoding, and a naming semantic similarity matrix ΔS is constructed. The similarity matrix records the cosine similarity score between the field names.

[0028] Using ΔP and ΔS as inputs for positional and semantic distributions respectively, a cost matrix for field matching is constructed. The Sinkhorn distance algorithm is then used to perform regularized optimal transmission calculation on the cost matrix to obtain the weighted matching score W for each candidate template.

[0029] Preferably, the step of calculating the weighted matching score W includes:

[0030] The field position offset matrix ΔP and the naming semantic similarity matrix ΔS are weighted and merged according to a preset ratio to generate a unified field matching cost matrix C. The ratio is set according to the degree of influence of position and semantic features on matching accuracy.

[0031] Construct normalized weight distribution vectors for field set T2 and template field set T1 respectively;

[0032] Using the field matching cost matrix C and the field weight distribution as input, the Sinkhorn optimal transmission algorithm is used for regularized iterative calculation to obtain the optimal transmission scheme between the two field sets.

[0033] The weighted matching score W of the candidate template is calculated based on the sum of the products of the field matching probability and the corresponding cost value in the optimal transmission scheme.

[0034] Preferably, the step of generating the preliminary accounting voucher structure V0 includes:

[0035] Invoke the preset field mapping rules in the matching template T*. The field mapping rules define the correspondence between the original fields and the voucher fields, including the field naming correspondence table, field type conversion rules and default value settings;

[0036] Based on the field naming correspondence, extract the field content corresponding to the voucher fields from the preliminary field set T2;

[0037] The converted field content is filled into the preset field positions of the accounting voucher template to construct the preliminary accounting voucher structure V0, and the mapping source and conversion status are marked.

[0038] Preferably, the step of calling the business rule engine to perform logical validation and compliance correction on the key fields in V0 includes:

[0039] Load a preset set of business rules, which includes rules for field value ranges, rules for logical relationships between fields, and rules for account compliance, all defined in the form of rule expressions;

[0040] Perform rule-based validation on each key field in the initial accounting voucher structure V0. If a field value is outside the defined range or there is a logical conflict between fields, mark it as a validation failure and record the exception type.

[0041] For fields that fail validation, the content is automatically replaced, completed, or the format is adjusted according to the correction strategy set in the corresponding rule;

[0042] Reorganize the set of fields that have passed verification or been corrected into a final accounting document V that is structurally complete and conforms to business rules.

[0043] Preferably, the steps of performing rule validation on each key field in the preliminary accounting voucher structure V0 include:

[0044] Identify a pre-defined set of key fields from the initial accounting document structure V0;

[0045] For each key field, the corresponding rule validation expression is called according to the field type to validate the field value range, data format and logical consistency between fields, and generate field validation results;

[0046] When a field validation result is detected as not meeting the rule constraints, the corresponding violation type and field identifier are recorded, and the field is marked as pending correction.

[0047] The technical effects and advantages provided by the present invention in the above technical solution are as follows:

[0048] 1. This invention provides an automatic accounting voucher generation method based on template matching. It employs a multi-stage matching mechanism that fuses structural and semantic features. Through field structure vector construction, semantic similarity modeling, and regularization optimization using the Sinkhorn distance algorithm, it achieves high-precision matching between original documents and standard voucher templates. This method effectively solves the problems of matching failure or misjudgment in traditional rule-based matching methods under scenarios of field position offset, inconsistent naming, and non-standard formats. It significantly improves the accuracy and stability of the voucher generation process and possesses strong fault tolerance and generalization capabilities.

[0049] 2. This invention also introduces structured field mapping rules, a rule-expression-driven business logic validation engine, and an automatic correction strategy mechanism to ensure that the generated accounting vouchers are not only structurally complete but also comply with accounting standards and industry standards in terms of business operations. This method supports multi-source document formats, cross-industry templates, personalized rule configuration, and interface output, possessing excellent system integration and scalability. It is suitable for high-concurrency, low-fault-tolerance requirements in enterprise financial automation scenarios and has broad engineering application prospects. Attached Figure Description

[0050] To more clearly illustrate the technical solutions in the embodiments of this application or the prior art, the drawings used in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments recorded in this invention. For those skilled in the art, other drawings can be obtained based on these drawings.

[0051] Figure 1 This is a flowchart of the method of the present invention. Detailed Implementation

[0052] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0053] For examples, please refer to Figure 1 As shown in this embodiment, an automatic accounting voucher generation method based on template matching includes:

[0054] S100: Collect multiple standard accounting document templates from the preset template library and extract the structured field feature set T1 from each template; where T1 includes field position, field name and field relative hierarchy.

[0055] In this invention, the core of step S100 lies in performing structured modeling of standard accounting document templates to provide accurate template feature basis for the subsequent matching process.

[0056] Specifically, the system first collects and builds a preset template library, which contains multiple representative standard accounting document templates. These templates can be derived from different industries, different financial systems, or historically archived verified documents, and are characterized by clear structure and complete fields, covering accounting voucher scenarios for most common business types.

[0057] For each standard accounting document template, the system performs structured parsing of its content, extracts its key field information, and constructs a corresponding structured field feature set T1. This set includes the following three types of features:

[0058] Field location features: These refer to the two-dimensional spatial coordinates of each field within the document, including the coordinates of the top-left corner, width and height dimensions, and row and column position indexes. This feature is used to characterize the visual layout structure of the fields, facilitating position alignment and offset analysis with fields in the original document.

[0059] Field naming features: These are semantic tags for fields, such as "Amount," "Date," "Summary," and "Customer Name." These features can be generated based on field title text or contextual semantic annotations and are used for subsequent semantic matching and fuzzy judgment. Field naming supports multilingual recognition of Chinese, English, and common financial terms.

[0060] Field relative hierarchy features: These refer to the nesting or hierarchical relationships between fields in the logical structure. For example, a "fee category" field may contain subfields such as "transportation expenses" or "travel expenses," or certain fields may belong to a parallel structure within the same table area. This feature helps to construct semantic dependency graphs and mapping constraints among fields, improving the accuracy of complex template matching.

[0061] Through the feature extraction process described above, the system transforms each standard template into a structured template description model, forming a structured field feature set T1={t1,t2,...,tn}, where each ti represents a triplet feature (position, name, level) of a field. This set, as a digital representation of the template, is stored in the template feature library for use in subsequent matching and recognition stages.

[0062] It is worth noting that template feature extraction can be completed automatically by combining manual annotation with machine learning model training. For scenarios with a sufficient number of historical documents, batch template modeling can be achieved through clustering and field recognition models, which greatly improves the efficiency of database construction.

[0063] S200: Collect images of the original accounting documents to be processed, and use OCR to recognize and construct its preliminary field set T2.

[0064] In this invention, step S200 is used to convert the original accounting document image to be processed into a structured field set T2, providing basic data support for the subsequent template matching process.

[0065] First, acquire color images of the original accounting documents using image acquisition equipment. The image format should be JPEG or PNG, with a resolution of at least 300 DPI to ensure clarity for subsequent text recognition. After acquisition, perform standardized preprocessing on the images, mainly including the following steps:

[0066] Grayscale processing: Convert the color image into a single-channel grayscale image to remove color interference. The pixel grayscale value is calculated using a weighted average method, which is to multiply the red, green and blue channel values ​​by 0.299, 0.587 and 0.114 respectively and then sum them.

[0067] Image denoising: Median filtering algorithm is used to filter out salt-and-pepper noise in the image to avoid misidentification of characters;

[0068] Image enhancement: Histogram equalization algorithm is applied to enhance the local contrast of the image, making the text area more prominent and improving the accuracy of subsequent recognition;

[0069] Tilt Correction: The tilt angle of the main text lines in the image is detected by Hough transform, and then corrected by affine transformation to ensure that the text is horizontally aligned.

[0070] The above preprocessing steps can significantly improve image quality and provide more ideal input conditions for character recognition.

[0071] After image preprocessing, optical character recognition (OCR) technology is used to identify text regions in the image. This invention selects a deep learning model (CRNN) based on a combination of convolutional neural networks and recurrent neural networks as the core model for character recognition. This model includes three stages:

[0072] Feature extraction stage: Convolutional neural networks (CNNs) are used to perform multi-layer convolution operations on the image to extract the spatial features of the character image;

[0073] Sequence modeling stage: The extracted two-dimensional feature maps are converted into one-dimensional sequence inputs, which are then input into a bidirectional long short-term memory network (Bi-LSTM) to model the contextual relationships between characters;

[0074] Output prediction stage: The character sequence is aligned and decoded using the Connectionist Temporal Classification (CTC) algorithm, and the final text recognition result is output.

[0075] During the recognition process, the model returns the following data fields for each detected text region: text content, the position coordinates of the text in the image (represented by the x and y coordinates of the top-left corner and width and height), and recognition confidence (a floating-point number with a value between 0 and 1). All recognition fields are combined to form the initial field dataset, which serves as the input for the next step of layout analysis.

[0076] After obtaining the initial field dataset, the original image is analyzed for layout structure by combining the text location coordinates from the recognition results. This process employs a density-based clustering-based region partitioning algorithm, and the specific steps are as follows:

[0077] Field clustering: All identified fields are clustered according to the horizontal or vertical coordinate spacing. The DBSCAN (Density-Based Spatial Clustering of Applications with Noise) algorithm is selected. The horizontal distance threshold ε is set to 1.5% of the image width, and the minimum number of neighboring samples is set to 3 to form field rows or columns with structural consistency.

[0078] Text block association: Within each cluster region, calculate the relative arrangement order and hierarchical relationship of text blocks to identify header fields, data fields, and memo fields;

[0079] Construct candidate regions: Based on the clustering results and structural features, generate candidate field regions for each region, and record its location information, number of fields contained, field arrangement features, and average distance between adjacent fields.

[0080] The candidate regions for fields generated in this step have clear spatial layout and structural characteristics, providing contextual information support for field semantic matching.

[0081] After identifying candidate regions for fields, semantic matching is performed on the field content within each region with a preset key field dictionary to determine its corresponding structured field label.

[0082] The key field dictionary is generated through manual annotation and automatic expansion using machine learning, and includes standard names, synonyms, and contextual keywords for common accounting fields. For example, the "amount" field includes multiple variant entries such as "amount," "payment amount," and "receipt amount."

[0083] The semantic matching process includes the following steps:

[0084] Similarity calculation: The Word2Vec word vector model is used to encode the field content and dictionary entries, and the target field with the closest semantics is determined by calculating the cosine similarity.

[0085] Threshold judgment: Set the similarity threshold to 0.85. If the similarity between the current field and any word in the dictionary is greater than the threshold, it is judged as a valid match.

[0086] Field labeling: Bind the successfully matched fields to the corresponding structured tags, record their position, text content and named tags to form a structured field object;

[0087] Field set construction: All annotated field sets are uniformly constructed into a preliminary field set T2, which serves as the basis for comparison with the standard template field set T1 in the subsequent template matching steps.

[0088] Through the above field recognition and semantic annotation process, the unstructured text information in the original image is transformed into a set of fields T2 with structural, positional and semantic attributes, providing a high-quality source of input data for template matching in this invention.

[0089] To verify the effectiveness of the accounting document image structuring processing method described in this invention, the field extraction performance of existing methods based on traditional OCR rule engines and the method of this invention on the same batch of real document samples was compared. The experiment was set up as follows:

[0090] Experimental data include:

[0091] Test sample size: 1000 scanned images of real accounting documents from different industries;

[0092] Document types covered: receipts, payment notices, invoices, and internal expense reports;

[0093] Image resolution: uniformly adjusted to 300 DPI;

[0094] Evaluation metrics: Field recognition accuracy: the percentage of correctly labeled fields out of the number of recognized fields; Field recall: the percentage of successfully recognized fields out of the number of real fields; Average field location error: the average pixel offset between the center point position of the field and the manually labeled result.

[0095] Image preprocessing: The median filter window size is set to 3×3, and the Hough transform angle resolution is 1°;

[0096] OCR model: CRNN structure implemented in PyTorch, with a pre-trained character set including commonly used accounting terms in Chinese and English;

[0097] Clustering algorithm: DBSCAN threshold ε is set to 1.5% of the image width, and the minimum number of samples is 3;

[0098] Semantic matching model: using Word2Vec word vectors, with a dictionary capacity of 285 standard accounting fields and their variants.

[0099] The experimental results are as follows:

[0100] Identification method Field recognition accuracy Field Recall Average field positioning error (pixels) Traditional OCR + rule matching 81.2% 76.5% 17.4 The method of this invention (CRNN + clustering + semantic matching) 93.7% 90.1% 6.3

[0101] Comparative analysis:

[0102] In terms of field recognition accuracy, the method of this invention improves by about 15.4% compared with the traditional rule-based method, greatly reducing the need for manual proofreading;

[0103] In terms of field recall, the method of clustering to identify text region structure improved the recognition coverage of non-standard fields by approximately 13.6%.

[0104] The average field positioning error was reduced by 64%, proving that layout analysis and spatial relationship modeling greatly enhanced the ability to accurately locate field boundaries;

[0105] For documents with format offsets or inconsistent field naming, the semantic matching mechanism in this invention exhibits stronger fault tolerance and generalization ability.

[0106] In this embodiment, the present invention combines image preprocessing, deep learning OCR recognition, spatial clustering structure analysis, and semantic matching techniques to achieve high-precision extraction of structured fields from original accounting document images. Compared with existing traditional methods based on fixed rules or template positions, the present invention significantly improves accuracy, recall, and field location precision. It is particularly suitable for handling real-world scenarios with non-standard formats, inconsistent field descriptions, or image interference, greatly enhancing the intelligence and adaptability of the automatic voucher generation system.

[0107] S300: Based on the structural similarity between T2 and each T1 in the template library, the similarity weight is calculated by combining the semantic matching algorithm to establish a matching candidate set M.

[0108] In this invention, step S300 is used to establish candidate matching relationships between the initial field set T2 and each template field set T1 in the template library, so as to narrow down the template range for subsequent fine matching. This step includes the following specific processes:

[0109] After obtaining the initial field set T2 and the template field sets T1 in the template library, a field structure vector is constructed for each field in both sets. The field structure vector describes the spatial layout characteristics of the field in the document, and its components include:

[0110] The field's position coordinates in the image are represented by the horizontal and vertical coordinates of the top-left corner of the field's bounding box;

[0111] Field length is defined as the pixel width of the field bounding box in the horizontal direction;

[0112] The relative distance between adjacent fields is defined as the distance between the center point of the current field and its nearest neighbor field in the vertical direction.

[0113] By using the three dimensions mentioned above, each field is mapped to a multi-dimensional numerical vector, thus enabling the layout structure information of the field to be quantitatively expressed in numerical form. After construction, the initial field set T2 and each template field set T1 are represented as corresponding field structure vector sets.

[0114] After constructing the field structure vectors, field-level structural similarity is calculated between the initial field set T2 and the template field set T1. Specifically, for each field structure vector in T2, the normalized Euclidean distance is calculated with the field structure vector of the corresponding semantic category in T1.

[0115] The normalized Euclidean distance is calculated as follows: First, the numerical differences between the two field structure vectors in each dimension are calculated, and the square root is obtained by summing the squares. Then, the distance value is divided by the preset maximum structure distance threshold to eliminate the influence of different document sizes on the distance calculation, so that the distance result is limited to between 0 and 1.

[0116] The structural similarity score is obtained by inversely mapping the normalized distance result; that is, the smaller the distance value, the higher the structural similarity score. After summarizing the structural similarity scores of all matching field pairs, the overall structural similarity score between the preliminary field set T2 and the current template field set T1 is obtained.

[0117] Based on the structural similarity calculation, the semantic similarity of field names in the preliminary field set T2 and the template field set T1 is calculated. The specific implementation is as follows:

[0118] First, a word vector model trained on a large-scale accounting text corpus is used to vectorize the field-named text. This word vector model maps field names to a fixed-dimensional real-valued vector space, making semantically similar field names less distant in the vector space.

[0119] Subsequently, the cosine similarity between the field naming vectors in T2 and the field naming vectors in T1 is calculated. Cosine similarity measures the semantic closeness by comparing the angle between two vectors, and its value ranges from 0 to 1, with a larger value indicating a stronger semantic relevance.

[0120] By statistically analyzing and summarizing the cosine similarity of all matching field naming pairs, the semantic similarity score between the initial field set T2 and the corresponding template field set T1 is obtained.

[0121] After obtaining the structural similarity score and semantic similarity score, the two are weighted and fused to calculate the overall matching score between the initial field set T2 and each template field set T1. In the weighting method, structural similarity and semantic similarity are each assigned a preset weight value, and the sum of the weights is 1, which is used to balance the influence of field spatial layout consistency and field semantic consistency in template matching.

[0122] Subsequently, the overall matching score is compared with a preset matching threshold, which is set based on historical template matching experiment results and is used to distinguish between acceptable and unacceptable matching templates. When the overall matching score corresponding to a certain template field set T1 is greater than the matching threshold, the template is determined to be a candidate matching template and added to the candidate matching set M.

[0123] Through the above process, the original template library is filtered into a limited set of matching candidates M with a high degree of matching, providing an input basis for the subsequent template selection steps based on field residuals and fine scoring.

[0124] S400, further feature residual analysis is performed on each candidate template in M ​​to extract the field position offset matrix ΔP and the naming semantic similarity matrix ΔS, and the weighted matching score W is calculated.

[0125] In this invention, to further improve the accuracy of candidate template matching, after the initial screening of the candidate matching set M, structural and semantic residual analysis is performed on each candidate template, and the accurate weighted matching score W is calculated. This process includes steps such as constructing the field position offset matrix ΔP and the named semantic similarity matrix ΔS, cost matrix synthesis, Sinkhorn regularized optimal transmission calculation, and score solving, specifically implemented as follows:

[0126] For the alignable fields in the initial field set T2 and the candidate template field set T1, their two-dimensional position coordinates are extracted, and a field position offset matrix ΔP is constructed. Each element ΔP(i,j) of this matrix represents the normalized position offset of the i-th field in T2 and the j-th field in T1 in the image.

[0127] The specific calculation method is as follows:

[0128] First, obtain the coordinates of the center point of the field bounding box;

[0129] Then calculate the pixel distance between the two center points in the horizontal and vertical directions respectively;

[0130] Finally, divide the distance by the image width and height, normalize them respectively, and take the square root of the sum of their squares as the value of ΔP(i,j).

[0131] This matrix comprehensively reflects the degree of difference between T2 and T1 in terms of page layout structure.

[0132] To measure the semantic similarity of field names, semantic encoding was performed on the naming text of all fields in T2 and T1. The word vector model used was a Word2Vec model trained based on the Skip-Gram structure, with a word vector dimension of 300. The training corpus was derived from an industry accounting voucher corpus, covering common field names and their semantic variations.

[0133] After generating word vectors for each field, the semantic similarity between any pair of field names is calculated, using cosine similarity as the metric. Each element ΔS(i,j) of the semantic similarity matrix ΔS is calculated as follows:

[0134] Normalize the word vectors of the i-th field and the j-th field respectively;

[0135] Calculate the dot product of the two results and use it as the cosine similarity score.

[0136] The score ranges from 0 to 1, with scores closer to 1 indicating greater semantic similarity.

[0137] The residual matrices of types ΔP and ΔS are weighted and fused according to a preset ratio to construct a unified field matching cost matrix C, which comprehensively reflects the matching deviation between structure and semantics. The weighted fusion formula is as follows: For any position (i,j), the cost is... Where α and β are the weighting coefficients for structure and semantics, satisfying α + β = 1; the weight settings are determined based on actual business needs and field matching sensitivity, with default values ​​of α = 0.6 and β = 0.4. Smaller values ​​in this matrix indicate that the structural positions of the field pairs are closer, and their semantics are more similar.

[0138] To ensure greater global consistency in field matching, weighted distribution vectors are constructed for the fields in T2 and T1, representing the relative importance of each field in the document. These weights can be determined based on field frequency, field length, or OCR recognition confidence.

[0139] In this invention, a uniform field distribution method is adopted, that is, the weight of each field is set to 1 divided by the total number of fields, ensuring that all fields have equal weighted contributions. This also satisfies the regularization requirement of the Sinkhorn algorithm that the sum of rows and columns must be 1.

[0140] Using the field matching cost matrix C and the field weight distribution as input, the Sinkhorn optimal transfer algorithm is executed to obtain the optimal matching relationship between field sets T2 and T1. This algorithm belongs to the regularized optimal transfer method. By introducing an entropy regularization term, it enables traditional linear programming problems to converge quickly to sparse solutions. The calculation steps are as follows:

[0141] The matching matrix is ​​initialized as the outer product of the weight distributions;

[0142] Iteratively update the row and column normalization factors to ensure that the transfer matrix satisfies the marginal conditions;

[0143] The regularization parameter λ (lambda) controls the smoothness of the solution, with a typical value of 0.1;

[0144] The iteration stops when the difference between two update results is less than a set error threshold (e.g., 10 to the power of -4) or when the maximum number of iterations is reached (e.g., 100).

[0145] Finally, a field matching probability matrix T is obtained, where T(i,j) represents the matching probability between the i-th field and the j-th field.

[0146] After obtaining the optimal field transmission scheme, the weighted matching score W of the candidate template is calculated based on the sum of the products of matching cost and matching probability. The specific formula is: W = 1 minus the weighted sum of all T(i,j) × C(i,j). The score W ranges from 0 to 1; the closer the value is to 1, the higher the degree of matching between the template and the current document. Finally, this score serves as the ranking basis for selecting the optimal template in subsequent steps.

[0147] Through the above process, this invention introduces the Sinkhorn regularized optimal transmission algorithm to achieve flexible matching based on structural residuals and semantic residuals. It can not only handle scenarios with inconsistent number of fields, but also significantly reduce misjudgments caused by positional errors and semantic drift, and improve matching accuracy and adaptability. It is particularly suitable for accounting document matching tasks with complex field layouts and non-standard naming.

[0148] In this embodiment, the following experiments are designed to empirically demonstrate the significant advantages of the present invention over traditional matching algorithms in practical applications, specifically including:

[0149] Experimental objective: To verify that the technical solution of this invention, which constructs a field position offset matrix and a naming semantic similarity matrix, and calculates a weighted matching score W based on the Sinkhorn distance, has better accuracy and robustness in candidate template screening than existing template matching methods.

[0150] Experiment setup and test dataset:

[0151] A total of 1,000 real accounting document images from different industries and formats were selected as test samples;

[0152] The types of documents include payment slips, receipts, expense reports, invoices, and other similar documents.

[0153] The corresponding standard template library contains 80 standardized templates.

[0154] Comparison method:

[0155] Method A (Traditional Structure Matching): Matches based solely on Euclidean distance of field positions;

[0156] Method B (Simple Weighted Structural and Semantic Approach): The cost score is calculated based on a weighted average of positional offset and semantic similarity, but the optimal transmission algorithm is not used.

[0157] Method C (the method of this invention): Construct a field offset matrix and a semantic matrix, and obtain the final matching score by regularizing the transmission using the Sinkhorn algorithm.

[0158] Evaluation indicators:

[0159] Top-1 matching accuracy: Whether the highest-scoring template is a true template;

[0160] Top-3 match hit rate: Whether the true template is included in the top three highest-scoring templates;

[0161] Field mismatch rate: The ratio of the number of incorrectly labeled fields to the total number of fields;

[0162] Matching time: The average time (milliseconds) for filtering a single document template.

[0163] Experimental results:

[0164] method Top-1 matching accuracy Top-3 match hit rate Field mismatch rate Average matching time Method A 82.3% 91.0% 11.5% 29ms Method B 88.5% 95.2% 8.2% 35ms Method C (This invention) 95.1% 98.7% 4.3% 41ms

[0165] The results are analyzed as follows:

[0166] The method of this invention improves the Top-1 accuracy by 12.8 percentage points, significantly reducing the template matching error rate; it approaches saturation in the Top-3 hit rate, ensuring that most real templates are in the candidate set; the field mismatch rate is reduced to less than half, and it can still be correctly identified, especially when the field naming is not standardized or the field order changes; the average time consumption is slightly increased, but it is completely acceptable in actual business scenarios (response time requirement <100ms).

[0167] This embodiment fully illustrates that the present invention, by constructing a position offset matrix and a semantic similarity matrix, combined with the Sinkhorn optimal transmission algorithm to perform flexible matching of field sets, effectively solves the problem of low matching accuracy in complex scenarios such as missing fields, rearrangement, and inconsistent naming in traditional methods. Compared with traditional algorithms, it significantly improves the accuracy, robustness, and practical adaptability of template matching, and has good engineering feasibility.

[0168] S500: Select the candidate template T* with the highest matching score from the weighted matching scores W, and use it as the matching template for the current original document.

[0169] In this invention, step S500 is used to select the optimal matching template after completing the residual analysis of the candidate templates and calculating the weighted matching score W of each candidate template, so as to ensure the accuracy and stability of the subsequent voucher generation process.

[0170] Specifically, this step includes the following processes:

[0171] First, based on the matching candidate set M constructed in the previous step, the weighted matching score W is calculated for each candidate template. The score W is the global optimal field alignment score obtained by the Sinkhorn distance algorithm after joint modeling of structural residuals and semantic similarity. Its value range is from 0 to 1. The higher the score, the higher the degree of structural and semantic matching between the template and the current original document.

[0172] Subsequently, all templates in the candidate set M are sorted in descending order according to their weighted matching score W, and the template with the highest score is extracted and denoted as T*, which is used as the optimal matching template for the current original accounting document.

[0173] During the T* selection process, the system can also set a minimum matching score threshold Wmin, typically set to 0.75, to remove mismatched templates with low matching scores but high rankings. When the maximum value of W is less than this threshold, an exception handling process or manual review can be triggered to prevent low-quality templates from entering the voucher generation process.

[0174] Through this step, the final output optimal template T* will serve as the structural basis for subsequent field mapping and accounting voucher construction processes, ensuring that field content can be accurately filled and classified according to standard templates consistent with business scenarios, thereby improving the accuracy of voucher generation and business compliance.

[0175] S600, based on the field mapping rules in the candidate template T*, map the field content in the original document to the accounting voucher template to generate the preliminary accounting voucher structure V0;

[0176] In this invention, step S600 is used to accurately map the contents of the structured field set T2 in the original document to the corresponding accounting voucher field position according to the field mapping rules defined in the template after determining the optimal matching template T*, thereby constructing a preliminary accounting voucher structure V0 and providing a data foundation for subsequent verification and generation steps.

[0177] Once the optimal matching template T* is determined, its internally configured field mapping rules are extracted. These mapping rules define the static and dynamic mapping relationships between fields in the original document and fields in the accounting voucher. The mapping rules consist of the following three parts:

[0178] Field naming mapping table: Used to establish a one-to-one mapping relationship between original field names and voucher field names. For example, the original field "Reimbursement Person" is mapped to the voucher field "Applicant", and the field "Expense Type" is mapped to the voucher field "Summary".

[0179] Field type conversion rules: For data types such as date, amount, and quantity, set standardized format conversion methods, such as uniformly converting date fields to "YYYY-MM-DD" format, and rounding amount fields to two decimal places;

[0180] Default value setting rules: When a corresponding field is missing in the original field set T2, a default value is preset according to the business template. For example, the default setting of "subject code" is "660101" to represent office expenses.

[0181] The mapping rules mentioned above are formulated by business experts and finance personnel during the template creation phase and stored in the form of a structured configuration file, which is invoked together with the template T*.

[0182] After obtaining the field naming correspondence, iterate through each field name in the initial field set T2 and match it with the corresponding accounting voucher field name. The content of the successfully matched field will be extracted as raw data for voucher field population.

[0183] For the extracted field values, perform the following operations according to the field type conversion rules:

[0184] Numeric field processing: For example, for the "amount" field, its Chinese expression (such as "壹仟元整") is converted to Arabic numerals (such as "1000.00"), with two decimal places retained;

[0185] Date field processing: For example, for the "reimbursement date" field, original texts in different formats (such as "December 5, 20xx" or "20xx / 12 / 05") are uniformly converted to "20xx-12-05";

[0186] Text field processing: Perform cleaning operations such as removing leading and trailing spaces and cleaning illegal characters to ensure compliance with the input requirements of voucher fields.

[0187] If no corresponding entry for the field is found in T2, the default value setting rule is invoked to fill the field, and the field is marked as "default filled".

[0188] After completing the extraction and conversion of field contents, they are filled one by one into the accounting voucher structure defined by the matching template T*. This structure includes, but is not limited to, a plurality of field positions such as voucher date, voucher summary, accounting subject, amount, preparer, and number of attached documents.

[0189] During the filling process, the following two pieces of metadata are recorded for each field:

[0190] Mapping source type: including "direct mapping", "default filling", "field merging", "split mapping", etc.;

[0191] Field conversion status: including identifiers such as "conversion successful", "format exception", and "missing substitution", which are used for tracking of subsequent verification logic.

[0192] Finally, the filled field set is assembled into a standard voucher data structure to form a preliminary accounting voucher structure V0, which is temporarily stored in a memory cache or an intermediate database for invocation in subsequent steps of logic verification and voucher confirmation.

[0193] By introducing structured field mapping rules, standardized conversion mechanisms and metadata annotation mechanisms, this step not only ensures the consistency between field contents and the voucher template, but also provides traceability and verifiability, effectively avoiding common problems in traditional automatic voucher generation such as field misalignment, format exceptions and field missing, improving the automation and accuracy of the voucher generation process, and having clear engineering implementability.

[0194] S700: Invoke the business rule engine to perform logic verification and compliance correction on the key fields in V0, so as to obtain the final accounting voucher V.

[0195] In this invention, the rule verification operation in step S700 is used to identify and handle potential field errors, missing fields, or business logic conflicts in the preliminary accounting voucher structure V0. To ensure that the generated final accounting voucher V complies with the requirements of financial regulations and accounting standards in terms of business operations, this step performs item-by-item logical verification and anomaly marking processing on key fields based on a preset rule set, specifically including the following steps:

[0196] After the initial accounting voucher structure V0 is generated, the first step is to extract the set of key fields that require focused verification based on the field importance levels defined in the configuration file. These key fields include, but are not limited to:

[0197] Accounting subject field (used for accounting classification);

[0198] Amount field (used to reflect business value);

[0199] Voucher date field (used to determine the accounting period).

[0200] The key field set is identified through field label comparison and structural indexing, and marked as "needs verification" in the data structure.

[0201] In this invention, the set of business rules is defined in the form of structured rule expressions.

[0202] Each business rule is defined in the form of a structured data record, containing the following fields:

[0203] Field Name illustrate Rule Number Unique rule identifier for easy reference and tracking Rule Name Human-readable rule descriptions, such as "amounts cannot be negative". Functional field The key field names to which this rule applies include, for example, "Amount". Rule Type Indicates the logical category of the rule, such as "value range" or "field relationship". Regular expressions Logical expressions written in an interpretable language Error Type Error code or error description returned when verification fails Correct strategy number If the rule fails, the corresponding correction strategy number will be invoked.

[0204] In this invention, the rule expressions are defined using a DSL (Domain Specific Language) approach, possessing parsability and executableness, and are suitable for business logic validation. The expression syntax includes variable referencing, logical judgments, range definitions, string and numerical operations, etc., with the following basic form:

[0205] Regular expressions: <field variable><comparison operator><judgment value>[logical connector]<other conditions>; Example expressions include: Amount field must be positive: Amount > 0; Voucher date must not be later than the current system date: Voucher date <= current system date; If the debit account is "Accounts Payable", the summary must contain the keyword "Payment": (Debit account == 'Accounts Payable') AND (Summary contains 'Payment'); Field variables in the expression are all bound to the actual field content in V0. Comparison operators include common ones such as ==, !=, >, <, >=, <=, contain, and matching regular expressions; Logical connectors support compound judgments such as AND, OR, and NOT.

[0206] The rule expression is parsed and executed by the business rule execution engine. The execution flow is as follows:

[0207] Load the field contents of the initial accounting voucher structure V0 as context variables;

[0208] Parse the regular expression into an abstract syntax tree or a chain of Boolean expressions;

[0209] The expression evaluation process is executed to obtain a Boolean verification result.

[0210] If the result is False, the current rule number and the field of effect are recorded, an error record is generated, and the correction strategy associated with the rule is activated.

[0211] The expression execution engine supports dynamically adding new rules and supports rule version management to adapt to the different accounting compliance requirements of different enterprises or industries.

[0212] For each field, select the appropriate validation expression based on its type, and perform the following validation operations:

[0213] Field value range validation: Applicable to numeric or time fields such as amount fields and voucher date fields. Example rules include: "Amount field value should be greater than 0", "Voucher date must not be later than the current system date", etc.

[0214] Field format validation: Applicable to format-sensitive fields such as dates, numbers, and encodings. It uses regular expressions to match the format, such as the date format should be "YYYY-MM-DD".

[0215] Inter-field logical consistency check: Applicable to field pairs that need to be mutually constrained, such as "if the debit account is 'bank deposit', then the credit account must not be 'cash'"; or "the account and summary content must match common business logic combinations".

[0216] Each validation operation returns a boolean result and generates a field validation result object, including information such as field identifier, validation type, pass / fail status, and trigger rule number.

[0217] If a field fails validation, meaning its current value or format does not meet the defined conditions of the corresponding business rule, the system will automatically perform the following processing:

[0218] Record the violation type corresponding to this field, such as "negative amount", "date exceeds limit", "subject mismatch", etc.

[0219] The unique identifier of a record field in V0 (such as field name, position index);

[0220] Mark this field as "pending correction" in the data structure and attach the reception processing rule number so that the compliance correction strategy can be invoked in subsequent correction steps.

[0221] All violation records will be compiled into a "Field Validation Anomaly List" and passed along with the V0 structure to the subsequent correction process.

[0222] Through the above-mentioned item-by-item verification mechanism, this step realizes the legality review of the business logic of the core fields in the initially generated accounting voucher structure. It relies on a configurable engine driven by rule expressions to perform judgments and performs differentiated processing based on field type and rule type to ensure the data quality and accounting compliance of each field, providing accurate input basis for subsequent voucher correction and accounting processes.

[0223] S800, output the accounting voucher V and store it in the accounting system.

[0224] In this invention, after completing the business logic verification and compliance correction of the preliminary accounting voucher structure V0, a ​​final accounting voucher V with complete structure and compliant data is obtained. To achieve system integration and business implementation of the voucher data, this accounting voucher V needs to be output and stored in the target accounting system, becoming formal accounting data for accounting process management. The specific steps include the following:

[0225] First, the final accounting voucher V is constructed into a standardized output structure according to the accounting system interface specifications. The output structure typically uses key-value pairs and includes, but is not limited to, the following fields:

[0226] Voucher number (automatically generated or system preset); voucher date; summary information; debit account and amount; credit account and amount; number of attachments; preparer and reviewer (if configured); generation timestamp; field correction record and verification log (for audit traceability).

[0227] The output structure uses an encoding format consistent with the accounting system interface protocol, such as JSON, XML, or structured SQL insert statements.

[0228] Based on the preset data interface configuration, the system sends the completed accounting voucher V to the target accounting system via a standard data communication protocol. Data transmission methods may include:

[0229] API push method: Submit voucher data to the accounting system's open API via HTTP or HTTPS protocol using the POST method.

[0230] Database writing method: Insert voucher V into the voucher master table and detail table of the accounting system, and map the fields one by one;

[0231] Message queue delivery method: The voucher data is encapsulated into a message body and sent to middleware queues such as Kafka and RabbitMQ, and then consumed asynchronously by the backend of the accounting system.

[0232] All output processes must handle return status and perform anomaly monitoring to ensure the reliability and consistency of data writing.

[0233] After a voucher is successfully written to the accounting system, the following output information is recorded as an operation log for auditing or retrying in case of failure: voucher number and generation time; output target system identifier; interface return status code and response information; if the output fails, the reason for failure, stack trace information, and exception fields are recorded. This log can be bound to accounting voucher V for subsequent retrospective, accountability, or reprocessing operations.

[0234] By standardizing the structure of accounting voucher output, connecting to the accounting system interface, and recording output logs, this invention achieves fully automated closed-loop management of the entire process from original documents to formal accounting vouchers. This ensures that voucher data is efficiently and reliably written into the main financial system, provided that the structure is compliant and the logic is correct. This significantly reduces the workload of manual data entry and improves voucher processing efficiency and data consistency.

[0235] The above description is merely a specific embodiment of this application, but the scope of protection of this application is not limited thereto. Any changes or substitutions that can be easily conceived by those skilled in the art within the scope of the technology disclosed in this application should be included within the scope of protection of this application.

Claims

1. A method for automatically generating accounting vouchers based on template matching, characterized in that: include: S100: Collect multiple standard accounting document templates from the preset template library and extract the structured field feature set T1 from each template; where T1 includes field position, field name and field relative hierarchy; S200: Collect images of the original accounting documents to be processed, use OCR to recognize them and construct their preliminary field set T2; S300: Based on the structural similarity between T2 and each T1 in the template library, the similarity weight is calculated by combining the semantic matching algorithm to establish a matching candidate set M; S400, further perform feature residual analysis on each candidate template in M, extract the field position offset matrix ΔP and the naming semantic similarity matrix ΔS, and calculate the weighted matching score W; S500: Select the candidate template T* with the highest matching score from the weighted matching scores W, and use it as the matching template for the current original document. S600, based on the field mapping rules in the candidate template T*, map the field content in the original document to the accounting voucher template to generate the preliminary accounting voucher structure V0; S700 calls the business rules engine to perform logical verification and compliance correction on the key fields in V0, and obtains the final accounting voucher V; S800, output the accounting voucher V and store it in the accounting system.

2. The method for automatically generating accounting vouchers based on template matching according to claim 1, characterized in that: The steps of using OCR to identify and construct its initial field set T2 include: Obtain image data from the original accounting documents and perform image preprocessing on them; A deep learning-based optical character recognition model is used to perform text recognition on the preprocessed document image, and an initial dataset containing field text and its position in the image is extracted. The initial dataset is subjected to layout analysis, and candidate regions for fields are constructed based on the relative positional relationships of text blocks and the layout structure. Based on the text content of the candidate field region, semantic matching is performed with the preset key field dictionary to identify the corresponding structured fields and form a preliminary field set T2.

3. The method for automatically generating accounting vouchers based on template matching according to claim 1, characterized in that: in, The steps for calculating similarity weights using semantic matching algorithms and establishing a candidate matching set M include: For each field in the initial field set T2 and each template field set T1, a field structure vector is constructed. The field structure vector includes the field's position coordinates in the image, the field length, and the relative distance between adjacent fields. Normalized Euclidean distance is used to calculate the field-level structural similarity between T2 and the structural vectors in each T1, and the structural similarity score is obtained. The naming of fields in T2 and T1 is semantically encoded using a word vector model, and the semantic similarity score is obtained by calculating the cosine similarity between word vectors. The overall matching score is calculated based on the weighted result of structural similarity and semantic similarity, and templates with scores higher than a set threshold are added to the matching candidate set M.

4. The method for automatically generating accounting vouchers based on template matching according to claim 1, characterized in that: in, The steps for further feature residual analysis of each candidate template in M ​​include: Based on the field position coordinates of the initial field set T2 and the candidate template field set T1, construct the field position offset matrix ΔP; Based on the field names of the initial field set T2 and the candidate template field set T1, a pre-trained word vector model is used for semantic encoding, and a naming semantic similarity matrix ΔS is constructed. The similarity matrix records the cosine similarity score between the field names. Using ΔP and ΔS as inputs for positional and semantic distributions respectively, a cost matrix for field matching is constructed. The Sinkhorn distance algorithm is then used to perform regularized optimal transmission calculation on the cost matrix to obtain the weighted matching score W for each candidate template.

5. The method for automatically generating accounting vouchers based on template matching according to claim 4, characterized in that: in, The steps for obtaining the weighted matching score W include: The field position offset matrix ΔP and the naming semantic similarity matrix ΔS are weighted and merged according to a preset ratio to generate a unified field matching cost matrix C. The ratio is set according to the degree of influence of position and semantic features on matching accuracy. Construct normalized weight distribution vectors for field set T2 and template field set T1 respectively; Using the field matching cost matrix C and the field weight distribution as input, the Sinkhorn optimal transmission algorithm is used for regularized iterative calculation to obtain the optimal transmission scheme between the two field sets. The weighted matching score W of the candidate template is calculated based on the sum of the products of the field matching probability and the corresponding cost value in the optimal transmission scheme.

6. The method for automatically generating accounting vouchers based on template matching according to claim 1, characterized in that: in, The steps for generating the preliminary accounting document structure V0 include: Invoke the preset field mapping rules in the matching template T*. The field mapping rules define the correspondence between the original fields and the voucher fields, including the field naming correspondence table, field type conversion rules and default value settings; Based on the field naming correspondence, extract the field content corresponding to the voucher fields from the preliminary field set T2; The converted field content is filled into the preset field positions of the accounting voucher template to construct the preliminary accounting voucher structure V0, and the mapping source and conversion status are marked.

7. The method for automatically generating accounting vouchers based on template matching according to claim 1, characterized in that: in, The steps of calling the business rule engine to perform logical validation and compliance correction on key fields in V0 include: Load a preset set of business rules, which includes rules for field value ranges, rules for logical relationships between fields, and rules for account compliance, all defined in the form of rule expressions; Perform rule-based validation on each key field in the initial accounting voucher structure V0. If a field value is outside the defined range or there is a logical conflict between fields, mark it as a validation failure and record the exception type. For fields that fail validation, the content is automatically replaced, completed, or the format is adjusted according to the correction strategy set in the corresponding rule; Reorganize the set of fields that have passed verification or been corrected into a final accounting document V that is structurally complete and conforms to business rules.

8. The method for automatically generating accounting vouchers based on template matching according to claim 7, characterized in that: in, The steps for performing rule validation on each key field in the preliminary accounting voucher structure V0 include: Identify a pre-defined set of key fields from the initial accounting document structure V0; For each key field, the corresponding rule validation expression is called according to the field type to validate the field value range, data format and logical consistency between fields, and generate field validation results; When a field validation result is detected as not meeting the rule constraints, the corresponding violation type and field identifier are recorded, and the field is marked as pending correction.