Project

General

Profile

1 53 aaronmk
#!/usr/bin/env python
2
# Maps one datasource to another, using a map spreadsheet if needed
3 986 aaronmk
# Exit status is the # of errors in the import, up to the maximum exit status
4 53 aaronmk
# For outputting an XML file to a PostgreSQL database, use the general format of
5
# http://vegbank.org/vegdocs/xml/vegbank_example_ver1.0.2.xml
6
7 1014 aaronmk
import csv
8 1714 aaronmk
import itertools
9 53 aaronmk
import os.path
10
import sys
11 299 aaronmk
import xml.dom.minidom as minidom
12 53 aaronmk
13 266 aaronmk
sys.path.append(os.path.dirname(__file__)+"/../lib")
14 53 aaronmk
15 1389 aaronmk
import csvs
16 344 aaronmk
import exc
17 1714 aaronmk
import iters
18 1705 aaronmk
import maps
19 64 aaronmk
import opts
20 1859 aaronmk
import parallel
21 281 aaronmk
import Parser
22 982 aaronmk
import profiling
23 131 aaronmk
import sql
24 1758 aaronmk
import streams
25 715 aaronmk
import strings
26 828 aaronmk
import term
27 310 aaronmk
import util
28 1014 aaronmk
import xpath
29 133 aaronmk
import xml_dom
30 86 aaronmk
import xml_func
31 1713 aaronmk
import xml_parse
32 53 aaronmk
33 1404 aaronmk
def get_with_prefix(map_, prefixes, key):
34 1484 aaronmk
    '''Gets all entries for the given key with any of the given prefixes'''
35
    values = []
36 1681 aaronmk
    for key_ in strings.with_prefixes(['']+prefixes, key): # also with no prefix
37
        try: value = map_[key_]
38 1484 aaronmk
        except KeyError, e: continue # keep going
39
        values.append(value)
40
41
    if values != []: return values
42
    else: raise e # re-raise last KeyError
43 1404 aaronmk
44 1018 aaronmk
def metadata_value(name): return None # this feature has been removed
45 84 aaronmk
46 1360 aaronmk
def cleanup(val):
47
    if val == None: return val
48 1374 aaronmk
    return util.none_if(strings.cleanup(strings.ustr(val)), u'', u'\\N')
49 1360 aaronmk
50 847 aaronmk
def main_():
51 131 aaronmk
    env_names = []
52
    def usage_err():
53 944 aaronmk
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)+' '
54 847 aaronmk
            +sys.argv[0]+' [map_path...] [<input] [>output]')
55 838 aaronmk
56 1570 aaronmk
    ## Get config from env vars
57 838 aaronmk
58 1570 aaronmk
    # Modes
59 946 aaronmk
    test = opts.env_flag('test', False, env_names)
60 947 aaronmk
    commit = opts.env_flag('commit', False, env_names) and not test
61 944 aaronmk
        # never commit in test mode
62 947 aaronmk
    redo = opts.env_flag('redo', test, env_names) and not commit
63
        # never redo in commit mode (manually run `make empty_db` instead)
64 1570 aaronmk
65
    # Ranges
66
    start = util.cast(int, opts.get_env_var('start', '0', env_names))
67 1572 aaronmk
    if test: end_default = 1
68
    else: end_default = None
69
    end = util.cast(int, util.none_if(
70
        opts.get_env_var('n', end_default, env_names), u''))
71 1570 aaronmk
    if end != None: end += start
72
73 1846 aaronmk
    # Optimization
74 1851 aaronmk
    if test: cpus_default = 0
75
    else: cpus_default = None
76 1856 aaronmk
    cpus = util.cast(int, util.none_if(opts.get_env_var('cpus', cpus_default,
77
        env_names), u''))
78 1846 aaronmk
79 1570 aaronmk
    # Debugging
80 946 aaronmk
    debug = opts.env_flag('debug', False, env_names)
81 859 aaronmk
    sql.run_raw_query.debug = debug
82 1574 aaronmk
    verbose = debug or opts.env_flag('verbose', not test, env_names)
83 944 aaronmk
    opts.get_env_var('profile_to', None, env_names) # add to env_names
84 131 aaronmk
85 1570 aaronmk
    # DB
86
    db_config_names = ['engine', 'host', 'user', 'password', 'database']
87
    def get_db_config(prefix):
88
        return opts.get_env_vars(db_config_names, prefix, env_names)
89
    in_db_config = get_db_config('in')
90
    out_db_config = get_db_config('out')
91
    in_is_db = 'engine' in in_db_config
92
    out_is_db = 'engine' in out_db_config
93
94
    ##
95
96 838 aaronmk
    # Logging
97 662 aaronmk
    def log(msg, on=verbose):
98 1901 aaronmk
        if on: sys.stderr.write(msg+'\n')
99
    if debug: log_debug = lambda msg: log(msg, debug)
100
    else: log_debug = sql.log_debug_none
101 662 aaronmk
102 53 aaronmk
    # Parse args
103 510 aaronmk
    map_paths = sys.argv[1:]
104 512 aaronmk
    if map_paths == []:
105
        if in_is_db or not out_is_db: usage_err()
106
        else: map_paths = [None]
107 53 aaronmk
108 646 aaronmk
    def connect_db(db_config):
109 1901 aaronmk
        log('Connecting to '+sql.db_config_str(db_config))
110
        return sql.connect(db_config, log_debug=log_debug)
111 646 aaronmk
112 1573 aaronmk
    if end != None: end_str = str(end-1)
113
    else: end_str = 'end'
114 1901 aaronmk
    log('Processing input rows '+str(start)+'-'+end_str)
115 1573 aaronmk
116 1014 aaronmk
    ex_tracker = exc.ExPercentTracker(iter_text='row')
117
    profiler = profiling.ItersProfiler(start_now=True, iter_text='row')
118
119 1856 aaronmk
    # Parallel processing
120 1862 aaronmk
    pool = parallel.MultiProducerPool(cpus)
121 1901 aaronmk
    log('Using '+str(pool.process_ct)+' parallel CPUs')
122 1846 aaronmk
123 1014 aaronmk
    doc = xml_dom.create_doc()
124
    root = doc.documentElement
125 751 aaronmk
    out_is_xml_ref = [False]
126 1014 aaronmk
    in_label_ref = [None]
127
    def update_in_label():
128
        if in_label_ref[0] != None:
129
            xpath.get(root, '/_ignore/inLabel="'+in_label_ref[0]+'"', True)
130
    def prep_root():
131
        root.clear()
132
        update_in_label()
133
    prep_root()
134 751 aaronmk
135 838 aaronmk
    def process_input(root, row_ready, map_path):
136 512 aaronmk
        '''Inputs datasource to XML tree, mapping if needed'''
137
        # Load map header
138
        in_is_xpaths = True
139 751 aaronmk
        out_is_xpaths = True
140 512 aaronmk
        out_label = None
141
        if map_path != None:
142
            metadata = []
143
            mappings = []
144
            stream = open(map_path, 'rb')
145
            reader = csv.reader(stream)
146
            in_label, out_label = reader.next()[:2]
147 1402 aaronmk
148 512 aaronmk
            def split_col_name(name):
149 1402 aaronmk
                label, sep, root = name.partition(':')
150
                label, sep2, prefixes_str = label.partition('[')
151
                prefixes_str = strings.remove_suffix(']', prefixes_str)
152
                prefixes = strings.split(',', prefixes_str)
153
                return label, sep != '', root, prefixes
154 1198 aaronmk
                    # extract datasrc from "datasrc[data_format]"
155 1402 aaronmk
156 1705 aaronmk
            in_label, in_root, prefixes = maps.col_info(in_label)
157
            in_is_xpaths = in_root != None
158 1014 aaronmk
            in_label_ref[0] = in_label
159
            update_in_label()
160 1705 aaronmk
            out_label, out_root = maps.col_info(out_label)[:2]
161
            out_is_xpaths = out_root != None
162 1841 aaronmk
            if out_is_xpaths: has_types = out_root.find('/*s/') >= 0
163 1705 aaronmk
                # outer elements are types
164 1402 aaronmk
165 512 aaronmk
            for row in reader:
166
                in_, out = row[:2]
167
                if out != '':
168
                    if out_is_xpaths: out = xpath.parse(out_root+out)
169
                    mappings.append((in_, out))
170 1402 aaronmk
171 512 aaronmk
            stream.close()
172
173
            root.ownerDocument.documentElement.tagName = out_label
174
        in_is_xml = in_is_xpaths and not in_is_db
175 751 aaronmk
        out_is_xml_ref[0] = out_is_xpaths and not out_is_db
176 56 aaronmk
177 1897 aaronmk
        def process_rows(process_row, rows, rows_start=0):
178
            '''Processes input rows
179 838 aaronmk
            @param process_row(in_row, i)
180 1897 aaronmk
            @rows_start The row # of the first row in rows. Set this only if the
181
                pre-start rows have already been skipped.
182 297 aaronmk
            '''
183 1897 aaronmk
            rows = iter(rows)
184
185
            if end != None: row_nums = xrange(rows_start, end)
186
            else: row_nums = itertools.count(rows_start)
187
            for i in row_nums:
188 1718 aaronmk
                try: row = rows.next()
189
                except StopIteration: break # no more rows
190
                if i < start: continue # not at start row yet
191
192 838 aaronmk
                process_row(row, i)
193
                row_ready(i, row)
194 1718 aaronmk
            row_ct = i-start
195 982 aaronmk
            return row_ct
196 838 aaronmk
197 1898 aaronmk
        def map_rows(get_value, rows, **kw_args):
198 838 aaronmk
            '''Maps input rows
199
            @param get_value(in_, row):str
200
            '''
201
            def process_row(row, i):
202 316 aaronmk
                row_id = str(i)
203
                for in_, out in mappings:
204
                    value = metadata_value(in_)
205 662 aaronmk
                    if value == None:
206 1901 aaronmk
                        log_debug('Getting '+str(in_))
207 1360 aaronmk
                        value = cleanup(get_value(in_, row))
208 1348 aaronmk
                    if value != None:
209 1901 aaronmk
                        log_debug('Putting '+str(out))
210 1360 aaronmk
                        xpath.put_obj(root, out, row_id, has_types, value)
211 1898 aaronmk
            return process_rows(process_row, rows, **kw_args)
212 297 aaronmk
213 1898 aaronmk
        def map_table(col_names, rows, **kw_args):
214 1416 aaronmk
            col_names_ct = len(col_names)
215 1403 aaronmk
            col_idxs = util.list_flip(col_names)
216
217
            i = 0
218
            while i < len(mappings): # mappings len changes in loop
219
                in_, out = mappings[i]
220
                if metadata_value(in_) == None:
221 1404 aaronmk
                    try: mappings[i] = (
222
                        get_with_prefix(col_idxs, prefixes, in_), out)
223
                    except KeyError:
224
                        del mappings[i]
225
                        continue # keep i the same
226 1403 aaronmk
                i += 1
227
228
            def get_value(in_, row):
229 1484 aaronmk
                return util.coalesce(*util.list_subset(row.list, in_))
230 1416 aaronmk
            def wrap_row(row):
231
                return util.ListDict(util.list_as_length(row, col_names_ct),
232
                    col_names, col_idxs) # handle CSV rows of different lengths
233 1403 aaronmk
234 1898 aaronmk
            return map_rows(get_value, util.WrapIter(wrap_row, rows), **kw_args)
235 1403 aaronmk
236 1758 aaronmk
        stdin = streams.LineCountStream(sys.stdin)
237
        def on_error(e):
238
            exc.add_msg(e, term.emph('input line #:')+' '+str(stdin.line_num))
239
            ex_tracker.track(e)
240
241 1700 aaronmk
        if in_is_db:
242 130 aaronmk
            assert in_is_xpaths
243 126 aaronmk
244 1136 aaronmk
            in_db = connect_db(in_db_config)
245 1898 aaronmk
            cur = sql.select(in_db, table=in_root, limit=end, start=start)
246
            row_ct = map_table(list(sql.col_names(cur)), sql.rows(cur),
247
                rows_start=start) # rows_start: pre-start rows have been skipped
248 1136 aaronmk
249 1849 aaronmk
            in_db.db.close()
250 161 aaronmk
        elif in_is_xml:
251 1715 aaronmk
            def get_rows(doc2rows):
252 1758 aaronmk
                return iters.flatten(itertools.imap(doc2rows,
253
                    xml_parse.docs_iter(stdin, on_error)))
254 1715 aaronmk
255 1714 aaronmk
            if map_path == None:
256 1715 aaronmk
                def doc2rows(in_xml_root):
257 1701 aaronmk
                    iter_ = xml_dom.NodeElemIter(in_xml_root)
258
                    util.skip(iter_, xml_dom.is_text) # skip metadata
259 1715 aaronmk
                    return iter_
260
261
                row_ct = process_rows(lambda row, i: root.appendChild(row),
262
                    get_rows(doc2rows))
263 1714 aaronmk
            else:
264 1715 aaronmk
                def doc2rows(in_xml_root):
265 1701 aaronmk
                    rows = xpath.get(in_xml_root, in_root, limit=end)
266 1714 aaronmk
                    if rows == []: raise SystemExit('Map error: Root "'
267
                        +in_root+'" not found in input')
268
                    return rows
269
270
                def get_value(in_, row):
271
                    in_ = './{'+(','.join(strings.with_prefixes(
272
                        ['']+prefixes, in_)))+'}' # also with no prefix
273
                    nodes = xpath.get(row, in_, allow_rooted=False)
274
                    if nodes != []: return xml_dom.value(nodes[0])
275
                    else: return None
276
277 1715 aaronmk
                row_ct = map_rows(get_value, get_rows(doc2rows))
278 56 aaronmk
        else: # input is CSV
279 133 aaronmk
            map_ = dict(mappings)
280 1389 aaronmk
            reader, col_names = csvs.reader_and_header(sys.stdin)
281 1403 aaronmk
            row_ct = map_table(col_names, reader)
282 982 aaronmk
283
        return row_ct
284 53 aaronmk
285 838 aaronmk
    def process_inputs(root, row_ready):
286 982 aaronmk
        row_ct = 0
287
        for map_path in map_paths:
288
            row_ct += process_input(root, row_ready, map_path)
289
        return row_ct
290 512 aaronmk
291 1886 aaronmk
    pool.share_vars(locals())
292 130 aaronmk
    if out_is_db:
293 53 aaronmk
        import db_xml
294
295 646 aaronmk
        out_db = connect_db(out_db_config)
296 53 aaronmk
        try:
297 947 aaronmk
            if redo: sql.empty_db(out_db)
298 982 aaronmk
            row_ins_ct_ref = [0]
299 1886 aaronmk
            pool.share_vars(locals())
300 449 aaronmk
301 838 aaronmk
            def row_ready(row_num, input_row):
302 452 aaronmk
                def on_error(e):
303 835 aaronmk
                    exc.add_msg(e, term.emph('row #:')+' '+str(row_num))
304 828 aaronmk
                    exc.add_msg(e, term.emph('input row:')+'\n'+str(input_row))
305
                    exc.add_msg(e, term.emph('output row:')+'\n'+str(root))
306 1617 aaronmk
                    ex_tracker.track(e, row_num)
307 1886 aaronmk
                pool.share_vars(locals())
308 452 aaronmk
309 449 aaronmk
                xml_func.process(root, on_error)
310 442 aaronmk
                if not xml_dom.is_empty(root):
311
                    assert xml_dom.has_one_child(root)
312
                    try:
313 982 aaronmk
                        sql.with_savepoint(out_db,
314
                            lambda: db_xml.put(out_db, root.firstChild,
315 1850 aaronmk
                                row_ins_ct_ref, on_error))
316 1849 aaronmk
                        if commit: out_db.db.commit()
317 449 aaronmk
                    except sql.DatabaseErrors, e: on_error(e)
318 1010 aaronmk
                prep_root()
319 449 aaronmk
320 982 aaronmk
            row_ct = process_inputs(root, row_ready)
321
            sys.stdout.write('Inserted '+str(row_ins_ct_ref[0])+
322 460 aaronmk
                ' new rows into database\n')
323 1868 aaronmk
324
            # Consume asynchronous tasks
325
            pool.main_loop()
326 53 aaronmk
        finally:
327 1849 aaronmk
            out_db.db.rollback()
328
            out_db.db.close()
329 751 aaronmk
    else:
330 759 aaronmk
        def on_error(e): ex_tracker.track(e)
331 838 aaronmk
        def row_ready(row_num, input_row): pass
332 982 aaronmk
        row_ct = process_inputs(root, row_ready)
333 759 aaronmk
        xml_func.process(root, on_error)
334 751 aaronmk
        if out_is_xml_ref[0]:
335
            doc.writexml(sys.stdout, **xml_dom.prettyxml_config)
336
        else: # output is CSV
337
            raise NotImplementedError('CSV output not supported yet')
338 985 aaronmk
339 1868 aaronmk
    # Consume any asynchronous tasks not already consumed above
340 1862 aaronmk
    pool.main_loop()
341
342 982 aaronmk
    profiler.stop(row_ct)
343
    ex_tracker.add_iters(row_ct)
344 990 aaronmk
    if verbose:
345
        sys.stderr.write('Processed '+str(row_ct)+' input rows\n')
346
        sys.stderr.write(profiler.msg()+'\n')
347
        sys.stderr.write(ex_tracker.msg()+'\n')
348 985 aaronmk
    ex_tracker.exit()
349 53 aaronmk
350 847 aaronmk
def main():
351
    try: main_()
352 1719 aaronmk
    except Parser.SyntaxError, e: raise SystemExit(str(e))
353 847 aaronmk
354 846 aaronmk
if __name__ == '__main__':
355 847 aaronmk
    profile_to = opts.get_env_var('profile_to', None)
356
    if profile_to != None:
357
        import cProfile
358 1584 aaronmk
        sys.stderr.write('Profiling to '+profile_to+'\n')
359 847 aaronmk
        cProfile.run(main.func_code, profile_to)
360
    else: main()