-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProcessDayStats.py
164 lines (136 loc) · 5.21 KB
/
ProcessDayStats.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Script to process all per-day summaries of locations found in TV news .seg
files (in geoCache/dayStats/) and write out the aggregated data into
.json files (in the json/ folder) at daily, weekly, and yearly granularities
that the newsscope.js Javascript code can then read when rendering the
NewsSCOPE interface.
"""
import os
import json
import sys
import datetime
import pycountry
reload(sys)
sys.setdefaultencoding('utf8')
jsonDir = './json/'
dayFiles = [ f for f in os.listdir('./geoCache/dayStats/') if os.path.isfile(os.path.join('./geoCache/dayStats/', f)) ]
dayFiles.sort()
thisMonth = ''
thisYear = ''
monthData = { 'allPlaces':{}, 'netPlaces':{} }
yearData = { 'allPlaces':{}, 'netPlaces':{} }
def processDayFile(dayPath):
global monthData, yearData
allSection = True
day = dayPath.split('.')[0]
dayData = { 'allPlaces':{}, 'netPlaces':{} }
with open(os.path.join('./geoCache/dayStats/', dayPath), 'r') as dayFile:
print "processing " + dayPath
for line in dayFile:
lineArray = line.strip().split("\t")
if (lineArray[0] == 'LAT'):
allSection = True
continue
elif (lineArray[0] == 'NETWORK'):
allSection = False
continue
# Parse coordinate-based or network-based sections of the daily stats
# file (code is ugly, I know)
if (allSection == True):
network = None
lat = lineArray[0]
lon = lineArray[1]
name = lineArray[2]
count = lineArray[3]
ccode = lineArray[4]
ptype = lineArray[5]
fcode = lineArray[6]
else:
network = lineArray[0]
lat = lineArray[1]
lon = lineArray[2]
name = lineArray[3]
count = lineArray[4]
ccode = lineArray[5]
ptype = lineArray[6]
fcode = lineArray[7]
"""
Implement various ad-hoc corrections for the returned place matches,
based mostly on the detected place's country code. Some of these
are hacks to make the results better, while others deal with geo-
political realities (e.g., Yugoslavia no longer exists).
"""
# Antarctica is a weird trash bin for misplaced locations, so ignore
# them.
if ((ccode == 'AQ') and (name.lower() != "antarctica")):
continue
elif (ccode == 'YU'):
countryID = 'YUG'
countryName = "Yugoslavia"
elif (ccode == 'CS'):
countryID = 'SCG'
countryName = "Serbia and Montenegro"
elif (ccode == 'XK'):
countryID = 'RKS'
countryName = "Kosovo"
elif (ccode == 'GC'):
countryID = 'GC'
countryName = "Gulf Cooperation Council"
elif (ccode == 'IC'):
countryID = 'ISL'
countryName = "Iceland"
else:
country = pycountry.historic_countries.get(alpha2=ccode)
countryID = country.alpha3
countryName = country.name
dayData = addPlace(dayData, allSection, {'lat':lat, 'lon':lon, 'name':name, 'count':count, 'country':countryID, 'type':ptype, 'countryName':countryName, 'featureCode':fcode}, network)
monthData = addPlace(monthData, allSection, {'lat':lat, 'lon':lon, 'name':name, 'count':count, 'country':countryID, 'type':ptype, 'countryName':countryName, 'featureCode':fcode}, network)
yearData = addPlace(yearData, allSection, {'lat':lat, 'lon':lon, 'name':name, 'count':count, 'country':countryID, 'type':ptype, 'countryName':countryName, 'featureCode':fcode}, network)
with open(jsonDir + day + '.json', 'w') as jsonFile:
json.dump(dayData, jsonFile)
# Function to add a place to the JSON summary of a given time period
# (day, month, year)
def addPlace(fileData, allSection, placeData, network):
coords = str(placeData['lat']) + "," + str(placeData['lon'])
if (allSection == True):
if (coords in fileData['allPlaces']):
fileData['allPlaces'][coords]['count'] = int(fileData['allPlaces'][coords]['count']) + int(placeData['count'])
else:
fileData['allPlaces'][coords] = placeData
else:
if (network not in fileData['netPlaces']):
fileData['netPlaces'][network] = {}
if (coords in fileData['netPlaces'][network]):
fileData['netPlaces'][network][coords]['count'] = int(fileData['netPlaces'][network][coords]['count']) + int(placeData['count'])
else:
fileData['netPlaces'][network][coords] = placeData
return fileData
# MAIN
for dayPath in dayFiles:
month = '-'.join(dayPath.split('-')[0:2])
year = dayPath.split('-')[0]
if (int(year) != 2016):
continue
if (month != thisMonth):
if (thisMonth == ''):
thisMonth = month
else:
with open(jsonDir + thisMonth + '.json', 'w') as jsonFile:
json.dump(monthData, jsonFile)
thisMonth = month
monthData = { 'allPlaces':{}, 'netPlaces':{} }
if (year != thisYear):
if (thisYear == ''):
thisYear = year
else:
with open(jsonDir + thisYear + '.json', 'w') as jsonFile:
json.dump(yearData, jsonFile)
thisYear = year
yearData = { 'allPlaces':{}, 'netPlaces':{} }
processDayFile(dayPath)
with open(jsonDir + year + '.json', 'w') as jsonFile:
json.dump(yearData, jsonFile)
with open(jsonDir + month + '.json', 'w') as jsonFile:
json.dump(monthData, jsonFile)