Initial Code Commit

This commit is contained in:
2025-10-24 02:07:59 -04:00
commit f099f36838
63 changed files with 4425 additions and 0 deletions

View File

@@ -0,0 +1,100 @@
// @ts-nocheck
import { NextResponse } from 'next/server';
import { CosmosClient } from "@azure/cosmos";
const cosmosClient = new CosmosClient({
endpoint: process.env.COSMOS_ENDPOINT!,
key: process.env.COSMOS_KEY!
});
const database = cosmosClient.database(process.env.COSMOS_DATABASE_ID!);
const container = database.container(process.env.COSMOS_CONTAINER_ID!);
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const id = searchParams.get('id');
console.log("Received GET request with id:", id);
try {
if (id) {
// Get a single building
console.log("Attempting to get building with id:", id);
const querySpec = {
query: "SELECT * FROM c WHERE c.id = @id",
parameters: [{ name: "@id", value: id }]
};
const { resources } = await container.items.query(querySpec).fetchAll();
console.log("Query result:", resources);
if (resources && resources.length > 0) {
console.log("Returning resource for id:", id);
return NextResponse.json(resources[0]);
} else {
console.log("Building not found for id:", id);
return NextResponse.json({ message: "Building not found" }, { status: 404 });
}
} else {
// Get all buildings
console.log("Attempting to get all buildings");
const { resources } = await container.items.readAll().fetchAll();
console.log("Number of buildings retrieved:", resources.length);
return NextResponse.json(resources);
}
} catch (error) {
console.error("Error in GET request:", error);
return NextResponse.json({ message: "Error fetching data", error }, { status: 500 });
}
}
// function deepMerge(target: any, source: any) {
// for (const key in source) {
// if (Array.isArray(source[key])) {
// if (!target[key]) target[key] = [];
// target[key] = [...target[key], ...source[key]];
// } else if (source[key] instanceof Object && key in target) {
// deepMerge(target[key], source[key]);
// } else {
// target[key] = source[key];
// }
// }
// return target;
// }
export async function PATCH(request: Request) {
try {
const { id, operation, ...data } = await request.json();
// Query for the existing item
const querySpec = {
query: "SELECT * FROM c WHERE c.id = @id",
parameters: [{ name: "@id", value: id }]
};
const { resources } = await container.items.query(querySpec).fetchAll();
let existingItem = resources[0] || { id };
if (operation === 'deleteWasteEntry') {
// Remove the waste entry at the specified index
const index = data.index;
existingItem.wasteGeneration.splice(index, 1);
} else {
// Deep merge the existing data with the new data
existingItem = { ...existingItem, ...data };
}
// Upsert the item
const { resource: result } = await container.items.upsert(existingItem);
console.log("Update successful. Result:", result);
return NextResponse.json({ message: "Building updated successfully", result });
} catch (error) {
return NextResponse.json({ message: "Error updating data", error }, { status: 500 });
}
}

74
Project/app/api/chat/route.ts Executable file
View File

@@ -0,0 +1,74 @@
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
try {
const { imageURL, type } = await request.json();
if (!imageURL) {
return NextResponse.json({ error: "No image URL provided" }, { status: 400 });
}
const payload = {
messages: [
{
role: "user",
content: [
{
type: "text",
text: ` Analyze the following ${type} bill image and extract the following information:
1. Multiple data points of usage, each with a date and ${type === 'gas' ? 'therms' : 'kWh'} used
2. Any other relevant usage data
Format the output as a JSON object with an array of data points and any additional data.
You must output valid JSON in the following format, or an empty array if no data is found:
{
"dataPoints": [
{
"date": "<ISO 8601 date string>",
"usage": <number>
},
// ... more data points
]
}
`
},
{
type: "image_url",
image_url: {
url: imageURL
}
}
]
}
],
temperature: 0.4,
top_p: 0.95,
max_tokens: 1000
};
const response = await fetch(process.env.AZURE_OPENAI_ENDPOINT as string, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-key': process.env.AZURE_OPENAI_KEY as string,
},
body: JSON.stringify(payload),
});
console.log('CHAT RESPONSE', response);
if (!response.ok) {
throw new Error('Failed to generate description: ' + response.status + " " + response.statusText);
}
const data = await response.json();
const description = data.choices[0].message.content;
console.log("CHAT DESCRIPTION", description);
return NextResponse.json({ response: description });
} catch (error) {
console.error('Error processing chat:', error);
return NextResponse.json({ error: (error as Error).message }, { status: 500 });
}
}

View File

@@ -0,0 +1,43 @@
// @ts-nocheck
import { NextRequest, NextResponse } from 'next/server';
import { toBase64 } from 'openai/core';
export async function POST(request: NextRequest) {
try {
const formData = await request.formData();
let res = await fetch(process.env.PDF_URI, {
method: 'POST',
body: formData
});
res = await res.json();
const pdfBuffer = await res[0];
let b64 = await toBase64(pdfBuffer);
console.log(b64);
console.log(request);
// Step 2: Use the image with the chat route
const chatResponse = await fetch(process.env.PROD_URL + '/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
imageURL: `data:image/png;base64,${b64}`,
type: formData.get('type'),
}),
});
const chatData = await chatResponse.json();
console.log("CHAT RESPONSE", chatData);
return NextResponse.json({ message: 'PDF converted successfully', response: chatData });
} catch (error) {
console.error('Error processing PDF:', error);
return NextResponse.json({ error: 'Failed to process PDF' }, { status: 500 });
}
}