Skip to content

Commit

Permalink
🚀 feat: introduced update transcription and summary features, several…
Browse files Browse the repository at this point in the history
… bugs improvements
  • Loading branch information
asifrahaman13 committed Aug 7, 2024
1 parent 6595c33 commit 81efb69
Show file tree
Hide file tree
Showing 11 changed files with 116 additions and 139 deletions.
53 changes: 5 additions & 48 deletions frontend/src/app/api/patients/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ async function confirmSave(
console.log(access_token, patientId, details, summary_details);
try {
const response = await axios.post(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/users/update-transcript`,
`${process.env.NEXT_PUBLIC_BACKEND_URL}/users/update`,
{ visitId: patientId, details: details, summary: summary_details },
{
headers: {
Expand All @@ -150,54 +150,12 @@ async function confirmSave(
},
}
);
if (response.status === 200) {
const upload_to_s3 = await axios.post(
`${process.env.NEXT_PUBLIC_AI_SECOND_BACKEND_URI}/uploads3`,
{ patient_id: patientId },
{
headers: {
'Content-Type': 'application/json',
APISECRET: process.env.NEXT_PUBLIC_APISECRET,
Authorization: `Bearer ${access_token}`,
},
}
);

if (upload_to_s3.status === 200) {
return response;
}
}
} catch (err) {
console.log(err);
}
}

async function uploadData(
access_token: string,
trasncription: string,
patientId: string
) {
try {
const response = await axios.post(
`${process.env.NEXT_PUBLIC_AI_BACKEND_URL}/upload-files`,
{
transcription: trasncription,
secret_key: 'approved',
patient_id: patientId,
},
{
headers: {
'Content-Type': 'application/json',
APISECRET: process.env.NEXT_PUBLIC_APISECRET,
Authorization: `Bearer ${access_token}`,
},
}
);
if (response.status === 200) {
return response;
}
} catch (err) {
console.log(err);
} catch (err: any) {
throw new Error(err);
}
}

Expand Down Expand Up @@ -267,8 +225,8 @@ async function generateSummary(
if (response.status === 200) {
return response;
}
} catch (err) {
console.log(err);
} catch (err: any) {
throw new Error(err);
}
}

Expand All @@ -278,7 +236,6 @@ export {
saveData,
appendData,
confirmSave,
uploadData,
getSummary,
sendDetailedData,
generateSummary,
Expand Down
5 changes: 3 additions & 2 deletions frontend/src/app/dashboard/components/Notes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@ const Notes = ({ patientId }: Patient) => {
async function ConfirmSave() {
try {
const access_token = localStorage.getItem('access_token') || '';
console.log(historySlice.summary, historySlice.details, patientId);
const response = await confirmSave(
access_token,
patientId,
historySlice.details,
JSON.parse(JSON.stringify(historySlice.summary))
);
} catch (error) {
console.log(error);
} catch (error: any) {
throw new Error(error);
}
}

Expand Down
58 changes: 29 additions & 29 deletions frontend/src/app/dashboard/pages/PatientDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,52 +58,52 @@ const PatientDetail: React.FC<PatientDetailProps> = ({ patient }) => {
<strong>Health Data Points:</strong>
</p>
<ul className="ml-4 list-disc text-gray-600 mb-2">
{patient?.data.map((dataPoint: any, index: number) => (
{patient?.data?.map((dataPoint: any, index: number) => (
<li key={index}>
<div>
<strong>Timestamp:</strong>{' '}
{new Date(dataPoint.timestamp * 1000).toLocaleString()}
{new Date(dataPoint?.timestamp * 1000).toLocaleString()}
</div>
{dataPoint.systol_blood_pressure && (
{dataPoint?.systol_blood_pressure && (
<div>Systolic BP: {dataPoint.systol_blood_pressure} mmHg</div>
)}
{dataPoint.diastol_blood_pressure && (
<div>Diastolic BP: {dataPoint.diastol_blood_pressure} mmHg</div>
{dataPoint?.diastol_blood_pressure && (
<div>Diastolic BP: {dataPoint?.diastol_blood_pressure} mmHg</div>
)}
{dataPoint.heart_rate && (
<div>Heart Rate: {dataPoint.heart_rate} bpm</div>
{dataPoint?.heart_rate && (
<div>Heart Rate: {dataPoint?.heart_rate} bpm</div>
)}
{dataPoint.respiratory_rate && (
<div>Respiratory Rate: {dataPoint.respiratory_rate} bpm</div>
{dataPoint?.respiratory_rate && (
<div>Respiratory Rate: {dataPoint?.respiratory_rate} bpm</div>
)}
{dataPoint.body_temperature && (
<div>Body Temperature: {dataPoint.body_temperature} °C</div>
{dataPoint?.body_temperature && (
<div>Body Temperature: {dataPoint?.body_temperature} °C</div>
)}
{dataPoint.blood_temperature && (
<div>Blood Temperature: {dataPoint.blood_temperature} °C</div>
{dataPoint?.blood_temperature && (
<div>Blood Temperature: {dataPoint?.blood_temperature} °C</div>
)}
{dataPoint.step_count && (
<div>Step Count: {dataPoint.step_count}</div>
{dataPoint?.step_count && (
<div>Step Count: {dataPoint?.step_count}</div>
)}
{dataPoint.calories_burned && (
{dataPoint?.calories_burned && (
<div>Calories Burned: {dataPoint.calories_burned}</div>
)}
{dataPoint.distance_travelled && (
<div>Distance Travelled: {dataPoint.distance_travelled} km</div>
{dataPoint?.distance_travelled && (
<div>Distance Travelled: {dataPoint?.distance_travelled} km</div>
)}
{dataPoint.sleep_duration && (
<div>Sleep Duration: {dataPoint.sleep_duration} hours</div>
{dataPoint?.sleep_duration && (
<div>Sleep Duration: {dataPoint?.sleep_duration} hours</div>
)}
{dataPoint.water_consumed && (
{dataPoint?.water_consumed && (
<div>Water Consumed: {dataPoint.water_consumed} L</div>
)}
{dataPoint.caffeine_consumed && (
<div>Caffeine Consumed: {dataPoint.caffeine_consumed} mg</div>
{dataPoint?.caffeine_consumed && (
<div>Caffeine Consumed: {dataPoint?.caffeine_consumed} mg</div>
)}
{dataPoint.alcohol_consumed && (
<div>Alcohol Consumed: {dataPoint.alcohol_consumed} mL</div>
{dataPoint?.alcohol_consumed && (
<div>Alcohol Consumed: {dataPoint?.alcohol_consumed} mL</div>
)}
{dataPoint.weight && <div>Weight: {dataPoint.weight} kg</div>}
{dataPoint?.weight && <div>Weight: {dataPoint?.weight} kg</div>}
</li>
))}
</ul>
Expand All @@ -112,13 +112,13 @@ const PatientDetail: React.FC<PatientDetailProps> = ({ patient }) => {
</p>
<ul className="ml-4 list-disc text-gray-600 mb-2">
<li>
<strong>MRN:</strong> {patient?.qr.mrn}
<strong>MRN:</strong> {patient?.qr?.mrn}
</li>
<li>
<strong>URL:</strong> {patient?.qr.url}
<strong>URL:</strong> {patient?.qr?.url}
</li>
<li>
<strong>Password:</strong> {patient?.qr.password}
<strong>Password:</strong> {patient?.qr?.password}
</li>
</ul>
</div>
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/app/dashboard/patients/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default function Page() {
<>
<h1 className="text-4xl font-semibold mb-8">Patients</h1>
<div className="grid gap-6 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 max-w-screen-2xl w-full px-4">
{patients.map((patient, index) => (
{patients?.map((patient, index) => (
<button
key={index}
className="bg-white rounded-lg shadow-lg w-full transition-transform transform hover:scale-105"
Expand Down
43 changes: 7 additions & 36 deletions frontend/src/app/dashboard/visits/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,6 @@ import { setAllHistory } from '@/lib/features/history/allHistorySlice';
import axios from 'axios';
import Patient from '../components/Patient';

interface PrevItem {
privJson: string;
privSpeakerId: string;
}

interface TranscriptionData {
visitId: string;
prev: PrevItem[];
}

export default function Page() {
const pollsSlice = useSelector((state: RootState) => state.polls);
const allHistorySlice = useSelector((state: RootState) => state.allHistory);
Expand All @@ -56,11 +46,7 @@ export default function Page() {
) {
await appendData(access_token, patientId, p);
}
const [currSpeaker, setCurrSpeaker] = useState('');
const [t, setT] = useState<TranscriptionData>({
visitId: pollsSlice.patientDetails.visitId,
prev: [],
});

const initializeSpeechRecognizer = async () => {
try {
if (!SpeechConfig) {
Expand All @@ -87,12 +73,7 @@ export default function Page() {

const access_token = localStorage.getItem('access_token') || '';
if (isRecording) {
conversationTranscriber.sessionStarted = function (s: any, e: any) {
setT((prev) => ({
...prev,
visitId: pollsSlice.patientDetails.visitId,
}));
};
conversationTranscriber.sessionStarted = function (s: any, e: any) {};
conversationTranscriber.sessionStopped = function (s: any, e: any) {
conversationTranscriber.stopTranscribingAsync();
};
Expand All @@ -105,24 +86,12 @@ export default function Page() {
let newSpeakerId = parts.join('-');
if (e.result.speakerId != 'Unknown') {
console.log(`${newSpeakerId}: ${e.result.text}`);
setCurrSpeaker(newSpeakerId);
setData((prev) => [...prev, `${newSpeakerId}: ${e.result.text}`]);
AppendData(
access_token,
pollsSlice.patientDetails.visitId,
`${newSpeakerId}: ${e.result.text}`
);

setT((prev) => ({
...prev,
prev: [
...prev.prev,
{
privJson: e.result.privJson,
privSpeakerId: e.result.privSpeakerId,
},
],
}));
}
};

Expand Down Expand Up @@ -171,12 +140,14 @@ export default function Page() {

setIsRecording(false);
stopClock();
conversationTranscriber.stopTranscribingAsync();
// try {
// conversationTranscriber.stopTranscribingAsync();
// } catch (error: any) {
// throw new Error(error);
// }

try {
const access_token = localStorage.getItem('access_token') || '';
// await sendDetailedData(access_token, t);
// await uploadData(access_token, data.join(","), pollsSlice.patientDetails.visitId);
await generateSummary(
access_token,
pollsSlice.patientDetails.visitId,
Expand Down
24 changes: 12 additions & 12 deletions src/application/web/controllers/user_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
from src.domain.interfaces.user_interface import UserInterface
from fastapi.security import OAuth2PasswordBearer
from datetime import timedelta
from src.domain.entities.user import UserBase, UserData, PatientData, PatientDataUpdate
from src.domain.entities.user import UserBase, UserData, PatientData, PatientDataSummary
from src.domain.interfaces.auth_interface import AuthInterface
from src.domain.entities.chat import Summary
from fastapi import APIRouter
from src.infastructure.exceptions.exceptions import HttePrequestErrors
from src.domain.entities.chat import QrData
from exports.exports import get_auth_service, get_chat_service, get_user_service
from exports.exports import get_auth_service, get_user_service


user_controller = APIRouter()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
Expand Down Expand Up @@ -191,9 +192,9 @@ async def get_summary(
return HttePrequestErrors.not_found()


@user_controller.post("/update-transcript")
@user_controller.post("/update")
async def update_transcript(
patient: PatientDataUpdate,
patient: PatientDataSummary,
current_user: str = Depends(get_current_user),
auth_interface: AuthInterface = Depends(get_auth_service),
user_interface: UserInterface = Depends(get_user_service),
Expand All @@ -203,14 +204,13 @@ async def update_transcript(
if user == False:
return HttePrequestErrors.unauthorized()
try:
update_data = user_interface.update_transctiption(
patient["visitId"], patient["details"], patient["summary"]
)
return update_data
update_data = user_interface.update_details(patient)
if update_data is True:
return {"status": 200, "message": "updated"}
return HttePrequestErrors.internal_server_error()

except Exception as e:
print(e)
return False
return False


@user_controller.post("/create-qr")
Expand Down Expand Up @@ -239,9 +239,9 @@ async def get_all_patients(
auth_interface: AuthInterface = Depends(get_auth_service),
user_interface: UserInterface = Depends(get_user_service),
):
print(current_user)

user = auth_interface.get_current_user(current_user)
print(user)

if user == False:
return HttePrequestErrors.unauthorized()
try:
Expand Down
8 changes: 7 additions & 1 deletion src/domain/entities/user.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pydantic import BaseModel
from typing import List, Optional
from typing import Any, List, Optional


class User(BaseModel):
Expand Down Expand Up @@ -104,3 +104,9 @@ class PatientDataUpdate(BaseModel):
visitId: str | None = None
details: List[str]
summary: Summary | None = None


class PatientDataSummary(BaseModel):
visitId: str
details: Any
summary: Any
5 changes: 5 additions & 0 deletions src/domain/interfaces/user_interface.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
from typing import Any, Dict
from src.domain.entities.user import User
from src.domain.entities.user import PatientData

Expand Down Expand Up @@ -43,3 +44,7 @@ def update_qr(self, patient_id: str, data: dict):
@abstractmethod
def get_all_patients(self, doctor_username: str):
pass

@abstractmethod
def update_details(self, data: Any):
pass
Loading

0 comments on commit 81efb69

Please sign in to comment.