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

Revision 33191, 7.3 KB (checked in by davidb, 2 months ago)

Code tidy-up

Line 
1import xlrd
2import csv
3import os
4
5import xlsutil
6
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
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
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
79def excel_to_bound_pdf_csv(excel_filename):
80    workbook = xlrd.open_workbook(excel_filename)
81
82    worksheet = workbook.sheet_by_index(xlsutil.worksheet_index_pos)
83    ## worksheet = workbook.sheet_by_name(xlsutil.worksheet_name)
84
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
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
102    #      => remove sp spaces, change "Report Identifier" to hnz.Identifier
103    # 3. Process the rest of the file, checking if accompanying
104    #     PDF file present or not and only printing out the header-names
105    #     specified in 'sanitized_headers'
106
107    num_rows = worksheet.nrows
108
109    # 1. Get header-line hashmap of header-names to column numbers
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:
116        # 2. Process Header into Greenstone friendly metadata terms     
117
118        entry_utf8_row = []
119        row_i = 0;
120
121        for header_name in xlsutil.sanitized_headers:
122
123            if header_name in header_names_mapping:
124                header_col_j = header_names_mapping[header_name]
125
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
145        unbound_wr.writerow(entry_utf8_row)
146
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)
150                     
151        # 3. Process the rest of the file (metadata values) ...
152
153        row_i = row_i + 1
154        while row_i<num_rows:
155            num_cols = worksheet.row_len(row_i)
156            formatted_utf8_row = []
157
158            found_pdf = False
159
160#            for col_j in range(num_cols):
161            for header_name in xlsutil.sanitized_headers:
162
163                if header_name in header_names_mapping:
164                    col_j = header_names_mapping[header_name]
165
166                    cell_value = worksheet.cell_value(row_i,col_j)
167
168                    formatted_cell_value = xlsutil.format_if_int(cell_value)
169
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)
181
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 + "'"
190
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();
195
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
206            if found_pdf:
207                pdfbound_wr.writerow(formatted_utf8_row)
208            else:
209                unbound_wr.writerow(formatted_utf8_row)
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 browser.