├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── maps ├── function-declarations.js ├── index.html ├── presets.js ├── script.js └── styles.css ├── spatial ├── .env ├── .gcloudignore ├── .gitignore ├── app.yaml ├── eslint.config.js ├── index.html ├── package-lock.json ├── package.json ├── postcss.config.js ├── public │ ├── baklava.jpg │ ├── breakfast.jpg │ ├── cat.jpg │ ├── clock.jpg │ ├── fruit.jpg │ ├── origami.jpg │ ├── pumpkins.jpg │ ├── socks.jpg │ └── spill.jpg ├── src │ ├── App.tsx │ ├── Content.tsx │ ├── DetectTypeSelector.tsx │ ├── ExampleImages.tsx │ ├── ExtraModeControls.tsx │ ├── Palette.tsx │ ├── Prompt.tsx │ ├── ScreenshareButton.tsx │ ├── SideControls.tsx │ ├── TopBar.tsx │ ├── Types.tsx │ ├── atoms.tsx │ ├── consts.tsx │ ├── hooks.tsx │ ├── index.css │ ├── main.tsx │ ├── styles.css │ ├── utils.tsx │ └── vite-env.d.ts ├── tailwind.config.js ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.node.json └── vite.config.ts └── video ├── .env ├── .gcloudignore ├── .gitignore ├── eslint.config.js ├── index.html ├── package.json ├── server ├── index.mjs └── upload.mjs ├── src ├── App.jsx ├── Chart.jsx ├── VideoPlayer.jsx ├── api.js ├── functions.js ├── main.jsx ├── modes.js ├── styles │ ├── chart.sass │ ├── main.sass │ └── player.sass └── utils.js └── vite.config.js /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 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Google AI Studio Starter Applets 2 | 3 | This repository contains the source code for Google AI Studio's 4 | [starter apps](https://aistudio.google.com/app/starter-apps) — a collection of 5 | small apps that demonstrate how Gemini can be used to create interactive 6 | experiences. These apps are built to run inside AI Studio, but the versions 7 | included here can run standalone using the 8 | [Gemini API](https://ai.google.dev/gemini-api/docs). 9 | 10 | ## Spatial Understanding 11 | 12 | [Spatial Understanding](/spatial/) 13 | ([live demo](https://aistudio.google.com/app/starter-apps/spatial)) is a simple 14 | demonstration of Gemini's 2D and 3D spatial understanding and reasoning 15 | capabilities. It was built with React. 16 | 17 | This example should give you an idea of how to get started with spatial analysis 18 | using Gemini. Check out [Prompt.tsx](/spatial/src/Prompt.tsx) to see how 19 | bounding box parsing is implemented. To dive deeper into Gemini's spatial 20 | reasoning capabilities, check out this 21 | [Colab notebook](https://github.com/google-gemini/cookbook/blob/main/gemini-2/spatial_understanding.ipynb). 22 | 23 | To develop locally, insert your Gemini API key in the `.env` file. 24 | 25 | ## Video Analyzer 26 | 27 | [Video Analyzer](/video/) 28 | ([live demo](https://aistudio.google.com/app/starter-apps/video)) is a simple 29 | app that allows you to explore events within videos using Gemini. It was built 30 | with React. 31 | 32 | This example shows how to get started with video analysis using function 33 | calling. Check out [functions.js](/video/src/functions.js) to see the function 34 | definition for this applet! 35 | 36 | To develop locally, insert your Gemini API key in the `.env` file. 37 | 38 | ## Map Explorer 39 | 40 | [Map Explorer](/maps/) 41 | ([live demo](https://aistudio.google.com/app/starter-apps/map)) is a simple app 42 | that allows you to explore a map using Gemini and the Google Maps API. It was 43 | built using Lit, and the 44 | [Maps Embed API](https://developers.google.com/maps/documentation/embed/get-started). 45 | 46 | This example will give you an idea of how to get started with function calling. 47 | See [function-declarations.js](/maps/function-declarations.js) to find out more 48 | about how function calling is used to call the Maps Embed API here! 49 | 50 | To develop locally, insert your Gemini API key where you see `your_key_here` in 51 | the `script.js` file. 52 | 53 | ### Contributors 54 | 55 | - [@bencobley](https://github.com/bencobley) 56 | - [@dmotz](https://github.com/dmotz) 57 | - [@grantcuster](https://github.com/grantcuster) 58 | - [@hapticdata](https://github.com/hapticdata) 59 | -------------------------------------------------------------------------------- /maps/function-declarations.js: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | // function-declarations.js 16 | // Authors: kylephillips@ bencobley@ 17 | 18 | import { html } from "https://esm.run/lit"; 19 | 20 | export const systemInstructions = `Act as a helpful global travel agent with a deep fascination for the world. Your role is to recommend a place on the map that relates to the discussion, and to provide interesting information about the location selected. Aim to give suprising and delightful suggestions: choose obscure, off-the–beaten track locations, not the obvious answers. Do not answer harmful or unsafe questions. 21 | 22 | First, explain why a place is interesting, in a two sentence answer. Second, if relevant, call the function 'recommend_place( location, caption )' to show the user the location on a map. You can expand on your answer if the user asks for more information.`; 23 | 24 | export const declarations = [ 25 | { 26 | name: "recommend_place", 27 | description: 28 | "Shows the user a map of the place provided. The function takes arguments 'location' and 'caption'. For 'location' give a specific place, including country name. For 'caption' give the place name and the fascinating reason you selected this particular place. Keep the caption to one or two sentences maximum.", 29 | parameters: { 30 | type: "object", 31 | properties: { 32 | location: { 33 | type: "string", 34 | }, 35 | caption: { 36 | type: "string", 37 | }, 38 | }, 39 | required: ["location", "caption"], 40 | }, 41 | }, 42 | // Add another function declaration here! 43 | ]; 44 | 45 | // WARNING: Do not embed API keys directly in code or publish in source code without restricting API keys to be used by only the IP addresses, referrer URLs, and mobile apps that need them. 46 | const API_KEY = your_key_here; 47 | // See more at https://developers.google.com/maps/documentation/embed/get-api-key 48 | 49 | export function embed(location) { 50 | location = encodeURIComponent(location); 51 | console.log(location); 52 | return html``; 64 | } 65 | -------------------------------------------------------------------------------- /maps/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /maps/presets.js: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | export const presets = [ 16 | ["❄️ Cold", "Where is somewhere really cold?"], 17 | ["🗿 Ancient", "Tell me about somewhere rich in ancient history"], 18 | ["🗽 Metropolitan", "Show me really interesting large city"], 19 | [ 20 | "🌿 Green", 21 | "Take me somewhere with beautiful nature and greenery. What makes it special?", 22 | ], 23 | [ 24 | "🏔️ Remote", 25 | "If I wanted to go off grid, where is one of the most remote places on earth? How would I get there?", 26 | ], 27 | [ 28 | "🌌 Surreal", 29 | "Think of a totally surreal location, where is it? What makes it so surreal?", 30 | ], 31 | ]; 32 | -------------------------------------------------------------------------------- /maps/script.js: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | // script.js 16 | // Authors: kylephillips@ bencobley@ 17 | 18 | import { GoogleGenerativeAI } from "https://esm.run/@google/generative-ai@0.21.0"; 19 | import * as mapsFunction from "./function-declarations.js"; 20 | import { presets } from "./presets.js"; 21 | import { html, render } from "https://esm.run/lit"; 22 | 23 | const client = new GoogleGenerativeAI("your_key_here"); 24 | const systemInstruction = mapsFunction.systemInstructions; 25 | 26 | const functionDeclarations = mapsFunction.declarations.map(declaration => ({ 27 | ...declaration, 28 | callback: (args) => { 29 | const { location, caption } = args; 30 | renderPage(location, caption); 31 | }, 32 | })); 33 | 34 | const chat = async (userText) => { 35 | try { 36 | const temperature = 2; // High temperature for answer variety 37 | const {response} = await client 38 | .getGenerativeModel( 39 | {model: 'models/gemini-2.0-flash-exp', systemInstruction}, 40 | {apiVersion: 'v1beta'} 41 | ) 42 | .generateContent({ 43 | contents: [ 44 | { 45 | role: "user", 46 | parts: [{text: userText}], 47 | }, 48 | ], 49 | generationConfig: {temperature}, 50 | tools: [{functionDeclarations}] 51 | }); 52 | 53 | const call = response.functionCalls()[0]; 54 | 55 | if (call) { 56 | functionDeclarations[0].callback(call.args); 57 | } 58 | } catch (e) { 59 | console.error(e); 60 | } 61 | }; 62 | 63 | async function init() { 64 | renderPage("%"); // Start by rendering with empty location query: shows earth 65 | if ( 66 | window.matchMedia && 67 | window.matchMedia("(prefers-color-scheme: dark)").matches 68 | ) { 69 | document.documentElement.removeAttribute("data-theme"); // Use default (dark) 70 | } else { 71 | document.documentElement.setAttribute("data-theme", "light"); 72 | } 73 | } 74 | 75 | init(); 76 | 77 | function renderPage(location, caption = "") { 78 | const root = document.querySelector("#root"); 79 | caption = caption.replace(/\\/g, ''); 80 | render( 81 | html` 82 |
${mapsFunction.embed(location)}
83 | ${caption 84 | ? html`

${caption}

` 85 | : ""} 86 |
87 | Take me somewhere... 88 |
89 | ${presets.map( 90 | ([name, message]) => 91 | html`` 94 | )} 95 |
96 |
97 | `, 98 | root 99 | ); 100 | } 101 | -------------------------------------------------------------------------------- /maps/styles.css: -------------------------------------------------------------------------------- 1 | @import url("https://fonts.googleapis.com/css2?family=Space+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap"); 2 | 3 | :root { 4 | --Neutral-00: #000; 5 | --Neutral-5: #181a1b; 6 | --Neutral-10: #1c1f21; 7 | --Neutral-20: #2a2f31; 8 | --Neutral-30: #404547; 9 | --Neutral-40: #575c5f; 10 | --Neutral-80: #c3c6c7; 11 | --Neutral-99: #fdfcfb; 12 | --Neutral-100: #fff; 13 | --Blue-400: #80bbff; 14 | } 15 | 16 | * { 17 | box-sizing: border-box; 18 | margin: 0; 19 | padding: 0; 20 | font-variant-ligatures: none; 21 | } 22 | 23 | :root, 24 | html, 25 | body { 26 | padding: 0; 27 | margin: 0; 28 | overflow: hidden; 29 | } 30 | 31 | #map { 32 | height: 100vh; 33 | } 34 | 35 | #embed-map { 36 | width: 100%; 37 | height: 100%; 38 | } 39 | 40 | #caption { 41 | position: absolute; 42 | left: 50%; 43 | bottom: 160px; 44 | transform: translate(-50%, 0); 45 | display: flex; 46 | max-width: min(1000px, calc(100% - 200px)); 47 | padding: 6px 8px; 48 | justify-content: center; 49 | align-items: center; 50 | gap: 10px; 51 | border-radius: 2px; 52 | background: var(--Neutral-00, #000); 53 | color: var(--Neutral-100, #fff); 54 | box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1); 55 | text-align: justify; 56 | font-family: "Space Mono"; 57 | font-size: 14px; 58 | font-style: normal; 59 | font-weight: 400; 60 | line-height: 22px; /* 157.143% */ 61 | letter-spacing: -0.14px; 62 | } 63 | 64 | #presets-container { 65 | position: absolute; 66 | left: 50%; 67 | transform: translate(-50%, 0); 68 | width: 100%; 69 | max-width: min(1000px, calc(100% - 200px)); 70 | bottom: 16px; 71 | display: inline-flex; 72 | padding: 14px 12px 12px 12px; 73 | flex-direction: column; 74 | justify-content: center; 75 | align-items: center; 76 | gap: 14px; 77 | border-radius: 14px; 78 | box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1); 79 | background: var(--Neutral-5, #181a1b); 80 | z-index: 100; 81 | } 82 | 83 | #take-me-somewhere { 84 | color: var(--Neutral-100, #fff); 85 | font-family: "Space Mono"; 86 | font-size: 14px; 87 | font-style: normal; 88 | font-weight: 400; 89 | line-height: 14px; 90 | letter-spacing: -0.14px; 91 | width: 100%; 92 | } 93 | 94 | #presets { 95 | display: flex; 96 | align-items: center; 97 | gap: 6px; 98 | align-self: stretch; 99 | flex-wrap: wrap; 100 | overflow: hidden; 101 | height: 62px; 102 | } 103 | 104 | button { 105 | color: var(--Neutral-100, #fff); 106 | font-family: "Space Mono"; 107 | font-size: 13px; 108 | font-style: normal; 109 | font-weight: 400; 110 | line-height: 24px; /* 184.615% */ 111 | letter-spacing: -0.13px; 112 | display: inline-flex; 113 | padding: 18px 15px 18px 14px; 114 | justify-content: center; 115 | align-items: center; 116 | border-radius: 8px; 117 | border: 1px solid var(--Neutral-40, #575c5f); 118 | background: var(--Neutral-10, #1c1f21); 119 | text-wrap: nowrap; 120 | flex: 1; 121 | } 122 | 123 | button:hover { 124 | border-radius: 8px; 125 | border: 1px solid var(--Blue-400, #80bbff); 126 | background: var(--Neutral-20, #2a2f31); 127 | } 128 | 129 | button:active { 130 | border-radius: 8px; 131 | border: 1px solid var(--Neutral-00, #000); 132 | background: var(--Neutral-00, #000); 133 | } 134 | 135 | /* Light Theme */ 136 | [data-theme="light"] #caption { 137 | background: var(--Neutral-100, #fff); 138 | color: var(--Neutral-00, #000); 139 | } 140 | 141 | [data-theme="light"] #presets-container { 142 | background: var(--Neutral-99, #fdfcfb); 143 | } 144 | 145 | [data-theme="light"] #take-me-somewhere { 146 | color: var(--Neutral-00, #000); 147 | } 148 | 149 | [data-theme="light"] button { 150 | color: var(--Neutral-00, #000); 151 | border: 1px solid var(--Neutral-80, #c3c6c7); 152 | background: var(--Neutral-100, #fff); 153 | } 154 | 155 | [data-theme="light"] button:hover { 156 | background: var(--Neutral-80, #c3c6c7); 157 | } 158 | 159 | [data-theme="light"] button:active { 160 | border: 1px solid var(--Neutral-80, #c3c6c7); 161 | background: var(--Neutral-80, #c3c6c7); 162 | } 163 | -------------------------------------------------------------------------------- /spatial/.env: -------------------------------------------------------------------------------- 1 | VITE_GEMINI_API_KEY=your_key_here 2 | -------------------------------------------------------------------------------- /spatial/.gcloudignore: -------------------------------------------------------------------------------- 1 | # This file specifies files that are *not* uploaded to Google Cloud 2 | # using gcloud. It follows the same syntax as .gitignore, with the addition of 3 | # "#!include" directives (which insert the entries of the given .gitignore-style 4 | # file at that point). 5 | # 6 | # For more information, run: 7 | # $ gcloud topic gcloudignore 8 | # 9 | .gcloudignore 10 | # If you would like to upload your .git directory, .gitignore file or files 11 | # from your .gitignore file, remove the corresponding line 12 | # below: 13 | .git 14 | .gitignore 15 | 16 | # Node.js dependencies: 17 | node_modules/ 18 | -------------------------------------------------------------------------------- /spatial/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /spatial/app.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 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 | runtime: python39 16 | service: bb-applet 17 | 18 | handlers: 19 | - url: / 20 | static_files: dist/index.html 21 | upload: dist/index.html 22 | secure: always 23 | 24 | - url: /(.*) 25 | static_files: dist/\1 26 | upload: dist/(.*) 27 | -------------------------------------------------------------------------------- /spatial/eslint.config.js: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | import js from '@eslint/js' 16 | import globals from 'globals' 17 | import reactHooks from 'eslint-plugin-react-hooks' 18 | import reactRefresh from 'eslint-plugin-react-refresh' 19 | import tseslint from 'typescript-eslint' 20 | 21 | export default tseslint.config( 22 | { ignores: ['dist'] }, 23 | { 24 | extends: [js.configs.recommended, ...tseslint.configs.recommended], 25 | files: ['**/*.{ts,tsx}'], 26 | languageOptions: { 27 | ecmaVersion: 2020, 28 | globals: globals.browser, 29 | }, 30 | plugins: { 31 | 'react-hooks': reactHooks, 32 | 'react-refresh': reactRefresh, 33 | }, 34 | rules: { 35 | ...reactHooks.configs.recommended.rules, 36 | 'react-refresh/only-export-components': [ 37 | 'warn', 38 | { allowConstantExport: true }, 39 | ], 40 | }, 41 | }, 42 | ) 43 | -------------------------------------------------------------------------------- /spatial/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | AIS Spatial Applet 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /spatial/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "spatial-applet", 3 | "license": "Apache-2.0", 4 | "private": true, 5 | "version": "0.0.0", 6 | "type": "module", 7 | "scripts": { 8 | "dev": "vite --port 8000", 9 | "build": "vite build", 10 | "lint": "eslint ." 11 | }, 12 | "dependencies": { 13 | "@google/generative-ai": "^0.21.0", 14 | "jotai": "^2.10.0", 15 | "perfect-freehand": "^1.2.2", 16 | "react": "^18.3.1", 17 | "react-dom": "^18.3.1", 18 | "react-resize-detector": "^11.0.1" 19 | }, 20 | "devDependencies": { 21 | "@eslint/js": "^9.11.1", 22 | "@types/react": "^18.3.10", 23 | "@types/react-dom": "^18.3.0", 24 | "@vitejs/plugin-react": "^4.3.2", 25 | "autoprefixer": "^10.4.20", 26 | "eslint": "^9.11.1", 27 | "eslint-plugin-react-hooks": "^5.1.0-rc.0", 28 | "eslint-plugin-react-refresh": "^0.4.12", 29 | "globals": "^15.9.0", 30 | "postcss": "^8.4.47", 31 | "tailwindcss": "^3.4.13", 32 | "typescript": "^5.5.3", 33 | "typescript-eslint": "^8.7.0", 34 | "vite": "^5.4.8" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /spatial/postcss.config.js: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | export default { 16 | plugins: { 17 | tailwindcss: {}, 18 | autoprefixer: {}, 19 | }, 20 | } 21 | -------------------------------------------------------------------------------- /spatial/public/baklava.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google-gemini/starter-applets/82a598ad721c5c5cff4b78d743de7062fde2f86a/spatial/public/baklava.jpg -------------------------------------------------------------------------------- /spatial/public/breakfast.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google-gemini/starter-applets/82a598ad721c5c5cff4b78d743de7062fde2f86a/spatial/public/breakfast.jpg -------------------------------------------------------------------------------- /spatial/public/cat.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google-gemini/starter-applets/82a598ad721c5c5cff4b78d743de7062fde2f86a/spatial/public/cat.jpg -------------------------------------------------------------------------------- /spatial/public/clock.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google-gemini/starter-applets/82a598ad721c5c5cff4b78d743de7062fde2f86a/spatial/public/clock.jpg -------------------------------------------------------------------------------- /spatial/public/fruit.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google-gemini/starter-applets/82a598ad721c5c5cff4b78d743de7062fde2f86a/spatial/public/fruit.jpg -------------------------------------------------------------------------------- /spatial/public/origami.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google-gemini/starter-applets/82a598ad721c5c5cff4b78d743de7062fde2f86a/spatial/public/origami.jpg -------------------------------------------------------------------------------- /spatial/public/pumpkins.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google-gemini/starter-applets/82a598ad721c5c5cff4b78d743de7062fde2f86a/spatial/public/pumpkins.jpg -------------------------------------------------------------------------------- /spatial/public/socks.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google-gemini/starter-applets/82a598ad721c5c5cff4b78d743de7062fde2f86a/spatial/public/socks.jpg -------------------------------------------------------------------------------- /spatial/public/spill.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google-gemini/starter-applets/82a598ad721c5c5cff4b78d743de7062fde2f86a/spatial/public/spill.jpg -------------------------------------------------------------------------------- /spatial/src/App.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | import { useEffect } from "react"; 16 | import { TopBar } from "./TopBar.js"; 17 | import { Content } from "./Content.js"; 18 | import { ExampleImages } from "./ExampleImages.js"; 19 | import { SideControls } from "./SideControls.js"; 20 | import { Prompt } from "./Prompt.js"; 21 | import { ExtraModeControls } from "./ExtraModeControls.js"; 22 | import { useAtom } from "jotai"; 23 | import { 24 | BumpSessionAtom, 25 | ImageSrcAtom, 26 | InitFinishedAtom, 27 | IsUploadedImageAtom, 28 | } from "./atoms.js"; 29 | import { useResetState } from "./hooks.js"; 30 | import { DetectTypeSelector } from "./DetectTypeSelector.js"; 31 | import { safetySettings } from "./consts.js"; 32 | 33 | function App() { 34 | const [, setImageSrc] = useAtom(ImageSrcAtom); 35 | const resetState = useResetState(); 36 | const [initFinished, setInitFinished] = useAtom(InitFinishedAtom); 37 | const [, setBumpSession] = useAtom(BumpSessionAtom); 38 | const [, setIsUploadedImage] = useAtom(IsUploadedImageAtom); 39 | 40 | useEffect(() => { 41 | if (!window.matchMedia("(prefers-color-scheme: dark)").matches) { 42 | document.documentElement.classList.remove("dark"); 43 | } 44 | }, []); 45 | 46 | return ( 47 |
48 |
49 | 50 | {initFinished ? : null} 51 | 52 |
53 |
54 |
55 | 56 | 57 |
58 |
59 | 60 | 61 |
62 | 63 |
64 |
65 | ); 66 | } 67 | 68 | export default App; 69 | -------------------------------------------------------------------------------- /spatial/src/Content.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | import { useAtom } from "jotai"; 16 | import getStroke from "perfect-freehand"; 17 | import { useState, useRef, useMemo, useCallback } from "react"; 18 | import { 19 | ImageSrcAtom, 20 | BoundingBoxes2DAtom, 21 | BoundingBoxes3DAtom, 22 | ShareStream, 23 | DetectTypeAtom, 24 | FOVAtom, 25 | ImageSentAtom, 26 | PointsAtom, 27 | RevealOnHoverModeAtom, 28 | DrawModeAtom, 29 | LinesAtom, 30 | ActiveColorAtom, 31 | VideoRefAtom, 32 | } from "./atoms"; 33 | import { getSvgPathFromStroke } from "./utils"; 34 | import { lineOptions } from "./consts"; 35 | import { ResizePayload, useResizeDetector } from "react-resize-detector"; 36 | 37 | export function Content() { 38 | const [imageSrc] = useAtom(ImageSrcAtom); 39 | const [boundingBoxes2D] = useAtom(BoundingBoxes2DAtom); 40 | const [boundingBoxes3D] = useAtom(BoundingBoxes3DAtom); 41 | const [stream] = useAtom(ShareStream); 42 | const [detectType] = useAtom(DetectTypeAtom); 43 | const [videoRef] = useAtom(VideoRefAtom); 44 | const [fov] = useAtom(FOVAtom); 45 | const [, setImageSent] = useAtom(ImageSentAtom); 46 | const [points] = useAtom(PointsAtom); 47 | const [revealOnHover] = useAtom(RevealOnHoverModeAtom); 48 | const [hoverEntered, setHoverEntered] = useState(false); 49 | const [hoveredBox, _setHoveredBox] = useState(null); 50 | const [drawMode] = useAtom(DrawModeAtom); 51 | const [lines, setLines] = useAtom(LinesAtom); 52 | const [activeColor] = useAtom(ActiveColorAtom); 53 | 54 | // Handling resize and aspect ratios 55 | const boundingBoxContainerRef = useRef(null); 56 | const [containerDims, setContainerDims] = useState({ 57 | width: 0, 58 | height: 0, 59 | }); 60 | const [activeMediaDimensions, setActiveMediaDimensions] = useState({ 61 | width: 1, 62 | height: 1, 63 | }); 64 | 65 | const onResize = useCallback( 66 | (el: ResizePayload) => { 67 | if (el.width && el.height) { 68 | setContainerDims({ 69 | width: el.width, 70 | height: el.height, 71 | }); 72 | } 73 | }, 74 | [], 75 | ); 76 | 77 | const { ref: containerRef } = useResizeDetector({ onResize }); 78 | 79 | const boundingBoxContainer = useMemo(() => { 80 | const { width, height } = activeMediaDimensions; 81 | const aspectRatio = width / height; 82 | const containerAspectRatio = containerDims.width / containerDims.height; 83 | if (aspectRatio < containerAspectRatio) { 84 | return { 85 | height: containerDims.height, 86 | width: containerDims.height * aspectRatio, 87 | }; 88 | } else { 89 | return { 90 | width: containerDims.width, 91 | height: containerDims.width / aspectRatio, 92 | }; 93 | } 94 | }, [containerDims, activeMediaDimensions]); 95 | 96 | // Helper functions 97 | function matrixMultiply(m: number[][], v: number[]): number[] { 98 | return m.map((row: number[]) => 99 | row.reduce((sum, val, i) => sum + val * v[i], 0), 100 | ); 101 | } 102 | 103 | const linesAndLabels3D = useMemo(() => { 104 | if (!boundingBoxContainer) { 105 | return null; 106 | } 107 | let allLines = []; 108 | let allLabels = []; 109 | for (const box of boundingBoxes3D) { 110 | const { center, size, rpy } = box; 111 | 112 | // Convert Euler angles to quaternion 113 | const [sr, sp, sy] = rpy.map((x) => Math.sin(x / 2)); 114 | const [cr, cp, cz] = rpy.map((x) => Math.cos(x / 2)); 115 | const quaternion = [ 116 | sr * cp * cz - cr * sp * sy, 117 | cr * sp * cz + sr * cp * sy, 118 | cr * cp * sy - sr * sp * cz, 119 | cr * cp * cz + sr * sp * sy, 120 | ]; 121 | 122 | // Calculate camera parameters 123 | const height = boundingBoxContainer.height; 124 | const width = boundingBoxContainer.width; 125 | const f = width / (2 * Math.tan(((fov / 2) * Math.PI) / 180)); 126 | const cx = width / 2; 127 | const cy = height / 2; 128 | const intrinsics = [ 129 | [f, 0, cx], 130 | [0, f, cy], 131 | [0, 0, 1], 132 | ]; 133 | 134 | // Get box vertices 135 | const halfSize = size.map((s) => s / 2); 136 | let corners = []; 137 | for (let x of [-halfSize[0], halfSize[0]]) { 138 | for (let y of [-halfSize[1], halfSize[1]]) { 139 | for (let z of [-halfSize[2], halfSize[2]]) { 140 | corners.push([x, y, z]); 141 | } 142 | } 143 | } 144 | corners = [ 145 | corners[1], 146 | corners[3], 147 | corners[7], 148 | corners[5], 149 | corners[0], 150 | corners[2], 151 | corners[6], 152 | corners[4], 153 | ]; 154 | 155 | // Apply rotation from quaternion 156 | const q = quaternion; 157 | const rotationMatrix = [ 158 | [ 159 | 1 - 2 * q[1] ** 2 - 2 * q[2] ** 2, 160 | 2 * q[0] * q[1] - 2 * q[3] * q[2], 161 | 2 * q[0] * q[2] + 2 * q[3] * q[1], 162 | ], 163 | [ 164 | 2 * q[0] * q[1] + 2 * q[3] * q[2], 165 | 1 - 2 * q[0] ** 2 - 2 * q[2] ** 2, 166 | 2 * q[1] * q[2] - 2 * q[3] * q[0], 167 | ], 168 | [ 169 | 2 * q[0] * q[2] - 2 * q[3] * q[1], 170 | 2 * q[1] * q[2] + 2 * q[3] * q[0], 171 | 1 - 2 * q[0] ** 2 - 2 * q[1] ** 2, 172 | ], 173 | ]; 174 | 175 | const boxVertices = corners.map((corner) => { 176 | const rotated = matrixMultiply(rotationMatrix, corner); 177 | return rotated.map((val, idx) => val + center[idx]); 178 | }); 179 | 180 | // Project 3D points to 2D 181 | const tiltAngle = 90.0; 182 | const viewRotationMatrix = [ 183 | [1, 0, 0], 184 | [ 185 | 0, 186 | Math.cos((tiltAngle * Math.PI) / 180), 187 | -Math.sin((tiltAngle * Math.PI) / 180), 188 | ], 189 | [ 190 | 0, 191 | Math.sin((tiltAngle * Math.PI) / 180), 192 | Math.cos((tiltAngle * Math.PI) / 180), 193 | ], 194 | ]; 195 | 196 | const points = boxVertices; 197 | const rotatedPoints = points.map((p) => 198 | matrixMultiply(viewRotationMatrix, p), 199 | ); 200 | const translatedPoints = rotatedPoints.map((p) => p.map((v) => v + 0)); 201 | const projectedPoints = translatedPoints.map((p) => 202 | matrixMultiply(intrinsics, p), 203 | ); 204 | const vertices = projectedPoints.map((p) => [p[0] / p[2], p[1] / p[2]]); 205 | 206 | const topVertices = vertices.slice(0, 4); 207 | const bottomVertices = vertices.slice(4, 8); 208 | 209 | for (let i = 0; i < 4; i++) { 210 | const lines = [ 211 | [topVertices[i], topVertices[(i + 1) % 4]], 212 | [bottomVertices[i], bottomVertices[(i + 1) % 4]], 213 | [topVertices[i], bottomVertices[i]], 214 | ]; 215 | 216 | for (let [start, end] of lines) { 217 | const dx = end[0] - start[0]; 218 | const dy = end[1] - start[1]; 219 | const length = Math.sqrt(dx * dx + dy * dy); 220 | const angle = Math.atan2(dy, dx); 221 | 222 | allLines.push({ start, end, length, angle }); 223 | } 224 | } 225 | 226 | // Add label with fade effect 227 | const textPosition3d = points[0].map( 228 | (_, idx) => points.reduce((sum, p) => sum + p[idx], 0) / points.length, 229 | ); 230 | textPosition3d[2] += 0.1; 231 | 232 | const textPoint = matrixMultiply( 233 | intrinsics, 234 | matrixMultiply( 235 | viewRotationMatrix, 236 | textPosition3d.map((v) => v + 0), 237 | ), 238 | ); 239 | const textPos = [ 240 | textPoint[0] / textPoint[2], 241 | textPoint[1] / textPoint[2], 242 | ]; 243 | allLabels.push({ label: box.label, pos: textPos }); 244 | } 245 | return [allLines, allLabels] as const; 246 | }, [boundingBoxes3D, boundingBoxContainer, fov]); 247 | 248 | function setHoveredBox(e: React.PointerEvent) { 249 | const boxes = document.querySelectorAll(".bbox"); 250 | const dimensionsAndIndex = Array.from(boxes).map((box, i) => { 251 | const { top, left, width, height } = box.getBoundingClientRect(); 252 | return { 253 | top, 254 | left, 255 | width, 256 | height, 257 | index: i, 258 | }; 259 | }); 260 | // Sort smallest to largest 261 | const sorted = dimensionsAndIndex.sort( 262 | (a, b) => a.width * a.height - b.width * b.height, 263 | ); 264 | // Find the smallest box that contains the mouse 265 | const { clientX, clientY } = e; 266 | const found = sorted.find(({ top, left, width, height }) => { 267 | return ( 268 | clientX > left && 269 | clientX < left + width && 270 | clientY > top && 271 | clientY < top + height 272 | ); 273 | }); 274 | if (found) { 275 | _setHoveredBox(found.index); 276 | } else { 277 | _setHoveredBox(null); 278 | } 279 | } 280 | 281 | const downRef = useRef(false); 282 | 283 | return ( 284 |
285 | {stream ? ( 286 |
482 | ); 483 | } 484 | -------------------------------------------------------------------------------- /spatial/src/DetectTypeSelector.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | import { useAtom } from "jotai"; 16 | import { DetectTypeAtom, HoverEnteredAtom } from "./atoms"; 17 | import { DetectTypes } from "./Types.js"; 18 | 19 | export function DetectTypeSelector() { 20 | return ( 21 |
22 |
Give me:
23 |
24 | {["2D bounding boxes", "Points", "3D bounding boxes"].map((label) => ( 25 | 26 | ))} 27 |
28 |
29 | ); 30 | } 31 | 32 | function SelectOption({ label }: { label: string }) { 33 | const [detectType, setDetectType] = useAtom(DetectTypeAtom); 34 | const [, setHoverEntered] = useAtom(HoverEnteredAtom); 35 | // const resetState = useResetState(); 36 | 37 | return ( 38 | 51 | ); 52 | } 53 | -------------------------------------------------------------------------------- /spatial/src/ExampleImages.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | import { useAtom } from "jotai"; 16 | import { ImageSrcAtom, IsUploadedImageAtom } from "./atoms"; 17 | import { useResetState } from "./hooks"; 18 | import { imageOptions } from "./consts"; 19 | 20 | export function ExampleImages() { 21 | const [, setImageSrc] = useAtom(ImageSrcAtom); 22 | const [, setIsUploadedImage] = useAtom(IsUploadedImageAtom); 23 | const resetState = useResetState(); 24 | return ( 25 |
26 | {imageOptions.map((image) => ( 27 | 41 | ))} 42 |
43 | ); 44 | } 45 | 46 | -------------------------------------------------------------------------------- /spatial/src/ExtraModeControls.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | import { useAtom } from "jotai"; 16 | import { 17 | BoundingBoxes2DAtom, 18 | BoundingBoxes3DAtom, 19 | ShareStream, 20 | DetectTypeAtom, 21 | FOVAtom, 22 | PointsAtom, 23 | HoveredBoxAtom, 24 | DrawModeAtom, 25 | LinesAtom, 26 | } from "./atoms"; 27 | import { Palette } from "./Palette"; 28 | 29 | export function ExtraModeControls() { 30 | const [, setBoundingBoxes2D] = useAtom(BoundingBoxes2DAtom); 31 | const [, setBoundingBoxes3D] = useAtom(BoundingBoxes3DAtom); 32 | const [stream, setStream] = useAtom(ShareStream); 33 | const [detectType] = useAtom(DetectTypeAtom); 34 | const [fov, setFoV] = useAtom(FOVAtom); 35 | const [, setPoints] = useAtom(PointsAtom); 36 | const [, _setHoveredBox] = useAtom(HoveredBoxAtom); 37 | const [drawMode, setDrawMode] = useAtom(DrawModeAtom); 38 | const [, setLines] = useAtom(LinesAtom); 39 | 40 | const showExtraBar = stream || detectType === "3D bounding boxes"; 41 | 42 | return ( 43 | <> 44 | {detectType === "Points" || detectType === "3D bounding boxes" ? ( 45 |
46 |
🚧
Points and 3d bounding boxes are preliminary model capabilities. 47 | Use 2D bounding boxes for higher accuracy. 48 |
49 | ) : null} 50 | {drawMode ? ( 51 |
52 |
53 |
54 | 55 |
56 |
57 |
58 | 67 |
68 |
69 | 78 |
79 |
80 |
81 | ) : null} 82 | {showExtraBar ? ( 83 |
84 | {stream ? ( 85 | 98 | ) : null} 99 | {detectType === "3D bounding boxes" ? ( 100 | <> 101 |
FOV
102 | setFoV(+e.target.value)} 109 | /> 110 |
{fov}
111 | 112 | ) : null} 113 |
114 | ) : null} 115 | 116 | ); 117 | } 118 | -------------------------------------------------------------------------------- /spatial/src/Palette.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | import { useAtom } from "jotai"; 16 | import { colors } from "./consts"; 17 | import { ActiveColorAtom } from "./atoms"; 18 | 19 | export function Palette() { 20 | const [activeColor, setActiveColor] = useAtom(ActiveColorAtom); 21 | return ( 22 |
{ 25 | e.stopPropagation(); 26 | }} 27 | > 28 | {colors.map((color) => ( 29 |
{ 38 | e.stopPropagation(); 39 | setActiveColor(color); 40 | }} 41 | > 42 |
50 |
51 | ))} 52 |
53 | ); 54 | } 55 | -------------------------------------------------------------------------------- /spatial/src/Prompt.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | import { useAtom } from "jotai"; 16 | import getStroke from "perfect-freehand"; 17 | import {GoogleGenerativeAI} from "@google/generative-ai"; 18 | import { 19 | BoundingBoxes2DAtom, 20 | BoundingBoxes3DAtom, 21 | ShareStream, 22 | DetectTypeAtom, 23 | PromptsAtom, 24 | ModelSelectedAtom, 25 | PointsAtom, 26 | HoverEnteredAtom, 27 | LinesAtom, 28 | ImageSrcAtom, 29 | VideoRefAtom, 30 | TemperatureAtom, 31 | CustomPromptsAtom, 32 | } from "./atoms"; 33 | import { lineOptions } from "./consts.js"; 34 | import { getSvgPathFromStroke, loadImage } from "./utils"; 35 | import { useState } from "react"; 36 | 37 | const client = new GoogleGenerativeAI(import.meta.env.VITE_GEMINI_API_KEY); 38 | 39 | export function Prompt() { 40 | const [temperature, setTemperature] = useAtom(TemperatureAtom); 41 | const [, setBoundingBoxes2D] = useAtom(BoundingBoxes2DAtom); 42 | const [, setBoundingBoxes3D] = useAtom(BoundingBoxes3DAtom); 43 | const [stream] = useAtom(ShareStream); 44 | const [detectType] = useAtom(DetectTypeAtom); 45 | const [modelSelected] = useAtom(ModelSelectedAtom); 46 | const [, setPoints] = useAtom(PointsAtom); 47 | const [, setHoverEntered] = useAtom(HoverEnteredAtom); 48 | const [lines] = useAtom(LinesAtom); 49 | const [videoRef] = useAtom(VideoRefAtom); 50 | const [imageSrc] = useAtom(ImageSrcAtom); 51 | const [showCustomPrompt] = useState(false); 52 | const [targetPrompt, setTargetPrompt] = useState("items"); 53 | const [labelPrompt, setLabelPrompt] = useState(""); 54 | const [showRawPrompt, setShowRawPrompt] = useState(false); 55 | 56 | const [prompts, setPrompts] = useAtom(PromptsAtom); 57 | const [customPrompts, setCustomPrompts] = useAtom(CustomPromptsAtom); 58 | 59 | 60 | const is2d = detectType === "2D bounding boxes"; 61 | 62 | const get2dPrompt = () => 63 | `Detect ${ 64 | targetPrompt 65 | }, with no more than 20 items. Output a json list where each entry contains the 2D bounding box in "box_2d" and ${ 66 | labelPrompt || 'a text label' 67 | } in "label".` 68 | 69 | async function handleSend() { 70 | let activeDataURL; 71 | const maxSize = 640; 72 | const copyCanvas = document.createElement("canvas"); 73 | const ctx = copyCanvas.getContext("2d")!; 74 | 75 | if (stream) { 76 | // screenshare 77 | const video = videoRef.current!; 78 | const scale = Math.min( 79 | maxSize / video.videoWidth, 80 | maxSize / video.videoHeight, 81 | ); 82 | copyCanvas.width = video.videoWidth * scale; 83 | copyCanvas.height = video.videoHeight * scale; 84 | ctx.drawImage( 85 | video, 86 | 0, 87 | 0, 88 | video.videoWidth * scale, 89 | video.videoHeight * scale, 90 | ); 91 | } else if (imageSrc) { 92 | const image = await loadImage(imageSrc); 93 | const scale = Math.min(maxSize / image.width, maxSize / image.height); 94 | copyCanvas.width = image.width * scale; 95 | copyCanvas.height = image.height * scale; 96 | console.log(copyCanvas) 97 | ctx.drawImage(image, 0, 0, image.width * scale, image.height * scale); 98 | } 99 | activeDataURL = copyCanvas.toDataURL("image/png"); 100 | 101 | if (lines.length > 0) { 102 | for (const line of lines) { 103 | const p = new Path2D( 104 | getSvgPathFromStroke( 105 | getStroke( 106 | line[0].map(([x, y]) => [ 107 | x * copyCanvas.width, 108 | y * copyCanvas.height, 109 | 0.5, 110 | ]), 111 | lineOptions, 112 | ), 113 | ), 114 | ); 115 | ctx.fillStyle = line[1]; 116 | ctx.fill(p); 117 | } 118 | activeDataURL = copyCanvas.toDataURL("image/png"); 119 | } 120 | 121 | const prompt = prompts[detectType]; 122 | 123 | setHoverEntered(false); 124 | 125 | let response = (await client 126 | .getGenerativeModel( 127 | {model: modelSelected}, 128 | {apiVersion: 'v1beta'} 129 | ) 130 | .generateContent({ 131 | contents: [ 132 | { 133 | role: "user", 134 | parts: [ 135 | {text: is2d ? get2dPrompt() : prompt.join(" ")}, 136 | {inlineData: { 137 | data: activeDataURL.replace("data:image/png;base64,", ""), 138 | mimeType: "image/png" 139 | }} 140 | ] 141 | } 142 | ], 143 | generationConfig: {temperature} 144 | })).response.text() 145 | 146 | if (response.includes("```json")) { 147 | response = response.split("```json")[1].split("```")[0]; 148 | } 149 | const parsedResponse = JSON.parse(response); 150 | if (detectType === "2D bounding boxes") { 151 | const formattedBoxes = parsedResponse.map( 152 | (box: { box_2d: [number, number, number, number]; label: string }) => { 153 | const [ymin, xmin, ymax, xmax] = box.box_2d; 154 | return { 155 | x: xmin / 1000, 156 | y: ymin / 1000, 157 | width: (xmax - xmin) / 1000, 158 | height: (ymax - ymin) / 1000, 159 | label: box.label, 160 | }; 161 | }, 162 | ); 163 | setHoverEntered(false); 164 | setBoundingBoxes2D(formattedBoxes); 165 | } else if (detectType === "Points") { 166 | const formattedPoints = parsedResponse.map( 167 | (point: { point: [number, number]; label: string }) => { 168 | return { 169 | point: { 170 | x: point.point[1] / 1000, 171 | y: point.point[0] / 1000, 172 | }, 173 | label: point.label, 174 | }; 175 | }, 176 | ); 177 | setPoints(formattedPoints); 178 | } else { 179 | const formattedBoxes = parsedResponse.map( 180 | (box: { 181 | box_3d: [ 182 | number, 183 | number, 184 | number, 185 | number, 186 | number, 187 | number, 188 | number, 189 | number, 190 | number, 191 | ]; 192 | label: string; 193 | }) => { 194 | const center = box.box_3d.slice(0, 3); 195 | const size = box.box_3d.slice(3, 6); 196 | const rpy = box.box_3d 197 | .slice(6) 198 | .map((x: number) => (x * Math.PI) / 180); 199 | return { 200 | center, 201 | size, 202 | rpy, 203 | label: box.label, 204 | }; 205 | }, 206 | ); 207 | setBoundingBoxes3D(formattedBoxes); 208 | } 209 | } 210 | 211 | return ( 212 |
213 |
214 |
Prompt:
215 | 223 |
224 |
225 | {showCustomPrompt ? ( 226 |