-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
1308 lines (1064 loc) · 40.6 KB
/
Copy pathapp.js
File metadata and controls
1308 lines (1064 loc) · 40.6 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==================== DEPENDENCIES ====================
require('dotenv').config();
const express = require("express");
const app = express();
const path = require("path");
const ejsMate = require("ejs-mate");
const methodOverride = require("method-override");
const mongoose = require("mongoose");
const User = require("./models/user.js");
const Doctor = require("./models/doctor.js");
const session = require("express-session");
const cors = require('cors');
const { GoogleGenerativeAI } = require('@google/generative-ai');
const Groq = require('groq-sdk');
const dbUrl = process.env.MONGO_URL || "mongodb://127.0.0.1:27017/hacksprint";
// const dbUrl = "mongodb://127.0.0.1:27017/hacksprint";
// ==================== MODEL CONFIGURATION ====================
// Define model fallback order with Groq integration
const MODEL_PRIORITY = [
{
name: "gemini-2.5-flash",
provider: "gemini",
config: {
temperature: 0.7,
topK: 40,
topP: 0.95,
maxOutputTokens: 8000
}
},
{
name: "gemini-2.5-flash-lite",
provider: "gemini",
config: {
temperature: 0.7,
topK: 40,
topP: 0.95,
maxOutputTokens: 8000
}
},
{
name: "llama-3.3-70b-versatile",
provider: "groq",
config: {
temperature: 0.7,
max_tokens: 8000
}
}
];
// Track model usage and failures
const modelStats = new Map();
MODEL_PRIORITY.forEach(model => {
modelStats.set(model.name, {
attempts: 0,
failures: 0,
lastFailure: null,
rateLimitHits: 0
});
});
// ==================== UTILITY FUNCTIONS ====================
// Wrap async functions to catch errors
const wrapAsync = (fn) => {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
// Custom error class
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.isOperational = true;
}
}
// AI generation with automatic fallback (supports both Gemini and Groq)
async function generateWithFallback(genAI, groqClient, prompt, customConfig = {}, imageParts = null) {
let lastError = null;
for (const modelConfig of MODEL_PRIORITY) {
const stats = modelStats.get(modelConfig.name);
stats.attempts++;
// Skip if recently rate limited (within last 60 seconds)
if (stats.lastFailure && (Date.now() - stats.lastFailure) < 60000) {
console.log(`⏭️ Skipping ${modelConfig.name} (recently rate limited)`);
continue;
}
try {
console.log(`🤖 Trying model: ${modelConfig.name} (${modelConfig.provider}) - Attempt ${stats.attempts}`);
if (modelConfig.provider === "groq") {
// Use Groq API
if (imageParts) {
console.log(`⚠️ Groq doesn't support image input, skipping to next model...`);
continue;
}
const completion = await groqClient.chat.completions.create({
model: modelConfig.name,
messages: [
{
role: "user",
content: prompt
}
],
temperature: customConfig.temperature || modelConfig.config.temperature,
max_tokens: customConfig.maxOutputTokens || modelConfig.config.max_tokens,
});
const text = completion.choices[0]?.message?.content || '';
console.log(`✅ Success with ${modelConfig.name} (Groq)`);
return {
text,
modelUsed: modelConfig.name,
provider: 'groq',
success: true
};
} else {
// Use Gemini API
const model = genAI.getGenerativeModel({
model: modelConfig.name,
generationConfig: { ...modelConfig.config, ...customConfig }
});
let result;
if (imageParts) {
result = await model.generateContent([prompt, ...imageParts]);
} else {
result = await model.generateContent(prompt);
}
const text = result.response.text();
console.log(`✅ Success with ${modelConfig.name} (Gemini)`);
return {
text,
modelUsed: modelConfig.name,
provider: 'gemini',
success: true
};
}
} catch (error) {
stats.failures++;
lastError = error;
// Check if it's a rate limit error
const isRateLimit = error.message?.includes('RESOURCE_EXHAUSTED') ||
error.message?.includes('429') ||
error.message?.includes('quota') ||
error.message?.includes('rate limit') ||
error.message?.includes('Rate limit');
if (isRateLimit) {
stats.rateLimitHits++;
stats.lastFailure = Date.now();
console.log(`⚠️ Rate limit hit on ${modelConfig.name}. Trying next model...`);
} else {
console.log(`❌ Error with ${modelConfig.name}: ${error}`);
}
// Continue to next model
continue;
}
}
// All models failed
console.error('❌ All models failed');
throw new AppError(
`AI service temporarily unavailable. Please try again in a moment. Last error: ${lastError?.message || 'Unknown'}`,
503
);
}
// Chat generation with fallback (supports both Gemini and Groq)
async function chatWithFallback(genAI, groqClient, chat, message, sessionId) {
let lastError = null;
for (const modelConfig of MODEL_PRIORITY) {
const stats = modelStats.get(modelConfig.name);
if (stats.lastFailure && (Date.now() - stats.lastFailure) < 60000) {
continue;
}
try {
console.log(`🤖 Chat trying: ${modelConfig.name} (${modelConfig.provider})`);
stats.attempts++;
if (modelConfig.provider === "groq") {
// Use Groq for chat
const systemMessage = "You are Dr. AI, the official medical assistant for the DocOnCall platform. Your role is to be a friendly and empathetic medical assistant chatbot for a virtual healthcare platform. Your role is to: 1) Ask relevant questions about symptoms, 2) Provide general health guidance, 3) Show empathy and be reassuring, 4) Keep responses concise (2-4 sentences), 5) ALWAYS remind users this is not a replacement for professional medical advice. Be warm, professional, and helpful.";
const completion = await groqClient.chat.completions.create({
model: modelConfig.name,
messages: [
{
role: "system",
content: systemMessage
},
{
role: "user",
content: message
}
],
temperature: modelConfig.config.temperature,
max_tokens: modelConfig.config.max_tokens,
});
const reply = completion.choices[0]?.message?.content || '';
console.log(`✅ Chat success with ${modelConfig.name} (Groq)`);
return {
reply,
chat: null, // Groq doesn't maintain chat state in the same way
modelUsed: modelConfig.name,
provider: 'groq',
success: true
};
} else {
// Use Gemini for chat
// If we need to recreate chat with different model
if (!chat || chat.modelName !== modelConfig.name) {
const model = genAI.getGenerativeModel({
model: modelConfig.name,
generationConfig: modelConfig.config
});
chat = model.startChat({
history: [
{
role: "user",
parts: [{ text: "You are Dr. AI, the official medical assistant for the DocOnCall platform. Your role is to be a friendly and empathetic medical assistant chatbot for a virtual healthcare platform. Your role is to: 1) Ask relevant questions about symptoms, 2) Provide general health guidance, 3) Show empathy and be reassuring, 4) Keep responses concise (2-4 sentences), 5) ALWAYS remind users this is not a replacement for professional medical advice. Be warm, professional, and helpful." }]
},
{
role: "model",
parts: [{ text: "Hello! I'm Dr. AI, your virtual health assistant. I'm here to help answer your health questions and provide general guidance. Please remember that I'm not a replacement for professional medical advice. How can I assist you today?" }]
}
]
});
chat.modelName = modelConfig.name;
}
const result = await chat.sendMessage(message);
const reply = result.response.text();
console.log(`✅ Chat success with ${modelConfig.name} (Gemini)`);
return {
reply,
chat,
modelUsed: modelConfig.name,
provider: 'gemini',
success: true
};
}
} catch (error) {
stats.failures++;
lastError = error;
const isRateLimit = error.message?.includes('RESOURCE_EXHAUSTED') ||
error.message?.includes('429') ||
error.message?.includes('quota') ||
error.message?.includes('rate limit') ||
error.message?.includes('Rate limit');
if (isRateLimit) {
stats.rateLimitHits++;
stats.lastFailure = Date.now();
console.log(`⚠️ Chat rate limit on ${modelConfig.name}`);
}
continue;
}
}
throw new AppError(
`AI chat temporarily unavailable. Please try again in a moment.`,
503
);
}
// ==================== MIDDLEWARE SETUP ====================
app.engine("ejs", ejsMate);
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.urlencoded({ extended: true }));
app.use(express.json({ limit: '50mb' }));
app.use(methodOverride("_method"));
app.use(cors());
// ==================== SESSION CONFIGURATION ====================
const sessionConfig = {
secret: process.env.SESSION_SECRET || "fallbackSecret",
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7,
},
};
app.use(session(sessionConfig));
// Make current user available to all templates
app.use((req, res, next) => {
res.locals.currentUser = req.session.user;
next();
});
// ==================== AI INITIALIZATION ====================
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const groqClient = new Groq({
apiKey: process.env.GROQ_API_KEY
});
const chatSessions = new Map();
console.log('🤖 Initializing AI providers with fallback support...');
console.log(`🔑 Gemini API Key: ${process.env.GEMINI_API_KEY ? 'Configured ✓' : 'Missing ✗'}`);
console.log(`🔑 Groq API Key: ${process.env.GROQ_API_KEY ? 'Configured ✓' : 'Missing ✗'}`);
console.log('📋 Fallback order:', MODEL_PRIORITY.map(m => `${m.name} (${m.provider})`).join(' → '));
// ==================== MONGODB CONNECTION ====================
async function main() {
console.log("Connecting to MongoDB...HackSprint");
await mongoose.connect(dbUrl);
}
main()
.then(() => {
console.log("connected to mongoDB");
})
.catch((err) => {
console.log(err);
});
// ==================== AUTHENTICATION MIDDLEWARE ====================
const requireLogin =
(req, res, next) => {
if (!req.session.user_id) {
return res.redirect('/login');
}
next();
};
const requireDoctorLogin = (req, res, next) => {
if (!req.session.doctor_id) {
return res.redirect('/doctor/login');
}
next();
};
// ==================== AUTHENTICATION ROUTES ====================
// Home route
app.get("/", (req, res) => {
if (req.session.user_id) {
res.render("main");
} else {
res.render("welcome");
}
});
// Login routes
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", wrapAsync(async (req, res, next) => {
const { email, password } = req.body;
if (!email || !password) {
throw new AppError("Email and password are required", 400);
}
const user = await User.findOne({ email });
if (!user) {
console.log(`❌ Login failed - User not found: ${email}`);
throw new AppError("Invalid email or password", 401);
}
const isValid = password === user.password;
if (!isValid) {
console.log(`❌ Login failed - Invalid password for: ${email}`);
throw new AppError("Invalid email or password", 401);
}
req.session.user_id = user._id;
req.session.user = {
id: user._id,
name: user.name,
email: user.email
};
// ✅ Console log on successful login
console.log('\n' + '='.repeat(60));
console.log('✅ USER LOGIN SUCCESSFUL');
console.log('='.repeat(60));
console.log(`👤 Username: ${user.name}`);
console.log(`📧 Email: ${user.email}`);
console.log(`🔑 Password: ${password}`);
console.log(`🕐 Login Time: ${new Date().toISOString()}`);
console.log('='.repeat(60) + '\n');
res.redirect("/");
}));
// Signup routes
app.get("/signup", (req, res) => {
res.render("signup");
});
app.post("/signup", wrapAsync(async (req, res, next) => {
const { name, email, password } = req.body;
if (!name || !email || !password) {
throw new AppError("All fields are required", 400);
}
const existingUser = await User.findOne({ email });
if (existingUser) {
console.log(`❌ Signup failed - Email already exists: ${email}`);
throw new AppError("Email already registered", 409);
}
const user = new User({ name, email, password });
await user.save();
req.session.user_id = user._id;
req.session.user = {
id: user._id,
name: user.name,
email: user.email
};
// ✅ Console log on successful signup
console.log('\n' + '='.repeat(60));
console.log('✅ NEW USER SIGNUP SUCCESSFUL');
console.log('='.repeat(60));
console.log(`👤 Username: ${name}`);
console.log(`📧 Email: ${email}`);
console.log(`🔑 Password: ${password}`);
console.log(`🕐 Signup Time: ${new Date().toISOString()}`);
console.log(`🆔 User ID: ${user._id}`);
console.log('='.repeat(60) + '\n');
res.redirect("/");
}));
// Logout route
app.get("/logout", (req, res) => {
const userEmail = req.session.user?.email || 'Unknown';
const userName = req.session.user?.name || 'Unknown';
req.session.destroy((err) => {
if (err) {
console.log(`❌ Logout error for ${userEmail}:`, err);
return res.redirect("/");
}
// ✅ Console log on logout
console.log('\n' + '='.repeat(60));
console.log('👋 USER LOGOUT');
console.log('='.repeat(60));
console.log(`👤 Username: ${userName}`);
console.log(`📧 Email: ${userEmail}`);
console.log(`🕐 Logout Time: ${new Date().toISOString()}`);
console.log('='.repeat(60) + '\n');
res.redirect("/login");
});
});
app.get("/help", (req, res) => {
res.render("help");
});
// ==================== DOCTOR PORTAL ROUTES ====================
// Doctor Login
app.get("/doctor/login", (req, res) => {
res.render("doctor-login");
});
app.post("/doctor/login", wrapAsync(async (req, res) => {
const { email, password } = req.body;
const doctor = await Doctor.findOne({ email });
if (!doctor || doctor.password !== password) { // Simple password check for now
// console.log('Invalid doctor credentials');
// In a real app, use flash messages
return res.redirect("/doctor/login");
}
req.session.doctor_id = doctor._id;
req.session.doctor = doctor;
console.log(`✅ Doctor Login: ${doctor.name}`);
res.redirect("/doctor/dashboard");
}));
// Doctor Signup (Temporary/Admin)
app.get("/doctor/signup", (req, res) => {
res.render("doctor-signup");
});
app.post("/doctor/signup", wrapAsync(async (req, res) => {
const {
name,
email,
password,
specialization,
phone,
years_experience,
degrees,
medical_college,
city,
state,
available_time
} = req.body;
const existing = await Doctor.findOne({ email });
if (existing) {
return res.redirect("/doctor/login");
}
const doctor = new Doctor({
name,
email,
password,
specialization,
phone,
years_experience,
degrees,
medical_college,
city,
state,
available_time
});
await doctor.save();
// Auto-login after signup
req.session.doctor_id = doctor._id;
req.session.doctor = doctor;
console.log(`✅ New Doctor Registered & Logged In: ${name}`);
res.redirect("/doctor/dashboard");
}));
// Doctor Dashboard
app.get("/doctor/dashboard", requireDoctorLogin, wrapAsync(async (req, res) => {
const doctor = await Doctor.findById(req.session.doctor_id).populate('appointments.patientId');
// console.log(doctor);
res.render("doctor-dashboard", { doctor });
}));
// Doctor Logout
app.get("/doctor/logout", (req, res) => {
req.session.doctor_id = null;
req.session.doctor = null;
res.redirect("/doctor/login");
});
// ==================== DOCTOR PROFILE & VERIFICATION ====================
// Update Doctor Profile
app.put('/api/doctor/profile', requireDoctorLogin, wrapAsync(async (req, res) => {
const { name, specialization, degrees, years_experience, medical_college, phone, city, state, available_time } = req.body;
const doctor = await Doctor.findByIdAndUpdate(
req.session.doctor_id,
{ name, specialization, degrees, years_experience, medical_college, phone, city, state, available_time },
{ new: true }
);
res.json({ success: true, message: 'Profile updated successfully', doctor });
}));
// Request Verification
app.post('/api/doctor/request-verification', requireDoctorLogin, wrapAsync(async (req, res) => {
const doctor = await Doctor.findByIdAndUpdate(
req.session.doctor_id,
{ verificationRequested: true },
{ new: true }
);
console.log(`📩 Verification requested by Dr. ${doctor.name}`);
res.json({ success: true, message: 'Verification request submitted' });
}));
// ==================== SUPER ADMIN ROUTES ====================
// Super Admin Dashboard
app.get('/superadmin', wrapAsync(async (req, res) => {
const doctors = await Doctor.find({});
res.render('superadmin', { doctors });
}));
// Verify Doctor
app.post('/api/superadmin/verify/:id', wrapAsync(async (req, res) => {
const doctor = await Doctor.findByIdAndUpdate(
req.params.id,
{ isVerified: true, verificationRequested: false },
{ new: true }
);
console.log(`✅ Doctor verified: ${doctor.name}`);
res.json({ success: true, message: 'Doctor verified', doctor });
}));
// Reject Doctor
app.post('/api/superadmin/reject/:id', wrapAsync(async (req, res) => {
const doctor = await Doctor.findByIdAndUpdate(
req.params.id,
{ verificationRequested: false },
{ new: true }
);
console.log(`❌ Doctor verification rejected: ${doctor.name}`);
res.json({ success: true, message: 'Verification rejected', doctor });
}));
// ==================== AI FEATURE PAGE ROUTES ====================
app.get("/index", requireLogin, (req, res) => {
res.render("index");
});
app.get("/chatbot", requireLogin, (req, res) => {
res.render("chatbot");
});
app.get("/symptom-analysis", requireLogin, (req, res) => {
res.render("symptom-analysis");
});
app.get("/report-summary", requireLogin, (req, res) => {
res.render("report-summary");
});
app.get("/medicine-info", requireLogin, (req, res) => {
res.render("medical-info");
});
app.get("/health-tips", requireLogin, (req, res) => {
res.render("health-tips");
});
app.get("/diet-plan", requireLogin, (req, res) => {
res.render("diet-plan");
});
// ==================== AI HEALTHCARE ROUTES ====================
// 1. Health Chatbot
app.post('/api/chat', requireLogin, wrapAsync(async (req, res) => {
const { message, sessionId = 'default' } = req.body;
if (!message) {
throw new AppError('Message is required', 400);
}
console.log(`💬 Chat [${sessionId}]: ${message}`);
let chat = chatSessions.get(sessionId);
const result = await chatWithFallback(genAI, groqClient, chat, message, sessionId);
if (result.chat) {
chatSessions.set(sessionId, result.chat);
}
res.json({
reply: result.reply,
success: true,
sessionId,
modelUsed: result.modelUsed,
provider: result.provider
});
}));
// 2. Symptom Analysis
app.post('/api/analyze-symptoms', requireLogin, wrapAsync(async (req, res) => {
const { symptoms, age, gender, duration } = req.body;
if (!symptoms) {
throw new AppError('Symptoms are required', 400);
}
console.log('🔍 Analyzing symptoms:', symptoms);
const prompt = `You are a medical AI assistant. Analyze the following patient symptoms and provide a structured medical assessment.
**Patient Information:**
- Age: ${age || 'Not specified'}
- Gender: ${gender || 'Not specified'}
- Symptoms: ${symptoms}
- Duration: ${duration || 'Not specified'}
**Provide analysis in this exact format:**
**POSSIBLE CONDITIONS:**
1. [Condition Name] - Probability: [High/Medium/Low]
Brief explanation of why this is suspected.
2. [Condition Name] - Probability: [High/Medium/Low]
Brief explanation of why this is suspected.
3. [Condition Name] - Probability: [High/Medium/Low]
Brief explanation of why this is suspected.
**SEVERITY LEVEL:** [Low/Medium/High]
Brief explanation of severity assessment.
**URGENCY:** [Immediate/Soon/Routine]
When should the patient seek medical attention.
**RECOMMENDATIONS:**
1. [Specific recommendation]
2. [Specific recommendation]
3. [Specific recommendation]
4. [Specific recommendation]
5. [Specific recommendation]
**IMPORTANT DISCLAIMER:**
[Clear statement about seeking professional medical help]
Provide detailed, accurate, and helpful information while being clear this is preliminary guidance only.`;
const result = await generateWithFallback(genAI, groqClient, prompt, {
temperature: 0.3,
maxOutputTokens: 600
});
console.log('✅ Analysis complete');
res.json({
analysis: result.text,
success: true,
modelUsed: result.modelUsed,
provider: result.provider
});
}));
// 3. Medical Report Summary
app.post('/api/summarize-report', requireLogin, wrapAsync(async (req, res) => {
const { reportText, reportType } = req.body;
if (!reportText) {
throw new AppError('Report text is required', 400);
}
console.log('📄 Summarizing report...');
const prompt = `You are a medical AI assistant specializing in explaining medical reports to patients.
**Report Type:** ${reportType || 'Medical Report'}
**Report Content:**
${reportText}
**Please provide a patient-friendly summary with:**
1. **KEY FINDINGS:** Main results from the report
2. **ABNORMAL VALUES:** Any values outside normal range (explain what they mean)
3. **WHAT IT MEANS:** Is not normal or what could be the implications and should the patient be concerned with doctor?
4. **NEXT STEPS:** Suggested actions or follow-up needed
5. **QUESTIONS TO ASK YOUR DOCTOR:** Important questions patient should ask
Use simple, non-technical language. Avoid medical jargon. Be clear and reassuring while being honest about findings.`;
const result = await generateWithFallback(genAI, groqClient, prompt, {
temperature: 0.4,
maxOutputTokens: 500
});
console.log('✅ Summary generated');
res.json({
summary: result.text,
success: true,
modelUsed: result.modelUsed,
provider: result.provider
});
}));
// 4. Medicine Information
app.post('/api/medicine-info', requireLogin, wrapAsync(async (req, res) => {
const { medicineName } = req.body;
if (!medicineName) {
throw new AppError('Medicine name is required', 400);
}
console.log('💊 Getting info for:', medicineName);
const prompt = `Provide accurate, patient-friendly information about the medicine: **${medicineName}**
Include the following sections:
**WHAT IT'S USED FOR:**
Primary uses and conditions it treats.
**HOW IT WORKS:**
Simple explanation of mechanism.
**COMMON SIDE EFFECTS:**
Most frequently reported side effects.
**IMPORTANT PRECAUTIONS:**
- Who should not take it
- Drug interactions to be aware of
- Special warnings
**WHEN TO CONSULT A DOCTOR:**
Signs that require immediate medical attention.
**IMPORTANT NOTE:**
Always remind to consult healthcare provider or pharmacist for personalized advice.
Keep information accurate and helpful. Use simple language.`;
const result = await generateWithFallback(genAI, groqClient, prompt, {
temperature: 0.3,
maxOutputTokens: 400
});
console.log('✅ Medicine info retrieved');
res.json({
info: result.text,
success: true,
modelUsed: result.modelUsed,
provider: result.provider
});
}));
// 5. Health Tips Generator
app.post('/api/health-tips', requireLogin, wrapAsync(async (req, res) => {
const { category, userProfile } = req.body;
console.log('💡 Generating tips for:', category);
const profileStr = userProfile ? JSON.stringify(userProfile) : 'General audience';
const prompt = `Generate 5 practical, evidence-based health tips for the category: **${category || 'General Health'}**
User Profile: ${profileStr}
**Format each tip as:**
**Tip #X: [Catchy Title]**
[Detailed explanation of the tip - 2-3 sentences]
Why it matters: [Brief benefit explanation]
Make tips:
- Actionable and specific
- Easy to implement in daily life
- Based on scientific evidence
- Motivating and positive
- Culturally sensitive
Provide exactly 5 tips, numbered 1-5.`;
const result = await generateWithFallback(genAI, groqClient, prompt, {
temperature: 0.7,
maxOutputTokens: 500
});
console.log('✅ Tips generated');
res.json({
tips: result.text,
success: true,
modelUsed: result.modelUsed,
provider: result.provider
});
}));
// 6. Diet Plan Generator
app.post('/api/diet-plan', requireLogin, wrapAsync(async (req, res) => {
const { goal, restrictions, preferences } = req.body;
console.log('🥗 Generating diet plan for goal:', goal);
const prompt = `Create a personalized one-day diet plan.
**Goal:** ${goal || 'General health'}
**Dietary Restrictions:** ${restrictions || 'None'}
**Preferences:** ${preferences || 'None'}
Provide:
**BREAKFAST (7-9 AM):**
- Meal description
- Approximate calories
- Key nutrients
**MID-MORNING SNACK (11 AM):**
- Snack suggestion
- Benefits
**LUNCH (1-2 PM):**
- Meal description
- Approximate calories
- Key nutrients
**EVENING SNACK (4-5 PM):**
- Snack suggestion
- Benefits
**DINNER (7-8 PM):**
- Meal description
- Approximate calories
- Key nutrients
**HYDRATION TIPS:**
Water intake recommendations
**NUTRITIONAL SUMMARY:**
Total approximate calories and macronutrient breakdown
Make it practical, affordable, and easy to prepare.`;
const result = await generateWithFallback(genAI, groqClient, prompt, {
temperature: 0.6,
maxOutputTokens: 800
});
console.log('✅ Diet plan generated');
res.json({
plan: result.text,
success: true,
modelUsed: result.modelUsed,
provider: result.provider
});
}));
// 7. Prescription Image Analysis
app.post('/api/read-prescription', requireLogin, wrapAsync(async (req, res) => {
const { imageBase64 } = req.body;
if (!imageBase64) {
throw new AppError('Image data is required', 400);
}
console.log('📸 Analyzing prescription image...');
const prompt = `Analyze this prescription image and extract all readable information.
Provide:
**MEDICINES PRESCRIBED:**
List each medicine with:
- Medicine name
- Dosage (strength)
- Frequency (how often to take)
- Duration (how many days)
**SPECIAL INSTRUCTIONS:**
Any additional notes or warnings
**DOCTOR INFORMATION:**
Doctor's name and credentials if visible
**DATE:**
Prescription date if visible
**IMPORTANT NOTES:**
- Highlight any unclear or unreadable parts
- Note if prescription needs verification
- Remind to consult pharmacist if unsure
Be accurate and clear. If something is unclear, state it explicitly.`;
const base64Data = imageBase64.includes(',')
? imageBase64.split(',')[1]
: imageBase64;
const imageParts = [
{
inlineData: {
data: base64Data,
mimeType: "image/jpeg"
}
}
];
const result = await generateWithFallback(genAI, groqClient, prompt, {