-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
223 lines (182 loc) · 5.96 KB
/
index.js
File metadata and controls
223 lines (182 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
const express = require('express');
const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
const { OpenAI } = require('openai');
const { Pinecone } = require('@pinecone-database/pinecone');
const nodemailer = require('nodemailer');
const functions = require('@google-cloud/functions-framework');
const cors = require('cors');
const fs = require('fs');
const medcodes = JSON.parse(fs.readFileSync('medcode.json', 'utf-8')); // Load medcode.json
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
// Set up OpenAI and Pinecone API keys
const openai = new OpenAI();
const pc = new Pinecone({
apiKey: process.env.PINECONE_API_KEY
});
const indexName = "medicalcodes";
console.log(pc.listIndexes());
const index = pc.Index(indexName);
// Initialize the Secret Manager client
const client = new SecretManagerServiceClient();
async function createSecret(patientId, username, password, ehrType, url) {
const projectId = "sinewave-mobile";
const secretData = JSON.stringify({
username,
password,
ehr_type: ehrType,
url: url,
});
const parent = `projects/${projectId}`;
try {
const [secret] = await client.createSecret({
parent,
secretId: patientId,
secret: {
replication: {
automatic: {}
}
}
});
console.log(`Created secret: ${secret.name}`);
const secretName = `projects/${projectId}/secrets/${patientId}`;
const [version] = await client.addSecretVersion({
parent: secretName,
payload: {
data: Buffer.from(secretData, 'utf-8')
}
});
console.log(`Added secret version: ${version.name}`);
return version;
} catch (error) {
console.error(`Secret creation failed: ${error}`);
return null;
}
}
async function fetchCredentials(patientId) {
const projectId = "sinewave-mobile";
const secretName = `projects/${projectId}/secrets/${patientId}/versions/latest`;
try {
const [version] = await client.accessSecretVersion({ name: secretName });
const secretPayload = version.payload.data.toString('utf-8');
const credentials = JSON.parse(secretPayload);
console.log(`Fetched credentials for patient_id: ${patientId}`);
return credentials;
} catch (error) {
console.error(`Failed to fetch secret: ${error}`);
return null;
}
}
app.get('/getCredentials', async (req, res) => {
const patientId = req.query.patient_id;
if (!patientId) {
return res.status(400).json({ message: "patient_id is required" });
}
const credentials = await fetchCredentials(patientId);
if (credentials) {
res.json(credentials);
} else {
res.status(404).json({ message: "Failed to fetch credentials" });
}
});
async function deleteSecret(patientId) {
const projectId = "sinewave-mobile";
const secretName = `projects/${projectId}/secrets/${patientId}`;
try {
// Delete the secret
await client.deleteSecret({ name: secretName });
console.log(`Deleted secret for patient_id: ${patientId}`);
return true;
} catch (error) {
console.error(`Failed to delete secret: ${error}`);
return false;
}
}
app.delete('/deleteCredentials', async (req, res) => {
const patientId = req.query.patient_id;
if (!patientId) {
return res.status(400).json({ message: "patient_id is required" });
}
const success = await deleteSecret(patientId);
if (success) {
res.json({ message: "Credentials deleted successfully" });
} else {
res.status(500).json({ message: "Failed to delete credentials" });
}
});
app.post('/storeCredentials', async (req, res) => {
const { username, password, ehr_type, patient_id, url } = req.body;
console.log(req.body);
const response = await createSecret(patient_id, username, password, ehr_type, url);
console.log(response);
res.json({ status: 'success', secret_version_id: response.name });
});
async function getOpenAIEmbeddings(text, model = "text-embedding-ada-002") {
text = text.replace(/\n/g, " ");
const response = await openai.embeddings.create({ input: [text], model });
return response.data[0].embedding;
}
async function queryCodes(queryText, topK) {
const queryEmbedding = await getOpenAIEmbeddings(queryText);
const queryResults = await index.query({ vector: queryEmbedding, topK, includeMetadata: true });
return queryResults.matches.map(match => [match.id, match.score]);
}
app.post('/get_medical_codes', async (req, res) => {
const { diagnosis } = req.body;
console.log(diagnosis);
if (!diagnosis) {
return res.status(400).json({ error: "No diagnosis text provided" });
}
const topK = 10;
const codes = await queryCodes(diagnosis, topK);
// Map the predicted codes to their descriptions
const results = codes.map(([code]) => {
return {
code,
description: medcodes[code] || "Description not available" // Return description if exists
};
});
res.json({ codes: results });
});
function sendSecureEmail(subject, body, sender, password, toEmail) {
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: sender,
pass: password
}
});
const mailOptions = {
from: sender,
to: toEmail,
subject: subject,
text: body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
app.post('/send_email', (req, res) => {
const { subject, body, to_email } = req.body;
console.log(req.body);
try {
const sender = process.env.MAIL_USERNAME;
const password = process.env.MAIL_PASSWORD;
sendSecureEmail(subject, body, sender, password, to_email);
res.json({ message: 'Email sent successfully!' });
} catch (error) {
res.status(500).json({ error: error.toString() });
}
});
app.get("/", (req, res) => {
const name = process.env.NAME || "World";
res.send(`Hello ${name} 8787!`);
});
// Export the Express app as a Cloud Function
exports.mainFunction = app;