Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 12,817 Bytes
81cdd5f |
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 |
/*
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
*/
import React, {useEffect, useRef, useState} from 'react';
import IconBackArrow from '../icons/IconBackArrow';
import IconCodeBlocks from '../icons/IconCodeBlocks';
import IconWarning from '../icons/IconWarning';
import MCQOption from '../components/MCQOption';
import ChatMessage from '../components/ChatMessage';
import styles from './ChatScreen.module.css';
import TextWithTooltips from '../components/TextWithTooltips';
import {redactPhrases} from "../components/RedactedTextView.js";
import {CONDITION_TERMS} from "../data/constants.js";
import { fetchWithRetry } from '../utils/fetchWithRetry';
const API_ENDPOINTS = {
getCaseImage: (journeyId) => `/api/case/${journeyId}/stub`,
getCaseQuestions: (journeyId) => `/api/case/${journeyId}/all-questions`,
summarizeCase: (journeyId) => `/api/case/${journeyId}/summarize`,
};
const ChatScreen = ({journey, onNavigate, onShowDetails, cachedImage, onImageLoad, onGoToSummary}) => {
const [allQuestions, setAllQuestions] = useState([]);
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
const [messages, setMessages] = useState([]);
const [caseImage, setCaseImage] = useState(cachedImage || '');
const [modelResponseHistory, setModelResponseHistory] = useState([]);
const [isSummarizing, setIsSummarizing] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [isImageLoading, setIsImageLoading] = useState(true);
const [imageError, setImageError] = useState(false);
const [userActionHistory, setUserActionHistory] = useState({});
const chatWindowRef = useRef(null);
const timeoutIdsRef = useRef([]);
useEffect(() => {
if (chatWindowRef.current) {
chatWindowRef.current.scrollTo({
top: chatWindowRef.current.scrollHeight,
behavior: 'smooth'
});
}
}, [messages, isLoading]);
useEffect(() => {
const fetchImage = async () => {
if (cachedImage) {
setCaseImage(cachedImage);
setIsImageLoading(false);
return;
}
if (journey) {
setIsImageLoading(true);
setImageError(false);
try {
const response = await fetchWithRetry(API_ENDPOINTS.getCaseImage(journey.id));
if (!response.ok) throw new Error("Failed to fetch case image");
const data = await response.json();
const imageUrl = data.download_image_url;
setCaseImage(imageUrl);
if (onImageLoad) onImageLoad(imageUrl);
} catch (error) {
console.error("Error fetching case data:", error);
setImageError(true);
} finally {
setIsImageLoading(false);
}
}
};
fetchImage();
}, [journey, cachedImage, onImageLoad]);
useEffect(() => {
if (!journey) {
setIsLoading(false);
return;
}
const fetchQuestions = async () => {
setIsLoading(true);
setMessages([]);
try {
const response = await fetchWithRetry(API_ENDPOINTS.getCaseQuestions(journey.id));
if (!response.ok) throw new Error("Failed to fetch questions");
const questions = await response.json();
if (questions && questions.length > 0) {
const questionsWithIds = questions.map((q, index) => ({...q, id: `q-${journey.id}-${index}`}));
setAllQuestions(questionsWithIds);
setCurrentQuestionIndex(0);
displayQuestion(questionsWithIds[0], 0, questionsWithIds.length);
} else {
setMessages([{
type: 'system',
id: Date.now(),
content: "Sorry, I couldn't load the questions for this case. Try again later!"
}]);
}
} catch (error) {
console.error("Error fetching questions:", error);
setMessages([{
type: 'system',
id: Date.now(),
content: "Sorry, I couldn't load the questions for this case. Try again later!"
}]);
} finally {
setIsLoading(false);
}
};
fetchQuestions();
}, [journey]);
useEffect(() => {
return () => {
timeoutIdsRef.current.forEach(clearTimeout);
};
}, []);
const displayQuestion = (questionData, index, totalQuestions) => {
let questionText = `Question ${index + 1}: ${questionData.question}`;
if (index === 0) {
questionText = `Okay, let's start with Case ${journey.id.padStart(2, '0')}. ${questionData.question}`;
}
const questionMessage = {type: 'system', id: Date.now(), content: questionText};
const mcqMessage = {
type: 'mcq',
id: questionData.id || `q-${index}`,
data: questionData,
isLast: index === totalQuestions - 1,
incorrectAttempts: [],
isAnswered: false,
};
setMessages(prev => [...prev, questionMessage, mcqMessage]);
};
const handleSelectOption = (selectedOptionKey, messageId) => {
const currentMCQMessageIndex = messages.findIndex(m => m.id === messageId && !m.isAnswered);
if (currentMCQMessageIndex === -1) return;
const currentMCQMessage = messages[currentMCQMessageIndex];
const {answer, rationale, hint, choices, id: questionId} = currentMCQMessage.data;
const selectedOptionText = choices[selectedOptionKey];
const isCorrect = selectedOptionKey === answer;
setUserActionHistory(prev => {
const newHistory = {...prev};
if (!newHistory[questionId]) {
newHistory[questionId] = {attempt1: selectedOptionKey};
} else if (!newHistory[questionId].attempt2) {
newHistory[questionId] = {...newHistory[questionId], attempt2: selectedOptionKey};
}
return newHistory;
});
let userResponseMessage = {type: 'user', id: Date.now(), content: `You responded: "${selectedOptionText}"`};
const updatedMessages = messages.map(msg =>
msg.id === messageId ? {...msg, isAnswered: true} : msg
);
setMessages([...updatedMessages, userResponseMessage]);
let feedbackMessages = [];
const handleNextStep = (isQuestionComplete) => {
if (isQuestionComplete) {
setModelResponseHistory(prev => [...prev, currentMCQMessage.data]);
}
if (currentMCQMessage.isLast && isQuestionComplete) {
feedbackMessages.push({type: 'summary_button', id: Date.now() + 2});
} else if (isQuestionComplete) {
const nextIndex = currentQuestionIndex + 1;
if (nextIndex < allQuestions.length) {
const timerId = setTimeout(() => {
setCurrentQuestionIndex(nextIndex);
displayQuestion(allQuestions[nextIndex], nextIndex, allQuestions.length);
}, 1500);
timeoutIdsRef.current.push(timerId);
}
}
};
let redactedRationale = "";
if (!currentMCQMessage.isLast) {
redactedRationale = redactPhrases(rationale, CONDITION_TERMS);
} else {
redactedRationale = rationale
}
if (isCorrect) {
feedbackMessages.push({type: 'system', id: Date.now() + 1, content: `That's right. ${redactedRationale}`});
handleNextStep(true);
} else {
const attempts = [...currentMCQMessage.incorrectAttempts, selectedOptionKey];
if (attempts.length < 2) {
feedbackMessages.push({
type: 'system_hint', id: Date.now() + 1,
content: `That's not quite right. Would you like to try again?`,
hint: `Hint: ${hint}`,
});
feedbackMessages.push({
...currentMCQMessage, type: 'mcq_retry', id: Date.now() + 2,
incorrectAttempts: attempts, isAnswered: false,
});
} else {
feedbackMessages.push({
type: 'system', id: Date.now() + 1,
content: `That's not right. The correct answer is "${choices[answer]}". ${redactedRationale}`
});
handleNextStep(true);
}
}
const timerId = setTimeout(() => {
setMessages(prev => [...prev, ...feedbackMessages]);
}, 800);
timeoutIdsRef.current.push(timerId);
};
const handleGoToSummary = async () => {
setIsSummarizing(true);
const conversation_history = modelResponseHistory.map(modelResponse => {
const userResponse = userActionHistory[modelResponse.id] || {};
const finalUserResponse = {
attempt1: userResponse.attempt1 || null,
attempt2: userResponse.attempt2 || null,
};
return {
ModelResponse: modelResponse,
UserResponse: finalUserResponse
};
});
try {
const response = await fetchWithRetry(API_ENDPOINTS.summarizeCase(journey.id), {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({conversation_history})
});
if (!response.ok) {
throw new Error(`Failed to fetch summary. Status: ${response.status}`);
}
const summaryData = await response.json();
onGoToSummary(summaryData);
} catch (error) {
console.error("Error fetching summary:", error);
setMessages(prev => [...prev, {
type: 'system',
id: Date.now(),
content: "Sorry, there was an error generating the summary.Please try again."
}]);
} finally {
setIsSummarizing(false);
}
};
return (
<div className={styles.pageContainer}>
<div className={styles.topNav}>
<button className={styles.navButton} onClick={() => onNavigate('landing')}>
<IconBackArrow/> <span>Exit</span>
</button>
<button className={styles.detailsButton} onClick={onShowDetails}>
<IconCodeBlocks fill="#004A77"/> Details about this Demo
</button>
</div>
<div className={styles.contentBox}>
<div className={styles.mainLayout}>
<div className={styles.leftPanel}>
{isImageLoading ? (
<div className={styles.loadingContainer}>
<div className={styles.loadingSpinner}></div>
<p className={styles.loadingText}>Loading Chest X-Ray image...</p>
</div>
) : imageError ? (
<div className={styles.imageErrorFallback}>
<p>⚠️</p>
<p>Could not load case image. Please try again.</p>
</div>
) : (
<img
src={caseImage}
alt={`Image for Case ${journey.label}`}
className={styles.caseImage}
/>
)}
</div>
<div className={styles.rightPanel}>
{!isLoading && allQuestions.length > 0 && (
<div className={styles.progressTracker}>
{modelResponseHistory.length} / {allQuestions.length} questions answered
</div>
)}
<div className={styles.chatWindow} ref={chatWindowRef}>
{isLoading ? (
<div className={styles.loadingContainer}>
<div className={styles.loadingSpinner}></div>
<p className={styles.loadingText}>Loading questions...</p>
</div>
) : (
messages.map((msg) => {
switch (msg.type) {
case 'mcq':
case 'mcq_retry':
return (
<div key={msg.id} className={styles.mcqOptionsOnly}>
{Object.entries(msg.data.choices).map(([key, value]) => (
<MCQOption
key={key}
text={value}
onClick={() => handleSelectOption(key, msg.id)}
disabled={msg.isAnswered || msg.incorrectAttempts.includes(key)}
isIncorrect={msg.incorrectAttempts.includes(key)}
/>
))}
</div>
);
case 'user':
return (
<ChatMessage key={msg.id} type="user" text={msg.content}/>
);
case 'system':
case 'system_hint':
return (
<ChatMessage key={msg.id} type="system">
<p>
<TextWithTooltips text={msg.content}/>
</p>
{msg.hint && (
<p className={styles.hintText}>
<TextWithTooltips text={msg.hint}/>
</p>
)}
</ChatMessage>
);
case 'summary_button':
return (
<div key={msg.id} className={styles.summaryButtonContainer}>
<button onClick={handleGoToSummary} className={styles.summaryButton} disabled={isSummarizing}>
{isSummarizing ? 'Generating Summary...' : 'Go to case review and summary'}
</button>
</div>
);
default:
return null;
}
})
)}
</div>
<div className={styles.disclaimerBox}>
<IconWarning className={styles.disclaimerIcon}/>
<p className={styles.disclaimerText}>This demonstration is for illustrative purposes of MedGemma’s
baseline capabilities only. It does not represent a finished or approved product, is not intended to
diagnose or suggest treatment of any disease or condition, and should not be used for medical
advice.</p>
</div>
</div>
</div>
</div>
</div>
);
};
export default ChatScreen; |