129 lines
4.2 KiB
Python
129 lines
4.2 KiB
Python
from flask import Blueprint, jsonify
|
||
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||
from models import db
|
||
from models.user import User
|
||
from models.token import Token
|
||
from models.usage_log import UsageLog
|
||
from datetime import datetime, timedelta
|
||
import logging
|
||
from sqlalchemy import func, and_
|
||
|
||
dashboard_bp = Blueprint('dashboard', __name__)
|
||
logger = logging.getLogger(__name__)
|
||
|
||
@dashboard_bp.route('/stats', methods=['GET'])
|
||
@jwt_required()
|
||
def get_dashboard_stats():
|
||
"""获取数据看板统计信息"""
|
||
current_user_id = int(get_jwt_identity())
|
||
user = User.query.get(current_user_id)
|
||
|
||
if not user:
|
||
return jsonify({'error': '用户不存在'}), 404
|
||
|
||
# 获取今日和7天的日期范围
|
||
today_start = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
|
||
seven_days_ago = today_start - timedelta(days=7)
|
||
|
||
# Token统计(今日)
|
||
today_logs = UsageLog.query.filter(
|
||
and_(
|
||
UsageLog.user_id == current_user_id,
|
||
UsageLog.created_at >= today_start
|
||
)
|
||
).all()
|
||
|
||
today_input = sum(log.input_tokens for log in today_logs)
|
||
today_output = sum(log.output_tokens for log in today_logs)
|
||
today_cache_create = 0 # 需要根据实际业务逻辑计算
|
||
today_cache_read = 0 # 需要根据实际业务逻辑计算
|
||
today_total = today_input + today_output
|
||
|
||
# Token统计(7天)
|
||
week_logs = UsageLog.query.filter(
|
||
and_(
|
||
UsageLog.user_id == current_user_id,
|
||
UsageLog.created_at >= seven_days_ago
|
||
)
|
||
).all()
|
||
|
||
week_input = sum(log.input_tokens for log in week_logs)
|
||
week_output = sum(log.output_tokens for log in week_logs)
|
||
week_total = week_input + week_output
|
||
|
||
# 性能指标
|
||
if today_logs:
|
||
total_duration = sum(log.duration or 0 for log in today_logs)
|
||
total_requests = len(today_logs)
|
||
avg_rpm = total_requests / (total_duration / 60) if total_duration > 0 else 0
|
||
avg_tpm = today_total / (total_duration / 60) if total_duration > 0 else 0
|
||
else:
|
||
avg_rpm = 0
|
||
avg_tpm = 0
|
||
|
||
# 模型消耗分布(示例数据,实际需要从数据库查询)
|
||
model_distribution = []
|
||
model_stats = db.session.query(
|
||
UsageLog.model,
|
||
func.sum(UsageLog.cost).label('total_cost')
|
||
).filter(
|
||
and_(
|
||
UsageLog.user_id == current_user_id,
|
||
UsageLog.created_at >= seven_days_ago
|
||
)
|
||
).group_by(UsageLog.model).all()
|
||
|
||
for model, cost in model_stats:
|
||
model_distribution.append({
|
||
'model': model,
|
||
'cost': float(cost) if cost else 0
|
||
})
|
||
|
||
return jsonify({
|
||
'account': {
|
||
'balance': float(user.balance),
|
||
'total_consumption': float(user.total_consumption),
|
||
'request_count': user.request_count
|
||
},
|
||
'usage': {
|
||
'request_count': user.request_count,
|
||
'stat_count': len(today_logs) # 统计次数
|
||
},
|
||
'token_stats': {
|
||
'today': {
|
||
'input': today_input,
|
||
'output': today_output,
|
||
'cache_create': today_cache_create,
|
||
'cache_read': today_cache_read,
|
||
'total': today_total
|
||
},
|
||
'week': {
|
||
'input': week_input,
|
||
'output': week_output,
|
||
'total': week_total
|
||
}
|
||
},
|
||
'performance': {
|
||
'avg_rpm': round(avg_rpm, 3),
|
||
'avg_tpm': round(avg_tpm, 3)
|
||
},
|
||
'model_distribution': model_distribution
|
||
}), 200
|
||
|
||
@dashboard_bp.route('/server-info', methods=['GET'])
|
||
@jwt_required()
|
||
def get_server_info():
|
||
"""获取服务器信息"""
|
||
# 验证token(用于调试)
|
||
try:
|
||
current_user_id = int(get_jwt_identity())
|
||
logger.info(f"Server info requested by user: {current_user_id}")
|
||
except Exception as e:
|
||
logger.error(f"JWT verification failed: {str(e)}")
|
||
|
||
return jsonify({
|
||
'name': '蓝星中国服务器',
|
||
'url': 'https://cc.honoursoft.cn',
|
||
'description': 'cn2网络回国优化,支持海外,国内双向访问。'
|
||
}), 200
|