Upload split_utils.py with huggingface_hub
Browse files123453 unmodified lines9101111121213141512 unmodified lines28293031323132333435363738394039414243444546474845464749505152535414 unmodified lines6970716872737410 unmodified lines8586878588899091929311 unmodified lines10510610710310410810911011111210911011311411511615 unmodified lines1321331341321351361371381391401411421431446 unmodified lines15115215315015115415515615721 unmodified lines17918018117918218318418518318618718818918819019119219311 unmodified lines2052062072062072082092102112112122122132142152163 unmodified lines2202212222222232242252262272262282292302312322337 unmodified lines24124224324024124424524624728 unmodified lines27627727827627928027828128228028328428516 unmodified lines302303304303305import itertoolsimport loggingimport refrom typing import Dict
3 unmodified lines
def parse_random_mix_string(input_str): """ Parses a string of format "source1[percentage1%]+source2[value2]+..." and returns a dictionary. """Parses a string of format "source1[percentage1%]+source2[value2]+..." and returns a dictionary.
Args: input_str (str): A string containing source names and their respective proportions. The format is12 unmodified lines >>> parse_random_mix_string("dale[90%]+oren[0.7]+mike") {'dale': 0.9, 'oren': 0.7, 'mike': 1.0} """
if not re.fullmatch(r"(([a-zA-Z]+\[\d*\.?\d*%?\]|[a-zA-Z]+)\+)*([a-zA-Z]+\[\d*\.?\d*%?\]|[a-zA-Z]+)", input_str): if not re.fullmatch( r"(([a-zA-Z]+\[\d*\.?\d*%?\]|[a-zA-Z]+)\+)*([a-zA-Z]+\[\d*\.?\d*%?\]|[a-zA-Z]+)", input_str, ): raise ValueError(f"Invalid input format for split '{input_str}'")
pattern = re.compile(r"([a-zA-Z]+)(\[\d*\.?\d*%?\])?") matches = pattern.findall(input_str)
return { name: float(value.strip("[]%")) / 100 if "%" in value else (float(value.strip("[]")) if value else 1.0) name: float(value.strip("[]%")) / 100 if "%" in value else (float(value.strip("[]")) if value else 1.0) for name, value in matches }
def parse_slices_string(input_str): """ Parses a string of format "source1[value1:value2] + source2[value2:] + source3 + ..." and returns a dictionary: {"source1": [(value1,value2)], "source2": [(value2, None)], "source3": [(None,None)]...} """Parses a string of format "source1[value1:value2] + source2[value2:] + source3 + ..." and returns a dictionary.
{"source1": [(value1,value2)], "source2": [(value2, None)], "source3": [(None,None)]...}.
If a source appears multiple times with different indices, all index pairs are included in the list.
14 unmodified lines >>> parse_slices_string("oren[:50]+jake[24:]+test+oren[5:10]") {'oren': [(None, 50), (5, 10)], 'jake': [(24, None)], 'test': [(None, None)]} """
result_dict = {}
# Split the input string into a list of sources10 unmodified lines name = source start = end = None else: raise ValueError(f'The input string "{input_str}" is not in the correct format.') raise ValueError( f'The input string "{input_str}" is not in the correct format.' )
if name not in result_dict: result_dict[name] = [(start, end)]11 unmodified lines if end is not None: stream = itertools.islice(stream, end)
for item in stream: yield item yield from stream # return stream
def slice_streams(input_streams, mapping): """ Slices multiple input streams according to a mapping and chains the results together. """Slices multiple input streams according to a mapping and chains the results together.
Args: input_streams (dict): A dictionary where the keys are the names of the input streams15 unmodified lines >>> slice_streams(old_streams, mapping) {"new_train": [1, 2, 3, 4, 5, 8, 9], "new_test": [12, 13, 14]} """
new_streams = {} for new_stream, sources in mapping.items():
def generator(new_stream, sources): for old_stream, slices in sources.items(): if old_stream not in input_streams: raise ValueError(f"'{old_stream}' is not available in input stream") old_stream_content = input_streams[old_stream] for start, end in slices: yield from slice_stream(old_stream_content, start, end)6 unmodified lines
def build_stream_routing(mapping): """ Builds the stream mapping dictionary based on the provided mapping. """Builds the stream mapping dictionary based on the provided mapping.
The stream mapping dictionary represents the mapping of old streams to new streams and their respective probabilities. It ensures that the probabilities for each old stream21 unmodified lines } } stream_mapping = build_stream_mapping(mapping) print(stream_mapping) logging.info(stream_mapping) # Output: {'my_old_stream1': (['my_new_stream', 'my_new_stream2'], [0.6, 0.4]), # 'my_old_stream2': (['my_new_stream', 'my_new_stream2'], [0.2, 0.8])} """
stream_mapping = {}
# Calculate total weight for each old stream total_weights = {} for new_stream, old_streams in mapping.items(): for _new_stream, old_streams in mapping.items(): for old_stream, weight in old_streams.items(): if old_stream not in total_weights: total_weights[old_stream] = weight11 unmodified lines if total_weights[old_stream] < 1: stream_mapping[old_stream][None] = 1 - total_weights[old_stream]
stream_mapping = {k: (list(v.keys()), list(v.values())) for k, v in stream_mapping.items()} return stream_mapping return {k: (list(v.keys()), list(v.values())) for k, v in stream_mapping.items()}
def rename_split(input_streams: Dict[str, Stream], mapping: Dict[str, str]): """ Renames the streams """Renames the streams.
Args: input_streams (dict): A dictionary containing the input streams, where each key is the name of the stream and the value is an iterable or generator3 unmodified lines
Returns: dict: A dictionary containing the generated new streams, where each key is the name of the new stream and the value is a generator representing the stream.""" of the new stream and the value is a generator representing the stream. """ return {mapping.get(key, key): val for key, val in input_streams.items()}
def random_mix_generator(new_stream_name, new_stream_sources, stream_routing, input_streams):def random_mix_generator( new_stream_name, new_stream_sources, stream_routing, input_streams): for old_stream_name in new_stream_sources: optinal_streams, weights = stream_routing[old_stream_name] with nested_seed(old_stream_name) as rand:7 unmodified lines
def random_mix_streams(input_streams, mapping): """ Creates new streams based on the provided input streams and mapping. """Creates new streams based on the provided input streams and mapping.
The create_streams function generates new streams by selectively including items from the old streams based on the specified mapping. Each item will be included in at most28 unmodified lines } new_streams = create_streams(input_streams, mapping) for new_stream_name, new_stream in new_streams.items(): print(f"{new_stream_name}:") logging.info(f"{new_stream_name}:") for _, item in zip(range(10), new_stream): print(item) logging.info(item) """
new_streams = {}
# Build stream routing16 unmodified lines
if __name__ == "__main__": print(parse_random_mix_string("dale[90%]+oren[0.7]+mike")) logging.info(parse_random_mix_string("dale[90%]+oren[0.7]+mike"))split_utils.py+34-32