Bimba.git

ref: 6a472fe3427cdf16857f62a4929861095be410a4

converter/converter.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
#!/bin/python3
# -*- coding: UTF-8 -*-
import yaml
import csv
import sqlite3
import requests
from bs4 import BeautifulSoup
import re
import os
from datetime import date
import zipfile
import io
from pathlib import Path
import hashlib
import gzip
import shutil


class TimetableDownloader:
    def __init__(self):
        self.__converter = TimetableConverter()

    def __call__(self):
        self.__download()
        self.__tidy_up()

        with open('metadata.yml', 'w') as metadata_file:
            yaml.dump(self.__metadata, metadata_file)

    def __download(self):
        self.__session = requests.session()
        html = self.__session.get(
            'https://www.ztm.poznan.pl/pl/dla-deweloperow/gtfsFiles',
            verify='bundle.pem')
        soup = BeautifulSoup(html.text, 'html.parser')
        names_table = [x.string.replace('.zip', '') for x in
                       soup.find_all('table')[-1]
                        .tbody
                        .find_all('td',
                                  string=re.compile('[0-9]{8}_[0-9]{8}'))]

        if not os.path.isfile('metadata.yml'):
            self.__metadata = []
        else:
            with open('metadata.yml', 'r+') as metadata_file:
                self.__metadata = yaml.load(metadata_file.read())

        to_download = [x for x in names_table if
                       self.__is_valid(x) or self.__will_valid(x)]

        to_download = self.__clean_overlapping(to_download)
        to_download = self.__select_not_had(to_download)

        for file in to_download:
            print('getting {}.zip'.format(file))
            self.__get_timetable(file)
            checksum = self.__converter()
            for p in Path('.').glob('*.txt'):
                p.unlink()
            size_u = os.path.getsize('timetable.db')
            self.__compress(checksum)
            self.__archive(file, checksum, size_u, os.path
                           .getsize('{}.db.gz'.format(checksum)))

    def __is_valid(self, name):
        today = date.today().strftime('%Y%m%d')
        start, end = name.split('_')
        return start <= today and today <= end

    def __will_valid(self, name):
        today = date.today().strftime('%Y%m%d')
        start, end = name.split('_')
        return today < start

    def __clean_overlapping(self, names):
        names.sort()
        if len(names) == 1:
            return names
        return_names = []
        i = 1
        for name in names[1:]:
            this_start, this_end = name.split('_')
            prev_start, prev_end = names[i-1].split('_')
            if this_start <= prev_start or this_end > prev_end:
                return_names.append(names[i-1])
            i = i + 1
        return_names.append(names[-1])
        return return_names

    def __select_not_had(self, names):
        had = ['_'.join((x['start'], x['end'])) for x in self.__metadata]
        return_names = []
        for name in names:
            if name not in had:
                return_names.append(name)
        return return_names

    def __get_timetable(self, name):
        response = self.__session.get('https://www.ztm.poznan.pl/pl/\
dla-deweloperow/getGTFSFile?file={}.zip'
                                      .format(name), verify='bundle.pem')
        zip_bytes = io.BytesIO(response.content)
        with zipfile.ZipFile(zip_bytes, 'r') as zip_file:
            zip_file.extractall()

    def __compress(self, checksum):
        with open('timetable.db', 'rb') as f_in:
            with gzip.open('{}.db.gz'.format(checksum), 'wb') as f_out:
                shutil.copyfileobj(f_in, f_out)

        Path('timetable.db').unlink()

    def __archive(self, name, checksum, size_u, size_c):
        metadata = {'size_uncompressed': size_u, 'size_compressed': size_c,
                    'id': checksum}
        start_date, end_date = name.split('_')
        metadata['start'] = start_date
        metadata['end'] = end_date
        self.__metadata.append(metadata)

    def __tidy_up(self):
        names = ['_'.join((row['start'], row['end'])) for row in
                 self.__metadata]
        to_stay = [name for name in names if self.__is_valid(name)
                   or self.__will_valid(name)]
        to_stay = self.__clean_overlapping(to_stay)
        to_remove = [name for name in names if name not in to_stay]
        to_remove = [row['id'] for row in self.__metadata
                     if '_'.join((row['start'], row['end'])) in to_remove]

        for name in to_remove:
            Path('{}.db.gz'.format(name)).unlink


class TimetableConverter:
    __BUF_SIZE = 65536

    def __call__(self):
        return self.__convert()

    def __convert(self):
        connection = sqlite3.connect('timetable.db')
        self.__cursor = connection.cursor()
        self.__create_tables()
        self.__insert_agency()
        self.__insert_stops()
        self.__insert_routes()
        self.__insert_trips()
        self.__insert_stop_times()
        self.__insert_calendar()
        self.__insert_calendar_dates()
        self.__insert_shapes()
        self.__insert_feed_info()

        self.__create_indexes()

        connection.commit()
        checksum = self.__hash_file('timetable.db')
        print(checksum)
        return checksum

    @classmethod
    def __hash_file(cls, file):
        checksum = hashlib.sha256()

        with open(file, 'rb') as f:
            while True:
                data = f.read(cls.__BUF_SIZE)
                if not data:
                    break
                checksum.update(data)

        return checksum.hexdigest()

    def __insert_agency(self):
        with open('agency.txt', 'r') as csvfile:
            is_header_parsed = False
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader:
                if not is_header_parsed:
                    is_header_parsed = True
                    continue
                self.__cursor.execute('''insert into agency values(?, ?, ?, ?, ?,
                                    ?)''', row)

    def __insert_stops(self):
        with open('stops.txt', 'r') as csvfile:
            is_header_parsed = False
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader:
                if not is_header_parsed:
                    is_header_parsed = True
                    continue
                self.__cursor.execute('''insert into stops values(?, ?, ?, ?, ?,
                                    ?)''', row)

    def __insert_routes(self):
        with open('routes.txt', 'r') as csvfile:
            is_header_parsed = False
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader:
                if not is_header_parsed:
                    is_header_parsed = True
                    continue
                self.__cursor.execute('''insert into routes values(?, ?, ?, ?, ?,
                                    ?, ?, ?)''', row)

    def __insert_trips(self):
        with open('trips.txt', 'r') as csvfile:
            is_header_parsed = False
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader:
                if not is_header_parsed:
                    is_header_parsed = True
                    continue
                self.__cursor.execute('''insert into trips values(?, ?, ?, ?, ?,
                                    ?, ?)''', row)

    def __insert_stop_times(self):
        with open('stop_times.txt', 'r') as csvfile:
            is_header_parsed = False
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader:
                if not is_header_parsed:
                    is_header_parsed = True
                    continue
                self.__cursor.execute('''insert into stop_times values(?, ?, ?,
                                    ?, ?, ?, ?, ?)''', row)

    def __insert_calendar(self):
        with open('calendar.txt', 'r') as csvfile:
            is_header_parsed = False
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader:
                if not is_header_parsed:
                    is_header_parsed = True
                    continue
                self.__cursor.execute('''insert into calendar values(?, ?, ?, ?,
                                    ?, ?, ?, ?, ?, ?)''', row)

    def __insert_calendar_dates(self):
        with open('calendar_dates.txt', 'r') as csvfile:
            is_header_parsed = False
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader:
                if not is_header_parsed:
                    is_header_parsed = True
                    continue
                self.__cursor.execute('''insert into calendar_dates values(?, ?,
                                    ?)''', row)

    def __insert_shapes(self):
        with open('shapes.txt', 'r') as csvfile:
            is_header_parsed = False
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader:
                if not is_header_parsed:
                    is_header_parsed = True
                    continue
                self.__cursor.execute('''insert into shapes values(?, ?, ?,
                                    ?)''', row)

    def __insert_feed_info(self):
        with open('feed_info.txt', 'r') as csvfile:
            is_header_parsed = False
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader:
                if not is_header_parsed:
                    is_header_parsed = True
                    continue
                self.__cursor.execute('''insert into feed_info values(?, ?, ?, ?,
                                    ?)''', row)

    def __create_tables(self):
        self.__cursor.execute('''create table agency(agency_id TEXT PRIMARY KEY,
                   agency_name TEXT,
                   agency_url TEXT,
                   agency_timezone TEXT,
                   agency_phone TEXT,
                   agency_lang TEXT)''')
        self.__cursor.execute('''create table stops(stop_id TEXT PRIMARY KEY,
                   stop_code TEXT,
                   stop_name TEXT,
                   stop_lat DOUBLE,
                   stop_lon DOUBLE,
                   zone_id TEXT)''')
        self.__cursor.execute('''create table routes(route_id TEXT PRIMARY KEY,
                   agency_id TEXT,
                   route_short_name TEXT,
                   route_long_name TEXT,
                   route_desc TEXT,
                   route_type INTEGER,
                   route_color TEXT,
                   route_text_color TEXT,
                   FOREIGN KEY(agency_id) REFERENCES agency(agency_id))''')
        self.__cursor.execute('''create table trips(route_id TEXT,
                   service_id TEXT,
                   trip_id TEXT PRIMARY KEY,
                   trip_headsign TEXT,
                   direction_id INTEGER,
                   shape_id TEXT,
                   wheelchair_accessible BOOL,
                   FOREIGN KEY(route_id) REFERENCES routes(route_id),
                   FOREIGN KEY(service_id) REFERENCES calendar(service_id),
                   FOREIGN KEY(shape_id) REFERENCES shapes(shape_id))''')
        self.__cursor.execute('''create table stop_times(trip_id TEXT,
                   arrival_time TEXT,
                   departure_time TEXT,
                   stop_id TEXT,
                   stop_sequence INTEGER,
                   stop_headsign TEXT,
                   pickup_type INTEGER,
                   drop_off_type INTEGER,
                   FOREIGN KEY(trip_id) REFERENCES trips(trip_id),
                   FOREIGN KEY(stop_id) REFERENCES stops(stop_id))''')
        self.__cursor.execute('''create table calendar(service_id TEXT PRIMARY KEY,
                   monday TEXT,
                   tuesday TEXT,
                   wednesday TEXT,
                   thursday TEXT,
                   friday TEXT,
                   saturday TEXT,
                   sunday TEXT,
                   start_date TEXT,
                   end_date TEXT)''')
        self.__cursor.execute('''create table calendar_dates(service_id TEXT,
                   date TEXT,
                   exception_type INTEGER,
                   FOREIGN KEY(service_id) REFERENCES calendar(service_id))''')
        self.__cursor.execute('''create table shapes(shape_id TEXT,
                   shape_pt_lat DOUBLE,
                   shape_pt_lon DOUBLE,
                   shape_pt_sequence INTEGER)''')
        self.__cursor.execute('''create table feed_info(feed_publisher_name TEXT,
                   feed_publisher_url TEXT,
                   feed_lang TEXT,
                   feed_start_date TEXT,
                   feed_end_date TEXT)''')

    def __create_indexes(self):
        self.__cursor.execute('''create index ix_stop_times__stop
                   on stop_times(stop_id)''')
        self.__cursor.execute('''create index ix_stop_times__trip
                   on stop_times(trip_id)''')
        self.__cursor.execute('''create index ix_shapes__shape
                   on shapes(shape_id)''')


if __name__ == '__main__':
    downloader = TimetableDownloader()
    downloader()