Kverna Sample Pipeline: Ad-hoc CSV+XML Data Wrangling ======================================================= Difficulty: Intermediate Nodes: 6 Description: Clean a messy CSV shipment log and merge it with a structured XML invoice feed using pandas. Demonstrates data:static for inline test data, multi-format date/amount parsing, CSV+XML join, PDF extraction from base64, and writing enriched results to an Excel table — all in a self-contained, replayable pipeline. This is an importable Kverna pipeline in JSON format. To import: Copy the JSON below, save as a .json file, then use Import in Kverna. --- BEGIN PIPELINE JSON --- { "version": "2.0.0", "exportedAt": "2026-03-08T16:25:16.177Z", "pipeline": { "id": "pipeline-1772985143818", "name": "Shipment CSV+XML Enrichment", "label": "Ad-hoc CSV+XML Data Wrangling", "version": "1.0.0", "changeVersion": 1843, "variables": { "ResultSheet": "Shipments", "FileName": "Invoice.pdf" }, "nodes": [ { "id": "pipeline-1772985143818_node_4", "type": "table:write", "position": { "x": 464.31, "y": 209.87 }, "config": { "tableName": "EnrichedShipments", "writeMode": "overwrite", "createIfMissing": true, "sheetName": "${ResultSheet}", "startCell": "A1" }, "dependencies": ["clean-and-merge"] }, { "id": "pipeline-1772985143818_node_5", "type": "transform:python", "position": { "x": 216.68, "y": 344.19 }, "config": { "packages": "", "code": "import xml.etree.ElementTree as ET\n\nxml_raw = input_0\nroot = ET.fromstring(xml_raw)\n\n# Find the first Attachment with mimeType application/pdf\nattachments = root.find('Attachments')\npdf_b64 = ''\nif attachments is not None:\n for att in attachments.findall('Attachment'):\n if att.get('mimeType') == 'application/pdf':\n data_el = att.find('Data')\n if data_el is not None and data_el.text:\n pdf_b64 = data_el.text.strip()\n break\n\nif not pdf_b64:\n raise ValueError('No PDF attachment found in XML')\n\npdf_b64\n", "enableCache": false }, "dependencies": ["read-xml"], "label": "Extract PDF from XML" }, { "id": "node-1772985170761", "type": "data:static", "dependencies": [], "position": { "x": -138.66, "y": 309.25 }, "config": { "data": "\n\n \n \n kverna-demo-bundle-shipping.pdf\n JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA2MTIgNzkyXSAvQ29udGVudHMgNCAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNSAwIFIgPj4gPj4gPj4KZW5kb2JqCjQgMCBvYmoKPDwgL0xlbmd0aCA0NCA+PgpzdHJlYW0KQlQgL0YxIDEyIFRmIDEwMCA3MDAgVGQgKEt2ZXJuYSBEZW1vIERvY3VtZW50KSBUaiBFVAplbmRzdHJlYW0KZW5kb2JqCjUgMCBvYmoKPDwgL1R5cGUgL0ZvbnQgL1N1YnR5cGUgL1R5cGUxIC9CYXNlRm9udCAvSGVsdmV0aWNhID4+CmVuZG9iagp4cmVmCjAgNgowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAwMDkgMDAwMDAgbiAKMDAwMDAwMDA2MyAwMDAwMCBuIAowMDAwMDAwMTE4IDAwMDAwIG4gCjAwMDAwMDAyOTYgMDAwMDAgbiAKMDAwMDAwMDM5MyAwMDAwMCBuIAp0cmFpbGVyCjw8IC9TaXplIDYgL1Jvb3QgMSAwIFIgPj4Kc3RhcnR4cmVmCjQ2OAolJUVPRg==\n \n \n \n
ORD-A043BAE1602025-09-122025-12-01CANCELLEDSGD38957.29NET30REF-D3DE77
\n Apex Trade LtdGB123456789LondonUnited KingdomBlueSea Carriers PteSG201912345SingaporeSingapore\n ECI-6500Electrical Cabinet IP65161875.002910.0027090.000.215688.9032778.90CPM-3300Control Panel Module31240.00137.273582.730.21752.374335.10\n SEA_FCLDDPBL-7AE85C6BD4B5CNTR-83ACE5F40FA2025-09-23RotterdamHouston\n CREATED2025-09-12T08:17:00ZsystemAuto-processedAPPROVED2025-09-16T13:50:00Zapprover@corpManual review\n \n
\n \n
ORD-3803A839C02025-01-132025-03-29DELIVEREDSGD11524.63NET60REF-534571
\n NordShip ASNO912345678OsloNorwayTransGlobal CorpUS-EIN-8812ChicagoUnited States\n BRG-24PKBearing Set (24-pack)7112.7532.20757.050.19143.84900.89HPA-7710Hydraulic Pump Assembly11940.50579.359766.150.000.009766.15\n SEA_LCLFCABL-1F81884FC924CNTR-E800E0616BE2025-02-02ShanghaiHouston\n CREATED2025-01-13T18:51:00ZsystemOKAPPROVED2025-01-16T15:14:00Zuser.a@corpManual review\n \n
\n \n
ORD-B488B91BAF2025-11-162026-01-05DELIVEREDCHF71181.832/10NET30REF-28E36F
\n Acme Logistics GmbHDE291837465BerlinGermanyIronclad Supplies BVNL854321987RotterdamNetherlands\n ICU-4400Industrial Compressor Unit102850.002701.8025798.200.102579.8228378.02ICU-4400Industrial Compressor Unit152850.001628.7841121.220.000.0041121.22\n ROAD_LTLDDPBL-A0A577E703A9N/A2025-11-26FelixstoweNew York\n DISPATCHED2025-11-16T12:49:00Zapprover@corpManual reviewAPPROVED2025-11-19T14:26:00Zapprover@corpSee attached\n \n
\n
\n" }, "label": "Shipping" }, { "id": "node-1772985172785", "type": "data:static", "dependencies": [], "position": { "x": -145.26, "y": 181.74 }, "config": { "data": "OrderID,RecordDate,Carrier,Amount,Currency,Status,TrackingNumber,PortOfLoading,PortOfDischarge,Notes\nORD-A043BAE160,2025-09-12,MSC,38957.29,SGD,Cancelled,TRK-29D04D0777FE,Rotterdam,Houston,\nORD-3803A839C0,,Maersk Line,39044.41,GBP,Delivered,TRK-C8EDD910FCFC,Hamburg,Houston,On schedule\nORD-B488B91BAF,2025-06-21,Hapag-Lloyd,10384.31,NOK,Delivered,TRK-0A4279E3D47D,Singapore,Houston,Fragile\nORD-5D7798221A-DUP,2025-06-10,DB Schenker,82368.08,EUR,Delivered,TRK-011734301FAD,Felixstowe,Oslo,On schedule\nORD-7BEF4958F5,17/05/2025,MSC,43550.31,NOK,In Transit,TRK-633DB32C0F37,Rotterdam,Antwerp,See invoice\nord-deadbeef01,2025/02/21,DHL Express,123747.93,GBP,Returned,TRK-16B85BCA27A0,Rotterdam,Dubai,Checked OK\nORD-MISSING001,31/13/2024,FedEx International,36073.14,CHF,Cancelled,TRK-29D04D0777FE,Rotterdam,Antwerp,\nORD-BADAMT0001,2025-03-08,Kuehne+Nagel,N/A,SGD,Customs Hold,TRK-16F4300E52DE,Hamburg,Oslo,Checked OK\nORD-EUROFMT001,2025-06-28,Hapag-Lloyd,\"63.108,49\",USD,In Transit,TRK-1815C83CA43C,Shanghai,Antwerp,Slight delay\nORD-USFMT0001,2025-05-07,MSC,\"$37,551\",SGD,In Transit,TRK-E9290F07C087,Hamburg,Antwerp,See invoice\n,2025-07-09,DHL Express,58223.84,GBP,Pending,TRK-5FD1B7FC4CF6,Shanghai,New York,On schedule\n" }, "label": "CSV" }, { "id": "transform:python-1772985474011-403", "type": "transform:python", "position": { "x": 206.24, "y": 168.82 }, "config": { "packages": ["pandas"], "code": "import pandas as pd\nimport io\nimport json\nimport re\nimport math\nfrom datetime import datetime\n\ncsv_raw = input_0\ndf = pd.read_csv(io.StringIO(csv_raw), dtype=str, keep_default_na=False)\n\ndf['OrderID'] = df['OrderID'].str.upper().str.strip()\ndf = df[df['OrderID'] != ''].copy()\ndf['IsDuplicate'] = df['OrderID'].str.endswith('-DUP')\ndf['OrderID'] = df['OrderID'].str.replace(r'-DUP$', '', regex=True)\ndf = df.drop_duplicates(subset='OrderID', keep='first').copy()\n\ndef parse_date(val):\n if not val or val.strip() == '': return None\n for fmt in ('%Y-%m-%d', '%d/%m/%Y', '%Y/%m/%d', '%d-%m-%y', '%d-%m-%Y'):\n try: return datetime.strptime(val.strip(), fmt).strftime('%Y-%m-%d')\n except ValueError: continue\n return None\n\ndf['RecordDate'] = df['RecordDate'].apply(parse_date)\n\ndef clean_amount(val):\n if not val or val.strip() in ('', 'N/A'): return None\n val = val.strip().replace('$', '').replace(' ', '')\n if re.match(r'^\\d{1,3}(\\.\\d{3})+(,\\d+)?$', val):\n val = val.replace('.', '').replace(',', '.')\n else:\n val = val.replace(',', '')\n try: return float(val)\n except ValueError: return None\n\ndf['Amount'] = df['Amount'].apply(clean_amount)\n\nlookup = {}\nfor _, row in df.iterrows():\n lookup[row['OrderID']] = {\n 'csv_RecordDate': row.get('RecordDate'), 'csv_Carrier': row.get('Carrier', ''),\n 'csv_Amount': row.get('Amount'), 'csv_Currency': row.get('Currency', ''),\n 'csv_Status': row.get('Status', ''), 'csv_TrackingNumber': row.get('TrackingNumber', ''),\n 'csv_PortOfLoading': row.get('PortOfLoading', ''), 'csv_PortOfDischarge': row.get('PortOfDischarge', ''),\n 'csv_Notes': row.get('Notes', ''), 'csv_IsDuplicate': str(row.get('IsDuplicate', False))\n }\n\nimport xml.etree.ElementTree as ET\nroot = ET.fromstring(input_1)\n\nrows = []\nfor inv in root.findall('ShipmentInvoice'):\n hdr = inv.find('Header')\n ship = inv.find('ShipmentDetails')\n parties = inv.find('Parties')\n seller = parties.find('Seller') if parties is not None else None\n buyer = parties.find('Buyer') if parties is not None else None\n audit = inv.find('AuditTrail')\n\n def txt(el, tag, default=''):\n if el is None: return default\n node = el.find(tag)\n return node.text.strip() if node is not None and node.text else default\n\n order_id = txt(hdr, 'OrderID')\n csv_data = lookup.get(order_id, {})\n\n li_el = inv.find('LineItems')\n li_count = int(li_el.get('count', 0)) if li_el is not None else 0\n net_total = sum(float(li.findtext('NetAmount') or 0) for li in (li_el or []))\n gross_total = sum(float(li.findtext('GrossAmount') or 0) for li in (li_el or []))\n vat_total = sum(float(li.findtext('VATAmount') or 0) for li in (li_el or []))\n\n last_event = last_event_ts = ''\n if audit is not None:\n events = audit.findall('Event')\n if events:\n last_event = events[-1].findtext('Type', '')\n last_event_ts = events[-1].findtext('Timestamp', '')\n\n rows.append({\n 'OrderID': order_id, 'IssueDate': txt(hdr, 'IssueDate'), 'DueDate': txt(hdr, 'DueDate'),\n 'XML_Status': txt(hdr, 'Status'), 'Currency': txt(hdr, 'Currency'),\n 'TotalGrossAmount': txt(hdr, 'TotalGrossAmount'), 'PaymentTerms': txt(hdr, 'PaymentTerms'),\n 'InternalRef': txt(hdr, 'InternalRef'), 'Seller': txt(seller, 'Name'),\n 'SellerCountry': txt(seller, 'Country'), 'Buyer': txt(buyer, 'Name'),\n 'BuyerCountry': txt(buyer, 'Country'), 'LineItemCount': li_count,\n 'LineItems_NetTotal': round(net_total, 2), 'LineItems_VATTotal': round(vat_total, 2),\n 'LineItems_GrossTotal': round(gross_total, 2), 'ShipMethod': txt(ship, 'Method'),\n 'Incoterm': txt(ship, 'Incoterm'), 'BillOfLading': txt(ship, 'BillOfLadingNumber'),\n 'ContainerID': txt(ship, 'ContainerID'), 'EstimatedDelivery': txt(ship, 'EstimatedDelivery'),\n 'XML_PortOfLoading': txt(ship, 'PortOfLoading'), 'XML_PortOfDischarge': txt(ship, 'PortOfDischarge'),\n 'LastAuditEvent': last_event, 'LastAuditTimestamp': last_event_ts,\n 'CSV_RecordDate': csv_data.get('csv_RecordDate', ''), 'CSV_Carrier': csv_data.get('csv_Carrier', ''),\n 'CSV_Amount': csv_data.get('csv_Amount', ''), 'CSV_Currency': csv_data.get('csv_Currency', ''),\n 'CSV_Status': csv_data.get('csv_Status', ''), 'CSV_TrackingNumber': csv_data.get('csv_TrackingNumber', ''),\n 'CSV_PortOfLoading': csv_data.get('csv_PortOfLoading', ''), 'CSV_PortOfDischarge': csv_data.get('csv_PortOfDischarge', ''),\n 'CSV_Notes': csv_data.get('csv_Notes', ''), 'CSV_WasDuplicate': csv_data.get('csv_IsDuplicate', ''),\n 'CSV_Matched': 'Yes' if csv_data else 'No'\n })\n\ndef sanitise(v):\n if isinstance(v, float) and math.isnan(v): return None\n return v\n\nclean_rows = [{k: sanitise(v) for k, v in r.items()} for r in rows]\njson.dumps(clean_rows)\n", "enableCache": false }, "dependencies": ["read-csv", "read-xml"], "label": "Clean and enrich from csv" }, { "id": "node-1772985603245", "type": "data:download", "dependencies": [], "position": { "x": 383.14, "y": 498.50 }, "config": { "filename": "${FileName}", "base64": true } } ], "triggers": [ { "type": "manual", "enabled": true, "id": "pipeline-1772985143818_trigger_1", "position": { "x": -63.72, "y": 0.61 } } ], "edges": [ {"source":"node-1772985170761","target":"pipeline-1772985143818_node_5","sourceHandle":"data-out","targetHandle":"input-0","id":"node-1772985170761-pipeline-1772985143818_node_5-data-out-orderedInput","type":"orderedInput","inputIndex":0}, {"source":"pipeline-1772985143818_trigger_1","target":"pipeline-1772985143818_node_5","sourceHandle":"execution-out","targetHandle":"execution-in","id":"pipeline-1772985143818_trigger_1-pipeline-1772985143818_node_5-execution-out-execution","type":"execution"}, {"source":"node-1772985172785","target":"transform:python-1772985474011-403","sourceHandle":"data-out","targetHandle":"input-0","id":"node-1772985172785-transform:python-1772985474011-403-data-out-orderedInput","type":"orderedInput","inputIndex":0}, {"source":"node-1772985170761","target":"transform:python-1772985474011-403","sourceHandle":"data-out","targetHandle":"input-1","id":"node-1772985170761-transform:python-1772985474011-403-data-out-orderedInput","type":"orderedInput","inputIndex":1}, {"source":"pipeline-1772985143818_trigger_1","target":"transform:python-1772985474011-403","sourceHandle":"execution-out","targetHandle":"execution-in","id":"pipeline-1772985143818_trigger_1-transform:python-1772985474011-403-execution-out-execution","type":"execution"}, {"source":"pipeline-1772985143818_node_5","target":"node-1772985603245","sourceHandle":"data-out","targetHandle":"data-in","id":"pipeline-1772985143818_node_5-node-1772985603245-data-out-data","type":"data"}, {"source":"pipeline-1772985143818_node_5","target":"node-1772985603245","sourceHandle":"execution-out","targetHandle":"execution-in","id":"pipeline-1772985143818_node_5-node-1772985603245-execution-out-execution","type":"execution"}, {"source":"transform:python-1772985474011-403","target":"pipeline-1772985143818_node_4","sourceHandle":"data-out","targetHandle":"data-in","id":"transform:python-1772985474011-403-pipeline-1772985143818_node_4-data-out-data","type":"data"}, {"source":"transform:python-1772985474011-403","target":"pipeline-1772985143818_node_4","sourceHandle":"execution-out","targetHandle":"execution-in","id":"transform:python-1772985474011-403-pipeline-1772985143818_node_4-execution-out-execution","type":"execution"} ], "description": "This pipeline is meant to demonstrate an otherwise time consuming data wrangling task. Two files, an inbound external invoice list from a shipment system (complex XML), and a manually maintained CSV meant to enrich the invoice.\nProcess: User adds two static nodes, one for csv, one for xml. Mark: Large files in static nodes might affect performance and the ability to save pipelines to sheet. For a one-off, this might be fine, but in general large files should be loaded from an external source like SharePoint or OneDrive. They connect both to a new python node and press Run. The python node will now have sample data. In the python configuration, copy the LLM prompt (this will include sample data). The user pastes this to his favorite LLM, and state the purpose (clean csv, combine with invoice data, return as a clean list).\nLLM produces code, this is copied to the python node. The user hits Run. If something fails, the user can either copy the error (found in the Results tab), or CTRL-C the entire node and CTRL-V into the LLM chat. On a strong LLM, this is normally from 0 to 2 ping pongs before success." } } --- END PIPELINE JSON ---