-
Notifications
You must be signed in to change notification settings - Fork 16
/
import_data.py
3261 lines (2568 loc) · 108 KB
/
import_data.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding=utf-8 -*-
import json
import re
import datetime
import os
import sys
import logging
import logging.config
import shutil
import requests
import pytz
import psycopg2
import sqlalchemy as sa
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from dateutil import parser as date_parser
from raven.contrib.django.raven_compat.models import client
from django.core.management.base import BaseCommand
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
from django.utils.dateparse import parse_datetime, parse_date
from django.utils.text import slugify, Truncator
from django.db.utils import IntegrityError, DataError
from django.db.models import Max
from councilmatic_core.models import Person, Bill, Organization, Action, ActionRelatedEntity, \
Post, Membership, Sponsorship, LegislativeSession, \
Document, BillDocument, Event, EventParticipant, EventDocument, \
EventAgendaItem, Jurisdiction
logging.config.dictConfig(settings.LOGGING)
logger = logging.getLogger(__name__)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
session = requests.Session()
for configuration in ['OCD_JURISDICTION_IDS',
'HEADSHOT_PATH',]:
if not hasattr(settings, configuration):
raise ImproperlyConfigured(
'You must define {0} in settings.py'.format(configuration))
app_timezone = pytz.timezone(settings.TIME_ZONE)
DB_CONN = 'postgresql://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}'
engine = sa.create_engine(DB_CONN.format(**settings.DATABASES['default']),
convert_unicode=True,
server_side_cursors=True)
if hasattr(settings, 'OCDAPI_BASE_URL'):
base_url = settings.OCDAPI_BASE_URL
else:
base_url = 'http://ocd.datamade.us'
if hasattr(settings, 'BOUNDARY_API_BASE_URL'):
bndry_base_url = settings.BOUNDARY_API_BASE_URL
else:
bndry_base_url = base_url
DEBUG = settings.DEBUG
class Command(BaseCommand):
help = 'loads in data from the open civic data API'
def add_arguments(self, parser):
parser.add_argument(
'--endpoints',
help='Indicates a specific endpoint from which to load data.'
'Be aware! Data about people depends on data about organizations,'
'and so, the people endpoint should not be run without the organization endpoint,'
'i.e., --endpoints=organizations,people',
default='organizations,people,bills,events')
parser.add_argument('--delete',
action='store_true',
default=False,
help='deletes all data, and then loads all legislative sessions (by default, this task does not delete data & only loads new/updated data from current legislative session)')
parser.add_argument('--update_since',
help='Only update objects in the database that have changed since this date')
parser.add_argument('--import_only',
action='store_true',
default=False,
help='Load already downloaded OCD data')
parser.add_argument('--download_only',
action='store_true',
default=False,
help='Only download OCD data')
parser.add_argument('--keep_downloads',
action='store_true',
help='Preserve JSON files in downloads directory')
def handle(self, *args, **options):
self.update_since = None
self.connection = engine.connect()
self.this_folder = os.path.abspath(os.path.dirname(__file__))
if options['update_since']:
self.update_since = date_parser.parse(options['update_since'])
endpoints = options['endpoints'].split(',')
if 'people' in endpoints and 'organizations' not in endpoints:
self.log_message('Huh? Those endpoints do not look right.', style='ERROR')
raise ValueError('You must import organization data to import people data: please include both endpoints')
for jurisdiction_id in settings.OCD_JURISDICTION_IDS:
self.jurisdiction_id = jurisdiction_id
self.jurisdiction_name = jurisdiction_id.rsplit(':', 1)[1].split('/')[0]
self.downloads_folder = os.path.join('downloads',
self.jurisdiction_name)
self.organizations_folder = os.path.join(self.downloads_folder, 'organizations')
self.posts_folder = os.path.join(self.downloads_folder, 'posts')
self.bills_folder = os.path.join(self.downloads_folder, 'bills')
self.people_folder = os.path.join(self.downloads_folder, 'people')
self.events_folder = os.path.join(self.downloads_folder, 'events')
self.create_jurisdiction()
self.create_legislative_sessions()
for endpoint in endpoints:
if endpoint not in ['organizations', 'people', 'bills', 'events']:
self.log_message('"{}" is not a valid endpoint'.format(endpoint), style='ERROR')
else:
download_only = options['download_only']
import_only = options['import_only']
if not import_only and not download_only:
download_only = True
import_only = True
try:
etl_method = getattr(self, '{}_etl'.format(endpoint))
etl_method(import_only=import_only,
download_only=download_only,
delete=options['delete'])
except Exception as e:
client.captureException()
logger.error(e, exc_info=True)
if not options['keep_downloads']:
shutil.rmtree(self.downloads_folder)
self.stdout.write('All files and folders cleared from {}'.format(self.downloads_folder))
def log_message(self,
message,
fancy=False,
style='HTTP_SUCCESS',
art_file=None,
center=False,
timestamp=True):
if timestamp:
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
message = '{0} {1}'.format(now, message)
if len(message) < 70 and center:
padding = (70 - len(message)) / 2
message = '{0}{1}{0}'.format(' ' * int(padding), message)
if fancy and not art_file:
thing_count = len(message) + 2
message = '\n{0}\n {1} \n{0}'.format('-' * 70, message)
elif art_file:
art = open(os.path.join(self.this_folder, 'art', art_file)).read()
message = '\n{0} \n {1}'.format(art, message)
style = getattr(self.style, style)
self.stdout.write(style('{}\n'.format(message)))
def organizations_etl(self,
import_only=True,
download_only=True,
delete=False):
if download_only:
self.log_message('Downloading organizations ...',
center=True,
art_file='organizations.txt')
self.grab_organizations()
if import_only:
self.log_message('Importing organizations ...',
center=True,
art_file='organizations.txt')
self.insert_raw_organizations(delete=delete)
self.insert_raw_posts(delete=delete)
self.update_existing_organizations()
self.update_existing_posts()
self.add_new_organizations()
self.add_new_posts()
self.log_message('Organizations Complete!',
fancy=True,
center=True,
style='SUCCESS')
def people_etl(self,
import_only=False,
download_only=False,
delete=False):
if download_only:
self.log_message('Downloading people ...',
center=True,
art_file='people.txt')
self.grab_people()
if import_only:
self.log_message('Importing people ...',
center=True,
art_file='people.txt')
self.insert_raw_people(delete=delete)
self.insert_raw_memberships(delete=delete)
self.update_existing_people()
self.update_existing_memberships()
self.add_new_people()
self.add_new_memberships()
self.log_message('People Complete!',
fancy=True,
center=True,
style='SUCCESS')
def bills_etl(self,
import_only=False,
download_only=False,
delete=False):
if download_only:
self.log_message('Downloading bills ...',
center=True,
art_file='bills.txt')
self.grab_bills()
if import_only:
self.log_message('Importing bills ...',
center=True,
art_file='bills.txt')
self.insert_raw_bills(delete=delete)
self.insert_raw_actions(delete=delete)
self.update_existing_bills()
self.update_existing_actions()
self.add_new_bills()
self.add_new_actions()
self.insert_raw_action_related_entity(delete=delete)
self.insert_raw_sponsorships(delete=delete)
self.insert_raw_billdocuments(delete=delete)
self.insert_raw_relatedbills(delete=delete)
self.update_existing_action_related_entity()
self.update_existing_sponsorships()
self.update_existing_billdocuments()
self.update_existing_relatedbills()
self.add_new_action_related_entity()
self.add_new_sponsorships()
self.add_new_billdocuments()
self.add_new_relatedbills()
self.insert_subjects()
self.log_message('Bills Complete!', fancy=True, style='SUCCESS', center=True)
def events_etl(self,
import_only=False,
download_only=False,
delete=False):
if download_only:
self.log_message('Downloading events ...',
center=True,
fancy=True)
self.grab_events()
if import_only:
self.log_message('Importing events ...',
center=True,
fancy=True)
self.insert_raw_events(delete=delete)
self.insert_raw_eventparticipants(delete=delete)
self.insert_raw_eventdocuments(delete=delete)
self.insert_raw_eventmedia(delete=delete)
self.update_existing_events()
self.update_existing_eventparticipants()
self.update_existing_eventdocuments()
self.update_existing_eventmedia()
self.add_new_events()
self.add_new_eventparticipants()
self.add_new_eventdocuments()
self.add_new_eventmedia()
self.insert_event_agenda_items()
self.log_message('Events Complete!', fancy=True, style='SUCCESS', center=True)
#########################
### ###
### DOWNLOAD FROM OCD ###
### ###
#########################
def grab_organizations(self):
os.makedirs(self.organizations_folder, exist_ok=True)
os.makedirs(self.posts_folder, exist_ok=True)
org_counter = 0
post_counter = 0
orgs_url = '{}/organizations/?sort=updated_at&jurisdiction_id={}'.format(base_url, self.jurisdiction_id)
r = self._get_response(orgs_url)
page_json = json.loads(r.text)
for i in range(page_json['meta']['max_page']):
r = self._get_response(orgs_url + '&page=' + str(i + 1))
page_json = json.loads(r.text)
org_counter += len(page_json['results'])
for result in page_json['results']:
post_count = self.grab_organization_posts({'id': result['id']})
post_counter += post_count
print('.', end='')
sys.stdout.flush()
print('\n')
self.log_message('Downloaded {0} orgs and {1} posts'.format(org_counter, post_counter))
# update relevant posts with shapes
if hasattr(settings, 'BOUNDARY_SET') and settings.BOUNDARY_SET:
self.populate_council_district_shapes()
def grab_organization_posts(self, org_dict):
url = base_url + '/organizations/'
r = self._get_response(url, params=org_dict)
page_json = json.loads(r.text)
organization_ocd_id = page_json['results'][0]['id']
url = base_url + '/' + organization_ocd_id + '/'
r = self._get_response(url)
page_json = json.loads(r.text)
if page_json.get('error'):
raise DataError(page_json['error'])
ocd_uuid = org_dict['id'].split('/')[-1]
organization_filename = '{}.json'.format(ocd_uuid)
with open(os.path.join(self.organizations_folder, organization_filename), 'w') as f:
f.write(json.dumps(page_json))
for post_json in page_json['posts']:
post_uuid = post_json['id'].split('/')[-1]
post_filename = '{}.json'.format(post_uuid)
post_json['org_ocd_id'] = org_dict['id']
with open(os.path.join(self.posts_folder, post_filename), 'w') as f:
f.write(json.dumps(post_json))
return len(page_json['posts'] + page_json['children'])
def grab_people(self):
# find people associated with existing organizations & bills
os.makedirs(self.people_folder, exist_ok=True)
seen_person = set()
counter = 0
for organization_json in os.listdir(self.organizations_folder):
org_info = json.load(open(os.path.join(self.organizations_folder, organization_json)))
for membership_json in org_info['memberships']:
person_id = membership_json['person']['id']
if person_id in seen_person:
continue
seen_person.add(person_id)
person_json = self.grab_person_memberships(person_id)
person_uuid = person_json['id'].split('/')[-1]
person_filename = '{}.json'.format(person_uuid)
with open(os.path.join(self.people_folder, person_filename), 'w') as f:
f.write(json.dumps(person_json))
print('.', end='')
sys.stdout.flush()
counter += 1
self.log_message('Downloaded {} people and memeberships'.format(counter), fancy=True)
def grab_person_memberships(self, person_id):
# this grabs a person and all their memberships
url = base_url + '/' + person_id + '/'
r = self._get_response(url)
page_json = json.loads(r.text)
# save image to disk
if page_json['image']:
r = self._get_response(page_json['image'], verify=False, raise_error=False)
if r:
with open((settings.HEADSHOT_PATH + page_json['id'] + ".jpg"), 'wb') as f:
for chunk in r.iter_content(1000):
f.write(chunk)
f.flush()
page_json['email'] = None
for contact_detail in page_json['contact_details']:
if contact_detail['type'] == 'email':
if contact_detail['value'] != 'mailto:':
page_json['email'] = contact_detail['value']
page_json['website_url'] = None
for link in page_json['links']:
if link['note'] == "web site":
page_json['website_url'] = link['url']
return page_json
def grab_bills(self):
os.makedirs(self.bills_folder, exist_ok=True)
organizations = session.get('{}/organizations/'.format(base_url),
params={'jurisdiction__id': self.jurisdiction_id})
organization_ids = [(o['id'], o['name']) for o in organizations.json()['results']]
if self.update_since is None:
max_updated = Bill.objects.all().aggregate(Max('ocd_updated_at'))['ocd_updated_at__max']
if max_updated is None:
max_updated = datetime.datetime(1900, 1, 1)
else:
max_updated = self.update_since
query_params = {
'sort': 'updated_at',
'updated_at__gte': max_updated.isoformat(),
}
self.log_message('Getting bills since {}'.format(query_params['updated_at__gte']), style='NOTICE')
search_url = '{}/bills/'.format(base_url)
counter = 0
for organization_id, organization_name in organization_ids:
query_params['from_organization__id'] = organization_id
query_params['page'] = 1
self.log_message('Getting bills from {}'.format(organization_name), style='NOTICE')
search_results = self._get_response(search_url, params=query_params)
page_json = search_results.json()
for page_num in range(page_json['meta']['max_page']):
query_params['page'] = int(page_num) + 1
result_page = self._get_response(search_url, params=query_params)
for result in result_page.json()['results']:
bill_url = '{base}/{bill_id}/'.format(
base=base_url, bill_id=result['id'])
bill_detail = self._get_response(bill_url)
bill_json = bill_detail.json()
ocd_uuid = bill_json['id'].split('/')[-1]
bill_filename = '{}.json'.format(ocd_uuid)
with open(os.path.join(self.bills_folder, bill_filename), 'w') as f:
f.write(json.dumps(bill_json))
counter += 1
print('.', end='')
sys.stdout.flush()
if counter % 1000 == 0:
print('\n')
self.log_message('Downloaded {} bills'.format(counter))
self.log_message('Downloaded {} bills'.format(counter), fancy=True)
def grab_events(self):
os.makedirs(self.events_folder, exist_ok=True)
events_url = '{0}/events/'.format(base_url)
params = {'jurisdiction_id': self.jurisdiction_id}
if self.update_since is None:
max_updated = Event.objects.all().aggregate(
Max('ocd_updated_at'))['ocd_updated_at__max']
if max_updated is None:
max_updated = datetime.datetime(1900, 1, 1)
else:
max_updated = self.update_since
params['updated_at__gte'] = max_updated.isoformat()
params['sort'] = 'updated_at'
r = self._get_response(events_url, params=params)
page_json = json.loads(r.text)
counter = 0
for i in range(page_json['meta']['max_page']):
params['page'] = str(i + 1)
r = self._get_response(events_url, params=params)
page_json = json.loads(r.text)
for event in page_json['results']:
ocd_uuid = event['id'].split('/')[-1]
event_filename = '{}.json'.format(ocd_uuid)
event_url = base_url + '/' + event['id'] + '/'
r = self._get_response(event_url)
if r.status_code == 200:
page_json = json.loads(r.text)
with open(os.path.join(self.events_folder, event_filename), 'w') as f:
f.write(json.dumps(page_json))
counter += 1
print('.', end='')
sys.stdout.flush()
if counter % 1000 == 0:
print('\n')
self.log_message('Downloaded {} events'.format(counter))
else:
self.log_message('Skipping event {} (cannot retrieve event data)'.format(event['id']), style='ERROR')
self.log_message('Downloaded {} events'.format(counter), fancy=True)
###########################
### ###
### INSERT RAW ENTITIES ###
### ###
###########################
def remake_raw(self, entity_type, delete=False):
if delete:
self.executeTransaction(
'TRUNCATE councilmatic_core_{} CASCADE'.format(entity_type))
print("deleted all {}".format(entity_type))
self.executeTransaction('DROP TABLE IF EXISTS raw_{}'.format(entity_type))
self.executeTransaction('''
CREATE TABLE raw_{0} AS (
SELECT * FROM councilmatic_core_{0}
) WITH NO DATA
'''.format(entity_type))
def setup_raw(self,
entity_type,
delete=False,
pk_cols=['ocd_id'],
updated_at=True):
self.remake_raw(entity_type, delete=delete)
if pk_cols:
self.executeTransaction('''
ALTER TABLE raw_{0} ADD PRIMARY KEY ({1})
'''.format(entity_type, ','.join(pk_cols)))
if updated_at:
self.executeTransaction('''
ALTER TABLE raw_{}
ALTER COLUMN updated_at SET DEFAULT NOW()
'''.format(entity_type))
def create_jurisdiction(self):
url = '{0}/jurisdictions/?id={1}'.format(base_url, self.jurisdiction_id)
r = self._get_response(url)
jurisdiction_info = json.loads(r.text)['results'][0]
try:
jurisdiction = Jurisdiction.objects.get(ocd_id=jurisdiction_info['id'])
self.log_message('Skipped creating jurisdiction {}'.format(jurisdiction_info['name']),
style='SUCCESS')
except Jurisdiction.DoesNotExist:
jurisdiction = Jurisdiction(ocd_id=jurisdiction_info['id'],
name=jurisdiction_info['name'],
classification=jurisdiction_info['classification'],
url=jurisdiction_info['url'])
jurisdiction.save()
self.log_message('Created jurisdiction {}'.format(jurisdiction_info['name']),
style='SUCCESS')
def create_legislative_sessions(self):
session_ids = []
if hasattr(settings, 'LEGISLATIVE_SESSIONS') and settings.LEGISLATIVE_SESSIONS:
session_ids = settings.LEGISLATIVE_SESSIONS
# for more than one jurisdiction, LEGISLATIVE_SESSIONS will be
# a dict where the keys are jurisdiction ids and the values are
# lists of legislative sessions
if isinstance(session_ids, dict):
session_ids = session_ids[self.jurisdiction_id]
else:
url = base_url + '/' + self.jurisdiction_id + '/'
r = self._get_response(url)
page_json = json.loads(r.text)
session_ids = ['{0}-{1}'.format(session['identifier'], self.jurisdiction_name)
for session in page_json['legislative_sessions']]
# Sort so most recent session last
session_ids.sort()
for leg_session in session_ids:
obj, created = LegislativeSession.objects.get_or_create(
identifier=leg_session,
jurisdiction_ocd_id=self.jurisdiction_id,
name='%s Legislative Session' % leg_session,
)
if created and DEBUG:
print('adding legislative session: %s' % obj.name)
def insert_raw_organizations(self, delete=False):
self.setup_raw('organization', delete=delete)
inserts = []
insert_query = '''
INSERT INTO raw_organization (
ocd_id,
name,
classification,
source_url,
slug,
parent_id,
jurisdiction_id
) VALUES (
:ocd_id,
:name,
:classification,
:source_url,
:slug,
:parent_id,
:jurisdiction_id
)
'''
for organization_json in os.listdir(self.organizations_folder):
with open(os.path.join(self.organizations_folder, organization_json)) as f:
org_info = json.loads(f.read())
source_url = None
if org_info['sources']:
source_url = org_info['sources'][0]['url']
parent_ocd_id = None
if org_info['parent']:
parent_ocd_id = org_info['parent']['id']
ocd_part = org_info['id'].rsplit('-', 1)[1]
slug = '{0}-{1}'.format(slugify(org_info['name']),ocd_part)
insert = {
'ocd_id': org_info['id'],
'name': org_info['name'],
'classification': org_info['classification'],
'source_url': source_url,
'slug': slug,
'parent_id': parent_ocd_id,
'jurisdiction_id': self.jurisdiction_id,
}
inserts.append(insert)
if inserts:
self.executeTransaction(sa.text(insert_query), *inserts)
raw_count = self.connection.execute('select count(*) from raw_organization').first().count
self.log_message('Inserted {0} raw organizations'.format(raw_count), style='SUCCESS')
def insert_raw_posts(self, delete=False):
self.setup_raw('post', delete=delete)
inserts = []
insert_query = '''
INSERT INTO raw_post (
ocd_id,
label,
role,
organization_id,
division_ocd_id
) VALUES (
:ocd_id,
:label,
:role,
:organization_id,
:division_ocd_id
)
'''
for post_json in os.listdir(self.posts_folder):
with open(os.path.join(self.posts_folder, post_json)) as f:
post_info = json.loads(f.read())
insert = {
'ocd_id': post_info['id'],
'label': post_info['label'],
'role': post_info['role'],
'organization_id': post_info['org_ocd_id'],
'division_ocd_id': post_info['division_id'],
}
inserts.append(insert)
if inserts:
self.executeTransaction(sa.text(insert_query), *inserts)
raw_count = self.connection.execute('select count(*) from raw_post').first().count
self.log_message('Inserted {0} raw posts'.format(raw_count), style='SUCCESS')
def insert_raw_people(self, delete=False):
self.setup_raw('person', delete=delete)
inserts = []
insert_query = '''
INSERT INTO raw_person (
ocd_id,
name,
headshot,
source_url,
source_note,
website_url,
email,
slug
) VALUES (
:ocd_id,
:name,
:headshot,
:source_url,
:source_note,
:website_url,
:email,
:slug
)
'''
for person_json in os.listdir(self.people_folder):
with open(os.path.join(self.people_folder, person_json)) as f:
person_info = json.loads(f.read())
source_url = None
if person_info['sources']:
source_url = person_info['sources'][0]['url']
source_note = None
if person_info['sources']:
source_note = person_info['sources'][0]['note']
ocd_part = person_info['id'].rsplit('-', 1)[1]
slug = '{0}-{1}'.format(slugify(person_info['name']),ocd_part)
insert = {
'ocd_id': person_info['id'],
'name': person_info['name'],
'headshot': person_info['image'],
'source_url': source_url,
'source_note': source_note,
'website_url': person_info['website_url'],
'email': person_info['email'],
'slug': slug,
}
inserts.append(insert)
if inserts:
self.executeTransaction(sa.text(insert_query), *inserts)
raw_count = self.connection.execute('select count(*) from raw_person').first().count
self.log_message('Inserted {0} raw people\n'.format(raw_count), style='SUCCESS')
def insert_raw_memberships(self, delete=False):
self.setup_raw('membership', delete=delete, pk_cols=[])
inserts = []
insert_query = '''
INSERT INTO raw_membership (
label,
role,
start_date,
end_date,
extras,
organization_id,
person_id,
post_id
) VALUES (
:label,
:role,
:start_date,
:end_date,
:extras,
:organization_id,
:person_id,
:post_id
)
'''
for person_json in os.listdir(self.people_folder):
with open(os.path.join(self.people_folder, person_json)) as f:
person_info = json.loads(f.read())
for membership_json in person_info['memberships']:
end_date = parse_date(membership_json['end_date'])
start_date = parse_date(membership_json['start_date'])
post_id = None
if membership_json['post']:
post_id = membership_json['post']['id']
insert = {
'label': membership_json['label'],
'role': membership_json['role'],
'start_date': start_date,
'end_date': end_date,
'extras': json.dumps(membership_json['extras']),
'organization_id': membership_json['organization']['id'],
'person_id': person_info['id'],
'post_id': post_id,
}
inserts.append(insert)
if inserts:
self.executeTransaction(sa.text(insert_query), *inserts)
raw_count = self.connection.execute('select count(*) from raw_membership').first().count
self.log_message('Inserted {0} raw memberships\n'.format(raw_count), style='SUCCESS')
def insert_raw_bills(self, delete=False):
self.setup_raw('bill', delete=delete)
inserts = []
insert_query = '''
INSERT INTO raw_bill (
ocd_id,
ocd_created_at,
ocd_updated_at,
description,
identifier,
classification,
source_url,
source_note,
from_organization_id,
full_text,
ocr_full_text,
html_text,
abstract,
legislative_session_id,
bill_type,
slug,
restrict_view
) VALUES (
:ocd_id,
:ocd_created_at,
:ocd_updated_at,
:description,
:identifier,
:classification,
:source_url,
:source_note,
:from_organization_id,
:full_text,
:ocr_full_text,
:html_text,
:abstract,
:legislative_session_id,
:bill_type,
:slug,
:restrict_view
)
'''
counter = 0
for bill_json in os.listdir(self.bills_folder):
with open(os.path.join(self.bills_folder, bill_json)) as f:
bill_info = json.loads(f.read())
# Add the web source, if available.
# Otherwise, assume that the 'api' source is available and add that.
source_url = None
source_note = None
for source in bill_info['sources']:
if source['note'] == 'web':
source_url = source['url']
source_note = source['note']
break
else:
source_url = source['url']
source_note = source['note']
full_text = None
if 'rtf_text' in bill_info['extras']:
full_text = bill_info['extras']['rtf_text']
ocr_full_text = None
if 'plain_text' in bill_info['extras']:
ocr_full_text = bill_info['extras']['plain_text']
html_text = None
if 'html_text' in bill_info['extras']:
html_text = bill_info['extras']['html_text']
abstract = None
if bill_info['abstracts']:
abstract = bill_info['abstracts'][0]['abstract']
if bill_info['extras'].get('local_classification'):
bill_type = bill_info['extras']['local_classification']
elif len(bill_info['classification']) == 1: