File size: 185,958 Bytes
ff5916c
 
29f5a33
 
 
ff5916c
29f5a33
 
d6e445f
 
ff5916c
29f5a33
ff5916c
29f5a33
 
ff5916c
29f5a33
ff5916c
29f5a33
ff5916c
 
 
29f5a33
ff5916c
29f5a33
 
 
 
ff5916c
29f5a33
ff5916c
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff5916c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff5916c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29f5a33
 
3c4e035
ff5916c
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff5916c
29f5a33
 
 
b708f85
29f5a33
b708f85
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff5916c
 
 
 
 
 
 
 
 
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6e445f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b59c5e
 
 
29f5a33
6b59c5e
 
29f5a33
 
 
 
 
 
 
 
 
 
 
6b59c5e
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b59c5e
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b59c5e
29f5a33
 
 
 
 
 
6b59c5e
29f5a33
 
6b59c5e
 
 
7a6f1a8
29f5a33
 
7a6f1a8
29f5a33
7a6f1a8
29f5a33
7a6f1a8
29f5a33
 
 
 
7a6f1a8
 
29f5a33
 
 
 
7a6f1a8
29f5a33
7a6f1a8
29f5a33
7a6f1a8
29f5a33
 
 
7a6f1a8
 
3c4e035
 
 
 
 
 
 
 
 
 
 
 
ff5916c
 
 
 
 
29f5a33
 
 
 
ff5916c
 
29f5a33
ff5916c
 
 
 
29f5a33
ff5916c
 
 
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff5916c
 
6b59c5e
 
 
 
 
 
 
29f5a33
 
6b59c5e
29f5a33
 
6b59c5e
29f5a33
6b59c5e
 
29f5a33
6b59c5e
29f5a33
 
6b59c5e
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
6b59c5e
 
 
 
 
29f5a33
6b59c5e
29f5a33
 
 
 
 
 
 
 
 
6b59c5e
29f5a33
 
dc0e0d7
6b59c5e
 
ff5916c
2cee926
6b59c5e
3c4e035
ff5916c
2cee926
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
6b59c5e
7a6f1a8
3c4e035
 
29f5a33
3c4e035
29f5a33
 
ff5916c
 
29f5a33
ff5916c
29f5a33
ff5916c
 
29f5a33
ff5916c
 
 
 
 
 
 
3c4e035
ff5916c
3c4e035
ff5916c
 
 
29f5a33
ff5916c
 
 
29f5a33
 
ff5916c
29f5a33
ff5916c
 
 
29f5a33
ff5916c
 
 
 
 
3c4e035
29f5a33
 
 
 
ff5916c
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6e445f
ff5916c
29f5a33
 
 
 
ff5916c
29f5a33
 
 
 
ff5916c
 
 
 
 
 
 
 
29f5a33
 
 
 
ff5916c
 
29f5a33
ff5916c
 
 
 
3c4e035
 
29f5a33
ff5916c
29f5a33
 
 
 
 
ff5916c
 
 
3c4e035
 
 
 
 
29f5a33
 
 
 
 
 
 
ff5916c
29f5a33
 
 
 
 
 
 
 
 
 
 
ff5916c
 
29f5a33
 
 
 
 
ff5916c
 
29f5a33
 
 
 
 
 
ff5916c
 
 
 
29f5a33
ff5916c
d6e445f
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
ff5916c
29f5a33
ff5916c
29f5a33
ff5916c
 
29f5a33
ff5916c
29f5a33
 
 
 
 
 
 
d6e445f
29f5a33
 
 
ff5916c
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b59c5e
29f5a33
ff5916c
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cee926
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff5916c
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
ff5916c
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b59c5e
 
 
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b59c5e
29f5a33
 
 
 
 
 
 
6b59c5e
 
 
29f5a33
 
ff5916c
 
6b59c5e
3c4e035
29f5a33
ff5916c
29f5a33
ff5916c
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff5916c
 
29f5a33
 
 
 
 
6b59c5e
29f5a33
 
 
 
 
 
 
ff5916c
29f5a33
 
 
 
 
 
 
b708f85
29f5a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
from __future__ import annotations

import base64
import json
import logging
import math
import os
import platform
import shutil
import subprocess
import tempfile
import threading
import time
import uuid
from datetime import datetime, timezone
from functools import lru_cache
from importlib import metadata
from pathlib import Path
from urllib.parse import quote

import cv2
import gradio as gr
import matplotlib
import numpy as np
import torch
import torch.nn as nn
from scipy.interpolate import interp1d
from scipy.signal import find_peaks

SCRIPT_DIR = Path(__file__).parent.resolve()


def resolve_runtime_log_dir() -> Path:
    configured_dir = os.getenv("USAGE_LOG_DIR") or os.getenv("LOG_DIR")
    if configured_dir:
        return Path(configured_dir).expanduser().resolve()
    data_dir = Path("/data")
    if data_dir.exists() and os.access(data_dir, os.W_OK):
        return data_dir / "rowing_validator_logs"
    return SCRIPT_DIR / "logs"


LOG_DIR = resolve_runtime_log_dir()
LOG_DIR.mkdir(parents=True, exist_ok=True)
USAGE_LOG_DIR = LOG_DIR / "usage"
USAGE_LOG_DIR.mkdir(parents=True, exist_ok=True)
USAGE_EVENTS_PATH = USAGE_LOG_DIR / "usage_events.jsonl"
USAGE_SUMMARY_PATH = USAGE_LOG_DIR / "usage_summary.json"
USAGE_LOG_LOCK = threading.Lock()
PROCESS_STOP_EVENT = threading.Event()
APP_STARTED_AT = datetime.now(timezone.utc).isoformat()

logging.basicConfig(
    level=getattr(logging, os.getenv("LOG_LEVEL", "INFO").upper(), logging.INFO),
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[
        logging.FileHandler(LOG_DIR / "app.log", encoding="utf-8"),
        logging.StreamHandler(),
    ],
)
logger = logging.getLogger(__name__)

FFMPEG_TIMEOUT_SECONDS = int(os.getenv("FFMPEG_TIMEOUT_SECONDS", "180"))

WEIGHT_DIR = SCRIPT_DIR / "Weight"
YOLO_MODEL_PATH = WEIGHT_DIR / "yolo11x-pose.pt"
DRIVE_MODEL_PATH = WEIGHT_DIR / "best_drive_ae_model.pt"
DRIVE_THRESHOLD_PATH = WEIGHT_DIR / "drive_threshold.npy"
RECOVERY_MODEL_PATH = WEIGHT_DIR / "best_recovery_ae_model.pt"
RECOVERY_THRESHOLD_PATH = WEIGHT_DIR / "recovery_threshold.npy"

KEYPOINT_NAMES = [
    "nose",
    "left_eye",
    "right_eye",
    "left_ear",
    "right_ear",
    "left_shoulder",
    "right_shoulder",
    "left_elbow",
    "right_elbow",
    "left_wrist",
    "right_wrist",
    "left_hip",
    "right_hip",
    "left_knee",
    "right_knee",
    "left_ankle",
    "right_ankle",
]

MODEL_KEYPOINT_NAMES = [
    "nose",
    "left_eye",
    "left_ear",
    "left_shoulder",
    "left_elbow",
    "left_wrist",
    "left_hip",
    "left_knee",
    "left_ankle",
]
MODEL_KEYPOINT_INDICES = [KEYPOINT_NAMES.index(name) for name in MODEL_KEYPOINT_NAMES]
MODEL_SKELETON = [
    (0, 1),
    (1, 2),
    (2, 3),
    (0, 3),
    (3, 4),
    (4, 5),
    (3, 6),
    (6, 7),
    (7, 8),
]

SKELETON = [
    (15, 13),
    (13, 11),
    (16, 14),
    (14, 12),
    (11, 12),
    (5, 11),
    (6, 12),
    (5, 6),
    (5, 7),
    (7, 9),
    (6, 8),
    (8, 10),
    (1, 2),
    (0, 1),
    (0, 2),
    (1, 3),
    (2, 4),
    (3, 5),
    (4, 6),
]

JOINT_COLOR = (255, 230, 120)
LINE_COLOR = (80, 220, 255)
TEXT_COLOR = (230, 240, 255)
MODEL_LINE_COLOR = (255, 100, 100)
MODEL_JOINT_COLOR = (255, 150, 150)
UPLOAD_WAIT_SECONDS = 60


USAGE_COUNTER_KEYS = {
    "page_visit": "page_visits",
    "video_upload": "video_uploads",
    "clip_created": "clips_created",
    "stickman_started": "stickman_runs_started",
    "stickman_completed": "stickman_runs_completed",
    "diagnosis_started": "diagnoses_started",
    "diagnosis_completed": "diagnoses_completed",
    "language_changed": "language_changes",
    "usage_refreshed": "usage_refreshes",
    "error": "errors",
}


def _default_usage_summary() -> dict:
    return {
        "app_started_at": APP_STARTED_AT,
        "first_event_at": None,
        "last_event_at": None,
        "total_events": 0,
        "page_visits": 0,
        "video_uploads": 0,
        "clips_created": 0,
        "stickman_runs_started": 0,
        "stickman_runs_completed": 0,
        "diagnoses_started": 0,
        "diagnoses_completed": 0,
        "language_changes": 0,
        "usage_refreshes": 0,
        "errors": 0,
    }


def read_usage_summary() -> dict:
    if not USAGE_SUMMARY_PATH.exists():
        return _default_usage_summary()
    try:
        with USAGE_SUMMARY_PATH.open("r", encoding="utf-8") as f:
            stored = json.load(f)
        summary = _default_usage_summary()
        summary.update(stored)
        return summary
    except Exception as exc:
        logger.warning("Could not read usage summary: %s", exc)
        return _default_usage_summary()


def write_usage_summary(summary: dict) -> None:
    tmp_path = USAGE_SUMMARY_PATH.with_suffix(".tmp")
    with tmp_path.open("w", encoding="utf-8") as f:
        json.dump(summary, f, ensure_ascii=False, indent=2)
    tmp_path.replace(USAGE_SUMMARY_PATH)


def log_usage_event(event_name: str, session_id: str | None = None, details: dict | None = None) -> None:
    timestamp = datetime.now(timezone.utc).isoformat()
    event = {
        "timestamp": timestamp,
        "event": event_name,
        "session_id": session_id,
        "details": details or {},
    }
    try:
        with USAGE_LOG_LOCK:
            with USAGE_EVENTS_PATH.open("a", encoding="utf-8") as f:
                f.write(json.dumps(event, ensure_ascii=False) + "\n")

            summary = read_usage_summary()
            summary["total_events"] = int(summary.get("total_events", 0)) + 1
            summary["first_event_at"] = summary.get("first_event_at") or timestamp
            summary["last_event_at"] = timestamp
            counter_key = USAGE_COUNTER_KEYS.get(event_name)
            if counter_key:
                summary[counter_key] = int(summary.get(counter_key, 0)) + 1
            write_usage_summary(summary)
    except Exception as exc:
        logger.warning("Could not write usage event '%s': %s", event_name, exc)


def _html_escape(value) -> str:
    return (
        str(value)
        .replace("&", "&")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
    )


def usage_storage_note() -> str:
    env_dir = os.getenv("USAGE_LOG_DIR") or os.getenv("LOG_DIR")
    if env_dir:
        return f"Persistent if this configured directory is mounted: {LOG_DIR}"
    if str(LOG_DIR).startswith("/data"):
        return f"Persistent Hugging Face storage: {LOG_DIR}"
    return f"Temporary runtime storage: {LOG_DIR}. Enable Space persistent storage or set USAGE_LOG_DIR for long-term retention."


def usage_summary_html() -> str:
    summary = read_usage_summary()
    metric_specs = [
        ("Visits", "page_visits"),
        ("Uploads", "video_uploads"),
        ("Clips", "clips_created"),
        ("Stickman Runs", "stickman_runs_completed"),
        ("Diagnoses", "diagnoses_completed"),
        ("Errors", "errors"),
    ]
    cards = "".join(
        f"""
        <div class="usage-card">
            <span>{label}</span>
            <strong>{int(summary.get(key, 0))}</strong>
        </div>
        """
        for label, key in metric_specs
    )
    return f"""
    <div class="usage-panel">
        <div class="usage-grid">{cards}</div>
        <div class="usage-note">
            <strong>Storage</strong>: {_html_escape(usage_storage_note())}<br/>
            <strong>Event log</strong>: {_html_escape(USAGE_EVENTS_PATH)}<br/>
            <strong>Summary</strong>: {_html_escape(USAGE_SUMMARY_PATH)}<br/>
            <strong>Last event</strong>: {_html_escape(summary.get("last_event_at") or "No events yet")}
        </div>
    </div>
    """


JOINT_DISPLAY_NAMES = {
    "nose": "鼻子",
    "left_eye": "左眼",
    "right_eye": "右眼",
    "left_ear": "左耳",
    "right_ear": "右耳",
    "left_shoulder": "左肩",
    "right_shoulder": "右肩",
    "shoulder": "肩部",
    "left_elbow": "左肘",
    "right_elbow": "右肘",
    "elbow": "肘部",
    "left_wrist": "左腕",
    "right_wrist": "右腕",
    "wrist": "手腕",
    "left_hip": "左髋",
    "right_hip": "右髋",
    "hip": "髋部",
    "left_knee": "左膝",
    "right_knee": "右膝",
    "knee": "膝盖",
    "left_ankle": "左踝",
    "right_ankle": "右踝",
    "ankle": "脚踝",
}


ROWING_ERROR_CATALOG = [
    {
        "error_id": "early_body_open",
        "error_name": "过早打开身体",
        "phase": "拉桨前期",
        "description": "Drive前20%身体提前后倒,影响蹬腿发力效率",
        "severity_levels": {
            "normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
            "low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
            "medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
            "high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
        },
    },
    {
        "error_id": "early_elbow_bend",
        "error_name": "曲臂过早",
        "phase": "拉桨前期",
        "description": "Drive前20%手肘提前弯曲,导致手臂先发力而非腿部",
        "severity_levels": {
            "normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
            "low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
            "medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
            "high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
        },
    },
    {
        "error_id": "shooting_slide",
        "error_name": "跑座板",
        "phase": "拉桨中期",
        "description": "Drive前40%座板速度明显快于手柄,导致力量浪费",
        "severity_levels": {
            "normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
            "low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
            "medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
            "high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
        },
    },
    {
        "error_id": "leg_recovery_issue",
        "error_name": "腿部回收异常",
        "phase": "回桨阶段",
        "description": "Recovery阶段膝盖回收动作异常(收腿过早/过晚/角度不对)",
        "severity_levels": {
            "normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
            "low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
            "medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
            "high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
        },
    },
    {
        "error_id": "excessive_layback",
        "error_name": "后仰过多",
        "phase": "出水阶段",
        "description": "Finish阶段躯干后倒角度过大,可能导致腰部压力",
        "severity_levels": {
            "normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
            "low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
            "medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
            "high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
        },
    },
    {
        "error_id": "knee_not_extended",
        "error_name": "膝盖未伸直",
        "phase": "出水阶段",
        "description": "Finish阶段膝盖未完全伸直,影响力量传递",
        "severity_levels": {
            "normal": {"threshold": 160, "color": "#6BCB77", "text": "正常"},
            "low": {"threshold": 150, "color": "#FFD93D", "text": "轻度"},
            "medium": {"threshold": 140, "color": "#FF9F43", "text": "中度"},
            "high": {"threshold": float("-inf"), "color": "#FF6B6B", "text": "重度"},
            "is_angle": True,
        },
    },
    {
        "error_id": "wavy_handle_path",
        "error_name": "手柄轨迹异常",
        "phase": "全程",
        "description": "手柄轨迹偏离直线,影响划桨效率",
        "severity_levels": {
            "normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
            "low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
            "medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
            "high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
        },
    },
    {
        "error_id": "catch_technique_issue",
        "error_name": "抓水技术问题",
        "phase": "抓水阶段",
        "description": "Catch阶段动作与标准模式偏差较大",
        "severity_levels": {
            "normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
            "low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
            "medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
            "high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
        },
    },
    {
        "error_id": "wrist_flexion",
        "error_name": "手腕折腕",
        "phase": "出水阶段",
        "description": "Finish阶段手腕过度伸展,影响握桨稳定性",
        "severity_levels": {
            "normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
            "low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
            "medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
            "high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
        },
    },
]


ERROR_LOCALIZATION = {
    "early_body_open": {
        "zh": {
            "name": "过早打开身体",
            "phase": "拉桨前期",
            "description": "Drive 前 20% 身体提前后倒,影响蹬腿发力效率。",
            "suggestion": "保持手臂放松伸直,先用腿推动脚踏,再让躯干逐步打开。",
        },
        "en": {
            "name": "Early Body Opening",
            "phase": "Early Drive",
            "description": "The trunk opens too early in the first 20% of the drive, reducing leg-drive efficiency.",
            "suggestion": "Keep the arms relaxed and long. Push with the legs first, then open the trunk progressively.",
        },
    },
    "early_elbow_bend": {
        "zh": {
            "name": "曲臂过早",
            "phase": "拉桨前期",
            "description": "Drive 前 20% 手肘提前弯曲,导致手臂先发力而非腿部主导。",
            "suggestion": "在蹬腿阶段保持手臂伸直,把手臂拉桨延后到身体打开之后。",
        },
        "en": {
            "name": "Early Elbow Bend",
            "phase": "Early Drive",
            "description": "The elbows bend too early in the first 20% of the drive, shifting load from legs to arms.",
            "suggestion": "Keep the arms straight during leg drive and delay the arm pull until after trunk opening.",
        },
    },
    "shooting_slide": {
        "zh": {
            "name": "跑座板",
            "phase": "拉桨中期",
            "description": "Drive 前 40% 座板速度明显快于手柄,导致力量传递效率下降。",
            "suggestion": "让手柄和座板同步移动,想象脚踏、髋部和手柄处在同一条发力链上。",
        },
        "en": {
            "name": "Shooting Slide",
            "phase": "Mid Drive",
            "description": "The seat moves faster than the handle in the first 40% of the drive, reducing force transfer.",
            "suggestion": "Synchronize seat and handle movement, keeping footplate, hips, and handle on one connected power chain.",
        },
    },
    "leg_recovery_issue": {
        "zh": {
            "name": "腿部回收异常",
            "phase": "回桨阶段",
            "description": "Recovery 阶段膝盖回收节奏或角度异常。",
            "suggestion": "按照手臂、身体、腿的顺序回桨,先让手柄越过膝盖,再逐步收腿。",
        },
        "en": {
            "name": "Leg Recovery Issue",
            "phase": "Recovery",
            "description": "The knee recovery timing or angle deviates from the expected recovery pattern.",
            "suggestion": "Recover in the arms-body-legs order. Let the handle pass the knees before gradually bending the legs.",
        },
    },
    "excessive_layback": {
        "zh": {
            "name": "后仰过多",
            "phase": "出水阶段",
            "description": "Finish 阶段躯干后倒角度过大,可能增加腰部压力。",
            "suggestion": "控制出水位置,保持核心稳定,躯干后仰以可控的小角度结束。",
        },
        "en": {
            "name": "Excessive Layback",
            "phase": "Finish",
            "description": "The trunk leans back excessively at the finish, which may increase lower-back stress.",
            "suggestion": "Control the finish position, keep the core stable, and finish with a smaller, controlled layback angle.",
        },
    },
    "knee_not_extended": {
        "zh": {
            "name": "膝盖未伸直",
            "phase": "出水阶段",
            "description": "Finish 阶段膝盖未充分伸展,影响力量传递。",
            "suggestion": "在身体明显打开和手臂发力前,优先完成腿部蹬伸。",
        },
        "en": {
            "name": "Incomplete Knee Extension",
            "phase": "Finish",
            "description": "The knees are not fully extended at the finish, limiting force transfer.",
            "suggestion": "Prioritize completing leg extension before the trunk opens strongly and the arms finish the stroke.",
        },
    },
    "wavy_handle_path": {
        "zh": {
            "name": "手柄轨迹异常",
            "phase": "全程",
            "description": "手柄轨迹偏离稳定路径,影响划桨效率。",
            "suggestion": "保持手柄路径平稳,出水和回桨时避免明显上下波动。",
        },
        "en": {
            "name": "Irregular Handle Path",
            "phase": "Full Stroke",
            "description": "The handle path deviates from a stable trajectory, reducing rowing efficiency.",
            "suggestion": "Keep the handle path smooth and avoid unnecessary vertical movement during finish and recovery.",
        },
    },
    "catch_technique_issue": {
        "zh": {
            "name": "抓水技术问题",
            "phase": "抓水阶段",
            "description": "Catch 阶段动作与参考模式偏差较大。",
            "suggestion": "在前端保持身体稳定、手臂自然伸展,先建立身体张力再启动蹬腿。",
        },
        "en": {
            "name": "Catch Technique Issue",
            "phase": "Catch",
            "description": "The catch position deviates from the learned reference movement pattern.",
            "suggestion": "Stay stable at the front end, keep the arms naturally extended, build body tension, then initiate leg drive.",
        },
    },
    "wrist_flexion": {
        "zh": {
            "name": "手腕折腕",
            "phase": "出水阶段",
            "description": "Finish 阶段手腕过度伸展或弯折,影响握桨稳定性。",
            "suggestion": "保持手腕中立,手柄由肘部和背部完成拉入,不要用手腕补动作。",
        },
        "en": {
            "name": "Wrist Flexion",
            "phase": "Finish",
            "description": "The wrist bends excessively at the finish, reducing handle stability.",
            "suggestion": "Keep the wrists neutral. Finish the handle draw with elbows and back rather than compensating with the wrists.",
        },
    },
}

SEVERITY_LOCALIZATION = {
    "zh": {"normal": "正常", "low": "轻度", "medium": "中度", "high": "重度"},
    "en": {"normal": "Normal", "low": "Low", "medium": "Medium", "high": "High"},
}


class LSTMAutoEncoder(nn.Module):
    def __init__(
        self,
        input_dim: int,
        hidden_dim: int,
        latent_dim: int,
        num_layers: int,
        dropout: float = 0.0,
    ) -> None:
        super().__init__()
        lstm_dropout = dropout if num_layers > 1 else 0.0
        self.encoder_lstm = nn.LSTM(
            input_dim,
            hidden_dim,
            num_layers,
            batch_first=True,
            dropout=lstm_dropout,
        )
        self.encoder_fc = nn.Linear(hidden_dim, latent_dim)
        self.decoder_fc = nn.Linear(latent_dim, hidden_dim)
        self.decoder_lstm = nn.LSTM(
            hidden_dim,
            hidden_dim,
            num_layers,
            batch_first=True,
            dropout=lstm_dropout,
        )
        self.output_layer = nn.Linear(hidden_dim, input_dim)

    def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        _, (hidden, _) = self.encoder_lstm(x)
        z = self.encoder_fc(hidden[-1])
        z_rep = z.unsqueeze(1).repeat(1, x.size(1), 1)
        decoded = self.decoder_fc(z_rep)
        decoded, _ = self.decoder_lstm(decoded)
        recon = self.output_layer(decoded)
        return recon, z


def choose_device() -> torch.device:
    if torch.backends.mps.is_available():
        return torch.device("mps")
    if torch.cuda.is_available():
        return torch.device("cuda")
    return torch.device("cpu")


def choose_ae_device() -> torch.device:
    # The autoencoder is lightweight; keep it on CPU in Spaces to reduce memory use.
    force_cpu_default = bool(os.getenv("SPACE_ID"))
    if env_flag("ROWING_AE_FORCE_CPU", force_cpu_default):
        return torch.device("cpu")
    return choose_device()


def get_yolo_device() -> str:
    """YOLO 设备字符串: 'mps' / '0' (cuda) / 'cpu'"""
    if torch.backends.mps.is_available():
        return "mps"
    if torch.cuda.is_available():
        return "0"
    return "cpu"


def env_flag(name: str, default: bool) -> bool:
    raw = os.getenv(name)
    if raw is None:
        return default
    return raw.strip().lower() in {"1", "true", "yes", "on"}


def env_int(name: str, default: int, minimum: int | None = None) -> int:
    try:
        value = int(os.getenv(name, str(default)))
    except (TypeError, ValueError):
        value = default
    if minimum is not None:
        value = max(minimum, value)
    return value


def cpu_fast_mode_enabled() -> bool:
    default = bool(os.getenv("SPACE_ID")) or get_yolo_device() == "cpu"
    return env_flag("ROWING_CPU_FAST_MODE", default)


def configure_cpu_runtime() -> None:
    torch_threads = env_int("ROWING_TORCH_THREADS", min(4, max(1, os.cpu_count() or 1)), 1)
    try:
        torch.set_num_threads(torch_threads)
    except Exception as exc:
        logger.warning("Could not set torch CPU threads: %s", exc)
    try:
        cv2.setNumThreads(0)
    except Exception as exc:
        logger.warning("Could not set OpenCV CPU threads: %s", exc)


def package_version(package_name: str) -> str:
    try:
        return metadata.version(package_name)
    except metadata.PackageNotFoundError:
        return "not installed"


def log_runtime_versions() -> None:
    logger.info(
        "Runtime versions: gradio=%s torch=%s torchvision=%s ultralytics=%s opencv=%s numpy=%s scipy=%s matplotlib=%s",
        package_version("gradio"),
        package_version("torch"),
        package_version("torchvision"),
        package_version("ultralytics"),
        cv2.__version__,
        np.__version__,
        package_version("scipy"),
        package_version("matplotlib"),
    )
    logger.info(
        "Runtime hardware: yolo_device=%s torch_threads=%s cpu_count=%s space_id=%s",
        get_yolo_device(),
        torch.get_num_threads(),
        os.cpu_count(),
        os.getenv("SPACE_ID", ""),
    )


def first_existing_index(names: list[str], candidates: list[str]) -> int | None:
    for candidate in candidates:
        if candidate in names:
            return names.index(candidate)
    return None


@lru_cache(maxsize=1)
def load_yolo_model():
    if not YOLO_MODEL_PATH.exists():
        raise FileNotFoundError(f"Missing YOLO model: {YOLO_MODEL_PATH}")
    from ultralytics import YOLO
    return YOLO(str(YOLO_MODEL_PATH))


def load_ae_model(model_path: Path, threshold_path: Path):
    device = choose_ae_device()
    logger.info("Loading AE model %s on device=%s", model_path.name, device)
    checkpoint = torch.load(str(model_path), map_location=device, weights_only=False)
    raw_config = checkpoint.get("config") or {}
    config = {
        "input_dim": int(checkpoint.get("input_dim", raw_config.get("input_dim", 18))),
        "hidden_dim": int(raw_config.get("hidden_dim", 96)),
        "latent_dim": int(raw_config.get("latent_dim", 24)),
        "num_layers": int(raw_config.get("num_layers", 2)),
        "dropout": float(raw_config.get("dropout", 0.0)),
        "target_len": int(raw_config.get("target_len", 100)),
        "phase_filter": raw_config.get("phase_filter", "drive"),
    }
    model = LSTMAutoEncoder(
        input_dim=config["input_dim"],
        hidden_dim=config["hidden_dim"],
        latent_dim=config["latent_dim"],
        num_layers=config["num_layers"],
        dropout=config["dropout"],
    ).to(device)
    model.load_state_dict(checkpoint["model_state_dict"])
    model.eval()
    threshold = float(np.load(str(threshold_path)))
    return model, config, threshold, device


def readable_seconds(seconds: float) -> str:
    if seconds < 60:
        return f"{seconds:.1f}s"
    minutes = int(seconds // 60)
    remain = seconds - minutes * 60
    return f"{minutes}m {remain:.0f}s"


def progress_description(done: int, total: int | None, start_time: float) -> tuple[float, str]:
    elapsed = max(0.0, time.time() - start_time)
    if total and total > 0:
        pct = min(1.0, float(done) / float(total))
        if done > 0 and pct > 0:
            estimated_total = elapsed / pct
            remaining = max(0.0, estimated_total - elapsed)
            eta_text = readable_seconds(remaining)
        else:
            eta_text = "calculating"
        desc = (
            f"Processing frame {done}/{total} - {pct * 100:.1f}% | "
            f"elapsed {readable_seconds(elapsed)} | ETA {eta_text}"
        )
        return pct, desc

    desc = f"Processing frame {done} | elapsed {readable_seconds(elapsed)}"
    return 0.0, desc


def encode_browser_mp4(input_path: Path, output_path: Path, fps: float) -> Path:
    ffmpeg = shutil.which("ffmpeg")
    if ffmpeg is None:
        print("FFmpeg not found; returning OpenCV mp4v output.", flush=True)
        return input_path

    cmd = [
        ffmpeg,
        "-y",
        "-i",
        str(input_path),
        "-r",
        f"{fps:.6f}",
        "-c:v",
        "libx264",
        "-preset",
        "veryfast",
        "-pix_fmt",
        "yuv420p",
        "-movflags",
        "+faststart",
        str(output_path),
    ]
    try:
        subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    except subprocess.CalledProcessError as exc:
        print(f"FFmpeg encode failed; returning OpenCV mp4v output. {exc.stderr[-800:]}", flush=True)
        return input_path
    return output_path if output_path.exists() and output_path.stat().st_size > 0 else input_path


@lru_cache(maxsize=8)
def ffmpeg_encoder_available(encoder_name: str) -> bool:
    ffmpeg = shutil.which("ffmpeg")
    if ffmpeg is None:
        return False
    try:
        result = subprocess.run(
            [ffmpeg, "-hide_banner", "-encoders"],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=10,
        )
    except Exception:
        return False
    return encoder_name in result.stdout


def run_ffmpeg_command(cmd: list[str], label: str) -> subprocess.CompletedProcess:
    logger.debug("%s command: %s", label, " ".join(cmd))
    return subprocess.run(
        cmd,
        check=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        timeout=FFMPEG_TIMEOUT_SECONDS,
    )


def ffmpeg_clip(input_path: Path, output_path: Path, start_sec: float, end_sec: float | None) -> Path:
    ffmpeg = shutil.which("ffmpeg")
    if ffmpeg is None:
        logger.error("FFmpeg not found in system path")
        raise gr.Error("FFmpeg is required to create a monitored clip.")

    logger.info(f"Starting ffmpeg clip: input={input_path}, output={output_path}, start_sec={start_sec:.3f}, end_sec={end_sec}")
    
    if not input_path.exists():
        logger.error(f"Input file does not exist: {input_path}")
        raise gr.Error(f"Input file not found: {input_path.name}")
    
    if input_path.stat().st_size == 0:
        logger.error(f"Input file is empty: {input_path}")
        raise gr.Error(f"Input file is empty: {input_path.name}")

    base_cmd = [ffmpeg, "-y", "-ss", f"{max(0.0, start_sec):.3f}", "-i", str(input_path)]
    if end_sec is not None and end_sec > start_sec:
        duration = end_sec - start_sec
        logger.info(f"Clipping with duration: {duration:.3f}s")
    else:
        duration = None
        logger.info("Clipping from start to end of video")

    fast_cmd = [*base_cmd]
    if duration is not None:
        fast_cmd.extend(["-t", f"{duration:.3f}"])
    fast_cmd.extend([
        "-map",
        "0:v:0",
        "-an",
        "-c:v",
        "copy",
        "-avoid_negative_ts",
        "make_zero",
        "-movflags",
        "+faststart",
        str(output_path),
    ])

    try:
        result = run_ffmpeg_command(fast_cmd, "FFmpeg fast clip")
        logger.info(f"FFmpeg fast clip completed successfully. stdout={result.stdout[:500]}")
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
        if output_path.exists():
            output_path.unlink(missing_ok=True)
        stderr = getattr(exc, "stderr", "") or ""
        logger.warning("FFmpeg fast clip failed; falling back to re-encode. %s", stderr[-800:])
        encode_cmd = [*base_cmd]
        if duration is not None:
            encode_cmd.extend(["-t", f"{duration:.3f}"])
        if platform.system() == "Darwin" and ffmpeg_encoder_available("h264_videotoolbox"):
            encode_cmd.extend(["-an", "-c:v", "h264_videotoolbox", "-b:v", "5000k", "-pix_fmt", "yuv420p"])
        else:
            encode_cmd.extend(["-an", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p"])
        encode_cmd.extend(["-movflags", "+faststart", str(output_path)])
        try:
            result = run_ffmpeg_command(encode_cmd, "FFmpeg re-encode clip")
            logger.info(f"FFmpeg re-encode completed successfully. stdout={result.stdout[:500]}")
        except subprocess.TimeoutExpired:
            logger.error("FFmpeg clip timed out after %ss", FFMPEG_TIMEOUT_SECONDS)
            raise gr.Error(
                "Video clipping timed out. Try a shorter clip, reduce the video resolution, or install Homebrew FFmpeg."
            )
        except subprocess.CalledProcessError as reencode_exc:
            logger.error(f"FFmpeg clip failed with exit code {reencode_exc.returncode}")
            logger.error(f"FFmpeg stderr: {reencode_exc.stderr}")
            raise gr.Error(f"Could not create the monitored clip. FFmpeg error: {reencode_exc.stderr[-500:]}")

    if not output_path.exists():
        logger.error(f"Output file was not created: {output_path}")
        raise gr.Error("The monitored clip was not created. Please check the start/end time.")
    
    if output_path.stat().st_size == 0:
        logger.error(f"Output file is empty: {output_path}")
        raise gr.Error("The monitored clip was empty. Please check the start/end time.")
    
    logger.info(f"Clip created successfully: {output_path}, size={output_path.stat().st_size/1024:.2f} KB")
    return output_path


def resolve_uploaded_video_path(video_input) -> Path | None:
    logger.debug(f"resolve_uploaded_video_path called with type={type(video_input).__name__}, value={video_input}")
    
    if video_input is None:
        logger.debug("video_input is None, returning None")
        return None
        
    if isinstance(video_input, (str, Path)):
        result = Path(video_input)
        logger.debug(f"video_input is str/Path, returning: {result}")
        return result
        
    if isinstance(video_input, dict):
        path = video_input.get("path") or video_input.get("name")
        result = Path(path) if path else None
        logger.debug(f"video_input is dict, keys={list(video_input.keys())}, path={path}, returning: {result}")
        return result
        
    if isinstance(video_input, (tuple, list)) and video_input:
        logger.debug(f"video_input is tuple/list, recursing on first element")
        return resolve_uploaded_video_path(video_input[0])
        
    path = getattr(video_input, "path", None) or getattr(video_input, "name", None)
    result = Path(path) if path else None
    logger.debug(f"video_input is object, path attr={path}, returning: {result}")
    return result


def smooth_keypoints(buffer: list[np.ndarray], keypoints: np.ndarray, window_size: int) -> np.ndarray:
    if window_size <= 1:
        return keypoints
    buffer.append(keypoints.copy())
    del buffer[:-window_size]
    stacked = np.stack(buffer, axis=0)
    smoothed = keypoints.copy()
    smoothed[:, :2] = stacked[:, :, :2].mean(axis=0)
    smoothed[:, 2] = stacked[:, :, 2].mean(axis=0)
    return smoothed


def draw_person(
    canvas: np.ndarray,
    keypoints: np.ndarray,
    point_conf: float,
    line_width: int,
    line_color=LINE_COLOR,
    joint_color=JOINT_COLOR,
    skeleton=None,
):
    points = keypoints[:, :2]
    confs = keypoints[:, 2]
    for a, b in (skeleton or SKELETON):
        if confs[a] < point_conf or confs[b] < point_conf:
            continue
        pa = tuple(np.round(points[a]).astype(int))
        pb = tuple(np.round(points[b]).astype(int))
        cv2.line(canvas, pa, pb, line_color, line_width, lineType=cv2.LINE_AA)
    radius = max(3, line_width + 2)
    for idx, (x, y) in enumerate(points):
        if confs[idx] < point_conf:
            continue
        cv2.circle(canvas, (int(round(x)), int(round(y))), radius, joint_color, -1, lineType=cv2.LINE_AA)


def draw_overlay_people(
    canvas: np.ndarray,
    people_keypoints: list[np.ndarray],
    point_conf: float,
    line_width: int,
    status_text: str,
) -> None:
    for keypoints in people_keypoints:
        draw_person(canvas, keypoints, point_conf, line_width + 4, (5, 8, 12), (5, 8, 12))
        draw_person(canvas, keypoints, point_conf, line_width)
    cv2.putText(canvas, status_text, (18, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.85, (5, 8, 12), 5, cv2.LINE_AA)
    cv2.putText(canvas, status_text, (18, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.85, TEXT_COLOR, 2, cv2.LINE_AA)


def normalize_cycle(cycle: np.ndarray, keypoint_names: list[str], target_len: int) -> np.ndarray:
    xy = cycle[:, :, :2].astype(np.float32)
    
    ankle = first_existing_index(keypoint_names, ["left_ankle", "right_ankle", "ankle"])
    left_hip = first_existing_index(keypoint_names, ["left_hip", "hip"])
    right_hip = first_existing_index(keypoint_names, ["right_hip"])
    
    if ankle is not None:
        origin = xy[:, ankle]
    elif left_hip is not None and right_hip is not None:
        origin = (xy[:, left_hip] + xy[:, right_hip]) / 2.0
    elif left_hip is not None:
        origin = xy[:, left_hip]
    else:
        origin = xy.mean(axis=1)

    centered = xy - origin[:, None, :]

    nose = first_existing_index(keypoint_names, ["nose", "head"])
    shoulder = first_existing_index(keypoint_names, ["left_shoulder", "right_shoulder", "shoulder"])
    hip = left_hip if left_hip is not None else right_hip

    scale_values = None
    if nose is not None and ankle is not None:
        scale_values = np.linalg.norm(centered[:, nose] - centered[:, ankle], axis=1)
    elif shoulder is not None and ankle is not None:
        scale_values = np.linalg.norm(centered[:, shoulder] - centered[:, ankle], axis=1)
    elif shoulder is not None and hip is not None:
        scale_values = np.linalg.norm(centered[:, shoulder] - centered[:, hip], axis=1)
    if scale_values is None:
        scale_values = np.linalg.norm(centered, axis=2).max(axis=1)

    scale = float(np.nanmedian(scale_values[scale_values > 1e-6])) if np.any(scale_values > 1e-6) else 1.0
    normalized = centered / scale

    t_orig = np.linspace(0, 1, normalized.shape[0])
    t_new = np.linspace(0, 1, target_len)
    interpolated = np.zeros((target_len, normalized.shape[1], 2), dtype=np.float32)
    for joint_idx in range(normalized.shape[1]):
        for axis in range(2):
            interpolator = interp1d(t_orig, normalized[:, joint_idx, axis], kind="linear", fill_value="extrapolate")
            interpolated[:, joint_idx, axis] = interpolator(t_new)
    return interpolated.reshape(target_len, -1)


def compute_angle(a: np.ndarray, b: np.ndarray, c: np.ndarray) -> float:
    ab = a - b
    bc = c - b
    cos_angle = np.dot(ab, bc) / (np.linalg.norm(ab) * np.linalg.norm(bc) + 1e-8)
    cos_angle = np.clip(cos_angle, -1.0, 1.0)
    return np.degrees(np.arccos(cos_angle))


def compute_torso_angle(shoulder: np.ndarray, hip: np.ndarray) -> float:
    torso_vec = shoulder - hip
    vertical_vec = np.array([0, -1])
    cos_angle = np.dot(torso_vec, vertical_vec) / (np.linalg.norm(torso_vec) + 1e-8)
    cos_angle = np.clip(cos_angle, -1.0, 1.0)
    angle = np.degrees(np.arccos(cos_angle))
    if torso_vec[0] > 0:
        angle = -angle
    return angle


def compute_knee_angle(hip: np.ndarray, knee: np.ndarray, ankle: np.ndarray) -> float:
    return compute_angle(hip, knee, ankle)


def diagnose_rowing_technique(
    pose: np.ndarray,
    keypoint_names: list[str],
    num_frames: int,
    reconstruction: np.ndarray | None = None,
    joint_frame_mse: np.ndarray | None = None,
    cycle_mse: float | None = None,
    mse_threshold: float | None = None,
    score: float | None = None,
) -> list[dict]:
    diagnoses = []
    
    def get_joint_idx(name_keyword: str) -> int:
        for idx, name in enumerate(keypoint_names):
            if name_keyword in name.lower():
                return idx
        return -1
    
    wrist_idx = get_joint_idx("wrist")
    elbow_idx = get_joint_idx("elbow")
    shoulder_idx = get_joint_idx("shoulder")
    hip_idx = get_joint_idx("hip")
    knee_idx = get_joint_idx("knee")
    ankle_idx = get_joint_idx("ankle")
    
    if wrist_idx < 0 or shoulder_idx < 0 or hip_idx < 0:
        return diagnoses
    
    torso_angles = np.array([
        compute_torso_angle(pose[i, shoulder_idx], pose[i, hip_idx])
        for i in range(num_frames)
    ])
    
    joint_errors = None
    avg_error = 0
    if reconstruction is not None and joint_frame_mse is not None:
        joint_errors = np.mean(joint_frame_mse, axis=0)
        avg_error = np.mean(joint_errors) if len(joint_errors) > 0 else 0
    score_value = float(score) if score is not None else None
    mse_threshold_value = float(mse_threshold or 0.0)
    
    recovery_start = int(0.75 * num_frames)
    drive_end = int(0.40 * num_frames)
    finish_start = int(0.85 * num_frames)
    catch_end = int(0.10 * num_frames)
    drive_early_end = int(0.20 * num_frames)
    
    def determine_severity(error_ratio: float, catalog_item: dict) -> str:
        levels = catalog_item["severity_levels"]
        is_angle = levels.get("is_angle", False)
        
        if is_angle:
            angle_value = error_ratio
            if angle_value >= levels["normal"]["threshold"]:
                return "normal"
            elif angle_value >= levels["low"]["threshold"]:
                return "low"
            elif angle_value >= levels["medium"]["threshold"]:
                return "medium"
            else:
                return "high"
        else:
            if error_ratio < levels["normal"]["threshold"]:
                return "normal"
            elif error_ratio < levels["low"]["threshold"]:
                return "low"
            elif error_ratio < levels["medium"]["threshold"]:
                return "medium"
            else:
                return "high"

    def moderate_severity(raw_severity: str, local_abs_error: float) -> str:
        if raw_severity in ("normal", "low"):
            return raw_severity

        joint_exceeds_threshold = mse_threshold_value > 0 and local_abs_error > mse_threshold_value
        joint_strongly_exceeds = mse_threshold_value > 0 and local_abs_error > mse_threshold_value * 2.0
        low_score = score_value is not None and score_value < 70.0
        very_low_score = score_value is not None and score_value < 55.0

        if raw_severity == "high":
            if very_low_score or joint_strongly_exceeds:
                return "high"
            if low_score or joint_exceeds_threshold:
                return "medium"
            return "low"

        if raw_severity == "medium":
            if low_score or joint_exceeds_threshold:
                return "medium"
            return "low"

        return raw_severity
    
    for catalog_item in ROWING_ERROR_CATALOG:
        error_id = catalog_item["error_id"]
        error_name = catalog_item["error_name"]
        phase = catalog_item["phase"]
        description = catalog_item["description"]
        
        error_ratio = 1.0
        local_abs_error = 0.0
        evidence = ""
        
        try:
            if error_id == "early_body_open":
                if drive_early_end > 0 and joint_errors is not None:
                    early_error = np.mean(joint_frame_mse[:drive_early_end, [shoulder_idx, hip_idx]]) if hip_idx < len(joint_errors) else 0
                    local_abs_error = float(early_error)
                    error_ratio = early_error / (avg_error + 1e-8)
                    early_torso_angle = np.mean(torso_angles[:drive_early_end])
                    evidence = f"躯干角度{early_torso_angle:.1f}°,上半身误差比{error_ratio:.2f}倍"
                
            elif error_id == "early_elbow_bend":
                if joint_errors is not None and elbow_idx >= 0 and elbow_idx < len(joint_errors):
                    local_abs_error = float(joint_errors[elbow_idx])
                    error_ratio = joint_errors[elbow_idx] / (avg_error + 1e-8)
                    evidence = f"手肘误差比{error_ratio:.2f}倍"
                
            elif error_id == "shooting_slide":
                if joint_errors is not None and drive_end > 0 and wrist_idx < len(joint_errors):
                    wrist_vx = np.abs(np.gradient(pose[:drive_end, wrist_idx, 0]))
                    hip_vx = np.abs(np.gradient(pose[:drive_end, hip_idx, 0]))
                    valid_mask = (wrist_vx > 0.001) & (hip_vx > 0.001)
                    if np.any(valid_mask):
                        speed_ratio = np.mean(hip_vx[valid_mask] / wrist_vx[valid_mask])
                        local_abs_error = float(avg_error)
                        error_ratio = speed_ratio / 1.5
                        evidence = f"座板速度是手柄的{speed_ratio:.2f}倍"
                    else:
                        evidence = "速度数据不足"
                
            elif error_id == "leg_recovery_issue":
                if joint_errors is not None and knee_idx >= 0 and knee_idx < len(joint_errors) and recovery_start < num_frames:
                    knee_error = np.mean(joint_frame_mse[recovery_start:, knee_idx])
                    local_abs_error = float(knee_error)
                    error_ratio = knee_error / (avg_error + 1e-8)
                    evidence = f"膝盖误差比{error_ratio:.2f}倍"
                
            elif error_id == "excessive_layback":
                if finish_start < num_frames and joint_errors is not None:
                    finish_error = np.mean(joint_frame_mse[finish_start:, [shoulder_idx, hip_idx]]) if hip_idx < len(joint_errors) else 0
                    local_abs_error = float(finish_error)
                    error_ratio = finish_error / (avg_error + 1e-8)
                    finish_torso_angle = np.mean(torso_angles[finish_start:])
                    evidence = f"躯干后仰{finish_torso_angle:.1f}°,上半身误差比{error_ratio:.2f}倍"
                
            elif error_id == "knee_not_extended":
                if knee_idx >= 0 and ankle_idx >= 0 and finish_start < num_frames:
                    knee_angles = np.array([
                        compute_knee_angle(pose[i, hip_idx], pose[i, knee_idx], pose[i, ankle_idx])
                        for i in range(num_frames)
                    ])
                    finish_knee_angle = np.mean(knee_angles[finish_start:])
                    if joint_frame_mse is not None and knee_idx < joint_frame_mse.shape[1]:
                        local_abs_error = float(np.mean(joint_frame_mse[finish_start:, knee_idx]))
                    error_ratio = finish_knee_angle
                    evidence = f"膝盖角度{finish_knee_angle:.1f}°"
                
            elif error_id == "wavy_handle_path":
                if joint_errors is not None and wrist_idx < len(joint_errors):
                    local_abs_error = float(joint_errors[wrist_idx])
                    error_ratio = joint_errors[wrist_idx] / (avg_error + 1e-8)
                    evidence = f"手腕误差比{error_ratio:.2f}倍"
                
            elif error_id == "catch_technique_issue":
                if catch_end > 0 and joint_frame_mse is not None:
                    catch_error = np.mean(joint_frame_mse[:catch_end])
                    local_abs_error = float(catch_error)
                    error_ratio = catch_error / (avg_error + 1e-8) if avg_error > 0 else 1.0
                    evidence = f"抓水误差比{error_ratio:.2f}倍"
                
            elif error_id == "wrist_flexion":
                if joint_errors is not None and wrist_idx < len(joint_errors) and finish_start < num_frames:
                    wrist_error = np.mean(joint_frame_mse[finish_start:, wrist_idx])
                    local_abs_error = float(wrist_error)
                    error_ratio = wrist_error / (avg_error + 1e-8)
                    evidence = f"手腕误差比{error_ratio:.2f}倍"
        except Exception:
            error_ratio = 1.0
            local_abs_error = 0.0
            evidence = "检测失败"
        
        severity = moderate_severity(determine_severity(error_ratio, catalog_item), local_abs_error)
        severity_info = catalog_item["severity_levels"][severity]
        
        diagnoses.append({
            "error_id": error_id,
            "error_name": error_name,
            "phase": phase,
            "description": description,
            "suggestion": ERROR_LOCALIZATION.get(error_id, {}).get("zh", {}).get("suggestion", ""),
            "severity": severity,
            "severity_text": severity_info["text"],
            "severity_color": severity_info["color"],
            "evidence": evidence,
            "local_mse": float(local_abs_error),
            "cycle_mse": float(cycle_mse or 0.0),
            "threshold": float(mse_threshold_value),
        })
    
    return diagnoses


def detect_cycles(wrist_x: np.ndarray, fps: float = 30.0) -> list[tuple[int, int, str]]:
    wrist_x = np.asarray(wrist_x, dtype=np.float32)
    n = len(wrist_x)
    if n < 8 or np.nanmax(wrist_x) - np.nanmin(wrist_x) < 1e-6:
        return []

    window_size = max(5, min(21, n // 12))
    if window_size % 2 == 0:
        window_size += 1
    kernel = np.ones(window_size, dtype=np.float32) / window_size
    smoothed = np.convolve(wrist_x, kernel, mode="same")
    half = window_size // 2
    smoothed[:half] = wrist_x[:half]
    smoothed[-half:] = wrist_x[-half:]

    amplitude = float(np.ptp(smoothed))
    fps = max(1.0, float(fps or 30.0))
    min_segment_frames = max(4, int(round(env_int("ROWING_MIN_PHASE_MS", 450, 100) / 1000.0 * fps)))
    max_segment_frames = max(min_segment_frames + 2, int(round(env_int("ROWING_MAX_PHASE_MS", 2800, 600) / 1000.0 * fps)))
    min_motion_ratio = float(os.getenv("ROWING_MIN_PHASE_MOTION_RATIO", "0.18"))
    min_motion_px = max(float(os.getenv("ROWING_MIN_PHASE_MOTION_PX", "8")), amplitude * min_motion_ratio)
    distance = max(3, min_segment_frames // 2)
    prominence = max(amplitude * 0.055, min_motion_px * 0.25, 0.5)
    max_peaks, _ = find_peaks(smoothed, distance=distance, prominence=prominence)
    min_peaks, _ = find_peaks(-smoothed, distance=distance, prominence=prominence)

    extrema = [(int(idx), "max") for idx in max_peaks] + [(int(idx), "min") for idx in min_peaks]
    edge_span = max(3, min(distance, n // 8))
    start_kind = "min" if smoothed[0] <= smoothed[edge_span] else "max"
    end_kind = "min" if smoothed[-1] <= smoothed[-1 - edge_span] else "max"
    extrema.extend([(0, start_kind), (n - 1, end_kind)])
    extrema.sort(key=lambda item: item[0])
    if len(extrema) < 2:
        return []

    filtered: list[tuple[int, str]] = []
    for idx, kind in extrema:
        if not filtered:
            filtered.append((idx, kind))
            continue
        prev_idx, prev_kind = filtered[-1]
        if kind != prev_kind:
            if idx - prev_idx >= max(2, distance // 4) or idx in (0, n - 1) or prev_idx in (0, n - 1):
                filtered.append((idx, kind))
            continue
        prev_val = smoothed[prev_idx]
        cur_val = smoothed[idx]
        keep_current = (kind == "max" and cur_val > prev_val) or (kind == "min" and cur_val < prev_val)
        if keep_current:
            filtered[-1] = (idx, kind)

    def segment_motion(start: int, end: int) -> float:
        if end <= start:
            return 0.0
        return float(abs(smoothed[end] - smoothed[start]))

    def split_long_segment(start: int, end: int, start_kind: str, end_kind: str) -> list[tuple[int, int, str, str]]:
        if end - start <= max_segment_frames:
            return [(start, end, start_kind, end_kind)]
        inner = [(idx, kind) for idx, kind in filtered if start < idx < end]
        if not inner:
            return []
        points = [(start, start_kind)] + inner + [(end, end_kind)]
        pieces = []
        for (piece_start, piece_start_kind), (piece_end, piece_end_kind) in zip(points, points[1:]):
            if piece_end - piece_start >= min_segment_frames:
                pieces.append((piece_start, piece_end, piece_start_kind, piece_end_kind))
        return pieces

    candidates = []
    for (start, start_kind), (end, end_kind) in zip(filtered, filtered[1:]):
        candidates.extend(split_long_segment(int(start), int(end), start_kind, end_kind))

    ranges = []
    drive_count = 0
    recovery_count = 0
    rejected_short = 0
    rejected_long = 0
    rejected_motion = 0
    for start, end, start_kind, end_kind in candidates:
        length = end - start
        motion = segment_motion(start, end)
        if length < min_segment_frames:
            rejected_short += 1
            continue
        if length > max_segment_frames:
            rejected_long += 1
            continue
        if motion < min_motion_px:
            rejected_motion += 1
            continue
        if start_kind == "min" and end_kind == "max":
            drive_count += 1
            ranges.append((int(start), int(end), f"cycle{drive_count}_drive"))
        elif start_kind == "max" and end_kind == "min":
            recovery_count += 1
            ranges.append((int(start), int(end), f"cycle{recovery_count}_recovery"))

    logger.info(
        "Cycle detection: frames=%s fps=%.2f amplitude=%.2f min_len=%s max_len=%s min_motion=%.2f extrema=%s ranges=%s rejected_short=%s rejected_long=%s rejected_motion=%s",
        n,
        fps,
        amplitude,
        min_segment_frames,
        max_segment_frames,
        min_motion_px,
        len(filtered),
        len(ranges),
        rejected_short,
        rejected_long,
        rejected_motion,
    )
    return ranges


def extract_model_keypoints(keypoints_17: np.ndarray) -> np.ndarray:
    keypoints_17 = np.asarray(keypoints_17, dtype=np.float32)
    if keypoints_17.shape[0] == len(MODEL_KEYPOINT_NAMES):
        return keypoints_17.copy()
    if keypoints_17.shape[0] < len(KEYPOINT_NAMES):
        padded = np.zeros((len(KEYPOINT_NAMES), 3), dtype=np.float32)
        padded[: keypoints_17.shape[0], : keypoints_17.shape[1]] = keypoints_17
        keypoints_17 = padded
    return keypoints_17[MODEL_KEYPOINT_INDICES].copy()


def prepare_wrist_signal(wrist_x_values: list[float]) -> np.ndarray:
    wrist_x = np.asarray(wrist_x_values, dtype=np.float32)
    valid = np.isfinite(wrist_x)
    if np.any(valid):
        valid_idx = np.flatnonzero(valid)
        return np.interp(np.arange(len(wrist_x)), valid_idx, wrist_x[valid_idx]).astype(np.float32)
    return np.zeros(len(wrist_x), dtype=np.float32)


def fallback_cycles(frame_numbers: list[int]) -> list[tuple[int, int, str]]:
    if len(frame_numbers) < 2:
        return []
    mid = len(frame_numbers) // 2
    if mid <= 0 or mid >= len(frame_numbers):
        return [(int(frame_numbers[0]), int(frame_numbers[-1]), "cycle1_drive")]
    return [
        (int(frame_numbers[0]), int(frame_numbers[mid]), "cycle1_drive"),
        (int(frame_numbers[mid]), int(frame_numbers[-1]), "cycle1_recovery"),
    ]


def fill_missing_keypoints(sequence: list[np.ndarray]) -> list[np.ndarray]:
    filled = []
    last_valid = None
    zero_pose = np.zeros((len(KEYPOINT_NAMES), 3), dtype=np.float32)
    for keypoints in sequence:
        keypoints = np.asarray(keypoints, dtype=np.float32)
        if keypoints.shape != zero_pose.shape:
            keypoints = zero_pose.copy()
        is_valid = bool(np.any(keypoints[:, 2] > 0.05))
        if is_valid:
            last_valid = keypoints.copy()
            filled.append(keypoints.copy())
        elif last_valid is not None:
            filled.append(last_valid.copy())
        else:
            filled.append(zero_pose.copy())
    return filled


def make_mse_plot(mse_state, frame_idx=0):
    if not mse_state:
        return None
    matplotlib.use("Agg")
    matplotlib.rcParams["font.sans-serif"] = [
        "PingFang SC",
        "Arial Unicode MS",
        "Heiti TC",
        "Noto Sans CJK SC",
        "DejaVu Sans",
    ]
    matplotlib.rcParams["axes.unicode_minus"] = False
    from matplotlib.figure import Figure

    frame_errors = np.asarray(mse_state.get("frame_errors", []), dtype=np.float32)
    joint_frame_mse = np.asarray(mse_state.get("joint_frame_mse", []), dtype=np.float32)
    keypoint_names = mse_state.get("keypoint_names", MODEL_KEYPOINT_NAMES)
    threshold = float(mse_state.get("threshold", 0.0))
    label = mse_state.get("label", "cycle")
    if frame_errors.size == 0 or joint_frame_mse.size == 0:
        return None

    frame_idx = max(0, min(int(frame_idx or 0), len(frame_errors) - 1))
    x = np.arange(len(frame_errors))
    fig = Figure(figsize=(11, 5.8), dpi=140, constrained_layout=True)
    ax = fig.subplots()
    ax.plot(x, frame_errors, color="#111827", linewidth=2.4, label="Total MSE", zorder=4)
    palette = ["#2563eb", "#059669", "#d97706", "#7c3aed", "#dc2626", "#0891b2", "#be123c", "#65a30d", "#9333ea"]
    for idx, name in enumerate(keypoint_names):
        label_name = name.replace("_", " ").title()
        ax.plot(x, joint_frame_mse[:, idx], linewidth=1.2, alpha=0.78, color=palette[idx % len(palette)], label=label_name)
        ax.scatter([frame_idx], [joint_frame_mse[frame_idx, idx]], s=16, color=palette[idx % len(palette)], zorder=5)
    ax.scatter([frame_idx], [frame_errors[frame_idx]], s=38, color="#111827", zorder=6)
    ax.axvline(frame_idx, color="#f59e0b", linestyle=":", linewidth=1.8, label=f"Selected frame {frame_idx + 1}")
    ax.axhline(threshold, color="#ef4444", linestyle="--", linewidth=1.2, label="Threshold")
    ax.set_title(f"{label} Frame and Joint MSE")
    ax.set_xlabel("Normalized Frame")
    ax.set_ylabel("MSE")
    ax.grid(alpha=0.24)
    ax.legend(loc="center left", bbox_to_anchor=(1.02, 0.5), fontsize=8, frameon=False)
    return fig


def render_mse_canvas(mse_state, frame_idx=0) -> np.ndarray | None:
    if not mse_state:
        return None
    frame_errors = np.asarray(mse_state.get("frame_errors", []), dtype=np.float32)
    joint_frame_mse = np.asarray(mse_state.get("joint_frame_mse", []), dtype=np.float32)
    keypoint_names = mse_state.get("keypoint_names", MODEL_KEYPOINT_NAMES)
    threshold = float(mse_state.get("threshold", 0.0))
    label = mse_state.get("label", "cycle")
    if frame_errors.size == 0 or joint_frame_mse.size == 0:
        return None

    frame_idx = max(0, min(int(frame_idx or 0), len(frame_errors) - 1))
    width, height = 1600, 760
    left, right, top, bottom = 96, 330, 86, 92
    plot_w = width - left - right
    plot_h = height - top - bottom
    canvas = np.full((height, width, 3), 255, dtype=np.uint8)

    max_value = float(max(np.max(frame_errors), np.max(joint_frame_mse), threshold, 1e-6))
    max_value *= 1.12
    n = len(frame_errors)

    def to_xy(i: int, value: float) -> tuple[int, int]:
        x = left + int(round((i / max(1, n - 1)) * plot_w))
        y = top + plot_h - int(round((float(value) / max_value) * plot_h))
        return x, y

    for frac in np.linspace(0, 1, 5):
        y = top + int(round(plot_h * frac))
        cv2.line(canvas, (left, y), (left + plot_w, y), (229, 233, 240), 2, cv2.LINE_AA)
    for frac in np.linspace(0, 1, 6):
        x = left + int(round(plot_w * frac))
        cv2.line(canvas, (x, top), (x, top + plot_h), (241, 245, 249), 1, cv2.LINE_AA)

    cv2.rectangle(canvas, (left, top), (left + plot_w, top + plot_h), (148, 163, 184), 2, cv2.LINE_AA)
    palette = [(235, 99, 37), (105, 150, 5), (6, 126, 217), (237, 58, 124), (211, 38, 38), (178, 91, 124), (194, 145, 8), (13, 148, 136), (168, 85, 247)]
    for idx in range(joint_frame_mse.shape[1]):
        pts = np.array([to_xy(i, joint_frame_mse[i, idx]) for i in range(n)], dtype=np.int32)
        cv2.polylines(canvas, [pts], False, palette[idx % len(palette)], 2, cv2.LINE_AA)

    total_pts = np.array([to_xy(i, frame_errors[i]) for i in range(n)], dtype=np.int32)
    cv2.polylines(canvas, [total_pts], False, (17, 24, 39), 5, cv2.LINE_AA)

    if threshold > 0:
        y_thr = to_xy(0, threshold)[1]
        cv2.line(canvas, (left, y_thr), (left + plot_w, y_thr), (68, 68, 239), 2, cv2.LINE_AA)
        cv2.putText(canvas, "Threshold", (left + plot_w + 18, y_thr + 6), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (68, 68, 239), 2, cv2.LINE_AA)

    x_sel = to_xy(frame_idx, 0)[0]
    cv2.line(canvas, (x_sel, top), (x_sel, top + plot_h), (11, 126, 245), 4, cv2.LINE_AA)
    cv2.circle(canvas, to_xy(frame_idx, frame_errors[frame_idx]), 8, (17, 24, 39), -1, cv2.LINE_AA)
    for idx in range(joint_frame_mse.shape[1]):
        cv2.circle(canvas, to_xy(frame_idx, joint_frame_mse[frame_idx, idx]), 5, palette[idx % len(palette)], -1, cv2.LINE_AA)

    title = f"{label} MSE | frame {frame_idx + 1}/{n}"
    cv2.putText(canvas, title, (left, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.05, (17, 24, 39), 3, cv2.LINE_AA)
    cv2.putText(canvas, "Normalized Frame", (left + plot_w // 2 - 120, height - 32), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (71, 85, 105), 2, cv2.LINE_AA)
    cv2.putText(canvas, "MSE", (24, top + plot_h // 2), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (71, 85, 105), 2, cv2.LINE_AA)
    cv2.putText(canvas, f"Total {frame_errors[frame_idx]:.6f}", (left + plot_w + 18, top + 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (17, 24, 39), 2, cv2.LINE_AA)

    legend_y = top + 76
    cv2.line(canvas, (left + plot_w + 18, legend_y), (left + plot_w + 62, legend_y), (17, 24, 39), 5, cv2.LINE_AA)
    cv2.putText(canvas, "Total MSE", (left + plot_w + 74, legend_y + 8), cv2.FONT_HERSHEY_SIMPLEX, 0.62, (51, 65, 85), 2, cv2.LINE_AA)
    for idx, name in enumerate(keypoint_names[: min(len(keypoint_names), joint_frame_mse.shape[1])]):
        y = legend_y + 38 + idx * 32
        color = palette[idx % len(palette)]
        cv2.line(canvas, (left + plot_w + 18, y), (left + plot_w + 62, y), color, 3, cv2.LINE_AA)
        cv2.putText(canvas, name.replace("_", " "), (left + plot_w + 74, y + 8), cv2.FONT_HERSHEY_SIMPLEX, 0.56, (51, 65, 85), 1, cv2.LINE_AA)
    return canvas


def render_mse_frame(mse_state, frame_idx=0) -> str | None:
    if mse_state and mse_state.get("frame_paths"):
        paths = mse_state["frame_paths"]
        frame_idx = max(0, min(int(frame_idx or 0), len(paths) - 1))
        return paths[frame_idx]
    canvas = render_mse_canvas(mse_state, frame_idx)
    if canvas is None:
        return None
    label = mse_state.get("label", "cycle") if mse_state else "cycle"
    out = Path(tempfile.mkdtemp(prefix="rowing_mse_")) / f"{label}_mse_{int(frame_idx or 0):03d}.png"
    cv2.imwrite(str(out), canvas)
    return str(out)


def build_mse_frame_paths(mse_state, output_dir: Path) -> list[str]:
    frame_errors = np.asarray(mse_state.get("frame_errors", []), dtype=np.float32)
    frame_paths = []
    for frame_idx in range(len(frame_errors)):
        canvas = render_mse_canvas(mse_state, frame_idx)
        if canvas is None:
            continue
        frame_path = output_dir / f"{mse_state.get('label', 'cycle')}_mse_{frame_idx:03d}.png"
        cv2.imwrite(str(frame_path), canvas)
        frame_paths.append(str(frame_path))
    return frame_paths


def gradio_file_url(path: str) -> str:
    return f"/gradio_api/file={quote(str(path), safe='/')}"


def make_fast_frame_viewer_html(compare_state, mse_state, frame_idx=0) -> str:
    compare_paths = (compare_state or {}).get("frame_paths") or []
    mse_paths = (mse_state or {}).get("frame_paths") or []
    if not compare_paths or not mse_paths:
        return """
        <div class="fast-frame-viewer-placeholder">
            Validate an action cycle to enable the fast frame viewer.
        </div>
        """

    total = min(len(compare_paths), len(mse_paths))
    frame_idx = max(0, min(int(frame_idx or 0), total - 1))
    compare_urls = [gradio_file_url(path) for path in compare_paths[:total]]
    mse_urls = [gradio_file_url(path) for path in mse_paths[:total]]
    rows_by_frame = [make_frame_joint_mse_rows(mse_state, idx)[:6] for idx in range(total)]
    viewer_id = f"rv_viewer_{uuid.uuid4().hex}"
    payload = {
        "compare": compare_urls,
        "mse": mse_urls,
        "rows": rows_by_frame,
        "initial": frame_idx,
        "total": total,
    }
    payload_b64 = base64.b64encode(json.dumps(payload, ensure_ascii=False).encode("utf-8")).decode("ascii")
    return f"""
    <div class="rv-fast-viewer" id="{viewer_id}" data-payload="{payload_b64}" onmouseenter="rvInitFrameViewer('{viewer_id}')" onclick="rvInitFrameViewer('{viewer_id}')">
      <div class="rv-fast-toolbar">
        <button type="button" class="rv-fast-btn" onclick="rvFramePrev('{viewer_id}')">◀</button>
        <button type="button" class="rv-fast-btn rv-play-btn" onclick="rvFramePlay('{viewer_id}')">▶ Play</button>
        <button type="button" class="rv-fast-btn" onclick="rvFrameNext('{viewer_id}')">▶</button>
        <span class="rv-frame-label" id="{viewer_id}_label">Frame {frame_idx + 1}/{total}</span>
        <span class="rv-load-label" id="{viewer_id}_load">Loading frames...</span>
      </div>
      <input
        id="{viewer_id}_range"
        class="rv-fast-range"
        type="range"
        min="0"
        max="{total - 1}"
        step="1"
        value="{frame_idx}"
        disabled
        oninput="rvFrameUpdate('{viewer_id}', this.value)"
      />
      <div class="rv-fast-grid">
        <div class="rv-fast-panel">
          <div class="rv-fast-title">Action Comparison</div>
          <canvas id="{viewer_id}_compare" width="960" height="560"></canvas>
        </div>
        <div class="rv-fast-panel">
          <div class="rv-fast-title">MSE Analysis</div>
          <canvas id="{viewer_id}_mse" width="1600" height="760"></canvas>
        </div>
      </div>
      <div class="rv-fast-joints" id="{viewer_id}_joints"></div>
    </div>
    """


def make_frame_joint_mse_rows(mse_state, frame_idx=0) -> list[list[str]]:
    if not mse_state:
        return []
    joint_frame_mse = np.asarray(mse_state.get("joint_frame_mse", []), dtype=np.float32)
    keypoint_names = mse_state.get("keypoint_names", MODEL_KEYPOINT_NAMES)
    if joint_frame_mse.size == 0:
        return []
    frame_idx = max(0, min(int(frame_idx or 0), joint_frame_mse.shape[0] - 1))
    values = joint_frame_mse[frame_idx]
    order = sorted(range(len(keypoint_names)), key=lambda idx: values[idx], reverse=True)
    return [
        [
            JOINT_DISPLAY_NAMES.get(keypoint_names[idx], keypoint_names[idx]),
            keypoint_names[idx],
            f"{float(values[idx]):.6f}",
        ]
        for idx in order
    ]


def compute_overlap_plot_params(normalized_pose: np.ndarray, recon_pose: np.ndarray) -> dict:
    foot_idx = first_existing_index(MODEL_KEYPOINT_NAMES, ["left_ankle", "ankle"])
    user = normalized_pose.copy()
    model = recon_pose.copy()
    if foot_idx is not None:
        user -= user[:, foot_idx : foot_idx + 1, :]
        model -= model[:, foot_idx : foot_idx + 1, :]

    all_points = np.vstack([user.reshape(-1, 2), model.reshape(-1, 2)])
    min_xy = all_points.min(axis=0)
    max_xy = all_points.max(axis=0)
    canvas_w, canvas_h = 960, 560
    margin = 14
    anchor = np.array([canvas_w * 0.13, canvas_h * 0.84], dtype=np.float32)
    candidates = []
    if max_xy[0] > 1e-6:
        candidates.append((canvas_w - margin - anchor[0]) / max_xy[0])
    if min_xy[0] < -1e-6:
        candidates.append((anchor[0] - margin) / abs(min_xy[0]))
    if max_xy[1] > 1e-6:
        candidates.append((canvas_h - margin - anchor[1]) / max_xy[1])
    if min_xy[1] < -1e-6:
        candidates.append((anchor[1] - margin) / abs(min_xy[1]))
    scale = float(max(1.0, min(candidates) * 0.998)) if candidates else 260.0
    scale *= 1.8
    return {
        "canvas_w": canvas_w,
        "canvas_h": canvas_h,
        "anchor": anchor.tolist(),
        "scale": scale,
        "foot_idx": foot_idx,
    }


def render_overlap_canvas(compare_state: dict, frame_idx=0) -> np.ndarray | None:
    if not compare_state:
        return None
    normalized_pose = np.asarray(compare_state["normalized_pose"], dtype=np.float32)
    recon_pose = np.asarray(compare_state["reconstruction_pose"], dtype=np.float32)
    frame_errors = np.asarray(compare_state["frame_errors"], dtype=np.float32)
    joint_frame_mse = np.asarray(compare_state.get("joint_frame_mse", []), dtype=np.float32)
    threshold = float(compare_state["threshold"])
    label = compare_state.get("label", "cycle")
    phase = compare_state.get("phase_type", "unknown")
    plot_params = compare_state.get("plot_params") or compute_overlap_plot_params(normalized_pose, recon_pose)
    frame_idx = max(0, min(int(frame_idx or 0), len(normalized_pose) - 1))

    user_pose = normalized_pose[frame_idx].copy()
    model_pose = recon_pose[frame_idx].copy()
    foot_idx = first_existing_index(MODEL_KEYPOINT_NAMES, ["left_ankle", "ankle"])
    if foot_idx is not None:
        user_pose -= user_pose[foot_idx]
        model_pose -= model_pose[foot_idx]

    canvas_w = int(plot_params["canvas_w"])
    canvas_h = int(plot_params["canvas_h"])
    scale = float(plot_params["scale"])
    anchor = np.asarray(plot_params["anchor"], dtype=np.float32)

    def to_canvas(points: np.ndarray) -> np.ndarray:
        converted = points.copy()
        converted[:, 0] = anchor[0] + converted[:, 0] * scale
        converted[:, 1] = anchor[1] + converted[:, 1] * scale
        return converted

    canvas = np.full((canvas_h, canvas_w, 3), 248, dtype=np.uint8)
    for y in range(70, canvas_h - 70, 80):
        cv2.line(canvas, (70, y), (canvas_w - 70, y), (228, 232, 238), 1, cv2.LINE_AA)
    for x in range(80, canvas_w - 70, 80):
        cv2.line(canvas, (x, 90), (x, canvas_h - 80), (232, 236, 242), 1, cv2.LINE_AA)

    user_kpts = np.column_stack((to_canvas(user_pose), np.ones(len(MODEL_KEYPOINT_NAMES), dtype=np.float32)))
    model_kpts = np.column_stack((to_canvas(model_pose), np.ones(len(MODEL_KEYPOINT_NAMES), dtype=np.float32)))
    draw_person(canvas, model_kpts, 0.1, 7, MODEL_LINE_COLOR, MODEL_JOINT_COLOR, MODEL_SKELETON)
    draw_person(canvas, user_kpts, 0.1, 5, LINE_COLOR, JOINT_COLOR, MODEL_SKELETON)

    foot = tuple(np.round(user_kpts[foot_idx, :2]).astype(int)) if foot_idx is not None else (int(anchor[0]), int(anchor[1]))
    cv2.circle(canvas, foot, 10, (30, 30, 30), 2, cv2.LINE_AA)
    cv2.putText(canvas, "foot overlap", (foot[0] + 12, foot[1] + 4), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA)

    title = f"{label} | {phase.upper()} model | frame {frame_idx + 1}/{len(normalized_pose)}"
    cv2.putText(canvas, title, (28, 38), cv2.FONT_HERSHEY_SIMPLEX, 0.78, (22, 31, 45), 2, cv2.LINE_AA)
    cv2.putText(canvas, f"MSE {frame_errors[frame_idx]:.6f} / threshold {threshold:.6f}", (28, 68), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (71, 85, 105), 1, cv2.LINE_AA)
    if joint_frame_mse.size:
        top_idx = int(np.argmax(joint_frame_mse[frame_idx]))
        top_name = JOINT_DISPLAY_NAMES.get(MODEL_KEYPOINT_NAMES[top_idx], MODEL_KEYPOINT_NAMES[top_idx])
        cv2.putText(canvas, f"Top joint: {top_name} {joint_frame_mse[frame_idx, top_idx]:.6f}", (28, 96), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (71, 85, 105), 1, cv2.LINE_AA)
    cv2.line(canvas, (28, canvas_h - 42), (70, canvas_h - 42), LINE_COLOR, 5, cv2.LINE_AA)
    cv2.putText(canvas, "Actual pose", (82, canvas_h - 36), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (51, 65, 85), 1, cv2.LINE_AA)
    cv2.line(canvas, (238, canvas_h - 42), (280, canvas_h - 42), MODEL_LINE_COLOR, 5, cv2.LINE_AA)
    cv2.putText(canvas, "Model reconstruction", (292, canvas_h - 36), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (51, 65, 85), 1, cv2.LINE_AA)
    return canvas


def render_overlap_frame(compare_state: dict, frame_idx=0) -> str | None:
    if compare_state and compare_state.get("frame_paths"):
        paths = compare_state["frame_paths"]
        frame_idx = max(0, min(int(frame_idx or 0), len(paths) - 1))
        return paths[frame_idx]
    canvas = render_overlap_canvas(compare_state, frame_idx)
    if canvas is None:
        return None
    label = compare_state.get("label", "cycle")
    out = Path(tempfile.mkdtemp(prefix="rowing_frame_")) / f"{label}_frame_{int(frame_idx or 0):03d}.png"
    cv2.imwrite(str(out), canvas)
    return str(out)


def create_monitored_clip(
    video_path,
    start_sec,
    end_sec,
    upload_guard,
    progress: gr.Progress = gr.Progress(track_tqdm=False),
):
    logger.info(f"create_monitored_clip called: video_path={video_path}, start_sec={start_sec}, end_sec={end_sec}, upload_guard={upload_guard}")
    
    source = resolve_uploaded_video_path(video_path)
    logger.info(f"Resolved source path: {source}")
    
    if source is None:
        logger.error("Failed to resolve video path, video_path type: %s, value: %s", type(video_path), video_path)
        if upload_guard == "uploading":
            for second in range(UPLOAD_WAIT_SECONDS):
                progress(second / UPLOAD_WAIT_SECONDS, desc=f"Waiting for video upload... {second + 1}/{UPLOAD_WAIT_SECONDS}s")
                time.sleep(1)
            return None, None, "The video is still uploading. Please wait until the upload preview appears."
        return None, None, "No video was uploaded. Please choose a video first."

    if not source.exists():
        logger.error(f"Video file does not exist: {source}")
        return None, None, f"Video file not found: {source}"
    
    if source.stat().st_size == 0:
        logger.error(f"Video file is empty: {source}")
        return None, None, f"Video file is empty: {source.name}"

    try:
        start_sec = max(0.0, float(start_sec or 0.0))
        end_sec = float(end_sec or 0.0)
        logger.info(f"Parsed time values: start_sec={start_sec}, end_sec={end_sec}")
    except (ValueError, TypeError) as e:
        logger.error(f"Failed to parse time values: {e}")
        return None, None, f"Invalid time values: {e}"

    end_value = end_sec if end_sec > start_sec else None

    workdir = Path(tempfile.mkdtemp(prefix="rowing_clip_"))
    clip_path = workdir / f"{source.stem}_monitored_clip.mp4"
    logger.info(f"Created work directory: {workdir}, output clip path: {clip_path}")

    try:
        progress(0, desc="Creating monitored clip...")
        clip_path = ffmpeg_clip(source, clip_path, start_sec, end_value)
    except gr.Error as e:
        logger.error(f"gr.Error during clip creation: {e}")
        raise
    except Exception as e:
        logger.error(f"Unexpected error during clip creation: {e}", exc_info=True)
        return None, None, f"Unexpected error: {str(e)}"

    summary = f"Clip ready.\n- Source: {source.name}\n- Start: {start_sec:.2f}s\n- End: {'video end' if end_value is None else f'{end_value:.2f}s'}"
    logger.info(f"Clip creation completed: {clip_path}")
    return str(clip_path), str(clip_path), summary


def build_stickman_video(
    video_path,
    clip_path,
    upload_guard,
    progress: gr.Progress = gr.Progress(track_tqdm=False),
):
    conf = 0.30
    point_conf = 0.25
    process_full_video = True
    max_frames = 300
    frame_stride = 1
    smoothing_window = 5
    line_width = 3
    yolo_imgsz = env_int("ROWING_YOLO_IMGSZ", 640, 32)
    yolo_imgsz = yolo_imgsz if yolo_imgsz > 0 else None
    default_overlay_delay = max(0, int(round((smoothing_window - 1) / 2.0)))
    overlay_delay_frames = env_int("ROWING_OVERLAY_DELAY_FRAMES", default_overlay_delay, 0)
    PROCESS_STOP_EVENT.clear()

    source = Path(clip_path) if clip_path else resolve_uploaded_video_path(video_path)
    if source is None:
        if upload_guard == "uploading":
            for second in range(UPLOAD_WAIT_SECONDS):
                progress(second / UPLOAD_WAIT_SECONDS, desc=f"Waiting for video upload... {second + 1}/{UPLOAD_WAIT_SECONDS}s")
                time.sleep(1)
            return None, None, None, []
        return None, None, None, []

    if not source.exists():
        return None, None, None, []

    model = load_yolo_model()
    cap = cv2.VideoCapture(str(source))
    if not cap.isOpened():
        return None, None, None, []

    fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 1280
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 720
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0

    frame_stride = max(1, int(frame_stride))
    smoothing_window = max(1, int(smoothing_window))
    max_frames = int(max_frames)
    if process_full_video or max_frames <= 0:
        frame_limit = total_frames if total_frames > 0 else math.inf
    else:
        frame_limit = min(max_frames, total_frames) if total_frames > 0 else max_frames
    progress_total = int(math.ceil(frame_limit / frame_stride)) if frame_limit != math.inf else None

    output_fps = max(1.0, fps / frame_stride)
    workdir = Path(tempfile.mkdtemp(prefix="rowing_space_"))
    raw_output_path = workdir / f"{source.stem}_stickman_overlay_raw.mp4"
    output_path = workdir / f"{source.stem}_stickman_overlay.mp4"
    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    writer = cv2.VideoWriter(str(raw_output_path), fourcc, output_fps, (width, height))

    if not writer.isOpened():
        cap.release()
        return None, None, None, []

    start_time = time.time()
    read_count = 0
    written_count = 0
    detected_person_frames = 0
    smoothing_buffers: list[list[np.ndarray]] = [[], [], []]
    
    all_keypoints = []
    wrist_x_values = []
    last_valid_keypoints = None

    progress(0, desc="Loading YOLO11x model and opening video...")
    logger.info(
        "START stickman source=%s size=%sx%s fps=%.2f total_frames=%s frame_limit=%s stride=%s yolo_imgsz=%s yolo_device=%s",
        source.name,
        width,
        height,
        fps,
        total_frames,
        progress_total or "unknown",
        frame_stride,
        yolo_imgsz or "default",
        get_yolo_device(),
    )
    logger.info(
        "Overlay delay compensation: smoothing_window=%s delay_processed_frames=%s delay_source_frames=%s delay_seconds=%.3f",
        smoothing_window,
        overlay_delay_frames,
        overlay_delay_frames * frame_stride,
        (overlay_delay_frames * frame_stride) / max(fps, 1e-6),
    )

    frame_buffer: list[tuple[int, np.ndarray]] = []
    last_overlay_people: list[np.ndarray] = []
    processed_count = 0

    while read_count < frame_limit:
        if PROCESS_STOP_EVENT.is_set():
            logger.info("Stickman processing stopped by user at read_frame=%s output_frame=%s", read_count, written_count)
            break

        ok, frame = cap.read()
        if not ok:
            break

        if read_count % frame_stride != 0:
            read_count += 1
            continue

        predict_kwargs = {"conf": conf, "verbose": False, "device": get_yolo_device()}
        if yolo_imgsz:
            predict_kwargs["imgsz"] = yolo_imgsz
        result = model.predict(frame, **predict_kwargs)[0]

        person_count = 0
        overlay_people: list[np.ndarray] = []
        if result.keypoints is not None and len(result.keypoints) > 0:
            kpts = result.keypoints.data.cpu().numpy()
            boxes_conf = result.boxes.conf.cpu().numpy() if result.boxes is not None else np.ones(len(kpts))
            order = np.argsort(boxes_conf)[::-1]
            for rank, person_idx in enumerate(order[:3]):
                smoothed_kpts = smooth_keypoints(smoothing_buffers[rank], kpts[person_idx], smoothing_window)
                overlay_people.append(smoothed_kpts.copy())
                person_count += 1
                if rank == 0:
                    all_keypoints.append(smoothed_kpts.copy())
                    last_valid_keypoints = smoothed_kpts.copy()
                    wrist_idx = KEYPOINT_NAMES.index("left_wrist") if "left_wrist" in KEYPOINT_NAMES else 9
                    wrist_x_values.append(smoothed_kpts[wrist_idx, 0])

        if person_count:
            detected_person_frames += 1
            for empty_rank in range(person_count, len(smoothing_buffers)):
                smoothing_buffers[empty_rank].clear()
        else:
            for buffer in smoothing_buffers:
                buffer.clear()
            if last_valid_keypoints is not None:
                all_keypoints.append(last_valid_keypoints.copy())
                wrist_idx = KEYPOINT_NAMES.index("left_wrist") if "left_wrist" in KEYPOINT_NAMES else 9
                wrist_x_values.append(last_valid_keypoints[wrist_idx, 0])
            else:
                all_keypoints.append(np.zeros((len(KEYPOINT_NAMES), 3), dtype=np.float32))
                wrist_x_values.append(np.nan)

        if overlay_people:
            last_overlay_people = [person.copy() for person in overlay_people]
        frame_buffer.append((read_count, frame.copy()))
        if len(frame_buffer) > overlay_delay_frames:
            display_frame_idx, canvas = frame_buffer.pop(0)
            status_text = f"frame {display_frame_idx} | persons {person_count}"
            draw_overlay_people(canvas, overlay_people, point_conf, line_width, status_text)
            writer.write(canvas)
            written_count += 1

        processed_count += 1
        read_count += 1

        pct, desc = progress_description(processed_count, progress_total, start_time)
        if processed_count > 0:
            per_frame = (time.time() - start_time) / processed_count
            desc = f"{desc} | {per_frame:.1f}s/frame"
        progress(pct, desc=desc)

    cap.release()
    while frame_buffer:
        display_frame_idx, canvas = frame_buffer.pop(0)
        status_text = f"frame {display_frame_idx} | persons {len(last_overlay_people)}"
        draw_overlay_people(canvas, last_overlay_people, point_conf, line_width, status_text)
        writer.write(canvas)
        written_count += 1
    writer.release()

    elapsed = time.time() - start_time
    if written_count == 0:
        return None, None, "No frames were processed. Try lowering frame stride.", []

    final_output_path = encode_browser_mp4(raw_output_path, output_path, output_fps)
    output_size_mb = final_output_path.stat().st_size / (1024 * 1024)

    all_keypoints = fill_missing_keypoints(all_keypoints)
    wrist_x = prepare_wrist_signal(wrist_x_values)
    cycles = detect_cycles(wrist_x, output_fps)
    used_cycle_fallback = False
    if not cycles:
        cycles = fallback_cycles(list(range(len(all_keypoints))))
        used_cycle_fallback = bool(cycles)
        logger.info("Cycle detection returned no extrema; using fallback segments: %s", cycles)
    drive_count = len([c for c in cycles if "drive" in c[2]])
    recovery_count = len([c for c in cycles if "recovery" in c[2]])
    
    fallback_note = "\n- Note: cycle detector fallback split was used" if used_cycle_fallback else ""
    summary = (
        f"{'Stopped.' if PROCESS_STOP_EVENT.is_set() else 'Done.'}\n"
        f"- Source: {source.name}\n"
        f"- Resolution: {width}x{height}, FPS: {fps:.2f}\n"
        f"- Read frames: {read_count}\n"
        f"- Output frames: {written_count}\n"
        f"- Detected persons: {detected_person_frames}\n"
        f"- Elapsed: {readable_seconds(elapsed)}\n"
        f"- Average: {elapsed / max(1, written_count):.1f}s/frame\n"
        f"- YOLO image size: {yolo_imgsz or 'default'}\n"
        f"- Output type: stickman overlay on source video\n"
        f"- Overlay delay compensation: {overlay_delay_frames} processed frames "
        f"({overlay_delay_frames * frame_stride} source frames, {(overlay_delay_frames * frame_stride) / max(fps, 1e-6):.3f}s)\n"
        f"- Cycle constraints: phase length {env_int('ROWING_MIN_PHASE_MS', 450, 100)}-{env_int('ROWING_MAX_PHASE_MS', 2800, 600)} ms, "
        f"motion ratio >= {float(os.getenv('ROWING_MIN_PHASE_MOTION_RATIO', '0.18')):.2f}\n"
        f"- Output size: {output_size_mb:.1f} MB\n"
        f"- Model: {YOLO_MODEL_PATH.name}\n"
        f"- Detected segments: {len(cycles)} ({drive_count} Drive, {recovery_count} Recovery)"
        f"{fallback_note}"
    )

    payload = {
        "cycles": cycles,
        "keypoints": [k.astype(np.float32).tolist() for k in all_keypoints],
        "source_path": str(source),
        "processed_video_path": str(final_output_path),
        "fps": float(fps),
        "output_fps": float(output_fps),
        "width": int(width),
        "height": int(height),
        "frame_stride": int(frame_stride),
        "written_count": int(written_count),
        "stopped": bool(PROCESS_STOP_EVENT.is_set()),
        "yolo_imgsz": int(yolo_imgsz) if yolo_imgsz else None,
        "overlay_delay_frames": int(overlay_delay_frames),
    }

    return str(final_output_path), str(final_output_path), summary, payload


def validate_cycle_and_compare(
    video_path,
    clip_path,
    cycle_payload,
    cycle_index,
    progress: gr.Progress = gr.Progress(track_tqdm=False),
):
    cycles = cycle_payload.get("cycles", []) if isinstance(cycle_payload, dict) else cycle_payload
    if cycles is None or len(cycles) == 0:
        return (
            None,
            None,
            "Error: No cycles detected. Please process a video first.",
            "",
            [],
            None,
            None,
            gr.update(value=0, maximum=99, interactive=False),
            None,
            [],
            "",
        )
    
    if cycle_index is None:
        cycle_index = 0
    cycle_index = int(cycle_index)
    
    if cycle_index < 0 or cycle_index >= len(cycles):
        cycle_index = 0
    
    cycle_info = cycles[cycle_index]
    start_frame, end_frame, label = cycle_info
    
    phase_type = "drive" if "drive" in label else "recovery"
    fps = float(cycle_payload.get("output_fps") or cycle_payload.get("fps") or 30.0) if isinstance(cycle_payload, dict) else 30.0

    progress(0, desc="Preparing extracted keypoints for validation...")

    if not isinstance(cycle_payload, dict) or not cycle_payload.get("keypoints"):
        return (
            None,
            None,
            "Error: Missing extracted keypoints. Please process the video again.",
            "",
            [],
            None,
            None,
            gr.update(value=0, maximum=99, interactive=False),
            None,
            [],
            "",
        )

    extracted_keypoints = [np.asarray(k, dtype=np.float32) for k in cycle_payload["keypoints"]]
    start_frame = max(0, int(start_frame))
    end_frame = min(len(extracted_keypoints) - 1, int(end_frame))
    cycle_keypoints_17 = extracted_keypoints[start_frame : end_frame + 1]
    cycle_keypoints = [extract_model_keypoints(k) for k in cycle_keypoints_17]
    
    if len(cycle_keypoints) < 2:
        return (
            None,
            None,
            "Error: Not enough frames in cycle",
            "",
            [],
            None,
            None,
            gr.update(value=0, maximum=99, interactive=False),
            None,
            [],
            "",
        )
    
    try:
        if phase_type == "drive":
            ae_model, config, threshold, device = load_ae_model(DRIVE_MODEL_PATH, DRIVE_THRESHOLD_PATH)
        else:
            ae_model, config, threshold, device = load_ae_model(RECOVERY_MODEL_PATH, RECOVERY_THRESHOLD_PATH)
        
        cycle_array = np.stack(cycle_keypoints, axis=0)
        normalized = normalize_cycle(cycle_array, MODEL_KEYPOINT_NAMES, config["target_len"])
        
        if normalized.shape[1] != config["input_dim"]:
            raise ValueError(
                f"输入维度不匹配: 模型需要 {config['input_dim']} 维,当前关键点归一化后为 {normalized.shape[1]} 维。"
            )
        
        x = torch.from_numpy(normalized[None, :, :]).float().to(device)
        with torch.no_grad():
            recon, z = ae_model(x)
            err = torch.mean((recon - x) ** 2).item()
        
        recon_np = recon.cpu().numpy()[0]
        normalized_pose = normalized.reshape(config["target_len"], len(MODEL_KEYPOINT_NAMES), 2)
        recon_pose = recon_np.reshape(config["target_len"], len(MODEL_KEYPOINT_NAMES), 2)
        
        diff = recon_pose - normalized_pose
        joint_frame_mse = np.mean(diff**2, axis=2)
        joint_errors = joint_frame_mse.mean(axis=0)
        frame_errors = joint_frame_mse.mean(axis=1)
        
        is_abnormal = err > threshold
        score = max(0.0, min(100.0, 100.0 * (1.0 - err / (threshold * 2.0))))
        
        diagnoses = diagnose_rowing_technique(
            normalized_pose,
            MODEL_KEYPOINT_NAMES,
            config["target_len"],
            recon_pose,
            joint_frame_mse,
            err,
            threshold,
            score,
        )
        
        progress(0.7, desc="Generating comparison visualization...")
        compare_state = {
            "normalized_pose": normalized_pose.astype(float).tolist(),
            "reconstruction_pose": recon_pose.astype(float).tolist(),
            "frame_errors": frame_errors.astype(float).tolist(),
            "joint_frame_mse": joint_frame_mse.astype(float).tolist(),
            "threshold": float(threshold),
            "label": label,
            "phase_type": phase_type,
            "plot_params": compute_overlap_plot_params(normalized_pose, recon_pose),
        }
        plot_params = compare_state["plot_params"]
        comp_width = int(plot_params["canvas_w"])
        comp_height = int(plot_params["canvas_h"])
        comp_workdir = Path(tempfile.mkdtemp(prefix="rowing_comp_"))
        comp_raw_path = comp_workdir / f"{label}_comparison_raw.mp4"
        comp_output_path = comp_workdir / f"{label}_comparison.mp4"
        comp_fps = max(1.0, fps / 2)
        
        comp_writer = cv2.VideoWriter(str(comp_raw_path), cv2.VideoWriter_fourcc(*"mp4v"), comp_fps, (comp_width, comp_height))
        frame_paths = []

        for frame_idx in range(config["target_len"]):
            canvas = render_overlap_canvas(compare_state, frame_idx)
            comp_writer.write(canvas)
            frame_path = comp_workdir / f"{label}_frame_{frame_idx:03d}.png"
            cv2.imwrite(str(frame_path), canvas)
            frame_paths.append(str(frame_path))
        
        comp_writer.release()
        compare_state["frame_paths"] = frame_paths
        final_comp_path = encode_browser_mp4(comp_raw_path, comp_output_path, comp_fps)
        
        report = (
            f"=== 动作验证报告 ===\n"
            f"片段: {label}\n"
            f"阶段: {phase_type.capitalize()}\n"
            f"帧数: {len(cycle_keypoints)} (原始) -> {config['target_len']} (归一化)\n"
            f"MSE: {err:.6f}\n"
            f"阈值: {threshold:.6f}\n"
            f"判定: {'异常 ⚠️' if is_abnormal else '正常 ✓'}\n"
            f"分数: {score:.1f}/100\n\n"
            f"=== 错误检测结果 ===\n"
        )
        
        for diag in diagnoses:
            color_map = {"normal": "🟢", "low": "🟡", "medium": "🟠", "high": "🔴"}
            report += f"{color_map[diag['severity']]} {diag['phase']}: {diag['error_name']} - {diag['severity_text']}\n"
            if diag["severity"] != "normal":
                report += f"     描述: {diag['description']}\n"
                report += f"     证据: {diag['evidence']}\n"
            report += "\n"
        
        mse_state = {
            "frame_errors": frame_errors.astype(float).tolist(),
            "joint_frame_mse": joint_frame_mse.astype(float).tolist(),
            "keypoint_names": MODEL_KEYPOINT_NAMES,
            "threshold": float(threshold),
            "label": label,
        }
        mse_state["frame_paths"] = build_mse_frame_paths(mse_state, comp_workdir)
        peak_frame = int(np.argmax(frame_errors))
        comparison_frame = render_overlap_frame(compare_state, peak_frame)
        fast_viewer_html = make_fast_frame_viewer_html(compare_state, mse_state, peak_frame)
        return (
            comparison_frame,
            str(final_comp_path),
            report,
            f"{score:.1f}/100",
            diagnoses,
            mse_state,
            compare_state,
            gr.update(value=peak_frame, maximum=config["target_len"] - 1, interactive=True),
            render_mse_frame(mse_state, peak_frame),
            make_frame_joint_mse_rows(mse_state, peak_frame),
            fast_viewer_html,
        )
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return (
            None,
            None,
            f"Validation error: {str(e)}",
            "",
            [],
            None,
            None,
            gr.update(value=0, maximum=99, interactive=False),
            None,
            [],
            "",
        )


i18n = {
    "zh": {
        "app_title": "RowingValidator Beta",
        "app_subtitle": "AI划船动作分析",
        "for_coaches": "FOR COACHES & ATHLETES",
        "hero_title": "先进的AI划船视频分析与虚拟教练平台",
        "hero_subtitle": "安全高效地划船",
        "start_free": "免费开始 →",
        "feature_1_title": "提高速度",
        "feature_1_desc": "通过技术优化,提升划行速度",
        "feature_2_title": "提升效率",
        "feature_2_desc": "提高能量转换效率,划得更省力",
        "feature_3_title": "减少受伤",
        "feature_3_desc": "纠正错误动作,减少运动损伤",
        "why_title": "为什么选择我们",
        "why_subtitle": "我们的AI技术帮助您深入分析划船动作,发现问题并提供专业指导",
        "why_1_title": "AI精准分析",
        "why_1_desc": "基于YOLO和自编码器模型,精准识别动作细节,提供专业反馈",
        "why_2_title": "实时对比",
        "why_2_desc": "将您的动作与标准动作进行实时对比,直观展示差异",
        "why_3_title": "个性化建议",
        "why_3_desc": "根据您的动作特点,提供针对性的改进建议和训练计划",
        "demo_title": "观看使用演示",
        "demo_subtitle": "了解如何使用我们的工具分析划船动作",
        "cta_title": "准备好提升您的划船技术了吗?",
        "cta_subtitle": "加入数千名使用我们的AI分析提升技术的运动员",
        "footer": "© 2026 RowingValidator Beta. All rights reserved.",
        "nav_features": "功能",
        "nav_demo": "演示",
        "back_home": "← 返回首页",
        "tool_title": "视频上传与分析",
        "tool_subtitle": "上传您的划船视频,让AI分析您的技术动作",
        "tab_1": "📹 视频上传与YOLO处理",
        "tab_2": "🔄 周期选择与动作对比",
        "tab_3": "📋 验证报告",
        "upload_label": "上传视频",
        "clip_settings": "视频裁剪设置",
        "start_time": "开始时间(秒)",
        "end_time": "结束时间(0=视频末尾)",
        "create_clip": "创建裁剪片段",
        "clip_preview": "裁剪预览",
        "clip_summary": "裁剪摘要",
        "process_video": "提取火柴人并叠加原视频",
        "stop_process": "停止处理",
        "stickman_result": "🎬 火柴人叠加结果",
        "stickman_video": "火柴人叠加视频",
        "download_video": "下载叠加视频",
        "process_summary": "处理摘要",
        "cycle_select": "周期选择",
        "select_cycle": "选择分析周期",
        "validate_action": "验证动作并生成对比",
        "cycle_info": "周期信息",
        "cycle_detail": "周期详情",
        "compare_title": "🆚 动作对比",
        "compare_subtitle": "逐帧对比:实际动作 vs 模型重建",
        "download_compare": "下载对比视频",
        "action_score": "动作评分",
        "score_label": "评分",
        "mse_analysis": "MSE 逐帧分析",
        "select_frame": "选择归一化帧",
        "mse_plot": "总 MSE 与各关节 MSE",
        "joint_mse": "各关节 MSE 详情",
        "report_title": "技术诊断报告",
        "error_list": "错误检测列表",
        "error_details": "错误详情",
        "error_stats": "错误分布统计",
        "usage_tab": "📈 使用统计",
        "usage_title": "使用统计",
        "usage_refresh": "刷新使用统计",
    },
    "en": {
        "app_title": "RowingValidator Beta",
        "app_subtitle": "AI Rowing Analysis",
        "for_coaches": "FOR COACHES & ATHLETES",
        "hero_title": "ADVANCED AI ROWING VIDEO ANALYSIS AND VIRTUAL COACHING PLATFORM",
        "hero_subtitle": "ROW SAFELY & EFFICIENTLY",
        "start_free": "START FOR FREE",
        "feature_1_title": "Increase Speed",
        "feature_1_desc": "Improve rowing speed through technical optimization",
        "feature_2_title": "Boost Efficiency",
        "feature_2_desc": "Improve energy conversion efficiency, row with less effort",
        "feature_3_title": "Reduce Injuries",
        "feature_3_desc": "Correct improper form and reduce sports injuries",
        "why_title": "Why Choose Us",
        "why_subtitle": "Our AI technology helps you deeply analyze rowing technique, identify issues, and provide professional guidance",
        "why_1_title": "AI-Powered Analysis",
        "why_1_desc": "Based on YOLO and autoencoder models, precisely identify movement details and provide professional feedback",
        "why_2_title": "Real-Time Comparison",
        "why_2_desc": "Compare your movements with standard form in real-time with intuitive visual differences",
        "why_3_title": "Personalized Advice",
        "why_3_desc": "Provide targeted improvement suggestions and training plans based on your movement characteristics",
        "demo_title": "Watch the Demo",
        "demo_subtitle": "Learn how to use our tool to analyze your rowing technique",
        "cta_title": "Ready to Improve Your Rowing Technique?",
        "cta_subtitle": "Join thousands of athletes improving their technique with our AI analysis",
        "footer": "© 2026 RowingValidator Beta. All rights reserved.",
        "nav_features": "Features",
        "nav_demo": "Demo",
        "back_home": "← Back to Home",
        "tool_title": "Video Upload & Analysis",
        "tool_subtitle": "Upload your rowing video and let AI analyze your technique",
        "tab_1": "📹 Video Upload & YOLO Processing",
        "tab_2": "🔄 Cycle Selection & Comparison",
        "tab_3": "📋 Validation Report",
        "upload_label": "Upload Video",
        "clip_settings": "Clip Settings",
        "start_time": "Start Time (s)",
        "end_time": "End Time (0=end)",
        "create_clip": "Create Clip",
        "clip_preview": "Clip Preview",
        "clip_summary": "Clip Summary",
        "process_video": "Extract Stickman & Overlay Video",
        "stop_process": "Stop Processing",
        "stickman_result": "🎬 Stickman Overlay Result",
        "stickman_video": "Stickman Overlay Video",
        "download_video": "Download Overlay Video",
        "process_summary": "Processing Summary",
        "cycle_select": "Cycle Selection",
        "select_cycle": "Select Analysis Cycle",
        "validate_action": "Validate & Compare",
        "cycle_info": "Cycle Info",
        "cycle_detail": "Cycle Details",
        "compare_title": "🆚 Action Comparison",
        "compare_subtitle": "Frame-by-frame: Actual vs Model Reconstruction",
        "download_compare": "Download Comparison Video",
        "action_score": "Action Score",
        "score_label": "Score",
        "mse_analysis": "MSE Frame Analysis",
        "select_frame": "Select Normalized Frame",
        "mse_plot": "Total MSE & Joint MSE",
        "joint_mse": "Joint MSE Details",
        "report_title": "Technical Diagnosis Report",
        "error_list": "Error Detection List",
        "error_details": "Error Details",
        "error_stats": "Error Distribution Statistics",
        "usage_tab": "📈 Usage",
        "usage_title": "Usage Tracking",
        "usage_refresh": "Refresh Usage Stats",
    },
}

import base64


def read_static_image_base64(filename: str) -> str:
    candidates = [
        SCRIPT_DIR / filename,
        SCRIPT_DIR / "assets" / filename,
        SCRIPT_DIR.parent / filename,
        Path.cwd() / filename,
    ]
    for path in candidates:
        if not path.exists():
            continue
        try:
            return base64.b64encode(path.read_bytes()).decode()
        except Exception as e:
            logger.warning(f"Could not read {path}: {e}")
    logger.warning(
        "Could not find %s. Tried: %s",
        filename,
        ", ".join(str(path) for path in candidates),
    )
    return ""


def static_file_url(filename: str) -> str:
    path = SCRIPT_DIR / filename
    if not path.exists():
        return ""
    return f"/gradio_api/file={quote(str(path), safe='/:')}"


def demo_video_html() -> str:
    video_url = static_file_url("Video1.mp4")
    if not video_url:
        return """
        <div class="demo-video-fallback">
            Demo video is not available. Upload a rowing clip in the Tool tab to start analysis.
        </div>
        """
    return f"""
        <video class="home-demo-video" autoplay muted loop playsinline controls>
            <source src="{_html_escape(video_url)}" type="video/mp4">
        </video>
        """


bg_base64 = ""
bg_why_base64 = ""
bg_cta_base64 = ""
bg_base64 = read_static_image_base64("background.png")
bg_why_base64 = read_static_image_base64("background_why.png")
bg_cta_base64 = read_static_image_base64("background_cta.png")

custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');

:root,
html,
body,
.gradio-container {
    color-scheme: light !important;
}

* {
    font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif !important;
}

""" + (f""".hero-section {{
    background: url(data:image/png;base64,{bg_base64});
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    position: relative;
    overflow: hidden;
    min-height: 100vh;
    height: 100vh;
    width: 150%;
    margin-left: -25%;
    margin-right: -25%;
    display: flex;
    align-items: center;
    justify-content: center;
}}
""" if bg_base64 else "") + (f""".why-section {{
    background: url(data:image/png;base64,{bg_why_base64});
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    width: 150%;
    margin-left: -25%;
    margin-right: -25%;
    padding: 160px 40px 200px;
}}
""" if bg_why_base64 else "") + (f""".cta-section {{
    background: url(data:image/png;base64,{bg_cta_base64});
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    position: relative;
    overflow: hidden;
    padding: 200px 40px 320px;
    width: 150%;
    margin-left: -25%;
    margin-right: -25%;
    text-align: center;
}}
""" if bg_cta_base64 else "") + """

.gradio-container {
    background: #ffffff !important;
    color: #0f172a !important;
    max-width: 100% !important;
    overflow: visible !important;
}

.gradio-container * {
    color: #0f172a !important;
}

html[data-theme="dark"],
body.dark,
.dark,
.dark .gradio-container {
    background: #ffffff !important;
    color: #0f172a !important;
}

.rv-fast-viewer {
    width: 100%;
    background: #ffffff;
    border: 1px solid #dbe3ef;
    border-radius: 8px;
    padding: 14px;
    margin: 8px 0 14px;
    box-shadow: 0 2px 10px rgba(15, 23, 42, 0.06);
}

.rv-fast-toolbar {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
}

.rv-fast-btn {
    border: 1px solid #cbd5e1;
    background: #f8fafc;
    color: #0f172a !important;
    border-radius: 6px;
    padding: 7px 12px;
    font-weight: 700;
    cursor: pointer;
}

.rv-fast-btn:hover {
    background: #e8f1ff;
    border-color: #93c5fd;
}

.rv-frame-label {
    margin-left: auto;
    font-weight: 800;
    color: #1a365d !important;
}

.rv-load-label {
    font-size: 12px;
    font-weight: 700;
    color: #64748b !important;
}

.rv-fast-grid {
    display: grid;
    grid-template-columns: minmax(0, 1fr);
    gap: 18px;
    align-items: start;
}

.rv-fast-panel {
    min-width: 0;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    overflow: hidden;
    background: #f8fafc;
}

.rv-fast-title {
    padding: 8px 10px;
    font-weight: 800;
    color: #334155 !important;
    background: #eef4fb;
    border-bottom: 1px solid #e2e8f0;
}

.rv-fast-panel canvas {
    display: block;
    width: 100%;
    height: auto;
    background: #ffffff;
}

.rv-fast-range {
    width: 100%;
    margin: 14px 0 10px;
    accent-color: #f97316;
}

.rv-fast-range:disabled {
    opacity: 0.42;
}

.rv-fast-joints {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 6px 10px;
    font-size: 13px;
    color: #334155 !important;
}

.rv-fast-joint-row {
    display: flex;
    justify-content: space-between;
    gap: 8px;
    padding: 7px 9px;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
}

.fast-frame-viewer-placeholder {
    border: 1px dashed #cbd5e1;
    border-radius: 8px;
    padding: 18px;
    color: #64748b !important;
    background: #f8fafc;
}

@media (max-width: 900px) {
    .rv-fast-grid,
    .rv-fast-joints {
        grid-template-columns: 1fr;
    }
}

html[data-theme="dark"] input,
html[data-theme="dark"] textarea,
html[data-theme="dark"] select,
html[data-theme="dark"] label,
.dark input,
.dark textarea,
.dark select,
.dark label {
    background: #ffffff !important;
    color: #1a365d !important;
}

.gradio-container,
.gradio-container .contain,
.gradio-container .wrap,
.gradio-container .block,
.gradio-container .form,
.gradio-container .panel,
.gradio-container .tabs,
.gradio-container .tabitem,
.gradio-container .tab-nav,
.gradio-container .dataframe,
.gradio-container .table-wrap,
.gradio-container table,
.gradio-container thead,
.gradio-container tbody,
.gradio-container tr,
.gradio-container th,
.gradio-container td,
.gradio-container iframe,
.gradio-container .file-preview,
.gradio-container .empty,
.gradio-container .dropzone,
.gradio-container .upload-container,
.gradio-container [data-testid="block-info"],
.gradio-container [data-testid="component-wrapper"],
.gradio-container [data-testid="dataframe"],
.gradio-container [data-testid="video"],
.gradio-container [data-testid="image"] {
    background-color: #ffffff !important;
    color: #1a365d !important;
}

.gradio-container input,
.gradio-container textarea,
.gradio-container select,
.gradio-container table input,
.gradio-container table textarea {
    background-color: #ffffff !important;
    color: #1a365d !important;
    -webkit-text-fill-color: #1a365d !important;
}

.gradio-container th {
    background-color: #f1f5f9 !important;
    color: #1a365d !important;
}

.gradio-container td {
    background-color: #ffffff !important;
    color: #1a365d !important;
    border-color: #e2e8f0 !important;
}

#global-language-toggle,
.global-language-toggle {
    position: fixed !important;
    top: 14px !important;
    right: 28px !important;
    z-index: 1200 !important;
    background: rgba(255, 255, 255, 0.96) !important;
    border: 1px solid rgba(26, 54, 93, 0.18) !important;
    border-radius: 9999px !important;
    padding: 0 !important;
    box-shadow: 0 8px 28px rgba(26, 54, 93, 0.12) !important;
}

#global-language-toggle,
#global-language-toggle *,
#global-language-toggle button,
.global-language-toggle,
.global-language-toggle *,
.global-language-toggle button {
    color: #1a365d !important;
    font-size: 13px !important;
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    border-radius: 9999px !important;
    min-width: 132px !important;
    padding: 8px 14px !important;
    font-weight: 650 !important;
}

.gradio-container .why-section h2,
.gradio-container .why-section p[data-i18n="why_subtitle"] {
    color: white !important;
    font-weight: 600 !important;
}

.gradio-container .cta-section * {
    color: white !important;
}

.gradio-container .cta-section h2,
.gradio-container .cta-section p,
.gradio-container .cta-section button {
    color: white !important;
    text-shadow: 0 1px 3px rgba(0,0,0,0.5);
}

.gradio-container .home-content p[data-i18n="footer"] {
    color: white !important;
    font-weight: 600 !important;
    font-size: 18px !important;
    text-shadow: 0 1px 3px rgba(0,0,0,0.5);
}

.why-section {
    position: relative !important;
    z-index: 999 !important;
    margin-top: 80px;
    padding: 80px 40px 120px;
}

.why-section::before {
    content: "";
    position: absolute;
    top: 0;
    left: -25%;
    width: 150%;
    height: 100%;
    z-index: -1;
}

.gr-box {
    border: 1px solid #e2e8f0 !important;
    border-radius: 16px !important;
    background: #ffffff !important;
}

.gr-input {
    border: 1px solid #e2e8f0 !important;
    border-radius: 12px !important;
}

.gr-textbox textarea, .gr-textbox input {
    border: 1px solid #e2e8f0 !important;
    border-radius: 12px !important;
    background: #ffffff !important;
    color: #1a365d !important;
}

.gr-number input {
    background: #ffffff !important;
    color: #1a365d !important;
    border: 1px solid #e2e8f0 !important;
    border-radius: 12px !important;
}

.gr-input, .gr-box {
    background: #ffffff !important;
    color: #1a365d !important;
}

.gr-input *, .gr-box * {
    color: #1a365d !important;
}

.gr-dropdown, .gr-dropdown * {
    background: #ffffff !important;
    color: #1a365d !important;
}

.gr-dropdown input {
    color: #1a365d !important;
}

.gr-slider {
    border: 1px solid #e2e8f0 !important;
    border-radius: 16px !important;
    background: #f8fafc !important;
    padding: 16px !important;
}

.gr-video {
    border: 2px solid #e2e8f0 !important;
    border-radius: 20px !important;
    overflow: hidden !important;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05) !important;
    background: #f1f5f9 !important;
}

.gr-image, .gr-plot {
    border: 2px solid #e2e8f0 !important;
    border-radius: 16px !important;
    background: #f8fafc !important;
}

.gr-image img, .gr-plot svg {
    border-radius: 12px !important;
}

.gr-image .label, .gr-video .label, .gr-plot .label {
    color: #ffffff !important;
    font-weight: 600 !important;
    background: rgba(26, 54, 93, 0.8) !important;
    padding: 8px 12px !important;
    border-radius: 8px !important;
}

.gradio-container label,
.gradio-container input,
.gradio-container textarea,
.gradio-container select,
.gradio-container .wrap,
.gradio-container .wrap * {
    color: #1a365d !important;
}

.gr-video .gr-button, .gr-image .gr-button, .gr-plot .gr-button {
    color: #1a365d !important;
    border-color: #1a365d !important;
}

.gr-video input, .gr-image input, .gr-plot input {
    color: #1a365d !important;
}

.upload-zone,
.upload-zone *,
.gr-file,
.gr-file *,
.gr-video,
.gr-video * {
    color: #1a365d !important;
}

.gr-video video,
.gr-image img {
    background: #f8fafc !important;
}

.gr-video .label,
.gr-image .label,
.gr-plot .label {
    color: #ffffff !important;
}

.comparison-frame,
.comparison-frame *,
.comparison-frame [data-testid="image"],
.comparison-frame .image-container {
    background: #f8fafc !important;
}

.comparison-frame img {
    object-fit: contain !important;
    max-height: 780px !important;
}

.report-card {
    border-radius: 16px;
    border: 1px solid #e2e8f0;
    background: #ffffff;
    padding: 16px 18px;
    margin: 12px 0;
    box-shadow: 0 8px 24px rgba(26, 54, 93, 0.06);
}

.report-card.normal { border-left: 6px solid #22c55e; }
.report-card.low { border-left: 6px solid #facc15; background: #fffdf2; }
.report-card.medium { border-left: 6px solid #fb923c; background: #fff7ed; }
.report-card.high { border-left: 6px solid #ef4444; background: #fff5f5; }

.report-head {
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 800;
    color: #1a365d;
    margin-bottom: 8px;
}

.severity-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    border-radius: 999px;
    padding: 4px 10px;
    font-size: 12px;
    font-weight: 800;
}

.severity-pill.normal { background: #dcfce7; color: #166534 !important; }
.severity-pill.low { background: #fef9c3; color: #854d0e !important; }
.severity-pill.medium { background: #ffedd5; color: #9a3412 !important; }
.severity-pill.high { background: #fee2e2; color: #991b1b !important; }

.report-card.high .report-title { color: #b91c1c !important; }
.report-card.medium .report-title { color: #c2410c !important; }
.report-card.low .report-title { color: #a16207 !important; }
.report-card p {
    margin: 6px 0;
    color: #334155 !important;
}

.gr-markdown {
    color: #0f172a !important;
}

.gr-markdown h1, .gr-markdown h2, .gr-markdown h3, .gr-markdown h4 {
    color: #0f172a !important;
    font-weight: 700 !important;
}

.hero-section::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(15, 23, 42, 0.4);
    z-index: 0;
}

.hero-section::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 200px;
    background: linear-gradient(to bottom, transparent 0%, rgba(255, 255, 255, 1) 100%);
    z-index: 1;
    pointer-events: none;
}

.hero-content {
    position: relative;
    z-index: 2;
    text-align: center;
    max-width: 1000px;
    margin: 0 15% 0 auto;
    opacity: 1 !important;
    visibility: visible !important;
    display: block !important;
}

.hero-content * {
    opacity: 1 !important;
    visibility: visible !important;
}

.hero-tag {
    display: inline-block;
    padding: 10px 28px;
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: white !important;
    border-radius: 9999px;
    font-size: 14px;
    font-weight: 600;
    letter-spacing: 2px;
    text-transform: uppercase;
    margin-bottom: 32px;
}

.hero-title {
    font-size: 52px;
    font-weight: 800;
    line-height: 1.2;
    margin-bottom: 28px;
    color: white !important;
    letter-spacing: -0.5px;
}

.hero-subtitle {
    font-size: 24px;
    font-weight: 600;
    color: rgba(255, 255, 255, 0.9) !important;
    margin-bottom: 48px;
    letter-spacing: 1px;
    text-transform: uppercase;
}

.hero-btn {
    display: inline-block;
    padding: 18px 48px;
    background: white !important;
    color: #0f172a !important;
    border: none;
    border-radius: 9999px;
    font-size: 16px;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
    text-transform: uppercase;
    letter-spacing: 1px;
}

.hero-btn:hover {
    transform: translateY(-3px);
    box-shadow: 0 15px 50px rgba(0, 0, 0, 0.3);
}

@keyframes float {
    0%, 100% { transform: translateY(0px); }
    50% { transform: translateY(-20px); }
}

.gradient-text {
    background: linear-gradient(135deg, #1a365d 0%, #319795 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.btn-primary {
    background: linear-gradient(135deg, #1a365d 0%, #319795 100%) !important;
    color: white !important;
    border: none !important;
    border-radius: 9999px !important;
    padding: 16px 40px !important;
    font-weight: 600 !important;
    font-size: 16px !important;
    box-shadow: 0 10px 40px rgba(26, 54, 93, 0.2) !important;
    transition: all 0.3s ease !important;
}

.btn-primary:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 15px 50px rgba(26, 54, 93, 0.3) !important;
}

.feature-card {
    background: white;
    border-radius: 24px;
    padding: 32px;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;
    border: 1px solid rgba(0, 0, 0, 0.04);
}

.home-demo-video {
    display: block;
    width: 100%;
    height: auto;
    max-height: 720px;
    object-fit: cover;
    background: #0f172a;
}

.demo-video-fallback {
    min-height: 320px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f1f5f9;
    color: #1a365d !important;
    font-weight: 700;
    border-radius: 20px;
}

.feature-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
}

.section-light {
    background: #f8fafc;
}

.section-dark {
    background: #1a365d;
    color: white;
}

.demo-video-container {
    position: relative;
    width: 180%;
    margin-left: -40%;
    margin-right: -40%;
    overflow: hidden;
    box-shadow: 0 25px 80px rgba(26, 54, 93, 0.2);
    margin-bottom: -20px;
}

.demo-video {
    width: 100% !important;
    height: auto !important;
    display: block !important;
    border-radius: 0 !important;
    object-fit: cover !important;
}

.tab-nav {
    border: none !important;
    background: transparent !important;
}

.tab-nav button {
    border: none !important;
    background: transparent !important;
    color: #64748b !important;
    font-weight: 500 !important;
    padding: 12px 24px !important;
    border-radius: 12px !important;
    transition: all 0.2s ease !important;
}

.tab-nav button.selected {
    background: #1a365d !important;
    color: white !important;
}

.gr-button {
    border-radius: 16px !important;
    font-weight: 700 !important;
    transition: all 0.2s ease !important;
    color: #1a365d !important;
    background: white !important;
    border: 2px solid #1a365d !important;
    box-shadow: 0 4px 12px rgba(26, 54, 93, 0.15) !important;
}

.gr-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 8px 25px rgba(26, 54, 93, 0.25) !important;
    background: #f0f7ff !important;
}

.gr-button-primary {
    background: linear-gradient(135deg, #1a365d 0%, #319795 100%) !important;
    color: white !important;
    border: none !important;
}

.gr-button-primary:hover {
    background: linear-gradient(135deg, #2d4a7c 0%, #2d8a87 100%) !important;
    color: white !important;
}

.action-btn {
    border: 2px solid #1a365d !important;
    color: #1a365d !important;
    background: white !important;
    font-weight: 700 !important;
    box-shadow: 0 4px 12px rgba(26, 54, 93, 0.2) !important;
    border-radius: 16px !important;
}

.action-btn:hover {
    background: #f0f7ff !important;
    border-color: #2d4a7c !important;
    box-shadow: 0 6px 20px rgba(26, 54, 93, 0.3) !important;
    transform: translateY(-2px);
}

.back-home-btn {
    border: 3px solid #1a365d !important;
    color: #1a365d !important;
    background: white !important;
    font-weight: 700 !important;
    font-size: 18px !important;
    box-shadow: 0 4px 12px rgba(26, 54, 93, 0.2) !important;
    border-radius: 16px !important;
    padding: 12px 24px !important;
}

.back-home-btn:hover {
    background: #f0f7ff !important;
    border-color: #2d4a7c !important;
    box-shadow: 0 6px 20px rgba(26, 54, 93, 0.3) !important;
}

.gr-video {
    border-radius: 20px !important;
    overflow: hidden !important;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1) !important;
}

.gr-slider input[type="range"]::-webkit-slider-thumb {
    background: #1a365d !important;
}

.report-container {
    max-height: 500px;
    overflow-y: auto;
    padding: 24px;
    background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
    border-radius: 20px;
    border: 1px solid #e2e8f0;
    color: #1a365d;
}

.upload-zone {
    border: 3px dashed #cbd5e1 !important;
    border-radius: 24px !important;
    min-height: 300px !important;
    transition: all 0.3s ease !important;
}

.upload-zone:hover {
    border-color: #1a365d !important;
    background: #f8fafc !important;
}

.home-content, .tool-content {
    padding-top: 0 !important;
    width: 100% !important;
    overflow: visible !important;
}

.main-tabs {
    display: block !important;
    visibility: visible !important;
    opacity: 1 !important;
    background: #ffffff !important;
}

.main-tabs > div,
.main-tabs [role="tabpanel"],
.home-content,
.tool-content {
    visibility: visible !important;
    opacity: 1 !important;
}

.tool-header {
    padding: 24px 32px !important;
    align-items: center !important;
    border-bottom: 1px solid #f1f5f9 !important;
    margin-bottom: 24px !important;
}

.tool-header button {
    background: transparent !important;
    border: 1px solid #e2e8f0 !important;
    color: #64748b !important;
    border-radius: 12px !important;
    padding: 8px 20px !important;
    font-weight: 500 !important;
    transition: all 0.2s ease !important;
}

.tool-header button:hover {
    border-color: #1a365d !important;
    color: #1a365d !important;
    background: transparent !important;
}

.usage-panel {
    border: 1px solid #e2e8f0;
    background: #ffffff;
    border-radius: 20px;
    padding: 24px;
    box-shadow: 0 10px 40px rgba(26, 54, 93, 0.08);
}

.usage-grid {
    display: grid;
    grid-template-columns: repeat(6, minmax(0, 1fr));
    gap: 12px;
    margin-bottom: 18px;
}

.usage-card {
    border: 1px solid #e2e8f0;
    background: #f8fafc;
    border-radius: 16px;
    padding: 16px;
}

.usage-card span {
    display: block;
    color: #64748b !important;
    font-size: 12px;
    margin-bottom: 8px;
}

.usage-card strong {
    display: block;
    color: #1a365d !important;
    font-size: 30px;
    line-height: 1;
}

.usage-note {
    color: #475569 !important;
    font-size: 13px;
    line-height: 1.8;
    word-break: break-word;
}

.rv-home {
    width: 100% !important;
    overflow: hidden !important;
    background: #ffffff !important;
}

.rv-hero {
    min-height: 680px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 96px 32px;
    position: relative;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.rv-hero-panel {
    width: min(1080px, 100%);
    text-align: center;
    position: relative;
    z-index: 2;
}

.rv-eyebrow {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 8px 18px;
    border-radius: 999px;
    background: rgba(255,255,255,0.18);
    border: 1px solid rgba(255,255,255,0.35);
    color: #ffffff !important;
    font-size: 14px;
    font-weight: 800;
    margin-bottom: 24px;
}

.rv-hero h1 {
    color: #ffffff !important;
    font-size: 56px;
    line-height: 1.1;
    margin: 0 auto 22px;
    max-width: 980px;
    font-weight: 850;
}

.rv-hero p {
    color: rgba(255,255,255,0.92) !important;
    font-size: 24px;
    font-weight: 650;
    margin: 0 0 36px;
}

.rv-hero-actions {
    display: flex;
    justify-content: center;
    gap: 14px;
    flex-wrap: wrap;
}

.rv-primary-link,
.rv-secondary-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-height: 48px;
    padding: 0 26px;
    border-radius: 999px;
    font-weight: 800;
    text-decoration: none !important;
    cursor: pointer;
}

.rv-primary-link {
    background: #ffffff !important;
    color: #12325b !important;
}

.rv-secondary-link {
    background: rgba(255,255,255,0.14) !important;
    color: #ffffff !important;
    border: 1px solid rgba(255,255,255,0.45);
}

.rv-section {
    padding: 72px 32px;
    background: #ffffff;
}

.rv-section.alt {
    background: #f8fafc;
}

.rv-section-inner {
    max-width: 1120px;
    margin: 0 auto;
}

.rv-section-title {
    color: #1a365d !important;
    font-size: 34px;
    line-height: 1.2;
    font-weight: 850;
    margin: 0 0 14px;
    text-align: center;
}

.rv-section-subtitle {
    color: #64748b !important;
    font-size: 16px;
    line-height: 1.7;
    max-width: 680px;
    margin: 0 auto 34px;
    text-align: center;
}

.rv-card-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 18px;
}

.rv-info-card {
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 18px;
    padding: 24px;
    box-shadow: 0 12px 36px rgba(26,54,93,0.08);
}

.rv-info-card h3 {
    color: #1a365d !important;
    font-size: 18px;
    margin: 0 0 10px;
    font-weight: 800;
}

.rv-info-card p {
    color: #475569 !important;
    font-size: 14px;
    line-height: 1.65;
    margin: 0;
}

.rv-demo-frame {
    width: min(980px, 100%);
    margin: 0 auto;
    overflow: hidden;
    border-radius: 20px;
    background: #f1f5f9;
    box-shadow: 0 20px 60px rgba(26,54,93,0.14);
    border: 1px solid #dbe4ef;
}

.rv-cta {
    padding: 82px 32px;
    text-align: center;
    background-size: cover;
    background-position: center;
    position: relative;
}

.rv-cta::before {
    content: "";
    position: absolute;
    inset: 0;
    background: rgba(26,54,93,0.68);
}

.rv-cta-inner {
    position: relative;
    z-index: 1;
    max-width: 720px;
    margin: 0 auto;
}

.rv-cta h2,
.rv-cta p {
    color: #ffffff !important;
}

.rv-cta h2 {
    font-size: 34px;
    margin: 0 0 16px;
}

.rv-cta p {
    font-size: 18px;
    margin: 0 0 28px;
}

@media (max-width: 800px) {
    .rv-hero {
        min-height: 560px;
        padding: 72px 20px;
    }
    .rv-hero h1 {
        font-size: 36px;
    }
    .rv-hero p {
        font-size: 18px;
    }
    .rv-card-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 900px) {
    .usage-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
}

"""


def t(lang: str, key: str) -> str:
    lang_map = i18n.get(lang, i18n["zh"])
    return lang_map.get(key, i18n["zh"].get(key, key))


def tool_header_html(lang: str) -> str:
    return f"""
                <div style="position: relative; padding: 20px; border: 3px solid #1a365d; border-radius: 16px; overflow: hidden; margin-bottom: 24px;">
                    <img src="data:image/png;base64,{bg_base64}" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; z-index: 0;">
                    <div style="position: relative; z-index: 1; display: flex; align-items: center; gap: 20px;">
                        <button onclick="switchToHome()" style="border: 3px solid #1a365d; color: #1a365d; background: rgba(255,255,255,0.9); font-weight: 700; font-size: 18px; padding: 12px 24px; border-radius: 16px; cursor: pointer; transition: all 0.2s; box-shadow: 0 4px 12px rgba(26,54,93,0.2);">{t(lang, "back_home")}</button>
                        <div style="flex: 1; text-align: center;">
                            <div style="display: inline-block; background: rgba(255,255,255,0.9); padding: 12px 30px; border-radius: 12px; border: 2px solid #1a365d; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
                                <h1 style="font-size: 36px; font-weight: 700; color: #1a365d; margin: 0; white-space: nowrap;">{t(lang, "tool_title")}</h1>
                                <p style="font-size: 18px; color: #1a365d; margin: 8px 0 0; font-weight: 500; white-space: nowrap;">{t(lang, "tool_subtitle")}</p>
                            </div>
                        </div>
                    </div>
                </div>
                """


def navbar_html(lang: str) -> str:
    return f"""
<div style="position: fixed; top: 0; left: 0; right: 0; z-index: 1000; background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(20px); border-bottom: 1px solid rgba(0,0,0,0.06);">
    <div style="max-width: 1200px; margin: 0 auto; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between;">
        <div style="display: flex; align-items: center; gap: 12px; cursor: pointer;" id="nav-logo">
            <div style="width: 40px; height: 40px; background: linear-gradient(135deg, #1a365d 0%, #319795 100%); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
            </div>
            <span style="font-size: 20px; font-weight: 700; color: #1a365d;">RowingValidator Beta</span>
        </div>
        <div style="display: flex; align-items: center; gap: 24px; padding-right: 160px;">
            <a href="#features" style="color: #64748b; text-decoration: none; font-size: 15px; font-weight: 500;">{t(lang, "nav_features")}</a>
            <a href="#demo" style="color: #64748b; text-decoration: none; font-size: 15px; font-weight: 500;">{t(lang, "nav_demo")}</a>
        </div>
    </div>
</div>
<div style="height: 72px;"></div>
    """


def home_html(lang: str) -> str:
    hero_background = (
        f"linear-gradient(90deg, rgba(15,23,42,0.70), rgba(15,23,42,0.36)), url(data:image/png;base64,{bg_base64})"
        if bg_base64
        else "linear-gradient(135deg, #1a365d 0%, #319795 100%)"
    )
    cta_background = (
        f"linear-gradient(90deg, rgba(26,54,93,0.72), rgba(49,151,149,0.48)), url(data:image/png;base64,{bg_cta_base64})"
        if bg_cta_base64
        else "linear-gradient(135deg, #1a365d 0%, #319795 100%)"
    )
    return f"""
<div class="rv-home">
    <section class="rv-hero" style="background-image: {hero_background};">
        <div class="rv-hero-panel">
            <div class="rv-eyebrow">{t(lang, "for_coaches")}</div>
            <h1>{t(lang, "hero_title")}</h1>
            <p>{t(lang, "hero_subtitle")}</p>
            <div class="rv-hero-actions">
                <button class="rv-primary-link" onclick="switchToTool()">{t(lang, "start_free")}</button>
                <a class="rv-secondary-link" href="#demo">{t(lang, "nav_demo")}</a>
            </div>
        </div>
    </section>

    <section id="features" class="rv-section">
        <div class="rv-section-inner">
            <h2 class="rv-section-title">{t(lang, "why_title")}</h2>
            <p class="rv-section-subtitle">{t(lang, "why_subtitle")}</p>
            <div class="rv-card-grid">
                <div class="rv-info-card">
                    <h3>{t(lang, "feature_1_title")}</h3>
                    <p>{t(lang, "feature_1_desc")}</p>
                </div>
                <div class="rv-info-card">
                    <h3>{t(lang, "feature_2_title")}</h3>
                    <p>{t(lang, "feature_2_desc")}</p>
                </div>
                <div class="rv-info-card">
                    <h3>{t(lang, "feature_3_title")}</h3>
                    <p>{t(lang, "feature_3_desc")}</p>
                </div>
            </div>
        </div>
    </section>

    <section class="rv-section alt">
        <div class="rv-section-inner">
            <h2 class="rv-section-title">{t(lang, "compare_title")}</h2>
            <p class="rv-section-subtitle">{t(lang, "compare_subtitle")}</p>
            <div class="rv-card-grid">
                <div class="rv-info-card">
                    <h3>{t(lang, "why_1_title")}</h3>
                    <p>{t(lang, "why_1_desc")}</p>
                </div>
                <div class="rv-info-card">
                    <h3>{t(lang, "why_2_title")}</h3>
                    <p>{t(lang, "why_2_desc")}</p>
                </div>
                <div class="rv-info-card">
                    <h3>{t(lang, "why_3_title")}</h3>
                    <p>{t(lang, "why_3_desc")}</p>
                </div>
            </div>
        </div>
    </section>

    <section id="demo" class="rv-section">
        <div class="rv-section-inner">
            <h2 class="rv-section-title">{t(lang, "demo_title")}</h2>
            <p class="rv-section-subtitle">{t(lang, "demo_subtitle")}</p>
            <div class="rv-demo-frame">{demo_video_html()}</div>
        </div>
    </section>

    <section class="rv-cta" style="background-image: {cta_background};">
        <div class="rv-cta-inner">
            <h2>{t(lang, "cta_title")}</h2>
            <p>{t(lang, "cta_subtitle")}</p>
            <button class="rv-primary-link" onclick="switchToTool()">{t(lang, "start_free")}</button>
        </div>
    </section>
</div>
    """


def localize_diagnosis(diagnosis: dict, lang: str) -> dict:
    lang = lang if lang in ("zh", "en") else "zh"
    error_id = diagnosis.get("error_id", "")
    localized = ERROR_LOCALIZATION.get(error_id, {}).get(lang, {})
    severity = diagnosis.get("severity", "normal")
    return {
        **diagnosis,
        "phase": localized.get("phase", diagnosis.get("phase", "")),
        "error_name": localized.get("name", diagnosis.get("error_name", "")),
        "description": localized.get("description", diagnosis.get("description", "")),
        "suggestion": localized.get("suggestion", diagnosis.get("suggestion", "")),
        "severity_text": SEVERITY_LOCALIZATION.get(lang, SEVERITY_LOCALIZATION["zh"]).get(severity, severity),
    }


def make_error_table_rows(diagnoses, lang: str):
    if not diagnoses:
        return [["-", "-", "-", "-", "-"]]
    rows = []
    for d in diagnoses:
        if not isinstance(d, dict):
            rows.append([str(d), "", "", "", ""])
            continue
        item = localize_diagnosis(d, lang)
        rows.append([
            item.get("phase", ""),
            item.get("error_name", ""),
            item.get("severity_text", ""),
            item.get("description", ""),
            item.get("suggestion", ""),
        ])
    return rows


def localize_evidence(evidence: str, lang: str) -> str:
    if lang != "en" or not evidence:
        return evidence or "-"
    replacements = [
        ("躯干角度", "Trunk angle "),
        ("上半身误差比", ", upper-body error ratio "),
        ("手肘误差比", "Elbow error ratio "),
        ("座板速度是手柄的", "Seat speed is "),
        ("膝盖误差比", "Knee error ratio "),
        ("躯干后仰", "Trunk layback "),
        ("膝盖角度", "Knee angle "),
        ("手腕误差比", "Wrist error ratio "),
        ("抓水误差比", "Catch error ratio "),
        ("速度数据不足", "Insufficient speed data"),
        ("检测失败", "Detection failed"),
        ("倍", "x"),
        ("°", " deg"),
    ]
    translated = evidence
    for zh, en in replacements:
        translated = translated.replace(zh, en)
    translated = translated.replace("手柄的", "the handle speed")
    return translated


def severity_icon(severity: str) -> str:
    return {
        "normal": "✓",
        "low": "!",
        "medium": "!!",
        "high": "!!!",
    }.get(severity, "!")


def make_report_markdown(diagnoses, score: str, lang: str) -> str:
    if not diagnoses:
        return ""
    ordered = sorted(
        [d for d in diagnoses if isinstance(d, dict)],
        key=lambda item: {"high": 0, "medium": 1, "low": 2, "normal": 3}.get(item.get("severity", "normal"), 4),
    )
    if lang == "en":
        cards = [f"<h2>Technical Diagnosis Report</h2><p><strong>Score:</strong> {score or '-'}</p><h3>Findings</h3>"]
        for d in ordered:
            item = localize_diagnosis(d, "en")
            sev = item.get("severity", "normal")
            cards.append(f"""
<div class="report-card {sev}">
  <div class="report-head">
    <span class="severity-pill {sev}">{severity_icon(sev)} {item['severity_text']}</span>
    <span class="report-title">{item['phase']} | {item['error_name']}</span>
  </div>
  <p><strong>Description:</strong> {item['description']}</p>
  <p><strong>Evidence:</strong> {localize_evidence(d.get('evidence', '-'), 'en')}</p>
  <p><strong>Suggestion:</strong> {item['suggestion']}</p>
</div>
""")
        return "\n".join(cards)
    cards = [f"<h2>技术诊断报告</h2><p><strong>评分:</strong>{score or '-'}</p><h3>检测结果</h3>"]
    for d in ordered:
        item = localize_diagnosis(d, "zh")
        sev = item.get("severity", "normal")
        cards.append(f"""
<div class="report-card {sev}">
  <div class="report-head">
    <span class="severity-pill {sev}">{severity_icon(sev)} {item['severity_text']}</span>
    <span class="report-title">{item['phase']} | {item['error_name']}</span>
  </div>
  <p><strong>描述:</strong>{item['description']}</p>
  <p><strong>证据:</strong>{d.get('evidence', '-')}</p>
  <p><strong>建议:</strong>{item['suggestion']}</p>
</div>
""")
    return "\n".join(cards)



with gr.Blocks(title="RowingValidator Beta - AI Rowing Analysis") as demo:
    lang_state = gr.State("zh")
    current_page = gr.State("home")
    clip_state = gr.State("")
    cycles_state = gr.State([])
    score_state = gr.State("")
    report_state = gr.State("")
    diagnoses_state = gr.State([])
    comparison_video_state = gr.State("")
    mse_state = gr.State(None)
    overlap_state = gr.State(None)
    session_state = gr.State("")
    upload_guard_input = gr.Textbox(value="empty", visible=False)

    nav_output = gr.HTML(navbar_html("zh"))
    language_button = gr.Button(
        "🌐 EN / 中文",
        elem_id="global-language-toggle",
        elem_classes=["global-language-toggle"],
    )

    with gr.Tabs(elem_classes=["main-tabs"]) as main_tabs:
        with gr.TabItem("首页 / Home", id="home-tab"):
            with gr.Column(elem_classes=["home-content"]):
                home_output = gr.HTML(home_html("zh"))
                gr.HTML("""<div style="display:none">
<div style="min-height: 100vh; padding-top: 0;">
    <div class="hero-section">
        <div class="hero-content">
            <div class="hero-tag" data-i18n="for_coaches">FOR COACHES & ATHLETES</div>
            <h1 class="hero-title" data-i18n="hero_title">ADVANCED AI ROWING VIDEO ANALYSIS AND VIRTUAL COACHING PLATFORM</h1>
            <div class="hero-subtitle" data-i18n="hero_subtitle">ROW SAFELY & EFFICIENTLY</div>
            <button class="hero-btn" onclick="switchToTool()" data-i18n="start_free">START FOR FREE</button>
        </div>
    </div>

    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px; max-width: 900px; margin: -40px auto 0; padding: 0 40px; position: relative; z-index: 10;">
        <div class="feature-card" style="background: white; border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.06); transition: all 0.3s ease;">
            <div style="width: 56px; height: 56px; background: linear-gradient(135deg, #fbbf24 0%, #f97316 100%); border-radius: 18px; display: flex; align-items: center; justify-content: center; margin-bottom: 20px;">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
            </div>
            <h3 style="font-size: 18px; font-weight: 600; color: #1a365d; margin-bottom: 8px;" data-i18n="feature_1_title">提高速度</h3>
            <p style="font-size: 14px; color: #64748b; line-height: 1.6;" data-i18n="feature_1_desc">通过技术优化,提升划行速度</p>
        </div>
        <div class="feature-card" style="background: white; border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.06); transition: all 0.3s ease;">
            <div style="width: 56px; height: 56px; background: linear-gradient(135deg, #60a5fa 0%, #06b6d4 100%); border-radius: 18px; display: flex; align-items: center; justify-content: center; margin-bottom: 20px;">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"/></svg>
            </div>
            <h3 style="font-size: 18px; font-weight: 600; color: #1a365d; margin-bottom: 8px;" data-i18n="feature_2_title">提升效率</h3>
            <p style="font-size: 14px; color: #64748b; line-height: 1.6;" data-i18n="feature_2_desc">提高能量转换效率,划得更省力</p>
        </div>
        <div class="feature-card" style="background: white; border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.06); transition: all 0.3s ease;">
            <div style="width: 56px; height: 56px; background: linear-gradient(135deg, #4ade80 0%, #10b981 100%); border-radius: 18px; display: flex; align-items: center; justify-content: center; margin-bottom: 20px;">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
            </div>
            <h3 style="font-size: 18px; font-weight: 600; color: #1a365d; margin-bottom: 8px;" data-i18n="feature_3_title">减少受伤</h3>
            <p style="font-size: 14px; color: #64748b; line-height: 1.6;" data-i18n="feature_3_desc">纠正错误动作,减少运动损伤</p>
        </div>
    </div>

    <div class="why-section" style="position: relative; overflow: visible; padding: 160px 40px 200px;">
        <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.3); z-index: 1;"></div>
        <div style="max-width: 1000px; margin: 0 auto; text-align: center; position: relative; z-index: 2;">
            <div style="background: rgba(0,0,0,0.5); backdrop-filter: blur(10px); border-radius: 24px; padding: 40px 60px; margin-bottom: 64px;">
                <div style="display: inline-block; padding: 8px 24px; background: rgba(49, 151, 149, 0.8); color: white; border-radius: 9999px; font-size: 18px; font-weight: 500; margin-bottom: 24px;" data-i18n="why_title">
                    为什么选择我们
                </div>
                <h2 style="font-size: 44px; font-weight: 700; color: white; margin-bottom: 16px;" data-i18n="why_title">为什么选择我们</h2>
                <p style="font-size: 20px; color: white; font-weight: 600; max-width: 500px; margin: 0 auto;" data-i18n="why_subtitle">
                    我们的AI技术帮助您深入分析划船动作,发现问题并提供专业指导
                </p>
            </div>
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 32px; text-align: left;">
                <div style="background: rgba(255,255,255,0.9); border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.1);">
                    <div style="width: 64px; height: 64px; background: linear-gradient(135deg, #a855f7 0%, #4f46e5 100%); border-radius: 20px; display: flex; align-items: center; justify-content: center; margin-bottom: 24px;">
                        <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg>
                    </div>
                    <h3 style="font-size: 20px; font-weight: 600; color: #1a365d; margin-bottom: 12px;" data-i18n="why_1_title">AI精准分析</h3>
                    <p style="font-size: 15px; color: #1a365d; line-height: 1.6;" data-i18n="why_1_desc">基于YOLO和自编码器模型,精准识别动作细节,提供专业反馈</p>
                </div>
                <div style="background: rgba(255,255,255,0.9); border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.1);">
                    <div style="width: 64px; height: 64px; background: linear-gradient(135deg, #3b82f6 0%, #06b6d4 100%); border-radius: 20px; display: flex; align-items: center; justify-content: center; margin-bottom: 24px;">
                        <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/></svg>
                    </div>
                    <h3 style="font-size: 20px; font-weight: 600; color: #1a365d; margin-bottom: 12px;" data-i18n="why_2_title">实时对比</h3>
                    <p style="font-size: 15px; color: #1a365d; line-height: 1.6;" data-i18n="why_2_desc">将您的动作与标准动作进行实时对比,直观展示差异</p>
                </div>
                <div style="background: rgba(255,255,255,0.9); border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.1);">
                    <div style="width: 64px; height: 64px; background: linear-gradient(135deg, #f43f5e 0%, #ec4899 100%); border-radius: 20px; display: flex; align-items: center; justify-content: center; margin-bottom: 24px;">
                        <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"/></svg>
                    </div>
                    <h3 style="font-size: 20px; font-weight: 600; color: #1a365d; margin-bottom: 12px;" data-i18n="why_3_title">个性化建议</h3>
                    <p style="font-size: 15px; color: #1a365d; line-height: 1.6;" data-i18n="why_3_desc">根据您的动作特点,提供针对性的改进建议和训练计划</p>
                </div>
            </div>
        </div>
    </div>

    <div style="padding: 80px 0;">
        <div style="max-width: 900px; margin: 0 auto; text-align: center; position: relative; z-index: 2;">
            <h2 style="font-size: 36px; font-weight: 700; color: #1a365d; margin-bottom: 16px;" data-i18n="demo_title">观看使用演示</h2>
            <p style="font-size: 16px; color: #64748b; margin-bottom: 48px;" data-i18n="demo_subtitle">了解如何使用我们的工具分析划船动作</p>
        </div>
    </div>

    <div class="cta-section" style="position: relative; width: 150%; margin-left: -25%; margin-right: -25%; padding: 220px 40px 340px; overflow: visible; margin-top: -60px;">
        <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(26,54,93,0.6); z-index: 1;"></div>
        <div style="max-width: 600px; margin: 0 auto; text-align: center; position: relative; z-index: 2;">
            <h2 style="font-size: 44px; font-weight: 800; color: white; margin-bottom: 24px;" data-i18n="cta_title">准备好提升您的划船技术了吗?</h2>
            <p style="font-size: 22px; font-weight: 600; color: white; margin-bottom: 48px;" data-i18n="cta_subtitle">
                加入数千名使用我们的AI分析提升技术的运动员
            </p>
            <button class="btn-primary" style="background: linear-gradient(135deg, #1a365d 0%, #319795 100%); color: white; font-size: 18px; font-weight: 600; padding: 16px 48px; border: none; border-radius: 9999px; cursor: pointer; box-shadow: 0 4px 20px rgba(26, 54, 93, 0.3); transition: all 0.2s;" onclick="document.querySelector('#tool-tab').click()" data-i18n="start_btn">免费开始 →</button>
        </div>
    </div>

    <div style="background: transparent; padding: 32px; text-align: center; border-top: none; margin-top: -230px; position: relative; z-index: 10;">
        <p style="color: white; font-size: 18px; font-weight: 600;" data-i18n="footer">© 2026 RowingValidator Beta. All rights reserved.</p>
    </div>
</div>
                """)

        with gr.TabItem("工具 / Tool", id="tool-tab"):
            with gr.Column(elem_classes=["tool-content"]):
                tool_header = gr.HTML(tool_header_html("zh"))

                with gr.Tabs(elem_classes=["tab-nav"]):
                    with gr.TabItem("📹 视频处理 / Process"):
                        with gr.Row():
                            with gr.Column(scale=1):
                                video_input = gr.Video(
                                    label="上传视频",
                                    format=None,
                                    elem_classes=["upload-zone"],
                                )

                                clip_settings_md = gr.Markdown("### 视频裁剪设置")
                                with gr.Row():
                                    start_input = gr.Number(value=0, precision=2, label="开始时间(秒)")
                                    end_input = gr.Number(value=0, precision=2, label="结束时间(0=视频末尾)")
                                create_clip_button = gr.Button("创建裁剪片段", variant="primary", elem_classes=["action-btn"])
                                clip_preview = gr.Video(label="裁剪预览", format="mp4", include_audio=False)
                                clip_summary = gr.Textbox(label="裁剪摘要", lines=3)

                                with gr.Row():
                                    process_button = gr.Button("提取火柴人并叠加原视频", variant="primary", elem_classes=["action-btn"])
                                    stop_button = gr.Button("停止处理", variant="stop", elem_classes=["action-btn"])

                            with gr.Column(scale=1):
                                stickman_result_md = gr.Markdown("### 🎬 火柴人叠加结果")
                                video_output = gr.Video(label="火柴人叠加视频", format="mp4", include_audio=False)
                                file_output = gr.File(label="下载叠加视频")
                                summary_output = gr.Textbox(label="处理摘要", lines=5)

                    with gr.TabItem("🔄 动作对比 / Compare"):
                        with gr.Row():
                            with gr.Column(scale=3):
                                compare_title_md = gr.Markdown("### 🆚 动作对比")
                                fast_frame_viewer = gr.HTML(
                                    "<div class='fast-frame-viewer-placeholder'>验证动作后可使用快速帧浏览器。</div>"
                                )
                                comparison_output = gr.Image(label="逐帧对比:实际动作 vs 模型重建", type="filepath", height=720, elem_classes=["comparison-frame"], visible=False)
                                comparison_file = gr.File(label="下载对比视频")
                                mse_analysis_md = gr.Markdown("### MSE 逐帧分析")
                                mse_plot_output = gr.Image(label="总 MSE 与各关节 MSE", type="filepath", height=680, visible=False)
                            with gr.Column(scale=1):
                                score_md = gr.Markdown("### 动作评分")
                                score_output = gr.Textbox(label="评分", value="", interactive=False)
                                
                                cycle_select_md = gr.Markdown("### 周期选择")
                                cycle_dropdown = gr.Dropdown(label="选择分析周期", choices=[], interactive=False)
                                validate_button = gr.Button("验证动作并生成对比", variant="primary", elem_classes=["action-btn"])
                                
                                cycle_info_md = gr.Markdown("### 周期信息")
                                cycle_info_output = gr.Textbox(label="周期详情", lines=3)
                                frame_slider = gr.Slider(0, 99, value=0, step=1, label="选择归一化帧", interactive=False, visible=False)
                        with gr.Row():
                            frame_joint_mse_table = gr.Dataframe(
                                headers=["关键点", "原始名称", "当前帧 MSE"],
                                datatype=["str", "str", "str"],
                                label="各关节 MSE 详情",
                            )

                    with gr.TabItem("📋 诊断报告 / Report"):
                        with gr.Column():
                            report_title_md = gr.Markdown("## 技术诊断报告")
                            report_markdown = gr.Markdown()

                            error_list_md = gr.Markdown("### 错误检测列表")
                            error_table = gr.Dataframe(
                                headers=["阶段", "错误类型", "严重程度", "描述", "建议"],
                                datatype=["str", "str", "str", "str", "str"],
                                label="错误详情",
                            )

                            error_stats_md = gr.Markdown("### 错误分布统计")
                            error_stats_output = gr.HTML()

                # Keep usage tracking connected to existing callbacks without exposing
                # a user-facing Usage tab.
                usage_title_md = gr.Markdown("", visible=False)
                usage_stats_output = gr.HTML(usage_summary_html(), visible=False)
                refresh_usage_button = gr.Button("", visible=False)


    # 辅助函数
    def update_tool_language(current_lang, session_id, diagnoses, score):
        lang_state_value = "en" if current_lang == "zh" else "zh"
        log_usage_event("language_changed", session_id=session_id, details={"language": lang_state_value})
        if lang_state_value == "en":
            joint_headers = ["Keypoint", "Original Name", "Current Frame MSE"]
            error_headers = ["Phase", "Error Type", "Severity", "Description", "Suggestion"]
        else:
            joint_headers = ["关键点", "原始名称", "当前帧 MSE"]
            error_headers = ["阶段", "错误类型", "严重程度", "描述", "建议"]
        return (
            lang_state_value,
            gr.update(value="🌐 中文 / EN" if lang_state_value == "en" else "🌐 EN / 中文"),
            navbar_html(lang_state_value),
            home_html(lang_state_value),
            tool_header_html(lang_state_value),
            f"### {t(lang_state_value, 'clip_settings')}",
            gr.update(label=t(lang_state_value, "upload_label")),
            gr.update(label=t(lang_state_value, "start_time")),
            gr.update(label=t(lang_state_value, "end_time")),
            gr.update(value=t(lang_state_value, "create_clip")),
            gr.update(label=t(lang_state_value, "clip_preview")),
            gr.update(label=t(lang_state_value, "clip_summary")),
            gr.update(value=t(lang_state_value, "process_video")),
            gr.update(value=t(lang_state_value, "stop_process")),
            f"### {t(lang_state_value, 'stickman_result')}",
            gr.update(label=t(lang_state_value, "stickman_video")),
            gr.update(label=t(lang_state_value, "download_video")),
            gr.update(label=t(lang_state_value, "process_summary")),
            f"### {t(lang_state_value, 'compare_title')}",
            gr.update(label=t(lang_state_value, "compare_subtitle")),
            gr.update(label=t(lang_state_value, "download_compare")),
            f"### {t(lang_state_value, 'action_score')}",
            gr.update(label=t(lang_state_value, "score_label")),
            f"### {t(lang_state_value, 'cycle_select')}",
            gr.update(label=t(lang_state_value, "select_cycle")),
            gr.update(value=t(lang_state_value, "validate_action")),
            f"### {t(lang_state_value, 'cycle_info')}",
            gr.update(label=t(lang_state_value, "cycle_detail")),
            f"### {t(lang_state_value, 'mse_analysis')}",
            gr.update(label=t(lang_state_value, "select_frame")),
            gr.update(label=t(lang_state_value, "mse_plot")),
            gr.update(label=t(lang_state_value, "joint_mse"), headers=joint_headers),
            f"## {t(lang_state_value, 'report_title')}",
            make_report_markdown(diagnoses, score, lang_state_value),
            f"### {t(lang_state_value, 'error_list')}",
            gr.update(label=t(lang_state_value, "error_details"), headers=error_headers, value=make_error_table_rows(diagnoses, lang_state_value)),
            f"### {t(lang_state_value, 'error_stats')}",
            update_error_stats(diagnoses, lang_state_value),
            f"## {t(lang_state_value, 'usage_title')}",
            gr.update(value=t(lang_state_value, "usage_refresh")),
            usage_summary_html(),
        )

    def update_cycle_dropdown(cycles_payload):
        cycles = cycles_payload.get("cycles", []) if isinstance(cycles_payload, dict) else cycles_payload
        if not cycles:
            return gr.update(choices=[], value=None, interactive=False)
        fps = float(cycles_payload.get("output_fps", 30)) if isinstance(cycles_payload, dict) else 30
        choices = [
            (f"{i+1}. {label} (frames {s}-{e}, {e - s + 1}f, {(e - s + 1) / max(fps, 1e-6):.2f}s)", i)
            for i, (s, e, label) in enumerate(cycles)
        ]
        return gr.update(choices=choices, value=0, interactive=True)

    def update_cycle_info(cycles_payload, cycle_idx, lang="zh"):
        cycles = cycles_payload.get("cycles", []) if isinstance(cycles_payload, dict) else cycles_payload
        if not cycles or cycle_idx is None:
            return ""
        idx = int(cycle_idx)
        if idx < 0 or idx >= len(cycles):
            return ""
        s, e, label = cycles[idx]
        fps = float(cycles_payload.get("output_fps", 30)) if isinstance(cycles_payload, dict) else 30
        duration = (e - s + 1) / fps
        if lang == "en":
            return f"Cycle {idx+1}: {label}\nFrames: {s}-{e}\nDuration: {duration:.2f}s"
        return f"周期 {idx+1}: {label}\n帧范围: {s}-{e}\n时长: {duration:.2f}秒"

    def update_first_cycle_info(cycles_payload, lang="zh"):
        cycles = cycles_payload.get("cycles", []) if isinstance(cycles_payload, dict) else cycles_payload
        if not cycles:
            return ""
        return update_cycle_info(cycles_payload, 0, lang)

    def update_overlap_frame(overlap_payload, frame_idx):
        return render_overlap_frame(overlap_payload, frame_idx)

    def update_mse_frame(mse_payload, frame_idx):
        return render_mse_frame(mse_payload, frame_idx), make_frame_joint_mse_rows(mse_payload, frame_idx)

    def update_analysis_frame(overlap_payload, mse_payload, frame_idx):
        return (
            render_overlap_frame(overlap_payload, frame_idx),
            render_mse_frame(mse_payload, frame_idx),
            make_frame_joint_mse_rows(mse_payload, frame_idx),
        )

    def update_error_table(diagnoses, lang="zh"):
        return make_error_table_rows(diagnoses, lang)

    def update_error_stats(diagnoses, lang="zh"):
        if not diagnoses:
            empty_text = "No diagnostics yet" if lang == "en" else "暂无诊断数据"
            return f'<div style="text-align:center; padding:20px; color:#94a3b8;">{empty_text}</div>'

        severity_counts = {"normal": 0, "low": 0, "medium": 0, "high": 0}
        for d in diagnoses:
            if isinstance(d, dict):
                sev = d.get("severity", "normal")
                severity_counts[sev] = severity_counts.get(sev, 0) + 1

        total = len(diagnoses)
        normal_pct = (severity_counts["normal"] / total * 100) if total > 0 else 0
        low_pct = (severity_counts["low"] / total * 100) if total > 0 else 0
        medium_pct = (severity_counts["medium"] / total * 100) if total > 0 else 0
        high_pct = (severity_counts["high"] / total * 100) if total > 0 else 0

        labels = SEVERITY_LOCALIZATION.get(lang, SEVERITY_LOCALIZATION["zh"])
        return f"""
        <div style="display: flex; gap: 12px; justify-content: center; flex-wrap: wrap;">
            <div style="background: rgba(107, 203, 119, 0.1); border: 1px solid rgba(107, 203, 119, 0.3); border-radius: 12px; padding: 16px 24px; text-align: center; min-width: 100px;">
                <div style="font-size: 28px; font-weight: bold; color: #6BCB77;">{severity_counts['normal']}</div>
                <div style="font-size: 12px; color: #94a3b8;">{labels['normal']} ({normal_pct:.1f}%)</div>
            </div>
            <div style="background: rgba(255, 217, 61, 0.1); border: 1px solid rgba(255, 217, 61, 0.3); border-radius: 12px; padding: 16px 24px; text-align: center; min-width: 100px;">
                <div style="font-size: 28px; font-weight: bold; color: #FFD93D;">{severity_counts['low']}</div>
                <div style="font-size: 12px; color: #94a3b8;">{labels['low']} ({low_pct:.1f}%)</div>
            </div>
            <div style="background: rgba(255, 159, 67, 0.1); border: 1px solid rgba(255, 159, 67, 0.3); border-radius: 12px; padding: 16px 24px; text-align: center; min-width: 100px;">
                <div style="font-size: 28px; font-weight: bold; color: #FF9F43;">{severity_counts['medium']}</div>
                <div style="font-size: 12px; color: #94a3b8;">{labels['medium']} ({medium_pct:.1f}%)</div>
            </div>
            <div style="background: rgba(255, 107, 107, 0.1); border: 1px solid rgba(255, 107, 107, 0.3); border-radius: 12px; padding: 16px 24px; text-align: center; min-width: 100px;">
                <div style="font-size: 28px; font-weight: bold; color: #FF6B6B;">{severity_counts['high']}</div>
                <div style="font-size: 12px; color: #94a3b8;">{labels['high']} ({high_pct:.1f}%)</div>
            </div>
        </div>
        """

    def format_score_output(score):
        return str(score or "")

    def initialize_session():
        session_id = str(uuid.uuid4())
        log_usage_event("page_visit", session_id=session_id)
        return session_id, usage_summary_html()

    def track_video_input(video_path, session_id):
        source = resolve_uploaded_video_path(video_path)
        if not source or not source.exists():
            return "empty", usage_summary_html()
        details = {
            "file_extension": source.suffix.lower(),
            "file_size_mb": round(source.stat().st_size / (1024 * 1024), 3),
        }
        log_usage_event("video_upload", session_id=session_id, details=details)
        return "uploaded", usage_summary_html()

    def refresh_usage(session_id):
        log_usage_event("usage_refreshed", session_id=session_id)
        return usage_summary_html()

    def request_stop_processing(session_id):
        PROCESS_STOP_EVENT.set()
        log_usage_event("processing_stop_requested", session_id=session_id)
        return usage_summary_html()

    def create_clip_with_usage(video_path, start_sec, end_sec, upload_guard, session_id, progress=gr.Progress(track_tqdm=False)):
        try:
            clip_path, preview_path, summary = create_monitored_clip(
                video_path,
                start_sec,
                end_sec,
                upload_guard,
                progress,
            )
            if clip_path:
                log_usage_event(
                    "clip_created",
                    session_id=session_id,
                    details={
                        "start_sec": float(start_sec or 0),
                        "end_sec": float(end_sec or 0),
                    },
                )
            return clip_path, preview_path, summary, usage_summary_html()
        except Exception as exc:
            log_usage_event("error", session_id=session_id, details={"stage": "clip", "message": str(exc)})
            raise

    def build_stickman_with_usage(video_path, clip_path, upload_guard, session_id, progress=gr.Progress(track_tqdm=False)):
        log_usage_event("stickman_started", session_id=session_id)
        try:
            video_out, file_out, summary, cycles = build_stickman_video(
                video_path,
                clip_path,
                upload_guard,
                progress,
            )
            cycle_list = cycles.get("cycles", []) if isinstance(cycles, dict) else cycles
            log_usage_event(
                "stickman_completed",
                session_id=session_id,
                details={
                    "cycles_detected": len(cycle_list or []),
                    "has_output_video": bool(video_out),
                },
            )
            return video_out, file_out, summary, cycles, usage_summary_html()
        except Exception as exc:
            log_usage_event("error", session_id=session_id, details={"stage": "stickman", "message": str(exc)})
            raise

    def validate_with_usage(video_path, clip_path, cycles, cycle_index, lang, session_id, progress=gr.Progress(track_tqdm=False)):
        cycle_list = cycles.get("cycles", []) if isinstance(cycles, dict) else cycles
        selected_label = ""
        if cycle_list and cycle_index is not None and 0 <= int(cycle_index) < len(cycle_list):
            selected_label = cycle_list[int(cycle_index)][2]
        log_usage_event(
            "diagnosis_started",
            session_id=session_id,
            details={"cycle_index": cycle_index, "cycle_label": selected_label},
        )
        try:
            result = validate_cycle_and_compare(video_path, clip_path, cycles, cycle_index, progress)
            score = result[3] if len(result) > 3 else ""
            diagnoses = result[4] if len(result) > 4 else []
            result = list(result)
            result[2] = make_report_markdown(diagnoses, score, lang)
            log_usage_event(
                "diagnosis_completed",
                session_id=session_id,
                details={
                    "cycle_index": cycle_index,
                    "cycle_label": selected_label,
                    "score": score,
                    "diagnosis_count": len(diagnoses or []),
                },
            )
            return (*result, usage_summary_html())
        except Exception as exc:
            log_usage_event("error", session_id=session_id, details={"stage": "diagnosis", "message": str(exc)})
            raise

    # 导航按钮事件 - 前端JS处理切换,后端仅占位

    demo.load(
        fn=initialize_session,
        inputs=None,
        outputs=[session_state, usage_stats_output],
        show_progress="hidden",
    )

    video_input.change(
        fn=track_video_input,
        inputs=[video_input, session_state],
        outputs=[upload_guard_input, usage_stats_output],
        show_progress="hidden",
    )

    refresh_usage_button.click(
        fn=refresh_usage,
        inputs=[session_state],
        outputs=[usage_stats_output],
        show_progress="hidden",
    )

    language_button.click(
        fn=update_tool_language,
        inputs=[lang_state, session_state, diagnoses_state, score_state],
        outputs=[
            lang_state,
            language_button,
            nav_output,
            home_output,
            tool_header,
            clip_settings_md,
            video_input,
            start_input,
            end_input,
            create_clip_button,
            clip_preview,
            clip_summary,
            process_button,
            stop_button,
            stickman_result_md,
            video_output,
            file_output,
            summary_output,
            compare_title_md,
            comparison_output,
            comparison_file,
            score_md,
            score_output,
            cycle_select_md,
            cycle_dropdown,
            validate_button,
            cycle_info_md,
            cycle_info_output,
            mse_analysis_md,
            frame_slider,
            mse_plot_output,
            frame_joint_mse_table,
            report_title_md,
            report_markdown,
            error_list_md,
            error_table,
            error_stats_md,
            error_stats_output,
            usage_title_md,
            refresh_usage_button,
            usage_stats_output,
        ],
        show_progress="hidden",
    )

    clip_event = create_clip_button.click(
        fn=create_clip_with_usage,
        inputs=[video_input, start_input, end_input, upload_guard_input, session_state],
        outputs=[clip_state, clip_preview, clip_summary, usage_stats_output],
        show_progress="full",
    )

    process_event = process_button.click(
        fn=build_stickman_with_usage,
        inputs=[
            video_input,
            clip_state,
            upload_guard_input,
            session_state,
        ],
        outputs=[video_output, file_output, summary_output, cycles_state, usage_stats_output],
        show_progress="full",
    ).then(
        fn=update_cycle_dropdown,
        inputs=[cycles_state],
        outputs=[cycle_dropdown],
    ).then(
        fn=update_first_cycle_info,
        inputs=[cycles_state, lang_state],
        outputs=[cycle_info_output],
    )

    validate_event = validate_button.click(
        fn=validate_with_usage,
        inputs=[
            video_input,
            clip_state,
            cycles_state,
            cycle_dropdown,
            lang_state,
            session_state,
        ],
        outputs=[
            comparison_output,
            comparison_file,
            report_markdown,
            score_state,
            diagnoses_state,
            mse_state,
            overlap_state,
            frame_slider,
            mse_plot_output,
            frame_joint_mse_table,
            fast_frame_viewer,
            usage_stats_output,
        ],
        show_progress="full",
    ).then(
        fn=format_score_output,
        inputs=[score_state],
        outputs=[score_output],
    ).then(
        fn=update_error_table,
        inputs=[diagnoses_state, lang_state],
        outputs=[error_table],
    ).then(
        fn=update_error_stats,
        inputs=[diagnoses_state, lang_state],
        outputs=[error_stats_output],
    )

    cycle_dropdown.change(
        fn=update_cycle_info,
        inputs=[cycles_state, cycle_dropdown, lang_state],
        outputs=[cycle_info_output],
    )

    frame_slider.change(
        fn=update_analysis_frame,
        inputs=[overlap_state, mse_state, frame_slider],
        outputs=[comparison_output, mse_plot_output, frame_joint_mse_table],
        queue=False,
        show_progress="hidden",
    )

    stop_button.click(
        fn=request_stop_processing,
        inputs=[session_state],
        outputs=[usage_stats_output],
        queue=False,
        show_progress="hidden",
        cancels=[clip_event, process_event, validate_event],
    )


if __name__ == "__main__":
    logger.info("Starting app...")
    configure_cpu_runtime()
    log_runtime_versions()
    if os.getenv("SPACE_ID"):
        logger.info("Skipping eager YOLO load on Space; model will load inside the processing callback.")
    else:
        logger.info("Loading YOLO model...")
        try:
            model = load_yolo_model()
            logger.info(f"YOLO model loaded: {YOLO_MODEL_PATH.name}")
        except Exception as e:
            logger.error(f"YOLO model load failed: {e}", exc_info=True)
    
    logger.info("Launching Gradio demo...")
    
    launch_kwargs = {
        "show_error": True,
        "allowed_paths": [str(SCRIPT_DIR), tempfile.gettempdir()],
        "ssr_mode": False,
        "css": custom_css,
        "theme": gr.themes.Default(),
        "head": '''
<script>
const i18nData = {
    "zh": {
        "app_title": "RowingValidator Beta",
        "app_subtitle": "AI划船动作分析",
        "for_coaches": "FOR COACHES & ATHLETES",
        "hero_title": "先进的AI划船视频分析与虚拟教练平台",
        "hero_subtitle": "安全高效地划船",
        "start_free": "免费开始 →",
        "feature_1_title": "提高速度",
        "feature_1_desc": "通过技术优化,提升划行速度",
        "feature_2_title": "提升效率",
        "feature_2_desc": "提高能量转换效率,划得更省力",
        "feature_3_title": "减少受伤",
        "feature_3_desc": "纠正错误动作,减少运动损伤",
        "why_title": "为什么选择我们",
        "why_subtitle": "我们的AI技术帮助您深入分析划船动作,发现问题并提供专业指导",
        "why_1_title": "AI精准分析",
        "why_1_desc": "基于YOLO和自编码器模型,精准识别动作细节,提供专业反馈",
        "why_2_title": "实时对比",
        "why_2_desc": "将您的动作与标准动作进行实时对比,直观展示差异",
        "why_3_title": "个性化建议",
        "why_3_desc": "根据您的动作特点,提供针对性的改进建议和训练计划",
        "demo_title": "观看使用演示",
        "demo_subtitle": "了解如何使用我们的工具分析划船动作",
        "cta_title": "准备好提升您的划船技术了吗?",
        "cta_subtitle": "加入数千名使用我们的AI分析提升技术的运动员",
        "footer": "© 2026 RowingValidator Beta. All rights reserved.",
        "back_home": "← 返回首页",
        "tool_title": "视频上传与分析",
        "tool_subtitle": "上传您的划船视频,让AI分析您的技术动作",
    },
    "en": {
        "app_title": "RowingValidator Beta",
        "app_subtitle": "AI Rowing Analysis",
        "for_coaches": "FOR COACHES & ATHLETES",
        "hero_title": "ADVANCED AI ROWING VIDEO ANALYSIS AND VIRTUAL COACHING PLATFORM",
        "hero_subtitle": "ROW SAFELY & EFFICIENTLY",
        "start_free": "START FOR FREE",
        "feature_1_title": "Increase Speed",
        "feature_1_desc": "Improve rowing speed through technical optimization",
        "feature_2_title": "Boost Efficiency",
        "feature_2_desc": "Improve energy conversion efficiency, row with less effort",
        "feature_3_title": "Reduce Injuries",
        "feature_3_desc": "Correct improper form and reduce sports injuries",
        "why_title": "Why Choose Us",
        "why_subtitle": "Our AI technology helps you deeply analyze rowing technique, identify issues, and provide professional guidance",
        "why_1_title": "AI-Powered Analysis",
        "why_1_desc": "Based on YOLO and autoencoder models, precisely identify movement details and provide professional feedback",
        "why_2_title": "Real-Time Comparison",
        "why_2_desc": "Compare your movements with standard form in real-time with intuitive visual differences",
        "why_3_title": "Personalized Advice",
        "why_3_desc": "Provide targeted improvement suggestions and training plans based on your movement characteristics",
        "demo_title": "Watch the Demo",
        "demo_subtitle": "Learn how to use our tool to analyze your rowing technique",
        "cta_title": "Ready to Improve Your Rowing Technique?",
        "cta_subtitle": "Join thousands of athletes improving their technique with our AI analysis",
        "footer": "© 2026 RowingValidator Beta. All rights reserved.",
        "back_home": "← Back to Home",
        "tool_title": "Video Upload & Analysis",
        "tool_subtitle": "Upload your rowing video and let AI analyze your technique",
    }
};

let currentLang = 'zh';

function applyLanguage(lang) {
    currentLang = lang;
    document.documentElement.lang = lang;
    
    const translations = i18nData[lang];
    if (!translations) return;
    
    document.querySelectorAll('[data-i18n]').forEach(el => {
        const key = el.getAttribute('data-i18n');
        if (translations[key]) {
            el.textContent = translations[key];
        }
    });
    
    const langBtn = document.getElementById('lang-toggle');
    if (langBtn) {
        langBtn.textContent = lang === 'zh' ? '🌐 EN / 中文' : '🌐 中文 / EN';
    }
    
    document.dispatchEvent(new CustomEvent('lang-change', { detail: { lang: lang } }));
}

function toggleLanguage(e) {
    if (e) {
        e.stopPropagation();
        e.preventDefault();
    }
    applyLanguage(currentLang === 'zh' ? 'en' : 'zh');
}

window.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => applyLanguage(currentLang), 500);
    setTimeout(applyTabLabels, 900);
});

function getMainTabs() {
    return document.querySelector('.main-tabs');
}

function inferCurrentLangFromButton() {
    const btn = document.querySelector('.global-language-toggle button') || document.querySelector('.global-language-toggle');
    const text = btn ? btn.textContent : '';
    return text.includes('中文 / EN') ? 'en' : 'zh';
}

function applyTabLabels() {
    const lang = inferCurrentLangFromButton();
    const labels = lang === 'en'
        ? ['Home', 'Tool', 'Video Process', 'Compare', 'Report']
        : ['首页', '工具', '视频处理', '动作对比', '诊断报告'];
    const buttons = Array.from(document.querySelectorAll('button')).filter(b => !b.closest('.global-language-toggle'));
    const patterns = [
        ['首页', 'Home'],
        ['工具', 'Tool'],
        ['视频处理', 'Video Process', 'Process'],
        ['动作对比', 'Compare'],
        ['诊断报告', 'Report'],
    ];
    patterns.forEach((pattern, idx) => {
        const btn = buttons.find(b => pattern.some(p => b.textContent.includes(p)));
        if (btn) btn.textContent = labels[idx];
    });
}

function switchToTool() {
    const tabs = getMainTabs();
    if (!tabs) return;
    const tabWrapper = tabs.querySelector(':scope > .tab-wrapper') || tabs.querySelector('.tab-wrapper') || tabs.querySelector('[role="tablist"]');
    if (!tabWrapper) return;
    const buttons = tabWrapper.querySelectorAll('button, [role="tab"]');
    let lastToolBtn = null;
    for (const btn of buttons) {
        if (btn.textContent.includes('工具') || btn.textContent.includes('Tool')) {
            lastToolBtn = btn;
        }
    }
    if (lastToolBtn) lastToolBtn.click();
    window.scrollTo({top: 0, behavior: 'smooth'});
}

function switchToHome() {
    const tabs = getMainTabs();
    if (!tabs) return;
    const tabWrapper = tabs.querySelector(':scope > .tab-wrapper') || tabs.querySelector('.tab-wrapper') || tabs.querySelector('[role="tablist"]');
    if (!tabWrapper) return;
    const buttons = tabWrapper.querySelectorAll('button, [role="tab"]');
    let lastHomeBtn = null;
    for (const btn of buttons) {
        if (btn.textContent.includes('首页') || btn.textContent.includes('Home')) {
            lastHomeBtn = btn;
        }
    }
    if (lastHomeBtn) lastHomeBtn.click();
    window.scrollTo({top: 0, behavior: 'smooth'});
}

function initPageSwitcher() {
    const buttons = document.querySelectorAll('button');
    buttons.forEach(btn => {
        if (btn._navBound) return;
        if (btn.textContent.includes('免费开始') || btn.textContent.includes('START') || btn.textContent.includes('Start')) {
            btn._navBound = true;
            btn.addEventListener('click', function(e) {
                setTimeout(switchToTool, 50);
            });
        }
        if (btn.textContent.includes('返回首页') || btn.textContent.includes('Back to Home')) {
            btn._navBound = true;
            btn.addEventListener('click', function(e) {
                setTimeout(switchToHome, 50);
            });
        }
    });
    
    const logo = document.getElementById('nav-logo');
    if (logo && !logo._navBound) {
        logo._navBound = true;
        logo.style.cursor = 'pointer';
        logo.addEventListener('click', function(e) {
            switchToHome();
        });
    }
}

window._navInitAttempts = 0;
function tryInitNav() {
    window._navInitAttempts++;
    const tabs = getMainTabs();
    if (tabs) {
        initPageSwitcher();
    }
    if (window._navInitAttempts < 30) {
        setTimeout(tryInitNav, 500);
    }
}
tryInitNav();

window.rvFrameViewers = window.rvFrameViewers || {};

function rvInitFrameViewer(id) {
    if (window.rvFrameViewers[id]) return window.rvFrameViewers[id];
    const viewer = document.getElementById(id);
    if (!viewer || !viewer.dataset.payload) return null;
    const binary = atob(viewer.dataset.payload);
    const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
    const data = JSON.parse(new TextDecoder().decode(bytes));
    const state = {
        data,
        idx: Number(data.initial || 0),
        playing: false,
        timer: null,
        raf: null,
        ready: false,
        loading: false,
        compareFrames: new Array(Number(data.total || 0)).fill(null),
        mseFrames: new Array(Number(data.total || 0)).fill(null),
        loadedPairs: 0,
    };
    window.rvFrameViewers[id] = state;
    rvSetViewerEnabled(id, false);
    rvLoadFrameViewer(id);
    return state;
}

function rvSetViewerEnabled(id, enabled) {
    const viewer = document.getElementById(id);
    if (!viewer) return;
    const range = document.getElementById(id + '_range');
    if (range) range.disabled = !enabled;
    viewer.querySelectorAll('.rv-fast-btn').forEach((btn) => {
        btn.disabled = !enabled;
        btn.style.opacity = enabled ? '1' : '0.5';
        btn.style.cursor = enabled ? 'pointer' : 'default';
    });
}

function rvSetLoadLabel(id, text) {
    const label = document.getElementById(id + '_load');
    if (label) label.textContent = text;
}

async function rvLoadBitmap(url) {
    const response = await fetch(url, {cache: 'force-cache'});
    if (!response.ok) throw new Error(`Frame load failed: ${response.status}`);
    const blob = await response.blob();
    if ('createImageBitmap' in window) {
        return await createImageBitmap(blob);
    }
    return await new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = () => resolve(image);
        image.onerror = reject;
        image.src = URL.createObjectURL(blob);
    });
}

async function rvLoadFramePair(state, idx) {
    if (state.compareFrames[idx] && state.mseFrames[idx]) return;
    const [compareFrame, mseFrame] = await Promise.all([
        rvLoadBitmap(state.data.compare[idx]),
        rvLoadBitmap(state.data.mse[idx]),
    ]);
    state.compareFrames[idx] = compareFrame;
    state.mseFrames[idx] = mseFrame;
    state.loadedPairs += 1;
}

async function rvLoadFrameViewer(id) {
    const state = window.rvFrameViewers[id];
    if (!state || state.loading) return;
    state.loading = true;
    const total = Number(state.data.total || 0);
    rvSetLoadLabel(id, `Loading frames 0/${total}`);
    try {
        await rvLoadFramePair(state, state.idx);
        rvDrawFrame(id, state.idx);
        rvRenderJointRows(id, state.idx);
        rvSetLoadLabel(id, `Loading frames ${state.loadedPairs}/${total}`);

        const indices = [];
        for (let i = 0; i < total; i++) {
            if (i !== state.idx) indices.push(i);
        }
        let cursor = 0;
        const worker = async () => {
            while (cursor < indices.length) {
                const idx = indices[cursor++];
                await rvLoadFramePair(state, idx);
                rvSetLoadLabel(id, `Loading frames ${Math.min(state.loadedPairs, total)}/${total}`);
            }
        };
        const workers = Array.from({length: Math.min(8, indices.length || 1)}, worker);
        await Promise.all(workers);
        state.ready = true;
        rvSetViewerEnabled(id, true);
        rvSetLoadLabel(id, 'Ready');
        rvFrameUpdate(id, state.idx);
    } catch (error) {
        console.error(error);
        rvSetLoadLabel(id, 'Frame loading failed. Try validating again.');
    }
}

function rvRenderJointRows(id, idx) {
    const state = rvInitFrameViewer(id);
    if (!state) return;
    const holder = document.getElementById(id + '_joints');
    if (!holder) return;
    const rows = (state.data.rows || [])[idx] || [];
    holder.innerHTML = rows.map((row) => {
        const name = row[0] || '';
        const value = row[2] || '';
        return `<div class="rv-fast-joint-row"><span>${name}</span><strong>${value}</strong></div>`;
    }).join('');
}

function rvFrameUpdate(id, value) {
    const state = rvInitFrameViewer(id);
    if (!state) return;
    const total = Number(state.data.total || 0);
    const idx = Math.max(0, Math.min(Number(value || 0), total - 1));
    state.idx = idx;
    if (!state.ready) {
        const range = document.getElementById(id + '_range');
        if (range && Number(range.value) !== idx) range.value = String(idx);
        return;
    }
    if (state.raf) cancelAnimationFrame(state.raf);
    state.raf = requestAnimationFrame(() => {
        const range = document.getElementById(id + '_range');
        if (range && Number(range.value) !== idx) range.value = String(idx);
        rvDrawFrame(id, idx);
        rvRenderJointRows(id, idx);
    });
}

function rvDrawFrame(id, idx) {
    const state = window.rvFrameViewers[id];
    if (!state) return;
    const total = Number(state.data.total || 0);
    const compareCanvas = document.getElementById(id + '_compare');
    const mseCanvas = document.getElementById(id + '_mse');
    const label = document.getElementById(id + '_label');
    if (label) label.textContent = `Frame ${idx + 1}/${total}`;
    if (compareCanvas && state.compareFrames[idx]) {
        const ctx = compareCanvas.getContext('2d', {alpha: false});
        ctx.clearRect(0, 0, compareCanvas.width, compareCanvas.height);
        ctx.drawImage(state.compareFrames[idx], 0, 0, compareCanvas.width, compareCanvas.height);
    }
    if (mseCanvas && state.mseFrames[idx]) {
        const ctx = mseCanvas.getContext('2d', {alpha: false});
        ctx.clearRect(0, 0, mseCanvas.width, mseCanvas.height);
        ctx.drawImage(state.mseFrames[idx], 0, 0, mseCanvas.width, mseCanvas.height);
    }
}

function rvFrameNext(id) {
    const state = rvInitFrameViewer(id);
    if (!state) return;
    const total = Number(state.data.total || 0);
    rvFrameUpdate(id, (state.idx + 1) % total);
}

function rvFramePrev(id) {
    const state = rvInitFrameViewer(id);
    if (!state) return;
    const total = Number(state.data.total || 0);
    rvFrameUpdate(id, (state.idx - 1 + total) % total);
}

function rvFramePlay(id) {
    const state = rvInitFrameViewer(id);
    if (!state || !state.ready) return;
    const btn = document.querySelector(`#${id} .rv-play-btn`);
    state.playing = !state.playing;
    if (btn) btn.textContent = state.playing ? '⏸ Pause' : '▶ Play';
    if (state.timer) {
        clearInterval(state.timer);
        state.timer = null;
    }
    if (state.playing) {
        state.timer = setInterval(() => rvFrameNext(id), 83);
    }
}

function rvInitAllFrameViewers() {
    document.querySelectorAll('.rv-fast-viewer[data-payload]').forEach((viewer) => {
        rvInitFrameViewer(viewer.id);
    });
}

setInterval(function() {
    initPageSwitcher();
    applyTabLabels();
    rvInitAllFrameViewers();
}, 3000);

</script>
        ''',
    }
    
    if os.getenv("SPACE_ID"):
        demo.queue().launch(**launch_kwargs)
    else:
        try:
            demo.queue().launch(
                server_name="127.0.0.1",
                server_port=int(os.getenv("GRADIO_SERVER_PORT", os.getenv("PORT", "7872"))),
                share=False,
                **launch_kwargs,
            )
        except Exception as e:
            logger.warning(f"Gradio startup check failed but server may be running: {e}")
            logger.info(f"Server should be available at http://127.0.0.1:{os.getenv('PORT', '7872')}")
            import time
            while True:
                time.sleep(3600)