File size: 177,159 Bytes
cfc612d
 
 
4f38d55
69a88d8
4f38d55
1e42121
 
b7eb8ee
55e1306
c29619c
ae50d23
e662497
0dd8be0
 
e8e273e
9113c12
6885eb2
1abca55
 
150aa78
1abca55
4f38d55
792260b
a19ee96
69a88d8
a19ee96
cfc612d
 
 
b54374c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
399b0ff
cfc612d
 
 
b54374c
 
9113c12
3d71918
51ef11a
8a8856d
51ef11a
45fbbc7
 
 
 
8a8856d
 
cfc612d
45fbbc7
 
 
 
 
51ef11a
495c308
98e97fd
495c308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfc612d
fd4a564
cfc612d
c4c9ca6
 
 
 
8a8856d
c4c9ca6
635ad1b
84ce5ef
b6b54c2
c4c9ca6
1abca55
8a8856d
 
 
1abca55
 
 
 
d9beac3
 
 
8166d74
bc58925
 
 
8166d74
635ad1b
84ce5ef
c5caabb
d9beac3
 
fd4a564
635ad1b
84ce5ef
fd4a564
 
 
 
84ce5ef
1abca55
d9beac3
cfc612d
635ad1b
 
bc58925
 
 
 
635ad1b
bc58925
635ad1b
84ce5ef
bc58925
84ce5ef
bc58925
635ad1b
 
 
 
 
 
 
 
 
84ce5ef
635ad1b
 
bc58925
635ad1b
bc58925
635ad1b
 
 
 
 
 
 
 
 
 
bc58925
84ce5ef
 
635ad1b
84ce5ef
635ad1b
d9beac3
fd4a564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dd8be0
8a8856d
1abca55
 
 
624fa1f
bc58925
1abca55
8a8856d
1abca55
624fa1f
 
8a8856d
624fa1f
1abca55
84ce5ef
1abca55
 
84ce5ef
1abca55
792260b
8a8856d
 
 
 
bc58925
 
8a8856d
 
 
 
881a092
8a8856d
0dd8be0
1abca55
fd4a564
8a8856d
 
 
 
 
 
 
 
 
 
45fbbc7
1abca55
8a8856d
 
1abca55
8a8856d
 
 
 
 
 
1abca55
8166d74
 
cfc612d
 
 
d8191da
 
 
 
 
39442b0
d8191da
 
 
 
 
 
 
 
 
39442b0
d8191da
 
 
0dd8be0
c45166f
ccb6bea
0dd8be0
39442b0
3f82996
 
 
ccb6bea
 
8a8856d
 
aff10a7
ccb6bea
 
1ea589c
b54374c
 
 
d8191da
 
 
 
3f82996
 
0dd8be0
 
b54374c
 
 
 
8a8856d
 
b54374c
ccb6bea
0dd8be0
ccb6bea
3f82996
 
 
 
 
ccb6bea
8a8856d
 
 
3f82996
 
ccb6bea
 
8a8856d
 
 
 
 
 
 
ccb6bea
 
 
8a8856d
 
aff10a7
ccb6bea
 
 
b54374c
 
8a8856d
 
 
ccb6bea
3f82996
0dd8be0
 
d66724a
b54374c
d66724a
 
 
 
 
 
cfc612d
fa37ed4
cfc612d
fa37ed4
150aa78
2292154
fa37ed4
4f38d55
fa37ed4
4f38d55
 
6885eb2
 
b54374c
6885eb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2292154
cfc612d
 
 
c7fd5aa
37cda30
1ea589c
37cda30
98e97fd
0d313c5
37cda30
 
 
98e97fd
f901639
 
0d313c5
 
e662497
98e97fd
808c524
084a731
c29619c
 
b54374c
 
 
 
 
 
c29619c
98e97fd
808c524
084a731
 
 
c8aec50
 
 
 
 
084a731
98e97fd
f901639
3f82996
 
 
d8191da
 
 
 
 
 
ccb6bea
98e97fd
ccb6bea
 
 
3f82996
98e97fd
0d313c5
37cda30
 
316d3d4
 
37cda30
 
7b3870a
 
 
 
1ea589c
7b3870a
 
 
 
 
 
 
 
 
cfc612d
 
 
7b3870a
 
1ea589c
7b3870a
 
 
1ea589c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b54374c
7b3870a
b54374c
1ea589c
 
b54374c
 
 
 
 
d8191da
b54374c
7b3870a
16ac63a
316d3d4
b54374c
 
69a88d8
3b6e242
b54374c
 
7eeb5f9
c7fd5aa
 
cfc612d
 
 
c7fd5aa
b54374c
c7fd5aa
3b6e242
98e97fd
a19ee96
c7fd5aa
 
98e97fd
3b6e242
 
a19ee96
b54374c
 
c7fd5aa
 
 
 
 
 
b54374c
3b6e242
9113c12
a19ee96
c7fd5aa
5ba3035
c7fd5aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b54374c
 
c7fd5aa
 
 
 
b54374c
 
 
c7fd5aa
b54374c
c7fd5aa
 
 
 
 
 
 
a19ee96
c7fd5aa
 
a19ee96
c7fd5aa
 
b54374c
c7fd5aa
 
 
b54374c
c7fd5aa
b54374c
c7fd5aa
 
 
 
 
a19ee96
 
6885eb2
a19ee96
b54374c
c7fd5aa
 
 
 
 
a19ee96
b54374c
 
 
 
 
 
 
 
 
 
7eeb5f9
cfc612d
 
 
b54374c
 
 
8660205
 
 
98e97fd
b54374c
 
7eeb5f9
8660205
7eeb5f9
981f66b
d1505c8
 
 
 
 
 
 
b54374c
d1505c8
98e97fd
d1505c8
 
 
 
 
c0e40af
98e97fd
7eeb5f9
cfc612d
4832843
cfc612d
4832843
52bd98e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4832843
c0e40af
 
52bd98e
fa37ed4
4832843
 
 
 
 
52bd98e
4832843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52bd98e
 
 
4832843
 
52bd98e
 
 
 
 
 
 
 
 
 
 
 
 
4832843
 
 
 
52bd98e
4832843
 
 
 
 
52bd98e
4832843
52bd98e
06cd0eb
52bd98e
 
 
06cd0eb
52bd98e
 
5123da4
52bd98e
 
 
 
4832843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c50a88
4832843
a432394
cfc612d
fd4a564
cfc612d
fa37ed4
 
 
fd4a564
a19ee96
 
011aaa9
 
 
 
 
 
 
 
 
 
a19ee96
48e4681
 
69a88d8
fa37ed4
 
 
b54374c
 
 
 
fa37ed4
e3e8ac3
 
4832843
 
fd4a564
fa37ed4
4832843
 
 
 
 
 
 
 
 
 
 
 
fd4a564
4832843
 
 
 
 
 
 
 
 
 
fa37ed4
 
 
 
 
 
b54374c
 
fa37ed4
b54374c
 
 
 
 
fd4a564
fa37ed4
4832843
 
b54374c
 
 
 
fa37ed4
b54374c
 
4832843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b54374c
 
 
 
 
fa37ed4
b54374c
 
 
 
fa37ed4
b54374c
 
 
 
 
 
4832843
b54374c
 
 
 
 
 
 
fa37ed4
0cf1ae0
e3e8ac3
4832843
fa37ed4
4832843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa37ed4
 
 
 
 
b54374c
 
fa37ed4
b54374c
 
 
 
 
fd4a564
b54374c
4832843
 
b54374c
 
 
 
 
 
 
4832843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b54374c
 
 
 
 
fa37ed4
b54374c
 
 
 
fa37ed4
b54374c
 
4832843
 
b54374c
 
 
4832843
b54374c
 
7eeb5f9
cfc612d
9744adf
cfc612d
084a731
c45166f
0dd8be0
7eeb5f9
 
 
c29619c
9744adf
 
d3404b2
9744adf
6885eb2
 
e662497
7eeb5f9
d3404b2
 
 
 
7eeb5f9
 
 
 
 
 
 
 
 
6885eb2
 
 
 
 
e662497
d3404b2
9744adf
e662497
 
011aaa9
9744adf
 
 
7eeb5f9
 
94f51cf
7b3870a
9744adf
 
 
 
 
6885eb2
 
 
 
9744adf
6885eb2
9744adf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd4a564
9744adf
 
 
 
 
 
 
 
 
6885eb2
9744adf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7fd5aa
9744adf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b3870a
9744adf
 
 
011aaa9
 
7eeb5f9
 
9744adf
011aaa9
c29619c
a19ee96
e662497
6885eb2
7eeb5f9
a19ee96
9744adf
 
011aaa9
 
 
 
9744adf
011aaa9
 
 
e662497
 
011aaa9
 
 
 
c7fd5aa
011aaa9
e662497
011aaa9
c7fd5aa
 
011aaa9
e662497
c7fd5aa
 
 
 
7eeb5f9
011aaa9
7eeb5f9
0dd8be0
cfc612d
fa37ed4
cfc612d
6885eb2
c45166f
0dd8be0
8a8856d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7eeb5f9
8a8856d
 
7eeb5f9
79f8c49
0dd8be0
7b3870a
 
b3f80c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85d582a
b3f80c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b3870a
85d582a
 
7eeb5f9
 
d8191da
85d582a
 
6885eb2
 
 
 
 
 
 
 
 
 
 
 
85d582a
6885eb2
85d582a
a19ee96
011aaa9
fa37ed4
c7fd5aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa37ed4
a19ee96
011aaa9
 
7eeb5f9
 
a791934
011aaa9
a19ee96
c7fd5aa
8a8856d
 
 
0dd8be0
a19ee96
9113c12
6885eb2
011aaa9
79f8c49
 
fa37ed4
 
 
 
 
 
 
 
79f8c49
fa37ed4
8a8856d
 
 
fa37ed4
8a8856d
fa37ed4
 
c7fd5aa
fa37ed4
79f8c49
8a8856d
cfc612d
 
 
e8e273e
 
7eeb5f9
 
 
 
 
 
 
e8e273e
 
7eeb5f9
 
 
 
 
 
e8e273e
 
 
 
 
7eeb5f9
 
 
 
 
 
 
 
 
e8e273e
0dd8be0
d66724a
c45166f
0dd8be0
8a8856d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7eeb5f9
8a8856d
 
7eeb5f9
 
 
0dd8be0
7eeb5f9
 
 
 
 
e8e273e
d66724a
 
c7fd5aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d66724a
 
 
7eeb5f9
 
39442b0
d66724a
 
7eeb5f9
8a8856d
 
 
0dd8be0
d66724a
9113c12
6885eb2
d66724a
7eeb5f9
c7fd5aa
 
 
 
 
 
 
 
 
 
 
8a8856d
 
 
c7fd5aa
8a8856d
c7fd5aa
d66724a
7eeb5f9
 
 
cfc612d
fd4a564
cfc612d
a19ee96
c45166f
0dd8be0
7eeb5f9
 
0dd8be0
011aaa9
7eeb5f9
fd4a564
 
 
 
 
 
 
 
 
011aaa9
c7fd5aa
011aaa9
fa37ed4
 
fd4a564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a19ee96
 
011aaa9
7eeb5f9
 
fd4a564
fa37ed4
a19ee96
011aaa9
fd4a564
 
 
fa37ed4
a791934
fa37ed4
 
 
fd4a564
fa37ed4
 
 
 
 
 
c7fd5aa
fa37ed4
 
 
 
 
 
 
fd4a564
 
c7fd5aa
fa37ed4
fd4a564
 
0dd8be0
cfc612d
fd4a564
cfc612d
e662497
c45166f
0dd8be0
7eeb5f9
 
 
fd4a564
 
 
7eeb5f9
 
 
0dd8be0
fd4a564
 
fa37ed4
 
e662497
4832843
fd4a564
 
 
4832843
 
 
 
 
 
 
 
 
 
 
 
 
fd4a564
e662497
fd4a564
 
 
 
 
 
38396d4
fd4a564
e662497
fd4a564
e662497
 
fd4a564
 
 
 
 
e662497
fd4a564
 
 
 
 
4832843
 
fd4a564
 
c6e931b
fd4a564
 
fa37ed4
 
 
 
 
fd4a564
fa37ed4
 
fd4a564
7eeb5f9
fd4a564
 
 
fa37ed4
fd4a564
fa37ed4
fd4a564
 
 
 
 
 
 
 
 
 
 
0dd8be0
fd4a564
fa37ed4
fd4a564
e662497
 
 
7eeb5f9
 
fd4a564
e662497
c29619c
fd4a564
c7fd5aa
fa37ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd4a564
fa37ed4
fd4a564
 
e662497
cfc612d
 
 
e662497
c45166f
0dd8be0
7eeb5f9
 
 
 
0dd8be0
7eeb5f9
1916360
 
e662497
1916360
7eeb5f9
1916360
c7fd5aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e1f62f
011aaa9
 
7eeb5f9
 
1ea589c
011aaa9
c29619c
0dd8be0
c7fd5aa
 
eaa797e
 
7eeb5f9
 
0dd8be0
ae50d23
c45166f
0dd8be0
7eeb5f9
 
 
 
0dd8be0
e662497
011aaa9
ae50d23
6885eb2
 
 
 
 
 
 
 
 
 
 
ae50d23
c29619c
c7fd5aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c29619c
6885eb2
 
c7fd5aa
 
 
 
 
 
 
 
 
 
 
 
 
 
6885eb2
c7fd5aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6885eb2
011aaa9
 
7eeb5f9
 
c7fd5aa
011aaa9
c29619c
0dd8be0
c7fd5aa
 
eaa797e
 
7eeb5f9
6885eb2
 
 
 
c29619c
cfc612d
fa37ed4
cfc612d
c8aec50
 
 
fa37ed4
 
 
c8aec50
fa37ed4
c8aec50
b3f80c9
fa37ed4
c8aec50
b3f80c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa37ed4
b3f80c9
 
fa37ed4
b3f80c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7fd5aa
fa37ed4
 
c8aec50
 
 
 
 
 
fa37ed4
c8aec50
b3f80c9
c7fd5aa
fa37ed4
 
c8aec50
fa37ed4
 
 
 
 
 
 
 
 
c7fd5aa
fa37ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7fd5aa
fa37ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6885eb2
fa37ed4
 
 
 
 
 
c8aec50
fa37ed4
 
 
 
 
 
 
 
 
 
 
 
c8aec50
cfc612d
4832843
cfc612d
4832843
 
 
 
be6645a
 
4832843
 
 
 
 
 
 
8a8856d
4832843
 
 
 
 
 
 
 
8a8856d
 
 
 
 
 
 
 
 
 
4832843
 
b771326
a19ee96
4832843
a19ee96
38a2b5c
a19ee96
fa37ed4
55e1306
4832843
 
b7eb8ee
4832843
 
 
 
 
 
 
 
7eeb5f9
4832843
 
 
 
 
 
 
 
 
 
 
51ef11a
 
7eeb5f9
 
be6645a
 
 
4832843
be6645a
4832843
 
 
 
 
be6645a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8166d74
 
 
be6645a
8166d74
be6645a
4832843
be6645a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a06215
be6645a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8166d74
be6645a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3f80c9
be6645a
b3f80c9
 
 
 
 
 
 
 
 
 
 
 
be6645a
 
b3f80c9
be6645a
b3f80c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be6645a
 
 
 
 
 
 
 
 
 
 
 
b3f80c9
be6645a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4832843
 
4f38d55
a19ee96
 
4832843
011aaa9
4832843
 
 
 
 
 
be6645a
fa37ed4
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
# ==============================================================================
# 🟢 پارت 1: وارد کردن کتابخانه‌ها و ماژول‌ها (Imports)
# ==============================================================================
import os
import time
import threading
import random
import aiohttp
import traceback
import asyncio
import base64
import mimetypes
import io
import json
import datetime
import string
import uuid
import concurrent.futures
import sqlite3     # 🟢 اضافه شده برای دیتابیس فوق‌سریع 
import copy        # 🟢 اضافه شده برای سیستم تشخیص تغییرات دیتابیس
from flask import Flask
from rubpy.bot import BotClient, filters  

from huggingface_hub import AsyncInferenceClient, HfApi, hf_hub_download
from PIL import Image
from pydub import AudioSegment

# ==============================================================================
# 🟢 پارت 2: تنظیمات سرورها، مدل‌های تغییر صدا و کلون صدا
# ==============================================================================
# --- تنظیمات آدرس سرورهای تغییر صدا ---
VC_BASE_URL = "https://sada8888-sada.hf.space"
LEGACY_BASE_URL = "https://ezmarynoori-rvc.hf.space"

LEGACY_MODELS = {
    "1": {"name": "شادمهر", "url": "https://huggingface.co/amirmatrix/shadmehr/resolve/main/added_IVF722_Flat_nprobe_1_shadmehr_v2.zip?download=true", "gender": "male"},
    "2": {"name": "معین", "url": "https://huggingface.co/datasets/Hamed744/Ezmary/resolve/main/Moein.zip?download=true", "gender": "male"},
    "3": {"name": "بیلی آیلیش", "url": "https://huggingface.co/datasets/Hamed744/Ezmary/resolve/main/Billie.zip?download=true", "gender": "female"},
    "4": {"name": "محسن چاوشی", "url": "https://huggingface.co/datasets/Hamed744/Ezmary/resolve/main/chavoshi250.zip?download=true", "gender": "male"},
    "5": {"name": "سیاوش قمیشی", "url": "https://huggingface.co/datasets/Hamed744/Ezmary/resolve/main/Ghomayshi250.zip?download=true", "gender": "male"},
    "6": {"name": "یاس", "url": "https://huggingface.co/datasets/Hamed744/Ezmary/resolve/main/Yas300.zip?download=true", "gender": "male"},
    "7": {"name": "عادل فردوسی‌پور", "url": "https://huggingface.co/datasets/Hamed744/Ezmary/resolve/main/Adel.zip?download=true", "gender": "male"},
    "8": {"name": "باب اسفنجی", "url": "https://huggingface.co/datasets/Hamed744/Ezmary/resolve/main/Bab_Asfanj300.zip?download=true", "gender": "male"}
}

STANDARD_MODELS = {
    "9": {"name": "علی سورنا", "ref": "https://huggingface.co/datasets/Hamed744/mp3/resolve/main/%D9%85%D8%AF%D9%84%20%D8%B5%D8%AF%D8%A7%DB%8C%20%D8%B3%D9%88%D8%B1%D9%86%D8%A7.mp3?download=true"},
    "10": {"name": "رونالدو", "ref": "https://huggingface.co/datasets/Hamed744/mp3/resolve/main/%D8%B1%D9%88%D9%86%D8%A7%D9%84%D8%AF%D9%88.wav?download=true"},
    "11": {"name": "مسی", "ref": "https://huggingface.co/datasets/Hamed744/mp3/resolve/main/%D8%B5%D8%AF%D8%A7%DB%8C-%D9%85%D8%B3%DB%8C.mp3?download=true"},
    "12": {"name": "مریم", "ref": "https://huggingface.co/datasets/Hamed744/mp3/resolve/main/%D8%B5%D8%AF%D8%A7%DB%8C%20%D8%AE%D8%A7%D9%86%D9%85.wav?download=true"}
}

# ==============================================================================
# 🟢 پارت 3: متغیرهای ادمین، سیستم ضد اسپم و توابع تبدیل تاریخ
# ==============================================================================
# --- کد مدیریت ---
ADMIN_CODE = "3011"
BOT_GUID = None

# =======================================================
# سیستم ضد اسپم کاربر-محور (بهینه شده برای جلوگیری از نشت مموری)
# =======================================================
user_message_times = {}

def is_user_spamming(chat_id):
    now = time.time()
    times = user_message_times.get(chat_id, [])
    # فقط زمان‌های ۳ ثانیه اخیر رو نگه دار
    times =[t for t in times if now - t < 3.0]
    times.append(now)
    user_message_times[chat_id] = times
    if len(times) > 4:
        return True
    return False

def gregorian_to_jalali(gy, gm, gd):
    g_d_m =[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
    gy2 = (gy + 1) if (gm > 2) else gy
    days = 355666 + (365 * gy) + ((gy2 + 3) // 4) - ((gy2 + 99) // 100) + ((gy2 + 399) // 400) + gd + g_d_m[gm - 1]
    jy = -1595 + (33 * (days // 12053))
    days %= 12053
    jy += 4 * (days // 1461)
    days %= 1461
    if days > 365:
        jy += (days - 1) // 365
        days = (days - 1) % 365
    if days < 186:
        jm = 1 + (days // 31)
        jd = 1 + (days % 31)
    else:
        jm = 7 + ((days - 186) // 30)
        jd = 1 + ((days - 186) % 30)
    return jy, jm, jd

# ==============================================================================
# 🟢 پارت 4: دیتابیس SQLite (نسخه جراحی + بازیابی هوشمند کاربران ویژه از JSON قدیمی)
# ==============================================================================
import os
import sqlite3
import json
import copy
import threading

DB_FILE = "/data/users_v6.db" 
OLD_DB_V3 = "/data/users_v3.db"
OLD_JSON_BAK = "users_db.json.bak" # نام فایل بکاپ جیسون شما

last_saved_state = {}
recent_messages_dict = {}
db_lock = threading.Lock()
msg_cache_lock = threading.Lock()

def init_sqlite_db():
    try:
        os.makedirs(os.path.dirname(DB_FILE), exist_ok=True)
        is_first_run = not os.path.exists(DB_FILE)

        conn = sqlite3.connect(DB_FILE, timeout=60.0)
        
        # 🚀 ژورنال TRUNCATE امن‌ترین حالت برای هاردهای شبکه‌ای (NFS) است
        conn.execute('PRAGMA journal_mode=TRUNCATE;') 
        conn.execute('PRAGMA synchronous=FULL;')
        
        # ایجاد جدول کاربران
        conn.execute('CREATE TABLE IF NOT EXISTS users (chat_id TEXT PRIMARY KEY, user_data TEXT)')
        conn.commit()

        if is_first_run:
            print("🚨 عملیات نجات جراحی از فایل v3 آغاز شد...")
            surgical_salvage(OLD_DB_V3, conn)
        
        # 🟢 بازگردانی کاربران دارای اشتراک از فایل جیسون قدیمی
        # این تابع همیشه چک می‌کند تا اگر کاربر ویژه‌ای جا مانده بود یا اشتراکش در دیتابیس فعلی پریده بود، آن را برگرداند.
        salvage_premium_from_json(OLD_JSON_BAK, conn)
        
        conn.close()
    except Exception as e:
        print(f"❌ خطا در راه اندازی دیتابیس: {e}")

# 🧲 تابع استخراج جراحی (رکورد به رکورد) برای پریدن از روی سکتورهای خراب دیتابیس
def surgical_salvage(old_file, new_conn):
    if not os.path.exists(old_file): 
        print(f"⚠️ فایل قدیمی {old_file} یافت نشد.")
        return
        
    print(f"🔍 در حال اسکن عمیق و جراحی رکوردهای {old_file} ...")
    extracted_count = 0
    corrupt_count = 0
    try:
        old_conn = sqlite3.connect(old_file, timeout=20.0)
        cursor = old_conn.cursor()
        
        # ابتدا بالاترین شماره سطر (ROWID) را پیدا می‌کنیم تا بدانیم چقدر باید بگردیم
        try:
            cursor.execute("SELECT MAX(rowid) FROM users")
            max_id = cursor.fetchone()[0]
            if not max_id: max_id = 150000
        except:
            max_id = 150000 # اگر فایل خیلی خراب بود، تا 150 هزار رکورد را دستی می‌گردیم
            
        print(f"تعداد رکوردهای احتمالی جهت اسکن: {max_id}. لطفا چند ثانیه صبر کنید...")
        
        # جستجوی دانه به دانه: اگر یکی خراب بود، فقط همون رو رد میکنه و میره بعدی!
        for i in range(1, max_id + 1):
            try:
                cursor.execute("SELECT chat_id, user_data FROM users WHERE rowid = ?", (i,))
                row = cursor.fetchone()
                if row:
                    new_conn.execute("INSERT OR IGNORE INTO users VALUES (?, ?)", row)
                    extracted_count += 1
            except sqlite3.DatabaseError:
                # این رکورد روی سکتور خراب هارد افتاده است -> رد میشویم
                corrupt_count += 1
                continue
            except Exception:
                corrupt_count += 1
                continue
                
        new_conn.commit()
        old_conn.close()
        print(f"✅ شاهکار نجات! {extracted_count} کاربر کاملا سالم استخراج شد و از روی {corrupt_count} رکورد خراب با موفقیت پریدیم.")
    except Exception as e:
        print(f"⚠️ توقف استخراج: {e} | تعداد نجات‌یافته تا این لحظه: {extracted_count}")

# 💎 تابع ارتقا یافته: بازیابی کاربران دارای اشتراک از فایل جیسون
def salvage_premium_from_json(json_file, new_conn):
    # بررسی وجود فایل در مسیر فعلی یا پوشه data
    target_path = json_file
    if not os.path.exists(target_path):
        alt_path = f"/data/{json_file}"
        if os.path.exists(alt_path):
            target_path = alt_path
        else:
            return # اگر فایل بکاپ کلا وجود نداشت، بی‌صدا رد می‌شود

    print(f"📦 در حال اسکن فایل بکاپ {target_path} جهت یافتن کاربران VIP جا مانده یا فاقد اشتراک...")
    try:
        with open(target_path, 'r', encoding='utf-8') as f:
            old_json_data = json.load(f)
            
        restored_count = 0
        cursor = new_conn.cursor()
        
        for chat_id, user_data in old_json_data.items():
            # فقط کاربرانی که دیتای آنها به صورت دیکشنری است و اشتراک فعال دارند را انتخاب می‌کنیم
            if isinstance(user_data, dict) and user_data.get("is_premium") == True:
                user_data_str = json.dumps(user_data, ensure_ascii=False)
                str_chat_id = str(chat_id)
                try:
                    # بررسی می‌کنیم آیا کاربر در دیتابیس فعلی (v6) وجود دارد یا خیر
                    cursor.execute("SELECT user_data FROM users WHERE chat_id = ?", (str_chat_id,))
                    existing_row = cursor.fetchone()
                    
                    if existing_row:
                        # کاربر وجود دارد. بررسی می‌کنیم آیا اشتراکش فعال است؟
                        existing_data = json.loads(existing_row[0])
                        if not existing_data.get("is_premium"):
                            # اگر در دیتابیس فعلی اشتراک نداشت، دیتای پولی جایگزین می‌شود
                            cursor.execute("UPDATE users SET user_data = ? WHERE chat_id = ?", (user_data_str, str_chat_id))
                            restored_count += 1
                    else:
                        # کاربر اصلا در دیتابیس وجود ندارد، او را اضافه می‌کنیم
                        cursor.execute("INSERT INTO users (chat_id, user_data) VALUES (?, ?)", (str_chat_id, user_data_str))
                        restored_count += 1
                        
                except Exception:
                    continue
                    
        new_conn.commit()
        if restored_count > 0:
            print(f"💎 فوق‌العاده! اطلاعات {restored_count} کاربر دارای اشتراک (که غایب بودند یا در نسخه جدید اشتراک نداشتند) با موفقیت ریکاوری شد.")
        else:
            print("💎 فایل بکاپ بررسی شد؛ تمام کاربران VIP از قبل با اشتراک فعال در دیتابیس فعلی موجود هستند.")
            
    except Exception as e:
        print(f"❌ خطا در پردازش فایل جیسون بکاپ: {e}")

def load_db():
    global last_saved_state, recent_messages_dict
    init_sqlite_db()
    db_dict = {}
    try:
        conn = sqlite3.connect(DB_FILE, timeout=60.0)
        conn.execute('PRAGMA journal_mode=TRUNCATE;')
        cursor = conn.cursor()
        
        cursor.execute("SELECT chat_id, user_data FROM users")
        for row in cursor.fetchall():
            db_dict[row[0]] = json.loads(row[1])
            
        conn.close()
        last_saved_state = copy.deepcopy(db_dict)
        print(f"🚀 دیتابیس ابری آماده شد. تعداد کل کاربران: {len(db_dict)}")
        return db_dict
    except Exception as e:
        print(f"⚠️ ارور در لود نهایی دیتابیس: {e}")
        return {}

def background_save_worker(changed_data):
    with db_lock:
        try:
            conn = sqlite3.connect(DB_FILE, timeout=60.0)
            conn.execute('PRAGMA journal_mode=TRUNCATE;')
            conn.execute('PRAGMA synchronous=FULL;')
            conn.executemany("INSERT OR REPLACE INTO users (chat_id, user_data) VALUES (?, ?)", changed_data)
            conn.commit()
            conn.close()
        except Exception as e:
            print(f"❌ خطا در ذخیره بک‌گراند: {e}")

def save_db(db_data):
    global last_saved_state
    changed = []
    for cid, data in db_data.items():
        if cid not in last_saved_state or last_saved_state[cid] != data:
            changed.append((str(cid), json.dumps(data, ensure_ascii=False)))
            
    if not changed: return
    
    for cid, _ in changed:
        last_saved_state[cid] = copy.deepcopy(db_data[cid])
        
    threading.Thread(target=background_save_worker, args=(changed,), daemon=True).start()

def is_message_processed(message_id):
    return str(message_id) in recent_messages_dict

def mark_message_processed(message_id):
    msg_id_str = str(message_id)
    with msg_cache_lock:
        recent_messages_dict[msg_id_str] = True
        if len(recent_messages_dict) > 15000:
            oldest_key = next(iter(recent_messages_dict))
            del recent_messages_dict[oldest_key]

user_credits_db = load_db()

# ==============================================================================
# 🟢 پارت 5: توابع کد معرف، مدیریت سهمیه حساب کاربری و تبدیل اعداد
# ==============================================================================
def get_or_create_referral_code(chat_id):
    user_data = user_credits_db[chat_id]
    if not user_data.get("referral_code"):
        while True:
            new_code = ''.join(random.choices(string.digits, k=8))
            exists = any(isinstance(u, dict) and u.get("referral_code") == new_code for u in user_credits_db.values())
            if not exists:
                user_data["referral_code"] = new_code
                save_db(user_credits_db)
                break
    return user_data["referral_code"]

def find_user_by_referral_code(code):
    code = code.strip()
    for uid, data in user_credits_db.items():
        if isinstance(data, dict) and data.get("referral_code", "") == code:
            return uid
    return None

def get_user_credits(chat_id):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    today_str = datetime.date.today().isoformat()
    
    if str_chat_id not in user_credits_db or not isinstance(user_credits_db[str_chat_id], dict):
        user_credits_db[str_chat_id] = {
            "is_premium": False,
            "expire_date": None,
            "last_reset": "",
            "chat": 10,
            "image": 0,
            "edit_image": 0,
            "podcast": 2,
            "tts": 5,
            "file": 1,
            "stt": 5,
            "voice_conv": 3,
            "voice_clone": 1,
            "last_msg_id": 0,
            "has_joined": False,
            "invited_count": 0,
            "used_referral": False,
            "referral_code": ""
        }
        save_db(user_credits_db)
        
    user_data = user_credits_db[str_chat_id]
    
    if "voice_conv" not in user_data: user_data["voice_conv"] = 3
    if "voice_clone" not in user_data: user_data["voice_clone"] = 1
    if "last_msg_id" not in user_data: user_data["last_msg_id"] = 0
    if "image" not in user_data: user_data["image"] = 0
    if "edit_image" not in user_data: user_data["edit_image"] = 0

    is_premium = user_data.get("is_premium", False)
    
    if is_premium and user_data.get("expire_date"):
        try:
            expire_date = datetime.datetime.fromisoformat(user_data["expire_date"])
            if datetime.datetime.now() > expire_date:
                user_data["is_premium"] = False
                user_data["expire_date"] = None
                is_premium = False
                user_data["image"] = 0
                user_data["edit_image"] = 0
                save_db(user_credits_db) 
        except Exception:
            pass

    if not is_premium:
        changed = False
        # صفر کردن سهمیه عکس کاربرانی که از دیروز اعتبار رایگان جا مانده دارند
        if user_data.get("image", 0) > 0 or user_data.get("edit_image", 0) > 0:
            user_data["image"] = 0
            user_data["edit_image"] = 0
            changed = True

        if user_data.get("last_reset") != today_str:
            user_data["last_reset"] = today_str
            user_data["chat"] = 10
            user_data["image"] = 0
            user_data["edit_image"] = 0
            user_data["podcast"] = 2
            user_data["tts"] = 5
            user_data["file"] = 1
            user_data["stt"] = 5
            user_data["voice_conv"] = 3
            user_data["voice_clone"] = 1
            changed = True
            
        if changed:
            save_db(user_credits_db)
            
    return user_data

def to_english_digits(text):
    if not text: return text
    persian_digits = '۰۱۲۳۴۵۶۷۸۹'
    arabic_digits = '٠١٢٣٤٥٦٧٨٩'
    english_digits = '0123456789'
    translation_table = str.maketrans(persian_digits + arabic_digits, english_digits * 2)
    return str(text).translate(translation_table)

# ==============================================================================
# 🟢 پارت 6: تنظیمات وب‌سرور (Flask) و توابع کمکی فایل‌ها
# ==============================================================================
# --- تنظیمات وب سرور ---
app = Flask(__name__)

@app.route('/')
def home():
    return "ربات یکپارچه آلفا (نسخه پرو + مدیریت اشتراک نامحدود + دعوت دوستان + سیستم تغییر صدا) روشن است! 🚀"

def run_flask():
    app.run(host="0.0.0.0", port=7860, threaded=True)

# --- توابع کمکی ---
def sync_save_image(image, file_name):
    rgb_im = image.convert('RGB')
    rgb_im.save(file_name, format="JPEG", quality=100)

def sync_write_file(file_name, data):
    with open(file_name, "wb") as f:
        f.write(data)

def sync_read_file(file_name):
    with open(file_name, 'rb') as f:
        return f.read()

def sync_combine_audio(current_audio, new_bytes):
    audio_segment = AudioSegment.from_file(io.BytesIO(new_bytes))
    return current_audio + audio_segment

def sync_export_audio(audio_obj, file_name):
    audio_obj.export(file_name, format="mp3")

# ==============================================================================
# 🟢 پارت 7: کیبوردها (دکمه‌های شیشه‌ای / منوها)
# ==============================================================================
# --- ساختار کیبورد ---
MAIN_KEYPAD_DICT = {
    "rows":[
        {
            "buttons":[
                {"id": "chat_btn", "type": "Simple", "button_text": "چت با هوش مصنوعی 🤖"}
            ]
        },
        {
            "buttons":[
                {"id": "img_btn", "type": "Simple", "button_text": "ساخت تصاویر🎨"},
                {"id": "edit_img_btn", "type": "Simple", "button_text": "ویرایش تصاویر 🪄"}
            ]
        },
        {
            "buttons":[
                {"id": "podcast_btn", "type": "Simple", "button_text": "ساخت پادکست 🎙️"},
                {"id": "tts_btn", "type": "Simple", "button_text": "تبدیل متن به صدا🗣️"}
            ]
        },
        {
            "buttons":[
                {"id": "vc_btn", "type": "Simple", "button_text": "تغییر صدا 🎙️"},
                {"id": "clone_btn", "type": "Simple", "button_text": "کلون کردن صدا 👤"}
            ]
        },
        {
            "buttons":[
                {"id": "stt_btn", "type": "Simple", "button_text": "فایل صوتی به متن 📝"},
                {"id": "file_btn", "type": "Simple", "button_text": "تحلیل فایل 📁"}
            ]
        },
        {
            "buttons":[
                {"id": "create_file_btn", "type": "Simple", "button_text": "ساخت فایل 📄"}
            ]
        },
        {
            "buttons":[
                {"id": "account_btn", "type": "Simple", "button_text": "حساب کاربری 👤"},
                {"id": "buy_btn", "type": "Simple", "button_text": "خرید اشتراک 💎"}
            ]
        },
        {
            "buttons":[
                {"id": "invite_btn", "type": "Simple", "button_text": "دعوت دوستان 🎁"},
                {"id": "referral_btn", "type": "Simple", "button_text": "ثبت کد هدیه 🎫"}
            ]
        },
        {
            "buttons":[
                {"id": "transfer_btn", "type": "Simple", "button_text": "انتقال اکانت از برنامه به ربات"}
            ]
        },
        {
            "buttons":[
                {"id": "cancel_btn", "type": "Simple", "button_text": "برگشت♻️"}
            ]
        }
    ],
    "resize_keyboard": True
}

CHANNEL_USERNAME = "aialpha"
CHANNEL_GUID = None

JOIN_KEYPAD_DICT = {
    "rows":[
        {
            "buttons":[
                {"id": "check_join_btn", "type": "Simple", "button_text": "✅ عضو شدم"}
            ]
        }
    ],
    "resize_keyboard": True
}

# ==============================================================================
# 🟢 پارت 8: تابع بررسی عضویت کانال، ارسال کیبورد و توکن روبیکا
# ==============================================================================
async def check_channel_membership(client, user_id):
    global CHANNEL_GUID
    if str(user_id) == str(BOT_GUID): return True
    
    try:
        if not CHANNEL_GUID:
            res = await client.get_object_by_username(CHANNEL_USERNAME)
            if isinstance(res, dict):
                if 'channel' in res and 'channel_guid' in res['channel']:
                    CHANNEL_GUID = res['channel']['channel_guid']
                elif 'data' in res and 'channel' in res['data']:
                    CHANNEL_GUID = res['data']['channel']['channel_guid']
                elif 'exist' in res and 'chat' in res['exist']:
                    CHANNEL_GUID = res['exist']['chat']['object_guid']
            else:
                if hasattr(res, 'channel'):
                    CHANNEL_GUID = getattr(res.channel, 'channel_guid', None)
                elif hasattr(res, 'data') and hasattr(res.data, 'channel'):
                    CHANNEL_GUID = getattr(res.data.channel, 'channel_guid', None)
                elif hasattr(res, 'exist') and hasattr(res.exist, 'chat'):
                    CHANNEL_GUID = getattr(res.exist.chat, 'object_guid', None)

        if not CHANNEL_GUID: return True

        payload = {"channel_guid": CHANNEL_GUID, "member_guid": user_id}
        res = await client._make_request("getChannelParticipant", payload)
        
        if isinstance(res, dict) and res.get("status") == "OK":
            data = res.get("data", {})
            if data and "participant" in data: return True
        elif hasattr(res, 'status') and getattr(res, 'status') == "OK":
            return True
        return False
    except Exception: return False

async def send_with_keyboard(client, chat_id, text, use_keyboard=True):
    try:
        if not use_keyboard: return await client.send_message(chat_id, text)
        payload = {"chat_id": chat_id, "text": text, "chat_keypad_type": "New", "chat_keypad": MAIN_KEYPAD_DICT}
        return await client._make_request("sendMessage", payload)
    except Exception:
        try: return await client.send_message(chat_id, text)
        except Exception: return None

bot_token = os.environ.get("RUBIKA_AUTH", "").strip()

# ==============================================================================
# 🟢 پارت 9: دانلودر قدرتمند و تابع ضد قطعی روبیکا
# ==============================================================================
# ==================================================================
# تابع دانلود ضد بمب اتم (پافشاری ۳۵ بار)
# ==================================================================
async def helper_download_file(client, msg_obj):
    errors =[]
    file_obj = None
    file_id = None
    
    for attr in['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
        val = getattr(msg_obj, attr, None)
        if val:
            file_obj = val
            if hasattr(val, 'file_id'): file_id = val.file_id
            elif isinstance(val, dict) and 'file_id' in val: file_id = val['file_id']
            break
            
    if not file_obj and hasattr(msg_obj, "file_id"):
        file_id = msg_obj.file_id
        file_obj = msg_obj

    if not file_id: raise Exception("خطا: هیچ فایلی در پیام یافت نشد.")

    temp_name = f"temp_dl_{uuid.uuid4().hex}.tmp"

    for attempt in range(20):
        try:
            url_get_file = f"https://botapi.rubika.ir/v3/{bot_token}/getFile"
            payload = {"file_id": str(file_id)}
            headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
            
            async with aiohttp.ClientSession() as session:
                async with session.post(url_get_file, json=payload, headers=headers, timeout=30) as resp:
                    if resp.status == 200:
                        res_data = await resp.json()
                        if res_data.get("status") == "OK" or res_data.get("status_det") == "OK":
                            download_url = res_data.get("data", {}).get("download_url") or res_data.get("data", {}).get("file_url")
                            if download_url:
                                for dl_attempt in range(3):
                                    try:
                                        async with session.get(download_url, headers=headers, timeout=60) as dl_resp:
                                            if dl_resp.status == 200:
                                                data = await dl_resp.read()
                                                if data and len(data) > 0: return data
                                            else: errors.append(f"DL HTTP {dl_resp.status}")
                                            await asyncio.sleep(2)
                                    except Exception as dl_err:
                                        errors.append(f"DL Error: {str(dl_err)[:30]}")
                                        await asyncio.sleep(2)
                            else: errors.append("No download URL in response.")
                        else: errors.append(f"API Not OK: {res_data.get('status')}")
                    elif resp.status in [502, 503, 500]:
                        errors.append(f"GetFile HTTP {resp.status}")
                        await asyncio.sleep(3.5)
                        continue
                    else:
                        errors.append(f"GetFile HTTP {resp.status}")
                        await asyncio.sleep(2)
        except Exception as e:
            errors.append(f"API Error: {str(e)[:50]}")
            await asyncio.sleep(2)

    if file_obj:
        for attempt in range(10):
            try:
                if hasattr(client, "download"):
                    result = await client.download(file_obj, save_as=temp_name)
                    if isinstance(result, bytes) and len(result) > 0: return result
                    if os.path.exists(temp_name):
                        data = await asyncio.to_thread(sync_read_file, temp_name)
                        os.remove(temp_name)
                        if data and len(data) > 0: return data
            except Exception as e:
                errors.append(f"Rubpy Obj Error: {str(e)[:50]}")
                await asyncio.sleep(3)

    for attempt in range(5):
        try:
            if hasattr(client, "download_file"):
                await client.download_file(file_id, file_name=temp_name)
                if os.path.exists(temp_name):
                    data = await asyncio.to_thread(sync_read_file, temp_name)
                    os.remove(temp_name)
                    if data and len(data) > 0: return data
        except Exception as e:
            errors.append(f"Rubpy FileId Error: {str(e)[:50]}")
            await asyncio.sleep(3)
            
    raise Exception(f"سرورهای دانلود روبیکا پس از ۳۵ بار تلاش پاسخ ندادند!\nلاگ خطاها: {str(errors[-5:])}")

async def helper_download_url_to_bytes(url):
    async with aiohttp.ClientSession() as session:
        for _ in range(3):
            try:
                async with session.get(url, timeout=30) as resp:
                    if resp.status == 200:
                        return await resp.read()
            except Exception:
                await asyncio.sleep(2)
    return None

# ==============================================================================
# 🟢 پارت 10: سیستم چرخش کلیدهای جیمینای و تنظیم توکن‌های هاگینگ فیس
# ==============================================================================
# ==================================================================
# توکن‌ها و کلیدها
# ==================================================================
GEMINI_KEYS_STR1 = os.environ.get("GEMINI_API_KEYS1", "")
GEMINI_KEYS_STR2 = os.environ.get("GEMINI_API_KEYS2", "")

_raw_keys =[]
if GEMINI_KEYS_STR1: _raw_keys.extend(GEMINI_KEYS_STR1.split(","))
if GEMINI_KEYS_STR2: _raw_keys.extend(GEMINI_KEYS_STR2.split(","))

GEMINI_KEYS = list(set([k.strip() for k in _raw_keys if k.strip()]))
print(f"✅ تعداد {len(GEMINI_KEYS)} کلید جیمینای با موفقیت شناسایی شد.")

current_gemini_key_index = 0
gemini_key_lock = threading.Lock()

def get_next_gemini_keys(count=100):
    global current_gemini_key_index
    with gemini_key_lock:
        total_keys = len(GEMINI_KEYS)
        if total_keys == 0: return[]
        actual_count = min(count, total_keys)
        selected_keys =[]
        for _ in range(actual_count):
            selected_keys.append(GEMINI_KEYS[current_gemini_key_index])
            current_gemini_key_index = (current_gemini_key_index + 1) % total_keys
        return selected_keys

HF_TOKENS_STR = os.environ.get("HF_TOKENS", "")
HF_TOKENS =[k.strip() for k in HF_TOKENS_STR.split(",") if k.strip()]

# ==============================================================================
# 🟢 پارت 11: آپلودر دوگانه هوشمند (آپلود در بله + بکاپ خودکار در روبیکا)
# ==============================================================================
BALE_BOT_TOKEN = os.environ.get("BALE_BOT_TOKEN", "").strip()
import shutil
import uuid
import asyncio
import os
import aiohttp
from pydub import AudioSegment

async def official_rubika_upload(chat_id, target_path, file_type, caption):
    """اجرای دقیق 3 مرحله مستندات رسمی روبیکا به همراه تشخیص و تبدیل فرمت‌های تقلبی"""
    global bot_token
    if not bot_token: return False, "توکن ربات یافت نشد", target_path

    api_file_type = "File"
    if file_type in ["photo", "Image", "image"]: api_file_type = "Image"
    elif file_type in ["voice", "Voice", "audio", "Music", "music"]: api_file_type = "Music"

    original_path = target_path

    # 🟢 تشخیص فایل‌های صوتی که پسوند mp3 دارند اما در واقع wav هستند
    if api_file_type == "Music":
        base_name, ext = os.path.splitext(target_path)
        needs_conversion = (ext.lower() != '.mp3')
        
        if not needs_conversion:
            try:
                with open(target_path, 'rb') as f:
                    header = f.read(4)
                    if header.startswith(b'RIFF') or header.startswith(b'OggS') or header.startswith(b'fLaC'):
                        needs_conversion = True
            except:
                pass
                
        if needs_conversion:
            mp3_path = f"{base_name}_conv_{uuid.uuid4().hex[:4]}.mp3"
            def convert_to_mp3():
                try:
                    audio = AudioSegment.from_file(original_path)
                    audio.export(mp3_path, format="mp3", bitrate="128k")
                    return True
                except Exception as e:
                    print(f"Error converting to MP3: {e}")
                    return False
            
            # 🚀 استفاده از تردپول عظیم برای جلوگیری از کندی سرور در تعداد کاربر بالا
            is_converted = await asyncio.to_thread(convert_to_mp3)
            if is_converted and os.path.exists(mp3_path):
                target_path = mp3_path

    try:
        async with aiohttp.ClientSession() as session:
            # 1️⃣ مرحله اول: requestSendFile (درخواست لینک آپلود)
            req_url = f"https://botapi.rubika.ir/v3/{bot_token}/requestSendFile"
            async with session.post(req_url, json={"type": api_file_type}, timeout=30) as r1:
                if r1.status != 200: return False, f"خطا در ارتباط با سرور: HTTP {r1.status}", target_path
                d1 = await r1.json()
                upload_url = d1.get("data", {}).get("upload_url")
                if not upload_url: return False, "آدرس آپلود در سرور یافت نشد", target_path

            # 2️⃣ مرحله دوم: آپلود فایل در لینک دریافتی
            with open(target_path, 'rb') as f:
                form = aiohttp.FormData()
                form.add_field('file', f, filename=os.path.basename(target_path))
                async with session.post(upload_url, data=form, timeout=120) as r2:
                    if r2.status != 200: return False, "خطا در آپلود فایل", target_path
                    d2 = await r2.json()
                    file_id = d2.get("data", {}).get("file_id")
                    if not file_id: return False, "فایل آیدی دریافت نشد", target_path

            # 3️⃣ مرحله سوم: sendFile (ارسال فایل نهایی به چت کاربر)
            send_url = f"https://botapi.rubika.ir/v3/{bot_token}/sendFile"
            payload = {
                "chat_id": str(chat_id),
                "file_id": str(file_id),
                "text": caption
            }
            async with session.post(send_url, json=payload, timeout=30) as r3:
                if r3.status != 200: return False, "خطا در ارسال پیام نهایی", target_path
                d3 = await r3.json()
                if d3.get("status") == "OK" or d3.get("status_det") == "OK":
                    return True, "موفق", target_path
                else:
                    return False, f"ارور ارسال پیام: {d3.get('status_det')}", target_path

    except Exception as e:
        return False, str(e), target_path


async def background_rubika_upload(client, chat_id, target_path, file_type, caption):
    """تسک (کارگر) پس‌زمینه که کاملا مستقل عمل کرده و هیچ کندی در ربات ایجاد نمی‌کند"""
    final_path = target_path
    new_path = target_path
    try:
        await asyncio.sleep(2.0)
        
        if not os.path.exists(final_path): return
            
        # 🚀 ارسال با کپشن اصلی کاربر بدون هیچ متن اضافی (دقیقاً مشابه اطلاعات فایل)
        success, err_msg, new_path = await official_rubika_upload(chat_id, final_path, file_type, caption)

        if not success:
            debug_txt = f"❌ [دیباگ کارگر]: آپلود مستقیم با API روبیکا شکست خورد.\nارور:\n`{err_msg[:600]}`"
            try: await send_with_keyboard(client, chat_id, debug_txt, True)
            except: pass

    except Exception:
        pass
    finally:
        # پاکسازی هوشمند فایل‌های موقت بدون ایجاد اختلال
        try:
            if os.path.exists(final_path): os.remove(final_path)
        except: pass
        try:
            if new_path != final_path and os.path.exists(new_path): os.remove(new_path)
        except: pass


async def helper_upload_file(client, chat_id, file_name, file_type="Image", caption=""):
    abs_path = os.path.abspath(file_name)
    error_logs = []
    
    # ==========================================
    # فاز 1: تلاش برای آپلود در بله (ساخت لینک)
    # ==========================================
    if BALE_BOT_TOKEN:
        bale_chat_id = BALE_BOT_TOKEN.split(":")[0]
        for attempt in range(3):
            try:
                bale_url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendDocument"
                with open(abs_path, "rb") as f:
                    form = aiohttp.FormData()
                    form.add_field('chat_id', bale_chat_id)
                    form.add_field('document', f, filename=os.path.basename(abs_path))
                    
                    async with aiohttp.ClientSession() as session:
                        async with session.post(bale_url, data=form, timeout=120) as resp:
                            if resp.status == 200:
                                bale_data = await resp.json()
                                if bale_data.get("ok"):
                                    try:
                                        file_id = bale_data['result']['document']['file_id']
                                    except KeyError:
                                        if 'audio' in bale_data['result']: file_id = bale_data['result']['audio']['file_id']
                                        elif 'video' in bale_data['result']: file_id = bale_data['result']['video']['file_id']
                                        elif 'voice' in bale_data['result']: file_id = bale_data['result']['voice']['file_id']
                                        elif 'photo' in bale_data['result']: file_id = bale_data['result']['photo'][-1]['file_id']
                                        else:
                                            error_logs.append("فرمت در بله شناخته نشد.")
                                            continue

                                    download_url = f"https://tapi.bale.ai/file/bot{BALE_BOT_TOKEN}/{file_id}"
                                    
                                    # حذف متن اضافه در انتهای لینک بله و برگشت به حالت قبل
                                    final_text = f"{caption}\n\n━━━━━━━━━━━━━━━━━━━\n🌐 لینک دانلود فایل شما:\n\n{download_url}\n\n━━━━━━━━━━━━━━━━━━━\n⚠️ **راهنمای دانلود:**\nلطفاً لینک بالا را کپی کرده و در **مرورگر گوشی خود** باز کنید.\n*(مستقیماً کلیک نکنید)*"
                                    
                                    send_res = await send_with_keyboard(client, chat_id, final_text, True)
                                    
                                    if send_res:
                                        try:
                                            # گرفتن کپی از فایل به صورت غیرهمزمان (آزاد کردن هسته پردازشی برای ترافیک بالا)
                                            base_name, ext = os.path.splitext(abs_path)
                                            bg_target_path = f"{base_name}_bg_{uuid.uuid4().hex[:6]}{ext}"
                                            await asyncio.to_thread(shutil.copy2, abs_path, bg_target_path)
                                            
                                            # 🟢 ایجاد یک کارگر پس‌زمینه کاملاً مستقل برای هزاران کاربر همزمان
                                            asyncio.create_task(background_rubika_upload(client, chat_id, bg_target_path, file_type, caption))
                                        except Exception:
                                            pass
                                        return True
                                else:
                                    error_logs.append(f"Bale API Err: {bale_data.get('description')}")
                            else:
                                error_logs.append(f"Bale HTTP Error: {resp.status}")
                                if resp.status in [500, 502, 503]: await asyncio.sleep(2)
            except Exception as e:
                error_logs.append(f"Bale Err: {str(e)[:100]}")
                await asyncio.sleep(2)

    # ==========================================
    # فاز 2: سیستم نجات! (اگر بله قطع بود، مستقیم ارسال شود)
    # ==========================================
    fallback_caption = f"{caption}\n\n⚠️ (به دلیل اختلال سرورهای بله، فایل مستقیماً ارسال شد)"

    success, err_msg, new_path = await official_rubika_upload(chat_id, abs_path, file_type, fallback_caption)
    
    if new_path != abs_path:
        try:
            if os.path.exists(new_path): os.remove(new_path)
        except: pass

    if success:
        return True
        
    error_logs.append(f"Rubika API Err: {err_msg}")
    return "\n".join(error_logs[-5:])

# ==============================================================================
# 🟢 پارت 12: توابع تغییر صدا و لیست گویندگان
# ==============================================================================
# ==================================================================
# لیست‌های اولیه ربات
# ==================================================================
WORKER_URLS =["https://opera8-ttspro.hf.space/generate"]

SPEAKERS = {
    "1": ("شهاب (مرد)", "Charon"), "2": ("آوا (زن)", "Zephyr"), "3": ("نوید (مرد)", "Achird"), 
    "4": ("آرمان (مرد)", "Zubenelgenubi"), "5": ("مهسا (زن)", "Vindemiatrix"), "6": ("دانا (مرد)", "Rasalgethi"),
    "7": ("سامان (مرد)", "Sadachbia"), "8": ("آرش (مرد)", "Sadaltager"), "9": ("شبنم (زن)", "Sulafat"),
    "10": ("سحر (زن)", "Laomedeia"), "11": ("مریم (زن)", "Achernar"), "12": ("بهرام (مرد)", "Alnilam"),
    "13": ("نیکان (مرد)", "Schedar"), "14": ("فرناز (زن)", "Gacrux"), "15": ("سارا (زن)", "Pulcherrima"),
    "16": ("مانی (مرد)", "Umbriel"), "17": ("آرتین (مرد)", "Algieba"), "18": ("دلنواز (زن)", "Despina"),
    "19": ("روژان (زن)", "Erinome"), "20": ("امید (مرد)", "Algenib"), "21": ("بردیا (مرد)", "Orus"),
    "22": ("ترانه (زن)", "Aoede"), "23": ("نیکو (زن)", "Callirrhoe"), "24": ("هستی (زن)", "Autonoe"),
    "25": ("کامیار (مرد)", "Enceladus"), "26": ("کیانوش (مرد)", "Iapetus"), "27": ("پویا (مرد)", "Puck"),
    "28": ("مهتاب (زن)", "Kore"), "29": ("سام (مرد)", "Fenrir"), "30": ("لیدا (زن)", "Leda")
}

user_states = {}

# ==============================================================================
# 🟢 پارت 12: لیست گویندگان و توابع تغییر صدا
# ==============================================================================
# ==================================================================
# لیست‌های اولیه ربات
# ==================================================================
# (آدرس کارگرها طبق درخواست حذف شد و پردازش به اسپیس پادکست منتقل گردید)

SPEAKERS = {
    "1": ("شهاب (مرد)", "Charon"), "2": ("آوا (زن)", "Zephyr"), "3": ("نوید (مرد)", "Achird"), 
    "4": ("آرمان (مرد)", "Zubenelgenubi"), "5": ("مهسا (زن)", "Vindemiatrix"), "6": ("دانا (مرد)", "Rasalgethi"),
    "7": ("سامان (مرد)", "Sadachbia"), "8": ("آرش (مرد)", "Sadaltager"), "9": ("شبنم (زن)", "Sulafat"),
    "10": ("سحر (زن)", "Laomedeia"), "11": ("مریم (زن)", "Achernar"), "12": ("بهرام (مرد)", "Alnilam"),
    "13": ("نیکان (مرد)", "Schedar"), "14": ("فرناز (زن)", "Gacrux"), "15": ("سارا (زن)", "Pulcherrima"),
    "16": ("مانی (مرد)", "Umbriel"), "17": ("آرتین (مرد)", "Algieba"), "18": ("دلنواز (زن)", "Despina"),
    "19": ("روژان (زن)", "Erinome"), "20": ("امید (مرد)", "Algenib"), "21": ("بردیا (مرد)", "Orus"),
    "22": ("ترانه (زن)", "Aoede"), "23": ("نیکو (زن)", "Callirrhoe"), "24": ("هستی (زن)", "Autonoe"),
    "25": ("کامیار (مرد)", "Enceladus"), "26": ("کیانوش (مرد)", "Iapetus"), "27": ("پویا (مرد)", "Puck"),
    "28": ("مهتاب (زن)", "Kore"), "29": ("سام (مرد)", "Fenrir"), "30": ("لیدا (زن)", "Leda")
}

user_states = {}

# ==================================================================
# توابع تغییر صدا و کلون کردن
# ==================================================================
async def process_standard_vc_job(client, chat_id, src_bytes, ref_bytes, job_type_name, credit_type):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    creds = get_user_credits(str_chat_id)
    
    proc_msg = await send_with_keyboard(client, chat_id, f"⏳ در حال آماده‌سازی فایل‌ها...\n(مدل: {job_type_name})", False)
    
    async with aiohttp.ClientSession() as session:
        job_id = None
        total_chunks = 1
        chunks = []
        
        # ♻️ سیستم تلاش مجدد پنهان (دور زدن ارور 429)
        for attempt in range(8):
            form = aiohttp.FormData()
            form.add_field('source_audio', src_bytes, filename='src.wav', content_type='audio/wav')
            form.add_field('ref_audio', ref_bytes, filename='ref.wav', content_type='audio/wav')
            
            try:
                async with session.post(f"{VC_BASE_URL}/upload", data=form, timeout=43200) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        job_id = data.get("job_id")
                        total_chunks = data.get("total_chunks", 1)
                        chunks = data.get("chunks", [])
                        break
                    elif resp.status == 429:
                        await asyncio.sleep(4 + attempt * 2) # تاخیر تصاعدی تا سرور خلوت شود
                    else:
                        await asyncio.sleep(3)
            except Exception as e:
                await asyncio.sleep(3)
                
        if not job_id:
            return await send_with_keyboard(client, chat_id, "❌ سرور پردازش صدا به دلیل ترافیک بالا پاسخگو نیست (خطای 429). لطفاً چند دقیقه دیگر امتحان کنید.", True)

        await send_with_keyboard(client, chat_id, "✅ فایل‌ها ارسال شد. در حال پردازش و تغییر صدا...\n(لطفا چند دقیقه صبور باشید)", False)
        
        final_filename = None
        for _ in range(10000):
            await asyncio.sleep(4)
            payload_check = {"job_id": job_id, "total_chunks": total_chunks, "chunks": chunks}
            try:
                async with session.post(f"{VC_BASE_URL}/check_status", json=payload_check, timeout=20) as c_resp:
                    if c_resp.status == 200:
                        c_data = await c_resp.json()
                        if c_data.get("status") == "completed":
                            final_filename = c_data.get("filename")
                            break
                        elif c_data.get("status") in ["failed", "error"]:
                            return await send_with_keyboard(client, chat_id, "❌ خطای سرور در حین پردازش صدا.", True)
                    elif c_resp.status == 429:
                        await asyncio.sleep(5)
            except Exception:
                pass
                
        if not final_filename:
            return await send_with_keyboard(client, chat_id, "❌ پردازش بیش از حد طول کشید و متوقف شد.", True)

        download_url = f"{VC_BASE_URL}/download/{final_filename}"
        await send_with_keyboard(client, chat_id, "📥 پردازش تمام شد! در حال آماده‌سازی لینک دانلود...", False)
        
        result_bytes = None
        for attempt in range(5):
            try:
                async with session.get(download_url, timeout=43200) as d_resp:
                    if d_resp.status == 200:
                        result_bytes = await d_resp.read()
                        break
                    elif d_resp.status == 429:
                        await asyncio.sleep(4 + attempt * 2)
                    else:
                        await asyncio.sleep(3)
            except Exception:
                await asyncio.sleep(3)

        if not result_bytes:
            return await send_with_keyboard(client, chat_id, "❌ خطا در اتصال هنگام دانلود خروجی از سرور اصلی.", True)

    file_name_mp3 = f"vc_standard_{uuid.uuid4().hex[:6]}.mp3"
    await asyncio.to_thread(sync_write_file, file_name_mp3, result_bytes)
    
    upload_result = False
    for up_att in range(3):
        res = await helper_upload_file(client, chat_id, file_name_mp3, "Music", f"🎙️ {job_type_name} شما آماده است!")
        if res is True:
            upload_result = True
            break
        await asyncio.sleep(4)

    if upload_result is True:
        if not creds.get("is_premium"):
            user_credits_db[str_chat_id][credit_type] -= 1
            save_db(user_credits_db)
    else:
        await send_with_keyboard(client, chat_id, "❌ فایل پردازش شد اما امکان ارسال فراهم نشد.", True)
        
    if os.path.exists(file_name_mp3): os.remove(file_name_mp3)

async def process_legacy_vc_job(client, chat_id, src_bytes, model_url, pitch, model_name):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    creds = get_user_credits(str_chat_id)
    
    proc_msg = await send_with_keyboard(client, chat_id, f"⏳ در حال آماده‌سازی فایل‌ها...\n(مدل: {model_name})", False)
    
    async with aiohttp.ClientSession() as session:
        job_id = None
        
        # ♻️ سیستم تلاش مجدد پنهان (دور زدن ارور 429)
        for attempt in range(8):
            form = aiohttp.FormData()
            form.add_field('audio_file', src_bytes, filename='input.wav', content_type='audio/wav')
            form.add_field('model_url', model_url)
            form.add_field('pitch', str(pitch))
            form.add_field('algo', 'rmvpe+')
            form.add_field('index_inf', '0.75')
            form.add_field('res_filter', '3')
            form.add_field('env_ratio', '0.25')
            form.add_field('protect', '0.33')
            form.add_field('denoise', 'false')
            form.add_field('reverb', 'false')
            
            try:
                async with session.post(f"{LEGACY_BASE_URL}/upload", data=form, timeout=43200) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        job_id = data.get("job_id")
                        break
                    elif resp.status == 429:
                        await asyncio.sleep(4 + attempt * 2)
                    else:
                        await asyncio.sleep(3)
            except Exception as e:
                await asyncio.sleep(3)
                
        if not job_id:
            return await send_with_keyboard(client, chat_id, "❌ سرور پردازش صدا به دلیل ترافیک بالا پاسخگو نیست (خطای 429). لطفاً چند دقیقه دیگر امتحان کنید.", True)

        await send_with_keyboard(client, chat_id, "✅ فایل ارسال شد. در حال پردازش و تغییر صدای شما...\n(لطفا چند دقیقه صبور باشید)", False)
        
        final_filename = None
        for _ in range(10000):
            await asyncio.sleep(5)
            try:
                async with session.get(f"{LEGACY_BASE_URL}/status/{job_id}", timeout=20) as c_resp:
                    if c_resp.status == 200:
                        c_data = await c_resp.json()
                        if c_data.get("status") == "completed":
                            final_filename = c_data.get("filename")
                            break
                        elif c_data.get("status") in ["failed", "error", "not_found"]:
                            return await send_with_keyboard(client, chat_id, "❌ خطای سرور در حین پردازش.", True)
                    elif c_resp.status == 429:
                        await asyncio.sleep(5)
            except Exception:
                pass
                
        if not final_filename:
            return await send_with_keyboard(client, chat_id, "❌ پردازش بیش از حد طول کشید و متوقف شد.", True)

        download_url = f"{LEGACY_BASE_URL}/download/{final_filename}"
        await send_with_keyboard(client, chat_id, "📥 پردازش تمام شد! در حال آماده‌سازی لینک دانلود...", False)
        
        result_bytes = None
        for attempt in range(5):
            try:
                async with session.get(download_url, timeout=43200) as d_resp:
                    if d_resp.status == 200:
                        result_bytes = await d_resp.read()
                        break
                    elif d_resp.status == 429:
                        await asyncio.sleep(4 + attempt * 2)
                    else:
                        await asyncio.sleep(3)
            except Exception:
                await asyncio.sleep(3)
                
        if not result_bytes:
            return await send_with_keyboard(client, chat_id, "❌ خطا در اتصال هنگام دانلود خروجی از سرور.", True)

    file_name_mp3 = f"vc_legacy_{uuid.uuid4().hex[:6]}.mp3"
    await asyncio.to_thread(sync_write_file, file_name_mp3, result_bytes)
    
    upload_result = False
    for up_att in range(3):
        res = await helper_upload_file(client, chat_id, file_name_mp3, "Music", f"🎙️ صدای خروجی با مدل {model_name} آماده است!")
        if res is True:
            upload_result = True
            break
        await asyncio.sleep(4)

    if upload_result is True:
        # اگر مدل باب اسفنجی نبود، از اعتبار کسر کن
        if not creds.get("is_premium") and model_name != "باب اسفنجی":
            user_credits_db[str_chat_id]["voice_conv"] -= 1
            save_db(user_credits_db)
    else:
        await send_with_keyboard(client, chat_id, "❌ فایل پردازش شد اما امکان ارسال لینک فراهم نشد.", True)
        
    if os.path.exists(file_name_mp3): os.remove(file_name_mp3)

# ==============================================================================
# 🟢 پارت 13: پردازش هوش مصنوعی متنی و تصویری جیمینای و هاگینگ‌فیس (ترکیب با Aya)
# ==============================================================================
async def process_gemini(client, chat_id, prompt, file_bytes=None, file_name=None):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    creds = get_user_credits(str_chat_id)
    if creds["chat"] <= 0:
        return await send_with_keyboard(client, chat_id, "❌ اعتبار پیام‌های چت شما تمام شده است. لطفاً از منوی اصلی وارد بخش «خرید اشتراک 💎» شوید.", False)

    proc_msg = await send_with_keyboard(client, chat_id, "🧠 در حال پردازش...", False)
    history = user_states[chat_id].get("history", [])
    new_parts = []
    
    is_image = False
    has_non_image_file = False
    
    if prompt: new_parts.append({"text": prompt})
    elif file_bytes: new_parts.append({"text": "لطفاً این فایل را به دقت بررسی کن."})
        
    if file_bytes and file_name:
        base64_data = base64.b64encode(file_bytes).decode('utf-8')
        mime_type, _ = mimetypes.guess_type(file_name)
        if not mime_type:
            if file_name.endswith(('.jpg', '.jpeg')): mime_type = "image/jpeg"
            elif file_name.endswith('.png'): mime_type = "image/png"
            elif file_name.endswith('.pdf'): mime_type = "application/pdf"
            elif file_name.endswith('.mp4'): mime_type = "video/mp4"
            elif file_name.endswith('.mp3'): mime_type = "audio/mp3"
            elif file_name.endswith(('.ogg', '.oga')): mime_type = "audio/ogg"
            elif file_name.endswith('.wav'): mime_type = "audio/wav"
            else: mime_type = "image/jpeg"
            
        is_image = mime_type.startswith('image/')
        if not is_image:
            has_non_image_file = True
            
        new_parts.append({"inlineData": {"mimeType": mime_type, "data": base64_data}})

    # اضافه کردن پیام جدید به تاریخچه مشترک ربات
    if history and history[-1]["role"] == "user": history[-1]["parts"].extend(new_parts)
    else: history.append({"role": "user", "parts": new_parts})

    # 🔴 محدود کردن طول تاریخچه به ۲۰ پیام (۱۰ پیام کاربر + ۱۰ پیام ربات)
    if len(history) > 50:
        history = history[-50:]
        if history[0]["role"] == "model": history = history[1:]

    final_answer = None

    # =========================================================================
    # 🔴 مسیر اول: اگر کاربر فایل یا عکس ارسال کرده باشد (استفاده از جیمینای)
    # =========================================================================
    if file_bytes is not None:
        if not GEMINI_KEYS: 
            try:
                if proc_msg:
                    msg_id = getattr(proc_msg, 'message_id', None)
                    if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
                    if msg_id: await client.delete_messages(chat_id, [msg_id])
            except Exception: pass
            return await send_with_keyboard(client, chat_id, "❌ کلیدهای API جیمینای تنظیم نشده‌اند.", False)

        for attempt in range(3):
            keys_to_try = get_next_gemini_keys(100)
            async with aiohttp.ClientSession() as session:
                for key in keys_to_try:
                    url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={key}"
                    payload = {"contents": history, "generationConfig": {"temperature": 0.7, "maxOutputTokens": 8192}}
                    try:
                        async with session.post(url, json=payload, timeout=60) as response:
                            if response.status == 200:
                                data = await response.json()
                                try:
                                    final_answer = data["candidates"][0]["content"]["parts"][0]["text"]
                                    break
                                except (KeyError, IndexError): continue 
                    except Exception: continue
            if final_answer: break
            await asyncio.sleep(2)

        if not final_answer:
            if has_non_image_file:
                if history and history[-1]["role"] == "user": history.pop()
                try:
                    if proc_msg:
                        msg_id = getattr(proc_msg, 'message_id', None)
                        if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
                        if msg_id: await client.delete_messages(chat_id, [msg_id])
                except Exception: pass
                await send_with_keyboard(client, chat_id, "❌ متأسفانه سرور اصلی در حال حاضر شلوغ است و در این شرایط **فعلاً تنها امکان تحلیل تصاویر** توسط سرور جایگزین در دسترس است.", False)
                return
                
            if HF_TOKENS:
                hf_messages = []
                for msg in history:
                    role = "assistant" if msg["role"] == "model" else "user"
                    content_parts = []
                    for part in msg["parts"]:
                        if "text" in part:
                            content_parts.append({"type": "text", "text": part["text"]})
                        elif "inlineData" in part:
                            mime_t = part["inlineData"]["mimeType"]
                            b64_d = part["inlineData"]["data"]
                            if mime_t.startswith('image/'):
                                content_parts.append({
                                    "type": "image_url",
                                    "image_url": {"url": f"data:{mime_t};base64,{b64_d}"}
                                })
                    if content_parts:
                        hf_messages.append({"role": role, "content": content_parts})

                for attempt in range(3):
                    keys_to_try_hf = HF_TOKENS.copy()
                    random.shuffle(keys_to_try_hf)
                    async with aiohttp.ClientSession() as session:
                        for hf_key in keys_to_try_hf:
                            url = "https://router.huggingface.co/v1/chat/completions"
                            headers = {"Authorization": f"Bearer {hf_key}", "Content-Type": "application/json"}
                            payload = {
                                "model": "google/gemma-4-31B-it:novita",
                                "messages": hf_messages,
                                "max_tokens": 4096
                            }
                            try:
                                async with session.post(url, headers=headers, json=payload, timeout=60) as response:
                                    if response.status == 200:
                                        data = await response.json()
                                        final_answer = data["choices"][0]["message"]["content"]
                                        break
                            except Exception:
                                continue
                    if final_answer: break
                    await asyncio.sleep(2)

    # =========================================================================
    # 🟢 مسیر دوم: اگر فقط متن بود (استفاده از اسپیس Cohere Labs Aya Expanse)
    # =========================================================================
    else:
        # 🟢 تزریق شخصیت و دستورالعمل جدید به مدل
        system_rules = """تو یک دستیار با مزه از برنامه هوش مصنوعی آلفا هستی😊 و توسط هوش مصنوعی آلفا توسعه داده شدی.
اینگونه می‌تونی خودت رو معرفی کنی، من یه هوش مصنوعیِ ساخته‌شده توسط تیم‌ تخصصی آلفا ام، و بر پایه مدل GPT-5.4 کار می‌کنم. یعنی یه نوع نرم‌افزار خیلی هوشمند که با کمک میلیون‌ها داده و آموزش‌های پیشرفته ساخته شده، تا بتونه بهت کمک کنه، سوالاتت رو جواب بده، یا حتی یه شوخی خنده‌دار برات بگه وقتی حال و هوات گرفته‌ست!
در واقع، من نتیجه سال‌ها تحقیقات و تلاش‌های مهندس‌ها و پژوهشگرها هستم، تا جایی که می‌تونم بهترین کمک رو بهت بکنم. این دستورات های تو هستند و بصورت رندوم متفاوت جواب بده و از شکلک های مناسب و جواب های جذاب استفاده کن. اگر در یک مکالمه اول سلام کردی در پیام های بعدی سلام نیاز نیست.."""

        # 🟢 استخراج تاریخچه و تبدیل آن به متنی پیوسته جهت تزریق مستقیم به حافظه مدل (تضمین ۱۰۰٪ یادآوری)
        text_history = ""
        gradio_history = []
        temp_user_msg = ""
        
        for msg in history[:-1]:
            text_content = "".join([p.get("text", "") for p in msg.get("parts", []) if "text" in p]).strip()
            if not text_content: continue
            
            if msg["role"] == "user":
                temp_user_msg = text_content
                text_history += f"کاربر: {text_content}\n"
            elif msg["role"] == "model":
                text_history += f"آلفا: {text_content}\n"
                if temp_user_msg:
                    gradio_history.append([temp_user_msg, text_content])
                    temp_user_msg = ""
                else:
                    gradio_history.append(["", text_content])
                    
        # ادغام دستورات، تاریخچه گذشته و پیام جدید به یک پرامپت قدرتمند
        if text_history:
            full_prompt = f"{system_rules}\n\n--- تاریخچه مکالمه تا این لحظه ---\n{text_history}\n--- پایان تاریخچه ---\n\nپیام جدید کاربر:\n{prompt}"
        else:
            full_prompt = f"{system_rules}\n\n---\nپیام جدید کاربر:\n{prompt}"

        session_hash = ''.join(random.choices(string.ascii_lowercase + string.digits, k=11))
        join_url = "https://coherelabs-aya-expanse.hf.space/gradio_api/queue/join"
        data_url = f"https://coherelabs-aya-expanse.hf.space/gradio_api/queue/data?session_hash={session_hash}"
        
        # ساختار Payload دقیقاً منطبق با اسپیس
        payload = {
            "data": [
                full_prompt,
                gradio_history,
                None,
                None
            ],
            "event_data": None,
            "fn_index": 2,
            "session_hash": session_hash,
            "trigger_id": 37
        }

        for attempt in range(3):
            try:
                async with aiohttp.ClientSession() as session:
                    async with session.post(join_url, json=payload, timeout=30) as resp:
                        if resp.status == 200:
                            async with session.get(data_url, timeout=120) as data_resp:
                                async for line_bytes in data_resp.content:
                                    line = line_bytes.decode('utf-8').strip()
                                    if line.startswith("data: "):
                                        try:
                                            json_data = json.loads(line[6:])
                                            if json_data.get("msg") == "process_completed":
                                                if json_data.get("success"):
                                                    output_data = json_data.get("output", {}).get("data", [])
                                                    if output_data and len(output_data) > 0:
                                                        result_hist = output_data[0]
                                                        if isinstance(result_hist, list) and len(result_hist) > 0:
                                                            final_answer = result_hist[-1][1] 
                                                break
                                        except Exception: pass
            except Exception: pass
            
            if final_answer: break
            await asyncio.sleep(2)

    # =========================================================================
    # 🏁 پایان پردازش و ارسال نتیجه نهایی به کاربر
    # =========================================================================
    try:
        if proc_msg:
            msg_id = getattr(proc_msg, 'message_id', None)
            if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
            if msg_id: await client.delete_messages(chat_id, [msg_id])
    except Exception: pass

    if not final_answer:
        if history and history[-1]["role"] == "user": history.pop()
        await send_with_keyboard(client, chat_id, "❌ تمامی سرورها شلوغ هستند. لطفاً بعداً امتحان کنید.", False)
        return

    # ذخیره پاسخ در تاریخچه چت کاربر
    history.append({"role": "model", "parts": [{"text": final_answer}]})
    user_states[chat_id]["history"] = history

    try:
        max_len = 1000 
        chunks = []
        temp_text = final_answer
        while len(temp_text) > max_len:
            split_idx = temp_text.rfind('\n', 0, max_len)
            if split_idx == -1: split_idx = temp_text.rfind(' ', 0, max_len)
            if split_idx == -1: split_idx = max_len
            chunks.append(temp_text[:split_idx])
            temp_text = temp_text[split_idx:].strip()
        if temp_text: chunks.append(temp_text)
        
        success_sent = False
        for idx, chunk in enumerate(chunks):
            if idx != len(chunks) - 1: chunk += "\n\n⏳ *(ادامه در پیام بعدی)...* 👇"
            try:
                res = await send_with_keyboard(client, chat_id, chunk, False)
                if res: success_sent = True
                await asyncio.sleep(2.5) 
            except Exception: await asyncio.sleep(2.5)
            
        if success_sent and not creds.get("is_premium"):
            user_credits_db[str_chat_id]["chat"] -= 1
            save_db(user_credits_db)
                
    except Exception:
        await send_with_keyboard(client, chat_id, "❌ خطایی در ارسال پیام رخ داد.", False)

# ==============================================================================
# 🟢 پارت 14: ساخت عکس با هوش مصنوعی
# ==============================================================================
async def process_image(client, chat_id, prompt, size_choice="1"):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    creds = get_user_credits(str_chat_id)
    
    is_prem = creds.get("is_premium", False)
    
    # === بررسی کاربران رایگان ===
    if not is_prem:
        msg = """کاربر گرامی،

ضمن تشکر از توجه شما، به اطلاع می‌رساند که قابلیت ساخت تصاویر در حال حاضر به صورت رایگان در دسترس نمی‌باشد. این سرویس به دلیل نیاز به منابع پردازشی بالا، جزو خدمات ویژه و نیازمند تهیه اشتراک است.

با این حال، شما می‌توانید از تست رایگان و امکانات سایر بخش‌های پلتفرم ما بهره‌مند شوید.

ما همواره در تلاش برای افزایش منابع و اضافه کردن خدمات رایگان بیشتر به کاربران عزیز هستیم.

در حال حاضر، می‌توانید از سایر بخش‌های رایگان موجود استفاده کنید و یا برای دسترسی کامل و نامحدود به تمامی قابلیت‌ها (از جمله ساخت تصاویر)، اشتراک تهیه نمایید.

از صبوری و همراهی شما سپاسگزاریم."""
        return await send_with_keyboard(client, chat_id, msg, False)

    # === بررسی اعتبار کاربران پولی ===
    if creds["image"] <= 0:
        msg = "⚠️ **اعتبار شما برای این بخش تمام شده است!**\nاز بقیه بخش‌ها می‌توانید نامحدود استفاده کنید. در حال افزایش منابع برای این بخش هستیم."
        return await send_with_keyboard(client, chat_id, msg, False)

    if not HF_TOKENS: return await send_with_keyboard(client, chat_id, "❌ توکن‌های هاگینگ فیس تنظیم نشده‌اند.", False)
    
    proc_msg = await send_with_keyboard(client, chat_id, "✨ در حال ترجمه و بهینه‌سازی پرامپت شما...\n(تبدیل به پرامپت حرفه‌ای)", False)
    
    aya_sys_prompt = f"You are an expert AI image generation prompt engineer. Translate the following user input to English, and enhance it with high-quality, highly detailed, 4k resolution, cinematic lighting, and visually striking descriptive keywords. Return ONLY the final English prompt string.\nUser input: {prompt}"
    
    enhanced_prompt = prompt
    session_hash = ''.join(random.choices(string.ascii_lowercase + string.digits, k=11))
    join_url = "https://coherelabs-aya-expanse.hf.space/gradio_api/queue/join"
    data_url = f"https://coherelabs-aya-expanse.hf.space/gradio_api/queue/data?session_hash={session_hash}"
    
    payload = {
        "data": [
            aya_sys_prompt,
            [],
            None,
            None
        ],
        "event_data": None,
        "fn_index": 2,
        "session_hash": session_hash,
        "trigger_id": 37
    }

    for attempt in range(3):
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(join_url, json=payload, timeout=30) as resp:
                    if resp.status == 200:
                        async with session.get(data_url, timeout=120) as data_resp:
                            async for line_bytes in data_resp.content:
                                line = line_bytes.decode('utf-8').strip()
                                if line.startswith("data: "):
                                    try:
                                        json_data = json.loads(line[6:])
                                        if json_data.get("msg") == "process_completed":
                                            if json_data.get("success"):
                                                output_data = json_data.get("output", {}).get("data", [])
                                                if output_data and len(output_data) > 0:
                                                    result_hist = output_data[0]
                                                    if isinstance(result_hist, list) and len(result_hist) > 0:
                                                        enhanced_prompt = result_hist[-1][1].strip()
                                            break
                                    except Exception: pass
        except Exception: pass
        if enhanced_prompt != prompt: break
        await asyncio.sleep(2)

    try:
        if proc_msg:
            msg_id = getattr(proc_msg, 'message_id', None)
            if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
            if msg_id: await client.delete_messages(chat_id,[msg_id])
    except Exception: pass
    
    w, h = 1024, 1024
    size_name = "مربع (1:1) ⬛"
    if size_choice == "2":
        w, h = 768, 1344
        size_name = "عمودی (9:16) 📱"
    elif size_choice == "3":
        w, h = 1344, 768
        size_name = "افقی (16:9) 🖥️"
    elif size_choice == "4":
        w, h = 1024, 768
        size_name = "استاندارد (4:3) 📸"

    short_preview = enhanced_prompt[:150] + "..." if len(enhanced_prompt) > 150 else enhanced_prompt
    proc_msg = await send_with_keyboard(client, chat_id, f"🎨 در حال طراحی عکس...\n\n📏 **ابعاد:** {size_name}\n📝 **پرامپت ساخته شده:**\n`{short_preview}`\n\n(ممکن است چند ثانیه زمان ببرد)", False)

    generated_image = None
    
    for attempt in range(5):
        keys_to_try = HF_TOKENS.copy()
        random.shuffle(keys_to_try)
        for token in keys_to_try:
            try:
                hf_client = AsyncInferenceClient(provider="fal-ai", api_key=token)
                generated_image = await hf_client.text_to_image(
                    enhanced_prompt, 
                    model="Tongyi-MAI/Z-Image-Turbo",
                    width=w,
                    height=h
                )
                break 
            except Exception as e:
                continue
        if generated_image: break
        await asyncio.sleep(2)
            
    try:
        if proc_msg:
            msg_id = getattr(proc_msg, 'message_id', None)
            if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
            if msg_id: await client.delete_messages(chat_id,[msg_id])
    except Exception: pass

    if not generated_image: 
        # === پیام اختصاصی جایگزین ارور اسپیس ===
        error_msg = "⚠️ **منابع این بخش در حال افزایش است!**\nموقتاً این بخش در حال ارتقا است. فعلاً اعتباری از شما کم نشد، به‌زودی این بخش در دسترس قرار خواهد گرفت."
        return await send_with_keyboard(client, chat_id, error_msg, True)

    try:
        file_name = f"image_{uuid.uuid4().hex}.jpg"
        await asyncio.to_thread(sync_save_image, generated_image, file_name)
        await asyncio.sleep(1)
        caption_text = f"🎨 تصویر شما با پرامپت هوشمند آماده شد!\n\n📏 ابعاد تصویر: {size_name}\n✨ ایده اولیه: {prompt}"
        
        upload_result = False
        for up_att in range(3):
            res = await helper_upload_file(client, chat_id, file_name, "Image", caption_text)
            if res is True:
                upload_result = True
                break
            else:
                await asyncio.sleep(4)
        
        if upload_result is True:
            # کسر اعتبار از کاربران پولی
            user_credits_db[str_chat_id]["image"] -= 1
            save_db(user_credits_db)
        else:
            await send_with_keyboard(client, chat_id, "❌ عکس ساخته شد اما آپلود در روبیکا با خطا مواجه شد.", True)
            
        if os.path.exists(file_name): os.remove(file_name)
    except Exception as e: 
        await send_with_keyboard(client, chat_id, f"❌ خطا در ذخیره و ارسال عکس:\n{str(e)[:150]}", True)


# ==============================================================================
# 🟢 پارت 15: توابع ترجمه و ویرایش عکس با هوش مصنوعی (Flux.2)
# ==============================================================================
async def translate_text_aloha(prompt_text):
    session_hash = ''.join(random.choices(string.ascii_lowercase + string.digits, k=11))
    join_url = "https://hamed744-translate-tts-aloha.hf.space/gradio_api/queue/join"
    payload = {
        "data":[prompt_text, "انگلیسی (آمریکا) - جنی (زن)", 0, 0, 0],
        "fn_index": 1,
        "session_hash": session_hash
    }
    
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(join_url, json=payload, timeout=20) as resp:
                if resp.status != 200:
                    return prompt_text
                    
            data_url = f"https://hamed744-translate-tts-aloha.hf.space/gradio_api/queue/data?session_hash={session_hash}"
            async with session.get(data_url, timeout=60) as resp:
                async for line_bytes in resp.content:
                    line = line_bytes.decode('utf-8').strip()
                    if line.startswith("data: "):
                        try:
                            json_data = json.loads(line[6:])
                            if json_data.get("msg") == "process_completed":
                                if json_data.get("success"):
                                    return json_data["output"]["data"][0]
                                break
                        except Exception:
                            pass
    except Exception:
        pass
        
    return prompt_text

async def process_image_edit(client, chat_id, image_bytes, prompt):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    creds = get_user_credits(str_chat_id)
    
    is_prem = creds.get("is_premium", False)
    
    # === بررسی کاربران رایگان (جهت اطمینان در لایه دوم) ===
    if not is_prem:
        msg = """کاربر گرامی،

ضمن تشکر از توجه شما، به اطلاع می‌رساند که قابلیت ویرایش تصاویر در حال حاضر به صورت رایگان در دسترس نمی‌باشد. این سرویس به دلیل نیاز به منابع پردازشی بالا، جزو خدمات ویژه و نیازمند تهیه اشتراک است.

با این حال، شما می‌توانید از تست رایگان و امکانات سایر بخش‌های پلتفرم ما بهره‌مند شوید.

ما همواره در تلاش برای افزایش منابع و اضافه کردن خدمات رایگان بیشتر به کاربران عزیز هستیم.

در حال حاضر، می‌توانید از سایر بخش‌های رایگان موجود استفاده کنید و یا برای دسترسی کامل و نامحدود به تمامی قابلیت‌ها (از جمله ویرایش تصاویر)، اشتراک تهیه نمایید.

از صبوری و همراهی شما سپاسگزاریم."""
        return await send_with_keyboard(client, chat_id, msg, False)

    # === بررسی اعتبار کاربران پولی ===
    if creds["edit_image"] <= 0:
        msg = "⚠️ **اعتبار شما برای این بخش تمام شده است!**\nاز بقیه بخش‌ها می‌توانید نامحدود استفاده کنید. در حال افزایش منابع برای این بخش هستیم."
        return await send_with_keyboard(client, chat_id, msg, False)

    if not HF_TOKENS:
        return await send_with_keyboard(client, chat_id, "❌ توکن‌های هاگینگ فیس تنظیم نشده‌اند.", False)

    proc_msg = await send_with_keyboard(client, chat_id, "🪄 در حال ترجمه دستور شما توسط اسپیس و اعمال جادوی FLUX.2...\n(این فرآیند ممکن است کمی طول بکشد)", False)
    
    translated_prompt = await translate_text_aloha(prompt)
    if not translated_prompt or translated_prompt.strip() == "":
        translated_prompt = prompt

    generated_image = None
    
    for attempt in range(5):
        keys_to_try = HF_TOKENS.copy()
        random.shuffle(keys_to_try)
        for token in keys_to_try:
            try:
                hf_client = AsyncInferenceClient(provider="fal-ai", api_key=token)
                generated_image = await hf_client.image_to_image(
                    image_bytes,
                    prompt=translated_prompt,
                    model="black-forest-labs/FLUX.2-dev"
                )
                break 
            except Exception as e:
                continue
        if generated_image: break
        await asyncio.sleep(2)
            
    try:
        if proc_msg:
            msg_id = getattr(proc_msg, 'message_id', None)
            if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
            if msg_id: await client.delete_messages(chat_id,[msg_id])
    except Exception: pass

    if not generated_image:
        # === پیام اختصاصی جایگزین ارور اسپیس ===
        error_msg = "⚠️ **منابع این بخش در حال افزایش است!**\nموقتاً این بخش در حال ارتقا است. فعلاً اعتباری از شما کم نشد، به‌زودی این بخش در دسترس قرار خواهد گرفت."
        return await send_with_keyboard(client, chat_id, error_msg, True)

    try:
        file_name = f"edited_flux_{uuid.uuid4().hex}.jpg"
        await asyncio.to_thread(sync_save_image, generated_image, file_name)
        await asyncio.sleep(1)
        caption_text = f"🪄 ویرایش عکس با هوش مصنوعی Flux.2 انجام شد!\n\n✨ تغییرات خواسته شده: {prompt}\n🔤 متن ارسال شده به هوش: {translated_prompt}"
        
        upload_result = False
        for up_att in range(3):
            res = await helper_upload_file(client, chat_id, file_name, "Image", caption_text)
            if res is True:
                upload_result = True
                break
            else:
                await asyncio.sleep(4)
        
        if upload_result is True:
            # کسر اعتبار از کاربران پولی
            user_credits_db[str_chat_id]["edit_image"] -= 1
            save_db(user_credits_db)
        else:
            await send_with_keyboard(client, chat_id, "❌ عکس ساخته شد اما خطا در ارسال به روبیکا رخ داد.", True)
            
        if os.path.exists(file_name): os.remove(file_name)
    except Exception as e:
        await send_with_keyboard(client, chat_id, f"❌ خطا در ذخیره عکس ویرایش شده:\n{str(e)[:150]}", True)

# ==============================================================================
# 🟢 پارت 16: ساخت صدا از روی متن (تبدیل متن به صدا - متصل به اسپیس پادکست)
# ==============================================================================
async def process_tts(client, chat_id, user_text, speaker_id, speaker_name):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    creds = get_user_credits(str_chat_id)
    if creds["tts"] <= 0:
        return await send_with_keyboard(client, chat_id, "❌ اعتبار تبدیل متن به صدای شما تمام شده است. لطفاً از منوی اصلی وارد بخش «خرید اشتراک 💎» شوید.", False)

    try:
        proc_msg = await send_with_keyboard(client, chat_id, f"⏳ در حال ساخت صدا با «{speaker_name}»...\n(لطفاً صبور باشید)", False)
        
        # اتصال مستقیم به اسپیس ساخت پادکست جهت تولید صدا
        tts_url = "https://opera8-podgen.hf.space/api/generate"
        payload = {
            "text": user_text, 
            "speaker": speaker_id, 
            "temperature": 0.9, 
            "is_custom": False
        }
        headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "application/json"}
        
        audio_bytes = None
        last_error = "پاسخی دریافت نشد"
        
        async with aiohttp.ClientSession(headers=headers, timeout=aiohttp.ClientTimeout(total=300)) as session:
            for attempt in range(6):
                try:
                    async with session.post(tts_url, json=payload) as response:
                        if response.status == 200:
                            content_type = response.headers.get('Content-Type', '')
                            if 'audio' in content_type or response.content_length > 1000:
                                audio_bytes = await response.read()
                                break
                            else: 
                                last_error = "فایل نامعتبر"
                        elif response.status == 429:
                            await asyncio.sleep(4 + attempt * 2)
                        else:
                            last_error = f"ارور ({response.status})"
                            await asyncio.sleep(2)
                except Exception as e: 
                    last_error = f"خطا: {str(e)}"
                    await asyncio.sleep(2)

        try:
            if proc_msg:
                msg_id = getattr(proc_msg, 'message_id', None)
                if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
                if msg_id: await client.delete_messages(chat_id, [msg_id])
        except Exception: pass

        if audio_bytes:
            # ذخیره با فرمت wav (چون سرور فایل wav برمی‌گرداند)
            file_name_audio = f"audio_{uuid.uuid4().hex}.wav"
            await asyncio.to_thread(sync_write_file, file_name_audio, audio_bytes)
            await asyncio.sleep(1)
            
            upload_result_file = False
            error_log_tts = ""
            for up_att in range(3):
                res = await helper_upload_file(client, chat_id, file_name_audio, "Music", "✅ صدای شما با موفقیت آماده شد:")
                if res is True:
                    upload_result_file = True
                    break
                else:
                    error_log_tts = res
                    await asyncio.sleep(4)
            
            if upload_result_file is True: 
                if not creds.get("is_premium"):
                    user_credits_db[str_chat_id]["tts"] -= 1
                    save_db(user_credits_db)
            else:
                await send_with_keyboard(client, chat_id, f"❌ فایل صدا ساخته شد اما سرور روبیکا اجازه آپلود نداد:\n`{str(error_log_tts)[:800]}`", True)
                
            if os.path.exists(file_name_audio): 
                os.remove(file_name_audio)
        else: 
            await send_with_keyboard(client, chat_id, f"❌ سرورها درگیر هستند.\nدلیل: {last_error}", True)
    except Exception: 
        traceback.print_exc()

# ==============================================================================
# 🟢 پارت 17: سیستم ساخت پادکست (ضد قطعی، بدون 429 و متصل به API هوشمند)
# ==============================================================================
async def process_podcast(client, chat_id, prompt):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    creds = get_user_credits(str_chat_id)
    if creds["podcast"] <= 0:
        return await send_with_keyboard(client, chat_id, "❌ اعتبار ساخت پادکست شما تمام شده است. لطفاً از منوی اصلی وارد بخش «خرید اشتراک 💎» شوید.", False)

    proc_msg = await send_with_keyboard(client, chat_id, "📻 در حال بررسی موضوع و شروع ساخت پادکست در سرور پردازشی...\n(با توجه به طولانی بودن این فرآیند، لطفاً چند دقیقه صبور باشید. ربات در حال انجام عملیات است)", False)
    
    available_speakers = []
    for num_key, (spk_name, spk_id) in SPEAKERS.items():
        gender = "male" if "مرد" in spk_name else "female"
        available_speakers.append({"id": spk_id, "name": spk_name.split(' (')[0], "gender": gender})

    # استفاده از API جدید که تمام کارها را صفر تا صد سمت اسپیس انجام می‌دهد
    url_create = "https://opera8-podgen.hf.space/api/auto-podcast"
    payload_create = {"prompt": prompt, "available_speakers": available_speakers}
    
    async with aiohttp.ClientSession() as session:
        task_id = None
        
        # 1. ارسال درخواست اولیه به اسپیس
        for attempt in range(5):
            try:
                async with session.post(url_create, json=payload_create, timeout=60) as resp:
                    if resp.status == 202: 
                        task_id = (await resp.json()).get("task_id")
                        break
                    elif resp.status == 429:
                        await asyncio.sleep(4 + attempt * 2)
                    else:
                        await asyncio.sleep(3)
            except Exception as e: 
                await asyncio.sleep(3)
        
        if not task_id:
            return await send_with_keyboard(client, chat_id, "❌ ارتباط با سرور پادکست در حال حاضر برقرار نشد. لطفاً چند دقیقه دیگر امتحان کنید.", True)

        # 2. بررسی وضعیت پردازش در پس‌زمینه سرور اسپیس
        url_status = f"https://opera8-podgen.hf.space/api/auto-podcast-status/{task_id}"
        final_filename = None
        last_progress_message = ""
        
        # ربات تا 1500 ثانیه (25 دقیقه) منتظر اتمام ساخت پادکست می‌ماند
        for _ in range(500):
            await asyncio.sleep(4)
            try:
                async with session.get(url_status, timeout=20) as resp:
                    if resp.status == 200:
                        status_data = await resp.json()
                        current_status = status_data.get("status")
                        progress_msg = status_data.get("progress", "")
                        
                        if current_status == "completed":
                            final_filename = status_data.get("filename")
                            break
                            
                        elif current_status == "failed":
                            error_detail = status_data.get("error", "نامشخص")
                            return await send_with_keyboard(client, chat_id, f"❌ سرور در ساخت پادکست با خطا مواجه شد.\nدلیل: {error_detail}", True)
                            
                    elif resp.status == 429:
                        await asyncio.sleep(5)
            except Exception: 
                pass
            
        if not final_filename: 
            return await send_with_keyboard(client, chat_id, "❌ زمان انتظار برای ساخت پادکست به پایان رسید و سرور پاسخ نهایی را نداد.", True)

        try:
            if proc_msg:
                msg_id = getattr(proc_msg, 'message_id', None)
                if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
                if msg_id: await client.delete_messages(chat_id, [msg_id])
        except: pass
        
        proc_msg = await send_with_keyboard(client, chat_id, "📥 پادکست ساخته شد! در حال دانلود فایل نهایی از سرور و آماده‌سازی جهت ارسال...", False)

        # 3. دانلود مستقیم فایل MP3 ترکیب شده از اسپیس
        download_url = f"https://opera8-podgen.hf.space/api/download-podcast/{final_filename}"
        audio_bytes = None
        
        for attempt in range(5):
            try:
                async with session.get(download_url, timeout=300) as resp:
                    if resp.status == 200:
                        audio_bytes = await resp.read()
                        break
                    else:
                        await asyncio.sleep(4)
            except Exception: 
                await asyncio.sleep(4)
                
        if not audio_bytes:
            return await send_with_keyboard(client, chat_id, "❌ فایل پادکست آماده شد اما ربات نتوانست آن را از سرور دانلود کند.", True)

        # 4. ذخیره محلی موقت و ارسال به روبیکا
        file_name_mp3 = f"final_podcast_{uuid.uuid4().hex}.mp3"
        await asyncio.to_thread(sync_write_file, file_name_mp3, audio_bytes)
        
        try:
            if proc_msg:
                msg_id = getattr(proc_msg, 'message_id', None)
                if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
                if msg_id: await client.delete_messages(chat_id, [msg_id])
        except: pass

        caption_file = f"🎧 فایل پادکست شما آماده است:\n\n💡 موضوع شما: {prompt}"
        
        upload_result_file = False
        error_log_pod = ""
        for up_att in range(3):
            res = await helper_upload_file(client, chat_id, file_name_mp3, "Music", caption_file)
            if res is True:
                upload_result_file = True
                break
            else:
                error_log_pod = res
                await asyncio.sleep(5)
        
        if upload_result_file is True: 
            if not creds.get("is_premium"):
                user_credits_db[str_chat_id]["podcast"] -= 1
                save_db(user_credits_db)
        else:
            await send_with_keyboard(client, chat_id, f"❌ پادکست دانلود شد اما روبیکا خطای آپلود داد.\n\n`{str(error_log_pod)[:800]}`", True)
            
        if os.path.exists(file_name_mp3): 
            os.remove(file_name_mp3)

# ==============================================================================
# 🟢 پارت 18: استخراج متن از صدا (STT) و تحلیل انواع فایل با هوش مصنوعی
# ==============================================================================
async def process_stt(client, chat_id, audio_bytes, file_name):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    creds = get_user_credits(str_chat_id)
    if creds["stt"] <= 0:
        return await send_with_keyboard(client, chat_id, "❌ اعتبار تبدیل صدا به متن شما تمام شده است. لطفاً از منوی اصلی وارد بخش «خرید اشتراک 💎» شوید.", False)

    if not GEMINI_KEYS: return await send_with_keyboard(client, chat_id, "❌ کلیدهای جیمینای تنظیم نشده‌اند.", False)
    
    proc_msg = await send_with_keyboard(client, chat_id, "📝 در حال گوش دادن و پیاده‌سازی متن...", False)
    base64_data = base64.b64encode(audio_bytes).decode('utf-8')
    mime_type, _ = mimetypes.guess_type(file_name)
    if not mime_type: mime_type = "audio/ogg" 
    
    prompt = "لطفاً این فایل صوتی/تصویری را با دقت کامل گوش بده و صحبت‌های داخل آن را کلمه به کلمه به متن تبدیل کن. هیچ توضیح اضافه‌ای نده."
    
    transcribed_text = None
    for attempt in range(5):
        keys_to_try = get_next_gemini_keys(100)
        async with aiohttp.ClientSession() as session:
            for key in keys_to_try:
                url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={key}"
                payload = {"contents":[{"parts":[{"text": prompt}, {"inlineData": {"mimeType": mime_type, "data": base64_data}}]}], "generationConfig": {"temperature": 0.2}}
                try:
                    async with session.post(url, json=payload, timeout=60) as response:
                        if response.status == 200:
                            data = await response.json()
                            transcribed_text = data["candidates"][0]["content"]["parts"][0]["text"]
                            break
                except Exception: continue
        if transcribed_text: break
        await asyncio.sleep(2)

    try:
        if proc_msg:
            msg_id = getattr(proc_msg, 'message_id', None)
            if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
            if msg_id: await client.delete_messages(chat_id,[msg_id])
    except Exception: pass

    if transcribed_text:
        sent = await send_with_keyboard(client, chat_id, f"📝 **متن استخراج شده:**\n\n{transcribed_text}", True)
        if sent and not creds.get("is_premium"):
            user_credits_db[str_chat_id]["stt"] -= 1
            save_db(user_credits_db)
    else: 
        await send_with_keyboard(client, chat_id, "❌ سرور شلوغ است فعلا بعدا امتحان کنید.", True)

async def process_file_analysis(client, chat_id, file_bytes, file_name, prompt):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    creds = get_user_credits(str_chat_id)
    if creds["file"] <= 0:
        return await send_with_keyboard(client, chat_id, "❌ اعتبار تحلیل فایل شما تمام شده است. لطفاً از منوی اصلی وارد بخش «خرید اشتراک 💎» شوید.", False)

    if not GEMINI_KEYS: return await send_with_keyboard(client, chat_id, "❌ کلید جیمینای تنظیم نیست.", False)
    
    proc_msg = await send_with_keyboard(client, chat_id, "👁️ در حال تحلیل فایل...", False)
    base64_data = base64.b64encode(file_bytes).decode('utf-8')
    mime_type, _ = mimetypes.guess_type(file_name)
    if not mime_type: 
        if file_name.endswith(('.jpg', '.jpeg')): mime_type = "image/jpeg"
        elif file_name.endswith('.png'): mime_type = "image/png"
        elif file_name.endswith('.pdf'): mime_type = "application/pdf"
        elif file_name.endswith('.mp4'): mime_type = "video/mp4"
        elif file_name.endswith('.mp3'): mime_type = "audio/mp3"
        elif file_name.endswith(('.ogg', '.oga')): mime_type = "audio/ogg"
        elif file_name.endswith('.wav'): mime_type = "audio/wav"
        else: mime_type = "image/jpeg"
        
    is_image = mime_type.startswith('image/')
    
    final_answer = None
    for attempt in range(5):
        keys_to_try = get_next_gemini_keys(100)
        async with aiohttp.ClientSession() as session:
            for key in keys_to_try:
                url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={key}"
                payload = {"contents": [{"parts":[{"text": prompt}, {"inlineData": {"mimeType": mime_type, "data": base64_data}}]}], "generationConfig": {"temperature": 0.6}}
                try:
                    async with session.post(url, json=payload, timeout=45) as response:
                        if response.status == 200:
                            data = await response.json()
                            final_answer = data["candidates"][0]["content"]["parts"][0]["text"]
                            break
                except Exception: continue
        if final_answer: break
        await asyncio.sleep(2)

    if not final_answer:
        if is_image and HF_TOKENS:
            for attempt in range(5):
                keys_to_try_hf = HF_TOKENS.copy()
                random.shuffle(keys_to_try_hf)
                
                hf_messages =[
                    {
                        "role": "user",
                        "content":[
                            {"type": "text", "text": prompt},
                            {
                                "type": "image_url",
                                "image_url": {"url": f"data:{mime_type};base64,{base64_data}"}
                            }
                        ]
                    }
                ]
                
                async with aiohttp.ClientSession() as session:
                    for hf_key in keys_to_try_hf:
                        url = "https://router.huggingface.co/v1/chat/completions"
                        headers = {"Authorization": f"Bearer {hf_key}", "Content-Type": "application/json"}
                        payload = {
                            "model": "google/gemma-4-31B-it:novita",
                            "messages": hf_messages,
                            "max_tokens": 4096
                        }
                        try:
                            async with session.post(url, headers=headers, json=payload, timeout=60) as response:
                                if response.status == 200:
                                    data = await response.json()
                                    final_answer = data["choices"][0]["message"]["content"]
                                    break
                        except Exception:
                            continue
                if final_answer: break
                await asyncio.sleep(2)

    try:
        if proc_msg:
            msg_id = getattr(proc_msg, 'message_id', None)
            if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
            if msg_id: await client.delete_messages(chat_id,[msg_id])
    except Exception: pass

    if final_answer: 
        sent = await send_with_keyboard(client, chat_id, f"💡 **نتیجه تحلیل:**\n\n{final_answer}", True)
        if sent and not creds.get("is_premium"):
            user_credits_db[str_chat_id]["file"] -= 1
            save_db(user_credits_db)
    else: 
        if not is_image:
            await send_with_keyboard(client, chat_id, "❌ متأسفانه سرور اصلی در حال حاضر شلوغ است و در این شرایط **فعلاً تنها امکان تحلیل تصاویر** توسط سرور جایگزین در دسترس است.", True)
        else:
            await send_with_keyboard(client, chat_id, "❌ تمامی سرورها شلوغ هستند. لطفاً بعداً امتحان کنید.", True)

# ==============================================================================
# 🟢 پارت 19: ساخت مقاله و خروجی فایل متنی (Word/PDF)
# ==============================================================================
async def process_create_file(client, chat_id, topic):
    str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
    creds = get_user_credits(str_chat_id)
    
    if creds["chat"] <= 0:
        return await send_with_keyboard(client, chat_id, "❌ اعتبار چت شما تمام شده است. لطفاً از منوی اصلی وارد بخش «خرید اشتراک 💎» شوید.", False)

    proc_msg = await send_with_keyboard(client, chat_id, "✍️ در حال تحقیق و نگارش مقاله جامع و حرفه‌ای...\n(این عملیات با توجه به طولانی بودن متن ممکن است کمی طول بکشد)", False)

    ai_prompt = f"یک مقاله بی‌نهایت جامع، کاملاً حرفه‌ای و بسیار بسیار طولانی درباره موضوع زیر به زبان فارسی بنویس. دقت کن که مقاله باید شامل بخش‌بندی‌های متعدد باشد و توضیحات زیر هر عنوان باید به شدت طولانی، مفصل و با جزئیات و مثال‌های فراوان (حداقل چند پاراگراف بلند برای هر بخش) نوشته شود؛ به هیچ وجه زیر عناوین توضیحات کوتاه نده. فقط متن اصلی مقاله را بده و هیچ توضیح اضافه‌ای ننویس:\n\nموضوع: {topic}"
    
    article_text = None
    session_hash = ''.join(random.choices(string.ascii_lowercase + string.digits, k=11))
    join_url = "https://coherelabs-aya-expanse.hf.space/gradio_api/queue/join"
    data_url = f"https://coherelabs-aya-expanse.hf.space/gradio_api/queue/data?session_hash={session_hash}"
    
    payload = {
        "data": [
            ai_prompt,
            [],
            None,
            None
        ],
        "event_data": None,
        "fn_index": 2,
        "session_hash": session_hash,
        "trigger_id": 37
    }

    for attempt in range(3):
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(join_url, json=payload, timeout=30) as resp:
                    if resp.status == 200:
                        async with session.get(data_url, timeout=180) as data_resp:
                            async for line_bytes in data_resp.content:
                                line = line_bytes.decode('utf-8').strip()
                                if line.startswith("data: "):
                                    try:
                                        json_data = json.loads(line[6:])
                                        if json_data.get("msg") == "process_completed":
                                            if json_data.get("success"):
                                                output_data = json_data.get("output", {}).get("data", [])
                                                if output_data and len(output_data) > 0:
                                                    result_hist = output_data[0]
                                                    if isinstance(result_hist, list) and len(result_hist) > 0:
                                                        article_text = result_hist[-1][1]
                                            break
                                    except Exception: pass
        except Exception: pass
        if article_text: break
        await asyncio.sleep(2)

    if not article_text:
        return await send_with_keyboard(client, chat_id, "❌ سرور تولید متن شلوغ است، لطفاً بعداً تلاش کنید.", True)

    try:
        if proc_msg:
            msg_id = getattr(proc_msg, 'message_id', None)
            if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
            if msg_id: await client.delete_messages(chat_id,[msg_id])
    except Exception: pass

    proc_msg = await send_with_keyboard(client, chat_id, "📄 مقاله با موفقیت نوشته شد! در حال ارتباط با هوش مصنوعی و دریافت فایل‌های PDF و Word...\n(لطفا صبور باشید)", False)

    converter_url = "https://opera8-texttopdf.hf.space/"
    uid = uuid.uuid4().hex

    pdf_success = False
    for attempt in range(30):
        try:
            pdf_bytes = None
            async with aiohttp.ClientSession() as session:
                form_data = aiohttp.FormData()
                form_data.add_field('content', article_text)
                form_data.add_field('format', 'pdf')
                async with session.post(converter_url, data=form_data, timeout=90) as resp:
                    if resp.status == 200:
                        data_bytes = await resp.read()
                        if data_bytes and len(data_bytes) > 100:
                            pdf_bytes = data_bytes
            
            if pdf_bytes:
                filename = f"Article_{uid}.pdf"
                await asyncio.to_thread(sync_write_file, filename, pdf_bytes)
                
                res_upload = False
                for _ in range(3):
                    r = await helper_upload_file(client, chat_id, filename, "File", f"📄 فایل PDF مقاله شما:\n\n💡 موضوع: {topic}")
                    if r is True:
                        res_upload = True
                        break
                    await asyncio.sleep(4)

                if os.path.exists(filename): 
                    os.remove(filename)
                
                if res_upload is True:
                    pdf_success = True
                    break 
        except Exception as e:
            print(f"PDF error (attempt {attempt+1}):", e)
        
        await asyncio.sleep(4)

    await asyncio.sleep(3.5)

    docx_success = False
    for attempt in range(30): 
        try:
            docx_bytes = None
            async with aiohttp.ClientSession() as session:
                form_data = aiohttp.FormData()
                form_data.add_field('content', article_text)
                form_data.add_field('format', 'docx')
                async with session.post(converter_url, data=form_data, timeout=90) as resp:
                    if resp.status == 200:
                        data_bytes = await resp.read()
                        if data_bytes and len(data_bytes) > 100:
                            docx_bytes = data_bytes
            
            if docx_bytes:
                filename = f"Article_{uid}.docx"
                await asyncio.to_thread(sync_write_file, filename, docx_bytes)
                
                res_upload = False
                for _ in range(3):
                    r = await helper_upload_file(client, chat_id, filename, "File", f"📝 فایل Word (DOCX) مقاله شما:\n\n💡 موضوع: {topic}")
                    if r is True:
                        res_upload = True
                        break
                    await asyncio.sleep(4)

                if os.path.exists(filename): 
                    os.remove(filename)
                
                if res_upload is True:
                    docx_success = True
                    break 
        except Exception as e:
            print(f"DOCX error (attempt {attempt+1}):", e)
        
        await asyncio.sleep(4)

    try:
        if proc_msg:
            msg_id = getattr(proc_msg, 'message_id', None)
            if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
            if msg_id: await client.delete_messages(chat_id,[msg_id])
    except Exception: pass

    if pdf_success and docx_success:
        if not creds.get("is_premium"):
            user_credits_db[str_chat_id]["chat"] -= 1
            save_db(user_credits_db)
        await send_with_keyboard(client, chat_id, "✅ مقاله شما با موفقیت به صورت هر دو فایل (PDF و Word) تحویل داده شد!", True)
    elif pdf_success or docx_success:
        if not creds.get("is_premium"):
            user_credits_db[str_chat_id]["chat"] -= 1
            save_db(user_credits_db)
        await send_with_keyboard(client, chat_id, "⚠️ یکی از فایل‌ها با موفقیت ارسال شد اما دیگری پس از تلاش‌های مکرر سرور با خطا مواجه شد.", True)
    else:
        await send_with_keyboard(client, chat_id, "❌ متأسفانه پس از تلاش‌های مکرر، سرور قادر به ساخت و ارسال هیچ‌یک از فایل‌ها نبود و اعتباری از شما کسر نشد.", True)

# ==============================================================================
# 🟢 پارت 20: بدنه اصلی ربات (Handler)، دستورات مدیریتی، حلقه اصلی و استارت
# ==============================================================================
# ==================================================================
# حلقه و مدیریت اصلی ربات
# ==================================================================

BOT_START_TIME = time.time()  # ⏳ زمان دقیق روشن شدن ربات ثبت می‌شود

# 🧹 سیستم پاکسازی هوشمند رم (Garbage Collector) مخصوص هزاران کاربر
async def ram_garbage_collector():
    """این تابع در پس‌زمینه می‌چرخد و فایل‌های رها شده در حافظه را پاک می‌کند تا رم سرور پر نشود"""
    while True:
        await asyncio.sleep(1800)  # هر ۳۰ دقیقه یکبار بررسی می‌کند
        now = time.time()
        try:
            # پاکسازی یوزراستیت‌ها
            for uid in list(user_states.keys()):
                if now - user_states[uid].get("last_time", 0) > 3600:
                    if user_states[uid].get("file_bytes") is not None:
                        user_states[uid]["file_bytes"] = None
                    if user_states[uid].get("ref_bytes") is not None:
                        user_states[uid]["ref_bytes"] = None
                    if len(user_states[uid].get("history",[])) > 5:
                        user_states[uid]["history"] = user_states[uid]["history"][-5:]
            
            # پاکسازی کش زمان پیام‌ها (ضد اسپم) که استفاده نمی‌شوند
            for uid in list(user_message_times.keys()):
                times = user_message_times[uid]
                valid_times =[t for t in times if now - t < 3.0]
                if not valid_times:
                    del user_message_times[uid]
                else:
                    user_message_times[uid] = valid_times
                    
        except Exception as e:
            pass

if not bot_token:
    print("خطا: توکن ربات روبیکا وارد نشده است!")
else:
    bot = BotClient(bot_token)

    @bot.on_update(filters.private)
    async def main_handler(client, update):
        global BOT_GUID
        
        try:
            if not BOT_GUID:
                try:
                    me_info = await client.get_me()
                    if me_info and hasattr(me_info, 'user'):
                        BOT_GUID = getattr(me_info.user, 'user_guid', None)
                except Exception:
                    pass

            msg_obj = getattr(update, "message", None) or getattr(update, "new_message", None)
            
            author_id = getattr(update, 'author_guid', None)
            if not author_id and msg_obj:
                author_id = msg_obj.get('author_object_guid') if isinstance(msg_obj, dict) else getattr(msg_obj, 'author_object_guid', None)
            
            if BOT_GUID and author_id == BOT_GUID:
                return
            
            chat_id = getattr(update, 'object_guid', None) or getattr(update, 'author_guid', None) or getattr(update, "chat_id", None)
            if not chat_id: return
            
            msg_id = getattr(update, "message_id", None)
            if not msg_id and msg_obj:
                msg_id = msg_obj.get("message_id") if isinstance(msg_obj, dict) else getattr(msg_obj, "message_id", None)
            
            str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
            creds = get_user_credits(str_chat_id)

            # ===================================================================
            # 🛑 سیستم صد در صد قطعی ضد تکرار پیام و فیلتر پیام‌های قدیمی (Timestamp)
            # ===================================================================
            if msg_id:
                str_msg_id = str(msg_id).strip()
                if is_message_processed(str_msg_id):
                    return
                
                # ⏳ تشخیص پیام‌های قدیمی (مربوط به قبل از ری‌استارت ربات)
                is_old = False
                try:
                    for attr in['timestamp', 'time', 'date', 'message_date']:
                        val = getattr(msg_obj, attr, None)
                        if not val and isinstance(msg_obj, dict):
                            val = msg_obj.get(attr)
                        if val:
                            val_int = int(val)
                            # روبیکا معمولا زمان را ۱۳ رقمی (میلی‌ثانیه) می‌دهد، تبدیل به ثانیه:
                            if val_int > 10000000000:
                                val_int = val_int / 1000
                            
                            # اگر پیام بیشتر از 60 ثانیه قبل از روشن شدن ربات فرستاده شده باشد، قدیمی است
                            if val_int < BOT_START_TIME - 60:
                                is_old = True
                            break
                except Exception:
                    pass

                # پیام چه قدیمی باشد چه جدید، در دیتابیس ثبت می‌شود که دیگر خوانده نشود
                mark_message_processed(str_msg_id)

                if is_old:
                    # پیام تلنبار شده و قدیمی است، کاملا بی‌سروصدا دور ریخته می‌شود (بدون جواب دادن)
                    return
            # ===================================================================

            user_text = getattr(update, "text", "") or getattr(msg_obj, "text", "")
            user_text_str = str(user_text).strip() if user_text else ""
            user_text_lower = user_text_str.lower()

            if is_user_spamming(str_chat_id):
                return

            if str_chat_id not in user_states:
                user_states[str_chat_id] = {"mode": None, "text": "", "history":[], "file_bytes": None, "file_name": None, "last_time": time.time()}
            else:
                user_states[str_chat_id]["last_time"] = time.time()  

            if user_text_lower.startswith(f"{ADMIN_CODE} pro=") or user_text_lower.startswith(f"{ADMIN_CODE}pro="):
                parts = user_text_str.split("=", 1)
                if len(parts) >= 2:
                    target_id = parts[1].replace("`", "").replace("'", "").replace('"', "").strip()
                    if target_id:
                        if target_id not in user_credits_db or not isinstance(user_credits_db[target_id], dict):
                            user_credits_db[target_id] = {
                                "is_premium": False,
                                "expire_date": None,
                                "last_reset": "",
                                "chat": 10,
                                "image": 0,
                                "edit_image": 0,
                                "podcast": 2,
                                "tts": 5,
                                "file": 1,
                                "stt": 5,
                                "voice_conv": 3,
                                "voice_clone": 1,
                                "last_msg_id": 0,
                                "has_joined": True,
                                "invited_count": 0,
                                "used_referral": False,
                                "referral_code": ""
                            }
                        
                        user_credits_db[target_id]["is_premium"] = True
                        expire_time = datetime.datetime.now() + datetime.timedelta(days=30)
                        user_credits_db[target_id]["expire_date"] = expire_time.isoformat()
                        
                        user_credits_db[target_id]["chat"] = 999999
                        user_credits_db[target_id]["image"] = 10
                        user_credits_db[target_id]["edit_image"] = 5
                        user_credits_db[target_id]["podcast"] = 999999
                        user_credits_db[target_id]["tts"] = 999999
                        user_credits_db[target_id]["file"] = 999999
                        user_credits_db[target_id]["stt"] = 999999
                        user_credits_db[target_id]["voice_conv"] = 999999
                        user_credits_db[target_id]["voice_clone"] = 999999
                        
                        save_db(user_credits_db)
                        await send_with_keyboard(client, chat_id, f"✅ حساب کاربر `{target_id}` به مدت ۳۰ روز شارژ شد و به پرو ارتقا یافت.", False)
                        try:
                            await send_with_keyboard(client, target_id, "🎉 **کاربر گرامی، تبریک!**\n\nحساب شما با موفقیت توسط پشتیبانی به **🌟 نسخه پرو (ویژه)** ارتقا یافت.\nهم‌اکنون بسته‌های نامحدود و طلایی یک‌ماهه شما فعال گردید.\n\nجهت مشاهده جزئیات روی دکمه «حساب کاربری 👤» کلیک کنید.", True)
                        except Exception: pass
                return
                
            if user_text_lower.startswith(f"{ADMIN_CODE} free=") or user_text_lower.startswith(f"{ADMIN_CODE}free="):
                parts = user_text_str.split("=", 1)
                if len(parts) >= 2:
                    target_id = parts[1].replace("`", "").replace("'", "").replace('"', "").strip()
                    if target_id:
                        if target_id in user_credits_db and isinstance(user_credits_db[target_id], dict):
                            user_credits_db[target_id]["is_premium"] = False
                            user_credits_db[target_id]["expire_date"] = None
                            user_credits_db[target_id]["last_reset"] = "" 
                            user_credits_db[target_id]["image"] = 0
                            user_credits_db[target_id]["edit_image"] = 0
                            save_db(user_credits_db)
                        await send_with_keyboard(client, chat_id, f"✅ اشتراک کاربر `{target_id}` لغو شد و به رایگان تبدیل گشت.", False)
                        try:
                            await send_with_keyboard(client, target_id, "⚠️ کاربر گرامی، اشتراک ویژه شما به پایان رسید و حساب شما به نسخه رایگان (آزمایشی) تغییر یافت.", True)
                        except Exception: pass
                return

            if user_text_lower.startswith(f"{ADMIN_CODE} =") or user_text_lower.startswith(f"{ADMIN_CODE}="):
                parts = user_text_str.split("=", 1)
                if len(parts) >= 2:
                    target_id = parts[1].replace("`", "").replace("'", "").replace('"', "").strip()
                    if target_id:
                        if target_id in user_credits_db and isinstance(user_credits_db[target_id], dict):
                            t_creds = user_credits_db[target_id]
                            is_prem = t_creds.get("is_premium", False)
                            
                            if is_prem:
                                expire_txt = "نامشخص"
                                days_left = 0
                                if t_creds.get("expire_date"):
                                    exp_d = datetime.datetime.fromisoformat(t_creds["expire_date"])
                                    now = datetime.datetime.now()
                                    diff = exp_d - now
                                    days_left = diff.days if diff.days >= 0 else 0
                                    
                                    jy, jm, jd = gregorian_to_jalali(exp_d.year, exp_d.month, exp_d.day)
                                    expire_txt = f"{jy:04d}/{jm:02d}/{jd:02d}"
                                status_text = f"🌟 نسخه پرو (ویژه)\n📅 انقضا: {expire_txt}\n⏳ باقیمانده: {days_left} روز"
                            else:
                                status_text = "🥉 نسخه رایگان (آزمایشی)\n⏳ وضعیت: سهمیه روزانه محدود"

                            chat_rem = "نامحدود ∞" if is_prem else t_creds.get('chat', 0)
                            vc_rem = "نامحدود ∞" if is_prem else t_creds.get('voice_conv', 0)
                            clone_rem = "نامحدود ∞" if is_prem else t_creds.get('voice_clone', 0)
                            podcast_rem = "نامحدود ∞" if is_prem else t_creds.get('podcast', 0)
                            tts_rem = "نامحدود ∞" if is_prem else t_creds.get('tts', 0)
                            file_rem = "نامحدود ∞" if is_prem else t_creds.get('file', 0)
                            stt_rem = "نامحدود ∞" if is_prem else t_creds.get('stt', 0)
                            image_rem = t_creds.get('image', 0)
                            edit_image_rem = t_creds.get('edit_image', 0)
                            invs = t_creds.get('invited_count', 0)
                            joined_status = "بله ✅" if t_creds.get('has_joined') else "خیر ❌"

                            info_msg = f"""🔍 **اطلاعات اختصاصی کاربر:**
👤 شناسه: `{target_id}`
عضو کانال: {joined_status}

🔹 **وضعیت اشتراک:**
{status_text}
🎁 **تعداد افراد دعوت شده:** {invs} نفر

📊 **سهمیه باقی‌مانده فعلی:**
💬 چت: {chat_rem}
🎨 تولید عکس: {image_rem}
🪄 ویرایش عکس: {edit_image_rem}
🎙️ تغییر صدا: {vc_rem}
👤 کلون کردن صدا: {clone_rem}
🎙 پادکست: {podcast_rem}
🗣 متن به صدا: {tts_rem}
📁 تحلیل فایل: {file_rem}
📝 صدا به متن: {stt_rem}"""
                            await send_with_keyboard(client, chat_id, info_msg, False)
                        else:
                            await send_with_keyboard(client, chat_id, f"❌ کاربری با شناسه `{target_id}` در دیتابیس ربات یافت نشد.", False)
                return

            is_file = False
            file_name = f"unknown_file_{uuid.uuid4().hex[:6]}.jpg"
            
            if msg_obj:
                for attr in['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
                    file_attr = getattr(msg_obj, attr, None)
                    if file_attr:
                        is_file = True
                        file_name = getattr(file_attr, 'file_name', file_name)
                        break
                
                if not is_file and hasattr(msg_obj, 'to_dict'):
                    msg_dict = msg_obj.to_dict()
                    for attr in['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
                        if attr in msg_dict:
                            is_file = True
                            file_attr = msg_dict.get(attr, {})
                            file_name = file_attr.get('file_name', file_name) if isinstance(file_attr, dict) else file_name
                            break

            if user_text_str == "✅ عضو شدم":
                if not creds.get("has_joined", False):
                    user_credits_db[str_chat_id]["has_joined"] = True
                    save_db(user_credits_db)
                    await send_with_keyboard(client, chat_id, "🎉 **عضویت شما با موفقیت تایید شد! خیلی خوش آمدید.**\n\nحالا می‌توانید از تمامی امکانات ربات استفاده کنید.\nلطفاً یکی از گزینه‌های منو را انتخاب کنید:", True)
                    return
                else:
                    await send_with_keyboard(client, chat_id, "✅ شما قبلاً عضو شده‌اید! لطفا از منوی اصلی استفاده کنید.", True)
                    return

            if not creds.get("has_joined", False):
                join_msg = "👋 **سلام کاربر گرامی!**\n\nجهت استفاده از خدمات ربات هوش مصنوعی آلفا و مطلع شدن از آخرین آپدیت‌ها، لطفا ابتدا در کانال رسمی ما عضو شوید:\n\n📢 **آیدی کانال:** @aialpha\n\n👇 پس از عضویت در کانال، بر روی دکمه **«✅ عضو شدم»** کلیک کنید تا ربات برای شما فعال شود."
                try:
                    payload = {"chat_id": chat_id, "text": join_msg, "chat_keypad_type": "New", "chat_keypad": JOIN_KEYPAD_DICT}
                    await client._make_request("sendMessage", payload)
                except Exception:
                    await client.send_message(chat_id, join_msg)
                return

            if user_text_lower.startswith("/start"):
                user_states[str_chat_id]["mode"] = None
                user_states[str_chat_id]["file_bytes"] = None
                await send_with_keyboard(client, chat_id, "سلام! به ربات هوش مصنوعی آلفا خوش آمدید 🤖\n\nلطفاً برای شروع، از کیبورد پایین یکی از بخش‌ها را انتخاب کنید:", True)
                return

            if user_text_str in["سلام", "لغو", "/cancel", "❌ لغو", "برگشت♻️"]:
                user_states[str_chat_id]["mode"] = None
                user_states[str_chat_id]["file_bytes"] = None
                await send_with_keyboard(client, chat_id, "سلام! به ربات هوش مصنوعی آلفا خوش آمدید 🤖\n\nلطفاً برای شروع، از کیبورد پایین یکی از بخش‌ها را انتخاب کنید:", True)
                return

            if user_text_str in["/account", "حساب کاربری 👤"]:
                is_prem = creds.get("is_premium", False)
                
                if is_prem:
                    expire_txt = "نامشخص"
                    days_left = 0
                    if creds.get("expire_date"):
                        exp_d = datetime.datetime.fromisoformat(creds["expire_date"])
                        now = datetime.datetime.now()
                        diff = exp_d - now
                        days_left = diff.days if diff.days >= 0 else 0
                        
                        jy, jm, jd = gregorian_to_jalali(exp_d.year, exp_d.month, exp_d.day)
                        expire_txt = f"{jy:04d}/{jm:02d}/{jd:02d} (ساعت {exp_d.hour:02d}:{exp_d.minute:02d})"
                        
                    status_text = "🌟 نسخه پرو (ویژه)"
                    expire_info = f"\n📅 **تاریخ انقضا:** {expire_txt}\n⏳ **زمان باقیمانده:** {days_left} روز"
                    daily_note = "*نکته: سهمیه پردازشی شما مختص همین دوره یک‌ماهه می‌باشد.*"
                else:
                    status_text = "🥉 نسخه رایگان (آزمایشی)"
                    expire_info = ""
                    daily_note = "*نکته: سهمیه شما هر روز ساعت ۰۰:۰۰ بامداد به صورت خودکار مجدداً شارژ می‌گردد.*"

                chat_rem = "نامحدود ∞" if is_prem else creds['chat']
                vc_rem = "نامحدود ∞" if is_prem else creds.get('voice_conv', 0)
                clone_rem = "نامحدود ∞" if is_prem else creds.get('voice_clone', 0)
                podcast_rem = "نامحدود ∞" if is_prem else creds['podcast']
                tts_rem = "نامحدود ∞" if is_prem else creds['tts']
                file_rem = "نامحدود ∞" if is_prem else creds['file']
                stt_rem = "نامحدود ∞" if is_prem else creds['stt']
                image_rem = creds['image']
                edit_image_rem = creds['edit_image']
                invited_count = creds.get('invited_count', 0)
                my_code = get_or_create_referral_code(str_chat_id)

                account_profile = f"""👤 **اطلاعات حساب کاربری شما**

🔹 **شناسه یکتا:** `{chat_id}`
🎫 **کد هدیه شما:** `{my_code}`
🔹 **وضعیت اشتراک:** {status_text}{expire_info}
🎁 **تعداد افراد دعوت شده:** {invited_count} نفر

📊 **سهمیه باقی‌مانده شما:**
- 💬 چت هوشمند: {chat_rem}
- 🎨 تولید تصویر: {image_rem} عدد
- 🪄 ویرایش تصویر: {edit_image_rem} عدد
- 🎙️ تغییر صدا: {vc_rem}
- 👤 کلون کردن صدا: {clone_rem}
- 🎙 ساخت پادکست: {podcast_rem}
- 🗣 تبدیل متن به صدا: {tts_rem}
- 📁 تحلیل فایل و سند: {file_rem}
- 📝 تبدیل صدا به متن: {stt_rem}

{daily_note}"""
                await send_with_keyboard(client, chat_id, account_profile, True)
                return

            if user_text_str in["/invite", "دعوت دوستان 🎁"]:
                invites = creds.get("invited_count", 0)
                remains = 10 - (invites % 10)
                my_code = get_or_create_referral_code(str_chat_id)
                
                invite_text = f"""🎁 **سیستم دعوت دوستان (دو سر سود)**

با دعوت دوستان خود به ربات آلفا، هم شما و هم دوستتان هدیه می‌گیرید!
به دوست خود بگویید پس از ورود به ربات، دکمه **«ثبت کد هدیه 🎫»** را بزند و کد زیر را وارد کند.
✨ **سود دوست شما:** در همان لحظه 10 تبدیل رایگان متن به صدا دریافت می‌کند.
✨ **سود شما:** به آمار دعوت‌هایتان اضافه می‌شود و به ازای هر **10 نفر**، **3 روز اشتراک پرو نامحدود** می‌گیرید.

📊 **آمار شما:**
- تعداد دعوت‌های موفق: {invites} نفر
- دعوت‌های باقی‌مانده تا جایزه بعدی: {remains} نفر

کد هدیه اختصاصی شما:
`{my_code}`

(متن زیر را کپی کرده و برای دوستانتان بفرستید 👇)"""
                await send_with_keyboard(client, chat_id, invite_text, True)
                
                forward_text = f"""🤖 **ربات هوش مصنوعی آلفا پرو**

✨ با این ربات می‌تونی کارهای زیر رو به راحتی انجام بدی:
💬 چت با پیشرفته‌ترین هوش مصنوعی
🎨 ساخت و ویرایش حرفه‌ای عکس
🎙️ تغییر صدا و کلون کردن صدا 
🎙 ساخت پادکست اختصاصی
🗣 تبدیل متن به صدا (30 گوینده مختلف)
📝 تبدیل صدا و ویدیو به متن
📁 تحلیل فایل‌ها و ساخت مقاله

👇 اول وارد ربات زیر شو:
@aialphabot

سپس دکمه **«ثبت کد هدیه 🎫»** را بزن و کد 8 رقمی زیر رو وارد کن تا همون اول **10 تا تبدیل صدا هدیه بگیری**:
`{my_code}`"""
                await send_with_keyboard(client, chat_id, forward_text, False)
                return

            if user_text_str in["/referral", "ثبت کد هدیه 🎫"]:
                if creds.get("used_referral", False):
                    await send_with_keyboard(client, chat_id, "❌ شما قبلاً کد هدیه یک نفر را ثبت کرده‌اید و فقط یک‌بار مجاز به استفاده از این امکان هستید.", True)
                    return
                user_states[str_chat_id]["mode"] = "waiting_for_referral_code"
                msg = "🎫 **ثبت کد هدیه**\n\nکد هدیه 8 رقمی (اعداد) که از دوست خود دریافت کرده‌اید را اینجا وارد کنید تا در همان لحظه **10 سهمیه تبدیل رایگان متن به صدا** هدیه بگیرید!\n\n(برای انصراف دکمه «برگشت♻️» را بزنید)"
                await send_with_keyboard(client, chat_id, msg, True)
                return

            if user_text_str in["/buy", "خرید اشتراک 💎"]:
                buy_text = f"""💎 **خرید اشتراک ویژه آلفا پرو (یک ماهه)**

با تهیه اشتراک ویژه، محدودیت‌ها را کنار بزنید و از نهایت قدرت هوش مصنوعی لذت ببرید! 🚀

━━━━━━━━━━━━━━━━━━━
🎁 **بسته طلایی یک‌ماهه شامل:**
🤖 چت با هوش مصنوعی: نامحدود ∞
🎙️ تغییر صدا و کلون کردن صدا: نامحدود ∞
🗣 تبدیل متن به صدا (۳۰ گوینده): نامحدود ∞
🎙 ساخت پادکست: نامحدود ∞
📁 تحلیل فایل و سند: نامحدود ∞
📝 تبدیل فایل صوتی به متن: نامحدود ∞
🪄 ویرایش تصویر: 5 عدد
🎨 تولید تصویر: 10 عدد
━━━━━━━━━━━━━━━━━━━

💳 **هزینه اشتراک یک ماهه:** 250 هزار تومان

💳 **شماره کارت جهت واریز:**
➖➖➖➖➖➖➖➖
`6219861411958035`
➖➖➖➖➖➖➖➖
👤 **به نام:** کوهی

✅ **نحوه فعال‌سازی:**
پس از واریز مبلغ، لطفاً رسید پرداختی را به همراه **شناسه یکتای خود** (که در پایین آمده) به آیدی پشتیبانی زیر ارسال کنید تا اشتراک شما فعال گردد:

🔑 **شناسه یکتای شما:**
`{chat_id}`

👨‍💻 **ارتباط با پشتیبانی:**
🆔 @aialpha_admin"""
                await send_with_keyboard(client, chat_id, buy_text, True)
                return

            if user_text_str in["/transfer", "انتقال اکانت از برنامه به ربات"]:
                transfer_text = f"""🔄 **انتقال اکانت از برنامه به ربات**

کاربر گرامی، در صورتی که داخل برنامه «هوش مصنوعی آلفا» پیش‌تر اشتراک تهیه کرده‌اید، نیازی به خرید مجدد اشتراک داخل ربات نیست! 🎉

کافیست **شناسه یکتای** ربات روبیکای خود را کپی کرده و برای پشتیبانی ما در برنامه هوش مصنوعی آلفا ارسال کنید تا اکانت اشتراکی شما به سرعت از برنامه به ربات روبیکا انتقال داده شود.

🔑 **شناسه یکتای ربات شما:**
`{chat_id}`

👨‍💻 **دقت کنید شناسه ربات رو به پشتیبانی داخل خود برنامه هوش مصنوعی آلفا ارسال کنید.**"""
                await send_with_keyboard(client, chat_id, transfer_text, True)
                return

            if user_text_str in["/chat", "💬 چت", "چت با هوش مصنوعی 🤖"]:
                user_states[str_chat_id]["mode"] = "chat"
                user_states[str_chat_id]["history"] =[]
                await send_with_keyboard(client, chat_id, "💬 شما وارد بخش **چت با هوش مصنوعی** شدید.\n\nهر سوالی دارید بفرستید تا جواب بدم:\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
                return

            if user_text_str in["/image", "🎨 عکس", "ساخت تصاویر🎨"]:
                user_states[str_chat_id]["mode"] = "image_waiting_for_text"
                await send_with_keyboard(client, chat_id, "🎨 شما وارد بخش **ساخت عکس پیشرفته** شدید.\n\nمتن (ایده) خود را به صورت کامل ارسال کنید:\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
                return

            if user_text_str in["/edit_image", "ویرایش تصاویر 🪄"]:
                if not creds.get("is_premium", False):
                    msg = """کاربر گرامی،

ضمن تشکر از توجه شما، به اطلاع می‌رساند که قابلیت ویرایش تصاویر در حال حاضر به صورت رایگان در دسترس نمی‌باشد. این سرویس به دلیل نیاز به منابع پردازشی بالا، جزو خدمات ویژه و نیازمند تهیه اشتراک است.

با این حال، شما می‌توانید از تست رایگان و امکانات سایر بخش‌های پلتفرم ما بهره‌مند شوید.

ما همواره در تلاش برای افزایش منابع و اضافه کردن خدمات رایگان بیشتر به کاربران عزیز هستیم.

در حال حاضر، می‌توانید از سایر بخش‌های رایگان موجود استفاده کنید و یا برای دسترسی کامل و نامحدود به تمامی قابلیت‌ها (از جمله ویرایش تصاویر)، اشتراک تهیه نمایید.

از صبوری و همراهی شما سپاسگزاریم."""
                    await send_with_keyboard(client, chat_id, msg, False)
                    return
                
                user_states[str_chat_id]["mode"] = "image_edit_waiting_for_image"
                user_states[str_chat_id]["file_bytes"] = None
                await send_with_keyboard(client, chat_id, "🪄 به بخش **ویرایش عکس (Flux.2)** خوش آمدید.\n\nلطفاً ابتدا عکسی که می‌خواهید ویرایش کنید را بفرستید:\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
                return

            if user_text_str in ["/tts", "🎙️ صدا", "تبدیل متن به صدا🗣️"]:
                user_states[str_chat_id]["mode"] = "tts_waiting_for_text"
                tts_msg = """🎙️ شما وارد بخش **تبدیل متن به صدا** شدید.


📝 لطفاً متنی که می‌خواهید به صدا تبدیل شود را ارسال کنید.

🌍 **پشتیبانی از تمامی زبان‌های دنیا!**
🎭 **درک لحن و احساسات:**
هوش مصنوعی ما احساسات رو درک می‌کنه! کافیه لحن دلخواهت رو داخل پرانتز بنویسی.
💡 *مثال:* هی، گوش کن! یه راز دارم که فقط به تو می‌گم. (با لحنی مرموز، شیطنت‌آمیز و نجواگونه)

(برای خروج دکمه «برگشت♻️» را بزنید)"""
                await send_with_keyboard(client, chat_id, tts_msg, True)
                return
            
            if user_text_str in ["/podcast", "📻 پادکست", "ساخت پادکست 🎙️"]:
                user_states[str_chat_id]["mode"] = "podcast_waiting_for_topic"
                podcast_msg = """📻 شما وارد بخش **ساخت پادکست** شدید.

لطفاً موضوع پادکست خود را بفرستید. این بخش متصل به هوش مصنوعی زبانی است و درخواست شما را قبل از ساخت کاملاً درک می‌کند! 🧠

➖➖➖➖➖➖➖➖➖➖
💡 **راهنمای استفاده:**
🔹 می‌توانید فقط یک موضوع بدهید (مثال: درباره تاریخچه پیدایش قهوه با سه گوینده یک پادکست جذاب بساز).
🔹 می‌توانید متن کامل یک مقاله از یک سایت را بفرستید تا هوش مصنوعی خودش محتوای اصلی را استخراج کرده و پادکست بسازد.
🔹 امکان مشخص کردن تعداد گویندگان و اسم آن‌ها به انتخاب شما وجود دارد!

➖➖➖➖➖➖➖➖➖➖
🎙️ **لیست ۳۰ گوینده اختصاصی ما:**
شهاب | آوا | نوید | آرمان | مهسا | دانا | سامان | آرش | شبنم | سحر | مریم | بهرام | نیکان | فرناز | سارا | مانی | آرتین | دلنواز | روژان | امید | بردیا | ترانه | نیکو | هستی | کامیار | کیانوش | پویا | مهتاب | سام | لیدا

➖➖➖➖➖➖➖➖➖➖
📌 **مثال برای درخواست:**
یک پادکست برام بساز در باره مدیریت زمان با دو گوینده امید و مهسا
اگر گوینده و تعداد آن از سمت شما مشخص نشه هوش مصنوعی خودش انتخاب میکنه

(برای خروج دکمه «برگشت♻️» را بزنید)"""
                await send_with_keyboard(client, chat_id, podcast_msg, True)
                return

            if user_text_str in["/vc", "تغییر صدا 🎙️"]:
                user_states[str_chat_id]["mode"] = "vc_waiting_for_voice"
                user_states[str_chat_id]["file_bytes"] = None
                await send_with_keyboard(client, chat_id, "🎙️ شما وارد بخش **تغییر صدا** شدید.\n\nلطفاً صدای خود (ویس) را بفرستید تا آن را به صدای شخصیت‌های معروف تبدیل کنم:\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
                return

            if user_text_str in["/clone", "کلون کردن صدا 👤"]:
                user_states[str_chat_id]["mode"] = "clone_waiting_for_src"
                user_states[str_chat_id]["file_bytes"] = None
                user_states[str_chat_id]["ref_bytes"] = None
                clone_text = """👤 **شما وارد بخش کلون کردن صدای اختصاصی شدید. با یک فایل صوتی کوتاه از هر شخصی صدای خودتونو به همون صدا تغییر بدید.**

✨ **این بخش چه کاری انجام می‌دهد؟**
با این ویژگی بی‌نظیر، شما می‌توانید صدای خود (یا هر فرد دیگری) را دقیقاً شبیه‌سازی کنید! کافیست یک نمونه از صدای خودتان صحبت کنید و یک نمونه از صدای شخص مورد نظر (الگو) را به هوش مصنوعی بدهید. ربات لحن و کلمات شما را گرفته و دقیقاً با جنس صدای شخص الگو بازسازی می‌کند.

📌 **راهنمای استفاده:**
شما در این مرحله به **2 فایل صوتی** نیاز دارید:
1️⃣ **صدای ورودی (شما):** صدایی که می‌خواهید متن و لحن آن خوانده شود.
2️⃣ **صدای الگو (هدف):** صدایی که می‌خواهید خروجی نهایی شبیه به آن شود (بدون نویز و موزیک پس‌زمینه، بین ۳ تا ۱۰ ثانیه بهترین نتیجه را می‌دهد).

👇 **مرحله اول:**
لطفاً ابتدا **صدای خودتان (ورودی)** را به صورت ویس یا فایل صوتی ارسال کنید:

*(برای خروج دکمه «برگشت♻️» را بزنید)*"""
                await send_with_keyboard(client, chat_id, clone_text, True)
                return

            if user_text_str in["/file", "تحلیل فایل 📁"]:
                user_states[str_chat_id]["mode"] = "file_waiting_for_file"
                user_states[str_chat_id]["file_bytes"] = None
                await send_with_keyboard(client, chat_id, "📁 شما وارد بخش **تحلیل فایل اختصاصی** شدید.\n\nلطفاً فایل خود را ارسال کنید:\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
                return

            if user_text_str in["/stt", "فایل صوتی به متن 📝"]:
                user_states[str_chat_id]["mode"] = "stt_waiting_for_audio"
                await send_with_keyboard(client, chat_id, "📝 شما وارد بخش **تبدیل صدا به متن** شدید.\n\nلطفاً فایل خود (ویس، آهنگ، ویدیو و...) را ارسال کنید:\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
                return

            if user_text_str in["/create_file", "ساخت فایل 📄"]:
                user_states[str_chat_id]["mode"] = "create_file_waiting_for_topic"
                await send_with_keyboard(client, chat_id, "📄 شما وارد بخش **ساخت فایل** شدید.\n\nلطفاً موضوع مقاله‌ای که می‌خواهید را کامل بفرستید.\nمثال: نحوه مدیریت زمان\n\nهوش مصنوعی یک مقاله کامل و طولانی نوشته و در نهایت فایل PDF و Word آن را به شما تحویل می‌دهد.\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
                return

            current_mode = user_states[str_chat_id].get("mode")

            if current_mode is None:
                if is_file: pass 
                elif user_text_str: await send_with_keyboard(client, chat_id, "⚠️ لطفاً ابتدا از کیبورد پایین، بخش مورد نظرتان را انتخاب کنید:", True)
                return

            elif current_mode == "waiting_for_referral_code":
                if user_text_str:
                    normalized_code = to_english_digits(user_text_str).strip()
                    
                    if not normalized_code.isdigit() or len(normalized_code) != 8:
                        await send_with_keyboard(client, chat_id, "❌ کد وارد شده نامعتبر است. لطفاً یک کد 8 رقمی صحیح بفرستید.", False)
                        return
                    
                    inviter_id = find_user_by_referral_code(normalized_code)
                    
                    if not inviter_id:
                        await send_with_keyboard(client, chat_id, "❌ کد هدیه یافت نشد. لطفاً کد را با دقت بررسی کنید.", False)
                        return
                        
                    if str(inviter_id) == str(str_chat_id):
                        await send_with_keyboard(client, chat_id, "❌ شما نمی‌توانید کد خودتان را ثبت کنید!", False)
                        return
                    
                    user_states[str_chat_id]["mode"] = None
                    
                    user_credits_db[str_chat_id]["used_referral"] = True
                    user_credits_db[str_chat_id]["tts"] = user_credits_db[str_chat_id].get("tts", 0) + 10
                    
                    user_credits_db[inviter_id]["invited_count"] = user_credits_db[inviter_id].get("invited_count", 0) + 1
                    current_invites = user_credits_db[inviter_id]["invited_count"]
                    
                    if current_invites > 0 and current_invites % 10 == 0:
                        inviter_data = user_credits_db[inviter_id]
                        inviter_data["is_premium"] = True
                        now = datetime.datetime.now()
                        if inviter_data.get("expire_date"):
                            try:
                                current_exp = datetime.datetime.fromisoformat(inviter_data["expire_date"])
                                if current_exp > now:
                                    new_exp = current_exp + datetime.timedelta(days=3)
                                else:
                                    new_exp = now + datetime.timedelta(days=3)
                            except:
                                new_exp = now + datetime.timedelta(days=3)
                        else:
                            new_exp = now + datetime.timedelta(days=3)
                            
                        inviter_data["expire_date"] = new_exp.isoformat()
                        inviter_data["chat"] = 999999
                        inviter_data["image"] = 10
                        inviter_data["edit_image"] = 5
                        inviter_data["podcast"] = 999999
                        inviter_data["tts"] = 999999
                        inviter_data["file"] = 999999
                        inviter_data["stt"] = 999999
                        
                        save_db(user_credits_db)
                        try:
                            msg_text = f"🎉 **تبریک ویژه!**\nیک دوست کد هدیه شما را ثبت کرد.\nتعداد کل دعوت‌های شما: {current_invites} نفر\n\n🎁 **هدیه شما:** ۳ روز اشتراک پرو نامحدود به حساب شما افزوده شد!"
                            asyncio.create_task(send_with_keyboard(client, inviter_id, msg_text, True))
                        except: pass
                    else:
                        save_db(user_credits_db)
                        remains = 10 - (current_invites % 10)
                        try:
                            msg_text = f"🎉 **تبریک!**\nیک دوست کد هدیه شما را ثبت کرد.\nتعداد کل دعوت‌های شما: {current_invites} نفر\n\n⏳ با دعوت {remains} نفر دیگر، ۳ روز اشتراک رایگان دریافت می‌کنید!"
                            asyncio.create_task(send_with_keyboard(client, inviter_id, msg_text, True))
                        except: pass

                    await send_with_keyboard(client, chat_id, "✅ کد هدیه با موفقیت ثبت شد!\n🎁 **10 سهمیه تبدیل رایگان متن به صدا** به حساب شما اضافه گردید.", True)
                return

            elif current_mode == "chat":
                if is_file:
                    await send_with_keyboard(client, chat_id, "📥 در حال دانلود فایل...", False)
                    try:
                        file_bytes = await helper_download_file(client, msg_obj)
                        user_states[str_chat_id]["file_bytes"] = file_bytes
                        user_states[str_chat_id]["file_name"] = file_name
                        user_states[str_chat_id]["mode"] = "chat_waiting_for_prompt"
                        await send_with_keyboard(client, chat_id, "✅ فایل با موفقیت دریافت شد.\n\nحالا لطفاً متنی بفرستید و بگویید **چه کاری با این فایل انجام دهم؟**\n(مثلاً: این تصویر را توصیف کن، یا متن این سند را خلاصه کن)", False)
                    except Exception as dl_err: 
                        await send_with_keyboard(client, chat_id, f"❌ خطا در دریافت فایل!\n{str(dl_err)}", False)
                elif user_text_str: 
                    asyncio.create_task(process_gemini(client, chat_id, user_text_str))
                return

            elif current_mode == "chat_waiting_for_prompt":
                if user_text_str:
                    saved_bytes = user_states[str_chat_id].get("file_bytes")
                    saved_name = user_states[str_chat_id].get("file_name", "file.jpeg")
                    user_states[str_chat_id]["mode"] = "chat"
                    user_states[str_chat_id]["file_bytes"] = None
                    asyncio.create_task(process_gemini(client, chat_id, user_text_str, file_bytes=saved_bytes, file_name=saved_name))
                else: 
                    await send_with_keyboard(client, chat_id, "⚠️ لطفاً درخواست خود را متنی بنویسید.", False)
                return

            elif current_mode == "image_waiting_for_text":
                if user_text_str:
                    user_states[str_chat_id]["text"] = user_text_str
                    user_states[str_chat_id]["mode"] = "image_waiting_for_size"
                    
                    size_menu = """🖼 **لطفاً ابعاد تصویر خود را انتخاب کنید:**

1️⃣ `1:1` (مربع) - مناسب پروفایل ⬛
2️⃣ `9:16` (عمودی) - مناسب استوری و پس‌زمینه گوشی 📱
3️⃣ `16:9` (افقی) - مناسب دسکتاپ و ویدیو 🖥️
4️⃣ `4:3` (استاندارد) - مناسب چاپ و پست 📸

(لطفاً فقط عدد 1 تا 4 را بفرستید)"""
                    await send_with_keyboard(client, chat_id, size_menu, False)
                else:
                    await send_with_keyboard(client, chat_id, "⚠️ لطفاً ایده عکس خود را به صورت متنی بفرستید.", False)
                return

            elif current_mode == "image_waiting_for_size":
                normalized_choice = to_english_digits(user_text_str).strip()
                if normalized_choice in["1", "2", "3", "4"]:
                    saved_text = user_states[str_chat_id].get("text", "")
                    user_states[str_chat_id]["mode"] = None
                    asyncio.create_task(process_image(client, chat_id, saved_text, normalized_choice))
                else:
                    await send_with_keyboard(client, chat_id, "❌ عدد وارد شده نامعتبر است! لطفاً فقط یکی از اعداد 1 تا 4 را بفرستید.", False)
                return

            elif current_mode == "image_edit_waiting_for_image":
                if not is_file: return await send_with_keyboard(client, chat_id, "⚠️ لطفاً ابتدا یک عکس ارسال کنید.", False)
                await send_with_keyboard(client, chat_id, "📥 در حال دانلود عکس...", False)
                try:
                    file_bytes = await helper_download_file(client, msg_obj)
                    user_states[str_chat_id]["file_bytes"] = file_bytes
                    user_states[str_chat_id]["mode"] = "image_edit_waiting_for_prompt"
                    await send_with_keyboard(client, chat_id, "✅ عکس با موفقیت دریافت شد.\n\nحالا دستور خود را به صورت متنی تایپ کنید.\nمثال: یک کلاه قرمز روی سر این گربه بگذار.", False)
                except Exception as dl_err: await send_with_keyboard(client, chat_id, f"❌ خطا در دریافت عکس!\n{str(dl_err)}", False)
                return

            elif current_mode == "image_edit_waiting_for_prompt":
                if user_text_str:
                    saved_bytes = user_states[str_chat_id].get("file_bytes")
                    user_states[str_chat_id]["mode"] = None 
                    user_states[str_chat_id]["file_bytes"] = None
                    asyncio.create_task(process_image_edit(client, chat_id, saved_bytes, user_text_str))
                else: await send_with_keyboard(client, chat_id, "⚠️ لطفاً درخواست خود را متنی بنویسید.", False)
                return

            elif current_mode == "tts_waiting_for_text":
                if user_text_str:
                    if len(user_text_str) > 2500: return await send_with_keyboard(client, chat_id, "⚠️ لطفاً متنی کوتاه‌تر از 2500 کاراکتر بفرستید.", False)
                    user_states[str_chat_id]["text"] = user_text_str
                    user_states[str_chat_id]["mode"] = "tts_waiting_for_speaker"
                    
                    speakers_menu = """✅ متن شما ذخیره شد.
لطفاً **شماره** گوینده مورد نظر خود را بفرستید:
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. لیدا"""
                    await send_with_keyboard(client, chat_id, speakers_menu, False)
                return

            elif current_mode == "tts_waiting_for_speaker":
                normalized_text = to_english_digits(user_text_str)
                
                if normalized_text.isdigit() and normalized_text in SPEAKERS:
                    spk_name, spk_id = SPEAKERS[normalized_text]
                    txt = user_states[str_chat_id]["text"]
                    user_states[str_chat_id]["mode"] = "tts_waiting_for_text"
                    asyncio.create_task(process_tts(client, chat_id, txt, spk_id, spk_name))
                else: 
                    await send_with_keyboard(client, chat_id, "❌ شماره نامعتبر است! لطفاً فقط یک عدد بین 1 تا 30 بفرستید.", False)
                return

            elif current_mode == "podcast_waiting_for_topic":
                if user_text_str: asyncio.create_task(process_podcast(client, chat_id, user_text_str))
                else: await send_with_keyboard(client, chat_id, "⚠️ لطفاً موضوع پادکست خود را به صورت متنی بفرستید.", False)
                return

            elif current_mode == "stt_waiting_for_audio":
                if not is_file: return await send_with_keyboard(client, chat_id, "⚠️ لطفاً یک فایل ارسال کنید.", False)
                await send_with_keyboard(client, chat_id, "📥 در حال دانلود فایل...", False)
                try:
                    audio_bytes = await helper_download_file(client, msg_obj)
                    asyncio.create_task(process_stt(client, chat_id, audio_bytes, file_name))
                except Exception as dl_err: await send_with_keyboard(client, chat_id, f"❌ خطا در دانلود فایل!\n{str(dl_err)}", False)
                return

            elif current_mode == "file_waiting_for_file":
                if not is_file: return await send_with_keyboard(client, chat_id, "⚠️ لطفاً ابتدا یک فایل ارسال کنید.", False)
                await send_with_keyboard(client, chat_id, "📥 در حال دریافت فایل...", False)
                try:
                    file_bytes = await helper_download_file(client, msg_obj)
                    user_states[str_chat_id]["file_bytes"] = file_bytes
                    user_states[str_chat_id]["file_name"] = file_name 
                    user_states[str_chat_id]["mode"] = "file_waiting_for_prompt"
                    await send_with_keyboard(client, chat_id, "✅ فایل با موفقیت دریافت شد.\n\nحالا لطفاً متنی بگویید **چگونه تحلیل شود؟**\n(می‌توانید سوال خاصی بپرسید یا فقط بخواهید فایل را توضیح دهد)", False)
                except Exception as dl_err: await send_with_keyboard(client, chat_id, f"❌ خطا در دریافت فایل!\n{str(dl_err)}", False)
                return

            elif current_mode == "file_waiting_for_prompt":
                if user_text_str:
                    saved_bytes = user_states[str_chat_id].get("file_bytes")
                    saved_name = user_states[str_chat_id].get("file_name", "file.jpeg")
                    user_states[str_chat_id]["mode"] = "file_waiting_for_file" 
                    asyncio.create_task(process_file_analysis(client, chat_id, saved_bytes, saved_name, user_text_str))
                else: await send_with_keyboard(client, chat_id, "⚠️ لطفاً درخواست خود را متنی بنویسید.", False)
                return

            elif current_mode == "create_file_waiting_for_topic":
                if user_text_str:
                    asyncio.create_task(process_create_file(client, chat_id, user_text_str))
                else: 
                    await send_with_keyboard(client, chat_id, "⚠️ لطفاً موضوع مقاله خود را به صورت متنی بفرستید.", False)
                return

            elif current_mode == "vc_waiting_for_voice":
                if not is_file: return await send_with_keyboard(client, chat_id, "⚠️ لطفاً یک فایل صوتی یا ویس ارسال کنید.", False)
                await send_with_keyboard(client, chat_id, "📥 در حال دانلود فایل صوتی شما...", False)
                try:
                    file_bytes = await helper_download_file(client, msg_obj)
                    user_states[str_chat_id]["file_bytes"] = file_bytes
                    user_states[str_chat_id]["mode"] = "vc_waiting_for_model"
                    
                    model_menu = "✅ صدای شما دریافت شد.\n\nلطفا **شماره** مدلی که می‌خواهید صدایتان به آن تبدیل شود را ارسال کنید:\n\n"
                    for k, v in LEGACY_MODELS.items():
                        if k == "8":
                            model_menu += f"{k}. {v['name']} (نامحدود رایگان)\n"
                        else:
                            model_menu += f"{k}. {v['name']}\n"
                    model_menu += "➖➖➖➖➖➖➖➖\n"
                    for k, v in STANDARD_MODELS.items(): model_menu += f"{k}. {v['name']}\n"
                    
                    await send_with_keyboard(client, chat_id, model_menu, False)
                except Exception as dl_err: 
                    await send_with_keyboard(client, chat_id, f"❌ خطا در دریافت فایل!\n{str(dl_err)}", False)
                return

            elif current_mode == "vc_waiting_for_model":
                choice = to_english_digits(user_text_str).strip()
                
                if choice in STANDARD_MODELS:
                    if creds["voice_conv"] <= 0: return await send_with_keyboard(client, chat_id, "❌ سهمیه تغییر صدای شما تمام شده است. لطفاً از منوی اصلی وارد بخش «خرید اشتراک 💎» شوید.", False)
                    user_states[str_chat_id]["mode"] = None
                    model = STANDARD_MODELS[choice]
                    src_bytes = user_states[str_chat_id]["file_bytes"]
                    await send_with_keyboard(client, chat_id, "📥 در حال آماده‌سازی فایل‌ها...", False)
                    ref_bytes = await helper_download_url_to_bytes(model["ref"])
                    if not ref_bytes: return await send_with_keyboard(client, chat_id, "❌ خطا در دسترسی به فایل صدای مدل.", False)
                    
                    asyncio.create_task(process_standard_vc_job(client, chat_id, src_bytes, ref_bytes, model["name"], "voice_conv"))
                
                elif choice in LEGACY_MODELS:
                    if choice != "8" and creds["voice_conv"] <= 0: 
                        return await send_with_keyboard(client, chat_id, "❌ سهمیه تغییر صدای شما تمام شده است. لطفاً از منوی اصلی وارد بخش «خرید اشتراک 💎» شوید.", False)
                    
                    user_states[str_chat_id]["selected_model"] = choice
                    user_states[str_chat_id]["mode"] = "vc_waiting_for_gender"
                    
                    gender_msg = f"✅ مدل {LEGACY_MODELS[choice]['name']} انتخاب شد.\n\nبرای تنظیم دقیق فرکانس‌ها به ما بگویید صدایی که خودتان فرستادید صدای یک **مرد** است یا **زن**؟\n\n1. مرد 👨\n2. زن 👩"
                    await send_with_keyboard(client, chat_id, gender_msg, False)
                else:
                    await send_with_keyboard(client, chat_id, "❌ شماره وارد شده صحیح نیست. لطفاً فقط عدد مدل را بفرستید.", False)
                return

            elif current_mode == "vc_waiting_for_gender":
                choice = to_english_digits(user_text_str).strip()
                if choice not in["1", "2"]:
                    return await send_with_keyboard(client, chat_id, "❌ لطفاً عدد 1 (مرد) یا 2 (زن) را ارسال کنید.", False)
                
                user_gender = "male" if choice == "1" else "female"
                model_key = user_states[str_chat_id]["selected_model"]
                model = LEGACY_MODELS[model_key]
                target_gender = model["gender"]
                
                pitch = 0
                if target_gender == "female" and user_gender == "male": pitch = 12
                elif target_gender == "male" and user_gender == "female": pitch = -12
                
                user_states[str_chat_id]["mode"] = None
                src_bytes = user_states[str_chat_id]["file_bytes"]
                asyncio.create_task(process_legacy_vc_job(client, chat_id, src_bytes, model["url"], pitch, model["name"]))
                return

            elif current_mode == "clone_waiting_for_src":
                if not is_file: return await send_with_keyboard(client, chat_id, "⚠️ لطفاً فایل صوتی صدای خودتان را بفرستید.", False)
                await send_with_keyboard(client, chat_id, "📥 در حال دانلود صدای شما...", False)
                try:
                    file_bytes = await helper_download_file(client, msg_obj)
                    user_states[str_chat_id]["file_bytes"] = file_bytes
                    user_states[str_chat_id]["mode"] = "clone_waiting_for_ref"
                    await send_with_keyboard(client, chat_id, "✅ صدای شما دریافت شد.\n\nحالا **فایل الگو (صدای شخصی که می‌خواهید شبیه‌سازی کنید)** را ارسال کنید.\n(پیشنهاد: فایل بدون نویز و موسیقی، بین ۳ تا ۱۰ ثانیه)", False)
                except Exception as dl_err: 
                    await send_with_keyboard(client, chat_id, f"❌ خطا در دریافت فایل!\n{str(dl_err)}", False)
                return

            elif current_mode == "clone_waiting_for_ref":
                if not is_file: return await send_with_keyboard(client, chat_id, "⚠️ لطفاً فایل صوتی الگوی هدف را بفرستید.", False)
                await send_with_keyboard(client, chat_id, "📥 در حال دانلود صدای الگو...", False)
                try:
                    ref_bytes = await helper_download_file(client, msg_obj)
                    
                    if creds["voice_clone"] <= 0: 
                        return await send_with_keyboard(client, chat_id, "❌ سهمیه کلون کردن صدای شما تمام شده است. نیازمند تهیه اشتراک هستید.", False)
                    
                    user_states[str_chat_id]["mode"] = None
                    src_bytes = user_states[str_chat_id]["file_bytes"]
                    
                    asyncio.create_task(process_standard_vc_job(client, chat_id, src_bytes, ref_bytes, "صدای اختصاصی (کلون شده)", "voice_clone"))
                except Exception as dl_err: 
                    await send_with_keyboard(client, chat_id, f"❌ خطا در دریافت فایل!\n{str(dl_err)}", False)
                return

        except Exception: traceback.print_exc()

if __name__ == "__main__":
    threading.Thread(target=run_flask, daemon=True).start()
    
    if bot_token:
        loop = asyncio.get_event_loop()
        
        loop.set_default_executor(concurrent.futures.ThreadPoolExecutor(max_workers=256))
        
        loop.create_task(ram_garbage_collector())
        
        print("🚀 ربات آلفا پرو (نسخه صنعتی + دیتابیس هوشمند + فیلتر زمان قطعی + 256 تونل همزمان) روشن شد...")
        bot.run()