├── LICENSE ├── README.md ├── db_to_gtfs.py ├── feed_stations.list └── requirements.txt /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # db-to-gtfs 2 | 3 | Convert the timetable data published through the [DB API](http://data.deutschebahn.com/apis/fahrplan/) to a GTFS feed. 4 | 5 | An example feed valid from February 28th to May 1rst can be found [here](http://patrickbrosi.de/de/projects/dbgtfs). 6 | 7 | **Update:** A complete GTFS feed for Germany (including busses, subways, trams, long distance, regional and urban rail) can now be found here: [http://gtfs.de](https://gtfs.de) 8 | 9 | ## Usage 10 | 11 | Get a GTFS feed valid from May 1st to August 1st 2016 12 | 13 | $ ./db_to_gtfs.py --api-key --start-date 2016-5-1 --end-date 2016-8-1 14 | 15 | ### Method 16 | 17 | The script begins at seed stations (Berlin Hbf, by default) and crawls to every station reachable by trips from the seed stations. Trips, routes and service dates are collected on the way and ultimately written to the GTFS files. 18 | 19 | ## Flags 20 | See 21 | 22 | $ ./db_to_gtfs.py --help 23 | 24 | for available command line arguments. 25 | 26 | ## Obtain API key 27 | 28 | See http://data.deutschebahn.com/apis/fahrplan/ 29 | 30 | ## License 31 | 32 | See LICENSE. 33 | -------------------------------------------------------------------------------- /db_to_gtfs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- encoding: utf-8 -*- 3 | """ 4 | DB API to GTFS converter- (C) 2016 by Patrick Brosi 5 | 6 | Harvests the Deutsche Bahn API and generates a GTFS feed 7 | 8 | Usage: 9 | db_to_gtfs.py --api-key= [--start-date=] [--end-date=] [--station-seed=] [--station-seed-file=] [--output-dir=] 10 | db_to_gtfs.py -h | --help 11 | db_to_gtfs.py --version 12 | 13 | Options: 14 | -h --help Show this screen. 15 | --version Show version. 16 | --start-date= Start date of the feed (current date by default) 17 | --end-date= End date of the feed (start date + 3 days by default) 18 | --station-seed= Comma separated list of seed stations (defaults to content of station-seed-file or "8011160") 19 | --station-seed-file= File containing comma-separated list of seed stations [default: feed_stations.list] 20 | --output-dir= Output directory [default: .] 21 | --api-key= DB-API-Key 22 | """ 23 | 24 | import urllib2 25 | import json 26 | import string 27 | import time 28 | import unicodecsv as csv 29 | import HTMLParser 30 | import os 31 | from dateutil.parser import parse as dateparse 32 | from datetime import timedelta 33 | from sets import Set 34 | import logging 35 | FORMAT = "%(message)s" 36 | #FORMAT = "%(asctime)-15s %(message)s" 37 | logging.basicConfig(level=logging.INFO,format=FORMAT) 38 | 39 | DEP_URL = 'http://open-api.bahn.de/bin/rest.exe/departureBoard?authKey=$key&lang=de&id=00$id&date=$date&time=$time&format=json' 40 | STATION_URL = 'http://open-api.bahn.de/bin/rest.exe/location.name?authKey=$key&lang=de&input=$search&format=json' 41 | MAX_TIMEOUT = 8192 42 | 43 | class DBApiToGTFS(object): 44 | 45 | """A GTFS converter for the DB API""" 46 | 47 | def __init__(self, options): 48 | self.stops = {} 49 | self.trips = [] 50 | self.routes = [] 51 | self.agencies = [] 52 | self.calendar_dates = [] 53 | self.processed = [] 54 | self.start_date = options['start_date'] 55 | self.end_date = options['end_date'] 56 | self.out_dir = options['output_dir'] 57 | self.htmlparser = HTMLParser.HTMLParser() 58 | self.unproced_counter = 0 59 | self.api_key = options['api_key'] 60 | 61 | def process_station_by_id(self, sid): 62 | """Process a station by its id""" 63 | if not int(sid) in self.stops: 64 | # get the 'official' writing of station name 65 | det = self.get_station_detail(sid) 66 | if det == None: 67 | logging.warn('Warning: station %d not found.', sid) 68 | self.process_station_by_ob(det) 69 | 70 | def process_station_by_ob(self, station): 71 | """Process a station by its object, already containing needed information""" 72 | if station == None: 73 | return 74 | if not int(station['id']) in self.stops: 75 | gtfs_station = self.get_station_ob(station) 76 | self.stops[int(station['id'])] = gtfs_station 77 | self.unproced_counter = self.unproced_counter + 1 78 | 79 | def get_all_trips_for_stop(self, stop): 80 | """Read all trips for a stop object""" 81 | if stop['trips_fetched']: 82 | return 83 | 84 | stop['trips_fetched'] = True 85 | 86 | while stop['last_date'] < self.end_date: 87 | logging.info('@ #%d (%s) on %s %s, unique trips collected: %d, unprocessed stations left: %d', stop['stop_id'], stop['stop_name'].encode('utf-8').strip(), stop['last_date'].strftime('%Y-%m-%d'), str(stop['last_check_h']) + ':' + str(stop['last_check_m']), len(self.trips), self.unproced_counter) 88 | requrl = string.Template(DEP_URL).substitute({ 89 | 'id': stop['stop_id'], 90 | 'date': stop['last_date'].strftime('%Y-%m-%d'), 91 | 'time': str(stop['last_check_h']) + ':' + str(stop['last_check_m']), 92 | 'key' : self.api_key 93 | }) 94 | data = self.fetch_json(requrl) 95 | 96 | # if no trips have been found, add 24 hours to search timespan 97 | stop['last_date'] = stop['last_date'] + timedelta(days=1) 98 | 99 | if 'DepartureBoard' in data and 'Departure' in data['DepartureBoard']: 100 | # catch strange behavior of the DB xml-to-json converter... 101 | if type(data['DepartureBoard']['Departure']) is dict: 102 | data['DepartureBoard']['Departure'] = [ 103 | data['DepartureBoard']['Departure']] 104 | 105 | for dep in data['DepartureBoard']['Departure']: 106 | # update last check time... 107 | if dep['time'].split(':')[0] > stop['last_check_h']: 108 | stop['last_check_h'] = dep['time'].split(':')[0] 109 | if dep['time'].split(':')[1] > stop['last_check_m']: 110 | stop['last_check_m'] = dep['time'].split(':')[1] 111 | if dateparse(dep['date']) > stop['last_date']: 112 | stop['last_date'] = dateparse(dep['date']) 113 | 114 | # only process deps for this stop 115 | if int(dep['stopid']) == stop['stop_id']: 116 | if not self.dep_processed(dep): 117 | # we assume train ids (the 55 in "ICE 55") are 118 | # unique per day! 119 | self.process_trip(dep['JourneyDetailRef']['ref']) 120 | self.processed.append(dep) 121 | 122 | self.unproced_counter = self.unproced_counter - 1 123 | 124 | def get_first_in_list(self, obj): 125 | """Expand the strange array format of the DB json format""" 126 | if type(obj) is list: 127 | return obj[0] 128 | return obj 129 | 130 | def dep_processed(self, dep): 131 | """Check if a dearture has already been processed""" 132 | for proced in self.processed: 133 | if proced['date'] == dep['date'] and proced['direction'] == dep['direction'] and proced['name'] == dep['name']: 134 | return True 135 | return False 136 | 137 | def fetch_json(self, url): 138 | """Fetch remote json""" 139 | 140 | timeout = 1 141 | while True: 142 | try: 143 | logging.debug('Opening %s.', url) 144 | response = urllib2.urlopen(url) 145 | break 146 | except urllib2.HTTPError as err: 147 | if timeout <= MAX_TIMEOUT: 148 | logging.warn('Error opening %s, error code %d, reason is %s.', url, err.code, err.reason) 149 | logging.warn('Waiting for %ds before retrying.', timeout) 150 | time.sleep(timeout) 151 | timeout *= 2 152 | else: 153 | logging.error('Error opening %s, error code %d, reason is %s.', url, err.code, err.reason) 154 | raise err 155 | 156 | data = json.load(response) 157 | 158 | return data 159 | 160 | def process_trip(self, trip_url): 161 | """Process a fetched trip""" 162 | data = self.fetch_json(trip_url) 163 | 164 | trip = { 165 | 'stoptimes': [], 166 | 'name': '', 167 | 'type': '', 168 | 'notes': [], 169 | 'service_dates': Set() 170 | } 171 | 172 | if 'JourneyDetail' in data and 'Names' in data['JourneyDetail']: 173 | if 'errorCode' in data['JourneyDetail']: 174 | logging.warn('DB API returned error "%s" (code: %s). Proceeding...', data['JourneyDetail']['errorText'], data['JourneyDetail']['errorCode']) 175 | return None 176 | 177 | # meta data 178 | name = data['JourneyDetail']['Names']['Name'] 179 | trip['name'] = self.get_first_in_list(name).get('name') 180 | trip['type'] = self.get_first_in_list(data['JourneyDetail']['Types']['Type']).get('type') 181 | trip['agency_id'] = self.get_first_in_list(data['JourneyDetail']['Operators']['Operator']).get('name') 182 | 183 | for stoptime in data['JourneyDetail']['Stops']['Stop']: 184 | # check if this station is known 185 | self.process_station_by_ob({ 186 | 'name': stoptime['name'], 187 | 'id': stoptime['id'], 188 | 'lat': stoptime['lat'], 189 | 'lon': stoptime['lon'] 190 | }) 191 | 192 | trip['stoptimes'].append({ 193 | 'stop_id': int(stoptime['id']), 194 | 'stop_sequence': int(stoptime['routeIdx']), 195 | 'arrival_time': stoptime['arrTime'] if 'arrTime' in stoptime else stoptime['depTime'], 196 | 'departure_time': stoptime['depTime'] if 'depTime' in stoptime else stoptime['arrTime'], 197 | 'arrival_date': stoptime['arrDate'] if 'arrDate' in stoptime else stoptime['depDate'], 198 | 'departure_date': stoptime['depDate'] if 'depDate' in stoptime else stoptime['arrDate'], 199 | }) 200 | 201 | self.stops[int(stoptime['id'])]['has_trip'] = True 202 | 203 | trip['route_id'] = self.route_append(trip) 204 | 205 | # discard 'empty' trips 206 | if len(trip['stoptimes']) > 1: 207 | self.pack_trip(trip) 208 | self.trip_append(trip) 209 | 210 | def trip_compare(self, trip1, trip2): 211 | """Check if two trips are equal""" 212 | if trip1['name'] != trip2['name']: 213 | return False 214 | 215 | if trip1['type'] != trip2['type']: 216 | return False 217 | 218 | if len(trip1['stoptimes']) != len(trip2['stoptimes']): 219 | return False 220 | 221 | # check departures 222 | for i in range(0, len(trip1['stoptimes']) - 1): 223 | if trip1['stoptimes'][i]['stop_id'] != trip2['stoptimes'][i]['stop_id']: 224 | return False 225 | if trip1['stoptimes'][i]['departure_time'] != trip2['stoptimes'][i]['departure_time']: 226 | return False 227 | 228 | return True 229 | 230 | def trip_append(self, trip_add): 231 | """Append a trip or add the added trips calendar date to an existing, equal trip""" 232 | for trip in self.trips: 233 | if self.trip_compare(trip, trip_add): 234 | trip['service_dates'].add(trip_add['service_date']) 235 | return 236 | 237 | trip_add['service_dates'].add(trip_add['service_date']) 238 | self.trips.append(trip_add) 239 | 240 | # append route based on trip, return route id 241 | def route_append(self, trip): 242 | """Append a route based on a trip (if route is new), return route id""" 243 | short_name = '' 244 | long_name = trip['name'] 245 | agency_id = trip['agency_id'] 246 | 247 | for rid, route in enumerate(self.routes): 248 | if route['route_long_name'] == long_name and route['agency_id'] == agency_id: 249 | return rid 250 | 251 | self.routes.append({ 252 | 'route_short_name': short_name, 253 | 'route_long_name': long_name, 254 | 'route_type': 3 if short_name == 'Bus' else 2, 255 | 'agency_id': agency_id 256 | }) 257 | 258 | if not agency_id in self.agencies: 259 | self.agencies.append(agency_id) 260 | 261 | return len(self.routes) - 1 262 | 263 | # packs the trip, corrects overhanging times to GTFS format etc 264 | def pack_trip(self, trip): 265 | """Finalize trip""" 266 | start_date = dateparse(trip['stoptimes'][0]['departure_date']) 267 | 268 | for stoptime in trip['stoptimes']: 269 | # gtfs needs stoptimes overlapping into the following day to have 270 | # times like 25:35:00 271 | arrdelta = (dateparse(stoptime['arrival_date']) - start_date).days 272 | depdelta = ( 273 | dateparse(stoptime['departure_date']) - start_date).days 274 | if arrdelta > 0: 275 | stoptime['arrival_date'] = start_date 276 | stoptime['arrival_time'] = str(int(stoptime['arrival_time'].split(':')[0]) + 24 * arrdelta) + ":" + stoptime[ 277 | 'arrival_time'].split(':')[1] 278 | 279 | if depdelta > 0: 280 | stoptime['departure_date'] = start_date 281 | stoptime['departure_time'] = str(int(stoptime['departure_time'].split(':')[0]) + 24 * depdelta) + ":" + stoptime[ 282 | 'departure_time'].split(':')[1] 283 | 284 | trip['headsign'] = self.stops[trip['stoptimes'][-1]['stop_id']]['stop_name'] 285 | trip['service_date'] = start_date 286 | 287 | def get_station_detail(self, stat_id): 288 | """Return station detail from remote""" 289 | requrl = string.Template(STATION_URL).substitute({'search': stat_id, 'key' : self.api_key}) 290 | data = self.fetch_json(requrl) 291 | station = data.get('LocationList', {}).get('StopLocation') 292 | return station 293 | 294 | def get_station_ob(self, station_ob): 295 | """Get internal station object from remote DB object""" 296 | gtfsstation = { 297 | 'stop_id': int(station_ob['id']), 298 | 'stop_name': self.htmlparser.unescape(station_ob['name']), 299 | 'stop_lat': float(station_ob['lat']), 300 | 'stop_lon': float(station_ob['lon']), 301 | 'last_check_h': 0, 302 | 'last_check_m': 0, 303 | 'last_date': self.start_date, 304 | 'has_trip': False, 305 | 'trips_fetched': False 306 | } 307 | return gtfsstation 308 | 309 | def generate_calendar_dates(self): 310 | """Generate minimized calendar dates""" 311 | for trip in self.trips: 312 | for sid, cdate in enumerate(self.calendar_dates): 313 | if cdate == trip['service_dates']: 314 | trip['service_id'] = sid 315 | break 316 | 317 | if 'service_id' not in trip: 318 | self.calendar_dates.append(trip['service_dates']) 319 | trip['service_id'] = len(self.calendar_dates) - 1 320 | 321 | def write_trips(self): 322 | """Write trips to file""" 323 | with open(os.path.join(self.out_dir, 'trips.txt'), 'wb') as fhandle, open(os.path.join(self.out_dir, 'stop_times.txt'), 'wb') as sfhandle: 324 | trip_fieldnames = [ 325 | 'route_id', 'service_id', 'trip_id', 'trip_headsign'] 326 | trip_writer = csv.DictWriter(fhandle, delimiter=',', 327 | quotechar='"', fieldnames=trip_fieldnames) 328 | trip_writer.writeheader() 329 | 330 | stoptimes_fieldnames = [ 331 | 'trip_id', 'arrival_time', 'departure_time', 'stop_id', 'stop_sequence'] 332 | stoptimes_writer = csv.DictWriter(sfhandle, delimiter=',', 333 | quotechar='"', fieldnames=stoptimes_fieldnames) 334 | stoptimes_writer.writeheader() 335 | 336 | for tid, trip in enumerate(self.trips): 337 | trip_writer.writerow({ 338 | 'route_id': trip['route_id'], 339 | 'service_id': trip['service_id'], 340 | 'trip_id': tid, 341 | 'trip_headsign': trip['headsign'] 342 | }) 343 | 344 | for stoptime in trip['stoptimes']: 345 | stoptimes_writer.writerow({ 346 | 'trip_id': tid, 347 | 'arrival_time': stoptime['arrival_time'] + ':00', 348 | 'departure_time': stoptime['departure_time'] + ':00', 349 | 'stop_id': stoptime['stop_id'], 350 | 'stop_sequence': stoptime['stop_sequence'] 351 | }) 352 | 353 | def write_routes(self): 354 | """Write routes to file""" 355 | with open(os.path.join(self.out_dir, 'routes.txt'), 'wb') as fhandle: 356 | route_fieldnames = [ 357 | 'route_id', 'route_short_name', 'route_long_name', 'route_type', 'agency_id'] 358 | route_writer = csv.DictWriter(fhandle, delimiter=',', 359 | quotechar='"', fieldnames=route_fieldnames) 360 | route_writer.writeheader() 361 | 362 | for rid, route in enumerate(self.routes): 363 | route_writer.writerow({ 364 | 'route_id': rid, 365 | 'route_short_name': route['route_short_name'], 366 | 'route_long_name': route['route_long_name'], 367 | 'route_type': route['route_type'], 368 | 'agency_id': route['agency_id'] 369 | }) 370 | 371 | def write_stops(self): 372 | """Write stops to file""" 373 | with open(os.path.join(self.out_dir, 'stops.txt'), 'wb') as fhandle: 374 | route_fieldnames = ['stop_id', 'stop_name', 'stop_lat', 'stop_lon'] 375 | route_writer = csv.DictWriter(fhandle, delimiter=',', 376 | quotechar='"', fieldnames=route_fieldnames) 377 | route_writer.writeheader() 378 | 379 | for stop in self.stops.itervalues(): 380 | if not stop['has_trip']: 381 | continue 382 | 383 | route_writer.writerow({ 384 | 'stop_id': stop['stop_id'], 385 | 'stop_name': stop['stop_name'], 386 | 'stop_lat': stop['stop_lat'], 387 | 'stop_lon': stop['stop_lon'] 388 | }) 389 | 390 | def write_calendar_dates(self): 391 | """Write calendar dates to file""" 392 | with open(os.path.join(self.out_dir, 'calendar_dates.txt'), 'wb') as fhandle: 393 | calendar_fieldnames = ['service_id', 'date', 'exception_type'] 394 | calendar_writer = csv.DictWriter(fhandle, delimiter=',', 395 | quotechar='"', fieldnames=calendar_fieldnames) 396 | calendar_writer.writeheader() 397 | 398 | for sid, cdate in enumerate(self.calendar_dates): 399 | for date in cdate: 400 | calendar_writer.writerow({ 401 | 'service_id': sid, 402 | 'date': date.strftime('%Y%m%d'), 403 | 'exception_type': 1 404 | }) 405 | 406 | def write_agencies(self): 407 | """Write agencies to file""" 408 | with open(os.path.join(self.out_dir, 'agency.txt'), 'wb') as fhandle: 409 | agency_fieldnames = [ 410 | 'agency_id', 'agency_name', 'agency_url', 'agency_timezone', 'agency_lang'] 411 | agency_writer = csv.DictWriter(fhandle, delimiter=',', 412 | quotechar='"', fieldnames=agency_fieldnames) 413 | agency_writer.writeheader() 414 | 415 | for agency in self.agencies: 416 | agency_writer.writerow({ 417 | 'agency_id': agency, 418 | 'agency_name': agency, 419 | 'agency_url': 'http://www.bahn.de', 420 | 'agency_timezone': 'Europe/Berlin', 421 | 'agency_lang': 'de' 422 | }) 423 | 424 | def write_feed_info(self): 425 | """Write feed_info to file""" 426 | with open(os.path.join(self.out_dir, 'feed_info.txt'), 'wb') as fhandle: 427 | fieldnames = [ 428 | 'feed_publisher_name', 'feed_publisher_url', 'feed_lang', 'feed_start_date', 'feed_end_date'] 429 | writer = csv.DictWriter(fhandle, delimiter=',', 430 | quotechar='"', fieldnames=fieldnames) 431 | writer.writeheader() 432 | 433 | writer.writerow({ 434 | 'feed_publisher_name': 'DB-to-GTFS converter, based on DB-API data', 435 | 'feed_publisher_url': 'http://www.patrickbrosi.de/de/dbgtfs', 436 | 'feed_lang': 'de', 437 | 'feed_start_date': self.start_date.strftime('%Y%m%d'), 438 | 'feed_end_date': self.end_date.strftime('%Y%m%d') 439 | }) 440 | 441 | def get_unfetched_station_id(self): 442 | """Return a station that has not yet been trip-processed""" 443 | for sid in self.stops: 444 | if not self.stops[sid]['trips_fetched']: 445 | return self.stops[sid]['stop_id'] 446 | return None 447 | 448 | def read_station_feeds(self, path): 449 | try: 450 | with open(path, 'r') as stationfile: 451 | stations = stationfile.read().replace('\n', '').split(',') 452 | return stations 453 | except IOError: 454 | print('Could not read station feed file %s' % path) 455 | return [] 456 | 457 | def main(options=None): 458 | if not options['--start-date']: 459 | options['--start-date'] = time.strftime("%Y-%m-%d") 460 | if not options['--end-date']: 461 | options['--end-date'] = ( 462 | dateparse(options['--start-date']) + timedelta(days=3)).strftime("%Y-%m-%d") 463 | 464 | converter = DBApiToGTFS({ 465 | 'start_date': dateparse(options['--start-date']), 466 | 'end_date': dateparse(options['--end-date']), 467 | 'output_dir': options['--output-dir'], 468 | 'api_key' : options['--api-key'] 469 | }) 470 | 471 | if options['--station-seed']: 472 | station_seed = options['--station-seed'].split(',') 473 | else: 474 | # try to use station seed file 475 | station_seed = converter.read_station_feeds(options['--station-seed-file']) 476 | 477 | if not station_seed: 478 | # initialize with Berlin Hbf by default 479 | station_seed = ['8011160'] 480 | 481 | logging.info('Generating GTFS feed from %s to %s', options['--start-date'], options['--end-date']) 482 | 483 | for idx, seed in enumerate(station_seed): 484 | if len(station_seed) > 10: 485 | print 'Fetching details for station "%s" (%i / %i)' % (seed, idx, len(station_seed)) 486 | converter.process_station_by_id(int(seed)) 487 | 488 | sid = converter.get_unfetched_station_id() 489 | while sid: 490 | converter.get_all_trips_for_stop(converter.stops[sid]) 491 | sid = converter.get_unfetched_station_id() 492 | 493 | converter.generate_calendar_dates() 494 | 495 | converter.write_trips() 496 | converter.write_stops() 497 | converter.write_calendar_dates() 498 | converter.write_routes() 499 | converter.write_agencies() 500 | converter.write_feed_info() 501 | 502 | logging.info('Done, written %d trips, %d routes, %s services, %s stops' % (len(converter.trips), len(converter.routes), len(converter.calendar_dates), len(converter.stops))) 503 | 504 | if __name__ == '__main__': 505 | from docopt import docopt 506 | 507 | arguments = docopt( 508 | __doc__, version='DB Api to GTFS converter 0,1, 2016 by Patrick Brosi') 509 | try: 510 | main(options=arguments) 511 | except KeyboardInterrupt: 512 | logging.error("Cancelled by user.") 513 | exit(0) 514 | -------------------------------------------------------------------------------- /feed_stations.list: -------------------------------------------------------------------------------- 1 | 5100005, 2 | 5100009, 3 | 5100010, 4 | 5100013, 5 | 5100015, 6 | 5100026, 7 | 5100032, 8 | 5100056, 9 | 5100061, 10 | 5100065, 11 | 5100066, 12 | 5100067, 13 | 5100071, 14 | 5100081, 15 | 5100082, 16 | 5101104, 17 | 5101307, 18 | 5103284, 19 | 5400001, 20 | 5400003, 21 | 5400014, 22 | 5400019, 23 | 5400022, 24 | 5400161, 25 | 5400201, 26 | 5400202, 27 | 5500003, 28 | 5500006, 29 | 5500008, 30 | 5500009, 31 | 5500016, 32 | 5500017, 33 | 5500080, 34 | 5500913, 35 | 5501413, 36 | 5600025, 37 | 5600081, 38 | 5600207, 39 | 5603745, 40 | 8000001, 41 | 8000002, 42 | 8000004, 43 | 8000009, 44 | 8000010, 45 | 8000013, 46 | 8000014, 47 | 8000020, 48 | 8000025, 49 | 8000026, 50 | 8000029, 51 | 8000031, 52 | 8000036, 53 | 8000039, 54 | 8000041, 55 | 8000044, 56 | 8000045, 57 | 8000049, 58 | 8000050, 59 | 8000055, 60 | 8000057, 61 | 8000058, 62 | 8000059, 63 | 8000064, 64 | 8000067, 65 | 8000068, 66 | 8000070, 67 | 8000073, 68 | 8000076, 69 | 8000078, 70 | 8000080, 71 | 8000082, 72 | 8000084, 73 | 8000085, 74 | 8000086, 75 | 8000087, 76 | 8000091, 77 | 8000093, 78 | 8000095, 79 | 8000096, 80 | 8000098, 81 | 8000103, 82 | 8000105, 83 | 8000107, 84 | 8000108, 85 | 8000111, 86 | 8000112, 87 | 8000115, 88 | 8000116, 89 | 8000118, 90 | 8000122, 91 | 8000124, 92 | 8000127, 93 | 8000128, 94 | 8000129, 95 | 8000139, 96 | 8000141, 97 | 8000142, 98 | 8000147, 99 | 8000149, 100 | 8000150, 101 | 8000152, 102 | 8000155, 103 | 8000156, 104 | 8000159, 105 | 8000162, 106 | 8000163, 107 | 8000168, 108 | 8000169, 109 | 8000170, 110 | 8000174, 111 | 8000176, 112 | 8000177, 113 | 8000181, 114 | 8000183, 115 | 8000189, 116 | 8000191, 117 | 8000192, 118 | 8000194, 119 | 8000196, 120 | 8000197, 121 | 8000199, 122 | 8000206, 123 | 8000207, 124 | 8000211, 125 | 8000213, 126 | 8000225, 127 | 8000230, 128 | 8000235, 129 | 8000236, 130 | 8000237, 131 | 8000238, 132 | 8000240, 133 | 8000244, 134 | 8000249, 135 | 8000250, 136 | 8000252, 137 | 8000253, 138 | 8000257, 139 | 8000259, 140 | 8000260, 141 | 8000261, 142 | 8000262, 143 | 8000263, 144 | 8000266, 145 | 8000271, 146 | 8000274, 147 | 8000275, 148 | 8000279, 149 | 8000283, 150 | 8000284, 151 | 8000286, 152 | 8000290, 153 | 8000291, 154 | 8000294, 155 | 8000297, 156 | 8000298, 157 | 8000301, 158 | 8000302, 159 | 8000306, 160 | 8000307, 161 | 8000309, 162 | 8000310, 163 | 8000312, 164 | 8000314, 165 | 8000316, 166 | 8000318, 167 | 8000320, 168 | 8000322, 169 | 8000323, 170 | 8000329, 171 | 8000331, 172 | 8000337, 173 | 8000349, 174 | 8000368, 175 | 8000377, 176 | 8000385, 177 | 8000483, 178 | 8000522, 179 | 8000571, 180 | 8000664, 181 | 8000667, 182 | 8000718, 183 | 8000732, 184 | 8000770, 185 | 8000774, 186 | 8000800, 187 | 8000879, 188 | 8000891, 189 | 8000935, 190 | 8000943, 191 | 8001055, 192 | 8001443, 193 | 8001751, 194 | 8001767, 195 | 8001768, 196 | 8001787, 197 | 8001844, 198 | 8001995, 199 | 8002041, 200 | 8002206, 201 | 8002218, 202 | 8002461, 203 | 8002548, 204 | 8002549, 205 | 8002553, 206 | 8002554, 207 | 8002757, 208 | 8002806, 209 | 8003016, 210 | 8003036, 211 | 8003065, 212 | 8003102, 213 | 8003184, 214 | 8003200, 215 | 8003330, 216 | 8003487, 217 | 8003494, 218 | 8003515, 219 | 8003545, 220 | 8003680, 221 | 8003701, 222 | 8003866, 223 | 8003930, 224 | 8003978, 225 | 8004009, 226 | 8004124, 227 | 8004158, 228 | 8004305, 229 | 8004343, 230 | 8004449, 231 | 8004488, 232 | 8004585, 233 | 8004610, 234 | 8004751, 235 | 8004760, 236 | 8004885, 237 | 8004965, 238 | 8005362, 239 | 8005424, 240 | 8005556, 241 | 8005609, 242 | 8005661, 243 | 8006053, 244 | 8006076, 245 | 8006272, 246 | 8006369, 247 | 8006421, 248 | 8006552, 249 | 8006730, 250 | 8007768, 251 | 8010004, 252 | 8010018, 253 | 8010022, 254 | 8010033, 255 | 8010050, 256 | 8010060, 257 | 8010066, 258 | 8010073, 259 | 8010077, 260 | 8010085, 261 | 8010089, 262 | 8010093, 263 | 8010097, 264 | 8010099, 265 | 8010101, 266 | 8010113, 267 | 8010133, 268 | 8010136, 269 | 8010139, 270 | 8010159, 271 | 8010193, 272 | 8010195, 273 | 8010205, 274 | 8010216, 275 | 8010217, 276 | 8010220, 277 | 8010222, 278 | 8010224, 279 | 8010240, 280 | 8010250, 281 | 8010255, 282 | 8010268, 283 | 8010282, 284 | 8010297, 285 | 8010304, 286 | 8010324, 287 | 8010334, 288 | 8010338, 289 | 8010355, 290 | 8010361, 291 | 8010366, 292 | 8010368, 293 | 8010382, 294 | 8010396, 295 | 8010404, 296 | 8010405, 297 | 8011044, 298 | 8011051, 299 | 8011102, 300 | 8011113, 301 | 8011160, 302 | 8011191, 303 | 8011956, 304 | 8012183, 305 | 8012666, 306 | 8012683, 307 | 8012763, 308 | 8013470, 309 | 8070003, 310 | 8070004, 311 | 8100001, 312 | 8100002, 313 | 8100004, 314 | 8100008, 315 | 8100012, 316 | 8100013, 317 | 8100014, 318 | 8100017, 319 | 8100040, 320 | 8100041, 321 | 8100042, 322 | 8100043, 323 | 8100044, 324 | 8100060, 325 | 8100061, 326 | 8100062, 327 | 8100063, 328 | 8100064, 329 | 8100065, 330 | 8100067, 331 | 8100070, 332 | 8100071, 333 | 8100079, 334 | 8100080, 335 | 8100081, 336 | 8100085, 337 | 8100090, 338 | 8100092, 339 | 8100093, 340 | 8100095, 341 | 8100097, 342 | 8100098, 343 | 8100099, 344 | 8100102, 345 | 8100108, 346 | 8100122, 347 | 8100131, 348 | 8100132, 349 | 8100137, 350 | 8100138, 351 | 8100147, 352 | 8100150, 353 | 8100173, 354 | 8100197, 355 | 8100309, 356 | 8100507, 357 | 8100514, 358 | 8100539, 359 | 8101917, 360 | 8103000, 361 | 8200100, 362 | 8300046, 363 | 8300048, 364 | 8300076, 365 | 8300084, 366 | 8300086, 367 | 8300089, 368 | 8300092, 369 | 8300093, 370 | 8300094, 371 | 8300098, 372 | 8300101, 373 | 8300106, 374 | 8300110, 375 | 8300113, 376 | 8300115, 377 | 8300120, 378 | 8300124, 379 | 8300126, 380 | 8300130, 381 | 8300148, 382 | 8300151, 383 | 8300179, 384 | 8300217, 385 | 8300257, 386 | 8300263, 387 | 8303915, 388 | 8400051, 389 | 8400055, 390 | 8400058, 391 | 8400066, 392 | 8400071, 393 | 8400173, 394 | 8400316, 395 | 8400322, 396 | 8400621, 397 | 8500010, 398 | 8500023, 399 | 8500026, 400 | 8500218, 401 | 8502113, 402 | 8502119, 403 | 8503000, 404 | 8503016, 405 | 8503424, 406 | 8503504, 407 | 8506000, 408 | 8506206, 409 | 8506210, 410 | 8506302, 411 | 8506314, 412 | 8507000, 413 | 8507100, 414 | 8507483, 415 | 8507492, 416 | 8507493, 417 | 8509000, 418 | 8509002, 419 | 8509411, 420 | 8600623, 421 | 8601318, 422 | 8601512, 423 | 8601899, 424 | 8601996, 425 | 8602553, 426 | 8602722, 427 | 8602887, 428 | 8700011, 429 | 8700023, 430 | 8700031, 431 | 8700074, 432 | 8700091, 433 | 8700152, 434 | 8700271, 435 | 8704918, 436 | 8704980, 437 | 8730082, 438 | 8730086, 439 | 8800002, 440 | 8800004, 441 | 8800012 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | unicodecsv 2 | docopt 3 | python-dateutil 4 | --------------------------------------------------------------------------------