Upload split_utils.py with huggingface_hub
Browse files12343 unmodified lines8910111213141512 unmodified lines282930313233343536373839404142434445464748495014 unmodified lines6566676869707110 unmodified lines8283848586878811 unmodified lines10010110210310410510610710810911011111211315 unmodified lines1291301311321331341351361371381391406 unmodified lines14714814915015115215315421 unmodified lines17617717817918018118218318418518618718818919019111 unmodified lines2032042052062072082092102112122132142153 unmodified lines2192202212222232242252262272282297 unmodified lines23723823924024124224324428 unmodified lines27327427527627727827928028128228316 unmodified lines300301302303import itertoolsimport refrom typing import Dict3 unmodified linesdef parse_random_mix_string(input_str):"""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):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)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)]...}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 linesname = sourcestart = end = Noneelse: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 linesif end is not None:stream = itertools.islice(stream, end)for item in stream:yield item# return streamdef slice_streams(input_streams, mapping):"""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():old_stream_content = input_streams[old_stream]for start, end in slices:yield from slice_stream(old_stream_content, start, end)6 unmodified linesdef build_stream_routing(mapping):"""Builds the stream mapping dictionary based on the provided mapping.The stream mapping dictionary represents the mapping of old streams to new streamsand their respective probabilities. It ensures that the probabilities for each old stream21 unmodified lines}}stream_mapping = build_stream_mapping(mapping)print(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 streamtotal_weights = {}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 linesif 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_mappingdef rename_split(input_streams: Dict[str, Stream], mapping: Dict[str, str]):"""Renames the streamsArgs:input_streams (dict): A dictionary containing the input streams, where each key isthe name of the stream and the value is an iterable or generator3 unmodified linesReturns:dict: A dictionary containing the generated new streams, where each key is the nameof 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):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 linesdef random_mix_streams(input_streams, mapping):"""Creates new streams based on the provided input streams and mapping.The create_streams function generates new streams by selectively including items fromthe 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}:")for _, item in zip(range(10), new_stream):print(item)"""new_streams = {}# Build stream routing16 unmodified linesif __name__ == "__main__":print(parse_random_mix_string("dale[90%]+oren[0.7]+mike"))123453 unmodified lines910111213141512 unmodified lines28293031323334353637383940414243444546474849505152535414 unmodified lines69707172737410 unmodified lines85868788899091929311 unmodified lines10510610710810911011111211311411511615 unmodified lines1321331341351361371381391401411421431446 unmodified lines15115215315415515615721 unmodified lines17918018118218318418518618718818919019119219311 unmodified lines2052062072082092102112122132142152163 unmodified lines2202212222232242252262272282292302312322337 unmodified lines24124224324424524624728 unmodified lines27627727827928028128228328428516 unmodified lines302303304305import itertoolsimport loggingimport refrom typing import Dict3 unmodified linesdef parse_random_mix_string(input_str):"""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,):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("[]%")) / 100if "%" in valueelse (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)]...}.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 linesname = sourcestart = end = Noneelse: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 linesif end is not None:stream = itertools.islice(stream, end)yield from stream# return streamdef slice_streams(input_streams, mapping):"""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 linesdef build_stream_routing(mapping):"""Builds the stream mapping dictionary based on the provided mapping.The stream mapping dictionary represents the mapping of old streams to new streamsand their respective probabilities. It ensures that the probabilities for each old stream21 unmodified lines}}stream_mapping = build_stream_mapping(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 streamtotal_weights = {}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 linesif total_weights[old_stream] < 1:stream_mapping[old_stream][None] = 1 - total_weights[old_stream]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.Args:input_streams (dict): A dictionary containing the input streams, where each key isthe name of the stream and the value is an iterable or generator3 unmodified linesReturns:dict: A dictionary containing the generated new streams, where each key is the nameof 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):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 linesdef random_mix_streams(input_streams, mapping):"""Creates new streams based on the provided input streams and mapping.The create_streams function generates new streams by selectively including items fromthe 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():logging.info(f"{new_stream_name}:")for _, item in zip(range(10), new_stream):logging.info(item)"""new_streams = {}# Build stream routing16 unmodified linesif __name__ == "__main__":logging.info(parse_random_mix_string("dale[90%]+oren[0.7]+mike"))
split_utils.py+34-32