├── .firebaserc ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── firebase.json ├── firestore.indexes.json ├── firestore.rules ├── functions ├── index.js └── package.json ├── public ├── index.html ├── main.css └── main.js └── screenshots ├── cloud-demo.gif ├── firebase-cli.png ├── firestore.png └── starter-demo-page.png /.firebaserc: -------------------------------------------------------------------------------- 1 | { 2 | "projects": { 3 | "default": "YOUR_FIREBASE_PROJECT" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *-lock.json 2 | *node_modules/ 3 | .DS_Store -------------------------------------------------------------------------------- /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 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows 28 | [Google's Open Source Community Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | # Demo: querying a custom AutoML model from a web app 4 | 5 | This demo shows how to call a custom AutoML model from a web app using the [AutoML API](https://cloud.google.com/vision/automl/docs/reference/rest/). It queries an [AutoML Vision](https://cloud.google.com/vision/automl/docs/) model, but the code can easily be adapted for [AutoML Natural Language](https://cloud.google.com/natural-language/automl/docs/) since the API is the same for both. The model I'm using for this predicts the type of cloud in an image: 6 | 7 | ![Demo gif](screenshots/cloud-demo.gif) 8 | 9 | *For more details on this specific vision model, check out the AutoML section of my [Cloud Next '18 talk](https://youtu.be/QU7_eU8HzAQ?t=16m12s).* 10 | 11 | ## Pre-requisites 12 | 13 | * You've built and trained a model with [Cloud AutoML](http://cloud.google.com/automl). 14 | * You've enabled the AutoML API in your Cloud project 15 | * You've created a project in the Firebase console and associated it with the same project where you trained your AutoML model. Using the [Firebase CLI](https://firebase.google.com/docs/cli/), make sure to initialize your project with Firestore, Functions, Hosting, and Storage: 16 | 17 | ![Firebase CLI](screenshots/firebase-cli.png) 18 | 19 | ## Deploying the function 20 | 21 | From within the `functions/` directory, run `npm install` to install the Node packages listed in `functions/package.json`. The `functions/index.js` file includes the functions code to call the custom AutoML model. 22 | 23 | First, replace the 3 placeholder strings at the top of the file with info for your own project and AutoML model: 24 | 25 | ```javascript 26 | const project = 'YOUR_PROJECT_NAME'; 27 | const region = 'YOUR_PROJECT_REGION'; 28 | const automl_model = 'YOUR_AUTOML_MODEL_ID'; 29 | ``` 30 | 31 | Now you're ready to deploy the function. From the root directory of this project, run the command: 32 | 33 | ```bash 34 | firebase deploy --only functions 35 | ``` 36 | 37 | Once your function deploys successfully you can test it by uploading a photo to the Firebase Storage bucket in your project. Then check your Firestore database. You should see the prediction data for that image: 38 | 39 | ![Firestore screenshot](screenshots/firestore.png) 40 | 41 | ## Deploying the frontend 42 | 43 | The frontend code for this app is all in the `public/` directory and uses good old jQuery :) In `public/main.js`, a photo is uploaded to the Firebase Storage bucket for your project which triggers the function calling the AutoML API. First, try it out by serving the frontend locally. Run `firebase serve` from the root directory of this project, navigate to `localhost:5000`, and you should see this: 44 | 45 | ![Starer demo page](screenshots/starter-demo-page.png) 46 | 47 | If the frontend is working correctly you're ready to deploy it. Run the command: 48 | 49 | ```bash 50 | firebase deploy --only hosting 51 | ``` 52 | 53 | Now your app should be deployed to a firebaseapp.com domain, woohoo! -------------------------------------------------------------------------------- /firebase.json: -------------------------------------------------------------------------------- 1 | { 2 | "firestore": { 3 | "rules": "firestore.rules", 4 | "indexes": "firestore.indexes.json" 5 | }, 6 | "hosting": { 7 | "public": "public", 8 | "ignore": [ 9 | "firebase.json", 10 | "**/.*", 11 | "**/node_modules/**" 12 | ], 13 | "rewrites": [ 14 | { 15 | "source": "**", 16 | "destination": "/index.html" 17 | } 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /firestore.indexes.json: -------------------------------------------------------------------------------- 1 | { 2 | // Example: 3 | // 4 | // "indexes": [ 5 | // { 6 | // "collectionId": "widgets", 7 | // "fields": [ 8 | // { "fieldPath": "foo", "mode": "ASCENDING" }, 9 | // { "fieldPath": "bar", "mode": "DESCENDING" } 10 | // ] 11 | // } 12 | // ] 13 | "indexes": [] 14 | } -------------------------------------------------------------------------------- /firestore.rules: -------------------------------------------------------------------------------- 1 | service cloud.firestore { 2 | match /databases/{database}/documents { 3 | match /{document=**} { 4 | allow read, write; 5 | } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /functions/index.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google LLC 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 | // https://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 | // Replace the strings below with your own project & model info 16 | const project = 'YOUR_PROJECT_NAME'; 17 | const region = 'YOUR_PROJECT_REGION'; 18 | const automl_model = 'YOUR_AUTOML_MODEL_ID'; 19 | 20 | const sizeOf = require('image-size'); 21 | const fs = require('fs'); 22 | const exec = require('child_process').exec; 23 | 24 | // GCP libraries 25 | const gcs = require('@google-cloud/storage'); 26 | const gcsClient = new gcs(); 27 | const automl = require('@google-cloud/automl'); 28 | const predictionClient = new automl.PredictionServiceClient(); 29 | 30 | // Firebase libraries 31 | const functions = require('firebase-functions'); 32 | const admin = require('firebase-admin'); 33 | const db = admin.firestore(); 34 | admin.initializeApp(functions.config().firebase); 35 | 36 | function resizeImg(filepath) { 37 | return new Promise((resolve, reject) => { 38 | exec(`convert ${filepath} -resize 600x ${filepath}`, (err) => { 39 | if (err) { 40 | console.error('Failed to resize image', err); 41 | reject(err); 42 | } else { 43 | console.log('resized image successfully'); 44 | resolve(filepath); 45 | } 46 | }); 47 | }); 48 | } 49 | 50 | function callAutoMLAPI(b64img) { 51 | return new Promise((resolve, reject) => { 52 | const payload = { 53 | "image": { 54 | "imageBytes": b64img 55 | } 56 | } 57 | const reqBody = { 58 | name: predictionClient.modelPath(project, region, automl_model), 59 | payload: payload 60 | } 61 | predictionClient.predict(reqBody) 62 | .then(responses => { 63 | console.log('Got a prediction from AutoML API!', JSON.stringify(responses)); 64 | resolve(responses); 65 | }) 66 | .catch(err => { 67 | console.log('AutoML API Error: ',err); 68 | reject(err); 69 | }); 70 | }); 71 | 72 | } 73 | 74 | exports.callCustomModel = functions.storage.object().onFinalize(event => { 75 | const file = gcsClient.bucket(event.bucket).file(event.name); 76 | let destination = '/tmp/' + event.name.replace(/\s/g, ''); 77 | return file.download({destination: destination}) 78 | .then(() => { 79 | if(sizeOf(destination).width > 600) { 80 | console.log('scaling image down...'); 81 | return resizeImg(destination); 82 | } else { 83 | return destination; 84 | } 85 | }) 86 | .then(() => { 87 | let bitmap = fs.readFileSync(destination); 88 | let data = new Buffer(bitmap).toString('base64'); 89 | return callAutoMLAPI(data); 90 | }) 91 | .then((response) => { 92 | let predictions = {}; 93 | 94 | // Get only the first prediction response 95 | let data = response[0]['payload']; 96 | predictions[data[0].displayName] = data[0].classification.score; 97 | 98 | if (Object.keys(predictions).length === 0) { 99 | predictions = {"predictionErr": "No high confidence predictions found"}; 100 | } 101 | return db.collection('images').doc(event.name).set(predictions); 102 | }) 103 | .then(() => { 104 | // Delete tmp image file to clean up resources 105 | return new Promise((resolve, reject) => { 106 | fs.unlinkSync(destination, (err) => { 107 | if (err) { 108 | reject(err); 109 | } else { 110 | resolve(); 111 | } 112 | }); 113 | }); 114 | }) 115 | .catch((err) => { 116 | console.log('error occurred', err); 117 | }); 118 | }); -------------------------------------------------------------------------------- /functions/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "functions", 3 | "description": "Cloud Functions for Firebase", 4 | "dependencies": { 5 | "@google-cloud/automl": "^0.1.1", 6 | "@google-cloud/storage": "^1.7.0", 7 | "firebase-admin": "^6.0.0", 8 | "firebase-functions": "^2.0.5", 9 | "image-size": "^0.6.3" 10 | }, 11 | "private": true 12 | } 13 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Cloud Detector 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 |
26 |
27 | cloud_queue 28 | Cloud Detector 29 |
30 | 34 |
35 |
36 |
37 |
38 |
39 |
40 |

41 |
42 |
43 | 44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 | 55 |
56 |
57 |
58 |
59 | 60 | 61 |
62 |
63 | 64 | 65 | -------------------------------------------------------------------------------- /public/main.css: -------------------------------------------------------------------------------- 1 | body { 2 | background: #ECEFF1; 3 | color: rgba(0,0,0,0.87); 4 | font-family: Roboto, Helvetica, Arial, sans-serif; 5 | margin: 25px; 6 | } 7 | 8 | #preview img { 9 | width: 300px; 10 | } 11 | 12 | i { 13 | margin: 10px; 14 | } 15 | 16 | div.mdl-layout__header-row { 17 | margin-left: 10px; 18 | padding: 0; 19 | } 20 | 21 | #file-select { 22 | cursor: pointer; 23 | font-size: 15px; 24 | font-weight: bold; 25 | } 26 | 27 | #progress-bar { 28 | display: none; 29 | } 30 | 31 | div.demo-card-wide.mdl-card.mdl-shadow--2dp { 32 | width: 450px; 33 | text-align: center; 34 | min-height: 300px; 35 | } 36 | 37 | .demo-card-wide > .mdl-card__title { 38 | color: #fff; 39 | background: url('../assets/demos/welcome_card.jpg') center / cover; 40 | } 41 | 42 | .mdl-card__title img { 43 | max-width: 350px; 44 | text-align: center; 45 | margin: 0 auto; 46 | padding: 5px; 47 | } 48 | 49 | #prediction-text { 50 | color: rgb(33,150,243); 51 | font-size: 16px; 52 | font-weight: bold; 53 | } 54 | 55 | #card { 56 | display: none; 57 | } -------------------------------------------------------------------------------- /public/main.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google LLC 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 | // https://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 forecast = { 16 | "altocumulus": { 17 | "weather": "These clouds are often spotted on warm and humid mornings. They can signal thunderstorms on the way or cold fronts." 18 | }, 19 | "altostratus": { 20 | "weather": "You might see this clouds before a warm front, or together with cumulus clouds during a cold front." 21 | }, 22 | "cirrus": { 23 | "weather": "Cirrus clouds can appear before warm fronts and big storms like nor'easters." 24 | }, 25 | "cumulonimbus": { 26 | "weather": "Uh oh. There's likely severe weather approaching nearby. Cumulonimbus clouds are usually associated with short periods of heavy rainfall, hail, or even tornadoes. If you're flying today, there might be turbulence." 27 | }, 28 | "cumulus": { 29 | "weather": "These clouds often develop on clear sunny days when the sun heats the ground directly below." 30 | } 31 | } 32 | 33 | function clearPrediction() { 34 | $('#img-predicted').html(''); 35 | $('#weather-summary', '#status', '#prediction-text').text(''); 36 | $('#card').css('display', 'none'); 37 | } 38 | 39 | function updateProgressBar(status) { 40 | if (status == 'show') { 41 | $('#progress-bar').css('display', 'inline-block'); 42 | $('#progress-bar').addClass('mdl-progress__indeterminate'); 43 | } else if (status == 'hide') { 44 | $('#progress-bar').css('display', 'none'); 45 | } 46 | } 47 | 48 | function displayPrediction(data) { 49 | $('#card').css('display', 'inline-block'); 50 | $('#status').text('Got a prediction!'); 51 | 52 | // This demo assumes only one label returned 53 | let cloudType = Object.keys(data)[0]; 54 | let resultText = `${cloudType}: ${(data[cloudType] * 100).toFixed(2)}%\n`; 55 | $('#prediction-text').text(resultText); 56 | $('#weather-summary').text(forecast[cloudType].weather); 57 | } 58 | 59 | function displayImage(file) { 60 | let img = document.createElement("img"); 61 | img.file = file; 62 | $('#img-predicted').append(img); 63 | 64 | let reader = new FileReader(); 65 | reader.onload = (function(imgDiv) { return function(e) { imgDiv.src = e.target.result; }; })(img); 66 | reader.readAsDataURL(file); 67 | } 68 | 69 | $(document).ready(() => { 70 | const storage = firebase.storage(); 71 | const storageRef = storage.ref(); 72 | const db = firebase.firestore(); 73 | 74 | $('#file-select').on('click', () => { 75 | $('#cloud-upload').trigger("click"); 76 | }); 77 | 78 | $('#cloud-upload').on('change', (e) => { 79 | let localFile = e.target.files[0]; 80 | clearPrediction(); 81 | updateProgressBar('show'); 82 | 83 | // Upload the image to Firebase Storage 84 | $('#status').text('Uploading image...'); 85 | let imgRef = storageRef.child(localFile.name); 86 | imgRef.put(localFile).then(() => { 87 | $('#status').text('Querying model...'); 88 | db.collection("images") 89 | .doc(localFile.name) 90 | .onSnapshot(function(doc) { 91 | if (doc.exists) { 92 | let cloudData = doc.data(); 93 | updateProgressBar('hide'); 94 | if (cloudData.predictionErr) { 95 | $('#status').text(`${cloudData.predictionErr} :(`); 96 | } else { 97 | displayPrediction(cloudData); 98 | displayImage(localFile); 99 | } 100 | } 101 | }); 102 | }); 103 | }); 104 | }); -------------------------------------------------------------------------------- /screenshots/cloud-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sararob/automl-api-demo/c449bbd0f5d4b4ccb917e4f4d2706d598c2ec429/screenshots/cloud-demo.gif -------------------------------------------------------------------------------- /screenshots/firebase-cli.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sararob/automl-api-demo/c449bbd0f5d4b4ccb917e4f4d2706d598c2ec429/screenshots/firebase-cli.png -------------------------------------------------------------------------------- /screenshots/firestore.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sararob/automl-api-demo/c449bbd0f5d4b4ccb917e4f4d2706d598c2ec429/screenshots/firestore.png -------------------------------------------------------------------------------- /screenshots/starter-demo-page.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sararob/automl-api-demo/c449bbd0f5d4b4ccb917e4f4d2706d598c2ec429/screenshots/starter-demo-page.png --------------------------------------------------------------------------------