File size: 104,664 Bytes
29c4f64
7eaf4b6
29c4f64
c824944
29c4f64
c824944
 
29c4f64
 
c824944
29c4f64
 
ae2f7ce
c824944
29c4f64
 
7c7f04f
 
c824944
da84373
 
7c7f04f
c824944
29c4f64
c824944
29c4f64
 
 
 
 
 
7eaf4b6
29c4f64
7c7f04f
29c4f64
b9e9c38
2d94de0
c824944
 
 
 
35c5863
c824944
 
 
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
29c4f64
c824944
 
29c4f64
c824944
 
 
 
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
3517146
29c4f64
 
 
c824944
 
29c4f64
 
c824944
 
29c4f64
 
 
7c7f04f
c824944
 
 
 
 
 
 
29c4f64
c824944
29c4f64
3517146
c824944
29c4f64
 
 
ea99d0b
 
 
29c4f64
 
 
ea99d0b
 
29c4f64
ea99d0b
 
29c4f64
ea99d0b
 
ae2f7ce
29c4f64
 
ea99d0b
29c4f64
 
ea99d0b
 
 
 
 
ae2f7ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea99d0b
 
ae2f7ce
 
 
ea99d0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2f7ce
 
 
 
 
29c4f64
 
ae2f7ce
 
 
 
 
 
 
 
 
 
 
ea99d0b
ae2f7ce
 
ea99d0b
29c4f64
 
ae2f7ce
ea99d0b
29c4f64
ea99d0b
ae2f7ce
 
 
 
ea99d0b
29c4f64
ea99d0b
29c4f64
ea99d0b
 
 
ae2f7ce
ea99d0b
ae2f7ce
 
 
 
 
 
 
 
ea99d0b
29c4f64
ea99d0b
ae2f7ce
 
 
 
 
29c4f64
ae2f7ce
29c4f64
 
 
 
ea99d0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2f7ce
 
 
 
 
 
29c4f64
ae2f7ce
ea99d0b
ae2f7ce
 
 
29c4f64
ae2f7ce
 
 
 
 
 
ea99d0b
 
ae2f7ce
 
 
 
 
 
 
 
 
 
 
 
 
 
ea99d0b
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da84373
 
c824944
 
 
29c4f64
3517146
c824944
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
64231a6
 
 
c824944
64231a6
 
c824944
29c4f64
c824944
 
29c4f64
 
 
 
 
 
 
 
 
 
 
c824944
 
29c4f64
 
c824944
 
29c4f64
c824944
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
 
 
 
 
 
 
29c4f64
c824944
29c4f64
c824944
29c4f64
c824944
 
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
 
 
 
 
 
 
 
 
 
 
 
29c4f64
c824944
 
 
29c4f64
c824944
 
29c4f64
c824944
 
 
 
29c4f64
c824944
 
 
 
 
29c4f64
 
 
 
 
 
c824944
29c4f64
 
 
 
c824944
 
 
29c4f64
7d2a4ca
 
 
c824944
29c4f64
 
 
 
 
 
 
 
 
c824944
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
c824944
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
 
 
 
7c7f04f
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
da84373
 
 
7c7f04f
c824944
29c4f64
 
 
c824944
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
 
 
 
 
 
 
 
 
29c4f64
c824944
7c7f04f
c824944
 
 
7c7f04f
c824944
 
 
 
 
 
 
 
29c4f64
 
 
 
c824944
29c4f64
 
 
 
 
 
 
 
c824944
 
 
 
 
 
29c4f64
 
 
 
 
 
 
c824944
29c4f64
c824944
29c4f64
 
 
 
 
 
 
 
 
 
 
 
7c7f04f
c824944
 
29c4f64
 
 
 
c824944
29c4f64
c824944
 
29c4f64
c824944
 
29c4f64
c824944
 
 
 
29c4f64
 
 
c824944
 
 
 
 
 
 
 
29c4f64
c824944
29c4f64
 
 
 
 
c824944
 
 
 
 
 
 
29c4f64
 
 
 
c824944
29c4f64
 
 
c824944
 
 
 
 
 
 
7c7f04f
29c4f64
c824944
3517146
c824944
29c4f64
 
 
7c7f04f
 
c824944
 
29c4f64
c824944
29c4f64
c824944
29c4f64
 
 
 
 
 
 
 
c824944
29c4f64
 
 
 
 
 
 
 
 
7c7f04f
 
 
c824944
7c7f04f
 
 
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
7c7f04f
29c4f64
 
7c7f04f
29c4f64
7c7f04f
 
 
29c4f64
c824944
 
 
 
 
373a0df
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373a0df
 
 
c824944
 
 
29c4f64
 
 
c824944
 
 
 
 
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
29c4f64
 
 
c824944
373a0df
29c4f64
 
 
c824944
 
373a0df
29c4f64
 
c824944
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
 
 
 
29c4f64
c824944
 
 
 
ae2f7ce
 
29c4f64
ae2f7ce
29c4f64
 
 
 
 
 
 
 
da84373
ae2f7ce
 
 
 
 
 
29c4f64
 
ae2f7ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29c4f64
 
 
 
ae2f7ce
 
29c4f64
 
 
 
 
 
 
 
 
ae2f7ce
 
29c4f64
 
 
ae2f7ce
 
 
 
 
 
 
da84373
ae2f7ce
 
 
 
 
 
 
 
 
 
 
 
 
da84373
 
ae2f7ce
 
 
da84373
 
ae2f7ce
 
da84373
ae2f7ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2f7ce
29c4f64
 
 
 
 
 
 
ae2f7ce
29c4f64
 
 
 
 
 
da84373
ae2f7ce
 
c824944
 
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3517146
29c4f64
 
 
 
 
 
da84373
29c4f64
c824944
29c4f64
c824944
 
7c7f04f
29c4f64
 
 
 
 
c824944
29c4f64
7c7f04f
29c4f64
7c7f04f
c824944
 
da84373
c824944
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
29c4f64
c824944
29c4f64
 
 
 
 
 
 
 
c824944
29c4f64
 
 
 
 
 
 
c824944
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c824944
29c4f64
 
 
 
 
 
 
 
 
c824944
29c4f64
c824944
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
c824944
 
 
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea99d0b
c824944
 
 
7c7f04f
ea99d0b
 
90d9092
ae2f7ce
 
 
 
 
 
 
 
 
ea99d0b
29c4f64
 
 
da84373
ae2f7ce
 
 
 
 
 
 
 
 
 
 
 
 
 
29c4f64
ae2f7ce
 
29c4f64
 
ea99d0b
 
ae2f7ce
 
 
 
 
ea99d0b
 
ae2f7ce
 
 
 
 
 
 
ea99d0b
 
 
29c4f64
 
ae2f7ce
 
29c4f64
 
 
 
ae2f7ce
 
 
 
 
 
29c4f64
ae2f7ce
 
 
 
29c4f64
ae2f7ce
 
 
 
 
 
 
 
 
29c4f64
ae2f7ce
 
29c4f64
 
 
 
13a41e9
 
29c4f64
ae2f7ce
29c4f64
 
13a41e9
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13a41e9
29c4f64
ae2f7ce
29c4f64
 
ae2f7ce
13a41e9
ae2f7ce
 
29c4f64
ae2f7ce
29c4f64
 
ae2f7ce
 
 
29c4f64
ae2f7ce
29c4f64
 
 
ae2f7ce
29c4f64
 
 
ae2f7ce
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2f7ce
13a41e9
29c4f64
 
 
 
13a41e9
29c4f64
 
 
 
ea99d0b
29c4f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea99d0b
da84373
ae2f7ce
 
 
 
 
 
 
 
 
 
 
 
 
 
29c4f64
ae2f7ce
 
 
 
 
29c4f64
ae2f7ce
 
 
 
 
29c4f64
ae2f7ce
 
 
 
 
 
29c4f64
ae2f7ce
 
 
 
 
 
29c4f64
ae2f7ce
 
 
 
 
29c4f64
ae2f7ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29c4f64
ae2f7ce
 
29c4f64
ae2f7ce
 
 
 
 
 
 
 
 
 
 
29c4f64
ae2f7ce
29c4f64
ae2f7ce
 
 
 
 
 
 
 
29c4f64
ae2f7ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29c4f64
ae2f7ce
29c4f64
ae2f7ce
 
 
 
 
 
 
 
29c4f64
ae2f7ce
 
 
 
 
 
 
 
 
29c4f64
ae2f7ce
 
 
29c4f64
ae2f7ce
 
 
 
 
 
 
c824944
29c4f64
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
# app.py
import os
import hashlib
import io
import json
import math
import zipfile
import time
import random
import tempfile
import uuid
import streamlit.components.v1 as components
from textwrap import dedent
from pathlib import Path
from typing import Optional, List, Dict, Tuple

import numpy as np
import pandas as pd
import nibabel as nib
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
from matplotlib import animation
from PIL import Image, ImageDraw, ImageFont
from skimage.measure import label as cc_label, regionprops
from scipy.ndimage import (
    binary_fill_holes,
    binary_dilation,
    binary_closing,
)  # use SciPy morphology
from skimage.morphology import disk  
import streamlit as st
import base64  

from streamlit_drawable_canvas import st_canvas
from utils.layer_util import ResizeAndConcatenate

# =========================
#      Config / paths
# =========================
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# Uncomment next line to force CPU only
# os.environ["CUDA_VISIBLE_DEVICES"] = ""

MODEL_PATH = "./models_final/SEG459.h5"

# ---------------------------------------------------------
# Keras custom_objects safety:
# If the saved model references these symbols by name, Keras
# may try to resolve them even with compile=False.
# Provide harmless dummy callables instead of None.
# ---------------------------------------------------------
def _dummy(*args, **kwargs):
    # Works for losses/metrics/custom functions; never used for inference.
    return tf.constant(0.0)

_CUSTOM_OBJECTS = {
    "focal_tversky_loss": _dummy,
    "dice_coef_no_bkg": _dummy,
    "ResizeAndConcatenate": ResizeAndConcatenate,  # must stay real
    "dice_myo": _dummy,
    "dice_blood": _dummy,
    "dice": _dummy,
}


@st.cache_resource(show_spinner=False)
def get_model():
    # Optional: avoid re-tracing / keep memory stable in some environments
    # tf.keras.backend.clear_session()
    return keras.models.load_model(
        MODEL_PATH,
        custom_objects=_CUSTOM_OBJECTS,
        compile=False,
    )


OUTPUT_ROOT = "/tmp/NIFTI_OUTPUTS"


# Inference & metrics settings
SIZE_X, SIZE_Y = 256, 256  # UNet3+ input grid
TARGET_HW = (SIZE_Y, SIZE_X)
N_CLASSES = 3
BATCH_SIZE = 16
MYO_DENSITY = 1.05  # g/mL β†’ mg via mm^3 * g/mL

# Resize mode for input images -> model grid
RESIZE_MODE = "auto"  # "auto", "bilinear", "area", or "fft"


# --- Progress weights (must sum to 1.0) ---
W_LOAD_PREP = 0.15
W_PREDICT   = 0.65
W_POST_GIF  = 0.20

assert abs((W_LOAD_PREP + W_PREDICT + W_POST_GIF) - 1.0) < 1e-6


# Island removal (3D)
ENABLE_ISLAND_REMOVAL = True
ISLAND_MIN_SLICE_SPAN = 2
ISLAND_MIN_AREA_PER_SLICE = 10
ISLAND_CENTROID_DIST_THRESH = 40

# Orientation / display
ORIENT_TARGET = None  # None (keep native), "LPS", or "RAS"
DISPLAY_MATCH_DICOM = False
DISPLAY_RULES = {
    "LPS": dict(rot90_cw=True, flip_ud=True, flip_lr=False),
    "RAS": dict(rot90_cw=True, flip_ud=False, flip_lr=True),
    None: dict(rot90_cw=False, flip_ud=False, flip_lr=False),
}
CURRENT_DISPLAY_ORIENT = ORIENT_TARGET

# ED/ES robust selection (mid-slices subset)
USE_MID_SLICES_FOR_ED_ES = True
MID_K = 4
MID_MIN_VALID_FRAC = 0.7
MID_A_BLOOD_MIN = 30
MID_A_MYO_MIN = 30

GIF_FPS = 1
GIF_DPI = 300

# Bigger drawing canvas for manual corrections (display only; masks still 256x256)
CANVAS_SCALE = 3  # 2x/3x/4x larger canvas than model grid

# =========================
#      Branding / UI
# =========================
LOGO_URL = (
    "https://raw.githubusercontent.com/whanisa/Segmentation/main/icon/logo.png"
)
LOGO_LINK = "https://github.com/whanisa/Segmentation"
LOGO_HEIGHT_PX = 120
SAFE_INSET_PX = 18


# --- CSS
def _inject_layout_css():
    # Tune these three knobs as needed
    CONTENT_MEASURE_PX = 920  # width of the hero + paragraphs column
    LEFT_OFFSET_PX = 40  # push BOTH text and uploader to the right (aligns with left gutter)
    UPLOAD_WIDTH_PX = 420  # make uploader column narrower

    st.markdown(
        f"""
    <style>
      :root {{
        --content-measure: {CONTENT_MEASURE_PX}px;
        --left-offset:     {LEFT_OFFSET_PX}px;
        --upload-width:    {UPLOAD_WIDTH_PX}px;

        /* Fixed-edge logo tunables */
        --logo-height: {LOGO_HEIGHT_PX}px;
        --edge-x: max(12px, env(safe-area-inset-left));
        /* Height of Streamlit/HF header; adjust to 40-56–64px if needed */
        --header-clear: 40px;
        --edge-y: calc(env(safe-area-inset-top) + var(--header-clear) + 0px);

        /* Gap below the logo before the tabs appear */
        --tabs-top-gap: calc(var(--logo-height) + 16px);

        /* Shift the tabs a bit to the right */
        --tabs-left-shift: 32px;

        /* Accent color for the active tab underline/text */
        --accent: #ef4444; /* red-500 */
      }}

      /* Ensure the fixed logo isn't clipped by Streamlit containers */
      .stApp, .appview-container, .main {{ overflow: visible !important; }}

      /* Compact page padding */
      .appview-container .main .block-container {{
        padding-top: 0.75rem;
        padding-bottom: 1rem;
      }}

      /* Outer wrapper */
      .content-wrap {{
        width: min(1300px, 100%);
        margin: 0 auto;
        padding: 0 18px;
        box-sizing: border-box;
      }}

      /* Text column (hero + paragraphs): same width + same left offset as uploader */
      .measure-wrap {{
        max-width: var(--content-measure);
        margin-left: var(--left-offset);
        margin-right: auto;
      }}

      /* ---- Fixed, far-left edge logo ---- */
      #fixed-edge-logo {{
        position: fixed;
        left: var(--edge-x);
        top: var(--edge-y);
        z-index: 1000;
        pointer-events: none;
      }}
      #fixed-edge-logo img {{
        height: var(--logo-height);
        width: auto;
        display: block;
      }}

      /* Spacer so tabs/hero don't hide under the fixed logo */
      .edge-logo-spacer {{ height: var(--tabs-top-gap); }}

      /* Title: justify both sides */
      .hero-title {{
        font-size: 40px;
        line-height: 1.25;
        font-weight: 800;
        margin: 0 0 20px;
        text-align: justify;
        text-justify: inter-word;
      }}

      .hero-title .sub {{
        display: block;
        font-size: 28px;
        line-height: 1.25;
        margin: 0;
      }}

      .text-wrap p {{
        margin: 0 0 14px 0;
        font-size: 17px;
        line-height: 1.5;
        text-align: justify;
        text-justify: inter-word;
        color: #333;
        hyphens: auto;
        -webkit-hyphens: auto;
        -ms-hyphens: auto;
      }}

      .text-wrap p a {{
        overflow-wrap: anywhere;
        word-break: break-word;
      }}

      .text-wrap a {{
        color: #0066cc;
        text-decoration: underline;
        text-underline-offset: 2px;
        text-decoration-thickness: 1.5px;
      }}

      .note-text {{
        font-size: 14px;
        color: #333;
        line-height: 1.4;
        margin-top: 4px;
      }}

      #upload-wrap {{
        max-width: var(--upload-width);
        margin-left: var(--left-offset);
        margin-right: auto;
      }}
      #upload-wrap [data-testid="stFileUploader"] {{
        width: 100% !important;
        margin-left: 0 !important;
        margin-right: 0 !important;
      }}
      #upload-wrap [data-testid="stFileUploaderDropzone"] {{
        padding-left: 0 !important;
        padding-right: 44px !important;
      }}

      /* ---- REAL Streamlit tabs styling and alignment ---- */
      div[data-testid="stTabs"] > div[role="tablist"],
      div[data-baseweb="tab-list"],
      .stTabs [role="tablist"] {{
        margin-left: calc(var(--left-offset) + var(--tabs-left-shift)) !important;
        margin-right: 18px !important;
        border-bottom: 0;
        padding-bottom: 6px;
      }}

      div[data-baseweb="tab-list"] button[role="tab"],
      .stTabs [role="tab"] {{
        color: #374151;
        background: transparent;
        border: none;
        outline: none;
        padding: 6px 14px 10px 14px;
        margin: 0 4px;
        font-weight: 600;
      }}

      div[data-baseweb="tab-list"] button[aria-selected="true"],
      .stTabs [role="tab"][aria-selected="true"] {{
        color: var(--accent) !important;
        border-bottom: 3px solid var(--accent) !important;
      }}
      div[data-baseweb="tab-highlight"] {{ display: none !important; }}

      @media (max-width: 480px) {{
        :root {{
          --logo-height: {max(48, int(LOGO_HEIGHT_PX*0.7))}px;
          --header-clear: 64px;
          --tabs-left-shift: 16px;
        }}
      }}


      /* Group wrapper: controls spacing between buttons */
      .dl-group {{
        display: flex;
        flex-direction: column;
        gap: 10px;
        margin-top: 8px;
      }}

      /* Each button row inside the group */
      .dl-row {{
        margin: 0 !important;
        padding: 0 !important;
      }}
 
      /* Tight stack for individual buttons */
      .dl-wrap {{ 
        margin: 0 !important; 
        padding: 0 !important; 
      }}
    

      /* Button look for grouped download links */
      a.dl-btn {{
        appearance: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;

        padding: 0.55rem 0.85rem;
        border-radius: 0.6rem;
        border: 1px solid rgba(49,51,63,.2);

        /* Use Streamlit theme vars if available; fall back safely */
        background: var(--background-color, white);
        color: var(--text-color, #111) !important;

        font-weight: 600;
        text-decoration: none !important;

        box-shadow: 0 1px 2px rgba(0,0,0,0.05);
        transition: all 0.15s ease;
        cursor: pointer;

        margin: 0 !important;
        user-select: none;
        -webkit-tap-highlight-color: transparent;
      }}
    
      a.dl-btn:hover {{
        color: var(--accent) !important;
        border-color: var(--accent) !important;
        box-shadow: 0 2px 6px rgba(239,68,68,0.25);
        transform: translateY(-1px);
      }}
    
      a.dl-btn.pressed {{
        background: var(--accent) !important;
        border-color: var(--accent) !important;
        color: white !important;
        box-shadow: 0 3px 10px rgba(239,68,68,0.35);
        transform: translateY(0);
      }}


      /* πŸ”₯ Remove Streamlit spacing */
      div[data-testid="stElementContainer"] {{
        margin-bottom: 0.2rem !important;
      }}

      /* Tighten Streamlit wrapper spacing around our download blocks */
      div[data-testid="stMarkdownContainer"]:has(.dl-wrap),
      div[data-testid="stVerticalBlock"] > div:has(.dl-wrap) {{
        margin-top: 0px !important;
        margin-bottom: 6px !important;
        padding-top: 0px !important;
        padding-bottom: 0px !important;
      }}

    </style>
    """,
        unsafe_allow_html=True,
    )


# =========================
#      Small utilities
# =========================
def log(msg: str):
    print(f"[INFO] {msg}")


def _safe_rerun():
    """Compatibility rerun for old/new Streamlit."""
    if hasattr(st, "rerun"):
        st.rerun()
    elif hasattr(st, "experimental_rerun"):
        st.experimental_rerun()
    else:
        # very old / unusual environment
        raise RuntimeError("No rerun method available in this Streamlit version.")



def get_nifti_SF_quick(path: str) -> Tuple[int, int]:
    img = nib.load(path)
    shape = img.shape  # (X,Y,Z) or (X,Y,Z,T)
    S = int(shape[2]) if len(shape) >= 3 else 1
    F = int(shape[3]) if len(shape) >= 4 else 1
    return S, F



def get_session_tmpdir() -> str:
    if "session_tmpdir" not in st.session_state:
        st.session_state["session_tmpdir"] = tempfile.mkdtemp(
            prefix=f"segapp_{uuid.uuid4().hex}_"
        )
    return st.session_state["session_tmpdir"]
    

def get_session_gifs_dir() -> str:
    d = os.path.join(get_session_tmpdir(), "GIFs")
    os.makedirs(d, exist_ok=True)
    return d

def get_session_csv_dir() -> str:
    d = os.path.join(get_session_tmpdir(), "CSV")
    os.makedirs(d, exist_ok=True)
    return d



def invalidate_download_caches():
    # Anything derived from cases/gifs that must be rebuilt after edits
    for k in [
        "mask_zip_bytes",
        "mask_zip_name",
        "mask_zip_bytes_corrected",
        "mask_zip_name_corrected",
        "gif_zip_bytes",
        "gif_zip_name",
        "gif_zip_bytes_corrected",
        "gif_zip_name_corrected",
    ]:
        st.session_state.pop(k, None)


        
def normalize_images(x):
    x = tf.convert_to_tensor(x, dtype=tf.float32)
    mn = tf.reduce_min(x, axis=[1, 2], keepdims=True)
    mx = tf.reduce_max(x, axis=[1, 2], keepdims=True)
    rng = mx - mn
    x_norm = tf.where(rng > 0.0, (x - mn) / rng, tf.zeros_like(x))
    return x_norm.numpy()


def _tf_resize_bilinear(img, *, target_h=SIZE_Y, target_w=SIZE_X):
    arr = img[np.newaxis, ..., np.newaxis].astype(np.float32)
    out = tf.image.resize(
        arr, [target_h, target_w], method="bilinear", antialias=True
    )
    return np.squeeze(out.numpy()).astype(np.float32)


def _tf_resize_auto(img, target_h=SIZE_Y, target_w=SIZE_X):
    H, W = img.shape
    method = "area" if (H > target_h or W > target_w) else "bilinear"
    arr = img[np.newaxis, ..., np.newaxis].astype(np.float32)
    out = tf.image.resize(arr, [target_h, target_w], method=method, antialias=True)
    return np.squeeze(out.numpy()).astype(np.float32)



def _resize_nn(img, new_h, new_w):
    arr = img[None, ..., None].astype(np.float32)
    out = tf.image.resize(arr, [new_h, new_w], method="nearest")
    return np.squeeze(out.numpy()).astype(img.dtype)


def _fft_kspace_resize(img, target_h=SIZE_Y, target_w=SIZE_X):
    """
    Resize via k-space:
      - Upsample: zero-fill
      - Downsample: crop center k-space
    """
    img = np.asarray(img, dtype=np.float32)
    H, W = img.shape

    if H == target_h and W == target_w:
        return img

    F = np.fft.fftshift(np.fft.fft2(img))

    # Create target k-space container
    kspace = np.zeros((target_h, target_w), dtype=np.complex64)

    # Compute copy ranges (centered)
    y_min = max(0, (target_h - H) // 2)
    x_min = max(0, (target_w - W) // 2)

    src_y_min = max(0, (H - target_h) // 2)
    src_x_min = max(0, (W - target_w) // 2)

    copy_h = min(H, target_h)
    copy_w = min(W, target_w)

    kspace[y_min:y_min + copy_h, x_min:x_min + copy_w] = \
        F[src_y_min:src_y_min + copy_h, src_x_min:src_x_min + copy_w]

    img_res = np.fft.ifft2(np.fft.ifftshift(kspace))
    return np.real(img_res).astype(np.float32)



def display_xform(img2d, orient_target=None, enable=DISPLAY_MATCH_DICOM):
    if orient_target is None:
        orient_target = CURRENT_DISPLAY_ORIENT
    if not enable:
        return img2d
    rule = DISPLAY_RULES.get(orient_target, DISPLAY_RULES[None])
    out = img2d
    if rule.get("rot90_cw"):
        out = np.rot90(out, k=-1)
    if rule.get("flip_ud"):
        out = np.flipud(out)
    if rule.get("flip_lr"):
        out = np.fliplr(out)
    return out


def _normalize_to_uint8(img2d: np.ndarray) -> np.ndarray:
    arr = np.asarray(img2d, dtype=np.float32)
    if arr.size == 0:
        return np.zeros_like(arr, dtype=np.uint8)
    mn = np.min(arr)
    mx = np.max(arr)
    if mx > mn:
        arr = (arr - mn) / (mx - mn)
    else:
        arr = np.zeros_like(arr)
    arr = (arr * 255.0).clip(0, 255).astype(np.uint8)
    return arr
    

def overlay_rgb_alpha(base_u8: np.ndarray, mask_u8: np.ndarray,
                      alpha_myo: float = 0.45, alpha_blood: float = 0.45) -> np.ndarray:
    """
    base_u8: (H,W) uint8 grayscale
    mask_u8: (H,W) uint8 labels (0,1,2)
    returns: (H,W,3) uint8 RGB
    """
    rgb = np.stack([base_u8]*3, axis=-1).astype(np.float32)

    myo = (mask_u8 == 1)
    blood = (mask_u8 == 2)

    # myocardium = blue
    if myo.any():
        blue = np.array([0, 0, 255], dtype=np.float32)
        rgb[myo] = (1 - alpha_myo) * rgb[myo] + alpha_myo * blue

    # blood pool = red (apply after myo so blood stays red inside the ring)
    if blood.any():
        red = np.array([255, 0, 0], dtype=np.float32)
        rgb[blood] = (1 - alpha_blood) * rgb[blood] + alpha_blood * red

    return rgb.clip(0, 255).astype(np.uint8)



def render_overlay_pil_scaled(img2d_256, mask2d_256, *, scale=CANVAS_SCALE):
    # 1) display-transform both consistently
    img_disp = display_xform(img2d_256)
    mask_disp = display_xform(mask2d_256.astype(np.uint8))

    # 2) uint8 grayscale
    base_u8 = _normalize_to_uint8(img_disp)

    # 3) overlay in RGB
    rgb = overlay_rgb_alpha(base_u8, mask_disp, alpha_myo=0.45, alpha_blood=0.45)

    # 4) upscale to match canvas
    pil = Image.fromarray(rgb)
    W = SIZE_X * scale
    H = SIZE_Y * scale
    pil = pil.resize((W, H), resample=Image.NEAREST)

    return pil




def build_zip_bytes(files: list, root_folder: Optional[str] = None):
    """
    files: list of tuples (arc_rel_path, bytes_content)
    root_folder: if provided, makes a top-level folder inside zip.
                 if None or "", files are placed at zip root.
    """
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as z:
        for rel_path, content in files:
            if root_folder:
                arc = f"{root_folder}/{rel_path}".replace("\\", "/")
            else:
                arc = f"{rel_path}".replace("\\", "/")
            z.writestr(arc, content)
    buf.seek(0)
    return buf.getvalue()


def build_corrected_gif_zip_bytes():
    zipstem = Path(st.session_state.get("_last_zip_name", "Results")).stem
    gif_root = f"{zipstem}_GIF_corrected"
    gif_zip_name = f"{gif_root}.zip"

    gif_files = []

    orig = st.session_state.get("gif_paths_original", {}) or {}
    corr = st.session_state.get("gif_paths_corrected", {}) or {}

    # corrected overrides original
    all_pids = sorted(set(orig.keys()) | set(corr.keys()))
    for pid in all_pids:
        gif_path = corr.get(pid) or orig.get(pid)
        if gif_path and os.path.exists(gif_path):
            with open(gif_path, "rb") as f:
                # filename rule: pid.gif (pid derived from nifti name)
                gif_files.append((f"{pid}.gif", f.read()))

    st.session_state["gif_zip_bytes_corrected"] = build_zip_bytes(
        gif_files,
        root_folder=gif_root
    )
    st.session_state["gif_zip_name_corrected"] = gif_zip_name


def build_corrected_masks_zip_bytes_per_mouse():
    zipstem = Path(st.session_state.get("_last_zip_name", "Results")).stem
    root = f"{zipstem}_Masks_corrected"
    zip_name = f"{root}.zip"

    mask_files = []
    cases = st.session_state.get("cases", {}) or {}

    for pid, case in cases.items():
        native_h, native_w, S, F = case["native_shape"]
        affine = case["affine"]

        # βœ… use corrected only if mask was edited; otherwise keep original mask
        if case.get("mask_edited", False):
            preds_src = case["preds_4d"]
        else:
            preds_src = case.get("preds_4d_orig", case["preds_4d"])

        mask_native = resize_masks_to_native(preds_src, native_h, native_w)

        session_tmp = get_session_tmpdir()
        tmp_mask_path = os.path.join(session_tmp, f"{pid}_mask.nii.gz")
        save_native_mask_nifti_with_labels(mask_native, affine, tmp_mask_path)

        with open(tmp_mask_path, "rb") as f:
            mask_files.append((f"{pid}/{pid}_mask.nii.gz", f.read()))

        try:
            os.remove(tmp_mask_path)
        except OSError:
            pass

    st.session_state["mask_zip_bytes_corrected"] = build_zip_bytes(mask_files, root_folder=root)
    st.session_state["mask_zip_name_corrected"] = zip_name




def _alpha_overlay_rgb(base_u8, mask_u8):
    """
    base_u8: (H,W) uint8 grayscale
    mask_u8: (H,W) uint8 labels (0,1,2)
    returns RGB uint8
    """
    base_rgb = np.stack([base_u8]*3, axis=-1).astype(np.float32)

    # myocardium (1) blue tint
    myo = (mask_u8 == 1)
    base_rgb[myo, 2] = np.clip(base_rgb[myo, 2] * 0.6 + 255 * 0.4, 0, 255)

    # blood (2) red tint
    blood = (mask_u8 == 2)
    base_rgb[blood, 0] = np.clip(base_rgb[blood, 0] * 0.6 + 255 * 0.4, 0, 255)

    return base_rgb.astype(np.uint8)

def build_frame_montage(images_4d_256, preds_4d, frame_idx, slice_indices, tile_cols=4, add_overlay=True):
    """
    Returns a PIL Image montage for a given frame over selected slices.
    """
    tiles = []
    for s in slice_indices:
        img = images_4d_256[:, :, s, frame_idx]
        img_u8 = _normalize_to_uint8(img)

        if add_overlay:
            mask = preds_4d[:, :, s, frame_idx].astype(np.uint8)
            tile = overlay_rgb_alpha(img_u8, mask, alpha_myo=0.45, alpha_blood=0.45)
            tile_pil = Image.fromarray(tile)
        else:
            tile_pil = Image.fromarray(img_u8).convert("RGB")

        # annotate slice number
        d = ImageDraw.Draw(tile_pil)
        d.text((5, 5), f"S{s+1}", fill=(255,255,255))
        tiles.append(tile_pil)

    if not tiles:
        return Image.new("RGB", (256, 256), (0,0,0))

    w, h = tiles[0].size
    n = len(tiles)
    cols = min(tile_cols, n)
    rows = int(math.ceil(n / cols))

    canvas = Image.new("RGB", (cols*w, rows*h), (0,0,0))
    for i, tile in enumerate(tiles):
        r = i // cols
        c = i % cols
        canvas.paste(tile, (c*w, r*h))
    return canvas



def _render_overlay_png(img2d, mask2d, title=None):
    fig, ax = plt.subplots(figsize=(3, 3))
    base = display_xform(img2d)
    myo_mask = display_xform((mask2d == 1).astype(np.uint8)).astype(bool)
    blood_mask = display_xform((mask2d == 2).astype(np.uint8)).astype(bool)
    ax.imshow(base, cmap="gray", interpolation="none")
    if myo_mask.any():
        ax.imshow(
            np.ma.masked_where(~myo_mask, myo_mask),
            cmap="Blues",
            alpha=0.45,
            vmin=0,
            vmax=1,
            interpolation="none",
        )
    if blood_mask.any():
        ax.imshow(
            np.ma.masked_where(~blood_mask, blood_mask),
            cmap="jet",
            alpha=0.45,
            vmin=0,
            vmax=1,
            interpolation="none",
        )
    ax.axis("off")
    if title:
        ax.set_title(title, fontsize=10)
    buf = io.BytesIO()
    fig.savefig(buf, format="png", bbox_inches="tight", pad_inches=0)
    plt.close(fig)
    buf.seek(0)
    return buf


# Colour and label maps for simple painting (kept for future use if needed)
_COLOR_MAP_RGB = {
    "Blood pool": np.array([255, 0, 0], dtype=np.int16),  # red
    "Myocardium": np.array([0, 0, 255], dtype=np.int16),  # blue
    "Eraser (background)": np.array([0, 0, 0], dtype=np.int16),  # black
}
_LABEL_MAP = {
    "Blood pool": 2,
    "Myocardium": 1,
    "Eraser (background)": 0,
}


def _apply_canvas_to_mask_slice(
    mask_slice: np.ndarray,
    canvas_rgba: np.ndarray,
    class_choice: str,
    color_tol: float = 30.0,
) -> np.ndarray:
    """
    Simple label-painting: update pixels where canvas color β‰ˆ selected class color.
    (Currently not exposed in the UI, but kept for possible future use.)
    """
    if canvas_rgba is None:
        return mask_slice

    if class_choice not in _COLOR_MAP_RGB or class_choice not in _LABEL_MAP:
        return mask_slice

    target_rgb = _COLOR_MAP_RGB[class_choice]
    label_value = _LABEL_MAP[class_choice]

    rgba = canvas_rgba.astype(np.int16)
    rgb = rgba[:, :, :3]
    alpha = rgba[:, :, 3]

    diff = np.linalg.norm(rgb - target_rgb[None, None, :], axis=-1)
    drawn_mask = (alpha > 0) & (diff < color_tol)

    updated = mask_slice.copy()
    updated[drawn_mask] = label_value
    return updated


def _thicken_close_and_fill(
    strokes: np.ndarray,
    dilate_iter: int = 1,
    close_radius: int = 2,
) -> np.ndarray:
    """
    Helper for LV contour editing:

    1. Thicken strokes (binary_dilation) so small gaps shrink.
    2. Binary closing (dilate+erode) to bridge breaks.
    3. Fill interior (binary_fill_holes).

    Input/Output: boolean mask.
    """
    if strokes is None or not strokes.any():
        return strokes

    # Small 3x3-ish disk to thicken the strokes
    selem_dilate = disk(1)
    # Slightly larger disk for closing, to bridge small end-point gaps
    selem_close = disk(close_radius)

    thick = binary_dilation(
        strokes,
        structure=selem_dilate,
        iterations=dilate_iter,
    )
    closed = binary_closing(
        thick,
        structure=selem_close,
    )
    filled = binary_fill_holes(closed)
    return filled


def _apply_lv_contour_style(
    mask_slice: np.ndarray,
    canvas_rgba: np.ndarray,
    color_tol: float = 30.0,
) -> np.ndarray:
    """
    Horos-style LV editing for a single 2D slice.

    Assumes the user has drawn:
      β€’ RED   (#FF0000)  -> inner border (endocardial / blood pool)
      β€’ BLUE  (#0000FF)  -> outer border (epicardial / myocardium)

    We:
      1. Detect red and blue stroke pixels from the RGBA canvas.
      2. Thicken & binary-close each stroke mask, then fill holes.
      3. Set:
           - blood pool = interior of red
           - myocardium = region between blue and red
         and overwrite any previous label 1/2 in this slice.
    """
    if canvas_rgba is None:
        return mask_slice

    rgba = canvas_rgba.astype(np.int16)
    rgb = rgba[:, :, :3]
    alpha = rgba[:, :, 3]

    endo_rgb = np.array([255, 0, 0], dtype=np.int16)  # red (blood pool)
    epi_rgb = np.array([0, 0, 255], dtype=np.int16)   # blue (myocardium)

    diff_endo = np.linalg.norm(rgb - endo_rgb[None, None, :], axis=-1)
    diff_epi = np.linalg.norm(rgb - epi_rgb[None, None, :], axis=-1)

    endo_strokes = (alpha > 0) & (diff_endo < color_tol)
    epi_strokes = (alpha > 0) & (diff_epi < color_tol)

    # If nothing was drawn, just return the slice unchanged
    if not endo_strokes.any() and not epi_strokes.any():
        return mask_slice

    # Thicken, close and fill each contour mask
    endo_region = _thicken_close_and_fill(endo_strokes)
    if endo_region is None:
        endo_region = np.zeros_like(endo_strokes, dtype=bool)

    epi_region = _thicken_close_and_fill(epi_strokes)
    if epi_region is None:
        epi_region = np.zeros_like(epi_strokes, dtype=bool)

    # Ensure epicardial region at least contains the endocardial one
    epi_region = epi_region | endo_region

    blood_region = endo_region
    myo_region = epi_region & ~endo_region

    updated = mask_slice.copy()

    # Clear existing LV labels on this slice, then re-assign
    updated[(updated == 1) | (updated == 2)] = 0
    updated[blood_region] = 2  # blood pool
    updated[myo_region] = 1    # myocardium

    return updated


# =========================
#    NIfTI I/O + spacing
# =========================
def _reorient_nifti(img: nib.Nifti1Image, target: Optional[str]):
    if not target:
        return img, None
    tgt = target.upper()
    if tgt not in ("LPS", "RAS"):
        raise ValueError("ORIENT_TARGET must be None, 'LPS', or 'RAS'")
    cur = nib.orientations.io_orientation(img.affine)
    wanted = nib.orientations.axcodes2ornt(tuple(tgt))
    xfm = nib.orientations.ornt_transform(cur, wanted)
    if np.allclose(xfm, np.array([[0, 1], [1, 1], [2, 1]])):
        return img, xfm
    data = img.get_fdata()
    data_re = nib.orientations.apply_orientation(data, xfm)
    aff_re = img.affine @ nib.orientations.inv_ornt_aff(xfm, img.shape)
    return nib.Nifti1Image(data_re, aff_re, header=img.header), xfm


def load_nifti_4d(path, orient_target: Optional[str] = ORIENT_TARGET):
    img_native = nib.load(path)
    img, _ = _reorient_nifti(img_native, orient_target)

    data = img.get_fdata(dtype=np.float32)  # (X,Y,Z[,T])
    if data.ndim == 3:
        data = data[..., None]
    data_4d = np.transpose(data, (1, 0, 2, 3)).astype(np.float32)  # -> (H,W,S,F)

    zooms = img.header.get_zooms()
    x_mm = float(zooms[0]) if len(zooms) > 0 else 1.0
    y_mm = float(zooms[1]) if len(zooms) > 1 else 1.0
    z_mm = float(zooms[2]) if len(zooms) > 2 else 1.0
    t = float(zooms[3]) if len(zooms) > 3 else None
    
    # data_4d = transpose(data, (1,0,2,3)) => (H,W)=(Y,X)
    spacing = dict(
        row_mm=y_mm,              # H spacing
        col_mm=x_mm,              # W spacing
        slice_thickness_mm=z_mm,
        frame_time_ms=t,
    )
    return data_4d, spacing, img.affine


# =========================
#        Inference
# =========================
def nifti_to_model_batches(data_4d):
    """
    Fast path (vectorized) for tf resize modes.
    Falls back to slow loop for fft resize.
    Returns:
      x: (S*F, 256,256,1) float32
      index: list of (s,f)
      shape4d: (H,W,S,F) native
      resize_method_used: str (for debugging/logging)
    """
    H, W, S, F = data_4d.shape

    # βœ… Validate resize mode early (fail fast)
    valid = {"auto", "bilinear", "area", "fft"}
    if RESIZE_MODE not in valid:
        raise ValueError(f"RESIZE_MODE must be one of {sorted(valid)}")

    # index mapping (matches stack order below: S-major, F-minor)
    index = [(s, f) for s in range(S) for f in range(F)]  # matches fft loop


    # ---- FFT needs per-slice handling (keep loop) ----
    if RESIZE_MODE == "fft":
        batches = []
        for s in range(S):
            for f in range(F):
                img = data_4d[..., s, f]
                img_resized = _fft_kspace_resize(img, target_h=SIZE_Y, target_w=SIZE_X)
                batches.append(img_resized[..., None])
        x = np.stack(batches, axis=0).astype(np.float32)
        return x, index, (H, W, S, F), "fft"


    # ---- Vectorized TF resize path (FAST) ----
    # Reshape (H,W,S,F) -> (S*F, H, W, 1)
    stack = (
        np.transpose(data_4d, (2, 3, 0, 1))
        .reshape(S * F, H, W, 1)
        .astype(np.float32)
    )

    # Decide method ONCE per case (since H,W are constant within a NIfTI)
    if RESIZE_MODE == "auto":
        method = "area" if (H > SIZE_Y or W > SIZE_X) else "bilinear"
    else:
        method = RESIZE_MODE  # "bilinear" or "area"

    x_tf = tf.image.resize(stack, [SIZE_Y, SIZE_X], method=method, antialias=True)
    x = x_tf.numpy().astype(np.float32)

    return x, index, (H, W, S, F), method




def _ensure_logits_last(preds):
    if isinstance(preds, (list, tuple)):
        preds = preds[-1]
    return preds


def predict_nifti_4d(
    model,
    data_4d,
    batch_size=None,
    *,
    progress_cb=None,
):
    """
    Run inference on a single (H,W,S,F) NIfTI case and return:
      preds_4d:        (256,256,S,F) uint8 labels
      imgs_4d_resized: (256,256,S,F) float32 resized images

    progress_cb (optional): callable(int images_done)
      - Called with number of 2D images processed so far within THIS file.
      - "2D images" here means S*F slices/frames after stacking.
      - This enables smooth progress updates (31->32->33...) within a file.
    """
    x, index, shape4d, resize_method_used = nifti_to_model_batches(data_4d)

    # Normalize (already vectorized)
    x_norm = normalize_images(x)

    # ---- Progress-aware prediction ----
    # If no progress_cb, keep the original fast path (single predict call).
    if progress_cb is None:
        preds = _ensure_logits_last(
            model.predict(x_norm, verbose=0, batch_size=batch_size)
        )
    else:
        # We must do batched prediction to emit progress updates.
        N = x_norm.shape[0]  # = S*F
        bs = int(batch_size or BATCH_SIZE or 16)
        bs = max(1, bs)

        outs = []
        done = 0
        # initial callback (optional, but helps UI start at 0 within-file)
        try:
            progress_cb(0)
        except Exception:
            pass

        for start in range(0, N, bs):
            end = min(start + bs, N)
            batch = x_norm[start:end]

            pred_b = _ensure_logits_last(model.predict(batch, verbose=0))
            outs.append(pred_b)

            done = end
            # update progress after each batch
            try:
                progress_cb(done)
            except Exception:
                pass

        preds = np.concatenate(outs, axis=0)

    labels = np.argmax(preds, axis=-1).astype(np.uint8)  # (S*F, 256,256)

    Hn, Wn, S, F = SIZE_Y, SIZE_X, shape4d[2], shape4d[3]

    # Reshape back:
    # x:      (S*F, Hn, Wn, 1) -> (S, F, Hn, Wn) -> (Hn, Wn, S, F)
    imgs_4d_resized = x[..., 0].reshape(S, F, Hn, Wn).transpose(2, 3, 0, 1)

    # labels: (S*F, Hn, Wn) -> (S, F, Hn, Wn) -> (Hn, Wn, S, F)
    preds_4d = labels.reshape(S, F, Hn, Wn).transpose(2, 3, 0, 1)

    return preds_4d, imgs_4d_resized




def resize_masks_to_native(preds_4d_256, native_h, native_w):
    Hm, Wm, S, F = preds_4d_256.shape
    out = np.zeros((native_h, native_w, S, F), dtype=preds_4d_256.dtype)
    for f in range(F):
        for s in range(S):
            out[..., s, f] = _resize_nn(
                preds_4d_256[..., s, f], native_h, native_w
            )
    return out


# =========================
#     Mask export (native)
# =========================
def save_native_mask_nifti(mask_hwst, affine, out_path):
    """
    mask_hwst: (H,W,S,F) uint8 labels
    affine: affine from load_nifti_4d()
    """
    data_xyzt = np.transpose(mask_hwst, (1, 0, 2, 3)).astype(np.uint8)
    img = nib.Nifti1Image(data_xyzt, affine)
    nib.save(img, out_path)
    return out_path



DEFAULT_LABELS = {
    0: {"name": "Background", "color": [0, 0, 0]},
    1: {"name": "Myocardium", "color": [0, 0, 255]},
    2: {"name": "LV Blood Pool", "color": [255, 0, 0]},
}

def _make_label_json(label_defs: dict) -> str:
    payload = {
        "type": "segmentation_labels",
        "version": 1,
        "labels": {str(k): v for k, v in label_defs.items()},
    }
    return json.dumps(payload, separators=(",", ":"), ensure_ascii=False)

def save_native_mask_nifti_with_labels(mask_hwst, affine, out_path, label_defs=DEFAULT_LABELS):
    """
    mask_hwst: (H,W,S,F) uint8 labels
    Saves NIfTI with:
      - header['descrip'] short string (max 80 bytes)
      - NIfTI header extension containing label JSON
    """
    data_xyzt = np.transpose(mask_hwst, (1, 0, 2, 3)).astype(np.uint8)
    img = nib.Nifti1Image(data_xyzt, affine)

    # short description (widely preserved)
    desc = "Labels:0=BG,1=Myo,2=Blood"
    img.header["descrip"] = desc.encode("ascii", "ignore")[:80]

    # embedded JSON extension (many tools preserve it; some viewers won't display it)
    label_json = _make_label_json(label_defs)
    ext = nib.nifti1.Nifti1Extension(40, label_json.encode("utf-8"))  # 40=comment
    exts = img.header.extensions
    exts.clear()
    exts.append(ext)

    nib.save(img, out_path)
    return out_path



# =========================
#   Cleaning + ED/ES + metrics
# =========================
def clean_predictions_per_frame_3d(mask_4d):
    H, W, S, F = mask_4d.shape
    out = mask_4d.copy()
    for f in range(F):
        vol_f = out[:, :, :, f]
        for cls in (1, 2):
            m = vol_f == cls
            if not m.any():
                continue
            cc = cc_label(m, connectivity=1)
            props = regionprops(cc)
            if not props:
                continue
            dom = max(props, key=lambda r: r.area)
            dom_centroid = np.array(dom.centroid)
            keep = {dom.label}
            for r in props:
                if r.label == dom.label:
                    continue
                zmin, zmax = r.bbox[2], r.bbox[5]
                slice_span = zmax - zmin
                areas = [
                    np.count_nonzero(cc[:, :, z] == r.label)
                    for z in range(zmin, zmax)
                ]
                median_area = np.median(areas) if areas else 0
                dist = np.linalg.norm(
                    np.array(r.centroid) - dom_centroid
                )
                if (
                    slice_span >= ISLAND_MIN_SLICE_SPAN
                    and median_area >= ISLAND_MIN_AREA_PER_SLICE
                    and dist <= ISLAND_CENTROID_DIST_THRESH
                ):
                    keep.add(r.label)
            drop = (cc > 0) & (~np.isin(cc, list(keep)))
            vol_f[drop] = 0
        out[:, :, :, f] = vol_f
    return out


def compute_per_frame_metrics(
    preds_4d, spacing, labels={"myo": 1, "blood": 2}
):
    row_mm = float(spacing["row_mm"])
    col_mm = float(spacing["col_mm"])
    thk = float(spacing["slice_thickness_mm"])
    voxel_mm3 = row_mm * col_mm * thk

    H, W, S, F = preds_4d.shape
    blood_counts = (preds_4d == labels["blood"]).sum(axis=(0, 1, 2))
    myo_counts = (preds_4d == labels["myo"]).sum(axis=(0, 1, 2))
    volume_uL = blood_counts * voxel_mm3
    myo_mass_mg = myo_counts * voxel_mm3 * MYO_DENSITY
    return pd.DataFrame(
        {
            "Frame": np.arange(F, dtype=int),
            "Volume_uL": volume_uL,
            "MyocardiumMass_mg": myo_mass_mg,
        }
    )


def slice_validity_matrix(preds_4d, A_blood_min=30, A_myo_min=30):
    H, W, S, F = preds_4d.shape
    blood = preds_4d == 2
    myo = preds_4d == 1
    areas_blood = blood.reshape(H * W, S, F).sum(axis=0)
    areas_myo = myo.reshape(H * W, S, F).sum(axis=0)
    has_blood = areas_blood >= A_blood_min
    has_myo = areas_myo >= A_myo_min
    return has_blood, has_myo, areas_blood, areas_myo


def choose_mid_slices(has_blood, has_myo, K=4, min_frac=0.7):
    S, F = has_blood.shape
    valid_frac = (has_blood & has_myo).sum(axis=1) / max(F, 1)
    target = int(S // 2)
    best = None
    for start in range(0, max(S - K + 1, 1)):
        block = list(range(start, min(start + K, S)))
        score = valid_frac[block].mean() - 0.01 * np.mean(
            [abs(s - target) for s in block]
        )
        if best is None or score > best[0]:
            best = (score, block)
    _, chosen = best
    if np.mean(valid_frac[chosen]) < min_frac:
        order = np.argsort(-valid_frac)
        chosen = sorted(order[:K].tolist())
    return chosen


def frame_volumes_subset_uL(preds_4d, spacing, slice_indices):
    voxel = (
        float(spacing["row_mm"])
        * float(spacing["col_mm"])
        * float(spacing["slice_thickness_mm"])
    )
    F = preds_4d.shape[3]
    vols = np.zeros(F, dtype=np.float32)
    for f in range(F):
        sub = preds_4d[:, :, slice_indices, f]
        vols[f] = (sub == 2).sum() * voxel
    return vols


def pick_ed_es_from_volumes(
    vols_uL, prefer_frame0=True, rel_tol=0.05, min_sep=1
):
    ed = int(np.argmax(vols_uL))
    if prefer_frame0 and abs(vols_uL[0] - vols_uL[ed]) <= rel_tol * max(
        vols_uL[ed], 1e-6
    ):
        ed = 0
    es = int(np.argsort(vols_uL)[0])
    for c in np.argsort(vols_uL):
        if abs(int(c) - ed) >= min_sep:
            es = int(c)
            break
    return ed, es


# =========================
#           GIF (ED vs ES)
# =========================
def gif_animation_for_patient_pred_only(
    images_4d, preds_4d, patient_id, ed_idx, es_idx, output_dir
):
    os.makedirs(output_dir, exist_ok=True)

    def overlay(ax, img, pred, alpha_myo=0.45, alpha_blood=0.45):
        base = display_xform(img)
        myo_mask = display_xform((pred == 1).astype(np.uint8)).astype(bool)
        blood_mask = display_xform((pred == 2).astype(np.uint8)).astype(bool)
        ax.imshow(base, cmap="gray", interpolation="none")
        if myo_mask.any():
            ax.imshow(
                np.ma.masked_where(~myo_mask, myo_mask),
                cmap="Blues",
                alpha=alpha_myo,
                vmin=0,
                vmax=1,
                interpolation="none",
            )
        if blood_mask.any():
            ax.imshow(
                np.ma.masked_where(~blood_mask, blood_mask),
                cmap="jet",
                alpha=alpha_blood,
                vmin=0,
                vmax=1,
                interpolation="none",
            )
        ax.axis("off")

    H, W, S, F = images_4d.shape
    fig, axarr = plt.subplots(1, 2, figsize=(8, 4))
    plt.tight_layout(rect=[0, 0, 1, 0.92])

    def update(slice_idx):
        axarr[0].clear()
        axarr[1].clear()
        overlay(
            axarr[0],
            images_4d[:, :, slice_idx, ed_idx],
            preds_4d[:, :, slice_idx, ed_idx],
        )
        axarr[0].set_title(f"ED (frame {ed_idx+1}) | Slice {slice_idx+1}")
        overlay(
            axarr[1],
            images_4d[:, :, slice_idx, es_idx],
            preds_4d[:, :, slice_idx, es_idx],
        )
        axarr[1].set_title(f"ES (frame {es_idx+1}) | Slice {slice_idx+1}")
        fig.suptitle(f"Mouse ID: {patient_id}", fontsize=14, y=0.98)

    # Slower animation (2 seconds per slice), fps still 2
    anim = animation.FuncAnimation(fig, update, frames=S, interval=2500)
    out_path = os.path.join(output_dir, f"{patient_id}_pred.gif")
    anim.save(out_path, writer="pillow", fps=GIF_FPS)
    plt.close(fig)
    return out_path


# =========================
#        CSV writer
# =========================
def write_all_in_one_csv(rows, per_frame_rows, csv_dir):
    df_summary = pd.DataFrame(rows)

    summary_cols = [
        "Patient_ID",
        "EDV_uL",
        "ESV_uL",
        "SV_uL",
        "EF_%",
        "MyocardiumMass_ED_mg",
        "MyocardiumMass_ES_mg",
        "ED_frame_index",
        "ES_frame_index",
        "Seg_PixelSpacing_row_mm",
        "Seg_PixelSpacing_col_mm",
        "Seg_SliceThickness_mm",
        "Native_PixelSpacing_row_mm",
        "Native_PixelSpacing_col_mm",
        "Native_SliceThickness_mm",
    ]
    df_summary = df_summary.reindex(columns=summary_cols)

    if per_frame_rows:
        df_perframe = pd.concat(per_frame_rows, ignore_index=True)
    else:
        df_perframe = pd.DataFrame(
            columns=["Patient_ID", "Frame", "Volume_uL", "MyocardiumMass_mg"]
        )

    if not df_perframe.empty:
        df_perframe["Frame"] = df_perframe["Frame"].astype(int) + 1
    if not df_summary.empty:
        for c in ("ED_frame_index", "ES_frame_index"):
            if c in df_summary.columns:
                df_summary[c] = df_summary[c].astype("Int64") + 1
        for c in (
            "EF_%",
            "EDV_uL",
            "ESV_uL",
            "SV_uL",
            "MyocardiumMass_ED_mg",
            "MyocardiumMass_ES_mg",
            "Seg_PixelSpacing_row_mm",
            "Seg_PixelSpacing_col_mm",
            "Seg_SliceThickness_mm",
            "Native_PixelSpacing_row_mm",
            "Native_PixelSpacing_col_mm",
            "Native_SliceThickness_mm",
        ):
            if c in df_summary.columns:
                df_summary[c] = df_summary[c].astype(float).map(
                    lambda x: f"{x:.2f}"
                )
        for c in ("Volume_uL", "MyocardiumMass_mg"):
            if c in df_perframe.columns and not df_perframe.empty:
                df_perframe[c] = df_perframe[c].astype(float).map(
                    lambda x: f"{x:.2f}"
                )

    all_in_one = df_perframe.merge(
        df_summary[summary_cols],
        on="Patient_ID",
        how="left",
    )[
        [
            "Patient_ID",
            "ED_frame_index",
            "ES_frame_index",
            "EDV_uL",
            "ESV_uL",
            "SV_uL",
            "EF_%",
            "MyocardiumMass_ED_mg",
            "MyocardiumMass_ES_mg",
            "Frame",
            "Volume_uL",
            "MyocardiumMass_mg",
            "Seg_PixelSpacing_row_mm",
            "Seg_PixelSpacing_col_mm",
            "Seg_SliceThickness_mm",
            "Native_PixelSpacing_row_mm",
            "Native_PixelSpacing_col_mm",
            "Native_SliceThickness_mm",
        ]
    ]

    os.makedirs(csv_dir, exist_ok=True)
    out_csv = os.path.join(csv_dir, "Results.csv")
    all_in_one.to_csv(out_csv, index=False)
    log(f"CSV written: {out_csv}")
    return out_csv


# =========================
#   Same-tab download
# =========================
def _same_tab_download_button(
    label: str,
    data_bytes: bytes,
    file_name: str,
    mime: str = "text/csv",
    *,
    key: Optional[str] = None,
):
    import html, hashlib, base64
    import streamlit as st
    import streamlit.components.v1 as components

    b64 = base64.b64encode(data_bytes).decode("ascii")
    btn_id = f"dl_{(key or file_name)}_{hashlib.sha256((key or file_name).encode()).hexdigest()[:8]}"

    st.markdown(
        f"""
    <style>
      a#{btn_id} {{
        appearance: none;
        display: inline-flex; align-items: center; justify-content: center;
        padding: 0.5rem 0.75rem;
        border-radius: 0.5rem;
        border: 1px solid rgba(49,51,63,.2);
        background: var(--background-color);
        color: var(--text-color);
        font-weight: 600; text-decoration: none !important;
        box-shadow: 0 1px 2px rgba(0,0,0,0.04);
        transition: color .15s ease, border-color .15s ease,
                   box-shadow .15s ease, transform .05s ease, background-color .15s;
        cursor: pointer;
        user-select: none;
        -webkit-tap-highlight-color: transparent;
      }}
      a#{btn_id}:hover, a#{btn_id}:focus {{
        background: var(--background-color);
        color: var(--accent) !important;
        border-color: var(--accent) !important;
        box-shadow: 0 2px 6px rgba(239,68,68,0.20);
        transform: translateY(-1px);
      }}
      a#{btn_id}:active,
      a#{btn_id}.pressed {{
        background: var(--accent) !important;
        border-color: var(--accent) !important;
        color: #fff !important;
        box-shadow: 0 3px 10px rgba(239,68,68,0.35);
        transform: translateY(0);
      }}
      a#{btn_id}:focus-visible {{
        outline: none;
        box-shadow: 0 0 0 0.2rem rgba(239,68,68,0.35);
      }}
    </style>
    """,
        unsafe_allow_html=True,
    )


    st.markdown(
        f'''
        <div class="dl-wrap">
          <a class="dl-btn" id="{btn_id}" href="#"
             data-b64="{b64}"
             data-mime="{html.escape(mime)}"
             data-fname="{html.escape(file_name)}">{html.escape(label)}</a>
        </div>
        ''',
        unsafe_allow_html=True,
    )


    components.html(
        f"""
<script>
(function () {{
  try {{
    const doc = window.parent.document;
    const a = doc.getElementById("{btn_id}");
    if (!a) return;

    const pressOn = () => a.classList.add("pressed");
    const pressOff = () => a.classList.remove("pressed");

    a.addEventListener("mousedown", pressOn, true);
    a.addEventListener("mouseup",   pressOff, true);
    a.addEventListener("mouseleave",pressOff, true);
    a.addEventListener("touchstart",pressOn,  {{passive:true}});
    a.addEventListener("touchend",  pressOff, true);
    a.addEventListener("touchcancel",pressOff, true);

    a.addEventListener("click", function(ev) {{
      ev.preventDefault();
      ev.stopImmediatePropagation();

      const b64 = a.getAttribute("data-b64");
      const mime = a.getAttribute("data-mime") || "application/octet-stream";
      const fname = a.getAttribute("data-fname") || "download";

      const bstr = atob(b64);
      const len = bstr.length;
      const u8 = new Uint8Array(len);
      for (let i = 0; i < len; i++) u8[i] = bstr.charCodeAt(i);
      const blob = new Blob([u8], {{ type: mime }});
      const url = URL.createObjectURL(blob);

      const tmp = doc.createElement("a");
      tmp.href = url;
      tmp.download = fname;
      tmp.style.display = "none";
      doc.body.appendChild(tmp);
      tmp.click();

      setTimeout(() => {{
        URL.revokeObjectURL(url);
        tmp.remove();
        pressOff();
      }}, 150);
    }}, true);
  }} catch (err) {{
    console.debug("download handler error:", err);
  }}
}})();
</script>
""",
        height=0,
    )



def render_download_group(buttons: List[dict], group_key: str):
    """
    buttons: list of dicts with keys: label, bytes, filename, mime, key
    """
    import base64, html, hashlib
    ids = []
    rows_html = []

    for b in buttons:
        b64 = base64.b64encode(b["bytes"]).decode("ascii")
        btn_id = f"dl_{group_key}_{hashlib.sha256(b['key'].encode()).hexdigest()[:8]}"
        ids.append(btn_id)

        rows_html.append(f"""
          <div class="dl-row">
            <a class="dl-btn" id="{btn_id}" href="#"
               data-b64="{b64}"
               data-mime="{html.escape(b['mime'])}"
               data-fname="{html.escape(b['filename'])}">
               {html.escape(b['label'])}
            </a>
          </div>
        """)

    st.markdown(
        f"""
        <div class="dl-group">
          {''.join(rows_html)}
        </div>
        """,
        unsafe_allow_html=True,
    )

    # one JS hook for all buttons in this group
    components.html(
        f"""
<script>
(function () {{
  const doc = window.parent.document;

  function wire(id) {{
    const a = doc.getElementById(id);
    if (!a) return;

    const pressOn = () => a.classList.add("pressed");
    const pressOff = () => a.classList.remove("pressed");

    a.addEventListener("mousedown", pressOn, true);
    a.addEventListener("mouseup", pressOff, true);
    a.addEventListener("mouseleave", pressOff, true);

    a.addEventListener("click", function(ev) {{
      ev.preventDefault();
      ev.stopImmediatePropagation();

      const b64 = a.getAttribute("data-b64");
      const mime = a.getAttribute("data-mime") || "application/octet-stream";
      const fname = a.getAttribute("data-fname") || "download";

      const bstr = atob(b64);
      const len = bstr.length;
      const u8 = new Uint8Array(len);
      for (let i = 0; i < len; i++) u8[i] = bstr.charCodeAt(i);

      const blob = new Blob([u8], {{ type: mime }});
      const url = URL.createObjectURL(blob);

      const tmp = doc.createElement("a");
      tmp.href = url;
      tmp.download = fname;
      tmp.style.display = "none";
      doc.body.appendChild(tmp);
      tmp.click();

      setTimeout(() => {{
        URL.revokeObjectURL(url);
        tmp.remove();
        pressOff();
      }}, 150);
    }}, true);
  }}

  {''.join([f"wire('{i}');" for i in ids])}
}})();
</script>
        """,
        height=0,
    )



# =========================
#    Per-file processing
# =========================
def process_nifti_case(
    nifti_path: str,
    model,
    rows_acc: List[Dict],
    per_frame_rows_acc: List[pd.DataFrame],
    *,
    progress_cb=None,
):
    """
    progress_cb(file_frac: float, msg: Optional[str]) where file_frac in [0,1]
    """

    def _p(frac: float, msg: Optional[str] = None):
        if progress_cb is None:
            return
        try:
            progress_cb(float(np.clip(frac, 0.0, 1.0)), msg)
        except Exception:
            pass

    name = Path(nifti_path).name
    pid = name.replace(".nii.gz", "").replace(".nii", "")
    log(f"[CASE] Using NIfTI input: {nifti_path}")

    # ---- Step A: load + prep (0 -> W_LOAD_PREP) ----
    _p(0.00, "Loading NIfTI...")
    imgs_4d, spacing, final_aff = load_nifti_4d(nifti_path, orient_target=ORIENT_TARGET)
    _p(W_LOAD_PREP, "Preparing inference...")

    # Orientation bookkeeping (unchanged)
    global CURRENT_DISPLAY_ORIENT
    if ORIENT_TARGET is None:
        try:
            axc = nib.aff2axcodes(final_aff)
            if tuple(axc[:3]) == ("L", "P", "S"):
                CURRENT_DISPLAY_ORIENT = "LPS"
            elif tuple(axc[:3]) == ("R", "A", "S"):
                CURRENT_DISPLAY_ORIENT = "RAS"
            else:
                CURRENT_DISPLAY_ORIENT = "LPS"
        except Exception:
            CURRENT_DISPLAY_ORIENT = "LPS"
    else:
        CURRENT_DISPLAY_ORIENT = ORIENT_TARGET

    native_h, native_w, S, F = imgs_4d.shape

    row_native = float(spacing["row_mm"])
    col_native = float(spacing["col_mm"])
    thk_native = float(spacing["slice_thickness_mm"])

    seg_row_mm = row_native * (native_h / float(SIZE_Y))
    seg_col_mm = col_native * (native_w / float(SIZE_X))
    seg_spacing = dict(
        row_mm=seg_row_mm,
        col_mm=seg_col_mm,
        slice_thickness_mm=thk_native,
        frame_time_ms=spacing.get("frame_time_ms", None),
    )

    # ---- Step B: prediction (W_LOAD_PREP -> W_LOAD_PREP + W_PREDICT) ----
    total_images = max(int(S * F), 1)

    def _pred_progress(done_images: int):
        frac = float(done_images) / float(total_images)
        frac = float(np.clip(frac, 0.0, 1.0))
        file_frac = W_LOAD_PREP + W_PREDICT * frac
        _p(file_frac, f"Predicting... ({int(round(frac * 100))}%)")

    preds_4d_256, imgs_4d_256 = predict_nifti_4d(
        model,
        imgs_4d,
        batch_size=BATCH_SIZE,
        progress_cb=_pred_progress,   # βœ… smooth & real
    )

    preds_4d = preds_4d_256

    # ---- Step C: postprocess + metrics + GIF (remaining W_POST_GIF) ----
    post0 = W_LOAD_PREP + W_PREDICT

    # Split W_POST_GIF into real milestones
    # island: 35%, metrics: 25%, gif: 40% (of the post chunk)
    w_island  = W_POST_GIF * 0.35
    w_metrics = W_POST_GIF * 0.25
    w_gif     = W_POST_GIF * 0.40

    # Island removal
    if ENABLE_ISLAND_REMOVAL:
        _p(post0 + 0.10 * w_island, "Cleaning islands...")
        preds_4d = clean_predictions_per_frame_3d(preds_4d)
        _p(post0 + w_island, "Cleaning islands... done")
    else:
        _p(post0 + w_island, "Skipping island removal")

    preds_4d_orig = preds_4d.copy()   # βœ… immutable snapshot

    # Metrics
    _p(post0 + w_island + 0.10 * w_metrics, "Computing metrics...")

    voxel_mm3 = (
        seg_spacing["row_mm"]
        * seg_spacing["col_mm"]
        * seg_spacing["slice_thickness_mm"]
    )

    mid_slices = None
    if USE_MID_SLICES_FOR_ED_ES:
        has_blood, has_myo, _, _ = slice_validity_matrix(
            preds_4d, A_blood_min=MID_A_BLOOD_MIN, A_myo_min=MID_A_MYO_MIN
        )
        mid_slices = choose_mid_slices(
            has_blood,
            has_myo,
            K=min(MID_K, preds_4d.shape[2]),
            min_frac=MID_MIN_VALID_FRAC,
        )
        vols_subset = frame_volumes_subset_uL(preds_4d, seg_spacing, mid_slices)
        ed_idx, es_idx = pick_ed_es_from_volumes(
            vols_subset, prefer_frame0=True, rel_tol=0.05, min_sep=1
        )
        vols_full = np.array(
            [(preds_4d[..., f] == 2).sum() * voxel_mm3 for f in range(F)],
            dtype=np.float32,
        )
        EDV_uL = float(vols_full[ed_idx])
        ESV_uL = float(vols_full[es_idx])
    else:
        vols_full = np.array(
            [(preds_4d[..., f] == 2).sum() * voxel_mm3 for f in range(F)],
            dtype=np.float32,
        )
        ed_idx, es_idx = pick_ed_es_from_volumes(
            vols_full, prefer_frame0=True, rel_tol=0.05, min_sep=1
        )
        EDV_uL = float(vols_full[ed_idx])
        ESV_uL = float(vols_full[es_idx])

    SV_uL = EDV_uL - ESV_uL
    EF_pct = (SV_uL / EDV_uL * 100.0) if EDV_uL > 0 else 0.0

    per_frame_df = compute_per_frame_metrics(preds_4d, seg_spacing)

    # Safer indexing
    try:
        myo_mass_ED_mg = float(per_frame_df.loc[per_frame_df["Frame"] == ed_idx, "MyocardiumMass_mg"].values[0])
    except Exception:
        myo_mass_ED_mg = 0.0
    try:
        myo_mass_ES_mg = float(per_frame_df.loc[per_frame_df["Frame"] == es_idx, "MyocardiumMass_mg"].values[0])
    except Exception:
        myo_mass_ES_mg = 0.0

    per_frame_df.insert(0, "Patient_ID", pid)
    per_frame_rows_acc.append(per_frame_df)

    rows_acc.append(
        {
            "Patient_ID": pid,
            "EDV_uL": EDV_uL,
            "ESV_uL": ESV_uL,
            "SV_uL": SV_uL,
            "EF_%": EF_pct,
            "MyocardiumMass_ED_mg": myo_mass_ED_mg,
            "MyocardiumMass_ES_mg": myo_mass_ES_mg,
            "ED_frame_index": int(ed_idx),
            "ES_frame_index": int(es_idx),
            "Seg_SliceThickness_mm": seg_spacing["slice_thickness_mm"],
            "Seg_PixelSpacing_row_mm": seg_spacing["row_mm"],
            "Seg_PixelSpacing_col_mm": seg_spacing["col_mm"],
            "Native_SliceThickness_mm": spacing["slice_thickness_mm"],
            "Native_PixelSpacing_row_mm": spacing["row_mm"],
            "Native_PixelSpacing_col_mm": spacing["col_mm"],
        }
    )

    _p(post0 + w_island + w_metrics, "Computing metrics... done")

    # GIF
    _p(post0 + w_island + w_metrics + 0.10 * w_gif, "Creating GIF...")
    gif_path = gif_animation_for_patient_pred_only(
        imgs_4d_256, preds_4d, pid, ed_idx, es_idx, get_session_gifs_dir()
    )
    log(f"[CASE] GIF saved: {gif_path}")

    if "gif_paths" not in st.session_state:
        st.session_state["gif_paths"] = {}
    st.session_state["gif_paths"][pid] = gif_path

    case_info = dict(
        pid=pid,
        imgs_4d_256=imgs_4d_256,
        preds_4d=preds_4d,
        preds_4d_orig=preds_4d_orig,
        seg_spacing=seg_spacing,
        native_spacing=spacing,
        native_shape=(native_h, native_w, S, F),
        affine=final_aff,
        ed_idx_auto=int(ed_idx),
        es_idx_auto=int(es_idx),
        ed_idx_user=int(ed_idx),
        es_idx_user=int(es_idx),
        ed_es_confirmed=False,
        mid_slices=mid_slices,
    )
    case_info["dirty"] = False
    case_info["mask_edited"] = False

    if "cases" not in st.session_state:
        st.session_state["cases"] = {}
    st.session_state["cases"][pid] = case_info

    # βœ… Done for this file
    _p(1.0, "Done")



# =========================
#   Recompute metrics from corrected masks
# =========================
def recompute_metrics_from_session_cases_dirty_gif_only():
    """
    Choice 1:
      - Recompute metrics for ALL cases (cheap; keeps CSV consistent)
      - Regenerate GIF ONLY for cases marked case["dirty"] == True (expensive; saved)
      - Clear dirty flag after regenerating GIF

    Uses user-confirmed ED/ES if available; otherwise falls back to current case ed/es.
    """
    if "cases" not in st.session_state or not st.session_state["cases"]:
        return [], [], False

    rows: List[Dict] = []
    per_frame_rows: List[pd.DataFrame] = []
    updated_any_gif = False

    if "gif_paths_corrected" not in st.session_state:
        st.session_state["gif_paths_corrected"] = {}

    for pid, case in st.session_state["cases"].items():
        preds_4d = case["preds_4d"]
        imgs_4d_256 = case["imgs_4d_256"]
        seg_spacing = case["seg_spacing"]
        spacing = case["native_spacing"]

        # --- choose ED/ES indices ---
        # Prefer user-confirmed indices if present; else fall back to stored ones.
        if case.get("ed_es_confirmed", False):
            ed_idx = int(case["ed_idx_user"])
            es_idx = int(case["es_idx_user"])
        else:
            ed_idx = int(case["ed_idx_auto"])
            es_idx = int(case["es_idx_auto"])


        # --- recompute metrics for ALL cases (cheap) ---
        voxel_mm3 = (
            seg_spacing["row_mm"]
            * seg_spacing["col_mm"]
            * seg_spacing["slice_thickness_mm"]
        )
        F = preds_4d.shape[3]
        vols_full = np.array(
            [(preds_4d[..., f] == 2).sum() * voxel_mm3 for f in range(F)],
            dtype=np.float32,
        )

        EDV_uL = float(vols_full[ed_idx]) if 0 <= ed_idx < F else 0.0
        ESV_uL = float(vols_full[es_idx]) if 0 <= es_idx < F else 0.0
        SV_uL = EDV_uL - ESV_uL
        EF_pct = (SV_uL / EDV_uL * 100.0) if EDV_uL > 0 else 0.0

        per_frame_df = compute_per_frame_metrics(preds_4d, seg_spacing)

        # Guard in case indices are out of bounds (shouldn't happen, but safe)
        try:
            myo_mass_ED_mg = float(
                per_frame_df.loc[per_frame_df["Frame"] == ed_idx, "MyocardiumMass_mg"].values[0]
            )
        except Exception:
            myo_mass_ED_mg = 0.0
        try:
            myo_mass_ES_mg = float(
                per_frame_df.loc[per_frame_df["Frame"] == es_idx, "MyocardiumMass_mg"].values[0]
            )
        except Exception:
            myo_mass_ES_mg = 0.0

        per_frame_df.insert(0, "Patient_ID", pid)
        per_frame_rows.append(per_frame_df)

        rows.append(
            {
                "Patient_ID": pid,
                "EDV_uL": EDV_uL,
                "ESV_uL": ESV_uL,
                "SV_uL": SV_uL,
                "EF_%": EF_pct,
                "MyocardiumMass_ED_mg": myo_mass_ED_mg,
                "MyocardiumMass_ES_mg": myo_mass_ES_mg,
                "ED_frame_index": int(ed_idx),
                "ES_frame_index": int(es_idx),
                "Seg_SliceThickness_mm": seg_spacing["slice_thickness_mm"],
                "Seg_PixelSpacing_row_mm": seg_spacing["row_mm"],
                "Seg_PixelSpacing_col_mm": seg_spacing["col_mm"],
                "Native_SliceThickness_mm": spacing["slice_thickness_mm"],
                "Native_PixelSpacing_row_mm": spacing["row_mm"],
                "Native_PixelSpacing_col_mm": spacing["col_mm"],
            }
        )


        # --- regenerate GIF only if dirty ---
        if case.get("dirty", False):
            gif_path = gif_animation_for_patient_pred_only(
                imgs_4d_256,
                preds_4d,
                pid,
                ed_idx,
                es_idx,
                get_session_gifs_dir(),
            )
            st.session_state["gif_paths_corrected"][pid] = gif_path
            case["dirty"] = False
            updated_any_gif = True

    return rows, per_frame_rows, updated_any_gif



# =========================
#           UI
# =========================
def main():
    st.set_page_config(layout="wide", initial_sidebar_state="collapsed")
    _inject_layout_css()

    st.markdown(
        f'''
        <div id="fixed-edge-logo" aria-hidden="true" role="presentation">
          <img src="{LOGO_URL}" alt="Pre-Clinical Cardiac MRI Segmentation">
        </div>
        <div class="edge-logo-spacer"></div>
        ''',
        unsafe_allow_html=True,
    )

    tab1, tab2, tab3 = st.tabs(
        ["Segmentation App", "Dataset", "NIfTI converter"]
    )

    # ===== Tab 1: Segmentation App =====
    with tab1:
        st.markdown(
            """
            <style>
            [data-testid="stHeading"] a,
            h1 a[href^="#"],
            h2 a[href^="#"],
            h3 a[href^="#"] {
                display: none !important;
                visibility: hidden !important;
            }
            </style>
            """,
            unsafe_allow_html=True,
        )

        HERO_HTML = dedent(
            """\
        <div class="content-wrap">
        <div class="measure-wrap">
        <div class="text-wrap">
        <h1 class="hero-title">
        Open-Source Pre-Clinical Image Segmentation:<br>
        Mouse cardiac MRI datasets with a deep learning segmentation framework
        </h1>
        </div>
        <div class="text-wrap">
        <p>We present the first publicly-available pre-clinical cardiac MRI dataset, along with an open-source DL segmentation model (both available on GitHub:
        <a href="https://github.com/mrphys/Open-Source_Pre-Clinical_Segmentation.git" target="_blank" rel="noopener">https://github.com/mrphys/Open-Source_Pre-Clinical_Segmentation.git</a>) and this web-based interface for easy deployment.</p>
        <p>The dataset comprises complete cine short-axis cardiac MRI images from 130 mice with diverse phenotypes. It also contains expert manual segmentations of left ventricular (LV) blood pool and myocardium at end-diastole, end-systole, as well as additional timeframes with artefacts to improve robustness.</p>
        <p>Using this resource, we developed an open-source DL segmentation model based on the UNet3+ architecture.</p>
        <p>This Streamlit application consists of the inference model to provide an easy-to-use interface for our DL segmentation model, without the need for local installation. The application requires the complete SAX cine image data to be uploaded in NIfTI format, as a ZIP file using the simple file browser below.</p>
        <p>Pre-processing and inference are then performed on all 2D images. The resulting blood-pool and myocardial volumes are combined across all slices at each timeframe and output to a .csv file. The blood-pool volumes are used to identify ED and ES, and these volumes are displayed as a GIF with the segmentations overlaid.</p>
        <p class="note-text">(Note: This Hugging Face model was developed as part of a manuscript submitted to the <em>Journal of Cardiovascular Magnetic Resonance</em>)</p>
        </div>
        </div>
        </div>
        """
        )
        st.markdown(HERO_HTML, unsafe_allow_html=True)

        st.markdown(
            '<div class="content-wrap"><div class="measure-wrap" id="upload-wrap">',
            unsafe_allow_html=True,
        )
        st.markdown(
            """
            <h2 style='margin-bottom:0.2rem;'>
                Data Upload <span style='font-size:33px;'>πŸ“€</span>
            </h2>
            """,
            unsafe_allow_html=True,
        )
        uploaded_zip = st.file_uploader(
            "Upload ZIP of NIfTI files 🐭",
            type="zip",
            label_visibility="visible",
        )

        st.markdown(
            """
            <p style="margin-top:0.3rem; font-size:15px; color:#444;">
            Or download our <a href="https://huggingface.co/spaces/mrphys/Pre-clinical_DL_segmentation/tree/main/NIfTI_dataset" target="_blank" rel="noopener">
            sample NIfTI dataset</a> to try it out!
            </p>
            """,
            unsafe_allow_html=True,
        )

        st.markdown("</div></div>", unsafe_allow_html=True)


        


        # Reset state when a new ZIP is uploaded (by CONTENT, not only name)
        if uploaded_zip is not None:
            zip_bytes_now = uploaded_zip.getvalue()
            zip_hash_now = hashlib.sha256(zip_bytes_now).hexdigest()
        
            if st.session_state.get("_last_zip_hash") != zip_hash_now:
                for key in [
                    "csv_bytes_orig",
                    "csv_name_orig",
                    "csv_bytes_corrected",
                    "csv_name_corrected",
                    "rows_count",
                    "cases",
                    "gif_paths",
                    "gif_paths_original",
                    "gif_paths_corrected",
                    "session_tmpdir",
                    # cached zips
                    "mask_zip_bytes",
                    "mask_zip_name",
                    "gif_zip_bytes",
                    "gif_zip_name",
                    # βœ… add these
                    "processing_done",
                    "processing_running",
                ]:
                    st.session_state.pop(key, None)

                invalidate_download_caches()
        
                st.session_state["_last_zip_hash"] = zip_hash_now
                st.session_state["_last_zip_name"] = uploaded_zip.name
                st.session_state["_last_zip_bytes"] = zip_bytes_now  # reuse without re-reading



        def extract_zip(zip_path, extract_to):
            os.makedirs(extract_to, exist_ok=True)
            with zipfile.ZipFile(zip_path, "r") as zip_ref:
                valid_files = [
                    f
                    for f in zip_ref.namelist()
                    if "__MACOSX" not in f and not os.path.basename(f).startswith("._")
                ]
                zip_ref.extractall(extract_to, members=valid_files)
        

    
        
        # --- Process button / ZIP pipeline ---
        if uploaded_zip and st.button("Process Data"):
            # βœ… processing flags
            st.session_state["processing_running"] = True
            st.session_state["processing_done"] = False
            zip_label = uploaded_zip.name or "ZIP"
        
            # βœ… 1) fixed-position spinner placeholder (right after button)
            spinner_ph = st.empty()
        
            # βœ… 2) progress + status BELOW spinner
            prog = st.progress(0.0)
            status = st.empty()
        
            # βœ… 3) GIF gallery BELOW everything (so it doesn't push spinner)
            gif_gallery = st.container()
        
            # Use cached bytes (set in the reset block); fallback to getvalue()
            zip_bytes = st.session_state.get("_last_zip_bytes", uploaded_zip.getvalue())
        
            try:
                # βœ… render spinner INSIDE placeholder so it stays in one fixed slot
                with spinner_ph:
                    with st.spinner(f"Processing {zip_label}..."):
                        tmpdir = tempfile.mkdtemp()
                        zpath = os.path.join(tmpdir, uploaded_zip.name)
        
                        # write uploaded zip to disk (DON'T use uploaded_zip.read())
                        with open(zpath, "wb") as f:
                            f.write(zip_bytes)
        
                        extract_zip(zpath, tmpdir)
        
                        nii_files: List[str] = []
                        for root, _, files in os.walk(tmpdir):
                            for fn in files:
                                low = fn.lower()
                                if low.endswith(".nii") or low.endswith(".nii.gz"):
                                    nii_files.append(os.path.join(root, fn))
        
                        if not nii_files:
                            st.error("No NIfTI files (.nii / .nii.gz) found in the uploaded ZIP.")
                        else:
                            model = get_model()
                            log("[MODEL] Loaded segmentation model (cached).")
        
                            rows: List[Dict] = []
                            per_frame_rows: List[pd.DataFrame] = []
        
                            st.session_state["cases"] = {}
                            st.session_state["gif_paths"] = {}
        
                            nii_files_sorted = sorted(nii_files)
                            total = len(nii_files_sorted)
        
                            # Start at 0%
                            prog.progress(0.0)
                            status.markdown(
                                f"**ZIP:** `{zip_label}`  \n"
                                f"**Progress:** 0% (0/{total})  \n"
                                f"**Now:** `-`  \n"
                                f"**Step:** Waiting..."
                            )
        
                            for i, fp in enumerate(nii_files_sorted, start=1):
                                name = Path(fp).name
                                pid = name.replace(".nii.gz", "").replace(".nii", "")
        
                                # Fraction completed by finished files
                                base = (i - 1) / max(total, 1)
                                span = 1.0 / max(total, 1)
        
                                # Avoid backwards jitter (per-file)
                                overall_state = {"last_overall": float(base)}
        
                                def file_progress_cb(file_frac: float, msg: Optional[str] = None):
                                    """
                                    file_frac: 0..1 for THIS file; map to global progress 0..1
                                    msg: step message (optional)
                                    """
                                    overall = base + span * float(np.clip(file_frac, 0.0, 1.0))
        
                                    # Never go backwards
                                    overall = max(overall, overall_state["last_overall"])
                                    overall_state["last_overall"] = overall
        
                                    prog.progress(float(np.clip(overall, 0.0, 1.0)))
        
                                    pct = int(round(overall * 100))
                                    line_msg = msg or "Working..."
                                    status.markdown(
                                        f"**ZIP:** `{zip_label}`  \n"
                                        f"**Progress:** {pct}% ({i}/{total})  \n"
                                        f"**Now:** `{pid}`  \n"
                                        f"**Step:** {line_msg}"
                                    )
        
                                # Make sure UI shows which file started immediately
                                file_progress_cb(0.0, "Starting...")
        
                                try:
                                    process_nifti_case(
                                        fp,
                                        model,
                                        rows,
                                        per_frame_rows,
                                        progress_cb=file_progress_cb,  # βœ… weighted, real progress + step messages
                                    )
        
                                    # βœ… show GIF immediately (stacking)
                                    gif_path = st.session_state.get("gif_paths", {}).get(pid)
                                    if gif_path and os.path.exists(gif_path):
                                        with gif_gallery:
                                            with open(gif_path, "rb") as fgif:
                                                st.image(
                                                    fgif.read(),
                                                    caption=f"{pid} – ED/ES GIF (original)",
                                                    use_column_width=True,
                                                )
        
                                except Exception as e:
                                    st.warning(f"Failed: {name} β€” {e}")
        
                                # After each file, force progress to at least the file boundary
                                file_progress_cb(1.0, "Done")
        
                            # Ensure end at 100%
                            prog.progress(1.0)
                            status.markdown(f"βœ… **Done:** `{zip_label}` β€” {total}/{total} (100%)")
        
                            csv_path = write_all_in_one_csv(rows, per_frame_rows, get_session_csv_dir())
                            csv_download_name = f"{Path(zip_label).stem}_Results.csv"
        
                            with open(csv_path, "rb") as fcsv:
                                st.session_state["csv_bytes_orig"] = fcsv.read()
        
                            st.session_state["csv_name_orig"] = csv_download_name
                            st.session_state["rows_count"] = len(rows)
                            st.session_state["gif_paths_original"] = dict(st.session_state.get("gif_paths", {}))
        
            finally:
                # βœ… always clear spinner + set flags, even if something errors
                spinner_ph.empty()
                st.session_state["processing_running"] = False
                st.session_state["processing_done"] = True
                invalidate_download_caches()


        
            
        # --- Reserve stable slots so layout doesn't jump ---
        downloads_slot = st.container()
        downloads_spacer = st.empty()
        
        if not st.session_state.get("processing_done", False):
            downloads_spacer.markdown(
                "<div style='min-height:120px'></div>",
                unsafe_allow_html=True
            )
        else:
            downloads_spacer.empty()      
            with downloads_slot:
            
                # Show the green success banner once (only if results exist)
                if "csv_bytes_orig" in st.session_state and "csv_name_orig" in st.session_state:
                    st.success(f"Processed {st.session_state.get('rows_count', 0)} NIfTI file(s).")
            
                # =========================
                # ORIGINAL downloads group
                # =========================
            
                # 1) Ensure ORIGINAL mask zip exists
                if "cases" in st.session_state and st.session_state["cases"]:
                    if "mask_zip_bytes" not in st.session_state:
                        zipstem = Path(st.session_state.get("_last_zip_name", "Results")).stem
                        mask_zip_name = f"{zipstem}_Mask.zip"
            
                        mask_files = []
                        for pid, case in st.session_state["cases"].items():
                            native_h, native_w, S, F = case["native_shape"]
                            affine = case["affine"]
                            mask_native = resize_masks_to_native(case["preds_4d_orig"], native_h, native_w)
            
                            session_tmp = get_session_tmpdir()
                            tmp_mask_path = os.path.join(session_tmp, f"{pid}_mask.nii.gz")
                            save_native_mask_nifti_with_labels(mask_native, affine, tmp_mask_path)
            
                            with open(tmp_mask_path, "rb") as f:
                                mask_files.append((f"{pid}_mask.nii.gz", f.read()))
                            try:
                                os.remove(tmp_mask_path)
                            except OSError:
                                pass
            
                        st.session_state["mask_zip_bytes"] = build_zip_bytes(mask_files, root_folder=None)
                        st.session_state["mask_zip_name"] = mask_zip_name
            
                # 2) Ensure ORIGINAL gif zip exists
                if "gif_paths_original" in st.session_state:
                    if "gif_zip_bytes" not in st.session_state:
                        zipstem = Path(st.session_state.get("_last_zip_name", "Results")).stem
                        gif_root = f"{zipstem}_GIF"
                        gif_zip_name = f"{gif_root}.zip"
            
                        gif_files = []
                        orig = st.session_state.get("gif_paths_original", {}) or {}
            
                        for pid, gif_path in orig.items():
                            if gif_path and os.path.exists(gif_path):
                                with open(gif_path, "rb") as f:
                                    gif_files.append((f"{pid}.gif", f.read()))
            
                        st.session_state["gif_zip_bytes"] = build_zip_bytes(gif_files, root_folder=gif_root)
                        st.session_state["gif_zip_name"] = gif_zip_name
            
                # 3) Build ONE button group
                buttons = []
            
                if "csv_bytes_orig" in st.session_state and "csv_name_orig" in st.session_state:
                    buttons.append({
                        "label": "Download CSV",
                        "bytes": st.session_state["csv_bytes_orig"],
                        "filename": st.session_state["csv_name_orig"],
                        "mime": "text/csv",
                        "key": "orig_csv",
                    })
            
                if "mask_zip_bytes" in st.session_state and "mask_zip_name" in st.session_state:
                    buttons.append({
                        "label": "Download Masks",
                        "bytes": st.session_state["mask_zip_bytes"],
                        "filename": st.session_state["mask_zip_name"],
                        "mime": "application/zip",
                        "key": "orig_masks",
                    })
            
                if "gif_zip_bytes" in st.session_state and "gif_zip_name" in st.session_state:
                    buttons.append({
                        "label": "Download GIF",
                        "bytes": st.session_state["gif_zip_bytes"],
                        "filename": st.session_state["gif_zip_name"],
                        "mime": "application/zip",
                        "key": "orig_gif",
                    })
            
                if buttons:
                    render_download_group(buttons, group_key="orig")

                
    


              
        # ==========================================================
        #      Slice-level manual correction (drawable canvas)
        # ==========================================================
        if "cases" in st.session_state and st.session_state["cases"]:
            st.markdown("---")
            st.markdown("## Optional: Slice-level manual correction")
        
            cases = st.session_state["cases"]
            case_ids = list(cases.keys())
        
            selected_pid = st.selectbox(
                "Select NIfTI / mouse ID to inspect",
                case_ids,
                key="edit_pid",
            )
        
            case = cases[selected_pid]
            imgs_4d_256 = case["imgs_4d_256"]  # (256,256,S,F)
            preds_4d = case["preds_4d"]        # (256,256,S,F)
            _, _, S, F = preds_4d.shape
        
                    
            # ==========================================================
            # Step 1 β€” Confirm ED/ES (required before editing)
            # ==========================================================
            st.markdown("### Step 1 β€” Confirm ED/ES (required before editing)")
            
            colA, colB = st.columns(2)
            
            with colA:
                st.markdown("**ED frame (1-based)**")
            
                ed_state_key = f"ed_user_1b_state_{selected_pid}"
                if ed_state_key not in st.session_state:
                    st.session_state[ed_state_key] = int(case["ed_idx_user"]) + 1
            
                ed_user_1b = st.slider(
                    "ED frame (1-based)",
                    min_value=1,
                    max_value=F,
                    value=int(st.session_state[ed_state_key]),
                    key=f"ed_user_slider_{selected_pid}",
                    label_visibility="collapsed",
                )
                st.session_state[ed_state_key] = int(ed_user_1b)
            
                bprev, _, bnext = st.columns([1, 10, 1])
                with bprev:
                    if st.button("β¬…", key=f"ed_prev_{selected_pid}", use_container_width=True):
                        st.session_state[ed_state_key] = max(1, int(st.session_state[ed_state_key]) - 1)
                        _safe_rerun()
            
                with bnext:
                    if st.button("➑", key=f"ed_next_{selected_pid}", use_container_width=True):
                        st.session_state[ed_state_key] = min(F, int(st.session_state[ed_state_key]) + 1)
                        _safe_rerun()
            
            with colB:
                st.markdown("**ES frame (1-based)**")
            
                es_state_key = f"es_user_1b_state_{selected_pid}"
                if es_state_key not in st.session_state:
                    st.session_state[es_state_key] = int(case["es_idx_user"]) + 1
            
                es_user_1b = st.slider(
                    "ES frame (1-based)",
                    min_value=1,
                    max_value=F,
                    value=int(st.session_state[es_state_key]),
                    key=f"es_user_slider_{selected_pid}",
                    label_visibility="collapsed",
                )
                st.session_state[es_state_key] = int(es_user_1b)
            
                bprev, _, bnext = st.columns([1, 10, 1])
                with bprev:
                    if st.button("β¬…", key=f"es_prev_{selected_pid}", use_container_width=True):
                        st.session_state[es_state_key] = max(1, int(st.session_state[es_state_key]) - 1)
                        _safe_rerun()
            
                with bnext:
                    if st.button("➑", key=f"es_next_{selected_pid}", use_container_width=True):
                        st.session_state[es_state_key] = min(F, int(st.session_state[es_state_key]) + 1)
                        _safe_rerun()
            
            # ----------------------------------------------------------
            # πŸ”₯ PREVIEWS (always visible; updates when sliders change)
            # ----------------------------------------------------------
            slice_indices = list(range(S))
            
            col_prevA, col_prevB = st.columns(2)
            
            with col_prevA:
                montage_ed = build_frame_montage(
                    imgs_4d_256,
                    preds_4d,
                    frame_idx=int(st.session_state[ed_state_key]) - 1,
                    slice_indices=slice_indices,
                    tile_cols=4,
                    add_overlay=True,
                )
                st.image(montage_ed, caption=f"ED preview β€” frame {st.session_state[ed_state_key]}")
            
            with col_prevB:
                montage_es = build_frame_montage(
                    imgs_4d_256,
                    preds_4d,
                    frame_idx=int(st.session_state[es_state_key]) - 1,
                    slice_indices=slice_indices,
                    tile_cols=4,
                    add_overlay=True,
                )
                st.image(montage_es, caption=f"ES preview β€” frame {st.session_state[es_state_key]}")
            
            # βœ… THEN confirm button
            confirm = st.button(
                f"Confirm ED/ES for {selected_pid}",
                key=f"confirm_ed_es_{selected_pid}",
            )
            
            if confirm:
                ed_user_1b = int(st.session_state[ed_state_key])
                es_user_1b = int(st.session_state[es_state_key])
                case["ed_idx_user"] = ed_user_1b - 1
                case["es_idx_user"] = es_user_1b - 1
                case["ed_es_confirmed"] = True
                case["dirty"] = True
                st.success(f"Confirmed: ED frame {ed_user_1b}, ES frame {es_user_1b}. Editing unlocked.")

            


            # Gate the editor - replace st.stop() with else
            if not case.get("ed_es_confirmed", False):
                st.info("Confirm ED/ES above to enable mask editing.")
            else:
            
                # ==========================================================
                # Step 2 β€” Select Frame to Edit (ED/ES only)
                # ==========================================================
                st.markdown("### Step 2 β€” Select Frame to Edit")
                
                frame_mode = st.radio(
                    "Frame to edit",
                    ["ED", "ES"],
                    horizontal=True,
                    key=f"edit_frame_mode_{selected_pid}",
                )
                
                # Use the CONFIRMED ED/ES
                if frame_mode == "ED":
                    f = int(case["ed_idx_user"])
                    frame_idx_1b = f + 1
                    frame_label = f"ED (confirmed frame {frame_idx_1b})"
                else:
                    f = int(case["es_idx_user"])
                    frame_idx_1b = f + 1
                    frame_label = f"ES (confirmed frame {frame_idx_1b})"
                
                st.caption(f"Editing is locked to: **{frame_label}**")
                
        
                # ==========================================================
                # Step 3 β€” Select Slice to Edit
                # ==========================================================
                st.markdown("### Step 3 β€” Select Slice to Edit")
                
                state_key = f"edit_slice_idx_state_{selected_pid}_{f}"
                if state_key not in st.session_state:
                    st.session_state[state_key] = 1  # 1-based default
                
                # -------------------------
                # Row 1: slider ONLY
                # -------------------------
                slice_idx_1b = st.slider(
                    "Slice to edit (1-based)",
                    min_value=1,
                    max_value=S,
                    value=int(st.session_state[state_key]),
                    key=f"edit_slice_idx_slider_{selected_pid}_{f}",
                )
                st.session_state[state_key] = int(slice_idx_1b)
                
                # 0-based slice index
                s = int(st.session_state[state_key]) - 1
                
                # -------------------------
                # Row 2: buttons at ENDS
                # -------------------------
                bprev, _, bnext = st.columns([2, 10, 2])
                
                with bprev:
                    if st.button("β¬… Previous slice", key=f"edit_prev_slice_{selected_pid}_{f}", use_container_width=True):
                        st.session_state[state_key] = max(1, int(st.session_state[state_key]) - 1)
                        _safe_rerun()
                
                with bnext:
                    if st.button("Next slice ➑", key=f"edit_next_slice_{selected_pid}_{f}", use_container_width=True):
                        st.session_state[state_key] = min(S, int(st.session_state[state_key]) + 1)
                        _safe_rerun()
                


                
                # Now show preview (uses updated slice index)
                st.markdown(
                    f"**Current segmentation preview – Mouse {selected_pid}, "
                    f"Slice {st.session_state[state_key]}, {frame_label}**"
                )
                

                DISP_W = SIZE_X * CANVAS_SCALE

                preview_pil = render_overlay_pil_scaled(
                    imgs_4d_256[:, :, s, f],
                    preds_4d[:, :, s, f],
                )
                
                st.image(preview_pil, width=DISP_W)


            
                # ----- LV contour paint only -----
                with st.expander("LV contour paint for this slice / frame"):
                    st.markdown(
                        "Draw LV contours:\n\n"
                        "- **Red** line β†’ inner border (LV blood pool / endocardium)\n"
                        "- **Blue** line β†’ outer border (LV myocardium / epicardium)\n\n"
                        "The filled interior of the red contour becomes **blood pool**; "
                        "the ring between blue and red becomes **myocardium**. "
                        "Existing LV labels on this slice are replaced."
                    )
            
                    min_effective_width = 1
                    recommended_canvas_width = int(min_effective_width * CANVAS_SCALE)
            
                    st.caption(
                        f"Tip: with CANVAS_SCALE={CANVAS_SCALE}, a brush β‰₯ {recommended_canvas_width}px "
                        f"is recommended so the contour is at least ~{min_effective_width}px thick in 256Γ—256."
                    )
    
                    stroke_width = st.slider(
                        "Brush width (pixels)",
                        min_value=recommended_canvas_width,
                        max_value=40,
                        value=recommended_canvas_width,
                        key=f"edit_brush_width_{selected_pid}",
                    )
        
                    slice_img_uint8 = _normalize_to_uint8(imgs_4d_256[:, :, s, f])
                    slice_pil_small = Image.fromarray(slice_img_uint8)
                    slice_pil = slice_pil_small.resize(
                        (SIZE_X * CANVAS_SCALE, SIZE_Y * CANVAS_SCALE),
                        resample=Image.NEAREST,
                    )
            
                    lv_contour_choice = st.radio(
                        "Which contour are you drawing now?",
                        ["Blood pool (inner, red)", "Myocardium (outer, blue)"],
                        horizontal=True,
                        key=f"lv_contour_choice_{selected_pid}",
                    )
            
                    stroke_color_hex = "#ff0000" if "Blood" in lv_contour_choice else "#0000ff"
            
                    canvas_key = f"canvas_{selected_pid}_{s}_{f}"
                    canvas_result = st_canvas(
                        fill_color=stroke_color_hex,
                        stroke_width=stroke_width,
                        stroke_color=stroke_color_hex,
                        background_image=slice_pil,
                        background_color=None,
                        height=SIZE_Y * CANVAS_SCALE,
                        width=SIZE_X * CANVAS_SCALE,
                        drawing_mode="freedraw",
                        update_streamlit=True,
                        key=canvas_key,
                    )
            
                    apply_btn = st.button(
                        "Apply LV contour correction to this slice / frame",
                        key=f"apply_lv_{selected_pid}_{s}_{f}",
                    )
    
                    if apply_btn:
                        if canvas_result is None or canvas_result.image_data is None:
                            st.warning("No contours detected on the canvas.")
                        else:
                            canvas_rgba = canvas_result.image_data.astype(np.uint8)
            
                            # Downsample back to 256Γ—256 in label space
                            rgba_resized = np.array(
                                Image.fromarray(canvas_rgba).resize((SIZE_X, SIZE_Y), resample=Image.NEAREST)
                            )
            
                            updated_slice = _apply_lv_contour_style(
                                preds_4d[:, :, s, f],
                                rgba_resized,
                            )
                            preds_4d[:, :, s, f] = updated_slice
                            case["preds_4d"] = preds_4d
                            case["dirty"] = True
                            case["mask_edited"] = True   # mask was actually changed
                            invalidate_download_caches()


                            DISP_W = SIZE_X * CANVAS_SCALE
                            
                            st.success("LV blood pool & myocardium updated from red/blue contours.")
                            
                            updated_pil = render_overlay_pil_scaled(
                                imgs_4d_256[:, :, s, f],
                                preds_4d[:, :, s, f],
                            )
                            
                            st.image(updated_pil, width=DISP_W)

            
                    clear_btn = st.button(
                        "No mask for this image (clear LV segmentation)",
                        key=f"clear_mask_{selected_pid}_{s}_{f}",
                    )
                    if clear_btn:
                        preds_4d[:, :, s, f] = 0
                        case["preds_4d"] = preds_4d
                        case["dirty"] = True
                        case["mask_edited"] = True   # mask was actually changed
                        invalidate_download_caches()


                        DISP_W = SIZE_X * CANVAS_SCALE

                        st.success("LV mask cleared for this slice / frame.")
                        
                        updated_pil = render_overlay_pil_scaled(
                            imgs_4d_256[:, :, s, f],
                            preds_4d[:, :, s, f],
                        )
                        
                        st.image(updated_pil, width=DISP_W)


                # ==========================================================
                # Recompute + regenerate corrected CSV/GIFs
                # ==========================================================
                st.markdown("---")
                recompute_clicked = st.button(
                    "Recompute cardiac function & regenerate CSV/GIFs from corrected masks",
                    key="recompute_metrics_btn",
                )
                
                if recompute_clicked:
                    with st.spinner("Recomputing metrics and regenerating CSV/GIFs from corrected masks..."):
                        new_rows, new_per_frame_rows, updated_any_gif = recompute_metrics_from_session_cases_dirty_gif_only()
                
                        if not new_rows:
                            st.error("No cases available to recompute metrics.")
                        else:
                            csv_path = write_all_in_one_csv(new_rows, new_per_frame_rows, get_session_csv_dir())
                
                            base_name = "Results"
                            if st.session_state.get("_last_zip_name"):
                                base_name = Path(st.session_state["_last_zip_name"]).stem + "_Results_corrected"
                            csv_download_name = f"{base_name}.csv"
                
                            with open(csv_path, "rb") as fcsv:
                                csv_bytes = fcsv.read()
                
                            st.session_state["csv_bytes_corrected"] = csv_bytes
                            st.session_state["csv_name_corrected"] = csv_download_name
                
                            # βœ… important: clear any cached zips so they rebuild
                            invalidate_download_caches()
                
                            st.success(
                                "CSV updated. Regenerated results for edited mice."
                                if updated_any_gif
                                else "CSV updated. No edited mice detected β€” GIFs unchanged."
                            )
                
                # ==========================================================
                # Updated Results (ONLY 3 buttons live here)
                # ==========================================================                
                if "csv_bytes_corrected" in st.session_state and "csv_name_corrected" in st.session_state:
                    st.markdown("#### Updated Results")
                
                    # Ensure corrected zips exist BEFORE building the group
                    if "mask_zip_bytes_corrected" not in st.session_state:
                        build_corrected_masks_zip_bytes_per_mouse()
                
                    if "gif_zip_bytes_corrected" not in st.session_state:
                        build_corrected_gif_zip_bytes()
                
                    buttons = [
                        {
                            "label": "Download CSV (corrected)",
                            "bytes": st.session_state["csv_bytes_corrected"],
                            "filename": st.session_state["csv_name_corrected"],
                            "mime": "text/csv",
                            "key": "corr_csv",
                        },
                        {
                            "label": "Download Masks (corrected)",
                            "bytes": st.session_state["mask_zip_bytes_corrected"],
                            "filename": st.session_state["mask_zip_name_corrected"],
                            "mime": "application/zip",
                            "key": "corr_masks",
                        },
                        {
                            "label": "Download GIF (corrected)",
                            "bytes": st.session_state["gif_zip_bytes_corrected"],
                            "filename": st.session_state["gif_zip_name_corrected"],
                            "mime": "application/zip",
                            "key": "corr_gif",
                        },
                    ]
                
                    render_download_group(buttons, group_key="corr")
                
                    # Optional: show previews (unchanged)
                    if st.session_state.get("gif_paths_corrected"):
                        st.markdown("##### Updated ED/ES GIFs")
                        for pid, gif_path in st.session_state["gif_paths_corrected"].items():
                            try:
                                with open(gif_path, "rb") as fg:
                                    st.image(fg.read(), caption=f"{pid} – ED/ES GIF (corrected)", use_column_width=True)
                            except Exception:
                                st.image(gif_path, caption=f"{pid} – ED/ES GIF (corrected)")





    # ===== Tab 2: Dataset =====
    with tab2:
        st.markdown(
            """
    <style>
    .ds-hero-section {
      background: #082c3a;
      padding: 30px 10px;
      text-align: center;
      margin-left: -100vw;
      margin-right: -100vw;
      left: 0; right: 0; position: relative;
    }
    .ds-hero-section-inner { max-width: 1100px; margin: 0 auto; }

    .ds-heroimg {
      max-width: 1000px; width: 100%; height: auto;
      border-radius: 10px; box-shadow: 0 8px 24px rgba(0,0,0,.25);
      display: block; margin: 0 auto;
    }

    .ds-caption {
      text-align: center; color: #e0f2f1;
      font-size: 18px; line-height: 1.5;
      margin: 14px 6px 0; font-style: italic;
    }

    .ds-hr {
      height: 8px;
      border: 0; background: #ea580c;
      margin: 24px 0 20px;
      border-radius: 3px;
    }

    .ds-wrap {
      max-width: var(--content-measure, 920px);
      margin-left: var(--left-offset, 40px);
      margin-right: auto;
      background: #fff; padding: 16px 24px; border-radius: 6px;
    }

    .ds-section h2 {
      font-size: 20px; font-weight: 700;
      margin: 0 0 2px;
      color: #082c3a;
    }

    .ds-section p {
      font-size: 16px; line-height: 1.6; color: #333;
      margin: 0 0 6px;
    }
    .ds-section ul {
      margin: 2px 0 8px 18px;
      padding: 0;
    }
    .ds-section li {
      font-size: 16px; line-height: 1.6; color: #333;
      margin-bottom: 10px;
    }
    .ds-section a {
      color: #0b66c3 !important; text-decoration: underline !important;
    }

    h2 a, [data-testid="stHeading"] a { display: none !important; }
    </style>

    <div class="ds-hero-section">
      <div class="ds-hero-section-inner">
        <img class="ds-heroimg"
             src="https://raw.githubusercontent.com/whanisa/Segmentation/main/icon/open_source.png"
             alt="Illustration of mouse with heart representing open-source pre-clinical cardiac MRI dataset" />
        <p class="ds-caption">
          The first publicly-available pre-clinical cardiac MRI dataset,<br/>
          with an open-source segmentation model and an easy-to-use web app.
        </p>
      </div>
    </div>

    <hr class="ds-hr"/>

    <div class="ds-wrap">
      <div class="ds-section">
        <h2>Repository & Paper Resources</h2>
        <p>GitHub:
          <a href="https://github.com/mrphys/Open-Source_Pre-Clinical_Segmentation.git" target="_blank">
            Open-Source_Pre-Clinical_Segmentation
          </a>
        </p>

    <h2>πŸ“Š Dataset Availability</h2>
    <ul>
      <li>
        <strong>Full dataset (130 mice, HDF5 format):</strong><br/>
        Available in our
        <a href="https://github.com/mrphys/Open-Source_Pre-Clinical_Segmentation/tree/master/Data" target="_blank">
          GitHub repository
        </a>.<br/>
        Each .h5 file contains the complete cine SAX MRI and expert manual segmentations.
      </li>
      <li>
        <strong>Sample datasets (3 mice, NIfTI format):</strong><br/>
        Available here:
        <a href="https://huggingface.co/spaces/mrphys/Pre-clinical_DL_segmentation/tree/main/NIfTI_dataset" target="_blank">
          NIfTI Sample Dataset
        </a>.<br/>
        We provide 3 example NIfTI datasets for quick download and direct use within the app.
      </li>
    </ul>
      </div>

      <hr class="ds-hr"/>

      <div class="ds-section">
        <h2>Notes</h2>
        <ul>
          <li>Complete SAX cine MRI for 130 mice with expert LV blood & myocardium labels (ED/ES).</li>
        </ul>
      </div>
    </div>
    """,
            unsafe_allow_html=True,
        )

    # ===== Tab 3: NIfTI converter =====
    with tab3:
        st.subheader("NIfTI converter")
        st.markdown(
            """
            **Working with Agilent data?**  
            Easily convert your fid files to NIfTI using our **fid2niix**.  

            ```bash
            fid2niix -z y -o /path/to/out -f "%p_%s" /path/to/fid_folder
            ```

            **πŸ’‘ Tips**  
            - Upload a ZIP file that includes both `fid` and `procpar`.
            - Conversion outputs **NIfTI-1** format, ready to use with our web app.
            """
        )


if __name__ == "__main__":
    main()