├── .gitignore ├── .mvn ├── jvm.config ├── maven.config └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── CODE_OF_CONDUCT.adoc ├── LICENSE ├── README.adoc ├── mvnw ├── mvnw.cmd ├── pom.xml ├── spring-cloud-starter-stream-processor-label-image ├── README.adoc ├── pom.xml └── src │ ├── main │ ├── java │ │ └── org │ │ │ └── springframework │ │ │ └── cloud │ │ │ └── stream │ │ │ └── app │ │ │ └── label │ │ │ └── image │ │ │ └── processor │ │ │ ├── LabelImageProcessorConfiguration.java │ │ │ ├── LabelImageProcessorProperties.java │ │ │ ├── LabelImageTensorflowInputConverter.java │ │ │ └── LabelImageTensorflowOutputConverter.java │ └── resources │ │ └── META-INF │ │ ├── spring-configuration-metadata-whitelist.properties │ │ └── spring.provides │ └── test │ ├── java │ └── org │ │ └── springframework │ │ └── cloud │ │ └── stream │ │ └── app │ │ └── label │ │ └── image │ │ └── processor │ │ ├── LabelImageProcessorPropertiesTest.java │ │ └── inception │ │ └── LabelImageTensorflowProcessorIntegrationTests.java │ └── resources │ ├── LICENSE │ ├── SCDF_TF_Sentiment.png │ └── images │ └── panda.jpeg ├── spring-cloud-starter-stream-processor-tensorflow ├── README.adoc ├── pom.xml └── src │ ├── main │ ├── java │ │ └── org │ │ │ └── springframework │ │ │ └── cloud │ │ │ └── stream │ │ │ └── app │ │ │ └── tensorflow │ │ │ └── processor │ │ │ ├── TensorFlowService.java │ │ │ ├── TensorTupleConverter.java │ │ │ ├── TensorflowInputConverter.java │ │ │ ├── TensorflowOutputConverter.java │ │ │ ├── TensorflowProcessorConfiguration.java │ │ │ └── TensorflowProcessorProperties.java │ └── resources │ │ ├── META-INF │ │ ├── spring-configuration-metadata-whitelist.properties │ │ └── spring.provides │ │ └── application.properties │ └── test │ ├── java │ └── org │ │ └── springframework │ │ └── cloud │ │ └── stream │ │ └── app │ │ └── tensorflow │ │ └── processor │ │ ├── TensorTupleConverterTest.java │ │ ├── TensorflowProcessorPropertiesTest.java │ │ └── logisticregression │ │ └── LinearRegressionTensorflowProcessorIntegrationTests.java │ └── resources │ └── TensorFlowProcessorArcutectureOverview.png ├── spring-cloud-starter-stream-processor-twitter-sentiment ├── README.adoc ├── pom.xml └── src │ ├── main │ ├── java │ │ └── org │ │ │ └── springframework │ │ │ └── cloud │ │ │ └── stream │ │ │ └── app │ │ │ └── twitter │ │ │ └── sentiment │ │ │ └── processor │ │ │ ├── Sentiment.java │ │ │ ├── TwitterSentimentProcessorConfiguration.java │ │ │ ├── TwitterSentimentProcessorProperties.java │ │ │ ├── TwitterSentimentTensorflowInputConverter.java │ │ │ ├── TwitterSentimentTensorflowOutputConverter.java │ │ │ └── WordVocabulary.java │ └── resources │ │ └── META-INF │ │ ├── spring-configuration-metadata-whitelist.properties │ │ └── spring.provides │ └── test │ ├── java │ └── org │ │ └── springframework │ │ └── cloud │ │ └── stream │ │ └── app │ │ └── twitter │ │ └── sentiment │ │ └── processor │ │ ├── TwitterSentimentProcessorPropertiesTest.java │ │ └── twitter │ │ └── TwitterSentimentTensorflowProcessorIntegrationTests.java │ └── resources │ └── SCDF_TF_Sentiment.png ├── tensorflow-app-dependencies └── pom.xml └── tensorflow-app-starters-test-support ├── pom.xml └── src └── main ├── java └── org │ └── springframework │ └── cloud │ └── stream │ └── app │ └── test │ └── tensorflow │ └── TensorflowProcessorTestConfiguration.java └── resources ├── doc └── VideoIcon.png ├── tensorflow ├── model │ ├── linear_regression.txt │ └── linear_regression_graph.proto └── python │ └── LinearRegression.py └── tfInput.json /.gitignore: -------------------------------------------------------------------------------- 1 | apps/ 2 | /application.yml 3 | /application.properties 4 | asciidoctor.css 5 | *~ 6 | .#* 7 | *# 8 | target/ 9 | build/ 10 | bin/ 11 | _site/ 12 | .classpath 13 | .project 14 | .settings 15 | .springBeans 16 | .DS_Store 17 | *.sw* 18 | *.iml 19 | *.ipr 20 | *.iws 21 | .idea/ 22 | .factorypath 23 | spring-xd-samples/*/xd 24 | dump.rdb 25 | coverage-error.log 26 | .apt_generated 27 | aws.credentials.properties 28 | -------------------------------------------------------------------------------- /.mvn/jvm.config: -------------------------------------------------------------------------------- 1 | -Xmx1024m -XX:CICompilerCount=1 -XX:TieredStopAtLevel=1 -Djava.security.egd=file:/dev/./urandom -------------------------------------------------------------------------------- /.mvn/maven.config: -------------------------------------------------------------------------------- 1 | -DaltSnapshotDeploymentRepository=repo.spring.io::default::https://repo.spring.io/libs-snapshot-local -P spring 2 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tzolov/tensorflow-spring-cloud-stream-app-starters/d58fec9917894c3797bec7db049141845192d6be/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.adoc: -------------------------------------------------------------------------------- 1 | = Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, and in the interest of fostering an open 4 | and welcoming community, we pledge to respect all people who contribute through reporting 5 | issues, posting feature requests, updating documentation, submitting pull requests or 6 | patches, and other activities. 7 | 8 | We are committed to making participation in this project a harassment-free experience for 9 | everyone, regardless of level of experience, gender, gender identity and expression, 10 | sexual orientation, disability, personal appearance, body size, race, ethnicity, age, 11 | religion, or nationality. 12 | 13 | Examples of unacceptable behavior by participants include: 14 | 15 | * The use of sexualized language or imagery 16 | * Personal attacks 17 | * Trolling or insulting/derogatory comments 18 | * Public or private harassment 19 | * Publishing other's private information, such as physical or electronic addresses, 20 | without explicit permission 21 | * Other unethical or unprofessional conduct 22 | 23 | Project maintainers have the right and responsibility to remove, edit, or reject comments, 24 | commits, code, wiki edits, issues, and other contributions that are not aligned to this 25 | Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors 26 | that they deem inappropriate, threatening, offensive, or harmful. 27 | 28 | By adopting this Code of Conduct, project maintainers commit themselves to fairly and 29 | consistently applying these principles to every aspect of managing this project. Project 30 | maintainers who do not follow or enforce the Code of Conduct may be permanently removed 31 | from the project team. 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an 34 | individual is representing the project or its community. 35 | 36 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by 37 | contacting a project maintainer at spring-code-of-conduct@pivotal.io . All complaints will 38 | be reviewed and investigated and will result in a response that is deemed necessary and 39 | appropriate to the circumstances. Maintainers are obligated to maintain confidentiality 40 | with regard to the reporter of an incident. 41 | 42 | This Code of Conduct is adapted from the 43 | http://contributor-covenant.org[Contributor Covenant], version 1.3.0, available at 44 | http://contributor-covenant.org/version/1/3/0/[contributor-covenant.org/version/1/3/0/] 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | # !!! This repository is deprecated as most of the work done here is already part of the official Spring Cloud DataFlow Tensorflow Application: https://github.com/spring-cloud-stream-app-starters/tensorflow !!! 2 | 3 | # Spring Cloud Stream TensorFlow Processor 4 | 5 | A processor that evaluates a machine learning models build with link:https://www.tensorflow.org/[TensorFlow] and stored 6 | in link:https://developers.google.com/protocol-buffers/[Protocol Buffer] binary format. 7 | 8 | The TensorFlow processor uses link:https://www.tensorflow.org/api_docs/java/reference/org/tensorflow/package-summary[TensorFlow Java API] library. 9 | 10 | To learn more about this application and the supported properties, please review the following details. 11 | 12 | include::spring-cloud-starter-stream-processor-tensorflow/README.adoc[] 13 | 14 | To customize Processor's input/output converters for handling different message formats and model types review 15 | the Twitter Sentiment processor extension. 16 | 17 | include::spring-cloud-starter-stream-processor-twitter-sentiment/README.adoc[] 18 | 19 | Label Image is a customized Processor that extends the core Tensorflow Processor to support the Inception Tensorflow model: 20 | 21 | 22 | include::spring-cloud-starter-stream-processor-label-image/README.adoc[] 23 | 24 | --- 25 | 26 | Video Tutorial: link:https://www.youtube.com/watch?v=QzF2Iii4s5c[Real-time Twitter Sentiment Analytics with TensorFlow and Spring Cloud Dataflow] 27 | 28 | image::tensorflow-app-starters-test-support/src/main/resources/doc/VideoIcon.png[] 29 | 30 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # 58 | # Look for the Apple JDKs first to preserve the existing behaviour, and then look 59 | # for the new JDKs provided by Oracle. 60 | # 61 | if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then 62 | # 63 | # Apple JDKs 64 | # 65 | export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home 66 | fi 67 | 68 | if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then 69 | # 70 | # Apple JDKs 71 | # 72 | export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home 73 | fi 74 | 75 | if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then 76 | # 77 | # Oracle JDKs 78 | # 79 | export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home 80 | fi 81 | 82 | if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then 83 | # 84 | # Apple JDKs 85 | # 86 | export JAVA_HOME=`/usr/libexec/java_home` 87 | fi 88 | ;; 89 | esac 90 | 91 | if [ -z "$JAVA_HOME" ] ; then 92 | if [ -r /etc/gentoo-release ] ; then 93 | JAVA_HOME=`java-config --jre-home` 94 | fi 95 | fi 96 | 97 | if [ -z "$M2_HOME" ] ; then 98 | ## resolve links - $0 may be a link to maven's home 99 | PRG="$0" 100 | 101 | # need this for relative symlinks 102 | while [ -h "$PRG" ] ; do 103 | ls=`ls -ld "$PRG"` 104 | link=`expr "$ls" : '.*-> \(.*\)$'` 105 | if expr "$link" : '/.*' > /dev/null; then 106 | PRG="$link" 107 | else 108 | PRG="`dirname "$PRG"`/$link" 109 | fi 110 | done 111 | 112 | saveddir=`pwd` 113 | 114 | M2_HOME=`dirname "$PRG"`/.. 115 | 116 | # make it fully qualified 117 | M2_HOME=`cd "$M2_HOME" && pwd` 118 | 119 | cd "$saveddir" 120 | # echo Using m2 at $M2_HOME 121 | fi 122 | 123 | # For Cygwin, ensure paths are in UNIX format before anything is touched 124 | if $cygwin ; then 125 | [ -n "$M2_HOME" ] && 126 | M2_HOME=`cygpath --unix "$M2_HOME"` 127 | [ -n "$JAVA_HOME" ] && 128 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 129 | [ -n "$CLASSPATH" ] && 130 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 131 | fi 132 | 133 | # For Migwn, ensure paths are in UNIX format before anything is touched 134 | if $mingw ; then 135 | [ -n "$M2_HOME" ] && 136 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 137 | [ -n "$JAVA_HOME" ] && 138 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 139 | # TODO classpath? 140 | fi 141 | 142 | if [ -z "$JAVA_HOME" ]; then 143 | javaExecutable="`which javac`" 144 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 145 | # readlink(1) is not available as standard on Solaris 10. 146 | readLink=`which readlink` 147 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 148 | if $darwin ; then 149 | javaHome="`dirname \"$javaExecutable\"`" 150 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 151 | else 152 | javaExecutable="`readlink -f \"$javaExecutable\"`" 153 | fi 154 | javaHome="`dirname \"$javaExecutable\"`" 155 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 156 | JAVA_HOME="$javaHome" 157 | export JAVA_HOME 158 | fi 159 | fi 160 | fi 161 | 162 | if [ -z "$JAVACMD" ] ; then 163 | if [ -n "$JAVA_HOME" ] ; then 164 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 165 | # IBM's JDK on AIX uses strange locations for the executables 166 | JAVACMD="$JAVA_HOME/jre/sh/java" 167 | else 168 | JAVACMD="$JAVA_HOME/bin/java" 169 | fi 170 | else 171 | JAVACMD="`which java`" 172 | fi 173 | fi 174 | 175 | if [ ! -x "$JAVACMD" ] ; then 176 | echo "Error: JAVA_HOME is not defined correctly." >&2 177 | echo " We cannot execute $JAVACMD" >&2 178 | exit 1 179 | fi 180 | 181 | if [ -z "$JAVA_HOME" ] ; then 182 | echo "Warning: JAVA_HOME environment variable is not set." 183 | fi 184 | 185 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 186 | 187 | # For Cygwin, switch paths to Windows format before running java 188 | if $cygwin; then 189 | [ -n "$M2_HOME" ] && 190 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 191 | [ -n "$JAVA_HOME" ] && 192 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 193 | [ -n "$CLASSPATH" ] && 194 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 195 | fi 196 | 197 | # traverses directory structure from process work directory to filesystem root 198 | # first directory with .mvn subdirectory is considered project base directory 199 | find_maven_basedir() { 200 | local basedir=$(pwd) 201 | local wdir=$(pwd) 202 | while [ "$wdir" != '/' ] ; do 203 | if [ -d "$wdir"/.mvn ] ; then 204 | basedir=$wdir 205 | break 206 | fi 207 | wdir=$(cd "$wdir/.."; pwd) 208 | done 209 | echo "${basedir}" 210 | } 211 | 212 | # concatenates all lines of a file 213 | concat_lines() { 214 | if [ -f "$1" ]; then 215 | echo "$(tr -s '\n' ' ' < "$1")" 216 | fi 217 | } 218 | 219 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} 220 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 221 | 222 | # Provide a "standardized" way to retrieve the CLI args that will 223 | # work with both Windows and non-Windows executions. 224 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 225 | export MAVEN_CMD_LINE_ARGS 226 | 227 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 228 | 229 | echo "Running version check" 230 | VERSION=$( sed '\!//' -e 's!.*$!!' ) 231 | echo "The found version is [${VERSION}]" 232 | 233 | if echo $VERSION | egrep -q 'M|RC'; then 234 | echo Activating \"milestone\" profile for version=\"$VERSION\" 235 | echo $MAVEN_ARGS | grep -q milestone || MAVEN_ARGS="$MAVEN_ARGS -Pmilestone" 236 | else 237 | echo Deactivating \"milestone\" profile for version=\"$VERSION\" 238 | echo $MAVEN_ARGS | grep -q milestone && MAVEN_ARGS=$(echo $MAVEN_ARGS | sed -e 's/-Pmilestone//') 239 | fi 240 | 241 | exec "$JAVACMD" \ 242 | $MAVEN_OPTS \ 243 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 244 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 245 | ${WRAPPER_LAUNCHER} ${MAVEN_ARGS} "$@" 246 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | set MAVEN_CMD_LINE_ARGS=%* 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | 121 | set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" 122 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 123 | 124 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% 125 | if ERRORLEVEL 1 goto error 126 | goto end 127 | 128 | :error 129 | set ERROR_CODE=1 130 | 131 | :end 132 | @endlocal & set ERROR_CODE=%ERROR_CODE% 133 | 134 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 135 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 136 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 137 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 138 | :skipRcPost 139 | 140 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 141 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 142 | 143 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 144 | 145 | exit /B %ERROR_CODE% 146 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | tensorflow-app-starters-build 5 | 1.2.0.RELEASE 6 | pom 7 | 8 | 9 | org.springframework.cloud.stream.app 10 | app-starters-build 11 | 1.2.0.RELEASE 12 | 13 | 14 | 15 | 16 | spring-cloud-starter-stream-processor-tensorflow 17 | tensorflow-app-dependencies 18 | tensorflow-app-starters-test-support 19 | spring-cloud-starter-stream-processor-twitter-sentiment 20 | spring-cloud-starter-stream-processor-label-image 21 | 22 | 23 | 24 | 25 | 26 | org.springframework.cloud.stream.app 27 | tensorflow-app-dependencies 28 | 1.2.0.RELEASE 29 | pom 30 | import 31 | 32 | 33 | 34 | 35 | 36 | spring 37 | 38 | 39 | spring-snapshots 40 | Spring Snapshots 41 | http://repo.spring.io/libs-snapshot-local 42 | 43 | true 44 | 45 | 46 | 47 | spring-milestones 48 | Spring Milestones 49 | http://repo.spring.io/libs-milestone-local 50 | 51 | false 52 | 53 | 54 | 55 | spring-releases 56 | Spring Releases 57 | http://repo.spring.io/release 58 | 59 | false 60 | 61 | 62 | 63 | spring-libs-release 64 | Spring Libs Release 65 | http://repo.spring.io/libs-release 66 | 67 | false 68 | 69 | 70 | 71 | 72 | false 73 | 74 | spring-milestone-release 75 | Spring Milestone Release 76 | http://repo.spring.io/libs-milestone 77 | 78 | 79 | 80 | 81 | spring-snapshots 82 | Spring Snapshots 83 | http://repo.spring.io/libs-snapshot-local 84 | 85 | true 86 | 87 | 88 | 89 | spring-milestones 90 | Spring Milestones 91 | http://repo.spring.io/libs-milestone-local 92 | 93 | false 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/README.adoc: -------------------------------------------------------------------------------- 1 | //tag::ref-doc[] 2 | = Image Labeling Processor 3 | 4 | A processor for real-time inference of pre-trained Inception TensorFlow model 5 | (https://github.com/tensorflow/models/tree/master/inception) that classifies JPEG images into 6 | 1 of 1000 categories. 7 | 8 | Result is JSON message in the format: 9 | 10 | ```json 11 | { 12 | "label" : "" 13 | } 14 | ``` 15 | 16 | If the `alternatives-length` is set to value K (where K > 0) the result will include an `alternatives` tag 17 | containing top K probable labels. For example for `alternatives-length=3` 18 | 19 | ```json 20 | { 21 | "alternatives": [ 22 | {"giant panda":0.98649305}, 23 | {"badger":0.010562794}, 24 | {"ice bear":0.001130851} 25 | ], 26 | "label" : "giant panda" 27 | } 28 | ``` 29 | 30 | == Options 31 | 32 | The **$$twitter-sentiment$$** $$processor$$ has the following options: 33 | 34 | //tag::configuration-properties[] 35 | $$inception.alternatives-length$$:: $$Number of top K alternatives to add to the result. Only used when the alternativesLength > 0.$$ *($$Integer$$, default: `$$-1$$`)* 36 | $$inception.labels-location$$:: $$$$ *($$Resource$$, default: `$$$$`)* 37 | $$tensorflow.model-location$$:: $$The location of the Tensorflow model file.$$ *($$Resource$$, default: `$$$$`)* 38 | $$tensorflow.output-index$$:: $$The model graph output index$$ *($$Integer$$, default: `$$0$$`)* 39 | $$tensorflow.output-name$$:: $$The model graph output name$$ *($$String$$, default: `$$$$`)* 40 | $$tensorflow.save-output-in-header$$:: $$Mark if the computed output has to stored in the outbound message's header or in the payload. 41 | Note: The Kafka binder requires you to withe list the custom headers. Therefore if you set the 42 | saveOutputInHeader to true the you have to start the SCDF server with this property: 43 | 44 | --spring.cloud.dataflow.applicationProperties.stream.spring.cloud.stream.kafka.binder.headers=TF_OUTPUT,TF_INPUT 45 | $$ *($$Boolean$$, default: `$$false$$`)* 46 | //end::configuration-properties[] 47 | 48 | //end::ref-doc[] 49 | == Build 50 | 51 | ``` 52 | $> mvn package 53 | ``` 54 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | spring-cloud-starter-stream-processor-label-image 6 | jar 7 | spring-cloud-starter-stream-processor-label-image 8 | Spring Cloud Stream processor-label-image core 9 | 10 | 11 | org.springframework.cloud.stream.app 12 | tensorflow-app-starters-build 13 | 1.2.0.RELEASE 14 | 15 | 16 | 17 | 18 | 19 | com.google.guava 20 | guava 21 | 21.0 22 | 23 | 24 | 25 | commons-io 26 | commons-io 27 | 28 | 29 | org.springframework.cloud.stream.app 30 | tensorflow-app-starters-test-support 31 | 32 | 33 | org.springframework.cloud.stream.app 34 | spring-cloud-starter-stream-processor-tensorflow 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.springframework.cloud 42 | spring-cloud-app-starter-doc-maven-plugin 43 | 44 | 45 | org.springframework.cloud.stream.app.plugin 46 | spring-cloud-stream-app-maven-plugin 47 | 48 | ${session.executionRootDirectory}/apps 49 | ${project.version} 50 | 51 | scs-bom 52 | org.springframework.cloud.stream.app 53 | tensorflow-app-dependencies 54 | ${project.version} 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/main/java/org/springframework/cloud/stream/app/label/image/processor/LabelImageProcessorConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.label.image.processor; 18 | 19 | import java.net.MalformedURLException; 20 | 21 | import org.apache.commons.logging.Log; 22 | import org.apache.commons.logging.LogFactory; 23 | 24 | import org.springframework.beans.factory.annotation.Autowired; 25 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 26 | import org.springframework.cloud.context.config.annotation.RefreshScope; 27 | import org.springframework.cloud.stream.annotation.EnableBinding; 28 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowInputConverter; 29 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowOutputConverter; 30 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorConfiguration; 31 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorProperties; 32 | import org.springframework.cloud.stream.messaging.Processor; 33 | import org.springframework.context.annotation.Bean; 34 | import org.springframework.context.annotation.Import; 35 | 36 | /** 37 | * A processor that evaluates a machine learning model stored in TensorFlow's ProtoBuf format. 38 | * 39 | * @author Christian Tzolov 40 | */ 41 | @EnableBinding(Processor.class) 42 | @EnableConfigurationProperties({ 43 | LabelImageProcessorProperties.class, TensorflowProcessorProperties.class}) 44 | @Import(TensorflowProcessorConfiguration.class) 45 | public class LabelImageProcessorConfiguration { 46 | 47 | private static final Log logger = LogFactory.getLog(LabelImageProcessorConfiguration.class); 48 | 49 | @Autowired 50 | private LabelImageProcessorProperties properties; 51 | 52 | @Bean 53 | public TensorflowOutputConverter tensorflowOutputConverter() { 54 | logger.info("Load list: " + properties.getLabelsLocation()); 55 | logger.info("Load LabelImageTensorflowOutputConverter"); 56 | return new LabelImageTensorflowOutputConverter(properties.getLabelsLocation(), properties.getAlternativesLength()); 57 | } 58 | 59 | @Bean 60 | @RefreshScope 61 | public TensorflowInputConverter tensorflowInputConverter() throws MalformedURLException { 62 | logger.info("Load LabelImageTensorflowInputConverter"); 63 | return new LabelImageTensorflowInputConverter(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/main/java/org/springframework/cloud/stream/app/label/image/processor/LabelImageProcessorProperties.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.label.image.processor; 18 | 19 | import javax.validation.constraints.NotNull; 20 | 21 | import org.springframework.boot.context.properties.ConfigurationProperties; 22 | import org.springframework.core.io.Resource; 23 | import org.springframework.validation.annotation.Validated; 24 | 25 | /** 26 | * @author Christian Tzolov 27 | */ 28 | @ConfigurationProperties("inception") 29 | @Validated 30 | public class LabelImageProcessorProperties { 31 | 32 | private Resource labelsLocation; 33 | 34 | /** 35 | * Number of top K alternatives to add to the result. Only used when the alternativesLength > 0. 36 | */ 37 | private int alternativesLength = -1; 38 | 39 | @NotNull 40 | public Resource getLabelsLocation() { 41 | return labelsLocation; 42 | } 43 | 44 | public void setLabelsLocation(Resource labelsLocation) { 45 | this.labelsLocation = labelsLocation; 46 | } 47 | 48 | public int getAlternativesLength() { 49 | return alternativesLength; 50 | } 51 | 52 | public void setAlternativesLength(int alternativesLength) { 53 | this.alternativesLength = alternativesLength; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/main/java/org/springframework/cloud/stream/app/label/image/processor/LabelImageTensorflowInputConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.label.image.processor; 18 | 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | import org.apache.commons.logging.Log; 23 | import org.apache.commons.logging.LogFactory; 24 | import org.tensorflow.DataType; 25 | import org.tensorflow.Graph; 26 | import org.tensorflow.Output; 27 | import org.tensorflow.Session; 28 | import org.tensorflow.Tensor; 29 | 30 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowInputConverter; 31 | import org.springframework.messaging.Message; 32 | 33 | /** 34 | * @author Christian Tzolov 35 | */ 36 | public class LabelImageTensorflowInputConverter implements TensorflowInputConverter, AutoCloseable { 37 | 38 | private static final Log logger = LogFactory.getLog(LabelImageTensorflowInputConverter.class); 39 | 40 | private final Graph graph; 41 | 42 | private final Output graphOutput; 43 | 44 | public LabelImageTensorflowInputConverter() { 45 | graph = new Graph(); 46 | GraphBuilder b = new GraphBuilder(graph); 47 | // Some constants specific to the pre-trained model at: 48 | // https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip 49 | // - The model was trained with images scaled to 224x224 pixels. 50 | // - The colors, represented as R, G, B in 1-byte each were converted to 51 | // float using (value - Mean)/Scale. 52 | final int H = 224; 53 | final int W = 224; 54 | final float mean = 117f; 55 | final float scale = 1f; 56 | 57 | final Output input = b.placeholder("input", DataType.STRING); 58 | graphOutput = 59 | b.div( 60 | b.sub( 61 | b.resizeBilinear( 62 | b.expandDims( 63 | b.cast(b.decodeJpeg(input, 3), DataType.FLOAT), 64 | b.constant("make_batch", 0)), 65 | b.constant("size", new int[] {H, W})), 66 | b.constant("mean", mean)), 67 | b.constant("scale", scale)); 68 | 69 | } 70 | 71 | private Tensor constructAndExecuteGraphToNormalizeImage3(byte[] imageBytes) { 72 | try (Session s = new Session(graph)) { 73 | try (Tensor inputTensor = Tensor.create(imageBytes)) { 74 | return s.runner().feed("input", inputTensor).fetch(graphOutput.op().name()).run().get(0); 75 | } 76 | } 77 | } 78 | 79 | @Override 80 | public Map convert(Message input, Map processorContext) { 81 | 82 | Object payload = input.getPayload(); 83 | 84 | if (payload instanceof byte[]) { 85 | Tensor inputImageTensor = constructAndExecuteGraphToNormalizeImage3((byte[]) payload); 86 | Map inputMap = new HashMap<>(); 87 | inputMap.put("input", inputImageTensor); 88 | 89 | return inputMap; 90 | } 91 | 92 | throw new IllegalArgumentException("Unsupported payload type:" + input.getPayload()); 93 | } 94 | 95 | @Override 96 | public void close() throws Exception { 97 | logger.info("Input Graph Destroyed"); 98 | if (graph != null) { 99 | graph.close(); 100 | } 101 | } 102 | 103 | // In the fullness of time, equivalents of the methods of this class should be auto-generated from 104 | // the OpDefs linked into libtensorflow_jni.so. That would match what is done in other languages 105 | // like Python, C++ and Go. 106 | static class GraphBuilder { 107 | private Graph g; 108 | 109 | GraphBuilder(Graph g) { 110 | this.g = g; 111 | } 112 | 113 | Output div(Output x, Output y) { 114 | return binaryOp("Div", x, y); 115 | } 116 | 117 | Output sub(Output x, Output y) { 118 | return binaryOp("Sub", x, y); 119 | } 120 | 121 | Output resizeBilinear(Output images, Output size) { 122 | return binaryOp("ResizeBilinear", images, size); 123 | } 124 | 125 | Output expandDims(Output input, Output dim) { 126 | return binaryOp("ExpandDims", input, dim); 127 | } 128 | 129 | Output cast(Output value, DataType dtype) { 130 | return g.opBuilder("Cast", "Cast").addInput(value).setAttr("DstT", dtype).build().output(0); 131 | } 132 | 133 | Output decodeJpeg(Output contents, long channels) { 134 | return g.opBuilder("DecodeJpeg", "DecodeJpeg") 135 | .addInput(contents) 136 | .setAttr("channels", channels) 137 | .build() 138 | .output(0); 139 | } 140 | 141 | Output constant(String name, Object value) { 142 | try (Tensor t = Tensor.create(value)) { 143 | return g.opBuilder("Const", name) 144 | .setAttr("dtype", t.dataType()) 145 | .setAttr("value", t) 146 | .build() 147 | .output(0); 148 | } 149 | } 150 | 151 | Output placeholder(String name, DataType dtype) { 152 | return g.opBuilder("Placeholder", name) 153 | .setAttr("dtype", dtype) 154 | .build() 155 | .output(0); 156 | } 157 | 158 | private Output binaryOp(String type, Output in1, Output in2) { 159 | return g.opBuilder(type, type).addInput(in1).addInput(in2).build().output(0); 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/main/java/org/springframework/cloud/stream/app/label/image/processor/LabelImageTensorflowOutputConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.label.image.processor; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | import java.nio.charset.Charset; 22 | import java.util.ArrayList; 23 | import java.util.Arrays; 24 | import java.util.HashMap; 25 | import java.util.List; 26 | import java.util.Map; 27 | 28 | import org.apache.commons.io.IOUtils; 29 | import org.apache.commons.logging.Log; 30 | import org.apache.commons.logging.LogFactory; 31 | import org.tensorflow.Tensor; 32 | 33 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowOutputConverter; 34 | import org.springframework.core.io.Resource; 35 | import org.springframework.util.Assert; 36 | 37 | import com.fasterxml.jackson.core.JsonProcessingException; 38 | import com.fasterxml.jackson.databind.ObjectMapper; 39 | import com.google.common.collect.Ordering; 40 | import com.google.common.primitives.Floats; 41 | 42 | /** 43 | * @author Christian Tzolov 44 | */ 45 | public class LabelImageTensorflowOutputConverter implements TensorflowOutputConverter { 46 | 47 | private static final Log logger = LogFactory.getLog(LabelImageTensorflowOutputConverter.class); 48 | 49 | private final List labels; 50 | 51 | private final ObjectMapper objectMapper; 52 | 53 | private final int alternativesLength; 54 | 55 | public LabelImageTensorflowOutputConverter(Resource labelsLocation, int alternativesLength) { 56 | this.alternativesLength = alternativesLength; 57 | try (InputStream is = labelsLocation.getInputStream()) { 58 | labels = IOUtils.readLines(is, Charset.forName("UTF-8")); 59 | objectMapper = new ObjectMapper(); 60 | Assert.notNull(labels, "Failed to initialize the labels list"); 61 | Assert.notNull(objectMapper, "Failed to initialize the objectMapper"); 62 | } 63 | catch (IOException e) { 64 | throw new RuntimeException("Failed to initialize the Vocabulary", e); 65 | } 66 | 67 | logger.info("Word Vocabulary Initialized"); 68 | 69 | } 70 | 71 | @Override 72 | public String convert(Tensor tensor, Map processorContext) { 73 | final long[] rshape = tensor.shape(); 74 | if (tensor.numDimensions() != 2 || rshape[0] != 1) { 75 | throw new RuntimeException( 76 | String.format( 77 | "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s", 78 | Arrays.toString(rshape))); 79 | } 80 | int nlabels = (int) rshape[1]; 81 | float[] labelProbabilities = tensor.copyTo(new float[1][nlabels])[0]; 82 | 83 | int mostProbableLabelIndex = maxProbabilityIndex(labelProbabilities); 84 | 85 | Map outputJsonMap = new HashMap<>(); 86 | outputJsonMap.put("label", labels.get(mostProbableLabelIndex)); 87 | 88 | 89 | if (alternativesLength > 0) { 90 | List top10Probabilities = topKProbabilities(labelProbabilities, alternativesLength); 91 | 92 | Map[] alternatives = new Map[top10Probabilities.size()]; 93 | for (int i = 0; i < top10Probabilities.size(); i++) { 94 | int probabilityInidex = top10Probabilities.get(i); 95 | alternatives[i] = toMap(labels.get(probabilityInidex), labelProbabilities[probabilityInidex]); 96 | } 97 | outputJsonMap.put("alternatives", alternatives); 98 | } 99 | 100 | try { 101 | return objectMapper.writeValueAsString(outputJsonMap); 102 | } 103 | catch (JsonProcessingException e) { 104 | throw new RuntimeException("Failed to generate JSON output", e); 105 | } 106 | } 107 | 108 | private List topKProbabilities(final float[] labelProbabilities, int k) { 109 | 110 | List list = new ArrayList<>(labelProbabilities.length); 111 | for (int i = 0; i < labelProbabilities.length; i++) { 112 | list.add(i); 113 | } 114 | 115 | List topK = new Ordering() { 116 | @Override 117 | public int compare(Integer left, Integer right) { 118 | return Floats.compare(labelProbabilities[left], labelProbabilities[right]); 119 | } 120 | }.greatestOf(list, k); 121 | 122 | return topK; 123 | } 124 | 125 | private Map toMap(String key, float value) { 126 | Map map = new HashMap<>(); 127 | map.put(key, value); 128 | return map; 129 | } 130 | 131 | private int maxProbabilityIndex(float[] probabilities) { 132 | int best = 0; 133 | for (int i = 1; i < probabilities.length; ++i) { 134 | if (probabilities[i] > probabilities[best]) { 135 | best = i; 136 | } 137 | } 138 | return best; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/main/resources/META-INF/spring-configuration-metadata-whitelist.properties: -------------------------------------------------------------------------------- 1 | configuration-properties.classes=org.springframework.cloud.stream.app.label.image.processor.LabelImageProcessorProperties, org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorProperties -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/main/resources/META-INF/spring.provides: -------------------------------------------------------------------------------- 1 | provides: spring-cloud-starter-stream-processor-label-image 2 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/test/java/org/springframework/cloud/stream/app/label/image/processor/LabelImageProcessorPropertiesTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.label.image.processor; 18 | 19 | import static org.hamcrest.core.IsEqual.equalTo; 20 | import static org.junit.Assert.assertThat; 21 | 22 | import org.junit.Test; 23 | 24 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 25 | import org.springframework.boot.test.util.EnvironmentTestUtils; 26 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 27 | import org.springframework.context.annotation.Configuration; 28 | 29 | /** 30 | * @author Christian Tzolov 31 | */ 32 | public class LabelImageProcessorPropertiesTest { 33 | 34 | @Test 35 | public void labelsLocationCanBeCustomized() { 36 | AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); 37 | EnvironmentTestUtils.addEnvironment(context, "inception.labelsLocation:/remote"); 38 | context.register(Conf.class); 39 | context.refresh(); 40 | LabelImageProcessorProperties properties = context.getBean(LabelImageProcessorProperties.class); 41 | assertThat(properties.getLabelsLocation(), equalTo(context.getResource("/remote"))); 42 | } 43 | 44 | @Test 45 | public void alternativesLengthCanBeCustomized() { 46 | AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); 47 | EnvironmentTestUtils.addEnvironment(context, "inception.labelsLocation:/remote"); 48 | EnvironmentTestUtils.addEnvironment(context, "inception.alternativesLength:5"); 49 | context.register(Conf.class); 50 | context.refresh(); 51 | LabelImageProcessorProperties properties = context.getBean(LabelImageProcessorProperties.class); 52 | assertThat(properties.getAlternativesLength(), equalTo(5)); 53 | } 54 | 55 | @Configuration 56 | @EnableConfigurationProperties(LabelImageProcessorProperties.class) 57 | static class Conf { 58 | 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/test/java/org/springframework/cloud/stream/app/label/image/processor/inception/LabelImageTensorflowProcessorIntegrationTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.label.image.processor.inception; 18 | 19 | import static org.hamcrest.Matchers.equalTo; 20 | import static org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorConfiguration.TF_OUTPUT_HEADER; 21 | 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | 25 | import org.apache.commons.io.IOUtils; 26 | import org.junit.Assert; 27 | import org.junit.Test; 28 | import org.junit.runner.RunWith; 29 | 30 | import org.springframework.beans.factory.annotation.Autowired; 31 | import org.springframework.boot.autoconfigure.SpringBootApplication; 32 | import org.springframework.boot.test.context.SpringBootTest; 33 | import org.springframework.cloud.stream.app.label.image.processor.LabelImageProcessorConfiguration; 34 | import org.springframework.cloud.stream.messaging.Processor; 35 | import org.springframework.cloud.stream.test.binder.MessageCollector; 36 | import org.springframework.context.annotation.Import; 37 | import org.springframework.core.io.ClassPathResource; 38 | import org.springframework.integration.support.MessageBuilder; 39 | import org.springframework.messaging.Message; 40 | import org.springframework.test.annotation.DirtiesContext; 41 | import org.springframework.test.context.TestPropertySource; 42 | import org.springframework.test.context.junit4.SpringRunner; 43 | 44 | /** 45 | * @author Christian Tzolov 46 | */ 47 | @SuppressWarnings("SpringJavaAutowiringInspection") 48 | @RunWith(SpringRunner.class) 49 | @SpringBootTest( 50 | webEnvironment = SpringBootTest.WebEnvironment.NONE, 51 | properties = { 52 | "tensorflow.modelLocation=http://dl.bintray.com/big-data/generic/tensorflow_inception_graph.pb", 53 | "tensorflow.outputName=output", 54 | "inception.labelsLocation=http://dl.bintray.com/big-data/generic/imagenet_comp_graph_label_strings.txt" 55 | }) 56 | @DirtiesContext 57 | public abstract class LabelImageTensorflowProcessorIntegrationTests { 58 | 59 | @Autowired 60 | protected Processor channels; 61 | 62 | @Autowired 63 | protected MessageCollector messageCollector; 64 | 65 | 66 | @TestPropertySource(properties = {"tensorflow.saveOutputInHeader=true"}) 67 | public static class OutputInHeaderTests extends LabelImageTensorflowProcessorIntegrationTests { 68 | 69 | @Test 70 | public void testEvaluationPositive() throws IOException { 71 | try(InputStream is = new ClassPathResource("/images/panda.jpeg").getInputStream()) { 72 | 73 | byte[] image = IOUtils.toByteArray(is); 74 | 75 | testEvaluationWithOutputInHeader( 76 | image, "{\"label\":\"giant panda\"}"); 77 | } 78 | } 79 | 80 | private void testEvaluationWithOutputInHeader(byte[] image, String resultJson) { 81 | channels.input().send(MessageBuilder.withPayload(image).build()); 82 | 83 | Message received = messageCollector.forChannel(channels.output()).poll(); 84 | 85 | Assert.assertThat(received.getHeaders().get(TF_OUTPUT_HEADER).toString(), equalTo(resultJson)); 86 | } 87 | } 88 | 89 | @TestPropertySource(properties = {"tensorflow.saveOutputInHeader=false"}) 90 | public static class OutputInPayloadTests extends LabelImageTensorflowProcessorIntegrationTests { 91 | 92 | @Test 93 | public void testEvaluationPositive() throws IOException { 94 | try(InputStream is = new ClassPathResource("/images/panda.jpeg").getInputStream()) { 95 | 96 | byte[] image = IOUtils.toByteArray(is); 97 | 98 | channels.input().send(MessageBuilder.withPayload(image).build()); 99 | 100 | Message received = (Message) messageCollector.forChannel(channels.output()).poll(); 101 | 102 | Assert.assertTrue(received.getPayload().getClass().isAssignableFrom(String.class)); 103 | 104 | Assert.assertThat(received.getPayload().toString(), 105 | equalTo("{\"label\":\"giant panda\"}")); 106 | } 107 | } 108 | } 109 | 110 | @TestPropertySource(properties = {"inception.alternativesLength=3"}) 111 | public static class OutputWithAlternativesTests extends LabelImageTensorflowProcessorIntegrationTests { 112 | 113 | @Test 114 | public void testEvaluationPositive() throws IOException { 115 | try(InputStream is = new ClassPathResource("/images/panda.jpeg").getInputStream()) { 116 | 117 | byte[] image = IOUtils.toByteArray(is); 118 | 119 | channels.input().send(MessageBuilder.withPayload(image).build()); 120 | 121 | Message received = (Message) messageCollector.forChannel(channels.output()).poll(); 122 | 123 | Assert.assertTrue(received.getPayload().getClass().isAssignableFrom(String.class)); 124 | 125 | Assert.assertThat(received.getPayload().toString(), 126 | equalTo("{\"alternatives\":[" + 127 | "{\"giant panda\":0.98649305}," + 128 | "{\"badger\":0.010562794}," + 129 | "{\"ice bear\":0.001130851}]," + 130 | "\"label\":\"giant panda\"}")); 131 | } 132 | } 133 | } 134 | 135 | @SpringBootApplication 136 | @Import(LabelImageProcessorConfiguration.class) 137 | public static class TensorflowProcessorApplication { 138 | 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/test/resources/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2015 The TensorFlow Authors. All rights reserved. 2 | 3 | Apache License 4 | Version 2.0, January 2004 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, 12 | and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by 15 | the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all 18 | other entities that control, are controlled by, or are under common 19 | control with that entity. For the purposes of this definition, 20 | "control" means (i) the power, direct or indirect, to cause the 21 | direction or management of such entity, whether by contract or 22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 23 | outstanding shares, or (iii) beneficial ownership of such entity. 24 | 25 | "You" (or "Your") shall mean an individual or Legal Entity 26 | exercising permissions granted by this License. 27 | 28 | "Source" form shall mean the preferred form for making modifications, 29 | including but not limited to software source code, documentation 30 | source, and configuration files. 31 | 32 | "Object" form shall mean any form resulting from mechanical 33 | transformation or translation of a Source form, including but 34 | not limited to compiled object code, generated documentation, 35 | and conversions to other media types. 36 | 37 | "Work" shall mean the work of authorship, whether in Source or 38 | Object form, made available under the License, as indicated by a 39 | copyright notice that is included in or attached to the work 40 | (an example is provided in the Appendix below). 41 | 42 | "Derivative Works" shall mean any work, whether in Source or Object 43 | form, that is based on (or derived from) the Work and for which the 44 | editorial revisions, annotations, elaborations, or other modifications 45 | represent, as a whole, an original work of authorship. For the purposes 46 | of this License, Derivative Works shall not include works that remain 47 | separable from, or merely link (or bind by name) to the interfaces of, 48 | the Work and Derivative Works thereof. 49 | 50 | "Contribution" shall mean any work of authorship, including 51 | the original version of the Work and any modifications or additions 52 | to that Work or Derivative Works thereof, that is intentionally 53 | submitted to Licensor for inclusion in the Work by the copyright owner 54 | or by an individual or Legal Entity authorized to submit on behalf of 55 | the copyright owner. For the purposes of this definition, "submitted" 56 | means any form of electronic, verbal, or written communication sent 57 | to the Licensor or its representatives, including but not limited to 58 | communication on electronic mailing lists, source code control systems, 59 | and issue tracking systems that are managed by, or on behalf of, the 60 | Licensor for the purpose of discussing and improving the Work, but 61 | excluding communication that is conspicuously marked or otherwise 62 | designated in writing by the copyright owner as "Not a Contribution." 63 | 64 | "Contributor" shall mean Licensor and any individual or Legal Entity 65 | on behalf of whom a Contribution has been received by Licensor and 66 | subsequently incorporated within the Work. 67 | 68 | 2. Grant of Copyright License. Subject to the terms and conditions of 69 | this License, each Contributor hereby grants to You a perpetual, 70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 71 | copyright license to reproduce, prepare Derivative Works of, 72 | publicly display, publicly perform, sublicense, and distribute the 73 | Work and such Derivative Works in Source or Object form. 74 | 75 | 3. Grant of Patent License. Subject to the terms and conditions of 76 | this License, each Contributor hereby grants to You a perpetual, 77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 78 | (except as stated in this section) patent license to make, have made, 79 | use, offer to sell, sell, import, and otherwise transfer the Work, 80 | where such license applies only to those patent claims licensable 81 | by such Contributor that are necessarily infringed by their 82 | Contribution(s) alone or by combination of their Contribution(s) 83 | with the Work to which such Contribution(s) was submitted. If You 84 | institute patent litigation against any entity (including a 85 | cross-claim or counterclaim in a lawsuit) alleging that the Work 86 | or a Contribution incorporated within the Work constitutes direct 87 | or contributory patent infringement, then any patent licenses 88 | granted to You under this License for that Work shall terminate 89 | as of the date such litigation is filed. 90 | 91 | 4. Redistribution. You may reproduce and distribute copies of the 92 | Work or Derivative Works thereof in any medium, with or without 93 | modifications, and in Source or Object form, provided that You 94 | meet the following conditions: 95 | 96 | (a) You must give any other recipients of the Work or 97 | Derivative Works a copy of this License; and 98 | 99 | (b) You must cause any modified files to carry prominent notices 100 | stating that You changed the files; and 101 | 102 | (c) You must retain, in the Source form of any Derivative Works 103 | that You distribute, all copyright, patent, trademark, and 104 | attribution notices from the Source form of the Work, 105 | excluding those notices that do not pertain to any part of 106 | the Derivative Works; and 107 | 108 | (d) If the Work includes a "NOTICE" text file as part of its 109 | distribution, then any Derivative Works that You distribute must 110 | include a readable copy of the attribution notices contained 111 | within such NOTICE file, excluding those notices that do not 112 | pertain to any part of the Derivative Works, in at least one 113 | of the following places: within a NOTICE text file distributed 114 | as part of the Derivative Works; within the Source form or 115 | documentation, if provided along with the Derivative Works; or, 116 | within a display generated by the Derivative Works, if and 117 | wherever such third-party notices normally appear. The contents 118 | of the NOTICE file are for informational purposes only and 119 | do not modify the License. You may add Your own attribution 120 | notices within Derivative Works that You distribute, alongside 121 | or as an addendum to the NOTICE text from the Work, provided 122 | that such additional attribution notices cannot be construed 123 | as modifying the License. 124 | 125 | You may add Your own copyright statement to Your modifications and 126 | may provide additional or different license terms and conditions 127 | for use, reproduction, or distribution of Your modifications, or 128 | for any such Derivative Works as a whole, provided Your use, 129 | reproduction, and distribution of the Work otherwise complies with 130 | the conditions stated in this License. 131 | 132 | 5. Submission of Contributions. Unless You explicitly state otherwise, 133 | any Contribution intentionally submitted for inclusion in the Work 134 | by You to the Licensor shall be under the terms and conditions of 135 | this License, without any additional terms or conditions. 136 | Notwithstanding the above, nothing herein shall supersede or modify 137 | the terms of any separate license agreement you may have executed 138 | with Licensor regarding such Contributions. 139 | 140 | 6. Trademarks. This License does not grant permission to use the trade 141 | names, trademarks, service marks, or product names of the Licensor, 142 | except as required for reasonable and customary use in describing the 143 | origin of the Work and reproducing the content of the NOTICE file. 144 | 145 | 7. Disclaimer of Warranty. Unless required by applicable law or 146 | agreed to in writing, Licensor provides the Work (and each 147 | Contributor provides its Contributions) on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 149 | implied, including, without limitation, any warranties or conditions 150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 151 | PARTICULAR PURPOSE. You are solely responsible for determining the 152 | appropriateness of using or redistributing the Work and assume any 153 | risks associated with Your exercise of permissions under this License. 154 | 155 | 8. Limitation of Liability. In no event and under no legal theory, 156 | whether in tort (including negligence), contract, or otherwise, 157 | unless required by applicable law (such as deliberate and grossly 158 | negligent acts) or agreed to in writing, shall any Contributor be 159 | liable to You for damages, including any direct, indirect, special, 160 | incidental, or consequential damages of any character arising as a 161 | result of this License or out of the use or inability to use the 162 | Work (including but not limited to damages for loss of goodwill, 163 | work stoppage, computer failure or malfunction, or any and all 164 | other commercial damages or losses), even if such Contributor 165 | has been advised of the possibility of such damages. 166 | 167 | 9. Accepting Warranty or Additional Liability. While redistributing 168 | the Work or Derivative Works thereof, You may choose to offer, 169 | and charge a fee for, acceptance of support, warranty, indemnity, 170 | or other liability obligations and/or rights consistent with this 171 | License. However, in accepting such obligations, You may act only 172 | on Your own behalf and on Your sole responsibility, not on behalf 173 | of any other Contributor, and only if You agree to indemnify, 174 | defend, and hold each Contributor harmless for any liability 175 | incurred by, or claims asserted against, such Contributor by reason 176 | of your accepting any such warranty or additional liability. 177 | 178 | END OF TERMS AND CONDITIONS 179 | 180 | APPENDIX: How to apply the Apache License to your work. 181 | 182 | To apply the Apache License to your work, attach the following 183 | boilerplate notice, with the fields enclosed by brackets "[]" 184 | replaced with your own identifying information. (Don't include 185 | the brackets!) The text should be enclosed in the appropriate 186 | comment syntax for the file format. We also recommend that a 187 | file or class name and description of purpose be included on the 188 | same "printed page" as the copyright notice for easier 189 | identification within third-party archives. 190 | 191 | Copyright 2015, The TensorFlow Authors. 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/test/resources/SCDF_TF_Sentiment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tzolov/tensorflow-spring-cloud-stream-app-starters/d58fec9917894c3797bec7db049141845192d6be/spring-cloud-starter-stream-processor-label-image/src/test/resources/SCDF_TF_Sentiment.png -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-label-image/src/test/resources/images/panda.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tzolov/tensorflow-spring-cloud-stream-app-starters/d58fec9917894c3797bec7db049141845192d6be/spring-cloud-starter-stream-processor-label-image/src/test/resources/images/panda.jpeg -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/README.adoc: -------------------------------------------------------------------------------- 1 | //tag::ref-doc[] 2 | = TensorFlow Processor 3 | 4 | A processor that evaluates a machine learning model stored in TensorFlow Protobuf format. 5 | 6 | image::src/test/resources/TensorFlowProcessorArcutectureOverview.png[] 7 | 8 | The TensorFlow Processor uses a `TensorflowInputConverter` to convert the input data into data format compliant with the 9 | TensorFlow Model used. The input converter converts the input `Messagea into key/value `Map`, where 10 | the Key corresponds to a model input placeholder and the content is `org.tensorflow.DataType` compliant value. 11 | The default converter implementation expects either Map payload or flat json message that can be converted int a Map. 12 | 13 | The `TensorflowInputConverter` can be extended and customized. See link::../spring-cloud-starter-stream-processor-twitter-sentiment/src/main/java/org/springframework/cloud/stream/app/twitter/sentiment/processor/TwitterSentimentTensorflowInputConverter.java[TwitterSentimentTensorflowInputConverter.java] for example 14 | 15 | Processor's output uses `TensorflowOutputConverter` to convert the computed `Tensor` result into a serializable 16 | message. The default implementation uses `Tuple` triple. 17 | 18 | Custom `TensorflowOutputConverter` can provide more convenient data representations. 19 | See link::../spring-cloud-starter-stream-processor-twitter-sentiment/src/main/java/org/springframework/cloud/stream/app/twitter/sentiment/processor/TwitterSentimentTensorflowOutputConverter.java[TwitterSentimentTensorflowOutputConverter.java] 20 | 21 | 22 | Following snippet shows how to export any `TensorFlow` model (trained as well) into `ProtocolBuffer` binary format as required by the Processor. 23 | ```python 24 | from tensorflow.python.framework.graph_util import convert_variables_to_constants 25 | ... 26 | SAVE_DIR = os.path.abspath(os.path.curdir) 27 | minimal_graph = convert_variables_to_constants(sess, sess.graph_def, ['']) 28 | tf.train.write_graph(minimal_graph, SAVE_DIR, 'my_graph.proto', as_text=False) 29 | tf.train.write_graph(minimal_graph, SAVE_DIR, 'my.txt', as_text=True) 30 | ``` 31 | 32 | == Options 33 | 34 | The **$$tensorflow$$** $$processor$$ has the following options: 35 | 36 | //tag::configuration-properties[] 37 | $$tensorflow.model-location$$:: $$The location of the Tensorflow model file.$$ *($$Resource$$, default: `$$$$`)* 38 | $$tensorflow.output-index$$:: $$The model graph output index$$ *($$Integer$$, default: `$$0$$`)* 39 | $$tensorflow.output-name$$:: $$The model graph output name$$ *($$String$$, default: `$$$$`)* 40 | $$tensorflow.save-output-in-header$$:: $$Mark if the computed output has to stored in the outbound message's header or in the payload. 41 | Note: The Kafka binder requires you to withe list the custom headers. Therefore if you set the 42 | saveOutputInHeader to true the you have to start the SCDF server with this property: 43 | 44 | --spring.cloud.dataflow.applicationProperties.stream.spring.cloud.stream.kafka.binder.headers=TF_OUTPUT,TF_INPUT 45 | $$ *($$Boolean$$, default: `$$false$$`)* 46 | //end::configuration-properties[] 47 | 48 | //end::ref-doc[] 49 | == Build 50 | 51 | ``` 52 | $> mvn package 53 | ``` 54 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | spring-cloud-starter-stream-processor-tensorflow 6 | jar 7 | spring-cloud-starter-stream-processor-tensorflow 8 | Spring Cloud Stream processor-tensorflow core 9 | 10 | 11 | org.springframework.cloud.stream.app 12 | tensorflow-app-starters-build 13 | 1.2.0.RELEASE 14 | 15 | 16 | 17 | 18 | org.tensorflow 19 | tensorflow 20 | 21 | 22 | commons-io 23 | commons-io 24 | 25 | 26 | org.springframework.cloud 27 | spring-cloud-bus 28 | 29 | 30 | org.springframework.cloud 31 | spring-cloud-starter-config 32 | 33 | 34 | org.springframework.cloud.stream.app 35 | tensorflow-app-starters-test-support 36 | 37 | 38 | 39 | 40 | 41 | 42 | org.springframework.cloud 43 | spring-cloud-app-starter-doc-maven-plugin 44 | 45 | 46 | org.springframework.cloud.stream.app.plugin 47 | spring-cloud-stream-app-maven-plugin 48 | 49 | ${session.executionRootDirectory}/apps 50 | ${project.version} 51 | 52 | scs-bom 53 | org.springframework.cloud.stream.app 54 | tensorflow-app-dependencies 55 | ${project.version} 56 | 57 | 58 | 59 | org.springframework.cloud.stream.app.test.tensorflow.TensorflowProcessorTestConfiguration.class 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/main/java/org/springframework/cloud/stream/app/tensorflow/processor/TensorFlowService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.tensorflow.processor; 18 | 19 | import static org.apache.commons.io.IOUtils.buffer; 20 | import static org.apache.commons.io.IOUtils.toByteArray; 21 | 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.util.Map; 25 | import java.util.Map.Entry; 26 | 27 | import org.apache.commons.logging.Log; 28 | import org.apache.commons.logging.LogFactory; 29 | import org.tensorflow.Graph; 30 | import org.tensorflow.Session; 31 | import org.tensorflow.Session.Runner; 32 | import org.tensorflow.Tensor; 33 | 34 | import org.springframework.core.io.Resource; 35 | import org.springframework.tuple.Tuple; 36 | 37 | /** 38 | * @author Christian Tzolov 39 | */ 40 | public class TensorFlowService implements AutoCloseable { 41 | 42 | private static final Log logger = LogFactory.getLog(TensorflowProcessorConfiguration.class); 43 | 44 | private Graph graph; 45 | 46 | public TensorFlowService(Resource modelLocation) throws IOException { 47 | try (InputStream is = modelLocation.getInputStream()) { 48 | graph = new Graph(); 49 | logger.info("Loading TensorFlow graph model: " + modelLocation); 50 | graph.importGraphDef(toByteArray(buffer(is))); 51 | logger.info("TensorFlow Graph Model Ready To Serve!"); 52 | } 53 | } 54 | 55 | public Tensor evaluate(Map feeds, String outputName, int outputIndex) { 56 | 57 | try (Session session = new Session(graph)) { 58 | 59 | Runner runner = session.runner(); 60 | 61 | // Keep tensor references to release them in the finally block 62 | Tensor[] feedTensors = new Tensor[feeds.size()]; 63 | try { 64 | int i = 0; 65 | for (Entry e : feeds.entrySet()) { 66 | String feedName = e.getKey(); 67 | feedTensors[i] = toFeedTensor(e.getValue()); 68 | runner = runner.feed(feedName, feedTensors[i]); 69 | i++; 70 | } 71 | return runner.fetch(outputName).run().get(outputIndex); 72 | } 73 | finally { 74 | // Release all feed tensors 75 | for (Tensor tensor : feedTensors) { 76 | if (tensor != null) { 77 | tensor.close(); 78 | } 79 | } 80 | } 81 | } 82 | } 83 | 84 | private Tensor toFeedTensor(Object value) { 85 | if (value instanceof Tensor) { 86 | return (Tensor) value; 87 | } 88 | else if (value instanceof Tuple) { 89 | return TensorTupleConverter.toTensor((Tuple) value); 90 | } 91 | 92 | return Tensor.create(value); 93 | } 94 | 95 | @Override 96 | public void close() throws Exception { 97 | logger.info("Close TensorFlow Graph!"); 98 | if (graph != null) { 99 | graph.close(); 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/main/java/org/springframework/cloud/stream/app/tensorflow/processor/TensorTupleConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.tensorflow.processor; 18 | 19 | import java.nio.ByteBuffer; 20 | 21 | import org.tensorflow.DataType; 22 | import org.tensorflow.Tensor; 23 | 24 | import org.springframework.tuple.Tuple; 25 | import org.springframework.tuple.TupleBuilder; 26 | 27 | /** 28 | * Utility that helps to covert {@link Tensor} to {@link Tuple} and in reverse. 29 | * @author Christian Tzolov 30 | */ 31 | public class TensorTupleConverter { 32 | 33 | public static final String TF_DATA_TYPE = "type"; 34 | 35 | public static final String TF_SHAPE = "shape"; 36 | 37 | public static final String TF_VALUE = "value"; 38 | 39 | public static Tuple toTuple(Tensor tensor) { 40 | ByteBuffer buffer = ByteBuffer.allocate(tensor.numBytes()); 41 | tensor.writeTo(buffer); 42 | 43 | // Retrieve all bytes in the buffer 44 | buffer.clear(); 45 | byte[] bytes = new byte[buffer.capacity()]; 46 | 47 | buffer.get(bytes, 0, bytes.length); 48 | 49 | return TupleBuilder.tuple() 50 | .put(TF_DATA_TYPE, tensor.dataType().name()) 51 | .put(TF_SHAPE, tensor.shape()) 52 | .put(TF_VALUE, bytes) 53 | .build(); 54 | } 55 | 56 | public static Tensor toTensor(Tuple tuple) { 57 | DataType dataType = DataType.valueOf(tuple.getString(TF_DATA_TYPE)); 58 | long[] shape = (long[]) tuple.getValue(TF_SHAPE); 59 | byte[] bytes = (byte[]) tuple.getValue(TF_VALUE); 60 | 61 | return Tensor.create(dataType, shape, ByteBuffer.wrap(bytes)); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/main/java/org/springframework/cloud/stream/app/tensorflow/processor/TensorflowInputConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.tensorflow.processor; 18 | 19 | import java.util.Map; 20 | 21 | import org.springframework.messaging.Message; 22 | 23 | /** 24 | * The {@link TensorflowInputConverter} is called by the TensorFlow Processor to convert the incoming {@link Message}s 25 | * into a data type that matches the input of the TensorFlow model being used. 26 | * 27 | * The default implementation assumes that the received data has already been covered (before sent to the processor) and 28 | * is encoded into key/value Map or flat key/value JSON message. Where each kek in the map corresponds to a model input 29 | * placeholder and the value is compliant with TensorFlow's {@link org.tensorflow.DataType}. 30 | * 31 | * @see TwitterSentimentTensorflowInputConverter.java for how to build custom {@link TensorflowInputConverter}. 32 | * 33 | * @author Christian Tzolov 34 | */ 35 | public interface TensorflowInputConverter { 36 | /** 37 | * 38 | * @param input Processor's input message 39 | * @param processorContext Context used to share information between the Input and Output converters 40 | * @return Returns map that corresponds to the TensorFlow model's input format. 41 | */ 42 | Map convert(Message input, Map processorContext); 43 | } 44 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/main/java/org/springframework/cloud/stream/app/tensorflow/processor/TensorflowOutputConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.tensorflow.processor; 18 | 19 | import java.util.Map; 20 | 21 | import org.tensorflow.Tensor; 22 | 23 | import org.springframework.tuple.Tuple; 24 | 25 | /** 26 | * The TensorFlow evaluation result is represented by a (non-serializable) {@link Tensor} instance. 27 | * 28 | * Implementations of this interface are responsible to convert the {@link Tensor} instance into a serializable type 29 | * that can be send as a Message. 30 | * 31 | * The default implementation coverts the {@link Tensor} into {@link org.springframework.tuple.Tuple} with 3 elements: 32 | *
  • 33 | * "type" : TensorFlow {@link org.tensorflow.DataType} name 34 | * "shape" : TensorFlow's shape 35 | * "value" : ByteBuffer encoded Tensor's value. 36 | *
  • 37 | * 38 | * It is the responsibility of the consumers of this message to decode the Tuple back into {@link Tensor} instance. 39 | * The helper {@link TensorTupleConverter#toTensor(Tuple)} static method helps to do this. 40 | * 41 | * A better approach is to provide a custom {@link TensorflowOutputConverter} implementation. 42 | * @see TwitterSentimentTensorflowOutputConverter.java for how to build custom {@link TensorflowOutputConverter}. 43 | * 44 | * @author Christian Tzolov 45 | */ 46 | public interface TensorflowOutputConverter { 47 | /** 48 | * 49 | * @param tensor {@link Tensor} result of the model evaluation. 50 | * @param processorContext processorContext Context used to share information between the Input and Output converters 51 | * @return Returns the converted {@link Tensor} data. 52 | */ 53 | T convert(Tensor tensor, Map processorContext); 54 | } 55 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/main/java/org/springframework/cloud/stream/app/tensorflow/processor/TensorflowProcessorConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.tensorflow.processor; 18 | 19 | import java.io.IOException; 20 | import java.util.Map; 21 | import java.util.concurrent.ConcurrentHashMap; 22 | 23 | import org.apache.commons.logging.Log; 24 | import org.apache.commons.logging.LogFactory; 25 | import org.tensorflow.Tensor; 26 | 27 | import org.springframework.beans.factory.annotation.Autowired; 28 | import org.springframework.beans.factory.annotation.Qualifier; 29 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 30 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 31 | import org.springframework.cloud.context.config.annotation.RefreshScope; 32 | import org.springframework.cloud.stream.annotation.EnableBinding; 33 | import org.springframework.cloud.stream.messaging.Processor; 34 | import org.springframework.context.annotation.Bean; 35 | import org.springframework.integration.annotation.ServiceActivator; 36 | import org.springframework.integration.support.MessageBuilder; 37 | import org.springframework.messaging.Message; 38 | import org.springframework.tuple.Tuple; 39 | 40 | /** 41 | * A processor that evaluates a machine learning model stored in TensorFlow's ProtoBuf format. 42 | * 43 | * Processor uses a {@link TensorflowInputConverter} to convert the input data into data format compliant with the 44 | * TensorFlow Model used. The input converter converts the input {@link Message} into key/value {@link Map}, where 45 | * the Key corresponds to a model input placeholder and the content is {@link org.tensorflow.DataType} compliant value. 46 | * The default converter implementation expects either Map payload or flat json message that can be converted int a Map. 47 | * 48 | * The {@link TensorflowInputConverter} can be extended and customized. 49 | * 50 | * Processor's output uses {@link TensorflowOutputConverter} to convert the computed {@link Tensor} result into a serializable 51 | * message. The default implementation uses {@link Tuple} triple (see: {@link TensorflowOutputConverter}). 52 | * 53 | * Custom {@link TensorflowOutputConverter} can provide more convenient data representations. 54 | * (see TwitterSentimentTensorflowOutputConverter.java 55 | * 56 | * @author Christian Tzolov 57 | */ 58 | @EnableBinding(Processor.class) 59 | @EnableConfigurationProperties(TensorflowProcessorProperties.class) 60 | public class TensorflowProcessorConfiguration implements AutoCloseable { 61 | 62 | private static final Log logger = LogFactory.getLog(TensorflowProcessorConfiguration.class); 63 | 64 | /** 65 | * Header name where the output is stored if the isSaveOutputInHeader is set 66 | */ 67 | public static final String TF_OUTPUT_HEADER = "TF_OUTPUT"; 68 | 69 | /** 70 | * Note: The Kafka binder requires you to withe list the custom headers. Therefore if you set the 71 | * saveOutputInHeader to true the you have to start the SCDF server with this property: 72 | * 73 | * --spring.cloud.dataflow.applicationProperties.stream.spring.cloud.stream.kafka.binder.headers=TF_OUTPUT,TF_INPUT 74 | * 75 | */ 76 | 77 | /** 78 | * Header name where the input is stored. 79 | * The default TensorflowInputConverter implementation will use TF_INPUT header if provided it over 80 | * the message payload. 81 | */ 82 | public static final String TF_INPUT_HEADER = "TF_INPUT"; 83 | 84 | 85 | @Autowired 86 | private TensorflowProcessorProperties properties; 87 | 88 | @Autowired 89 | @Qualifier("tensorflowInputConverter") 90 | private TensorflowInputConverter tensorflowInputConverter; 91 | 92 | @Autowired 93 | @Qualifier("tensorflowOutputConverter") 94 | private TensorflowOutputConverter tensorflowOutputConverter; 95 | 96 | @Autowired 97 | private TensorFlowService tensorFlowService; 98 | 99 | @ServiceActivator(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT) 100 | public Message evaluate(Message input) { 101 | 102 | Map processorContext = new ConcurrentHashMap<>(); 103 | 104 | Map inputData = tensorflowInputConverter.convert(input, processorContext); 105 | 106 | Tensor outputTensor = tensorFlowService.evaluate( 107 | inputData, properties.getOutputName(), properties.getOutputIndex()); 108 | 109 | Object outputData = tensorflowOutputConverter.convert(outputTensor, processorContext); 110 | 111 | if (properties.isSaveOutputInHeader()) { 112 | // Add the result to the message header 113 | return MessageBuilder 114 | .withPayload(input.getPayload()) 115 | .copyHeadersIfAbsent(input.getHeaders()) 116 | .setHeaderIfAbsent(TF_OUTPUT_HEADER, outputData) 117 | .build(); 118 | } 119 | 120 | // Add the outputData as part of the message payload 121 | Message outputMessage = MessageBuilder 122 | .withPayload(outputData) 123 | .copyHeadersIfAbsent(input.getHeaders()) 124 | .build(); 125 | 126 | return outputMessage; 127 | } 128 | 129 | @Bean 130 | @RefreshScope 131 | public TensorFlowService tensorFlowService() throws IOException { 132 | return new TensorFlowService(properties.getModelLocation()); 133 | } 134 | 135 | @Bean 136 | @ConditionalOnMissingBean(name = "tensorflowOutputConverter") 137 | public TensorflowOutputConverter tensorflowOutputConverter() { 138 | // Default implementations serializes the Tensor into Tuple 139 | return new TensorflowOutputConverter() { 140 | @Override 141 | public Tuple convert(Tensor tensor, Map processorContext) { 142 | return TensorTupleConverter.toTuple(tensor); 143 | } 144 | }; 145 | } 146 | 147 | @Bean 148 | @ConditionalOnMissingBean(name = "tensorflowInputConverter") 149 | public TensorflowInputConverter tensorflowInputConverter() { 150 | return new TensorflowInputConverter() { 151 | 152 | @Override 153 | public Map convert(Message input, Map processorContext) { 154 | 155 | if (input.getHeaders().containsKey(TF_INPUT_HEADER)) { 156 | return (Map) input.getHeaders().get(TF_INPUT_HEADER, Map.class); 157 | } 158 | else if (input.getPayload() instanceof Map) { 159 | return (Map) input.getPayload(); 160 | } 161 | 162 | throw new RuntimeException("Unsupported input format: " + input); 163 | 164 | } 165 | }; 166 | } 167 | 168 | @Override 169 | public void close() throws Exception { 170 | logger.info("Close TensorflowProcessorConfiguration"); 171 | tensorFlowService.close(); 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/main/java/org/springframework/cloud/stream/app/tensorflow/processor/TensorflowProcessorProperties.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.tensorflow.processor; 18 | 19 | import javax.validation.constraints.NotNull; 20 | 21 | import org.springframework.boot.context.properties.ConfigurationProperties; 22 | import org.springframework.core.io.Resource; 23 | import org.springframework.validation.annotation.Validated; 24 | 25 | /** 26 | * Holds configuration properties for the Tensorflow Processor module. 27 | * 28 | * @author Christian Tzolov 29 | */ 30 | @ConfigurationProperties("tensorflow") 31 | @Validated 32 | public class TensorflowProcessorProperties { 33 | 34 | /** 35 | * The location of the Tensorflow model file. 36 | */ 37 | private Resource modelLocation; 38 | 39 | /** 40 | * The model graph output name 41 | */ 42 | private String outputName; 43 | 44 | /** 45 | * The model graph output index 46 | */ 47 | private int outputIndex = 0; 48 | 49 | /** 50 | * Mark if the computed output has to stored in the outbound message's header or in the payload. 51 | * Note: The Kafka binder requires you to withe list the custom headers. Therefore if you set the 52 | * saveOutputInHeader to true the you have to start the SCDF server with this property: 53 | * 54 | * --spring.cloud.dataflow.applicationProperties.stream.spring.cloud.stream.kafka.binder.headers=TF_OUTPUT,TF_INPUT 55 | * 56 | */ 57 | private boolean saveOutputInHeader = false; 58 | 59 | @NotNull 60 | public String getOutputName() { 61 | return outputName; 62 | } 63 | 64 | public void setOutputName(String outputName) { 65 | this.outputName = outputName; 66 | } 67 | 68 | @NotNull 69 | public Resource getModelLocation() { 70 | return modelLocation; 71 | } 72 | 73 | public void setModelLocation(Resource modelLocation) { 74 | this.modelLocation = modelLocation; 75 | } 76 | 77 | public int getOutputIndex() { 78 | return outputIndex; 79 | } 80 | 81 | public void setOutputIndex(int outputIndex) { 82 | this.outputIndex = outputIndex; 83 | } 84 | 85 | public boolean isSaveOutputInHeader() { 86 | return saveOutputInHeader; 87 | } 88 | 89 | public void setSaveOutputInHeader(boolean saveOutputInHeader) { 90 | this.saveOutputInHeader = saveOutputInHeader; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/main/resources/META-INF/spring-configuration-metadata-whitelist.properties: -------------------------------------------------------------------------------- 1 | configuration-properties.classes=org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorProperties -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/main/resources/META-INF/spring.provides: -------------------------------------------------------------------------------- 1 | provides: spring-cloud-starter-stream-processor-tensorflow 2 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | tensorflow.management.security.enabled=false -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/test/java/org/springframework/cloud/stream/app/tensorflow/processor/TensorTupleConverterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.tensorflow.processor; 18 | 19 | import static org.junit.Assert.assertArrayEquals; 20 | import static org.junit.Assert.assertEquals; 21 | 22 | import org.junit.Test; 23 | import org.tensorflow.Tensor; 24 | 25 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorTupleConverter; 26 | import org.springframework.tuple.Tuple; 27 | 28 | /** 29 | * @author Christian Tzolov 30 | */ 31 | public class TensorTupleConverterTest { 32 | 33 | @Test 34 | public void longArray() { 35 | long[][] inLongArray = new long[2][2]; 36 | inLongArray[0][0] = 0; 37 | inLongArray[0][1] = 1; 38 | inLongArray[1][0] = 2; 39 | inLongArray[1][1] = 3; 40 | 41 | Tensor inTensor = Tensor.create(inLongArray); 42 | 43 | Tuple tuple = TensorTupleConverter.toTuple(inTensor); 44 | Tensor outTensor = TensorTupleConverter.toTensor(tuple); 45 | 46 | long[][] outLongArray = new long[2][2]; 47 | outLongArray = outTensor.copyTo(outLongArray); 48 | 49 | compareTensors(inTensor, outTensor); 50 | assertArrayEquals(inLongArray, outLongArray); 51 | } 52 | 53 | @Test 54 | public void longScalar() { 55 | long inLong = 666; 56 | 57 | Tensor inTensor = Tensor.create(inLong); 58 | 59 | Tuple tuple = TensorTupleConverter.toTuple(inTensor); 60 | 61 | Tensor outTensor = TensorTupleConverter.toTensor(tuple); 62 | 63 | compareTensors(inTensor, outTensor); 64 | assertEquals(inLong, outTensor.longValue()); 65 | } 66 | 67 | private void compareTensors(Tensor in, Tensor out) { 68 | assertEquals(in.dataType(), out.dataType()); 69 | assertEquals(in.numDimensions(), out.numDimensions()); 70 | assertEquals(in.numBytes(), out.numBytes()); 71 | assertArrayEquals(in.shape(), out.shape()); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/test/java/org/springframework/cloud/stream/app/tensorflow/processor/TensorflowProcessorPropertiesTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.tensorflow.processor; 18 | 19 | import static org.hamcrest.core.IsEqual.equalTo; 20 | import static org.junit.Assert.assertFalse; 21 | import static org.junit.Assert.assertThat; 22 | 23 | import org.junit.Before; 24 | import org.junit.Test; 25 | 26 | import org.springframework.beans.factory.BeanCreationException; 27 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 28 | import org.springframework.boot.test.util.EnvironmentTestUtils; 29 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 30 | import org.springframework.context.annotation.Configuration; 31 | 32 | /** 33 | * @author Christian Tzolov 34 | */ 35 | public class TensorflowProcessorPropertiesTest { 36 | 37 | private AnnotationConfigApplicationContext context; 38 | 39 | @Before 40 | public void beforeTest() { 41 | context = new AnnotationConfigApplicationContext(); 42 | EnvironmentTestUtils.addEnvironment(context, "tensorflow.modelLocation:NONE"); 43 | EnvironmentTestUtils.addEnvironment(context, "tensorflow.outputName:NONE"); 44 | } 45 | 46 | @Test 47 | public void modelLocationCanBeCustomized() { 48 | EnvironmentTestUtils.addEnvironment(context, "tensorflow.modelLocation:/remote"); 49 | context.register(Conf.class); 50 | context.refresh(); 51 | TensorflowProcessorProperties properties = context.getBean(TensorflowProcessorProperties.class); 52 | assertThat(properties.getModelLocation(), equalTo(context.getResource("/remote"))); 53 | } 54 | 55 | @Test 56 | public void outputNameCanBeCustomized() { 57 | EnvironmentTestUtils.addEnvironment(context, "tensorflow.outputName:output1"); 58 | context.register(Conf.class); 59 | context.refresh(); 60 | TensorflowProcessorProperties properties = context.getBean(TensorflowProcessorProperties.class); 61 | assertThat(properties.getOutputName(), equalTo("output1")); 62 | } 63 | 64 | @Test 65 | public void outputIndexCanBeCustomized() { 66 | EnvironmentTestUtils.addEnvironment(context, "tensorflow.outputIndex:666"); 67 | context.register(Conf.class); 68 | context.refresh(); 69 | TensorflowProcessorProperties properties = context.getBean(TensorflowProcessorProperties.class); 70 | assertThat(properties.getOutputIndex(), equalTo(666)); 71 | } 72 | 73 | @Test 74 | public void saveOutputInHeaderCanBeCustomized() { 75 | EnvironmentTestUtils.addEnvironment(context, "tensorflow.saveOutputInHeader:false"); 76 | context.register(Conf.class); 77 | context.refresh(); 78 | TensorflowProcessorProperties properties = context.getBean(TensorflowProcessorProperties.class); 79 | assertFalse(properties.isSaveOutputInHeader()); 80 | } 81 | 82 | 83 | @Configuration 84 | @EnableConfigurationProperties(TensorflowProcessorProperties.class) 85 | static class Conf { 86 | 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/test/java/org/springframework/cloud/stream/app/tensorflow/processor/logisticregression/LinearRegressionTensorflowProcessorIntegrationTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.tensorflow.processor.logisticregression; 18 | 19 | import static org.hamcrest.Matchers.equalTo; 20 | import static org.springframework.cloud.stream.app.tensorflow.processor.TensorTupleConverter.TF_SHAPE; 21 | import static org.springframework.cloud.stream.app.tensorflow.processor.TensorTupleConverter.TF_VALUE; 22 | 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | 26 | import org.junit.Assert; 27 | import org.junit.Test; 28 | import org.junit.runner.RunWith; 29 | import org.tensorflow.Tensor; 30 | 31 | import org.springframework.beans.factory.annotation.Autowired; 32 | import org.springframework.boot.autoconfigure.SpringBootApplication; 33 | import org.springframework.boot.test.context.SpringBootTest; 34 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorTupleConverter; 35 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowOutputConverter; 36 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorConfiguration; 37 | import org.springframework.cloud.stream.messaging.Processor; 38 | import org.springframework.cloud.stream.test.binder.MessageCollector; 39 | import org.springframework.context.annotation.Bean; 40 | import org.springframework.context.annotation.Import; 41 | import org.springframework.integration.support.MessageBuilder; 42 | import org.springframework.messaging.Message; 43 | import org.springframework.messaging.MessageHandlingException; 44 | import org.springframework.test.annotation.DirtiesContext; 45 | import org.springframework.test.context.TestPropertySource; 46 | import org.springframework.test.context.junit4.SpringRunner; 47 | import org.springframework.tuple.Tuple; 48 | import org.springframework.tuple.TupleBuilder; 49 | 50 | /** 51 | * Integration Tests for TensorflowProcessor. 52 | * 53 | * Uses the example model from the TensorFlow Core tutorial (https://www.tensorflow.org/get_started/get_started#complete_program) 54 | * The model is exported as protobuf file (linear_regression_graph.proto) using this snipped 55 | * 56 | * RUN_DIR = os.path.abspath(os.path.curdir) 57 | * minimal_graph = convert_variables_to_constants(sess, sess.graph_def, ['add']) 58 | * tf.train.write_graph(minimal_graph, RUN_DIR, 'linear_regression_graph.proto', as_text=False) 59 | * tf.train.write_graph(minimal_graph, RUN_DIR, 'linear_regression.txt', as_text=True) 60 | * 61 | * 62 | * The linear_regression.txt provides detail graph model description. 63 | * 64 | * The computational graph ('add' = W * 'Placeholder' + b) takes an input (called 'Placeholder' of type FLOAT) 65 | * and computes output (called 'add' of type FLOAT). The 'W' and 'b' are the trained variables. 66 | * 67 | * @author Christian Tzolov 68 | */ 69 | @SuppressWarnings("SpringJavaAutowiringInspection") 70 | @RunWith(SpringRunner.class) 71 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, 72 | properties = { 73 | "tensorflow.modelLocation=classpath:tensorflow/model/linear_regression_graph.proto", 74 | "tensorflow.outputName=add" 75 | } 76 | ) 77 | @DirtiesContext 78 | public abstract class LinearRegressionTensorflowProcessorIntegrationTests { 79 | 80 | @Autowired 81 | protected Processor channels; 82 | 83 | @Autowired 84 | protected MessageCollector messageCollector; 85 | 86 | @TestPropertySource(properties = { 87 | "tensorflow.saveOutputInHeader=true" 88 | }) 89 | public static class LinearRegressionInHeaderTests extends LinearRegressionTensorflowProcessorIntegrationTests { 90 | 91 | @Test 92 | public void testEvaluationPositive() { 93 | Map inMap = new HashMap<>(); 94 | inMap.put("Placeholder", 0.7f); 95 | Message msg = MessageBuilder.withPayload(inMap).build(); 96 | 97 | channels.input().send(msg); 98 | 99 | Message> received = (Message>) 100 | messageCollector.forChannel(channels.output()).poll(); 101 | 102 | Assert.assertThat((received.getPayload()), equalTo(inMap)); 103 | Assert.assertThat((Float) received.getHeaders().get(TensorflowProcessorConfiguration.TF_OUTPUT_HEADER), 104 | equalTo(0.29999298f)); 105 | } 106 | } 107 | 108 | @TestPropertySource(properties = { 109 | "tensorflow.saveOutputInHeader=false" 110 | }) 111 | public static class LinearRegressionInPayloadTests extends LinearRegressionTensorflowProcessorIntegrationTests { 112 | 113 | @Test 114 | public void testEvaluationFLoatInput() { 115 | testEvaluation(0.7f); 116 | } 117 | 118 | @Test 119 | public void testEvaluationWithTensorInput() { 120 | testEvaluation(Tensor.create(0.7f)); 121 | } 122 | 123 | @Test 124 | public void testEvaluationWithTupleInput() { 125 | testEvaluation(TensorTupleConverter.toTuple(Tensor.create(0.7f))); 126 | } 127 | 128 | @Test(expected = MessageHandlingException.class) 129 | public void testEvaluationIncorrectTupleInput() { 130 | Tuple incompleteInputTuple = TupleBuilder.tuple() 131 | // missing data type 132 | .put(TF_SHAPE, new long[0]) 133 | .put(TF_VALUE, new byte[0]) 134 | .build(); 135 | testEvaluation(incompleteInputTuple); 136 | } 137 | 138 | private void testEvaluation(Object input) { 139 | 140 | Map inMap = new HashMap<>(); 141 | inMap.put("Placeholder", input); 142 | 143 | Message msg = MessageBuilder.withPayload(inMap).build(); 144 | channels.input().send(msg); 145 | Message received = messageCollector.forChannel(channels.output()).poll(); 146 | Assert.assertThat((Float) received.getPayload(), equalTo(0.29999298f)); 147 | } 148 | } 149 | 150 | @SpringBootApplication 151 | @Import(TensorflowProcessorConfiguration.class) 152 | public static class LogisticRegressionTensorflowProcessorApplication { 153 | 154 | @Bean 155 | public TensorflowOutputConverter tensorflowOutputConverter() { 156 | return new TensorflowOutputConverter() { 157 | @Override 158 | public Object convert(Tensor tensor, Map processorContext) { 159 | float[] outputValue = new float[1]; 160 | tensor.copyTo(outputValue); 161 | return outputValue[0]; 162 | } 163 | }; 164 | } 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-tensorflow/src/test/resources/TensorFlowProcessorArcutectureOverview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tzolov/tensorflow-spring-cloud-stream-app-starters/d58fec9917894c3797bec7db049141845192d6be/spring-cloud-starter-stream-processor-tensorflow/src/test/resources/TensorFlowProcessorArcutectureOverview.png -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/README.adoc: -------------------------------------------------------------------------------- 1 | //tag::ref-doc[] 2 | = Twitter Sentiment Analysis Processor 3 | 4 | A processor that evaluates a machine learning model stored in TensorFlow Protobuf format. 5 | It operationalizes the https://github.com/danielegrattarola/twitter-sentiment-cnn 6 | 7 | image::src/test/resources/SCDF_TF_Sentiment.png[] 8 | 9 | link:https://www.youtube.com/watch?v=QzF2Iii4s5c[Real-time Twitter Sentiment Analytics with TensorFlow and Spring Cloud Dataflow] 10 | 11 | == Options 12 | 13 | The **$$twitter-sentiment$$** $$processor$$ has the following options: 14 | 15 | //tag::configuration-properties[] 16 | $$inception.vocabulary-location$$:: $$The location of the word vocabulary file. 17 | Note: the vocabulary must be the same used for training the model$$ *($$Resource$$, default: `$$$$`)* 18 | $$tensorflow.model-location$$:: $$The location of the Tensorflow model file.$$ *($$Resource$$, default: `$$$$`)* 19 | $$tensorflow.output-index$$:: $$The model graph output index$$ *($$Integer$$, default: `$$0$$`)* 20 | $$tensorflow.output-name$$:: $$The model graph output name$$ *($$String$$, default: `$$$$`)* 21 | $$tensorflow.save-output-in-header$$:: $$Mark if the computed output has to stored in the outbound message's header or in the payload. 22 | Note: The Kafka binder requires you to withe list the custom headers. Therefore if you set the 23 | saveOutputInHeader to true the you have to start the SCDF server with this property: 24 | 25 | --spring.cloud.dataflow.applicationProperties.stream.spring.cloud.stream.kafka.binder.headers=TF_OUTPUT,TF_INPUT 26 | $$ *($$Boolean$$, default: `$$false$$`)* 27 | //end::configuration-properties[] 28 | 29 | //end::ref-doc[] 30 | == Build 31 | 32 | ``` 33 | $> mvn package 34 | ``` 35 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | spring-cloud-starter-stream-processor-twitter-sentiment 6 | jar 7 | spring-cloud-starter-stream-processor-twitter-sentiment 8 | Spring Cloud Stream processor-twitter-sentiment core 9 | 10 | 11 | org.springframework.cloud.stream.app 12 | tensorflow-app-starters-build 13 | 1.2.0.RELEASE 14 | 15 | 16 | 17 | 18 | commons-io 19 | commons-io 20 | 21 | 22 | org.springframework.cloud.stream.app 23 | tensorflow-app-starters-test-support 24 | 25 | 26 | org.springframework.cloud.stream.app 27 | spring-cloud-starter-stream-processor-tensorflow 28 | 29 | 30 | 31 | 32 | 33 | 34 | org.springframework.cloud 35 | spring-cloud-app-starter-doc-maven-plugin 36 | 37 | 38 | org.springframework.cloud.stream.app.plugin 39 | spring-cloud-stream-app-maven-plugin 40 | 41 | ${session.executionRootDirectory}/apps 42 | ${project.version} 43 | 44 | scs-bom 45 | org.springframework.cloud.stream.app 46 | tensorflow-app-dependencies 47 | ${project.version} 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/main/java/org/springframework/cloud/stream/app/twitter/sentiment/processor/Sentiment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.twitter.sentiment.processor; 18 | 19 | /** 20 | * @author Christian Tzolov 21 | */ 22 | public enum Sentiment { 23 | POSITIVE, NEUTRAL, NEGATIVE; 24 | 25 | public static Sentiment get(float estimate) { 26 | if (estimate > 0.5) { 27 | return POSITIVE; 28 | } 29 | else if (estimate < 0.4) { 30 | return NEGATIVE; 31 | } 32 | 33 | return NEUTRAL; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/main/java/org/springframework/cloud/stream/app/twitter/sentiment/processor/TwitterSentimentProcessorConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.twitter.sentiment.processor; 18 | 19 | import java.net.MalformedURLException; 20 | 21 | import org.apache.commons.logging.Log; 22 | import org.apache.commons.logging.LogFactory; 23 | 24 | import org.springframework.beans.factory.annotation.Autowired; 25 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 26 | import org.springframework.cloud.context.config.annotation.RefreshScope; 27 | import org.springframework.cloud.stream.annotation.EnableBinding; 28 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowInputConverter; 29 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowOutputConverter; 30 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorConfiguration; 31 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorProperties; 32 | import org.springframework.cloud.stream.messaging.Processor; 33 | import org.springframework.context.annotation.Bean; 34 | import org.springframework.context.annotation.Import; 35 | 36 | /** 37 | * A processor that evaluates a machine learning model stored in TensorFlow's ProtoBuf format. 38 | * 39 | * @author Christian Tzolov 40 | */ 41 | @EnableBinding(Processor.class) 42 | @EnableConfigurationProperties({ 43 | TwitterSentimentProcessorProperties.class, TensorflowProcessorProperties.class}) 44 | @Import(TensorflowProcessorConfiguration.class) 45 | public class TwitterSentimentProcessorConfiguration { 46 | 47 | private static final Log logger = LogFactory.getLog(TwitterSentimentProcessorConfiguration.class); 48 | 49 | public static final String PROCESSOR_CONTEXT_TWEET_JSON_MAP = "tweetJsonMap"; 50 | 51 | @Autowired 52 | private TwitterSentimentProcessorProperties properties; 53 | 54 | @Bean 55 | public TensorflowOutputConverter tensorflowOutputConverter() { 56 | logger.info("Load TwitterSentimentTensorflowOutputConverter"); 57 | return new TwitterSentimentTensorflowOutputConverter(); 58 | } 59 | 60 | @Bean 61 | @RefreshScope 62 | public TensorflowInputConverter tensorflowInputConverter() throws MalformedURLException { 63 | logger.info("Load vocabulary: " + properties.getVocabularyLocation()); 64 | return new TwitterSentimentTensorflowInputConverter(properties.getVocabularyLocation()); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/main/java/org/springframework/cloud/stream/app/twitter/sentiment/processor/TwitterSentimentProcessorProperties.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.twitter.sentiment.processor; 18 | 19 | import javax.validation.constraints.NotNull; 20 | 21 | import org.springframework.boot.context.properties.ConfigurationProperties; 22 | import org.springframework.core.io.Resource; 23 | import org.springframework.validation.annotation.Validated; 24 | 25 | /** 26 | * Holds configuration properties for the Twitter Sentiment Analysis Processor module. 27 | * 28 | * @author Christian Tzolov 29 | */ 30 | @ConfigurationProperties("inception") 31 | @Validated 32 | public class TwitterSentimentProcessorProperties { 33 | 34 | /** 35 | * The location of the word vocabulary file. 36 | * Note: the vocabulary must be the same used for training the model 37 | */ 38 | private Resource vocabularyLocation; 39 | 40 | @NotNull 41 | public Resource getVocabularyLocation() { 42 | return vocabularyLocation; 43 | } 44 | 45 | public void setVocabularyLocation(Resource vocabularyLocation) { 46 | this.vocabularyLocation = vocabularyLocation; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/main/java/org/springframework/cloud/stream/app/twitter/sentiment/processor/TwitterSentimentTensorflowInputConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.twitter.sentiment.processor; 18 | 19 | import static org.springframework.cloud.stream.app.twitter.sentiment.processor.TwitterSentimentProcessorConfiguration.PROCESSOR_CONTEXT_TWEET_JSON_MAP; 20 | import static org.springframework.util.StringUtils.isEmpty; 21 | 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.util.HashMap; 25 | import java.util.Map; 26 | 27 | import org.apache.commons.logging.Log; 28 | import org.apache.commons.logging.LogFactory; 29 | 30 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowInputConverter; 31 | import org.springframework.core.io.Resource; 32 | import org.springframework.messaging.Message; 33 | import org.springframework.util.Assert; 34 | 35 | import com.fasterxml.jackson.databind.ObjectMapper; 36 | 37 | /** 38 | * Converts the input Tweet JSON message into key/value map that corresponds to the Twitter Sentiment CNN model: 39 | * 40 | * data_in : vectorized TEXT tag 41 | * dropout_keep_prob: 1.0f 42 | * 43 | * It also preservers the original Tweet (encoded as Java Map) in the processor context. Later is used by the 44 | * output converter to compose the output json message. 45 | * 46 | * @author Christian Tzolov 47 | */ 48 | public class TwitterSentimentTensorflowInputConverter implements TensorflowInputConverter, AutoCloseable { 49 | 50 | public static final Float DROPOUT_KEEP_PROB_VALUE = new Float(1.0); 51 | 52 | public static final String DATA_IN = "data_in"; 53 | 54 | public static final String DROPOUT_KEEP_PROB = "dropout_keep_prob"; 55 | 56 | public static final String TWEET_TEXT_TAG = "text"; 57 | 58 | public static final String TWEET_ID_TAG = "id"; 59 | 60 | private static final Log logger = LogFactory.getLog(TwitterSentimentTensorflowInputConverter.class); 61 | 62 | private final WordVocabulary wordVocabulary; 63 | 64 | private final ObjectMapper objectMapper; 65 | 66 | public TwitterSentimentTensorflowInputConverter(Resource vocabularLocation) { 67 | try (InputStream is = vocabularLocation.getInputStream()) { 68 | wordVocabulary = new WordVocabulary(is); 69 | objectMapper = new ObjectMapper(); 70 | Assert.notNull(wordVocabulary, "Failed to initialize the word vocabulary"); 71 | Assert.notNull(objectMapper, "Failed to initialize the objectMapper"); 72 | } 73 | catch (IOException e) { 74 | throw new RuntimeException("Failed to initialize the Vocabulary", e); 75 | } 76 | 77 | logger.info("Word Vocabulary Initialized"); 78 | } 79 | 80 | @Override 81 | public Map convert(Message input, Map processorContext) { 82 | 83 | try { 84 | Object payload = input.getPayload(); 85 | 86 | if (payload instanceof String) { 87 | Map tweetJsonMap = objectMapper.readValue((String) payload, Map.class); 88 | processorContext.put(PROCESSOR_CONTEXT_TWEET_JSON_MAP, tweetJsonMap); 89 | return getStringObjectMap(tweetJsonMap); 90 | } 91 | else if (payload instanceof Map) { 92 | processorContext.put(PROCESSOR_CONTEXT_TWEET_JSON_MAP, payload); 93 | return getStringObjectMap((Map) payload); 94 | } 95 | 96 | throw new IllegalArgumentException("Unsupported payload type:" + input.getPayload()); 97 | } 98 | catch (IOException e) { 99 | throw new RuntimeException("Can't parse input tweet json: " + input.getPayload()); 100 | } 101 | 102 | } 103 | 104 | private Map getStringObjectMap(Map jsonMap) { 105 | Assert.notNull(jsonMap, "Failed to parse the Tweet json!"); 106 | 107 | String tweetText = (String) jsonMap.get(TWEET_TEXT_TAG); 108 | 109 | if (isEmpty(tweetText)) { 110 | logger.warn("Tweet with out text: " + jsonMap.get(TWEET_ID_TAG)); 111 | tweetText = ""; 112 | } 113 | 114 | int[][] tweetVector = wordVocabulary.vectorizeSentence(tweetText); 115 | 116 | Assert.notEmpty(tweetVector, "Failed to vectorize the tweet text: " + tweetText); 117 | 118 | Map response = new HashMap<>(); 119 | response.put(DATA_IN, tweetVector); 120 | response.put(DROPOUT_KEEP_PROB, DROPOUT_KEEP_PROB_VALUE); 121 | 122 | return response; 123 | } 124 | 125 | @Override 126 | public void close() throws Exception { 127 | logger.info("Word Vocabulary Destroyed"); 128 | if (wordVocabulary != null) { 129 | wordVocabulary.close(); 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/main/java/org/springframework/cloud/stream/app/twitter/sentiment/processor/TwitterSentimentTensorflowOutputConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.twitter.sentiment.processor; 18 | 19 | import static org.springframework.cloud.stream.app.twitter.sentiment.processor.TwitterSentimentProcessorConfiguration.PROCESSOR_CONTEXT_TWEET_JSON_MAP; 20 | 21 | import java.util.HashMap; 22 | import java.util.Map; 23 | 24 | import org.tensorflow.Tensor; 25 | 26 | import org.springframework.cloud.stream.app.tensorflow.processor.TensorflowOutputConverter; 27 | 28 | import com.fasterxml.jackson.core.JsonProcessingException; 29 | import com.fasterxml.jackson.databind.ObjectMapper; 30 | 31 | /** 32 | * Decodes the evaluated result into POSITIVE, NEGATIVE and NEUTRAL values. 33 | * Then creates and returns a simple JSON message with this structure: 34 | * 35 | * { 36 | * "sentiment" : "... computed sentiment type ...", 37 | * "text" : "...TEXT tag form the input json tweet...", 38 | * "id" : "...ID tag form the input json tweet...", 39 | * "lang" : "...LANG tag form the input json tweet..." 40 | * } 41 | * 42 | * @author Christian Tzolov 43 | */ 44 | public class TwitterSentimentTensorflowOutputConverter implements TensorflowOutputConverter { 45 | 46 | public static final String SENTIMENT_TAG = "sentiment"; 47 | 48 | public static final String TEXT_TAG = "text"; 49 | 50 | public static final String ID_TAG = "id"; 51 | 52 | public static final String LANG_TAG = "lang"; 53 | 54 | private ObjectMapper objectMapper = new ObjectMapper(); 55 | 56 | @Override 57 | public String convert(Tensor tensor, Map processorContext) { 58 | // Read Tensor's value into float[][] matrix 59 | float[][] resultMatrix = new float[12][2]; 60 | tensor.copyTo(resultMatrix); 61 | String sentimentString = Sentiment.get(resultMatrix[0][1]).toString(); 62 | 63 | // Prepare teh output map 64 | Map inputJsonMap = (Map) processorContext.get(PROCESSOR_CONTEXT_TWEET_JSON_MAP); 65 | 66 | Map outputJsonMap = new HashMap<>(); 67 | outputJsonMap.put(SENTIMENT_TAG, sentimentString); 68 | outputJsonMap.put(TEXT_TAG, inputJsonMap.get(TEXT_TAG)); 69 | outputJsonMap.put(ID_TAG, inputJsonMap.get(ID_TAG)); 70 | outputJsonMap.put(LANG_TAG, inputJsonMap.get(LANG_TAG)); 71 | 72 | try { 73 | return objectMapper.writeValueAsString(outputJsonMap); 74 | } 75 | catch (JsonProcessingException e) { 76 | throw new RuntimeException("Failed to generate JSON output", e); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/main/java/org/springframework/cloud/stream/app/twitter/sentiment/processor/WordVocabulary.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.twitter.sentiment.processor; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.util.concurrent.ConcurrentHashMap; 24 | 25 | /** 26 | * @author Christian Tzolov 27 | */ 28 | public class WordVocabulary implements AutoCloseable { 29 | 30 | /** 31 | * This contains the word vocabulary used to train the TensorFlow model. 32 | */ 33 | private final ConcurrentHashMap vocabulary; 34 | 35 | public WordVocabulary(InputStream vocabularyInputStream) throws IOException { 36 | vocabulary = buildVocabulary(vocabularyInputStream); 37 | } 38 | 39 | public int[][] vectorizeSentence(String sentence) { 40 | int[][] vectorizedText = new int[1][128]; 41 | String[] words = clearText(sentence).split(" "); 42 | for (int i = 0; i < words.length; i++) { 43 | Integer v = vocabulary.get(words[i]); 44 | vectorizedText[0][i] = (v != null)? v : 0; 45 | } 46 | return vectorizedText; 47 | } 48 | 49 | private ConcurrentHashMap buildVocabulary(InputStream input) throws IOException { 50 | 51 | ConcurrentHashMap vocabulary = new ConcurrentHashMap<>(); 52 | 53 | try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { 54 | String l = buffer.readLine(); 55 | while (l != null ) { 56 | String p[] = l.split(","); 57 | if (p[1].length() > 1) { 58 | vocabulary.put(p[0], Integer.valueOf(p[1])); 59 | } 60 | l = buffer.readLine(); 61 | } 62 | } 63 | return vocabulary; 64 | } 65 | 66 | private String clearText(String sentence) { 67 | return sentence 68 | .trim() 69 | .replaceAll("[^A-Za-z0-9(),!?\\'\\`]", " ") 70 | .replaceAll("(.)\\1+", "\\1\\1") 71 | .replaceAll("\\'s", " \\'s") 72 | .replaceAll("\\'ve", " \\'ve") 73 | .replaceAll("n\\'t", " n\\'t") 74 | .replaceAll("\\'re", " \\'re") 75 | .replaceAll("\\'d", " \\'d") 76 | .replaceAll("\\'ll", " \\'ll") 77 | .replaceAll(",", " , ") 78 | .replaceAll("!", " ! ") 79 | .replaceAll("\\(", " \\( ") 80 | .replaceAll("\\)", " \\) ") 81 | .replaceAll("\\?", " \\? ") 82 | .replaceAll("\\s{2,}", " ") 83 | .toLowerCase(); 84 | } 85 | 86 | @Override 87 | public void close() throws Exception { 88 | vocabulary.clear(); 89 | } 90 | } 91 | 92 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/main/resources/META-INF/spring-configuration-metadata-whitelist.properties: -------------------------------------------------------------------------------- 1 | configuration-properties.classes=org.springframework.cloud.stream.app.twitter.sentiment.processor.TwitterSentimentProcessorProperties, org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorProperties -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/main/resources/META-INF/spring.provides: -------------------------------------------------------------------------------- 1 | provides: spring-cloud-starter-stream-processor-twitter-sentiment 2 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/test/java/org/springframework/cloud/stream/app/twitter/sentiment/processor/TwitterSentimentProcessorPropertiesTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.twitter.sentiment.processor; 18 | 19 | import static org.hamcrest.core.IsEqual.equalTo; 20 | import static org.junit.Assert.assertThat; 21 | 22 | import org.junit.Test; 23 | 24 | import org.springframework.beans.factory.BeanCreationException; 25 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 26 | import org.springframework.boot.test.util.EnvironmentTestUtils; 27 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 28 | import org.springframework.context.annotation.Configuration; 29 | 30 | /** 31 | * @author Christian Tzolov 32 | */ 33 | public class TwitterSentimentProcessorPropertiesTest { 34 | 35 | @Test 36 | public void vocabularyLocationCanBeCustomized() { 37 | AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); 38 | EnvironmentTestUtils.addEnvironment(context, "inception.vocabularyLocation:/remote"); 39 | context.register(Conf.class); 40 | context.refresh(); 41 | TwitterSentimentProcessorProperties properties = context.getBean(TwitterSentimentProcessorProperties.class); 42 | assertThat(properties.getVocabularyLocation(), equalTo(context.getResource("/remote"))); 43 | } 44 | 45 | @Configuration 46 | @EnableConfigurationProperties(TwitterSentimentProcessorProperties.class) 47 | static class Conf { 48 | 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/test/java/org/springframework/cloud/stream/app/twitter/sentiment/processor/twitter/TwitterSentimentTensorflowProcessorIntegrationTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.twitter.sentiment.processor.twitter; 18 | 19 | import static org.hamcrest.Matchers.equalTo; 20 | import static org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorConfiguration.TF_OUTPUT_HEADER; 21 | 22 | import org.junit.Assert; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | 26 | import org.springframework.beans.factory.annotation.Autowired; 27 | import org.springframework.boot.autoconfigure.SpringBootApplication; 28 | import org.springframework.boot.test.context.SpringBootTest; 29 | import org.springframework.cloud.stream.app.twitter.sentiment.processor.TwitterSentimentProcessorConfiguration; 30 | import org.springframework.cloud.stream.messaging.Processor; 31 | import org.springframework.cloud.stream.test.binder.MessageCollector; 32 | import org.springframework.context.annotation.Import; 33 | import org.springframework.integration.support.MessageBuilder; 34 | import org.springframework.messaging.Message; 35 | import org.springframework.test.annotation.DirtiesContext; 36 | import org.springframework.test.context.TestPropertySource; 37 | import org.springframework.test.context.junit4.SpringRunner; 38 | 39 | /** 40 | * Integration Tests for TwitterSentimentTensorflowProcessor 41 | * 42 | * @author Christian Tzolov 43 | */ 44 | @SuppressWarnings("SpringJavaAutowiringInspection") 45 | @RunWith(SpringRunner.class) 46 | @SpringBootTest( 47 | webEnvironment = SpringBootTest.WebEnvironment.NONE, 48 | properties = { 49 | "tensorflow.modelLocation=http://dl.bintray.com/big-data/generic/minimal_graph.proto", 50 | "tensorflow.outputName=output/Softmax", 51 | "inception.vocabularyLocation=http://dl.bintray.com/big-data/generic/vocab.csv" 52 | }) 53 | @DirtiesContext 54 | public abstract class TwitterSentimentTensorflowProcessorIntegrationTests { 55 | 56 | @Autowired 57 | protected Processor channels; 58 | 59 | @Autowired 60 | protected MessageCollector messageCollector; 61 | 62 | @TestPropertySource(properties = {"tensorflow.saveOutputInHeader=true"}) 63 | public static class OutputInHeaderTests extends TwitterSentimentTensorflowProcessorIntegrationTests { 64 | 65 | @Test 66 | public void testEvaluationPositive() { 67 | testEvaluationWithOutputInHeader( 68 | "{\"text\": \"RT @PostGradProblem: In preparation for the NFL lockout ...\", \"id\":666, \"lang\":\"en\" }", 69 | "{\"sentiment\":\"POSITIVE\",\"text\":\"RT @PostGradProblem: In preparation for the NFL lockout ...\",\"id\":666,\"lang\":\"en\"}"); 70 | } 71 | 72 | @Test 73 | public void testEvaluationNegative() { 74 | testEvaluationWithOutputInHeader( 75 | "{\"text\": \"This is really bad\", \"id\":666, \"lang\":\"en\" }", 76 | "{\"sentiment\":\"NEGATIVE\",\"text\":\"This is really bad\",\"id\":666,\"lang\":\"en\"}"); 77 | } 78 | 79 | private void testEvaluationWithOutputInHeader(String tweetJson, String resultJson) { 80 | channels.input().send(MessageBuilder.withPayload(tweetJson).build()); 81 | 82 | Message received = (Message) messageCollector.forChannel(channels.output()).poll(); 83 | 84 | Assert.assertThat(received.getPayload(), equalTo(tweetJson)); 85 | Assert.assertThat(received.getHeaders().get(TF_OUTPUT_HEADER).toString(), equalTo(resultJson)); 86 | } 87 | } 88 | 89 | @TestPropertySource(properties = {"tensorflow.saveOutputInHeader=false"}) 90 | public static class OutputInPayloadTests extends TwitterSentimentTensorflowProcessorIntegrationTests { 91 | 92 | @Test 93 | public void testEvaluationPositive() { 94 | String value = "{\"text\": \"RT @PostGradProblem: In preparation for the NFL lockout ...\", \"id\":666, \"lang\":\"en\" }"; 95 | 96 | channels.input().send(MessageBuilder.withPayload(value).build()); 97 | 98 | Message received = (Message) messageCollector.forChannel(channels.output()).poll(); 99 | 100 | Assert.assertTrue(received.getPayload().getClass().isAssignableFrom(String.class)); 101 | Assert.assertThat(received.getPayload().toString(), 102 | equalTo("{\"sentiment\":\"POSITIVE\",\"text\":\"RT @PostGradProblem: In preparation for the NFL lockout ...\",\"id\":666,\"lang\":\"en\"}")); 103 | } 104 | } 105 | 106 | @SpringBootApplication 107 | @Import(TwitterSentimentProcessorConfiguration.class) 108 | public static class TensorflowProcessorApplication { 109 | 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /spring-cloud-starter-stream-processor-twitter-sentiment/src/test/resources/SCDF_TF_Sentiment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tzolov/tensorflow-spring-cloud-stream-app-starters/d58fec9917894c3797bec7db049141845192d6be/spring-cloud-starter-stream-processor-twitter-sentiment/src/test/resources/SCDF_TF_Sentiment.png -------------------------------------------------------------------------------- /tensorflow-app-dependencies/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | org.springframework.cloud.stream.app 5 | tensorflow-app-dependencies 6 | 1.2.0.RELEASE 7 | pom 8 | tensorflow-app-dependencies 9 | Spring Cloud Stream tensorflow App Dependencies 10 | 11 | 12 | spring-cloud-dependencies-parent 13 | org.springframework.cloud 14 | 1.2.0.RELEASE 15 | 16 | 17 | 18 | 19 | 1.2.6 20 | 1.1.0-rc2 21 | 22 | 23 | 24 | 25 | 26 | org.springframework.cloud 27 | spring-cloud-bus 28 | 1.3.0.RELEASE 29 | 30 | 31 | org.springframework.cloud.stream.app 32 | spring-cloud-starter-stream-processor-tensorflow 33 | 1.2.0.RELEASE 34 | 35 | 36 | org.springframework.cloud.stream.app 37 | spring-cloud-starter-stream-processor-twitter-sentiment 38 | 1.2.0.RELEASE 39 | 40 | 41 | org.springframework.cloud.stream.app 42 | spring-cloud-starter-stream-processor-label-image 43 | 1.2.0.RELEASE 44 | 45 | 46 | org.tensorflow 47 | tensorflow 48 | ${tensorflow.version} 49 | 50 | 51 | commons-io 52 | commons-io 53 | 2.5 54 | 55 | 56 | 57 | org.springframework.cloud.stream.app 58 | tensorflow-app-starters-test-support 59 | 1.2.0.RELEASE 60 | test 61 | 62 | 63 | 64 | 65 | 66 | spring 67 | 68 | 69 | spring-snapshots 70 | Spring Snapshots 71 | http://repo.spring.io/libs-snapshot-local 72 | 73 | true 74 | 75 | 76 | 77 | spring-milestones 78 | Spring Milestones 79 | http://repo.spring.io/libs-milestone-local 80 | 81 | false 82 | 83 | 84 | 85 | spring-releases 86 | Spring Releases 87 | http://repo.spring.io/release 88 | 89 | false 90 | 91 | 92 | 93 | spring-libs-release 94 | Spring Libs Release 95 | http://repo.spring.io/libs-release 96 | 97 | false 98 | 99 | 100 | 101 | 102 | false 103 | 104 | spring-milestone-release 105 | Spring Milestone Release 106 | http://repo.spring.io/libs-milestone 107 | 108 | 109 | 110 | 111 | spring-snapshots 112 | Spring Snapshots 113 | http://repo.spring.io/libs-snapshot-local 114 | 115 | true 116 | 117 | 118 | 119 | spring-milestones 120 | Spring Milestones 121 | http://repo.spring.io/libs-milestone-local 122 | 123 | false 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /tensorflow-app-starters-test-support/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | tensorflow-app-starters-test-support 5 | 6 | 7 | org.springframework.cloud.stream.app 8 | tensorflow-app-starters-build 9 | 1.2.0.RELEASE 10 | 11 | 12 | 13 | 14 | org.springframework.cloud.stream.app 15 | app-starters-test-support 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /tensorflow-app-starters-test-support/src/main/java/org/springframework/cloud/stream/app/test/tensorflow/TensorflowProcessorTestConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.stream.app.test.tensorflow; 18 | 19 | import java.util.Properties; 20 | 21 | import org.springframework.cloud.stream.app.test.BinderTestPropertiesInitializer; 22 | import org.springframework.context.ConfigurableApplicationContext; 23 | import org.springframework.context.annotation.Bean; 24 | import org.springframework.context.annotation.Configuration; 25 | 26 | /** 27 | * Test configuration for the generated Tensorflow processor app. 28 | * 29 | * @author Christian Tzolov 30 | * 31 | */ 32 | @Configuration 33 | public class TensorflowProcessorTestConfiguration { 34 | 35 | @Bean 36 | public BinderTestPropertiesInitializer loadProps(ConfigurableApplicationContext context) { 37 | // minimal properties for the context to load 38 | Properties properties = new Properties(); 39 | properties.put("modelLocation", "classpath:tensorflow/model/linear_regression_graph.proto"); 40 | properties.put("outputName", "add"); 41 | return new BinderTestPropertiesInitializer(context, properties); 42 | } 43 | } -------------------------------------------------------------------------------- /tensorflow-app-starters-test-support/src/main/resources/doc/VideoIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tzolov/tensorflow-spring-cloud-stream-app-starters/d58fec9917894c3797bec7db049141845192d6be/tensorflow-app-starters-test-support/src/main/resources/doc/VideoIcon.png -------------------------------------------------------------------------------- /tensorflow-app-starters-test-support/src/main/resources/tensorflow/model/linear_regression.txt: -------------------------------------------------------------------------------- 1 | node { 2 | name: "Variable" 3 | op: "Const" 4 | attr { 5 | key: "dtype" 6 | value { 7 | type: DT_FLOAT 8 | } 9 | } 10 | attr { 11 | key: "value" 12 | value { 13 | tensor { 14 | dtype: DT_FLOAT 15 | tensor_shape { 16 | dim { 17 | size: 1 18 | } 19 | } 20 | float_val: -0.999996900558 21 | } 22 | } 23 | } 24 | } 25 | node { 26 | name: "Variable/read" 27 | op: "Identity" 28 | input: "Variable" 29 | attr { 30 | key: "T" 31 | value { 32 | type: DT_FLOAT 33 | } 34 | } 35 | attr { 36 | key: "_class" 37 | value { 38 | list { 39 | s: "loc:@Variable" 40 | } 41 | } 42 | } 43 | } 44 | node { 45 | name: "Variable_1" 46 | op: "Const" 47 | attr { 48 | key: "dtype" 49 | value { 50 | type: DT_FLOAT 51 | } 52 | } 53 | attr { 54 | key: "value" 55 | value { 56 | tensor { 57 | dtype: DT_FLOAT 58 | tensor_shape { 59 | dim { 60 | size: 1 61 | } 62 | } 63 | float_val: 0.999990820885 64 | } 65 | } 66 | } 67 | } 68 | node { 69 | name: "Variable_1/read" 70 | op: "Identity" 71 | input: "Variable_1" 72 | attr { 73 | key: "T" 74 | value { 75 | type: DT_FLOAT 76 | } 77 | } 78 | attr { 79 | key: "_class" 80 | value { 81 | list { 82 | s: "loc:@Variable_1" 83 | } 84 | } 85 | } 86 | } 87 | node { 88 | name: "Placeholder" 89 | op: "Placeholder" 90 | attr { 91 | key: "dtype" 92 | value { 93 | type: DT_FLOAT 94 | } 95 | } 96 | attr { 97 | key: "shape" 98 | value { 99 | shape { 100 | } 101 | } 102 | } 103 | } 104 | node { 105 | name: "mul" 106 | op: "Mul" 107 | input: "Variable/read" 108 | input: "Placeholder" 109 | attr { 110 | key: "T" 111 | value { 112 | type: DT_FLOAT 113 | } 114 | } 115 | } 116 | node { 117 | name: "add" 118 | op: "Add" 119 | input: "mul" 120 | input: "Variable_1/read" 121 | attr { 122 | key: "T" 123 | value { 124 | type: DT_FLOAT 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /tensorflow-app-starters-test-support/src/main/resources/tensorflow/model/linear_regression_graph.proto: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tzolov/tensorflow-spring-cloud-stream-app-starters/d58fec9917894c3797bec7db049141845192d6be/tensorflow-app-starters-test-support/src/main/resources/tensorflow/model/linear_regression_graph.proto -------------------------------------------------------------------------------- /tensorflow-app-starters-test-support/src/main/resources/tensorflow/python/LinearRegression.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | from tensorflow.python.framework.graph_util import convert_variables_to_constants 4 | import os 5 | 6 | # Model parameters 7 | W = tf.Variable([.3], tf.float32) 8 | b = tf.Variable([-.3], tf.float32) 9 | # Model input and output 10 | x = tf.placeholder(tf.float32) 11 | linear_model = W * x + b 12 | y = tf.placeholder(tf.float32) 13 | # loss 14 | loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares 15 | # optimizer 16 | optimizer = tf.train.GradientDescentOptimizer(0.01) 17 | train = optimizer.minimize(loss) 18 | # training data 19 | x_train = [1,2,3,4] 20 | y_train = [0,-1,-2,-3] 21 | # training loop 22 | init = tf.global_variables_initializer() 23 | sess = tf.Session() 24 | sess.run(init) # reset values to wrong 25 | for i in range(1000): 26 | sess.run(train, {x:x_train, y:y_train}) 27 | 28 | # evaluate training accuracy 29 | #curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x:x_train, y:y_train}) 30 | #print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss)) 31 | 32 | output = sess.run(linear_model, {x:0.7}) 33 | print(output) 34 | 35 | # for p in tf.global_variables(): 36 | # print(p) 37 | 38 | for n in tf.get_default_graph().as_graph_def().node: 39 | print(n.name) 40 | 41 | RUN_DIR = os.path.abspath(os.path.curdir) 42 | minimal_graph = convert_variables_to_constants(sess, sess.graph_def, ['add']) 43 | tf.train.write_graph(minimal_graph, RUN_DIR, 'linear_regression_graph.proto', as_text=False) 44 | tf.train.write_graph(minimal_graph, RUN_DIR, 'linear_regression.txt', as_text=True) 45 | -------------------------------------------------------------------------------- /tensorflow-app-starters-test-support/src/main/resources/tfInput.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "add", 4 | "type": "Pankaj", 5 | "value": "0.7" 6 | }, 7 | { 8 | "name": "add2", 9 | "type": "Pankaj3", 10 | "value": "0.7" 11 | }, 12 | ] --------------------------------------------------------------------------------