Upload dict_utils.py with huggingface_hub
Browse files177 unmodified lines1781791801811821831841851861871881891901911921932 unmodified lines19619719819920020120220320420527 unmodified lines23323423523623723823921 unmodified lines2612622632642652662672682692702712722732742753 unmodified lines27928028128228328428528617 unmodified lines30430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433522 unmodified lines3583593603613623633643653663673683692 unmodified lines3723733743753763773783793803813823831 unmodified line38538638738838939039139239339439539639739839940040140245 unmodified lines448449450451452453454455456457458459460461462463464465466467468469470471472177 unmodified lines):# We remove from dic the value from each and every element lead to by a path matching the query.# If remove_empty_ancestors=True, and the removal of any such value leaves its containing element (list or dict)# within dic empty -- remove that element as well, and continue recursivelyqpath = validate_query_and_break_to_components(query)if len(qpath) == 1:if qpath[0] in dic:dic.pop(qpath[0])returnif not not_exist_ok:raise ValueError(f"An attempt to delete from dictionary {dic}, an element {query}, that does not exist in the dictionary")try:success, new_val = delete_values(2 unmodified linesindex_into_query=(-1) * len(qpath),remove_empty_ancestors=remove_empty_ancestors,)if not success and not not_exist_ok:raise ValueError(f"An attempt to delete from dictionary {dic}, an element {query}, that does not exist in the dictionary")except Exception as e:raise ValueError(f"query {query} matches no path in dictionary {dic}") from e27 unmodified linesexcept:continuereturn (len(to_ret) > 0, to_ret)# next_component is indx or name, current_element must be a list or a dictif indx.match(component):component = int(component)21 unmodified linesreturn (True, value) # matched query all along!# current_element should be a list or dict: a containing elementif current_element and not isinstance(current_element, (list, dict)):current_element = None # give it a chance to become what is needed, if allowedif not current_element and not fixed_parameters["generate_if_not_exists"]:return (False, None)component = fixed_parameters["query"][index_into_query]if component == "*":if current_element and set_multiple:if isinstance(current_element, dict) and len(current_element) != len(value):return (False, None)if isinstance(current_element, list) and len(current_element) > len(value):3 unmodified linesreturn (False, None)# current_element must be a list, extend current_element to the length neededcurrent_element.extend([None] * (len(value) - len(current_element)))if not current_element:current_element = [None] * (len(value) if set_multiple else 1)# now current_element is of size suiting valueif isinstance(current_element, dict):keys = sorted(current_element.keys())17 unmodified linesexcept:continuereturn (any_success, current_element)# component is an index into a list or a key into a dictionaryif indx.match(component):if current_element and not isinstance(current_element, list):if not fixed_parameters["generate_if_not_exists"]:return (False, None)current_element = []component = int(component)if (current_element and component >= len(current_element)) or not current_element:if not fixed_parameters["generate_if_not_exists"]:return (False, None)# extend current_element to the length neededif not current_element:current_element = []current_element.extend([None] * (component + 1 - len(current_element)))next_current_element = current_element[component]else: # component is a key into a dictionaryif current_element and not isinstance(current_element, dict):if not fixed_parameters["generate_if_not_exists"]:return (False, None)current_element = {}if not current_element:current_element = {}if (component not in current_elementand not fixed_parameters["generate_if_not_exists"]22 unmodified linesdef dict_get(dic: dict,query: str,use_dpath: bool = True,not_exist_ok: bool = False,default: Any = None,):if use_dpath and "/" in query:components = validate_query_and_break_to_components(query)try:success, values = get_values(dic, components, -1 * len(components))if not success:2 unmodified linesraise ValueError(f'query "{query}" did not match any item in dict: {dic}')if isinstance(values, list) and len(values) == 0:if not_exist_ok:return defaultraise ValueError(f'query "{query}" did not match any item in dict: {dic} while not_exist_ok=False')return values1 unmodified lineif not_exist_ok:return defaultraise ValueError(f'query "{query}" did not match any item in dict: {dic} while not_exist_ok=False') from eif query.strip() in dic:return dic[query.strip()]if not_exist_ok:return defaultraise ValueError(f'query "{query}" did not match any item in dict: {dic} while not_exist_ok=False')# dict_set sets a value, 'value', which by itself, can be a dict or list or scalar, into 'dic', to become the value of45 unmodified linesdic: dict,query: str,value: Any,use_dpath=True,not_exist_ok=True,set_multiple=False,):if set_multiple and (not isinstance(value, list) or len(value) == 0 or "*" not in query):raise ValueError(f"set_multiple == True, and yet value, {value}, is not a list or '*' is not in query '{query}'")if not use_dpath or "/" not in query:if query.strip() in dic or not_exist_ok:dic[query] = valuereturnraise ValueError(f"not_exist_ok=False and the single component query '{query}' is not a key in dic {dic}")# use_dpath and "/" in querycomponents = validate_query_and_break_to_components(query)fixed_parameters = {"query": components,177 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002012 unmodified lines20420520620720820921021121221321421521621721821922027 unmodified lines24824925025125225325425521 unmodified lines2772782792802812822832842852862872882892902913 unmodified lines29529629729829930030130230330430530630730830917 unmodified lines32732832933033133233333433533633733833934034134234334434534634734834935035135235335435535622 unmodified lines3793803813823833843853863873883893903913923933943953963973982 unmodified lines4014024034044054061 unmodified line40840941041141241341441541641741841942042142242342445 unmodified lines470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513177 unmodified lines):# We remove from dic the value from each and every element lead to by a path matching the query.# If remove_empty_ancestors=True, and the removal of any such value leaves its containing element (list or dict)# within dic empty -- remove that element as well, and continue recursively, but stop one step before deleting dic# altogether, even if became {}. If successful, changes dic into its new shapeif dic is None or not isinstance(dic, (list, dict)):raise ValueError(f"dic {dic} is either None or not a list nor a dict. Can not delete from it.")if len(query) == 0:raise ValueError("Query is an empty string, implying the deletion of dic as a whole. This can not be done via this function call.")if isinstance(dic, dict) and query.strip() in dic:dic.pop(query.strip())returnqpath = validate_query_and_break_to_components(query)try:success, new_val = delete_values(2 unmodified linesindex_into_query=(-1) * len(qpath),remove_empty_ancestors=remove_empty_ancestors,)if success:if new_val == {}:dic.clear()returnif not not_exist_ok:raise ValueError(f"An attempt to delete from dictionary {dic}, an element {query}, that does not exist in the dictionary, while not_exist_ok=False")except Exception as e:raise ValueError(f"query {query} matches no path in dictionary {dic}") from e27 unmodified linesexcept:continuereturn (len(to_ret) > 0 or index_into_query == -1, to_ret)# when * is the last component, it refers to 'all the contents' of an empty list being current_element.# next_component is indx or name, current_element must be a list or a dictif indx.match(component):component = int(component)21 unmodified linesreturn (True, value) # matched query all along!# current_element should be a list or dict: a containing elementif current_element is not None and not isinstance(current_element, (list, dict)):current_element = None # give it a chance to become what is needed, if allowedif current_element is None and not fixed_parameters["generate_if_not_exists"]:return (False, None)component = fixed_parameters["query"][index_into_query]if component == "*":if current_element is not None and set_multiple:if isinstance(current_element, dict) and len(current_element) != len(value):return (False, None)if isinstance(current_element, list) and len(current_element) > len(value):3 unmodified linesreturn (False, None)# current_element must be a list, extend current_element to the length neededcurrent_element.extend([None] * (len(value) - len(current_element)))if current_element is None or current_element == []:current_element = [None] * (len(value)if set_multipleelse value is Noneor not isinstance(value, list)or len(value) > 0or index_into_query < -1)# now current_element is of size suiting valueif isinstance(current_element, dict):keys = sorted(current_element.keys())17 unmodified linesexcept:continuereturn (any_success or (len(keys) == 0 and index_into_query == -1),current_element,)# component is an index into a list or a key into a dictionaryif indx.match(component):if current_element is None or not isinstance(current_element, list):if not fixed_parameters["generate_if_not_exists"]:return (False, None)current_element = []# current_element is a listcomponent = int(component)if component >= len(current_element):if not fixed_parameters["generate_if_not_exists"]:return (False, None)# extend current_element to the length neededcurrent_element.extend([None] * (component + 1 - len(current_element)))next_current_element = current_element[component]else: # component is a key into a dictionaryif current_element is None or not isinstance(current_element, dict):if not fixed_parameters["generate_if_not_exists"]:return (False, None)current_element = {}if (component not in current_elementand not fixed_parameters["generate_if_not_exists"]22 unmodified linesdef dict_get(dic: dict,query: str,not_exist_ok: bool = False,default: Any = None,):if len(query.strip()) == 0:return dicif dic is None:raise ValueError("Can not get any value from a dic that is None")if isinstance(dic, dict) and query.strip() in dic:return dic[query.strip()]components = validate_query_and_break_to_components(query)if len(components) > 1:try:success, values = get_values(dic, components, -1 * len(components))if not success:2 unmodified linesraise ValueError(f'query "{query}" did not match any item in dict: {dic}')return values1 unmodified lineif not_exist_ok:return defaultraise ValueError(f'query "{query}" did not match any item in dict: {dic}') from e# len(components) == 1if components[0] in dic:return dic[components[0]]if not_exist_ok:return defaultraise ValueError(f'query "{query}" did not match any item in dict: {dic}')# dict_set sets a value, 'value', which by itself, can be a dict or list or scalar, into 'dic', to become the value of45 unmodified linesdic: dict,query: str,value: Any,not_exist_ok=True,set_multiple=False,): # sets dic to its new valueif dic is None or not isinstance(dic, (list, dict)):raise ValueError(f"Can not change dic that is either None or not a dict nor a list. Got dic = {dic}")if query.strip() == "":# change the whole input dic, as dic indeed matches ""if isinstance(dic, dict):if value is None or not isinstance(value, dict):raise ValueError(f"Through an empty query, trying to set a whole new value, {value}, to the whole of dic, {dic}, but value is not a dict")dic.clear()dic.update(value)returnif isinstance(dic, list):if value is None or not isinstance(value, list):raise ValueError(f"Through an empty query, trying to set a whole new value, {value}, to the whole of dic, {dic}, but value is not a list")dic.clear()dic.extend(value)returnif isinstance(dic, dict) and query.strip() in dic:dic[query.strip()] = valuereturnif set_multiple:if value is None or not isinstance(value, list) or len(value) == 0:raise ValueError(f"set_multiple=True, but value, {value}, can not be broken up, as either it is not a list or it is an empty list")components = validate_query_and_break_to_components(query)fixed_parameters = {"query": components,
dict_utils.py+97-56