[docs]defget_account_ambiguous_factory(G:nx.DiGraph)->Callable[[str],str]:""" Estimate the correct account name from a possibly ambiguous account name. Uses both literal and japanese phonetic matching. Parameters ---------- G : nx.DiGraph The account tree Returns ------- Callable[[str], str] A function that takes an account name and returns the closest match from the account tree """frompykakasiimportkakasifromrapidfuzzimportfuzzfromrapidfuzz.processimportextractOnekks=kakasi()defprocessor(s:str)->str:s=str(s)returns+"|"+"".join([item["hira"]foriteminkks.convert(s)])accounts=list(nx.get_node_attributes(G,"label").values())returnlambdaaccount:extractOne(account,accounts,processor=processor,scorer=fuzz.QRatio)[0]
[docs]defget_node_from_label(G:nx.DiGraph,label:str,cond:Callable[[Mapping[Any,Any]],bool]|None=None,multiple:bool=False,)->Any:""" Get the node from the label and condition Parameters ---------- G : nx.DiGraph The account tree label : str The label of the node cond : Callable[Mapping[Any, Any], bool] The condition to satisfy multiple : bool, optional Whether to return multiple nodes, by default False Returns ------- Any The node that satisfies the condition """nodes=[nforn,dinG.nodes.data()if(d["label"]==labeland(cond(n)ifcondisnotNoneelseTrue))]ifnotnodes:raiseValueError(f"Node with label {label} not found")ifmultiple:returnnodesiflen(nodes)>1:warnings.warn(f"Multiple nodes with label {label} found",stacklevel=2)returnnodes[0]
[docs]defget_account_type_factory(G:nx.DiGraph,ambiguous:bool=False)->Callable[[str],AccountType|None]:""" Get the account type from the account name Parameters ---------- G : nx.DiGraph The account tree ambiguous : bool, optional Whether to use the ambiguous account name resolver, by default False Returns ------- Callable[[str], AccountType | None] A function that takes an account name and returns the account type or None if the account is not found """nonabstract_nodes={d["label"]:d.get("account_type")for_,dinG.nodes(data=True)ifnotd["abstract"]}ifambiguous:get_amb=get_account_ambiguous_factory(G)def_(account:str)->AccountType|None:ifaccount==SUNDRY:returnAccountType.Sundryifambiguous:account=get_amb(account)returnnonabstract_nodes.get(account)return_