-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlister.py
2429 lines (2177 loc) · 119 KB
/
lister.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
from __future__ import annotations
import json
import os
import re
import warnings
import pathlib
from argparse import Namespace
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Tuple, Union, TypedDict
from io import StringIO
from pprint import pprint
# Prevent unresolved references
import platform
import unicodedata
from multiprocessing import freeze_support
# Third-party imports
import elabapi_python
import latex2mathml.converter
import pandas as pd
import urllib3
import xlsxwriter
from bs4 import BeautifulSoup, Tag
from docx import Document
from docx.shared import Mm, RGBColor
from elabapi_python.rest import ApiException
from gooey import Gooey, GooeyParser
from lxml import etree
from pathvalidate import sanitize_filepath
# TODO: remove the following line when the issue is fixed
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# -------------------------------- CLASSES TO HANDLE ENUMERATED CONCEPTS --------------------------------
# Control Flow Metadata Types
class CFMetadata(Enum):
STEP_TYPE = "step type"
FLOW_TYPE = "flow type"
FLOW_PARAMETER = "flow parameter"
FLOW_LOGICAL_OPERATOR = "flow logical parameter"
FLOW_COMPARED_VALUE = "flow compared value"
FLOW_RANGE = "flow range"
FLOW_OPERATION = "flow operation"
FLOW_MAGNITUDE = "flow magnitude"
FLOW_SECTION = "section"
FLOW_ITERATION_START = "start iteration value"
FLOW_ITERATION_END = "end iteration value"
class BracketPairErrorMsg(Enum):
IMPROPER_COMMENT_BRACKET = "ERROR: Mismatch between '(' and ')'. Check line "
IMPROPER_RANGE_BRACKET = "ERROR: Mismatch between '[' and ']'. Check line "
IMPROPER_KEY_VALUE_BRACKET = "ERROR: Mismatch between '{' and '}'. Check line "
IMPROPER_FLOW_BRACKET = "ERROR: Mismatch between '<' and '>'. Check line "
class MiscAlertMsg(Enum):
ARGUMENT_MISMATCH = "ERROR: Argument type mismatch: numerical value is found while string was expected. " \
"Check the value '{0}' in the following set of values: '{1}'."
UNRECOGNIZED_OPERATOR = "ERROR: The logical operator is not recognized. " \
"Please check the operator '{0}' in the following set of values: {1}. " \
"Only 'e', 'ne', 'lt', 'lte', 'gt', 'gte' and 'between' are supported."
UNRECOGNIZED_FLOW_TYPE = "WARNING: The flow type is not recognized. " \
"Please check the flow type {0} in the following set of values: {1}."
RANGE_NOT_TWO_ARGUMENTS = "ERROR: There should only be two numerical arguments on a range separated by a dash " \
"(-). Please check the following set of values: {0}."
RANGE_NOT_NUMBERS = "ERROR: The range values should only contain numbers." \
"Check the following part: {0}."
INVALID_ITERATION_OPERATOR = "ERROR: {0} is not a valid iteration operators. Only +, -, *, / and %% " \
"are supported.Check the following part: {1}."
IMPROPER_ARGUMENT_NO = "ERROR: Expected number of arguments in the '{0}' statement is {1}, but {2} was found." \
"Check the following part: '{3}'"
ITERATION_OPERATION_NOT_EXIST = "ERROR: The iteration operation is not found, please check the following part: {0}."
MAGNITUDE_NOT_EXIST = "ERROR: The magnitude of the iteration flow is not found, " \
"please check the following part: {0}."
INACCESSIBLE_RESOURCE = "ERROR: Resource with ID '{0}' is either unavailable or not accessible using the " \
"current user's API Token. " \
"Please check the resource ID and the user's permission. Reason: {1}, code: {2}, " \
"message: {3}, description: {4} Parsing this resource is skipped."
INACCESSIBLE_EXPERIMENT = "ERROR: Experiment with ID '{0}' is is either unavailable or not accessible using " \
"the current user's API Token." \
" Please check the experiment ID and the user's permission. Reason: {1}, code: {2}, " \
"message: {3}, description: {4} Parsing this experiment is skipped."
SIMILAR_PAR_KEY_FOUND = "WARNING: A combination of similar paragraph number and key has been found, '{0}'. " \
"Please make sure that this is intended."
INACCESSIBLE_ATTACHMENT = "WARNING: File with name '{0}' is not accessible, with the exception: " \
"\n {1}. \n Try contacting eLabFTW administrator reporting the exception mentioned."
INVALID_METADATA_SET_ELEMENT_NO = "ERROR: The number of key value element set must be either two (key-value) " \
"or four (key-value-measure-unit). There are {0} element(s) found in this " \
"key-value set: {1}."
SINGLE_PAIRED_BRACKET = "WARNING: A Key-Value split with length = 1 is found. This can be caused by a " \
"mathematical formula, which is okay and hence no KEY_VALUE pair is written to the " \
"metadata. Otherwise please check this pair: {0}."
MISSING_MML2OMML = "WARNING: Formula is found on the experiment entry. Parsing this formula to docx file " \
"requires MML2OMML.XSL file from Microsoft Office to be put on the same directory as " \
"config.json file. It is currently downloadable from " \
"https://www.exefiles.com/en/xsl/mml2omml-xsl/, Otherwise, formula parsing is disabled."
NON_TWO_COLUMNS_LINKED_TABLE = "WARNING: The linked category '{0}' has a table that with {1} column instead of " \
"2. This linked item is skipped. Please recheck and consider using two columns to " \
"allow key-value format."
NO_HTML_LINE_CONTENT = "WARNING: No HTML line content is found. This can be caused by an empty paragraph. "
class RegexPatterns(Enum):
EXPLICIT_KEY = r':.+?:' # catch explicit key which indicated within ":" sign
SURROUNDED_WITH_COLONS = r'^:.+?:$' # catch explicit key which indicated within ":" sign
KEY_VALUE_OR_FLOW = r'\{.+?\}|<.+?>' # find any occurrences of either KEY_VALUE or control flow
KEY_VALUE = r'\{.+?\}' # find any occurrences of KEY_VALUE
FLOW = r'<.+?>' # find any occurrences of control flows
DOI = r"\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\'<>])\S)+)\b" # catch DOI
COMMENT = r"\(.+?\)" # define regex for parsing comment
FORMULA = r"\$.*\$" # define regex for parsing formula
COMMENT_W_CAPTURE_GROUP = r"(\(.+?\)*.*\))"
COMMENT_VISIBLE = r"\(:(.+?):\)"
# COMMENT_VISIBLE = "\(:.+?:\)"
COMMENT_INVISIBLE = r"\(_.+?_\)"
# catch the end part of KEY_VALUE pairs (the key, tolerating trailing spaces)
SEPARATOR_AND_KEY = r"\|(\s*\w\s*\.*)+\}"
BRACKET_MARKUPS = r"([{}<>])" # catch KEY_VALUE/section bracket annotations
SEPARATOR_COLON_MARKUP = r"([|:])" # catch separator and colon annotation
SEPARATOR_MARKUP = r"([|])" # catch separator annotation
PRE_PERIOD_SPACES = r'\s+\.'
PRE_COMMA_SPACES = r'\s+,'
SUBSECTION = '(sub)*section'
SUBSECTION_W_EXTRAS = r'(sub)*section.+'
# SPAN_ATTR_VAL = r"(\w+-?\w+):(#?\w+?);"
SPAN_ATTR_VAL = r"(\w+-?\w+):(#?\w+?.?\w+?);" # catch span attribute value pairs
class ArgNum(Enum):
ARG_NUM_FOREACH = 2
ARG_NUM_IF = 4
ARG_NUM_ELSEIF = 4
ARG_NUM_ELSE = 1
ARG_NUM_WHILE = 4
ARG_NUM_ITERATE = 3
ARG_NUM_FOR = 5
ARG_NUM_KV = 2
ARG_NUM_COMMENT = 1
ARG_NUM_SECTION = 2
# -------------------------------------------- API Access-related Class -----------------------------------------------
class ApiAccess:
@classmethod
def get_resource_item(cls, api_v2_client: elabapi_python.api_client, resource_id: int) -> tuple[
elabapi_python.Item, str]:
"""
Get an item from eLabFTW using the resource item ID and API v2 client.
:param api_v2_client: The API v2 client.
:param resource_id: The item ID.
:return: The item (resource) content.
"""
log = ""
api_item_response = None
api_instance = elabapi_python.ItemsApi(api_v2_client)
print("------------------------------")
print(f"Accessing resource item with ID: {resource_id}")
try:
api_item_response = api_instance.get_item(resource_id, format='json')
except ApiException as e:
reason, code, message, description = cls.parse_api_exception(e)
log = MiscAlertMsg.INACCESSIBLE_RESOURCE.value.format(resource_id, reason, code, message, description)
print(log)
return api_item_response, log
@classmethod
def parse_api_exception(cls, e: ApiException) -> Tuple[str, str, str, str]:
"""
Parse an ApiException and return the error details.
"""
reason = e.reason
details = e.body.decode('utf-8') # Decode byte string to string
details_json = json.loads(details) # Parse string to JSON
code = details_json['code'] # Access the code
message = details_json['message'] # Access the message
description = details_json['description'] # Access the description
return reason, code, message, description
@classmethod
def get_attachment_long_name(cls, img_path: str) -> str:
"""
Get an uploads long name from the img path.
:param img_path: The path of the image.
:type img_path: str
:return: The long name of the upload.
:rtype: str
This method splits the image path by the separators '&' and '='.
It then returns the second element of the split path, which corresponds
to the randomly assigned long name used to access via the URI.
"""
split_path = GeneralHelper.split_by_separators(img_path, ('&', '='))
return split_path[1] # strip first 19 chars to get the long_name field in the upload dictionary
@classmethod
def get_exp_title(cls, api_v2_client, exp_item_no: int) -> str:
"""
Get the title of an experiment from eLabFTW using api_v2_client object the experiment item number.
:param api_v2_client: eLabFTW API v2 client object
:param int exp_item_no: eLabFTW experiment item number
:return: Experiment title as a string
"""
exp = cls.get_exp(api_v2_client, exp_item_no)
if exp is None:
raise ValueError("Failed to retrieve experiment entry.")
exp_title = exp.__dict__["_title"]
return exp_title
@classmethod
def get_exp_info(cls, experiment: dict) -> List[List[str]]:
"""
Get experiment information and return it as a list of lists.
:param experiment: An eLabFTW APIs Experiment object containing experiment information.
:return: A list of lists containing experiment information in the form of par.no-key-value-measure-units.
"""
metadata_pairs = [["", "metadata section", "Experiment Info", "", ""],
["", "title", experiment.__dict__["_title"], "", ""],
["", "creation date", experiment.__dict__["_created_at"], "", ""],
["", "category", experiment.__dict__["_type"], "", ""],
["", "author", experiment.__dict__["_fullname"], "", ""],
["", "tags", experiment.__dict__["_tags"], "", ""]]
return metadata_pairs
@classmethod
def get_exp(cls, api_v2_client: elabapi_python.ApiClient, experiment_id: int) -> elabapi_python.Experiment:
"""
Get an eLab experiment using the provided API client and experiment ID.
:param elabapi_python.ApiClient api_v2_client: The eLab API client instance.
:param int experiment_id: The ID of the experiment to retrieve.
:return: elabapi_python.Experiment exp_response: The retrieved eLab experiment.
This method uses the provided eLab API client to fetch an experiment with the given ID.
If an ApiException occurs, it prints the exception message and continues.
"""
exp_response = None
api_instance = elabapi_python.ExperimentsApi(api_v2_client)
print("------------------------------")
print("Accessing experiment with ID: " + str(experiment_id))
try:
exp_response = api_instance.get_experiment(experiment_id, format='json')
except ApiException as e:
reason, code, message, description = cls.parse_api_exception(e)
log = MiscAlertMsg.INACCESSIBLE_EXPERIMENT.value.format(experiment_id, reason, code,
message, description)
print(log)
return exp_response
@classmethod
def get_attachment_ids(cls, exp: Dict, content: Tag) -> tuple[list[dict[str, str | Any]], str]:
# def get_attachment_ids(cls, exp: Dict, content: Tag) -> tuple[list[dict[str, str, str]], str]:
"""
Get upload experiment_id from given experiment and content.
:param dict exp: a dictionary containing details of an experiment (html body, status, rating, next step, etc.).
:param bs4.element.Tag content: a bs4 Tag object containing <h1>/<p><img alt=... src=...> Tag that provides the
link to a particular image file.
:return: dictionary with keys 'upl_id', 'real_name', and 'hash'
WHERE
str upl_id: upload experiment_id of the image attachment, used to access the image through API,
str real_name: the name of the file when it was uploaded to eLabFTW.
str hash: the hash of the file when it was uploaded to eLabFTW.
"""
log = ""
images = content.find_all('img')
uploads = exp.__dict__['_uploads']
results = []
if len(uploads) > 0:
try:
for image in images:
upl_long_name = cls.get_attachment_long_name(image['src'])
result = {'upl_id': "", 'real_name': "", 'hash': "",
"image_path": image['src'], "upl_long_name": upl_long_name}
matched_upl = next(upload for upload in uploads if upload.__dict__['_long_name'] == upl_long_name)
result['upl_id'] = matched_upl.__dict__['_id']
result['real_name'] = matched_upl.__dict__['_real_name']
result['hash'] = matched_upl.__dict__['_hash']
results.append(result)
except Exception as e:
log = MiscAlertMsg.INACCESSIBLE_ATTACHMENT.value.format("NULL", str(e))
print(log)
print("Attachment download is skipped...")
# The dictionary 'result' already has default values set, so no need to set them again here
return results, log
@classmethod
def get_api_v2_endpoint(cls, api_v1_endpoint: str) -> str:
"""
Convert a version 1 API endpoint to a version 2 API endpoint.
:param str api_v1_endpoint: version 1 API endpoint.
:return: str v2endpoint: version 2 API endpoint.
"""
v2_endpoint = re.sub(r'http://', 'https://', api_v1_endpoint)
v2_endpoint = re.sub(r'/v1', '/v2', v2_endpoint)
return v2_endpoint
@classmethod
def create_api_v2_client(cls, api_endpoint: str, token: str) -> elabapi_python.ApiClient:
"""
Create an API v2 client with the given endpoint and token.
:param api_endpoint: The API endpoint.
:param token: The API token.
:return: The API v2 client.
:rtype: elabapi_python.ApiClient.
"""
endpoint_v2 = cls.get_api_v2_endpoint(api_endpoint)
api_v2_config = elabapi_python.Configuration()
api_v2_config.api_key['api_key'] = token
api_v2_config.api_key_prefix['api_key'] = 'Authorization'
api_v2_config.host = endpoint_v2
api_v2_config.debug = False
api_v2_config.verify_ssl = False
api_v2_client = elabapi_python.ApiClient(api_v2_config)
api_v2_client.set_default_header(header_name='Authorization', header_value=token)
return api_v2_client
@classmethod
def get_save_attachments(cls, path: str, api_v2_client: elabapi_python.ApiClient, exp_id: int) -> str:
"""
Get a list of attachments in the experiment entry and download these attachments, and return the logs as string.
:param str path: the path for downloading the attached files, typically named based on experiment title or ID.
:param elabapi_python.ApiClient api_v2_client: The API v2 client object.
:param int exp_id: The experiment ID.
:return log: The log as a string.
"""
log = ""
experiments_api = elabapi_python.ExperimentsApi(api_v2_client)
uploads_api = elabapi_python.UploadsApi(api_v2_client)
exp = experiments_api.get_experiment(int(exp_id))
if platform.system() == "Windows":
upload_saving_path = path + '\\' + 'attachments'
else:
upload_saving_path = path + '/' + 'attachments'
sanitized_upload_saving_path = sanitize_filepath(upload_saving_path, platform='auto')
PathHelper.check_and_create_path(sanitized_upload_saving_path)
# print("LIST OF EXPERIMENT ATTACHMENTS: ")
# pprint(uploads_api.read_uploads('experiments', exp.id))
for upload in uploads_api.read_uploads('experiments', exp.id):
try:
if platform.system() == "Windows":
upload_path = sanitized_upload_saving_path + "\\" + upload.hash + "_" + upload.real_name
else: # on Unix-based OS
upload_path = sanitized_upload_saving_path + "/" + upload.hash + "_" + upload.real_name
with open(upload_path, 'wb') as file:
print("Attachment found: ID: {0}, with name {1}. Writing to {2}.".format(str(upload.id),
upload.real_name, upload_path))
file.write(uploads_api.read_upload('experiments', exp.id, upload.id, format='binary',
_preload_content=False).data)
file.flush()
except FileNotFoundError as e:
print("ERROR: Attachment not found or not accessible: {0}".format(e))
log = log + "Attachment not found or not accessible: {0}".format(e)
return log
# ------------------------------------------------ GUI Helper Class ---------------------------------------------------
class GUIHelper:
@Gooey(optional_cols=0, program_name="LISTER: Life Science Experiment Metadata Parser", default_size=(753, 753),
navigation="TABBED")
def parse_gooey_args(self) -> Namespace:
"""
Get arguments from an existing JSON config to be passed to python Gooey library interface.
Manual debugging (i.e., printout) is necessary when Gooey is used.
:returns: args WHERE argparse.Namespace args is an object containing several attributes:
- str command (e.g., eLabFTW),
- str output_file_name,
- int exp_no,
- str endpoint,
- str base_output_dir,
- str token,
- bool uploadToggle.
"""
token, endpoint, output_file_name, experiment_no, resource_item_no = self.parse_cfg()
settings_msg = ('Please ensure to enter the fields below properly, or ask your eLabFTW admin if you '
'have questions.')
parser = GooeyParser(description=settings_msg)
subs = parser.add_subparsers(help='commands', dest='command')
base_output_path = PathHelper.get_default_output_path(output_file_name)
# ELABFTW EXPERIMENT PARAMETERS
elab_arg_parser = subs.add_parser('parse_experiment', prog="Parse Experiment",
help='Parse metadata from an eLabFTW experiment entry')
io_args = elab_arg_parser.add_argument_group("Input/Output Arguments", gooey_options={'columns': 1})
radio_group = io_args.add_mutually_exclusive_group(required=True,
gooey_options={'title': "Naming method for the outputs",
'initial_selection': 0})
radio_group.add_argument("-t", "--title", metavar="Title", action="store_true",
help='Name files and folders based on experiment title')
radio_group.add_argument("-i", "--experiment_id", metavar="ID", action="store_true",
help='Name files and folders based on the experiment ID')
io_args.add_argument('base_output_dir', metavar='Base output directory',
help='Local directory generally used to save your outputs', type=str,
default=base_output_path, widget='DirChooser')
elabftw_args = elab_arg_parser.add_argument_group("eLabFTW Arguments", gooey_options={'columns': 2})
elabftw_args.add_argument('exp_no', metavar='eLabFTW experiment ID',
help='Integer indicated in the URL of the experiment',
default=experiment_no, type=int)
elabftw_args.add_argument('endpoint', metavar="eLabFTW API endpoint URL",
help='Ask your eLabFTW admin to provide the endpoint URL for you', default=endpoint,
type=str)
elabftw_args.add_argument('token', metavar='eLabFTW API Token',
help='Ask your eLabFTW admin to generate an API token for you', default=token,
type=str)
# ELABFTW resource PARAMETERS
elab_arg_parser = subs.add_parser('parse_resource', prog="Parse Container",
help='Parse metadata from an eLabFTW resource/container items')
io_args = elab_arg_parser.add_argument_group("Input/Output Arguments", gooey_options={'columns': 1})
radio_group = io_args.add_mutually_exclusive_group(required=True,
gooey_options={'title': "Naming method for the outputs",
'initial_selection': 0})
radio_group.add_argument("-t", "--title", metavar="Title", action="store_true",
help='Name files and folders based on container type + title, including the '
'underlying experiments')
radio_group.add_argument("-i", "--experiment_id", metavar="ID", action="store_true",
help='Name files and folders based on container type + ID, including the '
'underlying experiments')
io_args.add_argument('base_output_dir', metavar='Base output directory',
help='Local directory generally used to save your outputs', type=str,
default=base_output_path, widget='DirChooser')
elabftw_args = elab_arg_parser.add_argument_group("eLabFTW Arguments", gooey_options={'columns': 2})
elabftw_args.add_argument('resource_item_no', metavar='eLabFTW Resource/Container Item ID',
help='Integer indicated in the URL of the resource/container item',
default=resource_item_no, type=int)
elabftw_args.add_argument('endpoint', metavar="eLabFTW API endpoint URL",
help='Ask your eLabFTW admin to provide the endpoint URL for you', default=endpoint,
type=str)
elabftw_args.add_argument('token', metavar='eLabFTW API Token',
help='Ask your eLabFTW admin to generate an API token for you', default=token,
type=str)
args = parser.parse_args()
return args
@classmethod
def parse_cfg(cls) -> Tuple[str, str, str, int, int]:
"""
Parse JSON config file, requires existing config.json file which should be specified on certain directory.
The directory is OS-dependent. On Windows/Linux, it is in the same folder as the script/executables.
On macOS, it is in the users' Apps/lister/config.json file.
:returns: tuple (token, endpoint, output_file_name, experiment_id)
str token: eLabFTW API Token,
str endpoint: eLabFTW API endpoint URL,
str output_file_name: filename to be used for all the outputs (xlsx/json metadata, docx documentation,
log file),
int experiment_id: the parsed experiment ID (int).
int resource_item_no: the parsed resource/container item ID (int).
"""
input_file = PathHelper.manage_input_path() + "config.json"
print("CONFIG FILE: %s" % input_file)
# using ...with open... allows file to be closed automatically.
with open(input_file, encoding="utf-8") as json_data_file:
data = json.load(json_data_file)
token = data['elabftw']['token']
endpoint = data['elabftw']['endpoint']
experiment_id = data['elabftw']['exp_no']
output_file_name = data['elabftw']['output_file_name']
resource_item_no = data['elabftw']['resource_item_no']
return token, endpoint, output_file_name, experiment_id, resource_item_no
# -------------------------------------------- File serialization Class ------------------------------------------------
class Serializer:
@classmethod
def write_to_docx(cls, exp: dict, path: str) -> str:
"""
fetch an experiment, clean the content from LISTER annotation markup and serialize the result to a docx file.
:param dict exp: dictionary containing the properties of the experiment, including its HTML body content.
:param str path: the path for writing the docx file, typically named based on experiment title or ID.
:return: str log: log of the process.
"""
document = Document()
all_references = []
log = ""
tagged_contents = TextCleaner.get_nonempty_body_tags(exp)
watched_tags = ['div', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'span', 'strong', 'sub', 'em', 'sup']
for content in tagged_contents: # iterate over a list of tags
if isinstance(content, Tag):
if content.name == "div":
print("A div tag is found, unwrapping...")
# print("The content is a div, unwrapping...")
content.unwrap()
if len(content.select("img")) > 0:
# upl_id, real_name, hash = ApiAccess.get_attachment_ids(experiment, content)
image_ids, log = ApiAccess.get_attachment_ids(exp, content)
for image_id in image_ids:
# print(str(image_id['real_name']), path)
DocxHelper.add_img_to_doc(document, image_id['real_name'], path, image_id['hash'])
elif any(x in content.name for x in watched_tags):
references, log = DocxHelper.write_tag_to_doc(document, content)
if len(references) > 0:
all_references.extend(references)
if content.name == "table":
print("A table is found, writing to docx...")
DocxHelper.add_table_to_doc(document, content)
if content.name == "img":
image_ids, log = ApiAccess.get_attachment_ids(exp, content)
for image_id in image_ids:
# print(str(image_id['real_name']), path)
DocxHelper.add_img_to_doc(document, image_id['real_name'], path, image_id['hash'])
if len(all_references) > 0:
document.add_heading("Reference", level=1)
for reference in all_references:
document.add_paragraph(reference, style='List Number')
try:
if platform.system() == "Windows":
docx_path = path + "\\" + PathHelper.derive_filename_from_experiment(exp) + '.docx'
docx_path = sanitize_filepath(docx_path, platform="auto")
else:
docx_path = path + '/' + PathHelper.derive_filename_from_experiment(exp) + '.docx'
document.save(docx_path)
except FileNotFoundError as e:
print("ERROR: DOCX file cannot be written: {0}".format(e))
log = log + "ERROR: DOCX file cannot be written: {0}".format(e)
return log
# Used to serialize extracted metadata to json file.
@classmethod
def write_to_json(cls, lst: List, exp: dict, path: str) -> None:
"""
Write a list to a JSON file.
:param lst: The list to write to the JSON file.
:param exp: The experiment title or ID.
:param path: The path for writing the JSON file.
"""
filename = f"{PathHelper.derive_filename_from_experiment(exp)}.json"
try:
if platform.system() == "Windows":
json_path = path + "\\" + filename
json_path = sanitize_filepath(json_path, platform="auto")
else:
json_path = path + '/' + filename
with open(json_path, "w", encoding="utf-8") as f:
json.dump(lst, f, ensure_ascii=False)
except FileNotFoundError as e:
print("ERROR: JSON file cannot be written: {0}".format(e))
# Used to write into the log file.
# def write_log(log, full_path=output_path_and_filename):
@classmethod
def write_log(cls, log_text: str, path: str) -> None:
"""
Write the log to a file.
:param log_text: The log to be written to the file.
:param path: The path for writing the log file.
"""
log_text = log_text.strip()
PathHelper.check_and_create_path(path)
try:
if platform.system() == "Windows":
log_path = path + "\\" + 'lister-report.log'
log_path = sanitize_filepath(log_path, platform="auto")
else:
log_path = path + '/' + 'lister-report.log'
with open(log_path, "w", encoding="utf-8") as f:
f.write(log_text)
except FileNotFoundError as e:
print("ERROR: LOG file cannot be written: {0}".format(e))
@classmethod
def write_to_xlsx(cls, metadata_set: List, exp: dict, path: str) -> None:
"""
Write extracted order/key/value/measure/unit to an Excel file.
:param list metadata_set: list containing the order (paragraph number)/key/value/measure/unit to be written.
:param dict exp: an experiment object.
:param str path: the path for writing the xlsx file, typically named based on experiment title or ID.
"""
PathHelper.check_and_create_path(path)
header = ["PARAGRAPH NUMBER", "KEY", "VALUE", "MEASURE", "UNIT"]
# json.dump(list, open(path + '/' + derive_filename_from_exp(experiment) + ".json", 'w', encoding="utf-8"),
# ensure_ascii=False)
try:
if platform.system() == "Windows":
xlsx_path = path + "\\" + PathHelper.derive_filename_from_experiment(exp) + ".xlsx"
xlsx_path = sanitize_filepath(xlsx_path, platform="auto")
else:
xlsx_path = path + '/' + PathHelper.derive_filename_from_experiment(exp) + ".xlsx"
with xlsxwriter.Workbook(xlsx_path) as workbook:
# formatting cells
header_format = workbook.add_format({'bold': True, 'bg_color': '9bbb59', 'font_color': 'ffffff'})
default_format = workbook.add_format({'border': 1, 'border_color': '9bbb59'})
section_format = workbook.add_format({'border': 1, 'border_color': '9bbb59', 'bg_color': 'ebf1de'})
# creating and formatting worksheet
worksheet = workbook.add_worksheet()
worksheet.write_row(0, 0, header, header_format)
worksheet.set_column('A:A', 19)
worksheet.set_column('B:B', 18)
worksheet.set_column('C:C', 30)
worksheet.set_column('D:E', 15)
for row_no, data in enumerate(metadata_set):
key = data[1]
# do not use regex here, or it will be very slow
# if re.match(RegexPatterns.SUBSECTION.value, data[1].lower()):
if len(key) >= 7 and key[0:7].casefold() == "section".casefold() or key.casefold() == ("metadata "
"section"):
worksheet.write_row(row_no + 1, 0, data, section_format)
else:
try:
worksheet.write_row(row_no + 1, 0, data, default_format)
except xlsxwriter.exceptions.FileCreateError as e:
print(e)
# print("ERROR: Excel file cannot be written: {0}".format(e))
except xlsxwriter.exceptions.FileCreateError as e:
print(e)
# ---------------------------------------------- Metadata Extraction Class --------------------------------------------
class MetadataExtractor:
@classmethod
def is_explicit_key(cls, key: str) -> bool:
"""
Check whether the string is an explicit key.
:param str key: checked string.
:return: bool stating whether the key is a LISTER explicit key.
"""
if re.match(RegexPatterns.EXPLICIT_KEY.value, key):
return True
else:
return False
@classmethod
def extract_flow_type(cls, paragraph_no: int, flow_control_pair: str) -> Tuple[List[List], str, bool]:
"""
Extracts the type of flow found on any annotation with angle brackets, which can be control flow or sectioning.
:param int paragraph_no: paragraph number on where the control flow fragment string was found.
:param str flow_control_pair: the control-flow pair string to be extracted for metadata.
:returns: tuple (key_value, flow_log, is_error)
WHERE
list key_value: list of list, each list contains a full complete control flow metadata line
e.g. [['-', 'section level 0', 'Precultures', '', '']],
str flow_log: log resulted from running this and subsequent functions,
bool is_error: flag that indicates whether an error occurred.
"""
flow_log = ""
# print("flow_control_pair: " + str(flow_control_pair))
key_value = []
cf = flow_control_pair[1:-1]
control_flow_split = re.split(r"\|", cf)
flow_type = control_flow_split[0]
flow_type = flow_type.strip()
flow_type = flow_type.lower()
if flow_type == "for each":
key_value, log, is_error = cls.process_foreach(paragraph_no, control_flow_split)
if log != "":
flow_log = flow_log + "\n" + log
elif flow_type == "while":
key_value, log, is_error = cls.process_while(paragraph_no, control_flow_split)
if log != "":
flow_log = flow_log + "\n" + log
elif flow_type == "if":
key_value, log, is_error = cls.process_if(paragraph_no, control_flow_split)
if log != "":
flow_log = flow_log + "\n" + log
elif flow_type == "else if" or flow_type == "elif":
key_value, log, is_error = cls.process_elseif(paragraph_no, control_flow_split)
if log != "":
flow_log = flow_log + "\n" + log
elif flow_type == "else":
key_value, log, is_error = cls.process_else(paragraph_no, control_flow_split)
if log != "":
flow_log = flow_log + "\n" + log
elif flow_type == "for":
key_value, log, is_error = cls.process_for(paragraph_no, control_flow_split)
if log != "":
flow_log = flow_log + "\n" + log
# elif flow_type.casefold() == "section".casefold():
elif re.match(RegexPatterns.SUBSECTION.value, flow_type, flags=re.IGNORECASE):
key_value, log, is_error = cls.process_section(control_flow_split)
if log != "":
flow_log = flow_log + "\n" + log
elif flow_type == "iterate":
key_value, log, is_error = cls.process_iterate(paragraph_no, control_flow_split)
if log != "":
flow_log = flow_log + "\n" + log
else:
is_error = True
log = MiscAlertMsg.UNRECOGNIZED_FLOW_TYPE.value.format(control_flow_split[0].upper(),
control_flow_split) # + "\n"
print(log)
flow_log = flow_log + "\n" + log
# print(flow_log)
# print("key_value: " + str(key_value) + "\n\n")
return key_value, flow_log, is_error
@classmethod
def process_section(cls, control_flow_split: List[str]) -> Tuple[List[List], str, bool]:
"""
Convert key value based on a section to a full section metadata entry
:param list control_flow_split: list of strings split e.g., ['Section', 'Remarks']
:returns: tuple (key_value, log, is_error)
WHERE
list key_value: list of list, each list contains a full section-metadata line
e.g. [['-', 'section level 0', 'Precultures', '', '']],
str log: log resulted from running this and subsequent functions,
bool is_error: flag that indicates whether an error occurred.
"""
key_value = []
section_log = ""
is_error = False
log, is_sect_error = Validator.validate_section(control_flow_split)
if is_sect_error:
is_error = True
section_log = section_log + "\n" + log
else:
section_keyword = control_flow_split[0].lower()
section_level = section_keyword.count("sub")
key_value.append(
["-", CFMetadata.FLOW_SECTION.value + " level " + str(section_level), control_flow_split[1], '', ''])
return key_value, section_log, is_error
@classmethod
def process_ref_resource_item(cls, api_v2_client: elabapi_python.ApiClient, item_api_response) -> None:
"""
Process reference resource item, using the initial resource ID for that container item (e.g., publication).
:param api_v2_client: An instance of the API v2 client object, containing eLabFTW API-related information.
:param item_api_response: The API response of the reference resource item.
:return: None
"""
# TODO: also get the list of related experiments instead of linked experiments only,
# status: pending. see https://github.com/elabftw/elabftw/issues/4811
try:
experiments = item_api_response.__dict__["_experiments_links"]
for experiment in experiments:
exp_path = output_path + PathHelper.slugify(experiment.__dict__["_title"])
cls.process_experiment(api_v2_client, experiment.__dict__["_entityid"], exp_path)
except ApiException as e:
print("Exception when calling ItemsApi->getItem: %s\n" % e)
@classmethod
def process_linked_resource_item_api_v2(cls, api_v2_client: elabapi_python.ApiClient, resource_id: int) -> \
Tuple[Union[List[List[str]], str], str]:
"""
Process a linked resource item and return its metadata and log.
:param elabapi_python.ApiClient api_v2_client: An instance of the API v2 client object, containing eLabFTW
API-related information.
:param resource_id: The ID of the linked resource item.
:return: A tuple containing the resource item metadata and log.
"""
api_instance = elabapi_python.ItemsApi(api_v2_client)
try:
# Read an item
linked_item = api_instance.get_item(resource_id)
html_body = getattr(linked_item, 'body')
# category = getattr(linked_item, 'mainattr_title') # only works for elabapi-python 0.4.1.
category = getattr(linked_item, 'category_title')
dfs = pd.read_html(StringIO(html_body))
df = pd.concat(dfs)
df_col_no = df.shape[1]
log = ""
if df_col_no != 2:
log = MiscAlertMsg.NON_TWO_COLUMNS_LINKED_TABLE.value.format(category, df_col_no) + "\n"
print(log)
resource_item_metadata_set = None
else:
df.columns = ["metadata section", category]
df.insert(loc=0, column="", value="")
df = df.reindex(df.columns.tolist() + ['', ''], axis=1) # add two empty columns
filtered_df = df.fillna('') # fill empty cells with empty string
resource_item_metadata_set = [filtered_df.columns.values.tolist()] + filtered_df.values.tolist()
except ApiException as e:
resource_item_metadata_set = ""
log = "Exception when calling ItemsApi->getItem: %s\n" % e
print(log)
return resource_item_metadata_set, log
@classmethod
def process_experiment(cls, api_v2_client: elabapi_python.ApiClient, exp_id: int, path: str) -> None:
"""
Process an experiment and save its information to various formats.
:param elabapi_python.ApiClient api_v2_client: The API v2 client.
:param int exp_id: The experiment number.
:param str path: The path for saving the output files.
"""
overall_log = ""
experiment_instance = elabapi_python.ExperimentsApi(api_v2_client)
print("------------------------------")
print("Accessing experiment with ID: " + str(exp_id))
try:
experiment_response = experiment_instance.get_experiment(exp_id)
linked_resources = experiment_response.__dict__['_items_links']
linked_entityids = [linked_resource.__dict__["_entityid"] for linked_resource in linked_resources]
# get the respective category of the linked resources
id_and_category = {}
excluded_item_types = ["MM", "Publication", "Protocols", "Protocol", "Methods", "Method", "Recipe"]
# this will only work with elabapi-python 0.4.1.
# unfortunately, the response from the API is not consistent between versions, so it may be a good idea to
# fix the version of elabapi-python to a specific version in the requirements.txt in the future.
# for linked_resource in linked_resources:
# id_and_category[linked_resource.__dict__["_itemid"]] = linked_resource.__dict__["_mainattr_title"]
for linked_entytyid in linked_entityids:
try:
# get the linked resource item by ID
linked_resource, resource_log = ApiAccess.get_resource_item(api_v2_client, linked_entytyid)
overall_log = overall_log + "\n" + resource_log
if linked_resource is not None:
id_and_category[linked_resource.__dict__["_id"]] = linked_resource.__dict__["_category_title"]
# pprint(id_and_category)
except ApiException as e:
reason, code, message, description = ApiAccess.parse_api_exception(e)
item_log = MiscAlertMsg.INACCESSIBLE_RESOURCE.value.format(id, reason, code, message, description)
print(item_log)
Serializer.write_log(item_log, path)
filtered_id_and_category = {key: value for key, value in id_and_category.items() if value.lower() not in
[item.lower() for item in excluded_item_types]}
# pprint(filtered_id_and_category)
overall_metadata_set = []
# the 'key' here is the ID of the resource item.
for key in filtered_id_and_category:
resource_item_metadata_set, log = MetadataExtractor.process_linked_resource_item_api_v2(api_v2_client,
key)
overall_log = overall_log + "\n" + log
overall_metadata_set.extend(resource_item_metadata_set)
experiment_metadata_info = ApiAccess.get_exp_info(experiment_response)
overall_metadata_set.extend(experiment_metadata_info)
experiment_metadata_set, log = (MetadataExtractor.conv_html_to_metadata
(experiment_response.__dict__["_body"]))
overall_log = overall_log + "\n" + log
overall_metadata_set.extend(experiment_metadata_set)
log = ApiAccess.get_save_attachments(path, api_v2_client, int(exp_id))
overall_log = overall_log + "\n" + log
docx_log = Serializer.write_to_docx(experiment_response, path)
overall_log = overall_log + "\n" + docx_log
Serializer.write_to_json(overall_metadata_set, experiment_response, path)
Serializer.write_to_xlsx(overall_metadata_set, experiment_response, path)
Serializer.write_log(overall_log, path)
except ApiException as e:
reason, code, message, description = ApiAccess.parse_api_exception(e)
exp_log = MiscAlertMsg.INACCESSIBLE_EXPERIMENT.value.format(id, reason, code, message, description)
print(exp_log)
Serializer.write_log(exp_log, path)
# only process the comment within (key value measure unit) pairs and remove its content
# (unless if it is begun with "!")
@classmethod
def process_internal_comment(cls, string_with_brackets: str) -> Tuple[str, str]:
"""
Separates actual part of a lister bracket annotation fragment (key/value/measure/unit) with the
trailing comments.
Internal comment refers to any comment that is available within a fragment of a lister bracket annotation.
Internal comment will not be bypassed to the metadata output.
However, internal comment is important to be provided to make the experiment clear-text readable in the
docx output.
:param str string_with_brackets: a lister bracket annotation fragment with a comment.
:returns: tuple (actual_fragment, internal_comment)
WHERE
str actual_fragment: string containing the actual element of metadata, it can be either
key/value/measure/unit,
str internal_comment: string containing the comment part of the string fragment, with brackets retained.
"""
comment = re.search(RegexPatterns.COMMENT.value, string_with_brackets)
comment = comment.group(0)
remains = string_with_brackets.replace(comment, '')
actual_fragment, internal_comment = remains.strip(), comment.strip()
return actual_fragment, internal_comment
@classmethod
def process_foreach(cls, paragraph_no: int, control_flow_split: List[str]) -> Tuple[List[List], str, bool]:
"""
Converts key-value based on foreach control-metadata entry.
:param int paragraph_no: paragraph number where string fragment containing the referred pair was found.
:param list control_flow_split: list of split string.
:returns: tuple (key_value, log, is_error)
WHERE
list key_value: list of list, each list contains a full control-flow metadata,
str log: log resulted from running this and subsequent functions,
bool is_error: flag that indicates whether an error occurred.
"""
key_value = []
log, is_error = Validator.validate_foreach(control_flow_split)
if is_error:
print(log)
step_type = "iteration"
key_value.append([paragraph_no, CFMetadata.STEP_TYPE.value, step_type, '', ''])
flow_type = control_flow_split[0]
key_value.append([paragraph_no, CFMetadata.FLOW_TYPE.value, flow_type, '', ''])
flow_param = control_flow_split[1]
key_value.append([paragraph_no, CFMetadata.FLOW_PARAMETER.value, flow_param, '', ''])
return key_value, log, is_error
@classmethod
def process_while(cls, paragraph_no: int, control_flow_split: List[str]) -> Tuple[List[List], str, bool]:
"""
Convert key value based on while control-metadata entry.
:param int paragraph_no: paragraph number where string fragment containing the referred pair was found.
:param list control_flow_split: list of split string.
:returns: tuple (key_value, log, is_error)
WHERE
list key_value: list of list, each list contains a full control-flow metadata,
str log: log resulted from running this and subsequent functions,
bool is_error: flag that indicates whether an error occurred.
"""
key_value = []
log, is_error = Validator.validate_while(control_flow_split)
if is_error:
print(log)
try:
step_type = "iteration"
key_value.append([paragraph_no, CFMetadata.STEP_TYPE.value, step_type, '', ''])
flow_type = control_flow_split[0]
key_value.append([paragraph_no, CFMetadata.FLOW_TYPE.value, flow_type, '', ''])
flow_param = control_flow_split[1]
key_value.append([paragraph_no, CFMetadata.FLOW_PARAMETER.value, flow_param, '', ''])
flow_logical_operator = control_flow_split[2]
key_value.append([paragraph_no, CFMetadata.FLOW_LOGICAL_OPERATOR.value, flow_logical_operator, '', ''])
flow_compared_value = control_flow_split[3]
key_value.append([paragraph_no, CFMetadata.FLOW_COMPARED_VALUE.value, flow_compared_value, '', ''])
except IndexError as e:
is_error = True
print(f"Iteration error occurred: {e}")
return key_value, log, is_error
@classmethod
def process_if(cls, paragraph_no: int, control_flow_split: List[str]) -> Tuple[List[List], str, bool]:
"""
Convert key-value based on if control-metadata entry.
:param int paragraph_no: paragraph number where string fragment containing the referred pair was found.
:param list control_flow_split: list of split string.
:returns: tuple (key_value, log, is_error)
WHERE
list key_value: list of list, each list contains a full control-flow metadata,
str log: log resulted from running this and subsequent functions,
bool is_error: flag that indicates whether an error occurred.
"""
key_value = []
log, is_error = Validator.validate_if(control_flow_split)
if is_error:
print(log)
step_type = "conditional"
key_value.append([paragraph_no, CFMetadata.STEP_TYPE.value, step_type, '', ''])
flow_type = control_flow_split[0]
key_value.append([paragraph_no, CFMetadata.FLOW_TYPE.value, flow_type, '', ''])