-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbuild_db.py
136 lines (108 loc) · 4.58 KB
/
build_db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#!/usr/bin/env python3
# The codes are started from DrQA (https://github.com/facebookresearch/DrQA) library.
"""A script to read in and store documents in a sqlite database."""
import argparse
import sqlite3
import json
import os
import logging
import importlib.util
import glob
import csv
from utils import process_jsonlines
from multiprocessing import Pool as ProcessPool
from tqdm import tqdm
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fmt = logging.Formatter('%(asctime)s: [ %(message)s ]', '%m/%d/%Y %I:%M:%S %p')
console = logging.StreamHandler()
console.setFormatter(fmt)
logger.addHandler(console)
# ------------------------------------------------------------------------------
# Import helper
# ------------------------------------------------------------------------------
PREPROCESS_FN = None
def init(filename):
global PREPROCESS_FN
if filename:
PREPROCESS_FN = import_module(filename).preprocess
def import_module(filename):
"""Import a module given a full path to the file."""
spec = importlib.util.spec_from_file_location('doc_filter', filename)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
# ------------------------------------------------------------------------------
# Store corpus.
# ------------------------------------------------------------------------------
def iter_files(path):
"""Walk through all files located under a root path."""
if os.path.isfile(path):
yield path
elif os.path.isdir(path):
for dirpath, _, filenames in os.walk(path):
for f in filenames:
yield os.path.join(dirpath, f)
else:
raise RuntimeError('Path %s is invalid' % path)
def get_contents(filename):
"""Parse the contents of a file. Each line is a JSON encoded document."""
global PREPROCESS_FN
documents = []
extracted_items = process_jsonlines(filename)
for extracted_item in extracted_items:
wiki_id = extracted_item["wiki_id"]
title = extracted_item["title"]
text = extracted_item["text"]
documents.append((title, text, wiki_id))
return documents
def store_contents(wiki_dir, save_path, preprocess, num_workers=None, lang=None):
"""Preprocess and store a corpus of documents in sqlite.
Args:
data_path: Root path to directory (or directory of directories) of files
containing json encoded documents (must have `id` and `text` fields).
save_path: Path to output sqlite db.
preprocess: Path to file defining a custom `preprocess` function. Takes
in and outputs a structured doc.
num_workers: Number of parallel processes to use when reading docs.
"""
filenames = [f for f in glob.glob(
wiki_dir + "/*/wiki_*", recursive=True) if ".bz2" not in f]
if os.path.isfile(save_path):
raise RuntimeError('%s already exists! Not overwriting.' % save_path)
logger.info('Reading into database...')
conn = sqlite3.connect(save_path)
c = conn.cursor()
c.execute(
"CREATE TABLE documents (id PRIMARY KEY, text, wiki_id);")
workers = ProcessPool(num_workers, initializer=init,
initargs=(preprocess,))
count = 0
content_processing_method = get_contents
with tqdm(total=len(filenames)) as pbar:
for pairs in tqdm(workers.imap_unordered(content_processing_method, filenames)):
count += len(pairs)
c.executemany(
"INSERT OR REPLACE INTO documents VALUES (?,?,?)", pairs)
pbar.update()
logger.info('Read %d docs.' % count)
logger.info('Committing...')
conn.commit()
conn.close()
# ------------------------------------------------------------------------------
# Main.
# ------------------------------------------------------------------------------
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('wiki_dir', type=str, help='/path/to/data')
parser.add_argument('save_path', type=str, help='/path/to/saved/db.db')
parser.add_argument('--preprocess', type=str, default=None,
help=('File path to a python module that defines '
'a `preprocess` function'))
parser.add_argument('--num-workers', type=int, default=None,
help='Number of CPU processes (for tokenizing, etc)')
parser.add_argument('--lang', type=str, default=None,
help='language_code')
args = parser.parse_args()
store_contents(
args.wiki_dir, args.save_path, args.preprocess, args.num_workers)