Skip to content

Commit

Permalink
Merge pull request #199 from mikepsinn/develop
Browse files Browse the repository at this point in the history
Global variable search, conversation to measurements, better date identification in statement2measurments
  • Loading branch information
mikepsinn authored May 3, 2024
2 parents b217262 + 809b6a1 commit 42a5731
Show file tree
Hide file tree
Showing 35 changed files with 540 additions and 684 deletions.
17 changes: 9 additions & 8 deletions apps/nextjs/app/api/conversation2measurements/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,37 @@ import { NextRequest, NextResponse } from 'next/server';
import { conversation2measurements } from "@/lib/conversation2measurements";
import {postMeasurements} from "@/lib/dfda";
import {getUserId} from "@/lib/getUserId";
import {handleError} from "@/lib/errorHandler";

export async function POST(request: NextRequest) {
let { statement, localDateTime, previousStatements } = await request.json();
let { statement, utcDateTime, timeZoneOffset, previousStatements } = await request.json();

try {
const measurements = await conversation2measurements(statement, localDateTime, previousStatements);
const measurements = await conversation2measurements(statement, utcDateTime, timeZoneOffset, previousStatements);
const userId = await getUserId();
if(userId){
await postMeasurements(measurements, userId)
}
return NextResponse.json({ success: true, measurements: measurements });
} catch (error) {
console.error('Error in conversation2measurements:', error);
return NextResponse.json({ success: false, message: 'Error in conversation2measurements' });
return handleError(error, "conversation2measurements")
}
}

export async function GET(req: NextRequest) {
const urlParams = Object.fromEntries(new URL(req.url).searchParams);
const statement = urlParams.statement as string;
const previousStatements = urlParams.previousStatements as string | null | undefined;
const localDateTime = urlParams.localDateTime as string | null | undefined;
let timeZoneOffset;
if(urlParams.timeZoneOffset){timeZoneOffset = parseInt(urlParams.timeZoneOffset);}
const utcDateTime = urlParams.utcDateTime as string | null | undefined;

try {
const measurements = await conversation2measurements(statement, localDateTime, previousStatements);
const measurements = await conversation2measurements(statement, utcDateTime, timeZoneOffset, previousStatements);
const userId = await getUserId();
if(userId){await postMeasurements(measurements, userId)}
return NextResponse.json({ success: true, measurements: measurements });
} catch (error) {
console.error('Error sending request to OpenAI:', error);
return NextResponse.json({ success: false, message: 'Error sending request to OpenAI' });
return handleError(error, "conversation2measurements")
}
}
4 changes: 2 additions & 2 deletions apps/nextjs/app/api/dfda/[dfdaPath]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function GET(req: Request, context: z.infer<typeof routeContextSche
const data = response.data ?? response;
return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json' } });
} catch (error) {
return handleError(error);
return handleError(error, "GET dfdaPath");
}
}

Expand All @@ -32,6 +32,6 @@ export async function POST(req: Request, context: z.infer<typeof routeContextSch
const data = response.data ?? response;
return new Response(JSON.stringify(data), { status: response.status, headers: { 'Content-Type': 'application/json' } });
} catch (error) {
return handleError(error);
return handleError(error, "POST dfdaPath");
}
}
5 changes: 2 additions & 3 deletions apps/nextjs/app/api/image2measurements/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import { NextRequest, NextResponse } from 'next/server';
import OpenAI from "openai";
import {handleError} from "@/lib/errorHandler";

// Initialize the OpenAI client with the API key. This key is essential for authenticating
// the requests with OpenAI's API services.
Expand Down Expand Up @@ -154,8 +155,6 @@ Please provide the JSON output without any additional text or explanations.
// Return the analysis in the response
return NextResponse.json({ success: true, analysis: analysis });
} catch (error) {
// Log and handle any errors encountered during the request to OpenAI
console.error('Error sending request to OpenAI:', error);
return NextResponse.json({ success: false, message: 'Error sending request to OpenAI' });
return handleError(error, "image2measurements");
}
}
32 changes: 14 additions & 18 deletions apps/nextjs/app/api/text2measurements/route.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,34 @@
import { NextRequest, NextResponse } from 'next/server';
import { text2measurements } from "@/lib/text2measurements";
import { postMeasurements} from "@/lib/dfda";
import {getUserId} from "@/lib/getUserId";
import {handleError} from "@/lib/errorHandler";

export async function POST(request: NextRequest) {
let { statement, localDateTime, text } = await request.json();
statement = statement || text;
let { statement, utcDateTime, timeZoneOffset, text } = await request.json();
if(!statement){statement = text;}

try {
const measurements = await text2measurements(statement, localDateTime);
const userId = await getUserId();
if(userId){
await postMeasurements(measurements, userId)
}
const measurements = await text2measurements(statement, utcDateTime, timeZoneOffset);
return NextResponse.json({ success: true, measurements: measurements });
} catch (error) {
// Log and handle any errors encountered during the request to OpenAI
console.error('Error sending request to OpenAI:', error);
return NextResponse.json({ success: false, message: 'Error sending request to OpenAI' });
return handleError(error, "text2measurements")
}
}

export async function GET(req: NextRequest) {
const urlParams = Object.fromEntries(new URL(req.url).searchParams);
const statement = urlParams.statement as string;
const localDateTime = urlParams.localDateTime as string | null | undefined;
const utcDateTime = urlParams.utcDateTime as string;
let timeZoneOffset = 0;
if(urlParams.timeZoneOffset){
timeZoneOffset = parseInt(urlParams.timeZoneOffset);
} else {
console.error("timeZoneOffset is not provided");
}

try {
const measurements = await text2measurements(statement, localDateTime);
const userId = await getUserId();
await postMeasurements(measurements, userId);
const measurements = await text2measurements(statement, utcDateTime, timeZoneOffset);
return NextResponse.json({ success: true, measurements: measurements });
} catch (error) {
console.error('Error sending request to OpenAI:', error);
return NextResponse.json({ success: false, message: 'Error sending request to OpenAI' });
return handleError(error, "text2measurements");
}
}
10 changes: 10 additions & 0 deletions apps/nextjs/app/api/trigger/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { createAppRoute } from "@trigger.dev/nextjs";
import { client } from "@/trigger";

import "@/jobs";

//this route is used to send and receive data with Trigger.dev
export const { POST, dynamic } = createAppRoute(client);

//uncomment this to set a higher max duration (it must be inside your plan limits). Full docs: https://vercel.com/docs/functions/serverless-functions/runtimes#max-duration
//export const maxDuration = 60;
2 changes: 1 addition & 1 deletion apps/nextjs/app/api/user/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ export async function GET(
const dfdaUser = await getOrCreateDfdaUser(session.user.id);
return new Response(JSON.stringify(dfdaUser), { status: 200, headers: { 'Content-Type': 'application/json' } })
} catch (error) {
return handleError(error)
return handleError(error, "GET dfdaUser");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ interface GlobalVariablePageProps {
// if (!user) {
// redirect(authOptions?.pages?.signIn || "/signin")
// }
// const response = await fetch(`/api/dfda/globalVariables?variableId=${params.variableId}&includeCharts=0`);
// const response = await fetch(`/api/dfda/variables?variableId=${params.variableId}&includeCharts=0`);
// const globalVariables = await response.json();
// const globalVariable = globalVariables[0];
//
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default async function GlobalVariableEdit({ params }: GlobalVariableEditP
}

const response = await fetch(
`/api/dfda/globalVariables?variableId=${params.variableId}&includeCharts=0`)
`/api/dfda/variables?variableId=${params.variableId}&includeCharts=0`)
const globalVariables = await response.json()
const globalVariable = globalVariables[0]

Expand Down
22 changes: 6 additions & 16 deletions apps/nextjs/app/dashboard/globalVariables/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import { redirect } from "next/navigation"

import { authOptions } from "@/lib/auth"
import { getCurrentUser } from "@/lib/session"
import { GlobalVariableAddButton } from "@/components/globalVariables/global-variable-add-button"
import { GenericVariableAddButton } from "@/components/genericVariables/generic-variable-add-button"
import { Shell } from "@/components/layout/shell"
import { DashboardHeader } from "@/components/pages/dashboard/dashboard-header"
import {GenericVariableList} from "@/components/genericVariables/generic-variable-list";
import {GlobalVariableSearch} from "@/components/globalVariables/global-variable-search";


export const metadata: Metadata = {
title: "Your Variables",
description: "Manage your treatments, symptoms, and other variables.",
title: "Search for a Variable",
description: "Find a food, drug, symptom, or other variable.",
}

export default async function GlobalVariablesPage() {
Expand All @@ -21,21 +21,11 @@ export default async function GlobalVariablesPage() {
redirect(authOptions?.pages?.signIn || "/signin")
}

// Define search parameters
const searchParams = {
includePublic: false,
sort: 'createdAt',
limit: 10,
offset: 0,
searchPhrase: "",
};

return (
<Shell>
<DashboardHeader heading="Your Variables" text="Manage your treatments, symptoms, and other variables.">
<GlobalVariableAddButton />
<DashboardHeader heading="Global Variables" text="Search for a food, drug, symptom or anything else.">
</DashboardHeader>
<GenericVariableList user={user} searchParams={searchParams} />
<GlobalVariableSearch user={user} />
</Shell>
)
}
7 changes: 4 additions & 3 deletions apps/nextjs/app/dashboard/image2measurements/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import {DashboardHeader} from "@/components/pages/dashboard/dashboard-header";
import {AnalyzeButton} from "@/components/AnalyzeButton";
import {FileUploader} from "@/components/FileUploader";
import {AnalysisResult} from "@/components/AnalysisResult";
import {CameraButton} from "@/components/CameraButton"; // Importing the CameraButton component
import {CameraButton} from "@/components/CameraButton";
import {getUtcDateTimeWithTimezone} from "@/lib/dateTimeWithTimezone";

// The main App component
const App: React.FC = () => {
// State management for various functionalities
const [file, setFile] = useState<File | null>(null); // Holds the selected image file
Expand All @@ -26,7 +26,7 @@ const App: React.FC = () => {

// Callback for handling file selection changes
const handleFileChange = useCallback(async (selectedFile: File) => {
// Updating state with the new file and its preview URL
// Updating the state with the new file and its preview URL
setFile(selectedFile);
setPreview(URL.createObjectURL(selectedFile));
setStatusMessage('Image selected. Click "Analyze Image" to proceed.');
Expand Down Expand Up @@ -65,6 +65,7 @@ const App: React.FC = () => {
body: JSON.stringify({
file: base64Image,
prompt: textInput,
utcDateTimeWithTimezone: getUtcDateTimeWithTimezone(),
}),
});

Expand Down
16 changes: 11 additions & 5 deletions apps/nextjs/app/dashboard/text2measurements/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import React, { useState } from 'react';
import {Shell} from "@/components/layout/shell";
import {DashboardHeader} from "@/components/pages/dashboard/dashboard-header";
import {Icons} from "@/components/icons";
import {getTimeZoneOffset, getUtcDateTime} from "@/lib/dateTimeWithTimezone";

// Define a type for the message objects
type Message = {
type: 'user' | 'response' | 'loading';
text: string;
time: string;
};

const App: React.FC = () => {
Expand All @@ -19,18 +19,24 @@ const App: React.FC = () => {

const sendMessage = async () => {
if (input.trim()) {
const localDateTime = new Date().toISOString(); // Get current date and time in ISO format
setMessages([...messages, { type: 'user', text: input, time: localDateTime }, { type: 'loading', text: 'Loading...', time: localDateTime }]);

setMessages([...messages, { type: 'user', text: input }, { type: 'loading', text: 'Loading...' }]);
setIsLoading(true);
const response = await fetch('/api/text2measurements', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ text: input, localDateTime }), // Include localDateTime in the request body
body: JSON.stringify({
text: input,
timeZoneOffset: getTimeZoneOffset(),
utcDateTime: getUtcDateTime(),
}),
});
const data = await response.json();
setMessages(prevMessages => prevMessages.filter(msg => msg.type !== 'loading').concat({ type: 'response', text: JSON.stringify(data), time: localDateTime }));
setMessages(prevMessages => prevMessages
.filter(msg => msg.type !== 'loading')
.concat({ type: 'response', text: JSON.stringify(data) }));
setIsLoading(false);
setInput('');
}
Expand Down
7 changes: 4 additions & 3 deletions apps/nextjs/app/dashboard/userVariables/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { redirect } from "next/navigation"

import { authOptions } from "@/lib/auth"
import { getCurrentUser } from "@/lib/session"
import { UserVariableAddButton } from "@/components/userVariables/user-variable-add-button"
import { GenericVariableList } from "@/components/genericVariables/generic-variable-list"
import { Shell } from "@/components/layout/shell"
import { DashboardHeader } from "@/components/pages/dashboard/dashboard-header"
import {GenericVariableAddButton} from "@/components/genericVariables/generic-variable-add-button";
import {UserVariableSearch} from "@/components/userVariables/user-variable-search";


export const metadata: Metadata = {
Expand All @@ -33,9 +34,9 @@ export default async function UserVariablesPage() {
return (
<Shell>
<DashboardHeader heading="Your Variables" text="Manage your treatments, symptoms, and other variables.">
<UserVariableAddButton />
<GenericVariableAddButton />
</DashboardHeader>
<GenericVariableList user={user} searchParams={searchParams} />
<UserVariableSearch user={user} />
</Shell>
)
}
Loading

0 comments on commit 42a5731

Please sign in to comment.