|
| 1 | +import json |
| 2 | +import superstyl |
| 3 | +import pandas as pd |
| 4 | +import os |
| 5 | + |
| 6 | +from superstyl.load import load_corpus |
| 7 | + |
| 8 | +def load_corpus_from_config(config_path): |
| 9 | + """ |
| 10 | + Load a corpus based on a JSON configuration file. |
| 11 | + |
| 12 | + Parameters: |
| 13 | + ----------- |
| 14 | + config_path : str |
| 15 | + Path to the JSON configuration file |
| 16 | + |
| 17 | + Returns: |
| 18 | + -------- |
| 19 | + tuple: (corpus, feat_list) - Same format as load_corpus function |
| 20 | + If multiple features are defined, returns the merged corpus and the combined feature list |
| 21 | + If only one feature is defined, returns that corpus and its feature list |
| 22 | + """ |
| 23 | + # Load configuration |
| 24 | + if not config_path.endswith('.json'): |
| 25 | + raise ValueError(f"Unsupported configuration file format: {config_path}. Only JSON format is supported.") |
| 26 | + |
| 27 | + with open(config_path, 'r') as f: |
| 28 | + config = json.load(f) |
| 29 | + |
| 30 | + # Get corpus paths |
| 31 | + if 'paths' in config: |
| 32 | + if isinstance(config['paths'], list): |
| 33 | + paths = config['paths'] |
| 34 | + elif isinstance(config['paths'], str): |
| 35 | + paths = [config['paths']] |
| 36 | + else: |
| 37 | + raise ValueError("Paths in config must be either a list or a glob pattern string") |
| 38 | + else: |
| 39 | + raise ValueError("No paths provided and no paths found in config") |
| 40 | + |
| 41 | + # Get sampling parameters |
| 42 | + sampling_params = config.get('sampling', {}) |
| 43 | + |
| 44 | + # Use the first feature to create the base corpus with sampling |
| 45 | + feature_configs = config.get('features', []) |
| 46 | + if not feature_configs: |
| 47 | + raise ValueError("No features specified in the configuration") |
| 48 | + |
| 49 | + # If there's only one feature, we can simply return the result of load_corpus |
| 50 | + if len(feature_configs) == 1: |
| 51 | + feature_config = feature_configs[0] |
| 52 | + feature_name = feature_config.get('name', "f1") |
| 53 | + |
| 54 | + # Check for feature list file |
| 55 | + feat_list = None |
| 56 | + feat_list_path = feature_config.get('feat_list') |
| 57 | + if feat_list_path: |
| 58 | + if feat_list_path.endswith('.json'): |
| 59 | + with open(feat_list_path, 'r') as f: |
| 60 | + feat_list = json.load(f) |
| 61 | + elif feat_list_path.endswith('.txt'): |
| 62 | + with open(feat_list_path, 'r') as f: |
| 63 | + feat_list = [[feat.strip(), 0] for feat in f.readlines()] |
| 64 | + |
| 65 | + # Set up other parameters |
| 66 | + params = { |
| 67 | + 'feats': feature_config.get('type', 'words'), |
| 68 | + 'n': feature_config.get('n', 1), |
| 69 | + 'k': feature_config.get('k', 5000), |
| 70 | + 'freqsType': feature_config.get('freq_type', 'relative'), |
| 71 | + 'format': config.get('format', 'txt'), |
| 72 | + 'sampling': sampling_params.get('enabled', False), |
| 73 | + 'units': sampling_params.get('units', 'words'), |
| 74 | + 'size': sampling_params.get('sample_size', 3000), |
| 75 | + 'step': sampling_params.get('sample_step', None), |
| 76 | + 'max_samples': sampling_params.get('max_samples', None), |
| 77 | + 'samples_random': sampling_params.get('sample_random', False), |
| 78 | + 'keep_punct': feature_config.get('keep_punct', False), |
| 79 | + 'keep_sym': feature_config.get('keep_sym', False), |
| 80 | + 'no_ascii': feature_config.get('no_ascii', False), |
| 81 | + 'identify_lang': feature_config.get('identify_lang', False), |
| 82 | + 'embedding': feature_config.get('embedding', None), |
| 83 | + 'neighbouring_size': feature_config.get('neighbouring_size', 10), |
| 84 | + 'culling': feature_config.get('culling', 0) |
| 85 | + } |
| 86 | + |
| 87 | + print(f"Loading corpus with {feature_name}...") |
| 88 | + corpus, features = load_corpus(paths, feat_list=feat_list, **params) |
| 89 | + |
| 90 | + return corpus, features |
| 91 | + |
| 92 | + # For multiple features, we need to process each one and merge the results |
| 93 | + corpora = {} |
| 94 | + feature_lists = {} |
| 95 | + |
| 96 | + # Process each feature configuration |
| 97 | + for i, feature_config in enumerate(feature_configs): |
| 98 | + feature_name = feature_config.get('name', f"f{i+1}") |
| 99 | + |
| 100 | + # Check for feature list file |
| 101 | + feat_list = None |
| 102 | + feat_list_path = feature_config.get('feat_list') |
| 103 | + if feat_list_path: |
| 104 | + if feat_list_path.endswith('.json'): |
| 105 | + with open(feat_list_path, 'r') as f: |
| 106 | + feat_list = json.load(f) |
| 107 | + elif feat_list_path.endswith('.txt'): |
| 108 | + with open(feat_list_path, 'r') as f: |
| 109 | + feat_list = [[feat.strip(), 0] for feat in f.readlines()] |
| 110 | + |
| 111 | + # Set up other parameters |
| 112 | + params = { |
| 113 | + 'feats': feature_config.get('type', 'words'), |
| 114 | + 'n': feature_config.get('n', 1), |
| 115 | + 'k': feature_config.get('k', 5000), |
| 116 | + 'freqsType': feature_config.get('freq_type', 'relative'), |
| 117 | + 'format': config.get('format', 'txt'), |
| 118 | + 'sampling': sampling_params.get('enabled', False), |
| 119 | + 'units': sampling_params.get('units', 'words'), |
| 120 | + 'size': sampling_params.get('sample_size', 3000), |
| 121 | + 'step': sampling_params.get('sample_step', None), |
| 122 | + 'max_samples': sampling_params.get('max_samples', None), |
| 123 | + 'samples_random': sampling_params.get('sample_random', False), |
| 124 | + 'keep_punct': config.get('keep_punct', False), |
| 125 | + 'keep_sym': config.get('keep_sym', False), |
| 126 | + 'no_ascii': config.get('no_ascii', False), |
| 127 | + 'identify_lang': config.get('identify_lang', False), |
| 128 | + 'embedding': feature_config.get('embedding', None), |
| 129 | + 'neighbouring_size': feature_config.get('neighbouring_size', 10), |
| 130 | + 'culling': feature_config.get('culling', 0) |
| 131 | + } |
| 132 | + |
| 133 | + print(f"Loading {feature_name}...") |
| 134 | + corpus, features = load_corpus(paths, feat_list=feat_list, **params) |
| 135 | + |
| 136 | + # Store corpus and features |
| 137 | + corpora[feature_name] = corpus |
| 138 | + feature_lists[feature_name] = features |
| 139 | + |
| 140 | + # Create a merged dataset |
| 141 | + print("Creating merged dataset...") |
| 142 | + first_corpus_name = next(iter(corpora)) |
| 143 | + |
| 144 | + # Start with metadata from the first corpus |
| 145 | + metadata = corpora[first_corpus_name][['author', 'lang']] |
| 146 | + |
| 147 | + # Create an empty DataFrame for the merged corpus |
| 148 | + merged = pd.DataFrame(index=metadata.index) |
| 149 | + |
| 150 | + # Add metadata |
| 151 | + merged = pd.concat([metadata, merged], axis=1) |
| 152 | + |
| 153 | + # Combine all features with prefixes to avoid name collisions |
| 154 | + all_features = [] |
| 155 | + |
| 156 | + # Add features from each corpus |
| 157 | + for name, corpus in corpora.items(): |
| 158 | + feature_cols = [col for col in corpus.columns if col not in ['author', 'lang']] |
| 159 | + |
| 160 | + # Rename columns to avoid duplicates |
| 161 | + renamed_cols = {col: f"{name}_{col}" for col in feature_cols} |
| 162 | + feature_df = corpus[feature_cols].rename(columns=renamed_cols) |
| 163 | + |
| 164 | + # Merge with the main DataFrame |
| 165 | + merged = pd.concat([merged, feature_df], axis=1) |
| 166 | + |
| 167 | + # Add features to the combined list with prefixes |
| 168 | + for feature in feature_lists[name]: |
| 169 | + all_features.append((f"{name}_{feature[0]}", feature[1])) |
| 170 | + |
| 171 | + # Return the merged corpus and combined feature list |
| 172 | + return merged, all_features |
| 173 | + |
0 commit comments