Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to build Android Example App using Bazel on Windows #6385

Closed
AndreyRub opened this issue Dec 18, 2016 · 51 comments
Closed

Unable to build Android Example App using Bazel on Windows #6385

AndreyRub opened this issue Dec 18, 2016 · 51 comments
Assignees
Labels
stat:awaiting tensorflower Status - Awaiting response from tensorflower type:build/install Build and install issues

Comments

@AndreyRub
Copy link

AndreyRub commented Dec 18, 2016

What related GitHub issues or StackOverflow threads have you found by searching the web for your problem?

#6101
#6383
http://stackoverflow.com/questions/40978859/creating-simple-android-app-using-android-studio-and-tensorflow

Environment info

Operating System: Windows

Installed version of CUDA and cuDNN:
(please attach the output of ls -l /path/to/cuda/lib/libcud*):
Cuda 8.0
cuDNN 5.0

If installed from source, provide

  1. The commit hash (git rev-parse HEAD)
    I downloaded the latest ZIP on 18 Dec 2016. Sorry, I have no idea how to get the version.

  2. The output of bazel version
    Build label: 0.4.2
    Build target: bazel-out/local-fastbuild/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
    Build time: Wed Dec 7 18:47:13 2016 (1481136433)
    Build timestamp: 1481136433
    Build timestamp as int: 1481136433

My goal is to build an Android App which loads pre-trained TensorFlow model and runs it on an Android device. I am working on Android Studio on Windows. Unfortunately using Android Studio on Linux is currently not an option.

Following previous advice from this forum, I am trying to build an Android example using Bazel on Windows.
I've successfully installed Bazel using Chocolatey.
Following the build instructions, I changed the SDK and NDK paths in WORKSPACE file and ran:
bazel build //tensorflow/examples/android:tensorflow_demo

So far I did the following to fix errors:

  1. copied aapt.exe to aapt, zipalign.exe to zipalign, since their name is different on Windows/Linux
  2. installed using pacman gcc

But I am stuck again. I am getting the following error which I have no idea how to fix:

ERROR: C:/Users/Andrey/AppData/Local/Temp/_bazel_Andrey/gd3-gSwg/external/protobuf/BUILD:73:1: C++ compilation of rule '@protobuf//:protobuf_lite' failed: arm-linux-androideabi-gcc failed: error executing command external/androidndk/ndk/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/bin/arm-linux-androideabi-gcc -fstack-protector-strong -fpic -ffunction-sections -funwind-tables ... (remaining 44 argument(s) skipped): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.
external/protobuf/src/google/protobuf/stubs/structurally_valid.cc:588:1: fatal error: opening dependency file bazel-out/android-arm-linux-androideabi-4.9-v7a-gnu-libstdcpp-fastbuild/bin/external/protobuf/_objs/protobuf_lite/external/protobuf/src/google/protobuf/stubs/structurally_valid.d: No such file or directory
 }  // namespace google
 ^
compilation terminated.
ERROR: C:/Tools/tensorflow-master/tensorflow/examples/android/BUILD:58:1: output 'tensorflow/examples/android/tensorflow_demo_symbols/R.txt' was not created.
ERROR: C:/Tools/tensorflow-master/tensorflow/examples/android/BUILD:58:1: output 'tensorflow/examples/android/tensorflow_demo.srcjar' was not created.
ERROR: C:/Tools/tensorflow-master/tensorflow/examples/android/BUILD:58:1: output 'tensorflow/examples/android/proguard/tensorflow_demo/_tensorflow_demo_proguard.cfg' was not created.
ERROR: C:/Tools/tensorflow-master/tensorflow/examples/android/BUILD:58:1: output 'tensorflow/examples/android/tensorflow_demo_processed_manifest/AndroidManifest.xml' was not created.
ERROR: C:/Tools/tensorflow-master/tensorflow/examples/android/BUILD:58:1: output 'tensorflow/examples/android/tensorflow_demo_files/resource_files.zip' was not created.
ERROR: C:/Tools/tensorflow-master/tensorflow/examples/android/BUILD:58:1: output 'tensorflow/examples/android/tensorflow_demo.ap_' was not created.
ERROR: C:/Users/Andrey/AppData/Local/Temp/_bazel_Andrey/gd3-gSwg/external/protobuf/BUILD:73:1: output 'external/protobuf/_objs/protobuf_lite/external/protobuf/src/google/protobuf/stubs/stringprintf.o' was not created.
ERROR: C:/Users/Andrey/AppData/Local/Temp/_bazel_Andrey/gd3-gSwg/external/protobuf/BUILD:73:1: output 'external/protobuf/_objs/protobuf_lite/external/protobuf/src/google/protobuf/arenastring.o' was not created.
ERROR: C:/Users/Andrey/AppData/Local/Temp/_bazel_Andrey/gd3-gSwg/external/protobuf/BUILD:113:1: output 'external/protobuf/_objs/protobuf/external/protobuf/src/google/protobuf/io/strtod.o' was not created.
ERROR: C:/Users/Andrey/AppData/Local/Temp/_bazel_Andrey/gd3-gSwg/external/protobuf/BUILD:73:1: output 'external/protobuf/_objs/protobuf_lite/external/protobuf/src/google/protobuf/repeated_field.o' was not created.
Target //tensorflow/examples/android:tensorflow_demo failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 4.722s, Critical Path: 1.16s

  1. Please advice how to proceed?
  2. Isn't there an easier way to achieve what I want? I just need pre-built TensorFlow binaries for Android Studio on Windows, to build an example application. So far I found only pre-built Python distribution and Bazel installation on Windows
@aselle aselle assigned mrry and petewarden and unassigned mrry Dec 20, 2016
@aselle
Copy link
Contributor

aselle commented Dec 20, 2016

@petewarden, you mentioned you have had experience with android builds on windows.

@aselle aselle added type:build/install Build and install issues stat:awaiting tensorflower Status - Awaiting response from tensorflower labels Dec 20, 2016
@AndreyRub
Copy link
Author

AndreyRub commented Dec 22, 2016

Ok, after trying to build the Bazel example Android project on Linux, and reverse engineering the .apk package, it looks like it depends only on a single .so native TensorFlow Android library, called libtensorflow_demo.so.

Currently in order to build this simple example on Windows, I needed to:

  1. Install chocolatey
  2. Install bazel
  3. Install pacman
  4. Download gcc using pacman
  5. Change CONFIGURATION file and find my SDK and NDK
  6. Change some sdk .exe files to no extenstion, to fit Linux
  7. And it still does not work 👎
    ... That is a very hard and tedious process

I think that it could really help if there was an example Android Studio project for windows which does not use Bazel at all. Instead let's put the mentioned above pre-compiled TensorFlow library available for download (for all possible Android architectures - arm64-v8a, armeabi, armeabi-v7a ,x86_64) ,together with a simple tutorial.

Obviously, it will not be as flexible as the ability to re-build TensorFlow, but for 99% of users it will suffice to update the pre-built libraries once in a while.

@andrewharp
Copy link
Contributor

Unfortunately Bazel doesn't support Android on Windows yet.

However we do have cmake support in tensorflow/contrib/android/cmake that should let you build the library necessary for simple Android inference on Windows (this excludes some native code created specifically for the demo). Full demo support should be coming soon, possibly including pre-built libs.

As a sort-of-hacky alternative you can grab the APK built by Jenkins here, and unzip it to grab libtensorflow_demo.so to manually place into your project.

@aselle aselle added stat:awaiting response Status - Awaiting response from author and removed stat:awaiting tensorflower Status - Awaiting response from tensorflower labels Dec 23, 2016
@andrewharp
Copy link
Contributor

@AndreyRub Please see http://ci.tensorflow.org/view/Nightly/job/nightly-android/ for a full selection of prebuilt Android TF libs, which has just come online.

You can either download libtensorflow_inference.so for something that can be dropped into a standalone app, or grab
libtensorflow_demo.so if you're trying to get the TF Android demo to run (contains libtensorflow_inference.so + demo-specific native code).

In either case you will need libandroid_tensorflow_inference_java.jar as well for the Java counterpart.

@bulatyauheni
Copy link

@andrewharp or @AndreyRub Could you please provide some steps for such goal:
In order to build simple example on Windows with retrained model, I needed to:

  1. Install chocolatey
  2. Install bazel
  3. ....

I am really stuck with it. Thank you.

@andrewharp
Copy link
Contributor

@bulatyauheni Bazel does not support Android on Windows yet. You might try the cmake build, but easiest thing to do if you just want to plug something into your Android Studio project is to grab the pre-built libraries referenced above.

@Anmolk22
Copy link

Anmolk22 commented Feb 27, 2017

@andrewharp Hey Andrew I am trying to build tensorflow/examples/android on windows 7 using Android Studio. Is it possible or not ?
And even if I can build it can you look into this error if possible
I also tried to write another commandLine 'export JAVA_HOME="$(ls -d C:/Program\ Files/Java/jdk* | sort | tail -n 1)"' but even this didn't work
errorandroidstudio

@aselle aselle added stat:awaiting tensorflower Status - Awaiting response from tensorflower and removed stat:awaiting response Status - Awaiting response from author labels Feb 27, 2017
@bulatyauheni
Copy link

@Anmolk22 I'll try to help you. Bazel does not work properly on Windows, so for building project you should use prebuilded libs.

  1. (Open this link and download last stable build archive http://ci.tensorflow.org/view/Nightly/job/nightly-android/) It should contains following files
    image
  2. Remove buildNative and copyNativeLibs tasks from build.gradle file.
  3. Copy libs from archive to libs derectory of android project.

@andrewharp
Copy link
Contributor

andrewharp commented Mar 8, 2017

The native libs necessary for the demo can now be built with make via Android Studio, completely removing the need for Bazel on Linux and OS X system. Set buildWithMake to true in build.gradle to try.

However, it seems some extra changes will still be required to get this to get the make builds to work on Windows, so reopening to track.

@andrewharp andrewharp reopened this Mar 8, 2017
@andrewharp
Copy link
Contributor

andrewharp commented Mar 8, 2017

Ok, I've got something sort of working. It needs some more tweaking, and I would recommend sticking with the prebuilts as described by @bulatyauheni above, but if you're feeling adventurous here's how you can build the Android TF libraries on Windows 10.

First, install Bash for Windows as described here: https://msdn.microsoft.com/en-us/commandline/wsl/about

Once that's done, start bash and run the following, adjusting directories appropriately:

# Install necessary components
sudo apt-get install make unzip autoconf ccache autogen libtool g++ zlibc-dev

# Download and install the NDK (has to be the Linux NDK)
wget https://dl.google.com/android/repository/android-ndk-r12b-linux-x86_64.zip
mkdir -p ~/android
unzip android-ndk-r12b-linux-x86_64.zip -d ~/android

# Build once to confirm it works and generate proto libs (which will be reused).
export NDK_ROOT=~/android/android-ndk-r12b
export CC_PREFIX=ccache
tensorflow/contrib/makefile/build_all_android.sh \
-s tensorflow/contrib/makefile/sub_makefiles/android/Makefile.in \
-t "libtensorflow_inference.so libtensorflow_demo.so"

Now create a file named "makefile_helper.bat" in tensorflow/ and add the following to it:

echo "BUILDING!"
bash -c 'NDK_ROOT=~/android/android-ndk-r12b CC_PREFIX=ccache tensorflow/contrib/makefile/build_all_android.sh -T -s tensorflow/contrib/makefile/sub_makefiles/android/Makefile.in -t "libtensorflow_inference.so libtensorflow_demo.so"'
exit

(The '-T' will prevent it from redownloading and compiling protobuf every time)

Then update build.gradle buildNativeMade to the following:

task buildNativeMake(type: Exec) {
    workingDir '../../..'
    commandLine = ['cmd', '/C', 'start', 'makefile_helper.bat']
}

Now, if you set buildWithMake = true, it should create the native libs exactly where gradle expects to find them and copy them into the app dir.

This should work similarly for bazel on Windows, if you wish to install that under bash instead.

I'd prefer not to check in a separate helper script, so if anybody has luck getting the command to run inline in the Exec task itself please let me know.

@ramarajan09
Copy link

@bulatyauheni @AndreyRub
I tried to follow the steps to build android example.

  1. imported examples/android/build gradle
  2. Edited the path to pre-built so
    def demoLibPath = '../libtensorflow_demo.so'
    def inferenceLibPath = '../libtensorflow_inference.so'
  3. I now get the following error
    **Error:Execution failed for task ':buildNativeBazel'.

A problem occurred starting process 'command '/usr/local/bin/bazel''**
Please find the attached build file.

Any help would be very useful!

build.txt

@bulatyauheni
Copy link

@ramarajan09
Try to remove this task

@ramarajan09
Copy link

ramarajan09 commented Mar 31, 2017

@bulatyauheni I tried to remove that task, however it throws multiple error in this task
tasks.whenTaskAdded { task ->
if (task.name == 'assembleDebug') {
task.dependsOn 'copyNativeLibs'
}
if (task.name == 'assembleRelease') {
task.dependsOn 'copyNativeLibs'
}
}

Could you share the build file you used

@bulatyauheni
Copy link

@ramarajan09
Try to remove this task instead
task buildNativeBazel(type: Exec) {
workingDir '../../..'
commandLine bazelLocation, 'build', '-c', 'opt',
'tensorflow/examples/android:tensorflow_native_libs',
'--crosstool_top=//external:android/crosstool',
'--cpu=' + cpuType,
'--host_crosstool_top=@bazel_tools//tools/cpp:toolchain'
}

@andrewharp
Copy link
Contributor

@vyse8 What are the contents of the apk as seen with unzip -v?

I'm not sure why you'd have an aar in jnilibs unless you put it there yourself (and you probably shouldn't).

All you should need to do is change cpuType to "armeabi-v7a". The code is already set up to composite the directory name correctly for you.

@vyse8
Copy link

vyse8 commented Apr 22, 2017

@andrewharp From what I can tell it looks like anything that is placed in my libs folder gets moved to jnilibs. I believe this occurs because of the following lines in build.gradle

manifest.srcFile 'AndroidManifest.xml'
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = [project.ext.ASSET_DIR]
jniLibs.srcDirs = ['libs']

I went ahead and changed the cputype back to armeabi-v7a but still getting the libtensorflow_demo.so couldn't be found error. I did find some additional info by using the Analyze apk feature in Android Studio. It looks like at the root there is a lib folder, and within that folder are the types (x86, x86_64, arm64_v8a, armeabi-v7a). However, within those folders, the only file listed in each one is libtensorflow_inference.so. This would explain why it is having difficulty finding the libtensorflow_demo.so. Should this file be located in the same directory ideally? I don't see it anywhere within the apk.

Also, if I were wanting to build the sample Hello World tensorflow example within Android, would I only need the latest inference file? Thank you so much for all of this help btw.

@andrewharp
Copy link
Contributor

@vyse8 In your situation I'd suggest just ignoring that the AAR even exists and following only the instructions in the original workaround. It's hard to tell what's going on if we don't even know what's in the APK (again, you can find out with unzip -v).

@vyse8
Copy link

vyse8 commented Apr 22, 2017

@andrewharp my apologies, I was unfamiliar with unzip so I equated it to Analyze APK, I see now that it provides a better output. Here it is:

Length Method Size Cmpr Date Time CRC-32 Name


4148  Defl:N     1184  72% 1980-00-00 00:00 745f1818  AndroidManifest.xml
 773  Defl:N      604  22% 1980-00-00 00:00 1dec76f1  META-INF/CERT.RSA
4944  Defl:N     2282  54% 1980-00-00 00:00 bb9069fb  META-INF/CERT.SF
4882  Defl:N     2241  54% 1980-00-00 00:00 2fd450e2  META-INF/MANIFEST.MF
 476  Defl:N      298  37% 1980-00-00 00:00 b6b9a342  assets/BUILD

10492 Defl:N 5554 47% 1980-00-00 00:00 bdb9b97a assets/imagenet_comp_graph_label_strings.txt
42335 Defl:N 4901 88% 1980-00-00 00:00 90dd4646 assets/multibox_location_priors.txt
18556306 Defl:N 16704579 10% 1980-00-00 00:00 cdeb207e assets/multibox_model.pb
563897 Defl:N 270926 52% 1980-00-00 00:00 7d7f4ff3 assets/stylize_quantized.pb
53884595 Defl:N 50111288 7% 1980-00-00 00:00 6d3b8d15 assets/tensorflow_inception_graph.pb
131978 Stored 131978 0% 1980-00-00 00:00 3228d14c assets/thumbnails/style0.jpg
113303 Stored 113303 0% 1980-00-00 00:00 13596907 assets/thumbnails/style1.jpg
151688 Stored 151688 0% 1980-00-00 00:00 a3e9c196 assets/thumbnails/style10.jpg
181154 Stored 181154 0% 1980-00-00 00:00 adb4f0a3 assets/thumbnails/style11.jpg
107888 Stored 107888 0% 1980-00-00 00:00 79dbb7d0 assets/thumbnails/style12.jpg
198586 Stored 198586 0% 1980-00-00 00:00 c97505a9 assets/thumbnails/style13.jpg
104584 Stored 104584 0% 1980-00-00 00:00 5832132a assets/thumbnails/style14.jpg
152269 Stored 152269 0% 1980-00-00 00:00 005ad28f assets/thumbnails/style15.jpg
168251 Stored 168251 0% 1980-00-00 00:00 6bccba6c assets/thumbnails/style16.jpg
146736 Stored 146736 0% 1980-00-00 00:00 132cbdcb assets/thumbnails/style17.jpg
173496 Stored 173496 0% 1980-00-00 00:00 9a6a37a7 assets/thumbnails/style18.jpg
227300 Stored 227300 0% 1980-00-00 00:00 a11b35b4 assets/thumbnails/style19.jpg
140121 Stored 140121 0% 1980-00-00 00:00 34147cc2 assets/thumbnails/style2.jpg
134506 Stored 134506 0% 1980-00-00 00:00 3df5a425 assets/thumbnails/style20.jpg
138136 Stored 138136 0% 1980-00-00 00:00 0754c15d assets/thumbnails/style21.jpg
168478 Stored 168478 0% 1980-00-00 00:00 25998a8e assets/thumbnails/style22.jpg
108525 Stored 108525 0% 1980-00-00 00:00 91f2c6b0 assets/thumbnails/style23.jpg
131414 Stored 131414 0% 1980-00-00 00:00 ead622b6 assets/thumbnails/style24.jpg
190320 Stored 190320 0% 1980-00-00 00:00 b39eb2ce assets/thumbnails/style25.jpg
181100 Stored 181100 0% 1980-00-00 00:00 a86a5141 assets/thumbnails/style3.jpg
181565 Stored 181565 0% 1980-00-00 00:00 9dfc14ff assets/thumbnails/style4.jpg
162432 Stored 162432 0% 1980-00-00 00:00 2e8636d3 assets/thumbnails/style5.jpg
167919 Stored 167919 0% 1980-00-00 00:00 560fdd11 assets/thumbnails/style6.jpg
97875 Stored 97875 0% 1980-00-00 00:00 684b2c5b assets/thumbnails/style7.jpg
121177 Stored 121177 0% 1980-00-00 00:00 d552dee2 assets/thumbnails/style8.jpg
208059 Stored 208059 0% 1980-00-00 00:00 83817fe1 assets/thumbnails/style9.jpg
740 Defl:N 471 36% 1980-00-00 00:00 e766d2a8 classes.dex
46084 Defl:N 23500 49% 1980-00-00 00:00 e4185116 classes2.dex
14990000 Defl:N 4886533 67% 1980-00-00 00:00 5177fbad lib/arm64-v8a/libtensorflow_inference.so
9553964 Defl:N 3998890 58% 1980-00-00 00:00 2f76c5e6 lib/armeabi-v7a/libtensorflow_inference.so
15087484 Defl:N 4981805 67% 1980-00-00 00:00 bdf2df5f lib/x86/libtensorflow_inference.so
15022832 Defl:N 4885743 68% 1980-00-00 00:00 41fd2ecb lib/x86_64/libtensorflow_inference.so
234 Stored 234 0% 1980-00-00 00:00 c560f719 res/drawable-hdpi-v4/tile.9.png
1129 Stored 1129 0% 1980-00-00 00:00 02df764b res/drawable-xxhdpi-v4/ic_action_info.png
10714 Stored 10714 0% 1980-00-00 00:00 fcef8ddf res/drawable-xxhdpi-v4/ic_launcher.png
404 Defl:N 228 44% 1980-00-00 00:00 97e57137 res/layout/activity_camera.xml
960 Defl:N 395 59% 1980-00-00 00:00 0df7a88 res/layout/camera_connection_fragment.xml
1356 Defl:N 501 63% 1980-00-00 00:00 fd74248b res/layout/camera_connection_fragment_stylize.xml
784 Defl:N 319 59% 1980-00-00 00:00 3cce775d res/layout/camera_connection_fragment_tracking.xml
4616 Stored 4616 0% 1980-00-00 00:00 6c367d8a resources.arsc


131783009 89887795 32% 50 files

@andrewharp
Copy link
Contributor

andrewharp commented Apr 22, 2017

Ok, if you really want to use the AAR try a directory different than libs/ for it (it could be "foobarbaz" as long as you update the dirs directive). "libs/" may be conflicting with where gradle expects to find the native libs.

You might also try the this option for manually placing the prebuilts in the right place.

We'll have cmake working for libtensorflow_demo.so possibly next week, so really this is not worth spending too much time on.

@vyse8
Copy link

vyse8 commented Apr 22, 2017

@andrewharp thanks for your assistance. Now that I scroll up I realize I hit the same issue that ramarajan09 had 22 days ago prior to the AAR. It looks like we both got the same exact error message so I'm not sure what is causing that for us. From further analysis of the apk it looks like dragging it to an arbitrary created libs folder doesn't signal to the APK to include it in the build. Do you know how these libs can be included as I think that would solve both of our issues?

One question that I think I might be stumbling on is the libs path. What is the recommendation as mine is currently set to:

def demoLibPath = '../libs/armeabi-v7a/libtensorflow_demo.so'
def inferenceLibPath = '../libs/armeabi-v7a/libtensorflow_inference.so'

The full path in reality is C:\Users\mattv\OneDrive\Documents\GitHub\tensorflow\tensorflow\examples\android\libs\armeabi-v7a.

Would this be causing the issue?

@andrewharp
Copy link
Contributor

andrewharp commented Apr 22, 2017

@vyse8
The paths you're quoting there are where the files need to be copied from after they are built. If you put the .so files in their destination manually they're irrelevant. As you have them now it seems to be pointing to tensorflow/examples/libs, which is incorrect both because that path doesn't exist (note the ..), and because I assume you meant tensorflow/examples/android/libs, which is actually the destination, not the source (which would be wherever bazel/make create them).

To clarify:

The AAR, if you use it, needs to go in an arbitrary folder that matches "aardir" in:

allprojects {
repositories {
jcenter()
flatDir {
dirs 'aardir'
}
}
}

The .so files, if placed manually, need to be put in the arbitrary folder that matches the "libs" in:
jniLibs.srcDirs = ['libs']

The only restriction is possibly that these two dirs should be different -- my original instruction to place the AAR in libs/ may have been incorrect (I actually tested using a different directory).

Note that when AS shows you the project outline visually, I think it shows up as "jniLibs", though the actual folder on your HD is "libs".

@ahmedezzat85
Copy link

I used the prebuilt libraries (copied the folder libs from the prebuilt APK as is in the root of the project) and modified the script as follows (I commented unnecessary tasks) and it is now building OK.

// This file provides basic support for building the TensorFlow demo
// in Android Studio with Gradle.
//
// Note that Bazel is still used by default to compile the native libs,
// and should be installed at the location noted below. This build file
// automates the process of calling out to it and copying the compiled
// libraries back into the appropriate directory.
//
// Alternatively, experimental support for Makefile builds is provided by
// setting buildWithMake below to true. This will allow building the demo
// on Windows machines, but note that full equivalence with the Bazel
// build is not yet guaranteed. See comments below for caveats and tips
// for speeding up the build, such as as enabling ccache.

// Set to true to build with make.
// NOTE: Running a make build will cause subsequent Bazel builds to *fail*
// unless the contrib/makefile/downloads/ and gen/ dirs are deleted afterwards.
def buildWithMake = false

// Controls output directory in APK and CPU type for Bazel builds.
// NOTE: Does not affect the Makefile build target API (yet), which currently
// assumes armeabi-v7a. If building with make, changing this will require
// editing the Makefile as well.
def cpuType = 'armeabi-v7a'

// Output directory in the local directory for packaging into the APK.
def nativeOutDir = 'libs/' + cpuType

// Default to building with Bazel and override with make if requested.
//def nativeBuildRule = 'buildNativeBazel'
def demoLibPath = 'libs/' + cpuType + 'libtensorflow_demo.so'
def inferenceLibPath = 'libs/' + cpuType + 'libtensorflow_inference.so'
//if (buildWithMake) {
//    nativeBuildRule = 'buildNativeMake'
//    demoLibPath = '../../../tensorflow/contrib/makefile/gen/lib/libtensorflow_demo.so'
//    inferenceLibPath = '../../../tensorflow/contrib/makefile/gen/lib/libtensorflow_inference.so'
//}

// Defines the NDK location for Makefile builds. Does *not* affect Bazel builds.
// Override with your absolute NDK location if this fails to get the location
// automatically.
def makeNdkRoot = System.getenv('NDK_ROOT')

// If building with Bazel, this is the location of the bazel binary.
// NOTE: Bazel does not yet support building for Android on Windows,
// so in this case the Makefile build must be used as described above.
def bazelLocation = '/usr/local/bin/bazel'

project.buildDir = 'gradleBuild'
getProject().setBuildDir('gradleBuild')

// import DownloadModels task
project.ext.ASSET_DIR = projectDir.toString() + '/assets'
project.ext.TMP_DIR   = project.buildDir.toString() + '/downloads'

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
    }
}

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.2"

    lintOptions {
        abortOnError false
    }

    sourceSets {
        main {
            // TensorFlow Java API sources.
            java {
                srcDir '../../java/src/main/java'
                exclude '**/examples/**'
            }

            // Android TensorFlow wrappers, etc.
            java {
                srcDir '../../contrib/android/java'
            }

            // Android demo app sources.
            java {
                srcDir 'src'
            }

            manifest.srcFile 'AndroidManifest.xml'
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = [project.ext.ASSET_DIR]
            jniLibs.srcDirs = ['libs']
        }

        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

//task buildNativeBazel(type: Exec) {
//    workingDir '../../..'
//    commandLine bazelLocation, 'build', '-c', 'opt',  \
//         'tensorflow/examples/android:tensorflow_native_libs',  \
//         '--crosstool_top=//external:android/crosstool',  \
//         '--cpu=' + cpuType,  \
//         '--host_crosstool_top=@bazel_tools//tools/cpp:toolchain'
//}

//task buildNativeMake(type: Exec) {
//    environment "NDK_ROOT", makeNdkRoot
//    // Tip: install ccache and uncomment the following to speed up
//    // builds significantly.
//    // environment "CC_PREFIX", 'ccache'
//    workingDir '../../..'
//    commandLine 'tensorflow/contrib/makefile/build_all_android.sh',  \
//         '-s',  \
//         'tensorflow/contrib/makefile/sub_makefiles/android/Makefile.in',  \
//         '-t',  \
//         'libtensorflow_inference.so libtensorflow_demo.so'  \
//         //, '-T'  // Uncomment to skip protobuf and speed up subsequent builds.
//}


task copyNativeLibs(type: Copy) {
    from demoLibPath
    from inferenceLibPath
    into nativeOutDir
    duplicatesStrategy = 'include'
//    dependsOn nativeBuildRule
    fileMode 0644
}


tasks.whenTaskAdded { task ->
    if (task.name == 'assembleDebug') {
        task.dependsOn 'copyNativeLibs'
    }
    if (task.name == 'assembleRelease') {
        task.dependsOn 'copyNativeLibs'
    }
}

// Download default models; if you wish to use your own models then
// place them in the "assets" directory and comment out this line.
//apply from: "download-models.gradle"


vrv pushed a commit to vrv/tensorflow that referenced this issue May 5, 2017
…ck if native implementation is not found. This means that compiling libtensorflow_demo.so will only be strictly necessary for the Detection example (which uses native object tracking). A followup change will add graceful degradation in that case too.

Java conversion may be slower depending on the device, but should still be acceptable for demo purposes as the majority of the compute time will still be spent on TF inference passes.

Note that this has no effect on the necessity of libtensorflow_inference.so, which provides the actual TF support. However libtensorflow_inference.so may be added to applications via the prebuilt AAR, so no native compilation is necessary.

Partially addresses tensorflow#6385
Change: 155121431
vrv pushed a commit to vrv/tensorflow that referenced this issue May 5, 2017
…ve ObjectTracker support is found. If libtensorflow_demo.so is not found in the APK, rendered boxes will simply be stationary and will be replaced whenever new results come in.

Partially addresses tensorflow#6385
Change: 155159326
@andrewharp
Copy link
Contributor

andrewharp commented May 5, 2017

Another update: libtensorflow_demo.so is now (as soon as the above commits get pushed to master) an optional library. If not present, YUV->RGB color conversion will be performed in Java (possibly slower), and object tracking will be disabled in the TF Detect demo, but otherwise things will work as usual.

This means the demo can be built on Windows with just the prebuilt tensorflow.aar dropped into your project folder. We're in the process of uploading this to jcenter, at which point it will only take a couple of lines of Gradle config to add a TF dep to Android projects.

Full cmake support for building TF is also still on the roadmap (no timeline for this yet though).

@andrewharp
Copy link
Contributor

andrewharp commented May 8, 2017

The AAR build of TF is now live! This is labeled 1.2.0 preview, but note that this is merely to indicate it comes between 1.1.0 and 1.2.0 (the 1.2.0 release branch has not even been cut yet). We'll be updating it on every point release going forward.

You can enable it in your Android app by adding the following to build.gradle:

repositories {
    jcenter()
}
dependencies {
    compile 'org.tensorflow:tensorflow-android:+'
}

For the official TF demo, you'll also want to remove the following to prevent redundant Java classes from being included:

            // TensorFlow Java API sources.
            java {
                srcDir '../../java/src/main/java'
                exclude '**/examples/**'
            }

            // Android TensorFlow wrappers, etc.
            java {
                srcDir '../../contrib/android/java'
            }

And remove the reference to the locally-built inference lib as well:
from inferenceLibPath

If using an arm64 device, change cpuType from armeabi-v7a to arm64-v8 (since you'll need libtensorflow_demo.so to be built at the highest architecture target your device can use that the AAR provides libtensorflow_inference.so at).

If using bazel to build, change the following in buildNativeBazel:
'tensorflow/examples/android:tensorflow_native_libs' -> 'tensorflow/examples/android:libtensorflow_demo.so'

and if using make, change the following in buildNativeMake:
'libtensorflow_inference.so libtensorflow_demo.so' -> 'libtensorflow_demo.so'

Once fd69bb2 and efa08d8 are pushed to master (which will make libtensorflow_demo.so an optional lib), you could also just remove the native lib dependencies altogether.

We'll be cleaning this up to make it easier to switch soon, and also add a cmake build for libtensorflow_demo.so

@jubjamie
Copy link
Contributor

Hi @andrewharp Just tried to follow some of the advice in here to get this running on Windows. I've found that by far the easiest method was to just download the nightly binaries and stick them in. I tried to use your above method to use the aar but I got an error saying that the compile method was not available. Seemed to suggest it was a gradle issue. Either way I couldn't fix and resorted to sticking the prebuilts in. Not sure if you've come across this?

On another note, this thread has lots of good information and is more detailed than the documentation. Are there plans to get the documentation up to spec to contain all this information? It's slightly unclear atm, especially regarding Windows. I did notice that you said some progress was being made. Thanks for your help.

@andrewharp
Copy link
Contributor

@jubjamie Can you paste the exact error message please? Haven't seen that one before.

The README.md files have recently been updated with AAR instructions, and I'm working on a detailed getting started guide that will cover all of the approaches to building and integrating TensorFlow into apps.

@jubjamie
Copy link
Contributor

jubjamie commented May 24, 2017

@andrewharp I've got around the error so not able to get it up again I don't think. It seems to be a common error within android so i've put a very similar message below. Most solutions appear to suggest removing the compile line however that's for those specific stack overflow situations. Here it's not so simple.

Error:(9, 0) Gradle DSL method not found: 'compile()'
Possible causes:The project 'AlexTest' may be using a version of Gradle that does not contain the method.
The build file may be missing a Gradle plugin.
link: Apply Gradle plugin

In my scenario I obviously had gradle installed etc. I noticed that in the latest release there is another compile call at the very end of build.gradle which it didn't pick up on (but I wonder if that is because it didn't get that far?). This was using android on Windows 10.

I was about to open another issue regarding performance of the android app using custom tensorflow for poets models (takes 5 times as long) but not sure it's really a bug or a stack overflow question. Can I email you? Otherwise I can open a stack overflow and paste the link here? @petewarden here too perhaps?

@andrewharp
Copy link
Contributor

andrewharp commented May 24, 2017

@jubjamie Ok -- I assume this sort of thing can be cleared up in Android Studio by just clicking to install/upgrade whatever Gradle-related thing it asks you to? Or were you building from the command line?

Re Inception: the performance of v3 (from the TF for Poets guide) is known to be slower than v1 (aka 5h, bundled with the demo). It's a much larger model so some difference is expected. Speeding it up is more of a Stack Overflow topic, but if you're interested you might try seeing what ops are taking up the most time on your device with tensorflow/tools/benchmark:benchmark_model.

@petewarden
Copy link
Contributor

As a note on performance, I've recently updated the TensorFlow for Poets script with the option to save out MobileNet models, which can be a lot smaller and faster than the default Inception v3, at the cost of some accuracy:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/docs_src/tutorials/image_retraining.md#other-model-architectures

It looks like the original issue is fixed, or at least obsolete now though? I'm closing this for the moment, please reopen with more information if that's incorrect.

@SimianRainbow
Copy link

The link referring to the AAR build is now giving a 404. Has the link for this windows build method now changed?

@darrinps
Copy link

darrinps commented Apr 19, 2018

So still no Windows support after a year when this issue was first brought up? Just tried to build the demo.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':buildNativeBazel'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
at
...
Caused by: java.io.IOException: Cannot run program "/usr/local/bin/bazel" (in directory "C:\GitProjects\tensorflow"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:25)
... 10 more
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(ProcessImpl.java:386)
at java.lang.ProcessImpl.start(ProcessImpl.java:137)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 11 more

@komputerboy
Copy link

there still no bazel support on windows, you can use cmake, but still its performance still no guarantee though

@nickcuypers
Copy link

Hey guys, I am trying to include some experimental operators located in the contrib folders(tensor_forest) to a tensorflow build so that I can load a tensorflow model in my xamarin.android project using these operators without an error that states that the operators are not recognized.

In order to do this I thought I started with trying to build tensorflow android throught this command:
bazel build -c opt //tensorflow/contrib/android:libtensorflow_inference.so --crosstool_top=//external:android/crosstool --host_crosstool_top=@bazel_tools//tools/cpp:toolchain --cxxopt=-std=c++11 --cpu=armeabi-v7a --verbose_failures

But I keep getting these kinds of errors
ERROR: C:/users/cuypeni/_bazel_cuypeni/jumq43mw/external/com_google_absl/absl/numeric/BUILD.bazel:25:1: C++ compilation of rule '@com_google_absl//absl/numeric:int128' failed (Exit -1). Note: Remote connection/protocol failed with: execution failed: clang failed: error executing command cd C:/users/cuypeni/_bazel_cuypeni/jumq43mw/execroot/org_tensorflow SET PATH=C:\msys64\usr\bin;C:\msys64\bin;C:\Users\cuypeni\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\local\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Users\cuypeni\bin;C:\Program Files\Anaconda3;C:\Program Files\Anaconda3\Library\mingw-w64\bin;C:\Program Files\Anaconda3\Library\usr\bin;C:\Program Files\Anaconda3\Library\bin;C:\Program Files\Anaconda3\Scripts;C:\Python37\Scripts;C:\Python37;C:\Program Files\Docker\Docker\Resources\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\Program Files (x86)\Shoreline Communications\ShoreWare Client;C:\Program Files\nodejs;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio;C:\Program Files\dotnet;C:\Program Files\Microsoft SQL Server\130\Tools\Binn;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn;C:\Program Files\Git\cmd;C:\ProgramData\chocolatey\bin;C:\Users\cuypeni\AppData\Local\Microsoft\WindowsApps;C:\Users\cuypeni\AppData\Roaming\npm;C:\Users\cuypeni\AppData\Local\Programs\Microsoft VS Code\bin;C:\ProgramData\chocolatey\lib\msys2;C:\msys64\usr\bin;C:\Program Files\Git\usr\bin\vendor_perl;C:\Program Files\Git\usr\bin\core_perl SET PWD=/proc/self/cwd SET PYTHON_BIN_PATH=C:/Program Files/Anaconda3/python.exe SET PYTHON_LIB_PATH=C:/Program Files/Anaconda3/lib/site-packages SET TF_DOWNLOAD_CLANG=0 SET TF_NEED_CUDA=0 SET TF_NEED_OPENCL_SYCL=0 SET TF_NEED_ROCM=0 external/androidndk/ndk/toolchains/llvm/prebuilt/windows-x86_64/bin/clang -D__ANDROID_API__=14 -isystemexternal/androidndk/ndk/sysroot/usr/include/arm-linux-androideabi -target armv7-none-linux-androideabi -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -gcc-toolchain external/androidndk/ndk/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64 -fpic -ffunction-sections -funwind-tables -fstack-protector-strong -Wno-invalid-command-line-argument -Wno-unused-command-line-argument -no-canonical-prefixes -mthumb -Os -g -DNDEBUG -MD -MF bazel-out/armeabi-v7a-opt/bin/external/com_google_absl/absl/numeric/_objs/int128/int128.d -frandom-seed=bazel-out/armeabi-v7a-opt/bin/external/com_google_absl/absl/numeric/_objs/int128/int128.o -D__CLANG_SUPPORT_DYN_ANNOTATION__ -iquote external/com_google_absl -iquote bazel-out/armeabi-v7a-opt/genfiles/external/com_google_absl -iquote bazel-out/armeabi-v7a-opt/bin/external/com_google_absl -iquote external/bazel_tools -iquote bazel-out/armeabi-v7a-opt/genfiles/external/bazel_tools -iquote bazel-out/armeabi-v7a-opt/bin/external/bazel_tools -w -std=c++11 -Wall -Wextra -Wcast-qual -Wconversion-null -Wmissing-declarations -Woverlength-strings -Wpointer-arith -Wunused-local-typedefs -Wunused-result -Wvarargs -Wvla -Wwrite-strings -Wno-sign-compare --sysroot=external/androidndk/ndk/platforms/android-14/arch-arm -isystem external/androidndk/ndk/sources/cxx-stl/llvm-libc++/include -isystem external/androidndk/ndk/sources/cxx-stl/llvm-libc++abi/include -isystem external/androidndk/ndk/sources/android/support/include -isystemexternal/androidndk/ndk/sysroot/usr/include -c external/com_google_absl/absl/numeric/int128.cc -o bazel-out/armeabi-v7a-opt/bin/external/com_google_absl/absl/numeric/_objs/int128/int128.o Action failed to execute: java.io.IOException: ERROR: src/main/native/windows/processes-jni.cc(239): CreateProcessW("C:\users\cuypeni\_bazel_cuypeni\jumq43mw\execroot\org_tensorflow\external\androidndk\ndk\toolchains\llvm\prebuilt\windows-x86_64\bin\clang" -D__ANDROID_API__=14 -isystemexternal/androidndk/ndk/sysroot/usr/include/arm-linux-androideabi -target armv7-none-linux-androideabi -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -gcc-toolchain external/androidndk/ndk/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64 -fpic -ffunction-sections -funwind-tables -fstack-protector-strong -Wno-invalid-command-line-argument -Wno-unused-command-line-argument -no-canonical-prefixes -mthumb -Os -g -DNDEBUG -MD -MF bazel-out/armeabi-v7a-opt/bin/external/com_google_absl/absl/numeric/_objs/int128/int128.d -frandom-seed=bazel-out/armeabi-v7a-opt/bin/external/com_google_absl/absl/numeric/_objs/int128/int128.o -D__CLANG_SUPPORT_DYN_ANNOTATION__ -iquote external/com_google_absl -iquote bazel-out/armeabi-v7a-opt/genfiles/external/com_google_absl -iquote bazel-out/armeabi-v7a-opt/bin/external/com_google_absl -iquote external/bazel_tools -iquote bazel-out/armeabi-v7a-opt/genfiles/external/bazel_tools -iquote bazel-out/armeabi-v7a-opt/bin/external/bazel_tools -w -std=c++11 -Wall -Wextra -Wcast-qual -Wconversion-null -Wmissing-declarations -Woverlength-strings -Wpointer-arith -Wunused-local-typedefs -Wunused-result -Wvarargs -Wvla -Wwrite-strings -Wno-sign-compare --sysroot=external/androidndk/ndk/platforms/android-14/arch-arm -isystem external/androidndk/ndk/sources/cxx-stl/llvm-libc++/include -isystem external/androidndk/ndk/sources/cxx-stl/llvm-libc++abi/include -isystem external/androidndk/ndk/sources/android/support/include -isystemexternal/androidndk/ndk/sysroot/usr/include -c external/com_google_absl/absl/numeric/int128.cc -o bazel-out/armeabi-v7a-opt/bin/external/com_google_absl/absl/numeric/_objs/int128/int128.o): The system cannot find the file specified.

Is there still no bazel support for windows?
Please some help I'm stuck on this ...

@cusitkhan
Copy link

Anmolk22 hi can you please tell how you should build libtensorflow_infrence.so file
i am using this command bazel build -c opt //tensorflow/contrib/android:libtensorflow_inference.so --crosstool_top=//external:android/crosstool --host_crosstool_top=@bazel_tools//tools/cpp:toolchain --cpu=armeabi-v7a but it give me error
ERROR: C:/users/sabir-pc/_bazel_sabir-pc/zp6kp3ov/external/com_google_absl/absl/strings/BUILD.bazel:32:1: C++ compilation of rule '@com_google_absl//absl/strings:strings' failed (Exit 1)
In file included from external/com_google_absl/absl/strings/str_cat.cc:15:
In file included from external/com_google_absl\absl/strings/str_cat.h:62:
In file included from external/com_google_absl\absl/strings/numbers.h:37:
In file included from external/com_google_absl\absl/numeric/int128.h:29:
In file included from external/androidndk/ndk/sources/cxx-stl/llvm-libc++/include\cmath:305:
In file included from external/androidndk/ndk/sources/android/support/include\math.h:32
3 errors generated.
Target //tensorflow/contrib/android:libtensorflow_inference.so failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 212.615s, Critical Path: 18.57s
INFO: 213 processes: 213 local.
FAILED: Build did NOT complete successfully

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stat:awaiting tensorflower Status - Awaiting response from tensorflower type:build/install Build and install issues
Projects
None yet
Development

No branches or pull requests