-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathadmin.py
More file actions
1618 lines (1406 loc) · 60.2 KB
/
admin.py
File metadata and controls
1618 lines (1406 loc) · 60.2 KB
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
from flask import Blueprint, render_template, request, redirect, url_for, flash, session, jsonify
from functools import wraps
from models import db, User, ActivationCode, PredictionRecord, SystemConfig, InviteCode, ZodiacSetting, ManualBetRecord
from datetime import datetime, timedelta
import csv
import json
import io
from collections import OrderedDict
from sqlalchemy import func, case, or_
admin_bp = Blueprint('admin', __name__, url_prefix='/admin')
LEARNING_PANEL_TERM_LABELS = {
'hot': '热门',
'cold': '冷门',
'trend': '走势',
'balanced': '均衡',
'hybrid': '综合',
'ml': '机器学习',
'ai': 'AI智能',
'feedback': '反馈',
'color': '波色',
'normal': '平码',
'overdue': '遗漏',
'parity': '单双',
'zodiac': '生肖',
}
PREDICTION_STRATEGY_LABELS = {
'hot': '热门预测',
'cold': '冷门预测',
'trend': '走势预测',
'balanced': '均衡预测',
'hybrid': '综合预测',
'ml': '机器学习预测',
'ai': 'AI预测',
}
def _normalize_visual_weights(weight_map):
cleaned = OrderedDict()
total = 0.0
for label, value in (weight_map or {}).items():
try:
numeric = max(0.0, float(value))
except Exception:
numeric = 0.0
cleaned[label] = numeric
total += numeric
if total <= 0:
return []
items = []
for label, numeric in cleaned.items():
percent = round((numeric / total) * 100, 1)
value = f"{int(percent)}%" if float(percent).is_integer() else f"{percent}%"
items.append({
'key': label,
'label': label,
'value': value,
})
return items
def _build_ml_visual_weights(config):
runtime_profile = str(config.get('primary_runtime_profile') or 'base').strip()
feature_profile = str(config.get('primary_feature_profile') or 'full').strip()
weight_map = OrderedDict([
('历史样本', 26),
('近期走势', 18),
('策略共识', 18),
('单双参考', 13),
('波色参考', 13),
('生肖参考', 12),
])
if runtime_profile == 'recent_bias':
weight_map['近期走势'] += 8
weight_map['历史样本'] -= 4
weight_map['策略共识'] -= 4
elif runtime_profile == 'context_bias':
weight_map['单双参考'] += 4
weight_map['波色参考'] += 4
weight_map['生肖参考'] += 4
weight_map['历史样本'] -= 6
weight_map['近期走势'] -= 3
weight_map['策略共识'] -= 3
elif runtime_profile == 'recency_trim':
weight_map['近期走势'] += 6
weight_map['历史样本'] -= 6
elif runtime_profile == 'learned_feature_bias':
weight_map['策略共识'] += 5
weight_map['单双参考'] += 2
weight_map['波色参考'] += 2
weight_map['历史样本'] -= 5
weight_map['近期走势'] -= 2
weight_map['生肖参考'] -= 2
if feature_profile == 'compact_attributes':
weight_map['单双参考'] += 3
weight_map['波色参考'] += 3
weight_map['生肖参考'] += 2
weight_map['历史样本'] -= 4
weight_map['近期走势'] -= 2
weight_map['策略共识'] -= 2
elif feature_profile == 'compact_structure':
weight_map['策略共识'] += 4
weight_map['近期走势'] += 2
weight_map['历史样本'] += 1
weight_map['单双参考'] -= 2
weight_map['波色参考'] -= 2
weight_map['生肖参考'] -= 3
elif feature_profile == 'compact_recency':
weight_map['近期走势'] += 6
weight_map['历史样本'] -= 4
weight_map['策略共识'] -= 2
return _normalize_visual_weights(weight_map)
def _build_ai_visual_weights(config):
history_window = max(1, int(config.get('history_window') or 12))
temperature = max(0.0, float(config.get('temperature') or 0.35))
weight_map = OrderedDict([
('历史样本', 30),
('近期走势', 18),
('单双参考', 14),
('波色参考', 14),
('生肖参考', 10),
('策略共识', 14),
])
if history_window >= 18:
weight_map['历史样本'] += 6
weight_map['策略共识'] += 2
weight_map['近期走势'] -= 3
weight_map['波色参考'] -= 2
weight_map['生肖参考'] -= 1
weight_map['单双参考'] -= 2
elif history_window <= 8:
weight_map['近期走势'] += 5
weight_map['单双参考'] += 2
weight_map['波色参考'] += 2
weight_map['历史样本'] -= 5
weight_map['策略共识'] -= 4
if temperature <= 0.3:
weight_map['策略共识'] += 4
weight_map['历史样本'] += 2
weight_map['近期走势'] -= 2
weight_map['生肖参考'] -= 2
weight_map['波色参考'] -= 1
weight_map['单双参考'] -= 1
elif temperature >= 0.7:
weight_map['近期走势'] += 4
weight_map['生肖参考'] += 2
weight_map['波色参考'] += 2
weight_map['历史样本'] -= 4
weight_map['策略共识'] -= 4
return _normalize_visual_weights(weight_map)
def _build_strategy_visual_weights(strategy, config):
weights = config.get('weights') or {}
if weights:
return [
{
'key': key,
'label': LEARNING_PANEL_TERM_LABELS.get(key, key),
'value': value
}
for key, value in sorted(weights.items())
]
if strategy == 'ml':
return _build_ml_visual_weights(config)
if strategy == 'ai':
return _build_ai_visual_weights(config)
return []
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
try:
# 检查用户是否登录
if 'user_id' not in session:
flash('请先登录', 'error')
return redirect(url_for('auth.login'))
# 检查用户是否是管理员
user = User.query.get(session['user_id'])
if not user or not user.is_admin:
flash('需要管理员权限才能访问此页面', 'error')
return redirect(url_for('auth.login'))
return f(*args, **kwargs)
except Exception as e:
flash(f'权限检查失败: {str(e)}', 'error')
return redirect(url_for('auth.login'))
return decorated_function
def _strategy_learning_panel_data():
from app import _load_strategy_config, _get_strategy_label
regions = [('hk', '香港'), ('macau', '澳门')]
strategies = ['hot', 'cold', 'trend', 'balanced', 'hybrid', 'ml', 'ai']
panel = []
for region_key, region_label in regions:
items = []
for strategy in strategies:
config = _load_strategy_config(strategy, region_key)
weight_items = _build_strategy_visual_weights(strategy, config)
mix = config.get('mix') or {}
mix_items = [
{
'key': key,
'label': LEARNING_PANEL_TERM_LABELS.get(key, key),
'value': value
}
for key, value in mix.items()
]
items.append({
'key': strategy,
'display_key': LEARNING_PANEL_TERM_LABELS.get(strategy, strategy),
'label': _get_strategy_label(strategy),
'updated_at': config.get('updated_at', ''),
'last_accuracy': round(float(config.get('last_accuracy') or 0.0) * 100, 1),
'last_total': int(config.get('last_total') or 0),
'accuracy_delta': round(float(config.get('accuracy_delta') or 0.0) * 100, 1),
'window': config.get('window'),
'trend_window': config.get('trend_window'),
'history_window': config.get('history_window'),
'feature_window': config.get('feature_window'),
'pool': config.get('pool'),
'special_pool': config.get('special_pool'),
'epochs': config.get('epochs'),
'learning_rate': config.get('learning_rate'),
'bucket_counts': config.get('bucket_counts') or [],
'mix': mix,
'mix_items': mix_items,
'weights': weight_items,
})
panel.append({
'region_key': region_key,
'region_label': region_label,
'items': items,
})
return panel
@admin_bp.route('/dashboard')
@admin_required
def dashboard():
try:
# 获取统计数据
total_users = User.query.count()
active_users = User.query.filter_by(is_active=True).count()
inactive_users = total_users - active_users
total_codes = ActivationCode.query.count()
used_codes = ActivationCode.query.filter_by(is_used=True).count()
unused_codes = total_codes - used_codes
total_predictions = PredictionRecord.query.count()
# 计算不同策略的准确率(只对比特码)
def calculate_accuracy(strategy):
predictions = PredictionRecord.query.filter_by(strategy=strategy, is_result_updated=True).all()
if not predictions:
return 0.0
correct_count = 0
total_count = 0
for pred in predictions:
if pred.actual_special_number and pred.special_number:
total_count += 1
if pred.special_number == pred.actual_special_number:
correct_count += 1
return round(correct_count / total_count * 100, 1) if total_count > 0 else 0.0
# 计算平均准确率(只对比特码)
all_predictions = PredictionRecord.query.filter_by(is_result_updated=True).all()
if all_predictions:
correct_count = 0
total_count = 0
for pred in all_predictions:
if pred.actual_special_number and pred.special_number:
total_count += 1
if pred.special_number == pred.actual_special_number:
correct_count += 1
avg_accuracy = round(correct_count / total_count * 100, 1) if total_count > 0 else 0.0
else:
avg_accuracy = 0.0
balanced_accuracy = calculate_accuracy('balanced')
ai_accuracy = calculate_accuracy('ai')
# 最近注册的用户
recent_users = User.query.order_by(User.created_at.desc()).limit(5).all()
# 最近的预测记录
recent_predictions = PredictionRecord.query.order_by(PredictionRecord.created_at.desc()).limit(5).all()
# 为预测记录添加用户名
for pred in recent_predictions:
if pred.user_id:
user = User.query.get(pred.user_id)
pred.username = user.username if user else '已删除用户'
else:
pred.username = '未知用户'
# 获取邀请统计数据
total_invite_codes = InviteCode.query.count()
used_invite_codes = InviteCode.query.filter_by(is_used=True).count()
unused_invite_codes = total_invite_codes - used_invite_codes
total_invites = User.query.filter(User.invited_by.isnot(None)).count()
invite_stats = {
'total_invite_codes': total_invite_codes,
'used_invite_codes': used_invite_codes,
'unused_invite_codes': unused_invite_codes,
'total_invites': total_invites
}
stats = {
'total_users': total_users,
'active_users': active_users,
'inactive_users': inactive_users,
'total_codes': total_codes,
'used_codes': used_codes,
'unused_codes': unused_codes,
'total_predictions': total_predictions,
'avg_accuracy': avg_accuracy,
'balanced_accuracy': balanced_accuracy,
'ai_accuracy': ai_accuracy,
'recent_users': recent_users,
'recent_predictions': recent_predictions,
'invite_stats': invite_stats
}
return render_template('admin/dashboard.html', stats=stats)
except Exception as e:
flash(f'加载控制台数据失败: {str(e)}', 'error')
return render_template('admin/dashboard.html', stats={
'total_users': 0,
'active_users': 0,
'inactive_users': 0,
'total_codes': 0,
'used_codes': 0,
'unused_codes': 0,
'total_predictions': 0,
'avg_accuracy': 0.0,
'balanced_accuracy': 0.0,
'ai_accuracy': 0.0,
'recent_users': [],
'recent_predictions': [],
'invite_stats': {
'total_invite_codes': 0,
'used_invite_codes': 0,
'unused_invite_codes': 0,
'total_invites': 0
}
})
@admin_bp.route('/users')
@admin_required
def users():
try:
page = request.args.get('page', 1, type=int)
search_query = request.args.get('search', '')
# 构建查询
query = User.query
# 如果有搜索关键词,添加搜索条件
if search_query:
search_term = f"%{search_query}%"
query = query.filter(
(User.username.like(search_term)) |
(User.email.like(search_term))
)
# 分页
users = query.paginate(
page=page, per_page=20, error_out=False
)
return render_template('admin/users.html', users=users, search_query=search_query)
except Exception as e:
flash(f'加载用户数据失败: {str(e)}', 'error')
# 创建空的分页对象
# 创建空的分页对象
class EmptyPagination:
def __init__(self):
self.items = []
self.page = 1
self.per_page = 20
self.total = 0
self.pages = 0
self.has_prev = False
self.has_next = False
self.prev_num = None
self.next_num = None
empty_users = EmptyPagination()
return render_template('admin/users.html', users=empty_users)
@admin_bp.route('/user/<int:user_id>/edit', methods=['GET', 'POST'])
@admin_required
def edit_user(user_id):
try:
user = User.query.get_or_404(user_id)
if request.method == 'POST':
# 获取表单数据
new_username = request.form.get('username')
new_email = request.form.get('email')
new_password = request.form.get('new_password')
is_active = 'is_active' in request.form
is_admin = 'is_admin' in request.form
# 保存原始用户名,用于判断是否是admin账号
original_username = user.username
print(f"DEBUG: original_username={original_username}, is_active={is_active}, user.is_active={user.is_active}")
# 对于admin账号,强制保持激活状态
if original_username == 'admin':
is_active = True
print(f"DEBUG: 设置admin用户is_active=True")
# 防止停用admin账号
if original_username == 'admin' and not is_active:
flash('不能停用admin账号', 'error')
return render_template('admin/edit_user.html', user=user)
# 更新用户信息
user.username = new_username
user.email = new_email
# 如果由未激活状态变为激活状态,默认开启预测
if is_active and not user.is_active:
user.auto_prediction_enabled = True
user.is_active = is_active
# 如果是admin账号,保持管理员权限
if original_username == 'admin':
user.is_admin = True
else:
user.is_admin = is_admin
# 如果提供了新密码,则更新密码
if new_password:
user.set_password(new_password)
# 处理激活过期时间
activation_expires_at = request.form.get('activation_expires_at')
if activation_expires_at:
try:
user.activation_expires_at = datetime.strptime(activation_expires_at, '%Y-%m-%dT%H:%M')
except ValueError:
flash('激活过期时间格式无效', 'error')
return render_template('admin/edit_user.html', user=user)
else:
# 如果用户是激活状态,则设置为永久有效期,否则不设置有效期
if user.is_active:
user.activation_expires_at = None
else:
# 未激活用户不应该有有效期
user.activation_expires_at = None
try:
db.session.commit()
flash('用户信息更新成功', 'success')
return redirect(url_for('admin.users'))
except Exception as e:
db.session.rollback()
flash(f'更新失败: {str(e)}', 'error')
return render_template('admin/edit_user.html', user=user)
except Exception as e:
flash(f'编辑用户失败: {str(e)}', 'error')
return redirect(url_for('admin.users'))
@admin_bp.route('/users/add', methods=['POST'])
@admin_required
def add_user():
"""添加新用户"""
try:
data = request.get_json()
if not data:
return jsonify({'success': False, 'message': '无效的数据格式'})
username = data.get('username', '').strip()
email = data.get('email', '').strip()
password = data.get('password', '')
is_admin = data.get('is_admin', False)
# 验证输入
if not username:
return jsonify({'success': False, 'message': '用户名不能为空'})
if not email:
return jsonify({'success': False, 'message': '邮箱不能为空'})
if not password or len(password) < 6:
return jsonify({'success': False, 'message': '密码长度不能少于6个字符'})
# 检查用户名是否已存在
if User.query.filter_by(username=username).first():
return jsonify({'success': False, 'message': '用户名已存在'})
# 检查邮箱是否已存在
if User.query.filter_by(email=email).first():
return jsonify({'success': False, 'message': '邮箱已被使用'})
# 创建新用户
user = User(username=username, email=email, is_active=True, is_admin=is_admin)
user.set_password(password)
db.session.add(user)
db.session.commit()
return jsonify({'success': True, 'message': '用户添加成功'})
except Exception as e:
db.session.rollback()
return jsonify({'success': False, 'message': str(e)})
@admin_bp.route('/users/<int:user_id>/activate', methods=['POST'])
@admin_required
def activate_user(user_id):
try:
user = User.query.get_or_404(user_id)
user.is_active = True
user.auto_prediction_enabled = True
db.session.commit()
return jsonify({'success': True})
except Exception as e:
db.session.rollback()
return jsonify({'success': False, 'message': str(e)})
@admin_bp.route('/users/<int:user_id>/deactivate', methods=['POST'])
@admin_required
def deactivate_user(user_id):
try:
user = User.query.get_or_404(user_id)
# 防止停用admin账号
if user.username == 'admin':
return jsonify({'success': False, 'message': '不能停用admin账号'})
user.is_active = False
db.session.commit()
return jsonify({'success': True})
except Exception as e:
db.session.rollback()
return jsonify({'success': False, 'message': str(e)})
@admin_bp.route('/users/<int:user_id>/reset_password', methods=['POST'])
@admin_required
def reset_user_password(user_id):
try:
user = User.query.get_or_404(user_id)
data = request.get_json()
if not data or 'new_password' not in data:
return jsonify({'success': False, 'message': '缺少新密码参数'})
new_password = data['new_password']
if not new_password or len(new_password) < 6:
return jsonify({'success': False, 'message': '密码长度不能少于6个字符'})
user.set_password(new_password)
db.session.commit()
return jsonify({'success': True, 'message': '密码重置成功'})
except Exception as e:
db.session.rollback()
return jsonify({'success': False, 'message': str(e)})
@admin_bp.route('/users/<int:user_id>/delete', methods=['DELETE'])
@admin_required
def delete_user(user_id):
try:
user = User.query.get_or_404(user_id)
# 防止删除管理员账号
if user.is_admin:
flash('不能删除管理员账号', 'error')
return redirect(url_for('admin.users'))
db.session.delete(user)
db.session.commit()
flash('用户删除成功', 'success')
except Exception as e:
db.session.rollback()
flash(f'删除用户失败: {str(e)}', 'error')
return redirect(url_for('admin.users'))
@admin_bp.route('/activation_codes')
@admin_required
def activation_codes():
"""激活码管理页面 - 使用AJAX加载数据"""
try:
# 不再在这里加载数据,而是通过JavaScript从API获取
return render_template('admin/activation_codes.html', now=datetime.utcnow())
except Exception as e:
flash(f'加载激活码页面失败: {str(e)}', 'error')
return redirect(url_for('admin.dashboard'))
# 删除generate_codes函数,因为已经在activation_code_routes.py中实现
SYSTEM_CONFIG_DEFAULTS = {
'ai_api_key': '',
'ai_api_url': 'https://api.deepseek.com/v1/chat/completions',
'ai_model': 'deepseek-chat',
'smtp_server': '',
'smtp_port': '587',
'smtp_username': '',
'smtp_password': '',
'site_name': '六合彩预测系统',
'site_description': '',
'invite_daily_limit': '3',
'invite_code_validity_days': '7',
'system_name': '六合彩预测系统',
'system_description': '',
'allow_registration': 'true',
'require_email_verification': 'false',
'enable_personalized_predictions': 'false',
}
@admin_bp.route('/system_config', methods=['GET', 'POST'])
@admin_required
def system_config():
try:
if request.method == 'POST':
configs = {
key: request.form.get(key, default)
for key, default in SYSTEM_CONFIG_DEFAULTS.items()
}
try:
for key, value in configs.items():
SystemConfig.set_config(key, value)
flash('系统配置更新成功', 'success')
except Exception as e:
flash(f'配置更新失败: {str(e)}', 'error')
return redirect(url_for('admin.system_config'))
configs = {
key: SystemConfig.get_config(key, default)
for key, default in SYSTEM_CONFIG_DEFAULTS.items()
}
return render_template(
'admin/system_config.html',
configs=configs,
learning_panel=_strategy_learning_panel_data(),
)
except Exception as e:
flash(f'加载系统配置失败: {str(e)}', 'error')
return render_template(
'admin/system_config.html',
configs=SYSTEM_CONFIG_DEFAULTS,
learning_panel=[],
)
@admin_bp.route('/system_config/save', methods=['POST'])
@admin_required
def save_system_config():
try:
data = request.get_json(silent=True)
if not data:
return jsonify({'success': False, 'message': '无效的数据格式'})
for key, value in data.items():
SystemConfig.set_config(key, value)
return jsonify({'success': True, 'message': '配置保存成功'})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
@admin_bp.route('/system_config/retrain_learning', methods=['POST'])
@admin_required
def retrain_learning_configs():
try:
from app import update_strategy_configs
payload = request.get_json(silent=True) or {}
region = (payload.get('region') or 'all').strip()
targets = ['hk', 'macau'] if region in ('', 'all') else [region]
allowed = {'hk', 'macau'}
targets = [item for item in targets if item in allowed]
if not targets:
return jsonify({'success': False, 'message': '无效的地区参数'})
refreshed = []
for item in targets:
update_strategy_configs(item)
refreshed.append(item)
return jsonify({
'success': True,
'message': f"已重算 {', '.join(refreshed)} 的学习参数",
'learning_panel': _strategy_learning_panel_data(),
})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
@admin_bp.route('/predictions')
@admin_required
def predictions():
try:
page = request.args.get('page', 1, type=int)
user_query = request.args.get('user', '').strip()
region_filter = request.args.get('region', '').strip()
strategy_filter = request.args.get('strategy', '').strip()
period_filter = request.args.get('period', '').strip()
filters = []
if user_query:
if user_query.isdigit():
filters.append(PredictionRecord.user_id == int(user_query))
else:
search_term = f"%{user_query}%"
user_ids = User.query.filter(
(User.username.like(search_term)) | (User.email.like(search_term))
).with_entities(User.id)
filters.append(PredictionRecord.user_id.in_(user_ids))
if region_filter:
filters.append(PredictionRecord.region == region_filter)
if strategy_filter:
filters.append(PredictionRecord.strategy == strategy_filter)
if period_filter:
filters.append(PredictionRecord.period.contains(period_filter))
groups_query = db.session.query(
PredictionRecord.region.label('region'),
PredictionRecord.period.label('period'),
func.max(PredictionRecord.created_at).label('latest_created_at'),
func.count(PredictionRecord.id).label('record_count'),
func.count(func.distinct(PredictionRecord.user_id)).label('user_count')
)
if filters:
groups_query = groups_query.filter(*filters)
predictions = groups_query.group_by(
PredictionRecord.region,
PredictionRecord.period
).order_by(
func.max(PredictionRecord.created_at).desc()
).paginate(
page=page, per_page=10, error_out=False
)
group_keys = [(item.region, item.period) for item in predictions.items]
page_records = []
if group_keys:
group_conditions = [
((PredictionRecord.region == region) & (PredictionRecord.period == period))
for region, period in group_keys
]
page_query = PredictionRecord.query.filter(or_(*group_conditions))
if filters:
page_query = page_query.filter(*filters)
page_records = page_query.order_by(
PredictionRecord.created_at.desc(),
PredictionRecord.id.desc()
).all()
regions = {
item.region
for item in predictions.items
if item.region
}
prediction_summary_cards = []
for region in regions:
history_query = PredictionRecord.query.filter(PredictionRecord.region == region)
if filters:
history_query = history_query.filter(*filters)
history_records = history_query.order_by(
PredictionRecord.created_at.asc(),
PredictionRecord.id.asc()
).all()
period_results = OrderedDict()
for record in history_records:
period_key = record.period
if period_key not in period_results:
period_results[period_key] = {
'has_result': False,
'is_hit': False,
}
if (
record.is_result_updated
and record.special_number
and record.actual_special_number
):
period_results[period_key]['has_result'] = True
if str(record.special_number).strip() == str(record.actual_special_number).strip():
period_results[period_key]['is_hit'] = True
total_special_hits = 0
consecutive_special_misses = 0
consecutive_special_hits = 0
max_consecutive_special_hits = 0
max_consecutive_special_misses = 0
resolved_periods = 0
for result in period_results.values():
if not result['has_result']:
continue
resolved_periods += 1
if result['is_hit']:
total_special_hits += 1
consecutive_special_hits += 1
consecutive_special_misses = 0
if consecutive_special_hits > max_consecutive_special_hits:
max_consecutive_special_hits = consecutive_special_hits
else:
consecutive_special_hits = 0
consecutive_special_misses += 1
if consecutive_special_misses > max_consecutive_special_misses:
max_consecutive_special_misses = consecutive_special_misses
prediction_summary_cards.append({
'region': region,
'region_label': '香港' if region == 'hk' else '澳门' if region == 'macau' else region,
'hit_periods': total_special_hits,
'miss_streak': consecutive_special_misses,
'max_hit_streak': max_consecutive_special_hits,
'max_miss_streak': max_consecutive_special_misses,
'resolved_periods': resolved_periods,
})
prediction_summary_cards.sort(
key=lambda item: 0 if item['region'] == 'hk' else 1 if item['region'] == 'macau' else 2
)
pending_updates = []
# 为预测记录添加用户名,并兜底补齐缺失生肖
strategy_order = {
'hot': 1,
'cold': 2,
'trend': 3,
'hybrid': 4,
'balanced': 5,
'ml': 6,
'ai': 7,
}
personalized_enabled = str(SystemConfig.get_config('enable_personalized_predictions', 'false')).strip().lower() == 'true'
for pred in page_records:
if personalized_enabled:
if pred.user_id:
user = User.query.get(pred.user_id)
pred.username = user.username if user else '已删除用户'
else:
pred.username = '未知用户'
else:
pred.username = ''
pred.strategy_label = PREDICTION_STRATEGY_LABELS.get(pred.strategy, pred.strategy)
pred.strategy_sort = strategy_order.get(pred.strategy, 99)
pred.display_special_zodiac = (pred.special_zodiac or '').strip()
if not pred.display_special_zodiac and pred.special_number:
try:
zodiac_year = ZodiacSetting.get_zodiac_year_for_date(
pred.created_at or datetime.now()
)
pred.display_special_zodiac = (
ZodiacSetting.get_zodiac_for_number(
zodiac_year, pred.special_number
) or ''
).strip()
if pred.display_special_zodiac:
pred.special_zodiac = pred.display_special_zodiac
pending_updates.append(pred)
except Exception:
pred.display_special_zodiac = ''
pred.display_actual_special_zodiac = (pred.actual_special_zodiac or '').strip()
if not pred.display_actual_special_zodiac and pred.actual_special_number:
try:
zodiac_year = ZodiacSetting.get_zodiac_year_for_date(
pred.created_at or datetime.now()
)
pred.display_actual_special_zodiac = (
ZodiacSetting.get_zodiac_for_number(
zodiac_year, pred.actual_special_number
) or ''
).strip()
if pred.display_actual_special_zodiac:
pred.actual_special_zodiac = pred.display_actual_special_zodiac
pending_updates.append(pred)
except Exception:
pred.display_actual_special_zodiac = ''
normal_numbers = [
value.strip()
for value in str(pred.normal_numbers or '').split(',')
if value.strip()
]
pred.normal_numbers_list = normal_numbers
actual_special = str(pred.actual_special_number or '').strip()
pred.is_special_hit = bool(
pred.is_result_updated
and actual_special
and str(pred.special_number or '').strip() == actual_special
)
pred.is_normal_number_hit = bool(
pred.is_result_updated
and actual_special
and not pred.is_special_hit
and actual_special in normal_numbers
)
pred.is_zodiac_hit = bool(
pred.is_result_updated
and actual_special
and not pred.is_special_hit
and not pred.is_normal_number_hit
and pred.display_special_zodiac
and pred.display_actual_special_zodiac
and pred.display_special_zodiac == pred.display_actual_special_zodiac
)
if pred.is_special_hit:
pred.result_label = '特码命中'
pred.result_class = 'hit'
elif pred.is_normal_number_hit:
pred.result_label = '平码命中'
pred.result_class = 'partial'
elif pred.is_zodiac_hit:
pred.result_label = '生肖命中'
pred.result_class = 'partial'
elif pred.is_result_updated:
pred.result_label = '未命中'
pred.result_class = 'miss'
else:
pred.result_label = '待开奖'
pred.result_class = 'pending'
if pending_updates:
try:
db.session.commit()
except Exception:
db.session.rollback()
prediction_groups_map = OrderedDict()
group_meta_map = {
f"{item.region}-{item.period}": item
for item in predictions.items
}
for pred in page_records:
group_key = f"{pred.region}-{pred.period}"
if group_key not in prediction_groups_map:
group_meta = group_meta_map.get(group_key)
prediction_groups_map[group_key] = {
'key': group_key,
'region': pred.region,
'period': pred.period,
'actual_special_number': pred.actual_special_number,
'display_actual_special_zodiac': pred.display_actual_special_zodiac,
'created_at': getattr(group_meta, 'latest_created_at', None) or pred.created_at,
'record_count': int(getattr(group_meta, 'record_count', 0) or 0),
'user_count': int(getattr(group_meta, 'user_count', 0) or 0),
'items': [],
'_seen_strategies': set(),
'_seen_prediction_signatures': set(),
'_users': set(),
}
group = prediction_groups_map[group_key]
prediction_signature = (
str(pred.strategy or '').strip(),
str(pred.special_number or '').strip(),
','.join(pred.normal_numbers_list),
)
if prediction_signature in group['_seen_prediction_signatures']:
continue
group['_seen_prediction_signatures'].add(prediction_signature)
if not personalized_enabled:
if pred.strategy in group['_seen_strategies']:
continue
group['_seen_strategies'].add(pred.strategy)