File size: 15,536 Bytes
6df1c09
9e1ba1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6df1c09
 
 
bf5da6b
 
e134c3f
 
 
bf5da6b
 
 
6df1c09
9b88237
 
 
 
 
 
6df1c09
 
 
 
09a360c
6df1c09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e369f2
6df1c09
3e369f2
3e95f42
 
e134c3f
 
 
 
 
 
 
3e95f42
e134c3f
c5a7e19
 
 
 
 
 
 
 
 
 
 
 
9e1ba1f
 
 
 
 
 
 
 
 
 
 
 
a453100
 
 
 
9e1ba1f
9eef730
3e369f2
3e95f42
 
 
 
 
 
 
 
 
 
e134c3f
3e95f42
 
6df1c09
3e95f42
 
 
 
8170b74
3e95f42
 
 
 
 
 
 
 
 
 
 
6df1c09
c5a7e19
 
 
 
 
 
 
46b55cb
c5a7e19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
789e997
c5a7e19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
789e997
c5a7e19
 
 
 
 
 
 
 
 
 
e134c3f
c5a7e19
 
e134c3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
789e997
bf5da6b
e134c3f
 
9e1ba1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e134c3f
9e1ba1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e134c3f
9e1ba1f
 
 
e134c3f
3e369f2
e134c3f
 
 
 
3e369f2
e134c3f
 
 
 
 
 
 
 
 
 
8170b74
 
bf6bb9b
c5a7e19
 
 
 
 
 
 
 
 
bf6bb9b
 
 
 
 
 
 
 
 
e134c3f
 
 
 
 
095c768
 
e134c3f
 
 
6df1c09
e134c3f
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
import { useState } from "react";

/* Minimal inline SVG icon components to avoid requiring 'lucide-react' */
const DownloadIcon = ({ className }: { className?: string }) => (
  <svg className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
    <path d="M12 3v12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    <path d="M8 11l4 4 4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    <path d="M21 21H3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

const FileTextIcon = ({ className }: { className?: string }) => (
  <svg className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    <path d="M14 2v6h6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    <path d="M16 13H8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    <path d="M16 17H8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

const Loader2Icon = ({ className }: { className?: string }) => (
  <svg className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
    <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" strokeOpacity="0.25"/>
    <path d="M22 12a10 10 0 0 0-10-10" stroke="currentColor" strokeWidth="4" strokeLinecap="round"/>
  </svg>
);

import { ImageWithFallback } from "./ImageWithFallback";
import { ReportModal } from "./ReportModal";
import axios from "axios";

interface ResultsPanelProps {
  uploadedImage: string | null;
  result?: any;
  loading?: boolean;
}

export function ResultsPanel({ uploadedImage, result, loading }: ResultsPanelProps) {
  const [showReportModal, setShowReportModal] = useState(false);
  // Make loading detection robust: sometimes values arrive as the string "true" from deployed envs
  const isLoading = loading === true || String(loading) === "true";

  // Helpful debug information when checking issues on deployed spaces (open browser devtools)
  // Keep as debug (console.debug) so it doesn't clutter normal logs.
  console.debug("ResultsPanel: props", { loading, isLoading, result });
  
  const handleGenerateReport = async (formData: FormData) => {
    try {
      const baseURL = import.meta.env.MODE === "development"
        ? "http://127.0.0.1:7860"
        : window.location.origin;
      const response = await axios.post(`${baseURL}/reports/`, formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });

      if (response.data.html_url) {
        // Open report in new tab
        window.open(`${baseURL}${response.data.html_url}`, "_blank");
      }
      if (response.data.pdf_url) {
        // Open PDF in new tab when available
        window.open(`${baseURL}${response.data.pdf_url}`, "_blank");
      }
      
      setShowReportModal(false);
    } catch (err: any) {
      console.error("Failed to generate report:", err);
      alert(err.response?.data?.error || "Failed to generate report");
    }
  };

  // Safely destructure result (keep undefined values when result is null) so we can render
  // a stable panel while loading and avoid early returns that change layout.
  const {
    model_used,
    detections,
    annotated_image_url,
    summary,
    // prediction (not used here)
    confidence,
  } = (result || {}) as any;

  const handleDownload = () => {
    if (annotated_image_url) {
      const link = document.createElement("a");
      link.href = annotated_image_url;
      link.download = "analysis_result.jpg";
      // For Firefox it is necessary to add the link to the DOM
      document.body.appendChild(link);
      link.click();
      link.remove();
    }
  };

  // Precompute some helpers for rendering confidences
  const isCINModel = /cin/i.test(String(model_used || ""));
  // Determine predicted class from summary.prediction if available, otherwise pick the highest confidence
  const predictedClassFromConfidence = (conf: any) => {
    try {
      const entries = Object.entries(conf || {});
      if (entries.length === 0) return "";
      return entries.reduce((a: any, b: any) => (Number(a[1]) > Number(b[1]) ? a : b))[0];
    } catch (e) {
      return "";
    }
  };
  // Prefer the class key present in the `confidence` object to ensure we use the exact key/casing
  // (this avoids showing all bars when `summary.prediction` has different casing/format).
  const predictedClass = predictedClassFromConfidence(confidence || {}) ||
    ((summary && (summary.prediction || summary.result)) ? String(summary.prediction || summary.result) : "");

  

  return (
    <div className="bg-white rounded-lg shadow-sm p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h2 className="text-2xl font-bold text-gray-800">
            {model_used || "Analysis Result"}
          </h2>
          <p className="text-sm text-gray-500">Automated Image Analysis</p>
        </div>

        {/* header actions intentionally empty; Generate Report button moved below analysis details */}
      </div>

      {/* If we're loading, show a centered loader inside the panel */}
      {isLoading ? (
        <div className="bg-white rounded-lg shadow-sm p-6 flex flex-col items-center justify-center"> 
          <Loader2Icon className="w-10 h-10 text-blue-600 animate-spin mb-3" /> 
          <p className="text-teal-700 font-medium">Analyzing image...</p> 
        </div>
      ) : (
        // Image
        <div className="relative mb-6 rounded-lg overflow-hidden border border-gray-200">
          <ImageWithFallback
            src={annotated_image_url || uploadedImage || "/ui.jpg"}
            alt="Analysis Result"
            className="w-full h-64 object-cover"
          />
        </div>
      )}

    {/* Summary Section - model-specific rendering (colposcopy, cytology, histopathology) */}
    {summary && (() => {
      const model = (model_used || "").toString();
      const isColpo = /colpo|colposcopy/i.test(model);
      const isCyto = /cyto|cytology/i.test(model);
      const isHistoLike = /mwt|cin|histopath/i.test(model);

      // ------helper values
      const abnormalCount = Number(summary.abnormal_cells) || 0;
      const pred = (summary.prediction || summary.result || "").toString().toLowerCase();
      const isAbnormal = abnormalCount > 0 || /abnormal|positive|high-grade|malignant/.test(pred);

      // Colposcopy: show only Abnormal / Normal (based on abnormal_cells count or prediction)
      if (isColpo) {
        return (
          <div className="bg-gray-50 p-4 rounded-lg mb-6">
            <h3 className="text-lg font-semibold text-gray-800 mb-2">AI Summary</h3>
            <p className="text-gray-700 text-sm">
              <strong>Result:</strong> {isAbnormal ? "Abnormal" : "Normal"}
            </p>
            <div className="mt-3 text-gray-800 text-sm italic border-t pt-2">
              {summary.ai_interpretation || "No AI interpretation available."}
            </div>
          </div>
        );
      }

      // Cytology: keep existing detailed summary (abnormal/normal counts + avg confidence + interpretation)
      if (isCyto) {
        return (
          <div className="bg-gray-50 p-4 rounded-lg mb-6">
            <h3 className="text-lg font-semibold text-gray-800 mb-2">AI Summary</h3>
            <p className="text-gray-700 text-sm leading-relaxed">
              {typeof summary.abnormal_cells !== 'undefined' && (
                <><strong>Abnormal Cells:</strong> {summary.abnormal_cells} <br /></>
              )}
              {typeof summary.normal_cells !== 'undefined' && (
                <><strong>Normal Cells:</strong> {summary.normal_cells} <br /></>
              )}
              {/* average confidence removed */}
            </p>
            <div className="mt-3 text-gray-800 text-sm italic border-t pt-2">
              {summary.ai_interpretation || "No AI interpretation available."}
            </div>
          </div>
        );
      }

      // Histopathology / CIN / MWT: show average confidence prominently + interpretation
      if (isHistoLike) {
        return (
          <div className="bg-gray-50 p-4 rounded-lg mb-6">
            <h3 className="text-lg font-semibold text-gray-800 mb-2">AI Summary</h3>
            <div className="mt-3 text-gray-800 text-sm italic border-t pt-2">
              {summary.ai_interpretation || "No AI interpretation available."}
            </div>
          </div>
        );
      }

      // Fallback: render only the fields that exist to avoid empty labels
      return (
        <div className="bg-gray-50 p-4 rounded-lg mb-6">
          <h3 className="text-lg font-semibold text-gray-800 mb-2">AI Summary</h3>
            <p className="text-gray-700 text-sm leading-relaxed">
            {typeof summary.abnormal_cells !== 'undefined' && (
              <><strong>Abnormal Cells:</strong> {summary.abnormal_cells} <br /></>
            )}
            {typeof summary.normal_cells !== 'undefined' && (
              <><strong>Normal Cells:</strong> {summary.normal_cells} <br /></>
            )}
          </p>
          <div className="mt-3 text-gray-800 text-sm italic border-t pt-2">
            {summary.ai_interpretation || "No AI interpretation available."}
          </div>
        </div>
      );
    })()}

    {/* Detection list */}
    {detections && detections.length > 0 && (
      <div className="mb-6">
        <h4 className="font-semibold text-gray-900 mb-3">
          Detected Objects
        </h4>
        <ul className="text-sm text-gray-700 list-disc list-inside space-y-1">
          {detections.map((det: any, i: number) => (
            <li key={i}>
              {det.name || "Object"} – {(det.confidence * 100).toFixed(1)}%
            </li>
          ))}
        </ul>
      </div>
    )}

    {/* Probability / MWT visualization */}
    {confidence && (
      <div className="mb-6">
        <h4 className="font-semibold text-gray-900 mb-3">Confidence Levels</h4>

        {/* If MWT, CIN, or Histopathology classifier, show a visual bar for average confidence and per-class bars */}
        {model_used && /mwt|cin|histopathology/i.test(model_used) ? (
          <div>
            {/* Average confidence bar */}
            {/* Average confidence removed from visualization */}

            {/* Per-class bars */}
            <div className="space-y-2">
              {isCINModel ? (
                // For CIN/colposcopy classifiers, show ONLY the predicted grade (no bars for other classes)
                (() => {
                  const cls = String(predictedClass || "");
                  const val = (confidence && (confidence as any)[cls]) || 0;
                  const num = Number(val) || 0;
                  const pct = num * 100;
                  const isNegative = cls.toLowerCase().includes("negative") ||
                                    cls.toLowerCase().includes("benign") ||
                                    cls.toLowerCase().includes("low-grade") ||
                                    cls.toLowerCase().includes("cin1");

                  if (!cls) {
                    return <div className="text-sm text-gray-600">Prediction not available.</div>;
                  }

                  return (
                    <div key={cls}>
                      <div className="flex items-center justify-between text-sm mb-1">
                        <span className="text-gray-700">{cls}</span>
                        <span className="text-gray-600">{pct.toFixed(2)}%</span>
                      </div>
                      <div className="w-full bg-gray-100 rounded-full h-3">
                        <div
                          className={`h-3 rounded-full ${isNegative ? "bg-green-500" : "bg-red-500"}`}
                          style={{ width: `${pct.toFixed(2)}%` }}
                        />
                      </div>
                    </div>
                  );
                })()
              ) : (
                Object.entries(confidence).map(([cls, val]) => {
                  const num = Number(val as any) || 0;
                  const pct = (num * 100);
                  
                  // Color coding: Positive/Malignant/High-grade = red, Negative/Benign/Low-grade = green
                  const isNegative = cls.toLowerCase().includes("negative") || 
                                    cls.toLowerCase().includes("benign") || 
                                    cls.toLowerCase().includes("low-grade");
                  
                  return (
                    <div key={cls}>
                      <div className="flex items-center justify-between text-sm mb-1">
                        <span className="text-gray-700">{cls}</span>
                        <span className="text-gray-600">{pct.toFixed(2)}%</span>
                      </div>
                      <div className="w-full bg-gray-100 rounded-full h-3">
                        <div
                          className={`h-3 rounded-full ${isNegative ? "bg-green-500" : "bg-red-500"}`}
                          style={{ width: `${pct.toFixed(2)}%` }}
                        />
                      </div>
                    </div>
                  );
                })
              )}
            </div>

            {/* Mistral comment */}
            <div className="mt-4 bg-gray-50 p-3 rounded-lg text-sm italic text-gray-800 border-t">
              {summary?.ai_interpretation || "No AI interpretation available."}
            </div>
          </div>
        ) : (
          // Fallback display for non-MWT models
          <pre className="bg-gray-100 rounded-lg p-3 text-sm overflow-x-auto">
            {JSON.stringify(confidence, null, 2)}
          </pre>
        )}
      </div>
    )}

    {/* Report Generation Modal */}
    {/* Show only when not loading and we have at least a result (so Generate Report is available even if summary/confidence are missing) */}
    {!isLoading && result && (
      <div className="flex items-center justify-end mb-6">
        {annotated_image_url && (
          <button
            onClick={handleDownload}
            className="flex items-center gap-2 mr-3 bg-gradient-to-r from-teal-700 via-teal-600 to-teal-700 text-white px-4 py-2 rounded-lg hover:opacity-90 transition-all"
          >
            <DownloadIcon className="w-4 h-4" />
            Download Image
          </button>
        )}
        <button
          onClick={() => setShowReportModal(true)}
          className="flex items-center gap-2 bg-gradient-to-r from-teal-700 via-teal-600 to-teal-700 text-white px-4 py-2 rounded-lg hover:opacity-90 transition-all"
        >
          <FileTextIcon className="w-4 h-4" />
          Generate Report
        </button>
      </div>
    )}
    <ReportModal 
      isOpen={showReportModal}
      onClose={() => setShowReportModal(false)}
      onSubmit={handleGenerateReport}
      analysisId={annotated_image_url || ""}
      // Include annotated_image_url in the analysis summary so the backend can embed it
      analysisSummaryJson={summary ? JSON.stringify({ ...summary, model_used, confidence, annotated_image_url }) : "{}"}
    />
  </div>
  );
}