Method for automatically extracting medical structured information from picture based on OCR and LLM
By combining OCR and large language model methods, the problems of inaccurate term recognition and insufficient multilingual support in medical pictures are solved, efficient and accurate medical structured information extraction is achieved, and the reliability and accuracy of information extraction are improved.
Patent Information
- Application Number
- CN202411006301.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-25
- Publication Date
- 2024-11-01
AI Technical Summary
The prior art has inaccurate term recognition in medical pictures, insufficient multilingual support, and weak text understanding and relationship extraction capabilities in text, resulting in errors and inaccurate information extraction.
Using OCR and large language model (LLM)-based methods, through optical character recognition, text blocking, information encoding, LLM reasoning and result integration, combined with specific prompt generation and information cleaning strategies, improve the accuracy of extracting medical structured information and reliability.
It effectively improves the multilingual support and professional information extraction capabilities, reduces the pressure of manually labeling data, improves the reliability of the extraction results, and is suitable for the effective management and application of medical picture information.
Smart Images

Figure CN118887684A_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the technical field of medical information processing, and in particular relates to a method for automatically extracting medical structured information from images based on OCR and LLM. Background Art
[0002] In the construction of medical informationization, automatic structured extraction of text information in images is a crucial link. Compared with traditional manual data entry, automated information extraction methods can give full play to the advantages of computers in data organization and processing, and provide reliable data support for the subsequent actual processing and application of medical information.
[0003] The existing technical solution adopts a step-by-step approach of optical character recognition (OCR) first and natural language processing (NLP) later to achieve the goal of automatically extracting medical structured information from images from multiple sources. The specific technical process includes image preprocessing, text detection and character recognition, text preprocessing, information extraction, and data storage and management.
[0004] First, the uploaded or scanned images are preprocessed, such as denoising and image enhancement, to improve the accuracy of subsequent OCR processing. This step is crucial because the quality of the image directly affects the recognition effect of OCR. Common preprocessing methods include grayscale, binarization, edge detection, etc. Deep learning models, such as convolutional neural networks (CNN) and recurrent neural networks (RNN), are used to perform text detection and character recognition to convert the text content in the image into machine-readable text. The introduction of the Transformer architecture further improves the recognition accuracy and speed of OCR. The text generated by OCR is preprocessed by cleaning, word segmentation, and word form restoration to prepare the text data for subsequent NLP processing. This step includes removing redundant spaces, standardizing punctuation marks, and normalizing synonyms. Named entity recognition (NER), relationship extraction, and text classification are performed through NLP technology to extract key entities and their relationships, and classify the information into predefined categories. This process combines machine learning and rule matching methods to achieve efficient and accurate information extraction. The extracted structured information is stored in a database to support subsequent query and analysis needs. Common databases include relational databases and NoSQL databases. The specific choice depends on the structure of the data and query requirements.
[0005] However, current technologies face some major challenges in NLP processing. Professional terms and abbreviations widely used in medical data may have different meanings in different contexts. Correctly identifying and understanding these terms requires building and maintaining complex domain-specific dictionaries and context models. Current systems are still insufficient in handling ambiguity, which can easily lead to information extraction errors. This work requires a lot of resources and time investment to ensure that the system can accurately parse the text and extract information. For example, the word "ECG" may refer to "electrocardiogram" or "electronic medical record" in different situations, which needs to be judged by context.
[0006] In medical information management, term alignment and translation accuracy in a multilingual environment is a major challenge, as documents of different types and sources may involve multiple languages. NLP technology needs to be able to effectively process and translate texts in different languages to ensure the comprehensiveness and accuracy of information extraction, which is especially important for processing documents from multilingual environments. Currently, Transformer-based multilingual models such as mBERT and XLM-R have made some progress in this field, but there is still room for improvement. Specifically, context understanding and information extraction of multilingual documents require more efficient cross-lingual models. Current multilingual models do not perform well when dealing with complex contexts and professional terminology.
[0007] Medical images have high information density, complex content, and involve multiple entities and relationships. Existing NLP models are still insufficient in accuracy and reliability when dealing with complex structures and extracting relationships. For example, extracting relationships between medication records, diagnosis results, and patient history information in medical records requires more sophisticated analysis and reasoning capabilities. At the same time, medical images often contain implicit information and inferences, such as the association between symptoms and potential diagnoses. The extraction and mining of this information requires more advanced natural language understanding and reasoning technologies. Summary of the invention
[0008] In view of the above, in order to solve the technical problems in the prior art such as inaccurate terminology recognition, insufficient multilingual support, weak text understanding and relationship extraction capabilities, the purpose of the present invention is to provide a method based on OCR and LLM (large language model) that can efficiently and accurately automatically extract medical structured information from images.
[0009] An embodiment of the present invention provides a method for automatically extracting medical structured information from an image based on OCR and LLM, comprising the following steps:
[0010] Perform optical character recognition on the medical image through OCR, and divide the OCR recognition result into multiple text blocks;
[0011] After encoding information of the multiple text blocks respectively, multiple prompt text contents are created for the multiple text blocks based on the encoding results, each prompt text content includes a document representation, a task description and a task label;
[0012] LLM is used to generate multiple candidate texts based on the content of multiple prompt texts;
[0013] The results of multiple candidate texts are integrated to obtain a unique text, and the unique text is cleaned to obtain the final text, which is the extracted medical structured information.
[0014] Preferably, dividing the OCR recognition result into text blocks to obtain a plurality of text blocks includes:
[0015] Read the text content and its position in the document from the OCR recognition result;
[0016] Initialize an empty list to store the blocks, and set a counter to track the text length of the current block;
[0017] Starting from the beginning of the document, read the text content and the corresponding bounding box line by line, check whether the length of the current block exceeds the limit, if the length of the current line does not exceed the limit after being added to the current block, then add the current line to the current block, if it exceeds the limit, then use the current line as the starting line of the next block and record its position, assign the exceeding part of the content to a new block, and mark the exceeding part of the content as the start of the new block, until all the text content is divided into blocks;
[0018] Check whether the last line of the text block is complete and contains text and corresponding position information. If it is incomplete, backtrack and move part of the content to the next line to ensure that the end of each text block is a complete text line or paragraph;
[0019] The text of each text block and its position coordinate information in the original document are saved for subsequent processing and output.
[0020] Preferably, the information encoding of the plurality of text blocks respectively comprises:
[0021] Get the width and height of the medical image, take the upper left corner as the origin, and save the overall coordinate information of the image;
[0022] Traverse each text block and obtain each text block including the text content and the corresponding four corner point bounding box coordinates;
[0023] Use the bounding box coordinates of the four corner points to calculate the center point coordinates (X, Y) of each paragraph of text content;
[0024] Normalization processing, that is, dividing the center point coordinates by the width and height of the image, converting the coordinate values into a ratio relative to the image size;
[0025] Quantization processing, that is, the normalized coordinates are multiplied by a fixed value and converted to integers to simplify the coordinate system;
[0026] Combine the text content in the text block and the quantized coordinates into an encoded result saved as a string, in the format of 'text X coordinate|Y coordinate'.
[0027] Preferably, creating multiple prompt text contents for multiple text blocks based on the encoded result, including:
[0028] Write the encoded result after information encoding into the document representation, represented in the format of 'text X|Y';
[0029] Briefly describe the task to be completed in text form, and use the text content of the brief description as the main body of the task description. At the same time, use a JSON object in the task description to represent the entity types to be extracted and their hierarchical structures;
[0030] Use the <extraction> tag to further indicate the task direction and emphasize the purpose;
[0031] Integrate the prompt content, represented in the structure of '<document>document representation< / document><task>task description< / task><extraction>', to generate the final prompt text content;
[0032] Ensure that the total token length of the prompt text content is within the input limit of the LLM. If it exceeds the limit, reduce the content of the document representation, move the excess content to the prompt of the next text block, and so on, to control the prompt length.
[0033] Preferably, the LLM undergoes pre-training processing before being cited, including the following processes:
[0034] Construct a medical information dataset, including data collection, data screening, Q&A pair construction, and data integration. Among them, Q&A pair construction includes: using OCR to identify the text content and coordinate information in the picture to obtain the original OCR result; performing information encoding and generating prompt text content on the original OCR result to obtain the structure of '<document>document representation< / document><task>task description< / task><extraction>', as the content of 'question' in the Q&A pair; starting from the 'task description', manually extract structured information from each picture to obtain JSON format data containing accurate text results and coordinate results, as the content of 'answer' in the Q&A pair; data integration includes aligning each Q&A pair in the format of 'dialogue / role - content / role - content' to form a medical information dataset;
[0035] Fine-tune the LLM using the constructed medical information dataset.
[0036] Preferably, QLoRA technology is used to fine-tune the LLM.
[0037] Preferably, when using LLM to perform reasoning based on multiple prompt text contents, a multi-sampling generation method is adopted, that is, the set generation parameters include temperature, the top K probability maximum values and the number of sampling times for each block, and these parameters are used for multiple samplings to generate multiple candidate texts.
[0038] Preferably, the step of integrating the results of multiple candidate texts to obtain a unique text includes:
[0039] JSON decoding, that is, extracting and parsing entity information from the JSON information corresponding to the generated candidate text to obtain multiple preliminary entity sets;
[0040] Entity mapping and merging, specifically: initialize a global entity set to store entities merged across blocks; traverse the preliminary entity set of each text block, process each entity, check whether the same entity already exists in the global entity set, if the same entity exists, merge the newly parsed entity with the existing entity, where the merging includes merging location information and / or completion attributes, if the same entity does not exist, add it directly to the global entity set;
[0041] Majority voting and consistency checking, specifically: initialize a voting array to record the number of votes for each entity; create a type list with the initial value containing the root type; perform recursive traversal to compare all entities of the same type, and if two entities are the same, increase their vote counts; remove the processed type from the type list and add its subtypes for recursive processing; finally return the entity value with the highest number of votes;
[0042] The entity values of multiple candidate texts are combined into high-quality unique texts after JSON decoding, entity mapping and merging, majority voting and consistency checking.
[0043] Preferably, the step of performing information cleaning on the unique text to obtain the final text includes:
[0044] For each entity in the unique text, the text content is compared with the original OCR recognition result to see if it exists in the original OCR recognition result. The entity is considered valid only when the text content and the coordinates match.
[0045] Delete the entity information that cannot be found in the original OCR recognition results;
[0046] Remove the coordinate information from the JSON information corresponding to the valid entity, delete the X|Y content, and retain the complete final text content.
[0047] Preferably, the medical image is pre-processed before OCR recognition, including denoising and grayscale processing.
[0048] Compared with the prior art, the present invention has the following beneficial effects:
[0049] In the present invention, a coding strategy is designed to clearly describe the entire process of LLM prompt generation suitable for medical image information extraction, including normalization and quantization of coordinate information, alignment of text content and quantized coordinates, LLM input control strategy and format expression of special prompts, etc., and the powerful natural language understanding ability of LLM is used to effectively improve the problem of insufficient multi-language support; at the same time, combined with the generated special prompts, LLM itself improves the ability to understand medical texts and extract professional information. The present invention uses a medical information data set constructed based on real-world data to efficiently achieve fine-tuning of a large language model and ensure the effect of overall information extraction, greatly reducing the pressure of manually annotating data and reducing labor cost expenses. The present invention effectively avoids the hallucination information generated by the generative large model by establishing an information extraction result verification method based on LLM, improves the reliability of the extraction results, and contributes to the effective management and application of medical image information. BRIEF DESCRIPTION OF THE DRAWINGS
[0050] In order to more clearly illustrate the embodiments of the present invention or the technical solutions in the prior art, the drawings required for use in the embodiments or the description of the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without creative work.
[0051] Figure 1 is a flow chart of a method for automatically extracting medical structured information from a picture based on OCR and LLM provided in an embodiment;
[0052] Figure 2 It is a schematic diagram of the original OCR result provided by the embodiment of the present invention.
[0053] Figure 3 This is a schematic diagram of extracting structured information provided by an embodiment of the present invention. Figure 1 .
[0054] Figure 4 This is a schematic diagram of extracting structured information provided by an embodiment of the present invention. Figure 2 .
[0055] Figure 5 This is a schematic diagram of extracting structured information provided by an embodiment of the present invention. Figure 3 .
[0056] Figure 6 It is a flowchart for constructing a medical information data set based on real-world data provided by an embodiment of the present invention.
[0057] Figure 7 Schematic diagram of a desensitized question-answer pair data set provided in an embodiment of the present invention. DETAILED DESCRIPTION
[0058] In order to make the purpose, technical solution and advantages of the present invention more clearly understood, the present invention is further described in detail below in conjunction with the accompanying drawings and embodiments. It should be understood that the specific implementation methods described herein are only used to explain the present invention and do not limit the scope of protection of the present invention.
[0059] The technical concept of the present invention is: in view of the current medical image structured information extraction methods, the existing OCR method and NLP method system have problems such as inaccurate medical terminology recognition, insufficient multi-language support, weak text understanding and relationship extraction capabilities, etc. The present invention proposes to use OCR technology to connect LLM to construct a solution for automatically extracting medical structured information from images.
[0060] Specifically considering the deployment and data security issues in practical applications, we selected PP-OCRv4 in the general OCR model and ChatGLM3-6B in the large language model. The medical question-and-answer data constructed based on real-world data was used as the large language model training data set. The QLoRA instruction fine-tuning scheme with lower storage requirements and lower computing requirements was adopted to train ChatGLM3-6B as a structured information extraction model suitable for the medical image structured information extraction scenario. By segmenting and encoding the original OCR results, text prompt content containing both text and layout information was constructed to facilitate LLM information understanding and corresponding relationship recognition. The original NLP model part was replaced by LLM, and the large-scale parameters, knowledge integration and few-sample learning capabilities of the former were used to effectively improve the ability of medical information structured extraction. For the common generative hallucination information in the field of large language models, in the information cleaning stage, the wrong extraction content was eliminated by repeated verification and entity matching methods, effectively avoiding the adverse effects of hallucination information on the extraction results.
[0061] PP-OCR (PaddlePaddle OCR) is a deep learning-based optical character recognition (OCR) tool library developed by Baidu. PP-OCRv4 is a general OCR open source model in the PP-OCR series. It combines the DB text detection algorithm, the detection frame correction algorithm, and the SVTR text recognition algorithm to form a pipeline structure. It has been widely recognized in the field of general OCR recognition.
[0062] ChatGLM3 is a conversation pre-training model jointly released by Zhipu AI and Tsinghua University KEG Laboratory. ChatGLM3-6B is an open source model in the ChatGLM3 series with 6 billion parameters (6B) that can capture rich language patterns and knowledge. It has performed well in a variety of tasks, including question-answering, text generation, translation, event extraction, etc., and has broad application prospects.
[0063] Figure 1 FIG. 1 is a flow chart of a method for automatically extracting medical structured information from an image based on OCR and LLM provided by an embodiment of the present invention. Figure 1 As shown, the present invention provides a method for automatically extracting medical structured information from images based on OCR and LLM, including OCR recognition, text segmentation, information encoding and prompt generation, LLM reasoning, result integration and information cleaning.
[0064] In the embodiment, OCR recognition is used to perform text detection and text recognition from medical images from multiple sources, extract characters, words and text lines, and record their position information (bounding box) to obtain OCR recognition results containing text content and position coordinates. The original medical image is pre-processed by denoising and grayscale to improve the image quality and obtain a pre-processed medical image. Further, the pre-processed image is formally OCR recognized to obtain the original OCR recognition result. The data content is as follows: Figure 2 shown.
[0065] Specifically, the collected medical image data are all from real-world medical scenarios, including but not limited to medical platform computer images taken by doctors, personal report documents taken by patients, electronic report documents generated by medical systems, document scans intercepted by medical institutions, etc. Through OCR recognition of the pre-processed state of the above images, each text contains three parts: the four-point coordinates of the detection boundary box, the text content body, and the recognition result confidence given by the algorithm calculation, which constitute the original OCR recognition result.
[0066] Text segmentation is performed when the OCR recognition result is reprocessed, mainly to ensure that the recognition result can be completely received by LLM. Specifically, the original OCR recognition result is too long, the extraction effect after the overall input to LLM is not good, and there is a situation that exceeds the LLM input limit. In this embodiment, the input limit of ChatGLM3-6B is adjusted to 1024tokens, which generally supports an input length of 768 words. When the text is segmented, after removing the confidence content in the original OCR recognition result, the text content and its position in the document are read from the OCR recognition result, and the text segment is cut and segmented with 768 words as the limit. Specifically, it includes: initializing an empty list for storing segments, and setting a counter for tracking the text length of the current block; reading the bounding box information and text content line by line, checking whether the length of the current block exceeds the limit, if the length of the current line does not exceed the limit after being added to the current block, then adding the current line to the current block, if it exceeds the limit, then using the current line as the starting line of the next block, and recording its position, assigning the excess content to a new block, and marking the excess content as the start of the new block. At the same time, additional rules are followed. The four-point bounding box of the front and back relationship and the text content are taken as a whole. When the breakpoint of the block is in the middle of a whole, the whole is used as the starting point of the next block. Furthermore, the margin operation is performed on the previous block. The cutting behavior of all text blocks is completed in sequence and the records are saved.
[0067] In the embodiment, information encoding and prompt generation are important steps in the method for automatically extracting medical structured information from images based on OCR and LLM, and are important factors affecting the final extraction result.
[0068] The information expression format of the four-point bounding box coordinates and the text content is not conducive to the understanding of LLM, and will seriously affect the ability of LLM to understand contextual semantics and identify key relationships during the reasoning process. This embodiment encodes the naturally generated OCR information expression format, including the text content and bounding box content, and performs information alignment to convert the lengthy original OCR results into a language form that is easy for the large language model to understand. At the same time, information encoding further reduces the input length of each block, providing input space for the generation of subsequent prompt content. The generated new format is easier for LLM to accept and understand, and information encoding is performed when optimizing image information.
[0069] Specifically, obtain the width and height of the medical image (image_width, image_height), with the upper left corner as the origin, and save the overall coordinate information of the image. Traverse each text block, and obtain the text content of each text block and the corresponding four-corner bounding box coordinates. The four-point bounding box coordinate information is verbose. Cancel the redundant information, and use the bounding box coordinates of the four corners to calculate the center point coordinates (X, Y) of each text content, and represent the position information with the text center point. The context relationship and the text order relationship are reflected by the normalization of the coordinates. Divide the center point coordinates by the width and height of the image, and convert the coordinate values into ratios relative to the image size, that is, divide the X coordinate of the center point by the image width image_width to obtain X_normalized for normalization, so that it is between 0 and 1, and divide the Y coordinate of the center point by the image width image_height to obtain Y_normalized for normalization, so that it is between 0 and 1, and obtain the normalized coordinates (X_normalized, Y_normalized). For quantization processing, multiply the normalized coordinates (X_normalized, Y_normalized) by a fixed value (such as 100) and convert them into integers to obtain the final quantized coordinates (X_final, Y_final). Concatenate and merge the text and the normalized and quantized center point coordinates into an encoded result in the format of "{text}{X_final}|{Y_final}".
[0070] In the embodiment, a prompt is to provide a piece of text or instruction to a large language model to guide or stimulate the model to generate a specific response or complete a specific task, improve the LLM's understanding ability of specific texts and the ability to extract professional information, and the prompt generation is performed when integrating image information and confirming the extraction target. After encoding the information of multiple text blocks respectively, create multiple prompt text contents for the multiple text blocks based on the encoding results. Each prompt text content includes a document representation, a task description, and a task label. The process includes:
[0071] Write the encoded result after information encoding into the document representation, which is represented in the format of 'text X|Y'; briefly describe the task to be completed in text form, and use the text content of the brief description as the main body of the task description. At the same time, use a JSON object in the task description to represent the entity types to be extracted and their hierarchical structures; further represent the task direction with the <extraction> tag to emphasize the purpose; integrate the prompt content, and the format is presented in the structure of '<document>document representation< / document><task>task description< / task><extraction>', and generate the final prompt text content; ensure that the total token length of the prompt text content is within the input limit of the LLM. If it exceeds the limit, reduce the content of the document representation, move the redundant content to the prompt of the next text block, and so on, to control the prompt length.
[0072] Specifically, in combination with the result format of information coding, prompts for medical information extraction were artificially constructed, as follows: "<Document>X 99|90XX Academy of Medical Sciences 36|129XXXXX Hospital 73|130 CT Diagnostic Report 55|216 Medical Insurance 11|265 Ordinary Patient 21|265 Examination Date 81|266 2024.01.26 03:11 96|265 Examination Number 13|329 CT1117076 23|325 Patient Number 36|329 Applying Department 2602 Emergency Surgery 70|326 Inpatient Number 89|326 M00417707746|330 Name 11|393 Wang San 20|393 Gender Female 35|393 Age 60 46|393 Years Old 54|392 Parameter CT Second Examination Room 67|388 Drugs None 14|458 None 37|457 Drug Usage Method None 67|452 Imaging Findings: 14|621 CD Burning: 58|623 Sheets 73|623 Film Quantity: 689|623 Sheets 102|623 The bilateral cerebral hemispheres are symmetrical, the gray and white matter boundaries are clear, the midline structure is centered, and there are mass-like high-density shadows in the left basal ganglia area and beside the lateral ventricles. Patchy low-density shadows can be seen around them. The larger section is approximately: 4.0 cm × 5.4 cm. The left 57|715 lateral ventricle is compressed, and patchy low-density shadows can be seen in the bilateral semi-oval centers. The ventricles, cerebral sulci, fissures, and cisterns are not significantly widened. The cerebellum and brainstem in the infratentorial region are normal. 26|812 The VR image shows that after the bilateral internal carotid arteries enter the skull, they give rise to the bilateral anterior cerebral arteries and bilateral middle cerebral arteries. After the bilateral vertebral arteries enter the skull, they converge into the basilar artery. The basilar artery gives rise to the bilateral anterior inferior cerebellar arteries, bilateral superior cerebellar arteries, and 56|909 bilateral posterior cerebral arteries. The blood vessels of the bilateral posterior cerebral arteries have a natural course, and the lumen is not stenosed. There are multiple calcified plaques in the siphon segments of the bilateral internal carotid arteries, and the lumen is mildly stenosed. 29|1005< / Document><Task>Please extract the information from the medical report in the document, generate a structured result, and save the coordinate information. Entity: {"Examination Date": "", "Report Date": "", "Name": "", "Gender": "", "Age": "", "Examination Number": "", "Inpatient Number": "", "Bed Number": "", "Imaging Findings": "", "Imaging Diagnosis": "", "Patient Number": "", "Other": ""}< / Task><Extraction>". As Figure 3 、 Figure 4 and Figure 5As shown, the prompt content expresses information in a quasi-XML format, which is conducive to the content understanding of large language models. The prompt consists of three main parts, including <Document>Document Representation< / Document>, <Task>Task Description< / Task>, and <Extraction>. The text content after information encoding is stored in <Document>Document Representation< / Document>. The large language model receives the text information and its relative positions. The specific task description, i.e., 'Extract information from the medical reports in the document and generate a structured result', is stored in <Task>Task Description< / Task>. Further, a structured JSON object is constructed in the form of 'entity' tags to determine the extraction target. <Extraction> further indicates the task direction and emphasizes the purpose.
[0073] In the embodiment, during the LLM inference, the constructed text prompt content is input into the LLM. To further improve the reliability of the LLM inference results, the multi-sampling strategy Top-K is adopted in the inference stage. In each step of the generation process, the K candidates with the highest probabilities are selected from all possible outputs, and then sampling is performed from these K candidates to reduce uncertainty and generation errors. In this embodiment, the parameters are set based on the local model ChatGLM3-6B. The temperature value is set to 0.5, the K value is set to 40, and the number of sampling times for each block is set to 16. Finally, 16 different candidate texts are generated after each inference of the large language model.
[0074] In the embodiment, after obtaining multiple candidate texts, result integration is also performed to obtain a unique text. The specific result integration process includes JSON decoding, entity mapping and merging, and majority voting and consistency checking.
[0075] JSON decoding refers to extracting and parsing entity information from the JSON information corresponding to the generated candidate texts to obtain multiple preliminary entity sets. The specific process is as follows: Initialize an empty set to store all parsed and located entities; traverse each JSON object; for each entity type, if it is a leaf entity type, directly call the entity value parsing function, and if it is a hierarchical entity type, recursively call the parsing function to parse the subtype; finally, return the parsed multiple preliminary entity sets. Entity mapping and merging are used to address the problem that 'the same entity may appear in different blocks and affect the consistency of the final result'. Through the cross-block entity merging strategy, such problems can be effectively solved, which specifically includes: Initialize a global entity set to store the entities after cross-block merging; traverse the preliminary entity sets of each text block, process each entity, check whether the same entity already exists in the global entity set, if the same entity exists, merge the newly parsed entity with the existing entity, where the merging includes merging location information and / or complementing attributes, etc., and if the same entity does not exist, directly add it to the global entity set.
[0076] Majority voting and consistency checking means that after completing the cross-block entity merge, a majority vote is performed on each entity in the global entity set to avoid connection errors and context disconnection problems of the same entity between different blocks, and a global entity set is obtained. For this set, a majority voting strategy is used to perform a majority vote on each entity in the set, and the entity value with the highest number of votes is returned. The specific process is: initialize a voting array to record the number of votes for each entity; create a type list with an initial value that includes the root type; perform a recursive traversal to compare all entities of the same type. If two entities are the same, their votes are increased; remove the processed type from the type list and add its subtype for recursive processing; finally, return the entity value with the highest number of votes.
[0077] Combining all the strategies in the above reasoning stage, multiple candidate texts are decoded by JSON, mapped and merged, and the entity values after majority voting and consistency check are combined into a high-quality unique text.
[0078] Generative large language models have the common problem of generating additional hallucination information. The embodiments provide a way of information cleaning to effectively avoid the erroneous influence of hallucination information on the extraction results. The particularities of the OCR technology and the large language model method system are combined to retain the JSON results obtained by the final reasoning of the large language model, and each entity text content is compared with the original OCR recognition result. Further, the location coordinates of each entity are compared with the original OCR recognition result. If the two match, the entity is deemed to be valid. If one of the two matches incorrectly, the entity content is deemed to be wrong and deleted, ensuring that only entity information that has been verified to be real is retained. The coordinate information of the JSON information corresponding to the valid entity is removed, the content of X|Y is deleted, and the complete final text content is retained.
[0079] In the embodiment, the large language model ChatGLM3-6B is a general generative large model, which is not sensitive to the medical information extraction task. In this embodiment, a medical data set collected from real-world data is constructed. Figure 6 This is a flowchart for constructing a medical information dataset based on real-world data, including multi-source image collection, image screening, OCR recognition, information encoding and prompt generation, and manual dataset construction. The two stages of OCR recognition and information encoding and prompt generation are consistent with the corresponding stages in the method of automatically extracting medical structured information from images based on OCR and LLM, so they will not be repeated here.
[0080] This embodiment collects various types of medical images from real medical scenarios, including municipal key hospitals, medical research platforms, professional medical institutions, etc. In the image screening stage, the image quality was controlled, and the images with a DPI lower than 300 were eliminated. Furthermore, all images were manually classified according to different medical scenarios, including five categories: pathological diagnosis reports, patient information sheets, test documents, department examination reports, and long text reports. 20 examples were randomly selected from each category of images, and a total of 100 examples formed a preliminary image data set. After the OCR recognition, information encoding, and prompt generation stages, this embodiment manually constructed a data set suitable for fine-tuning of the large model. The specific format is as follows: Figure 7 The schematic diagram of the desensitized question-answer pair data set is shown. Each question-answer pair consists of two parts, including 'role:user' and 'role:assistant' content. The user content is saved as the content generated by the prompt, including documents, tasks and extractions. The assistant content is saved as the result of manual extraction of the structured content of the 'entity' in the prompt. After the first round of manual annotation and construction, it undergoes another round of manual review to check all results such as text content and coordinate position to ensure accuracy. Taking each conversation as a question-answer pair data, this embodiment constructs a total of 100 question-answer pairs of data for QloRA fine-tuning training of ChatGLM3-6B.
[0081] This solution uses QLoRA (Quantized Low Rank Adaptation) technology to achieve efficient structured extraction of medical information. QLoRA significantly reduces the amount of video memory used during model loading and training by introducing a dual quantization method. The specific operation involves quantizing the original model parameters into NF4 format and dequantizing these parameters into BF16 format for updating during training. This method has the characteristics of low training cost and high parameter efficiency, and is particularly suitable for clinical application scenarios with limited resources.
[0082] In order to train the ChatGLM3-6B model to achieve structured extraction of medical information, this embodiment adopts the following steps:
[0083] First, the original model parameters are quantized into NF4 format to reduce memory usage. Assume that the model inference process is Y = XW, where X∈R b*h is the input, W∈R h*o is the weight matrix. Through low-rank decomposition, the updated parameters are expressed as W+ΔW, where ΔW=L1+L2. In order to maintain model accuracy, the quantized parameters will be dequantized to BF16 format during training. The specific reasoning process is: BF16 =X BF16 ·doubleDequant(c1 FP32 ,c2FP8 ,W NF4 )+X BF16 L1 BF16 L2 BF16 , where doubleDequant(c1 FP32 ,c2 FP8 ,W NF4 ) represents a double dequantization operation. First, c1 FP32 and c2 FP8 Dequantize, then dequantize W NF4 Get W BF16 .
[0084] During training, only the low-rank matrix L1 BF16 and L2 BF16 is updated, and the original quantization parameter W NF4 This method ensures the high efficiency of training and the stability of parameters. After training, the updated low-rank matrix L1 BF16 and L2 BF16 Import the original model. Finally, the fine-tuned model can be used for structured extraction of medical information, achieving efficient and accurate information processing.
[0085] The QLoRA scheme has the following significant advantages for extracting structured medical information from the ChatGLM3-6B model: high video memory efficiency. Through double quantization and low-rank decomposition technology, video memory usage is greatly reduced, allowing large models to run in resource-constrained environments; low training cost. Since only low-rank matrices are updated, the overall training process is more efficient, saving a lot of computing resources; strong applicability. The QLoRA scheme is suitable for various medical information extraction tasks, especially clinical application scenarios that require high precision and high efficiency. Through the above methods, the structured extraction of medical information will become more efficient and reliable, providing strong support for clinical decision-making.
[0086] The specific implementation methods described above provide a detailed description of the technical solutions and beneficial effects of the present invention. It should be understood that the above is only the most preferred embodiment of the present invention and is not intended to limit the present invention. Any modifications, supplements and equivalent substitutions made within the scope of the principles of the present invention should be included in the protection scope of the present invention.
Claims
1. A method for automatically extracting medical structured information from images based on OCR and LLM, characterized in that: Including the following steps: Perform optical character recognition (OCR) on the medical image, and perform text chunking on the OCR recognition result to obtain multiple text chunks; After separately encoding the information of multiple text chunks, create multiple prompt text contents for the multiple text chunks based on the encoding results. Each prompt text content includes a document representation, a task description, and a task label; Use the large language model (LLM) to perform inference based on the multiple prompt text contents to generate multiple candidate texts; Integrate the results of multiple candidate texts to obtain a unique text, and perform information cleaning on the unique text to obtain the final text, which is the extracted medical structured information.
2. The method for automatically extracting medical structured information from images based on OCR and LLM according to claim 1, characterized in that: The step of performing text chunking on the OCR recognition result to obtain multiple text chunks includes: Read the text content and its position in the document from the OCR recognition result; Initialize an empty list to store the chunks, and set a counter to track the text length of the current chunk; Starting from the beginning of the document, read the text content and the corresponding bounding box line by line. Check whether the length of the current chunk exceeds the limit. If the length does not exceed the limit after adding the current line to the current chunk, add the current line to the current chunk. If it exceeds the limit, use the current line as the starting line of the next chunk, record its position, allocate the excess content to a new chunk, and mark the excess content as the start of the new chunk until all text content is chunked; Check whether the last line of the text chunk is complete and contains text and the corresponding position information. If it is incomplete, backtrack and move some content to the next line to ensure that the end of each text chunk is a complete text line or paragraph; Save the text of each text chunk and its position coordinate information in the original document for subsequent processing and output.
3. The method for automatically extracting medical structured information from images based on OCR and LLM according to claim 1, characterized in that: The step of separately encoding the information of multiple text chunks includes: Obtain the width and height of the medical image, and take the upper left corner as the origin to save the overall coordinate information of the image; Traverse each text chunk to obtain the text content and the corresponding four-corner bounding box coordinates of each text chunk; Use the bounding box coordinates of the four corners to calculate the center point coordinates (X, Y) of each text content; Perform normalization processing, that is, divide the center point coordinates by the width and height of the image to convert the coordinate values into ratios relative to the image size; Perform quantization processing, that is, multiply the normalized coordinates by a fixed value and convert them into integers to simplify the coordinate system; Combine the text content in the text chunk and the quantized coordinates into an encoded result saved as a string in the format of 'text X coordinate|Y coordinate'.
4. The method for automatically extracting medical structured information from images based on OCR and LLM according to claim 1, characterized in that: The step of creating multiple prompt text contents for multiple text chunks based on the encoding results includes: Write the encoded result after information encoding into the document representation, which is represented in the format of 'text X|Y'; Briefly describe the task to be completed in text form, and use the text content of the brief description as the main body of the task description. At the same time, use a JSON object in the task description to represent the entity types to be extracted and their hierarchical structures; Use the <extraction> tag to represent the task direction and emphasize the purpose; Integrate the prompt content, and generate the final prompt text content in the format of '<document>document representation< / document><task>task description< / task><extraction>'; Ensure that the total token length of the prompt text content is within the input limit of the LLM. If it exceeds the limit, reduce the content represented by the document, move the excess content to the prompt of the next text block, and so on to control the prompt length.
5. The method for automatically extracting medical structured information from images based on OCR and LLM according to claim 1, characterized in that: Before the LLM is cited, it undergoes pre-training processing, including the following processes: Construct a medical information dataset, including data collection, data screening, Q&A pair construction, and data integration. Among them, Q&A pair construction includes: using OCR to recognize the text content and coordinate information in the picture to obtain the original OCR result; performing information encoding and prompt text content generation on the original OCR result to obtain the structural representation of '<document>document representation< / document><task>task description< / task><extraction>', which is used as the content of the 'question' in the Q&A pair; starting from the 'task description', manually extract structured information from each picture to obtain JSON format data containing accurate text results and coordinate results, which is used as the content of the 'answer' in the Q&A pair; data integration includes aligning each Q&A pair in the format of 'dialogue / role - content / role - content' to form a medical information dataset; Use the constructed medical information dataset to fine-tune the LLM.
6. The method for automatically extracting medical structured information from images based on OCR and LLM according to claim 5, characterized in that: Adopt the QLoRA technology to fine-tune the LLM.
7. The method for automatically extracting medical structured information from images based on OCR and LLM according to claim 1, characterized in that: When using the LLM to perform inference based on multiple prompt text contents, adopt the multi-sampling generation method, that is, the set generation parameters include temperature, the top K probability maxima, and the number of samples per block, and use these parameters to perform multiple samplings to generate multiple candidate texts.
8. The method for automatically extracting medical structured information from images based on OCR and LLM according to claim 1, characterized in that: The integration of the results of multiple candidate texts to obtain a unique text includes: JSON decoding, that is, extracting and parsing entity information from the JSON information corresponding to the generated candidate texts to obtain multiple preliminary entity sets; Entity mapping and merging, specifically: initialize a global entity set for storing entities merged across blocks; traverse the preliminary entity sets of each text block, process each entity, check whether the same entity already exists in the global entity set, if the same entity exists, merge the newly parsed entity with the existing entity, where the merge includes merging location information and / or complementing attributes, if the same entity does not exist, add it directly to the global entity set; Majority voting and consistency check, specifically: initialize a voting array for recording the voting times of each entity; create a type list, with the initial value including the root type; perform a recursive traversal, compare all entities of the same type, if two entities are the same, increase their voting times; remove the processed type from the type list and add its subtype for recursive processing; finally return the entity value with the highest number of votes; Form a high-quality unique text from the entity values of multiple candidate texts after JSON decoding, entity mapping and merging, and majority voting and consistency check.
9. The method for automatically extracting medical structured information from images based on OCR and LLM according to claim 1, characterized in that: The information cleaning of the unique text to obtain the final text includes: For each entity in the unique text, the text content is compared with the original OCR recognition result to see if it exists in the original OCR recognition result. The location coordinates of the entity are matched in the original OCR recognition result. The matching results of the text content and the coordinates are combined. Only when both match, the entity is considered valid. Delete the entity information that cannot be found in the original OCR recognition results; Remove the coordinate information from the JSON information corresponding to the valid entity, delete the X|Y content, and retain the complete final text content.
10. The method for automatically extracting medical structured information from images based on OCR and LLM according to claim 1, characterized in that: Before the OCR recognition, the medical image is pre-processed, including denoising and grayscale processing.
Citation Information
Patent Citations
Medical information determination method and device, equipment and medium
CN117373594A
Question and answer pair extraction method and device, electronic equipment and storage medium
CN117407502A
Image content structured information extraction method and device, equipment and storage medium
CN117437643A
Traditional Chinese medicine massage multi-modal knowledge graph construction method based on large model and comparative learning
CN118136264A
Intelligent document identification method and device, electronic equipment and storage medium
CN118194842A
Cited By
Financial data automatic extraction and articulation processing system and method
CN119831767A
A system and method for automatic extraction and reconciliation processing of financial data
CN119831767B
Text recognition method, classification method and device based on large model
CN120356230A
Large model-based text recognition method, classification method and device
CN120356230B
Medical data retrieval method and system and storage medium
CN122112235A
