### Install Pyx12 Source: https://context7.com/azoner/pyx12/llms.txt Install the library using pip. ```bash pip install pyx12 ``` -------------------------------- ### Install Pyx12 Source: https://github.com/azoner/pyx12/blob/master/README.md Commands for installing the package system-wide or within a virtual environment. ```bash pip install pyx12 ``` ```bash virtualenv my_env pip -E my_env install pyx12 ``` -------------------------------- ### Manage Runtime Configuration Source: https://context7.com/azoner/pyx12/llms.txt Configure validation parameters using the params class or an external XML configuration file. ```python import pyx12.params # Create params with default configuration param = pyx12.params.params() # Create params with custom config file param = pyx12.params.params('/path/to/pyx12.conf.xml') # Get configuration values map_path = param.get('map_path') charset = param.get('charset') # 'E' for extended, 'B' for basic # Set configuration values param.set('map_path', '/custom/map/path') param.set('exclude_external_codes', 'CODE1,CODE2') param.set('charset', 'E') param.set('xmlout', 'simple') # Configuration file format (pyx12.conf.xml): # # # # /usr/share/pyx12/map # # # # # ``` -------------------------------- ### Write X12 Files with X12Writer Source: https://context7.com/azoner/pyx12/llms.txt Use X12Writer to generate formatted X12 documents with automatic trailer generation. ```python import pyx12.x12file import pyx12.segment # Create a new X12 file with custom terminators with open('output.txt', 'w', encoding='ascii') as fd_out: writer = pyx12.x12file.X12Writer( fd_out, seg_term='~', ele_term='*', subele_term=':', eol='\n' ) # Write ISA segment isa = pyx12.segment.Segment( 'ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER *230101*1200*^*00501*000000001*0*P*:~', '~', '*', ':' ) writer.Write(isa) # Write GS segment gs = pyx12.segment.Segment( 'GS*BE*SENDER*RECEIVER*20230101*1200*1*X*005010X220A1~', '~', '*', ':' ) writer.Write(gs) # Write ST segment st = pyx12.segment.Segment('ST*834*0001*005010X220A1~', '~', '*', ':') writer.Write(st) # Write transaction content... bgn = pyx12.segment.Segment('BGN*00*12345*20230101*120000****4~', '~', '*', ':') writer.Write(bgn) # Close() auto-generates SE, GE, IEA trailers with correct counts writer.Close() ``` -------------------------------- ### Convert X12 to XML with x12xml Source: https://context7.com/azoner/pyx12/llms.txt Convert X12 documents into XML format. ```bash # Convert X12 to XML, output to stdout x12xml input_file.txt # Convert to XML with specific output file x12xml --outputfile output.xml input_file.txt # Convert with debug logging x12xml --debug input_file.txt ``` -------------------------------- ### Convert XML to X12 with xmlx12 Source: https://context7.com/azoner/pyx12/llms.txt Convert XML documents back into X12 format. ```bash # Convert XML to X12, output to stdout xmlx12 input.xml # Convert to X12 with specific output file xmlx12 --outputfile output.txt input.xml ``` -------------------------------- ### Normalize X12 Files with x12norm Source: https://context7.com/azoner/pyx12/llms.txt Fix structural errors and reformat X12 documents. ```bash # Add newlines after each segment for readability x12norm --eol input_file.txt # Fix counting errors (SE, GE, IEA counts and HL numbering) x12norm --fixcounting input_file.txt # Fix errors and modify file in place x12norm --inplace --fixcounting --eol input_file.txt # Output to specific file x12norm --output normalized.txt input_file.txt ``` -------------------------------- ### Validate and Process X12 Documents Source: https://context7.com/azoner/pyx12/llms.txt Demonstrates how to validate an X12 file and optionally generate 997/999 acknowledgments, HTML reports, or XML output. ```python with tempfile.TemporaryFile(mode='w+', encoding='ascii') as fd_997: result = pyx12.x12n_document.x12n_document( param=param, src_file='input_834.txt', fd_997=fd_997, # Output 997/999 acknowledgment fd_html=None, # No HTML report fd_xmldoc=None # No XML output ) if result: print("Validation passed") else: print("Validation failed") # Read generated 997/999 fd_997.seek(0) ack_content = fd_997.read() print("Acknowledgment response:") print(ack_content) ``` ```python with open('report.html', 'w') as fd_html: result = pyx12.x12n_document.x12n_document( param=param, src_file='input_834.txt', fd_997=None, fd_html=fd_html, fd_xmldoc=None ) ``` ```python with open('output.xml', 'w') as fd_xml: result = pyx12.x12n_document.x12n_document( param=param, src_file='input_834.txt', fd_997=None, fd_html=None, fd_xmldoc=fd_xml ) ``` -------------------------------- ### Loop-Aware X12 Parsing with X12ContextReader Source: https://context7.com/azoner/pyx12/llms.txt The X12ContextReader facilitates loop-aware parsing of X12 documents, enabling navigation through hierarchical structures. Initialize with parameters and an error handler. ```python import pyx12.x12context import pyx12.params import pyx12.error_handler # Initialize reader with parameters and error handler param = pyx12.params.params() errh = pyx12.error_handler.errh_null() with open('enrollment_834.txt', 'r', encoding='ascii') as fd_in: src = pyx12.x12context.X12ContextReader(param, errh, fd_in) # Iterate over all segments for datatree in src.iter_segments(): seg_id = datatree.id if datatree.type == 'seg': # Access segment data for seg_info in datatree.iterate_segments(): segment = seg_info['segment'] line_num = seg_info['cur_line_number'] print(f"Line {line_num}: {segment.get_seg_id()}") # Or iterate over specific loops (e.g., 2000 subscriber loops) for loop_2000 in src.iter_segments('2000'): # Get subscriber information subscriber_id = loop_2000.get_value('REF[0F]02') # Navigate to member name in 2100A loop member_name = loop_2000.get_value('2100A/NM103') print(f"Subscriber {subscriber_id}: {member_name}") ``` -------------------------------- ### Read X12 Files with X12Reader Source: https://context7.com/azoner/pyx12/llms.txt Use X12Reader for low-level streaming access to X12 segments and error tracking. ```python import pyx12.x12file # Read an X12 file and iterate over segments src = pyx12.x12file.X12Reader('enrollment_834.txt') for seg_data in src: seg_id = seg_data.get_seg_id() if seg_id == 'ISA': sender_id = seg_data.get_value('ISA06') receiver_id = seg_data.get_value('ISA08') print(f"Interchange from {sender_id} to {receiver_id}") elif seg_id == 'NM1': entity_type = seg_data.get_value('NM101') last_name = seg_data.get_value('NM103') first_name = seg_data.get_value('NM104') print(f"Entity {entity_type}: {first_name} {last_name}") elif seg_id == 'CLM': claim_id = seg_data.get_value('CLM01') amount = seg_data.get_value('CLM02') print(f"Claim {claim_id}: ${amount}") # Get terminators used in the file (seg_term, ele_term, subele_term, eol, rep_term) = src.get_term() print(f"Segment terminator: {repr(seg_term)}") # Check for errors after iteration src.cleanup() errors = src.pop_errors() for err in errors: print(f"Error: {err}") ``` -------------------------------- ### Normalize X12 File via CLI Source: https://github.com/azoner/pyx12/blob/master/README.md Fixes common X12 structural errors and sets end-of-line characters. ```bash x12norm --fix --eol ``` -------------------------------- ### Navigating and Modifying X12 Loop Trees with X12DataNode Source: https://context7.com/azoner/pyx12/llms.txt X12DataNode classes allow navigation and modification of X12 loop hierarchies. Use methods like `get_value`, `exists`, `count`, `select`, `set_value`, and `delete_node`. ```python import pyx12.x12context import pyx12.params import pyx12.error_handler param = pyx12.params.params() errh = pyx12.error_handler.errh_null() with open('claim_837.txt', 'r', encoding='ascii') as fd_in: src = pyx12.x12context.X12ContextReader(param, errh, fd_in) # Iterate over claim loops (2300) for claim_tree in src.iter_segments('2300'): # Get claim information claim_id = claim_tree.get_value('CLM01') claim_amount = claim_tree.get_value('CLM02') print(f"Processing Claim: {claim_id}") # Check if diagnosis codes exist if claim_tree.exists('HI'): diagnosis = claim_tree.get_value('HI01-2') print(f" Primary Diagnosis: {diagnosis}") # Count service lines service_count = claim_tree.count('2400') print(f" Service Lines: {service_count}") # Iterate over service line loops (2400) for service_line in claim_tree.select('2400'): line_num = service_line.get_value('LX01') proc_code = service_line.get_value('SV101-2') charge = service_line.get_value('SV102') print(f" Line {line_num}: {proc_code} - ${charge}") # Modify service line data service_line.set_value('SV102', '150.00') # Delete optional segments if service_line.exists('PWK'): service_line.delete_node('PWK') # Output modified segments for seg_node in claim_tree.iterate_segments(): print(seg_node['segment'].format()) ``` -------------------------------- ### Split Multi-Transaction X12 File Source: https://context7.com/azoner/pyx12/llms.txt Splits an X12 file containing multiple ST loops into separate files, one for each transaction. The output file names can be customized using a pattern. ```python import pyx12.x12file import tempfile import random from itertools import groupby def split_x12_by_transaction(source_file, output_pattern='split_{st_id}.txt'): """Split an X12 file into separate files per ST loop.""" src = pyx12.x12file.X12Reader(source_file) isa_seg = None gs_seg = None current_st_id = None segments_buffer = [] for seg_data in src: seg_id = seg_data.get_seg_id() if seg_id == 'ISA': isa_seg = seg_data elif seg_id == 'GS': gs_seg = seg_data elif seg_id == 'ST': current_st_id = seg_data.get_value('ST02') segments_buffer = [seg_data] elif seg_id == 'SE': segments_buffer.append(seg_data) # Write this transaction to a new file output_file = output_pattern.format(st_id=current_st_id) write_transaction(output_file, isa_seg, gs_seg, segments_buffer) print(f"Created: {output_file}") segments_buffer = [] elif seg_id in ('GE', 'IEA'): pass # Skip trailer segments else: if segments_buffer: # We're inside an ST loop segments_buffer.append(seg_data) def write_transaction(output_file, isa_seg, gs_seg, segments): """Write a single transaction to a file.""" with open(output_file, 'w', encoding='ascii') as fd_out: writer = pyx12.x12file.X12Writer(fd_out) # Update control numbers for the new file new_isa_id = "{:09d}".format(random.randint(1, 999999999)) isa_seg.set('ISA13', new_isa_id) writer.Write(isa_seg) new_gs_id = str(random.randint(1, 999999999)) gs_seg.set('GS06', new_gs_id) writer.Write(gs_seg) for seg in segments: writer.Write(seg) writer.Close() # Usage split_x12_by_transaction('multi_transaction.txt', 'transaction_{st_id}.txt') ``` -------------------------------- ### Iterate and Modify X12 Loops Source: https://github.com/azoner/pyx12/blob/master/README.md Demonstrates iterating over specific loops, accessing child segments, and modifying or deleting values within the X12 context. ```python src = pyx12.x12context.X12ContextReader(param, errh, fd_in) for datatree in src.iter_segments('2300'): # do something with a 2300 claim loop # we have access to the 2300 loop and all its children for loop2400 in datatree.select('2400'): print(loop2400.get_value('SV101')) # update something loop2400.set_value('SV102', 'xx') # delete something if loop2400.exists('PWK'): loop2400.delete('PWK') # iterate over all the child segments for seg_node in datatree.iterate_segments(): print(seg_node.format()) ``` -------------------------------- ### Validate X12 File via CLI Source: https://github.com/azoner/pyx12/blob/master/README.md Validates an ANSI X12N data file using the command line interface. ```bash x12valid ``` -------------------------------- ### Validate X12 Files with x12valid Source: https://context7.com/azoner/pyx12/llms.txt Validate X12 data files against HIPAA guidelines and generate acknowledgment responses. ```bash # Basic validation - outputs OK/Failure and generates .997 response file x12valid claim_file.txt # Validation with HTML error report x12valid --html claim_file.txt # Validation with custom map path and excluded external codes x12valid --map-path /path/to/maps --exclude-external-codes CODE1 claim_file.txt # Validation with debug logging x12valid --debug --verbose claim_file.txt # Validate multiple files with glob pattern x12valid *.txt ``` -------------------------------- ### De-identify PHI in 834 Files Source: https://context7.com/azoner/pyx12/llms.txt Scrub sensitive information from an 834 enrollment file by iterating through segments and replacing values. ```python import pyx12.x12context import pyx12.x12file import pyx12.params import pyx12.error_handler import random def deidentify_834(input_file, output_file): param = pyx12.params.params() errh = pyx12.error_handler.errh_null() with open(input_file, 'r', encoding='ascii') as fd_in: src = pyx12.x12context.X12ContextReader(param, errh, fd_in) with open(output_file, 'w', encoding='ascii') as fd_out: writer = pyx12.x12file.X12Writer(fd_out) for datatree in src.iter_segments('2000'): if datatree.id == '2000': # Generate fake data fake_ssn = "{:09d}".format(random.randint(100000000, 999999999)) fake_id = "{:010d}".format(random.randint(1000000000, 9999999999)) # Replace member identification datatree.set_value('REF[0F]02', fake_id) # Replace member name in 2100A loop datatree.set_value('2100A/NM103', 'LASTNAME') datatree.set_value('2100A/NM104', 'FIRSTNAME') datatree.set_value('2100A/NM105', '') datatree.set_value('2100A/NM109', fake_ssn) # Replace address datatree.set_value('2100A/N301', '123 MAIN ST') datatree.set_value('2100A/N302', '') # Replace date of birth datatree.set_value('2100A/DMG02', '19700101') # Write modified segments for seg_node in datatree.iterate_segments(): writer.Write(seg_node['segment']) writer.Close() ``` -------------------------------- ### Full X12 Document Validation with x12n_document Source: https://context7.com/azoner/pyx12/llms.txt The x12n_document function offers comprehensive validation for X12 documents with various output options. It requires parameters for configuration. ```python import pyx12.x12n_document import pyx12.params import tempfile param = pyx12.params.params() ``` -------------------------------- ### Manipulating X12 Segment Data with pyx12.segment Source: https://context7.com/azoner/pyx12/llms.txt Use the Segment class to parse, read, and modify individual X12 segments. It supports accessing elements by reference designator and handling composite elements. ```python import pyx12.segment # Create a segment from a string seg_str = 'NM1*IL*1*DOE*JOHN*A***34*123456789~' seg = pyx12.segment.Segment(seg_str, '~', '*', ':') # Get segment ID print(seg.get_seg_id()) # Output: NM1 # Get element values using reference designators entity_code = seg.get_value('NM101') # IL (Insured) last_name = seg.get_value('NM103') # DOE first_name = seg.get_value('NM104') # JOHN middle_name = seg.get_value('NM105') # A id_qualifier = seg.get_value('NM108') # 34 (SSN) ssn = seg.get_value('NM109') # 123456789 # Set element values seg.set('NM103', 'SMITH') seg.set('NM104', 'JANE') # Work with composite elements (using sub-element index) composite_seg = pyx12.segment.Segment('SV1*HC:99213:25*125.00*UN:1~', '~', '*', ':') procedure_code = composite_seg.get_value('SV101-2') # 99213 modifier = composite_seg.get_value('SV101-3') # 25 # Set composite sub-element composite_seg.set('SV101-2', '99214') # Format segment back to string formatted = seg.format('~', '*', ':') print(formatted) # NM1*IL*1*SMITH*JANE*A***34*123456789~ # Iterate over all values in segment for (refdes, ele_ord, comp_ord, val) in seg.values_iterator(): print(f"{refdes}: {val}") ``` -------------------------------- ### Capture Validation Errors Source: https://context7.com/azoner/pyx12/llms.txt Utilize error handler classes to capture and categorize validation errors by X12 segment level. ```python import pyx12.error_handler import pyx12.x12file # Create error handler errh = pyx12.error_handler.err_handler() # After validation, check error counts error_count = errh.get_error_count() print(f"Total errors: {error_count}") # Using errh_list for simpler error capture errh_list = pyx12.error_handler.errh_list() # Errors are captured by level # ISA level errors for err in errh_list.err_isa: print(f"ISA Error: {err[0]} - {err[1]}") # GS level errors for err in errh_list.err_gs: print(f"GS Error: {err[0]} - {err[1]}") # ST level errors for err in errh_list.err_st: print(f"ST Error: {err[0]} - {err[1]}") # Segment level errors for err in errh_list.err_seg: print(f"Segment Error: {err[0]} - {err[1]}") # Element level errors for err in errh_list.err_ele: print(f"Element Error: {err[0]} - {err[1]} Value: {err[2]}") # Handle errors from X12Reader src = pyx12.x12file.X12Reader('input.txt') for seg in src: pass # Pop errors after reading errors = src.pop_errors() errh_list.handle_errors(errors) ``` -------------------------------- ### De-identify 834 File Source: https://context7.com/azoner/pyx12/llms.txt This function de-identifies sensitive data within an 834 X12 file. Ensure the input and output file paths are correctly specified. ```python deidentify_834('input_834.txt', 'deidentified_834.txt') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.