File size: 5,838 Bytes
497bb49
fbf73ff
497bb49
fbf73ff
497bb49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbf73ff
497bb49
fbf73ff
 
 
497bb49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbf73ff
 
497bb49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbf73ff
497bb49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbf73ff
497bb49
fbf73ff
497bb49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbf73ff
497bb49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbf73ff
497bb49
 
 
 
fbf73ff
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
import { useState, useCallback, useRef, useEffect } from 'react'
import { apiClient } from '../api/client'
import type { SegmentationResult, JobStatus } from '../types'

// Polling interval in milliseconds
const POLLING_INTERVAL = 2000

/**
 * Hook for running segmentation with async job polling.
 *
 * Instead of waiting for the full inference to complete (which can timeout
 * on HuggingFace Spaces), this hook:
 * 1. Creates a job that returns immediately with a job ID
 * 2. Polls for job status/progress every 2 seconds
 * 3. Returns results when the job completes
 *
 * This avoids the ~60s gateway timeout on HF Spaces while providing
 * real-time progress updates to the user.
 */
export function useSegmentation() {
  // Result state
  const [result, setResult] = useState<SegmentationResult | null>(null)
  const [error, setError] = useState<string | null>(null)

  // Job tracking state
  const [jobId, setJobId] = useState<string | null>(null)
  const [jobStatus, setJobStatus] = useState<JobStatus | null>(null)
  const [progress, setProgress] = useState(0)
  const [progressMessage, setProgressMessage] = useState('')
  const [elapsedSeconds, setElapsedSeconds] = useState<number | undefined>(
    undefined
  )

  // Loading state - true from job creation until completion/failure
  const [isLoading, setIsLoading] = useState(false)

  // Refs for managing async operations
  const currentJobRef = useRef<string | null>(null)
  const pollingIntervalRef = useRef<number | null>(null)
  const abortControllerRef = useRef<AbortController | null>(null)

  /**
   * Stop polling for job status
   */
  const stopPolling = useCallback(() => {
    if (pollingIntervalRef.current) {
      clearInterval(pollingIntervalRef.current)
      pollingIntervalRef.current = null
    }
  }, [])

  /**
   * Poll for job status and update state
   */
  const pollJobStatus = useCallback(
    async (id: string, signal: AbortSignal) => {
      // Don't poll if this isn't the current job
      if (id !== currentJobRef.current) {
        stopPolling()
        return
      }

      try {
        const response = await apiClient.getJobStatus(id, signal)

        // Ignore results if job changed
        if (id !== currentJobRef.current) return

        // Update progress state
        setJobStatus(response.status)
        setProgress(response.progress)
        setProgressMessage(response.progressMessage)
        setElapsedSeconds(response.elapsedSeconds)

        // Handle completion
        if (response.status === 'completed' && response.result) {
          stopPolling()
          setIsLoading(false)
          setResult({
            dwiUrl: response.result.dwiUrl,
            predictionUrl: response.result.predictionUrl,
            metrics: {
              caseId: response.result.caseId,
              diceScore: response.result.diceScore,
              volumeMl: response.result.volumeMl,
              elapsedSeconds: response.result.elapsedSeconds,
            },
          })
        }

        // Handle failure
        if (response.status === 'failed') {
          stopPolling()
          setIsLoading(false)
          setError(response.error || 'Job failed')
          setResult(null)
        }
      } catch (err) {
        // Ignore abort errors
        if (err instanceof Error && err.name === 'AbortError') return

        // Don't stop polling on transient network errors - retry next interval
        console.warn('Polling error (will retry):', err)
      }
    },
    [stopPolling]
  )

  /**
   * Start segmentation job and begin polling
   */
  const runSegmentation = useCallback(
    async (caseId: string, fastMode = true) => {
      // Cancel any existing job/polling
      stopPolling()
      abortControllerRef.current?.abort()

      const abortController = new AbortController()
      abortControllerRef.current = abortController

      // Reset state
      setError(null)
      setResult(null)
      setProgress(0)
      setProgressMessage('Creating job...')
      setJobStatus('pending')
      setElapsedSeconds(undefined)
      setIsLoading(true)

      try {
        // Create the job
        const response = await apiClient.createSegmentJob(
          caseId,
          fastMode,
          abortController.signal
        )

        // Store job reference
        const newJobId = response.jobId
        setJobId(newJobId)
        currentJobRef.current = newJobId
        setJobStatus(response.status)
        setProgressMessage(response.message)

        // Start polling
        pollingIntervalRef.current = window.setInterval(() => {
          pollJobStatus(newJobId, abortController.signal)
        }, POLLING_INTERVAL)

        // Do an initial poll immediately
        await pollJobStatus(newJobId, abortController.signal)
      } catch (err) {
        // Ignore abort errors
        if (err instanceof Error && err.name === 'AbortError') return

        const message = err instanceof Error ? err.message : 'Failed to start job'
        setError(message)
        setIsLoading(false)
        setJobStatus('failed')
      }
    },
    [pollJobStatus, stopPolling]
  )

  /**
   * Cancel the current job (stops polling, clears loading state)
   */
  const cancelJob = useCallback(() => {
    stopPolling()
    abortControllerRef.current?.abort()
    currentJobRef.current = null
    setIsLoading(false)
    setJobStatus(null)
    setProgress(0)
    setProgressMessage('')
  }, [stopPolling])

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      stopPolling()
      abortControllerRef.current?.abort()
    }
  }, [stopPolling])

  return {
    // Result data
    result,
    error,

    // Job status
    jobId,
    jobStatus,
    progress,
    progressMessage,
    elapsedSeconds,

    // Loading state
    isLoading,

    // Actions
    runSegmentation,
    cancelJob,
  }
}