-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_to_sqlite_db.py
350 lines (273 loc) · 9.68 KB
/
json_to_sqlite_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
137
138
139
140
141
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import glob
import json as js
import os
import sqlite3
import gzip
import time
def check_for_errors(json_directory):
if os.path.isdir(json_directory):
dir_list = glob.glob(json_directory + "*.json")
for path in dir_list:
act = os.path.basename(path)
try:
with open(path) as jsn:
json_data = js.load(jsn)
# print(act + '-- OK')
except:
print(act + ' -- ERROR')
elif os.path.isfile(json_directory):
act = os.path.basename(json_directory)
try:
with open(json_directory) as jsn:
json_data = js.load(jsn)
print(act + '-- OK')
except:
print(act + ' -- ERROR')
def convert_to_sqlite(jsn_dir, sch_dir):
if os.path.isdir(jsn_dir):
dir_list = glob.glob(jsn_dir + "*.json")
os.makedirs('./' + "Database", exist_ok=True)
for path in dir_list:
act = os.path.basename(path)
act_name = act.replace('.json', '')
try:
with open(path) as jsn:
json_data = js.load(jsn)
db_path = ("./Database/" + act_name + '.db')
create_tables_in_db(db_path)
insert_act_details_to_db(db_path, json_data)
insert_tabs_to_db(db_path, json_data)
insert_contents_to_db(db_path, json_data)
insert_sections_to_db(db_path, json_data)
insert_schedules_to_db(db_path, json_data, act_name, sch_dir)
# print(act_name + '\tDone.')
except:
print(act + ' -- ERROR')
elif os.path.isfile(jsn_dir):
os.makedirs('./' + "Database", exist_ok=True)
act = os.path.basename(jsn_dir)
act_name = act.replace('.json', '')
try:
with open(jsn_dir) as jsn:
json_data = js.load(jsn)
db_path = ("./Database/" + act_name + '.db')
# Create the tables in database
create_tables_in_db(db_path)
# Insert act details to db
insert_act_details_to_db(db_path, json_data)
print('ok1')
# Insert tabs to db
insert_tabs_to_db(db_path, json_data)
# Insert contents to db
insert_contents_to_db(db_path, json_data)
print('ok2')
# Insert sections to db
insert_sections_to_db(db_path, json_data)
print('ok3')
# Insert schedule
insert_schedules_to_db(db_path, json_data, act_name, sch_dir)
print('ok4')
except:
print('Error')
def create_tables_in_db(d_path):
conn = sqlite3.connect(d_path)
c = conn.cursor()
# create act_details table
c.execute("""CREATE TABLE IF NOT EXISTS act_details (
act_name TEXT,
act_no TEXT,
act_year TEXT,
summary TEXT,
sections TEXT,
chapters TEXT,
enactment_date TEXT,
commencement_date TEXT,
enacted_by TEXT,
ministry TEXT,
department TEXT,
last_modified INT
)
""")
# create tabs table
c.execute("""
CREATE TABLE IF NOT EXISTS tabs (
tab TEXT
)
""")
# create contents table
c.execute(
"""
CREATE TABLE IF NOT EXISTS chapters (
title TEXT,
subtitle TEXT,
sections TEXT,
min_index INT,
max_index INT
)
"""
)
# create sections table
c.execute("""
CREATE TABLE IF NOT EXISTS sections (
title TEXT,
subtitle TEXT,
content TEXT,
footnotes TEXT
)
""")
# Create schedules table
c.execute("""
CREATE TABLE IF NOT EXISTS schedules (
schedule_heading TEXT,
schedule_content BLOB
)
""")
# commit the command
conn.commit()
conn.close()
def insert_act_details_to_db(d_path, jsn_data):
conn = sqlite3.connect(d_path)
c = conn.cursor()
# insert to act_details
act_details_to_write = (
jsn_data['act_details']['act_name'],
jsn_data['act_details']['act_no'],
jsn_data['act_details']['act_year'],
jsn_data['act_details']['summary'],
jsn_data['act_details']['sections'],
jsn_data['act_details']['chapters'],
jsn_data['act_details']['enactment_date'],
jsn_data['act_details']['commencement_date'],
jsn_data['act_details']['enacted_by'],
jsn_data['act_details']['ministry'],
jsn_data['act_details']['department'],
int(time.time())
)
c.execute("""INSERT INTO act_details VALUES (?,?,?,?,?,?,?,?,?,?,?,?)""", act_details_to_write)
conn.commit()
conn.close()
def insert_tabs_to_db(d_path, jsn_data):
conn = sqlite3.connect(d_path)
c = conn.cursor()
for tab in jsn_data['tabs']:
c.execute("INSERT INTO tabs VALUES (?)", (tab,))
conn.commit()
conn.close()
def insert_contents_to_db(d_path, jsn_data):
conn = sqlite3.connect(d_path)
c = conn.cursor()
contents_to_write = []
i = 0
while i < len(jsn_data['contents']):
contents_to_write.append((
jsn_data['contents'][str(i)]['title'],
jsn_data['contents'][str(i)]['subtitle'],
jsn_data['contents'][str(i)]['sections'],
jsn_data['contents'][str(i)]['min_index'],
jsn_data['contents'][str(i)]['max_index']
))
i += 1
c.executemany("INSERT INTO chapters VALUES (?,?,?,?,?)", contents_to_write)
conn.commit()
conn.close()
def insert_sections_to_db(d_path, jsn_data):
conn = sqlite3.connect(d_path)
c = conn.cursor()
sections_to_write = []
i = 0
while i < len(jsn_data['sections']):
content_string = ""
for content in jsn_data['sections'][str(i)]['content']:
content_string = content_string + content + '\n'
if len(jsn_data['sections'][str(i)]['footnotes']) > 0:
footnotes_string = ""
for footnote in jsn_data['sections'][str(i)]['footnotes']:
footnotes_string = footnotes_string + footnote + '\n'
else:
footnotes_string = ""
sections_to_write.append((
jsn_data['sections'][str(i)]['title'],
jsn_data['sections'][str(i)]['subtitle'],
content_string,
footnotes_string
))
i += 1
c.executemany("INSERT INTO sections VALUES (?,?,?,?)", sections_to_write)
conn.commit()
conn.close()
def insert_schedules_to_db(d_path, jsn_data, act_name, sch):
conn = sqlite3.connect(d_path)
c = conn.cursor()
schedules_to_write = []
if len(jsn_data['schedules']) > 0:
for schedule in jsn_data['schedules']:
file_path = (sch + schedule + '-' + act_name + '.pdf')
pdf_blob = convert_to_binary_data(file_path)
schedules_to_write.append((schedule, pdf_blob))
c.executemany("INSERT INTO schedules VALUES (?,?)", schedules_to_write)
conn.commit()
conn.close()
else:
pass
def compress_files(directory):
dir_list = glob.glob(directory + '*.db')
os.makedirs('./' + "Compressed DB", exist_ok=True)
for f in dir_list:
print(f)
base_name = os.path.basename(f)
binary_data = convert_to_binary_data(f)
with gzip.open('./Compressed DB/' + base_name + '.gz', 'wb') as out:
out.write(binary_data)
def compress_file(file_path):
base_name = os.path.basename(file_path)
binary_data = convert_to_binary_data(file_path)
with gzip.open('./' + base_name + '.gz', 'wb') as out:
out.write(binary_data)
def gen_acts_list(dir_path):
dir_list = glob.glob(dir_path + '*.json')
dir_list.sort()
cen_acts_tmp = {}
i = 0
while i < len(dir_list):
print(dir_list[i])
basename = os.path.basename(dir_list[i]).replace('.json', '')
cen_acts_tmp[str(i)] = {
"title": basename
}
i = i + 1
cen_acts = {
"central_acts": cen_acts_tmp
}
with open('acts_list.json', 'w') as out:
js.dump(cen_acts, out)
compress_file('./acts_list.json')
def convert_to_binary_data(filename):
# Convert digital data to binary format
with open(filename, 'rb') as file:
blob_data = file.read()
return blob_data
if __name__ == '__main__':
print("Select option:")
print("1. Check for errors Json file.")
print("2. Convert Json to Sqlite.")
print("3. Compress all db files in a directory.")
print("4. Compress single file.")
print("5. Generate acts list.")
option = int(input("Enter Option(1 or 2 or 3 or 4 or 5):"))
if option == 1:
path_to_json_files = str(input("Enter location of json file/s: "))
path_to_schedules = str(input("Enter location of schedules: "))
check_for_errors(path_to_json_files)
elif option == 2:
path_to_json_files = str(input("Enter location of json file/s: "))
path_to_schedules = str(input("Enter location of schedules: "))
convert_to_sqlite(path_to_json_files, path_to_schedules)
elif option == 3:
compress_dir = str(input('Enter directory to compress: '))
compress_files(compress_dir)
elif option == 4:
compress_path = str(input('Enter file to compress: '))
compress_file(compress_path)
else:
path_for_gen = str(input('Enter directory of json files: '))
gen_acts_list(path_for_gen)