source: main/trunk/model-sites-dev/heritage-nz/collect/pdf-reports/prepare/xls-to-csv.py@ 33191

Last change on this file since 33191 was 33191, checked in by davidb, 5 years ago

Code tidy-up

File size: 7.3 KB
RevLine 
[32807]1import xlrd
2import csv
3import os
4
[33188]5import xlsutil
6
[33018]7letter_to_folder = {
8 'a': "A - B",
9 'b': "A - B",
10 'c': "C - D",
11 'd': "C - D",
12 'e': "E - F",
13 'f': "E - F",
14 'g': "G - H",
15 'h': "G - H",
16 'i': "I - J",
17 'j': "I - J",
18 'k': "K - L",
19 'l': "K - L",
20 'm': "M - N",
21 'n': "M - N",
22 'o': "O - P",
23 'p': "O - P",
24 'q': "Q - R",
25 'r': "Q - R",
26 's': "S - T",
27 't': "S - T",
28 'u': "U - V",
29 'v': "U - V",
30 'w': "W - Z",
31 'x': "W - Z",
32 'y': "W - Z",
33 'z': "W - Z"
34}
35
36def id_to_relative_pdf_file(id):
37 first_char = id[0:1]
38 first_char_lower = first_char.lower()
39
40 file_tail = letter_to_folder[first_char_lower]
41 file_root = "Reports " + file_tail
42
43 pdf_file = os.path.join("Digital-Library-PDFs",file_root,id+".pdf")
44
45 return pdf_file
46
47
[33191]48# **** Written, but never used
49# **** Col numbers refer to older version of spreadsheet
50#
51# There is now a mapping of header-name to index position which would be
52# a better way to do thing
53
[33188]54def fixup_cell(col_num,cell_str):
55 # col == 1 => Author
56 # col == 2 => Title
57 # col == 4 => TLA
58 # col == 5 => AuthorityNo
59 # col == 6 => SiteNo
60
61 if col_num == 1: #Author
62 cell_str = re.sub('\|?(et al)|(Associates)', '', cell_str)
63
64 if col_num == 2: #Title
65 # Detect any ALL-CAPS titles, and change to title-case
66 onlyletters = re.sub('[^A-Za-z]+', '', cell_str)
67 if onlyletters.isupper:
68 cell_str = cell_str.title()
69
70 if col_num == 4: #TLA
71 if cell_str == "All": cell_str = ""
72 if cell_str == "n/a": cell_str = ""
73 if cell_str == "various": cell_str = "" # not a meaningful TLA
74
75
76 return cell_str
77
78
[32807]79def excel_to_bound_pdf_csv(excel_filename):
[33188]80 workbook = xlrd.open_workbook(excel_filename)
[32813]81
[33191]82 worksheet = workbook.sheet_by_index(xlsutil.worksheet_index_pos)
83 ## worksheet = workbook.sheet_by_name(xlsutil.worksheet_name)
84
[32807]85 excel_filename_split = os.path.split(excel_filename)
86 excel_dirname = excel_filename_split[0]
87 excel_file = excel_filename_split[1]
88 excel_file_splitext = os.path.splitext(excel_file)
89 excel_file_root = excel_file_splitext[0];
90
91 pdfbound_filename = os.path.join(excel_dirname,"PDF-BOUND "+excel_file_root+".csv")
92 unbound_filename = os.path.join(excel_dirname,"UNBOUND "+excel_file_root+".csv")
93
94 csv_pdfbound_ofile = open(pdfbound_filename, 'wb')
95 csv_unbound_ofile = open(unbound_filename, 'wb')
96
97 pdfbound_wr = csv.writer(csv_pdfbound_ofile, quoting=csv.QUOTE_ALL)
98 unbound_wr = csv.writer(csv_unbound_ofile, quoting=csv.QUOTE_ALL)
99
[33188]100 # 1. For header-line, build up hashmap of header-names to column number
101 # 2. Write out header-line as Greenstone friendly Metadata terms
[32820]102 # => remove sp spaces, change "Report Identifier" to hnz.Identifier
[32807]103 # 3. Process the rest of the file, checking if accompanying
[33188]104 # PDF file present or not and only printing out the header-names
105 # specified in 'sanitized_headers'
[32807]106
107 num_rows = worksheet.nrows
108
[33191]109 # 1. Get header-line hashmap of header-names to column numbers
[33188]110 header_names_mapping = xlsutil.getHeaderMappingToColNum(worksheet)
111
112 if header_names_mapping is None:
113 print "Failed to find metadata label 'Report Identifier' in column 0"
114 exit()
115 else:
[33191]116 # 2. Process Header into Greenstone friendly metadata terms
117
[32807]118 entry_utf8_row = []
[33188]119 row_i = 0;
[32813]120
[33188]121 for header_name in xlsutil.sanitized_headers:
[33024]122
[33188]123 if header_name in header_names_mapping:
124 header_col_j = header_names_mapping[header_name]
[32807]125
[33188]126 header_cell_value = worksheet.cell_value(row_i,header_col_j)
127
128 if header_cell_value == "Report Identifier":
129 header_cell_value = "hnz.Identifier"
130
131 if header_cell_value == "Title":
132 header_cell_value = "dc.Title"
133
134 if header_cell_value == "RelevantTLA's":
135 header_cell_value = "TLA"
136
137 header_cell_value_utf8 = unicode(header_cell_value).encode("utf-8")
138 metadata_name_utf8 = header_cell_value_utf8.replace(" ", "")
139
140 entry_utf8_row.append(metadata_name_utf8)
141
142 else:
143 print("Warning: Failed to column mapping in spreadsheet for header name \""+header_name+"\" => skipping")
144
[32807]145 unbound_wr.writerow(entry_utf8_row)
146
[32808]147 # Add in 'Filename' as first column in pdfbound CSV file
148 entry_utf8_row.insert(0, "Filename")
149 pdfbound_wr.writerow(entry_utf8_row)
[33188]150
[33191]151 # 3. Process the rest of the file (metadata values) ...
[32808]152
[32807]153 row_i = row_i + 1
154 while row_i<num_rows:
[32808]155 num_cols = worksheet.row_len(row_i)
[32820]156 formatted_utf8_row = []
[32808]157
158 found_pdf = False
159
[33188]160# for col_j in range(num_cols):
161 for header_name in xlsutil.sanitized_headers:
[32808]162
[33188]163 if header_name in header_names_mapping:
164 col_j = header_names_mapping[header_name]
[32813]165
[33188]166 cell_value = worksheet.cell_value(row_i,col_j)
[33018]167
[33188]168 formatted_cell_value = xlsutil.format_if_int(cell_value)
[33018]169
[33188]170 if header_name == "Report Identifier":
171 # Check to see if companion PDF file present
172 # pdf_filename = os.path.join(excel_dirname,"pdfs",formatted_cell_value+".pdf")
173 id = formatted_cell_value.replace(" ","")
174
175 pdf_file = id_to_relative_pdf_file(id)
176 pdf_file_root, pdf_ext = os.path.splitext(pdf_file)
177 PDF_file = pdf_file_root + ".PDF"
178
179 pdf_filename = os.path.join(excel_dirname,pdf_file)
180 PDF_filename = os.path.join(excel_dirname,PDF_file)
[33018]181
[33188]182 if os.path.exists(pdf_filename):
183 found_pdf = True
184 formatted_utf8_row.insert(0, pdf_file)
185 elif os.path.exists(PDF_filename):
186 found_pdf = True
187 formatted_utf8_row.insert(0, PDF_file)
188 else:
189 print "Unbound id: '" + id + "'"
[33018]190
[33188]191 if isinstance(formatted_cell_value, basestring):
192 # Remove any trailing whitespace.
193 # Newline at end particular harmful for a entry in the CSV file
194 formatted_cell_value = formatted_cell_value.rstrip();
[33018]195
[33188]196 formatted_cell_value_utf8 = unicode(formatted_cell_value).encode("utf-8")
197
198 ## Perform any cell transformations to make DL used spreadsheet
199 ## cleaner to build
200 # formatted_cell_value_utf8 = fixup_cell(col_j,formatted_cell_value_utf8)
201
202 formatted_utf8_row.append(formatted_cell_value_utf8)
203 else:
204 print "Warning: No column number mapping for header name \""+header_name+"\" => skipping"
205
[32808]206 if found_pdf:
[32820]207 pdfbound_wr.writerow(formatted_utf8_row)
[32808]208 else:
[32820]209 unbound_wr.writerow(formatted_utf8_row)
[32807]210
211 row_i = row_i + 1
212
213
214 csv_pdfbound_ofile.close()
215 csv_unbound_ofile.close()
216
217if __name__ == "__main__":
218 excel_to_bound_pdf_csv(os.sys.argv[1])
219
Note: See TracBrowser for help on using the repository browser.