├── .editorconfig ├── .firebaserc ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json └── tasks.json ├── LICENSE ├── README.md ├── angular.json ├── atlas-app-services ├── functions │ ├── Atlas_Triggers_analyzeReviewSentiment_1686394580.js │ ├── Atlas_Triggers_summarizeReviewsSentiment_1686475894.js │ └── config.json └── triggers │ ├── analyzeReviewSentiment.json │ └── summarizeReviewsSentiment.json ├── firebase.json ├── google-cloud-functions ├── analyze-media │ ├── index.js │ └── package.json ├── analyze-sentiment │ ├── index.js │ └── package.json ├── create-signed-url │ ├── index.js │ └── package.json └── summarize-review-sentiment │ ├── main.py │ └── requirements.txt ├── package-lock.json ├── package.json ├── src ├── app │ ├── address.ts │ ├── app-routing.module.ts │ ├── app.component.html │ ├── app.component.scss │ ├── app.component.ts │ ├── app.module.ts │ ├── change-events.ts │ ├── drag-and-drop.directive.ts │ ├── file-handle.service.spec.ts │ ├── file-handle.service.ts │ ├── grade.ts │ ├── helpers │ │ └── objectId.ts │ ├── image-detailed-dialog │ │ ├── media-dialog.component.html │ │ ├── media-dialog.component.scss │ │ └── media-dialog.component.ts │ ├── image-uplouder.service.ts │ ├── media-preview │ │ ├── media-preview.component.html │ │ ├── media-preview.component.scss │ │ └── media-preview.component.ts │ ├── media-upload-dialog │ │ ├── media-upload-dialog.component.html │ │ ├── media-upload-dialog.component.scss │ │ └── media-upload-dialog.component.ts │ ├── navbar │ │ ├── navbar.component.html │ │ ├── navbar.component.scss │ │ ├── navbar.component.spec.ts │ │ └── navbar.component.ts │ ├── realm-app.service.ts │ ├── restaurant-details-guided │ │ ├── restaurant-details-guided.component.html │ │ ├── restaurant-details-guided.component.scss │ │ └── restaurant-details-guided.component.ts │ ├── restaurant-details │ │ ├── restaurant-details.component.html │ │ ├── restaurant-details.component.scss │ │ └── restaurant-details.component.ts │ ├── restaurant.service.ts │ ├── restaurant.ts │ ├── restaurants-list-guided │ │ ├── restaurants-list-guided.component.html │ │ ├── restaurants-list-guided.component.scss │ │ └── restaurants-list-guided.component.ts │ ├── restaurants-list │ │ ├── restaurants-list.component.html │ │ ├── restaurants-list.component.scss │ │ └── restaurants-list.component.ts │ ├── review-form │ │ ├── review-form.component.html │ │ ├── review-form.component.scss │ │ └── review-form.component.ts │ ├── review.service.ts │ ├── review.ts │ ├── rxjs-operators.ts │ └── uploaded-media.ts ├── assets │ └── .gitkeep ├── config.ts ├── favicon.ico ├── index.html ├── main.ts └── styles.scss ├── tsconfig.app.json ├── tsconfig.json └── tsconfig.spec.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /.firebaserc: -------------------------------------------------------------------------------- 1 | { 2 | "targets": { 3 | "atlas-ai-demos": { 4 | "hosting": { 5 | "ai-restaurants": [ 6 | "atlas-ai-demos" 7 | ] 8 | } 9 | } 10 | }, 11 | "projects": { 12 | "default": "atlas-ai-demos" 13 | } 14 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # Compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | /bazel-out 8 | 9 | # Node 10 | /node_modules 11 | npm-debug.log 12 | yarn-error.log 13 | 14 | # IDEs and editors 15 | .idea/ 16 | .project 17 | .classpath 18 | .c9/ 19 | *.launch 20 | .settings/ 21 | *.sublime-workspace 22 | 23 | # Visual Studio Code 24 | .vscode/* 25 | !.vscode/settings.json 26 | !.vscode/tasks.json 27 | !.vscode/launch.json 28 | !.vscode/extensions.json 29 | .history/* 30 | 31 | # Miscellaneous 32 | /.angular/cache 33 | .sass-cache/ 34 | /connect.lock 35 | /coverage 36 | /libpeerconnection.log 37 | testem.log 38 | /typings 39 | 40 | # System files 41 | .DS_Store 42 | Thumbs.db 43 | 44 | # Firebase 45 | .firebase 46 | *-debug.log 47 | .runtimeconfig.json 48 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 3 | "recommendations": ["angular.ng-template"] 4 | } 5 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 3 | "version": "0.2.0", 4 | "configurations": [ 5 | { 6 | "name": "ng serve", 7 | "type": "chrome", 8 | "request": "launch", 9 | "preLaunchTask": "npm: start", 10 | "url": "http://localhost:4200/" 11 | }, 12 | { 13 | "name": "ng test", 14 | "type": "chrome", 15 | "request": "launch", 16 | "preLaunchTask": "npm: test", 17 | "url": "http://localhost:9876/debug.html" 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 3 | "version": "2.0.0", 4 | "tasks": [ 5 | { 6 | "type": "npm", 7 | "script": "start", 8 | "isBackground": true, 9 | "problemMatcher": { 10 | "owner": "typescript", 11 | "pattern": "$tsc", 12 | "background": { 13 | "activeOnStart": true, 14 | "beginsPattern": { 15 | "regexp": "(.*?)" 16 | }, 17 | "endsPattern": { 18 | "regexp": "bundle generation complete" 19 | } 20 | } 21 | } 22 | }, 23 | { 24 | "type": "npm", 25 | "script": "test", 26 | "isBackground": true, 27 | "problemMatcher": { 28 | "owner": "typescript", 29 | "pattern": "$tsc", 30 | "background": { 31 | "activeOnStart": true, 32 | "beginsPattern": { 33 | "regexp": "(.*?)" 34 | }, 35 | "endsPattern": { 36 | "regexp": "bundle generation complete" 37 | } 38 | } 39 | } 40 | } 41 | ] 42 | } 43 | -------------------------------------------------------------------------------- /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 | Copyright 2023 MongoDB Inc. 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Generative AI Sentiment Analysis and Summarization 2 | 3 | This is a demo of a sentiment analysis, tagging, and summarization Gemini — Google's next-generation AI model. 4 | 5 | ## Quickstart 6 | 7 | ### Google Cloud setup 8 | Create two public 2nd generation Cloud Functions with the following implementations. 9 | 10 | 1. [Analyze sentiment Google Cloud Function](./google-cloud-functions/analyze-sentiment/) 11 | 1. [Summarize reviews Google Cloud Function](./google-cloud-functions/summarize-review-sentiment/) 12 | 13 | Take a note of the deployed functions' URLs. You will need them later. 14 | 15 | ### MongoDB Atlas setup 16 | 17 | 1. Create a [free MongoDB Atlas account](https://mongodb.com/try?utm_campaign=devrel&utm_source=google.cloud&utm_medium=github&utm_content=sentiment.chef&utm_term=stanimira.vlaeva). 18 | 1. Database cluster 19 | - Deploy a new MongoDB database cluster in your Atlas account. You can use the free M0 tier for this demo. 20 | - Load the sample dataset. 21 | 1. Data API 22 | - Enable the Data API for your newly deployed cluster. 23 | - Set the `readAll` data access rule for the `sample_restaurants.restaurants` collection. 24 | 1. Atlas Functions 25 | - Create two new Atlas Functions with the following implementations. Replace the URL placeholders with the URls of the deployed Google Cloud Functions. 26 | - [Analyze sentiment Atlas Function](./atlas-app-services/functions/Atlas_Triggers_analyzeReviewSentiment_1686394580.js) 27 | - [Summarize reviews Atlas Function](./atlas-app-services/functions/Atlas_Triggers_summarizeReviewsSentiment_1686475894.js) 28 | 1. Atlas Triggers 29 | - Create two new Atlas Triggers with the following configuration. 30 | - [Analyze sentiment Atlas Trigger](./atlas-app-services/triggers/analyzeReviewSentiment.json) 31 | - [Summarize reviews Atlas Trigger](./atlas-app-services/triggers/summarizeReviewsSentiment.json) 32 | 33 | ## Contributors ✨ 34 | 35 | 36 | 37 | 38 | 39 | 45 | 46 |
40 | 41 |
42 | Stanimira Vlaeva 43 |

44 |
47 | 48 | 49 | 50 | 51 | ## Disclaimer 52 | 53 | Use at your own risk; not a supported MongoDB product 54 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "ai-restaurants": { 7 | "projectType": "application", 8 | "schematics": { 9 | "@schematics/angular:component": { 10 | "style": "scss" 11 | } 12 | }, 13 | "root": "", 14 | "sourceRoot": "src", 15 | "prefix": "app", 16 | "architect": { 17 | "build": { 18 | "builder": "@angular-devkit/build-angular:browser", 19 | "options": { 20 | "outputPath": "dist/ai-restaurants", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": [ 24 | "zone.js" 25 | ], 26 | "tsConfig": "tsconfig.app.json", 27 | "inlineStyleLanguage": "scss", 28 | "assets": [ 29 | "src/favicon.ico", 30 | "src/assets" 31 | ], 32 | "styles": [ 33 | "@angular/material/prebuilt-themes/indigo-pink.css", 34 | "src/styles.scss" 35 | ], 36 | "scripts": [] 37 | }, 38 | "configurations": { 39 | "production": { 40 | "budgets": [ 41 | { 42 | "type": "initial", 43 | "maximumWarning": "500kb", 44 | "maximumError": "5mb" 45 | }, 46 | { 47 | "type": "anyComponentStyle", 48 | "maximumWarning": "2kb", 49 | "maximumError": "4kb" 50 | } 51 | ], 52 | "outputHashing": "all" 53 | }, 54 | "development": { 55 | "buildOptimizer": false, 56 | "optimization": false, 57 | "vendorChunk": true, 58 | "extractLicenses": false, 59 | "sourceMap": true, 60 | "namedChunks": true 61 | } 62 | }, 63 | "defaultConfiguration": "production" 64 | }, 65 | "serve": { 66 | "builder": "@angular-devkit/build-angular:dev-server", 67 | "configurations": { 68 | "production": { 69 | "browserTarget": "ai-restaurants:build:production" 70 | }, 71 | "development": { 72 | "browserTarget": "ai-restaurants:build:development" 73 | } 74 | }, 75 | "defaultConfiguration": "development" 76 | }, 77 | "extract-i18n": { 78 | "builder": "@angular-devkit/build-angular:extract-i18n", 79 | "options": { 80 | "browserTarget": "ai-restaurants:build" 81 | } 82 | }, 83 | "test": { 84 | "builder": "@angular-devkit/build-angular:karma", 85 | "options": { 86 | "polyfills": [ 87 | "zone.js", 88 | "zone.js/testing" 89 | ], 90 | "tsConfig": "tsconfig.spec.json", 91 | "inlineStyleLanguage": "scss", 92 | "assets": [ 93 | "src/favicon.ico", 94 | "src/assets" 95 | ], 96 | "styles": [ 97 | "@angular/material/prebuilt-themes/purple-green.css", 98 | "src/styles.scss" 99 | ], 100 | "scripts": [] 101 | } 102 | }, 103 | "deploy": { 104 | "builder": "@angular/fire:deploy", 105 | "options": { 106 | "version": 2, 107 | "browserTarget": "ai-restaurants:build:production" 108 | } 109 | } 110 | } 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /atlas-app-services/functions/Atlas_Triggers_analyzeReviewSentiment_1686394580.js: -------------------------------------------------------------------------------- 1 | const serviceName = "M0"; 2 | const databaseName = "sample_restaurants"; 3 | const collectionName = "processed_reviews"; 4 | // Add the Google Cloud Function URL below 5 | const analyzeSentimentFunctionURL = ""; 6 | 7 | exports = async function(changeEvent) { 8 | const fullDocument = changeEvent?.fullDocument; 9 | const text = fullDocument?.text; 10 | 11 | if (!text) { 12 | throw new Error("Review text is required"); 13 | } 14 | 15 | const response = await context.http.post({ 16 | url: analyzeSentimentFunctionURL, 17 | body: { text }, 18 | encodeBodyAsJSON: true 19 | }); 20 | 21 | let analysis; 22 | let parsedResponse; 23 | try { 24 | // The response body is a BSON.Binary object. 25 | analysis = EJSON.parse(response?.body?.text())?.sentiment; 26 | parsedResponse = JSON.parse(analysis); 27 | } catch (error) { 28 | throw new Error("Parsing sentiment analysis failed. " + analysis); 29 | } 30 | 31 | if (!parsedResponse) { 32 | throw new Error("Sentiment analysis failed."); 33 | } 34 | 35 | if (parsedResponse?.sentiment === "Invalid review" || !parsedResponse?.sentiment) { 36 | throw new Error("Invalid review: ", text); 37 | } 38 | 39 | const collection = context?.services?.get(serviceName)?.db(databaseName)?.collection(collectionName); 40 | 41 | if (!collection) { 42 | throw new Error("Fetching destination collection failed."); 43 | } 44 | 45 | await collection.insertOne({ 46 | ...fullDocument, 47 | ...parsedResponse 48 | }); 49 | 50 | return parsedResponse; 51 | }; -------------------------------------------------------------------------------- /atlas-app-services/functions/Atlas_Triggers_summarizeReviewsSentiment_1686475894.js: -------------------------------------------------------------------------------- 1 | const serviceName = "M0"; 2 | const databaseName = "sample_restaurants"; 3 | const reviewsCollectionName = "processed_reviews"; 4 | const restaurantCollectionName = "restaurants"; 5 | // Add the Google Cloud Function URL below 6 | const summarizeFunctionURL = ""; 7 | 8 | exports = async function(changeEvent) { 9 | const restaurantId = changeEvent?.fullDocument?.restaurant_id; 10 | if (!restaurantId) { 11 | throw new Error("Extracting restaurant ID from review document failed."); 12 | } 13 | 14 | const restaurantCollection = getCollection(serviceName, databaseName, restaurantCollectionName); 15 | 16 | if (!shouldUpdateSummary(restaurantCollection, restaurantId)) { 17 | console.log("Summary generation skipped."); 18 | return; 19 | } 20 | 21 | const summary = await summarizeReviewSentiment(restaurantId); 22 | if (!summary) { 23 | return; 24 | } 25 | 26 | const updateResult = await restaurantCollection.updateOne({ 27 | _id: restaurantId 28 | }, { 29 | $set: { 30 | summary: summary, 31 | summaryDate: new Date() 32 | } 33 | }); 34 | 35 | return summary; 36 | }; 37 | 38 | async function summarizeReviewSentiment(restaurantId) { 39 | const collection = getCollection(serviceName, databaseName, reviewsCollectionName); 40 | 41 | const latestReviews = await collection.aggregate([ 42 | { 43 | $match: { restaurant_id: restaurantId } 44 | }, 45 | { 46 | $sort: { date: -1 } 47 | }, 48 | { 49 | $limit: 50 50 | }, 51 | { 52 | $project: { text: 1 } 53 | } 54 | ]).toArray(); 55 | 56 | if (latestReviews?.length < 3) { 57 | console.log("Unsufficient number of reviews.", latestReviews?.length); 58 | return; 59 | } 60 | 61 | const reviewsString = latestReviews.map(review => review.text).join(" | "); 62 | const response = await context.http.post({ 63 | url: summarizeFunctionURL, 64 | body: { text: reviewsString }, 65 | encodeBodyAsJSON: true 66 | }); 67 | 68 | const summary = JSON.parse(response?.body?.text())?.summary; 69 | if (!summary || (typeof summary === 'object' && isEmpty(summary))) { 70 | throw new Error("Summarizing reviews sentiment failed."); 71 | } 72 | 73 | return summary; 74 | } 75 | 76 | async function shouldUpdateSummary(collection, documentId, numberOfDays) { 77 | const restaurant = await collection.findOne({ 78 | _id: documentId 79 | }); 80 | 81 | if (!restaurant) { 82 | throw new Error(`Failed to fetch restaurant document. Restaurant ID: ${documentId}`); 83 | } 84 | 85 | if (!restaurant.summary) { 86 | return true; 87 | } 88 | 89 | const { summaryDate } = restaurant; 90 | 91 | if (!summaryDate || isDateOlderThanSpecifiedDays(summaryDate, numberOfDays)) { 92 | return true; 93 | } 94 | 95 | return false; 96 | } 97 | 98 | function isDateOlderThanSpecifiedDays(date, numberOfDays) { 99 | if (date instanceof Date && typeof numberOfDays === "number") { 100 | const specifiedDaysInMilliseconds = numberOfDays * 24 * 60 * 60 * 1000; 101 | const specifiedDaysAgoTimestamp = new Date().getTime() - specifiedDaysInMilliseconds; 102 | 103 | return date.getTime() < specifiedDaysAgoTimestamp; 104 | } else { 105 | throw new Error("Invalid input. ", date, numberOfDays); 106 | } 107 | } 108 | 109 | function getCollection(serviceName, databaseName, collectionName) { 110 | const collection = context?.services?.get(serviceName)?.db(databaseName)?.collection(collectionName); 111 | 112 | if (!collection) { 113 | throw new Error(`Fetching collection ${databaseName}.${collectionName} from the service ${serviceName} failed.`); 114 | } 115 | 116 | return collection; 117 | } 118 | 119 | function isEmpty(obj) { 120 | for (const prop in obj) { 121 | if (Object.hasOwn(obj, prop)) { 122 | return false; 123 | } 124 | } 125 | 126 | return true; 127 | } 128 | 129 | -------------------------------------------------------------------------------- /atlas-app-services/functions/config.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "Atlas_Triggers_analyzeReviewSentiment_1686394580", 4 | "private": false 5 | }, 6 | { 7 | "name": "Atlas_Triggers_summarizeReviewsSentiment_1686475894", 8 | "private": false 9 | } 10 | ] 11 | -------------------------------------------------------------------------------- /atlas-app-services/triggers/analyzeReviewSentiment.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "analyzeReviewSentiment", 3 | "type": "DATABASE", 4 | "config": { 5 | "operation_types": [ 6 | "INSERT" 7 | ], 8 | "database": "sample_restaurants", 9 | "collection": "raw_reviews", 10 | "service_name": "M0", 11 | "match": {}, 12 | "project": {}, 13 | "full_document": true, 14 | "full_document_before_change": false, 15 | "unordered": false, 16 | "skip_catchup_events": false, 17 | "tolerate_resume_errors": false 18 | }, 19 | "disabled": false, 20 | "event_processors": { 21 | "FUNCTION": { 22 | "config": { 23 | "function_name": "Atlas_Triggers_analyzeReviewSentiment_1686394580" 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /atlas-app-services/triggers/summarizeReviewsSentiment.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "summarizeReviewsSentiment", 3 | "type": "DATABASE", 4 | "config": { 5 | "operation_types": [ 6 | "INSERT" 7 | ], 8 | "database": "sample_restaurants", 9 | "collection": "processed_reviews", 10 | "service_name": "M0", 11 | "match": {}, 12 | "project": {}, 13 | "full_document": true, 14 | "full_document_before_change": false, 15 | "unordered": false, 16 | "skip_catchup_events": false, 17 | "tolerate_resume_errors": false 18 | }, 19 | "disabled": false, 20 | "event_processors": { 21 | "FUNCTION": { 22 | "config": { 23 | "function_name": "Atlas_Triggers_summarizeReviewsSentiment_1686475894" 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /firebase.json: -------------------------------------------------------------------------------- 1 | { 2 | "hosting": [ 3 | { 4 | "target": "ai-restaurants", 5 | "source": ".", 6 | "frameworksBackend": {} 7 | } 8 | ] 9 | } -------------------------------------------------------------------------------- /google-cloud-functions/analyze-media/index.js: -------------------------------------------------------------------------------- 1 | const functions = require('@google-cloud/functions-framework'); 2 | const { VertexAI } = require('@google-cloud/vertexai'); 3 | 4 | const projectId = 'atlas-ai-demos'; 5 | const location = 'us-central1'; 6 | const model = 'gemini-1.0-pro-vision'; 7 | 8 | const bucketName = ''; 9 | 10 | const prompt = ` 11 | Analyze the sentiment of the photo/video. 12 | Generate a description of the photo or video. 13 | Generate 5 tags describing what's in the photo/video. 14 | The information will be used for an application for restaurant reviews. The information must be relevant to the food, interior, service, and overal sentiment of the restaurant. 15 | 16 | The response must be a JSON object with the following definition: 17 | Field - Type 18 | sentiment - string 19 | description - string 20 | tags - array of strings 21 | `; 22 | 23 | const samples = [ 24 | // Sample prompt with just a text review 25 | { 26 | text: prompt 27 | }, 28 | { 29 | text: `{ "sentiment": "The sentiment in the image is positive.", "description": "A group of four friends are sitting at a table in a restaurant, laughing and talking.", "tags": ["beer", "outdoor seating", "nightlife"] }` 30 | } 31 | ]; 32 | 33 | functions.http('analyzeMedia', async (req, res) => { 34 | res.set('Access-Control-Allow-Origin', '*'); 35 | 36 | if (req.method === 'OPTIONS') { 37 | // Send response to OPTIONS requests 38 | res.set('Access-Control-Allow-Methods', 'GET'); 39 | res.set('Access-Control-Allow-Headers', 'Content-Type'); 40 | res.set('Access-Control-Max-Age', '3600'); 41 | return res.status(204).send(''); 42 | } 43 | 44 | const fileName = req.query.fileName; 45 | const fileType = req.query.fileType; 46 | if (!fileName || !fileType) { 47 | return res.status(400).send('You must provide fileName and fileType.'); 48 | } 49 | 50 | const file = { 51 | fileData: { 52 | fileUri: `${bucketName}/${fileName}`, 53 | mimeType: fileType 54 | } 55 | } 56 | 57 | const response = await createNonStreamingMultipartContent(file); 58 | 59 | try { 60 | const sanitizedResponse = response.replace(/^\s*```json\n|\n```$/g, ''); 61 | const parsedResponse = JSON.parse(sanitizedResponse); 62 | return res.send(parsedResponse); 63 | } catch (error) { 64 | console.error('Failed to parse model response: ', response, error); 65 | // Return unparsed response 66 | return res.send({ response }); 67 | } 68 | }); 69 | 70 | async function createNonStreamingMultipartContent( 71 | filePart, 72 | ) { 73 | // Initialize Vertex with your Cloud project and location 74 | const vertexAI = new VertexAI({project: projectId, location }); 75 | 76 | // Instantiate the model 77 | const generativeVisionModel = vertexAI.getGenerativeModel({ model }); 78 | 79 | const textPart = { 80 | text: prompt 81 | }; 82 | 83 | const request = { 84 | contents: [{role: 'user', parts: [...samples, filePart, textPart]}], 85 | }; 86 | 87 | const responseStream = 88 | await generativeVisionModel.generateContentStream(request); 89 | 90 | // Wait for the response stream to complete 91 | const aggregatedResponse = await responseStream.response; 92 | 93 | // Select the text from the response 94 | const fullTextResponse = 95 | aggregatedResponse.candidates[0].content.parts[0].text; 96 | 97 | return fullTextResponse; 98 | } 99 | -------------------------------------------------------------------------------- /google-cloud-functions/analyze-media/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "@google-cloud/functions-framework": "^3.0.0", 4 | "@google-cloud/vertexai": "^0.5.0" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /google-cloud-functions/analyze-sentiment/index.js: -------------------------------------------------------------------------------- 1 | const functions = require('@google-cloud/functions-framework'); 2 | const { VertexAI } = require('@google-cloud/vertexai'); 3 | const dJSON = require('dirty-json'); 4 | 5 | const projectId = 'atlas-ai-demos'; 6 | const location = 'us-central1'; 7 | const model = 'gemini-1.0-pro'; 8 | 9 | const prompt = ` 10 | Analyze the sentiment of this restaurant review. 11 | Assign a total score and scores for the food, the service, and the interior. The scores should be from 1 to 5 with 1 being the lowest and 5 — the highest. If there's no sufficient data for some of the scores, return 0 (as a Number). 12 | When assigning scores and overal sentiment take into account both the review text and the sentiments of the attached images and videos. 13 | Return the response in JSON format [{}]. "sentiment" - "positive", "negative", or "neutral", "food" (0-5), "service" (0-5), "interior" (0-5). The returned object should always be valid JSON. 14 | Return the result 'Invalid review', formatted as a JSON object, for any reviews that aren't contextually related to the restaurant, contain inappropriate language, and/or are meaningless. 15 | `; 16 | 17 | // Sample prompts that will be used when sending the few-shot prompt 18 | const samplePrompts = [ 19 | { 20 | text: ` 21 | ${prompt} 22 | 23 | Sentiments of the images and videos attached to the review start here. 24 | Attached media 1 - The sentiment of the image is positive. 25 | Sentiments of the attached images and videos end here. 26 | 27 | Review text starts here. 28 | The restaurant was nice. 29 | We went here for dinner. The food didn't live up to the expectations but the service was impeccable. 30 | 31 | Review text ends here. 32 | ` 33 | }, 34 | { 35 | text: `{ "sentiment": "positive", "food": 3, "service": 5, "interior": 5 }` 36 | }, 37 | { 38 | text: ` 39 | ${prompt} 40 | 41 | Sentiments of the images and videos attached to the review start here. 42 | Attached media 1 - The sentiment of the image is positive. 43 | Sentiments of the attached images and videos end here. 44 | 45 | Review text starts here. 46 | It was fine. 47 | Review text ends here. 48 | ` 49 | }, 50 | { 51 | text: `{ "sentiment": "positive", "food": 0, "service": 0, "interior": 0 }` 52 | }, 53 | { 54 | text: ` 55 | ${prompt} 56 | 57 | Sentiments of the images and videos attached to the review start here. 58 | Attached media 1 - The sentiment of the image is negative. 59 | Sentiments of the attached images and videos end here. 60 | 61 | Review text starts here. 62 | It was fine. 63 | Review text ends here. 64 | ` 65 | }, 66 | { 67 | text: `{ "sentiment": "negative", "total": 0, "food": 0, "service": 0, "interior": 0 }` 68 | }, 69 | ]; 70 | 71 | functions.http('analyzeReview', async (req, res) => { 72 | const text = req.body.text; 73 | const fileDescriptions = req.body.fileDescriptions || []; 74 | if (!text) { 75 | return res.status(400).send('You must provide text'); 76 | } 77 | 78 | const response = await createNonStreamingMultipartContent(text, fileDescriptions); 79 | 80 | try { 81 | const sanitizedResponse = response.replace(/^\s*```json\n|\n```$/g, '').match(/{.*?}/)[0]; 82 | const parsedResponse = dJSON.parse(sanitizedResponse); 83 | 84 | console.log("PARSED RESPONSE ------->>>", parsedResponse); 85 | 86 | return res.send(parsedResponse); 87 | } catch (error) { 88 | console.error('Failed to parse model response: ', response, error); 89 | // Return unparsed response 90 | return res.send({ response }); 91 | } 92 | }); 93 | 94 | async function createNonStreamingMultipartContent( 95 | review, 96 | fileDescriptions 97 | ) { 98 | // Initialize Vertex with your Cloud project and location 99 | const vertexAI = new VertexAI({project: projectId, location }); 100 | 101 | // Instantiate the model 102 | const generativeVisionModel = vertexAI.getGenerativeModel({ 103 | model, 104 | generation_config: { 105 | max_output_tokens: 60, 106 | // Lower temperature for more predictable analysis 107 | temperature: 0.2, 108 | }, 109 | }); 110 | 111 | const textPart = { 112 | text: ` 113 | ${prompt} 114 | 115 | Sentiments of the images and videos attached to the review start here. 116 | ${fileDescriptions.join('\n')} 117 | Sentiments of the attached images and videos end here. 118 | 119 | Review text starts here. 120 | ${review} 121 | Review text ends here. 122 | ` 123 | }; 124 | 125 | const request = { 126 | contents: [ 127 | { 128 | role: 'user', 129 | parts: [ 130 | ...samplePrompts, 131 | textPart 132 | ] 133 | } 134 | ], 135 | }; 136 | 137 | const responseStream = 138 | await generativeVisionModel.generateContentStream(request); 139 | 140 | // Wait for the response stream to complete 141 | const aggregatedResponse = await responseStream.response; 142 | 143 | // Select the text from the response 144 | const fullTextResponse = 145 | aggregatedResponse.candidates[0].content.parts[0].text; 146 | 147 | return fullTextResponse; 148 | } 149 | -------------------------------------------------------------------------------- /google-cloud-functions/analyze-sentiment/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "@google-cloud/functions-framework": "^3.0.0", 4 | "@google-cloud/vertexai": "^0.5.0", 5 | "dirty-json": "0.9.2" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /google-cloud-functions/create-signed-url/index.js: -------------------------------------------------------------------------------- 1 | const functions = require('@google-cloud/functions-framework'); 2 | const { Storage } = require('@google-cloud/storage'); 3 | const storage = new Storage(); 4 | 5 | const bucketName = ''; 6 | 7 | functions.http('getSignedUploadUrl', async (req, res) => { 8 | res.set('Access-Control-Allow-Origin', '*'); 9 | 10 | if (req.method === 'OPTIONS') { 11 | // Send response to OPTIONS requests 12 | res.set('Access-Control-Allow-Methods', 'GET'); 13 | res.set('Access-Control-Allow-Headers', 'Content-Type'); 14 | res.set('Access-Control-Max-Age', '3600'); 15 | return res.status(204).send(''); 16 | } 17 | 18 | const fileType = req.query.fileType; 19 | const fileName = req.query.fileName; 20 | if (!fileName) { 21 | return res.status(400).send('Invalid request. fileName is required.'); 22 | } 23 | 24 | const urlPut = await generateV4UploadSignedUrl(fileName, fileType); 25 | return res.send(urlPut); 26 | }); 27 | 28 | async function generateV4UploadSignedUrl(fileName, fileType) { 29 | // These options will allow temporary uploading of the file with outgoing 30 | // Content-Type: fileType header. 31 | const options = { 32 | version: 'v4', 33 | action: 'write', 34 | expires: Date.now() + 15 * 60 * 1000, // 15 minutes 35 | contentType: fileType, 36 | }; 37 | 38 | // Get a v4 signed URL for uploading file 39 | const [url] = await storage 40 | .bucket(bucketName) 41 | .file(fileName) 42 | .getSignedUrl(options); 43 | 44 | console.log('Generated PUT signed URL:'); 45 | console.log(url); 46 | console.log('You can use this URL with any user agent, for example:'); 47 | console.log( 48 | "curl -X PUT -H 'Content-Type: application/octet-stream' " + 49 | `--upload-file my-file '${url}'` 50 | ); 51 | 52 | return url; 53 | } 54 | 55 | async function generateV4ReadSignedUrl(fileName) { 56 | // These options will allow temporary read access to the file 57 | const options = { 58 | version: 'v4', 59 | action: 'read', 60 | expires: Date.now() + 15 * 60 * 1000, // 15 minutes 61 | }; 62 | 63 | // Get a v4 signed URL for reading the file 64 | const [url] = await storage 65 | .bucket(bucketName) 66 | .file(fileName) 67 | .getSignedUrl(options); 68 | 69 | return url; 70 | } 71 | -------------------------------------------------------------------------------- /google-cloud-functions/create-signed-url/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "@google-cloud/functions-framework": "^3.0.0", 4 | "@google-cloud/storage": "^7.8.0" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /google-cloud-functions/summarize-review-sentiment/main.py: -------------------------------------------------------------------------------- 1 | import functions_framework 2 | import json 3 | import vertexai 4 | from vertexai.preview.language_models import TextGenerationModel 5 | 6 | API_ENDPOINT = 'us-central1-aiplatform.googleapis.com' 7 | PROJECT_ID = 'atlas-ai-demos' 8 | MODEL_ID = 'text-bison@001' 9 | # Higher temperature for a more creative summary 10 | TEMPERATURE = 0.5 11 | MAX_DECODE_STEPS = 256 12 | TOP_P = 0.8 13 | TOP_K = 40 14 | REGION = 'us-central1' 15 | 16 | @functions_framework.http 17 | def summarize_sentiment(request): 18 | request_json = request.get_json(silent=True) 19 | 20 | if request_json and 'text' in request_json: 21 | text = request_json['text'] 22 | else: 23 | return '\'text\' argument required.' 24 | 25 | try: 26 | summary = predict_large_language_model_sample( 27 | PROJECT_ID, 28 | MODEL_ID, 29 | TEMPERATURE, 30 | MAX_DECODE_STEPS, 31 | TOP_P, 32 | TOP_K, 33 | '''Using sentiment analysis, create a 100-word summary of the customers' experiences at this restaurant based on the following reviews. 34 | 35 | Reviews: 36 | {reviews} 37 | 38 | input: 39 | output: 40 | '''.format(reviews=text), 41 | REGION 42 | ) 43 | 44 | print(f"Summary is: {summary}") 45 | 46 | data = { "summary": summary } 47 | return json.dumps(data), 200, {'Content-Type': 'application/json'} 48 | except: 49 | print("Analyzing sentiment failed.") 50 | raise 51 | 52 | def predict_large_language_model_sample( 53 | project_id: str, 54 | model_name: str, 55 | temperature: float, 56 | max_decode_steps: int, 57 | top_p: float, 58 | top_k: int, 59 | content: str, 60 | location: str, 61 | tuned_model_name: str = "", 62 | ) : 63 | """Predict using a Large Language Model.""" 64 | vertexai.init(project=project_id, location=location) 65 | model = TextGenerationModel.from_pretrained(model_name) 66 | if tuned_model_name: 67 | model = model.get_tuned_model(tuned_model_name) 68 | response = model.predict( 69 | content, 70 | temperature=temperature, 71 | max_output_tokens=max_decode_steps, 72 | top_k=top_k, 73 | top_p=top_p,) 74 | print(f"Response from Model: {response}") 75 | return response.text -------------------------------------------------------------------------------- /google-cloud-functions/summarize-review-sentiment/requirements.txt: -------------------------------------------------------------------------------- 1 | functions-framework==3.* 2 | google-cloud-aiplatform==1.25.* -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "genai-sentiment-analysis-summarization", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "watch": "ng build --watch --configuration development", 9 | "test": "ng test" 10 | }, 11 | "private": true, 12 | "dependencies": { 13 | "@angular/animations": "^16.0.0", 14 | "@angular/cdk": "^16.0.3", 15 | "@angular/common": "^16.0.0", 16 | "@angular/compiler": "^16.0.0", 17 | "@angular/core": "^16.0.0", 18 | "@angular/fire": "^7.6.1", 19 | "@angular/forms": "^16.0.0", 20 | "@angular/material": "^16.0.3", 21 | "@angular/platform-browser": "^16.0.0", 22 | "@angular/platform-browser-dynamic": "^16.0.0", 23 | "@angular/router": "^16.0.0", 24 | "ngx-guided-tour": "^2.0.1", 25 | "realm-web": "^2.0.0", 26 | "rxjs": "~7.8.0", 27 | "tslib": "^2.3.0", 28 | "zone.js": "~0.13.0" 29 | }, 30 | "devDependencies": { 31 | "@angular-devkit/build-angular": "^16.0.5", 32 | "@angular/cli": "~16.0.5", 33 | "@angular/compiler-cli": "^16.0.0", 34 | "@types/jasmine": "~4.3.0", 35 | "jasmine-core": "~4.6.0", 36 | "karma": "~6.4.0", 37 | "karma-chrome-launcher": "~3.2.0", 38 | "karma-coverage": "~2.2.0", 39 | "karma-jasmine": "~5.1.0", 40 | "karma-jasmine-html-reporter": "~2.0.0", 41 | "typescript": "~5.0.2" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/app/address.ts: -------------------------------------------------------------------------------- 1 | export interface Address { 2 | building: string; 3 | coord: [number, number]; 4 | street: string; 5 | zipcode: string; 6 | } -------------------------------------------------------------------------------- /src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { RouterModule, Routes } from '@angular/router'; 3 | import { RestaurantsListComponent } from './restaurants-list/restaurants-list.component'; 4 | import { RestaurantDetailsComponent } from './restaurant-details/restaurant-details.component'; 5 | 6 | const routes: Routes = [ 7 | { path: 'restaurants', component: RestaurantsListComponent }, 8 | { path: 'restaurants/:id', component: RestaurantDetailsComponent }, 9 | { path: '', redirectTo: 'restaurants', pathMatch: 'full' }, 10 | ]; 11 | 12 | @NgModule({ 13 | imports: [RouterModule.forRoot(routes)], 14 | exports: [RouterModule] 15 | }) 16 | export class AppRoutingModule { } 17 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 |
5 | -------------------------------------------------------------------------------- /src/app/app.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb-developer/Google-Cloud-Sentiment-Chef/6d2e932544dc6b4ea45b5c71bbd9ebd74c93c02a/src/app/app.component.scss -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html', 6 | styleUrls: ['./app.component.scss'] 7 | }) 8 | export class AppComponent { 9 | } 10 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { NgOptimizedImage, provideImgixLoader } from '@angular/common'; 3 | import { BrowserModule } from '@angular/platform-browser'; 4 | import { MatAutocompleteModule } from '@angular/material/autocomplete'; 5 | import { MatToolbarModule } from '@angular/material/toolbar'; 6 | import { MatCardModule } from '@angular/material/card'; 7 | import { MatButtonModule } from '@angular/material/button'; 8 | import { MatIconModule } from '@angular/material/icon'; 9 | import { MatInputModule } from '@angular/material/input'; 10 | import { MatDividerModule } from '@angular/material/divider'; 11 | import { MatFormFieldModule } from '@angular/material/form-field'; 12 | import { MatDatepickerModule } from '@angular/material/datepicker'; 13 | import { MatNativeDateModule } from '@angular/material/core'; 14 | import { ReactiveFormsModule } from '@angular/forms'; 15 | import { MatDialogModule } from '@angular/material/dialog'; 16 | 17 | import { AppRoutingModule } from './app-routing.module'; 18 | import { AppComponent } from './app.component'; 19 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 20 | import { RestaurantsListComponent } from './restaurants-list/restaurants-list.component'; 21 | import { RestaurantDetailsComponent } from './restaurant-details/restaurant-details.component'; 22 | import { ReviewFormComponent } from './review-form/review-form.component'; 23 | import { NavbarComponent } from './navbar/navbar.component'; 24 | import { DragAndDropDirective } from './drag-and-drop.directive'; 25 | import { HttpClientModule } from '@angular/common/http'; 26 | import { MediaUploadDialogComponent } from './media-upload-dialog/media-upload-dialog.component'; 27 | import { MediaDialog } from './image-detailed-dialog/media-dialog.component'; 28 | import { MediaPreviewComponent } from './media-preview/media-preview.component'; 29 | import { RestaurantsListGuidedComponent } from './restaurants-list-guided/restaurants-list-guided.component'; 30 | import { GuidedTourModule, GuidedTourService } from 'ngx-guided-tour'; 31 | import { RestaurantDetailsGuidedComponent } from './restaurant-details-guided/restaurant-details-guided.component'; 32 | import { config } from 'src/config'; 33 | 34 | @NgModule({ 35 | declarations: [ 36 | AppComponent, 37 | RestaurantsListComponent, 38 | RestaurantDetailsComponent, 39 | ReviewFormComponent, 40 | NavbarComponent, 41 | DragAndDropDirective, 42 | MediaUploadDialogComponent, 43 | MediaDialog, 44 | MediaPreviewComponent, 45 | RestaurantsListGuidedComponent, 46 | RestaurantDetailsGuidedComponent, 47 | ], 48 | imports: [ 49 | BrowserModule, 50 | AppRoutingModule, 51 | BrowserAnimationsModule, 52 | NgOptimizedImage, 53 | MatAutocompleteModule, 54 | MatButtonModule, 55 | MatCardModule, 56 | MatDividerModule, 57 | MatDatepickerModule, 58 | MatIconModule, 59 | MatInputModule, 60 | MatToolbarModule, 61 | MatFormFieldModule, 62 | MatNativeDateModule, 63 | ReactiveFormsModule, 64 | HttpClientModule, 65 | MatDialogModule, 66 | GuidedTourModule, 67 | ], 68 | providers: [ 69 | provideImgixLoader(config.imgixDomain), 70 | GuidedTourService, 71 | ], 72 | bootstrap: [AppComponent] 73 | }) 74 | export class AppModule { } 75 | -------------------------------------------------------------------------------- /src/app/change-events.ts: -------------------------------------------------------------------------------- 1 | export const isInsertEvent = (event: any): event is Realm.Services.MongoDB.InsertEvent => 2 | event.operationType === 'insert'; 3 | 4 | export const isUpdateEvent = (event: any): event is Realm.Services.MongoDB.UpdateEvent => 5 | event.operationType === 'update'; 6 | -------------------------------------------------------------------------------- /src/app/drag-and-drop.directive.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Directive, 3 | HostBinding, 4 | HostListener, 5 | Output, 6 | EventEmitter 7 | } from "@angular/core"; 8 | import { FileHandle, FileHandleService } from "./file-handle.service"; 9 | 10 | @Directive({ 11 | selector: "[appDrag]" 12 | }) 13 | export class DragAndDropDirective { 14 | @Output() files: EventEmitter = new EventEmitter(); 15 | 16 | @HostBinding("style.background") private background = "#eee"; 17 | 18 | constructor(private fileHandleService: FileHandleService) { } 19 | 20 | @HostListener("dragover", ["$event"]) public onDragOver(evt: DragEvent) { 21 | evt.preventDefault(); 22 | evt.stopPropagation(); 23 | this.background = "#999"; 24 | } 25 | 26 | @HostListener("dragleave", ["$event"]) public onDragLeave(evt: DragEvent) { 27 | evt.preventDefault(); 28 | evt.stopPropagation(); 29 | this.background = "#eee"; 30 | } 31 | 32 | @HostListener('drop', ['$event']) public onDrop(evt: DragEvent) { 33 | evt.preventDefault(); 34 | evt.stopPropagation(); 35 | this.background = '#eee'; 36 | 37 | let files: FileHandle[] = []; 38 | const filesFromEvent = evt?.dataTransfer?.files; 39 | if (!filesFromEvent?.length) { 40 | return; 41 | } 42 | 43 | for (let i = 0; i < filesFromEvent?.length; i++) { 44 | const file = filesFromEvent[i]; 45 | const handle = this.fileHandleService.sanitizeFile(file); 46 | files.push(handle); 47 | } 48 | if (files.length > 0) { 49 | this.files.emit(files); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/app/file-handle.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { FileHandleService } from './file-handle.service'; 4 | 5 | describe('FileHandleService', () => { 6 | let service: FileHandleService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(FileHandleService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/app/file-handle.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { DomSanitizer, SafeUrl } from '@angular/platform-browser'; 3 | 4 | export interface FileHandle { 5 | file: File, 6 | url: SafeUrl 7 | } 8 | 9 | @Injectable({ 10 | providedIn: 'root' 11 | }) 12 | export class FileHandleService { 13 | 14 | constructor(private sanitizer: DomSanitizer) { } 15 | 16 | sanitizeFile(file: File) { 17 | console.log(file); 18 | const url = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(file)); 19 | return { file, url }; 20 | } 21 | 22 | async fileFromUrl(url: string, mimeType: string) { 23 | // return new Promise((resolve, reject) => { 24 | // const request = new XMLHttpRequest(); 25 | // request.open('GET', url, true); 26 | // request.responseType = 'blob'; 27 | // request.onload = async function() { 28 | // const reader = new FileReader(); 29 | // reader.readAsDataURL(request.response); 30 | // reader.onload = function(e){ 31 | // const buffer = e.target?.result; 32 | // if (!buffer) { 33 | // return reject('Failed to load file'); 34 | // } 35 | 36 | // const name = `file-${Date.now()}.${mimeType.split('/').pop() || 'txt'}`; 37 | // const file = new File([buffer], name, { type: mimeType }); 38 | // console.log(file); 39 | // console.log(url); 40 | 41 | // return resolve({ file, url }); 42 | // }; 43 | // }; 44 | 45 | // request.send(); 46 | // }); 47 | 48 | const response = await fetch(url); 49 | const data = await response.blob(); 50 | const metadata = { 51 | type: mimeType 52 | }; 53 | 54 | const name = `file-${Date.now()}.${mimeType.split('/').pop() || 'txt'}`; 55 | const file = new File([data], name, metadata); 56 | 57 | return { file, url }; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/app/grade.ts: -------------------------------------------------------------------------------- 1 | export interface Grade { 2 | date: Date; 3 | grade: string; 4 | score: number; 5 | } -------------------------------------------------------------------------------- /src/app/helpers/objectId.ts: -------------------------------------------------------------------------------- 1 | import { BSON } from 'realm-web'; 2 | 3 | const ObjectId = BSON.ObjectId; 4 | 5 | export { ObjectId }; 6 | 7 | export function compareIds(a: any, b: any) { 8 | const oa = new ObjectId(a); 9 | const ob = new ObjectId(b); 10 | 11 | return oa.equals(ob); 12 | } 13 | -------------------------------------------------------------------------------- /src/app/image-detailed-dialog/media-dialog.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 |

AI-generated description and tags

7 | {{ file.description }} 8 | Tags: {{ file.tags.join(", ") }} 9 | Sentiment: {{ file.sentiment }} 10 |
11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/app/image-detailed-dialog/media-dialog.component.scss: -------------------------------------------------------------------------------- 1 | .dialog-content { 2 | display: flex; 3 | flex-direction: row; 4 | max-width: 1200px; 5 | } 6 | 7 | .description { 8 | display: flex; 9 | flex-direction: column; 10 | margin: 30px; 11 | gap: 15px; 12 | } 13 | 14 | @media screen and (max-width: 1024px) { 15 | .dialog-content { 16 | flex-direction: column; 17 | align-items: center; 18 | } 19 | } -------------------------------------------------------------------------------- /src/app/image-detailed-dialog/media-dialog.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Inject } from '@angular/core'; 2 | import { MAT_DIALOG_DATA } from '@angular/material/dialog'; 3 | import { UploadedMedia } from '../uploaded-media'; 4 | 5 | export interface ImageDetailsDialogData { 6 | media: UploadedMedia; 7 | } 8 | 9 | @Component({ 10 | templateUrl: './media-dialog.component.html', 11 | styleUrls: ['./media-dialog.component.scss'] 12 | }) 13 | export class MediaDialog { 14 | file: UploadedMedia; 15 | 16 | constructor( 17 | @Inject(MAT_DIALOG_DATA) public data: ImageDetailsDialogData 18 | ) { 19 | this.file = data.media; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/app/image-uplouder.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { firstValueFrom } from 'rxjs'; 4 | 5 | @Injectable({ 6 | providedIn: 'root' 7 | }) 8 | export class ImageUploaderService { 9 | constructor(private http: HttpClient) { } 10 | 11 | upload(file: File) { 12 | return new Promise<{ fileName: string, analysis: any }>(async (resolve, reject) => { 13 | const fileName = `reviews/${Date.now()}-${Math.floor(Math.random() * 100000)}.${file.name.split('.').pop()}`; 14 | 15 | const signedUrl = await this.createSignedUrl(fileName, file.type); 16 | const xhr = new XMLHttpRequest(); 17 | xhr.open('PUT', signedUrl, true); 18 | 19 | xhr.onload = async () => { 20 | const status = xhr.status; 21 | if (status === 200) { 22 | const analysis = await this.analyzeImage(fileName, file.type); 23 | const response = { 24 | fileName, 25 | analysis 26 | }; 27 | 28 | return resolve(response); 29 | 30 | } else { 31 | return reject({ 32 | status: xhr.status, 33 | statusText: xhr.statusText 34 | }); 35 | } 36 | }; 37 | 38 | xhr.onerror = () => { 39 | alert('Something went wrong'); 40 | return reject({ 41 | status: xhr.status, 42 | statusText: xhr.statusText 43 | }); 44 | }; 45 | 46 | xhr.setRequestHeader('Content-Type', file.type); 47 | xhr.send(file); 48 | }); 49 | } 50 | 51 | private analyzeImage(fileName: string, fileType: string) { 52 | console.log('file name ----> ' + fileName); 53 | return firstValueFrom(this.http.get( 54 | 'https://us-central1-atlas-ai-demos.cloudfunctions.net/analyzeMedia', 55 | { 56 | params: { fileName, fileType }, 57 | responseType: 'json' 58 | } 59 | )); 60 | } 61 | 62 | private createSignedUrl(fileName: string, fileType: string) { 63 | return firstValueFrom(this.http.get( 64 | 'https://us-central1-atlas-ai-demos.cloudfunctions.net/createSignedUrl', 65 | { 66 | params: { fileName, fileType }, 67 | responseType: 'text' 68 | } 69 | )); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/app/media-preview/media-preview.component.html: -------------------------------------------------------------------------------- 1 |
3 | 4 | 5 | 6 | 11 | 12 | 13 | 14 | 15 | 16 |
-------------------------------------------------------------------------------- /src/app/media-preview/media-preview.component.scss: -------------------------------------------------------------------------------- 1 | .media-wrapper { 2 | display: flex; 3 | align-items: center; 4 | justify-content: center; 5 | background-color: black; 6 | position: relative; 7 | border-radius: 6px; 8 | 9 | img, 10 | video { 11 | max-width: 100%; 12 | object-fit: cover; 13 | object-position: center; 14 | height: auto !important; 15 | width: auto !important; 16 | border-radius: 6px; 17 | } 18 | 19 | &.small { 20 | height: 124px; 21 | width: 186px; 22 | cursor: pointer; 23 | 24 | img, 25 | video { 26 | max-height: 124px; 27 | } 28 | } 29 | 30 | &.medium { 31 | height: 200px; 32 | width: 250px; 33 | 34 | img, 35 | video { 36 | max-height: 200px; 37 | } 38 | } 39 | 40 | &.big { 41 | height: 400px; 42 | width: 500px; 43 | 44 | img, 45 | video { 46 | max-height: 400px; 47 | } 48 | } 49 | } 50 | 51 | @media screen and (max-width: 1024px) { 52 | .media-wrapper.big { 53 | height: 200px; 54 | width: 250px; 55 | 56 | img, 57 | video { 58 | max-height: 200px; 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /src/app/media-preview/media-preview.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | import { UploadedMedia } from '../uploaded-media'; 3 | import { MediaDialog } from '../image-detailed-dialog/media-dialog.component'; 4 | import { MatDialog } from '@angular/material/dialog'; 5 | import { config } from 'src/config'; 6 | 7 | @Component({ 8 | selector: 'app-media-preview', 9 | templateUrl: './media-preview.component.html', 10 | styleUrls: ['./media-preview.component.scss'] 11 | }) 12 | export class MediaPreviewComponent { 13 | @Input() 14 | file: UploadedMedia; 15 | 16 | @Input() 17 | size: 'small' | 'medium' | 'big'; 18 | 19 | reviewImagesBucket = config.reviewImagesBucket; 20 | 21 | constructor( 22 | public dialog: MatDialog, 23 | ) { 24 | } 25 | 26 | openDetailsDialog() { 27 | if (this.size === 'small') { 28 | this.dialog.open(MediaDialog, { 29 | data: { media: this.file }, 30 | }); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/media-upload-dialog/media-upload-dialog.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Add images and videos

3 | 4 | Uploading your files... 5 | Uploading files failed! 6 | 7 |
8 |
9 |
10 | 11 |
12 |

AI-generated description and tags

13 | {{ file.description }} 14 | Tags: {{ file.tags.join(", ") }} 15 | Sentiment: {{ file.sentiment }} 16 |
17 |
18 |
19 |
20 |
21 | 22 |
23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/app/media-upload-dialog/media-upload-dialog.component.scss: -------------------------------------------------------------------------------- 1 | .dialog-container { 2 | min-width: 1000px; 3 | min-height: 500px; 4 | } 5 | 6 | h2 { 7 | font-size: 30px !important; 8 | margin: 30px; 9 | } 10 | 11 | .media-preview { 12 | margin: 20px 0; 13 | grid-gap: 16px 16px; 14 | display: flex; 15 | flex-direction: column; 16 | gap: 30px; 17 | 18 | .media-row { 19 | display: grid; 20 | grid-template-columns: 1fr 2fr; 21 | gap: 30px; 22 | } 23 | 24 | .media-preview { 25 | justify-self: center; 26 | } 27 | 28 | .description { 29 | display: flex; 30 | flex-direction: column; 31 | justify-content: center; 32 | gap: 5px; 33 | max-width: 600px; 34 | 35 | h3 { 36 | font-weight: bold; 37 | font-size: 18px; 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/app/media-upload-dialog/media-upload-dialog.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Inject } from '@angular/core'; 2 | import { MAT_DIALOG_DATA } from '@angular/material/dialog'; 3 | import { ImageUploaderService } from '../image-uplouder.service'; 4 | import { UploadedMedia } from '../uploaded-media'; 5 | import { FileHandle } from '../file-handle.service'; 6 | 7 | export interface MediaUploadDialogData { 8 | fileHandles: FileHandle[]; 9 | } 10 | 11 | @Component({ 12 | selector: 'app-media-upload-dialog', 13 | templateUrl: './media-upload-dialog.component.html', 14 | styleUrls: ['./media-upload-dialog.component.scss'] 15 | }) 16 | export class MediaUploadDialogComponent { 17 | fileHandles: FileHandle[] = []; 18 | uploading = false; 19 | allFailed = false; 20 | uploadedImages: Array = []; 21 | 22 | constructor( 23 | @Inject(MAT_DIALOG_DATA) public data: MediaUploadDialogData, 24 | private imageUploader: ImageUploaderService, 25 | ) { 26 | 27 | this.fileHandles = data.fileHandles; 28 | this.upload(); 29 | } 30 | 31 | 32 | upload(): void { 33 | const promises = []; 34 | let failedRequests = 0; 35 | for (let fileHandle of this.fileHandles) { 36 | this.uploading = true; 37 | 38 | const promise = this.imageUploader.upload(fileHandle.file) 39 | .then((result) => { 40 | this.uploadedImages.push({ 41 | fileName: result.fileName, 42 | mimeType: fileHandle.file.type, 43 | description: result.analysis?.description || '', 44 | tags: result.analysis?.tags || [], 45 | sentiment: result.analysis?.sentiment || '' 46 | }); 47 | }) 48 | .catch((error) => { 49 | failedRequests++; 50 | console.error(error); 51 | }); 52 | 53 | promises.push(promise); 54 | } 55 | 56 | Promise.all(promises).finally(() => { 57 | this.uploading = false; 58 | }); 59 | 60 | if (failedRequests === this.fileHandles.length) { 61 | this.allFailed = true; 62 | } 63 | } 64 | } 65 | 66 | -------------------------------------------------------------------------------- /src/app/navbar/navbar.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | restaurant_menu 4 | Restaurants 5 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 20 | 22 | 24 | 25 | {{ option.name }} 26 | 27 | 28 | 29 | 32 |
33 |
34 |
-------------------------------------------------------------------------------- /src/app/navbar/navbar.component.scss: -------------------------------------------------------------------------------- 1 | .spacer { 2 | flex: 1 1 auto; 3 | } 4 | 5 | 6 | .mat-toolbar a { 7 | margin-left: 8px; 8 | color: inherit; 9 | line-height: 18px; 10 | text-decoration: none; 11 | } 12 | 13 | header { 14 | position: fixed; 15 | top: 0; 16 | z-index: 11; 17 | transition: all 400ms ease-in-out; 18 | 19 | .main-header { 20 | @extend header; 21 | 22 | &.hidden { 23 | opacity: 0; 24 | } 25 | } 26 | } 27 | 28 | .search-block { 29 | @extend header; 30 | width: 0%; 31 | right: 0; 32 | background: #fff; 33 | 34 | 35 | &.active { 36 | width: 400px; 37 | 38 | input { 39 | width: 280px; 40 | } 41 | } 42 | 43 | .search-autocomplete-form { 44 | display: flex; 45 | 46 | .search-control { 47 | flex: 1; 48 | font-size: 1rem; 49 | border: 0; 50 | outline: none; 51 | padding-left: 10px; 52 | } 53 | } 54 | 55 | @media only screen and (max-width: 800px) { 56 | &.active, .search-autocomplete-form { 57 | width: 100%; 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /src/app/navbar/navbar.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { NavbarComponent } from './navbar.component'; 4 | 5 | describe('NavbarComponent', () => { 6 | let component: NavbarComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [NavbarComponent] 12 | }); 13 | fixture = TestBed.createComponent(NavbarComponent); 14 | component = fixture.componentInstance; 15 | fixture.detectChanges(); 16 | }); 17 | 18 | it('should create', () => { 19 | expect(component).toBeTruthy(); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /src/app/navbar/navbar.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'; 2 | import { FormBuilder, Validators, FormControl } from '@angular/forms'; 3 | import { Router } from '@angular/router'; 4 | import { Observable, filter, debounceTime, distinctUntilChanged, switchMap } from 'rxjs'; 5 | import { Restaurant } from '../restaurant'; 6 | import { RestaurantService } from '../restaurant.service'; 7 | 8 | @Component({ 9 | selector: 'app-navbar', 10 | templateUrl: './navbar.component.html', 11 | styleUrls: ['./navbar.component.scss'] 12 | }) 13 | export class NavbarComponent implements OnInit { 14 | username = ''; 15 | @ViewChild('searchbar') searchBar: ElementRef; 16 | 17 | toggleSearch: boolean = false; 18 | itemOptions: Observable; 19 | 20 | searchForm = this.fb.group({ 21 | query: ['', Validators.required], 22 | }); 23 | 24 | constructor( 25 | private fb: FormBuilder, 26 | private restaurantService: RestaurantService, 27 | private router: Router 28 | ) { 29 | 30 | this.itemOptions = this.search(this.searchForm.controls.query); 31 | } 32 | 33 | ngOnInit(): void { 34 | } 35 | 36 | openSearch() { 37 | this.toggleSearch = true; 38 | this.searchBar.nativeElement.focus(); 39 | } 40 | 41 | searchClose() { 42 | this.searchForm.patchValue({ 43 | query: '' 44 | }, { emitEvent: false }); 45 | this.toggleSearch = false; 46 | } 47 | 48 | itemSelected(event: any) { 49 | const item = event.option.value; 50 | if (!item || !item._id) { 51 | return; 52 | } 53 | 54 | // Workaround for https://github.com/angular/angular/issues/47813 55 | this.router.navigate(['/']).then(_ => { 56 | this.router.navigate([`/restaurants/${item._id}`]); 57 | }) 58 | 59 | this.searchClose(); 60 | } 61 | 62 | displayName(item: any) { 63 | return item.name; 64 | } 65 | 66 | private search(formControl: FormControl) { 67 | return formControl.valueChanges.pipe( 68 | filter(text => text!.length > 1), 69 | debounceTime(250), 70 | distinctUntilChanged(), 71 | switchMap(searchTerm => this.restaurantService.search(searchTerm!)), 72 | ); 73 | } 74 | } -------------------------------------------------------------------------------- /src/app/realm-app.service.ts: -------------------------------------------------------------------------------- 1 | import * as Realm from 'realm-web'; 2 | import { Injectable } from '@angular/core'; 3 | import { config } from '../config'; 4 | 5 | @Injectable({ 6 | providedIn: 'root' 7 | }) 8 | export class RealmAppService { 9 | private static app: Realm.App; 10 | 11 | async getAppInstance() { 12 | if (!RealmAppService.app) { 13 | RealmAppService.app = new Realm.App({ id: config.realmAppId }); 14 | 15 | const credentials = Realm.Credentials.anonymous(); 16 | await RealmAppService.app.logIn(credentials); 17 | } 18 | 19 | return RealmAppService.app; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/app/restaurant-details-guided/restaurant-details-guided.component.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/app/restaurant-details-guided/restaurant-details-guided.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb-developer/Google-Cloud-Sentiment-Chef/6d2e932544dc6b4ea45b5c71bbd9ebd74c93c02a/src/app/restaurant-details-guided/restaurant-details-guided.component.scss -------------------------------------------------------------------------------- /src/app/restaurant-details-guided/restaurant-details-guided.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, Output } from '@angular/core'; 2 | import { GuidedTour, Orientation, GuidedTourService } from 'ngx-guided-tour'; 3 | import { Restaurant } from '../restaurant'; 4 | import { NewReview, RawReview } from '../review'; 5 | import { BehaviorSubject } from 'rxjs'; 6 | 7 | export interface ReviewFormState { 8 | review?: Partial, 9 | attachImages?: boolean, 10 | submitReview?: boolean, 11 | } 12 | 13 | const reviews: NewReview[] = [ 14 | { 15 | name: 'Clementine', 16 | text: `Incredible place. I would love to visit again. This is a very nice restaurant with tasty creative food and attentive staff. The food is delicious, with a nice twist of the original recipes. The staff is very nice, not only they advised me on a the choice of dishes and desert, but even brought me an Ethiopian desert after I had a question. Would definitely come again!`, 17 | date: new Date().toString() 18 | }, 19 | { 20 | name: 'Mary', 21 | text: `Went here for an early dinner last night. Don't drive here. Parking is terrible. Seated promptly. No liquor license yet. We didn't enjoy it at all and the service wasn't great either. The food was mediocre.`, 22 | date: new Date().toString() 23 | }, 24 | { 25 | name: 'Joel', 26 | text: `We came here for drinks.`, 27 | date: new Date().toString() 28 | }, 29 | { 30 | name: 'Joel', 31 | text: `We came here for drinks.`, 32 | date: new Date().toString(), 33 | images: [ 34 | { 35 | fileName: 'https://i.ibb.co/pvQtyx7/fun-1.jpg', 36 | mimeType: 'image/jpeg' 37 | }, 38 | { 39 | fileName: 'https://i.ibb.co/K9SL0SR/stock-photo-1.jpg', 40 | mimeType: 'image/jpeg' 41 | }, 42 | { 43 | fileName: 'https://i.ibb.co/k4z8SGs/fun-2.jpg', 44 | mimeType: 'image/jpeg' 45 | }, 46 | ] 47 | }, 48 | ]; 49 | 50 | @Component({ 51 | selector: 'app-restaurant-details-guided', 52 | templateUrl: './restaurant-details-guided.component.html', 53 | styleUrls: ['./restaurant-details-guided.component.scss'] 54 | }) 55 | export class RestaurantDetailsGuidedComponent { 56 | currentReview: NewReview; 57 | reviewsCounter = 0; 58 | toursCounter = 0; 59 | 60 | @Input() restaurant: Restaurant; 61 | @Input() reviewFormState: BehaviorSubject = new BehaviorSubject({}); 62 | @Input() searchState: BehaviorSubject = new BehaviorSubject(''); 63 | 64 | tours: GuidedTour[] = [ 65 | { 66 | tourId: 'review-1-submit', 67 | useOrb: true, 68 | steps: [ 69 | { 70 | title: 'Restaurant Page: Unleash the full potential of Sentiment Chef!', 71 | selector: '.restaurant-name', 72 | content: 'This page is the beating heart of the Sentiment Chef demo. Click \'Next\' to embark on an exciting exploration of its features!', 73 | orientation: Orientation.Bottom, 74 | useHighlightPadding: true, 75 | }, 76 | { 77 | title: 'Restaurant Details', 78 | selector: '.restaurant-details', 79 | content: 'The information on this page, including cuisine, neighborhood, and description, is fetched from a MongoDB Atlas database.', 80 | orientation: Orientation.Bottom, 81 | useHighlightPadding: true, 82 | }, 83 | { 84 | title: 'AI-powered Reviews', 85 | selector: '.restaurant-review-form', 86 | content: 'Let\'s fill out a customer review to witness the capabilities of AI-driven sentiment analysis.', 87 | closeAction: () => this.fillOutReview(), 88 | orientation: Orientation.Right, 89 | useHighlightPadding: true 90 | }, 91 | { 92 | selector: '.restaurant-review-form', 93 | content: 'Click the \'Done\' button to submit the review and wait for the AI model to analyse it!', 94 | closeAction: () => { 95 | this.submitReview(); 96 | 97 | // Wait for the first review to be analysed 98 | setTimeout(() => { 99 | this.startNextTour(); 100 | }, 3000); 101 | }, 102 | orientation: Orientation.Right, 103 | useHighlightPadding: true 104 | }, 105 | ] 106 | }, 107 | { 108 | tourId: 'review-1-tour', 109 | steps: [ 110 | { 111 | selector: '.first-review', 112 | content: 'Gemini analysed the sentiment of your review!', 113 | orientation: Orientation.Right, 114 | useHighlightPadding: true, 115 | }, 116 | { 117 | selector: '.first-review .restaurant-review-details-header', 118 | content: 'The review has been assigned a sentiment label.', 119 | orientation: Orientation.Bottom, 120 | useHighlightPadding: true, 121 | }, 122 | { 123 | selector: '.first-review .restaurant-review-scores', 124 | content: 'The sentiment of the review has been evaluated across three distinct categories with scores from 1 to 5.', 125 | orientation: Orientation.Bottom, 126 | useHighlightPadding: true, 127 | closeAction: () => this.startNextTour(), 128 | }, 129 | ] 130 | }, 131 | 132 | { 133 | tourId: 'review-2-submit', 134 | steps: [ 135 | { 136 | selector: '.restaurant-review-form', 137 | content: 'Let\'s put the AI model to the test with a more negative review.', 138 | closeAction: () => this.fillOutReview(), 139 | orientation: Orientation.Right, 140 | useHighlightPadding: true 141 | }, 142 | { 143 | selector: '.restaurant-review-form', 144 | content: 'Click the \'Done\' button to submit the review and wait for the AI model to analyse it!', 145 | closeAction: () => { 146 | this.submitReview(); 147 | this.startNextTour(); 148 | }, 149 | orientation: Orientation.Right, 150 | useHighlightPadding: true 151 | }, 152 | ] 153 | }, 154 | 155 | { 156 | tourId: 'review-2-tour', 157 | steps: [ 158 | { 159 | selector: '.first-review', 160 | content: 'The sentiment analysis is different this time.', 161 | orientation: Orientation.Right, 162 | useHighlightPadding: true, 163 | }, 164 | { 165 | selector: '.first-review .restaurant-review-details-header', 166 | content: 'The sentiment of the review was notably negative as indicated by the AI model.', 167 | orientation: Orientation.Bottom, 168 | useHighlightPadding: true, 169 | }, 170 | { 171 | selector: '.first-review .restaurant-review-scores', 172 | content: 'The category scores are also low.', 173 | orientation: Orientation.Bottom, 174 | useHighlightPadding: true, 175 | closeAction: () => this.startNextTour(), 176 | }, 177 | ] 178 | }, 179 | 180 | { 181 | tourId: 'review-3-submit', 182 | steps: [ 183 | { 184 | selector: '.restaurant-review-form', 185 | content: 'Let\'s put the AI model to one more test.', 186 | closeAction: () => this.fillOutReview(), 187 | orientation: Orientation.Right, 188 | useHighlightPadding: true 189 | }, 190 | { 191 | selector: '.restaurant-review-form', 192 | content: 'Click the \'Done\' button to submit the review and wait for the AI model to analyse it!', 193 | closeAction: () => { 194 | this.submitReview(); 195 | this.startNextTour(); 196 | }, 197 | orientation: Orientation.Right, 198 | useHighlightPadding: true 199 | }, 200 | ] 201 | }, 202 | 203 | { 204 | tourId: 'review-3-tour', 205 | steps: [ 206 | { 207 | selector: '.first-review', 208 | content: 'This review was too succinct for the AI model to determine the sentiment. However, people quite often leave short reviews but attach images. Photos can also carry sentiment! Let\'s see what happens if we attach some photos to the same review and submit it again.', 209 | orientation: Orientation.Right, 210 | useHighlightPadding: true, 211 | closeAction: () => this.startNextTour(), 212 | }, 213 | ] 214 | }, 215 | 216 | { 217 | tourId: 'review-4-fill-out', 218 | steps: [ 219 | { 220 | selector: '.restaurant-review-form', 221 | content: 'Let\'s submit the same review but this time attach some photos to it!', 222 | closeAction: async () => { 223 | this.fillOutReview(); 224 | setTimeout(() => { 225 | this.startNextTour(); 226 | }, 3000); 227 | }, 228 | orientation: Orientation.Right, 229 | useHighlightPadding: true 230 | } 231 | ] 232 | }, 233 | 234 | { 235 | tourId: 'media-upload-tour', 236 | steps: [ 237 | { 238 | selector: '.media-upload-dialog', 239 | content: 'The attached photos may take a couple of seconds to upload. Click \'Next\' after they have been uploaded.', 240 | orientation: Orientation.Right, 241 | useHighlightPadding: true 242 | }, 243 | { 244 | selector: '.media-upload-dialog', 245 | content: 'The AI model can detect objects and sentiment in the images. It has generated a description, extracted useful tags and analysed the sentiment of the images. This data will be used to enhance the sentiment analysis of the whole review.', 246 | orientation: Orientation.Right, 247 | useHighlightPadding: true, 248 | closeAction: () => { 249 | this.attachPhotos(); 250 | this.startNextTour(); 251 | }, 252 | }, 253 | ] 254 | }, 255 | { 256 | tourId: 'review-4-submit', 257 | steps: [ 258 | { 259 | selector: '.restaurant-review-form', 260 | content: 'The images have been attached to the review. Click the \'Done\' button to submit the review and wait for the AI model to analyse it!', 261 | closeAction: () => { 262 | this.submitReview(); 263 | this.startNextTour(); 264 | }, 265 | orientation: Orientation.Right, 266 | useHighlightPadding: true 267 | } 268 | ] 269 | }, 270 | { 271 | tourId: 'review-4-tour', 272 | steps: [ 273 | { 274 | selector: '.first-review', 275 | content: 'This time, depending on the result we get from the AI model, we might see a different sentiment label for the review.', 276 | orientation: Orientation.Right, 277 | useHighlightPadding: true, 278 | closeAction: () => this.startNextTour(), 279 | }, 280 | ] 281 | }, 282 | 283 | { 284 | tourId: 'search', 285 | steps: [ 286 | { 287 | selector: '.search-form', 288 | content: 'The application uses MongoDB Atlas Search to provide a powerful search functionality. The search utilises not only the reviews text but also extracted image tags and descriptions.', 289 | orientation: Orientation.Bottom, 290 | useHighlightPadding: true, 291 | }, 292 | { 293 | selector: '.search-form', 294 | content: 'Let\'s try searching for a review with a specific keyword.', 295 | orientation: Orientation.Bottom, 296 | useHighlightPadding: true, 297 | closeAction: () => { 298 | this.search('beer'); 299 | setTimeout(() => { 300 | this.startNextTour(); 301 | }, 1000); 302 | } 303 | }, 304 | ] 305 | }, 306 | 307 | { 308 | tourId: 'search-results', 309 | steps: [ 310 | { 311 | selector: '.first-review', 312 | content: 'Even though the text doesn\'t mention beer, the AI model has detected beer in the images and extracted it as a tag. Atlas Search indexes the image tags together with the review texts. This is why the review was returned in the search results.', 313 | orientation: Orientation.Right, 314 | useHighlightPadding: true, 315 | closeAction: () => this.startNextTour(), 316 | }, 317 | ] 318 | }, 319 | 320 | { 321 | tourId: 'summarization-tour', 322 | steps: [ 323 | { 324 | selector: '.restaurant-card-summary', 325 | content: 'Final AI treat! Based on the reviews we just wrote, the AI model also generated a summary for the restaurant.', 326 | orientation: Orientation.Left, 327 | useHighlightPadding: true, 328 | }, 329 | ] 330 | }, 331 | ]; 332 | 333 | constructor( 334 | private guidedTourService: GuidedTourService, 335 | ) { 336 | } 337 | 338 | async ngOnInit(): Promise { 339 | this.startNextTour(); 340 | } 341 | 342 | private fillOutReview() { 343 | this.currentReview = reviews[this.reviewsCounter++]; 344 | this.reviewFormState.next({ review: this.currentReview }); 345 | 346 | setTimeout(() => { 347 | // wait before showing the next step in the guide 348 | }, 1000); 349 | } 350 | 351 | submitReview() { 352 | this.currentReview = { name: '', text: '', date: new Date().toString() }; 353 | this.reviewFormState.next({ submitReview: true }); 354 | } 355 | 356 | attachPhotos() { 357 | this.reviewFormState.next({ attachImages: true }); 358 | } 359 | 360 | search(query: string) { 361 | this.searchState.next(query); 362 | } 363 | 364 | private startNextTour() { 365 | setTimeout(() => { 366 | const nextTour = this.tours[this.toursCounter++]; 367 | this.guidedTourService.startTour(nextTour); 368 | }, 3000); 369 | } 370 | } 371 | -------------------------------------------------------------------------------- /src/app/restaurant-details/restaurant-details.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 | 6 |
7 |
8 |
9 | 10 | 11 | 12 |

Overview

13 |
14 |
15 | 16 | 17 |

{{ restaurant.name }}

18 | 19 |
20 |
21 |
🍽️ {{ restaurant.cuisine }}
22 |
📍 {{ restaurant.borough }}
23 |
24 | 25 | 26 |
27 | Nestled in the heart of a bustling city, the gastronomic paradise of "Flavorsome Haven" 28 | beckons food enthusiasts with 29 | its enchanting ambiance and delectable culinary offerings. 30 | As you step through the entrance, you're greeted by an elegant and modern interior that 31 | exudes a warm and inviting atmosphere. 32 |
33 |
34 | 35 | 36 | 37 |
38 |

Leave Your Review

39 |
40 | 41 |
42 |
43 | 44 |

Customer Reviews with AI Sentiment Analysis

45 | 46 |
47 | 48 | Filter reviews 49 | search 50 | 51 | 52 |
53 | 54 |
55 |
56 |
57 | 59 | {{ review.name }} 60 |
61 | 62 |
63 |
64 | 65 | 66 | Positive sentiment 67 | 🤩 68 | Negative sentiment 69 | 😢 70 | Neutral sentiment 71 | 😐 72 | 73 | 74 | Reviewed on {{review.date | date: 'mediumDate'}} 75 |
76 | 77 | {{review.text}} 78 |
79 |
80 | 81 | 82 | 83 |
84 |
85 |
86 | Food 87 | {{ review.food || 'Not specified' }} · 88 | 89 | Service 90 | {{ review.service || 'Not specified' }} · 91 | 92 | Atmosphere 93 | {{ review.interior || 'Not specified' }} 94 |
95 |
96 | 97 |
98 |
99 |
100 |
101 | 102 |
103 |
104 |
105 | 106 | 107 | 108 | 109 |

Make a Reservation

110 |
111 |
112 | 113 | 114 | 115 |
116 |
117 | 118 | 119 | MM/DD/YYYY 120 | 121 | 122 | 123 | 124 |
125 | 126 |
127 | 128 | 129 | 138 | 139 |
140 | 141 |
142 | 143 |
144 | 145 | 146 |
147 | 148 | 149 | 150 | 151 |

Rating and Scores

152 |
153 |
154 | 155 | 156 |
157 | ⭐⭐⭐⭐ 4.8/5 158 | #3 of 27,372 Restaurants in NYC 159 |
160 | 161 | 162 | 163 |
164 |
🍽️ Food⭐⭐⭐⭐⭐
165 |
💁‍♂️ Service⭐⭐⭐⭐
166 |
🎂 Atmosphere⭐⭐⭐⭐⭐
167 |
168 |
169 |
170 | 171 | 173 | 174 | 175 |

AI-Generated Summary

176 |
177 |
178 | 179 | 180 | {{ restaurant.summary }} 181 | 182 | 183 | 184 |
185 |
186 |
187 |
188 |
189 |
190 | 191 | 195 | -------------------------------------------------------------------------------- /src/app/restaurant-details/restaurant-details.component.scss: -------------------------------------------------------------------------------- 1 | .restaurant-wrapper { 2 | display: flex; 3 | flex-direction: column; 4 | max-width: 100rem; 5 | margin: -20px auto 0 auto; 6 | background: #fff; 7 | min-height: 2000px; 8 | } 9 | 10 | .restaurant-card.restaurant-card-details-page { 11 | 12 | .mat-mdc-card-header { 13 | padding-top: 0; 14 | } 15 | 16 | 17 | mat-card-title { 18 | padding-bottom: 0; 19 | } 20 | 21 | } 22 | 23 | .restaurant-description, .restaurant-review-text, .restaurant-summary { 24 | line-height: 30px; 25 | font-size: 18px; 26 | margin: 30px 0; 27 | } 28 | 29 | .restaurant-banner { 30 | position: relative; 31 | height: 500px; 32 | width: 100%; 33 | 34 | .restaurant-cover { 35 | object-fit: cover; 36 | } 37 | } 38 | 39 | .restaurant-scores-label { 40 | text-transform: uppercase; 41 | } 42 | 43 | .restaurant-scores { 44 | display: flex; 45 | flex-direction: column; 46 | width: 100%; 47 | line-height: 35px; 48 | 49 | & > div { 50 | display: flex; 51 | flex-direction: row; 52 | justify-content: space-between; 53 | } 54 | } 55 | 56 | .restaurant-rating { 57 | display: flex; 58 | flex-direction: column; 59 | margin: 20px 0; 60 | font-size: 18px; 61 | 62 | .restaurant-rating-stars { 63 | font-size: 30px; 64 | } 65 | 66 | span { 67 | margin: 10px 0; 68 | } 69 | 70 | mat-divider { 71 | margin: 20px 0; 72 | } 73 | 74 | } 75 | 76 | 77 | .restaurant-reviews { 78 | font-size: 20px; 79 | 80 | .restaurant-review { 81 | display: flex; 82 | flex-direction: row; 83 | gap: 30px; 84 | padding: 50px 0; 85 | border-bottom: 1px solid rgba(0,0,0,.12); 86 | } 87 | 88 | .restaurant-review-user { 89 | display: flex; 90 | flex-direction: column; 91 | text-align: center; 92 | color: #8e8e8e; 93 | } 94 | 95 | .restaurant-review-details { 96 | display: flex; 97 | flex-direction: column; 98 | justify-content: space-around; 99 | } 100 | 101 | .restaurant-review-details-header { 102 | display: flex; 103 | flex-direction: row; 104 | gap: 10px; 105 | } 106 | 107 | .restaurant-review-scores { 108 | font-weight: bold; 109 | margin-bottom: 20px; 110 | } 111 | } 112 | 113 | .restaurant-section-wrapper { 114 | align-self: center; 115 | 116 | .restaurant-section { 117 | width: 70rem; 118 | min-height: 100rem; 119 | display: flex; 120 | justify-content: center; 121 | flex-direction: row; 122 | margin-top: -68px; 123 | 124 | .restaurant-card-header-details, .restaurant-card-reservation { 125 | padding-left: 30px; 126 | padding-right: 30px; 127 | } 128 | 129 | .restaurant-card-header-details { 130 | width: 1000px; 131 | 132 | h1 { 133 | margin: 20px 0; 134 | font-size: 48px; 135 | line-height: 80px; 136 | font-weight: bold; 137 | } 138 | 139 | h3 { 140 | margin: 40px 0 20px 0; 141 | font-size: 32px; 142 | } 143 | 144 | .restaurant-features { 145 | display: flex; 146 | flex-direction: row; 147 | gap: 15px; 148 | font-size: 20px; 149 | margin: 20px 0; 150 | } 151 | 152 | 153 | } 154 | 155 | 156 | .restaurant-card-summary, .restaurant-card-reservation, .restaurant-card-scores { 157 | width: 350px; 158 | 159 | .mat-mdc-card-header { 160 | justify-content: center; 161 | } 162 | 163 | .mat-divider { 164 | margin-bottom: 25px; 165 | } 166 | } 167 | 168 | .restaurant-card-reservation { 169 | 170 | .restaurant-reservation-date-time { 171 | margin: 10px 0; 172 | display: flex; 173 | flex-direction: column; 174 | 175 | & > div { 176 | display: flex; 177 | flex-direction: column; 178 | } 179 | 180 | label { 181 | margin-left: 3px; 182 | margin-bottom: 5px; 183 | font-size: 16px; 184 | } 185 | } 186 | } 187 | 188 | } 189 | } 190 | 191 | 192 | .media-preview { 193 | grid-template-columns: repeat(3, 186px); 194 | } 195 | 196 | .search-form { 197 | .mat-mdc-form-field { 198 | width: 100%; 199 | } 200 | } -------------------------------------------------------------------------------- /src/app/restaurant-details/restaurant-details.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { RestaurantService } from '../restaurant.service'; 3 | import { ActivatedRoute } from '@angular/router'; 4 | import { CustomerReview, NewReview } from '../review'; 5 | import { ReviewService } from '../review.service'; 6 | import { BehaviorSubject, Observable, Subscription, debounceTime, distinctUntilChanged, filter, switchMap } from 'rxjs'; 7 | import { FormBuilder, FormControl, Validators } from '@angular/forms'; 8 | import { ReviewFormState } from '../restaurant-details-guided/restaurant-details-guided.component'; 9 | 10 | @Component({ 11 | selector: 'app-restaurant-details', 12 | templateUrl: './restaurant-details.component.html', 13 | styleUrls: ['./restaurant-details.component.scss'] 14 | }) 15 | export class RestaurantDetailsComponent { 16 | private currentId: string = ''; 17 | restaurant: any; 18 | reviews: CustomerReview[] = []; 19 | restaurantWatcher: Subscription; 20 | reviewsWatcher: Subscription; 21 | filteredReviews$: Observable; 22 | reviewFormState: BehaviorSubject = new BehaviorSubject({}); 23 | searchState: BehaviorSubject = new BehaviorSubject(''); 24 | 25 | constructor( 26 | private route: ActivatedRoute, 27 | private restaurantService: RestaurantService, 28 | private reviewService: ReviewService, 29 | private fb: FormBuilder, 30 | ) { 31 | } 32 | 33 | async ngOnInit() { 34 | this.searchState.subscribe({ 35 | next: async searchTerm => { 36 | this.searchForm.controls.query.setValue(searchTerm); 37 | } 38 | }); 39 | 40 | this.filteredReviews$ = this.search(this.searchForm.controls.query); 41 | this.filteredReviews$.subscribe({ 42 | next: async reviews => { 43 | // Stop watching for new reviews when the user starts searching 44 | this.reviewsWatcher?.unsubscribe(); 45 | this.reviews = reviews; 46 | } 47 | }); 48 | 49 | this.route.paramMap.subscribe({ 50 | next: async params => { 51 | const id = params.get('id'); 52 | if (!id) { 53 | return; 54 | } 55 | 56 | this.currentId = params.get('id')!; 57 | const item = await this.restaurantService.findOne(this.currentId); 58 | this.restaurant = item; 59 | this.reviews = await this.reviewService.listReviews(this.currentId); 60 | 61 | this.restaurantWatcher = (await this.restaurantService.getRestaurantObservable(this.currentId)).subscribe({ 62 | next: restaurant => { 63 | this.restaurant = restaurant; 64 | } 65 | }); 66 | 67 | this.reviewsWatcher = (await this.reviewService.getReviewsObservable(this.currentId)).subscribe({ 68 | next: review => { 69 | this.reviews = [review, ...this.reviews]; 70 | } 71 | }); 72 | } 73 | }); 74 | } 75 | 76 | ngOnDestroy() { 77 | this.restaurantWatcher?.unsubscribe(); 78 | this.reviewsWatcher?.unsubscribe(); 79 | } 80 | 81 | addReview(review: NewReview) { 82 | this.reviewService.insertOne(this.currentId, review); 83 | } 84 | 85 | searchForm = this.fb.group({ 86 | query: ['', Validators.required], 87 | }); 88 | 89 | private search(formControl: FormControl) { 90 | return formControl.valueChanges.pipe( 91 | filter(text => text!.length > 1), 92 | debounceTime(250), 93 | distinctUntilChanged(), 94 | switchMap(searchTerm => this.reviewService.search(this.currentId, searchTerm)), 95 | 96 | ); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/app/restaurant.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { RealmAppService } from './realm-app.service'; 3 | import { Restaurant } from './restaurant'; 4 | import { ObjectId } from './helpers/objectId'; 5 | import { fromChangeEvent } from './rxjs-operators'; 6 | import { isUpdateEvent } from './change-events'; 7 | import { filter, map } from 'rxjs'; 8 | 9 | @Injectable({ 10 | providedIn: 'root' 11 | }) 12 | export class RestaurantService { 13 | constructor(private realmAppService: RealmAppService) { } 14 | 15 | private async getCollection() { 16 | const realmApp = await this.realmAppService.getAppInstance(); 17 | 18 | const collection = realmApp?.currentUser?.mongoClient('M0')?.db('sample_restaurants')?.collection('restaurants'); 19 | 20 | if (!collection) { 21 | throw new Error('Failed to connect to Realm App'); 22 | } 23 | 24 | return collection; 25 | } 26 | 27 | async listRestaurants(limit = 24) { 28 | const collection = await this.getCollection(); 29 | 30 | return collection.aggregate([ 31 | { 32 | $sample: { size: limit } 33 | } 34 | ]) as Promise; 35 | } 36 | 37 | async findOne(id: any) { 38 | const collection = await this.getCollection(); 39 | if (!collection) { 40 | console.error('Failed to load collection.'); 41 | throw new Error('No item found.'); 42 | } 43 | 44 | return collection.findOne({ _id: new ObjectId(id) }); 45 | } 46 | 47 | async getRestaurantObservable(id: string) { 48 | const oid = new ObjectId(id); 49 | 50 | const collection = await this.getCollection(); 51 | const watcher = collection.watch({ 52 | filter: { 53 | operationType: 'update', 54 | 'fullDocument._id': oid 55 | } 56 | }); 57 | 58 | return fromChangeEvent(watcher) 59 | .pipe( 60 | filter(isUpdateEvent), 61 | map(event => ({...event.fullDocument})) 62 | ) 63 | } 64 | 65 | async search(query: string) { 66 | const collection = await this.getCollection(); 67 | 68 | return collection?.aggregate([ 69 | { 70 | $search: { 71 | index: 'restaurants', 72 | autocomplete: { 73 | path: 'name', 74 | query, 75 | } 76 | } 77 | }, 78 | { 79 | $limit: 5 80 | }, 81 | { 82 | $project: { 83 | _id: 1, 84 | name: 1, 85 | } 86 | } 87 | ]) as Promise; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/app/restaurant.ts: -------------------------------------------------------------------------------- 1 | import { BSON } from 'realm-web'; 2 | import { Grade } from './grade'; 3 | import { Address } from './address'; 4 | 5 | export interface Restaurant { 6 | _id: string | BSON.ObjectId; 7 | name: string; 8 | imageURL: string; 9 | borough: string; 10 | cuisine: string; 11 | grades: Grade[]; 12 | address: Address; 13 | } 14 | -------------------------------------------------------------------------------- /src/app/restaurants-list-guided/restaurants-list-guided.component.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/restaurants-list-guided/restaurants-list-guided.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb-developer/Google-Cloud-Sentiment-Chef/6d2e932544dc6b4ea45b5c71bbd9ebd74c93c02a/src/app/restaurants-list-guided/restaurants-list-guided.component.scss -------------------------------------------------------------------------------- /src/app/restaurants-list-guided/restaurants-list-guided.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { GuidedTour, GuidedTourService, Orientation } from 'ngx-guided-tour'; 4 | import { Restaurant } from '../restaurant'; 5 | 6 | @Component({ 7 | selector: 'app-restaurants-list-guided', 8 | templateUrl: './restaurants-list-guided.component.html', 9 | styleUrls: ['./restaurants-list-guided.component.scss'] 10 | }) 11 | export class RestaurantsListGuidedComponent { 12 | @Input() restaurants: Restaurant[]; 13 | 14 | dashboardTour: GuidedTour = { 15 | tourId: 'restaurants-tour', 16 | useOrb: true, 17 | steps: [ 18 | { 19 | title: 'Welcome to Sentiment Chef!', 20 | selector: '.primary-header', 21 | content: 'Learn how to analyze the sentiment of restaurant reviews, extract information from images and videos and perform full-text search.', 22 | orientation: Orientation.Bottom 23 | }, 24 | { 25 | title: 'Select a Restaurant', 26 | selector: '.first', 27 | content: 'To get started, let\'s navigate to the first restaurant in the list.', 28 | closeAction: () => this.goToFirstRestaurant(), 29 | orientation: Orientation.Right 30 | }, 31 | ] 32 | }; 33 | 34 | constructor( 35 | private guidedTourService: GuidedTourService, 36 | private router: Router, 37 | ) { 38 | } 39 | 40 | async ngOnInit(): Promise { 41 | setTimeout(() => { 42 | this.guidedTourService.startTour(this.dashboardTour); 43 | }, 1000); 44 | } 45 | 46 | goToFirstRestaurant() { 47 | this.router.navigate(['/restaurants/', this.restaurants[0]._id.toString()]); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/app/restaurants-list/restaurants-list.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Sentiment Chef

3 |

AI-Driven Sentiment Analysis, Summarization, Image Tagging and Search for Restaurant Reviews

4 |

Powered by MongoDB Atlas and Gemini — Google's next generation AI model

5 |
6 | 7 |
8 | 13 | 14 | {{ restaurant.name }} 15 | 16 | Cuisine: {{ restaurant.cuisine }} 17 | Rating: ⭐⭐⭐⭐⭐ 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 35 | 36 | 37 | 38 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | Go to restaurant 55 | 56 | 57 |
58 | 59 | -------------------------------------------------------------------------------- /src/app/restaurants-list/restaurants-list.component.scss: -------------------------------------------------------------------------------- 1 | mat-card-title a { 2 | margin-right: 8px; 3 | color: inherit; 4 | line-height: 18px; 5 | text-decoration: none; 6 | } -------------------------------------------------------------------------------- /src/app/restaurants-list/restaurants-list.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { RestaurantService } from '../restaurant.service'; 3 | import { Restaurant } from '../restaurant'; 4 | 5 | @Component({ 6 | selector: 'app-restaurants-list', 7 | templateUrl: './restaurants-list.component.html', 8 | styleUrls: ['./restaurants-list.component.scss'] 9 | }) 10 | export class RestaurantsListComponent { 11 | restaurants: Restaurant[] = []; 12 | 13 | 14 | constructor( 15 | private restaurantService: RestaurantService, 16 | ) { 17 | } 18 | 19 | async ngOnInit(): Promise { 20 | this.restaurants = await this.restaurantService.listRestaurants(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/app/review-form/review-form.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | Name 4 | 5 | 6 | 7 | 8 | Review 9 | 10 | 11 | 12 |
13 |
14 |
Drag and drop your images and videos here
15 |
16 |
17 | 18 |
19 | 20 | 21 |
22 | 23 | 25 |
26 | -------------------------------------------------------------------------------- /src/app/review-form/review-form.component.scss: -------------------------------------------------------------------------------- 1 | .review-form { 2 | display: flex; 3 | flex-direction: column; 4 | } 5 | 6 | .submit-review { 7 | padding: 27px 0; 8 | font-size: 20px; 9 | border-radius: 30px; 10 | } 11 | 12 | .dropzone { 13 | border-radius: 6px; 14 | min-height: 100px; 15 | min-width: 400px; 16 | display: table; 17 | width: 100%; 18 | background-color: #eee; 19 | border: dotted 1px #aaa; 20 | 21 | .text-wrapper { 22 | display: table-cell; 23 | vertical-align: middle; 24 | 25 | div { 26 | font-weight: bold; 27 | text-align: center; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/app/review-form/review-form.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; 2 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 3 | import { BehaviorSubject } from 'rxjs'; 4 | 5 | import { RawReview } from '../review'; 6 | import { CdkTextareaAutosize } from '@angular/cdk/text-field'; 7 | import { MatDialog, MatDialogRef } from '@angular/material/dialog'; 8 | import { MediaUploadDialogComponent } from '../media-upload-dialog/media-upload-dialog.component'; 9 | import { UploadedMedia } from '../uploaded-media'; 10 | import { FileHandle, FileHandleService } from '../file-handle.service'; 11 | import { ReviewFormState } from '../restaurant-details-guided/restaurant-details-guided.component'; 12 | 13 | @Component({ 14 | selector: 'app-review-form', 15 | templateUrl: './review-form.component.html', 16 | styleUrls: ['./review-form.component.scss'] 17 | }) 18 | export class ReviewFormComponent implements OnInit { 19 | @Input() 20 | state: BehaviorSubject; 21 | 22 | @Output() 23 | formValuesChanged = new EventEmitter(); 24 | 25 | @Output() 26 | formSubmitted = new EventEmitter(); 27 | 28 | @ViewChild('autosize') autosize: CdkTextareaAutosize; 29 | 30 | reviewForm: FormGroup; 31 | 32 | uploadImagesDialog: MatDialogRef; 33 | 34 | get name() { return this.reviewForm.get('name')!; } 35 | get text() { return this.reviewForm.get('text')!; } 36 | 37 | constructor( 38 | public dialog: MatDialog, 39 | private fb: FormBuilder, 40 | private fileHandleService: FileHandleService 41 | ) { } 42 | 43 | ngOnInit(): void { 44 | this.reviewForm = this.fb.group({ 45 | name: [ '', [Validators.required] ], 46 | text: [ '', [ Validators.required, Validators.minLength(10) ] ], 47 | images: [ [] ], 48 | }); 49 | 50 | this.state.subscribe(async ({ review, attachImages, submitReview }) => { 51 | if (review) { 52 | this.reviewForm = this.fb.group({ 53 | name: [ review.name, [Validators.required] ], 54 | text: [ review.text, [ Validators.required, Validators.minLength(10) ] ], 55 | images: [ review.images ], 56 | }); 57 | 58 | if (review.images?.length) { 59 | const images = review.images; 60 | const fileHandles = []; 61 | 62 | for (let image of images) { 63 | const fileHandle = await this.fileHandleService.fileFromUrl(image.fileName, image.mimeType); 64 | fileHandles.push(fileHandle); 65 | } 66 | 67 | this.filesDropped(fileHandles); 68 | } 69 | } 70 | 71 | if (attachImages) { 72 | const result = this.uploadImagesDialog.componentInstance.uploadedImages; 73 | this.uploadImagesDialog.close(result); 74 | this.uploadedImages = result; 75 | this.uploading = false; 76 | } 77 | 78 | if (submitReview) { 79 | this.submitForm(); 80 | } 81 | }); 82 | } 83 | 84 | submitForm() { 85 | this.formSubmitted.emit({ 86 | ...this.reviewForm.value, 87 | date: new Date(), 88 | images: this.uploadedImages 89 | }); 90 | 91 | this.reviewForm.reset(); 92 | this.resetUploader(); 93 | 94 | this.reviewForm.markAsUntouched(); 95 | Object.keys(this.reviewForm.controls).forEach((name) => { 96 | let control = this.reviewForm.controls[name]; 97 | control.setErrors(null); 98 | }); 99 | } 100 | 101 | fileHandles: FileHandle[] = []; 102 | uploadedImages: Array = []; 103 | uploading = false; 104 | 105 | filesDropped(fileHandles: FileHandle[]): void { 106 | this.uploading = true; 107 | this.uploadImagesDialog = this.dialog.open(MediaUploadDialogComponent, { 108 | data: { fileHandles }, 109 | disableClose: true, 110 | }); 111 | 112 | this.uploadImagesDialog.afterClosed().subscribe(result => { 113 | this.uploadedImages = result; 114 | this.uploading = false; 115 | }); 116 | } 117 | 118 | resetUploader() { 119 | this.fileHandles = []; 120 | this.uploadedImages = []; 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/app/review.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { RealmAppService } from './realm-app.service'; 3 | import { CustomerReview, NewReview, RawReview } from './review'; 4 | import { ObjectId } from './helpers/objectId'; 5 | import { filter, map, tap } from 'rxjs'; 6 | import { fromChangeEvent } from './rxjs-operators'; 7 | import { isInsertEvent } from './change-events'; 8 | 9 | @Injectable({ 10 | providedIn: 'root' 11 | }) 12 | export class ReviewService { 13 | constructor(private realmAppService: RealmAppService) { } 14 | 15 | private async getWriteCollection() { 16 | const realmApp = await this.realmAppService.getAppInstance(); 17 | 18 | const collection = realmApp?.currentUser?.mongoClient('M0')?.db('sample_restaurants')?.collection('raw_reviews'); 19 | 20 | if (!collection) { 21 | throw new Error('Failed to connect to Realm App'); 22 | } 23 | 24 | return collection; 25 | } 26 | 27 | private async getReadCollection() { 28 | const realmApp = await this.realmAppService.getAppInstance(); 29 | 30 | const collection = realmApp?.currentUser?.mongoClient('M0')?.db('sample_restaurants')?.collection('processed_reviews'); 31 | 32 | if (!collection) { 33 | throw new Error('Failed to connect to Realm App'); 34 | } 35 | 36 | return collection; 37 | } 38 | 39 | async listReviews(restaurantId: any, limit = 5) { 40 | const collection = await this.getReadCollection(); 41 | const oId = new ObjectId(restaurantId); 42 | 43 | return collection.aggregate([ 44 | { $match: { restaurant_id: oId } }, 45 | { $sort: { date: -1 } }, 46 | { $limit: limit }, 47 | ]) as Promise; 48 | } 49 | 50 | async getReviewsObservable(restarauntId: string) { 51 | const oid = new ObjectId(restarauntId); 52 | 53 | const collection = await this.getReadCollection(); 54 | const watcher = collection.watch({ 55 | filter: { 56 | operationType: 'insert', 57 | 'fullDocument.restaurant_id': oid 58 | } 59 | }); 60 | 61 | return fromChangeEvent(watcher) 62 | .pipe( 63 | filter(isInsertEvent), 64 | map(event => ({ ...event.fullDocument })), 65 | tap(review => console.log('New review:', review)) 66 | ) 67 | } 68 | 69 | async insertOne(restarauntId: string, review: NewReview) { 70 | const reviewToInsert: RawReview = { 71 | _id: new ObjectId(), 72 | restaurant_id: new ObjectId(restarauntId), 73 | ...review 74 | }; 75 | 76 | const collection = await this.getWriteCollection(); 77 | collection.insertOne(reviewToInsert); 78 | } 79 | 80 | 81 | async search(restaurant_id: string, query: string) { 82 | const pipeline = [ 83 | { 84 | $search: { 85 | index: "reviews", 86 | compound: { 87 | must: { 88 | text: { 89 | query, 90 | path: { 91 | wildcard: "*" 92 | } 93 | } 94 | }, 95 | filter: { 96 | equals: { 97 | path: 'restaurant_id', 98 | value: new ObjectId(restaurant_id) 99 | } 100 | } 101 | } 102 | } 103 | } 104 | ] 105 | 106 | const collection = await this.getReadCollection(); 107 | return collection.aggregate(pipeline) as Promise; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/app/review.ts: -------------------------------------------------------------------------------- 1 | import { BSON } from 'realm-web'; 2 | import { UploadedMedia } from './uploaded-media'; 3 | 4 | export interface NewReview { 5 | name: string; 6 | text: string; 7 | date: string; 8 | images?: { fileName: string, mimeType: string }[]; 9 | tags?: string[]; 10 | } 11 | 12 | export interface RawReview extends NewReview { 13 | _id: string | BSON.ObjectId; 14 | restaurant_id: string | BSON.ObjectId; 15 | } 16 | 17 | export interface CustomerReview extends RawReview { 18 | sentiment: string; 19 | food: number; 20 | service: number; 21 | interior: number; 22 | total: number; 23 | images: UploadedMedia[]; 24 | } 25 | -------------------------------------------------------------------------------- /src/app/rxjs-operators.ts: -------------------------------------------------------------------------------- 1 | import { from, Observable } from 'rxjs'; 2 | 3 | export function fromChangeEvent(source: AsyncGenerator>) 4 | : Observable> { 5 | 6 | return new Observable(subscriber => { 7 | const subscription = from(source).subscribe({ 8 | next(value) { 9 | subscriber.next(value); 10 | }, 11 | error(error) { 12 | subscriber.error(error); 13 | }, 14 | complete() { 15 | subscriber.complete(); 16 | } 17 | }) 18 | 19 | return () => { 20 | // Stop the collection watcher 21 | source.return(undefined); 22 | 23 | subscription.unsubscribe(); 24 | }; 25 | }); 26 | } -------------------------------------------------------------------------------- /src/app/uploaded-media.ts: -------------------------------------------------------------------------------- 1 | export interface UploadedMedia { 2 | fileName: string; 3 | mimeType: string; 4 | description: string; 5 | tags: string[]; 6 | sentiment: string; 7 | } 8 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb-developer/Google-Cloud-Sentiment-Chef/6d2e932544dc6b4ea45b5c71bbd9ebd74c93c02a/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | export const config = { 2 | realmAppId: "", 3 | imgixDomain: "", 4 | reviewImagesBucket: "", 5 | }; 6 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb-developer/Google-Cloud-Sentiment-Chef/6d2e932544dc6b4ea45b5c71bbd9ebd74c93c02a/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Sentiment Chef 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 2 | 3 | import { AppModule } from './app/app.module'; 4 | 5 | 6 | platformBrowserDynamic().bootstrapModule(AppModule) 7 | .catch(err => console.error(err)); 8 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | 3 | @import '../node_modules/ngx-guided-tour/scss/guided-tour-base-theme.scss'; 4 | 5 | ngx-guided-tour .tour-step .tour-title { 6 | padding: 0 !important; 7 | } 8 | 9 | html, 10 | body { 11 | height: 100%; 12 | } 13 | 14 | body { 15 | margin: 0; 16 | color: #2d333f; 17 | } 18 | 19 | body, 20 | span, 21 | p, 22 | .mat-mdc-card, 23 | .mat-h3, 24 | .mat-subtitle-1, 25 | .mat-typography .mat-h3, 26 | .mat-typography .mat-subtitle-1, 27 | .mat-typography h3, 28 | .mat-h2, 29 | .mat-headline-6, 30 | .mat-typography .mat-h2, 31 | .mat-typography .mat-headline-6, 32 | .mat-typography h2, 33 | .mat-body, 34 | .mat-body-2, 35 | .mat-typography .mat-body, 36 | .mat-typography .mat-body-2, 37 | .mat-typography, 38 | ngx-guided-tour .tour-step .tour-buttons .next-button { 39 | font-family: "Euclid Circular A", Roboto, "Helvetica Neue", sans-serif; 40 | } 41 | 42 | ngx-guided-tour .tour-step .tour-buttons .next-button { 43 | background-color: #3F51B9; 44 | color: #ffffff; 45 | padding: 4px 0; 46 | 47 | &:hover { 48 | background-color: #616ebc; 49 | } 50 | } 51 | 52 | ngx-guided-tour .tour-step .tour-buttons .next-button { 53 | border-radius: 15px !important; 54 | } 55 | 56 | .center { 57 | text-align: center; 58 | } 59 | 60 | .content-wrapper { 61 | padding: 20px 70px; 62 | display: block; 63 | background: #fafafa; 64 | } 65 | 66 | .text-accent { 67 | color: orange; 68 | } 69 | 70 | .positive-text { 71 | color: green; 72 | } 73 | 74 | .negative-text { 75 | color: red; 76 | } 77 | 78 | .neutral-text { 79 | color: grey; 80 | } 81 | 82 | .restaurant-card { 83 | width: 600px; 84 | margin: 0 30px 40px 0; 85 | 86 | mat-card-title { 87 | padding: 20px; 88 | font-size: 36px; 89 | margin-top: 20px; 90 | } 91 | 92 | .restaurant-card-details>span, 93 | mat-card-actions>a { 94 | padding: 0 20px; 95 | font-size: 20px; 96 | line-height: 36px; 97 | font-weight: lighter; 98 | } 99 | } 100 | 101 | .restaurant-card-wrapper { 102 | display: flex; 103 | flex-direction: row; 104 | flex-wrap: wrap; 105 | justify-content: center; 106 | align-items: center; 107 | gap: 40px; 108 | 109 | .restaurant-card-details { 110 | display: flex; 111 | flex-direction: column; 112 | } 113 | } 114 | 115 | .cropped { 116 | object-fit: cover; 117 | margin: 10px 0; 118 | } 119 | 120 | .img-link { 121 | cursor: pointer; 122 | } 123 | 124 | .text-label { 125 | font-weight: bold; 126 | } 127 | 128 | .cdk-overlay-container { 129 | margin-top: 4px; 130 | } 131 | 132 | .primary-header { 133 | background: #F9EBFF; 134 | color: #00684A; 135 | padding: 35px 0 35px 12%; 136 | margin: -20px -70px 50px -70px; 137 | 138 | h1 { 139 | font-size: 64px; 140 | line-height: 72px; 141 | font-family: 'MongoDB Value Serif'; 142 | } 143 | 144 | h2 { 145 | font-size: 18px; 146 | line-height: 32px; 147 | color: #001E2B; 148 | font-weight: lighter; 149 | } 150 | 151 | @media only screen and (max-width: 400px) { 152 | padding: 35px; 153 | 154 | h1 { 155 | font-size: 45px; 156 | text-align: center; 157 | } 158 | 159 | h2 { 160 | display: none; 161 | } 162 | } 163 | } 164 | 165 | .media-preview { 166 | margin: 20px 0; 167 | grid-gap: 16px 16px; 168 | display: grid; 169 | grid-template-columns: repeat(4, 186px); 170 | 171 | } 172 | 173 | .text-bold { 174 | font-weight: bold; 175 | } 176 | -------------------------------------------------------------------------------- /tsconfig.app.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/app", 6 | "types": [] 7 | }, 8 | "files": [ 9 | "src/main.ts" 10 | ], 11 | "include": [ 12 | "src/**/*.d.ts" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "baseUrl": "./", 6 | "outDir": "./dist/out-tsc", 7 | "forceConsistentCasingInFileNames": true, 8 | "strict": true, 9 | "noImplicitOverride": true, 10 | "noPropertyAccessFromIndexSignature": true, 11 | "noImplicitReturns": true, 12 | "noFallthroughCasesInSwitch": true, 13 | "sourceMap": true, 14 | "declaration": false, 15 | "downlevelIteration": true, 16 | "experimentalDecorators": true, 17 | "moduleResolution": "node", 18 | "importHelpers": true, 19 | "target": "ES2022", 20 | "module": "ES2022", 21 | "useDefineForClassFields": false, 22 | "lib": [ 23 | "ES2022", 24 | "dom" 25 | ], 26 | "allowSyntheticDefaultImports": true, 27 | "strictPropertyInitialization": false 28 | }, 29 | "angularCompilerOptions": { 30 | "enableI18nLegacyMessageIdFormat": false, 31 | "strictInjectionParameters": true, 32 | "strictInputAccessModifiers": true, 33 | "strictTemplates": true 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/spec", 6 | "types": [ 7 | "jasmine" 8 | ] 9 | }, 10 | "include": [ 11 | "src/**/*.spec.ts", 12 | "src/**/*.d.ts" 13 | ] 14 | } 15 | --------------------------------------------------------------------------------