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

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

Completion of initial work on supporting from-country voting to produce docs in the DL; written, then tested with building collection. This is the result after debugging

  • Property svn:executable set to *
File size: 8.8 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 tl_to_country = tl_rec.get('To country')
100 tl_year = tl_rec.get('Year')
101 # tl_vote_type = tl_rec.get('Jury or Televoting')
102 tl_to_country_id = re.sub(r'\s+', '', tl_to_country) + str(tl_year)
103
104 for to_country_year_vote in to_country_year_votes:
105 to_country = to_country_year_vote.get('To country')
106 year = to_country_year_vote.get('Year')
107 from_country = to_country_year_vote.get('From country')
108 vote_type = to_country_year_vote.get('Jury or Televoting')
109 points = to_country_year_vote.get('Points')
110
111 id_from_country = re.sub(r'\s+', '', from_country)
112
113 voting_rec = { "name": id_from_country+"-"+vote_type, "content": points }
114
115 metadata_array.append(voting_rec)
116
117 if (vote_type == "J"):
118 jury_metadata_vals.append(id_from_country+"-J")
119 jury_from_countries[id_from_country] = 1
120 to_country_jury_total = to_country_jury_total + points
121
122 elif (vote_type == "T"):
123 tele_metadata_vals.append(id_from_country+"-T")
124 tele_from_countries[id_from_country] = 1
125 to_country_tele_total = to_country_tele_total + points
126 else:
127 util.eprint("Warning: Unrecognized voting type: " + vote_type)
128
129 if (len(jury_metadata_vals)>0):
130 metadata_array.append({ "name": "JuryVotesJSON", "content": json.dumps(jury_metadata_vals) })
131 metadata_array.append({ "name": "JuryVotesTotal", "content": to_country_jury_total})
132 if (len(tele_metadata_vals)>0):
133 metadata_array.append({ "name": "TeleVotesJSON", "content": json.dumps(tele_metadata_vals) })
134 metadata_array.append({ "name": "TeleVotesTotal", "content": to_country_tele_total})
135
136 # id_to_country = to_country_year_votes[0].get('To country')
137 # id_to_country = re.sub(r'\s+', '', id_to_country)
138 #id_year = to_country_year_votes[0].get('Year');
139 #id = id_to_country + str(id_year);
140
141 filename_id = tl_to_country_id + "\\.nul"
142
143 fileset = {
144 "FileSet" : [
145 { "FileName": filename_id, },
146 { "Description" : { "Metadata" : metadata_array } }
147 ]
148 }
149
150 return fileset
151
152
153def gs_directory_metadata(to_country_year_voting_groups):
154 # Next step is to express the grouped to-country voting data
155 # in the Greenstone JSON metadata format:
156
157 # { "DirectoryMetadata":
158 # [
159 # { "FileSet":
160 # [
161 # { "FileName": "France1991\.nul" },
162 # { "Description":
163 # {
164 # "Metadata":
165 # [
166 # { "name": "Germany-J", "content": "12" }, # J = Jury Vote
167 # ...
168 # ]
169 # }
170 # }
171 # ]
172 # }
173 # ...
174 # ]
175 # }
176
177 directory_metadata = []
178
179 for to_country_year_votes in to_country_year_voting_groups:
180
181 fileset = fileset_voting_for_esc_country_in_year(to_country_year_votes)
182 directory_metadata.append(fileset)
183
184 filename_id = fileset.get('FileSet')[0].get('FileName')
185 num_countries_voting_data = len(fileset.get('FileSet')[1].get('Description').get('Metadata'))
186
187 print(" " + filename_id.ljust(28) + ": " + str(num_countries_voting_data) + " votes")
188
189
190 greenstone_metadata_json = { "DirectoryMetadata": directory_metadata }
191
192 return greenstone_metadata_json
193
194
195def display_gs_head_metadata_tags():
196
197 print()
198 print()
199 print("For, e.g., '<display><format>' section of collectionConfig.xml:")
200 print()
201 print(" <gsf:headMetaTags>")
202
203 for from_country in sorted(jury_from_countries.keys()):
204 print(" <gsf:metadata name=\""+from_country+"-J\" />")
205
206 print()
207 for from_country in sorted(tele_from_countries.keys()):
208 print(" <gsf:metadata name=\""+from_country+"-T\" />")
209
210 print(" </gsf:headMetaTags>")
211
212
213if __name__ == "__main__":
214
215 parser = argparse.ArgumentParser()
216 parser.add_argument('--sheetname', help="The name of the sheet within the Excel file to extractc data from")
217 parser.add_argument('--votingtype', choices=['J','T'], help="Filter to only J=Jury or T=Tele cast votes")
218 parser.add_argument('input-file.xlsx')
219 parser.add_argument('output-file.json', nargs='?')
220
221
222 args = parser.parse_args()
223
224 sheetname = getattr(args,'sheetname');
225 voting_type = getattr(args,'votingtype');
226
227 excel_input_filename = getattr(args,'input-file.xlsx');
228 json_output_filename = getattr(args,'output-file.json');
229
230 if (json_output_filename == None):
231 json_output_filename = os.path.splitext(excel_input_filename)[0]+'.json'
232
233 worksheet = xlsxutil.load_xslx_sheet(excel_input_filename,sheetname)
234
235 data_hashmap_array = xlsxutil.convert_worksheet_to_hashmaps(worksheet)
236
237 print("Number of data rows in Excel file: " + str(len(data_hashmap_array)))
238
239 # Filter down to just the voting results concerning finals
240 data_hashmap_array_filtered = list(filter(xlsxutil.filter_finalist_votes, data_hashmap_array))
241
242
243 print("Number of finalist voting data rows: " + str(len(data_hashmap_array_filtered)))
244
245 if voting_type != None:
246 # Further filter down by the type of voting results cast
247 if (voting_type == "J"):
248 data_hashmap_array_filtered = list(filter(xlsxutil.filter_jury_votes, data_hashmap_array_filtered))
249 print("Number Jury cast data rows: " + str(len(data_hashmap_array_filtered)))
250 else:
251 # Must be "T"
252 data_hashmap_array_filtered = list(filter(xlsxutil.filter_tele_votes, data_hashmap_array_filtered))
253 print("Number Televoting cast data rows: " + str(len(data_hashmap_array_filtered)))
254
255
256 to_country_year_voting_groups = create_to_country_voting_groups(data_hashmap_array_filtered)
257
258 # Debug output
259 #
260 # print(to_country_year_voting_groups)
261
262 print()
263 print("Generating Greenstone JSON to-country voting metadata received by:")
264 greenstone_metadata_json = gs_directory_metadata(to_country_year_voting_groups)
265
266 print("Saving output as: " + json_output_filename)
267 xlsxutil.save_greenstone_json_metadata(greenstone_metadata_json,json_output_filename)
268
269 display_gs_head_metadata_tags()
270
271 print()
272
Note: See TracBrowser for help on using the repository browser.