强迫症格式化

This commit is contained in:
liuyulvv 2022-08-05 13:03:08 +08:00
parent 7248ac6750
commit a6eaad2587
17 changed files with 520 additions and 546 deletions

View File

@ -18,9 +18,9 @@ load("//mediapipe/framework/port:build_config.bzl", "mediapipe_proto_library")
load( load(
"//mediapipe/framework/tool:mediapipe_graph.bzl", "//mediapipe/framework/tool:mediapipe_graph.bzl",
"mediapipe_binary_graph", "mediapipe_binary_graph",
) ) # @unused
load("//mediapipe/framework:mediapipe_cc_test.bzl", "mediapipe_cc_test") load("//mediapipe/framework:mediapipe_cc_test.bzl", "mediapipe_cc_test") # @unused
load("//mediapipe/framework:encode_binary_proto.bzl", "encode_binary_proto") load("//mediapipe/framework:encode_binary_proto.bzl", "encode_binary_proto") # @unused
licenses(["notice"]) licenses(["notice"])

View File

@ -1,6 +1,5 @@
"""Build defs for Objectron.""" """Build defs for Objectron."""
def generate_manifest_values(application_id, app_name): def generate_manifest_values(application_id, app_name):
manifest_values = { manifest_values = {
"applicationId": application_id, "applicationId": application_id,

View File

@ -4,15 +4,14 @@
TransitiveDescriptorInfo = provider( TransitiveDescriptorInfo = provider(
"The transitive descriptors from a set of protos.", "The transitive descriptors from a set of protos.",
fields=["descriptors"], fields = ["descriptors"],
) )
DirectDescriptorInfo = provider( DirectDescriptorInfo = provider(
"The direct descriptors from a set of protos.", "The direct descriptors from a set of protos.",
fields=["descriptors"], fields = ["descriptors"],
) )
def calculate_transitive_descriptor_set(actions, deps, output): def calculate_transitive_descriptor_set(actions, deps, output):
"""Calculates the transitive dependencies of the deps. """Calculates the transitive dependencies of the deps.
@ -27,15 +26,13 @@ def calculate_transitive_descriptor_set(actions, deps, output):
# Join all proto descriptors in a single file. # Join all proto descriptors in a single file.
transitive_descriptor_sets = depset( transitive_descriptor_sets = depset(
transitive=[ transitive = [
dep[ProtoInfo].transitive_descriptor_sets dep[ProtoInfo].transitive_descriptor_sets if ProtoInfo in dep else dep[TransitiveDescriptorInfo].descriptors
if ProtoInfo in dep
else dep[TransitiveDescriptorInfo].descriptors
for dep in deps for dep in deps
] ],
) )
args = actions.args() args = actions.args()
args.use_param_file(param_file_arg="--arg-file=%s") args.use_param_file(param_file_arg = "--arg-file=%s")
args.add_all(transitive_descriptor_sets) args.add_all(transitive_descriptor_sets)
# Because `xargs` must take its arguments before the command to execute, # Because `xargs` must take its arguments before the command to execute,
@ -47,18 +44,17 @@ def calculate_transitive_descriptor_set(actions, deps, output):
# We look to see if the first argument begins with a '--arg-file=' and # We look to see if the first argument begins with a '--arg-file=' and
# selectively choose xargs vs. just supplying the arguments to `cat`. # selectively choose xargs vs. just supplying the arguments to `cat`.
actions.run_shell( actions.run_shell(
outputs=[output], outputs = [output],
inputs=transitive_descriptor_sets, inputs = transitive_descriptor_sets,
progress_message="Joining descriptors.", progress_message = "Joining descriptors.",
command=( command = (
'if [[ "$1" =~ ^--arg-file=.* ]]; then xargs "$1" cat; ' 'if [[ "$1" =~ ^--arg-file=.* ]]; then xargs "$1" cat; ' +
+ 'else cat "$@"; fi >{output}'.format(output=output.path) 'else cat "$@"; fi >{output}'.format(output = output.path)
), ),
arguments=[args], arguments = [args],
) )
return output return output
def _transitive_descriptor_set_impl(ctx): def _transitive_descriptor_set_impl(ctx):
"""Combine descriptors for all transitive proto dependencies into one file. """Combine descriptors for all transitive proto dependencies into one file.
@ -70,15 +66,14 @@ def _transitive_descriptor_set_impl(ctx):
just one so that this limitation won't impact you. just one so that this limitation won't impact you.
""" """
output = ctx.actions.declare_file( output = ctx.actions.declare_file(
ctx.attr.name + "-transitive-descriptor-set.proto.bin" ctx.attr.name + "-transitive-descriptor-set.proto.bin",
) )
calculate_transitive_descriptor_set(ctx.actions, ctx.attr.deps, output) calculate_transitive_descriptor_set(ctx.actions, ctx.attr.deps, output)
return DefaultInfo( return DefaultInfo(
files=depset([output]), files = depset([output]),
runfiles=ctx.runfiles(files=[output]), runfiles = ctx.runfiles(files = [output]),
) )
# transitive_descriptor_set outputs a single file containing a binary # transitive_descriptor_set outputs a single file containing a binary
# FileDescriptorSet with all transitive dependencies of the given proto # FileDescriptorSet with all transitive dependencies of the given proto
# dependencies. # dependencies.
@ -90,16 +85,15 @@ def _transitive_descriptor_set_impl(ctx):
# deps = [":my_proto"], # deps = [":my_proto"],
# ) # )
transitive_descriptor_set = rule( transitive_descriptor_set = rule(
attrs={ attrs = {
"deps": attr.label_list(providers=[[ProtoInfo], [TransitiveDescriptorInfo]]), "deps": attr.label_list(providers = [[ProtoInfo], [TransitiveDescriptorInfo]]),
}, },
outputs={ outputs = {
"out": "%{name}-transitive-descriptor-set.proto.bin", "out": "%{name}-transitive-descriptor-set.proto.bin",
}, },
implementation=_transitive_descriptor_set_impl, implementation = _transitive_descriptor_set_impl,
) )
def calculate_direct_descriptor_set(actions, deps, output): def calculate_direct_descriptor_set(actions, deps, output):
"""Calculates the direct dependencies of the deps. """Calculates the direct dependencies of the deps.
@ -113,7 +107,7 @@ def calculate_direct_descriptor_set(actions, deps, output):
""" """
descriptor_set = depset( descriptor_set = depset(
[dep[ProtoInfo].direct_descriptor_set for dep in deps if ProtoInfo in dep], [dep[ProtoInfo].direct_descriptor_set for dep in deps if ProtoInfo in dep],
transitive=[ transitive = [
dep[DirectDescriptorInfo].descriptors dep[DirectDescriptorInfo].descriptors
for dep in deps for dep in deps
if ProtoInfo not in dep if ProtoInfo not in dep
@ -121,22 +115,20 @@ def calculate_direct_descriptor_set(actions, deps, output):
) )
actions.run_shell( actions.run_shell(
outputs=[output], outputs = [output],
inputs=descriptor_set, inputs = descriptor_set,
progress_message="Joining direct descriptors.", progress_message = "Joining direct descriptors.",
command=("cat %s > %s") command = ("cat %s > %s") %
% ( (
" ".join([d.path for d in descriptor_set.to_list()]), " ".join([d.path for d in descriptor_set.to_list()]),
output.path, output.path,
), ),
) )
return output return output
def _direct_descriptor_set_impl(ctx): def _direct_descriptor_set_impl(ctx):
calculate_direct_descriptor_set(ctx.actions, ctx.attr.deps, ctx.outputs.out) calculate_direct_descriptor_set(ctx.actions, ctx.attr.deps, ctx.outputs.out)
# direct_descriptor_set outputs a single file containing a binary # direct_descriptor_set outputs a single file containing a binary
# FileDescriptorSet with all direct, non transitive dependencies of # FileDescriptorSet with all direct, non transitive dependencies of
# the given proto dependencies. # the given proto dependencies.
@ -148,11 +140,11 @@ def _direct_descriptor_set_impl(ctx):
# deps = [":my_proto"], # deps = [":my_proto"],
# ) # )
direct_descriptor_set = rule( direct_descriptor_set = rule(
attrs={ attrs = {
"deps": attr.label_list(providers=[[ProtoInfo], [DirectDescriptorInfo]]), "deps": attr.label_list(providers = [[ProtoInfo], [DirectDescriptorInfo]]),
}, },
outputs={ outputs = {
"out": "%{name}-direct-descriptor-set.proto.bin", "out": "%{name}-direct-descriptor-set.proto.bin",
}, },
implementation=_direct_descriptor_set_impl, implementation = _direct_descriptor_set_impl,
) )

View File

@ -22,26 +22,24 @@ Args:
is_executable: A boolean indicating whether the output file should be executable is_executable: A boolean indicating whether the output file should be executable
""" """
def expand_template_impl(ctx): def expand_template_impl(ctx):
ctx.actions.expand_template( ctx.actions.expand_template(
template=ctx.file.template, template = ctx.file.template,
output=ctx.outputs.out, output = ctx.outputs.out,
substitutions={ substitutions = {
k: ctx.expand_location(v, ctx.attr.data) k: ctx.expand_location(v, ctx.attr.data)
for k, v in ctx.attr.substitutions.items() for k, v in ctx.attr.substitutions.items()
}, },
is_executable=ctx.attr.is_executable, is_executable = ctx.attr.is_executable,
) )
expand_template = rule( expand_template = rule(
implementation=expand_template_impl, implementation = expand_template_impl,
attrs={ attrs = {
"template": attr.label(mandatory=True, allow_single_file=True), "template": attr.label(mandatory = True, allow_single_file = True),
"substitutions": attr.string_dict(mandatory=True), "substitutions": attr.string_dict(mandatory = True),
"out": attr.output(mandatory=True), "out": attr.output(mandatory = True),
"is_executable": attr.bool(default=False, mandatory=False), "is_executable": attr.bool(default = False, mandatory = False),
"data": attr.label_list(allow_files=True), "data": attr.label_list(allow_files = True),
}, },
) )

View File

@ -39,7 +39,6 @@ Args:
PROTOC = "@com_google_protobuf//:protoc" PROTOC = "@com_google_protobuf//:protoc"
def _canonicalize_proto_path_oss(all_protos, genfile_path): def _canonicalize_proto_path_oss(all_protos, genfile_path):
"""For the protos from external repository, canonicalize the proto path and the file name. """For the protos from external repository, canonicalize the proto path and the file name.
@ -50,9 +49,7 @@ def _canonicalize_proto_path_oss(all_protos, genfile_path):
proto_file_names = [] proto_file_names = []
for s in all_protos.to_list(): for s in all_protos.to_list():
if s.path.startswith(genfile_path): if s.path.startswith(genfile_path):
repo_name, _, file_name = s.path[ repo_name, _, file_name = s.path[len(genfile_path + "/external/"):].partition("/")
len(genfile_path + "/external/") :
].partition("/")
# handle virtual imports # handle virtual imports
if file_name.startswith("_virtual_imports"): if file_name.startswith("_virtual_imports"):
@ -64,7 +61,6 @@ def _canonicalize_proto_path_oss(all_protos, genfile_path):
proto_file_names.append(s.path) proto_file_names.append(s.path)
return ([" --proto_path=" + path for path in proto_paths], proto_file_names) return ([" --proto_path=" + path for path in proto_paths], proto_file_names)
def _get_proto_provider(dep): def _get_proto_provider(dep):
"""Get the provider for protocol buffers from a dependnecy. """Get the provider for protocol buffers from a dependnecy.
@ -81,79 +77,78 @@ def _get_proto_provider(dep):
else: else:
fail("cannot happen, rule definition requires .proto or ProtoInfo") fail("cannot happen, rule definition requires .proto or ProtoInfo")
def _encode_binary_proto_impl(ctx): def _encode_binary_proto_impl(ctx):
"""Implementation of the encode_binary_proto rule.""" """Implementation of the encode_binary_proto rule."""
all_protos = depset( all_protos = depset(
direct=[], direct = [],
transitive=[ transitive = [
_get_proto_provider(dep).transitive_sources for dep in ctx.attr.deps _get_proto_provider(dep).transitive_sources
for dep in ctx.attr.deps
], ],
) )
textpb = ctx.file.input textpb = ctx.file.input
binarypb = ctx.outputs.output or ctx.actions.declare_file( binarypb = ctx.outputs.output or ctx.actions.declare_file(
textpb.basename.rsplit(".", 1)[0] + ".binarypb", textpb.basename.rsplit(".", 1)[0] + ".binarypb",
sibling=textpb, sibling = textpb,
) )
path_list, file_list = _canonicalize_proto_path_oss( path_list, file_list = _canonicalize_proto_path_oss(
all_protos, ctx.genfiles_dir.path all_protos,
ctx.genfiles_dir.path,
) )
# Note: the combination of absolute_paths and proto_path, as well as the exact # Note: the combination of absolute_paths and proto_path, as well as the exact
# order of gendir before ., is needed for the proto compiler to resolve # order of gendir before ., is needed for the proto compiler to resolve
# import statements that reference proto files produced by a genrule. # import statements that reference proto files produced by a genrule.
ctx.actions.run_shell( ctx.actions.run_shell(
tools=all_protos.to_list() + [textpb, ctx.executable._proto_compiler], tools = all_protos.to_list() + [textpb, ctx.executable._proto_compiler],
outputs=[binarypb], outputs = [binarypb],
command=" ".join( command = " ".join(
[ [
ctx.executable._proto_compiler.path, ctx.executable._proto_compiler.path,
"--encode=" + ctx.attr.message_type, "--encode=" + ctx.attr.message_type,
"--proto_path=" + ctx.genfiles_dir.path, "--proto_path=" + ctx.genfiles_dir.path,
"--proto_path=" + ctx.bin_dir.path, "--proto_path=" + ctx.bin_dir.path,
"--proto_path=.", "--proto_path=.",
] ] +
+ path_list path_list +
+ file_list file_list +
+ ["<", textpb.path, ">", binarypb.path], ["<", textpb.path, ">", binarypb.path],
), ),
mnemonic="EncodeProto", mnemonic = "EncodeProto",
) )
output_depset = depset([binarypb]) output_depset = depset([binarypb])
return [ return [
DefaultInfo( DefaultInfo(
files=output_depset, files = output_depset,
data_runfiles=ctx.runfiles(transitive_files=output_depset), data_runfiles = ctx.runfiles(transitive_files = output_depset),
) ),
] ]
_encode_binary_proto = rule( _encode_binary_proto = rule(
implementation=_encode_binary_proto_impl, implementation = _encode_binary_proto_impl,
attrs={ attrs = {
"_proto_compiler": attr.label( "_proto_compiler": attr.label(
executable=True, executable = True,
default=Label(PROTOC), default = Label(PROTOC),
cfg="host", cfg = "host",
), ),
"deps": attr.label_list( "deps": attr.label_list(
providers=[[ProtoInfo], ["proto"]], providers = [[ProtoInfo], ["proto"]],
), ),
"input": attr.label( "input": attr.label(
mandatory=True, mandatory = True,
allow_single_file=True, allow_single_file = True,
), ),
"message_type": attr.string( "message_type": attr.string(
mandatory=True, mandatory = True,
), ),
"output": attr.output(), "output": attr.output(),
}, },
) )
def encode_binary_proto(name, input, message_type, deps, **kwargs): def encode_binary_proto(name, input, message_type, deps, **kwargs):
if type(input) == type("string"): if type(input) == type("string"):
input_label = input input_label = input
@ -169,18 +164,21 @@ def encode_binary_proto(name, input, message_type, deps, **kwargs):
fail("input should be a string or a dict, got %s" % input) fail("input should be a string or a dict, got %s" % input)
_encode_binary_proto( _encode_binary_proto(
name=name, input=input_label, message_type=message_type, deps=deps, **kwargs name = name,
input = input_label,
message_type = message_type,
deps = deps,
**kwargs
) )
def _generate_proto_descriptor_set_impl(ctx): def _generate_proto_descriptor_set_impl(ctx):
"""Implementation of the generate_proto_descriptor_set rule.""" """Implementation of the generate_proto_descriptor_set rule."""
all_protos = depset( all_protos = depset(
transitive=[ transitive = [
_get_proto_provider(dep).transitive_sources _get_proto_provider(dep).transitive_sources
for dep in ctx.attr.deps for dep in ctx.attr.deps
if ProtoInfo in dep or hasattr(dep, "proto") if ProtoInfo in dep or hasattr(dep, "proto")
] ],
) )
descriptor = ctx.outputs.output descriptor = ctx.outputs.output
@ -188,32 +186,31 @@ def _generate_proto_descriptor_set_impl(ctx):
# order of gendir before ., is needed for the proto compiler to resolve # order of gendir before ., is needed for the proto compiler to resolve
# import statements that reference proto files produced by a genrule. # import statements that reference proto files produced by a genrule.
ctx.actions.run( ctx.actions.run(
inputs=all_protos, inputs = all_protos,
tools=[ctx.executable._proto_compiler], tools = [ctx.executable._proto_compiler],
outputs=[descriptor], outputs = [descriptor],
executable=ctx.executable._proto_compiler, executable = ctx.executable._proto_compiler,
arguments=[ arguments = [
"--descriptor_set_out=%s" % descriptor.path, "--descriptor_set_out=%s" % descriptor.path,
"--proto_path=" + ctx.genfiles_dir.path, "--proto_path=" + ctx.genfiles_dir.path,
"--proto_path=" + ctx.bin_dir.path, "--proto_path=" + ctx.bin_dir.path,
"--proto_path=.", "--proto_path=.",
] ] +
+ [s.path for s in all_protos.to_list()], [s.path for s in all_protos.to_list()],
mnemonic="GenerateProtoDescriptor", mnemonic = "GenerateProtoDescriptor",
) )
generate_proto_descriptor_set = rule( generate_proto_descriptor_set = rule(
implementation=_generate_proto_descriptor_set_impl, implementation = _generate_proto_descriptor_set_impl,
attrs={ attrs = {
"_proto_compiler": attr.label( "_proto_compiler": attr.label(
executable=True, executable = True,
default=Label(PROTOC), default = Label(PROTOC),
cfg="host", cfg = "host",
), ),
"deps": attr.label_list( "deps": attr.label_list(
providers=[[ProtoInfo], ["proto"]], providers = [[ProtoInfo], ["proto"]],
), ),
}, },
outputs={"output": "%{name}.proto.bin"}, outputs = {"output": "%{name}.proto.bin"},
) )

View File

@ -2,41 +2,39 @@
DEFAULT_ADDITIONAL_TEST_DEPS = [] DEFAULT_ADDITIONAL_TEST_DEPS = []
def mediapipe_cc_test( def mediapipe_cc_test(
name, name,
srcs=[], srcs = [],
data=[], data = [],
deps=[], deps = [],
size=None, size = None,
tags=[], tags = [],
timeout=None, timeout = None,
args=[], args = [],
additional_deps=DEFAULT_ADDITIONAL_TEST_DEPS, additional_deps = DEFAULT_ADDITIONAL_TEST_DEPS,
platforms=["linux", "android", "ios", "wasm"], platforms = ["linux", "android", "ios", "wasm"],
exclude_platforms=None, exclude_platforms = None,
# ios_unit_test arguments # ios_unit_test arguments
ios_minimum_os_version="9.0", ios_minimum_os_version = "9.0",
# android_cc_test arguments # android_cc_test arguments
open_gl_driver=None, open_gl_driver = None,
emulator_mini_boot=True, emulator_mini_boot = True,
requires_full_emulation=True, requires_full_emulation = True,
# wasm_web_test arguments # wasm_web_test arguments
browsers=None, browsers = None,
**kwargs **kwargs):
):
native.cc_library( native.cc_library(
name=name + "_lib", name = name + "_lib",
testonly=1, testonly = 1,
srcs=srcs, srcs = srcs,
data=data, data = data,
deps=deps + additional_deps, deps = deps + additional_deps,
alwayslink=1, alwayslink = 1,
) )
native.cc_test( native.cc_test(
name=name, name = name,
size=size, size = size,
timeout=timeout, timeout = timeout,
deps=[":{}_lib".format(name)], deps = [":{}_lib".format(name)],
) )

View File

@ -45,7 +45,6 @@ Args
load("//mediapipe/framework/tool:build_defs.bzl", "clean_dep") load("//mediapipe/framework/tool:build_defs.bzl", "clean_dep")
def _mediapipe_register_type_generate_cc_impl(ctx): def _mediapipe_register_type_generate_cc_impl(ctx):
"""Generate a cc file that registers types with mediapipe.""" """Generate a cc file that registers types with mediapipe."""
file_data_template = """ file_data_template = """
@ -62,65 +61,66 @@ def _mediapipe_register_type_generate_cc_impl(ctx):
if " " in registration_type: if " " in registration_type:
fail( fail(
( (
'registration type "{}" should be fully qualified ' 'registration type "{}" should be fully qualified ' +
+ "and must not include spaces" "and must not include spaces"
).format(registration_type) ).format(registration_type),
) )
registration_lines.append( registration_lines.append(
"#define TEMP_MP_TYPE {}".format(registration_type), "#define TEMP_MP_TYPE {}".format(registration_type),
) )
registration_lines.append( registration_lines.append(
( (
"MEDIAPIPE_REGISTER_TYPE(\n" "MEDIAPIPE_REGISTER_TYPE(\n" +
+ " TEMP_MP_TYPE,\n" " TEMP_MP_TYPE,\n" +
+ ' "{}",\n'.format(registration_type) ' "{}",\n'.format(registration_type) +
+ " nullptr, nullptr);\n" " nullptr, nullptr);\n"
), ),
) )
registration_lines.append("#undef TEMP_MP_TYPE") registration_lines.append("#undef TEMP_MP_TYPE")
file_data = file_data_template.format( file_data = file_data_template.format(
include_headers="\n".join(header_lines), include_headers = "\n".join(header_lines),
registration_commands="\n".join(registration_lines), registration_commands = "\n".join(registration_lines),
) )
ctx.actions.write(ctx.outputs.output, file_data) ctx.actions.write(ctx.outputs.output, file_data)
mediapipe_register_type_generate_cc = rule( mediapipe_register_type_generate_cc = rule(
implementation=_mediapipe_register_type_generate_cc_impl, implementation = _mediapipe_register_type_generate_cc_impl,
attrs={ attrs = {
"deps": attr.label_list(), "deps": attr.label_list(),
"types": attr.string_list( "types": attr.string_list(
mandatory=True, mandatory = True,
), ),
"include_headers": attr.string_list( "include_headers": attr.string_list(
mandatory=True, mandatory = True,
), ),
"output": attr.output(), "output": attr.output(),
}, },
) )
def mediapipe_register_type( def mediapipe_register_type(
base_name, types, deps=[], include_headers=[], visibility=["//visibility:public"] base_name,
): types,
deps = [],
include_headers = [],
visibility = ["//visibility:public"]):
mediapipe_register_type_generate_cc( mediapipe_register_type_generate_cc(
name=base_name + "_registration_cc", name = base_name + "_registration_cc",
types=types, types = types,
include_headers=include_headers, include_headers = include_headers,
output=base_name + "_registration.cc", output = base_name + "_registration.cc",
) )
native.cc_library( native.cc_library(
name=base_name + "_registration", name = base_name + "_registration",
srcs=[base_name + "_registration.cc"], srcs = [base_name + "_registration.cc"],
deps=depset( deps = depset(
deps deps +
+ [ [
clean_dep("//mediapipe/framework:type_map"), clean_dep("//mediapipe/framework:type_map"),
] ],
), ),
visibility=visibility, visibility = visibility,
alwayslink=1, alwayslink = 1,
) )

View File

@ -12,23 +12,22 @@ def _config_setting_always_true(name, visibility):
name_on = name + "_stamp_binary_on_check" name_on = name + "_stamp_binary_on_check"
name_off = name + "_stamp_binary_off_check" name_off = name + "_stamp_binary_off_check"
native.config_setting( native.config_setting(
name=name_on, name = name_on,
values={"stamp": "1"}, values = {"stamp": "1"},
) )
native.config_setting( native.config_setting(
name=name_off, name = name_off,
values={"stamp": "0"}, values = {"stamp": "0"},
) )
return selects.config_setting_group( return selects.config_setting_group(
name=name, name = name,
visibility=visibility, visibility = visibility,
match_any=[ match_any = [
":" + name_on, ":" + name_on,
":" + name_off, ":" + name_off,
], ],
) )
def _config_setting_always_false(name, visibility): def _config_setting_always_false(name, visibility):
"""Returns a config_setting with the given name that's always false. """Returns a config_setting with the given name that's always false.
@ -38,44 +37,42 @@ def _config_setting_always_false(name, visibility):
name_on = name + "_stamp_binary_on_check" name_on = name + "_stamp_binary_on_check"
name_off = name + "_stamp_binary_off_check" name_off = name + "_stamp_binary_off_check"
native.config_setting( native.config_setting(
name=name_on, name = name_on,
values={"stamp": "1"}, values = {"stamp": "1"},
) )
native.config_setting( native.config_setting(
name=name_off, name = name_off,
values={"stamp": "0"}, values = {"stamp": "0"},
) )
return selects.config_setting_group( return selects.config_setting_group(
name=name, name = name,
visibility=visibility, visibility = visibility,
match_all=[ match_all = [
":" + name_on, ":" + name_on,
":" + name_off, ":" + name_off,
], ],
) )
def _config_setting_negation(name, negate, visibility = None):
def _config_setting_negation(name, negate, visibility=None):
_config_setting_always_true( _config_setting_always_true(
name=name + "_true", name = name + "_true",
visibility=visibility, visibility = visibility,
) )
_config_setting_always_false( _config_setting_always_false(
name=name + "_false", name = name + "_false",
visibility=visibility, visibility = visibility,
) )
native.alias( native.alias(
name=name, name = name,
actual=select( actual = select(
{ {
"//conditions:default": ":%s_true" % name, "//conditions:default": ":%s_true" % name,
negate: ":%s_false" % name, negate: ":%s_false" % name,
} },
), ),
visibility=visibility, visibility = visibility,
) )
more_selects = struct( more_selects = struct(
config_setting_negation=_config_setting_negation, config_setting_negation = _config_setting_negation,
) )

View File

@ -6,18 +6,15 @@
load("@com_google_protobuf//:protobuf.bzl", "cc_proto_library", "py_proto_library") load("@com_google_protobuf//:protobuf.bzl", "cc_proto_library", "py_proto_library")
load("//mediapipe/framework/tool:mediapipe_graph.bzl", "mediapipe_options_library") load("//mediapipe/framework/tool:mediapipe_graph.bzl", "mediapipe_options_library")
def provided_args(**kwargs): def provided_args(**kwargs):
"""Returns the keyword arguments omitting None arguments.""" """Returns the keyword arguments omitting None arguments."""
return {k: v for k, v in kwargs.items() if v != None} return {k: v for k, v in kwargs.items() if v != None}
def replace_suffix(string, old, new): def replace_suffix(string, old, new):
"""Returns a string with an old suffix replaced by a new suffix.""" """Returns a string with an old suffix replaced by a new suffix."""
return string.endswith(old) and string[: -len(old)] + new or string return string.endswith(old) and string[:-len(old)] + new or string
def replace_deps(deps, old, new, drop_google_protobuf = True):
def replace_deps(deps, old, new, drop_google_protobuf=True):
"""Returns deps with an old suffix replaced by a new suffix. """Returns deps with an old suffix replaced by a new suffix.
Args: Args:
@ -34,27 +31,25 @@ def replace_deps(deps, old, new, drop_google_protobuf=True):
deps = [replace_suffix(dep, old, new) for dep in deps] deps = [replace_suffix(dep, old, new) for dep in deps]
return deps return deps
# TODO: load this macro from a common helper file. # TODO: load this macro from a common helper file.
def mediapipe_proto_library( def mediapipe_proto_library(
name, name,
srcs, srcs,
deps=[], deps = [],
exports=None, exports = None,
visibility=None, visibility = None,
testonly=None, testonly = None,
compatible_with=None, compatible_with = None,
def_proto=True, def_proto = True,
def_cc_proto=True, def_cc_proto = True,
def_py_proto=True, def_py_proto = True,
def_java_lite_proto=True, def_java_lite_proto = True,
def_portable_proto=True, def_portable_proto = True,
def_objc_proto=True, def_objc_proto = True,
def_java_proto=True, def_java_proto = True,
def_jspb_proto=True, def_jspb_proto = True,
def_options_lib=True, def_options_lib = True,
portable_deps=None, portable_deps = None):
):
"""Defines the proto_library targets needed for all mediapipe platforms. """Defines the proto_library targets needed for all mediapipe platforms.
Args: Args:
@ -82,7 +77,7 @@ def mediapipe_proto_library(
def_java_proto, def_java_proto,
def_jspb_proto, def_jspb_proto,
portable_deps, portable_deps,
] ] # @unused
# The proto_library targets for the compiled ".proto" source files. # The proto_library targets for the compiled ".proto" source files.
proto_deps = [":" + name] proto_deps = [":" + name]
@ -90,13 +85,13 @@ def mediapipe_proto_library(
if def_proto: if def_proto:
native.proto_library( native.proto_library(
**provided_args( **provided_args(
name=name, name = name,
srcs=srcs, srcs = srcs,
deps=deps, deps = deps,
exports=exports, exports = exports,
visibility=visibility, visibility = visibility,
testonly=testonly, testonly = testonly,
compatible_with=compatible_with, compatible_with = compatible_with,
) )
) )
@ -104,12 +99,12 @@ def mediapipe_proto_library(
cc_deps = replace_deps(deps, "_proto", "_cc_proto", False) cc_deps = replace_deps(deps, "_proto", "_cc_proto", False)
mediapipe_cc_proto_library( mediapipe_cc_proto_library(
**provided_args( **provided_args(
name=replace_suffix(name, "_proto", "_cc_proto"), name = replace_suffix(name, "_proto", "_cc_proto"),
srcs=srcs, srcs = srcs,
deps=proto_deps, deps = proto_deps,
cc_deps=cc_deps, cc_deps = cc_deps,
visibility=visibility, visibility = visibility,
testonly=testonly, testonly = testonly,
) )
) )
@ -117,24 +112,24 @@ def mediapipe_proto_library(
py_deps = replace_deps(deps, "_proto", "_py_pb2") py_deps = replace_deps(deps, "_proto", "_py_pb2")
mediapipe_py_proto_library( mediapipe_py_proto_library(
**provided_args( **provided_args(
name=replace_suffix(name, "_proto", "_py_pb2"), name = replace_suffix(name, "_proto", "_py_pb2"),
srcs=srcs, srcs = srcs,
proto_deps=proto_deps, proto_deps = proto_deps,
py_proto_deps=py_deps, py_proto_deps = py_deps,
api_version=2, api_version = 2,
visibility=visibility, visibility = visibility,
testonly=testonly, testonly = testonly,
) )
) )
if def_java_lite_proto: if def_java_lite_proto:
native.java_lite_proto_library( native.java_lite_proto_library(
**provided_args( **provided_args(
name=replace_suffix(name, "_proto", "_java_proto_lite"), name = replace_suffix(name, "_proto", "_java_proto_lite"),
deps=proto_deps, deps = proto_deps,
visibility=visibility, visibility = visibility,
testonly=testonly, testonly = testonly,
compatible_with=compatible_with, compatible_with = compatible_with,
) )
) )
@ -142,25 +137,23 @@ def mediapipe_proto_library(
cc_deps = replace_deps(deps, "_proto", "_cc_proto") cc_deps = replace_deps(deps, "_proto", "_cc_proto")
mediapipe_options_library( mediapipe_options_library(
**provided_args( **provided_args(
name=replace_suffix(name, "_proto", "_options_lib"), name = replace_suffix(name, "_proto", "_options_lib"),
proto_lib=name, proto_lib = name,
deps=cc_deps, deps = cc_deps,
visibility=visibility, visibility = visibility,
testonly=testonly, testonly = testonly,
compatible_with=compatible_with, compatible_with = compatible_with,
) )
) )
def mediapipe_py_proto_library( def mediapipe_py_proto_library(
name, name,
srcs, srcs,
visibility=None, visibility = None,
py_proto_deps=[], py_proto_deps = [],
proto_deps=None, proto_deps = None,
api_version=None, api_version = None,
testonly=0, testonly = 0):
):
"""Generate py_proto_library for mediapipe open source version. """Generate py_proto_library for mediapipe open source version.
Args: Args:
@ -172,23 +165,26 @@ def mediapipe_py_proto_library(
proto_deps: a list of dependency labels for bazel use. proto_deps: a list of dependency labels for bazel use.
testonly: test only proto or not. testonly: test only proto or not.
""" """
_ignore = [api_version, proto_deps] _ignore = [api_version, proto_deps] # @unused
py_proto_library( py_proto_library(
**provided_args( **provided_args(
name=name, name = name,
srcs=srcs, srcs = srcs,
visibility=visibility, visibility = visibility,
default_runtime="@com_google_protobuf//:protobuf_python", default_runtime = "@com_google_protobuf//:protobuf_python",
protoc="@com_google_protobuf//:protoc", protoc = "@com_google_protobuf//:protoc",
deps=py_proto_deps + ["@com_google_protobuf//:protobuf_python"], deps = py_proto_deps + ["@com_google_protobuf//:protobuf_python"],
testonly=testonly, testonly = testonly,
) )
) )
def mediapipe_cc_proto_library( def mediapipe_cc_proto_library(
name, srcs, visibility=None, deps=[], cc_deps=[], testonly=0 name,
): srcs,
visibility = None,
deps = [],
cc_deps = [],
testonly = 0):
"""Generate cc_proto_library for mediapipe open source version. """Generate cc_proto_library for mediapipe open source version.
Args: Args:
@ -196,19 +192,20 @@ def mediapipe_cc_proto_library(
srcs: the .proto files of the cc_proto_library for Bazel use. srcs: the .proto files of the cc_proto_library for Bazel use.
visibility: visibility of this target. visibility: visibility of this target.
deps: a list of dependency labels for Bazel use; must be cc_proto_library. deps: a list of dependency labels for Bazel use; must be cc_proto_library.
cc_deps:
testonly: test only proto or not. testonly: test only proto or not.
""" """
_ignore = [deps] _ignore = [deps] # @unused
cc_proto_library( cc_proto_library(
**provided_args( **provided_args(
name=name, name = name,
srcs=srcs, srcs = srcs,
visibility=visibility, visibility = visibility,
deps=cc_deps, deps = cc_deps,
testonly=testonly, testonly = testonly,
cc_libs=["@com_google_protobuf//:protobuf"], cc_libs = ["@com_google_protobuf//:protobuf"],
protoc="@com_google_protobuf//:protoc", protoc = "@com_google_protobuf//:protoc",
default_runtime="@com_google_protobuf//:protobuf", default_runtime = "@com_google_protobuf//:protobuf",
alwayslink=1, alwayslink = 1,
) )
) )

View File

@ -5,7 +5,6 @@
def clean_dep(dep): def clean_dep(dep):
return str(Label(dep)) return str(Label(dep))
# Sanitize a list of dependencies so that they work correctly from targets that # Sanitize a list of dependencies so that they work correctly from targets that
# include MediaPipe as an external dependency. # include MediaPipe as an external dependency.
def clean_deps(dep_list): def clean_deps(dep_list):

View File

@ -17,8 +17,8 @@ Example:
load( load(
"//mediapipe/framework:encode_binary_proto.bzl", "//mediapipe/framework:encode_binary_proto.bzl",
"encode_binary_proto", "encode_binary_proto", # @unused
"generate_proto_descriptor_set", "generate_proto_descriptor_set", # @unused
) )
load("//mediapipe/framework:transitive_protos.bzl", "transitive_protos") load("//mediapipe/framework:transitive_protos.bzl", "transitive_protos")
load("//mediapipe/framework/deps:expand_template.bzl", "expand_template") load("//mediapipe/framework/deps:expand_template.bzl", "expand_template")
@ -33,11 +33,23 @@ load(
"cc_library_with_tflite", "cc_library_with_tflite",
) )
def mediapipe_binary_graph( def mediapipe_binary_graph(
name, graph=None, output_name=None, deps=[], testonly=False, **kwargs name,
): graph = None,
"""Converts a graph from text format to binary format.""" output_name = None,
deps = [],
testonly = False,
**kwargs): # @unused
"""Converts a graph from text format to binary format.
Args:
name:
graph:
output_name:
deps:
testonly:
**kwargs:
"""
if not graph: if not graph:
fail("No input graph file specified.") fail("No input graph file specified.")
@ -46,42 +58,41 @@ def mediapipe_binary_graph(
fail("Must specify the output_name.") fail("Must specify the output_name.")
transitive_protos( transitive_protos(
name=name + "_gather_cc_protos", name = name + "_gather_cc_protos",
deps=deps, deps = deps,
testonly=testonly, testonly = testonly,
) )
# Compile a simple proto parser binary using the deps. # Compile a simple proto parser binary using the deps.
native.cc_binary( native.cc_binary(
name=name + "_text_to_binary_graph", name = name + "_text_to_binary_graph",
visibility=["//visibility:private"], visibility = ["//visibility:private"],
deps=[ deps = [
clean_dep("//mediapipe/framework/tool:text_to_binary_graph"), clean_dep("//mediapipe/framework/tool:text_to_binary_graph"),
name + "_gather_cc_protos", name + "_gather_cc_protos",
], ],
tags=["manual"], tags = ["manual"],
testonly=testonly, testonly = testonly,
) )
# Invoke the proto parser binary. # Invoke the proto parser binary.
native.genrule( native.genrule(
name=name, name = name,
srcs=[graph], srcs = [graph],
outs=[output_name], outs = [output_name],
cmd=( cmd = (
"$(location " "$(location " +
+ name name +
+ "_text_to_binary_graph" "_text_to_binary_graph" +
+ ") " ") " +
+ ("--proto_source=$(location %s) " % graph) ("--proto_source=$(location %s) " % graph) +
+ ('--proto_output="$@" ') ('--proto_output="$@" ')
), ),
tools=[name + "_text_to_binary_graph"], tools = [name + "_text_to_binary_graph"],
testonly=testonly, testonly = testonly,
) )
def data_as_c_string(name, srcs, outs = None, testonly = None):
def data_as_c_string(name, srcs, outs=None, testonly=None):
"""Encodes the data from a file as a C string literal. """Encodes the data from a file as a C string literal.
This produces a text file containing the quoted C string literal. It can be This produces a text file containing the quoted C string literal. It can be
@ -100,25 +111,23 @@ def data_as_c_string(name, srcs, outs=None, testonly=None):
outs = [name] outs = [name]
encode_as_c_string = clean_dep("//mediapipe/framework/tool:encode_as_c_string") encode_as_c_string = clean_dep("//mediapipe/framework/tool:encode_as_c_string")
native.genrule( native.genrule(
name=name, name = name,
srcs=srcs, srcs = srcs,
outs=outs, outs = outs,
cmd='$(location %s) "$<" > "$@"' % encode_as_c_string, cmd = '$(location %s) "$<" > "$@"' % encode_as_c_string,
tools=[encode_as_c_string], tools = [encode_as_c_string],
testonly=testonly, testonly = testonly,
) )
def mediapipe_simple_subgraph( def mediapipe_simple_subgraph(
name, name,
register_as, register_as,
graph, graph,
deps=[], deps = [],
tflite_deps=None, tflite_deps = None,
visibility=None, visibility = None,
testonly=None, testonly = None,
**kwargs **kwargs):
):
"""Defines a registered subgraph for inclusion in other graphs. """Defines a registered subgraph for inclusion in other graphs.
Args: Args:
@ -134,69 +143,68 @@ def mediapipe_simple_subgraph(
""" """
graph_base_name = name graph_base_name = name
mediapipe_binary_graph( mediapipe_binary_graph(
name=name + "_graph", name = name + "_graph",
graph=graph, graph = graph,
output_name=graph_base_name + ".binarypb", output_name = graph_base_name + ".binarypb",
deps=deps, deps = deps,
testonly=testonly, testonly = testonly,
) )
data_as_c_string( data_as_c_string(
name=name + "_inc", name = name + "_inc",
srcs=[graph_base_name + ".binarypb"], srcs = [graph_base_name + ".binarypb"],
outs=[graph_base_name + ".inc"], outs = [graph_base_name + ".inc"],
) )
# cc_library for a linked mediapipe graph. # cc_library for a linked mediapipe graph.
expand_template( expand_template(
name=name + "_linked_cc", name = name + "_linked_cc",
template=clean_dep("//mediapipe/framework/tool:simple_subgraph_template.cc"), template = clean_dep("//mediapipe/framework/tool:simple_subgraph_template.cc"),
out=name + "_linked.cc", out = name + "_linked.cc",
substitutions={ substitutions = {
"{{SUBGRAPH_CLASS_NAME}}": register_as, "{{SUBGRAPH_CLASS_NAME}}": register_as,
"{{SUBGRAPH_INC_FILE_PATH}}": native.package_name() "{{SUBGRAPH_INC_FILE_PATH}}": native.package_name() +
+ "/" "/" +
+ graph_base_name graph_base_name +
+ ".inc", ".inc",
}, },
testonly=testonly, testonly = testonly,
) )
if not tflite_deps: if not tflite_deps:
native.cc_library( native.cc_library(
name=name, name = name,
srcs=[ srcs = [
name + "_linked.cc", name + "_linked.cc",
graph_base_name + ".inc", graph_base_name + ".inc",
], ],
deps=[ deps = [
clean_dep("//mediapipe/framework:calculator_framework"), clean_dep("//mediapipe/framework:calculator_framework"),
clean_dep("//mediapipe/framework:subgraph"), clean_dep("//mediapipe/framework:subgraph"),
] ] +
+ deps, deps,
alwayslink=1, alwayslink = 1,
visibility=visibility, visibility = visibility,
testonly=testonly, testonly = testonly,
**kwargs **kwargs
) )
else: else:
cc_library_with_tflite( cc_library_with_tflite(
name=name, name = name,
srcs=[ srcs = [
name + "_linked.cc", name + "_linked.cc",
graph_base_name + ".inc", graph_base_name + ".inc",
], ],
tflite_deps=tflite_deps, tflite_deps = tflite_deps,
deps=[ deps = [
clean_dep("//mediapipe/framework:calculator_framework"), clean_dep("//mediapipe/framework:calculator_framework"),
clean_dep("//mediapipe/framework:subgraph"), clean_dep("//mediapipe/framework:subgraph"),
] ] +
+ deps, deps,
alwayslink=1, alwayslink = 1,
visibility=visibility, visibility = visibility,
testonly=testonly, testonly = testonly,
**kwargs **kwargs
) )
def mediapipe_reexport_library(name, actual, **kwargs): def mediapipe_reexport_library(name, actual, **kwargs):
"""Defines a cc_library that exports the headers of other libraries. """Defines a cc_library that exports the headers of other libraries.
@ -214,12 +222,15 @@ def mediapipe_reexport_library(name, actual, **kwargs):
actual: the targets to combine and export together. actual: the targets to combine and export together.
**kwargs: Remaining keyword args, forwarded to cc_library. **kwargs: Remaining keyword args, forwarded to cc_library.
""" """
native.cc_library(name=name, textual_hdrs=actual, deps=actual, **kwargs) native.cc_library(name = name, textual_hdrs = actual, deps = actual, **kwargs)
def mediapipe_options_library( def mediapipe_options_library(
name, proto_lib, deps=[], visibility=None, testonly=None, **kwargs name,
): proto_lib,
deps = [],
visibility = None,
testonly = None,
**kwargs):
"""Registers options protobuf metadata for defining options packets. """Registers options protobuf metadata for defining options packets.
Args: Args:
@ -232,87 +243,87 @@ def mediapipe_options_library(
""" """
transitive_descriptor_set( transitive_descriptor_set(
name=proto_lib + "_transitive", name = proto_lib + "_transitive",
deps=[proto_lib], deps = [proto_lib],
testonly=testonly, testonly = testonly,
) )
direct_descriptor_set( direct_descriptor_set(
name=proto_lib + "_direct", name = proto_lib + "_direct",
deps=[proto_lib], deps = [proto_lib],
testonly=testonly, testonly = testonly,
) )
data_as_c_string( data_as_c_string(
name=name + "_inc", name = name + "_inc",
srcs=[proto_lib + "_transitive-transitive-descriptor-set.proto.bin"], srcs = [proto_lib + "_transitive-transitive-descriptor-set.proto.bin"],
outs=[proto_lib + "_descriptors.inc"], outs = [proto_lib + "_descriptors.inc"],
) )
native.genrule( native.genrule(
name=name + "_type_name", name = name + "_type_name",
srcs=[proto_lib + "_direct-direct-descriptor-set.proto.bin"], srcs = [proto_lib + "_direct-direct-descriptor-set.proto.bin"],
outs=[name + "_type_name.h"], outs = [name + "_type_name.h"],
cmd=( cmd = (
"$(location " "$(location " +
+ "//mediapipe/framework/tool:message_type_util" "//mediapipe/framework/tool:message_type_util" +
+ ") " ") " +
+ ( (
"--input_path=$(location %s) " "--input_path=$(location %s) " %
% (proto_lib + "_direct-direct-descriptor-set.proto.bin") (proto_lib + "_direct-direct-descriptor-set.proto.bin")
) ) +
+ ( (
"--root_type_macro_output_path=$(location %s) " "--root_type_macro_output_path=$(location %s) " %
% (name + "_type_name.h") (name + "_type_name.h")
) )
), ),
tools=["//mediapipe/framework/tool:message_type_util"], tools = ["//mediapipe/framework/tool:message_type_util"],
visibility=visibility, visibility = visibility,
testonly=testonly, testonly = testonly,
) )
expand_template( expand_template(
name=name + "_cc", name = name + "_cc",
template=clean_dep("//mediapipe/framework/tool:options_lib_template.cc"), template = clean_dep("//mediapipe/framework/tool:options_lib_template.cc"),
out=name + ".cc", out = name + ".cc",
substitutions={ substitutions = {
"{{MESSAGE_NAME_HEADER}}": native.package_name() "{{MESSAGE_NAME_HEADER}}": native.package_name() +
+ "/" "/" +
+ name name +
+ "_type_name.h", "_type_name.h",
"{{MESSAGE_PROTO_HEADER}}": native.package_name() "{{MESSAGE_PROTO_HEADER}}": native.package_name() +
+ "/" "/" +
+ proto_lib.replace("_proto", ".pb.h"), proto_lib.replace("_proto", ".pb.h"),
"{{DESCRIPTOR_INC_FILE_PATH}}": native.package_name() "{{DESCRIPTOR_INC_FILE_PATH}}": native.package_name() +
+ "/" "/" +
+ proto_lib proto_lib +
+ "_descriptors.inc", "_descriptors.inc",
}, },
testonly=testonly, testonly = testonly,
) )
native.cc_library( native.cc_library(
name=proto_lib.replace("_proto", "_options_registry"), name = proto_lib.replace("_proto", "_options_registry"),
srcs=[ srcs = [
name + ".cc", name + ".cc",
proto_lib + "_descriptors.inc", proto_lib + "_descriptors.inc",
name + "_type_name.h", name + "_type_name.h",
], ],
deps=[ deps = [
clean_dep("//mediapipe/framework:calculator_framework"), clean_dep("//mediapipe/framework:calculator_framework"),
clean_dep("//mediapipe/framework/port:advanced_proto"), clean_dep("//mediapipe/framework/port:advanced_proto"),
clean_dep("//mediapipe/framework/tool:options_registry"), clean_dep("//mediapipe/framework/tool:options_registry"),
proto_lib.replace("_proto", "_cc_proto"), proto_lib.replace("_proto", "_cc_proto"),
] ] +
+ deps, deps,
alwayslink=1, alwayslink = 1,
visibility=visibility, visibility = visibility,
testonly=testonly, testonly = testonly,
features=["-no_undefined"], features = ["-no_undefined"],
**kwargs **kwargs
) )
mediapipe_reexport_library( mediapipe_reexport_library(
name=name, name = name,
actual=[ actual = [
proto_lib.replace("_proto", "_cc_proto"), proto_lib.replace("_proto", "_cc_proto"),
proto_lib.replace("_proto", "_options_registry"), proto_lib.replace("_proto", "_options_registry"),
], ],
visibility=visibility, visibility = visibility,
testonly=testonly, testonly = testonly,
**kwargs **kwargs
) )

View File

@ -14,19 +14,17 @@
"""Extract a cc_library compatible dependency with only the top level proto rules.""" """Extract a cc_library compatible dependency with only the top level proto rules."""
ProtoLibsInfo = provider(fields=["targets", "out"]) ProtoLibsInfo = provider(fields = ["targets", "out"])
def _get_proto_rules(deps, proto_rules = None):
def _get_proto_rules(deps, proto_rules=None):
useful_deps = [dep for dep in deps if hasattr(dep, "proto_rules")] useful_deps = [dep for dep in deps if hasattr(dep, "proto_rules")]
if proto_rules == None: if proto_rules == None:
proto_rules = depset() proto_rules = depset()
proto_rules = depset( proto_rules = depset(
transitive=[proto_rules] + [dep.proto_rules for dep in useful_deps], transitive = [proto_rules] + [dep.proto_rules for dep in useful_deps],
) )
return proto_rules return proto_rules
def _proto_rules_aspect_impl(target, ctx): def _proto_rules_aspect_impl(target, ctx):
# Make sure the rule has a srcs attribute. # Make sure the rule has a srcs attribute.
proto_rules = depset() proto_rules = depset()
@ -43,16 +41,14 @@ def _proto_rules_aspect_impl(target, ctx):
proto_rules = _get_proto_rules(deps, proto_rules) proto_rules = _get_proto_rules(deps, proto_rules)
return struct( return struct(
proto_rules=proto_rules, proto_rules = proto_rules,
) )
proto_rules_aspect = aspect( proto_rules_aspect = aspect(
implementation=_proto_rules_aspect_impl, implementation = _proto_rules_aspect_impl,
attr_aspects=["deps"], attr_aspects = ["deps"],
) )
def _transitive_protos_impl(ctx): def _transitive_protos_impl(ctx):
"""Implementation of transitive_protos rule. """Implementation of transitive_protos rule.
@ -65,16 +61,15 @@ def _transitive_protos_impl(ctx):
cc_info_sets = [] cc_info_sets = []
for dep in ctx.attr.deps: for dep in ctx.attr.deps:
cc_info_sets.append(dep.proto_rules) cc_info_sets.append(dep.proto_rules)
cc_infos = depset(transitive=cc_info_sets).to_list() cc_infos = depset(transitive = cc_info_sets).to_list()
return [cc_common.merge_cc_infos(cc_infos=cc_infos)] return [cc_common.merge_cc_infos(cc_infos = cc_infos)]
transitive_protos = rule( transitive_protos = rule(
implementation=_transitive_protos_impl, implementation = _transitive_protos_impl,
attrs={ attrs = {
"deps": attr.label_list( "deps": attr.label_list(
aspects=[proto_rules_aspect], aspects = [proto_rules_aspect],
), ),
}, },
provides=[CcInfo], provides = [CcInfo],
) )

View File

@ -16,7 +16,7 @@ load("@bazel_skylib//lib:selects.bzl", "selects")
load("//mediapipe/gpu:metal.bzl", "metal_library") load("//mediapipe/gpu:metal.bzl", "metal_library")
load("@build_bazel_rules_apple//apple:ios.bzl", "ios_unit_test") load("@build_bazel_rules_apple//apple:ios.bzl", "ios_unit_test")
load("//mediapipe/framework/port:build_config.bzl", "mediapipe_cc_proto_library", "mediapipe_proto_library") load("//mediapipe/framework/port:build_config.bzl", "mediapipe_cc_proto_library", "mediapipe_proto_library")
load("//mediapipe/framework:mediapipe_cc_test.bzl", "mediapipe_cc_test") load("//mediapipe/framework:mediapipe_cc_test.bzl", "mediapipe_cc_test") # @unused
load("//mediapipe/framework:more_selects.bzl", "more_selects") load("//mediapipe/framework:more_selects.bzl", "more_selects")
licenses(["notice"]) licenses(["notice"])

View File

@ -1,4 +1,4 @@
"""Experimental Skylark rules for Apple's Metal. """Experimental Starlark rules for Apple's Metal.
This creates a .metallib file containing compiled Metal shaders. This creates a .metallib file containing compiled Metal shaders.
Note that the default behavior in Xcode is to put all metal shaders into a Note that the default behavior in Xcode is to put all metal shaders into a
@ -36,19 +36,21 @@ load(
"resources", "resources",
) )
def _metal_compiler_args( def _metal_compiler_args(
ctx, src, obj, minimum_os_version, copts, diagnostics, deps_dump ctx,
): src,
obj,
minimum_os_version,
copts,
diagnostics,
deps_dump):
"""Returns arguments for metal compiler.""" """Returns arguments for metal compiler."""
apple_fragment = ctx.fragments.apple apple_fragment = ctx.fragments.apple
platform = apple_fragment.single_arch_platform platform = apple_fragment.single_arch_platform
if not minimum_os_version: if not minimum_os_version:
minimum_os_version = ctx.attr._xcode_config[ minimum_os_version = ctx.attr._xcode_config[apple_common.XcodeVersionConfig].minimum_os_for_platform_type(
apple_common.XcodeVersionConfig
].minimum_os_for_platform_type(
platform.platform_type, platform.platform_type,
) )
@ -76,21 +78,19 @@ def _metal_compiler_args(
] ]
return args return args
def _metal_compiler_inputs(srcs, hdrs, deps = []):
def _metal_compiler_inputs(srcs, hdrs, deps=[]):
"""Determines the list of inputs required for a compile action.""" """Determines the list of inputs required for a compile action."""
cc_infos = [dep[CcInfo] for dep in deps if CcInfo in dep] cc_infos = [dep[CcInfo] for dep in deps if CcInfo in dep]
dep_headers = depset( dep_headers = depset(
transitive=[cc_info.compilation_context.headers for cc_info in cc_infos] transitive = [cc_info.compilation_context.headers for cc_info in cc_infos],
) )
return depset(srcs + hdrs, transitive=[dep_headers]) return depset(srcs + hdrs, transitive = [dep_headers])
def _metal_library_impl(ctx): def _metal_library_impl(ctx):
"""Implementation for metal_library Skylark rule.""" """Implementation for metal_library Starlark rule."""
# A unique path for rule's outputs. # A unique path for rule's outputs.
objs_outputs_path = "{}.objs/".format(ctx.label.name) objs_outputs_path = "{}.objs/".format(ctx.label.name)
@ -115,16 +115,18 @@ def _metal_library_impl(ctx):
apple_support.run( apple_support.run(
ctx, ctx,
xcode_path_resolve_level=apple_support.xcode_path_resolve_level.args, xcode_path_resolve_level = apple_support.xcode_path_resolve_level.args,
inputs=_metal_compiler_inputs( inputs = _metal_compiler_inputs(
ctx.files.srcs, ctx.files.hdrs, ctx.attr.deps ctx.files.srcs,
ctx.files.hdrs,
ctx.attr.deps,
), ),
outputs=[obj, diagnostics, deps_dump], outputs = [obj, diagnostics, deps_dump],
mnemonic="MetalCompile", mnemonic = "MetalCompile",
executable="/usr/bin/xcrun", executable = "/usr/bin/xcrun",
arguments=args, arguments = args,
use_default_shell_env=False, use_default_shell_env = False,
progress_message=("Compiling Metal shader %s" % (basename)), progress_message = ("Compiling Metal shader %s" % (basename)),
) )
output_lib = ctx.actions.declare_file(ctx.label.name + ".metallib") output_lib = ctx.actions.declare_file(ctx.label.name + ".metallib")
@ -137,18 +139,20 @@ def _metal_library_impl(ctx):
apple_support.run( apple_support.run(
ctx, ctx,
xcode_path_resolve_level=apple_support.xcode_path_resolve_level.args, xcode_path_resolve_level = apple_support.xcode_path_resolve_level.args,
inputs=output_objs, inputs = output_objs,
outputs=(output_lib,), outputs = (output_lib,),
mnemonic="MetalLink", mnemonic = "MetalLink",
executable="/usr/bin/xcrun", executable = "/usr/bin/xcrun",
arguments=args, arguments = args,
progress_message=("Linking Metal library %s" % ctx.label.name), progress_message = ("Linking Metal library %s" % ctx.label.name),
) )
objc_provider = apple_common.new_objc_provider( objc_provider = apple_common.new_objc_provider(
providers=[ providers = [
x[apple_common.Objc] for x in ctx.attr.deps if apple_common.Objc in x x[apple_common.Objc]
for x in ctx.attr.deps
if apple_common.Objc in x
], ],
) )
@ -156,30 +160,29 @@ def _metal_library_impl(ctx):
if ctx.files.hdrs: if ctx.files.hdrs:
cc_infos.append( cc_infos.append(
CcInfo( CcInfo(
compilation_context=cc_common.create_compilation_context( compilation_context = cc_common.create_compilation_context(
headers=depset([f for f in ctx.files.hdrs]), headers = depset([f for f in ctx.files.hdrs]),
), ),
), ),
) )
return [ return [
DefaultInfo( DefaultInfo(
files=depset([output_lib]), files = depset([output_lib]),
), ),
objc_provider, objc_provider,
cc_common.merge_cc_infos(cc_infos=cc_infos), cc_common.merge_cc_infos(cc_infos = cc_infos),
# Return the provider for the new bundling logic of rules_apple. # Return the provider for the new bundling logic of rules_apple.
resources.bucketize_typed([output_lib], "unprocessed"), resources.bucketize_typed([output_lib], "unprocessed"),
] ]
METAL_LIBRARY_ATTRS = dicts.add( METAL_LIBRARY_ATTRS = dicts.add(
apple_support.action_required_attrs(), apple_support.action_required_attrs(),
{ {
"srcs": attr.label_list(allow_files=[".metal"], allow_empty=False), "srcs": attr.label_list(allow_files = [".metal"], allow_empty = False),
"hdrs": attr.label_list(allow_files=[".h"]), "hdrs": attr.label_list(allow_files = [".h"]),
"deps": attr.label_list( "deps": attr.label_list(
providers=[["objc", CcInfo], [apple_common.Objc, CcInfo]] providers = [["objc", CcInfo], [apple_common.Objc, CcInfo]],
), ),
"copts": attr.string_list(), "copts": attr.string_list(),
"minimum_os_version": attr.string(), "minimum_os_version": attr.string(),
@ -187,20 +190,8 @@ METAL_LIBRARY_ATTRS = dicts.add(
) )
metal_library = rule( metal_library = rule(
implementation=_metal_library_impl, implementation = _metal_library_impl,
attrs=METAL_LIBRARY_ATTRS, attrs = METAL_LIBRARY_ATTRS,
fragments=["apple", "objc", "swift"], fragments = ["apple", "objc", "swift"],
output_to_genfiles=True, output_to_genfiles = True,
) )
"""
Builds a Metal library.
Args:
srcs: Metal shader sources.
hdrs: Header files used by the shader sources.
deps: objc_library targets whose headers should be visible to the shaders.
The header files declared in this rule are also visible to any objc_library
rules that have it as a dependency, so that constants and typedefs can be
shared between Metal and Objective-C code.
"""

View File

@ -12,6 +12,11 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
load(
"//mediapipe/framework/tool:mediapipe_graph.bzl",
"mediapipe_binary_graph",
)
licenses(["notice"]) licenses(["notice"])
package(default_visibility = ["//visibility:public"]) package(default_visibility = ["//visibility:public"])
@ -74,11 +79,6 @@ cc_library(
], ],
) )
load(
"//mediapipe/framework/tool:mediapipe_graph.bzl",
"mediapipe_binary_graph",
)
mediapipe_binary_graph( mediapipe_binary_graph(
name = "mobile_cpu_binary_graph", name = "mobile_cpu_binary_graph",
graph = "object_detection_mobile_cpu.pbtxt", graph = "object_detection_mobile_cpu.pbtxt",

View File

@ -12,33 +12,33 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Generates MediaPipe AAR including different variants of .so in jni folder. """Generates MediaPipe AAR including different variants of .so in jni folder.\r
\r
Usage: Usage:\r
\r
Creates a new mediapipe_aar() target in a BUILD file. For example, Creates a new mediapipe_aar() target in a BUILD file. For example,\r
putting the following code into mediapipe/examples/android/aar_demo/BUILD. putting the following code into mediapipe/examples/android/aar_demo/BUILD.\r
\r
``` ```\r
load("//mediapipe/java/com/google/mediapipe:mediapipe_aar.bzl", "mediapipe_aar") load("//mediapipe/java/com/google/mediapipe:mediapipe_aar.bzl", "mediapipe_aar")\r
\r
mediapipe_aar( mediapipe_aar(\r
name = "demo", name = "demo",\r
calculators = ["//mediapipe/calculators/core:pass_through_calculator"], calculators = ["//mediapipe/calculators/core:pass_through_calculator"],\r
) )\r
``` ```\r
\r
Then, runs the following Bazel command to generate the aar. Then, runs the following Bazel command to generate the aar.\r
\r
``` ```\r
$ bazel build --strip=always -s -c opt \ $ bazel build --strip=always -s -c opt \\\r
--host_crosstool_top=@bazel_tools//tools/cpp:toolchain \ --host_crosstool_top=@bazel_tools//tools/cpp:toolchain \\\r
--fat_apk_cpu=arm64-v8a,armeabi-v7a \ --fat_apk_cpu=arm64-v8a,armeabi-v7a \\\r
mediapipe/examples/android/aar_demo:demo.aar mediapipe/examples/android/aar_demo:demo.aar\r
``` ```\r
\r
Finally, imports the aar into Android Studio. Finally, imports the aar into Android Studio.\r
\r
""" """
load("@build_bazel_rules_android//android:rules.bzl", "android_binary", "android_library") load("@build_bazel_rules_android//android:rules.bzl", "android_binary", "android_library")
@ -178,7 +178,7 @@ EOF
_aar_with_jni(name, name + "_android_lib") _aar_with_jni(name, name + "_android_lib")
def _mediapipe_proto(name): def _mediapipe_proto(name): #@unused
"""Generates MediaPipe java proto libraries. """Generates MediaPipe java proto libraries.
Args: Args:

View File

@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
load("//mediapipe/java/com/google/mediapipe:mediapipe_aar.bzl", "mediapipe_aar")
package(default_visibility = ["//visibility:public"]) package(default_visibility = ["//visibility:public"])
licenses(["notice"]) licenses(["notice"])
@ -128,8 +130,6 @@ cc_library(
alwayslink = 1, alwayslink = 1,
) )
load("//mediapipe/java/com/google/mediapipe:mediapipe_aar.bzl", "mediapipe_aar")
mediapipe_aar( mediapipe_aar(
name = "solution_core", name = "solution_core",
srcs = glob(["**/*.java"]), srcs = glob(["**/*.java"]),