2023-04-09 19:21:45 +00:00
|
|
|
import collections
|
|
|
|
import re
|
|
|
|
|
2023-04-30 02:24:32 +00:00
|
|
|
from keras_core.api_export import keras_core_export
|
2023-05-03 22:33:40 +00:00
|
|
|
from keras_core.backend.common import global_state
|
2023-04-09 19:21:45 +00:00
|
|
|
|
|
|
|
|
|
|
|
def auto_name(prefix):
|
|
|
|
prefix = to_snake_case(prefix)
|
|
|
|
return uniquify(prefix)
|
|
|
|
|
|
|
|
|
|
|
|
def uniquify(name):
|
2023-04-30 02:24:32 +00:00
|
|
|
object_name_uids = global_state.get_global_attribute(
|
2023-04-30 02:15:11 +00:00
|
|
|
"object_name_uids",
|
|
|
|
default=collections.defaultdict(int),
|
|
|
|
set_to_default=True,
|
|
|
|
)
|
|
|
|
if name in object_name_uids:
|
|
|
|
unique_name = f"{name}_{object_name_uids[name]}"
|
2023-04-09 19:21:45 +00:00
|
|
|
else:
|
|
|
|
unique_name = name
|
2023-04-30 02:15:11 +00:00
|
|
|
object_name_uids[name] += 1
|
2023-04-09 19:21:45 +00:00
|
|
|
return unique_name
|
|
|
|
|
|
|
|
|
|
|
|
def to_snake_case(name):
|
2023-04-16 01:51:10 +00:00
|
|
|
name = re.sub(r"\W+", "", name)
|
2023-04-09 19:21:45 +00:00
|
|
|
name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
|
|
|
|
name = re.sub("([a-z])([A-Z])", r"\1_\2", name).lower()
|
|
|
|
return name
|
|
|
|
|
|
|
|
|
2023-04-30 02:24:32 +00:00
|
|
|
@keras_core_export("keras_core.backend.get_uid")
|
|
|
|
def get_uid(prefix=""):
|
|
|
|
"""Associates a string prefix with an integer counter.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
prefix: String prefix to index.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Unique integer ID.
|
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
>>> get_uid('dense')
|
|
|
|
1
|
|
|
|
>>> get_uid('dense')
|
|
|
|
2
|
|
|
|
"""
|
|
|
|
object_name_uids = global_state.get_global_attribute(
|
|
|
|
"object_name_uids",
|
|
|
|
default=collections.defaultdict(int),
|
|
|
|
set_to_default=True,
|
|
|
|
)
|
|
|
|
object_name_uids[prefix] += 1
|
|
|
|
return object_name_uids[prefix]
|
|
|
|
|
|
|
|
|
2023-04-09 19:21:45 +00:00
|
|
|
def reset_uids():
|
2023-04-30 02:24:32 +00:00
|
|
|
global_state.set_global_attribute(
|
|
|
|
"object_name_uids", collections.defaultdict(int)
|
|
|
|
)
|
2023-04-16 01:51:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
def get_object_name(obj):
|
|
|
|
if hasattr(obj, "name"): # Most Keras objects.
|
|
|
|
return obj.name
|
|
|
|
elif hasattr(obj, "__name__"): # Function.
|
|
|
|
return to_snake_case(obj.__name__)
|
|
|
|
elif hasattr(obj, "__class__"): # Class instance.
|
|
|
|
return to_snake_case(obj.__class__.__name__)
|
|
|
|
return to_snake_case(str(obj))
|