Skip to content

Wikipedia

Domain lexicons from Wikipedia for the wiki method of data augmentation, read from the SQL dumps of a Wikipedia or from its API. Comparing the candidates with the gold terms needs the optional transformers dependencies: pip install 'termxtract[transformers]'.

wikipedia

Domain lexicons from Wikipedia for Wiki-TermDA (Banerjee, 2025, Algorithm 1): the links of the articles in the categories of a domain's article, mapped to the gold terms they are similar to.

The articles and links come from the SQL dumps of a Wikipedia (WikipediaDump), which are a fixed snapshot, or from its API (WikipediaAPI), which needs no download. Both take categories, articles and links in the same order, so that given the same Wikipedia they find the same candidates.

USER_AGENT = f'termxtract/{__version__} (https://github.com/TeangaNLP/TermXtract)' module-attribute

The User-Agent of requests to Wikimedia, which asks that clients name themselves.

TABLES = ('page', 'page_props', 'categorylinks', 'linktarget', 'pagelinks') module-attribute

The SQL dumps read by WikipediaDump.

QUALIFIER = re.compile('\\s+\\([^()]*\\)$') module-attribute

The qualifier of an article title, as in "Mercury (planet)".

ESCAPES = {b'0': b'\x00', b'n': b'\n', b'r': b'\r', b'Z': b'\x1a', b't': b'\t'} module-attribute

The escapes of MySQL strings other than an escaped character standing for itself.

STRING = b"'((?:[^'\\\\]|\\\\.)*)'" module-attribute

A MySQL string in a dump.

ROWS = {'page': re.compile(b'\\((\\d+),(-?\\d+),' + STRING + b','), 'page_props': re.compile(b"\\((\\d+),'(hiddencat)',"), 'categorylinks': re.compile(b'\\((\\d+),' + STRING + b",'[^']*'," + STRING + b",'(\\w+)',\\d+,(\\d+)\\)"), 'linktarget': re.compile(b'\\((\\d+),(-?\\d+),' + STRING + b'\\)')} module-attribute

The start of a row of each table but pagelinks, with the columns read.

BLOCK = 1 << 26 module-attribute

The size of the blocks in which the dumps are read.

DIGITS = bytes(c if chr(c).isdigit() and c < 128 else 32 for c in range(256)) module-attribute

A table that turns every byte but the digits into a space.

WikipediaSource

Bases: Protocol

A Wikipedia to collect candidate terms from, such as WikipediaDump.

candidates(titles, max_candidates=2000)

Collect the candidate terms of the domains of some articles.

Parameters:

Name Type Description Default
titles List[str]

The titles of the articles, such as "Heart failure".

required
max_candidates int

The number of candidates after which no more articles are read.

2000

Returns:

Type Description
dict[str, list[str]]

Dict[str, List[str]]: The candidates of each title, in lower case.

WikipediaAPI(language='en', cache_dir=None, user_agent=USER_AGENT)

A Wikipedia read through its API. A domain takes a few dozen requests, sent one at a time; they can be cached on disk, so that they are only sent once.

Parameters:

Name Type Description Default
language str

The language code of the Wikipedia, such as "en".

'en'
cache_dir Optional[Union[str, Path]]

A directory to keep each response in, or None to cache nothing.

None
user_agent str

The User-Agent of the requests.

USER_AGENT

query(**params)

Send a query, following its continuations.

Parameters:

Name Type Description Default
**params str

The parameters of the query.

{}

Returns:

Type Description
Iterator[dict]

Iterator[dict]: The query part of each response.

get(params)

Send a request, from the cache if it has been sent before.

categories(title)

The categories of an article that are not hidden, by title, without the namespace.

members(category)

The articles of a category, by sort key.

The links to articles of each article, by title, fetched batch articles at a time.

candidates(titles, max_candidates=2000)

Collect the candidate terms of the domains of some articles.

Parameters:

Name Type Description Default
titles List[str]

The titles of the articles, such as "Heart failure".

required
max_candidates int

The number of candidates after which no more articles are read.

2000

Returns:

Type Description
dict[str, list[str]]

Dict[str, List[str]]: The candidates of each title, in lower case.

WikipediaDump(directory=None, language='en', date='latest')

A Wikipedia read from its SQL dumps (https://dumps.wikimedia.org): the page, page_props, categorylinks, linktarget and pagelinks tables, about 14 GB for English. Each table is read a few times for each call to candidates, so the candidates of every domain should be collected in one call; they are cached in the directory of the dumps.

Parameters:

Name Type Description Default
directory Optional[Union[str, Path]]

The directory of the dumps, or None for wikipedia in the data directory of termxtract.datasets.

None
language str

The language code of the Wikipedia, such as "en".

'en'
date str

The date of the dumps, such as "20261101", or "latest".

'latest'

path(table)

The file of the dump of a table.

url(table)

The URL of the dump of a table.

download(user_agent=USER_AGENT)

Download the dumps that are missing.

Parameters:

Name Type Description Default
user_agent str

The User-Agent of the requests.

USER_AGENT

blocks(table)

Read the dump of a table in blocks of whole lines.

Parameters:

Name Type Description Default
table str

The table.

required

Returns:

Type Description
Iterator[bytes]

Iterator[bytes]: Blocks of about 64 MB.

Raises:

Type Description
FileNotFoundError

If the dump has not been downloaded.

rows(table, keys=None, needles=())

Read the rows of a table, one per line as the dumps write them, whose first column is one of keys or that contain one of needles.

Parameters:

Name Type Description Default
table str

The table.

required
keys Optional[Set[int]]

The first columns of the rows wanted, or None.

None
needles Iterable[bytes]

Text of the rows wanted, which should be rare: a row that has both a key and a needle is read twice.

()

Returns:

Type Description
Iterator[tuple[bytes, ...]]

Iterator[Tuple[bytes, ...]]: The columns of ROWS of each row read.

Read the links from some pages to articles, parsing the numbers of pagelinks with numpy, as it has billions of rows.

Parameters:

Name Type Description Default
pages Set[int]

The ids of the pages.

required

Returns:

Type Description
Iterator[tuple[int, int]]

Iterator[Tuple[int, int]]: The id of each page and of the link target of

Iterator[tuple[int, int]]

each of its links.

candidates(titles, max_candidates=2000)

Collect the candidate terms of the domains of some articles.

Parameters:

Name Type Description Default
titles List[str]

The titles of the articles, such as "Heart failure".

required
max_candidates int

The number of candidates after which no more articles are read.

2000

Returns:

Type Description
dict[str, list[str]]

Dict[str, List[str]]: The candidates of each title, in lower case.

collect(categories, members, links, max_candidates)

Collect candidates as in Algorithm 1 of Banerjee (2025): the links, in lower case, of the articles in each category in turn, until there are max_candidates.

Parameters:

Name Type Description Default
categories List[str]

The categories of the domain's article, in order.

required
members Callable[[str], List[str]]

The articles of a category, in order.

required
links Callable[[List[str]], Iterator[List[str]]]

The links of each of some articles, in order, generated lazily so that no more are fetched than are read.

required
max_candidates int

The number of candidates after which no more articles are read.

required

Returns:

Type Description
list[str]

List[str]: The candidates, without duplicates, in the order found.

lexicon(source, title, terms, encoder=None, threshold=0.75, max_candidates=2000)

Build the lexicon of a domain for Wiki-TermDA (Banerjee, 2025, Algorithm 1).

The candidates are the links of the articles in the categories of the domain's article. Each term is mapped to the candidates whose embedding has a cosine similarity above threshold with its own. Qualifiers in brackets are dropped from the candidates, so that "Mercury (planet)" is "mercury", and a term is not its own replacement.

Parameters:

Name Type Description Default
source WikipediaSource

The Wikipedia, a WikipediaDump or a WikipediaAPI.

required
title str

The title of the domain's article, such as "Heart failure".

required
terms Iterable[str]

The gold terms.

required
encoder Optional[Encoder]

The encoder of the terms, or None for Encoder(), all-MiniLM-L6-v2 as in Banerjee (2025), which needs the 'transformers' extra.

None
threshold float

The minimum similarity of a replacement.

0.75
max_candidates int

The number of candidates after which no more articles are read.

2000

Returns:

Type Description
dict[str, list[str]]

Dict[str, List[str]]: The replacements of each term, in lower case; terms

dict[str, list[str]]

without replacements are left out.

unescape(value)

Undo the escapes of a MySQL string.

title(value)

The title of a page in a dump, with spaces.