Skip to content

Commit

Permalink
Gemini generates tips for all rooms
Browse files Browse the repository at this point in the history
  • Loading branch information
srgtuszy committed Oct 28, 2024
1 parent 3ad8f6c commit 67397f0
Show file tree
Hide file tree
Showing 5 changed files with 121 additions and 45 deletions.
4 changes: 2 additions & 2 deletions dashboard/hotel-dashboard/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const geistMono = localFont({
});

export const metadata: Metadata = {
title: "Create Next App",
title: "Hotel Dashboard",
description: "Generated by create next app",
};

Expand All @@ -26,7 +26,7 @@ export default function RootLayout({
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-black`}
>
{children}
</body>
Expand Down
55 changes: 54 additions & 1 deletion emulator/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
<!-- Include Material Design Lite CSS -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<!-- Include Firebase SDK -->
<!-- Include Firebase SDKs -->
<script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-firestore-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-functions-compat.js"></script>
<!-- Include Material Design Lite JS -->
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<style>
Expand Down Expand Up @@ -73,6 +74,10 @@
<div class="page-content">
<!-- Buttons -->
<div class="emulator-button">
<div>
<label for="emulator-checkbox">Use Firebase Emulator:</label>
<input type="checkbox" id="emulator-checkbox">
</div>
<button id="emulateButton" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored">
Start Emulating
</button>
Expand All @@ -85,6 +90,10 @@
<button id="removeRoomsButton" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect">
Remove All Rooms
</button>
<button id="generateTipsButton" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect">
<i id="generateTipsIcon" class="material-icons">lightbulb</i>
<span id="generateTipsText">Generate Tips</span>
</button>
</div>
<!-- Spinner -->
<div class="spinner">
Expand Down Expand Up @@ -117,10 +126,27 @@
var isEmulating = false;
var emulateInterval;

const app = firebase.initializeApp(firebaseConfig);

// Get a reference to the Firebase Functions service
const functions = firebase.functions();

var emulateButton = document.getElementById('emulateButton');
var clearButton = document.getElementById('clearButton');
var spinner = document.querySelector('.spinner');
var entityList = document.getElementById('entityList');
// Enable or disable functions emulator based on checkbox state
document.getElementById('emulator-checkbox').addEventListener('change', function() {
if (this.checked) {
functions.useEmulator("localhost", 5001);
db.useEmulator("localhost", 8081);
console.log("Emulator enabled");
} else {
functions.useEmulator(null, 0);
db.useEmulator(null, 0);
console.log("Emulator disabled");
}
});

emulateButton.addEventListener('click', function() {
if (!isEmulating) {
Expand Down Expand Up @@ -272,6 +298,33 @@
darkModeSwitch.addEventListener('change', function() {
document.body.classList.toggle('mdl-theme--dark');
});

var generateTipsButton = document.getElementById('generateTipsButton');
var generateTipsIcon = document.getElementById('generateTipsIcon');
var generateTipsText = document.getElementById('generateTipsText');

generateTipsButton.addEventListener('click', function() {
// Disable the button and show loading spinner
generateTipsButton.disabled = true;
generateTipsIcon.textContent = 'hourglass_empty';
generateTipsText.textContent = 'Generating Tips...';

// Invoke the Firebase function
var triggerGenerateTips = firebase.functions().httpsCallable('triggerGenerateTips');
triggerGenerateTips()
.then(function(result) {
console.log('Tips generated successfully');
})
.catch(function(error) {
console.error('Error generating tips:', error);
})
.finally(function() {
// Enable the button and restore the original icon and text
generateTipsButton.disabled = false;
generateTipsIcon.textContent = 'lightbulb';
generateTipsText.textContent = 'Generate Tips';
});
});
</script>
</body>
</html>
50 changes: 45 additions & 5 deletions functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,13 @@ const schema = {
description: "The tip value",
nullable: false,
},
roomNumber: {
type: SchemaType.INTEGER,
description: "The room number the tip is for",
nullable: false,
},
},
required: ["tip"],
required: ["tip", "roomNumber"],
},
};

Expand All @@ -37,7 +42,10 @@ onInit(() => {
});
});

exports.triggerGenerateTips = onCall({cors: true}, async (data, context) => {
exports.triggerGenerateTips = onCall({
cors: true,
timeoutSeconds: 540 // Extend the timeout to 9 minutes (540 seconds)
}, async (data, context) => {
console.log("Generating tips");
const tips = await generateTips();
const tipsCollection = db.collection("tips");
Expand All @@ -50,12 +58,14 @@ exports.triggerGenerateTips = onCall({cors: true}, async (data, context) => {

async function generateTips() {
console.log('Generating tips using Gemini...');
const table = await collectionToTable(db.collection("electricity"));
const table = await allRoomMeasurementsToTable();
console.log(table);
const prompt = `
Given the following electricity measurements: ${table}. The kwh means kilowatt hours and the date is the date of the measurement.
Given the following electricity and water measurements: ${table}. The unit for electricity samples is Watts and for water samples is Liters.
Please provide several tips on how the user can increase sustainability. The tips should be concise and actionable. Each tip should refer to concrete
measurements that the user can take to reduce their electricity consumption. Reference those measurements in the tips. Mention if the energy usage is too high or too low.`;
measurements that the user can take to reduce their electricity consumption. Reference those measurements in the tips. Mention if the energy usage is too high or too low.
The tips should be individual for every room number mentioned in the measurements.
`;
try {
const result = await model.generateContent(prompt);
const generatedText = result.response.text();
Expand All @@ -69,6 +79,36 @@ async function generateTips() {
}
}

async function roomMeasurementsToTable(roomId) {
const roomRef = db.collection('rooms').doc(roomId);
const measurementsSnapshot = await roomRef.collection('measurements').get();

let table = '';

measurementsSnapshot.forEach((doc) => {
const measurement = doc.data();
table += `date: ${measurement.date.toDate().toLocaleString('en-US', { timeZone: 'UTC' })}\n`;
table += `type: "${measurement.type}"\n`;
table += `value: ${measurement.value}\n\n`;
});

return table;
}

async function allRoomMeasurementsToTable() {
const roomsSnapshot = await db.collection('rooms').get();

let allTables = '';

for (const roomDoc of roomsSnapshot.docs) {
const roomId = roomDoc.id;
const roomTable = await roomMeasurementsToTable(roomId);
allTables += `Room Number: ${roomDoc.data().roomNumber}\n${roomTable}\n`;
}

return allTables;
}

async function collectionToTable(collectionRef) {
const snapshot = await collectionRef.get();
const documents = snapshot.docs.map(doc => doc.data());
Expand Down
55 changes: 19 additions & 36 deletions functions/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"dependencies": {
"@google/generative-ai": "^0.21.0",
"firebase-admin": "^12.6.0",
"firebase-functions": "^6.0.1",
"firebase-functions": "^6.1.0",
"node-fetch": "^3.3.2"
},
"devDependencies": {
Expand Down

0 comments on commit 67397f0

Please sign in to comment.