| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447 |
- /*
- Copyright (C) 2025 QuantumNous
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as
- published by the Free Software Foundation, either version 3 of the
- License, or (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <https://www.gnu.org/licenses/>.
- For commercial licensing, please contact support@quantumnous.com
- */
- import { useState, useCallback, useEffect } from 'react';
- import { initVChartSemiTheme } from '@visactor/vchart-semi-theme';
- import {
- modelColorMap,
- renderNumber,
- renderQuota,
- modelToColor,
- getQuotaWithUnit,
- } from '../../helpers';
- import {
- processRawData,
- calculateTrendData,
- aggregateDataByTimeAndModel,
- generateChartTimePoints,
- updateChartSpec,
- updateMapValue,
- initializeMaps,
- } from '../../helpers/dashboard';
- export const useDashboardCharts = (
- dataExportDefaultTime,
- setTrendData,
- setConsumeQuota,
- setTimes,
- setConsumeTokens,
- setPieData,
- setLineData,
- setModelColors,
- t,
- ) => {
- // ========== 图表规格状态 ==========
- const [spec_pie, setSpecPie] = useState({
- type: 'pie',
- data: [
- {
- id: 'id0',
- values: [{ type: 'null', value: '0' }],
- },
- ],
- outerRadius: 0.8,
- innerRadius: 0.5,
- padAngle: 0.6,
- valueField: 'value',
- categoryField: 'type',
- pie: {
- style: {
- cornerRadius: 10,
- },
- state: {
- hover: {
- outerRadius: 0.85,
- stroke: '#000',
- lineWidth: 1,
- },
- selected: {
- outerRadius: 0.85,
- stroke: '#000',
- lineWidth: 1,
- },
- },
- },
- title: {
- visible: true,
- text: t('模型调用次数占比'),
- subtext: `${t('总计')}:${renderNumber(0)}`,
- },
- legends: {
- visible: true,
- orient: 'left',
- },
- label: {
- visible: true,
- },
- tooltip: {
- mark: {
- content: [
- {
- key: (datum) => datum['type'],
- value: (datum) => renderNumber(datum['value']),
- },
- ],
- },
- },
- color: {
- specified: modelColorMap,
- },
- });
- const [spec_line, setSpecLine] = useState({
- type: 'bar',
- data: [
- {
- id: 'barData',
- values: [],
- },
- ],
- xField: 'Time',
- yField: 'Usage',
- seriesField: 'Model',
- stack: true,
- legends: {
- visible: true,
- selectMode: 'single',
- },
- title: {
- visible: true,
- text: t('模型消耗分布'),
- subtext: `${t('总计')}:${renderQuota(0, 2)}`,
- },
- bar: {
- state: {
- hover: {
- stroke: '#000',
- lineWidth: 1,
- },
- },
- },
- tooltip: {
- mark: {
- content: [
- {
- key: (datum) => datum['Model'],
- value: (datum) => renderQuota(datum['rawQuota'] || 0, 4),
- },
- ],
- },
- dimension: {
- content: [
- {
- key: (datum) => datum['Model'],
- value: (datum) => datum['rawQuota'] || 0,
- },
- ],
- updateContent: (array) => {
- array.sort((a, b) => b.value - a.value);
- let sum = 0;
- for (let i = 0; i < array.length; i++) {
- if (array[i].key == '其他') {
- continue;
- }
- let value = parseFloat(array[i].value);
- if (isNaN(value)) {
- value = 0;
- }
- if (array[i].datum && array[i].datum.TimeSum) {
- sum = array[i].datum.TimeSum;
- }
- array[i].value = renderQuota(value, 4);
- }
- array.unshift({
- key: t('总计'),
- value: renderQuota(sum, 4),
- });
- return array;
- },
- },
- },
- color: {
- specified: modelColorMap,
- },
- });
- // 模型消耗趋势折线图
- const [spec_model_line, setSpecModelLine] = useState({
- type: 'line',
- data: [
- {
- id: 'lineData',
- values: [],
- },
- ],
- xField: 'Time',
- yField: 'Count',
- seriesField: 'Model',
- legends: {
- visible: true,
- selectMode: 'single',
- },
- title: {
- visible: true,
- text: t('模型消耗趋势'),
- subtext: '',
- },
- tooltip: {
- mark: {
- content: [
- {
- key: (datum) => datum['Model'],
- value: (datum) => renderNumber(datum['Count']),
- },
- ],
- },
- },
- color: {
- specified: modelColorMap,
- },
- });
- // 模型调用次数排行柱状图
- const [spec_rank_bar, setSpecRankBar] = useState({
- type: 'bar',
- data: [
- {
- id: 'rankData',
- values: [],
- },
- ],
- xField: 'Model',
- yField: 'Count',
- seriesField: 'Model',
- legends: {
- visible: true,
- selectMode: 'single',
- },
- title: {
- visible: true,
- text: t('模型调用次数排行'),
- subtext: '',
- },
- bar: {
- state: {
- hover: {
- stroke: '#000',
- lineWidth: 1,
- },
- },
- },
- tooltip: {
- mark: {
- content: [
- {
- key: (datum) => datum['Model'],
- value: (datum) => renderNumber(datum['Count']),
- },
- ],
- },
- },
- color: {
- specified: modelColorMap,
- },
- });
- // ========== 数据处理函数 ==========
- const generateModelColors = useCallback((uniqueModels, modelColors) => {
- const newModelColors = {};
- Array.from(uniqueModels).forEach((modelName) => {
- newModelColors[modelName] =
- modelColorMap[modelName] ||
- modelColors[modelName] ||
- modelToColor(modelName);
- });
- return newModelColors;
- }, []);
- const updateChartData = useCallback(
- (data) => {
- const processedData = processRawData(
- data,
- dataExportDefaultTime,
- initializeMaps,
- updateMapValue,
- );
- const {
- totalQuota,
- totalTimes,
- totalTokens,
- uniqueModels,
- timePoints,
- timeQuotaMap,
- timeTokensMap,
- timeCountMap,
- } = processedData;
- const trendDataResult = calculateTrendData(
- timePoints,
- timeQuotaMap,
- timeTokensMap,
- timeCountMap,
- dataExportDefaultTime,
- );
- setTrendData(trendDataResult);
- const newModelColors = generateModelColors(uniqueModels, {});
- setModelColors(newModelColors);
- const aggregatedData = aggregateDataByTimeAndModel(
- data,
- dataExportDefaultTime,
- );
- const modelTotals = new Map();
- for (let [_, value] of aggregatedData) {
- updateMapValue(modelTotals, value.model, value.count);
- }
- const newPieData = Array.from(modelTotals)
- .map(([model, count]) => ({
- type: model,
- value: count,
- }))
- .sort((a, b) => b.value - a.value);
- const chartTimePoints = generateChartTimePoints(
- aggregatedData,
- data,
- dataExportDefaultTime,
- );
- let newLineData = [];
- chartTimePoints.forEach((time) => {
- let timeData = Array.from(uniqueModels).map((model) => {
- const key = `${time}-${model}`;
- const aggregated = aggregatedData.get(key);
- return {
- Time: time,
- Model: model,
- rawQuota: aggregated?.quota || 0,
- Usage: aggregated?.quota
- ? getQuotaWithUnit(aggregated.quota, 4)
- : 0,
- };
- });
- const timeSum = timeData.reduce((sum, item) => sum + item.rawQuota, 0);
- timeData.sort((a, b) => b.rawQuota - a.rawQuota);
- timeData = timeData.map((item) => ({ ...item, TimeSum: timeSum }));
- newLineData.push(...timeData);
- });
- newLineData.sort((a, b) => a.Time.localeCompare(b.Time));
- updateChartSpec(
- setSpecPie,
- newPieData,
- `${t('总计')}:${renderNumber(totalTimes)}`,
- newModelColors,
- 'id0',
- );
- updateChartSpec(
- setSpecLine,
- newLineData,
- `${t('总计')}:${renderQuota(totalQuota, 2)}`,
- newModelColors,
- 'barData',
- );
- // ===== 模型调用次数折线图 =====
- let modelLineData = [];
- chartTimePoints.forEach((time) => {
- const timeData = Array.from(uniqueModels).map((model) => {
- const key = `${time}-${model}`;
- const aggregated = aggregatedData.get(key);
- return {
- Time: time,
- Model: model,
- Count: aggregated?.count || 0,
- };
- });
- modelLineData.push(...timeData);
- });
- modelLineData.sort((a, b) => a.Time.localeCompare(b.Time));
- // ===== 模型调用次数排行柱状图 =====
- const rankData = Array.from(modelTotals)
- .map(([model, count]) => ({
- Model: model,
- Count: count,
- }))
- .sort((a, b) => b.Count - a.Count);
- updateChartSpec(
- setSpecModelLine,
- modelLineData,
- `${t('总计')}:${renderNumber(totalTimes)}`,
- newModelColors,
- 'lineData',
- );
- updateChartSpec(
- setSpecRankBar,
- rankData,
- `${t('总计')}:${renderNumber(totalTimes)}`,
- newModelColors,
- 'rankData',
- );
- setPieData(newPieData);
- setLineData(newLineData);
- setConsumeQuota(totalQuota);
- setTimes(totalTimes);
- setConsumeTokens(totalTokens);
- },
- [
- dataExportDefaultTime,
- setTrendData,
- generateModelColors,
- setModelColors,
- setPieData,
- setLineData,
- setConsumeQuota,
- setTimes,
- setConsumeTokens,
- t,
- ],
- );
- // ========== 初始化图表主题 ==========
- useEffect(() => {
- initVChartSemiTheme({
- isWatchingThemeSwitch: true,
- });
- }, []);
- return {
- // 图表规格
- spec_pie,
- spec_line,
- spec_model_line,
- spec_rank_bar,
- // 函数
- updateChartData,
- generateModelColors,
- };
- };
|