|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from __future__ import absolute_import |
| 3 | +from __future__ import division |
| 4 | +from __future__ import print_function |
| 5 | + |
| 6 | +"""Script to predict with a fully trained model. |
| 7 | +
|
| 8 | +Reads one source (TTL syntax) per line from stdin and writes one JSON line to |
| 9 | +stdout. |
| 10 | +""" |
| 11 | + |
| 12 | +import json |
| 13 | +import logging |
| 14 | +import sys |
| 15 | + |
| 16 | +import SPARQLWrapper |
| 17 | +from rdflib.util import from_n3 |
| 18 | + |
| 19 | + |
| 20 | +# noinspection PyUnresolvedReferences |
| 21 | +import logging_config |
| 22 | + |
| 23 | +# not all import on top due to scoop and init... |
| 24 | + |
| 25 | +logger = logging.getLogger(__name__) |
| 26 | + |
| 27 | + |
| 28 | +def predict(sparql, timeout, gps, source, |
| 29 | + fusion_methods=None, max_results=0, max_target_candidates_per_gp=0): |
| 30 | + from fusion import fuse_prediction_results |
| 31 | + from gp_learner import predict_target_candidates |
| 32 | + |
| 33 | + gp_tcs = predict_target_candidates(sparql, timeout, gps, source) |
| 34 | + fused_results = fuse_prediction_results( |
| 35 | + gps, |
| 36 | + gp_tcs, |
| 37 | + fusion_methods |
| 38 | + ) |
| 39 | + orig_length = max([len(v) for k, v in fused_results.items()]) |
| 40 | + if max_results > 0: |
| 41 | + for k, v in fused_results.items(): |
| 42 | + del v[max_results:] |
| 43 | + mt = max_target_candidates_per_gp |
| 44 | + if mt < 1: |
| 45 | + mt = None |
| 46 | + # logger.info(gp_tcs) |
| 47 | + res = { |
| 48 | + 'source': source, |
| 49 | + 'orig_result_length': orig_length, |
| 50 | + 'graph_pattern_target_candidates': [sorted(tcs)[:mt] for tcs in gp_tcs], |
| 51 | + 'fused_results': fused_results, |
| 52 | + } |
| 53 | + return res |
| 54 | + |
| 55 | + |
| 56 | +def parse_args(): |
| 57 | + import argparse |
| 58 | + |
| 59 | + parser = argparse.ArgumentParser( |
| 60 | + description='gp learner prediction', |
| 61 | + formatter_class=argparse.ArgumentDefaultsHelpFormatter, |
| 62 | + ) |
| 63 | + |
| 64 | + parser.add_argument( |
| 65 | + "--sparql_endpoint", |
| 66 | + help="the SPARQL endpoint to query", |
| 67 | + action="store", |
| 68 | + default=config.SPARQL_ENDPOINT, |
| 69 | + ) |
| 70 | + parser.add_argument( |
| 71 | + "--max_queries", |
| 72 | + help="limits the amount of queries per prediction (0: no limit). " |
| 73 | + "You want to use the same limit as in training for late fusion " |
| 74 | + "models.", |
| 75 | + action="store", |
| 76 | + type=int, |
| 77 | + default=100, |
| 78 | + ) |
| 79 | + parser.add_argument( |
| 80 | + "--clustering_variant", |
| 81 | + help="if specified use this clustering variant for query reduction, " |
| 82 | + "otherwise select the best from various.", |
| 83 | + action="store", |
| 84 | + type=str, |
| 85 | + default=None, |
| 86 | + ) |
| 87 | + parser.add_argument( |
| 88 | + "--fusion_methods", |
| 89 | + help="Which fusion methods to use. During prediction, each of " |
| 90 | + "the learned patterns can generate a list of target candidates. " |
| 91 | + "Fusion re-combines these into a single ranked list of " |
| 92 | + "predicted targets. By default this will use all " |
| 93 | + "implemented fusion methods. Any of them, or a ',' delimited list " |
| 94 | + "can be used to reduce the output (just make sure you ran " |
| 95 | + "--predict=train_set on them before). Also supports 'basic' and " |
| 96 | + "'classifier' as shorthands. Make sure to only select methods the " |
| 97 | + "selected model was also trained on!", |
| 98 | + action="store", |
| 99 | + type=str, |
| 100 | + default=None, |
| 101 | + ) |
| 102 | + |
| 103 | + parser.add_argument( |
| 104 | + "--timeout", |
| 105 | + help="sets the timeout in seconds for each query (0: auto calibrate)", |
| 106 | + action="store", |
| 107 | + type=float, |
| 108 | + default=2., |
| 109 | + ) |
| 110 | + parser.add_argument( |
| 111 | + "--max_results", |
| 112 | + help="limits the result list lengths to save bandwidth (0: no limit)", |
| 113 | + action="store", |
| 114 | + type=int, |
| 115 | + default=100, |
| 116 | + ) |
| 117 | + parser.add_argument( |
| 118 | + "--max_target_candidates_per_gp", |
| 119 | + help="limits the target candidate list lengths to save bandwidth " |
| 120 | + "(0: no limit)", |
| 121 | + action="store", |
| 122 | + type=int, |
| 123 | + default=100, |
| 124 | + ) |
| 125 | + |
| 126 | + parser.add_argument( |
| 127 | + "resdir", |
| 128 | + help="result directory of the trained model (overrides --RESDIR)", |
| 129 | + action="store", |
| 130 | + ) |
| 131 | + |
| 132 | + |
| 133 | + cfg_group = parser.add_argument_group( |
| 134 | + 'Advanced config overrides', |
| 135 | + 'The following allow overriding default values from config/defaults.py' |
| 136 | + ) |
| 137 | + config.arg_parse_config_vars(cfg_group) |
| 138 | + |
| 139 | + prog_args = vars(parser.parse_args()) |
| 140 | + # the following were aliased above, make sure they're updated globally |
| 141 | + prog_args.update({ |
| 142 | + 'SPARQL_ENDPOINT': prog_args['sparql_endpoint'], |
| 143 | + 'RESDIR': prog_args['resdir'], |
| 144 | + }) |
| 145 | + config.finalize(prog_args) |
| 146 | + |
| 147 | + return prog_args |
| 148 | + |
| 149 | + |
| 150 | + |
| 151 | +def main( |
| 152 | + resdir, |
| 153 | + sparql_endpoint, |
| 154 | + max_queries, |
| 155 | + clustering_variant, |
| 156 | + fusion_methods, |
| 157 | + timeout, |
| 158 | + max_results, |
| 159 | + max_target_candidates_per_gp, |
| 160 | + **_ # gulp remaining kwargs |
| 161 | +): |
| 162 | + from gp_query import calibrate_query_timeout |
| 163 | + from serialization import load_results |
| 164 | + from serialization import find_last_result |
| 165 | + from cluster import cluster_gps_to_reduce_queries |
| 166 | + from gp_learner import init_workers |
| 167 | + |
| 168 | + # init workers |
| 169 | + init_workers() |
| 170 | + |
| 171 | + sparql = SPARQLWrapper.SPARQLWrapper(sparql_endpoint) |
| 172 | + timeout = timeout if timeout > 0 else calibrate_query_timeout(sparql) |
| 173 | + |
| 174 | + # load model |
| 175 | + last_res = find_last_result() |
| 176 | + if not last_res: |
| 177 | + logger.error('cannot find fully trained model in %s', resdir) |
| 178 | + sys.exit(1) |
| 179 | + result_patterns, coverage_counts, gtp_scores = load_results(last_res) |
| 180 | + gps = [gp for gp, _ in result_patterns] |
| 181 | + gps = cluster_gps_to_reduce_queries( |
| 182 | + gps, max_queries, gtp_scores, clustering_variant) |
| 183 | + |
| 184 | + # main loop |
| 185 | + for line in sys.stdin: |
| 186 | + line = line.strip() |
| 187 | + if not line: |
| 188 | + continue |
| 189 | + if line[0] not in '<"': |
| 190 | + logger.error( |
| 191 | + 'expected inputs to start with < or ", but got: %s', line) |
| 192 | + sys.exit(1) |
| 193 | + source = from_n3(line) |
| 194 | + |
| 195 | + res = predict( |
| 196 | + sparql, timeout, gps, source, fusion_methods, |
| 197 | + max_results, max_target_candidates_per_gp |
| 198 | + ) |
| 199 | + print(json.dumps(res)) |
| 200 | + |
| 201 | + |
| 202 | +if __name__ == "__main__": |
| 203 | + logger.info('init run: origin') |
| 204 | + import config |
| 205 | + prog_kwds = parse_args() |
| 206 | + main(**prog_kwds) |
| 207 | +else: |
| 208 | + logger.info('init run: worker') |
0 commit comments