Skip to content

Instantly share code, notes, and snippets.

@ap-Codkelden
Last active October 9, 2016 10:49
Show Gist options
  • Save ap-Codkelden/da2d03390287cec0a8344f0b43cb0ab4 to your computer and use it in GitHub Desktop.
Save ap-Codkelden/da2d03390287cec0a8344f0b43cb0ab4 to your computer and use it in GitHub Desktop.
Process map data from ATO map at infolight.org.ua
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Process map data from ATO map
# map URL is:
# http://infolight.org.ua/thememap/karta-obstriliv-ta-boyovyh-diy-u-zoni-ato-second-edition
"""
The MIT License (MIT)
Copyright (c) 2016 Renat Nasridinov, <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import argparse
import csv
import bz2
import json
import locale
import os.path
import re
import sys
import urllib.request
from datetime import datetime
class MapArgumentParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('Помилка: {}\n'.format(message))
self.print_help()
sys.exit(2)
arg_parser = MapArgumentParser(prog="Map 2.0",
usage= "вказати або URL карти на <http://infolight.org.ua> або шлях до "
"збереженого сирого JSON.\nУ разі зберігання сирих даних з сайту, вони "
"зберігаються у JSON файл з ім'ям `raw_data.json` та можуть бути оброблені "
"пізніше з використанням параметра `-j/--jsonfile`.\nОброблені дані може бути "
"збережено у файли формату JSON або CSV (і опціонально стиснено в архів "
"bzip2), файли за замовчуванням матимуь назву `data` із відповідним "
"розширенням.\nОпції відступу не працюють для збереженого файлу "
"сирих даних.",
description="Отримує дані із карти та зберігає їх як JSON-файл.",
epilog='Для відображення довгого формата дати українською необхідно мати '
'встановлену в системі відповідну локаль.')
group = arg_parser.add_mutually_exclusive_group(required=True)
group.add_argument("-j", "--jsonfile", help="Файл JSON (із масиву `features`) "
"веб-сторінки")
group.add_argument("-u", "--url", help="Отримати дані за посиланням на "
"веб-сторінку з мапою")
indent_group = arg_parser.add_mutually_exclusive_group(required=False)
indent_group.add_argument("--tabs", action='store_true', help="Формувати JSON "
"із відступами символами табуляції")
indent_group.add_argument("--spaces", dest='spaces', const=4, action='store',
nargs='?', type=int, help="Формувати JSON із відступами символами пробілу")
arg_parser.add_argument('-s', '--store', action='store_true', help='лише '
'зберегти сирі дані із карти')
arg_parser.add_argument('-l', '--longdate', action='store_true',
help='використовувати довгий формат дати (`23 сер 2016`) замість '
'короткого (`23.08.2016`)',)
arg_parser.add_argument('-a', '--ascii', action='store_true', help='вивести '
'ASCII-сумісний JSON-файл')
arg_parser.add_argument('-b', '--bzip', action='store_true', help='запакувати '
'CSV або JSON-файл у gZIP-архів')
arg_parser.add_argument('-c', '--csv', action='store_true', help='зберегти '
'дані у CSV-файл замість JSON')
arg_parser.add_argument('-o', '--output', action='store', type=str, help= "ім'я"
"(без розширення) файлу для збереження даних", default="data")
class Error(Exception):
pass
class NoDataExtracted(Error):
def __init__(self, message):
self.message = message
class NoJSONFileExists(Error):
def __init__(self, path):
self.path = path
self.message = "Файл `{}` не існує.".format(self.path)
class MapData:
def __init__(self, data, args):
if args.spaces:
self.json_indent = args.spaces
elif args.tabs:
self.json_indent = '\t'
else:
self.json_indent = None
self.data = data
self.DATE_TEMPLATE = "%d %b %Y" if args.longdate else "%d.%m.%Y"
self.ascii = args.ascii
self.bzip = args.bzip
self.csv = args.csv
self.output = args.output
self.place_re = re.compile("<p class=title>(.+?)</p>")
self.event_re = re.compile("<p class=clock>(\d{2}\.\d{2})\-(\d{2}\.\d{2})\s\-\s(.+?)</p>")
def _elements(self):
for i in self.data:
yield i
def _parse_html(self, dates, html):
r = {}
events_placeholder = []
events_array = [x for x in html.split(';') if x]
#for e in events_array:
for e in range(len(dates)):
if e == 0:
r['place'] = self.place_re.search(events_array[e]).group(1)
events = self.event_re.findall(events_array[e])
single_event = {'date': dates[e], 'events': [{'time_start': x[0],
'time_end': x[1], 'action': x[2]} for x in events]}
events_placeholder.append(single_event)
r['place_events'] = events_placeholder
return r
def _parse_items(self):
items = []
for e in self._elements():
try:
if 'html' in e['properties']:
if not e['properties']['html']:
continue
dates_array = [datetime.strftime(datetime.strptime(x, "%Y,%m,%d"),
self.DATE_TEMPLATE) for x \
in e['properties']['date'].split(';') if x]
events_array = e['properties']['html']
parsed_array = self._parse_html(dates_array, events_array)
parsed_array['id'], parsed_array['coordinates'] = \
e['id'], {'lon': e['geometry']['coordinates'][1], \
'lat': e['geometry']['coordinates'][0]}
items.append(parsed_array)
except KeyError:
print(e)
raise
return items
def _generate_path(self):
name = '{}.{}'.format(self.output, 'csv' if self.csv else 'json')
if self.bzip:
name = '{}.{}'.format(name, 'bz2')
return os.path.join(os.getcwd(), name)
def make_json(self):
p = self._parse_items()
if self.bzip:
with bz2.open(self._generate_path(), 'wt') as f:
f.write(json.dumps(p, f, ensure_ascii=self.ascii,
indent=self.json_indent))
else:
with open(self._generate_path(), 'w', encoding="utf-8") as f:
json.dump(p, f, ensure_ascii=self.ascii, indent=self.json_indent)
return 0
def make_csv(self):
fieldnames = ['id','place','lat','lon','date','time_start', 'time_end',
'action',]
out_rows = []
j = self._parse_items()
for r in j:
for e in r['place_events']:
for action in e['events']:
time_start, time_end, action, id_, event_date, place, lon, \
lat = action['time_start'], action['time_end'], \
action['action'], r['id'], e['date'], r['place'], \
r['coordinates']['lon'], r['coordinates']['lat']
row = {'id':id_,'place':place,'lat':lat,'lon':lon,
'date':event_date,'time_start':time_start,
'time_end':time_end,'action':action,}
out_rows.append(row)
if self.bzip:
with bz2.open(self._generate_path(), 'wt') as bz2_csvfile:
writer = csv.DictWriter(bz2_csvfile, fieldnames=fieldnames)
writer.writeheader()
for r in out_rows:
writer.writerow(r)
else:
with open(self._generate_path(), 'w', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for r in out_rows:
writer.writerow(r)
return 0
def retreive_raw_data(url, store=False):
p = json_data = None
feat_regex = re.compile("features\(\[(.+?)\]\)")
no_data_error_msg = 'З сайту отримано дані, що не містять інформації ' \
'про бойові зіткнення'
try:
with urllib.request.urlopen(url) as response:
html = response.read()
except:
print("Помилка отримання даних з сайту.")
sys.exit(1)
try:
for i in [y.strip() for y in str(html,'utf-8').split('\n')]:
if i.startswith('.container'):
p = i
break
if not p:
raise NoDataExtracted(no_data_error_msg)
m = feat_regex.findall(p)
if not m:
raise NoDataExtracted(no_data_error_msg)
for i in m:
i = json.loads('[{}]'.format(i.replace("'",'"')))
if i[0]['geometry']['type'].lower() == "point":
json_data = i
break
if not json:
raise NoDataExtracted(no_data_error_msg)
except NoDataExtracted as e:
print(e.message)
sys.exit(1)
else:
del m
if not store:
return json_data
else:
try:
with open('raw_data.json', 'w', encoding="utf-8") as f:
json.dump(json_data, f, ensure_ascii=True)
except:
print("Помилка зберігання файлу.\nExit code: 1.")
exit_code = 1
else:
print('Файл сирих даних `raw_data.json` збережено.')
exit_code = 0
finally:
sys.exit(exit_code)
def read_json(json_filename):
try:
with open(json_filename) as f:
json_data = json.load(f)
except json.decoder.JSONDecodeError:
print("Помилка зчитування файла, можливо це не JSON або файл пустий.")
sys.exit(1)
else:
return json_data
def load_json_from_file(json_filename):
try:
json_file = os.path.isfile(json_filename)
if not json_file:
raise NoJSONFileExists(json_filename)
except NoJSONFileExists as e:
print(e.message)
sys.exit(1)
else:
return read_json(json_filename)
def main():
results = arg_parser.parse_args()
if not results.longdate:
try:
if sys.platform in ['linux', 'linux2', 'darwin']:
locale.setlocale(locale.LC_ALL, "uk_UA.UTF-8")
elif sys.platform == 'win32':
locale.setlocale(locale.LC_ALL, locale='ukr_ukr')
except:
print("Українська локаль відсутня, буде використано системну.")
if results.jsonfile:
j = load_json_from_file(results.jsonfile)
elif results.url:
j = retreive_raw_data(results.url, results.store)
map_data = MapData(j, results)
if results.csv:
func = map_data.make_csv
else:
func = map_data.make_json
res = func()
if res == 0:
result_msg = 'Дані успішно збережено.'
else:
result_msg = 'Зберігання даних зазнало краху.'
print(result_msg)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment