aboutsummaryrefslogtreecommitdiff
path: root/backend/hist_data/gen_desc_data.py
blob: bcd88708a47f5f131bacd300a5cc09fc254fccbe (plain)
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
#!/usr/bin/python3

"""
Maps events to short descriptions from Wikipedia, and stores them in the database.
"""

import argparse
import os
import sqlite3

ENWIKI_DB = os.path.join('enwiki', 'desc_data.db')
DB_FILE = 'data.db'

def genData(enwikiDb: str, dbFile: str) -> None:
	print('Creating table')
	dbCon = sqlite3.connect(dbFile)
	dbCur = dbCon.cursor()
	dbCur.execute('CREATE TABLE descs (id INT PRIMARY KEY, wiki_id INT, desc TEXT)')

	print('Getting events')
	titleToId: dict[str, int] = {}
	for eventId, title in dbCur.execute('SELECT id, title FROM events'):
		titleToId[title] = eventId

	print('Getting Wikipedia descriptions')
	enwikiCon = sqlite3.connect(enwikiDb)
	enwikiCur = enwikiCon.cursor()
	iterNum = 0
	for title, eventId in titleToId.items():
		iterNum += 1
		if iterNum % 1e4 == 0:
			print(f'At iteration {iterNum}')

		# Get wiki ID
		row = enwikiCur.execute('SELECT id FROM pages WHERE title = ?', (title,)).fetchone()
		if row is None:
			continue
		wikiId = row[0]

		# Check for redirect
		wikiIdToGet = wikiId
		query = \
			'SELECT pages.id FROM redirects INNER JOIN pages ON redirects.target = pages.title WHERE redirects.id = ?'
		row = enwikiCur.execute(query, (wikiId,)).fetchone()
		if row is not None:
			wikiIdToGet = row[0]

		# Get desc
		row = enwikiCur.execute('SELECT desc FROM descs where id = ?', (wikiIdToGet,)).fetchone()
		if row is None:
			continue
		dbCur.execute('INSERT INTO descs VALUES (?, ?, ?)', (eventId, wikiId, row[0]))

	print('Closing databases')
	dbCon.commit()
	dbCon.close()

if __name__ == '__main__':
	parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
	args = parser.parse_args()

	genData(ENWIKI_DB, DB_FILE)