File size: 102,508 Bytes
2d755d5
 
 
ebfc6b3
 
a507fa7
4842c69
25889c7
 
 
 
 
795747f
c1c515b
 
10801c1
ef81af8
044a537
 
 
 
 
2d755d5
122c8fc
25889c7
2d755d5
25889c7
ab54bfa
2d755d5
 
25889c7
2d755d5
25889c7
2d755d5
 
25889c7
122c8fc
2d755d5
25889c7
 
2d755d5
 
 
 
4842c69
2d755d5
 
 
 
4842c69
2d755d5
 
ab54bfa
 
 
 
 
 
 
c1c515b
044a537
2d755d5
 
044a537
c1c515b
795747f
2d755d5
ab54bfa
 
 
 
 
 
 
 
 
044a537
c1c515b
 
2d755d5
 
 
 
 
 
 
 
 
 
ab54bfa
2d755d5
25889c7
2d755d5
ab54bfa
2d755d5
 
25889c7
 
 
2d755d5
 
ab54bfa
 
2d755d5
 
25889c7
ab54bfa
10801c1
25889c7
ab54bfa
25889c7
 
 
2d755d5
25889c7
ab54bfa
25889c7
2d755d5
25889c7
795747f
2d755d5
 
 
795747f
2d755d5
25889c7
044a537
2d755d5
 
 
 
 
 
 
795747f
2d755d5
 
 
 
 
 
 
 
 
 
 
122c8fc
 
 
 
 
 
2d755d5
 
 
 
 
 
122c8fc
 
2d755d5
 
 
 
 
 
 
10801c1
 
2d755d5
 
10801c1
2d755d5
10801c1
 
 
 
122c8fc
2d755d5
 
 
10801c1
2d755d5
 
10801c1
2d755d5
10801c1
 
 
2d755d5
 
10801c1
2d755d5
10801c1
 
 
2d755d5
 
 
 
10801c1
2d755d5
10801c1
 
 
 
 
 
2d755d5
 
 
 
 
10801c1
 
 
 
 
 
 
2d755d5
 
10801c1
2d755d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab54bfa
2d755d5
 
 
 
 
 
ab54bfa
 
2d755d5
 
 
 
 
 
 
 
 
 
 
ab54bfa
 
 
 
 
 
 
2d755d5
 
ab54bfa
2d755d5
 
 
 
 
 
 
 
ab54bfa
2d755d5
 
 
 
 
 
 
ab54bfa
2d755d5
 
 
 
ab54bfa
2d755d5
 
ab54bfa
2d755d5
 
ab54bfa
2d755d5
 
ab54bfa
 
 
 
 
2d755d5
 
 
 
 
 
 
ab54bfa
 
 
 
 
 
2d755d5
 
 
122c8fc
2d755d5
ab54bfa
2d755d5
 
122c8fc
 
 
 
10801c1
2d755d5
 
 
1fec881
2d755d5
1fec881
 
 
 
2d755d5
 
 
 
 
 
 
044a537
1fec881
 
 
2d755d5
 
 
 
 
 
 
9087721
 
2d755d5
 
 
 
 
 
 
044a537
10801c1
 
 
2d755d5
1fec881
2d755d5
ab54bfa
 
 
2d755d5
 
 
 
 
 
 
 
 
044a537
2d755d5
1fec881
2d755d5
 
 
 
9087721
2d755d5
 
795747f
 
2d755d5
 
 
 
 
 
10801c1
 
 
ab54bfa
2d755d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
795747f
c1c515b
2d755d5
 
 
 
ab54bfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d755d5
 
ab54bfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc134c2
2d755d5
 
 
 
 
 
0ae7933
2d755d5
 
 
 
 
 
 
ebfc6b3
2d755d5
37fdac2
 
ef81af8
2d755d5
 
 
10801c1
2d755d5
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2a2364
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5d1658
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc54095
 
 
 
 
 
 
d5d1658
 
 
 
 
 
 
 
 
 
 
bc54095
 
 
 
d5d1658
bc54095
 
 
 
d5d1658
 
 
 
 
bc54095
 
 
 
 
 
 
 
 
 
 
 
d5d1658
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc54095
 
 
 
 
 
 
 
 
 
d5d1658
 
 
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
8a41149
bc54095
 
 
 
41fb562
 
 
bc54095
 
8a41149
bc54095
 
 
41fb562
 
 
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41fb562
 
 
bc54095
905fc6c
41fb562
905fc6c
bc54095
 
905fc6c
bc54095
 
 
 
 
 
 
 
 
905fc6c
bc54095
 
41fb562
 
8a41149
41fb562
905fc6c
 
bc54095
 
 
 
905fc6c
 
bc54095
 
905fc6c
41fb562
bc54095
905fc6c
 
 
bc54095
 
 
905fc6c
bc54095
 
905fc6c
 
 
41fb562
 
 
 
 
 
905fc6c
 
 
bc54095
 
41fb562
 
 
 
 
bc54095
 
41fb562
bc54095
 
 
905fc6c
bc54095
905fc6c
41fb562
 
905fc6c
41fb562
 
 
 
8a41149
905fc6c
bc54095
 
41fb562
 
 
 
 
 
bc54095
41fb562
bc54095
 
 
41fb562
 
905fc6c
 
bc54095
 
905fc6c
bc54095
 
905fc6c
41fb562
 
 
 
 
 
 
905fc6c
8a41149
41fb562
 
905fc6c
41fb562
905fc6c
 
41fb562
 
905fc6c
 
41fb562
8a41149
905fc6c
 
41fb562
 
905fc6c
 
41fb562
 
905fc6c
41fb562
8a41149
41fb562
905fc6c
41fb562
bc54095
 
 
 
41fb562
bc54095
 
 
 
 
41fb562
 
 
bc54095
 
 
 
41fb562
bc54095
 
 
 
 
41fb562
bc54095
 
 
41fb562
bc54095
 
 
 
 
 
 
 
 
8a41149
905fc6c
bc54095
 
 
 
 
 
 
 
 
 
 
2d755d5
 
 
629549f
1be3e2c
2d755d5
1be3e2c
905fc6c
 
 
 
1be3e2c
629549f
2d755d5
 
1be3e2c
2d755d5
 
 
4848790
629549f
2d755d5
905fc6c
2d755d5
 
 
 
 
 
 
 
1be3e2c
2d755d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
795747f
1be3e2c
 
4848790
1be3e2c
 
 
 
 
4848790
1be3e2c
4848790
1be3e2c
4848790
1be3e2c
4848790
2d755d5
 
 
 
 
795747f
2d755d5
 
 
 
 
 
1be3e2c
905fc6c
2d755d5
 
 
 
 
 
 
 
1be3e2c
 
 
10801c1
4848790
 
bc54095
 
 
 
 
 
 
 
 
 
 
 
4091051
bc54095
 
1be3e2c
 
bc54095
 
1be3e2c
4848790
 
bc54095
ab54bfa
bc54095
 
 
1f72340
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d755d5
1be3e2c
bc54095
 
 
1be3e2c
bc54095
 
 
 
 
 
 
 
1be3e2c
bc54095
 
1be3e2c
bc54095
1be3e2c
bc54095
 
 
1be3e2c
bc54095
 
1be3e2c
bc54095
 
1be3e2c
bc54095
 
 
 
 
 
 
 
 
 
 
 
1be3e2c
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1be3e2c
bc54095
 
 
1be3e2c
bc54095
10801c1
 
905fc6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3d1c1c
905fc6c
 
 
 
2d755d5
 
 
10801c1
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1be3e2c
 
 
 
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1be3e2c
 
 
 
 
 
 
 
 
 
 
 
 
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1be3e2c
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1be3e2c
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1be3e2c
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41fb562
 
bc54095
 
7db4de0
bc54095
7db4de0
 
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab54bfa
ad7f495
41fb562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc54095
ab54bfa
bc54095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c7a03d
ab54bfa
 
6ec40e7
ab54bfa
c19569d
 
21b561c
6ec40e7
bc54095
 
 
 
 
 
2573dbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc54095
2573dbd
 
 
 
 
 
 
bc54095
2573dbd
bc54095
7de629a
bc54095
 
 
 
ab54bfa
90830b0
6ec40e7
 
 
b3d1c1c
90830b0
5aea58d
90830b0
 
 
 
 
 
6ec40e7
90830b0
 
 
 
6ec40e7
90830b0
 
6ec40e7
90830b0
 
6ec40e7
90830b0
07bf060
bc54095
 
2ddfc45
bc54095
2ddfc45
e9ca807
da25c3d
 
bc54095
 
1490c4a
 
 
 
6ec40e7
a6d25fc
be55781
90830b0
2933bfe
90830b0
be55781
 
 
 
1490c4a
2933bfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6d25fc
 
6ec40e7
 
2933bfe
a6d25fc
 
90830b0
6ec40e7
90830b0
be55781
 
 
 
a6d25fc
6ec40e7
2933bfe
a6d25fc
 
90830b0
6ec40e7
90830b0
6ec40e7
90830b0
 
a6d25fc
93b1017
173e2b4
 
99798ee
 
 
 
 
173e2b4
99798ee
 
 
173e2b4
99798ee
 
 
 
173e2b4
99798ee
93b1017
173e2b4
 
 
93b1017
 
 
 
 
 
 
 
 
be55781
93b1017
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173e2b4
 
93b1017
173e2b4
 
 
 
 
bc54095
93b1017
 
 
 
2d755d5
 
bc54095
 
 
 
 
 
 
1be3e2c
2d755d5
 
c19569d
84e4497
bc54095
1f72340
84e4497
044a537
69e43f2
da25c3d
 
e9ca807
173e2b4
 
 
e9ca807
 
 
da25c3d
6ec40e7
bc54095
e9ca807
cc5d85e
da25c3d
795747f
967bcc6
ba55b48
e9ca807
bc54095
89f9c17
da25c3d
 
 
 
 
c52ae2c
 
 
 
 
 
 
 
 
 
 
 
 
 
7de629a
1490c4a
2219ee8
 
 
 
 
 
 
1490c4a
2219ee8
e642327
 
 
 
 
 
 
 
 
 
2219ee8
1490c4a
 
 
 
 
2219ee8
1490c4a
2219ee8
 
1490c4a
e642327
 
2219ee8
e642327
2219ee8
 
 
 
1490c4a
2219ee8
2933bfe
1490c4a
 
2933bfe
 
2219ee8
2933bfe
173e2b4
93b1017
 
1be3e2c
a6d25fc
e9ca807
 
 
 
 
 
 
c19569d
93b1017
 
 
 
 
 
 
 
2219ee8
93b1017
6ec40e7
be55781
f6353b4
93b1017
6ec40e7
ab54bfa
f6353b4
2933bfe
6ec40e7
ab54bfa
90830b0
1be3e2c
bc54095
2ddfc45
ab54bfa
b8cec79
2ddfc45
b8cec79
c9f6aff
b8cec79
 
5c7a03d
6ec40e7
 
 
9d376da
6ec40e7
 
 
 
 
2ddfc45
6ec40e7
 
c1c515b
ebfc6b3
bc54095
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
####################################################################################################
### PART 1: Imports & Basic Utilities
####################################################################################################
import sys
from pathlib import Path
import uuid
import tempfile
import subprocess
import torch
import torch.nn.functional as F
import torchaudio
import os
from typing import Any
import time
from contextlib import contextmanager
from gradio.helpers import create_examples 

@contextmanager
def timer(name: str):
    start = time.time()
    print(f"{name}...")
    yield
    print(f"  -> {name} completed in {time.time() - start:.2f} sec")

def _coerce_audio_path(audio_path: Any) -> str:
    # Common Gradio case: tuple where first item is the filepath
    if isinstance(audio_path, tuple) and len(audio_path) > 0:
        audio_path = audio_path[0]

    # Some gradio versions pass a dict-like object
    if isinstance(audio_path, dict):
        # common keys: "name", "path"
        audio_path = audio_path.get("name") or audio_path.get("path")

    # pathlib.Path etc.
    if not isinstance(audio_path, (str, bytes, os.PathLike)):
        raise TypeError(f"audio_path must be a path-like, got {type(audio_path)}: {audio_path}")

    return os.fspath(audio_path)


####################################################################################################
### PART 2: Audio Extraction & Matching Utilities
####################################################################################################
def extract_audio_wav_ffmpeg(video_path: str, target_sr: int = 48000) -> str | None:
    """
    Extract audio from a video into a temp WAV (mono, target_sr).
    Returns path, or None if the video has no audio stream.
    """
    out_path = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name

    # Check if there's an audio stream
    probe_cmd = [
        "ffprobe", "-v", "error",
        "-select_streams", "a:0",
        "-show_entries", "stream=codec_type",
        "-of", "default=nw=1:nk=1",
        video_path,
    ]
    try:
        out = subprocess.check_output(probe_cmd).decode("utf-8").strip()
        if not out:
            return None
    except subprocess.CalledProcessError:
        return None

    # Extract + resample + mono
    cmd = [
        "ffmpeg", "-y", "-v", "error",
        "-i", video_path,
        "-vn",
        "-ac", "1",
        "-ar", str(int(target_sr)),
        "-c:a", "pcm_s16le",
        out_path
    ]
    subprocess.check_call(cmd)
    return out_path

def match_audio_to_duration(
    audio_path: str,
    target_seconds: float,
    target_sr: int = 48000,
    to_mono: bool = True,
    pad_mode: str = "silence",  # "silence" | "repeat"
    device: str = "cuda",
):
    """
    Load audio, resample, (optionally) mono, then trim/pad to exactly target_seconds.
    Returns: (waveform[T] or [1,T], sr)
    """
    audio_path = _coerce_audio_path(audio_path)

    wav, sr = torchaudio.load(audio_path)  # [C, T] float32 CPU

    # Resample to target_sr (recommended so duration math is stable)
    if sr != target_sr:
        wav = torchaudio.functional.resample(wav, sr, target_sr)
        sr = target_sr

    # Mono (common expectation; if your model supports stereo, set to_mono=False)
    if to_mono and wav.shape[0] > 1:
        wav = wav.mean(dim=0, keepdim=True)  # [1, T]

    # Exact target length in samples
    target_len = int(round(target_seconds * sr))
    cur_len = wav.shape[-1]

    if cur_len > target_len:
        wav = wav[..., :target_len]
    elif cur_len < target_len:
        pad_len = target_len - cur_len
        if pad_mode == "repeat" and cur_len > 0:
            # Repeat then cut to exact length
            reps = (target_len + cur_len - 1) // cur_len
            wav = wav.repeat(1, reps)[..., :target_len]
        else:
            # Silence pad
            wav = F.pad(wav, (0, pad_len))

    # move to device
    wav = wav.to(device, non_blocking=True)
    return wav, sr

def sh(cmd): subprocess.check_call(cmd, shell=True)


####################################################################################################
### PART 3: LTX Pipeline Imports & Constants
####################################################################################################
# Add packages to Python path
current_dir = Path(__file__).parent
sys.path.insert(0, str(current_dir / "packages" / "ltx-pipelines" / "src"))
sys.path.insert(0, str(current_dir / "packages" / "ltx-core" / "src"))

import spaces
import flash_attn_interface
import time
import gradio as gr
import numpy as np
import random
import torch
from typing import Optional
from pathlib import Path
import torchaudio
from huggingface_hub import hf_hub_download, snapshot_download
from ltx_pipelines.distilled import DistilledPipeline
from ltx_core.model.video_vae import TilingConfig
from ltx_core.model.audio_vae.ops import AudioProcessor
from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
from ltx_pipelines.utils.constants import (
    DEFAULT_SEED,
    DEFAULT_1_STAGE_HEIGHT,
    DEFAULT_1_STAGE_WIDTH ,
    DEFAULT_NUM_FRAMES,
    DEFAULT_FRAME_RATE,
    DEFAULT_LORA_STRENGTH,
)
from ltx_core.loader.single_gpu_model_builder import enable_only_lora
from ltx_core.model.audio_vae import decode_audio
from ltx_core.model.audio_vae import encode_audio
from PIL import Image

MAX_SEED = np.iinfo(np.int32).max
# Import from public LTX-2 package
# Install with: pip install git+https://github.com/Lightricks/LTX-2.git
from ltx_pipelines.utils import ModelLedger
from ltx_pipelines.utils.helpers import generate_enhanced_prompt
import imageio
import cv2

# HuggingFace Hub defaults
DEFAULT_REPO_ID = "Lightricks/LTX-2"
DEFAULT_GEMMA_REPO_ID = "unsloth/gemma-3-12b-it-qat-bnb-4bit"
DEFAULT_CHECKPOINT_FILENAME = "ltx-2-19b-dev.safetensors"


####################################################################################################
### PART 4: Download Helpers
####################################################################################################
def get_hub_or_local_checkpoint(repo_id: str, filename: str):
    """Download from HuggingFace Hub."""
    print(f"Downloading {filename} from {repo_id}...")
    ckpt_path = hf_hub_download(repo_id=repo_id, filename=filename)
    print(f"Downloaded to {ckpt_path}")
    return ckpt_path

def download_gemma_model(repo_id: str):
    """Download the full Gemma model directory."""
    print(f"Downloading Gemma model from {repo_id}...")
    local_dir = snapshot_download(repo_id=repo_id)
    print(f"Gemma model downloaded to {local_dir}")
    return local_dir


####################################################################################################
### PART 5: Text Encoder Initialization
####################################################################################################
# Initialize model ledger and text encoder at startup (load once, keep in memory)
print("=" * 80)
print("Loading Gemma Text Encoder...")
print("=" * 80)

checkpoint_path = get_hub_or_local_checkpoint(DEFAULT_REPO_ID, DEFAULT_CHECKPOINT_FILENAME)
gemma_local_path = download_gemma_model(DEFAULT_GEMMA_REPO_ID)
device = "cuda"

print(f"Initializing text encoder with:")
print(f"  checkpoint_path={checkpoint_path}")
print(f"  gemma_root={gemma_local_path}")
print(f"  device={device}")

model_ledger = ModelLedger(
    dtype=torch.bfloat16,
    device=device,
    checkpoint_path=checkpoint_path,
    gemma_root_path=DEFAULT_GEMMA_REPO_ID,
    local_files_only=False
)

# Load text encoder once and keep it in memory
text_encoder = model_ledger.text_encoder()

print("=" * 80)
print("Text encoder loaded and ready!")
print("=" * 80)

def on_lora_change(selected: str):
    # Only Detailer might need handling, but we simplified motion control out
    needs_video = selected in {"Detailer"} 
    return (
        selected,
        gr.update(visible=not needs_video, value=None if needs_video else None),
        gr.update(visible=needs_video, value=None if not needs_video else None),
    )


####################################################################################################
### PART 6: Video/Frame Utilities
####################################################################################################
def load_video_frames(video_path: str):
    """Return list of frames as numpy arrays (H,W,3) uint8."""
    frames = []
    with imageio.get_reader(video_path) as reader:
        for frame in reader:
            frames.append(frame)
    return frames

def write_video_mp4(frames_float_01, fps: float, out_path: str):
    """Write frames in float [0..1] to mp4 as uint8."""
    frames_uint8 = [(f * 255).astype(np.uint8) for f in frames_float_01]

    # PyAV backend doesn't support `quality=...`
    with imageio.get_writer(out_path, fps=fps, macro_block_size=1) as writer:
        for fr in frames_uint8:
            writer.append_data(fr)
    return out_path

import json

def probe_video_duration_seconds(video_path: str) -> float:
    """Return duration in seconds using ffprobe."""
    cmd = [
        "ffprobe", "-v", "error",
        "-select_streams", "v:0",
        "-show_entries", "format=duration",
        "-of", "json",
        video_path,
    ]
    out = subprocess.check_output(cmd).decode("utf-8")
    data = json.loads(out)
    dur = float(data["format"]["duration"])
    return dur


####################################################################################################
### PART 7: FFmpeg Utils & Frame Prep
####################################################################################################
def trim_video_to_seconds_ffmpeg(video_path: str, target_seconds: float, fps: float = None) -> str:
    """
    Trim video to [0, target_seconds]. Re-encode for accuracy & compatibility.
    If fps is provided, also normalize fps.
    Returns new temp mp4 path.
    """
    target_seconds = max(0.01, float(target_seconds))

    out_path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name

    vf = []
    if fps is not None:
        vf.append(f"fps={float(fps)}")
    vf_str = ",".join(vf) if vf else None

    cmd = ["ffmpeg", "-y", "-v", "error"]

    # Accurate trim: use -t and re-encode.
    cmd += ["-i", video_path, "-t", f"{target_seconds:.6f}"]

    if vf_str:
        cmd += ["-vf", vf_str]

    # Safe default encode
    cmd += [
        "-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "veryfast", "-crf", "18",
        "-an",  # conditioning video doesn't need audio
        out_path
    ]

    subprocess.check_call(cmd)
    return out_path

def extract_first_frame_png(video_path: str) -> str:
    """Extract first frame as png; returns png path."""
    out_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
    cmd = [
        "ffmpeg", "-y", "-v", "error",
        "-i", video_path,
        "-frames:v", "1",
        out_path
    ]
    subprocess.check_call(cmd)
    return out_path

def _coerce_video_path(video_path: Any) -> str:
    if isinstance(video_path, tuple) and len(video_path) > 0:
        video_path = video_path[0]
    if isinstance(video_path, dict):
        video_path = video_path.get("name") or video_path.get("path")
    if not isinstance(video_path, (str, bytes, os.PathLike)):
        raise TypeError(f"video_path must be a path-like, got {type(video_path)}: {video_path}")
    return os.fspath(video_path)


####################################################################################################
### PART 8: Prompt Encoding Logic
####################################################################################################
def encode_text_simple(text_encoder, prompt: str):
    """Simple text encoding without using pipeline_utils."""
    v_context, a_context, _ = text_encoder(prompt)
    return v_context, a_context

@spaces.GPU()
def encode_prompt(
    prompt: str,
    enhance_prompt: bool = True,
    input_image=None,   # this is now filepath (string) or None
    seed: int = 42,
    negative_prompt: str = ""
):
    start_time = time.time()
    try:
        final_prompt = prompt
        if enhance_prompt:
            final_prompt = generate_enhanced_prompt(
                text_encoder=text_encoder,
                prompt=prompt,
                image_path=input_image if input_image is not None else None,
                seed=seed,
            )

        with torch.inference_mode():
            video_context, audio_context = encode_text_simple(text_encoder, final_prompt)

        video_context_negative = None
        audio_context_negative = None
        if negative_prompt:
            video_context_negative, audio_context_negative = encode_text_simple(text_encoder, negative_prompt)

        # IMPORTANT: return tensors directly (no torch.save)
        embedding_data = {
            "video_context": video_context.detach().cpu(),
            "audio_context": audio_context.detach().cpu(),
            "prompt": final_prompt,
            "original_prompt": prompt,
        }
        if video_context_negative is not None:
            embedding_data["video_context_negative"] = video_context_negative
            embedding_data["audio_context_negative"] = audio_context_negative
            embedding_data["negative_prompt"] = negative_prompt

        elapsed_time = time.time() - start_time
        if torch.cuda.is_available():
            allocated = torch.cuda.memory_allocated() / 1024**3
            peak = torch.cuda.max_memory_allocated() / 1024**3
            status = f"✓ Encoded in {elapsed_time:.2f}s | VRAM: {allocated:.2f}GB allocated, {peak:.2f}GB peak"
        else:
            status = f"✓ Encoded in {elapsed_time:.2f}s (CPU mode)"

        return embedding_data, final_prompt, status

    except Exception as e:
        import traceback
        error_msg = f"Error: {str(e)}\n{traceback.format_exc()}"
        print(error_msg)
        return None, prompt, error_msg

# Default prompt from docstring example
DEFAULT_PROMPT = "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a breath-taking, movie-like shot."


####################################################################################################
### PART 9: Pipeline Constants & Checkpoint Paths
####################################################################################################
# HuggingFace Hub defaults
DEFAULT_REPO_ID = "Lightricks/LTX-2"
DEFAULT_CHECKPOINT_FILENAME = "ltx-2-19b-dev.safetensors"
DEFAULT_DISTILLED_LORA_FILENAME = "ltx-2-19b-distilled-lora-384.safetensors"
DEFAULT_SPATIAL_UPSAMPLER_FILENAME = "ltx-2-spatial-upscaler-x2-1.0.safetensors"

def get_hub_or_local_checkpoint_pipeline(repo_id: Optional[str] = None, filename: Optional[str] = None):
    """Download from HuggingFace Hub or use local checkpoint."""
    if repo_id is None and filename is None:
        raise ValueError("Please supply at least one of `repo_id` or `filename`")

    if repo_id is not None:
        if filename is None:
            raise ValueError("If repo_id is specified, filename must also be specified.")
        print(f"Downloading {filename} from {repo_id}...")
        ckpt_path = hf_hub_download(repo_id=repo_id, filename=filename)
        print(f"Downloaded to {ckpt_path}")
    else:
        ckpt_path = filename

    return ckpt_path


# Initialize pipeline at startup
print("=" * 80)
print("Loading LTX-2 Distilled pipeline...")
print("=" * 80)

checkpoint_path = get_hub_or_local_checkpoint_pipeline(DEFAULT_REPO_ID, DEFAULT_CHECKPOINT_FILENAME)
spatial_upsampler_path = get_hub_or_local_checkpoint_pipeline(DEFAULT_REPO_ID, DEFAULT_SPATIAL_UPSAMPLER_FILENAME)

print(f"Initializing pipeline with:")
print(f"  checkpoint_path={checkpoint_path}")
print(f"  spatial_upsampler_path={spatial_upsampler_path}")

distilled_lora_path = get_hub_or_local_checkpoint_pipeline(
    DEFAULT_REPO_ID,
    DEFAULT_DISTILLED_LORA_FILENAME,
)

static_lora_path = get_hub_or_local_checkpoint_pipeline(
    "Lightricks/LTX-2-19b-LoRA-Camera-Control-Static",
    "ltx-2-19b-lora-camera-control-static.safetensors",
)
dolly_in_lora_path = get_hub_or_local_checkpoint_pipeline(
    "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-In",
    "ltx-2-19b-lora-camera-control-dolly-in.safetensors",
)
dolly_out_lora_path = get_hub_or_local_checkpoint_pipeline(
    "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Out",
    "ltx-2-19b-lora-camera-control-dolly-out.safetensors",
)
dolly_left_lora_path = get_hub_or_local_checkpoint_pipeline(
    "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Left",
    "ltx-2-19b-lora-camera-control-dolly-left.safetensors",
)
dolly_right_lora_path = get_hub_or_local_checkpoint_pipeline(
    "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Right",
    "ltx-2-19b-lora-camera-control-dolly-right.safetensors",
)
jib_down_lora_path = get_hub_or_local_checkpoint_pipeline(
    "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Down",
    "ltx-2-19b-lora-camera-control-jib-down.safetensors",
)
jib_up_lora_path = get_hub_or_local_checkpoint_pipeline(
    "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Up",
    "ltx-2-19b-lora-camera-control-jib-up.safetensors",
)

detailer_lora_path = get_hub_or_local_checkpoint_pipeline(
    "Lightricks/LTX-2-19b-IC-LoRA-Detailer",
    "ltx-2-19b-ic-lora-detailer.safetensors",
)


####################################################################################################
### PART 10: LoRA Setup & Configuration
####################################################################################################
# Load distilled LoRA as a regular LoRA
loras = [
    # --- fused / base behavior ---
    LoraPathStrengthAndSDOps(
        path=distilled_lora_path,
        strength=0.6,
        sd_ops=LTXV_LORA_COMFY_RENAMING_MAP,
    ),
    LoraPathStrengthAndSDOps(static_lora_path,      DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
    LoraPathStrengthAndSDOps(detailer_lora_path,    DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
    LoraPathStrengthAndSDOps(dolly_in_lora_path,    DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
    LoraPathStrengthAndSDOps(dolly_out_lora_path,   DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
    LoraPathStrengthAndSDOps(dolly_left_lora_path,  DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
    LoraPathStrengthAndSDOps(dolly_right_lora_path, DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
    LoraPathStrengthAndSDOps(jib_down_lora_path,    DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
    LoraPathStrengthAndSDOps(jib_up_lora_path,      DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
]

# Runtime-toggle LoRAs (exclude fused distilled at index 0)
VISIBLE_RUNTIME_LORA_CHOICES = [
    ("No LoRA", -1),
    ("Static", 0),
    ("Detailer", 1),
    ("Zoom In", 2),
    ("Zoom Out", 3),
    ("Slide Left", 4),
    ("Slide Right", 5),
    ("Slide Down", 6),
    ("Slide Up", 7),
]

RUNTIME_LORA_CHOICES = [
    ("No LoRA", -1),
    ("Static", 0),
    ("Detailer", 1),
    ("Zoom In", 2),
    ("Zoom Out", 3),
    ("Slide Left", 4),
    ("Slide Right", 5),
    ("Slide Down", 6),
    ("Slide Up", 7),
]


####################################################################################################
### PART 11: Pipeline Initialization
####################################################################################################
# Initialize pipeline WITHOUT text encoder (gemma_root=None)
# Text encoding will be done by external space
pipeline = DistilledPipeline(
    device=torch.device("cuda"),
    checkpoint_path=checkpoint_path,
    spatial_upsampler_path=spatial_upsampler_path,
    gemma_root=None,  # No text encoder in this space
    loras=loras,
    fp8transformer=False,
    local_files_only=False,
)

pipeline._video_encoder = pipeline.model_ledger.video_encoder()
pipeline._transformer = pipeline.model_ledger.transformer()

print("=" * 80)
print("Pipeline fully loaded and ready!")
print("=" * 80)


####################################################################################################
### PART 12: Custom Component - RadioAnimated
####################################################################################################
class RadioAnimated(gr.HTML):
    """
    Animated segmented radio (like iOS pill selector).
    Outputs: selected option string, e.g. "768x512"
    """
    def __init__(self, choices, value=None, **kwargs):
        if not choices or len(choices) < 2:
            raise ValueError("RadioAnimated requires at least 2 choices.")
        if value is None:
            value = choices[0]

        uid = uuid.uuid4().hex[:8]  # unique per instance
        group_name = f"ra-{uid}"

        inputs_html = "\n".join(
            f"""
            <input class="ra-input" type="radio" name="{group_name}" id="{group_name}-{i}" value="{c}">
            <label class="ra-label" for="{group_name}-{i}">{c}</label>
            """
            for i, c in enumerate(choices)
        )

        # NOTE: use classes instead of duplicate IDs
        html_template = f"""
        <div class="ra-wrap" data-ra="{uid}">
          <div class="ra-inner">
            <div class="ra-highlight"></div>
            {inputs_html}
          </div>
        </div>
        """

        js_on_load = r"""
        (() => {
            const wrap = element.querySelector('.ra-wrap');
            const inner = element.querySelector('.ra-inner');
            const highlight = element.querySelector('.ra-highlight');
            const inputs = Array.from(element.querySelectorAll('.ra-input'));
            const labels = Array.from(element.querySelectorAll('.ra-label'));

            if (!inputs.length || !labels.length) return;

            const choices = inputs.map(i => i.value);
            const PAD = 6; // must match .ra-inner padding and .ra-highlight top/left

            let currentIdx = 0;

            function setHighlightByIndex(idx) {
                currentIdx = idx;

                const lbl = labels[idx];
                if (!lbl) return;

                const innerRect = inner.getBoundingClientRect();
                const lblRect = lbl.getBoundingClientRect();

                // width matches the label exactly
                highlight.style.width = `${lblRect.width}px`;

                // highlight has left: 6px, so subtract PAD to align
                const x = (lblRect.left - innerRect.left - PAD);
                highlight.style.transform = `translateX(${x}px)`;
            }

            function setCheckedByValue(val, shouldTrigger=false) {
                const idx = Math.max(0, choices.indexOf(val));
                inputs.forEach((inp, i) => { inp.checked = (i === idx); });

                // Wait a frame in case fonts/layout settle (prevents rare drift)
                requestAnimationFrame(() => setHighlightByIndex(idx));

                props.value = choices[idx];
                if (shouldTrigger) trigger('change', props.value);
            }

            // Init
            setCheckedByValue(props.value ?? choices[0], false);

            // Input handlers
            inputs.forEach((inp) => {
                inp.addEventListener('change', () => setCheckedByValue(inp.value, true));
            });

            // Recalc on resize (important in Gradio layouts)
            window.addEventListener('resize', () => setHighlightByIndex(currentIdx));

            // sync from Python (Examples / backend updates)
            let last = props.value;
            const syncFromProps = () => {
              if (props.value !== last) {
                last = props.value;
                setCheckedByValue(last, false);
              }
              requestAnimationFrame(syncFromProps);
            };
            requestAnimationFrame(syncFromProps);

        })();

        """

        super().__init__(
            value=value,
            html_template=html_template,
            js_on_load=js_on_load,
            **kwargs
        )


####################################################################################################
### PART 13: Custom Component - PromptBox
####################################################################################################
class PromptBox(gr.HTML):
    """
    Prompt textarea with an internal footer slot (.ds-footer) where we can inject dropdowns.
    """
    def __init__(self, value="", placeholder="دستور ساخت ویدیو را اینجا بنویسید...", **kwargs):
        uid = uuid.uuid4().hex[:8]

        html_template = f"""
        <div class="ds-card" data-ds="{uid}">
          <div class="ds-top">
            <textarea class="ds-textarea" rows="3" placeholder="{placeholder}"></textarea>

            <!-- footer slot -->
            <div class="ds-footer" aria-label="prompt-footer"></div>
          </div>
        </div>
        """

        js_on_load = r"""
        (() => {
          const textarea = element.querySelector(".ds-textarea");
          if (!textarea) return;
        
          const autosize = () => {
            textarea.style.height = "0px";
            textarea.style.height = Math.min(textarea.scrollHeight, 240) + "px";
          };
        
          const setValue = (v, triggerChange=false) => {
            const val = (v ?? "");
            if (textarea.value !== val) textarea.value = val;
            autosize();
            props.value = textarea.value;
            if (triggerChange) trigger("change", props.value);
          };
        
          setValue(props.value, false);
        
          textarea.addEventListener("input", () => {
            autosize();
            props.value = textarea.value;
            trigger("change", props.value);
          });
        
          // ✅ Focus-on-load (robust)
          const shouldAutoFocus = () => {
            // don’t steal focus if user already clicked/typed somewhere
            const ae = document.activeElement;
            if (ae && ae !== document.body && ae !== document.documentElement) return false;
            // don’t auto-focus on small screens (optional; avoids mobile keyboard pop)
            if (window.matchMedia && window.matchMedia("(max-width: 768px)").matches) return false;
            return true;
          };
        
          const focusWithRetry = (tries = 30) => {
            if (!shouldAutoFocus()) return;
            // only focus if still not focused
            if (document.activeElement !== textarea) textarea.focus({ preventScroll: true });
            if (document.activeElement === textarea) return;
            if (tries > 0) requestAnimationFrame(() => focusWithRetry(tries - 1));
          };
        
          // wait a tick so Gradio/layout settles
          requestAnimationFrame(() => focusWithRetry());
        
          // keep your sync loop
          let last = props.value;
          const syncFromProps = () => {
            if (props.value !== last) {
              last = props.value;
              setValue(last, false);
            }
            requestAnimationFrame(syncFromProps);
          };
          requestAnimationFrame(syncFromProps);
        })();

        """

        super().__init__(value=value, html_template=html_template, js_on_load=js_on_load, **kwargs)


####################################################################################################
### PART 14: Custom Component - CameraDropdown
####################################################################################################
class CameraDropdown(gr.HTML):
    """
    Custom dropdown (More-style) with optional icons per item.
    Outputs: selected option string, e.g. "16:9"
    """
    def __init__(self, choices, value="None", title="Dropdown", **kwargs):
        if not choices:
            raise ValueError("CameraDropdown requires choices.")

        # Normalize choices -> list of dicts: {label, value, icon(optional)}
        norm = []
        for c in choices:
            if isinstance(c, dict):
                label = str(c.get("label", c.get("value", "")))
                val = str(c.get("value", label))
                icon = c.get("icon", None)  # emoji or svg/html
                norm.append({"label": label, "value": val, "icon": icon})
            else:
                s = str(c)
                norm.append({"label": s, "value": s, "icon": None})

        uid = uuid.uuid4().hex[:8]

        def render_item(item):
            icon_html = ""
            if item["icon"]:
                icon_html = f'<span class="cd-icn">{item["icon"]}</span>'
            return (
                f'<button type="button" class="cd-item" '
                f'data-value="{item["value"]}">'
                f'{icon_html}<span class="cd-label">{item["label"]}</span>'
                f'</button>'
            )

        items_html = "\n".join(render_item(item) for item in norm)

        html_template = f"""
        <div class="cd-wrap" data-cd="{uid}">
            <button type="button" class="cd-trigger" aria-haspopup="menu" aria-expanded="false">
              <span class="cd-trigger-icon"></span>
              <span class="cd-trigger-text"></span>
              <span class="cd-caret">▾</span>
            </button>

          <div class="cd-menu" role="menu" aria-hidden="true">
            <div class="cd-title">{title}</div>
            <div class="cd-items">
              {items_html}
            </div>
          </div>
        </div>
        """

        # Pass a mapping value->label so the trigger can show label text
        # (and still output value to Python)
        value_to_label = {it["value"]: it["label"] for it in norm}
        value_to_icon = {it["value"]: (it["icon"] or "") for it in norm}

        js_on_load = r"""
        (() => {
          const wrap = element.querySelector(".cd-wrap");
          const trigger = element.querySelector(".cd-trigger");
          const triggerIcon = element.querySelector(".cd-trigger-icon");
          const triggerText = element.querySelector(".cd-trigger-text");
          const menu = element.querySelector(".cd-menu");
          const items = Array.from(element.querySelectorAll(".cd-item"));
          if (!wrap || !trigger || !menu || !items.length) return;

          const valueToLabel = __VALUE_TO_LABEL__;
          const valueToIcon  = __VALUE_TO_ICON__;
        
          const safeLabel = (v) => (valueToLabel && valueToLabel[v]) ? valueToLabel[v] : (v ?? "None");
          const safeIcon  = (v) => (valueToIcon  && valueToIcon[v])  ? valueToIcon[v]  : "";


          function closeMenu() {
            menu.classList.remove("open");
            trigger.setAttribute("aria-expanded", "false");
            menu.setAttribute("aria-hidden", "true");
          }

          function openMenu() {
            menu.classList.add("open");
            trigger.setAttribute("aria-expanded", "true");
            menu.setAttribute("aria-hidden", "false");
          }

          function setValue(val, shouldTrigger = false) {
            const v = (val ?? "None");
            props.value = v;

            // Trigger shows LABEL only (icons stay in menu)
            triggerText.textContent = safeLabel(v);
            if (triggerIcon) {
              triggerIcon.innerHTML = safeIcon(v);
              triggerIcon.style.display = safeIcon(v) ? "inline-flex" : "none";
            }


            items.forEach(btn => {
              btn.dataset.selected = (btn.dataset.value === v) ? "true" : "false";
            });

            if (shouldTrigger) trigger("change", props.value);
          }

          trigger.addEventListener("pointerdown", (e) => {
            e.preventDefault();
            e.stopPropagation();
            if (menu.classList.contains("open")) closeMenu();
            else openMenu();
          });

          document.addEventListener("pointerdown", (e) => {
            if (!wrap.contains(e.target)) closeMenu();
          }, true);

          document.addEventListener("keydown", (e) => {
            if (e.key === "Escape") closeMenu();
          });

          wrap.addEventListener("focusout", (e) => {
            if (!wrap.contains(e.relatedTarget)) closeMenu();
          });

          items.forEach((btn) => {
            btn.addEventListener("pointerdown", (e) => {
              e.preventDefault();
              e.stopPropagation();
              closeMenu();
              setValue(btn.dataset.value, true);
            });
          });

          // init
          setValue((props.value ?? "None"), false);

          // sync from Python
          let last = props.value;
          const syncFromProps = () => {
            if (props.value !== last) {
              last = props.value;
              setValue(last, false);
            }
            requestAnimationFrame(syncFromProps);
          };
          requestAnimationFrame(syncFromProps);
        })();
        """

        # Inject mapping into JS safely
        import json
        js_on_load = js_on_load.replace("__VALUE_TO_LABEL__", json.dumps(value_to_label))
        js_on_load = js_on_load.replace("__VALUE_TO_ICON__", json.dumps(value_to_icon))

        super().__init__(
            value=value,
            html_template=html_template,
            js_on_load=js_on_load,
            **kwargs
        )


####################################################################################################
### PART 15: Custom Component - PresetGallery
####################################################################################################
class PresetGallery(gr.HTML):
    """
    Clickable image presets -> outputs selected index (int as string, then cast in python)
    """
    def __init__(self, items, title="Click an Example", **kwargs):
        """
        items: list[dict] with keys:
          - thumb: str (path to image file, e.g. "supergirl.png")
          - label: str (optional)
        """
        uid = uuid.uuid4().hex[:8]

        cards_html = []
        for i, it in enumerate(items):
            thumb = it["thumb"]
            label = it.get("label", "")
            cards_html.append(f"""
              <button type="button" class="pg-card" data-idx="{i}" aria-label="{label}">
                <img class="pg-img" src="gradio_api/file={thumb}" alt="{label}">
              </button>
            """)

        html_template = f"""
        <style>
        .pg-modal-overlay-custom {{
            position: fixed; top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.6); display: none;
            align-items: center; justify-content: center; z-index: 999999;
            backdrop-filter: blur(2px);
        }}
        .pg-modal-custom {{
            background: #2b2b2b; padding: 24px; border-radius: 16px;
            border: 1px solid rgba(255,255,255,0.12); color: rgba(255,255,255,0.9);
            text-align: center; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; 
            min-width: 320px; box-shadow: 0 10px 30px rgba(0,0,0,0.5);
            direction: rtl;
        }}
        .pg-modal-custom p {{
            font-size: 16px; margin: 0 0 20px 0; font-weight: 600;
        }}
        .pg-modal-btns-custom {{
            display: flex; gap: 12px; justify-content: center;
        }}
        .pg-modal-btns-custom button {{
            padding: 10px 24px; border: none; border-radius: 10px; cursor: pointer; 
            font-weight: 700; font-size: 14px; font-family: inherit; transition: opacity 0.2s;
        }}
        .pg-modal-btns-custom button:hover {{
            opacity: 0.8;
        }}
        .pg-btn-confirm-custom {{ 
            background: #4b2ab5; color: white; 
        }}
        .pg-btn-cancel-custom {{ 
            background: transparent; color: rgba(255,255,255,0.7); 
            border: 1px solid rgba(255,255,255,0.2) !important;
        }}
        </style>

        <div class="pg-wrap" data-pg="{uid}">
          <div class="pg-title">
            <div class="pg-h1">{title}</div>
          </div>
          <div class="pg-grid">
            {''.join(cards_html)}
          </div>
          
          <!-- پیام تاییدی (Modal) اضافه شده -->
          <div class="pg-modal-overlay-custom">
            <div class="pg-modal-custom">
              <p>آیا می‌خواهید نمونه به بالا اضافه بشه؟</p>
              <div class="pg-modal-btns-custom">
                <button class="pg-btn-confirm-custom">تایید</button>
                <button class="pg-btn-cancel-custom">انصراف</button>
              </div>
            </div>
          </div>
        </div>
        """

        # --- JAVASCRIPT LOGIC UPDATED ---
        # Logic updated to show confirmation prompt before triggering action
        js_on_load = r"""
        (() => {
          const wrap = element.querySelector(".pg-wrap");
          const cards = Array.from(element.querySelectorAll(".pg-card"));
          const modalOverlay = element.querySelector(".pg-modal-overlay-custom");
          const btnConfirm = element.querySelector(".pg-btn-confirm-custom");
          const btnCancel = element.querySelector(".pg-btn-cancel-custom");
          
          if (!wrap || !cards.length || !modalOverlay) return;
        
          function setDim(activeIdx) {
            cards.forEach((c, i) => {
              // Dim cards that are not the active one.
              c.dataset.dim = (activeIdx !== null && i !== activeIdx) ? "true" : "false";
              // Set the active state for the clicked card.
              c.dataset.active = (i === activeIdx) ? "true" : "false";
            });
          }
        
          let lastSent = null;
          let lock = false;
          let pendingIdxNumber = null;
          
          // Action for "تایید"
          btnConfirm.addEventListener("pointerdown", (e) => {
              e.preventDefault();
              e.stopPropagation();
              modalOverlay.style.display = "none"; // Hide Modal
              
              if (pendingIdxNumber !== null) {
                  const idxString = String(pendingIdxNumber);
                  
                  // 1. Update visual state immediately on confirmed click.
                  setDim(pendingIdxNumber);
                  
                  // 2. Only update Python backend if the value has actually changed.
                  if (idxString !== lastSent) {
                      lastSent = idxString;
                      // ✅ Set props.value to send data to Python.
                      props.value = idxString;
                  }
                  
                  pendingIdxNumber = null;
              }
          });
          
          // Action for "انصراف"
          btnCancel.addEventListener("pointerdown", (e) => {
              e.preventDefault();
              e.stopPropagation();
              modalOverlay.style.display = "none"; // Hide Modal
              pendingIdxNumber = null;
          });

          // Close modal if clicked directly on background overlay
          modalOverlay.addEventListener("pointerdown", (e) => {
              if (e.target === modalOverlay) {
                  e.preventDefault();
                  e.stopPropagation();
                  modalOverlay.style.display = "none";
                  pendingIdxNumber = null;
              }
          });
        
          cards.forEach((card) => {
            card.addEventListener("pointerdown", (e) => {
              e.preventDefault();
              e.stopPropagation();
        
              if (lock) return;
              lock = true;
              setTimeout(() => (lock = false), 250);
        
              // Save clicked index and display modal
              pendingIdxNumber = Number(card.dataset.idx);
              modalOverlay.style.display = "flex";
              
            }, { passive: false });
          });
        
          // Initially, no card is selected.
          setDim(null);
        })();
        """

        super().__init__(value="", html_template=html_template, js_on_load=js_on_load, **kwargs)


####################################################################################################
### PART 16: Custom Component - AudioDropUpload (FIXED)
####################################################################################################
class AudioDropUpload(gr.HTML):
    """
    Custom audio drop/click UI that proxies file into a hidden gr.Audio component.
    IMPORTANT:
    - Pass target_audio_elem_id = elem_id of your hidden gr.Audio.
    - The hidden gr.Audio must be type="filepath" (or whatever you need).
    """
    def __init__(self, target_audio_elem_id: str, value=None, **kwargs):
        uid = uuid.uuid4().hex[:8]

        html_template = f"""
        <div class="aud-wrap" data-aud="{uid}">
          <div class="aud-drop" role="button" tabindex="0" aria-label="بارگذاری صدا">
            <div><strong>(اختیاری) فایل صوتی را اینجا بکشید و رها کنید</strong></div>
            <div class="aud-hint">…یا برای انتخاب کلیک کنید</div>
          </div>
          <div class="aud-row" aria-live="polite">
            <audio class="aud-player" controls></audio>
            <button class="aud-remove" type="button" aria-label="حذف صدا">
              <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
                <path d="M18 6L6 18M6 6l12 12"
                      stroke="currentColor"
                      stroke-width="2.25"
                      stroke-linecap="round"/>
              </svg>
            </button>
          </div>
          <div class="aud-filelabel"></div>
        </div>
        """

        # JS:
        # - finds the hidden gr.Audio upload <input type=file> inside the component with elem_id=target_audio_elem_id
        # - sets the selected file onto it (DataTransfer) and dispatches change
        js_on_load = """
        (() => {
          // Helper: access Gradio shadow DOM safely
          function grRoot() {
            const ga = document.querySelector("gradio-app");
            return (ga && ga.shadowRoot) ? ga.shadowRoot : document;
          }
          const root = grRoot();
          const wrap = element.querySelector(".aud-wrap");
          const drop = element.querySelector(".aud-drop");
          const row  = element.querySelector(".aud-row");
          const player = element.querySelector(".aud-player");
          const removeBtn = element.querySelector(".aud-remove");
          const label = element.querySelector(".aud-filelabel");
          const TARGET_ID = "__TARGET_ID__";
          let currentUrl = null;
          function findHiddenAudioFileInput() {
            const host = root.querySelector("#" + CSS.escape(TARGET_ID));
            if (!host) return null;
            // Gradio's Audio component contains an <input type=file> for upload.
            // This selector works in most Gradio 3/4 themes.
            const inp = host.querySelector('input[type="file"]');
            return inp;
          }
          function showDrop() {
            drop.style.display = "";
            row.style.display = "none";
            label.style.display = "none";
            label.textContent = "";
          }
          function showPlayer(filename) {
            drop.style.display = "none";
            row.style.display = "flex";
            if (filename) {
              label.textContent = "فایل بارگذاری شده: " + filename;
              label.style.display = "block";
            }
          }
          function clearPreview() {
            player.pause();
            player.removeAttribute("src");
            player.load();
            if (currentUrl) {
              URL.revokeObjectURL(currentUrl);
              currentUrl = null;
            }
          }
          function clearHiddenGradioAudio() {
            const fileInput = findHiddenAudioFileInput();
            if (!fileInput) return;
            // Clear file input (works by replacing its files with empty DataTransfer)
            fileInput.value = "";
            const dt = new DataTransfer();
            fileInput.files = dt.files;
            fileInput.dispatchEvent(new Event("input",  { bubbles: true }));
            fileInput.dispatchEvent(new Event("change", { bubbles: true }));
          }
          function clearAll() {
            clearPreview();
          
            // Attempt DOM clear (still useful)
            clearHiddenGradioAudio();
          
            // Tell Gradio/Python explicitly to clear backend state
            props.value = "__CLEAR__";
            trigger("change", props.value);
          
            showDrop();
          }

          function loadFileToPreview(file) {
            if (!file) return;
            if (!file.type || !file.type.startsWith("audio/")) {
              alert("لطفا یک فایل صوتی انتخاب کنید.");
              return;
            }
            clearPreview();
            currentUrl = URL.createObjectURL(file);
            player.src = currentUrl;
            showPlayer(file.name);

          }
          function pushFileIntoHiddenGradioAudio(file) {
            const fileInput = findHiddenAudioFileInput();
            if (!fileInput) {
              console.warn("Could not find hidden gr.File input. Check elem_id:", TARGET_ID);
              return;
            }
          
            // Hard reset (important for re-selecting same file)
            fileInput.value = "";
          
            const dt = new DataTransfer();
            dt.items.add(file);
            fileInput.files = dt.files;
          
            // Trigger Gradio listeners
            fileInput.dispatchEvent(new Event("input",  { bubbles: true }));
            fileInput.dispatchEvent(new Event("change", { bubbles: true }));
          }

          function handleFile(file) {
            loadFileToPreview(file);
            pushFileIntoHiddenGradioAudio(file);
          }
          // Click-to-browse uses a *local* ephemeral input (not Gradio’s),
          // then we forward to hidden gr.Audio.
          const localPicker = document.createElement("input");
          localPicker.type = "file";
          localPicker.accept = "audio/*";
          localPicker.style.display = "none";
          wrap.appendChild(localPicker);
          localPicker.addEventListener("change", () => {
            const f = localPicker.files && localPicker.files[0];
            if (f) handleFile(f);
            localPicker.value = "";
          });
          drop.addEventListener("click", () => localPicker.click());
          drop.addEventListener("keydown", (e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              localPicker.click();
            }
          });
          removeBtn.addEventListener("click", clearAll);
          // Drag & drop
          ["dragenter","dragover","dragleave","drop"].forEach(evt => {
            drop.addEventListener(evt, (e) => {
              e.preventDefault();
              e.stopPropagation();
            });
          });
          drop.addEventListener("dragover", () => drop.classList.add("dragover"));
          drop.addEventListener("dragleave", () => drop.classList.remove("dragover"));
          drop.addEventListener("drop", (e) => {
            drop.classList.remove("dragover");
            const f = e.dataTransfer.files && e.dataTransfer.files[0];
            if (f) handleFile(f);
          });
          // init
          showDrop();

          function setPreviewFromPath(path) {
            if (path === "__CLEAR__") path = null;
            
            if (!path) {
              clearPreview();
              showDrop();
              return;
            }
          
            // If path already looks like a URL, use it directly
            // otherwise serve it through Gradio's file route.
            let url = path;
            if (!/^https?:\/\//.test(path) && !path.startsWith("gradio_api/file=") && !path.startsWith("/file=")) {
              url = "gradio_api/file=" + path;
            }
          
            clearPreview();
            player.src = url;
            showPlayer(path.split("/").pop());
          }
          
          // ---- sync from Python (Examples / backend updates) ----
          let last = props.value;
          const syncFromProps = () => {
            const v = props.value;
          
            if (v !== last) {
              last = v;
              if (!v || v === "__CLEAR__") setPreviewFromPath(null);
              else setPreviewFromPath(String(v));
            }
            requestAnimationFrame(syncFromProps);
          };
          requestAnimationFrame(syncFromProps);


        })();
        """
        js_on_load = js_on_load.replace("__TARGET_ID__", target_audio_elem_id)
        
        super().__init__(
            value=value,
            html_template=html_template,
            js_on_load=js_on_load,
            **kwargs
        )


####################################################################################################
### PART 17: Wrapper Functions (Resolution, Duration, Examples)
####################################################################################################
def generate_video_example(first_frame, prompt, camera_lora, resolution, radioanimated_mode, input_video, input_audio, end_frame, progress=gr.Progress(track_tqdm=True)):

    w, h = apply_resolution(resolution)
    
    # We pass input_video (from example) to generate_video, though the logic inside generate_video 
    # might ignore it since we removed the Motion Control block.
    # We keep the argument in this function signature to align with the examples_list columns.
    
    # Default duration for examples
    duration_s = 5

    with timer(f'generating with LoRA:{camera_lora} in {w}x{h}'):
        output_video = generate_video(
            first_frame,
            end_frame,
            prompt,
            10,
            input_video, 
            radioanimated_mode,
            True,                    
            42,                      
            True,                    
            h,  
            w,   
            camera_lora,     
            input_audio,
            progress
        )
    return output_video

def get_duration(
    first_frame,
    end_frame,
    prompt,
    duration,
    input_video,
    radioanimated_mode,
    enhance_prompt,
    seed,
    randomize_seed,
    height,
    width,
    camera_lora,
    audio_path,
    progress
):
    extra_time = 0

    if audio_path is not None:
        extra_time += 10

    if input_video is not None:
        extra_time += 60

    if duration <= 3:
        return 60 + extra_time
    elif duration <= 5:
        return 80 + extra_time
    elif duration <= 10:
        return 120 + extra_time
    else:
        return 180 + extra_time


####################################################################################################
### PART 18: Main Generation Function (Modified)
####################################################################################################
@spaces.GPU(duration=get_duration)
def generate_video(
    first_frame,
    end_frame,
    prompt: str,
    duration: float,
    input_video = None,
    generation_mode = "تبدیل تصویر به ویدیو", # Default changed to Persian
    enhance_prompt: bool = True,
    seed: int = 42,
    randomize_seed: bool = True,
    height: int = DEFAULT_1_STAGE_HEIGHT,
    width: int = DEFAULT_1_STAGE_WIDTH,
    camera_lora: str = "No LoRA", 
    audio_path = None,
    progress=gr.Progress(track_tqdm=True),
):
    """
    Generate a short cinematic video from a text prompt and optional input image using the LTX-2 distilled pipeline.
    """

    # Removed the 15s warning check since 15s option is removed from UI

    if audio_path is None:
        print(f'generating with duration:{duration} and LoRA:{camera_lora} in {width}x{height}')
    else:
        print(f'generating with duration:{duration} and audio in {width}x{height}')

    # Randomize seed if checkbox is enabled
    current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)

    # Calculate num_frames from duration (using fixed 24 fps)
    frame_rate = 24.0
    num_frames = int(duration * frame_rate) + 1  # +1 to ensure we meet the duration
    video_seconds = int(duration)

    with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
        output_path = tmpfile.name


    images = []
    videos = []

    # Removed Motion Control block

    if first_frame is not None:
        images = []
        images.append((first_frame, 0, 1.0))

    # Updated logic for Persian string
    if generation_mode == "ویدیو با دو تصویر":
      if end_frame is not None:
          end_idx = max(0, num_frames - 1)
          images.append((end_frame, end_idx, 0.5))

    embeddings, final_prompt, status = encode_prompt(
        prompt=prompt,
        enhance_prompt=enhance_prompt,
        input_image=first_frame,
        seed=current_seed,
        negative_prompt="",
    )
    
    video_context = embeddings["video_context"].to("cuda", non_blocking=True)
    audio_context = embeddings["audio_context"].to("cuda", non_blocking=True)
    print("✓ Embeddings loaded successfully")


    # free prompt enhancer / encoder temps ASAP
    del embeddings, final_prompt, status
    torch.cuda.empty_cache()

    # ✅ if user provided audio, use a neutral audio_context
    n_audio_context = None

    if audio_path is not None:
        with torch.inference_mode():
            _, n_audio_context = encode_text_simple(text_encoder, "")  # returns tensors on GPU already
            del audio_context
            audio_context = n_audio_context

        if len(videos) == 0:
            camera_lora = "Static"

    torch.cuda.empty_cache()

    # Map dropdown name -> adapter index
    name_to_idx = {name: idx for name, idx in RUNTIME_LORA_CHOICES}
    selected_idx = name_to_idx.get(camera_lora, -1)

    enable_only_lora(pipeline._transformer, selected_idx)
    torch.cuda.empty_cache()

    # True video duration in seconds based on your rounding
    video_seconds = (num_frames - 1) / frame_rate

    if audio_path is not None:
        input_waveform, input_waveform_sample_rate = match_audio_to_duration(
            audio_path=audio_path,
            target_seconds=video_seconds,
            target_sr=48000,     # pick what your model expects; 48k is common for AV models
            to_mono=True,        # set False if your model wants stereo
            pad_mode="silence",  # or "repeat" if you prefer looping over silence
            device="cuda",
        )
    else:
        input_waveform = None
        input_waveform_sample_rate = None

    with timer(f'generating with LoRA:{camera_lora} in {width}x{height}'):
        with torch.inference_mode():
            pipeline(
                prompt=prompt,
                output_path=str(output_path),
                seed=current_seed,
                height=height,
                width=width,
                num_frames=num_frames,
                frame_rate=frame_rate,
                images=images,
                video_conditioning=videos,
                tiling_config=TilingConfig.default(),
                video_context=video_context,
                audio_context=audio_context,
                input_waveform=input_waveform,
                input_waveform_sample_rate=input_waveform_sample_rate, 
            )
    del video_context, audio_context
    torch.cuda.empty_cache()
    print("successful generation")

    return str(output_path)


def apply_resolution(resolution: str):

    if resolution == "16:9":
        w, h = 768, 512
    elif resolution == "1:1":
        w, h = 512, 512
    elif resolution == "9:16":
        w, h = 512, 768
        
    return int(w), int(h)

def apply_duration(duration: str):
    duration_s = int(duration[:-1])
    return duration_s

def on_mode_change(selected: str):
    is_motion = False # Removed Motion Control
    # Updated logic for Persian string
    is_interpolate = (selected == "ویدیو با دو تصویر")

    return (gr.update(visible=is_motion), gr.update(visible=is_interpolate))


####################################################################################################
### PART 19: CSS Styles
####################################################################################################
css = """

    /* Make the row behave nicely */
    #controls-row {
    display: none !important;
    align-items: center;
    gap: 12px;
    flex-wrap: nowrap; /* or wrap if you prefer on small screens */
    }

    /* Stop these components from stretching */
    #controls-row > * {
    flex: 0 0 auto !important;
    width: auto !important;
    min-width: 0 !important;
    }

    
    #col-container {
        margin: 0 auto;
        max-width: 1600px;
    }
    #modal-container {
    width: 100vw;            /* Take full viewport width */
    height: 100vh;           /* Take full viewport height (optional) */
    display: flex;           
    justify-content: center; /* Center content horizontally */
    align-items: center;     /* Center content vertically if desired */
    }
    #modal-content {
    width: 100%;
    max-width: 700px;         /* Limit content width */
    margin: 0 auto;
    border-radius: 8px;
    padding: 1.5rem;
    }
    #step-column {
        padding: 10px;
        border-radius: 8px;
        box-shadow: var(--card-shadow);
        margin: 10px;
    }
    #col-showcase {
        margin: 0 auto;
        max-width: 1100px;
    }
    .button-gradient {
        background: linear-gradient(45deg, rgb(255, 65, 108), rgb(255, 75, 43), rgb(255, 155, 0), rgb(255, 65, 108)) 0% 0% / 400% 400%;
        border: none;
        padding: 14px 28px;
        font-size: 16px;
        font-weight: bold;
        color: white;
        border-radius: 10px;
        cursor: pointer;
        transition: 0.3s ease-in-out;
        animation: 2s linear 0s infinite normal none running gradientAnimation;
        box-shadow: rgba(255, 65, 108, 0.6) 0px 4px 10px;
    }
    .toggle-container {
    display: inline-flex;
    background-color: #ffd6ff;  /* light pink background */
    border-radius: 9999px;
    padding: 4px;
    position: relative;
    width: fit-content;
    font-family: sans-serif;
    }
    .toggle-container input[type="radio"] {
    display: none;
    }
    .toggle-container label {
    position: relative;
    z-index: 2;
    flex: 1;
    text-align: center;
    font-weight: 700;
    color: #4b2ab5; /* dark purple text for unselected */
    padding: 6px 22px;
    border-radius: 9999px;
    cursor: pointer;
    transition: color 0.25s ease;
    }
    /* Moving highlight */
    .toggle-highlight {
    position: absolute;
    top: 4px;
    left: 4px;
    width: calc(50% - 4px);
    height: calc(100% - 8px);
    background-color: #4b2ab5; /* dark purple background */
    border-radius: 9999px;
    transition: transform 0.25s ease;
    z-index: 1;
    }
    /* When "True" is checked */
    #true:checked ~ label[for="true"] {
    color: #ffd6ff; /* light pink text */
    }
    /* When "False" is checked */
    #false:checked ~ label[for="false"] {
    color: #ffd6ff; /* light pink text */
    }
    /* Move highlight to right side when False is checked */
    #false:checked ~ .toggle-highlight {
    transform: translateX(100%);
    }

    /* Center items inside that row */
    #mode-row{
      justify-content: center !important;
      align-items: center !important;
    }
    
    /* Center the mode row contents */
    #mode-row {
      display: flex !important;
      justify-content: center !important;
      align-items: center !important;
      width: 100% !important;
    }
    
    /* Stop Gradio from making children stretch */
    #mode-row > * {
      flex: 0 0 auto !important;
      width: auto !important;
      min-width: 0 !important;
    }
    
    /* Specifically ensure the HTML component wrapper doesn't take full width */
    #mode-row .gr-html,
    #mode-row .gradio-html,
    #mode-row .prose,
    #mode-row .block {
      width: auto !important;
      flex: 0 0 auto !important;
      display: inline-block !important;
    }
    
    /* Center the pill itself */
    #radioanimated_mode {
      display: inline-flex !important;
      justify-content: center !important;
      width: auto !important;
    }

    """

css += """
    .cd-trigger-icon{
      color: rgba(255,255,255,0.9);
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 18px;
      height: 18px;
    }
    .cd-trigger-icon svg {
      width: 18px;
      height: 18px;
      display: block;
    }
    """


css += """
    /* ---- radioanimated ---- */
    .ra-wrap{
      width: fit-content;
    }
    .ra-inner{
      position: relative;
      display: inline-flex;
      align-items: center;
      gap: 0;
      padding: 6px;
      background: #0b0b0b;
      border-radius: 9999px;
      overflow: hidden;
      user-select: none;
    }
    .ra-input{
      display: none;
    }
    .ra-label{
      position: relative;
      z-index: 2;
      padding: 10px 18px;
      font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
      font-size: 14px;
      font-weight: 600;
      color: rgba(255,255,255,0.7);
      cursor: pointer;
      transition: color 180ms ease;
      white-space: nowrap;
    }
    .ra-highlight{
      position: absolute;
      z-index: 1;
      top: 6px;
      left: 6px;
      height: calc(100% - 12px);
      border-radius: 9999px;
      background: #8bff97; /* green knob */
      transition: transform 200ms ease, width 200ms ease;
    }
    /* selected label becomes darker like your screenshot */
    .ra-input:checked + .ra-label{
      color: rgba(0,0,0,0.75);
    }
    """

css += """
.cd-icn svg{
  width: 18px;
  height: 18px;
  display: block;
}
.cd-icn svg *{
  stroke: rgba(255,255,255,0.9);
}
"""


css += """
    /* --- prompt box --- */
    .ds-prompt{
      width: 100%;
      max-width: 720px;
      margin-top: 3px;
    }
    
    .ds-textarea{
      width: 100%;
      box-sizing: border-box;
      background: #2b2b2b;
      color: rgba(255,255,255,0.9);
      border: 1px solid rgba(255,255,255,0.12);
      border-radius: 14px;
      padding: 14px 16px;
      outline: none;
      font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
      font-size: 15px;
      line-height: 1.35;
      resize: none;
      min-height: 210px;
      max-height: 210px;
      overflow-y: auto;
    
      /* IMPORTANT: space for the footer controls */
      padding-bottom: 72px;
    }


    .ds-card{
      width: 100%;
      max-width: 720px;
      margin: 0 auto;
    }
    .ds-top{
      position: relative;
    }
    
    /* Make room for footer inside textarea */
    .ds-textarea{
      padding-bottom: 72px;
    }
    
    /* Footer positioning */
    .ds-footer{
      position: absolute;
      right: 12px;
      bottom: 10px;
      display: flex;
      gap: 8px;
      align-items: center;
      justify-content: flex-end;
      z-index: 3;
    }
    
    /* Smaller pill buttons inside footer */
    .ds-footer .cd-trigger{
      min-height: 32px;
      padding: 6px 10px;
      font-size: 12px;
      gap: 6px;
      border-radius: 9999px;
    }
    .ds-footer .cd-trigger-icon,
    .ds-footer .cd-icn{
      width: 14px;
      height: 14px;
    }
    .ds-footer .cd-trigger-icon svg,
    .ds-footer .cd-icn svg{
      width: 14px;
      height: 14px;
    }
    .ds-footer .cd-caret{
      font-size: 11px;
    }
    
    /* Bottom safe area bar (optional but looks nicer) */
    .ds-top::after{
      content: "";
      position: absolute;
      left: 1px;
      right: 1px;
      bottom: 1px;
      height: 56px;
      background: #2b2b2b;
      border-bottom-left-radius: 13px;
      border-bottom-right-radius: 13px;
      pointer-events: none;
      z-index: 2;
    }

    """

css += """
    /* ---- camera dropdown ---- */

    /* 1) Fix overlap: make the Gradio HTML block shrink-to-fit when it contains a CameraDropdown.
    Gradio uses .gr-html for HTML components in most versions; older themes sometimes use .gradio-html.
    This keeps your big header HTML unaffected because it doesn't contain .cd-wrap.
    */

    /* 2) Actual dropdown layout */
    .cd-wrap{
    position: relative;
    display: inline-block;
    }

    /* 3) Match RadioAnimated pill size/feel */
    .cd-trigger{
    margin-top: 2px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 10px;

    border: none;

    box-sizing: border-box;
    padding: 10px 18px;
    min-height: 52px;
    line-height: 1.2;

    border-radius: 9999px;
    background: #0b0b0b;

    font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
    font-size: 14px;

    /* ✅ match .ra-label exactly */
    color: rgba(255,255,255,0.7) !important;
    font-weight: 600 !important;

    cursor: pointer;
    user-select: none;
    white-space: nowrap;
    }

    /* Ensure inner spans match too */
    .cd-trigger .cd-trigger-text,
    .cd-trigger .cd-caret{
    color: rgba(255,255,255,0.7) !important;
    }

    /* keep caret styling */
    .cd-caret{
    opacity: 0.8;
    font-weight: 900;
    }

    /* 4) Ensure menu overlays neighbors and isn't clipped */
    /* Move dropdown a tiny bit up (closer to the trigger) */
    .cd-menu{
      position: absolute;
      top: calc(100% + 4px);   /* was +10px */
      left: 0;
    
      min-width: 240px;
      background: #2b2b2b;
      border: 1px solid rgba(255,255,255,0.14);
      border-radius: 14px;
      box-shadow: 0 18px 40px rgba(0,0,0,0.35);
      padding: 10px;
    
      opacity: 0;
      transform: translateY(-6px);
      pointer-events: none;
      transition: opacity 160ms ease, transform 160ms ease;
    
      z-index: 9999;
    }

    .cd-title{
      font-size: 12px;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.04em;
    
      color: rgba(255,255,255,0.45); /* 👈 muted grey */
      margin-bottom: 6px;
      padding: 0 6px;
      pointer-events: none; /* title is non-interactive */
    }
    
        
    .cd-menu.open{
      opacity: 1;
      transform: translateY(0);
      pointer-events: auto;
    }
    
    .cd-items{
      display: flex;
      flex-direction: column;
      gap: 0px; /* tighter, more like a native menu */
    }
    
    /* Items: NO "boxed" buttons by default */
    .cd-item{
      width: 100%;
      text-align: left;
      border: none;
      background: transparent;          /* ✅ removes box look */
      color: rgba(255,255,255,0.92);
      padding: 8px 34px 8px 12px;     /* right padding leaves room for tick */
      border-radius: 10px;             /* only matters on hover */
      cursor: pointer;
    
      font-size: 14px;
      font-weight: 700;
    
      position: relative;
      transition: background 120ms ease;
    }
    
    /* “Box effect” only on hover (not always) */
    .cd-item:hover{
      background: rgba(255,255,255,0.08);
    }
    
    /* Tick on the right ONLY on hover */
    .cd-item::after{
      content: "✓";
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      opacity: 0;                      /* hidden by default */
      transition: opacity 120ms ease;
      color: rgba(255,255,255,0.9);
      font-weight: 900;
    }
    
    /* show tick ONLY for selected item */
    .cd-item[data-selected="true"]::after{
      opacity: 1;
    }
    
    /* keep hover box effect, but no tick change */
    .cd-item:hover{
      background: rgba(255,255,255,0.08);
    }

    
    /* Kill any old “selected” styling just in case */
    .cd-item.selected{
      background: transparent !important;
      border: none !important;
    }


    """

css += """
/* icons in dropdown items */
.cd-item{
  display: flex;
  align-items: center;
  gap: 10px;
}
.cd-icn{
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 18px;
  height: 18px;
  flex: 0 0 18px;
}
.cd-label{
  flex: 1;
}

/* =========================
   FIX: prompt border + scrollbar bleed
   ========================= */

/* Put the border + background on the wrapper, not the textarea */
.ds-top{
  position: relative;
  background: #2b2b2b;
  border: 1px solid rgba(255,255,255,0.12);
  border-radius: 14px;
  overflow: hidden; /* ensures the footer bar is clipped to rounded corners */
}

/* Make textarea "transparent" so wrapper owns the border/background */
.ds-textarea{
  background: transparent !important;
  border: none !important;
  border-radius: 0 !important; /* wrapper handles radius */
  outline: none;

  /* keep your spacing */
  padding: 14px 16px;
  padding-bottom: 72px; /* room for footer */
  width: 100%;
  box-sizing: border-box;

  /* keep scroll behavior */
  overflow-y: auto;

  /* prevent scrollbar bleed by hiding native scrollbar */
  scrollbar-width: none;          /* Firefox */
}
.ds-textarea::-webkit-scrollbar{  /* Chrome/Safari */
  width: 0;
  height: 0;
}

/* Safe-area bar: now it matches perfectly because it's inside the same bordered wrapper */
.ds-top::after{
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 56px;
  background: #2b2b2b;
  pointer-events: none;
  z-index: 2;
}

/* Footer above the bar */
.ds-footer{
  position: absolute;
  right: 12px;
  bottom: 10px;
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: flex-end;
  z-index: 3;
}

/* Ensure textarea content sits below overlays */
.ds-textarea{
  position: relative;
  z-index: 1;
}

/* ===== FIX dropdown menu being clipped/behind ===== */

/* Let the dropdown menu escape the prompt wrapper */
.ds-top{
  overflow: visible !important;  /* IMPORTANT: do not clip the menu */
}

/* Keep the rounded "safe area" look without clipping the menu */
.ds-top::after{
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  border-bottom-left-radius: 14px !important;
  border-bottom-right-radius: 14px !important;
}

/* Ensure the footer stays above the safe-area bar */
.ds-footer{
  z-index: 20 !important;
}

/* Make sure the opened menu is above EVERYTHING */
.ds-footer .cd-menu{
  z-index: 999999 !important;
}

/* Sometimes Gradio/columns/cards create stacking contexts;
   force the whole prompt card above nearby panels */
.ds-card{
  position: relative;
  z-index: 50;
}

/* --- Fix focus highlight shape (make it match rounded container) --- */

/* Kill any theme focus ring on the textarea itself */
.ds-textarea:focus,
.ds-textarea:focus-visible{
  outline: none !important;
  box-shadow: none !important;
}

/* Optional: if some themes apply it even when not focused */
.ds-textarea{
  outline: none !important;
}

/* Apply the focus ring to the rounded wrapper instead */
.ds-top:focus-within{
  border-color: rgba(255,255,255,0.22) !important;
  box-shadow: 0 0 0 3px rgba(255,255,255,0.06) !important;
  border-radius: 14px !important;
}

/* If you see any tiny square corners, ensure the wrapper clips its own shadow properly */
.ds-top{
  border-radius: 14px !important;
}

/* =========================
   CameraDropdown: force readable menu text in BOTH themes
   ========================= */

/* Menu surface */
.cd-menu{
  background: #2b2b2b !important;
  border: 1px solid rgba(255,255,255,0.14) !important;
}

/* Title */
.cd-title{
  color: rgba(255,255,255,0.55) !important;
}

/* Items + all descendants (fixes spans / inherited theme colors) */
.cd-item,
.cd-item *{
  color: rgba(255,255,255,0.92) !important;
}

/* Hover state */
.cd-item:hover{
  background: rgba(255,255,255,0.10) !important;
}

/* Checkmark */
.cd-item::after{
  color: rgba(255,255,255,0.92) !important;
}

/* (Optional) make sure the trigger stays readable too */
.cd-trigger,
.cd-trigger *{
  color: rgba(255,255,255,0.75) !important;
}

/* ---- preset gallery ---- */
.pg-wrap{
  width: 100%;
  max-width: 1100px;
  margin: 18px auto 0 auto;
}
.pg-title{
  text-align: center;
  margin-bottom: 14px;
}
.pg-h1{
  font-size: 34px;
  font-weight: 800;
  line-height: 1.1;

  /* ✅ theme-aware */
  color: var(--body-text-color);
}
.pg-h2{
  font-size: 14px;
  font-weight: 600;
  color: var(--body-text-color-subdued);
  margin-top: 6px;
}

.pg-grid{
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr)); /* 3 per row */
  gap: 18px;
}

.pg-card{
  border: none;
  background: transparent;
  padding: 0;
  cursor: pointer;
  border-radius: 12px;
  overflow: hidden;
  position: relative;
  transform: translateZ(0);
}

.pg-img{
  width: 100%;
  height: 220px;              /* adjust to match your look */
  object-fit: cover;
  display: block;
  border-radius: 12px;
  transition: transform 160ms ease, filter 160ms ease, opacity 160ms ease;
}

/* hover: slight zoom on hovered card */
.pg-card:hover .pg-img{
  transform: scale(1.02);
}

/* dim others while hovering */
.pg-card[data-dim="true"] .pg-img{
  opacity: 0.35;
  filter: saturate(0.9);
}

/* keep hovered/active crisp */
.pg-card[data-active="true"] .pg-img{
  opacity: 1.0;
  filter: none;
}


"""


css += """
/* ---- AudioDropUpload ---- */
.aud-wrap{
  width: 100%;
  max-width: 720px;
}
.aud-drop{
  border: 2px dashed var(--body-text-color-subdued);
  border-radius: 16px;
  padding: 18px;
  text-align: center;
  cursor: pointer;
  user-select: none;
  color: var(--body-text-color);
  background: var(--block-background-fill);
}
.aud-drop.dragover{
  border-color: rgba(255,255,255,0.35);
  background: rgba(255,255,255,0.06);
}
.aud-hint{
  color: var(--body-text-color-subdued);
  font-size: 0.95rem;
  margin-top: 6px;
}
/* pill row like your other controls */
.aud-row{
  display: none;
  align-items: center;
  gap: 10px;
  background: #0b0b0b;
  border-radius: 9999px;
  padding: 8px 10px;
}
.aud-player{
  flex: 1;
  width: 100%;
  height: 34px;
  border-radius: 9999px;
}
.aud-remove{
  appearance: none;
  border: none;
  background: transparent;
  color: rgba(255,255,255);
  cursor: pointer;
  width: 36px;
  height: 36px;
  border-radius: 9999px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  transition: background 120ms ease, color 120ms ease, opacity 120ms ease;
  opacity: 0.9;
  flex: 0 0 auto;
}
.aud-remove:hover{
  background: rgba(255,255,255,0.08);
  color: rgb(255,255,255);
  opacity: 1;
}
.aud-filelabel{
  margin: 10px 6px 0;
  color: var(--body-text-color-subdued);
  font-size: 0.95rem;
  display: none;
}
#audio_input_hidden { display: none !important; }
"""

# Hiding Gradio Footer, Branding and Settings
css += """
footer {
    display: none !important;
}
.gradio-container footer {
    display: none !important;
}
div.footer {
    display: none !important;
}
.flagging {
    display: none !important;
}
/* Hide the 'Use via API' link if visible */
.api-logo, .built-with {
    display: none !important;
}
"""


def apply_example(idx: str):
    idx = int(idx)

    # Read the example row from your list
    img, prompt_txt, cam, res, mode, vid, aud, end_img = examples_list[idx]

    img_path = img if img else None
    vid_path = vid if vid else None
    aud_path = aud if aud else None

    input_image_update = img_path
    prompt_update = prompt_txt
    camera_update = cam
    resolution_update = res
    mode_update = mode
    video_update = gr.update(value=vid_path, visible=(mode == "Motion Control"))
    audio_update = aud_path
    end_image = end_img

    return (
        input_image_update,
        prompt_update,
        camera_update,
        resolution_update,
        mode_update,
        video_update,
        audio_update,
        audio_update,
        end_image,
    )


####################################################################################################
### PART 20: Gradio UI Layout & Launch (CPU-OPTIMIZED & GPU-GENERATION SPLIT)
####################################################################################################
import requests
import time

# JS Function to handle download request via PostMessage
js_download_video = """
async (video) => {
    if (!video) { 
        alert("لطفاً ابتدا ویدیو را تولید کنید."); 
        return; 
    }
    
    let fileUrl = "";
    
    // پیدا کردن لینک فایل از داخل ساختار پیچیده خروجی گاردریو نسخه 4
    if (typeof video === 'string') {
        fileUrl = video;
    } else if (video && video.video && typeof video.video.url === 'string') {
        fileUrl = video.video.url;
    } else if (video && video.video && typeof video.video.path === 'string') {
        fileUrl = video.video.path;
    } else if (video && typeof video.url === 'string') {
        fileUrl = video.url;
    } else if (video && typeof video.path === 'string') {
        fileUrl = video.path;
    }

    if (!fileUrl) {
        alert("خطا: مسیر ویدیو یافت نشد.");
        return;
    }

    if (fileUrl && !fileUrl.startsWith('http') && !fileUrl.startsWith('blob:')) { 
        let cleanPath = fileUrl.startsWith('/') ? fileUrl.substring(1) : fileUrl;
        
        // اطمینان از قرار گرفتن کلمه file= برای گاردریو
        if (!cleanPath.startsWith('gradio_api/') && !cleanPath.startsWith('file=')) {
            cleanPath = 'file=' + cleanPath;
        }
        
        fileUrl = window.location.origin + "/" + cleanPath;
    }
    
    if (fileUrl) {
        console.log("Sending download request for:", fileUrl);
        window.parent.postMessage({ type: 'DOWNLOAD_REQUEST', url: fileUrl }, '*');
    }
}
"""

def enhance_prompt_on_cpu(image_path: str, prompt: str, mode: str):
    """
    این تابع روی CPU اجرا می‌شود و هیچ سهمیه‌ای از GPU کم نمی‌کند.
    """
    if mode not in ['تبدیل تصویر به ویدیو', 'ویدیو با دو تصویر'] or not image_path:
        return prompt

    print("Running prompt enhancement on CPU...")
    url = 'https://ezmarynoori-vidtolani.hf.space/api/enhance-animation-prompt'
    try:
        with open(image_path, 'rb') as f:
            files = {'image': f}
            data = {'prompt': prompt, 'is_extension': 'false'}
            response = requests.post(url, files=files, data=data, timeout=60)
            
            if response.status_code == 200:
                result = response.json()
                enhanced = result.get("animation_prompt", prompt)
                print(f"Success! Enhanced prompt: {enhanced[:50]}...")
                return enhanced
            else:
                print(f"API Error {response.status_code}: {response.text}")
                return prompt
    except Exception as e:
        print(f"CPU Enhancement failed (using original): {e}")
        return prompt

def apply_example(idx: str):
    idx = int(idx)
    img, prompt_txt, cam, res, mode, vid, aud, end_img, dur = examples_list[idx]
    return (
        img or None, prompt_txt, cam, dur, res, mode,
        gr.update(value=vid or None, visible=(mode == "Motion Control")),
        aud or None, aud or None, end_img or None,
        gr.update(value=None), gr.update(visible=False)
    )

# تعریف متغیرهای متنی برای دکمه‌ها با استایل‌های داخلی (کوچک کردن کلمه پیشفرض)
ENHANCE_YES_TEXT = "دستور بهینه شود <span style='font-size: 0.75em; font-weight: normal; opacity: 0.75;'>(پیشفرض)</span> ✨"
ENHANCE_NO_TEXT = "دستور بهینه نشود ✋"

# --- توابع کنترل کننده (بدون وابستگی محلی) ---

def ui_lock_and_enhance(first_frame, prompt, mode, enhance_toggle, audio_input, duration):
    """
    مرحله ۱: قفل کردن UI و بررسی اینکه آیا پرامپت نیاز به بهینه‌سازی دارد یا خیر
    """
    # بررسی محدودیت زمانی برای فایل صوتی
    if audio_input is not None and float(duration) > 5.0:
        raise gr.Error("در صورت وجود همزمان فایل صوتی امکان ساخت فقط تا پنج ثانیه امکان پذیر است")

    if enhance_toggle == ENHANCE_YES_TEXT:
        yield (
            gr.Button(value="⏳ در حال بهینه سازی پرامپت (CPU)...", interactive=False),
            gr.update(), 
            gr.update(), 
            None 
        )
        
        enhanced = enhance_prompt_on_cpu(first_frame, prompt, mode)
        
        yield (
            gr.Button(value="🚀 در حال ساخت ویدیو (GPU)...", interactive=False),
            gr.update(value=enhanced), 
            enhanced, 
            None
        )
    else:
        # اگر کاربر نخواست پرامپت بهینه شود، مستقیما به مرحله تولید می‌رویم
        yield (
            gr.Button(value="🚀 در حال ساخت ویدیو (GPU)...", interactive=False),
            gr.update(value=prompt), 
            prompt, 
            None
        )

@spaces.GPU(duration=get_duration)
def ui_generate_video(
    first_frame, end_frame, enhanced_prompt, duration, input_video,
    radioanimated_mode, enhance_toggle, seed, randomize_seed,
    height, width, camera_lora, audio_input, progress=gr.Progress(track_tqdm=True)
):
    """
    مرحله ۲: ساخت ویدیو با استفاده از GPU
    """
    # بررسی مجدد محدودیت زمانی برای اطمینان در مرحله ساخت
    if audio_input is not None and float(duration) > 5.0:
        raise gr.Error("در صورت وجود همزمان فایل صوتی امکان ساخت فقط تا پنج ثانیه امکان پذیر است")

    video_path = generate_video(
        first_frame, end_frame, enhanced_prompt, duration, input_video,
        radioanimated_mode, False, seed, randomize_seed,
        height, width, camera_lora, audio_input, progress
    )
    return (
        gr.Button(value="🤩 ساخت ویدیو", interactive=True),
        video_path,
        gr.Button(visible=True)
    )


# کدهای جاوااسکریپت قدرتمند برای بازکردن قفل دکمه هنگام خطا
relocate_js = r"""
(() => { 
    function getGradioRoot() {
        const app = document.querySelector('gradio-app');
        return app && app.shadowRoot ? app.shadowRoot : document;
    }

    function moveIntoFooter() { 
        const root = getGradioRoot();
        const p = root.querySelector("#prompt_ui");
        const f = p ? p.querySelector(".ds-footer") : null; 
        if (!f) return false; 
        
        const d = root.querySelector("#duration_ui .cd-wrap");
        const r = root.querySelector("#resolution_ui .cd-wrap");
        const c = root.querySelector("#camera_ui .cd-wrap"); 
        if (!d || !r || !c) return false; 
        
        f.appendChild(d); f.appendChild(r); f.appendChild(c); 
        return true; 
    } 
    
    function checkAndReset(mutations) {
        let errorFound = false;
        
        // بررسی افزوده شدن Toast ها
        if (mutations) {
            mutations.forEach(m => {
                m.addedNodes.forEach(node => {
                    if (node.nodeType === 1) {
                        const txt = (node.textContent || "").toLowerCase();
                        if (txt.includes("quota") || txt.includes("exceeded") || txt.includes("error") || txt.includes("خطا") || txt.includes("فایل صوتی")) {
                            errorFound = true;
                        }
                        if (node.classList && node.classList.contains("toast-wrap")) {
                            errorFound = true; 
                        }
                    }
                });
            });
        }

        // بررسی متون در کل صفحه (حتی مواردی که توسط کد شما مخفی شده‌اند)
        const root = getGradioRoot();
        const fullText = ((document.body.textContent || "") + " " + (root.textContent || "")).toLowerCase();
        if (fullText.includes("exceeded your gpu quota") || fullText.includes("gpu quota")) {
            errorFound = true;
        }

        if (errorFound && !window._resetFiredBtn) {
            window._resetFiredBtn = true;
            console.log("Error or Quota detected! Forcing reset...");
            
            // کلیک کردن دکمه مخفی پایتون که صف رو دور می‌زند
            const rb = root.querySelector('#reset_btn');
            if (rb) {
                const btn = rb.tagName === 'BUTTON' ? rb : rb.querySelector('button');
                if (btn) btn.click();
            }
            
            // باز کردن فیزیکی قفل دکمه تولید (احتیاط ثانویه)
            const gbWrap = root.querySelector('#generate_btn');
            if (gbWrap) {
                const gb = gbWrap.tagName === 'BUTTON' ? gbWrap : gbWrap.querySelector('button');
                if (gb) {
                    gb.innerText = "🤩 ساخت ویدیو";
                    gb.disabled = false;
                    gb.classList.remove("disabled"); 
                    gb.style.pointerEvents = "auto";
                }
            }
            
            // جلوگیری از کلیک مکرر به مدت ۵ ثانیه
            setTimeout(() => { window._resetFiredBtn = false; }, 5000);
        }
    }

    function setupErrorObserver() {
        const observer = new MutationObserver(checkAndReset);
        observer.observe(document.body, { childList: true, subtree: true });
        
        const root = getGradioRoot();
        if (root !== document) {
            observer.observe(root, { childList: true, subtree: true });
        }
        
        // اسکن دائمی صفحه هر 1 ثانیه به عنوان روش تضمینی
        setInterval(() => checkAndReset(), 1000);
    }
    
    const tick = () => { 
        if (!moveIntoFooter()) requestAnimationFrame(tick); 
        else setupErrorObserver(); 
    }; 
    requestAnimationFrame(tick); 
})();
"""

with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
    
    # مخفی کردن فیزیکی دکمه ریست بدون استفاده از visible=False
    gr.HTML("<style>#reset_btn { display: none !important; }</style>")
    
    gr.HTML(
        """
        <div style="text-align: center; padding: 20px;">
            <h1 style="font-size: 28px; font-weight: bold; margin-bottom: 10px; color: var(--body-text-color);">
                ساخت ویدیو با هوش مصنوعی
            </h1>
            <p style="font-size: 18px; color: var(--body-text-color-subdued); margin: 0;">
                با پشتیبانی از صدا و دو تصویر
            </p>
        </div>
        """
    )
    
    with gr.Column(elem_id="col-container"):
        with gr.Row(elem_id="mode-row"):
            radioanimated_mode = RadioAnimated(choices=["تبدیل تصویر به ویدیو", "ویدیو با دو تصویر"], value="تبدیل تصویر به ویدیو", elem_id="radioanimated_mode")
        with gr.Row():
            with gr.Column(elem_id="step-column"):
                with gr.Row():
                    first_frame = gr.Image(label="تصویر اول (برای بهینه‌سازی پرامپت الزامی است)", type="filepath", height=256)
                    end_frame = gr.Image(label="تصویر آخر (اختیاری)", type="filepath", height=256, visible=False)
                    input_video = gr.Video(label="Motion Reference Video", height=256, visible=False)
                
                relocate = gr.HTML(value="", html_template="<div></div>", js_on_load=relocate_js)
                
                prompt_ui = PromptBox(value="این تصویر را با حرکت سینمایی و انیمیشن روان زنده کن", elem_id="prompt_ui")
                audio_input = gr.File(label="Audio (Optional)", file_types=["audio"], type="filepath", elem_id="audio_input_hidden")
                audio_ui = AudioDropUpload(target_audio_elem_id="audio_input_hidden", elem_id="audio_ui")
                prompt = gr.Textbox(label="Prompt", value="این تصویر را با حرکت سینمایی و انیمیشن روان زنده کن", lines=3, max_lines=3, visible=False)
                
                with gr.Accordion("تنظیمات پیشرفته", open=False, visible=False):
                    seed = gr.Slider(label="سید (Seed)", minimum=0, maximum=MAX_SEED, value=DEFAULT_SEED, step=1)
                    randomize_seed = gr.Checkbox(label="استفاده از سید تصادفی", value=True)
            
            with gr.Column(elem_id="step-column"):
                output_video = gr.Video(label="ویدیوی ساخته شده", autoplay=True, height=512, interactive=False)
                with gr.Row():
                    download_btn = gr.Button("📥 دانلود ویدیو", variant="secondary", size="sm", scale=0, visible=False)
                with gr.Row(elem_id="controls-row"):
                    duration_ui = CameraDropdown(choices=["3s", "5s", "8s", "10s"], value="5s", title="مدت زمان ویدیو", elem_id="duration_ui")
                    duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=5.0, step=0.1, visible=False)
                    ICON_16_9, ICON_1_1, ICON_9_16 = ("<svg viewBox='0 0 24 24' fill='none' aria-hidden='true'><rect x='3' y='7' width='18' height='10' rx='2' stroke='currentColor' stroke-width='2'/></svg>", "<svg viewBox='0 0 24 24' fill='none' aria-hidden='true'><rect x='6' y='6' width='12' height='12' rx='2' stroke='currentColor' stroke-width='2'/></svg>", "<svg viewBox='0 0 24 24' fill='none' aria-hidden='true'><rect x='7' y='3' width='10' height='18' rx='2' stroke='currentColor' stroke-width='2'/></svg>")
                    resolution_ui = CameraDropdown(choices=[{"label": "16:9", "value": "16:9", "icon": ICON_16_9}, {"label": "1:1", "value": "1:1", "icon": ICON_1_1}, {"label": "9:16", "value": "9:16", "icon": ICON_9_16}], value="16:9", title="ابعاد تصویر", elem_id="resolution_ui")
                    width = gr.Number(label="Width", value=DEFAULT_1_STAGE_WIDTH, precision=0, visible=False)
                    height = gr.Number(label="Height", value=DEFAULT_1_STAGE_HEIGHT, precision=0, visible=False)
                    
                    camera_choices_fa = [
                        {"label": "بدون افکت", "value": "No LoRA"},
                        {"label": "ثابت", "value": "Static"},
                        {"label": "جزئیات بیشتر", "value": "Detailer"},
                        {"label": "زوم به داخل", "value": "Zoom In"},
                        {"label": "زوم به بیرون", "value": "Zoom Out"},
                        {"label": "حرکت به چپ", "value": "Slide Left"},
                        {"label": "حرکت به راست", "value": "Slide Right"},
                        {"label": "حرکت به پایین", "value": "Slide Down"},
                        {"label": "حرکت به بالا", "value": "Slide Up"},
                    ]
                    camera_ui = CameraDropdown(choices=camera_choices_fa, value="No LoRA", title="افکت دوربین (LoRA)", elem_id="camera_ui")
                    camera_lora = gr.Dropdown(label="Camera Control LoRA", choices=[(c["label"], c["value"]) for c in camera_choices_fa], value="No LoRA", visible=False)
                
                # استایل‌های بهینه‌شده برای کوچکتر کردن دکمه‌ها و قرار دادن در مرکز صفحه
                gr.HTML("""
                <style>
                #enhance-toggle-col {
                    display: flex !important;
                    flex-direction: column !important;
                    align-items: center !important;
                    justify-content: center !important;
                    margin: 15px auto !important;
                    width: 100% !important;
                    text-align: center !important;
                }
                #enhance_toggle {
                    display: flex !important;
                    justify-content: center !important;
                    align-items: center !important;
                    width: 100% !important;
                }
                #enhance_toggle .ra-wrap {
                    margin: 0 auto !important;
                }
                /* استایل برای کوچکتر کردن سایز دکمه‌های RadioAnimated به طور خاص */
                #enhance_toggle .ra-label {
                    padding: 7px 12px !important;
                    font-size: 12.5px !important;
                }
                .enhance-helper-text {
                    font-size: 11px; /* متن راهنما نیز کمی کوچکتر شد */
                    color: rgba(255, 255, 255, 0.55);
                    text-align: center;
                    margin-top: 8px;
                    margin-left: auto;
                    margin-right: auto;
                    max-width: 90%;
                    line-height: 1.5;
                }
                </style>
                """)

                # افزودن سوییچ پرامپت با متون سفارشی
                with gr.Column(elem_id="enhance-toggle-col"):
                    enhance_toggle = RadioAnimated(
                        choices=[ENHANCE_YES_TEXT, ENHANCE_NO_TEXT], 
                        value=ENHANCE_YES_TEXT, 
                        elem_id="enhance_toggle"
                    )
                    gr.HTML('<div class="enhance-helper-text">بهترین حالت برای درک بهتر دستور و ساخت ویدیو بر اساس پرامپت شما، بهتره حالت روی «بهینه شود» باشه.</div>')

                generate_btn = gr.Button("🤩 ساخت ویدیو", variant="primary", elem_classes="button-gradient", elem_id="generate_btn")
                
                reset_btn = gr.Button("Reset", elem_id="reset_btn")

    # اتصال رویدادها
    camera_ui.change(fn=lambda x: x, inputs=camera_ui, outputs=camera_lora, api_visibility="private")
    radioanimated_mode.change(fn=on_mode_change, inputs=radioanimated_mode, outputs=[input_video, end_frame], api_visibility="private")
    duration_ui.change(fn=apply_duration, inputs=duration_ui, outputs=[duration], api_visibility="private")
    resolution_ui.change(fn=apply_resolution, inputs=resolution_ui, outputs=[width, height], api_visibility="private")
    prompt_ui.change(fn=lambda x: x, inputs=prompt_ui, outputs=prompt, api_visibility="private")
    audio_ui.change(fn=lambda v: None if v == "__CLEAR__" or not v else gr.update(), inputs=audio_ui, outputs=audio_input, api_visibility="private")
    download_btn.click(fn=None, inputs=[output_video], js=js_download_video)
    
    reset_btn.click(
        fn=lambda: gr.Button(value="🤩 ساخت ویدیو", interactive=True),
        inputs=[],
        outputs=[generate_btn],
        api_visibility="private",
        queue=False 
    )
    
    # زنجیره اصلی ساخت ویدیو
    generate_btn.click(
        fn=ui_lock_and_enhance,
        inputs=[first_frame, prompt, radioanimated_mode, enhance_toggle, audio_input, duration],
        outputs=[generate_btn, prompt_ui, prompt, output_video]
    ).then(
        fn=ui_generate_video,
        inputs=[
            first_frame, end_frame, prompt, 
            duration, input_video, radioanimated_mode, enhance_toggle, 
            seed, randomize_seed, height, width, camera_lora, audio_input
        ],
        outputs=[generate_btn, output_video, download_btn]
    )

    # منطق نمونه ها همراه با زمان
    examples_list = [
        ["examples/supergirl-2.png", "A fuzzy puppet superhero character resembling a female puppet with blonde hair and a blue superhero suit sleeping in bed and just waking up, she gradually gets up, rubbing her eyes and looking at her dog that just popped on the bed. the scene feels chaotic, comedic, and emotional with expressive puppet reactions, cinematic lighting, smooth camera motion, shallow depth of field, and high-quality puppet-style animation", "Static", "16:9", "تبدیل تصویر به ویدیو", None, "examples/supergirl.m4a", None, "5s"],
        ["examples/frame3.png", "انار خوردن یک خانم با لباس سفید و گفتن وای چقدر خوشمزه است به فارسی . حتما به فارسی باید بگوید", "Static", "16:9", "ویدیو با دو تصویر", None, None, "examples/frame4.png", "10s"],
        ["examples/supergirl.png", "A fuzzy puppet superhero character resembling a female puppet with blonde hair and a blue superhero suit stands inside an icy cave made of frozen walls and icicles, she looks panicked and frantic, rapidly turning her head left and right and scanning the cave while waving her arms and shouting angrily and desperately, mouthing the words “where the hell is my dog,” her movements exaggerated and puppet-like with high energy and urgency, suddenly a second puppet dog bursts into frame from the side, jumping up excitedly and tackling her affectionately while licking her face repeatedly, she freezes in surprise and then breaks into relief and laughter as the dog continues licking her, the scene feels chaotic, comedic, and emotional with expressive puppet reactions, cinematic lighting, smooth camera motion, shallow depth of field, and high-quality puppet-style animation", "No LoRA", "16:9", "تبدیل تصویر به ویدیو", None, None, None, "5s"],
        ["examples/highland.png", "Realistic POV selfie-style video in a snowy, foggy field. Two shaggy Highland cows with long curved horns stand ahead. The camera is handheld and slightly shaky. The woman filming talks nervously and excitedly in a vlog tone: \"Oh my god guys… look how big those horns are… I’m kinda scared.\" The cow on the left walks toward the camera in a cute, bouncy, hopping way, curious and gentle. Snow crunches under its hooves, breath visible in the cold air. The horns look massive from the POV. As the cow gets very close, its wet nose with slight dripping fills part of the frame. She laughs nervously but reaches out and pets the cow. The cow makes deep, soft, interesting mooing and snorting sounds, calm and friendly. Ultra-realistic, natural lighting, immersive audio, documentary-style realism.", "No LoRA", "16:9", "تبدیل تصویر به ویدیو", None, None, None, "5s"],
        ["examples/wednesday.png", "A cinematic dolly out of Wednesday Addams frozen mid-dance on a dark, blue-lit ballroom floor as students move indistinctly behind her, their footsteps and muffled music reduced to a distant, underwater thrum; the audio foregrounds her steady breathing and the faint rustle of fabric as she slowly raises one arm, never breaking eye contact with the camera, then after a deliberately long silence she speaks in a flat, dry, perfectly controlled voice, “I don’t dance… I vibe code,” each word crisp and unemotional, followed by an abrupt cutoff of her voice as the background sound swells slightly, reinforcing the deadpan humor, with precise lip sync, minimal facial movement, stark gothic lighting, and cinematic realism.", "Zoom Out", "16:9", "تبدیل تصویر به ویدیو", None, None, None, "5s"],
        ["examples/astronaut.png", "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a breath-taking, movie-like shot.", "Static", "1:1", "تبدیل تصویر به ویدیو", None, None, None, "5s"],
    ]

    preset_gallery = PresetGallery(
        items=[{"thumb": "examples/supergirl-2.png", "label": "تصویر و صدا به ویدیو"}, {"thumb": "examples/frame3.png", "label": "تصویر اول و آخر"}, {"thumb": "examples/supergirl.png", "label": "تصویر به ویدیو (عروسک)"}, {"thumb": "examples/highland.png", "label": "تصویر به ویدیو (گاو)"}, {"thumb": "examples/wednesday.png", "label": "تصویر به ویدیو (ونزدی)"}, {"thumb": "examples/astronaut.png", "label": "تصویر به ویدیو (فضانورد)"}],
        title="نمونه ها",
    )

    preset_gallery.change(
        fn=apply_example,
        inputs=preset_gallery,
        outputs=[first_frame, prompt_ui, camera_ui, duration_ui, resolution_ui, radioanimated_mode, input_video, audio_input, audio_ui, end_frame, output_video, download_btn],
        api_visibility="private",
    )

if __name__ == "__main__":
    demo.launch(ssr_mode=False, mcp_server=True, css=css, allowed_paths=["./examples"])