Datasets:

ArXiv:
Elron commited on
Commit
62f686e
1 Parent(s): f9f6136

Upload parsing_utils.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. parsing_utils.py +231 -0
parsing_utils.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # An artifact is fetched from the catalog through the name by which it was added to that catalog.
2
+ # When first instantiated as an object (of class Artifact, or an extension thereof), values are set to the artifact's
3
+ # class arguments.
4
+ # When added to the catalog, the type (name of immediate class) along with the values of its arguments, are specified
5
+ # in the catalog record (json file) of that artifact, associated with the name given to that record upon adding to
6
+ # the catalog.
7
+ # When the artifact is later fetched from the catalog by that name, the values of its arguments are fetched as well,
8
+ # and used to instantiate the artifact into the object it was when added to the catalog.
9
+ #
10
+ # An addendum to this fetching process is a specification of alternative values to replace, upon fetching, (some of)
11
+ # the fetched values of the artifact's arguments, and to use the thus updated values for the instantiation following
12
+ # this fetching.
13
+ #
14
+ # The alternative arguments values, aka overwrites, are expressed as a string-ed series of key-value pairs, enclosed
15
+ # in square brackets, appended to the name of the artifact name.
16
+ #
17
+ # Overall, the formal definition of a query string, by which an artifact is fetched and instantiated, is as follows:
18
+ #
19
+ # query -> name | name [overwrites]
20
+ # overwrites -> assignment (, assignment)*
21
+ # assignment -> name = term
22
+ # term -> [ term (, term)* ] | { assignment (, assignment)* } | name_value | query
23
+ #
24
+ # name_value starting at a given point in the query string is the longest substring of the query string,
25
+ # that starts at that point, and ends upon reaching the end of the query string, or one of these chars: [],:{}=
26
+ # spaces are allowed.
27
+ # name is a name_value that is not evaluated to an int, or float, or boolean.
28
+ #
29
+ # The following code processes a given query string, verifies that it conforms with the above format syntax, throwing
30
+ # exceptions otherwise, and returns a pair of: (a) artifact name in the catalog, and (b) a (potentially empty)
31
+ # dictionary whose keys are names of (some of) the class arguments of the artifact, associated with the alternative
32
+ # values to set to these arguments, upon the instantiation of the artifact as a response to this query.
33
+ #
34
+ # Note: the code does not verify that a name of an artifact's argument is indeed a name of an argument of that
35
+ # artifact. The instantiation process that follows the parsing will verify that.
36
+ # Also, if an alternative value of an argument is specified, in turn, as a query with overwrites, the conforming
37
+ # of that query with the above syntax is done when processing the major query of the artifact, but the parsing of the
38
+ # overwrites (in the argument's query) is delayed to the stage when the recursive instantiation of the major artifact
39
+ # reaches the instantiation of that argument.
40
+ #
41
+ #
42
+ from typing import Any, Tuple
43
+
44
+
45
+ def consume_name_val(instring: str) -> Tuple[Any, str]:
46
+ name_val = ""
47
+ for char in instring:
48
+ if char in "[],:{}=":
49
+ break
50
+ name_val += char
51
+ instring = instring[len(name_val) :].strip()
52
+ name_val = name_val.strip()
53
+
54
+ if name_val == "True":
55
+ return (True, instring)
56
+ if name_val == "False":
57
+ return (False, instring)
58
+
59
+ sign = 1
60
+ if name_val.startswith("-"):
61
+ sign = -1
62
+ name_val = name_val[1:]
63
+ if name_val.isdigit():
64
+ return (sign * int(name_val), instring)
65
+ if name_val.replace(".", "", 1).isdigit() and name_val.count(".") < 2:
66
+ return (sign * float(name_val), instring)
67
+
68
+ if sign == -1:
69
+ name_val = "-" + name_val
70
+ return (name_val, instring)
71
+
72
+
73
+ def consume_name(instring: str) -> Tuple[Any, str]:
74
+ orig_instring = instring
75
+ (name_val, instring) = consume_name_val(instring)
76
+ if (
77
+ name_val is None
78
+ or isinstance(name_val, (int, float, bool))
79
+ or len(name_val) == 0
80
+ ):
81
+ raise ValueError(f"malformed name at the beginning of: {orig_instring}")
82
+ return (name_val, instring)
83
+
84
+
85
+ # flake8: noqa: C901
86
+ def consume_term(instring: str) -> Tuple[Any, str]:
87
+ orig_instring = instring
88
+ if instring.startswith("["):
89
+ toret = []
90
+ instring = instring[1:].strip()
91
+ (term, instring) = consume_term(instring)
92
+ toret.append(term)
93
+ while instring.startswith(","):
94
+ (term, instring) = consume_term(instring[1:].strip())
95
+ toret.append(term)
96
+ if not instring.startswith("]"):
97
+ raise ValueError(f"malformed list in: {orig_instring}")
98
+ instring = instring[1:].strip()
99
+ return (toret, instring)
100
+
101
+ if instring.startswith("{"):
102
+ instring = instring[1:].strip()
103
+ (items, instring) = consume_overwrites(instring, "}")
104
+ if not instring.startswith("}"):
105
+ raise ValueError(f"malformed dict in: {orig_instring}")
106
+ instring = instring[1:].strip()
107
+ return (items, instring)
108
+
109
+ (name_val, instring) = consume_name_val(instring)
110
+ instring = instring.strip()
111
+ if not (
112
+ name_val is None
113
+ or isinstance(name_val, (int, float, bool))
114
+ or len(name_val) == 0
115
+ ) and instring.startswith("["):
116
+ # term is a query with args
117
+ (overwrites, instring) = consume_overwrites(instring[1:].strip(), "]")
118
+ instring = instring.strip()
119
+ if not instring.startswith("]"):
120
+ raise ValueError(f"malformed query as a term in: {orig_instring}")
121
+ instring = instring[1:].strip()
122
+ toret = orig_instring[: len(orig_instring) - len(instring)]
123
+ # argument's alternative value specified by query with overwrites.
124
+ # the parsing of that query is delayed, to be synchronizes with the recursive loading
125
+ # of the artifact from the catalog
126
+ return (toret, instring)
127
+
128
+ return (name_val, instring)
129
+
130
+
131
+ def consume_assignment(instring: str) -> Tuple[Any, str]:
132
+ orig_instring = instring
133
+ (name, instring) = consume_name(instring)
134
+
135
+ if not instring.startswith("="):
136
+ raise ValueError(f"malformed assignment in: {orig_instring}")
137
+ (term, instring) = consume_term(instring[1:].strip())
138
+ if (term is None) or not (isinstance(term, (int, float, bool)) or len(term) > 0):
139
+ raise ValueError(f"malformed assigned value in: {orig_instring}")
140
+ return ({name: term}, instring)
141
+
142
+
143
+ def consume_overwrites(instring: str, valid_follower: str) -> Tuple[Any, str]:
144
+ if instring.startswith(valid_follower):
145
+ return ({}, instring)
146
+ (toret, instring) = consume_assignment(instring.strip())
147
+ while instring.startswith(","):
148
+ instring = instring[1:].strip()
149
+ (assignment, instring) = consume_assignment(instring.strip())
150
+ toret = {**toret, **assignment}
151
+ return (toret, instring)
152
+
153
+
154
+ def consume_query(instring: str) -> Tuple[Tuple[str, any], str]:
155
+ orig_instring = instring
156
+ (name, instring) = consume_name(instring)
157
+ instring = instring.strip()
158
+ if len(instring) == 0 or not instring.startswith("["):
159
+ return ((name, None), instring)
160
+
161
+ (overwrites, instring) = consume_overwrites(instring[1:], "]")
162
+ instring = instring.strip()
163
+ if len(instring) == 0 or not instring.startswith("]"):
164
+ raise ValueError(
165
+ f"malformed end of query: overwrites not closed by ] in: {orig_instring}"
166
+ )
167
+ return ((name, overwrites), instring[1:].strip())
168
+
169
+
170
+ def parse_key_equals_value_string_to_dict(args: str) -> dict:
171
+ """Parses a query string of the form 'key1=value1,key2=value2,...' into a dictionary.
172
+
173
+ The function converts numeric values into integers or floats as appropriate, and raises an
174
+ exception if the query string is malformed or does not conform to the expected format.
175
+
176
+ :param query: The query string to be parsed.
177
+ :return: A dictionary with keys and values extracted from the query string, with spaces stripped from keys.
178
+ """
179
+ instring = args.strip()
180
+ if len(instring) == 0:
181
+ return {}
182
+ args_dict, instring = consume_overwrites(instring, " ")
183
+ if len(instring.strip()) > 0:
184
+ raise ValueError(f"Illegal key-values structure in {args}")
185
+ return args_dict
186
+
187
+
188
+ def separate_inside_and_outside_square_brackets(s: str) -> Tuple[str, any]:
189
+ """Separates the content inside and outside the first level of square brackets in a string.
190
+
191
+ Allows text before the first bracket and nested brackets within the first level. Raises a ValueError for:
192
+ - Text following the closing bracket of the first bracket pair
193
+ - Unmatched brackets
194
+ - Multiple bracket pairs at the same level
195
+
196
+ :param s: The input string to be parsed.
197
+ :return: A tuple (outside, inside) where 'outside' is the content outside the first level of square brackets,
198
+ and 'inside' is the content inside the first level of square brackets. If there are no brackets,
199
+ 'inside' will be None.
200
+ """
201
+ start = s.find("[")
202
+ end = s.rfind("]")
203
+
204
+ # Handle no brackets
205
+ if start == -1 and end == -1:
206
+ return s, None
207
+
208
+ # Validate brackets
209
+ if start == -1 or end == -1 or start > end:
210
+ raise ValueError("Illegal structure: unmatched square brackets.")
211
+
212
+ after = s[end + 1 :]
213
+
214
+ # Check for text after the closing bracket
215
+ if len(after.strip()) != 0:
216
+ raise ValueError(
217
+ "Illegal structure: text follows after the closing square bracket."
218
+ )
219
+
220
+ instring = s.strip()
221
+ orig_instring = instring
222
+ if "[" not in instring:
223
+ # no alternative values to artifact: consider the whole input string as an artifact name
224
+ return (instring, None)
225
+ # parse to identify artifact name and alternative values to artifact's arguments
226
+ (query, instring) = consume_query(instring)
227
+ if len(instring) > 0:
228
+ raise ValueError(
229
+ f"malformed end of query: excessive text following the ] that closes the overwrites in: {orig_instring}"
230
+ )
231
+ return query