Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 2x 12x 12x 12x 12x 12x 12x 12x 12x 2x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 12x 12x | import { FolderOpen, RotateCcw, X } from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/ahuora-design-system/ui/button";
import { Progress } from "@/ahuora-design-system/ui/progress";
import {
useCoreMlCreateMutation,
useCoreMlUploadMlModelCreateMutation,
useLazyUploadsCsvInspectRetrieveQuery,
} from "@/api/apiStore.gen";
import { useMLTrainRefresh } from "@/hooks/cache/useMLTrainRefresh";
import { useProjectId } from "@/hooks/project";
import { scanCsvHeadersLocal } from "@/lib/uploads/csvHeader";
import { formatUploadProgress } from "@/lib/uploads/formatUploadProgress";
import { NUMERIC_COLUMNS_TOOLTIP } from "@/lib/uploads/importNotes";
import { isSameUploadedFileSelection } from "@/lib/uploads/isSameUploadedFileSelection";
import { resolveUploadActivityStatus } from "@/lib/uploads/resolveUploadActivityStatus";
import {
ML_INPUT_CSV_EXPIRY_NOTE,
PARTIAL_UPLOAD_EXPIRY_NOTE,
} from "@/lib/uploads/retention";
import { UploadActivityStatus } from "@/lib/uploads/UploadActivityStatus";
import { UploadWarningNotice } from "@/lib/uploads/UploadWarningNotice";
import { useResumableMultipartUpload } from "@/lib/uploads/useResumableMultipartUpload.ts";
import CSVUploader from "@/pages/flowsheet-page/multi-steady-state/CSVUploader";
/** Local or backend-confirmed header information shown during the ML upload flow. */
export type CsvHeaderPreviewState = {
headers: string[];
delimiter: string | null;
warnings: string[];
source: "local" | "backend";
};
interface UploadCSVProps {
simulationObject: number;
onCsvHeaderPreviewChange: (preview: CsvHeaderPreviewState | null) => void;
}
function isCsvFile(file: File): boolean {
return file.name.toLowerCase().endsWith(".csv");
}
export default function UploadCSV({
simulationObject,
onCsvHeaderPreviewChange,
}: UploadCSVProps) {
const fileInputRef = useRef<HTMLInputElement | null>(null);
const flowsheetId = Number(useProjectId());
const { refreshMLTrainDependencies } = useMLTrainRefresh();
const [isFinalizingUpload, setIsFinalizingUpload] = useState(false);
const [submitMlUpload] = useCoreMlCreateMutation();
const [inspectUploadedCsv] = useLazyUploadsCsvInspectRetrieveQuery();
const [uploadModel] = useCoreMlUploadMlModelCreateMutation();
const uploadContext = useMemo(
() => ({
purpose: "ml_training_csv" as const,
flowsheet_id: flowsheetId,
simulationObject_id: simulationObject,
}),
[flowsheetId, simulationObject],
);
const { state, startUpload, abortUpload, clearUploadState } =
useResumableMultipartUpload({
storageKey: `csv-upload:ml:${simulationObject}`,
context: uploadContext,
});
/** Attach a completed object-storage upload session to the ML model and refresh headers. */
async function finalizeUploadedCsv(uploadSessionId: string): Promise<void> {
setIsFinalizingUpload(true);
try {
await submitMlUpload({
uploadSession: {
simulationObject,
upload_session_id: Number(uploadSessionId),
},
}).unwrap();
refreshMLTrainDependencies();
try {
const confirmedHeaders = await inspectUploadedCsv(
{ uploadSessionId: Number(uploadSessionId) },
true,
).unwrap();
onCsvHeaderPreviewChange({
headers: confirmedHeaders.headers,
delimiter: confirmedHeaders.detected_delimiter,
warnings: confirmedHeaders.warnings ?? [],
source: "backend",
});
} catch {
// The backend header endpoint remains the source of truth in the next wizard step.
}
clearUploadState();
toast.success("CSV upload complete.");
} catch (error) {
toast.error("Upload finalization failed", {
description:
error instanceof Error
? error.message
: "The uploaded CSV could not be attached to the ML model.",
});
} finally {
setIsFinalizingUpload(false);
}
}
/** Upload a CSV to object storage, attach it to the ML model, and refresh headers. */
async function handleUpload(file: File): Promise<void> {
if (!isCsvFile(file)) {
toast.error("Unsupported file", {
description: "Please upload a CSV file.",
});
return;
}
try {
const localHeaders = await scanCsvHeadersLocal(file);
if (
localHeaders.guessedDelimiter == null ||
localHeaders.headers.length === 0
) {
toast.error("Unsupported CSV format", {
description:
localHeaders.warnings[0] ??
"Only UTF-8 CSV files with comma or semicolon delimiters are supported.",
});
return;
}
onCsvHeaderPreviewChange({
headers: localHeaders.headers,
delimiter: localHeaders.guessedDelimiter,
warnings: localHeaders.warnings,
source: "local",
});
if (isSameUploadedFileSelection(state, file)) {
toast.warning("CSV already uploaded", {
description:
"This file has already completed uploading. Use Finish upload if you still need to attach it.",
});
return;
}
const completedUpload = await startUpload(file);
await finalizeUploadedCsv(completedUpload.upload_session_id);
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") {
return;
}
toast.error("Upload failed", {
description:
error instanceof Error
? error.message
: "The CSV file could not be uploaded.",
});
}
}
const handleImportClick = () => {
fileInputRef.current?.click();
};
const importModel = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
try {
const jsonData = e.target?.result;
uploadModel({
uploadModel: {
json_data: jsonData,
simulationObject,
},
});
} catch (error) {
alert("Invalid JSON file");
}
};
reader.readAsText(file);
}
};
const showMultipartStatus = state.status !== "idle";
const uploadActivityStatus = resolveUploadActivityStatus({
uploadStatus: state.status,
progressPercentage: state.progress.percentage,
uploadingLabel: "Uploading the CSV to object storage.",
finalizingUploadLabel:
"Finishing the CSV upload before attaching it to the ML model.",
processingLabel: isFinalizingUpload
? "Finalizing the upload and attaching the CSV to the ML model."
: null,
isProcessing: isFinalizingUpload,
});
return (
<div className="flex flex-col gap-4">
<p>Upload your csv dataset</p>
<CSVUploader
onUpload={handleUpload}
accept=".csv,text/csv"
inputAriaLabel="Upload CSV file"
tooltipContent={NUMERIC_COLUMNS_TOOLTIP}
promptText={
state.status === "resume_available"
? "Resume upload by selecting the same CSV file again"
: "Drag a CSV file here, or click to upload"
}
/>
<div className="flex flex-col gap-1 text-xs text-muted-foreground">
<p>{ML_INPUT_CSV_EXPIRY_NOTE}</p>
</div>
{showMultipartStatus && (
<div className="rounded-lg border bg-muted/40 p-3 flex flex-col gap-3">
<div className="flex items-center justify-between gap-3">
<div className="flex flex-col gap-1">
<p className="text-sm font-medium">
{state.status === "uploading"
? "Uploading CSV to object storage"
: state.status === "resume_available"
? "A resumable upload is waiting"
: state.status === "uploaded"
? "CSV uploaded"
: state.status === "failed"
? "Upload failed"
: "Upload cancelled"}
</p>
{state.fileName && (
<p className="text-xs text-muted-foreground">
{state.fileName}
</p>
)}
</div>
<div className="flex items-center gap-2">
{state.status === "uploading" && (
<Button
variant="outline"
size="sm"
onClick={() => void abortUpload()}
>
<X className="w-4 h-4" />
Cancel
</Button>
)}
{(state.status === "resume_available" ||
state.status === "failed") && (
<Button variant="outline" size="sm" onClick={clearUploadState}>
<RotateCcw className="w-4 h-4" />
Start over
</Button>
)}
{state.status === "uploaded" && state.uploadSessionId && (
<Button
variant="outline"
size="sm"
disabled={isFinalizingUpload}
onClick={() =>
void finalizeUploadedCsv(state.uploadSessionId!)
}
>
Finish upload
</Button>
)}
</div>
</div>
<Progress
value={state.progress.percentage}
aria-label="ml-upload-progress"
/>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>{state.progress.percentage}%</span>
<span>
{formatUploadProgress(
state.progress.uploadedBytes,
state.progress.totalBytes,
)}
</span>
</div>
{state.error && <UploadWarningNotice message={state.error} />}
{state.status === "uploading" && (
<p className="text-xs text-muted-foreground">
{PARTIAL_UPLOAD_EXPIRY_NOTE}
</p>
)}
<UploadActivityStatus {...uploadActivityStatus} />
</div>
)}
<p>or</p>
<div>
<input
type="file"
accept=".json"
onChange={importModel}
ref={fileInputRef}
className="hidden"
/>
<Button variant="outline" onClick={handleImportClick}>
<FolderOpen />
Import Model
</Button>
</div>
</div>
);
}
|