Skip to content

processing

logger = get_logger() module-attribute

create_default_search_index(path=None, force=True)

Source code in datasets/tasks/processing.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
@shared_task()
def create_default_search_index(
    path: str = None,
    force: bool = True,
):
    logger.info(f"Creating default search index")

    search_index_dir = DEFAULT_SEARCH_INDEX
    if search_index_dir.exists():
        if force:
            logger.info(f"Removing existing search index at {search_index_dir}")
            shutil.rmtree(search_index_dir)
        else:
            logger.info(f"Default search index already exists")
            return

    search_index_dir.mkdir(parents=True, exist_ok=True)

    tmp_dir = (Path(path) if path else DOWNLOAD_DIR) / random_string(10)
    tmp_dir.mkdir(parents=True, exist_ok=True)

    try:
        terms_files = [
            settings.BASE_DIR.joinpath('data', 'rdf.tsv'),
            settings.BASE_DIR.joinpath('data', 'rdfs.tsv'),
            settings.BASE_DIR.joinpath('data', 'owl.tsv'),
            settings.BASE_DIR.joinpath('data', 'foaf.tsv'),
        ]

        logger.info('Creating search index from documents')
        consume_print(BoldCli.cmd(
            ['build-index', '--force', *map(str, terms_files), '--index', str(search_index_dir)]
        ))

        logger.info('Search index created')
    finally:
        logger.info(f"Cleaning up {tmp_dir}")
        shutil.rmtree(tmp_dir, ignore_errors=True)

create_search_index(dataset_id, min_term_count=3, path=None, force=True)

Source code in datasets/tasks/processing.py
 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
137
138
139
@shared_task()
def create_search_index(
    dataset_id: UUID,
    min_term_count: int = 3,
    path: str = None,
    force: bool = True,
):
    dataset = Dataset.objects.get(id=dataset_id)
    logger.info(f"Creating search index for {dataset.name}")

    database = dataset.local_database
    if database is None:
        raise Exception("Dataset has no database")

    search_index_dir = DATA_DIR / f'search_index_{database}'
    if search_index_dir.exists():
        if force:
            logger.info(f"Removing existing search index at {search_index_dir}")
            shutil.rmtree(search_index_dir)
        else:
            logger.info(f"Search index already exists for {dataset.name}")
            return

    search_index_dir.mkdir(parents=True, exist_ok=True)

    tmp_dir = (Path(path) if path else DOWNLOAD_DIR) / random_string(10)
    tmp_dir.mkdir(parents=True, exist_ok=True)
    try:
        terms_files = []

        terms_s_file = tmp_dir / 'terms_s.tsv'
        query = QUERY_EXPORT_SEARCH \
            .replace('{triple}', '{ ?t ?p ?v }') \
            .replace('{min_count}', str(min_term_count)) \
            .replace('{pos}', '0')
        logger.info(f'Exporting subject search terms {terms_s_file}')
        query_to_file(database, query, terms_s_file, timeout=60 * 60 * 1000)
        terms_files.append(terms_s_file)

        terms_p_file = tmp_dir / 'terms_p.tsv'
        query = QUERY_EXPORT_SEARCH \
            .replace('{triple}', '{ ?s ?t ?v }') \
            .replace('{min_count}', str(min_term_count)) \
            .replace('{pos}', '1')
        logger.info(f'Exporting predicate search terms {terms_p_file}')
        query_to_file(database, query, terms_p_file, timeout=60 * 60 * 1000)
        terms_files.append(terms_p_file)

        terms_o_file = tmp_dir / 'terms_o.tsv'
        query = QUERY_EXPORT_SEARCH \
            .replace('{triple}', '{ ?s ?p ?t FILTER(?p != rdfs:label) }') \
            .replace('{min_count}', str(min_term_count)) \
            .replace('{pos}', '2')
        logger.info(f'Exporting object search terms {terms_o_file}')
        query_to_file(database, query, terms_o_file, timeout=60 * 60 * 1000)
        terms_files.append(terms_o_file)

        logger.info('Creating search index from documents')
        consume_print(BoldCli.cmd(
            ['build-index', '--force', *map(str, terms_files), '--index', str(search_index_dir)]
        ))

        logger.info('Search index created')
    finally:
        logger.info(f"Cleaning up {tmp_dir}")
        shutil.rmtree(tmp_dir, ignore_errors=True)

query_to_file(database, query, file, timeout=5000, **kwargs)

Source code in datasets/tasks/processing.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def query_to_file(database: str, query: str, file: Path, timeout=5000, **kwargs):
    endpoint = settings.STARDOG_ENDPOINT.rstrip('/')
    credentials = base64.b64encode(f'{settings.STARDOG_USER}:{settings.STARDOG_PASS}'.encode('utf-8')).decode(
        'utf-8')

    headers = {
        'Content-Type': 'application/sparql-query',
        'Accept': 'text/tsv',
        'Authorization': f'Basic {credentials}',
    }

    response = requests.post(f'{endpoint}/{database}/query', headers=headers, data=query, params={
        **kwargs,
        'timeout': timeout,
    }, stream=True)

    with response as r:
        r.raw.decode_content = True
        with file.open('wb') as f:
            # https://stackoverflow.com/a/49684845
            shutil.copyfileobj(r.raw, f)