source: main/trunk/model-sites-dev/eurovision-lod/collect/eurovision/prepare/voting-excel/xlsx-tocountry-jsonmetadata.py@ 34919

Last change on this file since 34919 was 34919, checked in by davidb, 3 years ago

Additional metadata now stored

  • Property svn:executable set to *
File size: 8.7 KB
Line 
1#!/usr/bin/env python
2
3from __future__ import print_function
4
5import os
6import re
7import sys
8import json
9
10import argparse
11import openpyxl
12
13import util
14import xlsxutil
15
16jury_from_countries = {}
17tele_from_countries = {}
18
19
20def create_to_country_voting_groups(data_hashmap_array):
21
22 # Example values for header-names
23 # (semi-) final: f, sf
24 # Jury or Televoting: J, T
25 # Year: 1975, ...
26 # To country: Belgium
27 # From country: Belgium
28 # Edition: 1975f, 1975sf
29
30
31 # Sort so array entries are grouped by the country receiving the votes in a given year
32 data_hashmap_array.sort(key=xlsxutil.sortkey_year_to_country)
33
34
35 # Debug output
36 #
37 # for data_hashmap in data_hashmap_array:
38 # print(data_hashmap.get('To country'), data_hashmap.get('Year'), data_hashmap.get('Points'), "(Points from " + data_hashmap.get('From country') + ")")
39
40
41 # Build array of country groups
42 # A country grouping includes all the votes that country receive that year
43 country_groups = []
44
45 prev_data_hashmap = data_hashmap_array[0]
46 country_group = [ ]
47
48 i = 1
49 num_rows = len(data_hashmap_array)
50
51 while (i < num_rows):
52 country_group.append(prev_data_hashmap)
53 data_hashmap = data_hashmap_array[i]
54
55 if (data_hashmap.get('To country') != prev_data_hashmap.get('To country')):
56 # moving on to a new country group
57 country_groups.append(country_group)
58 country_group = [ ]
59
60 prev_data_hashmap = data_hashmap
61 i = i + 1
62
63 country_group.append(prev_data_hashmap)
64 country_groups.append(country_group)
65
66 return country_groups
67
68
69def fileset_voting_for_esc_country_in_year(to_country_year_votes):
70
71 # Looking to build data-structure (for output as JSON) in the form
72 # { "FileSet":
73 # [
74 # { "FileName": "France1991\.nul" },
75 # { "Description":
76 # {
77 # "Metadata":
78 # [
79 # { "name": "Germany-J", "content": 12 }, # J = Jury Vote
80 # { "name": "Germany-T", "content": 6 }, # T = Televote (if present)
81 # ...
82 # ]
83 # }
84 # }
85 # ]
86 # }
87
88 metadata_array = []
89
90 jury_metadata_vals = []
91 tele_metadata_vals = []
92
93 to_country_jury_total = 0
94 to_country_tele_total = 0
95
96 # Use the first record to be a representative for 'top level' (tl)
97 # metadata about the votes cast 'To country'
98 tl_rec = to_country_year_votes[0]
99
100 tl_to_country = tl_rec.get('To country')
101 tl_year = tl_rec.get('Year')
102 tl_final = tl_rec.get("(semi-) final") == "f"
103
104 tl_to_country_id = re.sub(r'\s+', '', tl_to_country) + str(tl_year)
105
106 metadata_array.append({ "name": "Final","content": tl_final })
107
108 for to_country_year_vote in to_country_year_votes:
109 to_country = to_country_year_vote.get('To country')
110 year = to_country_year_vote.get('Year')
111 from_country = to_country_year_vote.get('From country')
112 vote_type = to_country_year_vote.get('Jury or Televoting')
113 points = to_country_year_vote.get('Points')
114
115 id_from_country = re.sub(r'\s+', '', from_country)
116
117 voting_rec = { "name": id_from_country+"-"+vote_type, "content": points }
118
119 metadata_array.append(voting_rec)
120
121 if (vote_type == "J"):
122 jury_metadata_vals.append(id_from_country+"-J")
123 jury_from_countries[id_from_country] = 1
124 to_country_jury_total = to_country_jury_total + points
125
126 elif (vote_type == "T"):
127 tele_metadata_vals.append(id_from_country+"-T")
128 tele_from_countries[id_from_country] = 1
129 to_country_tele_total = to_country_tele_total + points
130 else:
131 util.eprint("Warning: Unrecognized voting type: " + vote_type)
132
133 if (len(jury_metadata_vals)>0):
134 metadata_array.append({ "name": "JuryVotesJSON", "content": json.dumps(jury_metadata_vals) })
135 metadata_array.append({ "name": "JuryVotesTotal", "content": to_country_jury_total})
136 if (len(tele_metadata_vals)>0):
137 metadata_array.append({ "name": "TeleVotesJSON", "content": json.dumps(tele_metadata_vals) })
138 metadata_array.append({ "name": "TeleVotesTotal", "content": to_country_tele_total})
139
140 filename_id = tl_to_country_id + "\\.nul"
141
142 fileset = {
143 "FileSet" : [
144 { "FileName": filename_id, },
145 { "Description" : { "Metadata" : metadata_array } }
146 ]
147 }
148
149 return fileset
150
151
152def gs_directory_metadata(to_country_year_voting_groups):
153 # Next step is to express the grouped to-country voting data
154 # in the Greenstone JSON metadata format:
155
156 # { "DirectoryMetadata":
157 # [
158 # { "FileSet":
159 # [
160 # { "FileName": "France1991\.nul" },
161 # { "Description":
162 # {
163 # "Metadata":
164 # [
165 # { "name": "Germany-J", "content": "12" }, # J = Jury Vote
166 # ...
167 # ]
168 # }
169 # }
170 # ]
171 # }
172 # ...
173 # ]
174 # }
175
176 directory_metadata = []
177
178 for to_country_year_votes in to_country_year_voting_groups:
179
180 fileset = fileset_voting_for_esc_country_in_year(to_country_year_votes)
181 directory_metadata.append(fileset)
182
183 filename_id = fileset.get('FileSet')[0].get('FileName')
184 num_countries_voting_data = len(fileset.get('FileSet')[1].get('Description').get('Metadata'))
185
186 print(" " + filename_id.ljust(28) + ": " + str(num_countries_voting_data) + " votes")
187
188
189 greenstone_metadata_json = { "DirectoryMetadata": directory_metadata }
190
191 return greenstone_metadata_json
192
193
194def display_gs_head_metadata_tags():
195
196 print()
197 print()
198 print("For, e.g., '<display><format>' section of collectionConfig.xml:")
199 print()
200 print(" <gsf:headMetaTags>")
201
202 for from_country in sorted(jury_from_countries.keys()):
203 print(" <gsf:metadata name=\""+from_country+"-J\" />")
204
205 print()
206 for from_country in sorted(tele_from_countries.keys()):
207 print(" <gsf:metadata name=\""+from_country+"-T\" />")
208
209 print(" </gsf:headMetaTags>")
210
211
212if __name__ == "__main__":
213
214 parser = argparse.ArgumentParser()
215 parser.add_argument('--sheetname', help="The name of the sheet within the Excel file to extractc data from")
216 parser.add_argument('--votingtype', choices=['J','T'], help="Filter to only J=Jury or T=Tele cast votes")
217 parser.add_argument('input-file.xlsx')
218 parser.add_argument('output-file.json', nargs='?')
219
220
221 args = parser.parse_args()
222
223 sheetname = getattr(args,'sheetname');
224 voting_type = getattr(args,'votingtype');
225
226 excel_input_filename = getattr(args,'input-file.xlsx');
227 json_output_filename = getattr(args,'output-file.json');
228
229 if (json_output_filename == None):
230 json_output_filename = os.path.splitext(excel_input_filename)[0]+'.json'
231
232 worksheet = xlsxutil.load_xslx_sheet(excel_input_filename,sheetname)
233
234 data_hashmap_array = xlsxutil.convert_worksheet_to_hashmaps(worksheet)
235
236 print("Number of data rows in Excel file: " + str(len(data_hashmap_array)))
237
238 # Filter down to just the voting results concerning finals
239 data_hashmap_array_filtered = list(filter(xlsxutil.filter_finalist_votes, data_hashmap_array))
240
241
242 print("Number of finalist voting data rows: " + str(len(data_hashmap_array_filtered)))
243
244 if voting_type != None:
245 # Further filter down by the type of voting results cast
246 if (voting_type == "J"):
247 data_hashmap_array_filtered = list(filter(xlsxutil.filter_jury_votes, data_hashmap_array_filtered))
248 print("Number Jury cast data rows: " + str(len(data_hashmap_array_filtered)))
249 else:
250 # Must be "T"
251 data_hashmap_array_filtered = list(filter(xlsxutil.filter_tele_votes, data_hashmap_array_filtered))
252 print("Number Televoting cast data rows: " + str(len(data_hashmap_array_filtered)))
253
254
255 to_country_year_voting_groups = create_to_country_voting_groups(data_hashmap_array_filtered)
256
257 # Debug output
258 #
259 # print(to_country_year_voting_groups)
260
261 print()
262 print("Generating Greenstone JSON to-country voting metadata received by:")
263 greenstone_metadata_json = gs_directory_metadata(to_country_year_voting_groups)
264
265 print("Saving output as: " + json_output_filename)
266 xlsxutil.save_greenstone_json_metadata(greenstone_metadata_json,json_output_filename)
267
268 display_gs_head_metadata_tags()
269
270 print()
271
Note: See TracBrowser for help on using the repository browser.