-
Notifications
You must be signed in to change notification settings - Fork 1
/
BdplMainApp.py
1917 lines (1441 loc) · 81.7 KB
/
BdplMainApp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import chardet
from collections import OrderedDict
from collections import Counter
import csv
import datetime
import errno
import fnmatch
import glob
import hashlib
import itertools
from lxml import etree
import math
import openpyxl
import os
import paramiko
import pickle
import psutil
import re
import shelve
import shutil
import sqlite3
import stat
import subprocess
import sys
import time
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from urllib.parse import unquote
import urllib.request
import uuid
import webbrowser
import zipfile
# import from dfxml project
import Objects
#BDPL files
from BdplObjects import Unit, Shipment, DigitalObject, Spreadsheet, MasterSpreadsheet, ManualPremisEvent, RipstationBatch, SdaBatchDeposit, McoBatchDeposit, BatchDeaccession
#set up main app as controller
class BdplMainApp(tk.Tk):
def __init__(self, bdpl_work_drive, bdpl_archiver_drive):
tk.Tk.__init__(self)
self.geometry("+0+0")
self.title("Indiana University Library Born-Digital Preservation Lab")
self.iconbitmap(r'C:/BDPL/scripts/favicon.ico')
self.protocol('WM_DELETE_WINDOW', lambda: close_app(self))
self.bdpl_work_drive = bdpl_work_drive
self.bdpl_archiver_drive = bdpl_archiver_drive
self.bdpl_archiver_general_dir = os.path.join(self.bdpl_archiver_drive, 'general%2fmediaimages')
#bdpl_work_drive includes several non-unit folders; list them here so we can exclude them from some operations
self.non_unit_dirs = ['TEST', 'media-images', 'bdpl_transfer_lists', 'bdpl_resources', 'Ripstation']
#store IP addresses for storage locations in a local file
#line 0: IP address and path for BDPL workspace; line 1: IP address and path for main BDPL folder (access to Archiver); line 2: name of server for Avalon dropbox; line 3: path (from root) to Avalon dropbox folder
self.addresses = 'C:/BDPL/resources/addresses.txt'
if not os.path.exists(self.addresses):
messagebox.showwarning(title='WARNING', message="You must create {} for this application to run. See BDPL wiki for more information on file contents.".format(self.addresses), master=self)
return
with open(self.addresses, 'r') as f:
self.ip_addresses = f.read().splitlines()
self.main_server_address = self.ip_addresses[0]
#variables entered into BDPL interface
self.job_type = tk.StringVar()
self.path_to_content = tk.StringVar()
self.identifier = tk.StringVar()
self.unit_name = tk.StringVar()
self.shipment_date = tk.StringVar()
self.source_device = tk.StringVar()
self.other_device = tk.StringVar()
self.disk_525_type = tk.StringVar()
self.re_analyze = tk.BooleanVar()
self.bdpl_failure_notification = tk.BooleanVar()
self.media_attached = tk.BooleanVar()
#SDA Deposit variables
self.separations_status = tk.BooleanVar()
self.separations_file = tk.StringVar()
#GUI metadata variables
self.collection_title = tk.StringVar()
self.collection_creator = tk.StringVar()
self.content_source_type = tk.StringVar()
self.item_title = tk.StringVar()
self.label_transcription = tk.StringVar()
self.item_description = tk.StringVar()
self.appraisal_notes = tk.StringVar()
self.bdpl_instructions = tk.StringVar()
#GUI vars for RipstationIngest
self.ripstation_ingest_option = tk.StringVar()
#GUI vars for MCO Deposit
self.combine_rows = tk.BooleanVar()
#create notebook to start creating app
self.bdpl_notebook = ttk.Notebook(self)
self.bdpl_notebook.pack(pady=10, fill=tk.BOTH, expand=True)
#update info on current tab when it's switched
self.bdpl_notebook.bind('<<NotebookTabChanged>>', self.update_tab)
self.tabs = {}
#other tabs: bag_prep, bdpl_to_mco, RipstationIngest
app_tabs = {BdplIngest : 'BDPL Ingest', RipstationIngest : 'RipStation Ingest', SdaDeposit : 'Deposit to SDA', McoDeposit : 'Deposit to MCO', DeaccessionContent : 'Deaccession Content'}
for tab, description in app_tabs.items():
tab_name = tab.__name__
new_tab = tab(parent=self.bdpl_notebook, controller=self)
self.bdpl_notebook.add(new_tab, text = description)
self.tabs[tab_name] = new_tab
self.option_add('*tearOff', False)
self.menubar = tk.Menu(self)
self.config(menu = self.menubar)
self.actions_ = tk.Menu(self.menubar)
self.menubar.add_cascade(menu=self.actions_, label='Other actions')
self.actions_.add_command(label='Check shipment status', command=self.shipment_status)
self.actions_.add_separator()
self.actions_.add_command(label='Move media images', command=self.media_images)
self.actions_.add_separator()
self.actions_.add_command(label='Add Manual PREMIS event', command= lambda: ManualPremisEvent(self))
self.actions_.add_separator()
self.connect=tk.Menu(self.actions_)
self.actions_.add_cascade(menu=self.connect, label = 'Connect to server...')
self.connect.add_command(label = 'BDPL Workspace', command=lambda:self.connect_to_server('bdpl_workspace'))
self.connect.add_command(label = 'BDPL Archiver', command=lambda:self.connect_to_server('bdpl_archiver'))
self.actions_.add_separator()
self.actions_.add_command(label='Run BDPL Ingest stats', command=self.run_stats)
self.actions_.add_separator()
self.actions_.add_command(label='Update BDPL scripts', command=self.update_scripts)
self.help_ = tk.Menu(self.menubar)
self.menubar.add_cascade(menu=self.help_, label='Help')
self.help_.add_command(label='Open BDPL wiki', command = lambda: webbrowser.open_new(r"https://wiki.dlib.indiana.edu/display/DIGIPRES/Born+Digital+Preservation+Lab"))
def get_current_tab(self):
return self.bdpl_notebook.tab(self.bdpl_notebook.select(), 'text')
def update_scripts(self):
restart = messagebox.askyesno(title='Update BDPL Scripts', message='Updating scripts will close the BDPL app. Continue?')
if restart:
#run batch file to update git repos
cmd = 'START CMD /C "C:/BDPL/scripts/update_BDPL_scripts.bat"'
subprocess.run(cmd, shell=True)
#close app
sys.exit(0)
def update_tab(self, event):
event.widget.update_idletasks()
tab = event.widget.nametowidget(event.widget.select())
event.widget.configure(height=tab.winfo_reqheight())
if self.bdpl_notebook.tab(self.bdpl_notebook.select(), 'text') in ['Deposit to SDA']:
if not self.check_connection(self.bdpl_archiver_drive):
messagebox.showwarning(title='WARNING', message='\n\nMap Archiver_spool to {} before proceeding!'.format(self.bdpl_archiver_drive), master=self)
self.clear_gui()
def check_main_vars(self, skip_barcode=False):
if self.unit_name.get() == '':
return (False, '\n\nERROR: please make sure you have entered a unit ID abbreviation.')
#make sure we are connected to appropriate unit share
if not self.check_connection(self.bdpl_work_drive):
return (False, '\n\nMap {} to appropriate server share before proceeding!'.format(self.bdpl_work_drive))
if self.bdpl_notebook.tab(self.bdpl_notebook.select(), 'text') in ['Deposit to SDA']:
if not self.check_connection(self.bdpl_archiver_drive):
return (False, '\n\nMap Archiver_spool to {} before proceeding!'.format(self.bdpl_archiver_drive))
if self.shipment_date.get() == '':
return (False, '\n\nERROR: please make sure you have entered a shipment date.')
#check barcode value, too, if we're using standard BDPL Ingest tab
if self.get_current_tab() == 'BDPL Ingest':
if skip_barcode:
return (True, 'Unit name and shipment date included.')
if self.identifier.get() == '':
return (False, '\n\nERROR: please make sure you have entered a barcode value.')
#if RipStation job, make sure essential info/files are identified
elif self.get_current_tab() == 'RipStation Ingest':
if not self.ripstation_ingest_option.get() in ['CDs', 'DVD_Data']:
return (False, '\n\nERROR: select RipStation job option before continuing.')
#if we get through the above, then we are good to go!
return (True, 'Unit name and shipment date included.')
def end_connection(self, drive_letter):
cmd = 'NET USE {} /DELETE'.format(drive_letter.replace('\\', ''))
try:
out = subprocess.check_output(cmd, shell=True, text=True)
print('\n\nDisconnecting {} drive.\n\n{}'.format(drive_letter, out))
except subprocess.CalledProcessError as e:
messagebox.showwarning(title='WARNING', message="Failed to disconnect.\n\n{}".format(e), master=self)
#drive_letter is a list with the drive letters we want to check: bdpl-workspace and/or Archiver_spool
def check_connection(self, drive_letter):
#get list of all mapped drives and associated paths
cmd = 'net use'
drive_info = subprocess.check_output(cmd, shell=True, text=True).splitlines()
#now parse output into a list of lists
drive_info = [ls.split() for ls in drive_info]
#finally, get info for each mounted drive letter in a dictionary (key=drive letter, value=address)
drive_info = {ls[1]:ls[2] for ls in drive_info if len(ls)==3 and ls[0]=='OK'}
d_l = drive_letter.replace('\\', '')
if d_l in drive_info.keys():
server_name = drive_info[d_l]
if drive_letter == self.bdpl_work_drive:
#there may be variation in how someone maps to unit workspace; check both options
name = 'bdpl_workspace'
target = os.path.join(self.ip_addresses[0], 'bdpl-workspace-{}'.format(self.unit_name.get().lower()))
shares = [os.path.join(self.ip_addresses[0], 'bdpl', 'workspace', self.unit_name.get()), target]
if any(share for share in shares if share == server_name):
status = True
else:
status = False
elif drive_letter == self.bdpl_archiver_drive:
name = 'bdpl_archiver'
target = self.ip_addresses[1]
if 'archiver-spool' in server_name.lower():
status = True
else:
status = False
#if there's an issue with the connection, we need to disconnect and reconnect
if not status:
option = messagebox.askokcancel(title='WARNING', message='{} is currently mapped to {}.\n\nBased upon the provided Unit Name, this should be {}.\n\nOptions:\n\n(a)Click "OK" to connect to {}\n(MAKE SURE NO FILES ON ARE OPEN!!!)\n\n\(b)Click "Cancel" to correct the Unit Name.'.format(drive_letter, server_name, target, target), master=self)
if option:
#disconnect from current server
self.end_connection(drive_letter)
#now connect to appropriate server
self.connect_to_server(name)
return True
else:
return False
#if there's no problem, just return True
else:
return True
#if our drive_letter is not currently connected, we need to connect
else:
if drive_letter == self.bdpl_work_drive:
if self.unit_name.get() != '':
self.connect_to_server('bdpl_workspace')
return True
else:
return False
elif drive_letter == self.bdpl_archiver_drive:
self.connect_to_server('bdpl_archiver')
return True
def shipment_status(self):
status, msg = self.check_main_vars(True)
if not status:
messagebox.showwarning(title='WARNING', message=msg, master=self)
return
shipment_spreadsheet = Spreadsheet(self)
shipment_spreadsheet.check_shipment_progress()
def categorize_source(self, source):
optical = ['cd', 'dvd', 'optical', 'cdrom']
usb_drives = ['cruzer', 'usb', 'flash', 'thumb']
hard_drives = ['passport', 'external', 'hard']
other_transfer = ['n/a', 'email', 'cloud', 'tar', 'folder']
if source is None:
return 'other'
elif any(f in source.lower() for f in optical):
return 'optical_disk'
elif '3.5' in source:
return '3.5"_floppy'
elif '5.25' in source:
return '5.25"_floppy'
elif 'zip' in source.lower():
return 'zip_disk'
elif any(f in source.lower() for f in usb_drives):
return 'usb_drive'
elif any(f in source.lower() for f in hard_drives):
return 'external_harddrive'
elif any(f in source.lower() for f in other_transfer):
return 'other'
else:
return source.split(' (')[0].lower().replace(' ', '').replace('?', '')
def convert_to_bytes(self, size):
if 'bytes' in size:
volume = int(size.split(' ')[0])
elif 'KB' in size:
volume = int(size.split(' ')[0]) * 1000
elif 'MB' in size:
volume = int(size.split(' ')[0]) * 1000000
elif 'GB' in size:
volume = int(size.split(' ')[0]) * 1000000000
elif 'GB' in size:
volume = int(size.split(' ')[0]) * 1000000000000
return volume
def write_stats(self, f, label, item_count, file_count, extent, formats, inaccurate_file_count, items_not_done=None):
f.write('\t{}\n'.format(label))
f.write('\t\tItems: {}\n'.format(item_count))
if not items_not_done is None:
f.write('\t\tItems NOT completed: {}\n'.format(items_not_done))
f.write('\t\tFiles: {} '.format(file_count))
#add disclaimer if file count is not accurate
if inaccurate_file_count:
f.write('(NOTE: legacy stats lack accurate count of individual files in SDA)\n')
else:
f.write('\n')
f.write('\t\tVolume: {} bytes ({})\n'.format(extent, Shipment(self).convert_size(extent)))
if len(formats) > 0:
f.write('\t\tSource formats:\n')
for k, v in Counter(formats).most_common():
f.write('\t\t\t{} : {}\n'.format(k, v))
f.write('\n')
def run_stats(self):
newscreen()
#make sure we aren't messing up a current project; give user option to quit if GUI shouldn't be cleared
if self.unit_name.get() == '':
messagebox.showwarning(title='WARNING', message="Indicate Unit before proceeding", master=self)
return
if not self.check_connection(self.bdpl_work_drive):
return
else:
self.clear_gui()
current_unit = Unit(self)
print('GETTING STATS FOR {} CURRENT SHIPMENTS...'.format(current_unit.unit_name))
#get a list of all unit directories
#assign output variable; remove file if it exists
stats_output = "C:/BDPL/bdpl_stats.txt"
if os.path.exists(stats_output):
os.remove(stats_output)
current_stats = {}
#loop through all shipment folders
for shipment in [ship for ship in os.listdir(current_unit.ingest_dir) if os.path.isdir(os.path.join(current_unit.ingest_dir, ship))]:
self.shipment_date.set(shipment)
current_shipment = Shipment(self)
print('\n\tReviewing shipment: {}'.format(current_shipment.shipment_name))
#skip item if we don't have a spreadsheet in the folder
status, msg = current_shipment.verify_spreadsheet()
if not status:
print('\n\t\t{}'.format(msg.lstrip()))
continue
#create spreadsheet object
current_spreadsheet = Spreadsheet(self)
#check to see if this spreadsheet has been copied to 'completed spreadsheets'--will only happen if shipment is completed. If so, continue to next shipment
if os.path.exists(current_spreadsheet.completed_spreadsheet):
print('\n\t\t Completed.')
continue
#open the spreadsheet and read to memory
current_spreadsheet.open_wb()
#get index of columns in appraisal worksheet based on column titles; adjust index for use with iterrows
ws_columns = current_spreadsheet.get_spreadsheet_columns(current_spreadsheet.app_ws, True)
#add a shipment dict to our current_dict
if not current_stats.get(current_shipment.shipment_date):
current_stats[current_shipment.shipment_date] = {'formats' : [], 'item_count' : 0, 'size' : 0, 'file_count' : 0, 'failed' : 0, 'items_not_done' : 0}
#now loop through barcodes in appraisal spreadsheet
iterrows = current_spreadsheet.app_ws.iter_rows()
next(iterrows)
for row in iterrows:
if not row[ws_columns['identifier']].value is None:
if row[ws_columns['migration_outcome']].value == 'Success':
current_stats[current_shipment.shipment_date]['item_count'] += 1
current_stats[current_shipment.shipment_date]['file_count'] += int(row[ws_columns['item_file_count']].value)
source_type = self.categorize_source(row[ws_columns['content_source_type']].value)
current_stats[current_shipment.shipment_date]['formats'].append(source_type)
if row[ws_columns['extent_raw']].value == '-':
current_stats[current_shipment.shipment_date]['size'] += self.convert_to_bytes(int(row[ws_columns['extent_normal']].value))
else:
current_stats[current_shipment.shipment_date]['size'] += int(row[ws_columns['extent_raw']].value)
else:
current_stats[current_shipment.shipment_date]['failed'] += 1
#now see how many items haven't been completed.
app_barcodes = current_spreadsheet.get_items_on_app_ws()
inv_barcodes, inv_list = current_spreadsheet.get_items_on_inv_ws()
current_stats[current_shipment.shipment_date]['items_not_done'] = len(list(set(inv_list) - set(app_barcodes)))
#set variables for grand totals
total_items = 0
total_unfinished = 0
total_file_count = 0
total_size = 0
total_formats = []
#loop through current_stats dict and write info to our output file; add values to grand totals
with open(stats_output, 'a') as f:
f.write('BDPL STATISTICS for {}\nPrepared on: {}\n\nCURRENT SHIPMENTS:\n'.format(current_unit.unit_name, datetime.date.today().strftime("%B %d, %Y")))
for ship_date in sorted(current_stats.keys()):
label = 'Shipment {}:'.format(ship_date)
self.write_stats(f, label, current_stats[ship_date]['item_count'], current_stats[ship_date]['file_count'], current_stats[ship_date]['size'], current_stats[ship_date]['formats'], False, current_stats[ship_date]['items_not_done'])
#collect variables
label ='Current work totals for {}:'.format(current_unit.unit_name)
unit_items = sum([current_stats[ship_date]['item_count'] for ship_date in current_stats.keys()])
total_items += unit_items
unit_unfinished = sum([current_stats[ship_date]['items_not_done'] for ship_date in current_stats.keys()])
total_unfinished += unit_unfinished
unit_file_count = sum([current_stats[ship_date]['file_count'] for ship_date in current_stats.keys()])
total_file_count += unit_file_count
unit_size = sum([current_stats[ship_date]['size'] for ship_date in current_stats.keys()])
total_size += unit_size
unit_formats = list(itertools.chain.from_iterable([current_stats[ship_date]['formats'] for ship_date in current_stats.keys()]))
total_formats += unit_formats
#now use write_stats method
self.write_stats(f, label, unit_items, unit_file_count, unit_size, unit_formats, False, unit_unfinished)
#now write grand totals for current work
f.write('\nGRAND TOTALS FOR CURRENT WORK:\n')
self.write_stats(f, '', total_items, total_file_count, total_size, total_formats, False, total_unfinished)
'''NEXT, GET STATS ON CONTENT DEPOSITED TO SDA'''
print('\n\n\nCOLLECTING STATISTICS FOR CONTENT DEPOSITED TO SDA...')
#get a copy of master spreadsheet; open
master_spreadsheet = MasterSpreadsheet(self)
master_spreadsheet.open_wb()
ws_columns = master_spreadsheet.get_spreadsheet_columns(master_spreadsheet.item_ws, True)
master_stats = {}
iterrows = master_spreadsheet.item_ws.iter_rows()
next(iterrows)
years = set()
for row in iterrows:
current_dict = {}
#set a flag in case we will not have an accurate file count from legacy SDA stats
inaccurate_count = False
sip_creation_date = str(row[ws_columns['sip_creation_date']].value)[:4]
years.add(sip_creation_date)
content_source_type = self.categorize_source(row[ws_columns['content_source_type']].value)
unit_name = row[ws_columns['unit_name']].value
#as of Feb. 2021, legacy stats are not complete; account for None values...
if row[ws_columns['item_file_count']].value is None:
file_count = 1
inaccurate_count = True
else:
file_count = int(row[ws_columns['item_file_count']].value)
if row[ws_columns['extent_raw']].value is None:
extent_raw = int(row[ws_columns['sip_extent']].value)
else:
extent_raw = int(row[ws_columns['extent_raw']].value)
#create a dictionary for each unit if they do not exist
if not master_stats.get(unit_name):
master_stats[unit_name] = {}
#if it's the first time we've encountered a year, create a new dict for it and add values
if not master_stats[unit_name].get(sip_creation_date):
master_stats[unit_name][sip_creation_date] = {'AIP_count' : 1, 'file_count' : file_count, 'extent_raw' : extent_raw, 'formats' : [content_source_type], 'inaccurate_file_count' : inaccurate_count}
#if we've already seen this year, increment our existing values
else:
master_stats[unit_name][sip_creation_date]['AIP_count'] += 1
master_stats[unit_name][sip_creation_date]['file_count'] += file_count
master_stats[unit_name][sip_creation_date]['extent_raw'] += extent_raw
master_stats[unit_name][sip_creation_date]['formats'].append(content_source_type)
if inaccurate_count:
master_stats[unit_name][sip_creation_date]['inaccurate_file_count'] = inaccurate_count
#now write out results; first for individual units, and then totals per year
with open(stats_output, 'a') as f:
f.write('\n\nCONTENT DEPOSITED TO SDA:\n\n')
#loop through unit info in dict
for key in sorted(master_stats.keys()):
#write unit name
f.write('{}:\n'.format(key))
#now loop through each year and use write_stats method
for deposit_year in sorted(master_stats[key].keys()):
label = '{}:'.format(deposit_year)
self.write_stats(f, label, master_stats[key][deposit_year]['AIP_count'], master_stats[key][deposit_year]['file_count'], master_stats[key][deposit_year]['extent_raw'], master_stats[key][deposit_year]['formats'], master_stats[key][deposit_year]['inaccurate_file_count'])
label = 'Total {} SDA deposits:'.format(key)
unit_items = sum([master_stats[key][y]['AIP_count'] for y in master_stats[key].keys()])
unit_file_count = sum([master_stats[key][y]['file_count'] for y in master_stats[key].keys()])
unit_total_size = sum([master_stats[key][y]['extent_raw'] for y in master_stats[key].keys()])
unit_formats = list(itertools.chain.from_iterable([master_stats[key][y]['formats'] for y in master_stats[key].keys()]))
unit_inaccurate = any([master_stats[key][y]['inaccurate_file_count'] for y in master_stats[key].keys()])
self.write_stats(f, label, unit_items, unit_file_count, unit_total_size, unit_formats, unit_inaccurate)
print('\nText file with these statistics located at: {}'.format(stats_output))
self.clear_gui()
#remove local copy of master spreadsheet and open output file
cmd = 'notepad %s' % stats_output
subprocess.call(cmd)
def media_images(self):
#make sure main variables--unit_name, shipment_date, and barcode--are included. Return if either is missing
#make sure unit value is not empty and that
if self.unit_name.get() == '':
print('\n\nError; please make sure you have entered a unit ID abbreviation.')
return
if not self.check_connection(self.bdpl_work_drive):
return
current_unit = Unit(self)
current_unit.move_media_images()
def add_manual_premis_event(self):
#make sure main variables--unit_name, shipment_date, and barcode--are included. Return if either is missing
status, msg = self.check_main_vars()
if not status:
messagebox.showwarning(title='WARNING', message=msg, master=self)
return
#create a manual PREMIS object
new_premis_event = ManualPremisEvent(self)
def update_combobox(self, combobox):
if self.unit_name.get() == '':
combobox_list = []
else:
folders = os.path.join(self.bdpl_work_drive, 'ingest')
combobox_list = glob.glob1(folders, '*')
combobox['values'] = sorted(combobox_list)
def clear_gui(self):
newscreen()
#reset all text fields/labels
self.content_source_type.set('')
self.collection_title.set('')
self.collection_creator.set('')
self.item_title.set('')
self.label_transcription.set('')
self.item_description.set('')
self.appraisal_notes.set('')
self.bdpl_instructions.set('')
self.identifier.set('')
self.path_to_content.set('')
self.other_device.set('')
#reset 5.25" floppy disk type
self.disk_525_type.set('N/A')
#reset checkbuttons
self.bdpl_failure_notification.set(False)
self.re_analyze.set(False)
self.media_attached.set(False)
self.combine_rows.set(False)
#reset radio buttons
self.job_type.set(None)
self.source_device.set(None)
self.ripstation_ingest_option.set(None)
#reset note text box
self.tabs['BdplIngest'].bdpl_technician_note.delete(1.0, tk.END)
if self.get_current_tab() == 'RipStation Ingest':
self.unit_name.set('')
self.shipment_date.set('')
self.separations_file.set('')
self.separations_status.set(False)
elif self.get_current_tab() in ['Deposit to MCO', 'Deposit to SDA']:
self.unit_name.set('')
self.shipment_date.set('')
def connect_to_server(self, servername):
ServerConnect(self, servername)
def check_list(self, list_name, identifier):
if not os.path.exists(list_name):
return False
with open(list_name, 'r') as f:
for item in f:
if identifier in item.strip():
return True
else:
continue
return False
def write_list(self, list_name, message):
with open(list_name, 'a') as f:
f.write('{}\n'.format(message))
class ServerConnect(tk.Toplevel):
def __init__(self, controller, servername=None):
tk.Toplevel.__init__(self, controller)
self.title('BDPL Ingest: Connect to Server')
self.iconbitmap(r'C:/BDPL/scripts/favicon.ico')
self.protocol('WM_DELETE_WINDOW', self.close_top)
self.attributes('-topmost', 'true')
self.servername = servername
self.server = tk.StringVar()
self.drive_letter = tk.StringVar()
self.username = tk.StringVar()
self.password = tk.StringVar()
self.connection_message = tk.StringVar()
self.controller = controller
if self.servername == 'bdpl_workspace':
self.server.set(self.controller.ip_addresses[0])
self.drive_letter.set(self.controller.bdpl_work_drive.replace('\\', ''))
target_server = 'BDPL unit workspace'
elif self.servername == 'bdpl_archiver':
self.server.set(self.controller.ip_addresses[1])
self.drive_letter.set(self.controller.bdpl_archiver_drive.replace('\\', ''))
target_server = 'ArchiverShell dropbox location'
'''
CREATE FRAMES!
'''
tab_frames_list = [('message_frame', ''), ('login_frame', 'Login Information:'), ('button_frame', 'Actions:')]
self.tab_frames_dict = {}
for name_, label_ in tab_frames_list:
f = tk.LabelFrame(self, text = label_)
f.pack(fill=tk.BOTH, expand=True, pady=5)
self.tab_frames_dict[name_] = f
'''
MESSAGE
'''
self.connection_message.set('Log in to {}'.format(target_server))
ttk.Label(self.tab_frames_dict['message_frame'], textvariable=self.connection_message).pack(padx=10, pady=10)
'''
LOGIN FIELDS
'''
entry_fields = [('Username:', self.username), ('Password:', self.password)]
if self.servername == 'bdpl_workspace':
entry_fields.insert(0, ('Unit:', self.controller.unit_name))
self.entries={}
c = 0
for label_, var in entry_fields:
l = tk.Label(self.tab_frames_dict['login_frame'], text=label_, anchor='e', justify=tk.RIGHT, width=10)
l.grid(row = c, column=0, padx=(10,0), pady=10)
e = ttk.Entry(self.tab_frames_dict['login_frame'], width=30, textvariable=var)
if label_ == 'Password:':
e.config(show='*')
e.grid(row = c, column=1, padx=(0,10), pady=10)
self.entries[label_] = e
c+=1
self.display_pw = tk.BooleanVar()
self.display_pw.set(False)
display = ttk.Checkbutton(self.tab_frames_dict['login_frame'], text='Show password?', variable=self.display_pw, command=self.display_text)
display.grid(row = 1, column=2, padx=10, pady=10)
'''
BUTTONS
'''
self.button_id = {}
buttons = ['Connect', 'Cancel']
c=1
for b in buttons:
button = tk.Button(self.tab_frames_dict['button_frame'], text=b, bg='light slate gray', width = 10)
button.grid(row=0, column=c, padx=25, pady=10)
self.button_id[b] = button
c+=1
self.tab_frames_dict['button_frame'].grid_columnconfigure(0, weight=1)
self.tab_frames_dict['button_frame'].grid_columnconfigure(3, weight=1)
self.button_id['Connect'].config(command=self.login)
self.button_id['Cancel'].config(command=self.close_top)
def display_text(self):
if self.display_pw.get():
self.entries['Password:'].config(show='')
else:
self.entries['Password:'].config(show='*')
def login(self):
if self.servername == 'bdpl_workspace':
if self.controller.unit_name.get() == '':
messagebox.showwarning(title='WARNING', message='Enter unit name before proceeding!', master=self)
return
else:
self.server.set(os.path.join(self.controller.ip_addresses[0], 'bdpl-workspace-{}'.format(self.controller.unit_name.get().lower())))
cmd = 'NET USE {} {} /user:BL-LBLG\{} "{}"'.format(self.drive_letter.get(), self.server.get(), self.username.get(), self.password.get())
p = subprocess.run(cmd, shell=True, text=True, capture_output=True)
if p.returncode == 0:
messagebox.showinfo(title='SUCCESS', message='Successfully mapped {} to drive {}'.format(self.server.get(), self.drive_letter.get()), master=self)
self.close_top()
if self.servername == 'bdpl_archiver':
targets = glob.glob1(self.controller.bdpl_archiver_drive, '*')
self.controller.tabs['SdaDeposit'].archiver_combobox['values'] = targets
self.controller.tabs['SdaDeposit'].archiver_combobox.current(targets.index('general%2fmediaimages'))
else:
messagebox.showwarning(title='WARNING', message='Failed to connect to {}:\n\n{}'.format(self.server.get(), p.stderr), master=self)
def close_top(self):
#close window
self.destroy()
class McoConnect(ServerConnect):
def __init__(self, controller, mco_server, parent):
ServerConnect.__init__(self, controller)
self.parent = parent
#add unique features for McoConnect
self.server.set(mco_server)
self.connection_message.set('Log in to {}'.format(self.server.get()))
self.button_id['Connect'].config(command=self.get_credentials)
def get_credentials(self):
#return username and password so these can be used by McoSftpClient
self.parent.username = self.username.get()
self.parent.password = self.password.get()
#close TopLevel once info has been assigned to parent
self.destroy()
class McoSftpClient:
def __init__(self, controller, username, password, host, mco_dir):
self.controller = controller
self.host = host
self.username = username
self.password = password
self.port = 22
self.mco_dir = mco_dir
def create_client(self):
try:
self.transport = paramiko.Transport((self.host, self.port))
except socket.gaierror as e:
messagebox.showwarning(title='WARNING', message='Unable to connect to MCO dropbox ({}).'.format(e), master=self)
return
try:
self.transport.connect(None, self.username, self.password)
except paramiko.ssh_exception.AuthenticationException as e:
messagebox.showwarning(title='WARNING', message='Authentication issue. Check username / password and try again.', master=self.controller)
return
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
def get_collection_list(self):
ls = [fileattr.filename for fileattr in self.sftp.listdir_attr(self.mco_dir) if stat.S_ISDIR(fileattr.st_mode)]
return sorted(ls)
def make_dirs(self, asset_path):
dirs_ = []
while len(asset_path) > 1:
dirs_.append(asset_path)
asset_path, _ = os.path.split(asset_path)
if len(asset_path) == 1 and not asset_path.startswith("/"):
dirs_.append(asset_path)
while len(dirs_):
asset_path = dirs_.pop()
try:
self.sftp.stat(asset_path)
except:
self.sftp.mkdir(asset_path)
def close_client(self):
try:
if self.sftp:
self.sftp.close()
if self.transport:
self.transport.close()
except NameError:
print('\n\nError; SFTP client not created.')
return
class BdplIngest(tk.Frame):
def __init__(self, parent, controller):
#create main frame in notebook
tk.Frame.__init__(self, parent)
self.config(height=700)
self.pack(fill=tk.BOTH, expand=True)
self.parent = parent
self.controller = controller
'''
CREATE FRAMES!
'''
tab_frames_list = [('batch_info_frame', 'Basic Information:'), ('job_type_frame', 'Select Job Type:'), ('path_frame', 'Path to content / file list:'), ('source_device_frame', 'Select physical media or drive type:'), ('button_frame', 'BDPL Ingest Actions:'), ('bdpl_note_frame', 'Note from BDPL technician on transfer & analysis:'), ('item_metadata_frame', 'Item Metadata:')]
self.tab_frames_dict = {}
for name_, label_ in tab_frames_list:
f = tk.LabelFrame(self, text = label_)
f.pack(fill=tk.BOTH, expand=True, pady=5)
self.tab_frames_dict[name_] = f
'''
BATCH INFORMATION FRAME: includes entry fields to capture barcode, unit, and shipment date
'''
entry_fields = [('Item barcode:', 20, self.controller.identifier), ('Unit:', 5, self.controller.unit_name), ('Shipment date:', 10, self.controller.shipment_date)]
for label_, width_, var_ in entry_fields:
if label_ == 'Shipment date:':
ttk.Label(self.tab_frames_dict['batch_info_frame'], text=label_).pack(padx=(20,0), pady=10, side=tk.LEFT)
self.date_combobox = ttk.Combobox(self.tab_frames_dict['batch_info_frame'], width=20, textvariable=var_, postcommand = lambda: self.controller.update_combobox(self.date_combobox))
self.date_combobox.pack(padx=10, pady=10, side=tk.LEFT)
else:
ttk.Label(self.tab_frames_dict['batch_info_frame'], text=label_).pack(padx=(20,0), pady=10, side=tk.LEFT)
e = ttk.Entry(self.tab_frames_dict['batch_info_frame'], width=width_, textvariable=var_)
e.pack(padx=10, pady=10, side=tk.LEFT)
#set up the job type frame
radio_buttons = [('Copy only', 'Copy_only'), ('Disk Image', 'Disk_image'), ('DVD', 'DVD'), ('CDDA', 'CDDA')]
self.controller.job_type.set(None)
for k, v in radio_buttons:
ttk.Radiobutton(self.tab_frames_dict['job_type_frame'], text = k, variable = self.controller.job_type, value = v, command = self.set_jobtype_options).pack(side=tk.LEFT, padx=30, pady=5)
self.re_analyze_chkbx = ttk.Checkbutton(self.tab_frames_dict['job_type_frame'], text='Rerun analysis?', variable=self.controller.re_analyze)
self.re_analyze_chkbx.pack(side=tk.LEFT, padx=25, pady=5)
'''
PATH FRAME: entry box to display directory path and button to launch askfiledialog
'''
self.source_entry = ttk.Entry(self.tab_frames_dict['path_frame'], width=80, textvariable=self.controller.path_to_content)
self.source_entry.pack(side=tk.LEFT, padx=(20,5), pady=5)
self.source_button = tk.Button(self.tab_frames_dict['path_frame'], text='Browse', bg='light slate gray', command=self.source_browse)
self.source_button.pack(side=tk.LEFT, padx=(5,20), pady=5)
'''
SOURCE DEVICE FRAME: radio buttons and other widgets to record information on the source media and/or device
'''
devices = [('CD/DVD', '/dev/sr0'), ('3.5"', '/dev/fd0'), ('5.25"', '5.25'), ('5.25_menu', 'menu'), ('Zip', 'Zip'), ('Other', 'Other'), ('Other_device', 'Other device name'), ('Attached?', 'Is media attached?')]
disk_type_options = ['N/A', 'Apple DOS 3.3 (16-sector)', 'Apple DOS 3.2 (13-sector)', 'Apple ProDOS', 'Commodore 1541', 'TI-99/4A 90k', 'TI-99/4A 180k', 'TI-99/4A 360k', 'Atari 810', 'MS-DOS 1200k', 'MS-DOS 360k', 'North Star MDS-A-D 175k', 'North Star MDS-A-D 350k', 'Kaypro 2 CP/M 2.2', 'Kaypro 4 CP/M 2.2', 'CalComp Vistagraphics 4500', 'PMC MicroMate', 'Tandy Color Computer Disk BASIC', 'Motorola VersaDOS']
#loop through our devices to create radiobuttons.
for k, v in devices:
#Insert an option menu for 5.25" floppy disk types
if k == '5.25_menu':
self.controller.disk_525_type.set('N/A')
self.disk_menu = tk.OptionMenu(self.tab_frames_dict['source_device_frame'], self.controller.disk_525_type, *disk_type_options)
self.disk_menu.pack(side=tk.LEFT, padx=10, pady=5)
#add an entry field to add POSIX name for 'other' device
elif k == 'Other_device':
self.controller.other_device.set('')
ttk.Label(self.tab_frames_dict['source_device_frame'], text="(& name)").pack(side=tk.LEFT, pady=5)
self.other_deviceEntry = tk.Entry(self.tab_frames_dict['source_device_frame'], width=5, textvariable=self.controller.other_device)
self.other_deviceEntry.pack(side=tk.LEFT, padx=(0,10), pady=5)
elif k == 'Attached?':
self.controller.media_attached.set(False)
ttk.Checkbutton(self.tab_frames_dict['source_device_frame'], text=k, variable=self.controller.media_attached).pack(side=tk.LEFT, padx=10, pady=5)
#otherwise, create radio buttons
else:
ttk.Radiobutton(self.tab_frames_dict['source_device_frame'], text=k, value=v, variable=self.controller.source_device).pack(side=tk.LEFT, padx=10, pady=5)
'''
BUTTON FRAME: buttons for BDPL Ingest actions
'''
button_id = {}
buttons = ['New', 'Load', 'Transfer', 'Analyze', 'Quit']
for b in buttons:
button = tk.Button(self.tab_frames_dict['button_frame'], text=b, bg='light slate gray', width = 10)
button.pack(side=tk.LEFT, padx=25, pady=10)
button_id[b] = button
#now use button instances to assign commands
button_id['New'].config(command = self.controller.clear_gui)
button_id['Load'].config(command = self.launch_session)
button_id['Transfer'].config(command = self.launch_transfer)
button_id['Analyze'].config(command = self.launch_analysis)
button_id['Quit'].config(command = lambda: close_app(self.controller))
'''
BDPL NOTE FRAME: text widget to record notes on the transfer/analysis process. Also checkbox to document item failure
'''
self.bdpl_technician_note = tk.Text(self.tab_frames_dict['bdpl_note_frame'], height=2, width=60, wrap = 'word')
self.bdpl_note_scroll = ttk.Scrollbar(self.tab_frames_dict['bdpl_note_frame'], orient = tk.VERTICAL, command=self.bdpl_technician_note.yview)
self.bdpl_technician_note.config(yscrollcommand=self.bdpl_note_scroll.set)
self.bdpl_technician_note.grid(row=0, column=0, padx=(30, 0), pady=10)
self.bdpl_note_scroll.grid(row=0, column=1, padx=(0, 10), pady=(10, 0), sticky='ns')
tk.Button(self.tab_frames_dict['bdpl_note_frame'], text="Save", width=5, bg='light slate gray', command=self.write_technician_note).grid(row=0, column=2, padx=10)
self.controller.bdpl_failure_notification.set(False)
ttk.Checkbutton(self.tab_frames_dict['bdpl_note_frame'], text="Record failed transfer with note", variable=self.controller.bdpl_failure_notification).grid(row=1, column=0, columnspan=2, padx=20, pady=(0, 10))
'''
ITEM METADATA FRAME: display info about our item to BDPL technician
'''
canvas = tk.Canvas(self.tab_frames_dict['item_metadata_frame'])