├── .gitignore ├── CONTRIBUTING.md ├── LICENSE.txt ├── README.md ├── natural-language ├── local.json ├── package.json └── twitter.js ├── nl-firebase-twitter ├── backend │ ├── index.js │ ├── local.json │ └── package.json └── frontend │ ├── database.rules.json │ ├── emoji-happy.png │ ├── emoji-sad.png │ ├── firebase.json │ ├── index.html │ ├── main.css │ └── main.js ├── project-settings.png ├── service-accounts.png ├── speech └── request.sh ├── table-schema.png ├── vision-api-firebase ├── cors.json ├── database.rules.json ├── firebase.json ├── functions │ ├── index.js │ └── package.json ├── icon.png ├── index.html ├── main.css └── main.js └── vision-speech-nl-translate ├── requirements.txt └── textify.py /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | *.log 3 | *.firebaserc 4 | *.eslintrc.js 5 | nl-firebase-twitter/backend/local.sample.json -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution, 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult [GitHub Help] for more 22 | information on using pull requests. 23 | 24 | [GitHub Help]: https://help.github.com/articles/about-pull-requests/ -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | *This is not an official Google product* 2 | 3 | # ML API next talk demos 4 | 5 | This repo includes 4 demos from my [Google Next talk](https://youtu.be/w1xNTLH1zlA) and [Google I/O talk](https://www.youtube.com/watch?v=ETeeSYMGZn0) on the Cloud ML APIs. To run the demos, follow the instructions below. 6 | 7 | ## Vision API + Firebase demo 8 | 9 | 1. `cd` into `vision-api-firebase` 10 | 2. Create a project in the [Firebase console](http://firebase.google.com/console) and install the [Firebase CLI](https://firebase.google.com/docs/cli/) 11 | 3. Run `firebase login` via the CLI and then `firebase init functions` to initialize the Firebase SDK for Cloud Functions. When prompted, don't overwrite `functions/package.json` or `functions/index.js`. 12 | 4. In your Cloud console for the same project, enable the Vision API 13 | 5. Generate a service account for your project by navigating to the "Project settings" tab in your Firebase console and then selecting "Service Accouts". Click "Generate New Private Key" and save the file to your `functions/` directory in a file called `keyfile.json`: 14 | 15 | ![Project settings](project-settings.png) 16 | 17 | ![Service accounts](service-accounts.png) 18 | 19 | 6. In `functions/index.js` replace both instances of `your-firebase-project-id` with the ID of your Firebase project 20 | 7. Deploy your Cloud Function by running `firebase deploy --only functions` 21 | 8. From the Authentication tab in your Firebase console, enable *Twitter authentication* (you can use whichever auth provider you'd like, I chose Twitter). 22 | 9. Run the frontend locally by running `firebase serve` from the `vision-api-firebase/` directory of this project. Navigate to `localhost:5000` to try uploading a photo. After uploading a photo check your Functions logs and then your Firebase Database to confirm the function executed correctly. 23 | 10. Deploy the frontend by running `firebase deploy --only hosting`. For future deploys you can run `firebase deploy` to deploy Functions and Hosting simultaneously. 24 | 25 | ## Speech API Bash demo 26 | 27 | 1. `cd` into `speech/` 28 | 2. Make sure you have [SoX](http://sox.sourceforge.net/) installed. On a Mac: `brew install sox --with-flac` 29 | 3. Create a project in the Cloud console and generate a new API key. Add your API key in `request.sh` 30 | 3. Run the script: `bash request.sh` 31 | 32 | ## Natural Language API BigQuery demo 33 | 34 | 1. `cd` into `natural-language/` 35 | 2. Generate [Twitter Streaming API](https://dev.twitter.com/streaming/overview) credentials and copy them to `local.json` 36 | 3. Create a Google Cloud project, generate a JSON keyfile, and add the filepath to `local.json` 37 | 4. Create a BigQuery dataset and table with the below schema, add them to `local.json` 38 | 39 | 40 | 5. Generate an API key and add it to `local.json` 41 | 6. Change line 37 to filter tweets on whichver terms you'd like 42 | 7. Install node modules: `npm install` 43 | 8. Run the script: `node twitter.js` 44 | 45 | ## Natural Language API + Firebase realtime Twitter dashboard demo 46 | 47 | 1. `cd` into `nl-firebase-twitter/` 48 | 2. Create a project in the [Firebase console](http://firebase.google.com/console) and install the [Firebase CLI](https://firebase.google.com/docs/cli/) 49 | 3. `cd` into the `frontend/` directory and run `firebase login` and `firebase init` to associate this with the Firebase project you just created. When prompted, don't overwrite existing files. Create a **database** and **hosting** project (no Functions). 50 | 4. In your Firebase console, click "Add Firebase to your web app". Copy the credentials to the top of the main.js file 51 | 5. `cd` into the `backend/` directory and run `npm install` to install dependencies 52 | 6. Generate a service account for your project by navigating to the "Project settings" tab in your Firebase console and then selecting "Service Accouts". Click "Generate New Private Key" and save this in your `backend/` directory as `keyfile.json` 53 | 7. Generate [Twitter Streaming API](https://dev.twitter.com/streaming/overview) credentials and copy them to `backend/local.json` 54 | 8. Navigate to the Cloud console for our project. Enabled the Natural Language API and generate an API key. Replace `YOUR-API-KEY` in `backend/local.json` with this key. 55 | 9. Replace `searchTerms` in `backend/index.js` with the search terms you'd like to filter tweets on 56 | 10. Replace `FIREBASE-PROJECT-ID` in `backend/local.json` with the id of your Firebase project 57 | 11. Set up BigQuery: in your Cloud console for the same project, create a BigQuery dataset. Then create a table in that dataset. When creating the table, click **Edit as text** and paste the following: 58 | ``` 59 | id:STRING,text:STRING,user:STRING,user_time_zone:STRING,user_followers_count:INTEGER,hashtags:STRING,tokens:STRING,score:STRING,magnitude:STRING,entities:STRING 60 | ``` 61 | 12. Add your BigQuery dataset and table names to `backend/local.json`. 62 | 11. Run the server: from the `backend/` directory run `node index.js`. You should see tweet data being written to your Firebase database 63 | 12. In a separate terminal process, run the frontend: from the `frontend/` directory run `firebase serve` 64 | 13. Deploy your frontend: from the `frontend/` directory run `firebase deploy` 65 | 66 | 67 | ## Multiple API demo 68 | 69 | 1. `cd` into `vision-speech-nl-translate` 70 | 2. Make sure you've set up your [GOOGLE_APPLICATION_CREDENTIALS](https://developers.google.com/identity/protocols/application-default-credentials) with a Cloud project that has the Vision, Speech, NL, and Translation APIs enabled 71 | 3. Run the script: `python textify.py` 72 | 4. Note: if you're running it with image OCR, copy an image file to your local directory 73 | -------------------------------------------------------------------------------- /natural-language/local.json: -------------------------------------------------------------------------------- 1 | { 2 | "twitter": { 3 | "consumer_key": "TWITTER_KEY", 4 | "consumer_secret": "TWITTER_SECRET", 5 | "access_token_key": "ACCESS_TOKEN", 6 | "access_token_secret": "ACCESS_SECRET" 7 | }, 8 | "nl_api_key": "your_nl_api_key", 9 | "keyfile_path": "~/path_to_your_keyfile.json", 10 | "cloud_project_id": "your_cloud_project", 11 | "bigquery_dataset": "your_bq_dataset", 12 | "bigquery_table": "your_bq_table" 13 | } 14 | -------------------------------------------------------------------------------- /natural-language/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "natural-language", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "twitter.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "@google-cloud/bigquery": "^1.0.0", 14 | "async": "^2.6.0", 15 | "request": "^2.83.0", 16 | "twitter": "^1.7.1" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /natural-language/twitter.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | 'use strict'; 16 | const request = require('request'); 17 | const Twitter = require('twitter'); 18 | const async = require('async'); 19 | const config = require('./local.json'); 20 | const client = new Twitter(config.twitter); 21 | 22 | // Set up BigQuery 23 | // Replace this with the name of your project and the path to your keyfile 24 | const bigquery = require('@google-cloud/bigquery')({ 25 | projectId: config.cloud_project_id, 26 | keyFilename: config.keyfile_path 27 | }); 28 | const dataset = bigquery.dataset(config.bigquery_dataset); 29 | const table = dataset.table(config.bigquery_table); 30 | 31 | // Replace searchTerms with whatever tweets you want to stream 32 | // Details here: https://dev.twitter.com/streaming/overview/request-parameters#track 33 | const searchTerms = '#googlenext17,@googlecloud,google cloud'; 34 | 35 | function callNLMethod(tweet, method) { 36 | const textUrl = `https://language.googleapis.com/v1/documents:${method}?key=${config.nl_api_key}`; 37 | let requestBody = { 38 | "document": { 39 | "type": "PLAIN_TEXT", 40 | "content": tweet.text 41 | } 42 | } 43 | 44 | let options = { 45 | url: textUrl, 46 | method: "POST", 47 | body: requestBody, 48 | json: true 49 | } 50 | 51 | return new Promise((resolve, reject) => { 52 | request(options, function(err, resp, body) { 53 | if ((!err && resp.statusCode == 200) && (body.sentences.length != 0)) { 54 | resolve(body); 55 | } else { 56 | reject(err); 57 | } 58 | }); 59 | }) 60 | } 61 | 62 | client.stream('statuses/filter', {track: searchTerms, language: 'en'}, function(stream) { 63 | 64 | stream.on('data', function(tweet) { 65 | if ((tweet.text != undefined) && (tweet.text.substring(0,2) != 'RT')) { 66 | async function analyzeTweet() { 67 | try { 68 | let syntaxData = await callNLMethod(tweet, 'analyzeSyntax'); 69 | let sentimentData = await callNLMethod(tweet, 'analyzeSentiment'); 70 | 71 | let row = { 72 | id: tweet.id_str, 73 | text: tweet.text, 74 | created_at: tweet.timestamp_ms.toString(), 75 | user_followers_count: tweet.user.followers_count, 76 | hashtags: JSON.stringify(tweet.entities.hashtags), 77 | tokens: JSON.stringify(syntaxData.tokens), 78 | score: sentimentData.documentSentiment.score, 79 | magnitude: sentimentData.documentSentiment.magnitude 80 | }; 81 | 82 | table.insert(row, function(error, insertErr, apiResp) { 83 | if (error) { 84 | console.log('err', error); 85 | } else if (insertErr.length == 0) { 86 | console.log('success!'); 87 | } 88 | }); 89 | 90 | } catch (err) { 91 | console.log('API error: ', err); 92 | } 93 | } 94 | analyzeTweet(); 95 | } 96 | 97 | }); 98 | 99 | stream.on('error', function(error) { 100 | throw error; 101 | }); 102 | }); 103 | -------------------------------------------------------------------------------- /nl-firebase-twitter/backend/index.js: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Google Inc. 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | 'use strict'; 16 | 17 | const request = require('request'); 18 | const Twitter = require('twitter'); 19 | const config = require('./local.json'); 20 | const client = new Twitter({ 21 | consumer_key: config.twitter_consumer_key, 22 | consumer_secret: config.twitter_consumer_secret, 23 | access_token_key: config.twitter_access_key, 24 | access_token_secret: config.twitter_access_secret 25 | }); 26 | 27 | const gcloud = require('google-cloud')({ 28 | keyFilename: 'keyfile.json', 29 | projectId: config.project_id 30 | }); 31 | const bigquery = gcloud.bigquery(); 32 | const dataset = bigquery.dataset(config.bigquery_dataset); 33 | const table = dataset.table(config.bigquery_table); 34 | 35 | const Filter = require('bad-words'), 36 | filter = new Filter(); 37 | 38 | // Replace searchTerms with whatever tweets you want to stream 39 | // Details here: https://dev.twitter.com/streaming/overview/request-parameters#track 40 | const searchTerms = 'googleio,googledevelopers,googlecloud,firebase,machine learning,io17,googleio17'; 41 | 42 | // Add a filter-level param? 43 | client.stream('statuses/filter', {track: searchTerms, language: 'en'}, function(stream) { 44 | stream.on('data', function(event) { 45 | // Exclude tweets starting with "RT" 46 | if ((event.text != undefined) && (event.text.substring(0,2) != 'RT') && (event.text === filter.clean(event.text))) { 47 | callNLApi(event); 48 | } 49 | }); 50 | stream.on('error', function(error) { 51 | console.log('twitter api error: ', error); 52 | }); 53 | }); 54 | 55 | 56 | // INITIALIZE FIREBASE 57 | var admin = require("firebase-admin"); 58 | var serviceAccount = require("./keyfile.json"); 59 | admin.initializeApp({ 60 | credential: admin.credential.cert(serviceAccount), 61 | databaseURL: "https://" + config.project_id + ".firebaseio.com" 62 | }); 63 | 64 | const db = admin.database(); 65 | const tweetRef = db.ref('latest'); 66 | const hashtagRef = db.ref('hashtags'); 67 | 68 | // Uses a Firebase transaction to incrememnt a counter 69 | function incrementCount(ref, child, valToIncrement) { 70 | ref.child(child).transaction(function(data) { 71 | if (data != null) { 72 | data += valToIncrement; 73 | } else { 74 | data = 1; 75 | } 76 | return data; 77 | }); 78 | } 79 | 80 | 81 | tweetRef.on('value', function (snap) { 82 | if (snap.exists()) { 83 | let tweet = snap.val(); 84 | let tokens = tweet['tokens']; 85 | let hashtags = tweet['hashtags']; 86 | 87 | for (let i in tokens) { 88 | let token = tokens[i]; 89 | let word = token.lemma.toLowerCase(); 90 | 91 | if ((acceptedWordTypes.indexOf(token.partOfSpeech.tag) != -1) && !(word.match(/[^A-Za-z0-9]/g))) { 92 | let posRef = db.ref('tokens/' + token.partOfSpeech.tag); 93 | incrementCount(posRef, word, 1); 94 | } 95 | 96 | } 97 | 98 | if (hashtags) { 99 | for (let i in hashtags) { 100 | let ht = hashtags[i]; 101 | let text = ht.text.toLowerCase(); 102 | let htRef = hashtagRef.child(text); 103 | incrementCount(htRef, 'totalScore', tweet.score); 104 | incrementCount(htRef, 'numMentions', 1); 105 | } 106 | } 107 | } 108 | }); 109 | 110 | 111 | const acceptedWordTypes = ['ADJ']; // Add the parts of speech you'd like to graph to this array ('NOUN', 'VERB', etc.) 112 | 113 | function callNLApi(tweet) { 114 | const textUrl = "https://language.googleapis.com/v1/documents:annotateText?key=" + config.cloud_api_key; 115 | let requestBody = { 116 | "document": { 117 | "type": "PLAIN_TEXT", 118 | "content": tweet.text 119 | }, 120 | "features": { 121 | "extractSyntax": true, 122 | "extractEntities": true, 123 | "extractDocumentSentiment": true 124 | } 125 | } 126 | 127 | let options = { 128 | url: textUrl, 129 | method: "POST", 130 | body: requestBody, 131 | json: true 132 | } 133 | 134 | request(options, function(err, resp, body) { 135 | if ((!err && resp.statusCode == 200) && (body.sentences.length != 0)) { 136 | let tweetForFb = { 137 | id: tweet.id_str, 138 | text: tweet.text, 139 | user: tweet.user.screen_name, 140 | user_time_zone: tweet.user.time_zone, 141 | user_followers_count: tweet.user.followers_count, 142 | hashtags: tweet.entities.hashtags, 143 | tokens: body.tokens, 144 | score: body.documentSentiment.score, 145 | magnitude: body.documentSentiment.magnitude, 146 | entities: body.entities 147 | }; 148 | 149 | let bqRow = { 150 | id: tweet.id_str, 151 | text: tweet.text, 152 | user: tweet.user.screen_name, 153 | user_time_zone: tweet.user.time_zone, 154 | user_followers_count: tweet.user.followers_count, 155 | hashtags: JSON.stringify(tweet.entities.hashtags), 156 | tokens: JSON.stringify(body.tokens), 157 | score: body.documentSentiment.score, 158 | magnitude: body.documentSentiment.magnitude, 159 | entities: JSON.stringify(body.entities) 160 | } 161 | 162 | tweetRef.set(tweetForFb); 163 | table.insert(bqRow, function(error, insertErr, apiResp) { 164 | if (error) { 165 | console.log('err', error); 166 | } else if (insertErr.length == 0) { 167 | console.log('success!'); 168 | } 169 | }); 170 | 171 | } else { 172 | console.log('NL API error: ', err); 173 | } 174 | }); 175 | } 176 | -------------------------------------------------------------------------------- /nl-firebase-twitter/backend/local.json: -------------------------------------------------------------------------------- 1 | { 2 | "twitter_consumer_key": "", 3 | "twitter_consumer_secret": "", 4 | "twitter_access_key": "", 5 | "twitter_access_secret": "", 6 | "project_id": "", 7 | "bigquery_dataset": "", 8 | "bigquery_table": "", 9 | "cloud_api_key": "" 10 | } -------------------------------------------------------------------------------- /nl-firebase-twitter/backend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "twitter-nl-fb", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "async": "^2.4.0", 14 | "bad-words": "^1.5.1", 15 | "firebase-admin": "^4.2.1", 16 | "google-cloud": "^0.53.0", 17 | "request": "^2.81.0", 18 | "twitter": "^1.7.0" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /nl-firebase-twitter/frontend/database.rules.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | ".read": true, 4 | ".write": "auth != null", 5 | "tokens": { 6 | "ADJ": { 7 | ".indexOn": ".value" 8 | } 9 | }, 10 | "hashtags": { 11 | ".indexOn": "numMentions" 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /nl-firebase-twitter/frontend/emoji-happy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sararob/ml-talk-demos/91a3327a3b8b8e536789647151b3046c0dee5e36/nl-firebase-twitter/frontend/emoji-happy.png -------------------------------------------------------------------------------- /nl-firebase-twitter/frontend/emoji-sad.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sararob/ml-talk-demos/91a3327a3b8b8e536789647151b3046c0dee5e36/nl-firebase-twitter/frontend/emoji-sad.png -------------------------------------------------------------------------------- /nl-firebase-twitter/frontend/firebase.json: -------------------------------------------------------------------------------- 1 | { 2 | "database": { 3 | "rules": "database.rules.json" 4 | }, 5 | "hosting": { 6 | "public": "." 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /nl-firebase-twitter/frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Twitter NLP Analysis 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 |
31 |
32 | Tweet Dashboard 33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |

Latest tweet data

41 |
42 |
43 | 44 |
45 |
46 |

Nouns

47 |

Verbs

48 |

Adjectives

49 |
50 |
51 |

52 |

53 |

54 |
55 |
56 | 57 |
58 |
59 |

Latest tweet sentiment

60 |
61 |
62 | 63 |
64 | 65 |
66 |
67 |
68 | 69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 | 82 | 83 | -------------------------------------------------------------------------------- /nl-firebase-twitter/frontend/main.css: -------------------------------------------------------------------------------- 1 | .chart-container { 2 | width: 500px; 3 | height: 500px; 4 | display: inline-block; 5 | position: absolute; 6 | margin: 30px; 7 | } 8 | 9 | @media (max-width: 600px) { 10 | body { margin-top: 0; background: white; box-shadow: none; } 11 | body { border-top: 16px solid #ffa100; } 12 | } 13 | 14 | 15 | #latest-sentiment { 16 | font-size: 25px; 17 | } 18 | 19 | .title { 20 | font-size: 16px; 21 | } 22 | 23 | .pos { 24 | color: #03A9F4; 25 | font-weight: bold; 26 | } 27 | 28 | .latest-tweet-header { 29 | margin-bottom: -20px; 30 | } 31 | 32 | #sentiment-plot { 33 | background-color: #03A9F4; 34 | width: 400px; 35 | height: 30px; 36 | z-index: 1; 37 | position: absolute; 38 | } 39 | 40 | #current-sentiment-val, #current-sentiment-latest-val { 41 | height: 30px; 42 | width: 4px; 43 | background-color: #FFC107; 44 | margin-top: -30px; 45 | position: absolute; 46 | z-index: 2; 47 | margin-top: 0px; 48 | } 49 | 50 | #android-emoji-sad, #android-emoji-happy { 51 | width: 40px; 52 | } 53 | 54 | #android-emoji-sad { 55 | margin-left: 318px; 56 | } -------------------------------------------------------------------------------- /nl-firebase-twitter/frontend/main.js: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Google Inc. 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | 16 | 17 | 18 | // TODO: initialize Firebase. Place your Firebase config credentials here 19 | // var config = {....} 20 | // firebase.initializeApp(config); 21 | 22 | const database = firebase.database(); 23 | const adjRef = database.ref('tokens').child('ADJ'); 24 | const htRef = database.ref('hashtags'); 25 | 26 | 27 | database.ref('latest').on('value', function(data) { 28 | 29 | let tweet = data.val(); 30 | let currentScore = tweet.score; 31 | 32 | let hashtagArr = []; 33 | let entityArr = []; 34 | let nounArr = []; 35 | let adjArr = []; 36 | let verbArr = []; 37 | 38 | for (let i in tweet.hashtags) { 39 | let htText = tweet.hashtags[i].text; 40 | hashtagArr.push(htText); 41 | } 42 | 43 | for (let i in tweet.entities) { 44 | let entityText = tweet.entities[i].name; 45 | entityArr.push(entityText); 46 | } 47 | 48 | for (let i in tweet.tokens) { 49 | let token = tweet.tokens[i]; 50 | if ((token.partOfSpeech.tag === "NOUN") && (token.lemma != "#") && (token.lemma.substring(0,4) != "http")) { 51 | nounArr.push(token.lemma.toLowerCase()); 52 | } else if (token.partOfSpeech.tag === "ADJ") { 53 | adjArr.push(token.lemma.toLowerCase()); 54 | } if (token.partOfSpeech.tag === "VERB") { 55 | verbArr.push(token.lemma.toLowerCase()); 56 | } 57 | } 58 | 59 | 60 | $('#latest-tweet').fadeOut(); 61 | $('#latest-tweet').html(''); 62 | $('#latest-tweet').fadeIn(); 63 | $('.nouns').text(nounArr.join(', ')); 64 | $('.verbs').text(verbArr.join(', ')); 65 | $('.adjectives').text(adjArr.join(', ')); 66 | 67 | 68 | // Adjust the sentiment scale for the latest tweet 69 | let scaleWidthPx = 400; // width of our scale in pixels 70 | let scaledSentiment = (scaleWidthPx * (currentScore + 1)) / 2; 71 | $('#current-sentiment-latest-val').css('margin-left', scaledSentiment + 'px'); 72 | 73 | }); 74 | 75 | Chart.defaults.global.defaultFontColor = '#03A9F4'; 76 | Chart.defaults.global.defaultFontStyle = 'bold'; 77 | Chart.defaults.global.defaultFontSize = 14; 78 | Chart.defaults.global.elements.rectangle.borderColor = '#2196F3'; 79 | Chart.defaults.global.elements.rectangle.backgroundColor = '#90CAF9'; 80 | Chart.defaults.global.legend.display = false; 81 | 82 | 83 | adjRef.orderByValue().limitToLast(10).once('value', function(data) { 84 | 85 | let chartLabels = []; 86 | let chartData = []; 87 | 88 | data.forEach(function(token) { 89 | let word = token.key; 90 | chartLabels.push(word); 91 | chartData.push(token.val()); 92 | }); 93 | 94 | var ctx = document.getElementById("adjChart"); 95 | 96 | var myChart = new Chart(ctx, { 97 | type: 'bar', 98 | data: { 99 | labels: chartLabels.reverse(), 100 | datasets: [{ 101 | label: '# of mentions', 102 | data: chartData.reverse(), 103 | borderWidth: 1 104 | }] 105 | }, 106 | options: { 107 | scales: { 108 | yAxes: [{ 109 | ticks: { 110 | beginAtZero:true, 111 | minRotation: 1, 112 | autoSkip: true 113 | } 114 | }] 115 | }, 116 | title: { 117 | display: true, 118 | text: 'Most common adjectives' 119 | }, 120 | showTooltips: true 121 | } 122 | }); 123 | 124 | 125 | adjRef.orderByValue().limitToLast(10).on('value', function(newData) { 126 | 127 | let updatedLabels = []; 128 | let updatedData = []; 129 | 130 | newData.forEach(function(token) { 131 | let word = token.key; 132 | updatedLabels.push(word); 133 | updatedData.push(token.val()); 134 | }); 135 | 136 | myChart.data.datasets[0].data = updatedData.reverse(); 137 | myChart.data.labels = updatedLabels.reverse(); 138 | myChart.update(); 139 | 140 | }); 141 | }); 142 | 143 | htRef.orderByChild('numMentions').limitToLast(10).on('value', function(data) { 144 | 145 | let htChartLabels = []; 146 | let labelSentiments = []; 147 | 148 | data.forEach(function(snap) { 149 | let ht = snap.key; 150 | htChartLabels.push(ht); 151 | let numMentions = snap.val().numMentions; 152 | let sentiment = snap.val().totalScore / numMentions; 153 | labelSentiments.push(sentiment); 154 | }); 155 | 156 | var scaleChart = document.getElementById("htChart"); 157 | 158 | var htChart = new Chart(scaleChart, { 159 | type: 'horizontalBar', 160 | data: { 161 | labels: htChartLabels, 162 | datasets: [{ 163 | label: 'sentiment value', 164 | data: labelSentiments, 165 | borderWidth: 1 166 | }] 167 | }, 168 | options: { 169 | elements: { 170 | rectangle: { 171 | borderWidth: 2 172 | } 173 | }, 174 | title: { 175 | display: true, 176 | text: 'Sentiment by hashtag' 177 | }, 178 | scales: { 179 | xAxes: [{ 180 | ticks: { 181 | min: -1, 182 | max: 1 183 | } 184 | }] 185 | }, 186 | responsive: true 187 | } 188 | }); 189 | }); -------------------------------------------------------------------------------- /project-settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sararob/ml-talk-demos/91a3327a3b8b8e536789647151b3046c0dee5e36/project-settings.png -------------------------------------------------------------------------------- /service-accounts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sararob/ml-talk-demos/91a3327a3b8b8e536789647151b3046c0dee5e36/service-accounts.png -------------------------------------------------------------------------------- /speech/request.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2017 Google Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # Create a request file with our JSON request in the current directory 18 | FILENAME="request-"`date +"%s".json` 19 | cat < $FILENAME 20 | { 21 | "config": { 22 | "encoding":"FLAC", 23 | "sampleRateHertz":16000, 24 | "profanityFilter": true, 25 | "languageCode": "en-US", 26 | "speechContexts": { 27 | "phrases": [''] 28 | }, 29 | "maxAlternatives": 1 30 | }, 31 | "audio": { 32 | "content": 33 | } 34 | } 35 | EOF 36 | 37 | # Update the languageCode parameter if one was supplied 38 | if [ $# -eq 1 ] 39 | then 40 | sed -i '' -e "s/en-US/$1/g" $FILENAME 41 | fi 42 | 43 | # Record an audio file, base64 encode it, and update our request object 44 | read -p "Press enter when you're ready to record" rec 45 | if [ -z $rec ]; then 46 | rec --channels=1 --bits=16 --rate=16000 audio.flac trim 0 5 47 | echo \"`base64 audio.flac`\" > audio.base64 48 | sed -i '' -e '/"content":/r audio.base64' $FILENAME 49 | fi 50 | echo Request "file" $FILENAME created: 51 | head -7 $FILENAME # Don't print the entire file because there's a giant base64 string 52 | echo $'\t"Your base64 string..."\n\x20\x20}\n}' 53 | 54 | # Call the speech API (requires an API key) 55 | read -p $'\nPress enter when you\'re ready to call the Speech API' var 56 | if [ -z $var ]; 57 | then 58 | echo "Running the following curl command:" 59 | echo "curl -s -X POST -H 'Content-Type: application/json' --data-binary @${FILENAME} https://speech.googleapis.com/v1/speech:recognize?key=API_KEY" 60 | curl -s -X POST -H "Content-Type: application/json" --data-binary @${FILENAME} https://speech.googleapis.com/v1/speech:recognize?key=YOUR_API_KEY 61 | fi -------------------------------------------------------------------------------- /table-schema.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sararob/ml-talk-demos/91a3327a3b8b8e536789647151b3046c0dee5e36/table-schema.png -------------------------------------------------------------------------------- /vision-api-firebase/cors.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "origin": ["*"], 4 | "method": ["GET"], 5 | "maxAgeSeconds": 3600 6 | } 7 | ] -------------------------------------------------------------------------------- /vision-api-firebase/database.rules.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | ".read": true, 4 | ".write": true, 5 | "entities": { 6 | ".indexOn": ".value" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /vision-api-firebase/firebase.json: -------------------------------------------------------------------------------- 1 | { 2 | "database": { 3 | "rules": "database.rules.json" 4 | }, 5 | "hosting": { 6 | "public": ".", 7 | "rewrites": [ 8 | { 9 | "source": "**", 10 | "destination": "/index.html" 11 | } 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /vision-api-firebase/functions/index.js: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Google Inc. 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | 'use strict'; 16 | 17 | const functions = require('firebase-functions'); 18 | const config = require('./local.json'); 19 | 20 | const fbConfig = { 21 | projectId: "your-firebase-project-id", 22 | keyfileName: 'keyfile.json' 23 | }; 24 | 25 | const vision = require('@google-cloud/vision')(fbConfig); 26 | 27 | const admin = require("firebase-admin"); 28 | const serviceAccount = require("./keyfile.json"); 29 | admin.initializeApp({ 30 | credential: admin.credential.cert(serviceAccount), 31 | databaseURL: "https://your-firebase-project-id.firebaseio.com" 32 | }); 33 | 34 | const db = admin.database(); 35 | const imageRef = db.ref('images'); 36 | const entitiesRef = db.ref('entities'); 37 | const labelsRef = db.ref('labels'); 38 | const faceRef = db.ref('faces'); 39 | const emojiRef = db.ref('emojis'); 40 | const latestImgDataRef = db.ref('latestImgData'); 41 | const emotions = ['anger','joy','sorrow','surprise']; 42 | let userRef; 43 | 44 | // Use a Firebase transaction to increment a counter 45 | function incrementCount(ref, child, valToIncrement) { 46 | ref.child(child).transaction(function(data) { 47 | if (data != null) { 48 | data += valToIncrement; 49 | } else { 50 | data = 1; 51 | } 52 | return data; 53 | }); 54 | } 55 | 56 | function detectFacesAndLabels(faces, entities) { 57 | if (faces) { 58 | for (let i in faces) { 59 | let face = faces[i]; 60 | for (let j in emotions) { 61 | let emotion = emotions[j]; 62 | if ((face[emotion + 'Likelihood'] === "VERY_LIKELY") || (face[emotion + 'Likelihood'] === "LIKELY") || (face[emotion + 'Likelihood'] === "POSSIBLE")) { 63 | incrementCount(faceRef, emotion, 1); 64 | } 65 | } 66 | } 67 | } 68 | 69 | if (entities) { 70 | for (let i in entities) { 71 | let entity = entities[i].description.toLowerCase(); 72 | entity.replace(/\.|#|\$|\[|\]|\//g,''); // Remove ".", "#", "$", "[", or "]" (illegal Firebase path name) 73 | incrementCount(entitiesRef, entity, 1); 74 | } 75 | } 76 | } 77 | 78 | exports.callVision = functions.storage.object().onChange(event => { 79 | const obj = event.data; 80 | 81 | const gcsUrl = "gs://" + obj.bucket + "/" + obj.name; 82 | const userId = obj.name.substring(0, obj.name.indexOf('/')); 83 | userRef = db.ref('users').child(userId); 84 | 85 | return Promise.resolve() 86 | .then(() => { 87 | if (obj.resourceState === 'not_exists') { 88 | // This was a deletion event, we don't want to process this 89 | return; 90 | } 91 | if (!obj.bucket) { 92 | throw new Error('Bucket not provided. Make sure you have a "bucket" property in your request'); 93 | } 94 | if (!obj.name) { 95 | throw new Error('Filename not provided. Make sure you have a "name" property in your request'); 96 | } 97 | 98 | let visionReq = { 99 | "image": { 100 | "source": { 101 | "imageUri": gcsUrl 102 | } 103 | }, 104 | "features": [ 105 | { 106 | "type": "FACE_DETECTION" 107 | }, 108 | { 109 | "type": "LABEL_DETECTION" 110 | }, 111 | { 112 | "type": "LANDMARK_DETECTION" 113 | }, 114 | { 115 | "type": "WEB_DETECTION" 116 | }, 117 | { 118 | "type": "IMAGE_PROPERTIES" 119 | }, 120 | { 121 | "type": "SAFE_SEARCH_DETECTION" 122 | } 123 | ] 124 | }; 125 | 126 | return vision.annotate(visionReq); 127 | }) 128 | .then(([visionData]) => { 129 | let imgMetadata = visionData[0]; 130 | console.log('got vision data: ',imgMetadata); 131 | imageRef.push(imgMetadata); 132 | userRef.child('visionData').set(imgMetadata); 133 | latestImgDataRef.set(imgMetadata); 134 | return detectFacesAndLabels(imgMetadata.faceAnnotations, imgMetadata.webDetection.webEntities); 135 | }) 136 | .then(() => { 137 | console.log(`Parsed vision annotation and wrote to Firebase`); 138 | }); 139 | }); -------------------------------------------------------------------------------- /vision-api-firebase/functions/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "functions", 3 | "description": "Cloud Functions for Firebase", 4 | "dependencies": { 5 | "@google-cloud/vision": "^0.11.2", 6 | "firebase-admin": "^4.1.2", 7 | "firebase-functions": "^0.5", 8 | "google-cloud": "^0.53.0" 9 | }, 10 | "private": true 11 | } 12 | -------------------------------------------------------------------------------- /vision-api-firebase/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sararob/ml-talk-demos/91a3327a3b8b8e536789647151b3046c0dee5e36/vision-api-firebase/icon.png -------------------------------------------------------------------------------- /vision-api-firebase/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Realtime Photo Fun 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
32 |
33 | 34 | 35 | 36 |
37 |
38 |
39 |
Permission Denied
40 |
41 | 42 |
43 |
44 | 45 |
46 |
47 | 48 |
49 |
50 |

Latest photo

51 | 52 |
53 |
54 | 55 |
56 |

Latest image data

57 |
58 |
59 |
60 |
61 | 62 | 63 |
64 |
65 |

Total photos:

66 |
67 |
68 | 69 | 70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 | 84 | 85 | -------------------------------------------------------------------------------- /vision-api-firebase/main.css: -------------------------------------------------------------------------------- 1 | /* Copyright 2017 Google Inc. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | body { 16 | margin: 10px; 17 | background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; 18 | } 19 | 20 | 21 | #c { 22 | display: none; 23 | } 24 | 25 | .chart-container { 26 | width: 100% !important; 27 | max-width: 800px; 28 | height: auto !important; 29 | } 30 | 31 | 32 | .grid-3-section { 33 | background-color: #E0E0E0; 34 | } 35 | 36 | @media (min-width: 0px) and (max-width: 500px) { 37 | #loadFileXml { 38 | display: block; 39 | padding-bottom: 3px; 40 | -webkit-appearance: none; 41 | width: 60%; 42 | margin-left: 20%; 43 | margin-right:20%; 44 | } 45 | } 46 | 47 | #total-selfies { 48 | color: rgb(63,81,181); 49 | } 50 | 51 | #latest-selfie, #user-latest-img { 52 | width: 120px; 53 | } 54 | 55 | img { 56 | border-radius: 5px; 57 | } 58 | 59 | .data-spinner-container { 60 | margin: 10px; 61 | 62 | } 63 | 64 | .permission-denied { 65 | visibility: hidden; 66 | color: #C5CAE9; 67 | } 68 | 69 | .mdl-spinner { 70 | display: block; 71 | margin-top: 15px; 72 | } 73 | 74 | .mdl-layout__header-row { 75 | padding-left: 40px; 76 | } 77 | 78 | #loadFileXml.btn { 79 | background-color: white; 80 | } 81 | 82 | .icon { 83 | width: 40px; 84 | margin-right: 20px; 85 | margin-left: -60px; 86 | } 87 | 88 | span.cell-header { 89 | color: rgb(63,81,181); 90 | font-size: 16px; 91 | font-weight: bold; 92 | margin-bottom: 5px; 93 | } 94 | 95 | 96 | .selfie-grid { 97 | text-align: center; 98 | margin-bottom: 35px; 99 | } 100 | 101 | .selfie-container { 102 | margin-bottom: 35px; 103 | } 104 | 105 | .graph-header-sec { 106 | text-align: center; 107 | font-size: 20px; 108 | font-weight: bold; 109 | } -------------------------------------------------------------------------------- /vision-api-firebase/main.js: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Google Inc. 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const storage = firebase.storage(); 16 | const storageRef = storage.ref(); 17 | const db = firebase.database(); 18 | 19 | const facesRef = db.ref('faces'); 20 | const labelsRef = db.ref('labels'); 21 | const entitiesRef = db.ref('entities'); 22 | const latestImageRef = db.ref('latest'); 23 | const numPhotosRef = db.ref('images'); 24 | const devicesRef = db.ref('devices'); 25 | const latestImgDataRef = db.ref('latestImgData'); 26 | const emotions = ['joy', 'anger', 'sorrow', 'surprise']; 27 | const provider = new firebase.auth.TwitterAuthProvider(); 28 | 29 | let isiPhone = false; 30 | let userId; 31 | let userRef; 32 | 33 | // Set default chart settings 34 | Chart.defaults.global.defaultFontColor = '#3F51B5'; 35 | Chart.defaults.global.defaultFontStyle = 'bold'; 36 | Chart.defaults.global.elements.rectangle.borderColor = '#3F51B5'; 37 | Chart.defaults.global.elements.rectangle.backgroundColor = '#9FA8DA'; 38 | Chart.defaults.global.legend.display = false; 39 | 40 | numPhotosRef.on('value', function(snap) { 41 | let numPhotos = snap.numChildren(); 42 | $('#num-selfies').html('' + numPhotos + ''); 43 | }); 44 | 45 | function writeImgtoFb(dataURL, imageRef) { 46 | imageRef.putString(dataURL, 'data_url').then(function(snapshot) { 47 | $('#user-img-data').html(""); 48 | $('.data-load-spinner').addClass('is-active'); 49 | let gcsUrl = "gs://" + imageRef.location.bucket + "/" + imageRef.location.path; 50 | userRef.child('gcsUrl').set(gcsUrl); 51 | latestImageRef.set({gcsUrl: gcsUrl}); 52 | }).catch(function(error) { 53 | if (error.code === "storage/unauthorized") { 54 | $(".mdl-spinner").remove(); 55 | $('.permission-denied').css('visibility', 'visible'); 56 | } 57 | }); 58 | 59 | 60 | } 61 | 62 | 63 | 64 | 65 | // iPhones do a weird image rotation thing - this checks for iPhone using WURFL 66 | function checkIfiPhone(deviceType) { 67 | if (deviceType.toLowerCase().includes('iphone')) { 68 | isiPhone = true; 69 | } 70 | } 71 | 72 | devicesRef.push(WURFL); 73 | checkIfiPhone(WURFL.complete_device_name); 74 | 75 | firebase.auth().onAuthStateChanged(function(user) { 76 | if (user) { 77 | 78 | userId = user.uid; 79 | userRef = db.ref('users').child(userId); 80 | 81 | latestImgDataRef.on('value', function (snap) { 82 | 83 | let latestImgData = snap.val(); 84 | let facesStr = ""; 85 | let labelsStr = "Labels found: "; 86 | 87 | if (latestImgData !== null) { 88 | 89 | if (latestImgData.faceAnnotations) { 90 | facesStr += "Found a face!"; 91 | let face = latestImgData.faceAnnotations[0]; 92 | 93 | for (let j in emotions) { 94 | let emotion = emotions[j]; 95 | if ((face[emotion + 'Likelihood'] === "VERY_LIKELY") || (face[emotion + 'Likelihood'] === "LIKELY") || (face[emotion + 'Likelihood'] === "POSSIBLE")) { 96 | facesStr += " Detected " + emotion + "."; 97 | } 98 | } 99 | } 100 | 101 | if (latestImgData.webDetection.webEntities) { 102 | let labels = latestImgData.webDetection.webEntities; 103 | let labelsFound = []; 104 | for (let i in labels) { 105 | let label = labels[i].description.toLowerCase(); 106 | if (label.length > 1) { 107 | labelsFound.push("" + label + ""); 108 | } 109 | } 110 | labelsStr += labelsFound.join(", "); 111 | } 112 | 113 | $('#user-img-data').html(labelsStr + "
" + facesStr); 114 | $('.data-load-spinner').removeClass('is-active'); 115 | $('.img-load-spinner').removeClass('is-active'); 116 | } 117 | }); 118 | 119 | } else { 120 | firebase.auth().signInWithRedirect(provider).then(function(result) { 121 | // This gives you a the Twitter OAuth 1.0 Access Token and Secret. 122 | // You can use these server side with your app's credentials to access the Twitter API. 123 | let token = result.credential.accessToken; 124 | let secret = result.credential.secret; 125 | // The signed-in user info. 126 | let user = result.user; 127 | 128 | }).catch(function(error) { 129 | 130 | let errorCode = error.code; 131 | let errorMessage = error.message; 132 | let credential = error.credential; 133 | }); 134 | } 135 | }); 136 | 137 | 138 | function valueToEmoji(emotion) { 139 | if (emotion === "joy") { 140 | return ":‑)"; 141 | } else if (emotion === "sorrow") { 142 | return ":‑("; 143 | } else if (emotion === "anger"){ 144 | return ">:("; 145 | } else if (emotion === "surprise") { 146 | return " :‑o"; 147 | } else { 148 | return ":-/"; 149 | } 150 | } 151 | 152 | 153 | 154 | facesRef.on('value', function(snap) { 155 | let faceLabels = []; 156 | let faceCount = []; 157 | 158 | snap.forEach(function(faceData) { 159 | let emotion = faceData.key; 160 | let emoji = valueToEmoji(emotion); 161 | faceLabels.push(emoji); 162 | faceCount.push(faceData.val()); 163 | }); 164 | 165 | let faceChart = document.getElementById("faceChart"); 166 | 167 | let htChart = new Chart(faceChart, { 168 | type: 'horizontalBar', 169 | data: { 170 | labels: faceLabels, 171 | datasets: [{ 172 | label: 'number of faces', 173 | data: faceCount, 174 | borderWidth: 1, 175 | }] 176 | }, 177 | options: { 178 | elements: { 179 | rectangle: { 180 | borderWidth: 2 181 | } 182 | }, 183 | title: { 184 | display: true, 185 | text: 'Total emotions detected' 186 | }, 187 | scales: { 188 | yAxes: [{ 189 | ticks: { 190 | fontSize: 30, 191 | beginAtZero: true 192 | } 193 | }], 194 | xAxes: [{ 195 | ticks: { 196 | beginAtZero: true 197 | } 198 | }] 199 | }, 200 | responsive: true 201 | } 202 | }); 203 | 204 | }); 205 | 206 | 207 | 208 | entitiesRef.orderByValue().limitToLast(10).on('value', function(snap) { 209 | let labels = []; 210 | let counts = []; 211 | 212 | snap.forEach(function(labelData) { 213 | let label = labelData.key; 214 | labels.push(label); 215 | counts.push(labelData.val()); 216 | }); 217 | 218 | let labelsChart = document.getElementById("labelsChart"); 219 | 220 | let htChart = new Chart(labelsChart, { 221 | type: 'horizontalBar', 222 | data: { 223 | labels: labels.reverse(), 224 | datasets: [{ 225 | label: '# of pictures', 226 | data: counts.reverse(), 227 | borderWidth: 1 228 | }] 229 | }, 230 | options: { 231 | elements: { 232 | rectangle: { 233 | borderWidth: 2 234 | } 235 | }, 236 | title: { 237 | display: true, 238 | text: 'Total entities detected' 239 | }, 240 | scales: { 241 | yAxes: [{ 242 | fontSize: 20 243 | }], 244 | xAxes: [{ 245 | ticks: { 246 | beginAtZero: true 247 | } 248 | }] 249 | }, 250 | responsive: true 251 | } 252 | }); 253 | 254 | }); 255 | 256 | 257 | function rotateBase64Image90Degree(base64data, imageRef) { 258 | let canvas = document.getElementById("c"); 259 | let ctx = canvas.getContext("2d"); 260 | let image = new Image(); 261 | 262 | image.src = base64data; 263 | image.onload = function() { 264 | canvas.width = image.height; 265 | canvas.height = image.width; 266 | ctx.rotate(90 * Math.PI / 180); 267 | ctx.translate(0, -canvas.width); 268 | ctx.drawImage(image, 0, 0); 269 | 270 | let b64 = canvas.toDataURL(); 271 | writeImgtoFb(b64, imageRef); 272 | }; 273 | } 274 | 275 | 276 | // Save image to Firebase Storage 277 | $(function() { 278 | $("#img-select").change(function (){ 279 | 280 | if (userId) { 281 | $('.img-load-spinner').addClass('is-active'); 282 | $("#img-status").html("Uploading to Firebase..."); 283 | 284 | 285 | let elm = document.getElementById('img-select'), 286 | img = elm.files[0], 287 | fileName = img.name, 288 | fileSize = img.size; 289 | 290 | let reader = new FileReader(); 291 | 292 | reader.onload = function(e) { 293 | let dataURL = reader.result; 294 | 295 | let imageRef = storageRef.child(userId + '/' + fileName); 296 | if (isiPhone) { 297 | rotateBase64Image90Degree(dataURL, imageRef); 298 | } else { 299 | writeImgtoFb(dataURL, imageRef); 300 | } 301 | }; 302 | reader.readAsDataURL(img); 303 | } 304 | }); 305 | }); 306 | 307 | latestImageRef.on('value', function(data) { 308 | let gsRef = storage.refFromURL(data.val().gcsUrl); 309 | gsRef.getDownloadURL().then(function(url) { 310 | $('.img-load-spinner').removeClass('is-active'); 311 | let img = document.getElementById('latest-selfie'); 312 | img.src = url; 313 | 314 | 315 | }).catch(function(error) { 316 | // Handle any errors 317 | }); 318 | 319 | }); -------------------------------------------------------------------------------- /vision-speech-nl-translate/requirements.txt: -------------------------------------------------------------------------------- 1 | sounddevice==0.3.6 2 | scipy==0.18.1 3 | ffmpy==0.2.2 4 | httplib2==0.9.2 5 | readline==6.2.4.1 6 | oauth2client==4.0.0 7 | google.cloud==0.22.0 8 | termcolor==1.1.0 9 | pick==0.6.1 10 | pygments==2.2.0 -------------------------------------------------------------------------------- /vision-speech-nl-translate/textify.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Google Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # Unless required by applicable law or agreed to in writing, software 7 | # distributed under the License is distributed on an "AS IS" BASIS, 8 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | # See the License for the specific language governing permissions and 10 | # limitations under the License. 11 | from __future__ import print_function 12 | import base64 13 | import json 14 | import io 15 | import os 16 | import readline 17 | import time 18 | import ffmpy 19 | import httplib2 20 | from googleapiclient import discovery 21 | from oauth2client.client import GoogleCredentials 22 | from google.cloud import translate 23 | from pick import pick 24 | from termcolor import colored 25 | import sounddevice as sd 26 | import scipy.io.wavfile as scipy 27 | from pygments import highlight, lexers, formatters 28 | # Audio recording duration and sample rate 29 | DURATION = 5 30 | SAMPLE_RATE = 16000 31 | # Languages supported by Neural Machine Translation 32 | SUPPORTED_LANGUAGES = {"German": "de", "Spanish": "es", "French": "fr", 33 | "Japanese": "ja", "Korean": "ko", "Portuguese": "pt", 34 | "Turkish": "tr", "Chinese(Simplified)": "zh-CN"} 35 | # [START authenticating] 36 | DISCOVERY_URL = ('https://{api}.googleapis.com/$discovery/rest?' 37 | 'version={apiVersion}') 38 | # Application default credentials provided by env variable 39 | # GOOGLE_APPLICATION_CREDENTIALS 40 | 41 | 42 | def get_service(api, version): 43 | credentials = GoogleCredentials.get_application_default().create_scoped( 44 | ['https://www.googleapis.com/auth/cloud-platform']) 45 | http = httplib2.Http() 46 | credentials.authorize(http) 47 | return discovery.build( 48 | api, version, http=http, discoveryServiceUrl=DISCOVERY_URL) 49 | # [END authenticating] 50 | 51 | 52 | def call_nl_api(text): 53 | service = get_service('language', 'v1') 54 | service_request = service.documents().annotateText( 55 | body={ 56 | 'document': { 57 | 'type': 'PLAIN_TEXT', 58 | 'content': text, 59 | }, 60 | 'features': { 61 | "extractSyntax": True, 62 | "extractEntities": True, 63 | "extractDocumentSentiment": True, 64 | } 65 | } 66 | ) 67 | response = service_request.execute() 68 | print(colored("\nHere's the JSON repsonse" + 69 | "for one token of your text:\n", 70 | "cyan")) 71 | formatted_json = json.dumps(response['tokens'][0], indent=2) 72 | colorful_json = highlight(formatted_json, 73 | lexers.JsonLexer(), 74 | formatters.TerminalFormatter()) 75 | print(colorful_json) 76 | score = response['documentSentiment']['score'] 77 | output_text = colored(analyze_sentiment(score), "cyan") 78 | if response['entities']: 79 | entities = str(analyze_entities(response['entities'])) 80 | output_text += colored("\nEntities found: " + entities, "white") 81 | return [output_text, response['language']] 82 | 83 | 84 | def translate_text_with_model(text, model=translate.NMT): 85 | # Translates text into the target language. 86 | title = "Which language would you like to translate it to?" 87 | options = ["German", "Spanish", "French", "Japanese", 88 | "Korean", "Portuguese", "Turkish", "Chinese(Simplified)"] 89 | lang, index = pick(options, title) 90 | lang_code = SUPPORTED_LANGUAGES[lang] 91 | translate_client = translate.Client() 92 | result = translate_client.translate( 93 | text, 94 | target_language=lang_code, 95 | model=model) 96 | translate_back = translate_client.translate( 97 | result['translatedText'], 98 | target_language="en", 99 | model=model) 100 | print(colored(("Translated in " + lang + 101 | ": " + result['translatedText']), "white")) 102 | print(colored("Your text translated back to English: " + 103 | translate_back['translatedText'], "white")) 104 | 105 | 106 | def call_speech(): 107 | speech_prompt = input(colored("Press enter to start recording " + 108 | str(DURATION) + " seconds of audio", "cyan")) 109 | if speech_prompt == "": 110 | # Record audio and write to file using sounddevice 111 | myrecording = sd.rec(DURATION * SAMPLE_RATE, 112 | samplerate=SAMPLE_RATE, 113 | channels=1, 114 | blocking=True) 115 | print(colored("Writing your audio to a file...", "magenta")) 116 | scipy.write('test.wav', SAMPLE_RATE, myrecording) 117 | filename = 'speech-' + str(int(time.time())) + '.flac' 118 | rec = ffmpy.FFmpeg( 119 | inputs={'test.wav': None}, 120 | outputs={filename: None} 121 | ) 122 | rec.run() 123 | # Encode audio file and call the Speech API 124 | with io.open(filename, "rb") as speech: 125 | # Base64 encode the binary audio file for inclusion in the JSON 126 | # request. 127 | speech_content = base64.b64encode(speech.read()) 128 | service = get_service('speech', 'v1beta1') 129 | print(colored("Transcribing your audio with the Speech API...", 130 | "magenta")) 131 | service_request = service.speech().syncrecognize( 132 | body={ 133 | 'config': { 134 | 'encoding': 'FLAC', # raw 16-bit signed LE samples 135 | 'sampleRate': SAMPLE_RATE, # 16 khz 136 | 'languageCode': 'en-US', # a BCP-47 language tag 137 | }, 138 | 'audio': { 139 | 'content': speech_content.decode('UTF-8') 140 | } 141 | }) 142 | response = service_request.execute() 143 | text_response = response['results'][0]['alternatives'][0]['transcript'] 144 | return text_response 145 | 146 | 147 | def call_vision(filename): 148 | service = get_service('vision', 'v1') 149 | with open(filename, 'rb') as image: 150 | image_content = base64.b64encode(image.read()) 151 | service_request = service.images().annotate(body={ 152 | 'requests': [{ 153 | 'image': { 154 | 'content': image_content.decode('UTF-8') 155 | }, 156 | 'features': [{ 157 | 'type': 'DOCUMENT_TEXT_DETECTION' 158 | }] 159 | }] 160 | }) 161 | response = service_request.execute() 162 | ocr_text = response['responses'][0]['textAnnotations'][0]['description'] 163 | return ocr_text 164 | 165 | 166 | def analyze_sentiment(score): 167 | sentiment_str = "You seem " 168 | if -1 <= score < -0.5: 169 | sentiment_str += "angry. Hope you feel better soon!" 170 | elif -0.5 <= score < 0.5: 171 | sentiment_str += "pretty neutral." 172 | else: 173 | sentiment_str += "very happy! Yay :)" 174 | return sentiment_str + "\n" 175 | 176 | 177 | def analyze_entities(entities): 178 | arr = [] 179 | for entity in entities: 180 | if 'wikipedia_url' in entity['metadata']: 181 | arr.append(entity['name'] + ': ' + 182 | entity['metadata']['wikipedia_url']) 183 | else: 184 | arr.append(entity['name']) 185 | return arr 186 | 187 | 188 | def handle_nl_and_translate_call(text): 189 | nl_response = call_nl_api(text) 190 | analyzed_text = nl_response[0] 191 | print(analyzed_text) 192 | translate_ready = input(colored("Next, we'll translate your text using" + 193 | " Neural Machine Translation.\n" + 194 | "Press enter when you're ready\n", "cyan")) 195 | if translate_ready == "": 196 | translate_text_with_model(text) 197 | 198 | 199 | print(colored("We're going to send some text to the Natural Language API!\n" + 200 | "It supports English, Spanish, and Japanese.\n", "cyan")) 201 | STEP_ONE = input(colored("Enter 't' to type your text,\n" + 202 | "'r' to record your text,\n" + 203 | "or 'p' to send a photo with text: ", "cyan")) 204 | print("\r") 205 | if STEP_ONE == 't': 206 | NL_TEXT = input(colored("Enter your text to send\n", "cyan")) 207 | handle_nl_and_translate_call(NL_TEXT) 208 | elif STEP_ONE == 'r': 209 | TRANSCRIBED_TEXT = call_speech() 210 | print("You said: " + TRANSCRIBED_TEXT) 211 | handle_nl_and_translate_call(TRANSCRIBED_TEXT) 212 | elif STEP_ONE == 'p': 213 | # Get image url 214 | URL = input(colored("Enter the filepath of your image: ", "cyan")) 215 | if os.path.exists(URL): 216 | print(colored("Valid image URL, sending your image" + 217 | " to the Vision API...", "cyan")) 218 | IMG_TEXT = call_vision(URL) 219 | print(colored("Found this text in your image: \n" + IMG_TEXT, "white")) 220 | handle_nl_and_translate_call(IMG_TEXT) 221 | else: 222 | STEP_ONE = input("That's not a valid entry.") 223 | --------------------------------------------------------------------------------