pidsmaker 5.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pidsmaker/__init__.py +1 -0
- pidsmaker/cli.py +81 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1824 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +323 -0
- pidsmaker/debug_tests.py +30 -0
- pidsmaker/decoders/__init__.py +5 -0
- pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
- pidsmaker/decoders/custom_mlp_decoder.py +10 -0
- pidsmaker/decoders/edge_linear_decoder.py +16 -0
- pidsmaker/decoders/inner_product_decoder.py +18 -0
- pidsmaker/decoders/nodlink_decoder.py +56 -0
- pidsmaker/detection/__init__.py +0 -0
- pidsmaker/detection/evaluation_methods/__init__.py +9 -0
- pidsmaker/detection/evaluation_methods/edge_evaluation.py +255 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -0
- pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
- pidsmaker/detection/evaluation_methods/plot.py +192 -0
- pidsmaker/detection/evaluation_methods/queue_evaluation.py +456 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -0
- pidsmaker/detection/flash_detection.py +162 -0
- pidsmaker/detection/magic_knn.py +190 -0
- pidsmaker/detection/node_scoring.py +52 -0
- pidsmaker/detection/threatrace_detection.py +65 -0
- pidsmaker/detection/training_methods/__init__.py +1 -0
- pidsmaker/detection/training_methods/inference_loop.py +287 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +168 -0
- pidsmaker/detection/training_methods/training_loop.py +383 -0
- pidsmaker/encoders/__init__.py +22 -0
- pidsmaker/encoders/argus_encoder.py +69 -0
- pidsmaker/encoders/custom_mlp.py +75 -0
- pidsmaker/encoders/custom_mlp_encoder.py +10 -0
- pidsmaker/encoders/egraphsage_encoder.py +56 -0
- pidsmaker/encoders/gat.py +67 -0
- pidsmaker/encoders/gcn.py +27 -0
- pidsmaker/encoders/gin.py +48 -0
- pidsmaker/encoders/glstm.py +298 -0
- pidsmaker/encoders/graph_attention.py +63 -0
- pidsmaker/encoders/gru.py +29 -0
- pidsmaker/encoders/hetero/__init__.py +4 -0
- pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
- pidsmaker/encoders/hetero/entity_encoder.py +33 -0
- pidsmaker/encoders/hetero/event_encoder.py +81 -0
- pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
- pidsmaker/encoders/lares_encoder.py +68 -0
- pidsmaker/encoders/linear_encoder.py +16 -0
- pidsmaker/encoders/magic_encoder.py +161 -0
- pidsmaker/encoders/rcaid_encoder.py +81 -0
- pidsmaker/encoders/rgcn.py +75 -0
- pidsmaker/encoders/sage.py +51 -0
- pidsmaker/encoders/shadewatcher_encoder.py +149 -0
- pidsmaker/encoders/sum_aggregation.py +20 -0
- pidsmaker/encoders/temporal_wrappers.py +80 -0
- pidsmaker/encoders/textrcnn.py +82 -0
- pidsmaker/encoders/tgn_encoder.py +193 -0
- pidsmaker/experiments/tuning.py +102 -0
- pidsmaker/experiments/uncertainty.py +261 -0
- pidsmaker/factory.py +1456 -0
- pidsmaker/featurization/__init__.py +0 -0
- pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +30 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +66 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +478 -0
- pidsmaker/mimicry.py +284 -0
- pidsmaker/model.py +382 -0
- pidsmaker/objectives/__init__.py +16 -0
- pidsmaker/objectives/autoencode_edge_emb.py +43 -0
- pidsmaker/objectives/deep_graph_infomax.py +94 -0
- pidsmaker/objectives/detect_few_shot.py +21 -0
- pidsmaker/objectives/one_class.py +75 -0
- pidsmaker/objectives/predict_edge_contrastive.py +165 -0
- pidsmaker/objectives/predict_edge_supervised.py +77 -0
- pidsmaker/objectives/predict_edge_type.py +28 -0
- pidsmaker/objectives/predict_masked_struct.py +49 -0
- pidsmaker/objectives/predict_node_type.py +36 -0
- pidsmaker/objectives/predict_process_tag.py +169 -0
- pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
- pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
- pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
- pidsmaker/objectives/reconstruct_node_emb.py +13 -0
- pidsmaker/objectives/reconstruct_node_feat.py +13 -0
- pidsmaker/objectives/validation_wrapper.py +55 -0
- pidsmaker/preprocessing/__init__.py +0 -0
- pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
- pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +825 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -0
- pidsmaker/preprocessing/cleaning.py +258 -0
- pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
- pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
- pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
- pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
- pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
- pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
- pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
- pidsmaker/pretrained/__init__.py +5 -0
- pidsmaker/pretrained/data/__init__.py +4 -0
- pidsmaker/pretrained/data/behavior_signatures.py +548 -0
- pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
- pidsmaker/pretrained/data/edge_filter.py +381 -0
- pidsmaker/pretrained/data/entity_classes.py +476 -0
- pidsmaker/pretrained/data/sampler.py +926 -0
- pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
- pidsmaker/pretrained/detect.py +1427 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1434 -0
- pidsmaker/pretrained/models/__init__.py +20 -0
- pidsmaker/pretrained/models/behavior.py +348 -0
- pidsmaker/pretrained/models/bert.py +286 -0
- pidsmaker/pretrained/models/deepwalk.py +128 -0
- pidsmaker/pretrained/models/dgi.py +120 -0
- pidsmaker/pretrained/models/gae.py +114 -0
- pidsmaker/pretrained/models/gnn_distill.py +475 -0
- pidsmaker/pretrained/models/graphmae.py +373 -0
- pidsmaker/pretrained/models/hf_pretrained.py +213 -0
- pidsmaker/pretrained/models/llama.py +110 -0
- pidsmaker/pretrained/models/modernbert.py +567 -0
- pidsmaker/pretrained/models/roberta.py +147 -0
- pidsmaker/pretrained/models/rope_utils.py +99 -0
- pidsmaker/pretrained/models/ropebert.py +322 -0
- pidsmaker/pretrained/models/spider.py +204 -0
- pidsmaker/pretrained/models/tgn.py +770 -0
- pidsmaker/pretrained/pretrain/__init__.py +3 -0
- pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
- pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
- pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
- pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
- pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
- pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
- pidsmaker/pretrained/pretrain/pretrain_main.py +275 -0
- pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
- pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
- pidsmaker/pretrained/training_utils.py +157 -0
- pidsmaker/process_reapr_gt.py +101 -0
- pidsmaker/resources/config/anomal_e.yml +25 -0
- pidsmaker/resources/config/argus.yml +56 -0
- pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
- pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
- pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
- pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
- pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
- pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
- pidsmaker/resources/config/default.yml +315 -0
- pidsmaker/resources/config/egraphsage.yml +95 -0
- pidsmaker/resources/config/euler.yml +104 -0
- pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
- pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
- pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
- pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
- pidsmaker/resources/config/flash.yml +79 -0
- pidsmaker/resources/config/jbeil.yml +65 -0
- pidsmaker/resources/config/kairos.yml +121 -0
- pidsmaker/resources/config/lares.yml +115 -0
- pidsmaker/resources/config/magic.yml +86 -0
- pidsmaker/resources/config/nodlink.yml +79 -0
- pidsmaker/resources/config/ocrapt.yml +91 -0
- pidsmaker/resources/config/orthrus.yml +126 -0
- pidsmaker/resources/config/orthrus_fixed.yml +17 -0
- pidsmaker/resources/config/pretrained/README.md +101 -0
- pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
- pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
- pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
- pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
- pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
- pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
- pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
- pidsmaker/resources/config/prographer.yml +136 -0
- pidsmaker/resources/config/rcaid.yml +88 -0
- pidsmaker/resources/config/shadewatcher.yml +146 -0
- pidsmaker/resources/config/tests.yml +10 -0
- pidsmaker/resources/config/threatrace.yml +73 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
- pidsmaker/resources/config/velox.yml +10 -0
- pidsmaker/resources/config/viz_config.yml +10 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
- pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
- pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
- pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
- pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
- pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
- pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
- pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
- pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
- pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
- pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
- pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
- pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
- pidsmaker/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +47 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +241 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +17 -0
- pidsmaker/tasks/transformation.py +306 -0
- pidsmaker/tasks/triage.py +143 -0
- pidsmaker/tgn.py +635 -0
- pidsmaker/tokenization/__init__.py +112 -0
- pidsmaker/tokenization/base.py +58 -0
- pidsmaker/tokenization/bpe_tokenizer.py +83 -0
- pidsmaker/tokenization/hf_tokenizer.py +61 -0
- pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
- pidsmaker/tokenization/label_tokenizer.py +24 -0
- pidsmaker/tokenization/nltk_tokenizer.py +84 -0
- pidsmaker/tokenization/substitution.py +295 -0
- pidsmaker/triage/__init__.py +0 -0
- pidsmaker/triage/tracing_methods/__init__.py +1 -0
- pidsmaker/triage/tracing_methods/depimpact.py +213 -0
- pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
- pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
- pidsmaker/utils/__init__.py +0 -0
- pidsmaker/utils/cache_utils.py +256 -0
- pidsmaker/utils/console.py +282 -0
- pidsmaker/utils/data_utils.py +1742 -0
- pidsmaker/utils/database.py +150 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +570 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +445 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +712 -0
- pidsmaker/vizgen/__init__.py +1 -0
- pidsmaker/vizgen/backfill_manifests.py +100 -0
- pidsmaker/vizgen/dimensionality_reduction.py +249 -0
- pidsmaker/vizgen/embed_exporter.py +467 -0
- pidsmaker/vizgen/exporter.py +493 -0
- pidsmaker/vizgen/html_builder.py +936 -0
- pidsmaker/vizgen/web/__init__.py +1 -0
- pidsmaker/vizgen/web/export.py +62 -0
- pidsmaker/vizgen/web/static/css/app.css +250 -0
- pidsmaker/vizgen/web/static/index.html +182 -0
- pidsmaker/vizgen/web/static/js/app.js +627 -0
- pidsmaker/vizgen/web/static/js/campaign.js +123 -0
- pidsmaker/vizgen/web/static/js/data.js +119 -0
- pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
- pidsmaker/vizgen/web/static/js/jobs.js +75 -0
- pidsmaker/vizgen/web/static/js/scene.js +651 -0
- pidsmaker/vizgen/web/static/js/ui.js +370 -0
- pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
- pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
- pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
- pidsmaker/vizgen/web/viz_server.py +2176 -0
- pidsmaker-5.0.0.dist-info/METADATA +597 -0
- pidsmaker-5.0.0.dist-info/RECORD +339 -0
- pidsmaker-5.0.0.dist-info/WHEEL +5 -0
- pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
"""Writing of Parquet datasets (format: see `pidsmaker/utils/database.py`), used by the scripts
|
|
2
|
+
that build datasets from their raw files (`dataset_preprocessing/`), which give the rows of each
|
|
3
|
+
table from Python (`DatasetBuilder`):
|
|
4
|
+
|
|
5
|
+
- a node table is a single file, whose rows are in the order in which they were given;
|
|
6
|
+
- the event table is sorted by `timestamp_rec, event_uuid` (then `_id`, for duplicate records),
|
|
7
|
+
one file per day (UTC);
|
|
8
|
+
- the serial column `_id` of event tables numbers the events from 1 in the order in which they
|
|
9
|
+
are given.
|
|
10
|
+
|
|
11
|
+
The tables have the columns, with their names, order and types, of the published datasets (see
|
|
12
|
+
`TableSpec`), and values follow the same rules (see `to_arrow`).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import datetime
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import shutil
|
|
19
|
+
import time
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
|
|
22
|
+
EVENT_ORDER = "timestamp_rec, event_uuid"
|
|
23
|
+
DAY_NS = 86_400 * 10**9
|
|
24
|
+
ROW_GROUP_SIZE = 1_000_000
|
|
25
|
+
|
|
26
|
+
# SQL types of the columns of the datasets (as named in the manifests), and their DuckDB types
|
|
27
|
+
VARCHAR, BIGINT, INTEGER, SMALLINT, DOUBLE = (
|
|
28
|
+
"character varying",
|
|
29
|
+
"bigint",
|
|
30
|
+
"integer",
|
|
31
|
+
"smallint",
|
|
32
|
+
"double precision",
|
|
33
|
+
)
|
|
34
|
+
DUCKDB_TYPES = {
|
|
35
|
+
VARCHAR: "VARCHAR",
|
|
36
|
+
BIGINT: "BIGINT",
|
|
37
|
+
INTEGER: "INTEGER",
|
|
38
|
+
SMALLINT: "SMALLINT",
|
|
39
|
+
DOUBLE: "DOUBLE",
|
|
40
|
+
}
|
|
41
|
+
# Largest value of a serial column of each type
|
|
42
|
+
SERIAL_MAX = {INTEGER: 2**31 - 1, BIGINT: 2**63 - 1}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def sql_str(s):
|
|
46
|
+
return "'" + s.replace("'", "''") + "'"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def sql_list(paths):
|
|
50
|
+
return "[" + ", ".join(sql_str(p) for p in paths) + "]"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def utc_now():
|
|
54
|
+
return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def connect_duckdb(temp_dir, threads=None, memory_gb=None):
|
|
58
|
+
"""DuckDB connection that writes Parquet files: rows of queries without ORDER BY are kept in
|
|
59
|
+
the order of their source, and large sorts spill to `temp_dir`."""
|
|
60
|
+
import duckdb
|
|
61
|
+
|
|
62
|
+
config = {"temp_directory": temp_dir, "preserve_insertion_order": True}
|
|
63
|
+
if threads:
|
|
64
|
+
config["threads"] = threads
|
|
65
|
+
if memory_gb:
|
|
66
|
+
config["memory_limit"] = f"{memory_gb}GB"
|
|
67
|
+
return duckdb.connect(config=config)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def copy_to_parquet(db, query, path, row_group_size=ROW_GROUP_SIZE):
|
|
71
|
+
"""Writes the rows of `query` to the Parquet file `path`, in the order of the query."""
|
|
72
|
+
db.execute(
|
|
73
|
+
f"COPY ({query}) TO {sql_str(path)} "
|
|
74
|
+
f"(FORMAT parquet, COMPRESSION zstd, ROW_GROUP_SIZE {row_group_size});"
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def count_rows(db, paths):
|
|
79
|
+
return db.execute(f"SELECT count(*) FROM read_parquet({sql_list(paths)});").fetchone()[0]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def write_events_by_day(
|
|
83
|
+
db, source, columns, staging, table_dir, row_group_size=ROW_GROUP_SIZE, log=print, order=None
|
|
84
|
+
):
|
|
85
|
+
"""Writes the events of `source` (a DuckDB relation with the `columns` of the event table)
|
|
86
|
+
sorted by `order` (default: `EVENT_ORDER`), one file per day (UTC) in `table_dir`.
|
|
87
|
+
|
|
88
|
+
Events are copied unsorted, partitioned by day, in `staging` (removed at the end), then
|
|
89
|
+
each day is sorted. Returns the description of the table in the manifest."""
|
|
90
|
+
db.execute(
|
|
91
|
+
f"COPY (SELECT *, timestamp_rec // {DAY_NS} AS _day FROM {source}) "
|
|
92
|
+
f"TO {sql_str(staging)} (FORMAT parquet, COMPRESSION zstd, PARTITION_BY (_day));"
|
|
93
|
+
)
|
|
94
|
+
log("copied, sorting each day")
|
|
95
|
+
|
|
96
|
+
# Partition folders are `_day=<day>`, NULL timestamps (if any) in a non-numeric one, sorted
|
|
97
|
+
# last
|
|
98
|
+
def day_key(folder):
|
|
99
|
+
value = folder.split("=", 1)[1]
|
|
100
|
+
return (0, int(value)) if value.lstrip("-").isdigit() else (1, 0)
|
|
101
|
+
|
|
102
|
+
names = ", ".join(f'"{n}"' for n in columns)
|
|
103
|
+
files = []
|
|
104
|
+
for folder in sorted(os.listdir(staging), key=day_key):
|
|
105
|
+
is_day, day = day_key(folder)
|
|
106
|
+
name = (
|
|
107
|
+
f"part-{datetime.datetime.utcfromtimestamp(day * 86400):%Y-%m-%d}.parquet"
|
|
108
|
+
if is_day == 0
|
|
109
|
+
else "part-null.parquet"
|
|
110
|
+
)
|
|
111
|
+
day_dir = os.path.join(staging, folder)
|
|
112
|
+
copy_to_parquet(
|
|
113
|
+
db,
|
|
114
|
+
f"SELECT {names} FROM read_parquet({sql_str(day_dir + '/*.parquet')}) "
|
|
115
|
+
f"ORDER BY {order or EVENT_ORDER}",
|
|
116
|
+
os.path.join(table_dir, name),
|
|
117
|
+
row_group_size,
|
|
118
|
+
)
|
|
119
|
+
files.append(name)
|
|
120
|
+
shutil.rmtree(day_dir)
|
|
121
|
+
shutil.rmtree(staging)
|
|
122
|
+
return {"files": files, "order": f"ORDER BY {EVENT_ORDER}"}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def write_manifest(dataset_dir, database, source, tables):
|
|
126
|
+
"""Writes the manifest of a dataset. `tables` is {table: description} (files, order, number
|
|
127
|
+
of rows and columns of each table)."""
|
|
128
|
+
manifest = {
|
|
129
|
+
"format_version": 1,
|
|
130
|
+
"database": database,
|
|
131
|
+
"source": source,
|
|
132
|
+
"created_at": utc_now(),
|
|
133
|
+
"tables": tables,
|
|
134
|
+
}
|
|
135
|
+
with open(os.path.join(dataset_dir, "manifest.json"), "w") as f:
|
|
136
|
+
json.dump(manifest, f, indent=2)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# --------------------------------------------------------------------------------------
|
|
140
|
+
# Datasets built from Python
|
|
141
|
+
# --------------------------------------------------------------------------------------
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@dataclass
|
|
145
|
+
class TableSpec:
|
|
146
|
+
"""A table of a dataset.
|
|
147
|
+
|
|
148
|
+
Attributes:
|
|
149
|
+
name: name of the table.
|
|
150
|
+
columns: [(column, SQL type)] in the order of the table.
|
|
151
|
+
not_null: columns that cannot be null.
|
|
152
|
+
serial: column numbering the rows from 1 in the order in which they are given (filled
|
|
153
|
+
by the writer, not given in rows), or None.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
name: str
|
|
157
|
+
columns: list
|
|
158
|
+
not_null: tuple = ()
|
|
159
|
+
serial: str = None
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def names(self):
|
|
163
|
+
return [name for name, _ in self.columns]
|
|
164
|
+
|
|
165
|
+
@property
|
|
166
|
+
def row_columns(self):
|
|
167
|
+
"""[(column, type)] of the values of the rows given to the writer (all but `serial`)."""
|
|
168
|
+
return [(name, kind) for name, kind in self.columns if name != self.serial]
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def is_event_table(self):
|
|
172
|
+
return "timestamp_rec" in self.names and "event_uuid" in self.names
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def node_table_spec(table, attribute_columns):
|
|
176
|
+
"""Node table: `node_uuid`, `hash_id`, the attribute columns (strings) and `index_id`."""
|
|
177
|
+
columns = [("node_uuid", VARCHAR), ("hash_id", VARCHAR)]
|
|
178
|
+
columns += [(column, VARCHAR) for column in attribute_columns] + [("index_id", BIGINT)]
|
|
179
|
+
return TableSpec(table, columns, not_null=("node_uuid", "hash_id"))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def event_table_spec(table, extra_columns=(), serial_type=BIGINT):
|
|
183
|
+
"""Event table: the standard event columns, then `extra_columns` [(column, type)]."""
|
|
184
|
+
columns = [
|
|
185
|
+
("src_node", VARCHAR),
|
|
186
|
+
("src_index_id", VARCHAR),
|
|
187
|
+
("operation", VARCHAR),
|
|
188
|
+
("dst_node", VARCHAR),
|
|
189
|
+
("dst_index_id", VARCHAR),
|
|
190
|
+
("event_uuid", VARCHAR),
|
|
191
|
+
("timestamp_rec", BIGINT),
|
|
192
|
+
("_id", serial_type),
|
|
193
|
+
] + list(extra_columns)
|
|
194
|
+
return TableSpec(table, columns, not_null=("event_uuid",), serial="_id")
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def schema_tables(schema, serial_type=BIGINT):
|
|
198
|
+
"""[TableSpec] of the tables of a dataset schema (see `pidsmaker/config/schemas.py`): a node
|
|
199
|
+
table per node type, with the columns of its attributes, and the event table, with the
|
|
200
|
+
columns of the edge attributes (strings for categorical ones, floats for numeric ones) and
|
|
201
|
+
the label column. The `_id` of events is an `integer` in the provenance datasets, a
|
|
202
|
+
`bigint` in the network datasets."""
|
|
203
|
+
tables = [node_table_spec(nt.table, [col for _, col in nt.columns]) for nt in schema.node_types]
|
|
204
|
+
extra = [
|
|
205
|
+
(a.column, VARCHAR if a.kind == "categorical" else DOUBLE) for a in schema.edge_attributes
|
|
206
|
+
]
|
|
207
|
+
if schema.label_column:
|
|
208
|
+
extra.append((schema.label_column, SMALLINT))
|
|
209
|
+
tables.append(event_table_spec(schema.event_table, extra, serial_type))
|
|
210
|
+
return tables
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _text(value, column):
|
|
214
|
+
"""Value of a text column from a Python value: integers are stored as strings."""
|
|
215
|
+
if value is None or isinstance(value, str):
|
|
216
|
+
return value
|
|
217
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
218
|
+
return str(value)
|
|
219
|
+
raise TypeError(f"Invalid value {value!r} ({type(value).__name__}) of text column {column}")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def to_arrow(values, column, kind, not_null=False, empty_as_null=False):
|
|
223
|
+
"""Arrow array of the Python values of a column of SQL type `kind`.
|
|
224
|
+
|
|
225
|
+
Integers must fit the type (floats are refused), and `not_null` columns cannot be null.
|
|
226
|
+
Integers given to text columns are stored as strings. With `empty_as_null`, empty strings
|
|
227
|
+
are null (as in the network datasets)."""
|
|
228
|
+
import pyarrow as pa
|
|
229
|
+
import pyarrow.compute as pc
|
|
230
|
+
|
|
231
|
+
if kind == VARCHAR:
|
|
232
|
+
try:
|
|
233
|
+
array = pa.array(values, pa.string())
|
|
234
|
+
except (pa.ArrowTypeError, pa.ArrowInvalid):
|
|
235
|
+
array = pa.array([_text(v, column) for v in values], pa.string())
|
|
236
|
+
if empty_as_null:
|
|
237
|
+
array = pc.if_else(pc.equal(array, ""), pa.scalar(None, pa.string()), array)
|
|
238
|
+
elif kind == DOUBLE:
|
|
239
|
+
array = pa.array(values, pa.float64())
|
|
240
|
+
else:
|
|
241
|
+
# Integers are converted after inference, so that floats are refused (instead of
|
|
242
|
+
# being truncated), and values out of the range of the type raise an error
|
|
243
|
+
array = pa.array(values)
|
|
244
|
+
if not (pa.types.is_integer(array.type) or pa.types.is_null(array.type)):
|
|
245
|
+
raise TypeError(f"Column {column} ({kind}) expects integers, got {array.type}")
|
|
246
|
+
target = {BIGINT: pa.int64(), INTEGER: pa.int32(), SMALLINT: pa.int16()}[kind]
|
|
247
|
+
array = array.cast(target)
|
|
248
|
+
if not_null and array.null_count:
|
|
249
|
+
raise ValueError(f"Null value in column {column}, which cannot be null")
|
|
250
|
+
return array
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class TableWriter:
|
|
254
|
+
"""Appends rows to a staging Parquet file of a table, in order.
|
|
255
|
+
|
|
256
|
+
Rows are tuples of the values of `spec.row_columns`, converted by `to_arrow` (with
|
|
257
|
+
`empty_as_null`, empty strings are null). They are buffered and written by batches of
|
|
258
|
+
`buffer_rows`.
|
|
259
|
+
|
|
260
|
+
A writer of the event table can be used in another process than the builder (e.g. to load
|
|
261
|
+
files in parallel): its file is then given to `DatasetBuilder.add_staging_file`."""
|
|
262
|
+
|
|
263
|
+
def __init__(self, spec, path, empty_as_null=False, buffer_rows=1_000_000):
|
|
264
|
+
import pyarrow as pa
|
|
265
|
+
|
|
266
|
+
self.spec = spec
|
|
267
|
+
self.path = path
|
|
268
|
+
self.empty_as_null = empty_as_null
|
|
269
|
+
self.buffer_rows = buffer_rows
|
|
270
|
+
self.columns = spec.row_columns
|
|
271
|
+
type_of = {VARCHAR: pa.string(), BIGINT: pa.int64(), INTEGER: pa.int32()}
|
|
272
|
+
type_of.update({SMALLINT: pa.int16(), DOUBLE: pa.float64()})
|
|
273
|
+
fields = [(name, type_of[kind]) for name, kind in self.columns]
|
|
274
|
+
self.schema = pa.schema(fields)
|
|
275
|
+
self.rows = []
|
|
276
|
+
self.num_rows = 0
|
|
277
|
+
self._writer = None
|
|
278
|
+
|
|
279
|
+
def add(self, row):
|
|
280
|
+
self.rows.append(row)
|
|
281
|
+
if len(self.rows) >= self.buffer_rows:
|
|
282
|
+
self.flush()
|
|
283
|
+
|
|
284
|
+
def add_rows(self, rows):
|
|
285
|
+
for row in rows:
|
|
286
|
+
self.add(row)
|
|
287
|
+
|
|
288
|
+
def flush(self):
|
|
289
|
+
if not self.rows:
|
|
290
|
+
return
|
|
291
|
+
import pyarrow as pa
|
|
292
|
+
import pyarrow.parquet as pq
|
|
293
|
+
|
|
294
|
+
width = len(self.columns)
|
|
295
|
+
for row in self.rows:
|
|
296
|
+
if len(row) != width:
|
|
297
|
+
raise ValueError(
|
|
298
|
+
f"{self.spec.name}: row of {len(row)} values instead of {width}: {row!r}"
|
|
299
|
+
)
|
|
300
|
+
arrays = [
|
|
301
|
+
to_arrow(values, name, kind, name in self.spec.not_null, self.empty_as_null)
|
|
302
|
+
for values, (name, kind) in zip(zip(*self.rows), self.columns)
|
|
303
|
+
]
|
|
304
|
+
if self._writer is None:
|
|
305
|
+
os.makedirs(os.path.dirname(self.path), exist_ok=True)
|
|
306
|
+
self._writer = pq.ParquetWriter(
|
|
307
|
+
self.path, self.schema, compression="zstd", compression_level=1
|
|
308
|
+
)
|
|
309
|
+
self._writer.write_batch(pa.RecordBatch.from_arrays(arrays, schema=self.schema))
|
|
310
|
+
self.num_rows += len(self.rows)
|
|
311
|
+
self.rows = []
|
|
312
|
+
if self.spec.serial:
|
|
313
|
+
check_serial(self.spec, self.num_rows)
|
|
314
|
+
|
|
315
|
+
def close(self):
|
|
316
|
+
"""Writes the remaining rows. Returns the number of rows of the file (no file is written
|
|
317
|
+
without rows)."""
|
|
318
|
+
self.flush()
|
|
319
|
+
if self._writer is not None:
|
|
320
|
+
self._writer.close()
|
|
321
|
+
self._writer = None
|
|
322
|
+
return self.num_rows
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def check_serial(spec, num_rows):
|
|
326
|
+
kind = dict(spec.columns)[spec.serial]
|
|
327
|
+
if num_rows > SERIAL_MAX[kind]:
|
|
328
|
+
raise OverflowError(
|
|
329
|
+
f"{spec.name}: {num_rows} rows, more than the maximum value of its serial column "
|
|
330
|
+
f"{spec.serial} ({kind}, {SERIAL_MAX[kind]})"
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
class DatasetBuilder:
|
|
335
|
+
"""Builds a Parquet dataset from rows given by Python code.
|
|
336
|
+
|
|
337
|
+
with DatasetBuilder(dataset_dir, tables, source="...") as builder:
|
|
338
|
+
builder.table("file_node_table").add(row)
|
|
339
|
+
...
|
|
340
|
+
|
|
341
|
+
Rows of each table are written to staging Parquet files as they come (see `TableWriter`),
|
|
342
|
+
so that memory does not depend on the size of the dataset. At the end of the `with` block
|
|
343
|
+
(or with `finish`), node tables are copied in the order of their rows, events are numbered
|
|
344
|
+
and sorted (see `write_events_by_day`), and the manifest is written. The dataset is written to
|
|
345
|
+
`<dataset_dir>.tmp`, renamed to `dataset_dir` when complete, and removed on errors.
|
|
346
|
+
|
|
347
|
+
Args:
|
|
348
|
+
dataset_dir: folder of the dataset (`<datasets_dir>/<database>`).
|
|
349
|
+
tables: [TableSpec] of the tables of the dataset.
|
|
350
|
+
source: how the dataset was built, recorded in the manifest.
|
|
351
|
+
overwrite: replaces an existing dataset (otherwise, raises FileExistsError).
|
|
352
|
+
empty_as_null: empty strings are stored as null (see `to_arrow`).
|
|
353
|
+
threads, memory_gb: DuckDB threads and memory limit (default: DuckDB's defaults).
|
|
354
|
+
log: function printing progress messages.
|
|
355
|
+
"""
|
|
356
|
+
|
|
357
|
+
def __init__(
|
|
358
|
+
self,
|
|
359
|
+
dataset_dir,
|
|
360
|
+
tables,
|
|
361
|
+
source,
|
|
362
|
+
overwrite=False,
|
|
363
|
+
empty_as_null=False,
|
|
364
|
+
threads=None,
|
|
365
|
+
memory_gb=None,
|
|
366
|
+
row_group_size=ROW_GROUP_SIZE,
|
|
367
|
+
log=print,
|
|
368
|
+
):
|
|
369
|
+
self.dataset_dir = os.path.abspath(dataset_dir)
|
|
370
|
+
if os.path.exists(self.dataset_dir) and not overwrite:
|
|
371
|
+
raise FileExistsError(
|
|
372
|
+
f"The dataset {self.dataset_dir} already exists. Use --overwrite to replace it."
|
|
373
|
+
)
|
|
374
|
+
self.specs = {spec.name: spec for spec in tables}
|
|
375
|
+
self.source = source
|
|
376
|
+
self.empty_as_null = empty_as_null
|
|
377
|
+
self.threads = threads or min(16, os.cpu_count() or 1)
|
|
378
|
+
self.memory_gb = memory_gb
|
|
379
|
+
self.row_group_size = row_group_size
|
|
380
|
+
self.log = log
|
|
381
|
+
self.tmp_dir = self.dataset_dir + ".tmp"
|
|
382
|
+
if os.path.exists(self.tmp_dir):
|
|
383
|
+
shutil.rmtree(self.tmp_dir)
|
|
384
|
+
os.makedirs(self.tmp_dir)
|
|
385
|
+
self.staging_dir = os.path.join(self.tmp_dir, "_staging")
|
|
386
|
+
self._writers = {}
|
|
387
|
+
self._staging = {name: [] for name in self.specs} # [(path, number of rows)]
|
|
388
|
+
self._done = False
|
|
389
|
+
|
|
390
|
+
def table(self, name):
|
|
391
|
+
"""TableWriter of a table, whose rows come after those of the files already added."""
|
|
392
|
+
if name not in self._writers:
|
|
393
|
+
self._writers[name] = TableWriter(
|
|
394
|
+
self.specs[name], self.staging_path(name, "main"), self.empty_as_null
|
|
395
|
+
)
|
|
396
|
+
return self._writers[name]
|
|
397
|
+
|
|
398
|
+
def staging_path(self, table, key):
|
|
399
|
+
"""Path of a staging file of a table, for a TableWriter of another process."""
|
|
400
|
+
return os.path.join(self.staging_dir, table, f"{key}.parquet")
|
|
401
|
+
|
|
402
|
+
def add_staging_file(self, table, path, num_rows):
|
|
403
|
+
"""Adds the rows of a staging file of the event table (written by a TableWriter of
|
|
404
|
+
`spec(table)`) after the rows already added to the table."""
|
|
405
|
+
if not self.specs[table].is_event_table:
|
|
406
|
+
raise ValueError(f"{table}: the rows of node tables must be given by `table()`")
|
|
407
|
+
if num_rows:
|
|
408
|
+
self._staging[table].append((path, num_rows))
|
|
409
|
+
|
|
410
|
+
def spec(self, table):
|
|
411
|
+
return self.specs[table]
|
|
412
|
+
|
|
413
|
+
def __enter__(self):
|
|
414
|
+
return self
|
|
415
|
+
|
|
416
|
+
def __exit__(self, exc_type, exc, tb):
|
|
417
|
+
if exc_type is not None:
|
|
418
|
+
self.abort()
|
|
419
|
+
elif not self._done:
|
|
420
|
+
try:
|
|
421
|
+
self.finish()
|
|
422
|
+
except BaseException:
|
|
423
|
+
self.abort()
|
|
424
|
+
raise
|
|
425
|
+
return False
|
|
426
|
+
|
|
427
|
+
def abort(self):
|
|
428
|
+
for writer in self._writers.values():
|
|
429
|
+
try:
|
|
430
|
+
writer.close()
|
|
431
|
+
except Exception:
|
|
432
|
+
pass
|
|
433
|
+
shutil.rmtree(self.tmp_dir, ignore_errors=True)
|
|
434
|
+
|
|
435
|
+
def _query(self, db, spec, files):
|
|
436
|
+
"""Query of the rows of a table (with the columns of the table), in the order of its
|
|
437
|
+
files and of their rows, with the serial column of events."""
|
|
438
|
+
if not files:
|
|
439
|
+
cols = ", ".join(f'CAST(NULL AS {DUCKDB_TYPES[k]}) AS "{n}"' for n, k in spec.columns)
|
|
440
|
+
return f"SELECT {cols} LIMIT 0"
|
|
441
|
+
paths = sql_list([path for path, _ in files])
|
|
442
|
+
if not spec.serial:
|
|
443
|
+
# DuckDB keeps the order of the files and of their rows (`preserve_insertion_order`)
|
|
444
|
+
cols = ", ".join(f'"{n}"' for n in spec.names)
|
|
445
|
+
return f"SELECT {cols} FROM read_parquet({paths}, hive_partitioning = false)"
|
|
446
|
+
import pyarrow as pa
|
|
447
|
+
|
|
448
|
+
# The serial column numbers the rows in the order of the files and of their rows
|
|
449
|
+
offsets, total = [], 0
|
|
450
|
+
for _, num_rows in files:
|
|
451
|
+
offsets.append(total)
|
|
452
|
+
total += num_rows
|
|
453
|
+
check_serial(spec, total)
|
|
454
|
+
view = f"_offsets_{spec.name}"
|
|
455
|
+
db.register(view, pa.table({"_file": [p for p, _ in files], "_offset": offsets}))
|
|
456
|
+
kind = DUCKDB_TYPES[dict(spec.columns)[spec.serial]]
|
|
457
|
+
cols = ", ".join(
|
|
458
|
+
f'CAST(o._offset + s.file_row_number + 1 AS {kind}) AS "{n}"'
|
|
459
|
+
if n == spec.serial
|
|
460
|
+
else f's."{n}"'
|
|
461
|
+
for n in spec.names
|
|
462
|
+
)
|
|
463
|
+
return (
|
|
464
|
+
f"SELECT {cols} FROM read_parquet({paths}, hive_partitioning = false, "
|
|
465
|
+
f"filename = true, file_row_number = true) s JOIN {view} o ON s.filename = o._file"
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
def finish(self):
|
|
469
|
+
"""Writes the tables and the manifest, and renames the dataset to its final folder."""
|
|
470
|
+
t0 = time.time()
|
|
471
|
+
for name, writer in self._writers.items():
|
|
472
|
+
# The rows of `table()` come after the files of other processes
|
|
473
|
+
if writer.close():
|
|
474
|
+
self._staging[name].append((writer.path, writer.num_rows))
|
|
475
|
+
duck_tmp = os.path.join(self.tmp_dir, "_duckdb_tmp")
|
|
476
|
+
db = connect_duckdb(duck_tmp, self.threads, self.memory_gb)
|
|
477
|
+
tables = {}
|
|
478
|
+
for name in sorted(self.specs):
|
|
479
|
+
spec, files = self.specs[name], self._staging[name]
|
|
480
|
+
expected = sum(n for _, n in files)
|
|
481
|
+
table_dir = os.path.join(self.tmp_dir, name)
|
|
482
|
+
os.makedirs(table_dir)
|
|
483
|
+
t = time.time()
|
|
484
|
+
query = self._query(db, spec, files)
|
|
485
|
+
if spec.is_event_table:
|
|
486
|
+
if not files:
|
|
487
|
+
raise ValueError(f"No events in {name}")
|
|
488
|
+
order = EVENT_ORDER + (f', "{spec.serial}"' if spec.serial else "")
|
|
489
|
+
info = write_events_by_day(
|
|
490
|
+
db,
|
|
491
|
+
f"({query})",
|
|
492
|
+
spec.names,
|
|
493
|
+
os.path.join(self.tmp_dir, f"_staging_{name}"),
|
|
494
|
+
table_dir,
|
|
495
|
+
self.row_group_size,
|
|
496
|
+
lambda msg: self.log(f"{name}: {msg}"),
|
|
497
|
+
order,
|
|
498
|
+
)
|
|
499
|
+
else:
|
|
500
|
+
path = os.path.join(table_dir, "part-00000.parquet")
|
|
501
|
+
copy_to_parquet(db, query, path, self.row_group_size)
|
|
502
|
+
info = {"files": ["part-00000.parquet"], "order": "insertion"}
|
|
503
|
+
num_rows = count_rows(db, [os.path.join(table_dir, f) for f in info["files"]])
|
|
504
|
+
if num_rows != expected:
|
|
505
|
+
raise RuntimeError(f"{name}: {num_rows} rows written, {expected} given")
|
|
506
|
+
info.update(num_rows=num_rows, columns=[list(c) for c in spec.columns])
|
|
507
|
+
tables[name] = info
|
|
508
|
+
for path, _ in files:
|
|
509
|
+
os.remove(path)
|
|
510
|
+
self.log(
|
|
511
|
+
f"{name}: {num_rows:,} rows, {len(info['files'])} files ({time.time() - t:.0f}s)"
|
|
512
|
+
)
|
|
513
|
+
db.close()
|
|
514
|
+
shutil.rmtree(duck_tmp, ignore_errors=True)
|
|
515
|
+
shutil.rmtree(self.staging_dir, ignore_errors=True)
|
|
516
|
+
write_manifest(self.tmp_dir, os.path.basename(self.dataset_dir), self.source, tables)
|
|
517
|
+
if os.path.exists(self.dataset_dir):
|
|
518
|
+
shutil.rmtree(self.dataset_dir)
|
|
519
|
+
os.rename(self.tmp_dir, self.dataset_dir)
|
|
520
|
+
self._done = True
|
|
521
|
+
size = sum(
|
|
522
|
+
os.path.getsize(os.path.join(root, f))
|
|
523
|
+
for root, _, names in os.walk(self.dataset_dir)
|
|
524
|
+
for f in names
|
|
525
|
+
)
|
|
526
|
+
self.log(
|
|
527
|
+
f"Dataset written to {self.dataset_dir}: {size / 1e9:.2f} GB "
|
|
528
|
+
f"({(time.time() - t0) / 60:.1f} min to sort and write the tables)"
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def update_table(dataset_dir, table, column, value, where, relations=None, note=None, log=print):
|
|
533
|
+
"""`UPDATE table SET column = value WHERE where` on a Parquet dataset: rewrites the files of
|
|
534
|
+
the table in place (rows keep their order). `relations` ({name: Arrow table}) are tables
|
|
535
|
+
that `where` may query. `note` is added to the source of the dataset in its manifest.
|
|
536
|
+
Returns the number of rows matched by `where`."""
|
|
537
|
+
with open(os.path.join(dataset_dir, "manifest.json")) as f:
|
|
538
|
+
manifest = json.load(f)
|
|
539
|
+
info = manifest["tables"][table]
|
|
540
|
+
db = connect_duckdb(os.path.join(dataset_dir, "_duckdb_tmp"))
|
|
541
|
+
for name, relation in (relations or {}).items():
|
|
542
|
+
db.register(name, relation)
|
|
543
|
+
cols = ", ".join(
|
|
544
|
+
f'CAST(CASE WHEN {where} THEN {value} ELSE "{name}" END AS {DUCKDB_TYPES[kind]}) '
|
|
545
|
+
f'AS "{name}"'
|
|
546
|
+
if name == column
|
|
547
|
+
else f'"{name}"'
|
|
548
|
+
for name, kind in info["columns"]
|
|
549
|
+
)
|
|
550
|
+
updated = 0
|
|
551
|
+
for name in info["files"]:
|
|
552
|
+
path = os.path.join(dataset_dir, table, name)
|
|
553
|
+
rows = f"read_parquet({sql_str(path)}, file_row_number = true)"
|
|
554
|
+
n = db.execute(f"SELECT count(*) FROM {rows} WHERE {where};").fetchone()[0]
|
|
555
|
+
if n:
|
|
556
|
+
tmp = path + ".tmp"
|
|
557
|
+
# `where` may be a join, which does not keep the order of the rows
|
|
558
|
+
copy_to_parquet(db, f"SELECT {cols} FROM {rows} ORDER BY file_row_number", tmp)
|
|
559
|
+
if count_rows(db, [tmp]) != count_rows(db, [path]):
|
|
560
|
+
raise RuntimeError(f"{tmp}: wrong number of rows")
|
|
561
|
+
os.replace(tmp, path)
|
|
562
|
+
log(f"{table}/{name}: {n} rows updated")
|
|
563
|
+
updated += n
|
|
564
|
+
db.close()
|
|
565
|
+
shutil.rmtree(os.path.join(dataset_dir, "_duckdb_tmp"), ignore_errors=True)
|
|
566
|
+
if note and note not in manifest["source"]:
|
|
567
|
+
manifest["source"] += f", {note}"
|
|
568
|
+
with open(os.path.join(dataset_dir, "manifest.json"), "w") as f:
|
|
569
|
+
json.dump(manifest, f, indent=2)
|
|
570
|
+
return updated
|