auto-reference-generator 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ """
2
+ auto_classification_generator package definitions
3
+
4
+ Author: Christopher Prince
5
+ license: Apache License 2.0"
6
+ """
7
+
8
+ from .common import *
9
+ from .reference_generator import ReferenceGenerator
10
+ from .cli import parse_args,run_cli
11
+ import importlib.metadata
12
+
13
+ __author__ = "Christopher Prince (c.pj.prince@gmail.com)"
14
+ __license__ = "Apache License Version 2.0"
15
+ __version__ = importlib.metadata.version("auto_reference_generator")
@@ -0,0 +1,537 @@
1
+ """
2
+ Auto Reference Generator tool
3
+
4
+ This tool is utilised to recursively generator reference codes, following an ISAD(G) convention, for a given directory / folder to an Excel or CSV spreadsheet.
5
+
6
+ It is compatible with Windows, MacOS and Linux Operating Systems.
7
+
8
+ author: Christopher Prince
9
+ license: Apache License 2.0"
10
+ """
11
+
12
+ from auto_reference_generator.common import *
13
+ from auto_reference_generator.hash import *
14
+ import os, time, datetime
15
+ import pandas as pd
16
+ import configparser
17
+ from typing import Optional
18
+
19
+ class ReferenceGenerator():
20
+ """
21
+ A Tool for generating archival references for any given directory for use by Digital Archivists.
22
+ Will turn the hierarchy of a folder into and return the results as spreadsheet (or other output).
23
+
24
+ :param root: the root directory to generate references for. Subsequent directories and files will be included.
25
+ :param output_path: set the output path for the generated spreadsheet.
26
+ :param prefix: set a prefix to append to generated references
27
+ :param accprefix: set a prefix to append to generated accession references
28
+ :param suffix: set a suffix to append to generated references
29
+ :param suffix_options: set whether to apply the suffix to files, folders or both
30
+ :param start_ref: set the starting reference, only affects first instance
31
+ :param fixity: set whether to generate fixities
32
+ :param empty_flag: set whether to delete and log empty directories
33
+ :param skip_flag: set whether to skip reference generation (outputs set data)
34
+ :param accession_flag: set whether to generate accession reference (running number)
35
+ :param meta_dir_flag: set whether to generate a 'meta' dir for output
36
+ :param hidden_flag: set to include hidden files/directories
37
+ :param output_format: set to specify output format [xlsx, csv, ods, xml, json, dict] are supported, may require additional modules.
38
+ :param delimiter: set delimiter for generated references
39
+ :param keywords: set to replace numbers in reference with alphabetical characters, specified in list
40
+ :param keywords_mode: set to specify keywords mode [initialise, firstletters]
41
+ :param keywords_retain_order: set to continue counting reference, if keyword is used, skips numbers if not
42
+ :param sort_key: set the sort key, can be any valid function for sorted
43
+ :param keywords_abbreviation: set int for number of characters to abbreviate to for keywords mode
44
+ :param keywords_case_sensitivity: set to change case sensitivity for keyword matching
45
+ :param options_file: set an options file to adjust field parameters
46
+ """
47
+ def __init__(self,
48
+ root: str,
49
+ output_path: str = os.getcwd(),
50
+ prefix: Optional[str] = None,
51
+ suffix: Optional[str] = None,
52
+ suffix_options: Optional[str] = 'apply_to_files',
53
+ level_limit: Optional[int] = None,
54
+ accprefix: Optional[str] = None,
55
+ start_ref: int = 1,
56
+ fixity: Optional[str] = None,
57
+ empty_flag: bool = False,
58
+ skip_flag: bool = False,
59
+ accession_flag: Optional[str] = None,
60
+ meta_dir_flag: bool = True,
61
+ hidden_flag: bool = False,
62
+ output_format: str = "xlsx",
63
+ delimiter: str = "/",
64
+ keywords: list|str|None = None,
65
+ keywords_mode: Optional[str] = None,
66
+ keywords_retain_order: bool = False,
67
+ keywords_case_sensitivity: Optional[bool] = True,
68
+ sort_key = lambda x: (os.path.isfile(x), str.casefold(x)),
69
+ keywords_abbreviation_number: Optional[int] = None,
70
+ options_file: str = os.path.join(os.path.dirname(__file__),'options','options.properties')
71
+ ) -> None:
72
+
73
+ self.root = os.path.abspath(root)
74
+ self.root_level = self.root.count(os.sep)
75
+ self.root_path = os.path.dirname(self.root)
76
+ self.output_path = output_path
77
+ self.output_format = output_format
78
+ self.prefix = prefix
79
+ self.suffix = suffix
80
+ self.suffix_options = suffix_options
81
+ self.level_limit = level_limit
82
+ self.start_ref = start_ref
83
+ self.fixity = fixity
84
+ self.delimiter = delimiter
85
+ if self.delimiter is None:
86
+ self.delimiter_flag = False
87
+ else:
88
+ self.delimiter_flag = True
89
+ self.keywords_list = keywords
90
+ self.keywords_mode = keywords_mode
91
+ self.keywords_retain_order = keywords_retain_order
92
+ self.keywords_case_sensitivity = keywords_case_sensitivity
93
+ self.sort_key = sort_key
94
+ self.keywords_abbreviation_number = keywords_abbreviation_number
95
+
96
+ self.accession_count = start_ref
97
+ if accprefix:
98
+ self.accession_prefix = accprefix
99
+ else:
100
+ self.accession_prefix = prefix
101
+
102
+ self.reference_list = []
103
+ self.record_list = []
104
+ self.empty_list = []
105
+ self.accession_list = []
106
+
107
+ self.meta_dir_flag = meta_dir_flag
108
+ self.accession_flag = accession_flag
109
+ self.empty_flag = empty_flag
110
+ self.skip_flag = skip_flag
111
+ self.hidden_flag = hidden_flag
112
+
113
+ if options_file is None:
114
+ options_file = os.path.join(os.path.dirname(__file__),'options','options.properties')
115
+ self.parse_config(options_file=os.path.abspath(options_file))
116
+ self.start_time = datetime.datetime.now()
117
+
118
+ def parse_config(self, options_file = os.path.join('options','options.properties')) -> None:
119
+ config = configparser.ConfigParser()
120
+ config.read(options_file, encoding='utf-8')
121
+ global INDEX_FIELD
122
+ INDEX_FIELD = config['options']['INDEX_FIELD']
123
+ global PATH_FIELD
124
+ PATH_FIELD = config['options']['PATH_FIELD']
125
+ global RELATIVE_FIELD
126
+ RELATIVE_FIELD = config['options']['RELATIVE_FIELD']
127
+ global PARENT_FIELD
128
+ PARENT_FIELD = config['options']['PARENT_FIELD']
129
+ global PARENT_REF
130
+ PARENT_REF = config['options']['PARENT_REF']
131
+ global REFERENCE_FIELD
132
+ REFERENCE_FIELD = config['options']['REFERENCE_FIELD']
133
+ global ACCESSION_FIELD
134
+ ACCESSION_FIELD = config['options']['ACCESSION_FIELD']
135
+ global REF_SECTION
136
+ REF_SECTION = config['options']['REF_SECTION']
137
+ global LEVEL_FIELD
138
+ LEVEL_FIELD = config['options']['LEVEL_FIELD']
139
+ global BASENAME_FIELD
140
+ BASENAME_FIELD = config['options']['BASENAME_FIELD']
141
+ global EXTENSION_FIELD
142
+ EXTENSION_FIELD = config['options']['EXTENSION_FIELD']
143
+ global ATTRIBUTE_FIELD
144
+ ATTRIBUTE_FIELD = config['options']['ATTRIBUTE_FIELD']
145
+ global SIZE_FIELD
146
+ SIZE_FIELD = config['options']['SIZE_FIELD']
147
+ global CREATEDATE_FIELD
148
+ CREATEDATE_FIELD = config['options']['CREATEDATE_FIELD']
149
+ global MODDATE_FIELD
150
+ MODDATE_FIELD = config['options']['MODDATE_FIELD']
151
+ global ACCESSDATE_FIELD
152
+ ACCESSDATE_FIELD = config['options']['ACCESSDATE_FIELD']
153
+ global OUTPUTSUFFIX
154
+ OUTPUTSUFFIX = config['options']['OUTPUTSUFFIX']
155
+ global METAFOLDER
156
+ METAFOLDER = config['options']['METAFOLDER']
157
+ global EMPTYDIRSREMOVED
158
+ EMPTYDIRSREMOVED = config['options']['EMPTYSUFFIX']
159
+ global ACCDELIMTER
160
+ ACCDELIMTER = config['options']['ACCDELIMTER']
161
+
162
+ def remove_empty_directories(self) -> None:
163
+ """
164
+ Remove empty directories with a warning.
165
+ """
166
+ confirm_delete = input('\n***WARNING*** \
167
+ \n\nYou have selected the Remove Empty Folders Option. \
168
+ \nThis process is NOT reversible! \
169
+ \n\nPlease confirm this by typing: "Y" \
170
+ \nTyping any other character will abort the program... \
171
+ \n\nPlease confirm your choice: ')
172
+ if confirm_delete.lower() != "y":
173
+ print('Aborting...')
174
+ time.sleep(1)
175
+ raise SystemExit()
176
+ empty_dirs = []
177
+ for dirpath, dirnames, filenames in os.walk(self.root, topdown = False):
178
+ if not any((dirnames, filenames)):
179
+ empty_dirs.append(dirpath)
180
+ try:
181
+ os.rmdir(dirpath)
182
+ print(f'Removed Directory: {dirpath}')
183
+ except OSError as e:
184
+ print(f"Error removing directory '{dirpath}': {e}")
185
+ if empty_dirs:
186
+ output_txt = define_output_file(self.output_path, self.root, METAFOLDER, self.meta_dir_flag,
187
+ output_suffix = EMPTYDIRSREMOVED, output_format = "txt")
188
+ export_list_txt(empty_dirs, output_txt)
189
+ else:
190
+ print('No directories removed!')
191
+
192
+ def filter_directories(self, directory, sort_key = lambda x: (os.path.isfile(x), str.casefold(x))) -> list:
193
+ """
194
+ Sorts the list alphabetically and filters out certain files.
195
+ """
196
+ try:
197
+ if self.hidden_flag is False:
198
+ list_directories = sorted([win_256_check(os.path.join(directory, f.name)) for f in os.scandir(directory)
199
+ if not f.name.startswith('.')
200
+ and filter_win_hidden(win_256_check(os.path.join(directory, f.name))) is False
201
+ and f.name != METAFOLDER
202
+ and f.name != os.path.basename(__file__)],
203
+ key = sort_key)
204
+ elif self.hidden_flag is True:
205
+ list_directories = sorted([os.path.join(directory, f.name) for f in os.scandir(directory) \
206
+ if f.name != METAFOLDER \
207
+ and f.name != os.path.basename(__file__)],
208
+ key = sort_key)
209
+ else:
210
+ list_directories = []
211
+ return list_directories
212
+ except Exception:
213
+ print('Failed to Filter')
214
+ raise SystemError()
215
+
216
+ def parse_directory_dict(self, file_path: str, level: int, ref: str|int) -> dict:
217
+ """
218
+ Parses directory / file data into a dict which is then appended to a list
219
+ """
220
+ try:
221
+ if file_path.startswith(u'\\\\?\\'):
222
+ parse_path = file_path.replace(u'\\\\?\\', "")
223
+ else:
224
+ parse_path = file_path
225
+ file_stats = os.stat(file_path)
226
+ if self.accession_flag is not None:
227
+ if self.delimiter_flag is False:
228
+ self.delimiter = ACCDELIMTER
229
+ acc_ref = self.accession_running_number(parse_path, self.delimiter)
230
+ self.accession_list.append(acc_ref)
231
+ if os.path.isdir(file_path):
232
+ file_type = "Dir"
233
+ else:
234
+ file_type = "File"
235
+ class_dict = {
236
+ PATH_FIELD: str(os.path.abspath(parse_path)),
237
+ RELATIVE_FIELD: str(parse_path).replace(self.root_path, ""),
238
+ BASENAME_FIELD: os.path.splitext(os.path.basename(file_path))[0],
239
+ EXTENSION_FIELD: os.path.splitext(file_path)[1],
240
+ PARENT_FIELD: os.path.abspath(os.path.join(os.path.abspath(parse_path), os.pardir)),
241
+ ATTRIBUTE_FIELD: file_type,
242
+ SIZE_FIELD: file_stats.st_size,
243
+ CREATEDATE_FIELD: datetime.datetime.fromtimestamp(file_stats.st_ctime),
244
+ MODDATE_FIELD: datetime.datetime.fromtimestamp(file_stats.st_mtime),
245
+ ACCESSDATE_FIELD: datetime.datetime.fromtimestamp(file_stats.st_atime),
246
+ LEVEL_FIELD: level,
247
+ REF_SECTION: ref}
248
+
249
+ if self.fixity and not os.path.isdir(file_path):
250
+ hash = HashGenerator(self.fixity).hash_generator(file_path)
251
+ class_dict.update({"Algorithm": self.fixity, "Hash": hash})
252
+ self.record_list.append(class_dict)
253
+ return class_dict
254
+ except:
255
+ print('Failed to Parse')
256
+ raise SystemError()
257
+
258
+
259
+ def list_directories(self, directory: str, ref: str|int = 1) -> None:
260
+ """
261
+ Generates a list of directories. Also calculates level and a running reference number.
262
+ """
263
+ ref = int(ref)
264
+ pref = None
265
+ list_directory = self.filter_directories(directory, sort_key = self.sort_key)
266
+ try:
267
+ if directory.startswith(u'\\\\?\\'):
268
+ level = directory.replace(u'\\\\?\\', "").count(os.sep) - self.root_level + 1
269
+ else:
270
+ level = directory.count(os.sep) - self.root_level + 1
271
+ for file_path in list_directory:
272
+ file_name = win_file_split(file_path)
273
+ #Keyword Replacement
274
+ if self.keywords_list is not None:
275
+ # Case Sensitivity Check
276
+ if self.keywords_case_sensitivity is True:
277
+ keyword_file_name = file_name.upper()
278
+ elif self.keywords_case_sensitivity is False:
279
+ keyword_file_name = file_name
280
+ else:
281
+ keyword_file_name = file_name
282
+ if len(self.keywords_list) == 0 and os.path.isdir(file_path):
283
+ if self.keywords_retain_order is False:
284
+ pref = ref - 1
285
+ elif self.keywords_retain_order is True:
286
+ pref = ref
287
+ ref = str(keyword_replace(keyword_file_name, mode=self.keywords_mode, abbreviation_number=self.keywords_abbreviation_number))
288
+ elif any(keyword_file_name in keyword for keyword in self.keywords_list) and os.path.isdir(file_path):
289
+ if self.keywords_retain_order is False:
290
+ pref = ref - 1
291
+ elif self.keywords_retain_order is True:
292
+ pref = ref
293
+ ref = str(keyword_replace(keyword_file_name, mode=self.keywords_mode, abbreviation_number=self.keywords_abbreviation_number))
294
+ elif self.keywords_mode == "from_json" and os.path.isdir(file_path):
295
+ try:
296
+ os.path.exists(os.path.abspath(self.keywords_list[0]))
297
+ except Exception as e:
298
+ print('Error accessing JSON file, please check path.')
299
+ import json
300
+ with open(os.path.abspath(self.keywords_list[0])) as file:
301
+ keyword_dict = json.load(file)
302
+ if not isinstance(keyword_dict, dict):
303
+ print('Keywords JSON file is not a valid dictionary.')
304
+ raise SystemExit()
305
+ if self.keywords_case_sensitivity is True:
306
+ keyword_dict = {k.upper(): v for k, v in keyword_dict.items()}
307
+ if any(keyword_file_name in keyword for keyword in keyword_dict.keys()) and os.path.isdir(file_path):
308
+ if self.keywords_retain_order is False:
309
+ pref = ref - 1
310
+ elif self.keywords_retain_order is True:
311
+ pref = ref
312
+ ref = str(keyword_dict.get(keyword_file_name))
313
+ else:
314
+ pass
315
+ #Suffix Addition
316
+ if self.suffix is not None:
317
+ if self.suffix_options == 'apply_to_files' and os.path.isfile(file_path):
318
+ ref = str(ref) + str(self.suffix)
319
+ elif self.suffix_options == 'apply_to_folders' and os.path.isdir(file_path):
320
+ ref = str(ref) + str(self.suffix)
321
+ elif self.suffix_options == 'apply_to_both':
322
+ ref = str(ref) + str(self.suffix)
323
+ else:
324
+ pass
325
+ if self.level_limit is not None and level > self.level_limit:
326
+ self.parse_directory_dict(file_path, level, ref='')
327
+ else:
328
+ self.parse_directory_dict(file_path, level, ref)
329
+ #Suffix Removal for next reference increment
330
+ if self.suffix is not None:
331
+ if self.suffix_options == 'apply_to_files' and os.path.isfile(file_path):
332
+ ref = str(ref).replace(str(self.suffix), "")
333
+ elif self.suffix_options == 'apply_to_folders' and os.path.isdir(file_path):
334
+ ref = str(ref).replace(str(self.suffix), "")
335
+ elif self.suffix_options == 'apply_to_both':
336
+ ref = str(ref).replace(str(self.suffix), "")
337
+ if pref:
338
+ ref = int(pref) + 1
339
+ pref = None
340
+ else:
341
+ ref = int(ref) + 1
342
+ if os.path.isdir(file_path):
343
+ self.list_directories(file_path, ref = 1)
344
+ except Exception:
345
+ print("Error occurred for directory/file: {}".format(list_directory))
346
+ raise SystemError()
347
+
348
+ def init_dataframe(self) -> pd.DataFrame:
349
+ """
350
+ Lists the directories and forms dicts from the above two functions.
351
+ Looks up and pulls through the Parent row's data to the Child Row.
352
+ Merges the dataframe on itself, Parent is merged 'left' on FullName to pull through the Parent's data
353
+ (lookup is based on File Path's), and unnecessary data is dropped.
354
+ Any errors are turned to 0 and the result are based on the reference loop initialisation.
355
+ """
356
+ self.parse_directory_dict(file_path = self.root, level = 0, ref = 0)
357
+ self.list_directories(self.root, self.start_ref)
358
+ self.df = pd.DataFrame(self.record_list).copy()
359
+
360
+ merged = self.df.merge(self.df[[INDEX_FIELD, REF_SECTION]], how = 'left', left_on = PARENT_FIELD,
361
+ right_on = INDEX_FIELD, suffixes=('_x', '_y'))
362
+ parent_col = f'{REF_SECTION}_y'
363
+ parent_series = (pd.to_numeric(merged[parent_col], errors='coerce').fillna(0).astype(int).astype(str))
364
+
365
+ merged = merged.drop(columns=[f'{INDEX_FIELD}_y'])
366
+ merged = merged.rename(columns={f'{REF_SECTION}_x': REF_SECTION, parent_col: PARENT_REF, f'{INDEX_FIELD}_x': INDEX_FIELD})
367
+ merged[PARENT_REF] = parent_series.astype(str)
368
+ self.df = merged
369
+ # old method - resulted in dtype warning
370
+ # self.df = self.df.merge(self.df[[INDEX_FIELD, REF_SECTION]], how = 'left', left_on = PARENT_FIELD,
371
+ # right_on = INDEX_FIELD)
372
+ #self.df = self.df.drop([f'{INDEX_FIELD}_y'], axis = 1)
373
+ #self.df = self.df.rename(columns = {f'{REF_SECTION}_x': REF_SECTION, f'{REF_SECTION}_y': PARENT_REF,
374
+ # f'{INDEX_FIELD}_x': INDEX_FIELD})
375
+ #self.df.loc[:, PARENT_REF] = self.df[PARENT_REF].fillna(0)
376
+ #self.df.loc[:, PARENT_REF] = self.df.astype({PARENT_REF: str})
377
+ self.df.index.name = "Index"
378
+ self.list_loop = self.df[[REF_SECTION, PARENT_FIELD, LEVEL_FIELD]].values.tolist()
379
+ if self.skip_flag:
380
+ pass
381
+ else:
382
+ self.init_reference_loop()
383
+ return self.df
384
+
385
+ def init_reference_loop(self) -> pd.DataFrame:
386
+ """
387
+ Initialises the Reference loop. Sets some of the pre-variables necessary for the loop.
388
+ """
389
+ c = 0
390
+ tot = len(self.list_loop)
391
+ for ref, parent, level in self.list_loop:
392
+ c += 1
393
+ print(f"Generating Auto Reference for: {c} / {tot}", end = "\r")
394
+ if self.delimiter_flag is False:
395
+ self.delimiter = "/"
396
+ self.reference_loop(ref = ref, parent = parent, track = 1, level = level, delimiter = self.delimiter)
397
+
398
+ self.df.loc[:, REFERENCE_FIELD] = self.reference_list
399
+ if self.accession_flag is not None:
400
+ self.df.loc[:, ACCESSION_FIELD] = self.accession_list
401
+ return self.df
402
+
403
+ def reference_loop(self, ref: str, parent: str, track: int, level: int, new_ref: Optional[str] = None, delimiter: str = "/") -> None:
404
+ """
405
+ The Reference loop works upwards, running an "index lookup" against the parent folder until it reaches the top.
406
+
407
+ ref is the reference section derived from the list in the list_directories function. [Stays Constant]
408
+ PARENT is the parent folder of the child. [Varies]
409
+ TRACK is an iteration tracker to distinguish between first and later iterations. [Varies]
410
+ LEVEL is the level of the folder, 0 being the root. [Stays Constant]
411
+
412
+ new_ref is the archive reference constructed during this loop.
413
+
414
+ To do this, the reference loop works upwards, running an "index lookup" against the parent folder until it reaches the top.
415
+ 1) To start, the reference loop indexes from the dataframe established by listing the directories.
416
+ 2) The index compares FullName against the Parent (So acting on the Basis of File Path's)
417
+ 3) If the index fails / is 0, then the top has been reached.
418
+ 4) In that event if LEVEL is also 0 IE the top-most item is being looked at (normally the first thing). new_ref is set to ref
419
+ 5) Otherwise the top-most level has been reached and, new_ref is simply new_ref.
420
+ 6) If the index does matches, then top level has not yet been reached. In this case we also account for the PARENT's Reference, to avoid an error at the 2nd to top layer.
421
+ 7) parent_ref is looked up, by Indexing the Dataframe. Then if parent_ref is 0, IE we're on the 2nd top layer. We check the TRACK.
422
+ 8) If TRACK is 1, IE the first iteration on the 2nd layer, new_ref is just ref.
423
+ 9) If TRACK isn't 1, IE subsequent iterations on the 2nd layer, new_ref is just itself.
424
+ 10) If parent_ref isn't 0, then we concatenate the parent_ref with either ref or new_ref.
425
+ 11) If TRACK is 1, new_ref is parent_ref + ref.
426
+ 12) If TRACK isn't 1, new_ref is parent_ref + new_ref.
427
+ 13) At the end of the process the PARENT of the current folder is looked up and sub_parent replace's the PARENT variable. TRACK is also advanced.
428
+ 14) Then the function is then called upon recursively. In this way the loop will work through until it reaches the top.
429
+ 15) This is only called upon if the index does not fail. If it does fail, then the top-level is reached and the loop escaped.
430
+ 16) As this is acting within the Loop from the init stage, this will operate on all files within a list.
431
+ """
432
+ try:
433
+ idx = self.df.loc[self.df[INDEX_FIELD] == parent,INDEX_FIELD].index
434
+ if idx.size == 0:
435
+ if level == 0:
436
+ new_ref = str(ref)
437
+ if self.prefix:
438
+ new_ref = str(self.prefix)
439
+ else:
440
+ new_ref = str(new_ref)
441
+ if self.prefix:
442
+ new_ref = str(self.prefix) + delimiter + str(new_ref)
443
+ self.reference_list.append(new_ref)
444
+ else:
445
+ parent_ref = self.df.loc[idx, REF_SECTION].item()
446
+ if parent_ref == 0:
447
+ if track == 1:
448
+ new_ref = str(ref)
449
+ else:
450
+ new_ref = str(new_ref)
451
+ else:
452
+ if track == 1:
453
+ if ref == '':
454
+ new_ref = str(parent_ref)
455
+ else:
456
+ new_ref = str(parent_ref) + delimiter + str(ref)
457
+ else:
458
+ if ref == '' and parent_ref == '':
459
+ pass
460
+ else:
461
+ new_ref = str(parent_ref) + delimiter + str(new_ref)
462
+ parent = self.df.loc[idx,PARENT_FIELD].item()
463
+ track = track + 1
464
+ self.reference_loop(ref, parent, track, level, new_ref, delimiter=delimiter)
465
+
466
+ except Exception as e:
467
+ print('Error in Reference Loop.')
468
+ print(e)
469
+ raise SystemError()
470
+ pass
471
+
472
+ def accession_running_number(self, file_path: str, delimiter: str = "-") -> None|int|str:
473
+ """
474
+ Generates a Running Number / Accession Code, can be set to 3 different "modes", counting Files, Directories or Both
475
+ """
476
+ if self.accession_flag is not None:
477
+ if self.accession_flag.lower() == "file":
478
+ if os.path.isdir(file_path):
479
+ if self.accession_prefix is not None:
480
+ accession_ref = self.accession_prefix + delimiter + "Dir"
481
+ else:
482
+ accession_ref = "Dir"
483
+ else:
484
+ if self.accession_prefix is not None:
485
+ accession_ref = self.accession_prefix + delimiter + str(self.accession_count)
486
+ else:
487
+ accession_ref = self.accession_count
488
+ self.accession_count += 1
489
+ elif self.accession_flag.lower() == "dir":
490
+ if os.path.isdir(file_path):
491
+ if self.accession_prefix is not None:
492
+ accession_ref = self.accession_prefix + delimiter + str(self.accession_count)
493
+ else:
494
+ accession_ref = self.accession_count
495
+ self.accession_count += 1
496
+ else:
497
+ if self.accession_prefix is not None:
498
+ accession_ref = self.accession_prefix + delimiter + "File"
499
+ else:
500
+ accession_ref = "File"
501
+ elif self.accession_flag.lower() == "all":
502
+ if self.accession_prefix:
503
+ accession_ref = self.accession_prefix + delimiter + str(self.accession_count)
504
+ else:
505
+ if self.accession_prefix:
506
+ accession_ref = self.accession_prefix + self.accession_count
507
+ else:
508
+ accession_ref = self.accession_count
509
+ self.accession_count += 1
510
+ else:
511
+ accession_ref = None
512
+ else:
513
+ accession_ref = None
514
+ return accession_ref
515
+
516
+ def main(self) -> None|list:
517
+ """
518
+ Runs Program :)
519
+ """
520
+ if self.empty_flag:
521
+ self.remove_empty_directories()
522
+ self.init_dataframe()
523
+ output_file = define_output_file(self.output_path, self.root, meta_dir_flag = self.meta_dir_flag,
524
+ output_suffix = OUTPUTSUFFIX ,output_format = self.output_format)
525
+ if self.output_format == "xlsx":
526
+ export_xl(df = self.df, output_filename = output_file)
527
+ elif self.output_format == "csv":
528
+ export_csv(df = self.df, output_filename = output_file)
529
+ elif self.output_format == "ods":
530
+ export_ods(df = self.df, output_filename = output_file)
531
+ elif self.output_format == "json":
532
+ export_json(df = self.df, output_filename = output_file)
533
+ elif self.output_format == "xml":
534
+ export_xml(df = self.df, output_filename = output_file)
535
+ elif self.output_format == "dict":
536
+ return export_dict(df = self.df)
537
+ print_running_time(self.start_time)
@@ -0,0 +1,103 @@
1
+ from auto_reference_generator.reference_generator import ReferenceGenerator
2
+ import argparse, os
3
+ import importlib.metadata
4
+
5
+ def parse_args():
6
+ parser = argparse.ArgumentParser(prog="Auto_Reference_Generator", description = "Auto Reference Generator for Digital Cataloguing")
7
+ parser.add_argument('root', nargs = '?', default = os.getcwd(),
8
+ help = "The root directory to create references for")
9
+ parser.add_argument("-p", "--prefix", required = False, nargs = '?',
10
+ help = "Set a prefix to append onto generated references")
11
+ parser.add_argument("-s", "--suffix", required = False, nargs = '?',
12
+ help = "Set a suffix to append onto generated references")
13
+ parser.add_argument("--suffix-option", required = False, choices= ['apply_to_files','apply_to_folders','apply_to_both'], default = 'apply_to_files',
14
+ help = "Set whether to apply the suffix to files, folders or both when generating references")
15
+ parser.add_argument("--rm-empty", required = False, action = 'store_true',
16
+ help = "Sets the Program to remove any Empty Directory and Log removals to a text file")
17
+ parser.add_argument("-acc", "--accession", required = False, choices = ['dir', 'file', 'all'], default = None, type = str.lower,
18
+ help="Sets the program to create an accession listing - IE a running number of the files.")
19
+ parser.add_argument("-accp", "--acc-prefix", required = False, nargs = '?',
20
+ help = "Sets the Prefix for Accession Mode")
21
+ parser.add_argument("-o", "--output", required = False, nargs = '?',
22
+ help = "Set the output directory for created spreadsheet")
23
+ parser.add_argument("-l", "--level-limit", required = False, nargs = '?', type = int,
24
+ help = "Set a level limit to generate references to")
25
+ parser.add_argument("-str", "--start-ref", required = False, nargs = '?', default = 1, type=int,
26
+ help = "Set the starting reference number. Won't affect sub-folders/files")
27
+ parser.add_argument("-dlm", "--delimiter", required = False, nargs= '?', type = str,
28
+ help = "Set the delimiter to use between levels")
29
+ parser.add_argument("--disable-meta-dir", required = False, action = 'store_false', default = True,
30
+ help = "Set to disable creating a 'meta' file for spreadsheet; can be used in combination with output")
31
+ parser.add_argument("-skp","--skip", required = False, action = 'store_true', default = False,
32
+ help = "Set to skip creating references, will generate a spreadsheet listing")
33
+ parser.add_argument("-hid","--hidden", required = False , action = 'store_true', default = False,
34
+ help = "Set to include hidden files/folders in the listing")
35
+ parser.add_argument("-fmt", "--output-format", required = False, default = "xlsx", choices = ['xlsx', 'csv', 'json', 'ods', 'xml', 'dict'],
36
+ help = "Set to set output format. Note ods requires odfpy; xml requires lxml; dict requires pandas, please install via pip if needed")
37
+ parser.add_argument("-fx", "--fixity", required = False, nargs = '?', const = "SHA-1", default = None, choices = ['MD5', 'SHA-1', 'SHA1', 'SHA-256','SHA256','SHA-512','SHA512'], type = str.upper,
38
+ help = "Set to generate fixities, specify Algorithm to use (default SHA-1)")
39
+ parser.add_argument("-v", "--version", action = 'version', version = '%(prog)s {version}'.format(version = importlib.metadata.version("auto_reference_generator")),
40
+ help = "See version information, then exit")
41
+ parser.add_argument("-key","--keywords", nargs = '*', default = None,
42
+ help = "Set to replace reference numbers with given Keywords for folders (only Folders atm). Can be a list of keywords or a JSON file mapping folder names to keywords.")
43
+ parser.add_argument("--keywords-case-sensitivity", required = False, action = 'store_false', default = True,
44
+ help = "Set to change case keyword matching sensitivity. By default keyword matching is insensitive")
45
+ parser.add_argument("-keym","--keywords-mode", nargs = '?', const = "initialise", choices = ['initialise','firstletters','from_json'], default = 'initialise',
46
+ help = "Set to alternate keyword mode: 'initialise' will use initials of words; 'firstletters' will use the first letters of the string; 'from_json' will use a JSON file mapping names to keywords")
47
+ parser.add_argument("--keywords-retain-order", required = False, default = False, action = 'store_true',
48
+ help = "Set when using keywords to continue reference numbering. If not used keywords don't 'count' to reference numbering, e.g. if using initials 'Project Alpha' -> 'PA' then the next folder/file will still be '001' not '003'")
49
+ parser.add_argument("--keywords-abbreviation-number", required = False, nargs='+', default = None, type = int,
50
+ help = "Set to set the number of letters to abbreviate for 'firstletters' mode, does not impact 'initialise' mode.")
51
+ parser.add_argument("--sort-by", required=False, nargs = '?', default = 'folders_first', choices = ['folders_first','alphabetical'], type=str.lower,
52
+ help = "Set the sorting method, 'folders_first' sorts folders first then files alphabetically; 'alphabetically' sorts alphabetically (ignoring folder distinction)")
53
+ parser.add_argument("--options-file", required = False, nargs = '?', default = os.path.join(os.path.dirname(__file__),'options','options.properties'),
54
+ help = "Set the options file to use")
55
+ args = parser.parse_args()
56
+ return args
57
+
58
+ def run_cli():
59
+ args = parse_args()
60
+ if isinstance(args.root, str):
61
+ args.root = args.root.strip("\"").rstrip("\\")
62
+ if not args.output:
63
+ args.output = os.path.abspath(args.root)
64
+ print(f'Output path defaulting to root directory: {args.output}')
65
+ else:
66
+ args.output = os.path.abspath(args.output)
67
+ print(f'Output path set to: {args.output}')
68
+ if args.acc_prefix and not args.accession:
69
+ print(f'Accession Prefix set but Accession Mode not set, ignoring Accession Prefix')
70
+ sort_key = None
71
+ if args.sort_by:
72
+ if args.sort_by == "folders_first":
73
+ sort_key = lambda x: (os.path.isfile(x), str.casefold(x))
74
+ elif args.sort_by == "alphabetical":
75
+ sort_key = str.casefold
76
+
77
+ ReferenceGenerator(args.root,
78
+ output_path = args.output,
79
+ prefix = args.prefix,
80
+ accprefix = args.acc_prefix,
81
+ suffix = args.suffix,
82
+ suffix_options = args.suffix_option,
83
+ level_limit = args.level_limit,
84
+ fixity = args.fixity,
85
+ empty_flag = args.rm_empty,
86
+ accession_flag = args.accession,
87
+ hidden_flag = args.hidden,
88
+ start_ref = args.start_ref,
89
+ meta_dir_flag = args.disable_meta_dir,
90
+ skip_flag = args.skip,
91
+ output_format = args.output_format,
92
+ keywords = args.keywords,
93
+ keywords_mode = args.keywords_mode,
94
+ keywords_retain_order = args.keywords_retain_order,
95
+ keywords_case_sensitivity= args.keywords_case_sensitivity,
96
+ sort_key = sort_key,
97
+ delimiter = args.delimiter,
98
+ keywords_abbreviation_number = args.keywords_abbreviation_number,
99
+ options_file = args.options_file).main()
100
+ print('Complete!')
101
+
102
+ if __name__ == "__main__":
103
+ run_cli()
@@ -0,0 +1,165 @@
1
+ """
2
+ Common Tools used in both Opex Manifest and Auto Reference modules.
3
+
4
+ author: Christopher Prince
5
+ license: Apache License 2.0"
6
+ """
7
+
8
+ import os, time, sys, stat
9
+ import datetime
10
+ import pandas as pd
11
+ from typing import Optional
12
+
13
+ def path_check(path: str):
14
+ if os.path.exists(path):
15
+ pass
16
+ else:
17
+ os.makedirs(path)
18
+
19
+ def define_output_file(output_path: str, output_name: str, meta_dir_name: str = 'meta', meta_dir_flag: Optional[bool] = True, output_suffix: Optional[str] = None, output_format: str = "xlsx"):
20
+ path_check(output_path)
21
+ if meta_dir_flag:
22
+ path_check(os.path.join(output_path,meta_dir_name))
23
+ if output_suffix is None:
24
+ output_file = os.path.join(output_path,meta_dir_name,str(os.path.basename(output_name)) + "." + output_format)
25
+ else:
26
+ output_file = os.path.join(output_path,meta_dir_name,str(os.path.basename(output_name)) + output_suffix + "." + output_format)
27
+ else:
28
+ if output_suffix is None:
29
+ output_file = os.path.join(output_path,str(os.path.basename(output_name)) + "." + output_format)
30
+ else:
31
+ output_file = os.path.join(output_path,str(os.path.basename(output_name)) + output_suffix + "." + output_format)
32
+ return output_file
33
+
34
+ def export_list_txt(txt_list: list, output_filename: str):
35
+ try:
36
+ with open(output_filename,'w') as writer:
37
+ for line in txt_list:
38
+ writer.write(f"{line}\n")
39
+ except PermissionError as e:
40
+ print(e)
41
+ print('Waiting 10 Seconds to try again...')
42
+ time.sleep(10)
43
+ export_list_txt(txt_list, output_filename)
44
+ finally:
45
+ print(f"Saved to: {output_filename}")
46
+
47
+ def export_csv(df: pd.DataFrame, output_filename: str):
48
+ try:
49
+ df['Archive_Reference'] = df['Archive_Reference'].astype('string')
50
+ df.to_csv(output_filename,sep = ",",encoding = "utf-8")
51
+ except ModuleNotFoundError:
52
+ print('Pandas Module not found, cannot export to csv, please install via: pip install pandas')
53
+ except PermissionError as e:
54
+ print(e)
55
+ print('Waiting 10 Seconds to try again...')
56
+ time.sleep(10)
57
+ export_csv(df,output_filename)
58
+ print(f"Saved to: {output_filename}")
59
+
60
+ def export_json(df: pd.DataFrame, output_filename: str):
61
+ try:
62
+ df.to_json(output_filename,orient='index', indent=4)
63
+ except ModuleNotFoundError:
64
+ print('Pandas Module not found, cannot export to json, please install via: pip install pandas')
65
+ raise SystemExit()
66
+ except PermissionError as e:
67
+ print(e)
68
+ print('Waiting 10 Seconds to try again...')
69
+ time.sleep(10)
70
+ export_json(df, output_filename)
71
+ print(f"Saved to: {output_filename}")
72
+
73
+ def export_xml(df: pd.DataFrame, output_filename: str):
74
+ try:
75
+ df.to_xml(output_filename)
76
+ except ModuleNotFoundError:
77
+ print('lxml Module not found, cannot export to xml, please install via: pip install lxml')
78
+ raise SystemExit()
79
+ except PermissionError as e:
80
+ print(e)
81
+ print('Waiting 10 Seconds to try again...')
82
+ time.sleep(10)
83
+ export_xml(df, output_filename)
84
+ print(f"Saved to: {output_filename}")
85
+
86
+ def export_xl(df: pd.DataFrame, output_filename: str):
87
+ try:
88
+ with pd.ExcelWriter(output_filename,mode = 'w') as writer:
89
+ df.to_excel(writer)
90
+ except ModuleNotFoundError:
91
+ print('openpyxl Module not found, cannot export to xlsx, please install via: pip install openpyxl')
92
+ raise SystemExit()
93
+ except PermissionError as e:
94
+ print(e)
95
+ print('Waiting 10 Seconds to try again...')
96
+ time.sleep(10)
97
+ export_xl(df,output_filename)
98
+ print(f"Saved to: {output_filename}")
99
+
100
+ def export_ods(df: pd.DataFrame, output_filename: str):
101
+ try:
102
+ with pd.ExcelWriter(output_filename,engine='odf',mode = 'w') as writer:
103
+ df.to_excel(writer)
104
+ except ModuleNotFoundError:
105
+ print('odfpy Module not found, cannot export to ods, please install via: pip install odfpy')
106
+ raise SystemExit()
107
+ except PermissionError as e:
108
+ print(e)
109
+ print('Waiting 10 Seconds to try again...')
110
+ time.sleep(10)
111
+ export_xl(df,output_filename)
112
+ print(f"Saved to: {output_filename}")
113
+
114
+ def export_dict(df: pd.DataFrame):
115
+ try:
116
+ return df.to_dict('records')
117
+ except ModuleNotFoundError:
118
+ print('Pandas Module not found, cannot export to dict, please install via: pip install pandas')
119
+ raise SystemExit()
120
+
121
+ def win_256_check(path: str):
122
+ if len(path) > 255 and sys.platform == "win32":
123
+ if path.startswith(u'\\\\?\\'):
124
+ path = path
125
+ else:
126
+ path = u"\\\\?\\" + path
127
+ return path
128
+
129
+ def win_file_split(path: str):
130
+ if sys.platform == "win32":
131
+ path = path.rsplit("\\",1)[-1]
132
+ else:
133
+ path = path.rsplit("/",1)[-1]
134
+ return path
135
+
136
+ def filter_win_hidden(path: str):
137
+ try:
138
+ if bool(os.stat(path).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN) is True:
139
+ return True
140
+ else:
141
+ return False
142
+ except:
143
+ return False
144
+
145
+ def keyword_replace(text: str, mode: None|str = "initialise", keyword_dict: dict|None = None, abbreviation_number: int|None = None) -> str:
146
+ text = text.translate(str.maketrans('','',r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""))
147
+ if mode == "initialise":
148
+ if len(text.split(" ")) > 1:
149
+ if abbreviation_number is None:
150
+ abbreviation_number = -1
151
+ return "".join([x[0] for x in text.upper().split(" ", abbreviation_number)])
152
+ else:
153
+ if abbreviation_number is None:
154
+ abbreviation_number = 3
155
+ return text[0:abbreviation_number].upper().replace(' ','')
156
+ elif mode == "firstletters":
157
+ if abbreviation_number is None:
158
+ abbreviation_number = 3
159
+ return text[0:abbreviation_number].upper().replace(' ','')
160
+ else:
161
+ print('Invalid keyword mode')
162
+ raise SystemExit()
163
+
164
+ def print_running_time(start_time):
165
+ print(f'Running time: {datetime.datetime.now() - start_time}')
@@ -0,0 +1,27 @@
1
+ """
2
+ Hash Generator class for generating Fixities for files.
3
+
4
+ author: Christopher Prince
5
+ license: Apache License 2.0"
6
+ """
7
+
8
+ import hashlib
9
+
10
+ class HashGenerator():
11
+ def __init__(self,algorithm="SHA-1"):
12
+ self.algorithm = algorithm
13
+ self.buffer = 4096
14
+
15
+ def hash_generator(self,file_path):
16
+ if self.algorithm in ("SHA-1","SHA1"): hash = hashlib.sha1()
17
+ elif self.algorithm in ("MD5"): hash = hashlib.md5()
18
+ elif self.algorithm in ("SHA-256","SHA256"): hash = hashlib.sha256()
19
+ elif self.algorithm in ("SHA-512","SHA512"): hash = hashlib.sha512()
20
+ else: hash = hashlib.sha1()
21
+ print(f'Generating Fixity using {self.algorithm} for: {file_path}')#,end="\r")
22
+ with open(file_path,"rb") as f:
23
+ buff = f.read(self.buffer)
24
+ while buff:
25
+ hash.update(buff)
26
+ buff = f.read(self.buffer)
27
+ return hash.hexdigest().upper()
@@ -0,0 +1,26 @@
1
+ [options]
2
+
3
+ #Index Field - Set to either FullName or RelativeName (other fields untested)
4
+ INDEX_FIELD = FullName
5
+
6
+ PATH_FIELD = FullName
7
+ RELATIVE_FIELD = RelativeName
8
+ PARENT_FIELD = Parent
9
+ PARENT_REF = Parent_Ref
10
+ REFERENCE_FIELD = Archive_Reference
11
+ REF_SECTION = Ref_Section
12
+ ACCESSION_FIELD = Accession_Reference
13
+ LEVEL_FIELD = Level
14
+
15
+ BASENAME_FIELD = BaseName
16
+ EXTENSION_FIELD = Extension
17
+ ATTRIBUTE_FIELD = Attributes
18
+ SIZE_FIELD = Size
19
+ CREATEDATE_FIELD = Create_Date
20
+ MODDATE_FIELD = Modified_Date
21
+ ACCESSDATE_FIELD = Access_Date
22
+
23
+ ACCDELIMTER = -
24
+ METAFOLDER = meta
25
+ OUTPUTSUFFIX = _AutoRef
26
+ EMPTYSUFFIX = _EmptyDirsRemoved
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: auto_reference_generator
3
+ Version: 1.0.0
4
+ Summary: Auto Reference Generator Tool for Archivists
5
+ Author-email: Christopher Prince <c.pj.prince@gmail.com>
6
+ Project-URL: Homepage, https://github.com/CPJPRINCE/auto_reference_generator
7
+ Project-URL: Issues, https://github.com/CPJPRINCE/auto_reference_generator/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: System :: Archiving
12
+ License-File: LICENSE.md
13
+ Requires-Dist: pandas
14
+ Requires-Dist: openpyxl
15
+ Dynamic: license-file
@@ -0,0 +1,12 @@
1
+ auto_reference_generator/__init__.py,sha256=ZVyAC94zAaJkd-H9cMYGcF8TvFtT6Y9VFGwDHUNt3DQ,436
2
+ auto_reference_generator/classification_generator.py,sha256=2TW3JjiZrBqoqm4UYRfLQpADkqHFq0xJahmCDsKtbjc,27923
3
+ auto_reference_generator/cli.py,sha256=vEO7DlLL4lqXCN-mgIcuKgKWLC_XKGSfeNsfZLCGZQ0,8089
4
+ auto_reference_generator/common.py,sha256=y4cOZLfKVIPUvuAVJGbfuLTX2GbyMzgo3p4q7BIGPpg,6131
5
+ auto_reference_generator/hash.py,sha256=gDMXlE3kjJ48GjwO6rAqmTm3OH0k-8KjoHtGjDaYP7I,959
6
+ auto_reference_generator/options/options.properties,sha256=mUc1nfpWecP1i4KB5G_4Qe3HWn4GaPA9gWhT0rcUHKo,616
7
+ auto_reference_generator-1.0.0.dist-info/licenses/LICENSE.md,sha256=SbvpEU5JIU3yzMMkyzrI0dGqHDoJR_lMKGdl6GZHsy4,11558
8
+ auto_reference_generator-1.0.0.dist-info/METADATA,sha256=J1t7c8agpZysdYFJgS5ucC8pcWvX9sUyArpzIX3co58,630
9
+ auto_reference_generator-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
+ auto_reference_generator-1.0.0.dist-info/entry_points.txt,sha256=5T7LMqbCMhfrrso5rIYqd3j7K-kWO82DM28CrcnzrlU,66
11
+ auto_reference_generator-1.0.0.dist-info/top_level.txt,sha256=6Wc4NQwSE0dxwGeNm1stNj_faq2B7-0iq7BCM_cW-v8,25
12
+ auto_reference_generator-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ auto_ref = auto_reference_generator.cli:run_cli
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ auto_reference_generator