Elron commited on
Commit
6016778
1 Parent(s): 92d07f8

Upload split_utils.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. split_utils.py +34 -32
split_utils.py CHANGED
@@ -1,4 +1,5 @@
1
  import itertools
 
2
  import re
3
  from typing import Dict
4
 
@@ -8,8 +9,7 @@ from .stream import Stream
8
 
9
 
10
  def parse_random_mix_string(input_str):
11
- """
12
- Parses a string of format "source1[percentage1%]+source2[value2]+..." and returns a dictionary.
13
 
14
  Args:
15
  input_str (str): A string containing source names and their respective proportions. The format is
@@ -28,23 +28,27 @@ def parse_random_mix_string(input_str):
28
  >>> parse_random_mix_string("dale[90%]+oren[0.7]+mike")
29
  {'dale': 0.9, 'oren': 0.7, 'mike': 1.0}
30
  """
31
-
32
- if not re.fullmatch(r"(([a-zA-Z]+\[\d*\.?\d*%?\]|[a-zA-Z]+)\+)*([a-zA-Z]+\[\d*\.?\d*%?\]|[a-zA-Z]+)", input_str):
 
 
33
  raise ValueError(f"Invalid input format for split '{input_str}'")
34
 
35
  pattern = re.compile(r"([a-zA-Z]+)(\[\d*\.?\d*%?\])?")
36
  matches = pattern.findall(input_str)
37
 
38
  return {
39
- name: float(value.strip("[]%")) / 100 if "%" in value else (float(value.strip("[]")) if value else 1.0)
 
 
40
  for name, value in matches
41
  }
42
 
43
 
44
  def parse_slices_string(input_str):
45
- """
46
- Parses a string of format "source1[value1:value2] + source2[value2:] + source3 + ..." and returns a dictionary:
47
- {"source1": [(value1,value2)], "source2": [(value2, None)], "source3": [(None,None)]...}
48
 
49
  If a source appears multiple times with different indices, all index pairs are included in the list.
50
 
@@ -65,7 +69,6 @@ def parse_slices_string(input_str):
65
  >>> parse_slices_string("oren[:50]+jake[24:]+test+oren[5:10]")
66
  {'oren': [(None, 50), (5, 10)], 'jake': [(24, None)], 'test': [(None, None)]}
67
  """
68
-
69
  result_dict = {}
70
 
71
  # Split the input string into a list of sources
@@ -82,7 +85,9 @@ def parse_slices_string(input_str):
82
  name = source
83
  start = end = None
84
  else:
85
- raise ValueError(f'The input string "{input_str}" is not in the correct format.')
 
 
86
 
87
  if name not in result_dict:
88
  result_dict[name] = [(start, end)]
@@ -100,14 +105,12 @@ def slice_stream(stream, start, end):
100
  if end is not None:
101
  stream = itertools.islice(stream, end)
102
 
103
- for item in stream:
104
- yield item
105
  # return stream
106
 
107
 
108
  def slice_streams(input_streams, mapping):
109
- """
110
- Slices multiple input streams according to a mapping and chains the results together.
111
 
112
  Args:
113
  input_streams (dict): A dictionary where the keys are the names of the input streams
@@ -129,12 +132,13 @@ def slice_streams(input_streams, mapping):
129
  >>> slice_streams(old_streams, mapping)
130
  {"new_train": [1, 2, 3, 4, 5, 8, 9], "new_test": [12, 13, 14]}
131
  """
132
-
133
  new_streams = {}
134
  for new_stream, sources in mapping.items():
135
 
136
  def generator(new_stream, sources):
137
  for old_stream, slices in sources.items():
 
 
138
  old_stream_content = input_streams[old_stream]
139
  for start, end in slices:
140
  yield from slice_stream(old_stream_content, start, end)
@@ -147,8 +151,7 @@ def slice_streams(input_streams, mapping):
147
 
148
 
149
  def build_stream_routing(mapping):
150
- """
151
- Builds the stream mapping dictionary based on the provided mapping.
152
 
153
  The stream mapping dictionary represents the mapping of old streams to new streams
154
  and their respective probabilities. It ensures that the probabilities for each old stream
@@ -176,16 +179,15 @@ def build_stream_routing(mapping):
176
  }
177
  }
178
  stream_mapping = build_stream_mapping(mapping)
179
- print(stream_mapping)
180
  # Output: {'my_old_stream1': (['my_new_stream', 'my_new_stream2'], [0.6, 0.4]),
181
  # 'my_old_stream2': (['my_new_stream', 'my_new_stream2'], [0.2, 0.8])}
182
  """
183
-
184
  stream_mapping = {}
185
 
186
  # Calculate total weight for each old stream
187
  total_weights = {}
188
- for new_stream, old_streams in mapping.items():
189
  for old_stream, weight in old_streams.items():
190
  if old_stream not in total_weights:
191
  total_weights[old_stream] = weight
@@ -203,13 +205,12 @@ def build_stream_routing(mapping):
203
  if total_weights[old_stream] < 1:
204
  stream_mapping[old_stream][None] = 1 - total_weights[old_stream]
205
 
206
- stream_mapping = {k: (list(v.keys()), list(v.values())) for k, v in stream_mapping.items()}
207
- return stream_mapping
208
 
209
 
210
  def rename_split(input_streams: Dict[str, Stream], mapping: Dict[str, str]):
211
- """
212
- Renames the streams
213
  Args:
214
  input_streams (dict): A dictionary containing the input streams, where each key is
215
  the name of the stream and the value is an iterable or generator
@@ -219,11 +220,14 @@ def rename_split(input_streams: Dict[str, Stream], mapping: Dict[str, str]):
219
 
220
  Returns:
221
  dict: A dictionary containing the generated new streams, where each key is the name
222
- of the new stream and the value is a generator representing the stream."""
 
223
  return {mapping.get(key, key): val for key, val in input_streams.items()}
224
 
225
 
226
- def random_mix_generator(new_stream_name, new_stream_sources, stream_routing, input_streams):
 
 
227
  for old_stream_name in new_stream_sources:
228
  optinal_streams, weights = stream_routing[old_stream_name]
229
  with nested_seed(old_stream_name) as rand:
@@ -237,8 +241,7 @@ def random_mix_generator(new_stream_name, new_stream_sources, stream_routing, in
237
 
238
 
239
  def random_mix_streams(input_streams, mapping):
240
- """
241
- Creates new streams based on the provided input streams and mapping.
242
 
243
  The create_streams function generates new streams by selectively including items from
244
  the old streams based on the specified mapping. Each item will be included in at most
@@ -273,11 +276,10 @@ def random_mix_streams(input_streams, mapping):
273
  }
274
  new_streams = create_streams(input_streams, mapping)
275
  for new_stream_name, new_stream in new_streams.items():
276
- print(f"{new_stream_name}:")
277
  for _, item in zip(range(10), new_stream):
278
- print(item)
279
  """
280
-
281
  new_streams = {}
282
 
283
  # Build stream routing
@@ -300,4 +302,4 @@ def random_mix_streams(input_streams, mapping):
300
 
301
 
302
  if __name__ == "__main__":
303
- print(parse_random_mix_string("dale[90%]+oren[0.7]+mike"))
 
1
  import itertools
2
+ import logging
3
  import re
4
  from typing import Dict
5
 
 
9
 
10
 
11
  def parse_random_mix_string(input_str):
12
+ """Parses a string of format "source1[percentage1%]+source2[value2]+..." and returns a dictionary.
 
13
 
14
  Args:
15
  input_str (str): A string containing source names and their respective proportions. The format is
 
28
  >>> parse_random_mix_string("dale[90%]+oren[0.7]+mike")
29
  {'dale': 0.9, 'oren': 0.7, 'mike': 1.0}
30
  """
31
+ if not re.fullmatch(
32
+ r"(([a-zA-Z]+\[\d*\.?\d*%?\]|[a-zA-Z]+)\+)*([a-zA-Z]+\[\d*\.?\d*%?\]|[a-zA-Z]+)",
33
+ input_str,
34
+ ):
35
  raise ValueError(f"Invalid input format for split '{input_str}'")
36
 
37
  pattern = re.compile(r"([a-zA-Z]+)(\[\d*\.?\d*%?\])?")
38
  matches = pattern.findall(input_str)
39
 
40
  return {
41
+ name: float(value.strip("[]%")) / 100
42
+ if "%" in value
43
+ else (float(value.strip("[]")) if value else 1.0)
44
  for name, value in matches
45
  }
46
 
47
 
48
  def parse_slices_string(input_str):
49
+ """Parses a string of format "source1[value1:value2] + source2[value2:] + source3 + ..." and returns a dictionary.
50
+
51
+ {"source1": [(value1,value2)], "source2": [(value2, None)], "source3": [(None,None)]...}.
52
 
53
  If a source appears multiple times with different indices, all index pairs are included in the list.
54
 
 
69
  >>> parse_slices_string("oren[:50]+jake[24:]+test+oren[5:10]")
70
  {'oren': [(None, 50), (5, 10)], 'jake': [(24, None)], 'test': [(None, None)]}
71
  """
 
72
  result_dict = {}
73
 
74
  # Split the input string into a list of sources
 
85
  name = source
86
  start = end = None
87
  else:
88
+ raise ValueError(
89
+ f'The input string "{input_str}" is not in the correct format.'
90
+ )
91
 
92
  if name not in result_dict:
93
  result_dict[name] = [(start, end)]
 
105
  if end is not None:
106
  stream = itertools.islice(stream, end)
107
 
108
+ yield from stream
 
109
  # return stream
110
 
111
 
112
  def slice_streams(input_streams, mapping):
113
+ """Slices multiple input streams according to a mapping and chains the results together.
 
114
 
115
  Args:
116
  input_streams (dict): A dictionary where the keys are the names of the input streams
 
132
  >>> slice_streams(old_streams, mapping)
133
  {"new_train": [1, 2, 3, 4, 5, 8, 9], "new_test": [12, 13, 14]}
134
  """
 
135
  new_streams = {}
136
  for new_stream, sources in mapping.items():
137
 
138
  def generator(new_stream, sources):
139
  for old_stream, slices in sources.items():
140
+ if old_stream not in input_streams:
141
+ raise ValueError(f"'{old_stream}' is not available in input stream")
142
  old_stream_content = input_streams[old_stream]
143
  for start, end in slices:
144
  yield from slice_stream(old_stream_content, start, end)
 
151
 
152
 
153
  def build_stream_routing(mapping):
154
+ """Builds the stream mapping dictionary based on the provided mapping.
 
155
 
156
  The stream mapping dictionary represents the mapping of old streams to new streams
157
  and their respective probabilities. It ensures that the probabilities for each old stream
 
179
  }
180
  }
181
  stream_mapping = build_stream_mapping(mapping)
182
+ logging.info(stream_mapping)
183
  # Output: {'my_old_stream1': (['my_new_stream', 'my_new_stream2'], [0.6, 0.4]),
184
  # 'my_old_stream2': (['my_new_stream', 'my_new_stream2'], [0.2, 0.8])}
185
  """
 
186
  stream_mapping = {}
187
 
188
  # Calculate total weight for each old stream
189
  total_weights = {}
190
+ for _new_stream, old_streams in mapping.items():
191
  for old_stream, weight in old_streams.items():
192
  if old_stream not in total_weights:
193
  total_weights[old_stream] = weight
 
205
  if total_weights[old_stream] < 1:
206
  stream_mapping[old_stream][None] = 1 - total_weights[old_stream]
207
 
208
+ return {k: (list(v.keys()), list(v.values())) for k, v in stream_mapping.items()}
 
209
 
210
 
211
  def rename_split(input_streams: Dict[str, Stream], mapping: Dict[str, str]):
212
+ """Renames the streams.
213
+
214
  Args:
215
  input_streams (dict): A dictionary containing the input streams, where each key is
216
  the name of the stream and the value is an iterable or generator
 
220
 
221
  Returns:
222
  dict: A dictionary containing the generated new streams, where each key is the name
223
+ of the new stream and the value is a generator representing the stream.
224
+ """
225
  return {mapping.get(key, key): val for key, val in input_streams.items()}
226
 
227
 
228
+ def random_mix_generator(
229
+ new_stream_name, new_stream_sources, stream_routing, input_streams
230
+ ):
231
  for old_stream_name in new_stream_sources:
232
  optinal_streams, weights = stream_routing[old_stream_name]
233
  with nested_seed(old_stream_name) as rand:
 
241
 
242
 
243
  def random_mix_streams(input_streams, mapping):
244
+ """Creates new streams based on the provided input streams and mapping.
 
245
 
246
  The create_streams function generates new streams by selectively including items from
247
  the old streams based on the specified mapping. Each item will be included in at most
 
276
  }
277
  new_streams = create_streams(input_streams, mapping)
278
  for new_stream_name, new_stream in new_streams.items():
279
+ logging.info(f"{new_stream_name}:")
280
  for _, item in zip(range(10), new_stream):
281
+ logging.info(item)
282
  """
 
283
  new_streams = {}
284
 
285
  # Build stream routing
 
302
 
303
 
304
  if __name__ == "__main__":
305
+ logging.info(parse_random_mix_string("dale[90%]+oren[0.7]+mike"))