kernpy 0.0.1__py3-none-any.whl → 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.
Files changed (56) hide show
  1. kernpy/__init__.py +215 -0
  2. kernpy/__main__.py +217 -0
  3. kernpy/core/__init__.py +119 -0
  4. kernpy/core/_io.py +48 -0
  5. kernpy/core/base_antlr_importer.py +61 -0
  6. kernpy/core/base_antlr_spine_parser_listener.py +196 -0
  7. kernpy/core/basic_spine_importer.py +43 -0
  8. kernpy/core/document.py +965 -0
  9. kernpy/core/dyn_importer.py +30 -0
  10. kernpy/core/dynam_spine_importer.py +42 -0
  11. kernpy/core/error_listener.py +51 -0
  12. kernpy/core/exporter.py +535 -0
  13. kernpy/core/fing_spine_importer.py +42 -0
  14. kernpy/core/generated/kernSpineLexer.interp +444 -0
  15. kernpy/core/generated/kernSpineLexer.py +535 -0
  16. kernpy/core/generated/kernSpineLexer.tokens +236 -0
  17. kernpy/core/generated/kernSpineParser.interp +425 -0
  18. kernpy/core/generated/kernSpineParser.py +9954 -0
  19. kernpy/core/generated/kernSpineParser.tokens +236 -0
  20. kernpy/core/generated/kernSpineParserListener.py +1200 -0
  21. kernpy/core/generated/kernSpineParserVisitor.py +673 -0
  22. kernpy/core/generic.py +426 -0
  23. kernpy/core/gkern.py +526 -0
  24. kernpy/core/graphviz_exporter.py +89 -0
  25. kernpy/core/harm_spine_importer.py +41 -0
  26. kernpy/core/import_humdrum_old.py +853 -0
  27. kernpy/core/importer.py +285 -0
  28. kernpy/core/importer_factory.py +43 -0
  29. kernpy/core/kern_spine_importer.py +73 -0
  30. kernpy/core/mens_spine_importer.py +23 -0
  31. kernpy/core/mhxm_spine_importer.py +44 -0
  32. kernpy/core/pitch_models.py +338 -0
  33. kernpy/core/root_spine_importer.py +58 -0
  34. kernpy/core/spine_importer.py +45 -0
  35. kernpy/core/text_spine_importer.py +43 -0
  36. kernpy/core/tokenizers.py +239 -0
  37. kernpy/core/tokens.py +2011 -0
  38. kernpy/core/transposer.py +300 -0
  39. kernpy/io/__init__.py +14 -0
  40. kernpy/io/public.py +355 -0
  41. kernpy/polish_scores/__init__.py +13 -0
  42. kernpy/polish_scores/download_polish_dataset.py +357 -0
  43. kernpy/polish_scores/iiif.py +47 -0
  44. kernpy/test_grammar.sh +22 -0
  45. kernpy/util/__init__.py +14 -0
  46. kernpy/util/helpers.py +55 -0
  47. kernpy/util/store_cache.py +35 -0
  48. kernpy/visualize_analysis.sh +23 -0
  49. kernpy-1.0.0.dist-info/METADATA +501 -0
  50. kernpy-1.0.0.dist-info/RECORD +51 -0
  51. {kernpy-0.0.1.dist-info → kernpy-1.0.0.dist-info}/WHEEL +1 -2
  52. kernpy/example.py +0 -0
  53. kernpy-0.0.1.dist-info/LICENSE +0 -19
  54. kernpy-0.0.1.dist-info/METADATA +0 -19
  55. kernpy-0.0.1.dist-info/RECORD +0 -7
  56. kernpy-0.0.1.dist-info/top_level.txt +0 -1
kernpy/__init__.py CHANGED
@@ -0,0 +1,215 @@
1
+ """
2
+ # kernpy
3
+
4
+ =====
5
+
6
+
7
+ Python Humdrum kern and mens utilities package.
8
+
9
+
10
+
11
+ Execute the following command to run **kernpy** as a module:
12
+ ```shell
13
+ python -m kernpy --help
14
+ python -m kernpy <command> <options>
15
+ ```
16
+
17
+ Run `kernpy` from your script:
18
+ ```python
19
+ import kernpy
20
+
21
+ help(kernpy)
22
+ ```
23
+
24
+ While the package is not published in `pip`, the `kernpy` module must be in the root directory.
25
+
26
+ ## 🎯 **kern2ekern**: Convertir un solo archivo .krn a .ekern:
27
+
28
+ ```bash
29
+ python -m kernpy --kern2ekern --input_path <input_file> <v | --verbose [0-2]>
30
+ ```
31
+
32
+ The command has the following arguments:
33
+ * **input_path**: Ruta del archivo .krn a convertir.
34
+ * **output_path**: Ruta del archivo .ekern a generar (opcional). Si no se especifica, se generará en la misma ubicación.
35
+ * **-r**: Recursivo (opcional).
36
+ * **--verbose[0-2]**: Nivel de verbosidad (opcional).
37
+
38
+
39
+ 📌 Basic usage running **kernpy** as a module:
40
+ ```shell
41
+ python -m kernpy --input_path /my/path/to/file.krn # New ekern generated in /my/path/to/file.ekern
42
+ ```
43
+
44
+ 📌 Generate an _ekrn_ file in specific location running **kernpy** as a module:
45
+ ```shell
46
+ python -m kernpy --input_path /my/path/to/file.krn --output_path /new/output.ekern
47
+ ```
48
+
49
+ 📌 Converting all the .krn files in a directory to .ekern files running **kernpy** as a module:
50
+ * Every .krn file in the directory will be converted to .ekern in the same location.
51
+ * Using, at least, one additional directory level is required.
52
+ ```
53
+ root
54
+ ├─ kern-folder
55
+ │   ├── 1.krn
56
+ │   ├── 2.krn
57
+ │   └── 3.krn
58
+ ├── more-kerns
59
+ │   ├── 1.krn
60
+ │   ├── ...
61
+ ```
62
+ Run:
63
+ ```shell
64
+ python -m kernpy --input_path /my/path/to/directory/ -r
65
+ ```
66
+
67
+ ✏️ This function is also available as a python function:
68
+ ```python
69
+ # converter.py
70
+ from kernpy import kern_to_ekern
71
+
72
+ kern_to_ekern('/my/path/to/input.krn', '/to/my/output.ekrn')
73
+
74
+ # Many files
75
+ files = ['file1.krn', 'file2.krn', 'file3.krn']
76
+ [kern_to_ekern(f) for f in files]
77
+
78
+ # This function raises an exception if the conversion fails.
79
+ # Handle the errors using try-except statement if many files are going to be converted in series.
80
+ ```
81
+
82
+ ****************************************************************************************
83
+ ## 🎯 **ekern2kern**: Convertir un solo archivo .ekern a .krn:
84
+
85
+ ```bash
86
+ python -m kernpy --ekern2kern --input_path <input_file> <--verbose [0-2]>
87
+ ```
88
+
89
+ The command has the following arguments:
90
+ * **input_path**: Ruta del archivo .ekern a convertir.
91
+ * **output_path**: Ruta del archivo .krn a generar (opcional). Si no se especifica, se generará en la misma ubicación.
92
+ * **-r**: Recursivo (opcional).
93
+ * **--verbose[0-2]**: Nivel de verbosidad (opcional).
94
+
95
+ * Basic usage running **kernpy** as a module:
96
+ ```shell
97
+ python -m kernpy --input_path /my/path/to/file.ekern # New krn generated in /my/path/to/file.krn
98
+ ```
99
+
100
+ 📌 Generate a _krn_ file in specific location running **kernpy** as a module:
101
+ ```shell
102
+ python -m kernpy --input_path /my/path/to/file.ekern --output_path /new/output.krn
103
+ ```
104
+
105
+ 📌 Converting **all** the .ekern files in a directory to .krn files running **kernpy** as a module:
106
+
107
+ * Every .ekrn file in the directory will be converted to .krn in the same location.
108
+ * Using, at least, one additional directory level is required.
109
+ ```
110
+ root
111
+ ├─ ekern-folder
112
+ │   ├── 1.ekrn
113
+ │   ├── 2.ekrn
114
+ │   └── 3.ekrn
115
+ ├── more-ekerns
116
+ │   ├── 1.ekrn
117
+ │   ├── ...
118
+ ```
119
+ Run:
120
+ ```shell
121
+ python -m kernpy --input_path /my/path/to/directory/ -r
122
+ ```
123
+
124
+ ✏️ This function is also available as a python function:
125
+ ```python
126
+ # converter.py
127
+ from kernpy import ekern_to_krn
128
+
129
+ # Only one file
130
+ ekern_to_krn('/my/path/to/input.ekrn', '/to/my/output.krn')
131
+
132
+ # Many files
133
+ files = ['file1.ekrn', 'file2.ekrn', 'file3.ekrn']
134
+ [ekern_to_krn(f) for f in files]
135
+
136
+ # This function raises an exception if the conversion fails.
137
+ # Handle the errors using try-except statement if many files are going to be converted in series.
138
+ ```
139
+
140
+
141
+ ****************************************************************************************
142
+ ## 🎯 **create fragments**
143
+ Generate new valid _kern_ files from an original _kern_ file. Every new fragment will be a subset of the original file.
144
+
145
+ Explore the documentation website for more information about the parameters.
146
+
147
+
148
+ Use:
149
+ - **create_fragments_from_kern** to generate using always the same measure length.
150
+ - **create_fragments_from_directory** to generate using a Gaussian distribution for the measure length. Static measure is also available if the standard deviation is set to 0.
151
+
152
+
153
+ 📌 Create new scores from one original _kern_ directory running **kernpy** as a module:
154
+ ```shell
155
+ python -m kernpy --generate_fragments --input_directory /from/my/kerns --output_directory /to/my/fragments --log_file log.csv --verbose 2 --mean 4.2 --std_dev 1.5 --offset 1 --num_processes 12
156
+ ```
157
+
158
+
159
+ ✏️ Create new scores from one original _kern_ file:
160
+ ```python
161
+ # generator.py
162
+ from kernpy import create_fragments_from_kern
163
+
164
+ # View docs:
165
+ help(create_fragments_from_kern)
166
+
167
+ create_fragments_from_kern('/my/path/to/input.krn', '/to/my/output_dir/',
168
+ measure_length=4, offset=1,
169
+ log_file='/dev/null')
170
+ ```
171
+
172
+ ✏️ Create new scores from one original _kern_ directory:
173
+ - Using, at least, one additional directory level is required.
174
+ ```
175
+ root
176
+ ├─ kern-folder
177
+ │   ├── 1.krn
178
+ │   ├── 2.krn
179
+ │   └── 3.krn
180
+ ├── more-kerns
181
+ │   ├── 1.krn
182
+ │   ├── ...
183
+ ```
184
+
185
+ Run:
186
+ ```python
187
+ # generator.py
188
+ from kernpy import create_fragments_from_directory
189
+
190
+ # View docs:
191
+ help(create_fragments_from_directory)
192
+
193
+ create_fragments_from_directory('/my/path/to/input_dir/', '/to/my/output_dir/',
194
+ mean=4.1, std_dev=0.2, offset=2,
195
+ log_file='/logs/fragments.csv',
196
+ num_processes=12)
197
+ ```
198
+
199
+
200
+
201
+ """
202
+
203
+
204
+ from .core import *
205
+
206
+ from .io import *
207
+
208
+ from .util import *
209
+
210
+ from .polish_scores import *
211
+
212
+
213
+
214
+
215
+
kernpy/__main__.py ADDED
@@ -0,0 +1,217 @@
1
+ """
2
+ This module contains the main function for the kernpy package.
3
+
4
+ Use the following command to run `kernpy` as a module:
5
+ ```bash
6
+ python -m kernpy
7
+ ```
8
+
9
+ """
10
+
11
+ import argparse
12
+ import sys
13
+ import os
14
+
15
+ from kernpy import polish_scores, ekern_to_krn, kern_to_ekern, create_fragments_from_directory
16
+
17
+
18
+ def create_parser() -> argparse.ArgumentParser:
19
+ """
20
+ Create a parser for the command line arguments.
21
+
22
+ Examples:
23
+ >>> parser = create_parser()
24
+ >>> args = parser.parse_args()
25
+ >>> print(args.verbose)
26
+
27
+
28
+ Returns:
29
+ argparse.ArgumentParser: The parser object
30
+ """
31
+ parser = argparse.ArgumentParser(description="kernpy")
32
+
33
+ parser.add_argument('--verbose', default=1, help='Enable verbose mode')
34
+
35
+
36
+ # ekern to kern
37
+ kern_parser = parser.add_argument_group('Kern Parser options')
38
+ kern_parser.add_argument('--ekern2kern', action='store_true', help='Convert file from ekern to kern. [-r]')
39
+ kern_parser.add_argument('--kern2ekern', action='store_true', help='Convert file from kern to ekern. [-r]')
40
+
41
+ if '--ekern2kern' in sys.argv:
42
+ kern_parser.add_argument('--input_path', required=True, type=str,
43
+ help='Input file or directory path. Employ -r to use recursive mode')
44
+ kern_parser.add_argument('--output_path', required=False, type=str, help='Output file or directory path')
45
+ kern_parser.add_argument('-r', '--recursive', required=False, action='store_true', help='Recursive mode')
46
+
47
+ if '--kern2ekern' in sys.argv:
48
+ kern_parser.add_argument('--input_path', required=True, type=str,
49
+ help='Input file or directory path. Employ -r to use recursive mode')
50
+ kern_parser.add_argument('--output_path', required=False, type=str, help='Output file or directory path')
51
+ kern_parser.add_argument('-r', '--recursive', required=False, action='store_true', help='Recursive mode')
52
+
53
+ # Polish operations
54
+ # Create a group for optional arguments
55
+ polish_args = parser.add_argument_group('Polish Exporter options')
56
+ polish_args.add_argument('--polish', action='store_true', help='Enable Polish Exporter')
57
+ # Add the required flags, but only if --polish exists
58
+ if '--polish' in sys.argv:
59
+ polish_args.add_argument('--input_directory', required=True, type=str, help='Input directory path')
60
+ polish_args.add_argument('--output_directory', required=True, type=str, help='Output directory path')
61
+ polish_args.add_argument('--instrument', required=False, type=str, help='Instrument name')
62
+ polish_args.add_argument('--kern_type', required=False, type=str, help='Kern type: "krn" or "ekrn"')
63
+ polish_args.add_argument('--kern_spines_filter', required=False, type=str, help='How many kern spines scores will be exported. A number greater than 0', default=None)
64
+ polish_args.add_argument('--remove_empty_dirs', required=False, action='store_true', help='Remove empty directories after exporting the scores', default=True)
65
+
66
+ # Generate fragments
67
+ # Create a group for optional arguments
68
+ generate_fragments = parser.add_argument_group('Generate Fragments options')
69
+ generate_fragments.add_argument('--generate_fragments', action='store_true', help='Enable Generate Fragments')
70
+ if '--generate_fragments' in sys.argv:
71
+ generate_fragments.add_argument('--input_directory', required=True, type=str, help='Input directory path')
72
+ generate_fragments.add_argument('--output_directory', required=True, type=str, help='Output directory path')
73
+ generate_fragments.add_argument('--log_file', required=True, type=str, help='Log file path')
74
+ generate_fragments.add_argument('--check_file_extension', required=False, action='store_true', help='Check file extension', default=True)
75
+ generate_fragments.add_argument('--offset', required=True, type=int, help='Offset', default=1)
76
+ generate_fragments.add_argument('--num_processes', required=True, type=int, help='Number of processes')
77
+ generate_fragments.add_argument('--mean', required=True, type=float, help='Mean')
78
+ generate_fragments.add_argument('--std_dev', required=True, type=float, help='Standard deviation')
79
+
80
+ return parser
81
+
82
+
83
+ def handle_polish_exporter(args) -> None:
84
+ """
85
+ Handle the Polish options.
86
+
87
+ Args:
88
+ args: The parsed arguments
89
+
90
+ Returns:
91
+ None
92
+ """
93
+ # TODO: Add instrument argument to download_polish_dataset.main
94
+ if args.instrument:
95
+ print("Instrument:", args.instrument)
96
+ else:
97
+ print("Instrument: Not specified")
98
+
99
+ polish_scores.download_polish_dataset.main(
100
+ input_directory=args.input_directory,
101
+ output_directory=args.output_directory,
102
+ kern_spines_filter=args.kern_spines_filter,
103
+ exporter_kern_type=args.kern_type,
104
+ remove_empty_directories=args.remove_empty_dirs
105
+ )
106
+
107
+
108
+ def handle_ekern2kern(args) -> None:
109
+ """
110
+ Handle the ekern2kern options.
111
+
112
+ Args:
113
+ args: The parsed arguments
114
+
115
+ Returns:
116
+ None
117
+ """
118
+ if not args.output_path:
119
+ args.output_path = args.input_path.replace("ekrn", "krn")
120
+
121
+ if not args.recursive:
122
+ ekern_to_krn(args.input_path, args.output_path)
123
+ if int(args.verbose) > 0:
124
+ print(f"New kern generated in {args.output_path}")
125
+ return
126
+
127
+ # Recursive mode
128
+ for root, dirs, files in os.walk(args.input_path):
129
+ for directory in dirs:
130
+ files = os.listdir(os.path.join(root, directory))
131
+ for filename in files:
132
+ if filename.endswith(".ekrn"):
133
+ if int(args.verbose) > 0:
134
+ print("New kern: ", os.path.join(root, directory, filename))
135
+ try:
136
+ ekern_to_krn(os.path.join(root, directory, filename),
137
+ os.path.join(root, directory, filename.replace(".ekrn", ".krn")))
138
+ except Exception as e:
139
+ if int(args.verbose) > 0:
140
+ print(f"An error occurred converting:{filename}:{e}", file=sys.stderr)
141
+
142
+
143
+ def handle_kern2ekern(args) -> None:
144
+ """
145
+ Handle the kern2ekern options.
146
+
147
+ Args:
148
+ args: The parsed arguments
149
+
150
+ Returns:
151
+ None
152
+ """
153
+ if not args.output_path:
154
+ args.output_path = args.input_path.replace("krn", "ekrn")
155
+
156
+ if not args.recursive:
157
+ kern_to_ekern(args.input_path, args.output_path)
158
+ if int(args.verbose) > 0:
159
+ print(f"New ekern generated in {args.output_path}")
160
+ return
161
+
162
+ # Recursive mode
163
+ for root, dirs, files in os.walk(args.input_path):
164
+ for directory in dirs:
165
+ files = os.listdir(os.path.join(root, directory))
166
+ for filename in files:
167
+ if filename.endswith(".krn"):
168
+ if int(args.verbose) > 0:
169
+ print("New ekern: ", os.path.join(root, directory, filename))
170
+ try:
171
+ kern_to_ekern(os.path.join(root, directory, filename),
172
+ os.path.join(root, directory, filename.replace(".krn", ".ekrn")))
173
+ except Exception as e:
174
+ if int(args.verbose) > 0:
175
+ print(f"An error occurred converting:{filename}:{e}", file=sys.stderr)
176
+
177
+
178
+ def handle_generate_fragments(args) -> None:
179
+ """
180
+ Handle the generate_fragments options.
181
+
182
+ Args:
183
+ args: The parsed arguments
184
+
185
+ Returns:
186
+ None
187
+ """
188
+ create_fragments_from_directory(args.input_directory, args.output_directory, args.log_file,
189
+ check_file_extension=args.check_file_extension, offset=args.offset,
190
+ verbose=args.verbose, num_processes=args.num_processes, mean=args.mean,
191
+ std_dev=args.std_dev)
192
+
193
+
194
+ def main():
195
+ parser = create_parser()
196
+ args = parser.parse_args()
197
+
198
+ # Accessing the values of the options
199
+ if int(args.verbose) > 2:
200
+ print(f"All arguments: \n{50 * '*'}")
201
+ for key, value in vars(args).items():
202
+ print(key, value)
203
+ print(f"{50 * '*'}\n")
204
+
205
+ if args.polish:
206
+ handle_polish_exporter(args)
207
+ if args.ekern2kern:
208
+ handle_ekern2kern(args)
209
+ if args.kern2ekern:
210
+ handle_kern2ekern(args)
211
+ if args.generate_fragments:
212
+ handle_generate_fragments(args)
213
+
214
+
215
+ if __name__ == "__main__":
216
+ main()
217
+
@@ -0,0 +1,119 @@
1
+ """
2
+ kernpy.core
3
+
4
+ =====
5
+
6
+ This module contains the core functionality of the `kernpy` package.
7
+ """
8
+
9
+ from .tokens import *
10
+ from .document import *
11
+ from .importer import *
12
+ from .exporter import *
13
+ from .graphviz_exporter import *
14
+ from .importer_factory import *
15
+ from .dyn_importer import *
16
+ from .dynam_spine_importer import *
17
+ from .fing_spine_importer import *
18
+ from .harm_spine_importer import *
19
+ from .kern_spine_importer import *
20
+ from .mens_spine_importer import *
21
+ from .root_spine_importer import *
22
+ from .text_spine_importer import *
23
+ from .mhxm_spine_importer import *
24
+ from .basic_spine_importer import *
25
+ from .generic import *
26
+ from .tokenizers import *
27
+ from .transposer import *
28
+ from .pitch_models import *
29
+ from .gkern import *
30
+
31
+
32
+ __all__ = [
33
+ 'Document',
34
+ 'TokenCategory',
35
+ 'Importer',
36
+ 'ExportOptions',
37
+ 'Exporter',
38
+ 'Encoding',
39
+ 'GraphvizExporter',
40
+ 'ekern_to_krn',
41
+ 'kern_to_ekern',
42
+ 'get_kern_from_ekern',
43
+ 'Encoding',
44
+ 'Tokenizer',
45
+ 'KernTokenizer',
46
+ 'EkernTokenizer',
47
+ 'BekernTokenizer',
48
+ 'BkernTokenizer',
49
+ 'TokenizerFactory',
50
+ 'Token',
51
+ 'KernTokenizer',
52
+ 'BEKERN_CATEGORIES',
53
+ 'DynSpineImporter',
54
+ 'DynamSpineImporter',
55
+ 'FingSpineImporter',
56
+ 'HarmSpineImporter',
57
+ 'KernSpineImporter',
58
+ 'MensSpineImporter',
59
+ 'RootSpineImporter',
60
+ 'TextSpineImporter',
61
+ 'MxhmSpineImporter',
62
+ 'BasicSpineImporter',
63
+ 'SpineOperationToken',
64
+ 'PitchRest',
65
+ 'Duration',
66
+ 'DurationClassical',
67
+ 'DurationMensural',
68
+ 'read',
69
+ 'create',
70
+ 'export',
71
+ 'store',
72
+ 'store_graph',
73
+ 'transposer',
74
+ 'get_spine_types',
75
+ 'createImporter',
76
+ 'TokenCategoryHierarchyMapper',
77
+ 'TOKEN_SEPARATOR',
78
+ 'DECORATION_SEPARATOR',
79
+ 'Subtoken',
80
+ 'AbstractToken',
81
+ 'SimpleToken',
82
+ 'ComplexToken',
83
+ 'CompoundToken',
84
+ 'NoteRestToken',
85
+ 'HeaderToken',
86
+ 'HeaderTokenGenerator',
87
+ 'NotationEncoding',
88
+ 'AgnosticPitch',
89
+ 'PitchExporter',
90
+ 'PitchExporterFactory',
91
+ 'HumdrumPitchExporter',
92
+ 'AmericanPitchExporter',
93
+ 'PitchImporter',
94
+ 'PitchImporterFactory',
95
+ 'HumdrumPitchImporter',
96
+ 'AmericanPitchImporter',
97
+ 'Direction',
98
+ 'Intervals',
99
+ 'IntervalsByName',
100
+ 'transpose',
101
+ 'transpose_agnostics',
102
+ 'transpose_encoding_to_agnostic',
103
+ 'transpose_agnostic_to_encoding',
104
+ 'PositionInStaff',
105
+ 'distance',
106
+ 'agnostic_distance',
107
+ 'PitchPositionReferenceSystem',
108
+ 'Clef',
109
+ 'GClef',
110
+ 'F3Clef',
111
+ 'F4Clef',
112
+ 'C1Clef',
113
+ 'C2Clef',
114
+ 'C3Clef',
115
+ 'C4Clef',
116
+ 'ClefFactory',
117
+ 'AVAILABLE_INTERVALS'
118
+ ]
119
+
kernpy/core/_io.py ADDED
@@ -0,0 +1,48 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Optional, Union
6
+
7
+
8
+ def _write(path: Union[str, Path], content: str) -> None:
9
+ """
10
+ Store content in a file.
11
+
12
+ Args:
13
+ path (str): Path to the file.
14
+ content (str): Content to be stored in the file.
15
+
16
+ Returns: None
17
+
18
+ """
19
+ if not os.path.exists(os.path.dirname(Path(path).absolute())):
20
+ os.makedirs(os.path.dirname(path), exist_ok=True)
21
+
22
+ with open(path, 'w+') as f:
23
+ f.write(content)
24
+
25
+
26
+ def find_all_files(
27
+ path: Path,
28
+ extension: Optional[str] = None) -> list:
29
+ """
30
+ Find all files with the given extension in the given directory.
31
+ Args:
32
+ path (str): Path to the directory where the files are located.
33
+ extension (Optional[str]): Extension of the files to be found. If None, all files are returned.
34
+
35
+ Returns (List[str]): List of paths to the found files.
36
+
37
+ Examples:
38
+ >>> find_all_files('/kern_files', 'krn')
39
+ ...
40
+
41
+ >>> find_all_files('/files' )
42
+ ...
43
+ """
44
+ p = Path(path)
45
+ if extension is None:
46
+ return list(p.glob('**/*'))
47
+ else:
48
+ return list(p.glob(f'**/*.{extension}'))
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ from antlr4 import CommonTokenStream, ParseTreeWalker
6
+ from antlr4.InputStream import InputStream
7
+
8
+
9
+ class BaseANTLRImporter(ABC):
10
+ def __init__(self, input_string):
11
+ char_stream = InputStream(input_string)
12
+ self.lexer = self.createLexer(char_stream)
13
+ token_stream = CommonTokenStream(self.lexer)
14
+ self.parser = self.createParser(token_stream)
15
+
16
+ @abstractmethod
17
+ def createLexer(self, charStream):
18
+ pass
19
+
20
+ @abstractmethod
21
+ def createParser(self, tokenStream):
22
+ pass
23
+
24
+ @abstractmethod
25
+ def startRule(self):
26
+ pass
27
+
28
+
29
+ class BaseANTLRListenerImporter(BaseANTLRImporter):
30
+ def __init__(self, input_string):
31
+ super().__init__(input_string)
32
+ self.listener = self.createListener()
33
+
34
+ def start(self):
35
+ tree = self.startRule()
36
+ walker = ParseTreeWalker()
37
+ walker.walk(self.listener, tree)
38
+ #ParseTreeWalker.DEFAULT.walk(walker, tree)
39
+
40
+ @abstractmethod
41
+ def createListener(self):
42
+ pass
43
+
44
+
45
+ class BaseANTLRVisitorImporter(BaseANTLRImporter):
46
+ def __init__(self, input):
47
+ super().__init__(input)
48
+ self.visitor = self.createVisitor()
49
+
50
+ def start(self):
51
+ tree_context = self.startRule()
52
+ self.visitStart(tree_context)
53
+
54
+ @abstractmethod
55
+ def createVisitor(self):
56
+ pass
57
+
58
+ @abstractmethod
59
+ def visitStart(self, start_context):
60
+ pass
61
+